我目前在 Python 中遇到 pySerial 模块的问题。我的问题与连接和断开设备有关。我可以成功连接到我的设备并与它通信,只要我愿意,也可以随时断开连接。但是,一旦连接被切断,我就无法重新连接到设备。
这是我的程序用于与串行端口交互的包装类:
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)
有谁知道这个问题存在的原因以及我可以尝试做些什么来解决它?