示例#1
0
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()
示例#2
0
    def __init__(self, location):
        self.serial_port = '/dev/ttyUSB0'
        self.baud_rate = 57600
        self.broadcast_addr = b'\x00\x00\x00\x00\x00\x00\xff\xff'  # For DigiMesh
        #self.broadcast_addr = b'\xff\xff'                               # For ZigBee

        self.ser = serial.Serial(self.serial_port, self.baud_rate)

        time.sleep(1)

        try:
            self.xbee_device = DigiMesh(self.ser, callback=self.xbeeCallback)
            #self.xbee_device = ZigBee(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)

            self.fConv = FrameConvertor()
        else:
            rospy.loginfo(
                "!!!! ERROR - COMM NODE TYPE NOT RECOGNISED - %s !!!!",
                location)
示例#3
0
    def __init__(self):
        try:
            self.ser = serial.Serial('/dev/ttyUSB1', 9600, 5)
        except serial.SerialException:
            print "Wrong port, trying with a different one"
            self.ser = serial.Serial('/dev/ttyUSB0', 9600, 5)

        self.xbee = DigiMesh(self.ser)
        self.dest_addr = '\x00\x13\xA2\x00\x40\xC1\x65\xCE'

        self.addr_init_low = '\x00\x00\x00\x00'
        self.addr_init_high = '\x00\x00\x00\x00'
        self.chan_init = '\x00'
        self.pan_init = '\x00\x00'

        sleep(5)

        self.load_init()
示例#4
0
class PI_XBEE:
    def __init__(self, com_port):
        self.ser = serial.Serial(com_port, 9600)
        self.zb = DigiMesh(self.ser)
        start_new_thread(self.recv_thread, ())
        self.data = ""
        self.i = 0

    def recv_thread(self):
        #while True:
        incoming = self.zb.wait_read_frame()
        self.data = incoming.get('data').decode("utf-8")
        print(self.data)

    def send_msg(self, message):
        #sending code
        self.zb.send("tx", id = b'\x10', frame_id = b'\x00', \
                     dest_addr = b'\x00\x13\xA2\x00\x41\x54\xF3\xFF', \
                     reserved = b'\xFF\xFE', broadcast_radius = b'\x00', \
                     options = b'\x00', data = 'Obstruction Detected')
示例#5
0
def main(args=None):
    """The main routine."""
    if args is None:
        args = sys.argv[1:]

    try:
        global client
        client = mqtt.Client()
        client.on_connect = on_connect
        client.connect("broker.mqttdashboard.com", 1883, 5)
        time.sleep(1)
    except socket.gaierror as e:
        # print(sys.exc_info()[:2])
        print(str(e))
        exit()

    attached = get_serial_port()

    if attached is not None:
        print("Connected to XBee on {}.\n".format(attached))
        serial_port = serial.Serial(attached, 9600)
        xbee = DigiMesh(serial_port, callback=print_data)
        print("Connected to MQTT Broker.\n")
        client.loop_start()
    else:
        print("Unable to detect XBee.\n")
        exit()

    while True:
        try:
            time.sleep(0.001)
        except KeyboardInterrupt:
            break

    print("Disconnected from MQTT Broker.\n")
    client.disconnect()
    client.loop_stop()
    print("Disconnected from XBee on {}.\n".format(attached))
    xbee.halt()
    serial_port.close()
