Example #1
0
 def send_command(self, command):
     XBee(serial.Serial(PORT, BAUDRATE)).tx(dest_addr=self.source_addr,
                                            data=command)
import binascii
"""
Location/Site of beaglebone for Firebase.  Will change based on location
"""
SITE_NAME = "Jess S Jackson"

if __name__ == '__main__':
    """
	configure UART2.  BB_UART.setup() enables UART2 a.k.a. /dev/ttyO2 on Beaglebone
	"""
    BB_UART.setup('UART2')
    """
	Instantiate xbee module with uart serial port at 9600 baud
	"""
    ser = serial.Serial('/dev/ttyO2', 9600)
    xbee = XBee(ser, escaped=True)
    """
	configure firebase settings
	"""
    cf = config()
    auth = FirebaseAuthentication(cf.firebaseSecret, cf.firebaseEmail, True,
                                  True)
    fb = FirebaseApplication(cf.firebaseURL, auth)
    """
	defined commands FROM sensor
	"""
    s_cmds = {
        'Vegetronix': 'V',
        'IR_Low': 'IL',
        'IR_High': 'IH',
        'IR_Sens': 'Se',
Example #3
0
from serial import Serial
from xbee import XBee
from parameters import *
serial      = Serial(PORT,BAUDRATE)
xbee      = XBee(serial)


def notify_and_wait():
    
    #xbee = XBee(serial_port, callback=execute_command)
    xbee.halt()
    serial_port.close()

def execute_command(message)
    print(message)
Example #4
0
def sendXBeeMessage(address, data):
    PORT = '/dev/ttyUSB0'
    BAUD = 9600
    ser = Serial(PORT, BAUD)
    xbee = XBee(ser)
    xbee.tx(dest_addr='\x00\x01', data=data)
Example #5
0
                  lambda p: p['id'] == 'rx_explicit')
dispatch.register('rx_io_data_long_addr', default_handler,
                  lambda p: p['id'] == 'rx_io_data_long_addr')
dispatch.register('rx_io_data', default_handler,
                  lambda p: p['id'] == 'rx_io_data')
dispatch.register('tx_status', default_handler,
                  lambda p: p['id'] == 'tx_status')
dispatch.register('status', default_handler, lambda p: p['id'] == 'status')
dispatch.register('at_response', at_response_handler,
                  lambda p: p['id'] == 'at_response')
dispatch.register('remote_at_response', default_handler,
                  lambda p: p['id'] == 'remote_at_response')
dispatch.register('node_id_indicator', default_handler,
                  lambda p: p['id'] == 'node_id_indicator')

xbee = XBee(ser, callback=dispatch.dispatch, escaped=True)
dispatch.xbee = xbee

print("run...")
print("")
print("current status:")
xbee.send('at', command=b'ID', frame_id=b'\x01')
xbee.send('at', command=b'SH', frame_id=b'\x01')
xbee.send('at', command=b'SL', frame_id=b'\x01')
xbee.send('at', command=b'MY', frame_id=b'\x01')
print("")

time.sleep(1)

print("")
while True:
Example #6
0
 def __init__(self):
     super().__init__()
     self.router.add_get('/', self.handler)
     self.serial_port = serial.Serial('/dev/ttyUSB0', 9600)
     self.xbee = XBee(self.serial_port, callback=self.recv)
     self.buffer = []
