Пример #1
0
def send_data_xbee(data, dest_addr=None):
    """
    Sends the given data to the solar device with the given 64-bit address. If
    none is provided, the data is sent to all panels.

    Args:
        data (Bytearray): the data to send.
        dest_addr (String, optional): the 64-bit address of the solar panel to
            send the data to. If none is specified, the data will be sent to
            all panels.

    Returns:
         ``True`` if the data could be sent successfully, ``False`` otherwise.
    """
    try:
        if dest_addr is None:
            device.send_data_broadcast(data)
        else:
            device.send_data(
                RemoteXBeeDevice(device,
                                 XBee64BitAddress.from_hex_string(dest_addr)),
                data)
        return True
    except XBeeException as e:
        print_error("Could not send data: {}".format(str(e)))

    return False
def sendCommand(request):
    request.setHeader('Access-Control-Allow-Origin', '*')
    request.setHeader('Access-Control-Allow-Methods', 'GET')
    request.setHeader('Access-Control-Allow-Headers', 'x-prototype-version,x-requested-with')
    request.setHeader('Access-Control-Max-Age', 2520)
    
    content = json.loads(request.content.read().decode("utf8"))
    print(content)
    command = content['command']
    DID = content['deviceID']

    if DID != "00000000":
        toSend={"CMD":"HMOD","MODE":command, "TS": str(int(time.time()))}
        remote_device = RemoteXBeeDevice(device, XBee64BitAddress.from_hex_string(DID))

        # Send data using the remote object.
        device.send_data_async(remote_device, json.dumps(toSend))
    else:
        toSend={"CMD":"HMOD","MODE":command, "TS": str(int(time.time()))}
        print("broadcasting command " + json.dumps(toSend))
        device.send_data_broadcast(json.dumps(toSend))




    return json.dumps({"result":"success"})
Пример #3
0
class value_comm:
    device = XBeeDevice("/dev/tty.usbserial-A50285BI", 9600)
    remote_xbee = RemoteXBeeDevice(
        device, XBee64BitAddress.from_hex_string("0013A2004189A911"))

    def __init__(self, switch, speed, altitude, direction):
        self.switch = switch
        self.speed = speed
        self.altitude = altitude
        self.direction = direction

    def open_conn(self):
        self.device.open()

    def close_conn(self):
        self.device.close()

    def update_switch(self, value):
        self.switch = value

    def update_speed(self, value):
        self.speed = value

    def update_altitude(self, value):
        self.altitude = value

    def update_direction(self, value):
        self.direction = value

    def get_values(self):
        return self.switch, self.speed, self.altitude, self.direction

    def xbee_send(self):
        self.device.send_data(self.remote_xbee, str(self.get_values()))
Пример #4
0
 def __init__(self):
     self.serialPort = "COM3"
     self.device = XBeeDevice(self.serialPort, 9600)
     self.remote_device = RemoteXBeeDevice(
         self.device, XBee64BitAddress.from_hex_string(
             "0013A2004068CC5D"))  # "0013A20040XXXXXX"
     self.callback = None
def parse(data):
    global device, modeV, pub_send_u_rudder_sail, pub_send_control_mode, rudder_sail
    splitdata = data.split(b'#')

    try:
        index = splitdata.index(b'M')
        modeV = struct.unpack('i', splitdata[index + 1])[0]
    except ValueError:
        pass

    try:
        index = splitdata.index(b'C')
        splitted = splitdata[index + 1].split(b',')
        rudder = struct.unpack('d', splitted[0])[0]
        sail = struct.unpack('d', splitted[1])[0]

        rudder_sail = Twist()
        rudder_sail.angular.x = rudder
        rudder_sail.angular.y = sail
    except ValueError:
        pass
    try:
        index = splitdata.index(b'S')
        process = subprocess.run(splitdata[index + 1].decode('utf8').split(),
                                 stdout=subprocess.PIPE)
        output = process.stdout
        try:
            device.send_data(
                RemoteXBeeDevice(device,
                                 XBee64BitAddress.from_hex_string("00")),
                bytearray(("R#").encode('utf8') + output))
        except TimeoutException:
            print("timeout")
    except ValueError:
        pass
