PySerial non blocking read









up vote
0
down vote

favorite












At the moment I have to make a code that keeps reading the data from my COM port. But the moment I try to use read() it blocks the program, I've tried to use threads but when I make my thread target the read function it keeps on blocking.
So I added a return, the problem with this is that it will only return the value's it read when I press the button.



At this moment Lees() reads the data the moment I press the InsertText() button. I want Lees() to keep running in the background while I use my interface.



Interface:



 import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLineEdit
import serial_se_re
import threading

serialPort = serial_se_re.SerialPort()

def SendDataCommand():
serialPort.Stuur("Basic Send")

def Verbinden():
serialPort.Open("COM13",19200)

def InsertText():
print(serialPort.Lees())
#tekst_veld.insert(message)

app = QApplication()
window = QWidget()
layout = QVBoxLayout()
window.setWindowTitle('Python')

thread = threading.Thread(target=serialPort.Lees())
thread.start()

connect_button = QPushButton('Connect')
layout.addWidget(connect_button)
connect_button.clicked.connect(lambda: Verbinden())

stuur_data_button = QPushButton('Stuur message')
layout.addWidget(stuur_data_button)
stuur_data_button.clicked.connect(lambda: SendDataCommand())

instert_text = QPushButton('add')
layout.addWidget(instert_text)
instert_text.clicked.connect(lambda: InsertText())

tekst_veld = QLineEdit()
layout.addWidget(tekst_veld)

window.setLayout(layout)
window.show()
app.exec_()


SerialConnection:



import serial
import sys
import _thread
import threading

class SerialPort:
def __init__(self):
self.comportName = "COM13"
self.baud = 19200
self.isopen = False
self.timeout = None
self.serialport = serial.Serial()


def __del__(self):
try:
if self.serialport.is_open():
self.serialport.close()
except:
print("Kan de COM port niet sluiten, error: ", sys.exc_info()[0] )

def CheckOpen(self):
return self.isopen

def Open(self,port,baud):
if not self.isopen:
self.serialport.port = port
self.serialport.baudrate = baud
try:
self.serialport.open()
self.isopen = True
except:
print("Kan port niet openen, error: ", sys.exc_info()[0])

def Sluiten(self):
if self.isopen:
try:
self.serialport.close()
self.isopen = False
except:
print("Kan port niet sluiten, error: ", sys.exc_info()[0])

def Stuur(self,message):
if self.isopen:
try:
# Ensure that the end of the message has both r and n, not just one or the other
newmessage = message.strip()
newmessage += 'rn'
self.serialport.write(newmessage.encode('utf-8'))
except:
print("Error sending message: ", sys.exc_info()[0] )
else:
return True
else:
return False

def Lees(self):
if self.isopen:
try:
while(1):
message = self.serialport.read()
return(message)
except Exception:
print("error")
else:
print("Cannot open serial port")









share|improve this question







New contributor