Example #7
0
    def __init__(self, mode="SIMULATION MODE"):
        #self.width = 2.0
        #self.height = 1.2
        self.width = 6.0
        self.height = 3.0

        # set up walls, putting top left point first
        self.walls = []
        #self.walls.append(E160_wall([-0.5, 0.3, -0.5, -0.3], "vertical"))
        #self.walls.append(E160_wall([1, 0.8, 1, -0.3], "vertical"))
        self.walls.append(E160_wall([0, 1, 15, 1], "horizontal"))
        self.walls.append(E160_wall([0, -1, 15, -1], "horizontal"))
        #self.walls.append(E160_wall([-1, 0.8, -1, -0.3], "vertical"))

        # create vars for hardware vs simulation
        # "SIMULATION MODE" or "HARDWARE MODE"
        self.robot_mode = mode
        self.using_leapfrog = True
        self.control_mode = "MANUAL CONTROL MODE"

        # setup xbee communication
        if self.robot_mode == "HARDWARE MODE":
            self.serial = serial.Serial('COM9', 9600)
            print("Setting up serial port")
            try:
                self.xbee = XBee(self.serial)
                print("Found Computer XBee")
            except:
                print("Couldn't find the serial port")

            #serial_port2 = serial.Serial('COM5', 9600)
            #print(" Setting up serial port")
            #try:
            #    self.xbee2 = XBee(serial_port2)
            #except:
            #    print("Couldn't find the serial port")

        # Setup the robots

        self.file_name = 'Log/{}_All_Bots' '_' \
                         + datetime.datetime.now() \
                             .replace(microsecond=0) \
                             .strftime('%y-%m-%d %H.%M.%S') + '.txt'
        self.file_name = self.file_name.format(self.robot_mode)

        self.num_robots = 2
        if self.num_robots == 1:
            self.robot_pos = [(0, 0, 0)]
        elif self.num_robots == 2:
            self.robot_pos = [(0.5, 0, 0), (0, 0, 0)]
        self.robots = []
        self.state_odo = [E160_state() for _ in range(self.num_robots)]
        addresses = ['\x00\x0C', '\x00\x01']
        for i in range(self.num_robots):
            # TODO: assign different address to each bot
            r = E160_robot(self, addresses[i], i)
            self.robots.append(r)
            self.state_odo[i].set_from_tuple(self.robot_pos[i])

        # Pair the two robots up
        if self.num_robots == 2:
            self.robots[0].other_pair_id = 1
            self.robots[1].other_pair_id = 0

        # Store the measurements of all robots here.
        self.range_meas = [[0] for _ in self.robots]
        self.encoder_meas = [[0, 0] for _ in self.robots]
        self.last_encoder_meas = [[0, 0] for _ in self.robots]
        self.bearing_from_other = [0 for _ in self.robots]

        self.pf = E160_PF.E160_PF(self, self.robots)

        self.make_header(self.num_robots)
Example #8
0

def sendAction(throtle, servo):
    print((throtle, servo))
    packed_data = struct.Struct('f f').pack(*(throtle, servo))
    ba = bytearray(packed_data)
    xbee.send('tx', frame='A', dest_addr=b'\x00\x00', data=ba, options=b'\x04')


if __name__ == "__main__":
    PORT = "/dev/ttyUSB0"
    BAUD_RATE = 57600

    ser = serial.Serial(PORT, BAUD_RATE)
    # Async
    xbee = XBee(ser, escaped=True, callback=handleXbeeData)

    # Sync
    # xbee = XBee(ser, escaped=True)

    rospy.init_node('drift_car_teleop_joystick')
    subprocess.Popen(["rosrun", "joy", "joy_node"])

    global pub
    pub = rospy.Publisher('drift_car/state', Float64MultiArray, queue_size=1)
    rospy.Subscriber('/joy', Joy, callback, (pub), queue_size=1)

    print("======================================")
    print("Joystick Controller for Real Drift Car")
    print("======================================\n")
Example #9
0
 def __init__(self):
     self.isShot = False
     self.isButPressed = False
     self.ser = serial.Serial('COM6', 57600)
     self.xbee = XBee(self.ser, callback=self.xbee_get)
Example #10
0
        # didn't exist yet
        logfile = open(LOGFILENAME, 'w+')
        logfile.write("Started logging\n")
        logfile.flush()

LogMsg("SensorRelay.py version 100811 started", comment=True)

if USBPORT:
    try:
        serUSB = serial.Serial(USBPORT, BAUDRATE, timeout=TIMEOUT)
        serUSB.close()  # workaround for known problem when running on Windows
        serUSB.open()
    except:
        print "Unable to open USB port ", USBPORT, ". See ya."
        log.exception('usb port ' + USBPORT)
        sys.exit(1)

if XBEEPORT:
    try:
        serXBee = serial.Serial(XBEEPORT, BAUDRATE, timeout=TIMEOUT)
        serXBee.close()  # workaround for known problem when running on Windows
        serXBee.open()
        xbee = XBee(serXBee, callback=readXBeeData)
    except:
        print "Unable to open XBee port ", XBEEPORT, ". See ya."
        log.exception('XBee Port ' + XBEEPORT)
        sys.exit(1)

lastMin = -1
mainloop()
Example #11
0
from xbee import XBee
import serial

ser = serial.Serial('/dev/tts/0', 9600)
xb = XBee(ser)
xb.at(command='ND')  # Send Node Discovery command (ATND)
while True:
    try:
        frame = xb.wait_read_frame()
        print frame
    except KeyboardInterrupt:
        break