示例#6
0
class XBEE_PRO:
    """
        Initialize XbeePro instance, it check to which of the USB port it is connected (ttyUSB0 or ttyUSB1), also it sets
        the baudrate to 9600 (works better with this value you are free to try another baudrates: 2400, 4800, 9600, 19200,
        38400, 57600, 115200, 230400, 460800, 921600).
    """
    def __init__(self):
        try:
            self.ser = serial.Serial('/dev/ttyUSB1', 9600, 5)
        except serial.SerialException:
            print "Wrong port, trying with a different one"
            self.ser = serial.Serial('/dev/ttyUSB0', 9600, 5)

        self.xbee = DigiMesh(self.ser)
        self.dest_addr = '\x00\x13\xA2\x00\x40\xC1\x65\xCE'

        self.addr_init_low = '\x00\x00\x00\x00'
        self.addr_init_high = '\x00\x00\x00\x00'
        self.chan_init = '\x00'
        self.pan_init = '\x00\x00'

        sleep(5)

        self.load_init()

    def load_init(self):

        self.xbee.send("at", frame_id='A', command='AP', parameter="\x01")
        response = self.xbee.wait_read_frame()

        self.xbee.send("at", frame_id='F', command='WR')
        response = self.xbee.wait_read_frame()

        self.xbee.send("at", frame_id='A', command='CH')
        response = self.xbee.wait_read_frame()
        self.chan_init = response['parameter']

        self.xbee.send("at", frame_id='B', command='ID')
        response = self.xbee.wait_read_frame()
        self.pan_init = response['parameter']

        self.xbee.send("at", frame_id='C', command='DL')
        response = self.xbee.wait_read_frame()
        self.addr_init_low = response['parameter']

        self.xbee.send("at", frame_id='D', command='DH')
        response = self.xbee.wait_read_frame()
        self.addr_init_high = response['parameter']

        self.xbee.send("at", frame_id='A', command='AP', parameter="\x02")
        response = self.xbee.wait_read_frame()

        self.xbee.send("at", frame_id='F', command='WR')
        response = self.xbee.wait_read_frame()

        self.dest_addr = self.addr_init_high + self.addr_init_low
        """enable encryption"""
        self.xbee.send("at", frame_id='A', command='EE', parameter="\x01")
        response = self.xbee.wait_read_frame()
        """This encryption key represents "UQnetkeYUQnetkeY", if you want to change they key simply
        go to an online converter string->hex and the copy below in parameter, example:
        * if result string->hex = "58551556", then add the scape character before a byte,
        58551556 -> \x58\x55\x15\x56"""

        self.xbee.send(
            "at",
            frame_id='A',
            command='KY',
            parameter=
            "\x55\x51\x6e\x65\x74\x6b\x65\x59\x55\x51\x6e\x65\x74\x6b\x65\x59")
        response = self.xbee.wait_read_frame()

        self.xbee.send("at", frame_id='F', command='WR')
        response = self.xbee.wait_read_frame()

    """
        Set the channel to the DigiMesh antenna to communicate, you will be expecting 2 'OK' responses when you set this,
        one OK for setting the channel, and another one when writing to volatile memory in the device, if not then try
        again.
    """

    def set_chan(self):
        new_chan = raw_input("Enter new channel (from (0C to 17)): ")
        new_chan_hex = unhexlify(new_chan)

        #write the channel
        self.xbee.send("at",
                       frame_id='A',
                       command='CH',
                       parameter=new_chan_hex)
        response = self.xbee.wait_read_frame()
        self.resp_at_parsing(response)

        #write to volatile memory
        self.xbee.send("at", frame_id='F', command='WR')
        response = self.xbee.wait_read_frame()
        self.resp_at_parsing(response)

    """
        Set the panID to the DigiMesh antenna to communicate, you will be expecting 2 'OK' responses when you set this,
        one OK for setting the panID, and another one when writing to volatile memory in the device, if not then try
        again.
    """

    def set_pan_id(self):
        new_pan = raw_input("Enter new PAN ID (from (0000 to FFFF)): ")
        new_pan_hex = unhexlify(new_pan)

        #write the pandID
        self.xbee.send("at", frame_id='B', command='ID', parameter=new_pan_hex)
        response = self.xbee.wait_read_frame()
        self.resp_at_parsing(response)

        #write to volatile memory
        self.xbee.send("at", frame_id='F', command='WR')
        response = self.xbee.wait_read_frame()
        self.resp_at_parsing(response)

    """
        Set the destination address of the DigiMesh antenna, the default value for this variable is 0013A20040C165CE,
        if you are working with a different address then use this function and the variable will change. The variable of the
        address will be used to create the frame that will be sent to the base. You will be expecting three 'OK's responses
        one for setting the LSB of the address, another one when setting the MSB of the address and the last one when
        writting to volatile memory of the device.
    """

    def set_dest_addr(self):
        lower = raw_input("Enter LSBytes (from (00000000 to FFFFFFFF)): ")
        lower_hex = unhexlify(lower)

        #write LSB of the destination address
        self.xbee.send("at", frame_id='C', command='DL', parameter=lower_hex)
        response = self.xbee.wait_read_frame()
        self.resp_at_parsing(response)

        #write MSB of the destination address
        upper = raw_input("Enter MSBytes (from (00000000 to FFFFFFFF)): ")
        upper_hex = unhexlify(upper)
        self.xbee.send("at", frame_id='D', command='DH', parameter=upper_hex)
        response = self.xbee.wait_read_frame()
        self.resp_at_parsing(response)

        #write to volatile memory
        self.dest_addr = upper_hex + lower_hex
        self.xbee.send("at", frame_id='F', command='WR')
        response = self.xbee.wait_read_frame()
        self.resp_at_parsing(response)

    """
        Send the frame to the base, we create a frame because the device is working in API2 mode, it does not matter
        if the receiver (base) is in transparent mode or API2, the message will be receive accordingly to what it is
        needed. Example is the base is set to API2 mode, then we receive the entire frame, if the base is set to
        transparent mode then it will receive only the data needed. 
    """

    def send_data(self, message):
        self.xbee.send("tx",
                       frame_id='G',
                       dest_addr=self.dest_addr,
                       data=message)
        response = self.xbee.wait_read_frame()
        self.resp_tx_parsing(response)

    """
        Check status of the AT commands, if you want to be more specific on the responses you could add more of this
        options in the if statements, ['frame_id'] , ['command'] , ['status'] , ['parameter'].
    """

    def resp_at_parsing(self, response):
        if response['status'] == '\x00':
            print "OK"

        elif response['status'] == '\x01':
            print "ERROR"

        elif response['status'] == '\x02':
            print "Invalid Command"

        elif response['status'] == '\x03':
            print "Invalid Parameter"

        else:
            print "No Response"

    """
        Check status of the TX command, if you want to be more specific on the responses you could add more of this
        options in the if statements, ['frame_id'] , ['reserved'] , ['retries'] , ['deliver_status'] , ['discover_status']
    """

    def resp_tx_parsing(self, response):
        if response['deliver_status'] == '\x00':
            print "Success"

        elif response['deliver_status'] == '\x02':
            print "CCA Failure"

        elif response['deliver_status'] == '\x15':
            print "Invalid Destination Endpoint"

        elif response['deliver_status'] == '\x21':
            print "Network ACK Failure"

        elif response['deliver_status'] == '\x22':
            print "Not Joined to Network"

        elif response['deliver_status'] == '\x23':
            print "Self-addressed"

        elif response['deliver_status'] == '\x24':
            print "Address not found"

        elif response['deliver_status'] == '\x25':
            print "Route not found"

        else:
            print "No Response"

    def gui_save(self, **kwargs):
        for key, value in kwargs.iteritems():
            self.xbee.send("at",
                           frame_id='K',
                           command=key,
                           parameter=unhexlify(value))
            response = self.xbee.wait_read_frame()

            self.xbee.send("at", frame_id='F', command='WR')
            response = self.xbee.wait_read_frame()

            print response
        self.dest_addr = unhexlify(kwargs["DH"]) + unhexlify(kwargs["DL"])

    """
        Close the serial communication of the DigiMesh antenna.
    """

    def close(self):
        self.xbee.halt()
        self.ser.close()
