在python DigiXBee API中多次打开同一端口时出现问题

2024-10-08 21:12:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解为什么我不能用Digi Xbee(import Digi.Xbee)API为python多次打开相同的串行端口,而用Xbee(import Xbee)API为python多次打开相同的串行端口

当我运行下面的代码时,会引发异常digi.xbee.exception.InvalidOperatingModeException: Could not determine operating mode

from digi.xbee.devices import *
import time
import codecs


class start(object):
            
    while True:
        xbeeApi2 = DigiMeshDevice(port='/dev/ttyUSB0', baud_rate=9600)
        xbeeApi2.open()
        time.sleep(0.5)
        message = xbeeApi2.read_data(timeout=None)
        if message is not None:
            print(codecs.decode(message.data, 'utf-8'))  
        time.sleep(1) 

XBee模块是一个S2C(XB24C),设置为Digimesh 2.4 TH,固件9002(最新),带有USB加密狗。 Python是3.7&;我的主机硬件是运行Debian的Raspberry Pi 3 B+

任何帮助都将不胜感激

编辑1 第二次执行{xbeeApi2.open()}时引发异常。 事实上,我的原始代码有多个线程导入打开端口的类,在前一个线程有机会关闭它之前很多次。 运行良好的“原始”代码如下:

from xbee import ZigBee
import serial
import time



class start(object):
    
    while True:
        ser = serial.Serial('/dev/ttyUSB0', 9600)
        xbeeApi2 = ZigBee(ser, escaped=True)  # S2 e S2C
        time.sleep(0.5)
    message = ''
        try:
            message = xbeeApi2.wait_read_frame(timeout=0.5)
        except:
            pass #timeout exception
        if message is not None:
            print(message)
        time.sleep(1)

Tags: 端口代码importnoneapitruemessagetime
1条回答
网友
1楼 · 发布于 2024-10-08 21:12:41

好吧,你没有关上它。为什么不创建设备并在while True循环之前打开它呢

您可以将它配置为在message is None时只休眠0.1秒,以减少处理器负载。通过这种方式,您将能够跟上消息队列。如果有消息,您希望在进行任何睡眠之前立即检查另一个排队的消息

from digi.xbee.devices import *
import time
import codecs

class start(object):
    xbeeApi2 = DigiMeshDevice(port='/dev/ttyUSB0', baud_rate=9600)
    xbeeApi2.open()
    while True:
        message = xbeeApi2.read_data(timeout=None)
        if message is not None:
            print(codecs.decode(message.data, 'utf-8'))
        else:
            time.sleep(0.1) 

相关问题 更多 >

    热门问题