Пример #6
0
 def tx_callback(self, msg):
     ''' ROS: callback for data wanting to be transmitted by the XBee radio '''
     self.get_logger().info(f"Transmitting: {msg.data}")
     dev_addr = XBee64BitAddress.from_hex_string(msg.dev_addr)
     self.device.send_data_async_64(
         dev_addr,
         bytearray(struct.pack(str(len(msg.data)) + 'c', *msg.data)))
Пример #7
0
 def refreshSystem(self):  # 用于刷新全部系统信息
     Raw802Device.open()
     remote_device = RemoteXBeeDevice(
         Raw802Device, XBee64BitAddress.from_hex_string("0013A200415D2430"))
     Raw802Device.send_data(
         remote_device, " ")  # 二进制:0010 0000,0000为每次发送时的帧别信息,0000为接收平台所有信息
     Raw802Device.close()
Пример #8
0
def SendCommandEnvRec(res, dados, device):

    remote_device = RemoteXBeeDevice(
        device, XBee64BitAddress.from_hex_string('' + res))

    # Send data using the remote object.
    leit = "0"
    try:
        device.send_data(remote_device, dados)
        #time.sleep(0.2)

        timeout_start = time.time()
        xbee_message = device.read_data()

        while (xbee_message is None) and time.time() < timeout_start + timeout:
            xbee_message = device.read_data()
            print(xbee_message)
            if (xbee_message is not None):
                leit = str(float.fromhex(xbee_message.data.decode()))
                print("From %s >> %s" %
                      (xbee_message.remote_device.get_64bit_addr(),
                       float.fromhex(xbee_message.data.decode())))
                time.sleep(1)
    except:
        print("Erro ao enviar o comando")
    return leit
Пример #9
0
 def __init__(self):
     self.serialPort = "/dev/tty.SLAB_USBtoUART"  # port where Xbee is connected find by doing ls /dev/tty* on terminal
     self.device = XBeeDevice(self.serialPort, 9600)
     self.remote_device = RemoteXBeeDevice(
         self.device, XBee64BitAddress.from_hex_string(
             "0013A200406343f7"))  # "0013A20040XXXXXX"
     self.callback = None
Пример #10
0
 def terminalSignal(self):  # 用于获取平台本身的信息
     Raw802Device.open()
     remote_device = RemoteXBeeDevice(
         Raw802Device, XBee64BitAddress.from_hex_string("0013A200415D2430"))
     Raw802Device.send_data(
         remote_device,
         "!")  # 二进制:0010 0001,0010为每次发送时的帧别信息,0001为接收平台当前除模组信息外的信息
     Raw802Device.close()
Пример #11
0
 def getmodule(self):  # 要求平台发送模组信息,用于获得及刷新模组信息
     Raw802Device.open()
     remote_device = RemoteXBeeDevice(
         Raw802Device, XBee64BitAddress.from_hex_string("0013A200415D2430"))
     Raw802Device.send_data(
         remote_device,
         "“")  # 二进制:0010 0010,前0010为每次发送时的帧别信息,后0010为接收平台当前模组信息
     Raw802Device.close()
Пример #12
0
 def send(self, address, packet):
     try:
         self.device.send_data_async(
             RemoteXBeeDevice(self.device,
                              XBee64BitAddress.from_hex_string(address)),
             packet.encode)
     except (TimeoutException, InvalidPacketException):
         log.error(f'({address}) not found\n')
     except AttributeError:
         log.error('SEND: Antenna not connected\n')
def SendNewCoords(swarm_control_signal, agentNum):
    #Set up the remote device object for the specified agent
    remote_device = RemoteXBeeDevice(groundStation, XBee64BitAddress.from_hex_string(QUAD_ID[agentNum]))
    
    #Compile the 3-number coordinate set for the specified agent into a single string with each number delimited by a comma
    txPayload = numpy.array2string(swarm_control_signal[agentNum], separator=',')
    
    #For monitoring: 
    print("Sent: ", txPayload)

    #Send the data to the remote_device object defined above
    groundStation.send_data(remote_device, txPayload)
