Python with Serial Port
使用Python 抓取Serial Port非常簡單, 首先安裝pyserial.
pip install pyserial
請看如下代碼
import serial COM_PORT = 'COM3' BAUD_RATES = 115200 ser = serial.Serial(COM_PORT, BAUD_RATES)#initialized serial port try: while True: while ser.in_waiting:#waiting for data receive data_raw = ser.readline() data = data_raw.decode()#default using utf-8 print('接收到的原始資料:', data_raw) print('接收到的資料:', data) except KeyboardInterrupt: ser.close() print('close')
完整程式碼
底下為Lora usb port的訊息取得完整碼
# -*- coding: utf-8 -*- ########################################################################### ## Authorized : Thomas Wu(mahaljsp@gmail.com) ########################################################################### import wx import wx.xrc import serial import threading import time from string_pic import * from io import BytesIO from PIL import Image import base64 delay=0.2 COM_PORT = 'COM3' BAUD_RATES = 115200 slots = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32] class MainFrame(wx.Frame): def __init__(self, parent): wx.Frame.__init__(self, parent, id=wx.ID_ANY, title=u"Dakong Lora Master Receiver", pos=wx.DefaultPosition, size=wx.Size(794, 518), style=wx.DEFAULT_FRAME_STYLE | wx.MAXIMIZE | wx.TAB_TRAVERSAL) self.SetSizeHints(wx.DefaultSize, wx.DefaultSize) self.SetBackgroundColour(wx.Colour(196, 196, 255)) bSizer1 = wx.BoxSizer(wx.VERTICAL) bSizer2 = wx.BoxSizer(wx.HORIZONTAL) self.m_staticText1 = wx.StaticText(self, wx.ID_ANY, u"Port", wx.DefaultPosition, wx.DefaultSize, 0) self.m_staticText1.Wrap(-1) bSizer2.Add(self.m_staticText1, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) cmbPortChoices = [] self.cmbPort = wx.ComboBox(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, cmbPortChoices, 0) bSizer2.Add(self.cmbPort, 0, wx.ALL, 5) self.m_staticText3 = wx.StaticText(self, wx.ID_ANY, u" Freq", wx.DefaultPosition, wx.DefaultSize, 0) self.m_staticText3.Wrap(-1) bSizer2.Add(self.m_staticText3, 0, wx.ALIGN_CENTER | wx.ALL, 5) cmbFreqChoices = [u"923", u"924", u"925"] self.cmbFreq = wx.ComboBox(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, cmbFreqChoices, 0) bSizer2.Add(self.cmbFreq, 0, wx.ALL, 5) self.m_staticText4 = wx.StaticText(self, wx.ID_ANY, u"MHz", wx.DefaultPosition, wx.DefaultSize, 0) self.m_staticText4.Wrap(-1) bSizer2.Add(self.m_staticText4, 0, wx.ALIGN_CENTER | wx.ALL, 5) bSizer1.Add(bSizer2, 0, wx.ALIGN_CENTER, 5) self.lblMsg = wx.TextCtrl(self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, wx.TE_MULTILINE | wx.TE_READONLY) bSizer1.Add(self.lblMsg, 1, wx.ALL | wx.EXPAND, 5) bSizer3 = wx.BoxSizer(wx.HORIZONTAL) self.btnStart = wx.Button(self, wx.ID_ANY, u"Start", wx.DefaultPosition, wx.Size(-1, 50), 0) bSizer3.Add(self.btnStart, 0, wx.ALL, 5) self.btnStop = wx.Button(self, wx.ID_ANY, u"Stop", wx.DefaultPosition, wx.Size(-1, 50), 0) bSizer3.Add(self.btnStop, 0, wx.ALL, 5) bSizer1.Add(bSizer3, 0, wx.ALIGN_CENTER, 5) self.m_staticText5 = wx.StaticText(self, wx.ID_ANY, u"Thomas Wu (mahaljsp@gmail.com) ", wx.DefaultPosition, wx.Size(-1, 25), wx.ALIGN_RIGHT) self.m_staticText5.Wrap(-1) self.m_staticText5.SetFont(wx.Font(11, 70, 93, 90, False, wx.EmptyString)) self.m_staticText5.SetForegroundColour(wx.Colour(0, 100, 100)) self.m_staticText5.SetBackgroundColour(wx.Colour(240, 240, 240)) bSizer1.Add(self.m_staticText5, 0, wx.EXPAND, 5) self.SetSizer(bSizer1) self.Layout() self.Centre(wx.BOTH) self.Init() def __del__(self): pass def Init(self): self.runFlag=True; pil=Image.open(BytesIO(base64.b64decode(lora_png))) w, h=pil.size img=wx.Image(w,h) img.SetData(pil.convert("RGB").tobytes()) img.SetAlpha(pil.convert("RGBA").tobytes()[3::4]) bitmap=wx.Bitmap(img) icon=wx.Icon() icon.CopyFromBitmap(bitmap) self.SetIcon(icon) self.Bind(wx.EVT_BUTTON, self.OnStartClick, self.btnStart) self.Bind(wx.EVT_BUTTON, self.OnStopClick, self.btnStop) self.Bind(wx.EVT_CLOSE, self.OnClose) ports = ['COM%s' % (i + 1) for i in range(256)] coms=[] for port in ports: try: s=serial.Serial(port) s.close() coms.append(port) except: pass if len(coms)>0: self.cmbPort.AppendItems(coms) self.cmbPort.Select(0) self.cmbFreq.Select(0) self.btnStart.Enable(True) self.btnStop.Enable(False) def OnStartClick(self, event): self.btnStart.Enable(False) self.btnStop.Enable(True) self.cmbFreq.Enable(False) self.cmbPort.Enable(False) self.log="" self.runFlag=True self.serial=serial.Serial(self.cmbPort.Value, BAUD_RATES) if self.cmbFreq.Value=='923': self.gateway=1 self.channel=923 elif self.cmbFreq.Value=='924': self.gateway=2 self.channel = 924 else: self.gateway=3 self.channel = 925 t1=threading.Thread(target=self.LoraRead) t1.start() t2=threading.Thread(target=self.LoraSetting) t2.start() def OnStopClick(self, event): self.serial.write("LoraStartWork DISABLE\r".encode()) time.sleep(delay) self.runFlag=False self.serial.close() self.btnStart.Enable(True) self.btnStop.Enable(False) self.cmbFreq.Enable(True) self.cmbPort.Enable(True) def LoraSetting(self): try: self.serial.write("LoraSetMyAddr {0} 0 0\r".format(self.gateway).encode()) time.sleep(delay) self.serial.write("LoraSetChannelFreq 0 {0}\r".format(self.channel*1000000).encode()) time.sleep(delay) self.serial.write("LoraSaveChannelFreq\r".encode()) time.sleep(delay) for i in range(1, 33): self.serial.write("LoraRemoveSlaveNode {0}\r".format(i).encode()) time.sleep(delay) for slot in slots: self.serial.write("LoraAddSlaveNode 0 {0} {1}\r".format(self.gateway, slot).encode()) time.sleep(delay) for i, slot in enumerate(slots): self.serial.write("LoraSetSlaveNodeSlot {0} {1}\r".format(i+1, slot).encode()) time.sleep(delay) self.serial.write("LoraSaveSlaveNode {0}\r".format(i + 1).encode()) time.sleep(delay) self.serial.write("LoraGetMyAddr\r".encode()) time.sleep(delay) self.serial.write("LoraStartWork ENABLE\r".encode()) except: pass def LoraRead(self): while self.runFlag: while self.serial.in_waiting: s='' bytes=self.serial.readline() for byte in bytes: if byte >= 32 and byte <126: s+='{0:c}'.format(byte) elif byte!=10: s+=' {0:X} '.format(byte) self.log+=s+"\r\n" wx.CallAfter(self.UpdateMsg) print("close read") def UpdateMsg(self): self.lblMsg.SetLabelText(self.log) self.lblMsg.SetInsertionPointEnd() def OnClose(self, event): self.runFlag = False time.sleep(delay) try: self.serial.write("LoraStartWork DISABLE\r".encode()) time.sleep(delay) self.serial.close() except: pass app.ExitMainLoop() app=wx.App() frame=MainFrame(None) frame.Show() app.MainLoop()
pic2py.py
import base64 def pic2py(pics, py_name): datas = [] for pic in pics: image = open(pic, 'rb') key = pic.replace('.', '_') value = base64.b64encode(image.read()).decode() image.close() datas.append('{0} = "{1}"\n'.format(key, value)) f = open('{0}.py'.format(py_name), 'w+') for data in datas: f.write(data) f.close() if __name__ == '__main__': pics = ["lora.png"] pic2py(pics, 'string_pic')
todo