ser.close()
Example #12
0
    def __init__(self):
        self.width = 3.5
        self.height = 3.0
         # create vars for hardware vs simulation
        self.robot_mode = "HARDWARE MODE"  # "SIMULATION MODE" or "HARDWARE MODE"
        self.control_mode = "LINE FOLLOW MODE"

        self.walls = []
        if self.robot_mode == 'SIMULATION MODE':
        # set up walls, putting top left point first
            lines = [[7,10,7,0], [0,0,10,0], [2,2,2,-2], [2,1,7,1],\
                    [7,6,15,6], [7,4,15,4], [10,2,10,0], [10,1,15,1] ,[15,6,15,-2]]

            for wall in lines:
                # Scale the walls down to reasonable sizes
                wall[:] = [round(x/5, 1) for x in wall]

                # Shift it into the frame
                wall[0] = wall[0] - 1.5
                wall[2] = wall[2] - 1.5

                wall[1] = wall[1] - 1
                wall[3] = wall[3] - 1

                if wall[0] == wall[2]:
                    self.walls.append(E160_wall(wall, "vertical"))
                elif wall[1] == wall[3]:
                    self.walls.append(E160_wall(wall, "horizontal"))
                else:
                    print('Discarded wall:', wall)


        # self.walls.append(E160_wall([0.5, 0.5, 0.5, -0.5], "vertical"))
        # self.walls.append(E160_wall([-0.5, 0.5, 0.5, 0.5], "horizontal"))
        # self.walls.append(E160_wall([0.5, -0.5, 1.0, -0.5], "horizontal"))
        # self.walls.append(E160_wall([0.0, -0.5, 0.0, -1.0], "vertical"))



        # setup xbee communication
        if (self.robot_mode == "HARDWARE MODE"):
            self.serial_port = serial.Serial(
                '/dev/tty.usbserial-DN02Z1BF', 9600)
            print(" Setting up serial port")
            try:
                self.xbee = XBee(self.serial_port)
            except:
                print("Couldn't find the serial port")

        # Setup the robots
        self.num_robots = 1
        self.robots = []
        for i in range(0, self.num_robots):

            # TODO: assign different address to each bot
            r = E160_robot(self, '\x00\x0C', i)
            self.robots.append(r)

            if self.robot_mode == "HARDWARE MODE":
                input("Press enter to begin calibration.")
                print('starting calibration')
                r.calibrate()
Example #13
0
#halt_on_keyboard = wait_for_input()
#halt_on_keyboard.start()

sequential_timeouts = 0

current_mask = -1

last_radio_rx_time = int(time.time())

current_error = 0

last_radio_rx_time = 0

#ser = serial.Serial('/dev/tty.usbserial-FTE4XS76', 115200)

xbee = XBee(None)

print('booted')
print('digi time %s' % time.time())

ftp_pusher = FTPpush()
ftp_pusher.start()

poof = 0

#print "Got here and run: " + str(Run)

loop_counts = 0
while Run == 1:
    #            print "Got here 2"
    loop_counts = loop_counts + 1
def loop():

    global xb, telem, coord

    DEFAULT_COM_PORT = 'COM7'
    DEFAULT_BAUD_RATE = 57600
    DEFAULT_ADDRESS = '\x10\x21'
    DEFAULT_PAN = 0x1001
    
    if len(sys.argv) == 1:
        com = DEFAULT_COM_PORT
        baud = DEFAULT_BAUD_RATE
        addr = DEFAULT_ADDRESS
    elif len(sys.argv) == 4:
        com = sys.argv[1]
        baud = int(sys.argv[2])
        addr = pack('>H', int(sys.argv[3], 16))
    else:
        print "Wrong number of arguments. Must be: COM BAUD ADDR"
        sys.exit(1)
    
    ser = Serial(port = com, baudrate = baud) 
    xb = XBee(ser, callback = rxCallback)
    print "Setting PAN ID to " + hex(DEFAULT_PAN)
    xb.at(command = 'ID', parameter = pack('>H', DEFAULT_PAN))                 
    
    comm = CommandInterface(addr, txCallback)
    telem = TelemetryReader(addr, txCallback)
    kbint = KeyboardInterface(comm)
    coord = NetworkCoordinator(txCallback)
    
    comm.enableDebug()
    telem.setConsoleMode(True)
    telem.setFileMode(True)
    telem.writeHeader()
    coord.resume()
    
    comm.setSlewLimit(3.0)
    
    while True:

        try:   
            # Copied from code.activestate.com/recipes/134892/
            # TODO: Find a way to avoid this blocking call
            fd = sys.stdin.fileno()
            old_settings = termios.tcgetattr(fd)
            try:
                tty.setraw(sys.stdin.fileno())
                c = sys.stdin.read(1)
            finally:
                termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)             
            kbint.process(c)
            time.sleep(0.01)
            #comm.sendPing()
    
        except:        
            break
            
    telem.close()                
    xb.halt()
    ser.close()