Пример #14
0
 def send_sync(self, address, packet):
     """Aspetta l'ack, se scatta il
     timeout e non riceve risposta
     lancia l'eccezione
     """
     try:
         self.device.send_data(
             RemoteXBeeDevice(self.device,
                              XBee64BitAddress.from_hex_string(address)),
             packet.encode)
     except (TimeoutException, InvalidPacketException):
         log.error('ACK send_sync not received\n')
     except AttributeError:
         log.error('SEND_SYNC: Antenna not connected\n')
    def mandar_mensage(self,
                       dir_64,
                       msg=PING,
                       dir_16=None) -> TransmitStatusPacket:
        """
        Manda el mensaje al destinatario por defecto.
        """
        ack = None
        # Transformamos el mensaje recibido en un string tratable
        msg = str(msg)
        # Recuperamos la dirección del dispositivo remoto en formato de 64 bits
        high = None
        try:
            dir_64 = XBee64BitAddress.from_hex_string(dir_64)
            high = dir_64 or self.remote_zigbee.get_64bit_addr()
        except:
            high = XBee64BitAddress.UNKNOWN_ADDRESS

        # Recuperamos la dirección del dispositivo remoto en 16 bits o la marcamos como desconocida
        low = None
        try:
            low = XBee16BitAddress.from_hex_string(
                dir_16) or self.remote_zigbee.get_16bit_addr()
        except:
            low = XBee16BitAddress.UNKNOWN_ADDRESS

        try:
            # Intentamos mandar el mensaje
            ## Versión fragmentando el paquete

            ## Versión sin fragmentar el paquete
            ack = super().send_data_64_16(high, low, msg)
            # self.logger.debug(format(ack))
            if ack.transmit_status is not TransmitStatus.SUCCESS:
                self.logger.warning(
                    "Algo no fue bien mandando el mensaje:\n{}\nError:\t{}".
                    format(msg, ack))

        except Exception as e:
            error = "Se ha encontrado un error al mandar el mensaje\n\t" + str(
                e)
            self.logger.error(error)
            raise EOFError(error)
            # ack = super().send_data_64_16(high, low, msg)
            # Añadir código para el reintento
        else:
            # TODO Borrar esta traza de control
            self.logger.debug("Mandado mensaje:\t" + msg)
        return ack
Пример #16
0
def main():
    # Instantiate XBee device
    device = setup_xbee()

    try:
        remote_device = RemoteXBeeDevice(
            device, XBee64BitAddress.from_hex_string(MAC_ADDR))

        if remote_device is None:
            print("Invalid MAC Address")
            exit(1)

        print("Sending '%s' to %s" %
              (DATA_TO_SEND, remote_device.get_64bit_addr()))
        device.send_data(remote_device, DATA_TO_SEND)
        print("Success")

    finally:
        if device is not None and device.is_open():
            device.close()
Пример #17
0
    def _get_update_tasks_from_64bit_addr(self,
                                          x64bit_str,
                                          xpro_path,
                                          timeout=None):
        """
        Adds update tasks for node with the provided 64-bit address.

        Params:
            x64bit_str (String): 64-bit address of the node.
            xpro_path (String): Absolute path of the '.xpro' file in the gateway.
            timeout (Integer, optional, default=`None`): Maximum time to wait
                for target read operations during the apply profile.
        """
        if not XBee64BitAddress.is_valid(x64bit_str):
            log.warning("%s: invalid 64-bit address '%s'",
                        self._INVALID_TASK_ERROR, x64bit_str)
            return

        self._update_tasks.update({
            XBee64BitAddress.from_hex_string(x64bit_str): (xpro_path, timeout)
        })
Пример #18
0
 def send_data_to_address(self, address, data):
     remote_device = RemoteDigiMeshDevice(
         self.device, XBee64BitAddress.from_hex_string(address))
     self.device.send_data(remote_device, data)
Пример #19
0
def send_data():
    global count
    count = count + 1
    remote_device = RemoteXBeeDevice(
        my_device, XBee64BitAddress.from_hex_string(DRONE_ID))
    my_device.send_data(remote_device, DATA_TO_SEND + str(count))
