Ejemplo n.º 1
0
def publisher(xbee):
    '''Xbee station'''
    #****************************************************************************************#
    # TODO: Replace with the serial port where your local module is connected to.
    PORT = "/dev/ttyUSB0"  #La estacion
    # TODO: Replace with the baud rate of your local module.
    BAUD_RATE = 9600
    REMOTE_NODE_ID = "vtecboat"  #El remoto es el bote, Esta es la estacion
    #****************************************************************************************#

    print(" +--------------------------------------+")
    print(" |           Sender (Station)           |")
    print(" +--------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)
    try:
        device.open()
        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)
        print(" +--------------------------------------+")
        print(" |    Give 1 to receive GPS coords      |")
        print(" |    Give 2 to send target coords      |")
        print(" |    Give 3 to autonomous nav 1        |")
        print(" |    Give 4 to autonomous nav 2        |")
        print(" |    Give 5 to path planning           |")
        print(" +--------------------------------------+\n")
        action = input("action: ")
        xbee.set_action(action)
        if action == '1':
            xbee.set_target('0.000', '0.000')
        elif action == '2':
            print(
                "Dame la latitud y longitud del waypoint donde se iniciara el challenge: "
            )
            lat = input("\n lat: ")
            lon = input("\n lon: ")
            xbee.set_target(lat, lon)
        elif action == '5':
            #path planning
            print("path plan")
        device.send_data(remote_device, xbee.send())
        while True:
            xbee_message = device.read_data()
            if xbee_message is not None:
                jmessage = json.loads(bytes(
                    xbee_message.data).decode())  ###### Guarda el json
                print(jmessage)  #Imprime el json para prueba
                print("\n")
                xbee_network = device.get_network()
                remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
                action = input("action: ")
                xbee.set_action(action)
                if action == '1':
                    xbee.set_target('0.000', '0.000')
                elif action == '2':
                    print(
                        "Dame la latitud y longitud del waypoint donde se iniciara el challenge: "
                    )
                    lat = input("\n lat: ")
                    lon = input("\n lon: ")
                    xbee.set_target(lat, lon)
                elif action == '5':
                    #path planning
                    print("path plan")
                device.send_data(remote_device, xbee.send())

        print("Success")

    finally:
        if device is not None and device.is_open():
            device.close()
Ejemplo n.º 2
0
 def get_parameter(xbee: XBeeDevice, param: str) -> str:
     return utils.hex_to_string(xbee.get_parameter(param))
Ejemplo n.º 3
0
def main():
    print(" +-------------+")
    print(" | Calculating ..! |")
    print(" +-------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)

    try:
        device.open()
        # Obtain the remote XBee device from the XBee network.
        xbee_network = device.get_network()
        remote_device = xbee_network.discover_device(REMOTE_NODE_ID)
        if remote_device is None:
            print("Could not find the remote device")
            exit(1)
        while True:
            device.send_data(remote_device, 'a')
            rssi = device.get_parameter("DB")
            r = int.from_bytes(rssi, byteorder='big')
            res = (f"-{r}dbm")
            with open('web/data.csv', 'a') as outfile:
                writer = csv.writer(outfile)
                writer.writerow([res])
            print(res)

            time.sleep(0.2)

    finally:
        if device is not None and device.is_open():
            device.close()
Ejemplo n.º 4
0
def ensure_running_latest_micropython_app(build_dir: str,
                                          xbee: XBeeDevice) -> Error:
    """
    Deploys the compiled .mpy files to the target. Also ensures that no main.py file exists on the device.

    Assumes that the xbee device has already been already opened.

    A note about main.py versus main.mpy:
    We compile main.py to main.mpy and deploy the .mpy version to the device.
    Note that if the device already contains a main.py, it will run the main.py instead.
    It is therefore up to the host processor (if one) or else the MicroPython deployment process
    to ensure that no main.py file exists on the device. When I first started using XBees, I deployed
    .mpy versions of all files EXCEPT main.py so that you'd never have a case where you accidentally
    deploy an out-of-date main.py that keeps running at startup instead of your desired main.mpy file.
    But that approach has the following downsides: 1) waste RAM and time at startup because the device
    must compile the .py file every time, 2) more complexity because you need to train main.py
    as a special case, 3) you don't the compile-time checking advantages of cross-compiling main.py
    unless you compile it too. Short answer: Use main.mpy on the device.
    """

    # TODO Make this function also remote any extraneous .mpy file from the device!

    mpy_files = [
        XBeeFile(file_path) for file_path in glob.glob("%s/*.mpy" % build_dir)
    ]

    updated_files = False  # Indicates if file(s) were updated so that MicroPython interpreter can be restarted.
    main_py_was_deleted = False  # Indicates if main.py was removed so that MicroPython interpreter can be restarted.
    updated_atps = False  # Indicates if the ATPS setting (automatically launch MicroPython code at startup) is set.

    with OpenFileSystem(xbee) as fs:

        # Update any missing or out-of-date .mpy files on the device.
        for f in mpy_files:

            # Test if file needs to be deployed.
            log("Checking SHA-256 hash of the file %s" % f.name)
            f.retrieve_xbeehash(fs)
            if f.xbeehash == f.localhash:
                continue

            # Deploy the file.
            try:
                log("Deploying file %s" % f.name)
                fs.put_file(source_path=f.localpath,
                            dest_path=f.xbeepath,
                            secure=False)
            except FileSystemException as ex:
                return Error("ERROR: Failed to deploy file %s: %s" %
                             (f.xbeepath, ex))

            # Check that file was correctly deployed.
            log("Verifying correct deployment of the file %s" % f.name)
            f.retrieve_xbeehash(fs)
            if f.xbeehash != f.localhash:
                return Error(
                    "ERROR: Deployed file checksum mismatch! %s vs %s" %
                    (f.xbeehash, f.localhash))

            updated_files = True

        log("mpy_files:\n%s" % "\n".join(["%s" % f for f in mpy_files]))

        # Ensure that main.py does not exist on the device.
        try:
            fs.remove_element(MAIN_PY)
            main_py_was_deleted = True
            log("Successfully deleted file %s." % MAIN_PY)
        except FileSystemException as ex:
            if "ENOENT" not in repr(ex):
                return Error("ERROR: Failed to delete %s. Details: %s" %
                             (MAIN_PY, ex))
            log("Looks like file %s does not exist. Good." % MAIN_PY)

    # Ensure that ATPS is set to enable MicroPython to run at startup.
    param = "PS"
    desired = b"\x01"
    actual = xbee.get_parameter(param)
    if actual != desired:
        log("AT%s needs to be changed. was %s, changing to %s" %
            (param, actual, desired))
        xbee.set_parameter(param, desired)
        xbee.write_changes()  # Persist this change across device resets.
        updated_atps = True
        actual = xbee.get_parameter(param)
        if actual != desired:
            return Error("ERROR: Failed to change AT%s setting" % param)
    log("Confirmed that AT%s is set correctly." % param)

    # Determine if the MicroPython interpreter needs to be restarted.
    if updated_files or main_py_was_deleted or updated_atps:
        log("Need need to restart the MicroPython interpreter because %s%s%s" %
            ("one or more MicroPython files changed." if updated_files else "",
             "an old main.py was deleted." if main_py_was_deleted else "",
             "ATPS was not previously set." if updated_atps else ""))
        err = restart_micropython_interpreter(xbee)
        if err:
            return Error(
                "Error: Failed to restart MicroPython interpreter. Details: %s"
                % err)
        log("Successfully restarted MicroPython interpreter.")
    else:
        log("MicroPython interpreter does not need to be restarted. It is already running the latest code."
            )

    return Success
Ejemplo n.º 5
0
lightADC = IOLine.DIO1_AD1
tempADC = IOLine.DIO2_AD2
humidityADC = IOLine.DIO3_AD3

# IMPORTANT: Set these to the port that
# your coordinator is connected to and
# its baud rate.
port = "/dev/ttyUSB0"
baud = 9600

# IMPORTANT: Set these to the Node Identifiers (NI)
# for your remote sensors. The NI can be set
# with Digi's XCTU application.
node_ids = ["SENSE1", "SENSE2", "SENSE3"]

local_device = XBeeDevice(port, baud)
local_device.open()

# Obtain the remote XBee device from the XBee network.
net = local_device.get_network()
sensors = [net.discover_device(node) for node in node_ids]

# Set up TCP socket
host = ''
port = 12000
TCPSock = socket(AF_INET, SOCK_STREAM)
TCPSock.bind((host, port))
connected = False
while True:
    if not connected:
        print("Waiting for a connection...")
Ejemplo n.º 6
0
    def data_call(self):

        device = XBeeDevice(self.config.port, self.config.baudrate)

        return device
def main():
    def read_adc_task(indice):
        global systembusy
        while True or intentos[indice] < MAX_INTENTOS_LEER_DATOS:
            try:
                print("entro hilo")
                lock.acquire()
                print(threading.current_thread().getName())
                # Leemos el valor del nodo para luego calcular el valor de la resistencia del termistor mediante la
                # ley de Ohm para un divisor de tensión
                #time.sleep(1)
                vcc = nodos_activos[indice].get_parameter("%V")
                vcc = int(utils.hex_to_string(vcc).replace(' ', ''), 16)
                # Leemos el valor crudo de las entradas analógicas
                raw_value_1 = nodos_activos[indice].get_adc_value(IOLINE_IN_0)
                raw_value_2 = nodos_activos[indice].get_adc_value(IOLINE_IN_1)
                raw_value_3 = nodos_activos[indice].get_adc_value(IOLINE_IN_2)
                raw_value_4 = nodos_activos[indice].get_adc_value(IOLINE_IN_3)
                # Calculamos el valor de temperatura en cada entrada en función de la tensión de alimentación y del
                # valor crudo

                #print("Nodo %s" % nodos_activos[indice])
                tntc_1 = ntc10k_calculate_temp(raw_value_1, vcc)
                tntc_2 = ntc10k_calculate_temp(raw_value_2, vcc)
                tntc_3 = ntc10k_calculate_temp(raw_value_3, vcc)
                tntc_4 = ntc10k_calculate_temp(raw_value_4, vcc)

                # ************************************************************************
                # ESTA ES LA PARTE DE TELEGRAF
                intentos[indice] = 0
                print(str(datetime.now()))
                send_data_to_telegraf.main(REMOTE_NODES_ID[indice], tntc_1,
                                           tntc_2, tntc_3, tntc_4, float(vcc))
                print("Telegraf!")
                # Esperamos hasta la siguiente toma de muestras
                espera[indice] = LONG_WAIT
                print("Systembusy: %s" % systembusy)
                print("indice %s" % indice)
                print("Nodos esperas %s" % espera)
                lock.release()

            #except TimeoutException as ex:
            except:
                intentos[indice] += 1
                lock.release()
                espera[indice] = SHORT_WAIT
                print(REMOTE_NODES_ID[indice])
                print("Systembusy: %s" % systembusy)
                print("ADC timeouts %s" % intentos)
                print("Nodos esperas %s" % espera)

                if intentos[indice] > MAX_INTENTOS_LEER_DATOS:
                    #th[indice].join()
                    raise
            #print("Espera: %s" % espera)
            print(espera[indice])
            time.sleep(espera[indice])

    def status():
        global systembusy
        while True:
            print("Systembusy: %s" % systembusy)
            time.sleep(1)

    index_devices = 0
    th = []
    nodos_activos = []
    intentos = []
    print("Cantidad de nodos: %s" % len(REMOTE_NODES_ID))

    try:
        local_device = XBeeDevice(port, baud_rate)
        xbee_network = local_device.get_network()
        local_device.open()
        th2 = threading.Thread(name='log', target=status)
        #th2.start()

        for index in range(0, len(REMOTE_NODES_ID)):
            nodo_descubierto = False
            intentos.append(0)
            # Procedimiento de descubrimiento de nodos, ver que pasa si uno está apagado
            while (nodo_descubierto !=
                   True) and intentos[index] < MAX_INTENTOS_DESCUBRIMIENTO:
                remote_device = (xbee_network.discover_device(
                    REMOTE_NODES_ID[index]))
                if remote_device is None:
                    print("Could not find the remote device: " +
                          REMOTE_NODES_ID[index]
                          )  # ESTOY HAY QUE VER COMO SE HACE
                    intentos[index] += 1
                    print("Nodo: %s" % (REMOTE_NODES_ID[index]))
                    print("Intentos descubrimiento restantes: %s" %
                          (MAX_INTENTOS_DESCUBRIMIENTO - intentos[index]))
                    time.sleep(1)
                else:
                    nodos_activos.append(remote_device)
                    index_devices += 1
                    print('Descubierto: %s' % remote_device)
                    nodo_descubierto = True
        #ejecución de los hilos
        for index in range(0, index_devices):
            thread = threading.Thread(name=nodos_activos[index],
                                      target=read_adc_task,
                                      args=(index, ))
            th.append(thread)

        intentos = []
        espera = []
        for index in range(0, index_devices):
            intentos.append(0)
            espera.append(SHORT_WAIT)
            th[index].start()
            th[index].join()
            time.sleep(1)

    except:
        print("eRRor")

    finally:
        for index in range(0, index_devices):
            if th[index] is not None and th[index].isAlive():
                th[index].join()
        if local_device.is_open():
            local_device.close()
        exit(-1)
Ejemplo n.º 8
0
 def connect(self):
     self.device = XBeeDevice(self.PORT, self.BAUD_RATE)
Ejemplo n.º 9
0
from digi.xbee.devices import XBeeDevice
from digi.xbee.devices import RemoteXBeeDevice
from digi.xbee.models.address import XBee64BitAddress
import time
#Import regarding scheduler tasks
from apscheduler.schedulers.background import BackgroundScheduler

# define background scheduler
sched = BackgroundScheduler()

PORT = '/dev/ttyUSB0'
BAUD_RATE = 9600
DRONE_ID = "0013A200419B5208"
DATA_TO_SEND = "Hello World:"

my_device = XBeeDevice(PORT, BAUD_RATE)
count = 0

my_device.open()


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))