示例#7
0
# coding=utf-8

# requires python-xbee from [email protected]:thom-nic/python-xbee.git

import serial
from xbee import DigiMesh
import struct


def hexify(str):
    return ':'.join(x.encode('hex') for x in str)


serial_port = serial.Serial('/dev/XBEE_SERIAL', 115200)
xbee = DigiMesh(serial_port)

while True:
    try:
        #print serial_port.readline()
        frame = xbee.wait_read_frame()
        data = frame['data']
        seq_num = struct.unpack('B', data[1])[0]
        message_part = struct.unpack('B', data[2])[0]
        message_part_total = struct.unpack('B', data[3])[0]
        message_data = data[4:]
        num_sats = 0
        if len(message_data) > 2 and (message_data[0] == '\xdd'): ##or message_data[0] == '\xde'):
            num_sats = struct.unpack('B', message_data[2])[0]
        print hexify(data)
#        print seq_num, message_part, message_part_total, num_sats, len(data[4:]), hexify(message_data)
示例#8
0
# coding=utf-8

# requires python-xbee from [email protected]:thom-nic/python-xbee.git

import serial
from xbee import DigiMesh
import struct


def hexify(str):
    return ':'.join(x.encode('hex') for x in str)


serial_port = serial.Serial('/dev/XBEE_SERIAL', 115200)
xbee = DigiMesh(serial_port)