def main():
    print(" +----------------------------------------------------------+")
    print(" | XBee Python Library Network modifications Devices Sample |")
    print(" +----------------------------------------------------------+\n")

    xbee_network = None

    xbee = XBeeDevice(PORT, BAUD_RATE)

    try:
        xbee.open()

        xbee_network = xbee.get_network()

        xbee_network.set_discovery_timeout(15)  # 15 seconds.

        xbee_network.add_discovery_process_finished_callback(callback_discovery_finished)

        xbee_network.add_network_modified_callback(cb_network_modified)

        print("* Discover remote XBee devices...")

        xbee_network.start_discovery_process()

        while xbee_network.is_discovery_running():
            time.sleep(1)

        print_nodes(xbee_network)

        print("\n* Manually add a new remote XBee device...")
        remote = RemoteXBeeDevice(
            xbee,
            x64bit_addr=XBee64BitAddress.from_hex_string("1234567890ABCDEF"),
            node_id="manually_added")
        xbee_network.add_remote(remote)

        print_nodes(xbee_network)

        time.sleep(1)

        print("\n* Update the last added remote XBee device...")
        remote = RemoteXBeeDevice(xbee, x64bit_addr=remote.get_64bit_addr(), node_id="updated_node")
        xbee_network.add_remote(remote)

        print_nodes(xbee_network)

        time.sleep(1)

        print("\n* Manually remove a remote XBee device...")
        xbee_network.remove_device(remote)

        print_nodes(xbee_network)

        time.sleep(1)

        print("\n* Clear network...")
        xbee_network.clear()

        print_nodes(xbee_network)

    finally:
        if xbee_network is not None:
            xbee_network.del_discovery_process_finished_callback(callback_discovery_finished)
            xbee_network.del_network_modified_callback(cb_network_modified)

        if xbee is not None and xbee.is_open():
            xbee.close()
Пример #21
0
 def addRemoteAccessory(self, accessoryName, xbeeAddressString):
     self.remoteAccessories[accessoryName] = RemoteXBeeDevice(
         self.baseXbee, XBee64BitAddress.from_hex_string(xbeeAddressString))
Пример #22
0
#configure for XBee
PORT = '/dev/ttyUSB0'
BAUD_RATE = 230400
REMOTE_DRONE_ID = "0013A200419B5208"
DRONE_ID = '#d1'
data = {}
waypoint = {}
_send_mission_once = None
sending_label = None
command_queue = CommandQueue()

my_device = XBeeDevice(PORT, BAUD_RATE)
my_device.open()
remote_device = RemoteXBeeDevice(
    my_device, XBee64BitAddress.from_hex_string(REMOTE_DRONE_ID))

## Connect to socket
socket = SocketIO('https://nicwebpage.herokuapp.com', verify=True)
socket_a = socket.define(BaseNamespace, '/JT601')
socket_a.emit("joinPi")

#print("\nConnecting to vehicle on: %s" % connection_string)
print("Connecting to vehicle...")
vehicle = Drone('tcp:127.0.0.1:5762')
print("Connected!!!")


def is_timestamp_received(var):
    if command_queue.__contains__(var):
        return True