sched.add_job(send_data, 'interval', seconds=1)
sched.start()
Ejemplo n.º 10
0
def main():
    #log=""
    # Parámetros de conexión con el puerto serie al dispositivo local
    port = read_sys_config.ReadLocalPortFromFile()
    baud_rate = read_sys_config.ReadLocalBaudRateFromFile()
    local_device = XBeeDevice(port, baud_rate)


    try:

        print(" +-----------------------------------------------+")
        print(" |         Get Local XBee Parameters             |")
        print(" +-----------------------------------------------+\n")

        local_device.open()
       # Get Hardware Models with extended DIO (P5 to P9)
        Hardware_Extended = read_sys_config.ReadHardwareVersionWhithP5ToP9PinsFromFile()
       # Get parameters.
        # Diagnostic Commads
        VR = utils.hex_to_string(local_device.get_parameter("VR"))
        HV = utils.hex_to_string(local_device.get_parameter("HV"))
        AI = utils.hex_to_string(local_device.get_parameter("AI"))
        DB = utils.hex_to_string(local_device.get_parameter("DB"))
        V =  utils.hex_to_string(local_device.get_parameter("%V"))
        # Networking
        ID = utils.hex_to_string(local_device.get_parameter("ID"))
        SC = utils.hex_to_string(local_device.get_parameter("SC"))
        SD = utils.hex_to_string(local_device.get_parameter("SD"))
        ZS = utils.hex_to_string(local_device.get_parameter("ZS"))
        NJ = utils.hex_to_string(local_device.get_parameter("NJ"))
        NW = utils.hex_to_string(local_device.get_parameter("NW"))
        JV = utils.hex_to_string(local_device.get_parameter("JV"))
        JN = utils.hex_to_string(local_device.get_parameter("JN"))
        OP = utils.hex_to_string(local_device.get_parameter("OP"))
        OI = utils.hex_to_string(local_device.get_parameter("OI"))
        CH = utils.hex_to_string(local_device.get_parameter("CH"))
        NC = utils.hex_to_string(local_device.get_parameter("NC"))
        CE = utils.hex_to_string(local_device.get_parameter("CE"))
        DO = utils.hex_to_string(local_device.get_parameter("DO"))
        DC = utils.hex_to_string(local_device.get_parameter("DC"))
        # Addressing
        SH = utils.hex_to_string(local_device.get_parameter("SH"))
        SL = utils.hex_to_string(local_device.get_parameter("SL"))
        MY = utils.hex_to_string(local_device.get_parameter("MY"))
        MP = utils.hex_to_string(local_device.get_parameter("MP"))
        DH = utils.hex_to_string(local_device.get_parameter("DH"))
        DL = utils.hex_to_string(local_device.get_parameter("DL"))
        NI = local_device.get_parameter("NI").decode()
        NH = utils.hex_to_string(local_device.get_parameter("NH"))
        BH = utils.hex_to_string(local_device.get_parameter("BH"))
        AR = utils.hex_to_string(local_device.get_parameter("AR"))
        DD = utils.hex_to_string(local_device.get_parameter("DD"))
        NT = utils.hex_to_string(local_device.get_parameter("NT"))
        NO = utils.hex_to_string(local_device.get_parameter("NO"))
        NP = utils.hex_to_string(local_device.get_parameter("NP"))
        CR = utils.hex_to_string(local_device.get_parameter("CR"))
        # ZigBee Addressing
        SE = utils.hex_to_string(local_device.get_parameter("SE"))
        DE = utils.hex_to_string(local_device.get_parameter("DE"))
        CI = utils.hex_to_string(local_device.get_parameter("CI"))
        TO = utils.hex_to_string(local_device.get_parameter("TO"))
        # RF Interfacing
        PL = utils.hex_to_string(local_device.get_parameter("PL"))
        PM = utils.hex_to_string(local_device.get_parameter("PM"))
        PP = utils.hex_to_string(local_device.get_parameter("PP"))
        # Security
        EE = utils.hex_to_string(local_device.get_parameter("EE"))
        EO = utils.hex_to_string(local_device.get_parameter("EO"))
        KY = utils.hex_to_string(local_device.get_parameter("KY"))
        NK = utils.hex_to_string(local_device.get_parameter("NK"))
        # Serial Interfacing
        BD = utils.hex_to_string(local_device.get_parameter("BD"))
        NB = utils.hex_to_string(local_device.get_parameter("NB"))
        SB = utils.hex_to_string(local_device.get_parameter("SB"))
        RO = utils.hex_to_string(local_device.get_parameter("RO"))
        D6 = utils.hex_to_string(local_device.get_parameter("D6"))
        D7 = utils.hex_to_string(local_device.get_parameter("D7"))
        AP = utils.hex_to_string(local_device.get_parameter("AP"))
        AO = utils.hex_to_string(local_device.get_parameter("AO"))
        # AT Command Options
        CT = utils.hex_to_string(local_device.get_parameter("CT"))
        GT = utils.hex_to_string(local_device.get_parameter("GT"))
        CC = utils.hex_to_string(local_device.get_parameter("CC"))
        # Sleep Modes
        SP = utils.hex_to_string(local_device.get_parameter("SP"))
        SN = utils.hex_to_string(local_device.get_parameter("SN"))
        SM = utils.hex_to_string(local_device.get_parameter("SM"))
        ST = utils.hex_to_string(local_device.get_parameter("ST"))
        SO = utils.hex_to_string(local_device.get_parameter("SO"))
        WH = utils.hex_to_string(local_device.get_parameter("WH"))
        PO = utils.hex_to_string(local_device.get_parameter("PO"))
        # I/O Settomgs
        D0 = utils.hex_to_string(local_device.get_parameter("D0"))
        D1 = utils.hex_to_string(local_device.get_parameter("D1"))
        D2 = utils.hex_to_string(local_device.get_parameter("D2"))
        D3 = utils.hex_to_string(local_device.get_parameter("D3"))
        D4 = utils.hex_to_string(local_device.get_parameter("D4"))
        D5 = utils.hex_to_string(local_device.get_parameter("D5"))
        D8 = utils.hex_to_string(local_device.get_parameter("D8"))
        D9 = utils.hex_to_string(local_device.get_parameter("D9"))
        P0 = utils.hex_to_string(local_device.get_parameter("P0"))
        P1 = utils.hex_to_string(local_device.get_parameter("P1"))
        P2 = utils.hex_to_string(local_device.get_parameter("P2"))
        P3 = utils.hex_to_string(local_device.get_parameter("P3"))
        P4 = utils.hex_to_string(local_device.get_parameter("P4"))
        if HV == Hardware_Extended:
            P5 = utils.hex_to_string(local_device.get_parameter("P5"))
            P6 = utils.hex_to_string(local_device.get_parameter("P6"))
            P7 = utils.hex_to_string(local_device.get_parameter("P7"))
            P8 = utils.hex_to_string(local_device.get_parameter("P8"))
            P9 = utils.hex_to_string(local_device.get_parameter("P9"))
        PR = utils.hex_to_string(local_device.get_parameter("PR"))
        PD = utils.hex_to_string(local_device.get_parameter("PD"))
        LT = utils.hex_to_string(local_device.get_parameter("LT"))
        RP = utils.hex_to_string(local_device.get_parameter("RP"))
        # I/O Sampling
        IR = utils.hex_to_string(local_device.get_parameter("IR"))
        IC = utils.hex_to_string(local_device.get_parameter("IC"))
        Vplus = utils.hex_to_string(local_device.get_parameter("V+"))

        #print parameters
        log= " +-----------------------------+\n"
        log= log + " | Networking                  |\n"
        log = log + " +-----------------------------+\n"
        log = log + " PAN ID:                      %s" % ID + "\n"
        log = log + " Scan Channel:                %s" % SC + "\n"
        log = log + " Scan Duration:               %s" % SD + "\n"
        log = log + " Network Watchdog Timeout:    %s" % NW + "\n"
        log = log + " Channel Verification:        %s" % JV + "\n"
        log = log + " Join Notification:           %s" % JN + "\n"
        log = log + " Operating PAN ID:            %s" % OP + "\n"
        log = log + " Operating 16-bit PAN ID:     %s" % OI + "\n"
        log = log + " Operating Channel:           %s" % CH + "\n"
        log = log + " Number of Remaining Children:%s" % NC + "\n"
        log = log + " Coordinator Enable:          %s" % CE + "\n"
        log = log + " Device Options:              %s" % DO + "\n"
        log = log + " Device Controls:             %s" % DC + "\n\n"

        log = log + " +-----------------------------+\n"
        log = log + " | Addressing                  |\n"
        log = log + " +-----------------------------+\n"
        log = log + " Serial Number High:          %s" % SH + "\n"
        log = log + " Serial Number Low:           %s" % SL + "\n"
        log = log + " 16-bit Network Address:      %s" % MY + "\n"
        log = log + " 16-bit Parent Address:       %s" % MP + "\n"
        log = log + " Destination Address High:    %s" % DH + "\n"
        log = log + " Destination Address Low:     %s" % DL + "\n"
        log = log + " Node Identifier:             %s" % NI + "\n"
        log = log + " Maximum Hops:                %s" % NH + "\n"
        log = log + " Broadcast Radius:            %s" % BH + "\n"
        log = log + " Many-to-One Route Bro. Time: %s" % AR + "\n"
        log = log + " Device Type Identifier:      %s" % DD + "\n"
        log = log + " Node Discovery Backoff:      %s" % NT + "\n"
        log = log + " Node Discovery Options:      %s" % NO + "\n"
        log = log + " Maximum Num.Trans. Bytes:    %s" % NP + "\n"
        log = log + " PAN Conflict Threshold:      %s" % CR + "\n\n"

        log = log + " +-----------------------------+\n"
        log = log + " | ZigBee Addressing           |\n"
        log = log + " +-----------------------------+\n"
        log = log + " Zigbee Source Endpoint:      %s" % SE + "\n"
        log = log + " Zigbee Destination Endpoint: %s" % DE + "\n"
        log = log + " Zigbee Cluster ID:           %s" % CI + "\n"
        log = log + " Transmit Options:            %s" % TO + "\n\n"

        log = log + " +-----------------------------+\n"
        log = log + " | RF Interfacing              |\n"
        log = log + " +-----------------------------+\n"
        log = log + " Tx Power Level:              %s" % PL + "\n"
        log = log + " Power Mode:                  %s" % PM + "\n"
        log = log + " Power at PL4:                %s" % PP + "\n\n"

        log = log + " +-----------------------------+\n"
        log = log + " | Security                    |\n"
        log = log + " +-----------------------------+\n"
        log = log + " Encryption Enable:           %s" % EE + "\n"
        log = log + " Encryption Options:          %s" % EO + "\n"
        log = log + " Encryption Key:              %s" % KY + "\n"
        log = log + " Network Encryption Key:      %s" % NK + "\n\n"

        log = log + " +-----------------------------+\n"
        log = log + " | Serial Interfacing          |\n"
        log = log + " +-----------------------------+\n"
        log = log + " Baud Rate:                   %s" % BD + "\n"
        log = log + " Parity:                      %s" % NB + "\n"
        log = log + " Stop Bits:                   %s" % SB + "\n"
        log = log + " Packetization Timeout:       %s" % RO + "\n"
        log = log + " DIO6/nRTS Configuration  :   %s" % D6 + "\n"
        log = log + " DIO7/nCTS Configuration:     %s" % D7 + "\n"
        log = log + " API Enable:                  %s" % AP + "\n"
        log = log + " API Output Mode:             %s" % AO + "\n\n"

        log = log + " +-----------------------------+\n"
        log = log + " | AT Command Options          |\n"
        log = log + " +-----------------------------+\n"
        log = log + " AT Command Mode Timeout:     %s" % CT + "\n"
        log = log + " Guard Times:                 %s" % GT + "\n"
        log = log + " Command Sequence Character:  %s" % CC + "\n\n"

        log = log + " +-----------------------------+\n"
        log = log + " | Sleep Modes                 |\n"
        log = log + " +-----------------------------+\n"
        log = log + " Cyclic Sleep Period:         %s" % SP + "\n"
        log = log + " Number of Cyclic Sleep Per.: %s" % SN + "\n"
        log = log + " Sleep Mode:                  %s" % SM + "\n"
        log = log + " Time Before Sleep:sss        %s" % ST + "\n"
        log = log + " Sleep Options:               %s" % SO + "\n"
        log = log + " Wake Hosts:                  %s" % WH + "\n"
        log = log + " Poll Rate:                   %s" % PO + "\n\n"

        log = log + " +-----------------------------+\n"
        log = log + " | I/O Settings                |\n"
        log = log + " +-----------------------------+\n"
        log = log + " DIO0/ADO/CB Configuration:   %s" % D0 + "\n"
        log = log + " DIO1/AD1 Configuration:      %s" % D1 + "\n"
        log = log + " DIO2/AD2 Configuration:      %s" % D2 + "\n"
        log = log + " DIO3/AD3 Configuration:      %s" % D3 + "\n"
        log = log + " DIO4 Configuration:          %s" % D4 + "\n"
        log = log + " DIO5 Configuration:          %s" % D5 + "\n"
        log = log + " DIO8 Configuration:          %s" % D8 + "\n"
        log = log + " DIO9 Configuration:          %s" % D9 + "\n"
        log = log + " DIO10 Configuration:         %s" % P0 + "\n"
        log = log + " DIO11 Configuration:         %s" % P1 + "\n"
        log = log + " DIO12 Configuration:         %s" % P2 + "\n"
        log = log + " DIO13 Configuration:         %s" % P3 + "\n"
        log = log + " DIO14 Configuration:         %s" % P4 + "\n"
        if HV == Hardware_Extended:
            log = log + " DIO15 Configuration:         %s" % P5 + "\n"
            log = log + " DIO16 Configuration:         %s" % P6 + "\n"
            log = log + " DIO17 Configuration:         %s" % P7 + "\n"
            log = log + " DIO18 Configuration:         %s" % P8 + "\n"
            log = log + " DIO19 Configuration:         %s" % P9 + "\n"
        log = log + " Pull-UP Resistor Enable:     %s" % PR + "\n"
        log = log + " Pull-Up/down Direction:      %s" % PD + "\n"
        log = log + " Associate LED Blink Time:    %s" % LT + "\n"
        log = log + " RSSI PWM Timer:              %s" % RP + "\n\n"

        log = log + " +-----------------------------+\n"
        log = log + " | I/O Sampling                |\n"
        log = log + " +-----------------------------+\n"
        log = log + " IO Sampling Rate:            %s" % IR + "\n"
        log = log + " Digital IO Change Detection: %s" % IC + "\n"
        log = log + " Supply Votage High Thres.:   %s" % Vplus + "\n\n"

        log = log + " +-----------------------------+\n"
        log = log + " | Diagnostic Commands         |\n"
        log = log + " +-----------------------------+\n"
        log = log + " Firmaware Version:           %s" % VR + "\n"
        log = log + " Hardware Version:            %s" % HV + "\n"
        log = log + " Association Indication:      %s" % AI + "\n"
        log = log + " RSSI of Last Packet:         %s" % DB + "\n"

    except:
        if local_device.is_open():
            local_device.close()
        log ="Sorry an error has happened"
        pass


    finally:
        if local_device is not None and local_device.is_open():
            local_device.close()
        pass


    return log
