python实现串口自动触发工作的示例

时间:2022-08-28 17:41:11

最近在一个python工具中需要实现串口自动触发工作的功能,之前只在winform上面实现,今天使用python试试。这里简单记一下:

首先用wxpython实现一个Button,点击事件绑定函数OnButtonAutoStopAll

?
1
2
3
4
5
6
7
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)

再有ComboBox控件实现点击下拉时自动加载当前串口名

?
1
2
3
self.combox = wx.ComboBox(self, -1, pos=wx.Point(10,100), size=wx.Size(100,50),
    style=wx.CB_READONLY) #串口combox
self.combox.Bind(wx.EVT_COMBOBOX_DROPDOWN, self.evt_combox_dropdown)

下拉菜单事件函数

?
1
2
3
4
5
6
7
8
9
10
11
12
def evt_combox_dropdown(self, event):
    print 'combox%d dropdown'%self.sta_num
    serial_list = list(serial.tools.list_ports.comports())
    if serial_list: #判断是否为空
      portName_list = []
  #转换serial handle为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)

然后进入正题,这里根据DSR信号来触发。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#串口自动触发检测线程
class Job(threading.Thread):
  ...
 
  def run(self):
    while self.__running.isSet():
      self.__flag.wait()       # 为True时立即返回, 为False时阻塞直到内部的标识位为True后返回
      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)
 
  ...

即每当DSR信号置低时触发工作

以上这篇python实现串口自动触发工作的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/ubuntu14/article/details/75335106