Пример #23
0
def main():

    DevList = {}
    FormedAll = []  # Ana Dig values after passing through Format()
    FormedAnalog = []  # Ana values after passing through Format()
    FormedDigital = []  # Dig values after passing through Format()

    example_text = '''Example usage:

    # Run discovery process on nework to find XBEE-IO devices
    ./xbeeio.py --port ttyUSB1 --discover
     
    # Readback all IO in default format and output style
    ./xbeeio.py --port ttyUSB1 --remote XBEE1 --readall

    # Read all IO and format analogue readings as rounded up voltages
    ./xbeeio.py --port ttyUSB1 --remote XBEE1 --readall --format volts

    # Read ADC inputs 0,1 & 3 and format readings as rounded up (TMP36) temperatures 
    ./xbeeio.py --port ttyUSB1 --remote XBEE1 --readadc 031 --format temp

    # Read ADC input 2 and format reading as rounded up 4-20mA 
    ./xbeeio.py --port ttyUSB1 --remote XBEE1 --readadc 2  --format 420

    # Read Dig Ins 0,1,2 & 3 
    ./xbeeio.py --port ttyUSB1 --remote XBEE1 --readdigin 0321

    # Read Dig In 0 
    ./xbeeio.py --port ttyUSB1 --remote XBEE1 --readdigin 0

    # Set Dig Out 0,1 & 3 Enabled
    ./xbeeio.py --port ttyUSB1 --remote XBEE1 --setdigouts 1101

    # Set Dig out 1 & 3 Enabled
    ./xbeeio.py --port ttyUSB1 --remote XBEE1 --setdigouts 0101

    # Set Dig Out 0 = Enabled
    ./xbeeio.py --port ttyUSB1 --remote XBEE1 --setdigouts 1000

    # Read all inputs and output in a logline format with analog voltage formatted as rounded up volts
    ./xbeeio.py --port ttyUSB1 --remote XBEE1 --readall --outputlogline --format volts

    '''
    ap = ArgParser(description='XBEE-IO Communication Script',
                   epilog=example_text,
                   formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--port",
                    action='store',
                    dest='port',
                    help="serial port to connect to",
                    required=True)
    ap.add_argument("--discover",
                    action='store_true',
                    dest='show',
                    help="discover the digimesh network devices")
    ap.add_argument("--remote",
                    action='store',
                    dest='remote',
                    help="specify the target XBee NI identifier to talk to")
    ap.add_argument("--readall",
                    action='store_true',
                    dest='readall',
                    help="read back all input/output states")
    ap.add_argument("--format",
                    action='store',
                    dest='format',
                    help="printable format : volts|420|temp")
    ap.add_argument("--readadc",
                    action='store',
                    dest='anapins',
                    help="read back on or more analog inputs")
    ap.add_argument("--readdigin",
                    action='store',
                    dest='digipins',
                    help="read back one or more digital inputs")
    ap.add_argument("--outputstd",
                    action='store_true',
                    dest='std',
                    help="display the output in human readable form (default)")
    ap.add_argument("--outputlogline",
                    action='store_true',
                    dest='log',
                    help="display output in single data log format")
    ap.add_argument("--outputjson",
                    action='store_true',
                    dest='json',
                    help="display output in JSON format")
    ap.add_argument("--setdigouts",
                    action='store',
                    dest='setdigout',
                    help="set digouts as 4bit state <0123>")
    ap.add_argument("--quiet",
                    action='store_true',
                    dest='quiet',
                    help="suppress extra output")

    if len(sys.argv) == 1:
        ap.print_help(sys.stderr)
        sys.exit(1)
    args = ap.parse_args()

    PORT = '/dev/' + args.port

    try:

        if args.show:
            # Instatiate RPi Main Hub
            RPi = DigiMeshDevice(PORT, BAUD_RATE)
            RPi.open()

            DevList = ShowRemote(RPi, args.quiet)

            # Export network devices to file
            with open('network.conf', 'w+') as f:
                f.truncate(0)  # Reset file contents
                for node, address in DevList.items():
                    f.write(node + '|' + address + '\n')

        elif args.remote:

            # Instatiate RPi Main Hub
            RPi = DigiMeshDevice(PORT, BAUD_RATE)
            RPi.open()

            # Scan and save network if it does not exist
            if not os.path.exists('network.conf'):

                DevList = NetworkDiscovery(RPi, args.quiet)
                with open('network.conf', 'w+') as f:
                    for node, address in DevList.items():
                        f.write(node + '|' + address + '\n')

            # Repopulate dictionary for practicality
            with open("network.conf") as f:
                for line in f:
                    (node, address) = line.strip().split('|')
                    DevList.update({node: address})

            # Make sure target NodeID exists in network
            if args.remote in DevList.keys():
                RemoteXBee = RemoteDigiMeshDevice(
                    RPi,
                    XBee64BitAddress.from_hex_string(
                        str(DevList.get(args.remote))))
                #print("\n")
            else:
                print("Target NodeID: " + args.remote +
                      " not found in network.conf, try rescan first.")
                exit()

        if args.setdigout:
            SetDigitalOut(RemoteXBee, args.setdigout, args.quiet)

        # Either --readall
        if args.readall:
            args.anapins = '0,1,2,3'
            args.digipins = '0,1,2,3'
            readall = '0,1,2,3'

            ReadInputs = ReadAnalog(RemoteXBee, readall,
                                    args.quiet) + ReadDigital(
                                        RemoteXBee, readall, args.quiet)
            FormedAll = Format(RemoteXBee, ReadInputs, args.format,
                               args.anapins, args.digipins)

        # Or read specific
        else:
            if args.anapins:

                ReadInputs = ReadAnalog(RemoteXBee, args.anapins, args.quiet)
                FormedAnalog = Format(RemoteXBee, ReadInputs, args.format,
                                      args.anapins, '')  # No digital ''

            if args.digipins:

                ReadInputs = ReadDigital(RemoteXBee, args.digipins, args.quiet)
                FormedDigital = Format(RemoteXBee, ReadInputs, args.format, '',
                                       args.digipins)  # No analog ''

        if args.std:

            if FormedAll:
                Output(RemoteXBee, FormedAll, args.format, args.remote, 'std',
                       args.anapins, args.digipins, args.quiet)
            else:
                Output(RemoteXBee, FormedAnalog + FormedDigital, args.format,
                       args.remote, 'std', args.anapins, args.digipins,
                       args.quiet)

        elif args.json:

            if FormedAll:
                Output(RemoteXBee, FormedAll, args.format, args.remote, 'json',
                       args.anapins, args.digipins, args.quiet)
            else:
                Output(RemoteXBee, FormedAnalog + FormedDigital, args.format,
                       args.remote, 'json', args.anapins, args.digipins,
                       args.quiet)

        elif args.log:

            if FormedAll:
                Output(RemoteXBee, FormedAll, args.format, args.remote, 'log',
                       args.anapins, args.digipins, args.quiet)
            else:
                Output(RemoteXBee, FormedAnalog + FormedDigital, args.format,
                       args.remote, 'log', args.anapins, args.digipins,
                       args.quiet)

        else:

            if not args.show:
                if FormedAll:
                    Output(RemoteXBee, FormedAll, args.format, args.remote,
                           'default', args.anapins, args.digipins, args.quiet)
                else:
                    Output(RemoteXBee, FormedAnalog + FormedDigital,
                           args.format, args.remote, 'default', args.anapins,
                           args.digipins, args.quiet)

    finally:
        if RPi is not None and RPi.is_open():
            RPi.close()