Ejemplo n.º 11
0
from digi.xbee.devices import XBeeDevice
import serial
import time
import threading
import queue
import struct
import datetime

GPS_PORT = '/dev/serial/by-id/usb-FTDI_USB_Serial_Converter_FT8VW9AR-if00-port0'  #Pi ADCP
xbee_port = '/dev/serial/by-id/usb-FTDI_FT231X_USB_UART_DN02Z3LX-if00-port0'  #Pi xbee
COM_PORT = '/dev/serial/by-id/usb-FTDI_USB_Serial_Converter_FT8VWDWP-if00-port0'
BAUD_RATE = "115200"
ADCP_ser = serial.Serial(COM_PORT, BAUD_RATE, stopbits=serial.STOPBITS_ONE)
GPS_ser = serial.Serial(GPS_PORT, bytesize=8)
boat_xbee = XBeeDevice(xbee_port, 9600)

adcp_filename = 'Log/ADCP_' + datetime.datetime.now().replace(
    microsecond=0).strftime('%y-%m-%d %H.%M.%S') + '.bin'
gps_filename = 'Log/GPS_' + datetime.datetime.now().replace(
    microsecond=0).strftime('%y-%m-%d %H.%M.%S') + '.txt'

f = open(adcp_filename, 'wb')
gps_f = open(gps_filename, 'w')