Example #15
0
# Receives frames from Waspmote boards with Temperature, Humidity, Luminosity and/or Presence sensors and
# inserts them into a database
# Communication via Xbee PRO S1 802.15.4

import serial, json, re, mysql.connector, time
from xbee import XBee

PORT = '/dev/ttyUSB' + input("Port (Use 0-4 for ttyUSBX): ")
print("Using port", PORT)
BAUDRATE = 115200
NODEID = "SensorStation2"
serial_port = serial.Serial(PORT, BAUDRATE)
xbee = XBee(serial_port, escaped=True)

# --------- #


def insert_values(TEMP, LUMI, PIR):
    mydb = mysql.connector.connect(host="database_url",
                                   user="******",
                                   passwd="password",
                                   database="sensordb")
    cursor = mydb.cursor()
    now = time.strftime(r"%Y.%m.%d %H:%M:%S", time.localtime())
    print(now)
    sql_query = "INSERT INTO data (nodeid, time, temperature, light, presence) VALUES (%s, %s, %s, %s, %s)"
    val = (NODEID, now, TEMP, LUMI, PIR)
    cursor.execute(sql_query, val)

    mydb.commit()
Example #16
0
# Register the signal interupt handlers
log("Registering signal interupt handlers...", False)
for sig in [signal.SIGTERM, signal.SIGINT]:
    signal.signal(sig, interupt_signal_handler)

# Variable/Object definition before entering loop

# Serial communication with XBee:
PORT = '/dev/ttyUSB0'  # (use 'dmesg' to discover port)
BAUD_RATE = 9600

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

# Create XBee object and set the callback function
xbee = XBee(ser, callback=process_response)

# Socket statuses (1 = on, 0 = off)
# (defaults before firebase queried)
socket_1 = 1
socket_2 = 1
socket_3 = 1
socket_4 = 1
socket_5 = 1

# RF codes for sockets
SOCKET_1_ON = 4308444
SOCKET_1_OFF = 4308436
SOCKET_2_ON = 4308442
SOCKET_2_OFF = 4308434
SOCKET_3_ON = 4308441
def loop():

    DEFAULT_COM_PORT = 'COM0'
    DEFAULT_BAUD_RATE = 57600
    DEFAULT_ADDRESS = '\x10\x21'
    DEFAULT_PAN = '\x10\x01'

    if len(sys.argv) == 1:
        com = DEFAULT_COM_PORT
        baud = DEFAULT_BAUD_RATE
        addr = DEFAULT_ADDRESS
    elif len(sys.argv) == 4:
        com = sys.argv[1]
        baud = int(sys.argv[2])
        addr = pack('>H', int(sys.argv[3], 16))
    else:
        print "Wrong number of arguments. Must be: COM BAUD ADDR"
        sys.exit(1)

    coord = CommandInterface(addr, txCallback)
    coord.enableDebug()

    ser = Serial(port=com, baudrate=baud)
    xb = XBee(ser)
    print "Setting PAN ID to " + hex(DEFAULT_PAN)
    xb.at(command='ID', parameter=pack('>H', DEFAULT_PAN))

    thrust = 0.0
    yaw = 0.0
    elevator = 0.0

    while True:

        try:

            c = msvcrt.getch()

            if c == 'w':
                thrust = thrust + THRUST_INCREMENT
            elif c == 'a':
                yaw = yaw + YAW_INCREMENT
            elif c == 's':
                thrust = thrust - THRUST_INCREMENT
            elif c == 'd':
                yaw = yaw - YAW_INCREMENT
            elif c == 'r':
                elevator = elevator + ELEVATOR_INCREMENT
            elif c == 'f':
                elevator = elevator - ELEVATOR_INCREMENT
            elif c == 'q':
                thrust = 0.0
                yaw = 0.0
                elevator = 0.0
            elif c == 'e':
                break
            elif c == 't':
                coord.setRegulatorMode(RegulatorStates['Remote Control'])

            if thrust > THRUST_UPPER_LIMIT:
                thrust = THRUST_UPPER_LIMIT
            elif thrust < THRUST_LOWER_LIMIT:
                thrust = THRUST_LOWER_LIMIT

            if yaw > YAW_UPPER_LIMIT:
                yaw = YAW_UPPER_LIMIT
            elif yaw < YAW_LOWER_LIMIT:
                yaw = YAW_LOWER_LIMIT

            if elevator > ELEVATOR_UPPER_LIMIT:
                elevator = ELEVATOR_UPPER_LIMIT
            elif elevator < ELEVATOR_LOWER_LIMIT:
                elevator = ELEVATOR_LOWER_LIMIT

            coord.setRemoteControlValues(thrust, yaw, elevator)

        except:

            print "Exception: ", sys.exc_info()[0]
            break

    xb.halt()
    ser.close()