while True:
    try:
        #print serial_port.readline()
        frame = xbee.wait_read_frame()
        data = frame['data']
        seq_num = struct.unpack('B', data[1])[0]
        message_part = struct.unpack('B', data[2])[0]
        message_part_total = struct.unpack('B', data[3])[0]
        message_data = data[4:]
        num_sats = 0
        if len(message_data) > 2 and (
                message_data[0] == '\xdd'):  ##or message_data[0] == '\xde'):
            num_sats = struct.unpack('B', message_data[2])[0]
        print hexify(data)
#        print seq_num, message_part, message_part_total, num_sats, len(data[4:]), hexify(message_data)
示例#9
0
import json

# Configuration
BLE_PORT = "/dev/ttyACM0"
BLE_BAUD = 115200
XBEE_PORT = "/dev/ttyAMA0"
XBEE_BAUD = 9600
XBEE_MESH_ID = "1234"  # Xbee DigiMesh Network ID (0x0000 - 0xFFFF)
XBEE_MESH_CH = "0C"  # Xbee DigiMesh Channel ## (0x0C - 0x17)
XBEE_MESH_DH = "0"  # Default destination
XBEE_MESH_DL = "FFFF"  # Default destination
XBEE_MESH_DESC = "\x00\x00\x00\x00\x00\x00\xFF\xFF"  # Escaped Destination

ser_ble = serial.Serial(BLE_PORT, BLE_BAUD, timeout=1)
ser_xbee = serial.Serial(XBEE_PORT, XBEE_BAUD, timeout=1)
xbee = DigiMesh(ser_xbee)

tag_discovered = []  # MAC addresses of identified tags
tag_data = []  # data collected from tags


