Robust communication between Python and Xbee?


I am using Xbee API library for Python to process the data received by the Xbee module. I am wondering how to construct the robust protocol for sending and receiving data. What I would like to build is

  1. send the data request message to power monitoring uint (Xbee in remote).
  2. Receive the transmitted power monitoring data and process it in Python.

If the aforementioned process works in just one time, it would be great, but sometimes it does not work. Thus, I would like to code autonomous acknowledging procedure into this communication. That is

  1. send the data request message to power monitoring uint (Xbee in remote).
  2. If the dat is not received, go back to 1.
  3. If the data is received ok.

Here are my code, but it does not work all the time. Would you please look at how can I improve the code further to make it this ? The code is attached

def listeningAndClusterData(targetWT):

#targetWT–>this will be used to construct the target address
targetAddress = struct.pack(‘b’,0x00)+struct.pack(‘b’,targetWT)
Data = struct.pack(‘h’,0x0000) #prefix for requesting information
xbee.tx(dest_addr=targetAddress, data=Data)
response = xbee.wait_read_frame(100)
#wait for data packet from Xbee, if packet is not recieved within 100ms, return 1

watingData = 1;
while watingData:

if response != 1: # if the data is received
sa = hex(response[‘source_addr’])
rf = hex(response[‘rf_data’])
agentId = int(sa[2:4],24)

if datalength is compatible with two floats

if datalength==16:
watingData = 0 # I received the average data and escape the loop
else: #data is received but the format is not correct

if watingData != 0: #if the data is not received–> keep sending the request message
xbee.tx(dest_addr=targetAddress, data=Data)
print(“data is requested again”)
response = xbee.wait_read_frame(100)

except KeyboardInterrupt:

return voltage, current, power

power_monitoring.txt (1.76 KB)