Example #18
0
    # data = frame
    print frame['rf_data']


# PORT = rospy.get_param('~xbee_port', '/dev/ttyUSB0')

#You may need to change this port name, Eddie
PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600

ser = serial.Serial(PORT, BAUD_RATE)

# rospy.init_node('arduino_listener')

# for requested input
dev = XBee(ser, escaped=True)
dev = ZigBee(ser, escaped=True)

# for asynchronous use
# dev = XBee(ser, callback=make_msg)
# dev = ZigBee(ser, callback=make_msg)

# arduPub = rospy.Publisher('arduino', gait_hmm_ros.msg.ardu_msg, queue_size=50)
# r = rospy.Rate(50)
message_received = 0

# while not rospy.is_shutdown():
#         if message_received == 1:
#             arduPub.publish(data)
#             r.sleep()
Example #19
0
import serial
import time
from xbee import XBee

serial_port = serial.Serial('/dev/tty.usbserial-A104BR3A', 57600)


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()
Example #20
0
dispatch = Dispatch(ser)

# Register the packet handlers with the dispatch:
#  The string name allows one to distinguish between mutiple registrations
#   for a single callback function
#  The second argument is the function to call
#  The third argument is a function which determines whether to call its
#   associated callback when a packet arrives. It should return a boolean.
dispatch.register("status", status_handler,
                  lambda packet: packet['id'] == 'status')

dispatch.register("io_data", io_sample_handler,
                  lambda packet: packet['id'] == 'rx_io_data')

# Create API object, which spawns a new thread
# Point the asyncronous callback at Dispatch.dispatch()
#  This method will dispatch a single XBee data packet when called
xbee = XBee(ser, callback=dispatch.dispatch)

# Do other stuff in the main thread
while True:
    try:
        time.sleep(.1)
    except KeyboardInterrupt:
        break

# halt() must be called before closing the serial
# port in order to ensure proper thread shutdown
xbee.halt()
ser.close()
Example #21
0
cycle = 125  # ms for a leg cycle
# velocity profile
# [time intervals for setpoints]
# [position increments at set points]
# [velocity increments]   muliplied by 256
delta = [8, 8, 8, 8]  # adds up to 32 counts
#intervals = [0x8f, 0x19, 0x19, 0x8f]  # total 336 ms
intervals = [cycle / 4, cycle / 4, cycle / 4, cycle / 4]  # total 213 ms
#intervals = [40,40,10,10] # total 100 ms
vel = [
    delta[0] * 256 / intervals[0], delta[1] * 256 / intervals[1],
    delta[2] * 256 / intervals[2], delta[3] * 256 / intervals[3]
]  # = 256*delta/interval

ser = serial.Serial(shared.BS_COMPORT, shared.BS_BAUDRATE, timeout=3, rtscts=0)
xb = XBee(ser, callback=xbee_received)


def xb_send(status, type, data):
    payload = chr(status) + chr(type) + ''.join(data)
    xb.tx(dest_addr=DEST_ADDR, data=payload)


def resetRobot():
    xb_send(0, command.SOFTWARE_RESET, pack('h', 0))


def menu():
    print "-------------------------------------"
    print "e: radio echo test    | g: right motor gains | h: Help menu"
    print "l: left motor gains"
    print("... calculating...")
    P.solve()

    print("> Done! Multilat result:", t.loc)
    

