'How to build an XBee Hex Long address in Python
I am trying to build an XBee dest_addr_long (Hex address of the XBee) but I keep getting error
ValueError: The data provided for 'dest_addr_long' was not 8 bytes long
I have tried the example:
device={
"CO3":'\x00\x13\xa2\x00\x40\x52\x8d\x8a'
}
and this works, but I don't know the address until the device shows up on my PAN and then I get the address and store it in a database and change the Node ID.
Here is my code and how I am trying to generate the XBee Address
xbee_source_addr_long = xbee_packet['source_addr_long']
source_addr_long= ''.join(x.encode('hex') for x in xbee_source_addr_long)
xbee_source_addr_long_hex = (r"\x" + str(source_addr_long [0:2]) +
r"\x" + str(source_addr_long [2:4]) +
r"\x" + str(source_addr_long [4:6]) +
r"\x" + str(source_addr_long [6:8]) +
r"\x" + str(source_addr_long [8:10]) +
r"\x" + str(source_addr_long [10:12]) +
r"\x" + str(source_addr_long [12:14]) +
r"\x" + str(source_addr_long [14:16]))
This gives me a string in the correct format but the len is 32.
Question: How can I take the source_addr_long and generate a readable string that has a len of 8 and looks like this \x00\x13\xa2\x00\x40\x52\x8d\x8a
Solution 1:[1]
Take a look at Python's struct.pack() function. It can convert your array of values into a packed structure of bytes.
If you're going to be using XBee modules from Python, you might want to try the Open Source python-xbee library.
Something like:
struct.pack( "BBBBBBBB",
xbee_source_addr_long[0],
xbee_source_addr_long[1],
xbee_source_addr_long[2],
xbee_source_addr_long[3],
xbee_source_addr_long[4],
xbee_source_addr_long[5],
xbee_source_addr_long[6],
xbee_source_addr_long[7]);
Note that I'm not a Python programmer, so there might be an easier way to pull that off.
Solution 2:[2]
This post can solve your problem .
Assume, you are having following scenario .
source_addr = ['0x8f', '0x18']
source_addr_long = ['0x00', '0x13', '0xa2', '0x00', '0x40', '0xb5', '0xad', '0x6e']
# Coordinator transmit packet to any router .
# Decision can be taken at run time by coordinator.
# One to many nodes transmission is thus possible.
xbee1.tx
(
frame='0x1'
, dest_addr=bytearray( int(x,16) for x in source_addr)
, data='Hi'
, dest_addr_long= bytearray( int(x,16) for x in source_addr_long)
)
# It will Work . Go to very basic thing .
# string to int , int to hex , hex to int .
# hex(19) => '0x13'
# int('0x13',16) => 19
# x = '0x13'
# then int(x,16) will be 19
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Khaled.K |
