【问题标题】:Python Serial on Windows: USB monitor loop while reading serial information does not workWindows 上的 Python 串行:读取串行信息时 USB 监视器循环不起作用
【发布时间】:2019-08-02 12:50:11
【问题描述】:

我有一个网站和一个 USB rfid 阅读器。 python 脚本监视与 rfid 阅读器的 USB 连接。如果在脚本开头没有连接阅读器,则网站内容向右滑动并显示连接 rfid 阅读器的 USB 电缆的说明。如果然后连接,它会向左滑动并显示用户使用 rfid 卡来识别自己。阅读器只有在视口中有特定内容时才开始阅读 rfid 数据。但是我没有进入这一步,因为串行通信似乎被阻止了。

import serial 
import mysql.connector
import time
import datetime
from serial.tools import list_ports
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.common.keys import Keys
capabilities = webdriver.DesiredCapabilities().FIREFOX
capabilities["marionette"] = True
binary = FirefoxBinary('C:/Program Files/Mozilla Firefox/firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary, capabilities=capabilities, executable_path="C:/Python37x64/geckodriver.exe")

# ------------------ USB monitorloop -------------------------------------

stop = 0
swipe = 0
driver.get('https://website.php')
while True:
    try:
        myports = [tuple(p) for p in list(serial.tools.list_ports.comports())]
        arduino_port = [port for port in myports if 'COM3' in port ][0]
        def check_presence(correct_port, interval=0.1):
        global swipe
        global stop
            while True:
                myports = [tuple(p) for p in list(serial.tools.list_ports.comports())]
                if arduino_port not in myports:
                    stop = 1
                    swipe = swipe + 1
                    if swipe == 1:
                        print ("Arduino has been disconnected!")
                        driver.execute_script("$('.in_viewport,#usb_connect, #header_usb_connect').animate({ left: '+='+'100vw'});");
                        time.sleep(1.0)
                    else:
                        continue
                else:
                    if swipe >= 1 and stop == 1:
                        swipe = 0
                        print ("Arduino connected!")
                        driver.execute_script("$('.in_viewport,#usb_connect, #header_usb_connect').animate({ left: '-='+'100vw'});");
                        time.sleep(1.0)
                    else:
                        continue
        import threading
        port_controller = threading.Thread(target=check_presence, args=(arduino_port, 0.5,))
        port_controller.setDaemon(True)
        port_controller.start()
        break
    except:
        stop = 1
        if swipe == 0:
            print("Connect USB cable")
            driver.execute_script("$('.in_viewport,#usb_connect, #header_usb_connect').animate({ left: '+='+'100vw'});");
            time.sleep(1.0)
            swipe = 1
            continue
        else:
            time.sleep(1.0)


# --------- connecting to COM 3 and database -----------------------
device_port = 'COM3'
baud = 9600
while True:
    try:
        print ("Trying...",device_port)
        connect_arduino = serial.Serial(device_port, baud)
        print ("Successfully connected to",device_port)
        print ("Try to connect to database")
        db = mysql.connector.connect(host="",port="",user="",passwd="",db="") 
        print ("Successfully connected to database")
        break
    except mysql.connector.Error as err:
        print("Something went wrong: {}".format(err))
        print ("failed to connect to database")
        time.sleep(1)
        continue
# ------- reading the card identification number and current time -------------        
while True:
    try:
        print ("Reading USB device")
        rfid_data = connect_arduino.readline()
        now = datetime.datetime.now()
        print (rfid_data.decode('utf-8'),"read on", now.strftime("%d-%m-%Y"), "at", now.strftime("%H:%M:%S"))
        time.sleep(2)
        break
    except:
        time.sleep(2)
        continue

我希望能够serial.readline()rfid_data,但我认为监视器环路阻塞了串行端口以及与端口的通信。

【问题讨论】:

    标签: python windows selenium arduino


    【解决方案1】:

    很抱歉在这里介绍基础知识,但是您是否检查过您可以使用其他东西(例如终端仿真器)读取串行端口?

    我在串口方面遇到了无穷无尽的问题,尤其是 USB 版本。当我不想要它时,要么是其他东西抓住了端口,要么是在将 USB 映射到 COM 号时出现了问题。有时您需要其他东西来仔细检查它们。

    【讨论】:

    • 如果我打开Arduino IDE的串口监视器,读卡时会显示rfid卡的数据。 COM端口肯定是COM3。是的,我在使用任何 python 代码之前关闭了 arduino IDE。端口被监控回路阻塞。也许我需要一种全新的方法来处理其他监视器循环。我可能应该使用 windows 事件来让 com 端口打开。
    【解决方案2】:

    我认为您最大的问题是阅读循环中的break 语句。它按预期工作并打破了循环的正常流程,因此您只需调用一次串口读取函数。

    改善循环的一种方法是检查 RX 缓冲区是否为空:

    while True:
        if connect_arduino.inWaiting() != 0:
            print ("Reading USB device")
            rfid_data = connect_arduino.readline()
            now = datetime.datetime.now()
            print (rfid_data.decode('utf-8'),"read on", now.strftime("%d-%m-%Y"), "at", now.strftime("%H:%M:%S"))
    

    如果您仅在确定缓冲区中有数据并且知道 RFID 阅读器发送 \r\n 作为终止字符时才调用 readline(),则您确定您将始终读取标签。

    编辑:看来你想要的是嗅探端口。您不能直接从两个不同的应用程序保持相同的端口打开。如果你在 Windows 上,你可以试试this solution

    【讨论】:

    • 问题是我无法连接到这个端口,因为监控回路一直在使用这个端口。我想监控 USB 电缆的任何移除或重新连接,并在需要时同时读取端口。
    • 好的,我明白你的意思了,我会修改我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    相关资源
    最近更新 更多