def broadcast_ping():
    rssi_dict = {}
    # Broadcast ping
    send_data("ping", "\xFF\xFF")

if __name__ == "__main__":
    sense = SenseHat()
    print(">> Opening serial port...")
    ser = serial.Serial("/dev/ttyUSB1", 9600)
    xbee = XBee(ser, callback=receive_data)

    rssi_list = []
    rssi_dict = {}
    
    ## TODO: Fill anchor position dictionary!
    anchor_positions = {
        "add1": (0, 1),
        "add2": (0, 3),
        "add3": (0, 4)
    }

    print(">> Waiting for events...")
    print("Middle: clear_matrix, left: init_rssi_calc, right: three_anchor_bbox, down: broadcast_ping")
    print("Sequence: broadcast_ping -> three_anchor_bbox / three_anchor_multilat")
    while True:
Example #23
0
                    help='defines baud rate of serial port')
parser.add_argument("-o",
                    "--output",
                    default='serialOutput.txt',
                    help='filename for text file with serial port output')
parser.add_argument("-V", "--vid", default='0403', help='vendor ID of device')

# Parse known arguments
args, unknown = parser.parse_known_args()

# Create XBee explorer device object
expl = Device(name='XBee Explorer', vid=args.vid, baud=args.baud, timeout=1)

# Create a mock xbee device to get the hardware version
expl.connect()
mock_xbee = XBee(expl.ser, escaped=True)
mock_xbee.send('at', frame_id='\x01', command="DD")
response = mock_xbee.wait_read_frame()
device_descr = response['parameter'].encode('hex')[0:4]
mock_xbee.halt()
expl.disconnect()

# Get addresses for the XBees from the YAML address table
addr_path = rospkg.RosPack().get_path('xbee_loc') + '/param/addresses.yaml'
addr = yaml.load(file(addr_path, 'r'))
rx_addr = addr[device_descr]['RX']['SH'] + addr[device_descr]['RX']['SL']
tx1_addr = addr[device_descr]['TX1']['SH'] + addr[device_descr]['TX1'][
    'SL']  # Beacon 1
tx2_addr = addr[device_descr]['TX2']['SH'] + addr[device_descr]['TX2'][
    'SL']  # Beacon 2
