如何在pyserial中独占打开串口设备?

问题描述 投票:0回答:1

我想在ubuntu 20.04中仅通过pyserial打开串口设备。我尝试了以下两种方法。

  1. 在 pyserial 中使用独占标志。
ser = Serial(port=serialdevice, baudrate=115200, bytesize=8, timeout=2, exclusive=True)
  1. 使用 fcntl 如下。
        try:
            ser = Serial(port=serialdevice, baudrate=115200, bytesize=8, timeout=2)
            if ser.isOpen():
                try:
                    fcntl.flock(ser.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
                except Exception as e:
                    print(e)

        except Exception a e:
                    print(e)

这两种方法都不起作用。 /var/lock 下没有生成任何锁定文件。

最后,我只能在 /var/lock 下手动创建锁定文件,如下所示。

   try:
        device_name = serialdevice.split("/")[2]

        lock_file_name = "/var/lock/LCK.."+device_name
        ser = Serial(port=serialdevice, baudrate=115200, bytesize=8, timeout=2)
        if ser.isOpen():
            open(lock_file_name, 'w').write(str(os.getpid()))
        else:
            print("port not open")

    except Exception as e:
        print("Failed to open serial port exclusively. Pls check if the serial port is already used by other tools")
        print(e)
        return

请问前两种方法可能有什么问题?专门打开串口一般采用手动方式吗? python脚本退出时需要手动删除lock文件吗?

谢谢!

python ubuntu pyserial
1个回答
0
投票
  1. 在 pyserial 中使用独占标志。

使用

exclusive=True
创建串行对象将导致pyserial在内部使用flock来锁定串行设备,正如我们在serialposix.py的源代码中看到的那样。

  1. 使用 fcntl 如下。

这和第一种方法一样重要。

/var/lock 下没有生成任何锁定文件。

上面的方法锁定了串行字符设备文件,因此你不会看到 /var/lock 下生成的文件,因为锁定文件实际上是

/dev/ttyXXX
文件本身。

您的最终方法将不起作用,您只创建一个名为

"/var/lock/LCK.."+device_name
的文件,但不会发生锁定。如果您想使用最终方法来使用单独的锁定文件,您仍然需要自己对
"/var/lock/LCK.."+device_name
文件进行集群。示例:

try:
    device_name = serialdevice.split("/")[2]

    lock_file_name = "/var/lock/LCK.."+device_name
    ser = Serial(port=serialdevice, baudrate=115200, bytesize=8, timeout=2)
    if ser.isOpen():
        lock_file = open(lock_file_name, 'w')
        fcntl.flock(lock_file, fcntl.LOCK_EX)
        lock_file.write(str(os.getpid()))
    else:
        print("port not open")

except Exception as e:
    print("Failed to open serial port exclusively. Pls check if the serial port is already used by other tools")
    print(e)
    return

您实际上不需要删除该文件,因为它几乎不占用任何空间,但清理起来很好。

© www.soinside.com 2019 - 2024. All rights reserved.