###############################################################################
# GPS Setup Function
###############################################################################
def GPS_setup(gps_ser):
    gps_ser.baudrate = 19200
    gps_ser.parity = serial.PARITY_NONE
Ejemplo n.º 12
0
import random
import os
from digi.xbee.devices import XBeeDevice
from digi.xbee.devices import RemoteXBeeDevice
from digi.xbee.models.address import XBee64BitAddress
from digi.xbee.models.status import TransmitStatus
import tkinter as tk
from tkinter import *
from tkinter import font
import sys
import datetime
import time

Tx = XBeeDevice("COM5", 9600)
Rx1 = RemoteXBeeDevice(Tx,
                       XBee64BitAddress.from_hex_string("0013A200416411DF"))
Rx2 = RemoteXBeeDevice(Tx,
                       XBee64BitAddress.from_hex_string("0013A20041630A75"))
Rx3 = RemoteXBeeDevice(Tx,
                       XBee64BitAddress.from_hex_string("0013A200418B68F8"))
Tx.open()

window = tk.Tk()

window.title('LMU AirLions')
#You can set the geometry attribute to change the root windows size
window.geometry("1000x1000")  #You want the size of the app to be 500x500

back = tk.Frame(window, bg='black')
window.configure(background='black')
Ejemplo n.º 13
0
# Codigo desarrollado por Francisco Jose Lara.
# NODO-ROUTER

#Librerias
import serial, time, sys
from digi.xbee.devices import XBeeDevice, RemoteXBeeDevice
from digi.xbee.models.address import XBee64BitAddress, XBee16BitAddress
from digi.xbee.packets.common import TransmitPacket
from digi.xbee.packets.raw import TX64Packet
from digi.xbee.util import utils
import struct

#Inicio XBee Device
device = XBeeDevice("/dev/serial0", 9600)
device.open()
print("-- Dispositivo  abierto --")

while 1:
    #Leer
    mens = None
    print("\nEsperando peticion de datos...\n")
    while mens == None:
        # Recivo de coordinador
        mens = device.read_data()
        #print(".")
        time.sleep(0.5)
    # Decodifico mensaje
    com = mens.data.decode("utf8")
    print("Peticion decodificada: ", com, "\n")
    if com == 'Fin':
        break