Nashkigih is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.























    up vote
    0
    down vote

    favorite












    At the moment I have to make a code that keeps reading the data from my COM port. But the moment I try to use read() it blocks the program, I've tried to use threads but when I make my thread target the read function it keeps on blocking.
    So I added a return, the problem with this is that it will only return the value's it read when I press the button.



    At this moment Lees() reads the data the moment I press the InsertText() button. I want Lees() to keep running in the background while I use my interface.



    Interface:



     import sys
    from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLineEdit
    import serial_se_re
    import threading

    serialPort = serial_se_re.SerialPort()

    def SendDataCommand():
    serialPort.Stuur("Basic Send")

    def Verbinden():
    serialPort.Open("COM13",19200)

    def InsertText():
    print(serialPort.Lees())
    #tekst_veld.insert(message)

    app = QApplication()
    window = QWidget()
    layout = QVBoxLayout()
    window.setWindowTitle('Python')

    thread = threading.Thread(target=serialPort.Lees())
    thread.start()

    connect_button = QPushButton('Connect')
    layout.addWidget(connect_button)
    connect_button.clicked.connect(lambda: Verbinden())

    stuur_data_button = QPushButton('Stuur message')
    layout.addWidget(stuur_data_button)
    stuur_data_button.clicked.connect(lambda: SendDataCommand())

    instert_text = QPushButton('add')
    layout.addWidget(instert_text)
    instert_text.clicked.connect(lambda: InsertText())

    tekst_veld = QLineEdit()
    layout.addWidget(tekst_veld)

    window.setLayout(layout)
    window.show()
    app.exec_()


    SerialConnection:



    import serial
    import sys
    import _thread
    import threading

    class SerialPort:
    def __init__(self):
    self.comportName = "COM13"
    self.baud = 19200
    self.isopen = False
    self.timeout = None
    self.serialport = serial.Serial()


    def __del__(self):
    try:
    if self.serialport.is_open():
    self.serialport.close()
    except:
    print("Kan de COM port niet sluiten, error: ", sys.exc_info()[0] )

    def CheckOpen(self):
    return self.isopen

    def Open(self,port,baud):
    if not self.isopen:
    self.serialport.port = port
    self.serialport.baudrate = baud
    try:
    self.serialport.open()
    self.isopen = True
    except:
    print("Kan port niet openen, error: ", sys.exc_info()[0])

    def Sluiten(self):
    if self.isopen:
    try:
    self.serialport.close()
    self.isopen = False
    except:
    print("Kan port niet sluiten, error: ", sys.exc_info()[0])

    def Stuur(self,message):
    if self.isopen:
    try:
    # Ensure that the end of the message has both r and n, not just one or the other
    newmessage = message.strip()
    newmessage += 'rn'
    self.serialport.write(newmessage.encode('utf-8'))
    except:
    print("Error sending message: ", sys.exc_info()[0] )
    else:
    return True
    else:
    return False

    def Lees(self):
    if self.isopen:
    try:
    while(1):
    message = self.serialport.read()
    return(message)
    except Exception:
    print("error")
    else:
    print("Cannot open serial port")









    share|improve this question







    New contributor




    Nashkigih is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.





















      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      At the moment I have to make a code that keeps reading the data from my COM port. But the moment I try to use read() it blocks the program, I've tried to use threads but when I make my thread target the read function it keeps on blocking.
      So I added a return, the problem with this is that it will only return the value's it read when I press the button.



      At this moment Lees() reads the data the moment I press the InsertText() button. I want Lees() to keep running in the background while I use my interface.



      Interface:



       import sys
      from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLineEdit
      import serial_se_re
      import threading

      serialPort = serial_se_re.SerialPort()

      def SendDataCommand():
      serialPort.Stuur("Basic Send")

      def Verbinden():
      serialPort.Open("COM13",19200)

      def InsertText():
      print(serialPort.Lees())
      #tekst_veld.insert(message)

      app = QApplication()
      window = QWidget()
      layout = QVBoxLayout()
      window.setWindowTitle('Python')

      thread = threading.Thread(target=serialPort.Lees())
      thread.start()

      connect_button = QPushButton('Connect')
      layout.addWidget(connect_button)
      connect_button.clicked.connect(lambda: Verbinden())

      stuur_data_button = QPushButton('Stuur message')
      layout.addWidget(stuur_data_button)
      stuur_data_button.clicked.connect(lambda: SendDataCommand())

      instert_text = QPushButton('add')
      layout.addWidget(instert_text)
      instert_text.clicked.connect(lambda: InsertText())

      tekst_veld = QLineEdit()
      layout.addWidget(tekst_veld)

      window.setLayout(layout)
      window.show()
      app.exec_()


      SerialConnection:



      import serial
      import sys
      import _thread
      import threading

      class SerialPort:
      def __init__(self):
      self.comportName = "COM13"
      self.baud = 19200
      self.isopen = False
      self.timeout = None
      self.serialport = serial.Serial()


      def __del__(self):
      try:
      if self.serialport.is_open():
      self.serialport.close()
      except:
      print("Kan de COM port niet sluiten, error: ", sys.exc_info()[0] )

      def CheckOpen(self):
      return self.isopen

      def Open(self,port,baud):
      if not self.isopen:
      self.serialport.port = port
      self.serialport.baudrate = baud
      try:
      self.serialport.open()
      self.isopen = True
      except:
      print("Kan port niet openen, error: ", sys.exc_info()[0])

      def Sluiten(self):
      if self.isopen:
      try:
      self.serialport.close()
      self.isopen = False
      except:
      print("Kan port niet sluiten, error: ", sys.exc_info()[0])

      def Stuur(self,message):
      if self.isopen:
      try:
      # Ensure that the end of the message has both r and n, not just one or the other
      newmessage = message.strip()
      newmessage += 'rn'
      self.serialport.write(newmessage.encode('utf-8'))
      except:
      print("Error sending message: ", sys.exc_info()[0] )
      else:
      return True
      else:
      return False

      def Lees(self):
      if self.isopen:
      try:
      while(1):
      message = self.serialport.read()
      return(message)
      except Exception:
      print("error")
      else:
      print("Cannot open serial port")









      share|improve this question







      New contributor




      Nashkigih is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      At the moment I have to make a code that keeps reading the data from my COM port. But the moment I try to use read() it blocks the program, I've tried to use threads but when I make my thread target the read function it keeps on blocking.
      So I added a return, the problem with this is that it will only return the value's it read when I press the button.



      At this moment Lees() reads the data the moment I press the InsertText() button. I want Lees() to keep running in the background while I use my interface.



      Interface:



       import sys
      from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLineEdit
      import serial_se_re
      import threading

      serialPort = serial_se_re.SerialPort()

      def SendDataCommand():
      serialPort.Stuur("Basic Send")

      def Verbinden():
      serialPort.Open("COM13",19200)

      def InsertText():
      print(serialPort.Lees())
      #tekst_veld.insert(message)

      app = QApplication()
      window = QWidget()
      layout = QVBoxLayout()
      window.setWindowTitle('Python')

      thread = threading.Thread(target=serialPort.Lees())
      thread.start()

      connect_button = QPushButton('Connect')
      layout.addWidget(connect_button)
      connect_button.clicked.connect(lambda: Verbinden())

      stuur_data_button = QPushButton('Stuur message')
      layout.addWidget(stuur_data_button)
      stuur_data_button.clicked.connect(lambda: SendDataCommand())

      instert_text = QPushButton('add')
      layout.addWidget(instert_text)
      instert_text.clicked.connect(lambda: InsertText())

      tekst_veld = QLineEdit()
      layout.addWidget(tekst_veld)

      window.setLayout(layout)
      window.show()
      app.exec_()


      SerialConnection:



      import serial
      import sys
      import _thread
      import threading

      class SerialPort:
      def __init__(self):
      self.comportName = "COM13"
      self.baud = 19200
      self.isopen = False
      self.timeout = None
      self.serialport = serial.Serial()


      def __del__(self):
      try:
      if self.serialport.is_open():
      self.serialport.close()
      except:
      print("Kan de COM port niet sluiten, error: ", sys.exc_info()[0] )

      def CheckOpen(self):
      return self.isopen

      def Open(self,port,baud):
      if not self.isopen:
      self.serialport.port = port
      self.serialport.baudrate = baud
      try:
      self.serialport.open()
      self.isopen = True
      except:
      print("Kan port niet openen, error: ", sys.exc_info()[0])

      def Sluiten(self):
      if self.isopen:
      try:
      self.serialport.close()
      self.isopen = False
      except:
      print("Kan port niet sluiten, error: ", sys.exc_info()[0])

      def Stuur(self,message):
      if self.isopen:
      try:
      # Ensure that the end of the message has both r and n, not just one or the other
      newmessage = message.strip()
      newmessage += 'rn'
      self.serialport.write(newmessage.encode('utf-8'))
      except:
      print("Error sending message: ", sys.exc_info()[0] )
      else:
      return True
      else:
      return False

      def Lees(self):
      if self.isopen:
      try:
      while(1):
      message = self.serialport.read()
      return(message)
      except Exception:
      print("error")
      else:
      print("Cannot open serial port")






      python pyserial






      share|improve this question







      New contributor




      Nashkigih is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      Nashkigih is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      Nashkigih is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked Nov 8 at 13:02









      Nashkigih

      11




      11




      New contributor




      Nashkigih is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Nashkigih is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Nashkigih is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.



























          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );






          Nashkigih is a new contributor. Be nice, and check out our Code of Conduct.









           

          draft saved


          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53208316%2fpyserial-non-blocking-read%23new-answer', 'question_page');

          );

          Post as a guest



































          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          Nashkigih is a new contributor. Be nice, and check out our Code of Conduct.









           

          draft saved


          draft discarded


















          Nashkigih is a new contributor. Be nice, and check out our Code of Conduct.












          Nashkigih is a new contributor. Be nice, and check out our Code of Conduct.











          Nashkigih is a new contributor. Be nice, and check out our Code of Conduct.













           


          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53208316%2fpyserial-non-blocking-read%23new-answer', 'question_page');

          );

          Post as a guest














































































          Popular posts from this blog

          𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

          Edmonton

          Crossroads (UK TV series)