Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. Socket and Serial Read and Write using QThread
Forum Updated to NodeBB v4.3 + New Features

Socket and Serial Read and Write using QThread

Scheduled Pinned Locked Moved Solved Qt for Python
20 Posts 4 Posters 2.7k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • J J.Hilk
    20 Mar 2024, 10:45

    @VIDYUL-SHAH as a non python guy, Ai generated code is the best I can offer you, it's also something you could do on your own :P

    import sys
    from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QTextEdit
    from PyQt5.QtSerialPort import QSerialPort, QSerialPortInfo
    from PyQt5.QtCore import QObject, pyqtSignal, pyqtSlot
    
    
    class SerialPortManager(QObject):
        data_received = pyqtSignal(str)
    
        def __init__(self, parent=None):
            super().__init__(parent)
            self.serial_port = QSerialPort()
            self.serial_port.readyRead.connect(self.on_ready_read)
    
        def open_port(self, port_name):
            if self.serial_port.isOpen():
                self.serial_port.close()
            self.serial_port.setPortName(port_name)
            self.serial_port.setBaudRate(QSerialPort.Baud9600)
            self.serial_port.setDataBits(QSerialPort.Data8)
            self.serial_port.setParity(QSerialPort.NoParity)
            self.serial_port.setStopBits(QSerialPort.OneStop)
            self.serial_port.open(QSerialPort.ReadWrite)
    
        def write_data(self, data):
            if self.serial_port.isOpen():
                self.serial_port.writeData(data.encode())
    
        @pyqtSlot()
        def on_ready_read(self):
            if self.serial_port.canReadLine():
                data = self.serial_port.readLine().data().decode().strip()
                self.data_received.emit(data)
    
    
    class MainWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("Serial Port Communication")
            self.setGeometry(100, 100, 400, 300)
    
            self.text_edit = QTextEdit(self)
            self.text_edit.setGeometry(10, 10, 380, 200)
    
            self.send_button = QPushButton("Send Data", self)
            self.send_button.setGeometry(10, 220, 180, 30)
            self.send_button.clicked.connect(self.send_data)
    
            self.clear_button = QPushButton("Clear", self)
            self.clear_button.setGeometry(200, 220, 180, 30)
            self.clear_button.clicked.connect(self.clear_text)
    
            self.serial_manager = SerialPortManager()
            self.serial_manager.data_received.connect(self.on_data_received)
            self.serial_manager.open_port("/dev/ttyUSB0")  # Replace with your serial port name
    
        def send_data(self):
            data_to_send = "Hello from PyQt5"
            self.serial_manager.write_data(data_to_send)
    
        @pyqtSlot(str)
        def on_data_received(self, data):
            self.text_edit.append("Received: " + data)
    
        def clear_text(self):
            self.text_edit.clear()
    
    
    if __name__ == "__main__":
        app = QApplication(sys.argv)
        window = MainWindow()
        window.show()
        sys.exit(app.exec_())
    

    Code provided without guarantee of accuracy

    V Offline
    V Offline
    VIDYUL SHAH
    wrote on 21 Mar 2024, 04:13 last edited by VIDYUL SHAH
    #10

    @J-Hilk YEs this code works perfectly and has helped me a lot but I encountered an issue where the send button is not there instead the the data received is processed further and the updated data sends to be sent automatically which does not happen if I remove the clicked.connect method. Also, as said initially in my query, I had already achieved what you have shared but the only problem is sending of the data in the same port without the use of any buttons. The data will keep changing and needs to be sent continuously.

    here is my sample code that I tried:
    #!/usr/bin/env python3

    import os, sys
    from PyQt5 import QtWidgets
    from PyQt5.QtSerialPort import QSerialPort
    from PyQt5.QtCore import QLibraryInfo, pyqtSignal, pyqtSlot, QObject
    from PyQt5.QtWidgets import QDialog, QApplication
    from PyQt5.uic import loadUi

    os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = QLibraryInfo.location(
    QLibraryInfo.PluginsPath
    )

    class SerialPortManager(QObject):
    data_received = pyqtSignal(str)

    def __init__(self, parent=None):
        super().__init__(parent)
        self.serial_port = QSerialPort()
        self.serial_port.readyRead.connect(self.on_ready_read)
    
    def open_port(self, port_name):
        if self.serial_port.isOpen():
            self.serial_port.close()
        self.serial_port.setPortName(port_name)
        self.serial_port.setBaudRate(QSerialPort.Baud115200)
        self.serial_port.setDataBits(QSerialPort.Data8)
        self.serial_port.setParity(QSerialPort.NoParity)
        self.serial_port.setStopBits(QSerialPort.OneStop)
        self.serial_port.open(QSerialPort.ReadWrite)
    
    def write_data(self, data):
        if self.serial_port.isOpen():
            self.serial_port.writeData(data.encode())
    
    @pyqtSlot()
    def on_ready_read(self):
        if self.serial_port.canReadLine():
            data = self.serial_port.readLine().data().decode('ISO-8859-1').strip()
            self.data_received.emit(data)
    

    class GCS(QDialog):
    def init(self):
    super(GCS, self).init()
    loadUi('GCS.ui', self)

        self.serial_manager = SerialPortManager()
        self.serial_manager.open_port("/dev/ttyACM0")
        self.serial_manager.data_received.connect(self.on_data_received)
    
    def send_data(self):
        data_to_send = "1"
        self.serial_manager.write_data(data_to_send)
    
    @pyqtSlot(str)
    def on_data_received(self, data):
        self.send_data()
        print("Received: " + data)
    

    app=QApplication(sys.argv)
    mainwindow=GCS()
    widget=QtWidgets.QStackedWidget()
    widget.addWidget(mainwindow)
    widget.show()
    app.exec_()

    J 1 Reply Last reply 21 Mar 2024, 06:13
    0
    • V VIDYUL SHAH
      21 Mar 2024, 04:13

      @J-Hilk YEs this code works perfectly and has helped me a lot but I encountered an issue where the send button is not there instead the the data received is processed further and the updated data sends to be sent automatically which does not happen if I remove the clicked.connect method. Also, as said initially in my query, I had already achieved what you have shared but the only problem is sending of the data in the same port without the use of any buttons. The data will keep changing and needs to be sent continuously.

      here is my sample code that I tried:
      #!/usr/bin/env python3

      import os, sys
      from PyQt5 import QtWidgets
      from PyQt5.QtSerialPort import QSerialPort
      from PyQt5.QtCore import QLibraryInfo, pyqtSignal, pyqtSlot, QObject
      from PyQt5.QtWidgets import QDialog, QApplication
      from PyQt5.uic import loadUi

      os.environ["QT_QPA_PLATFORM_PLUGIN_PATH"] = QLibraryInfo.location(
      QLibraryInfo.PluginsPath
      )

      class SerialPortManager(QObject):
      data_received = pyqtSignal(str)

      def __init__(self, parent=None):
          super().__init__(parent)
          self.serial_port = QSerialPort()
          self.serial_port.readyRead.connect(self.on_ready_read)
      
      def open_port(self, port_name):
          if self.serial_port.isOpen():
              self.serial_port.close()
          self.serial_port.setPortName(port_name)
          self.serial_port.setBaudRate(QSerialPort.Baud115200)
          self.serial_port.setDataBits(QSerialPort.Data8)
          self.serial_port.setParity(QSerialPort.NoParity)
          self.serial_port.setStopBits(QSerialPort.OneStop)
          self.serial_port.open(QSerialPort.ReadWrite)
      
      def write_data(self, data):
          if self.serial_port.isOpen():
              self.serial_port.writeData(data.encode())
      
      @pyqtSlot()
      def on_ready_read(self):
          if self.serial_port.canReadLine():
              data = self.serial_port.readLine().data().decode('ISO-8859-1').strip()
              self.data_received.emit(data)
      

      class GCS(QDialog):
      def init(self):
      super(GCS, self).init()
      loadUi('GCS.ui', self)

          self.serial_manager = SerialPortManager()
          self.serial_manager.open_port("/dev/ttyACM0")
          self.serial_manager.data_received.connect(self.on_data_received)
      
      def send_data(self):
          data_to_send = "1"
          self.serial_manager.write_data(data_to_send)
      
      @pyqtSlot(str)
      def on_data_received(self, data):
          self.send_data()
          print("Received: " + data)
      

      app=QApplication(sys.argv)
      mainwindow=GCS()
      widget=QtWidgets.QStackedWidget()
      widget.addWidget(mainwindow)
      widget.show()
      app.exec_()

      J Offline
      J Offline
      jsulm
      Lifetime Qt Champion
      wrote on 21 Mar 2024, 06:13 last edited by
      #11

      @VIDYUL-SHAH said in Socket and Serial Read and Write using QThread:

      The data will keep changing and needs to be sent continuously

      What exactly is the problem? If you have new data to send then send it, you do not need any buttons for that.

      https://forum.qt.io/topic/113070/qt-code-of-conduct

      V 1 Reply Last reply 21 Mar 2024, 09:34
      1
      • J jsulm
        21 Mar 2024, 06:13

        @VIDYUL-SHAH said in Socket and Serial Read and Write using QThread:

        The data will keep changing and needs to be sent continuously

        What exactly is the problem? If you have new data to send then send it, you do not need any buttons for that.

        V Offline
        V Offline
        VIDYUL SHAH
        wrote on 21 Mar 2024, 09:34 last edited by
        #12

        @jsulm Maybe I am unable to explain what I am trying to achieve which show lack of communication skills from my side. Is there any way we can connect over internet like a zoom/google meet where I can explain what I want to achieve and how can I achieve it? Also, at the same time you can show me what is previously explain in my query by you and @JonB

        J 1 Reply Last reply 21 Mar 2024, 09:47
        0
        • V VIDYUL SHAH
          21 Mar 2024, 09:34

          @jsulm Maybe I am unable to explain what I am trying to achieve which show lack of communication skills from my side. Is there any way we can connect over internet like a zoom/google meet where I can explain what I want to achieve and how can I achieve it? Also, at the same time you can show me what is previously explain in my query by you and @JonB

          J Offline
          J Offline
          jsulm
          Lifetime Qt Champion
          wrote on 21 Mar 2024, 09:47 last edited by
          #13

          @VIDYUL-SHAH said in Socket and Serial Read and Write using QThread:

          Is there any way we can connect over internet like a zoom/google meet

          No
          But it should be possible to simply explain what you want to do and where you have problems.

          https://forum.qt.io/topic/113070/qt-code-of-conduct

          V 1 Reply Last reply 22 Mar 2024, 04:57
          1
          • J jsulm
            21 Mar 2024, 09:47

            @VIDYUL-SHAH said in Socket and Serial Read and Write using QThread:

            Is there any way we can connect over internet like a zoom/google meet

            No
            But it should be possible to simply explain what you want to do and where you have problems.

            V Offline
            V Offline
            VIDYUL SHAH
            wrote on 22 Mar 2024, 04:57 last edited by
            #14

            @jsulm Ok I tried the method you both suggested but if I used QSerialPort. I got to know it takes a while to update the data and print that is coming from QSerialPort, Also, I am taking live video from "127.0.0.7:5000", data from "127.0.0.7:5001", data from arduino serial port "/dev/ttyACM0", joystick input using inputs.get_gamepad and processing the whole data using ML after which I send a few data to arduino back to perform certain tasks and another bunch of data through the socket port "127.0.0.7:5001". Only in UI I am able to see the video and rest happens in background. I want to achieve this with zero latency and currently using QThread I am unable to achieve it. also tried the QSerialPort but saw latency there also.
            This is the summary what I am trying to achieve.

            J 1 Reply Last reply 22 Mar 2024, 06:23
            0
            • V VIDYUL SHAH
              22 Mar 2024, 04:57

              @jsulm Ok I tried the method you both suggested but if I used QSerialPort. I got to know it takes a while to update the data and print that is coming from QSerialPort, Also, I am taking live video from "127.0.0.7:5000", data from "127.0.0.7:5001", data from arduino serial port "/dev/ttyACM0", joystick input using inputs.get_gamepad and processing the whole data using ML after which I send a few data to arduino back to perform certain tasks and another bunch of data through the socket port "127.0.0.7:5001". Only in UI I am able to see the video and rest happens in background. I want to achieve this with zero latency and currently using QThread I am unable to achieve it. also tried the QSerialPort but saw latency there also.
              This is the summary what I am trying to achieve.

              J Offline
              J Offline
              jsulm
              Lifetime Qt Champion
              wrote on 22 Mar 2024, 06:23 last edited by
              #15

              @VIDYUL-SHAH said in Socket and Serial Read and Write using QThread:

              also tried the QSerialPort but saw latency there also

              What kind of latency? Is your UI thread freezing? Do you use the approach suggested (using readyRead signal without any threads, waiting and loops)?

              https://forum.qt.io/topic/113070/qt-code-of-conduct

              V 1 Reply Last reply 22 Mar 2024, 07:33
              0
              • J jsulm
                22 Mar 2024, 06:23

                @VIDYUL-SHAH said in Socket and Serial Read and Write using QThread:

                also tried the QSerialPort but saw latency there also

                What kind of latency? Is your UI thread freezing? Do you use the approach suggested (using readyRead signal without any threads, waiting and loops)?

                V Offline
                V Offline
                VIDYUL SHAH
                wrote on 22 Mar 2024, 07:33 last edited by VIDYUL SHAH
                #16

                @jsulm Using the method suggested (QSocketPort), I implemented to read data from Arduino and print the the data in next statement and the statment after this reads data from joystick and prints data. Both these data are stored in a dictionary. The print statement prints this dictiondary. Now when I give inputs from gamepad and arduino switches either gamepad value changes or arduino value changes and this I observed from the print statement.
                Should I try multithreading or I am making this complicated? If multithreading is done then just after receiving the data how is simultaneous send data on serial or tcp port is possible?
                Yes I used ready signal:
                def init(self, parent=None):
                super().init(parent)
                self.serial_port = QSerialPort()
                self.serial_port.readyRead.connect(self.on_ready_read)

                J 1 Reply Last reply 22 Mar 2024, 07:47
                0
                • V VIDYUL SHAH
                  22 Mar 2024, 07:33

                  @jsulm Using the method suggested (QSocketPort), I implemented to read data from Arduino and print the the data in next statement and the statment after this reads data from joystick and prints data. Both these data are stored in a dictionary. The print statement prints this dictiondary. Now when I give inputs from gamepad and arduino switches either gamepad value changes or arduino value changes and this I observed from the print statement.
                  Should I try multithreading or I am making this complicated? If multithreading is done then just after receiving the data how is simultaneous send data on serial or tcp port is possible?
                  Yes I used ready signal:
                  def init(self, parent=None):
                  super().init(parent)
                  self.serial_port = QSerialPort()
                  self.serial_port.readyRead.connect(self.on_ready_read)

                  J Offline
                  J Offline
                  jsulm
                  Lifetime Qt Champion
                  wrote on 22 Mar 2024, 07:47 last edited by
                  #17

                  @VIDYUL-SHAH said in Socket and Serial Read and Write using QThread:

                  I implemented to read data from Arduino and print the the data in next statement and the statment after this reads data from joystick and prints data. Both these data are stored in a dictionary

                  I'm still not sure I understand. Do you mean in the slot on_ready_read you also read something from joystick? If so why?

                  https://forum.qt.io/topic/113070/qt-code-of-conduct

                  V 1 Reply Last reply 22 Mar 2024, 08:05
                  0
                  • J jsulm
                    22 Mar 2024, 07:47

                    @VIDYUL-SHAH said in Socket and Serial Read and Write using QThread:

                    I implemented to read data from Arduino and print the the data in next statement and the statment after this reads data from joystick and prints data. Both these data are stored in a dictionary

                    I'm still not sure I understand. Do you mean in the slot on_ready_read you also read something from joystick? If so why?

                    V Offline
                    V Offline
                    VIDYUL SHAH
                    wrote on 22 Mar 2024, 08:05 last edited by
                    #18

                    @jsulm I read the serial data from arduino using on_ready_read but I am using a qthread to read data from joystick

                    J 1 Reply Last reply 22 Mar 2024, 10:09
                    0
                    • V VIDYUL SHAH
                      22 Mar 2024, 08:05

                      @jsulm I read the serial data from arduino using on_ready_read but I am using a qthread to read data from joystick

                      J Offline
                      J Offline
                      jsulm
                      Lifetime Qt Champion
                      wrote on 22 Mar 2024, 10:09 last edited by
                      #19

                      @VIDYUL-SHAH Then I don't understand what your problem is

                      https://forum.qt.io/topic/113070/qt-code-of-conduct

                      V 1 Reply Last reply 2 Apr 2024, 05:31
                      1
                      • J jsulm
                        22 Mar 2024, 10:09

                        @VIDYUL-SHAH Then I don't understand what your problem is

                        V Offline
                        V Offline
                        VIDYUL SHAH
                        wrote on 2 Apr 2024, 05:31 last edited by
                        #20

                        @jsulm No worries I have solved the issue and didn't use QSerial or QSocket instead used python serial and socket module inside QThread and it is efficient than using QSerial or QSocket as of what I have coded. THank for the help who all contributed here.

                        1 Reply Last reply
                        0
                        • V VIDYUL SHAH has marked this topic as solved on 2 Apr 2024, 05:32

                        • Login

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • Users
                        • Groups
                        • Search
                        • Get Qt Extensions
                        • Unsolved