Ejemplo n.º 14
0
def main():
    print(" +-----------------------------------------+")
    print(" | XBee Python Library Receive Data Sample |")
    print(" +-----------------------------------------+\n")

    device = XBeeDevice(PORT, BAUD_RATE)
    #remote_device=RemoteXBeeDevice(device,XBee64BitAddress.from_hex_string(REMOTE_NODE_ID))

    try:
        device.open()

        def data_receive_callback(xbee_message):
            data = xbee_message.data
            command = [
                int.from_bytes(data[:2], "big"),
                int.from_bytes(data[2:3], "big"),
                int.from_bytes(data[3:4], "big"),
                int.from_bytes(data[5:6], "big"),
                int.from_bytes(data[6:7], "big")
            ]
            print("Data[0]:", command[0])
            print("Data[1]:", command[1])
            print("Data[2]:", command[2])
            print("Data[3]:", command[3])
            print("Data[4]:", command[4])
            temperature, pressure, humidity = readBME280All()

            if command[1] == 3:
                if command[2] == 1:
                    if command[0] == 1:
                        #teste="teste2"
                        remote_device = RemoteXBeeDevice(
                            device,
                            XBee64BitAddress.from_hex_string(
                                "0000000000000000"))
                        print("Temp      = {0:0.3f} Deg C", temperature,
                              float.hex(temperature),
                              float.fromhex(float.hex(temperature)))
                        # Send data using the remote object.
                        print("", float.fromhex(float.hex(temperature)))
                        print("" + float.hex(temperature))
                        device.send_data(remote_device,
                                         '' + float.hex(temperature))

                    if command[0] == 2:
                        print("Press      = {0:0.3f}", pressure,
                              float.hex(pressure),
                              float.fromhex(float.hex(pressure)))
                        remote_device = RemoteXBeeDevice(
                            device,
                            XBee64BitAddress.from_hex_string(
                                "0000000000000000"))
                        # Send data using the remote object.
                        print("", float.fromhex(float.hex(pressure)))
                        print("" + float.hex(pressure))
                        device.send_data(remote_device,
                                         '' + float.hex(pressure))
                    if command[0] == 3:
                        print("Humity      = {0:0.3f} %", humidity,
                              float.hex(humidity),
                              float.fromhex(float.hex(humidity)))
                        remote_device = RemoteXBeeDevice(
                            device,
                            XBee64BitAddress.from_hex_string(
                                "0000000000000000"))
                        # Send data using the remote object.
                        print("", float.fromhex(float.hex(humidity)))
                        print("" + float.hex(humidity))
                        device.send_data(remote_device,
                                         '' + float.hex(humidity))
                    #if command[0]==4:
            if command[1] == 1:
                if command[2] == 2:
                    if command[4] == 1:
                        print("Meta-TEDS")

        device.add_data_received_callback(data_receive_callback)
        print("Waiting for data...\n")
        input()

    finally:
        if device is not None and device.is_open():
            device.close()
Ejemplo n.º 15
0
class XBee:
    _buffer = ExpiringDict(default_ttl=120)

    def __init__(self, port: str, baud_rate: int = 9600):
        self._device = XBeeDevice(port, baud_rate)

    @classmethod
    def _normalize_data(self, data: typing.Union[bytearray, bytes]):
        if isinstance(data, bytes):
            data = bytearray(data)
        return data

    def open(self):
        self._device.open()
        self._device.add_data_received_callback(self._on_data_received)

    def close(self):
        self._device.close()

    def send_broadcast(self, data: typing.Union[bytearray, bytes]):
        data = self._normalize_data(data)
        self._device.send_data_broadcast(data)

    def send(self, remote_address: bytearray, data: typing.Union[bytearray, bytes]):
        data = XBee._normalize_data(data)
        remote_device = RemoteXBeeDevice(self._device, x64bit_addr=XBee64BitAddress(remote_address))

        id = random.randint(0, 4000000)
        init_frame = InitFrame(id=id, size=len(data))

        self._device.send_data(remote_device, init_frame.serialize())

        sent = 0
        while sent < len(data):
            s = data[sent:sent + 50]
            frame = Frame(id=id, data=s)

            self._device.send_data(remote_device, frame.serialize())
            sent += len(s)

    async def discover_first_remote_device(self, discovery_timeout=25) -> typing.Optional[bytearray]:
        network = self._device.get_network()
        network.set_discovery_timeout(discovery_timeout)
        network.start_discovery_process()
        await asyncio.sleep(1)
        while network.is_discovery_running() and not network.get_devices():
            await asyncio.sleep(1)
        network.stop_discovery_process()

        devices = network.get_devices()
        return get_address(devices[0]) if devices else None

    def on_message_received(self, remote_address: bytearray, data: bytearray):
        pass

    def _on_data_received(self, message):
        if message.is_broadcast:
            # there are no support for fragmentation of broadcast messages yet :(
            return self.on_message_received(get_address(message.remote_device), message.data)

        init_frame = InitFrame.deserialize(message.data)
        try:
            if init_frame.id in self._buffer:
                frame = Frame.deserialize(message.data)
                self._buffer[frame.id][1].extend(frame.data)

                full_size = self._buffer[frame.id][0]
                if len(self._buffer[frame.id][1]) >= full_size:
                    self.on_message_received(get_address(message.remote_device), self._buffer[frame.id][1][:full_size])
                    del self._buffer[frame.id]
            else:
                self._buffer[init_frame.id] = [init_frame.size, bytearray()]
        except Exception as e:
            logger.error(e)
            self._buffer.pop(init_frame.id, None)
Ejemplo n.º 16
0
class Antenna:
    def __init__(self, port="", remote_address="", verbose=False):
        self.verbose = verbose
        if port == "":
            port = self.find_port()
        self.port = port
        self.verbose_print(f"Port: {self.port}")

        self.last_time_sent = 0

        if self.port != "" and remote_address != "":
            self.device = XBeeDevice(self.port, 9600)
            self.active = True
            self.has_remote = True

            try:
                self.device.open()
            except:
                self.active = False
            try:
                add_64 = (XBee64BitAddress.from_hex_string(remote_address))
                self.remote_device = RemoteXBeeDevice(self.device, add_64)
            except Exception as e:
                self.has_remote = False
                print("Error on remote device: ", e)
        else:
            self.active = False
            self.device = None

    def find_port(self):
        ports = prtlst.comports()
        for port in ports:
            try:
                if "FTDI" in port.manufacturer:
                    return port.device
            except Exception:
                pass
        return ""

    def send(self,
             data,
             time=None,
             data_key=None,
             skip_time=0,
             parent="",
             as_json=False):
        """
        Recursively send asynchronous data.
        """
        if as_json:
            data = loads(data)
        # Update Time
        if time == None:
            time = unixtimestamp()
            #self.last_time_sent = time
            # Skip if time buffer too low
            if skip_time != 0:
                if time - self.last_time_sent < skip_time:
                    return None
            self.last_time_sent = time

        if self.active:
            try:
                if type(data) == dict:
                    for key in data:
                        parent = "" if data_key == None else data_key
                        self.send(data[key],
                                  time=time,
                                  data_key=key,
                                  parent=parent)
                else:
                    send_data = {
                        "uts": time,
                        f"{parent}_{str(data_key)}": data
                    }
                    to_send = dumps(send_data).encode()
                    self.device.send_data_async(self.remote_device, to_send)
            except Exception as e:
                self.verbose_print(f"COULDN'T SEND {data}, ERROR {e}")
        return None

    def verbose_print(self, message):
        if self.verbose:
            print(message)

    def read_time(self, time=None):
        if not self.active:
            return "{}"
        try:
            d = self.device.read_data(time)
            if d is None:
                return "{}"
            return d.data.decode()
        except Exception as e:
            print(f"[low_level/low_comm.py]: {e}")
            return "{}"
Ejemplo n.º 17
0
 def __init__(self, port: str, baud_rate: int = 9600):
     self._device = XBeeDevice(port, baud_rate)
from digi.xbee.devices import XBeeDevice, XBee64BitAddress, RemoteXBeeDevice
import time

device = XBeeDevice("COM7", 9600)
device.open()
device.set_sync_ops_timeout(10)
remote_device = RemoteXBeeDevice(device, XBee64BitAddress.from_hex_string("0013A20041C7BFFC"))
while(1):
    device.send_data(remote_device, "Data")
    print("sent")
    time.sleep(3)
