电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

python 自動識別并連接串口的實現

瀏覽:59日期:2022-06-29 15:13:44

這個屬于我項目中一個函數,跟大家分享一下我的思路及最終實現

在編寫串口通信工具中,需要實現一個函數,自動找到對應com 口,并且連接該com口,保證后續通信正常作為初始化過程的一部分。

思路

在win 設備管理器中,經常會出現多個com 口,但并不是每個com 口都是目標設備所鏈接的。嘗試打開每個com 口,輸入enter 按鍵, 正確的com 口,會有ack log 返回,表明通信 正常

否則,沒有任何log 返回,則判斷為非目標設備所連接的com 口。

實現

python 自動識別并連接串口的實現

嘗試去打開所有com 口,然后發送enter, 如果在一段時間內有返回值,檢查com 口收到的字節數,如果非零,則表明找到了對應的com 口。

完整測試代碼如下:

import serialimport serial.tools.list_portsimport threadingimport binasciiimport timefrom datetime import datetime# default valuebaunRate = 115200is_read = Falseis_write = Falsewrite_buff = []sys_buff = []mSerial = Nonecallback = Noneis_opened = 0is_registed = 0class SerialPort: def __init__(self,port,buand): self.port = serial.Serial(port,buand) self.port.close() if not self.port.isOpen(): self.port.open() #the index of data_bytes for read operation,私有屬性 #only used in read lines self.__read_ptr = 0 self.__read_head = 0 #store all read bytes # used in read date, read lines self.__data_bytes = bytearray() def port_open(self): if not self.port.isOpen(): self.port.open() def port_close(self): self.port.close() def send(self): global is_write global write_buff while is_write: if len(write_buff):msg = write_buff.pop(0)msg = msg+'n'cmd = msg.encode()try: self.port.write(cmd)except: write_buff.clear() is_write = False write_buff.clear() def read_data(self): global is_read global is_opened byte_cnt = 0 while is_read: try:count = self.port.inWaiting()if count > 0: rec_str = self.port.read(count) self.__data_bytes = self.__data_bytes+rec_str#print('receive:',rec_str.decode()) #print(rec_str) byte_cnt += count if not is_opened: is_opened = 1 #print('累計收到:',byte_cnt) #time.sleep(0.5)self.read_lines() except:deinit() #將當前所有的數據都讀出,讀取位置不變,每次讀取指針依次移動,不漏數據, 讀取行為一直在進行 def read_lines(self): #reset line_cnt = 0 data_len = len(self.__data_bytes) #print ('') #print ('begin: prt=:', self.__read_ptr, ' head =', self.__read_head,'current len =',data_len) if self.__read_ptr >=data_len: return #get all lines in current data_bytes while(self.__read_ptr < data_len-1): if(self.__data_bytes[self.__read_ptr+1] == 0x0a and self.__data_bytes[self.__read_ptr] == 0x0d):tmp = bytearray()tmp = self.__data_bytes[self.__read_head:self.__read_ptr]try: line = tmp.decode()except: self.__read_head = self.__read_ptr + 2 self.__read_ptr = self.__read_head continueiprint(line)line_cnt += 1self.__read_head = self.__read_ptr + 2self.__read_ptr = self.__read_head else:self.__read_ptr = self.__read_ptr + 1def auto_open_serial(): global baunRate global mSerial global callback global is_registed global is_opened #reset deinit() # 列出所有當前的com口 port_list = list(serial.tools.list_ports.comports()) port_list_name = [] #get all com if len(port_list) <= 0: iprint('the serial port can’t find!') return False else: for itms in port_list: port_list_name.append(itms.device) #try open #print(port_list_name) for i in port_list_name: try: mSerial = SerialPort(i,baunRate) iprint('try open %s'%i) start_task() send('') #return True time.sleep(1) if is_opened:iprint('connect %s successfully'%i)return True else:deinit()if i == port_list_name[len(port_list_name)-1]: iprint('uart don’t open') breakcontinue except: iprint(' uart don’t open') deinit() return Falsedef deinit(): global mSerial global is_write global is_read global write_buff global is_opened if mSerial: mSerial.port_close() is_opened = 0 is_read = False is_write = False write_buff = [] mSerial = None time.sleep(1)def init(): global mSerial global callback global is_registed global is_opened global is_read global is_write #retry retry_time = 0 while not auto_open_serial(): if not is_opened: iprint('wait for uart connect, retry %s'%str(retry_time)) else: return True retry_time += 1 time.sleep(2) if retry_time == 10: iprint(' open uart fail') return Falsedef send(msg): global mSerial global is_write global write_buff if is_write: write_buff.append(msg)def start_task(): global mSerial global is_write global is_read if mSerial: is_write = True t1 = threading.Thread (target=mSerial.send) t1.setDaemon (False) t1.start () is_read = True t2 = threading.Thread (target=mSerial.read_data) t2.setDaemon (False) t2.start ()def iprint(msg): global callback global is_registed msg = '[Uart] '+str(msg) if is_registed: callback.append(msg) else: print(msg)def start_sys_cmd(): global is_registed if is_registed: t3 = threading.Thread (target=process_receive_sys_cmd) t3.setDaemon (False) t3.start()def process_receive_sys_cmd(): global sys_buff global is_registed global callback #print('process_receive_sys_cmd') while is_registed: #print ('wait,process_receive_sys_cmd') if len(sys_buff): #print ('receive,process_receive_sys_cmd') line = sys_buff.pop(0) if 'init' in line:if is_opened and is_read and is_write: iprint('already open uart') breakiprint('start init')init() if is_opened: break iprint('Eixt uart sys thread')def register_cback(list): global callback global is_registed callback = list is_registed = 1def unregister_cback(): global callback callback.clear()if __name__ == ’__main__’: receive = [] register_cback(receive) sys_buff.append('init') start_sys_cmd() def process_receive_msg(): global receive while True: #print('wait') if len(receive):#print('receive')print(receive.pop(0)) t = threading.Thread(target=process_receive_msg) t.setDaemon(False) t.start()

