def read_vars(): """Send read request message to remote device and wait for response, then update values""" global sent_messages serial_port = serial.Serial(PORT, BAUD_RATE) xbee = DigiMesh(serial_port, escaped=True) # , callback=message_received # Send read request message # TODO: Broadcast? for device in Device.objects.filter(active=True): if sent_messages: sent_messages.sort() message_id = sent_messages[-1] + 1 else: message_id = 1 logger.info('Sending message to device %s', device.slug) msg_request = struct.pack('HB', message_id, READ_REQUEST) try: xbee.tx(dest_addr=bytearray.fromhex(device.address), data=msg_request) except ValueError as e: logger.error("Message not sent to device %s", device.slug, exc_info=1) else: # Add message id to queue sent_messages.append(message_id) while sent_messages: # TODO: Why using callback function not working packet = xbee.wait_read_frame() message_received(packet) break # TODO: Implement something to clean sent_messages queue and remove this break serial_port.close()
import time from xbee import DigiMesh import serial #PORT = 'COM7' PORT = '/dev/cu.usbserial-A9CNVHXX' BAUD_RATE = 9600 # Open serial port ser = serial.Serial(PORT, BAUD_RATE) # Create API object xbee = DigiMesh(ser, escaped=True) import pprint pprint.pprint(xbee.api_commands) # xbee with long address XBEE2_ADDR_LONG = "\x00\x00\x00\x00\x00\x00\xFF\xFF" while True: try: print "send data" xbee.tx(frame='0x1', dest_addr=XBEE2_ADDR_LONG, data='Hello XBee 2') time.sleep(1) except KeyboardInterrupt: break xbee.halt() ser.close()
class CommNode: def __init__(self, location): self.serial_port = '/dev/ttyUSB1' self.baud_rate = 57600 self.broadcast_addr = b'\x00\x00\x00\x00\x00\x00\xff\xff' self.ser = serial.Serial(self.serial_port, self.baud_rate) time.sleep(1) try: self.xbee_device = DigiMesh(self.ser, callback=self.xbeeCallback) except: rospy.logwarn("!!!! ERROR - DigiMesh OBJECT NOT INITIALIZED !!!!") if location == 'AGENT': # Comm node onboard agent rospy.loginfo(" ::: NODE INITIALIZED AS AGENT COMM NODE ::: ") rospy.Subscriber("AgentInformation", AgentInfo, self.agentCallback) self.pubTasks = rospy.Publisher("AgentTasks", TaskMessage, queue_size=10) self.pubInit = rospy.Publisher("AgentInit", InitMessage, queue_size=10) elif location == 'GND': # Comm node on ground station rospy.loginfo(" ::: NODE INITIALIZED AS GCS COMM NODE ::: ") rospy.Subscriber("TaskActions", TaskMessage, self.tasksCallback) rospy.Subscriber("InitInformation", InitMessage, self.initCallback) self.pubEnemy = rospy.Publisher("EnemyInfo", EnemyInfo, queue_size=10) self.pubAgent = rospy.Publisher("AgentInfo", AgentInfo, queue_size=10) else: rospy.logwarn( "!!!! ERROR - COMM NODE TYPE NOT RECOGNISED - %s !!!!", location) self.fConv = FrameConvertor() ''' Python implementation of switch statement to publish to ROS topics ''' # These functions are shared for all comm nodes, only the relevant ones will be used def xbeeCallback(self, data): '''def pubInitMsg(self,msg): self.pubInit(msg) def pubTaskMsg(self,msg): self.pubTasks(msg) def pubAgentMsg(self,msg): # convert frame self.pubAgent(msg) def pubEnemyMsg(self,msg): # convert frame self.pubEnemy(msg) ''' def StringToROSTaskMsg(string): msg = TaskMessage() msgStr = string.split('|') # Split string into array of strings msg.agentId = int(msgStr[1]) msg.taskId = int(msgStr[2]) msg.targetId = int(msgStr[3]) msg.taskLocation[0] = float(msgStr[4]) msg.taskLocation[1] = float(msgStr[5]) msg.taskLocation[2] = float(msgStr[6]) msg.taskDeadline = float(msgStr[7]) msg.timestamp = float(msgStr[8]) return msg def StringToROSInitMsg(string): msg = InitMessage() msgStr = string.split('|') msg.agentId = int(msgStr[1]) msg.homeLocation[0] = float(msgStr[2]) msg.homeLocation[1] = float(msgStr[3]) msg.homeLocation[2] = float(msgStr[4]) msg.nominalHeading = float(msgStr[5]) return msg def StringToROSAgentMsg(string): msg = AgentInfo() msgStr = string.split('|') msg.agentId = int(msgStr[1]) msg.agentPosition[0] = float(msgStr[2]) msg.agentPosition[1] = float(msgStr[3]) msg.agentPosition[2] = float(msgStr[4]) msg.agentHeading = float(msgStr[5]) msg.agentBattery = float(msgStr[6]) if msgStr[7] == 'False': msg.agentPayload = False elif msgStr[7] == 'True': msg.agentPayload = True if msgStr[8] == 'False': msg.agentTaskStatus = False elif msgStr[8] == 'True': msg.agentTaskStatus = True msg.agentTaskId = int(msgStr[9]) if msgStr[10] == 'False': msg.agentWorkingStatus = False elif msgStr[10] == 'True': msg.agentWorkingStatus = True msg.taskDeadline = float(msgStr[11]) return msg def StringToROSEnemyMsg(string): msg = EnemyInfo() msgStr = string.split('|') msg.agentId = int(msgStr[1]) msg.confidence = float(msgStr[2]) msg.agentPosition[0] = float(msgStr[3]) msg.agentPosition[1] = float(msgStr[4]) msg.agentPosition[2] = float(msgStr[5]) return msg def StringDefault(string): rospy.loginfo("Received message type not known: %s", string[0]) string = data.get('data') #def stringToMsg(string,msg_orig): str_type = string[0] rospy.loginfo(" :: RECEIVED MESSAGE TYPE - %s ::", str_type) switcher1 = { "T": StringToROSTaskMsg, "I": StringToROSInitMsg, "A": StringToROSAgentMsg, "E": StringToROSEnemyMsg, } # See comment at top to module for string formats func = switcher1.get(str_type, lambda: StringDefault(string)) # return str_type, func(string) #msg_type, msg = stringToMsg(data.get('data')) msg_type = str_type msg = func(string) #msg_orig = None #stringToMsg(data.get('data')) #print msg_type #print msg_orig rospy.loginfo(" :: RECEIVING STRING - %s ::", msg_type) #print 'cucu1' #print msg if msg_type == 'A': print 'pub agents' self.pubAgent.publish(msg) elif msg_type == 'E': print 'pub enemy' self.pubEnemy.publish(msg) elif msg_type == 'I': print 'pub init' self.pubInit.publish(msg) elif msg_type == 'T': print 'pub tasks' self.pubTasks.publish(msg) else: rospy.loginfo(" : IGNORING MESSAGE :") ''' def pubInitMsg(self,msg): self.pubInit.publish(msg) def pubTaskMsg(self,msg): self.pubTasks.publish(msg) def pubAgentMsg(self,msg): # convert frame self.pubAgent.publish(msg) def pubEnemyMsg(self,msg): # convert frame self.pubEnemy.publish(msg) switcher = { "T": pubTaskMsg, "I": pubInitMsg, "A": pubAgentMsg, "E": pubEnemyMsg, } print 'cucu' if msg_type not in switcher: print " : IGNORING MESSAGE :" else: print "hell2" func = switcher.get(msg_type) #print msg func(msg) print msg''' def txString(self, str_msg): rospy.loginfo(" :: TRANSMITTING STRING ::") bin_str = stringToBinary(str_msg) try: self.xbee_device.tx(frame_id=b'\x10', dest_addr=self.broadcast_addr, data=bin_str) except: rospy.logwarn("!!!! ERROR - FAILURE TO TRANSMIT STRING !!!!") ''' Agent Comm functions ''' def agentCallback(self, data): rospy.loginfo("Recevived agent msg") str_msg = msgToString(data) self.txString(str_msg) ''' GCS Comm functions ''' def initCallback(self, data): ''' Local -> World Frame''' rospy.loginfo(" :: SENDING INITIALIZATION MESSAGE :: ") initInfo = data worldPos, worldHead = self.fConv.localToWorldFrame( data.homeLocation, data.nominalHeading) initInfo.homeLocation = worldPos initInfo.nominalHeading = worldHead # EDIT: send through xbee instead of publishing str_msg = msgToString(initInfo) self.txString(str_msg) #self.pubInit.publish(initInfo) def tasksCallback(self, data): ''' Local -> World Frame ''' rospy.loginfo(" :: SENDING TASK MESSAGE :: ") taskInfo = data worldPos, worldHead = self.fConv.localToWorldFrame( data.taskLocation, 0) taskInfo.taskLocation = worldPos # EDIT: send through xbee instead of publishing str_msg = msgToString(taskInfo) self.txString(str_msg) #self.pubTasks.publish(taskInfo) def enemyCallback(self, data): #str_msg = msgToString(data) #self.txString(str_msg) self.pubEnemy.publish(enemyInfo)
####################################################################### ## Scrip Start ####################################################################### xbee = ZigBee(ser=ser, escaped=True, callback=persist_data) digi = DigiMesh(ser=ser) url = baseurl + '/field_device' all_devices = requests.get(url, headers=headers).json()['objects'] while True: try: for device in all_devices: address = device['serial_id'] print("{0} - Requesting data from {1}".format( datetime.datetime.now(), address)) digi.tx(frame_id=b'\x01', dest_addr=bytes.fromhex(address), data=b'D') ## digi.tx(frame_id = b'\x01', dest_addr=address.decode('hex'), data=b'D') ## Request new data every five minutes. time.sleep(5 * 60) except KeyboardInterrupt: break # http://Tqbfj07ld xbee.halt() ser.close()
}) wf.seek(0, 0) fileReader = csv.DictReader(wf, fieldnames=fieldnames) mtuBreaker = 0 for row in fileReader: fileText = fileText + row['Test'] + ':' + row['Car'] + ' ' #fileArray.append(row['Test'] + ':' + row['Car']) mtuBreaker += 1 #Split into multiple packets if the file is longer than the mtu of 42 if mtuBreaker == 5: byteVar = bytearray() byteVar.extend(map(ord, fileText)) xbee.tx(id=b'\x10', frame_id=b'\x01', dest_addr=b'\x00\x00\x00\x00\x00\x00\xFF\xFF', options=b'\x00', data=byteVar) mtuBreaker = 0 fileText = '1 ' #if a packet of five was not completed, send the remaining if mtuBreaker != 0: byteVar = bytearray() byteVar.extend(map(ord, fileText)) xbee.tx(id=b'\x10', frame_id=b'\x01', dest_addr=b'\x00\x00\x00\x00\x00\x00\xFF\xFF', options=b'\x00', data=byteVar) #print(fileArray)
import array ser = serial.Serial('/dev/ttyUSB0', 9600) c=0 # Use an XBee 802.15.4 device xbee = DigiMesh(ser) with open('addresses.csv', 'r') as f: reader = csv.DictReader(f, dialect='excel-tab') for row in reader: if row['Car'] == '10': print(row['Car'], row['Address']) c=unhexlify(row['Address']) #xbee.tx_long_addr(dest_addr=b'\x13\xA2\x00\x41\x54\x53\xBC\xFE') a=b'\x10' b=b'\x01' #c=b'\x00\x13\xA2\x00\x41\x54\x53\xD0' c=b'\x00\x00\x00\x00\x00\x00\xFF\xFF' d=b'\x00' t1='15' t2='03' t3='33:33:33' tt= '0:' + t1 + ',' + t2 + ',' + t3 e= bytearray() e.extend(map(ord, tt)) print(c) xbee.tx(id=b'\x10', frame_id=b, dest_addr=c, radius=b'\x01', options=d, data=e) #response = xbee.wait_read_frame() #print(chr(response['status'])) #if response != '\x00': # print('error')