An Example of Automatic Triggering of Serial Port by python
- 2021-07-06 11:33:08
- OfStack
Recently in an python tool need to achieve the serial port automatic trigger work function, before only in winform above the implementation, today use python try. Here's a brief note:
First, implement an Button with wxpython, and click the event binding function OnButtonAutoStopAll
self.button_autoStopAll = wx.Button(id=wxID_FRAME1BUTTONAUTOSTARTALL, label=u'AUTO STOP ALL',
name='button_autoStop', parent=self.staticBox_common, pos=wx.Point(8, 284),
size=wx.Size(180, 80), style=0)
self.button_autoStopAll.SetFont(wx.Font(24, wx.SWISS, wx.NORMAL, wx.BOLD, False,
u'Agency FB'))
self.button_autoStopAll.Bind(wx.EVT_BUTTON, self.OnButtonAutoStopAll,
id=wxID_FRAME1BUTTONAUTOSTARTALL)
Then there is ComboBox control to automatically load the current serial port name when clicking drop-down
self.combox = wx.ComboBox(self, -1, pos=wx.Point(10,100), size=wx.Size(100,50),
style=wx.CB_READONLY) # Serial port combox
self.combox.Bind(wx.EVT_COMBOBOX_DROPDOWN, self.evt_combox_dropdown)
Drop-down menu event function
def evt_combox_dropdown(self, event):
print 'combox%d dropdown'%self.sta_num
serial_list = list(serial.tools.list_ports.comports())
if serial_list: # Determine whether it is null
portName_list = []
# Conversion serial handle For port name
for i in range(0, len(serial_list)):
portname = list(serial_list[i])
portName_list.append(str(portname[0]))
print portName_list
self.combox.SetItems(portName_list)
Then get down to business, which is triggered according to DSR signal.
# Serial port automatically triggers detection thread
class Job(threading.Thread):
...
def run(self):
while self.__running.isSet():
self.__flag.wait() # For True Return immediately when , For False Block until the internal ID bit is True Back
print "into job function"
i=0
isOpen = serial_isOpen(i)
if serial_list[i]!=1 and isOpen:
now_dsr = serial_list[i].getDSR()
if now_dsr != last_dsr[i]:
last_dsr[i] = now_dsr
print 'dsr level changed to %d'%now_dsr
if now_dsr == True:
if thread_list[i] != 1:
if ~thread_list[i].is_alive():
serial_Open(0, False)
#do something
else:
serial_Open(0, False)
#do something
break
time.sleep(1)
...
That is, every time the DSR signal is set low, it triggers the operation