到此這篇關于python 自動識別并連接串口的實現的文章就介紹到這了,更多相關python 自動識別并連接串口內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 光伏家 - 太阳能光伏发电_分布式光伏发电_太阳能光伏网 | 合肥注册公司|合肥代办营业执照、2024注册公司流程 | 润滑脂-高温润滑脂-轴承润滑脂-食品级润滑油-索科润滑油脂厂家 | 京港视通报道-质量走进大江南北-京港视通传媒[北京]有限公司 | T恤衫定做,企业文化衫制作订做,广告T恤POLO衫定制厂家[源头工厂]-【汉诚T恤定制网】 | 交通信号灯生产厂家_红绿灯厂家_电子警察监控杆_标志杆厂家-沃霖电子科技 | 氢氧化钙设备, 氢氧化钙生产线-淄博惠琛工贸有限公司 | 重庆轻质隔墙板-重庆安吉升科技有限公司| 袋式过滤器,自清洗过滤器,保安过滤器,篮式过滤器,气体过滤器,全自动过滤器,反冲洗过滤器,管道过滤器,无锡驰业环保科技有限公司 | 阴离子_阳离子聚丙烯酰胺厂家_聚合氯化铝价格_水处理絮凝剂_巩义市江源净水材料有限公司 | 渗透仪-直剪仪-三轴仪|苏州昱创百科 | 水质传感器_水质监测站_雨量监测站_水文监测站-山东水境传感科技有限公司 | 工程管道/塑料管材/pvc排水管/ppr给水管/pe双壁波纹管等品牌管材批发厂家-河南洁尔康建材 | 不锈钢管件(不锈钢弯头,不锈钢三通,不锈钢大小头),不锈钢法兰「厂家」-浙江志通管阀 | 小港信息港-鹤壁信息港 鹤壁老百姓便民生活信息网站 | 西安标准厂房_陕西工业厂房_西咸新区独栋厂房_长信科技产业园官方网站 | 非标压力容器_碳钢储罐_不锈钢_搪玻璃反应釜厂家-山东首丰智能环保装备有限公司 | 企业管理培训,企业培训公开课,企业内训课程,企业培训师 - 名课堂企业管理培训网 | 四川成人高考_四川成考报名网| 济南电缆桥架|山东桥架-济南航丰实业有限公司 | 道康宁消泡剂-瓦克-大川进口消泡剂供应商 | 广西绿桂涂料--承接隔热涂料、隔音涂料、真石漆、多彩仿石漆等涂料工程双包施工 | 手术示教系统-数字化手术室系统-林之硕医疗云智能视频平台 | 渗透仪-直剪仪-三轴仪|苏州昱创百科 | 冷镦机-多工位冷镦机-高速冷镦机厂家-温州金诺机械设备制造有限公司 | 陕西安闸机-伸缩门-车牌识别-广告道闸——捷申达门业科技 | 山东集装箱活动房|济南集装箱活动房-济南利森集装箱有限公司 | 皮带机_移动皮带机_大倾角皮带机_皮带机厂家 - 新乡市国盛机械设备有限公司 | 尊享蟹太太美味,大闸蟹礼卡|礼券|礼盒在线预订-蟹太太官网 | 铁艺,仿竹,竹节,护栏,围栏,篱笆,栅栏,栏杆,护栏网,网围栏,厂家 - 河北稳重金属丝网制品有限公司 山东太阳能路灯厂家-庭院灯生产厂家-济南晟启灯饰有限公司 | 天津仓储物流-天津电商云仓-天津云仓一件代发-博程云仓官网 | lcd条形屏-液晶长条屏-户外广告屏-条形智能显示屏-深圳市条形智能电子有限公司 | 天空彩票天下彩,天空彩天空彩票免费资料,天空彩票与你同行开奖,天下彩正版资料大全 | 水成膜泡沫灭火剂_氟蛋白泡沫液_河南新乡骏华消防科技厂家 | 编织人生 - 权威手工编织网站,编织爱好者学习毛衣编织的门户网站,织毛衣就上编织人生网-编织人生 | 珠海冷却塔降噪维修_冷却塔改造报价_凉水塔风机维修厂家- 广东康明节能空调有限公司 | 仓储货架_南京货架_钢制托盘_仓储笼_隔离网_环球零件盒_诺力液压车_货架-南京一品仓储设备制造公司 | 快速卷帘门_硬质快速卷帘门-西朗门业 | 厦门网站建设_厦门网站设计_小程序开发_网站制作公司【麦格科技】 | 手术室净化装修-手术室净化工程公司-华锐手术室净化厂家 | 动物麻醉机-数显脑立体定位仪-北京易则佳科技有限公司 |