Пример #24
0
from builtins import input
from digi.xbee.models.message import XBeeMessage
from digi.xbee.models.address import XBee16BitAddress, XBee64BitAddress
from DisplayManager import DisplayManager
import sys

try:
    COMport = sys.argv[1]
except IndexError:
    COMport = 'COM9'

baud_rate = 9600
remote_address = '0010'
transmitDevice = XBeeDevice(COMport, baud_rate)
remoteDevice = RemoteXBeeDevice(
    transmitDevice, XBee64BitAddress.from_hex_string(remote_address),
    XBee16BitAddress.from_hex_string(remote_address))


def main():

    xbeeCommunication()


def xbeeCommunication():
    transmitDevice.close()

    print('transmitting to: ')
    print(remoteDevice.get_16bit_addr())
    cont = 'y'
    pb = PB.PathBuilder()
Пример #25
0
        def callback_device_discovered(remote):
            print("Device discovered: %s" % remote)

            MAC = str(remote)
            MAC1 = MAC.split(' -')
            MAC = str(MAC1[:1])
            MACS = str(MAC[2:18])
            MACST = "" + MACS
            #realiza uma busca pelo MAC no banco de dados.
            cursor.execute("SELECT `MAC` FROM `ESTACAO` WHERE `MAC`='" +
                           MACST + "'")
            resultado = cursor.fetchall()
            #verifica se o MAC já foi inserido no banco de dados
            contrbanc = 0
            for linha in resultado:
                contrbanc = 1
            if contrbanc == 0:
                try:
                    # TODO: Replace with the 64-bit address of the remote device.
                    REMOTE_DEVICE_ADDRESS = XBee64BitAddress.from_hex_string(
                        "" + MACST)
                    remote_xbee = RemoteXBeeDevice(
                        device, x64bit_addr=REMOTE_DEVICE_ADDRESS)

                    device.read_device_info()
                    print("Read device info of local device successfully")
                    remote_xbee.read_device_info()
                    print("Read device info of remote device successfully")

                    print("\nLocal:")
                    print(device.get_node_id())
                    print(device.get_hardware_version())
                    print(hex_to_string(device.get_firmware_version()))
                    print(device.get_protocol())
                    # Read the output power level.
                    #print(""+str(device.get_power_level()))

                    print("\nRemote:")
                    print(remote_xbee.get_node_id())
                    print(remote_xbee.get_hardware_version())
                    print(hex_to_string(remote_xbee.get_firmware_version()))
                    print(remote_xbee.get_protocol())
                    print("Teste-->" + str(device.get_parameter("DB")))

                    #ni = ''.join(random.choice(string.ascii_letters) for i in range(random.randint(1, 20)))
                    #device.set_parameter("NI", bytearray(ni, "utf8"))
                    #param = device.get_parameter("NI")
                    #assert (param.decode() == ni)

                    #ni = ''.join(random.choice(string.ascii_letters) for i in range(random.randint(1, 20)))
                    #remote_xbee.set_parameter("NI", bytearray(ni, "utf8"))
                    #param = remote_xbee.get_parameter("NI")
                    #assert (param.decode() == ni)

                    print("\nTest finished successfully")

                    cursor.execute(
                        "INSERT INTO ESTACAO( MAC, NOM, VERSHARD, CODVER, PROTVERS) VALUES ('"
                        + MACST + "','" + str(remote_xbee.get_node_id()) +
                        "','" + str(remote_xbee.get_hardware_version()) +
                        "','" +
                        str(hex_to_string(remote_xbee.get_firmware_version()))
                        + "','" + str(remote_xbee.get_protocol()) + "')")
                    conexao.commit()
                    print("MAC inserido!!!")
                finally:
                    if device is not None and device.is_open():
                        print("Não inseriu no banco de dados!!!")
            else:
                print("MAC já inserido!!!")