# divides packet into Xbee MTU and sends
# packet structure {"id", "pn", "dt"}
# all packets share an id generated from hashing the data to send
# the header packet has the total packets to be sent as data
# pn is the packet number (used to join the packets), the header is 0
def packet_send(string):
    random_id = hash(string) % 768 + randint(
        0, 256)  # get and ID by hashing the string
    packet_num = 1  # starting number (from data)
    for piece in [string[x:x + 32] for x in range(0, len(string), 32)
示例#10
0
        url = baseurl + '/log_entry/'
        response = requests.post(url, headers=headers, json=payload)
        print("Response {0}".format(response.status_code))

        ## Handler needed to interpet the responses etc.

    print("END")


#######################################################################
## 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')
示例#11
0
from binascii import unhexlify
import csv
import sys
from xbee import DigiMesh
from xbee.python2to3 import byteToInt, intToByte
import serial
from binascii import hexlify, unhexlify, a2b_uu
ser = serial.Serial('/dev/ttyUSB0', 9600)

xbee = DigiMesh(ser)

while True:
    hexAddress = ""
    x = xbee.wait_read_frame()
    #if a tx packet and not tx_status
    try:
        address = x['source_addr']
    except KeyError:
        continue
    for y in address:
        y = (hex(y))
        hexAddress = hexAddress + y

#    print(x)
    data = x['data']
    data = data.split()
    frameType = data[0].decode('utf-8')
    #If radio receives update
    if frameType == '0':
        #data = 0 TT CC TT:TT:TT
        test = data[1].decode('utf-8')
# http://code.activestate.com/recipes/510399-byte-to-hex-and-hex-to-byte-string-conversion/
def ByteToHex(byteStr):
    return ''.join(["%02X" % ord(x) for x in byteStr]).strip()


def decodeReceivedFrame(data):
    source_addr = ByteToHex(data['source_addr'])
    rf_data = data['data']
    options = ByteToHex(data['options'])
    return [source_addr, rf_data, options]


# Open serial port
ser = serial.Serial(PORT, BAUD_RATE)

# Create API object
xbee = DigiMesh(ser, escaped=True)
import pprint
pprint.pprint(xbee.api_commands)

while True:
    try:
        data = xbee.wait_read_frame()
        decodedData = decodeReceivedFrame(data)
        print(decodedData)

    except KeyboardInterrupt:
        break

xbee.halt()
ser.close()
示例#13
0
#! /usr/bin/python

#import and init an XBee device
from xbee import DigiMesh
from binascii import unhexlify
import csv
import serial
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)
import serial
import time
from xbee import XBee, DigiMesh

serial_port = serial.Serial('/dev/ttyUSB0', 9600)


def error_call(e):
    print e


def print_data(data):
    print data['data']


xbee = DigiMesh(serial_port,
                callback=print_data,
                escaped=True,
                error_callback=error_call)

while True:
    try:
        time.sleep(0.001)
    except KeyboardInterrupt:
        break

xbee.halt()
serial_port.close()
示例#15
0
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)
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()
示例#17
0
import RPi.GPIO as GPIO
import time, serial
from xbee import DigiMesh
GPIO.setmode(GPIO.BCM)
ser = serial.Serial('/dev/ttyAMA0', 9600)
zb = DigiMesh(ser)
trig = 23
echo = 24
a = [0, 0, 0]
i = 0
feedback = 'Obstruction Detected!'

try:
    #Configure GPIO pins
    GPIO.setup(trig,GPIO.OUT)
    GPIO.setup(echo,GPIO.IN)
    GPIO.output(trig,False)

    time.sleep(1.5) #Delay between detections
    GPIO.output(trig,True)
    time.sleep(0.00001) #Pulse time = 10us
    GPIO.output(trig,False)

    while GPIO.input(echo) == 0:
        pulse_start = time.time() #Records the start time of the pulse

    while GPIO.input(echo) == 1:
        pulse_end = time.time() #Records the end time of the pulse

    pulse_duration = pulse_end - pulse_start #Calculates pulse time
示例#18
0
 def __init__(self, com_port):
     self.ser = serial.Serial(com_port, 9600)
     self.zb = DigiMesh(self.ser)
     start_new_thread(self.recv_thread, ())
     self.data = ""
     self.i = 0
示例#19
0
        root = tkinter.Tk()
    except:
        sys.exit()
    numpad = NumPad(root)
    root.attributes("-fullscreen", True)
    root.mainloop()


btn_list = ['7', '8', '9', '4', '5', '6', '1', '2', '3', 'Back', '0', 'Enter']

state = 0
labelVar = 0
testNum = carNum = carTime = ''

ser = serial.Serial('/dev/ttyUSB0', 9600)
xbee = DigiMesh(ser)


class NumPad(ttk.Frame):
    global labelVar

    def __init__(self, root):
        ttk.Frame.__init__(self, root)
        self.grid()
        self.labelCreate()
        self.entryBoxCreate()
        self.numpadCreate()

    def labelCreate(self, **options):
        global labelVar
        labelVar = StringVar()