如何区分特定设备与多个串行COM端口?

问题描述

我正在编写一个python程序。该程序的功能之一是通过USB从GPS接收器获取当前的纬度和经度。但是,计算机必须通过USB连接OBD-II(车载诊断程序)才能从车辆获取数据。我可以在计算机中找到所有可用的串行COM端口,但是我无法将GPS接收器与串行COM端口区分开,因为这两个设备在计算机中代表相似的标签

标签

Prolific USB-to-Serial Comm Port (COM5)
Prolific USB-to-Serial Comm Port (COM6)

我的测试代码

import serial
import pynmea2
import time
import traceback
import serial.tools.list_ports

def get_NMEA2_GPS():
    try:
        portList = list(serial.tools.list_ports_windows.comports())
        ser = None
        for port in portList:
            # print("-"*10)
            # print(port.usb_info())
            # print("Port: [%s],device: [%s],description: [%s]" %(str(port),str(port.device),str(port.description)))
            if "Prolific USB-to-Serial Comm Port" in port.description:
                ser = serial.Serial(port[0],"4800",timeout = 1.0)
                print("Start to obtain GPS via NMEA")
                break
            # End of if-condition
        # End of for-loop
        
        
        while True:
            # print("GPS data:" + data )
            data = ser.readline().decode('ascii').strip()
            print(data)
            try:  
                msg = pynmea2.parse(data)
                
            except pynmea2.nmea.ParseError:
                print("Warning: The checksum of the sentence is wrong!")
                continue
            except UnicodeDecodeError:
                continue
            else: 
                if msg.sentence_type == "RMC":
                    latitude = msg.latitude
                    longitude = msg.longitude
                    print("----The current position: %2.8f,%3.8f" %(latitude,longitude))
            # time.sleep(0.1)  
    except KeyboardInterrupt:
        print("Stop obtain GPS @R_228_4045@ion!")
        ser.close()
    except Exception:
        print("Error: 無法與GPS sensor連線")
        traceback.print_exc()

def main():
    get_NMEA2_GPS()
    print("="*60)
    print("Finish!")
    input("Please enter any key!")
# End of main

if __name__ == "__main__":
    main()
# End of if-condition

我确定COM5是GPS接收器,而COM6是OBD-II。但是,GPS接收器的COM端口可能会更改,因为我不能期望用户将GPS接收器插入相同的USB端口。顺便说一下,我使用的操作系统是Windows 10 64位。有人可以给我任何建议吗?

解决方法

Com端口具有要搜索的“描述”部分,似乎无法通过两个设备之间的描述来识别。我会看一下硬件ID,我猜这些将是唯一的? port.hwid这就是我要开始的地方。也许打印每个端口提供给您的所有信息,并寻找其他可识别的信息。

我不太了解您正在查看的两个设备的硬件。我只知道我过去曾经使用过hwid(或使用某些usb,vid / pid或序列号)

https://pyserial.readthedocs.io/en/latest/tools.html