device.close()
Ejemplo n.º 19
0
def main():
    print(" +----------------------------------+")
    print(" | Image send test - Xbee to Python |")
    print(" +----------------------------------+\n")
    Overallstart = time.time()
    dir = "/Users/IEEE/Desktop/Hog-pics/"
    pics = os.listdir("/Users/IEEE/Desktop/Hog-pics")
    device = XBeeDevice(PORT, BAUD_RATE)
    for img in pics:  #put everything in this loop so you until you send all the pic in the dir
        with open(dir + img, 'rb') as image:
            t0 = time.time()
            f = image.read()
            teststring = base64.b64encode(f)
            test1 = teststring.decode("utf-8")

            first_message = MessageBuffer()
            first_message.msg_type = 'BN'
            first_message.file_size = len(test1)
            first_message.offset = 0
            first_message.buffer = img  # filename

            s = first_message.firstmsg()
            print(s)

            try:
                device.open()
                device.send_data_broadcast(s)

                message = MessageBuffer()
                place = 0
                headersize = 0
                MAXbuffersize = 256
                buffersize = 0
                next_sting = 0
                packetcount = 0
                while place < first_message.file_size:

                    if first_message.file_size - place > 255:
                        message.msg_type = 'DT'
                    else:
                        message.msg_type = 'ED'

                    message.offset = place
                    headersize = message.getheadersize()
                    buffersize = MAXbuffersize - headersize
                    next_sting = buffersize + next_sting
                    message.buffer = test1[message.offset:next_sting]
                    place = buffersize + place
                    q = message.prepmsg()
                    #print(q)
                    device.send_data_broadcast(q)
                    packetcount = packetcount + 1

                t1 = time.time()
                total = t1 - t0
                print("Success")
                print("Number of Packets: " + str(packetcount))
                print("Time for Image " + first_message.buffer + ": " +
                      str(total))
                print("Size for Image " + first_message.buffer + ": " +
                      str(first_message.file_size))

            finally:
                if device is not None and device.is_open():
                    device.close()

    Overallend = time.time()
    overall = Overallend - Overallstart
    print("Overall time = " + str(overall))
Ejemplo n.º 20
0
def main():
    coord = XBeeDevice('COM7', 9600) # Create XBeeDevice object for the coordinator at COM7 with Baud Rate 9600 
    try:
        coord.open() # Open communication with the XBee device
        coord.flush_queues()

        xbee_network = coord.get_network() # Get the network that coord is connected to
        router2 = xbee_network.discover_device('R2') # Find the remote device on the network with ID 'R2'

        if router2 is None: # If we could not find R2 then the program will continue to run
            print("Could not find the remote alert device (R2)")
        else :
            print("Remote alert device (R2) found")

        timestamp, date, time_ = getTime(True)
        with open(".\\logs\\{0}-{1}.log".format(date, time_), mode="a") as myFile: # Creates a new log file
            myFile.write("# Date\t\tTime\t\tTimestamp\tTemperature\tHumidity\n")
            while True:
                xbee_message = coord.read_data() # Read the data from R1 on the Sensor Arduino
                if xbee_message is not None:
                    timestamp, date, time_ = getTime() # Get the time
                    data_raw = xbee_message.data.decode().split(",") # Turn the sensor data into a list
                    data = [float(element) for element in data_raw] # Turn each element of data_raw into a float
                    dataToSend = ""

                    # Temperature
                    print("\nAt {0} {1} Temperature is {2}".format(date, time_, data[0]), end=": ")
                    if data[0] > 24.65:
                        print("Unsafe")
                        dataToSend += "T1"
                        stateT = "U"
                    else:
                        print("Safe")
                        dataToSend += "T0"
                        stateT = "S"

                    ## Pressure
                    #print("At {0} {1} Pressure is {2}".format(date, time_, data[1]), end=": ")
                    #if data[1] > 1000:
                    #    print("Unsafe")
                    #    dataToSend += "P1"
                    #    stateP = "U"
                    #else:
                    #    print("Safe")
                    #    dataToSend += "P0"
                    #    stateP = "S"
                    
                    # Humidity
                    print("At {0} {1} Humidity is {2}".format(date, time_, data[2]), end=": ")
                    if data[2] > 70:
                        print("Unsafe")
                        dataToSend += "H1"
                        stateH = "U"
                    else:
                        print("Safe")
                        stateH = "S"
                        dataToSend += "H0"
                    
                    if router2 is not None:
                        coord.send_data(router2, dataToSend)

                    text = "{0}\t{1}\t{2}\t{3}{4}\t\t{5}{6}\n".format(date, time_, timestamp, stateT, data[0], stateH, data[2])
                    myFile.write(text)
    finally:
        if coord is not None and coord.is_open(): # Closes the communications to the coordinator when the program closes
            coord.close()
Ejemplo n.º 21
0
class strangenet_xbee:
    def __init__(self):
        logging.debug("Initializing local XBee...")

        port = os.getenv("STRANGENET_XBEE_PORT", "/dev/ttyUSB0")
        baud = os.getenv("STRANGENET_XBEE_BAUD", 230400)
        logging.debug("Using port: " + port + " and baud: " + str(baud))
        self.device = XBeeDevice(port, baud)
        self.device.open(
        )  # automatically does read_device_info() for local device

        # the XBee waits NT * 0.1 sec on a ND, DN or FN (default 0x82
        # self.device.set_parameter('NT', xbu.hex_string_to_bytes('10'))

        print('Printing NP value')
        print(self.device.get_parameter("NP"))  # NP: max packet size in hex
        self.mtu = self.device.get_parameter("NP")

        ipv4 = os.getenv('STRANGENET_IP', '10.0.0.1')
        logging.debug('Writing IP address ' + ipv4 + ' to XBee device...')
        self.device.set_parameter("NI", bytearray(('STR_' + ipv4), 'utf-8'))

        self.device.write_changes()  # in case of accidental reset

        # create a XBeeNetwork object to store discovered devices
        self.xnet = self.device.get_network()

    def tx(self, dst_ip, payload):

        # we have an IP, encode to NI
        # dst is a bytearray representing the destination IPv4
        # there is probably a cleaner way to do this
        dst = dst_ip.hex()  # in hex this should be a fixed size
        dstNI = 'STR_' + (
            str(int(dst[:2], 16)) + '.' + str(int(dst[2:4], 16)) + '.' +
            str(int(dst[4:6], 16)) + '.' + str(int(dst[6:8], 16)))
        print('\nSending to NI:', dstNI)

        # special procedures for broadcast
        if dstNI[3:] is "10.0.0.0":  # FIXME do the things to support other subnets
            return self.broadcast_tx(payload)

        # see if we have the MAC cached, note that caching last duration of runtime
        # so we do not have an easy way for devices to change IP
        destdev = self.xnet.get_device_by_node_id(dstNI)

        if destdev is None:  # not in xnet
            # we will have to resolve, this will block for NT * 0.1 sec
            # unpredictable behavior will result from duplicate NI's, the following picks the first
            destdev = self.xnet.discover_device(dstNI)
            if destdev is None:
                return "NOROUTE"

        # proceed to send the data now that we have destdev
        # TODO do this asynchronously

        try:
            self.device.send_data(destdev,
                                  payload)  # no exec == success (ACK recd)
        except TimeoutException:
            logging.warning("Timeout on XBee link")
            return "TIMEOUT"
        except XBeeException:  # wrong op mode, corrupt response, serial error
            return "ERROR"

    def broadcast_tx(self, payload):
        pass

    def poll(self, timeout):
        data = self.device.read_data()
        if data is not None:
            # we have an XBeeMessage object
            return {'payload': bytes(data.data)}
        else:
            return None  # None = no data w/in timeout (set to zero for instant)
def main():
    class ReadAD:
        def __init__(self, start=0):
            self.lock = threading.Lock()
            self.value = start

        def read_AD(self, indice):
            logging.debug('Waiting for lock')
            self.lock.acquire()
            try:
                self.timeout = False
                logging.debug('Acquired lock')
                vcc = nodos_activos[indice].get_parameter("%V")
                vcc = int(utils.hex_to_string(vcc).replace(' ', ''), 16)
                # Leemos el valor crudo de las entradas analógicas
                raw_value_1 = nodos_activos[indice].get_adc_value(IOLINE_IN_0)
                raw_value_2 = nodos_activos[indice].get_adc_value(IOLINE_IN_1)
                raw_value_3 = nodos_activos[indice].get_adc_value(IOLINE_IN_2)
                raw_value_4 = nodos_activos[indice].get_adc_value(IOLINE_IN_3)

                # Calculamos el valor de temperatura en cada entrada en función de la tensión de alimentación y del
                tntc_1 = ntc10k_calculate_temp(raw_value_1, vcc)
                tntc_2 = ntc10k_calculate_temp(raw_value_2, vcc)
                tntc_3 = ntc10k_calculate_temp(raw_value_3, vcc)
                tntc_4 = ntc10k_calculate_temp(raw_value_4, vcc)

                # ************************************************************************
                # ESTA ES LA PARTE DE TELEGRAF
                send_data_to_telegraf.main(REMOTE_NODES_ID[indice], tntc_1,
                                           tntc_2, tntc_3, tntc_4, float(vcc))

            except TimeoutException:
                self.timeout = True
                logging.debug('ADC error')
                local_device.reset()

            finally:
                self.lock.release()

            return self.timeout

