Search code examples
pythonxbee

A timeout is missing in XBee API Python library


I have a problem with this library: https://code.google.com/p/python-xbee/

There is the xbee.wait_read_frame() function without a timeout.

I am testing all serial ports for a signal, but if i cannot timout a try there is no way to do it.

Is there a posibility in Python to upgrade this function without editing the library? Or with small changes inside the library?

ports_available = []

for port in range(0,20):
    try:
        ser = serial.Serial(port, 9600)
        ports_available.append(port)
        ser.close()
    except:
        pass

print(ports_available)

for port in ports_available:
        ser = serial.Serial(port, 9600)
        bee = ZigBee(ser)
        bee.at(command=b"MY")
        print(bee.wait_read_frame()) #<----------
        ser.close()

Solution

  • Looks like you need to use the asynchronous mode described on page 3 of the documentation. It might be tricky unless the data frame includes a parameter for the serial port that received it. If it doesn't, you won't be able to connect the data to port that received it.

    import serial
    import time
    from xbee import XBee
    
    serial_port = serial.Serial('/dev/ttyUSB0', 9600)
    
    def print_data(data): """
        This method is called whenever data is received
        from the associated XBee device. Its first and
        only argument is the data contained within the
        frame.
        """
        print data
    
    xbee = XBee(serial_port, callback=print_data)
    
    while True:
        try:
            time.sleep(0.001)
        except KeyboardInterrupt:
            break
    
    xbee.halt()
    serial_port.close()