Reconnecting to device with pySerial

*爱你&永不变心* 提交于 2019-12-22 05:10:07

问题


I am currently having a problem with the pySerial module in Python. My problem relates to connecting and disconnecting to a device. I can successfully connect to my device and communicate with it for as long as I want to, and disconnect from it whenever I desire. However, I am unable to reconnect to the device once the connection has been severed.

Here is the wrapper class that my program uses to interface with the serial port:

import serial, tkMessageBox

class Controller:
""" Wrapper class for managing the serial connection with the MS-2000. """
    def __init__(self, settings):
        self.ser = None
        self.settings = settings

    def connect(self):
        """ Connect or disconnect to MS-2000. Return connection status."""
        try:
            if self.ser == None:
                self.ser = serial.Serial(self.settings['PORT'],
                                         self.settings['BAUDRATE'])
                print "Successfully connected to port %r." % self.ser.port
                return True
            else:
                if self.ser.isOpen():
                    self.ser.close()
                    print "Disconnected."
                    return False
                else:
                    self.ser.open()
                    print "Connected."
                    return True
        except serial.SerialException, e:
            return False

    def isConnected(self):
        '''Is the computer connected with the MS-2000?'''
        try:
            return self.ser.isOpen()
        except:
            return False

    def write(self, command):
        """ Sends command to MS-2000, appending a carraige return. """
        try:
            self.ser.write(command + '\r')
        except Exception, e:
            tkMessageBox.showerror('Serial connection error',
                                   'Error sending message "%s" to MS-2000:\n%s' %
                               (command, e))

    def read(self, chars):
        """ Reads specified number of characters from the serial port. """
        return self.ser.read(chars)

Does anybody know the reason why this problem exists and what I could try to do to fix it?


回答1:


You aren't releasing the serial port when you are finished. Use ser.close() to close the port before exiting your program, otherwise the port will stay locked indefinitely. I would suggest adding a method called disconnect() in your class for this.

If you are on Windows, to remedy the situation during testing, start Task Manager and kill any python.exe or pythonw.exe processes that may be locking the serial port.



来源:https://stackoverflow.com/questions/11092417/reconnecting-to-device-with-pyserial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!