# función que realiza las tareas de lectura de las entradas en los nodos

    timeouts = []

    def worker(c, i):
        #La petición se hace con tiempo variable, si no responde, esto es si da timeout se hacen más rápidas para ver
        #si el nodo estaba en una secuencia de sueño, si sobre pasa el límite de timeouts cortos ya no se le pregunta más
        timeouts.append(0)
        try:
            while True and (timeouts[i] < MAX_INTENTOS_LEER_DATOS):
                logging.debug('Stamp: %s', str(datetime.now()))
                logging.debug("TIMEOUTS %s",
                              timeouts)  #estudiar bien esto y quitar
                if c.read_AD(i):
                    timeouts[i] += 1
                    logging.debug("Timeouts %s", timeouts)
                    pause = SHORT_WAIT
                else:
                    #timeouts[i] = 0 #reseteamos la cuenta de timeouts
                    pause = LONG_WAIT
                logging.debug('Sleeping %0.02f', pause)
                time.sleep(pause)
        except ValueError:
            logging.debug('Worker error')

# función que realiza el procedimiento de descubrimiento de los nodos listado en el archivo list_of_nodes.ini

    nodos_activos = []

    def descubre_nodos():
        index_devices = 0
        try:
            for index in range(0, len(REMOTE_NODES_ID)):
                nodo_descubierto = False
                intentos_descubir = 0
                while (nodo_descubierto != True
                       ) and intentos_descubir < MAX_INTENTOS_DESCUBRIMIENTO:
                    remote_device = (xbee_network.discover_device(
                        REMOTE_NODES_ID[index]))
                    if remote_device is None:
                        logging.debug('Could not find the remote device: %s',
                                      REMOTE_NODES_ID[index])
                        intentos_descubir += 1
                        logging.debug("Nodo: %s", (REMOTE_NODES_ID[index]))
                        logging.debug(
                            'Intentos descubrimiento restantes: %s',
                            (MAX_INTENTOS_DESCUBRIMIENTO - intentos_descubir))
                        time.sleep(1)
                    else:
                        nodos_activos.append(remote_device)
                        index_devices += 1
                        logging.debug('Descubierto: %s', remote_device)
                        nodo_descubierto = True
        except:
            logging.debug('Error proceso descubrimiento')


# Configuracíon de la salida del log

    logging.basicConfig(
        level=logging.DEBUG,
        format='(%(threadName)-10s) %(message)s',
    )

    # Conexión al nodo local
    local_device = XBeeDevice(port, baud_rate)
    xbee_network = local_device.get_network()
    local_device.open()
    local_device.set_sync_ops_timeout(40)
    descubre_nodos()

    try:
        lectura = ReadAD()
        # Creación de un hilo por cada nodo activo
        for i in range(len(nodos_activos)):
            logging.debug('creando hilo')
            t = threading.Thread(name=nodos_activos[i],
                                 target=worker,
                                 args=(
                                     lectura,
                                     i,
                                 ))
            t.start()
        if len(nodos_activos) == 0:
            logging.debug('No nodes found')
            sys.exti(-1)
        else:
            logging.debug('Waiting for worker threads')
            main_thread = threading.main_thread()
            for t in threading.enumerate():
                if t is not main_thread:
                    t.join()
            logging.debug('Counter: %d', lectura.value)

    except:
        logging.debug('exept')
        sys.exit(1)
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()
Ejemplo n.º 24
0
def shutdown_cleanly(xbee: XBeeDevice) -> Error:
    """
    Helper function to attempt to cleanly shut down the XBee.

    Note that only XBee 3 Cellular devices require a clean shutdown; this function
    behaves as a NOP for XBee 3 Zigbee/802.15.4/DigiMesh devices.

    You should invoke this function prior to issuing the ATFR command or removing power to the XBee.
    Otherwise, you risk corrupting/bricking the XBee's cell modem chip.
    For more info, see the "Clean shutdown" page in the XBee3 Cellular User Guide:
    https://www.digi.com/resources/documentation/Digidocs/90002258/#Reference/r_clean_shutdown.htm

    This function assumes that the XBee is currently in API Mode Without Escapes.

    The clean shutdown is performed by issuing the XBee 3 Cellular ATSD (Shutdown) command to the XBee module.
    Note that on XBee 3 Zigbee and 802.15.4 devices, the ATSD command does something completely different
    (SD = Scan Duration).

    Note that ATSD command does NOT put the XBee 3 Cellular device to sleep. Rather, it simply
    puts the XBee module (particularly its cell modem chip) into a state in which it is safe to power off.
    The XBee will continue to respond to API Frames messages even after it is in this shutdown state.

    Note that the XBee 3 Cellular ATSD command takes a long time to respond, usually somewhere between
    6 and 12 seconds, but it could be longer, so give it a nice long timeout, say 30 seconds, since
    that is what the user guide recommends for alternate airplane mode shutdown approach.

    We don't retry the shutdown command in a loop because a failure is highly unlikely.
    If the shutdown command fails, we report the error, but we don't do anything else--
    chances are you're still going to turn off the power no matter what, but at least
    we tried to shut down so gracefully.

    If the XBee 3 Cellular ATSD fails, we do attempt an alternate, fallback shutdown approach.

    Note that the shutdown command (ATSD) was not introduced until the August 2019 release of
    the XBee3 Cellular firmware, so older versions of firmware will need to rely upon this
    alternate approach.

    One approach mentioned on the [Clean shutdown page of the User Guide](
    https://www.digi.com/resources/documentation/Digidocs/90002258/#Reference/r_clean_shutdown.htm)
    is to de-assert the DTR_n/SLEEP_REQUEST pin and wait until the SLEEP_STATUS pin goes low.

    However, if your XBee carrier board hardware was not designed with this in mind, you won't
    be able to monitor this. Instead, we just wait for a specific reasonable amount of time, say 30 seconds.
    After all, this is a fallback shutdown approach, and this is better than nothing.
    However, there is another, bigger issue with the DTR_n/SLEEP_REQUEST approach:
    this pin might not be configured as a sleep request input! In other words, the XBee register "D8"
    might instead have it configured as a general-purposes digital I/O pin, in which case strobing
    this pin won't work. Since I don't want to make any assumptions about how the XBee is configured,
    I'm going to avoid the pin-based approach.

    So instead, we will use the third shutdown approach described in the User Guide:
    send the ATAM (Airplane Mode) command to put the device into airplane mode. Then we wait
    30 seconds as prescribed in the User Guide to give it plenty of time to shut down.

    Note that the ATAM (Airplane Mode) command gets applied immediately;
    no need to subsequently send ATAC (Apply Configuration) to apply the changes.
    """

    proto = xbee.get_protocol()
    if proto not in (XBeeProtocol.CELLULAR, XBeeProtocol.CELLULAR_NBIOT):
        log("%s: Device is not an XBee 3 Cellular; no need for clean shutdown. Bypassing clean shutdown."
            % func())
        return Success

    xbee_atsd_timeout_sec = 30
    xbee_time_to_wait_in_airplane_mode_sec = 30

    log("%s: Adjusting the xbee-python command timeout value..." % func())
    try:
        default_timeout_sec = xbee.get_sync_ops_timeout(
        )  # Store default value so that we can put it back.
        xbee.set_sync_ops_timeout(
            xbee_atsd_timeout_sec
        )  # ATSD takes longer than most commands so give it extra time.
    except Exception as ex:
        return Error(
            "%s: Failed to adjust the xbee-python command timeout value. Reason: "
            % (func(), ex))

    log("%s: Attempting to cleanly shut down the XBee. Sending shutdown command (ATSD)..."
        % func())
    try:
        xbee.execute_command("SD")
        log("%s: XBee shutdown command (ATSD) succeeded. Now safe to remove power from the module."
            % func())
        return Success
    except Exception as ex:
        log("%s: XBee shutdown command (ATSD) failed. Reason: %s. Will attempt fallback approach."
            % (func(), ex))
    finally:
        xbee.set_sync_ops_timeout(default_timeout_sec)

    log("%s: Attempting fallback approach to cleanly shut down. Sending ATAM command and waiting for %s seconds."
        % (func(), xbee_time_to_wait_in_airplane_mode_sec))
    try:
        xbee.set_parameter("AM", b"\x01")
    except Exception as ex:
        return Error("%s: XBee ATAM command failed. Reason: %s" % (func(), ex))

    time.sleep(xbee_time_to_wait_in_airplane_mode_sec)
    log("%s: Done waiting for XBee to enter airplane mode. You may now remove power from the module."
        % func())
    return Success