Пример #26
0
 def remote_Zigbee(self, mac):
     self.__remote = RemoteZigBeeDevice(
         self, XBee64BitAddress.from_hex_string(mac))
Пример #27
0
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

from digi.xbee.models.address import XBee64BitAddress
from digi.xbee.devices import XBeeDevice, RemoteXBeeDevice
from digi.xbee.io import IOLine, IOMode

# TODO: Replace with the serial port where your local module is connected to.
PORT = "COM1"
# TODO: Replace with the baud rate of your local module.
BAUD_RATE = 9600
# TODO: Replace with the 64-bit address of the remote device.
REMOTE_DEVICE_ADDRESS = XBee64BitAddress.from_hex_string("0013A20040D47B73")


def main():

    print(" +---------------------+")
    print(" | Read IO Sample Test |")
    print(" +---------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()

        device.set_io_configuration(IOLine.DIO1_AD1, IOMode.DIGITAL_IN)
Пример #28
0
CMD_SHUTDOWN = 0xFF
CMD_ERROR = 0x55
CMD_POWERON = 0xEE
DETECTOR_SHUTDOWN = 0xD0
DETECTOR_OPERATIONAL = 0xD1
MAX_TEMP = 32

#adjust as appropriate for the configuration
BAUD_RATE = 9600
MAC_COORD_PORT = "/dev/tty.usbserial-DN01J874"
WIN_COORD_PORT = "COM"
PAN_ID = 0x4444
COORD_MAC = 0x0013A20041531EE7
ROUT_MAC = 0x0013A20041052F50
ROUTER_ID = "end-node"
router_64addr = XBee64BitAddress.from_hex_string("0013A20041052F50")


# main entry point for xbee_app
def main():

    coord = coordinator(MAC_COORD_PORT, BAUD_RATE)  #coordinator node

    # set up variables for tracking packets and temperature
    average_temp = 0
    read_count = 0
    total_temp = 0
    temperature_readings = []
    packet_num = 0

    # open the node, print it's information and connect the router node
Пример #29
0
'''
Created on Feb 18, 2019

@author: Jake
'''
from digi.xbee.devices import XBeeDevice, RemoteXBeeDevice
import RobotInstruction
from builtins import input
from digi.xbee.models.address import XBee16BitAddress, XBee64BitAddress


COMport = 'COM9'
baud_rate = 9600
remote_address = '0008'
transmitDevice = XBeeDevice(COMport,baud_rate)
remoteDevice = RemoteXBeeDevice(transmitDevice, XBee64BitAddress.from_hex_string(remote_address), XBee16BitAddress.from_hex_string(remote_address))


def main():
    transmitDevice.close()
    
    print('transmitting to: ')
    print(remoteDevice.get_16bit_addr())
    cont = 'y'
    while(cont != 'q'):
        try:
            transmitDevice.open()
            instruction = getCommand()
            
            #print(hex(instruction))
            sendInstructions(instruction)
Пример #30
0
def establish_connection(
        address):  # 首次建立连接时使用,平台端接收到电脑端的地址即成功,但是python的16进制实在操蛋,字符串先将就着用用
    remote_device = RemoteXBeeDevice(Raw802Device,
                                     XBee64BitAddress.from_hex_string(address))
    Raw802Device.send_data(remote_device,
                           "\x75\x03" + str(Raw802Device.get_64bit_addr()))