tx3_addr = addr[device_descr]['TX3']['SH'] + addr[device_descr]['TX3'][
Example #24
0
    def __init__(self):
        # create vars for hardware vs simulation
        self.robot_mode = "HARDWARE_MODE"
        #self.control_mode = "MANUAL_CONTROL_MODE"
        self.firstIter = True
        self.encoder_initial_L = 0
        self.encoder_initial_R = 0
        self.encoder_adjusted_L = 0
        self.encoder_adjusted_R = 0
        self.last_encoder_measurementL = 0
        self.last_encoder_measurementR = 0
        self.diffEncoderL = 0
        self.diffEncoderR = 0
        self.theta = 0

        # setup xbee communication, change ttyUSB0 to the USB port dongle is in
        if (self.robot_mode == "HARDWARE_MODE"):
            self.serial_port = serial.Serial('/dev/ttyUSB0', 9600)
            print(" Setting up serial port")
            try:
                self.xbee = XBee(self.serial_port)
            except:
                print("Couldn't find the serial port")

        print("Xbee setup successful")
        self.address = '\x00\x0C'  #you may use this to communicate with multiple bots

        # init an odometry instance, and configure odometry info
        self.odom_init()

        # init an ir instance, and configure ir info
        self.ir_init()

        # init log file, "False" indicate no log will be made, log will be in e190_bot/data folder
        self.log_init(data_logging=False, file_name="log.txt")

        rospy.init_node('botControl', anonymous=True)

        # Subscribe botControl node to /cmd_vel
        rospy.Subscriber("/cmd_vel", Twist, self.cmd_vel_callback)

        self.pubOdom = rospy.Publisher('/odom', Odometry, queue_size=10)

        # Publish ir (distance) sensor data
        # self.pubDistL = rospy.Publisher('/distL', ir_sensor, queue_size=10)
        # self.pubDistC = rospy.Publisher('/distC', ir_sensor, queue_size=10)
        # self.pubDistR = rospy.Publisher('/distR', ir_sensor, queue_size=10)
        self.pubDists = rospy.Publisher('/dists', Vector3, queue_size=10)

        self.time = rospy.Time.now()
        self.count = 0

        # Sets publishing rate
        self.rate = rospy.Rate(10)  # 10hz
        self.xbeeTimeout = .01  # set an xbee timeout such that we only skip one
        # or two odom pubs
        # self.rate = rospy.Rate(5) # 5hz

        while not rospy.is_shutdown():
            self.odom_pub()
            self.rate.sleep()
Example #25
0
    RSSI = "RSSI"
    SYNC_PROC = "SYNC_PROC"


if __name__ == "__main__":
    PORT = sys.argv[1]
    BAUD_RATE = 9600
    REQUESTS = int(sys.argv[2])

    # Open serial port
    ser = serial.Serial(PORT, BAUD_RATE)
    state = 0
    protocol = protocol()
    anchors = {}
    processors = {}
    xbee = XBee(ser)
    timeout = 0

    # Continuously read and print packets
    while True:
        try:
            if state == 0:
                # msg = bytes(protocol.FIND + protocol.END_COMMAND, 'utf-8')
                # print(msg)
                # ser.write(msg)
                msg = protocol.FIND
                xbee.send("tx", frame='A', dest_addr='\xFF\xFF', data=msg)
                timeout = int(round(time.time() * 1000))
                while int(round(time.time() * 1000)) - timeout < 1000:
                    # if ser.in_waiting:
                    # data = ser.readline()
Example #26
0
#!/usr/bin/env python2.7

#Author: Michael Doyle
#
#Purpose: First Attempt at XBee ZigBee Rx
#Note: Not adept in Python or any OOP for that matter
#		so go easy on me.

import serial
from xbee import XBee
import time, sys, datetime

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

xb = XBee(serial_port)

while True:
	try:
		data = xb.wait_read_frame()
		print data
	except KeyboardInterrupt:
		break
serial_port.close()
 def __init__(self, port_number, baud_rate=9600):
     self.xbee = XBee(port_number, baud_rate)
     self.xbee.open()
     print("XBee reader initialised")
Example #28
0
class Stream_handler:
    def __init__(self):
        self.nbr_packets =0
        self.file_name = str(uuid4())
        self.file_data = []
    def rcv_file_data(self,xbee_message):
        if xbee_message["rf_data"][0]=='\x00':
            self.nbr_packets  = struct.unpack(">I",xbee_message["rf_data"][1:5])[0]
        else:
            self.file_data.append(xbee_message["rf_data"][5:])
            index =struct.unpack(">I", xbee_message["rf_data"][1:5])[0]
            if index == self.nbr_packets:
                print ("writing to file")
                f = open(self.file_name, "wb")
                for e in self.file_data:
                    f.write(e)
                f.close()
                self.file_name = str(uuid4())

stream = Stream_handler()
xbee = XBee(serial_port, callback=stream.rcv_file_data)

while True:
    try:
        sleep(1)
    except KeyboardInterrupt:
        break

xbee.halt()
serial_port.close()
Example #29
0
import serial
from xbee import XBee

import sys

#print sys.argv[1]

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

if sys.argv[1] == '0':
	print 'Se apaga la luz'
	xbee.remote_at(dest_addr='\x00\x02', command='D0',  parameter='\x04')
else:
	print 'Se prende la luz'
	xbee.remote_at(dest_addr='\x00\x02', command='D0',  parameter='\x05')
  
xbee.remote_at(dest_addr='\x00\x02', command='WR')
Example #30
0
import serial
from firebase.firebase import FirebaseApplication, FirebaseAuthentication
from userConfig import config
from xbee import XBee
from datetime import datetime

### Setup and enable UART ports
#  UART1 (/dev/ttyO1): Rx -> p9_26, Tx -> P9_24
#  UART2 (/dev/ttyO2): Tx -> p9_21, Rx -> p9_22
UART.setup("UART1")

###  Initialize serial port for UART
s = serial.Serial('/dev/ttyO1', 9600)

###  Initialize XBee object
xbee = XBee(s)

### Initialize firebase client with user's config file
cf = config()
fbAuth = FirebaseAuthentication(cf.firebaseSecret, cf.firebaseEmail, True,
                                True)

fb = FirebaseApplication(cf.firebaseURL, fbAuth)

###  Main code

while True:
    try:
        packet = xbee.wait_read_frame()
        print packet
        #if packet['id'] == 'rx_io_data':