def main():

    print(" +---------------------------------+")
    print(" | Get and Set Params Local/Remote |")
    print(" +---------------------------------+\n")

    local_xbee = XBeeDevice(PORT, BAUD_RATE)

    try:
        local_xbee.open()
        remote_xbee = RemoteXBeeDevice(local_xbee,
                                       x64bit_addr=REMOTE_DEVICE_ADDRESS)

        local_xbee.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(local_xbee.get_node_id())
        print(local_xbee.get_hardware_version())
        print(hex_to_string(local_xbee.get_firmware_version()))
        print(local_xbee.get_protocol())
        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())

        ni = ''.join(
            random.choice(string.ascii_letters)
            for i in range(random.randint(1, 20)))
        local_xbee.set_parameter("NI", bytearray(ni, "utf8"))
        param = local_xbee.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")

    finally:
        if local_xbee is not None and local_xbee.is_open():
            local_xbee.close()
Ejemplo n.º 26
0
 def __init__(self, path_to_device, baud_rate=9600):
     self._device = XBeeDevice(path_to_device, baud_rate)
     self._device.open()
from tkinter import *
import tkinter.messagebox
from digi.xbee.devices import XBeeDevice
from digi.xbee.devices import RemoteXBeeDevice
from digi.xbee.models.address import XBee64BitAddress
from digi.xbee.reader import XBeeMessage
import time
import os
from datetime import *
from tkcalendar import Calendar
import sqlite3

os.system('sudo chmod 777 /dev/ttyUSB0')

coordenador = XBeeDevice('/dev/ttyUSB0', 9600)
router1 = RemoteXBeeDevice(
    coordenador, XBee64BitAddress.from_hex_string("0013A200409BAF15"))
router2 = RemoteXBeeDevice(
    coordenador, XBee64BitAddress.from_hex_string("0013A200409BAF12"))

print('Done')
try:
    coordenador.open()

except:
    print('\n\nERRO NA COMUNICAÇÃO!\n\n')
    exit()

DATABASE_EXISTS = False

if (os.path.isfile('agendamento.db') == False):
Ejemplo n.º 28
0
def main():
    def get_parameter(xbee: XBeeDevice, param: str) -> str:
        return utils.hex_to_string(xbee.get_parameter(param))

    local_xbee = XBeeDevice(PORT, BAUD_RATE)

    try:
        local_xbee.open()

        xbee_network = local_xbee.get_network()

        print("Cheking network...", end='', flush=True)

        xbee_network.start_discovery_process()

        while xbee_network.is_discovery_running():
            sleep(0.5)

        xbee_devices = xbee_network.get_devices()

        print("done")

        print(f"""
LOCAL XBEE
  - Node ID: {local_xbee.get_node_id()}
  - PAN ID: {get_parameter(local_xbee, "ID")}
  - Protocol: {local_xbee.get_protocol()}
  - 16-bit address: {local_xbee.get_16bit_addr()}
  - 64-bit address: {local_xbee.get_64bit_addr()}
  - API: {get_parameter(local_xbee, "AP")}
  - Encryption enabled: {get_parameter(local_xbee, "EE")}
  - Hardware version: {local_xbee.get_hardware_version()}
  - Firmware version: {utils.hex_to_string(local_xbee.get_firmware_version())}

NETWORK
  - Remote devices: {len(xbee_devices)}
""")

        for remote_device in xbee_devices:
            if not (remote_device is None):
                try:
                    remote_device.read_device_info()
                except:
                    continue

                print(f"""
REMOTE DEVICE:      
- Node ID: {remote_device.get_node_id()}
- PAN ID: {get_parameter(remote_device, "ID")}
- Protocol: {remote_device.get_protocol()}
- 16-bit address: {remote_device.get_16bit_addr()}
- 64-bit address: {remote_device.get_64bit_addr()}
- API: {get_parameter(remote_device, "AP")}
- Encryption enabled: {get_parameter(remote_device, "EE")}
- Hardware version: {remote_device.get_hardware_version()}
- Firmware version: {utils.hex_to_string(remote_device.get_firmware_version())}
""")

    finally:
        if local_xbee is not None and local_xbee.is_open():
            print("Closing device")
            local_xbee.close()
Ejemplo n.º 29
0
                     'comm_error': False
                 }}),
                 qos=1,
                 retain=True)
    MQTT.publish(topicAttr,
                 json.dumps({(turbineName + '_'): {
                                 'comm_error': False
                             }}),
                 qos=1,
                 retain=True)  #Send data to Wind Farm Observer dashboard
    lastMessageTime[turbineName] = time.time(
    )  #record the time this message was processed in seconds since epoch.


try:
    xbee = XBeeDevice(localXBeePort, 9600)
    xbee.open()
    xbee.add_data_received_callback(
        data_receive_callback
    )  # Subscribe to data message reception (for power pulse count data).
    xbee.add_io_sample_received_callback(
        io_sample_callback)  # Subscribe to IO samples reception.
    print("Waiting for data...\n", file=open(standardOutput, 'a'))
    while True:
        for name in name2addr.keys(
        ):  #we're going to cycle through our list of turbines to check a few things.
            try:  #first try to poll all of the turbines to get an update on their fault and on/off status
                remote = RemoteXBeeDevice(
                    xbee,
                    XBee64BitAddress.from_hex_string(name2addr.get(name)))
                io_sample_callback(remote.read_io_sample(), remote,
Ejemplo n.º 30
0
def main():
    coord = XBeeDevice('COM7', 9600) #create Xbeedevice Coord at COM7 & baud rate 9600 
    try:
        coord.open() #calling method to open communication with Xbee device
        coord.flush_queues()

        xbee_network = coord.get_network() #getting a newtwork and assigning it to the xbee
        router2 = xbee_network.discover_device('R3') # find the remote device on the network at R1

        if router2 is None:
            print("Could not find the remote device")
        else :
            print("Remote device found")

        while True:
            xbee_message = coord.read_data()
            if xbee_message is not None:
                timestamp = round(time.time())
                data_raw = xbee_message.data.decode().split(",")
                data = [float(element) for element in data_raw]
                # Temperature
                print("At {0} Temperature is {1}".format(timestamp, data[0]), end=": ")
                if data[0] > 23.7:
                    print("Unsafe")
                    if router2 is not None:
                        coord.send_data(router2, "T1")
                else:
                    print("Safe")
                    if router2 is not None:
                        coord.send_data(router2, "T0")
    finally:
        if coord is not None and coord.is_open():
            coord.close()
Ejemplo n.º 31
0
import time  #Time package gives time syncing functionality
from digi.xbee.devices import XBeeDevice  #XBee package gives XBee management functionality
import pygame  #Pygame package gives music playing functionality
from pygame import mixer

port = "COM7"  #The port the XBee is plugged in to.
BR = 9600  #Baud rate, configured in XCTU. Should stay as 9600.
my_xbee = XBeeDevice(
    port,
    BR)  #Declare/name the XBee that is plugged into the computer as "my_xbee"

song = "Freedom.mp3"  #This is the file name of the song you're using. Make sure this song file lives in the same folder as the code.
mixer.init()
mixer.music.load(song)  #Load the song

#Initialize light timing things, add as many cues as needed.
cueA = False
cueB = False
cueC = False
cueD = False
cueE = False
cueF = False
cueG = False
cueH = False
cueZ = False

mixer.music.play()  #Start playing the song

while pygame.mixer.music.get_busy():  #While the music is playing,
    ts = pygame.mixer.music.get_pos() / 1000.0  #Get the timestamp in the music
    if (