def check_mac(pymesh_config):
        lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868)
        MAC = int(str(ubinascii.hexlify(lora.mac()))[2:-1], 16)

        if pymesh_config.get('MAC') is None:
            # if MAC config unspecified, set it to LoRa MAC
            print("Set MAC in config file as ", MAC)
            pymesh_config['MAC'] = MAC
            PymeshConfig.write_config(pymesh_config, False)
        else:
            mac_from_config = pymesh_config.get('MAC')
            if mac_from_config != MAC:
                print("MAC different", mac_from_config, MAC)
                pymesh_config['MAC'] = MAC
                # if MAC in config different than LoRa MAC, set LoRa MAC as in config file
                fo = open("/flash/sys/lpwan.mac", "wb")
                mac_write = bytes([(MAC >> 56) & 0xFF, (MAC >> 48) & 0xFF,
                                   (MAC >> 40) & 0xFF, (MAC >> 32) & 0xFF,
                                   (MAC >> 24) & 0xFF, (MAC >> 16) & 0xFF,
                                   (MAC >> 8) & 0xFF, MAC & 0xFF])
                fo.write(mac_write)
                fo.close()
                print("reset")
                PymeshConfig.write_config(pymesh_config, True)

        print("MAC ok", MAC)
def join_otaa():
    """Joins the LoRaWAN network using Over The Air Activation (OTAA)"""
    lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.AS923)
    log('Initializing LoRaWAN (OTAA), DEV EUI: {} ...'.format(
        hexlify(lora.mac()).decode('ascii').upper()))

    if not LORA_OTAA_KEY:
        log('ERROR: LoRaWAN APP KEY not set!')
        log('Send your DEV EUI to [email protected] to obtain one.')
        return None

    pycom.rgbled(RGB_LORA)

    authentication = (unhexlify(LORA_OTAA_EUI), unhexlify(LORA_OTAA_KEY))

    lora.join(activation=LoRa.OTAA, auth=authentication, timeout=0)

    while not lora.has_joined():
        log('Joining...')
        pycom.rgbled(RGB_OFF)
        time.sleep(LED_TIMEOUT)
        pycom.rgbled(RGB_LORA)
        time.sleep(2.5)
        # if no connection in a few seconds, then reboot
        if utime.time() > 15:
            print("Possible timeout")
            machine.reset()

    pycom.rgbled(RGB_OFF)
    return lora
Example #3
0
def init_lora():
    """Initialize LoRaWAN connection"""

    lora = LoRa(mode=LoRa.LORAWAN)
    log('Initializing LoRaWAN, DEV EUI: {} ...'.format(
        hexlify(lora.mac()).decode('ascii').upper()))

    if not app_key:
        log('ERROR: LoRaWAN APP KEY not set!')
        log('Send your DEV EUI to [email protected] to obtain one.')
        return (None, None)

    pycom.rgbled(RGB_LORA_JOIN)

    lora.join(activation=LoRa.OTAA,
              auth=(dev_eui, app_eui, app_key),
              timeout=0)

    while not lora.has_joined():
        log('Joining...')
        pycom.rgbled(RGB_OFF)
        time.sleep(LED_TIMEOUT)
        pycom.rgbled(RGB_LORA_JOIN)
        time.sleep(2.5)

    pycom.rgbled(RGB_OFF)

    # Setup socket
    sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
    sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)  # Set data rate
    sock.setblocking(False)

    log('Done!')
    return (lora, sock)
Example #4
0
    def reset_configuration(self, logger):
        """
        Resets configuration to the default one and fetches device_id and device_eui
        :param logger: status logger
        :type logger: LoggerFactory object
        """
        try:
            self.configuration.clear()  # clear configuration
            self.set_config(
                self.default_configuration)  # set configuration to default

            self.set_config({
                "device_id":
                hexlify(unique_id()).upper().decode("utf-8")
            })  # set new device_id

            lora = LoRa(mode=LoRa.LORAWAN)
            self.set_config({
                "device_eui":
                hexlify(lora.mac()).upper().decode('utf-8')
            })  # set new device_EUI
            del lora

            logger.info('Configurations were reset')
            logger.warning('Please configure your device!')
        except Exception as e:
            logger.exception('Failed to reset configurations')
            raise ConfigurationException(str(e))
Example #5
0
class EasyLoraConnect(object):
    def __init__(self, resetOnFailure=True):
        self.lora = LoRa(mode=LoRa.LORAWAN,
                         region=LoRa.AS923,
                         tx_retries=config.N_TX,
                         device_class=LoRa.CLASS_A)
        self.resetOnFailure = resetOnFailure
        self._join_lora()

    def _join_lora(self, force_join=True):

        # create an OTA authentication params
        app_eui = binascii.unhexlify(config.APP_EUI.replace(' ', ''))
        app_key = binascii.unhexlify(config.APP_KEY.replace(' ', ''))

        # Switch the red led on
        pycom.rgbled(0xFF0000)

        # join a network using OTAA if not previously done
        self.lora.join(activation=LoRa.OTAA,
                       auth=(app_eui, app_key),
                       timeout=0)

        print(binascii.hexlify(self.lora.mac()).upper().decode('utf-8'))
        print("Joining Lora")

        # wait until the module has joined the network
        nb_try = 0
        while not self.lora.has_joined():
            time.sleep(2.5)
            print("Not joined yet in try " + str(nb_try))
            if self.resetOnFailure and nb_try > config.MAX_TRY:
                print("Cannot join so rebooting")
                machine.reset()
            nb_try = nb_try + 1
        print("LoRa Joined")
        # Switch the red led off
        pycom.rgbled(0x006400)

    def send(self, payload):
        '''Sending data over LoraWan '''
        pycom.rgbled(0xFF8C00)
        # create a LoRa socket
        s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

        # set the LoRaWAN data rate
        s.setsockopt(socket.SOL_LORA, socket.SO_DR, config.DATA_RATE)

        # make the socket blocking
        s.setblocking(True)

        s.send(payload)

        pycom.rgbled(0x006400)
        # closing the socket and saving the LoRa state
        s.close()

        self.lora.nvram_save()
Example #6
0
def go_LoRa():

    # Initialize LoRa in LORAWAN mode.
    lora = LoRa(mode=LoRa.LORAWAN)

    # Device EUI: 70 B3 D5 49 95 7A 21 5F - LoAirRohr01
    print(binascii.hexlify(lora.mac()).upper().decode('utf-8'))

    # Join LoRa network and TTN app "environment"
    #   using "Over the Air Activation (OTAA)"
    app_eui = binascii.unhexlify('xx xx xx xx xx xx xx xx'.replace(' ', ''))
    app_key = binascii.unhexlify('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
    lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)

    # Wait until the module has joined the network
    pycom.rgbled(red)
    while not lora.has_joined():
        print('Could not join LoRa network...')
        pycom.rgbled(off)
        time.sleep(0.1)
        pycom.rgbled(red)
        time.sleep(2)

    print('Joined LoRa network...')
    if useLED:
        pycom.rgbled(orange)
    else:
        pycom.rgbled(off)

    # Create a LoRa socket
    s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
    # Set the LoRaWAN data rate
    s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)
    #s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, True)
    s.setblocking(True)

    while True:
        t, h, p = readBME280()
        pm10, pm25 = readSDS011()
        bytesSent = s.send(t + ";" + h + ";" + p + ";" + pm10 + ";" + pm25)
        print('Sent %s bytes' % bytesSent)
        #print(lora.stats()) # only for received packets!
        if useLED:
            pycom.rgbled(green)
            time.sleep(0.1)
            pycom.rgbled(blue)
            time.sleep(4.9)
Example #7
0
    def reset_configuration(self, logger):

        try:
            self.configuration.clear()  # clear configuration
            self.set_config(self.default_configuration)  # set configuration to default

            self.set_config({"device_id": hexlify(unique_id()).upper().decode("utf-8")})  # set new device_id

            lora = LoRa(mode=LoRa.LORAWAN)
            self.set_config({"device_eui": hexlify(lora.mac()).upper().decode('utf-8')})  # set new device_EUI
            del lora

            logger.info('Configurations were reset')
            logger.warning('Please configure your device!')
        except Exception as e:
            logger.exception('Failed to reset configurations')
            raise ConfigurationException(str(e))
Example #8
0
def LORAConnection_OOTA(LoraConnectionTimeout):
    LoraConnected = False
    lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)
    print("LoRa MAC Address:  ",
          binascii.hexlify(lora.mac()).upper().decode('utf-8'))
    print("LoRa EUI: ", binascii.hexlify(machine.unique_id()))
    # create an OTAA authentication parameters
    app_eui = binascii.unhexlify('8493983621D5A1BC')
    app_key = binascii.unhexlify('9F68AE5FD1CE35D1F83CD48446CF7BBF')
    # L2
    # app_key = binascii.unhexlify('3F4A90ABF82EBD4067CCA30FD1D7ACDE')
    # L10
    # app_key = binascii.unhexlify('F8165748326F03346935F84BDE710AE4')
    # L12
    # app_key = binascii.unhexlify('38F812962FDF2BD64A78223F398381F3')
    # L13
    # app_key = binascii.unhexlify('8C0DF8D758F1B9340C9545B05DE3820B')
    # L14
    # app_key = binascii.unhexlify('82FBAED74A43BA32225751F9BC2BB693')

    #lora.callback(trigger = LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT | LoRa.TX_FAILED_EVENT, handler = OPCLoraEvent)
    #lora.callback(trigger = LoRa.TX_PACKET_EVENT, handler = OPCLoraTx)
    #lora.callback(trigger = LoRa.TX_FAILED_EVENT, handler = OPCLoraTxFail)

    # join a network using OTAA (Over the Air Activation)
    #lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
    try:
        lora.join(activation=LoRa.OTAA,
                  auth=(app_eui, app_key),
                  timeout=LoraConnectionTimeout)
        time.sleep_ms(8000)
        if (lora.has_joined()):
            LoraConnected = True
    except TimeoutError:
        print("timeout expired")
        LoraConnected = False
    # wait until the module has joined the network
    #while not lora.has_joined():
    #    time.sleep_ms(2500)
    #    print('Not yet joined...')
    #pass
    #print('Joined!')
    print('Lora connected = ', LoraConnected)
    return LoraConnected, lora
Example #9
0
def join_abp():
    """Joins the LoRaWAN network using Activation By Personalization (ABP)"""
    lora = LoRa(mode=LoRa.LORAWAN)
    log('Initializing LoRaWAN (ABP), DEV EUI: {} ...'.format(
        hexlify(lora.mac()).decode('ascii').upper()))

    authentication = (unpack(">l", unhexlify(LORA_ABP_DEVADDR))[0],
                      unhexlify(LORA_ABP_NETKEY),
                      unhexlify(LORA_ABP_APPKEY))

    lora.join(activation=LoRa.ABP, auth=authentication, timeout=0)

    for _ in range(1, 4):
        pycom.rgbled(RGB_LORA)
        time.sleep(LED_TIMEOUT)
        pycom.rgbled(RGB_OFF)
        time.sleep(LED_TIMEOUT)

    return lora
Example #10
0
    def __init__(self):
        lora = LoRa(mode=LoRa.LORAWAN, frequency=868000000)
        #lora.init(mode=LoRa.LORAWAN, frequency=868000000,sf=12)
        self.loraSocket = None

        print("MacAddress: ", [hex(x) for x in lora.mac()])

        app_eui = binascii.unhexlify('00 00 00 00 00 00 00 00'.replace(
            ' ', ''))
        app_key = binascii.unhexlify(
            '00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00'.replace(' ', ''))

        if not lora.has_joined():
            while not lora.has_joined():
                lora.join(activation=LoRa.OTAA,
                          auth=(app_eui, app_key),
                          timeout=0,
                          dr=1)
                time.sleep(6)
                print('Not yet joined...')
        # create a LoRa socket
        self.loraSocket = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
        # set the LoRaWAN data rate
        self.loraSocket.setsockopt(socket.SOL_LORA, socket.SO_DR, 3)
Example #11
0
from machine import UART
from network import LoRa
import binascii
import os
import pycom

pycom.heartbeat(False)

# Setting up the UART to dump the output to the console
uart = UART(0, 115200)
os.dupterm(uart)

# Getting the LoRa MAC
lora = LoRa(mode=LoRa.LORAWAN, public=1, adr=0, tx_retries=0)
print("LORA MAC")
print(binascii.hexlify(lora.mac()))
class Loramesh:
    """ Class for using Lora Mesh - openThread """

    STATE_DISABLED = const(0)
    STATE_DETACHED = const(1)
    STATE_CHILD = const(2)
    STATE_ROUTER = const(3)
    STATE_LEADER = const(4)
    STATE_LEADER_SINGLE = const(5)

    # rgb LED color for each state: disabled, detached, child, router, leader and single leader
    #RGBLED = [0x0A0000, 0x0A0000, 0x0A0A0A, 0x000A00, 0x00000A, 0x0A000A]
    RGBLED = [0x0A0000, 0x0A0000, 0x0A0A0A, 0x000A00, 0x0A000A, 0x000A0A]

    # TTN conf mode
    #RGBLED = [0x200505, 0x200505, 0x202020, 0x052005, 0x200020, 0x001818]

    # for outside/bright sun
    #RGBLED = [0xFF0000, 0xFF0000, 0x808080, 0x00FF00, 0x0000FF, 0xFF00FF]

    # mesh node state string
    STATE_STRING_LIST = ['Disabled', 'Detached', 'Child', 'Router', 'Leader']

    # address to be used for multicasting
    MULTICAST_MESH_ALL = 'ff03::1'
    MULTICAST_MESH_FTD = 'ff03::2'

    MULTICAST_LINK_ALL = 'ff02::1'
    MULTICAST_LINK_FTD = 'ff02::2'

    # Leader has an unicast IPv6: fdde:ad00:beef:0:0:ff:fe00:fc00
    LEADER_DEFAULT_RLOC = 'fc00'

    def __init__(self, config):
        """ Constructor """
        self.config = config
        config_lora = config.get('LoRa')
        self.lora = LoRa(mode=LoRa.LORA,
                         region=config_lora.get("region"),
                         frequency=config_lora.get("freq"),
                         bandwidth=config_lora.get("bandwidth"),
                         sf=config_lora.get("sf"))
        self.mesh = self.lora.Mesh()  #start Mesh

        # get Lora MAC address
        #self.MAC = str(ubinascii.hexlify(lora.mac()))[2:-1]
        self.MAC = int(str(ubinascii.hexlify(self.lora.mac()))[2:-1], 16)

        #last 2 letters from MAC, as integer
        self.mac_short = self.MAC & 0xFFFF  #int(self.MAC[-4:], 16)
        print_debug(
            5, "LoRa MAC: %s, short: %s" % (hex(self.MAC), self.mac_short))

        self.rloc16 = 0
        self.rloc = ''
        self.net_addr = ''
        self.ip_eid = ''
        self.ip_link = ''
        self.state = STATE_DISABLED

        # a dictionary with all direct neighbors
        # key is MAC for each neighbor
        # value is pair (age, mac, rloc16, role, rssi)
        #self.neigh_dict = {}
        self.router_data = RouterData()
        self.router_data.mac = self.MAC

        # a dictionary with all routers direct neighbors
        # key is MAC for each router
        # value is pair (age, rloc, neigh_num, (age, mac, rloc16, role, rssi))
        #self.leader_dict = {}
        self.leader_data = LeaderData()
        self.leader_data.mac = self.MAC

        # set of all MACS from whole current Mesh Network
        self.macs = set()
        self.macs_ts = -65535  # very old

        # list of all pairs (direct radio connections) inside Mesh
        self.connections = list()
        self.connections_ts = -65535  # very old

        # set a new unicast address
        self.unique_ip_prefix = "fdde:ad00:beef:0::"
        command = "ipaddr add " + self.ip_mac_unique(self.mac_short)
        self.mesh.cli(command)

    def ip_mac_unique(self, mac):
        ip = self.unique_ip_prefix + hex(mac & 0xFFFF)[2:]
        return ip

    def update_internals(self):
        self._state_update()
        self._rloc16_update()
        self._update_ips()
        self._rloc_ip_net_addr()

    def _rloc16_update(self):
        self.rloc16 = self.mesh.rloc()
        return self.rloc16

    def _update_ips(self):
        """ Updates all the unicast IPv6 of the Thread interface """
        ips = self.mesh.ipaddr()
        for line in ips:
            if line.startswith('fd'):
                # Mesh-Local unicast IPv6
                try:
                    addr = int(line.split(':')[-1], 16)
                except Exception:
                    continue
                if addr == self.rloc16:
                    # found RLOC
                    # RLOC IPv6 has x:x:x:x:0:ff:fe00:RLOC16
                    self.rloc = line
                elif ':0:ff:fe00:' not in line:
                    # found Mesh-Local EID
                    self.ip_eid = line
            elif line.startswith('fe80'):
                # Link-Local
                self.ip_link = line

    def is_connected(self):
        """ Returns true if it is connected if its Child, Router or Leader """
        connected = False
        if self.state in (STATE_CHILD, STATE_ROUTER, STATE_LEADER,
                          STATE_LEADER_SINGLE):
            connected = True
        return connected

    def _state_update(self):
        """ Returns the Thread role """
        self.state = self.mesh.state()
        if self.state < 0:
            self.state = self.STATE_DISABLED
        return self.state

    def _rloc_ip_net_addr(self):
        """ returns the family part of RLOC IPv6, without last word (2B) """
        self.net_addr = ':'.join(self.rloc.split(':')[:-1]) + ':'
        return self.net_addr

    def state_string(self):
        if self.state >= len(self.STATE_STRING_LIST):
            return 'none'
        return self.STATE_STRING_LIST[self.state]

    def led_state(self):
        """ Sets the LED according to the Thread role """
        if self.state == STATE_LEADER and self.mesh.single():
            pycom.rgbled(0x000A0A)
            time.sleep(1)
            pycom.rgbled(0)
        elif self.state == STATE_DETACHED:
            pycom.rgbled(0x0A0000)
            time.sleep(1)
            pycom.rgbled(0)
        else:
            do_nothing = "yes"
            # pycom.rgbled(self.RGBLED[self.state])

    def ip(self):
        """ Returns the IPv6 RLOC """
        return self.rloc

    # def parent_ip(self):
    #     # DEPRECATED, unused
    #     """ Returns the IP of the parent, if it's child node """
    #     ip = None
    #     state = self.state
    #     if state == STATE_CHILD or state == STATE_ROUTER:
    #         try:
    #             ip_words = self.rloc.split(':')
    #             parent_rloc = int(self.lora.cli('parent').split('\r\n')[1].split(' ')[1], 16)
    #             ip_words[-1] = hex(parent_rloc)[2:]
    #             ip = ':'.join(ip_words)
    #         except Exception:
    #             pass
    #     return ip

    # def neighbors_ip(self):
    #     # DEPRECATED, unused
    #     """ Returns a list with IP of the neighbors (children, parent, other routers) """
    #     state = self.state
    #     neigh = []
    #     if state == STATE_ROUTER or state == STATE_LEADER:
    #         ip_words = self.rloc.split(':')
    #         # obtain RLOC16 neighbors
    #         neighbors = self.lora.cli('neighbor list').split(' ')
    #         for rloc in neighbors:
    #             if len(rloc) == 0:
    #                 continue
    #             try:
    #                 ip_words[-1] = str(rloc[2:])
    #                 nei_ip = ':'.join(ip_words)
    #                 neigh.append(nei_ip)
    #             except Exception:
    #                     pass
    #     elif state == STATE_CHILD:
    #         neigh.append(self.parent_ip())
    #     return neigh

    # def cli(self, command):
    #     """ Simple wrapper for OpenThread CLI """
    #     return self.mesh.cli(command)

    def ipaddr(self):
        """ returns all unicast IPv6 addr """
        return self.mesh.ipaddr()

    # def ping(self, ip):
    #     """ Returns ping return time, to an IP """
    #     res = self.cli('ping ' + str(ip))
    #     """
    #     '8 bytes from fdde:ad00:beef:0:0:ff:fe00:e000: icmp_seq=2 hlim=64 time=236ms\r\n'
    #     'Error 6: Parse\r\n'
    #     no answer
    #     """
    #     ret_time = -1
    #     try:
    #         ret_time = int(res.split('time=')[1].split('ms')[0])
    #     except Exception:
    #         pass
    #     return ret_time

    def blink(self, num=3, period=.5, color=None):
        """ LED blink """
        if color is None:
            color = self.RGBLED[self.state]
        for _ in range(num):
            pycom.rgbled(0)
            time.sleep(period)
            pycom.rgbled(color)
            time.sleep(period)
        self.led_state()

    def slow_blink():
        # supposed to be for continually blink status in a thread till state change
        color = self.RGBLED[self.state]
        for _ in range(num):
            pycom.rgbled(0)
            time.sleep(1)
            pycom.rgbled(color)
            time.sleep(1)
            pycom.rgbled(0)

    def neighbors_update(self):
        """ update neigh_dict from cli:'neighbor table' """
        """ >>> print(lora.cli("neighbor table"))
        | Role | RLOC16 | Age | Avg RSSI | Last RSSI |R|S|D|N| Extended MAC     |
        +------+--------+-----+----------+-----------+-+-+-+-+------------------+
        |   C  | 0x2801 | 219 |        0 |         0 |1|1|1|1| 0000000000000005 |
        |   R  | 0x7400 |   9 |        0 |         0 |1|0|1|1| 0000000000000002 |

        """
        x = self.mesh.neighbors()
        print_debug(3, "Neighbors Table: %s" % x)

        if x is None:
            # bad read, just keep previous neigbors
            return

        # clear all pre-existing neigbors
        self.router_data = RouterData()
        self.router_data.mac = self.MAC
        self.router_data.rloc16 = self.rloc16
        self.router_data.role = self.state
        self.router_data.ts = time.time()
        self.router_data.coord = Gps.get_location()

        for nei_rec in x:
            # nei_rec = (role=3, rloc16=10240, rssi=0, age=28, mac=5)
            age = nei_rec.age
            if age > 300:
                continue  # shouln't add neighbors too old
            role = nei_rec.role
            rloc16 = nei_rec.rloc16
            # maybe we shouldn't add Leader (because this info is already available at Leader)
            # if rloc16 == self.leader_rloc():
            #   continue
            rssi = nei_rec.rssi
            mac = nei_rec.mac
            neighbor = NeighborData((
                mac,
                age,
                rloc16,
                role,
                rssi,
            ))
            self.router_data.add_neighbor(neighbor)
            #print("new Neighbor: %s"%(neighbor.to_string()))
            #except:
            #    pass
        # add own info in dict
        #self.neigh_dict[self.MAC] = (0, self.rloc16, self.state, 0)
        print_debug(3, "Neighbors: %s" % (self.router_data.to_string()))
        return

    def leader_add_own_neigh(self):
        """ leader adds its own neighbors in leader_dict """
        self.leader_data.add_router(self.router_data)
        return

    def neighbors_pack(self):
        """ packs in a struct all neighbors as (MAC, RLOC16, Role, rssi, age) """
        data = self.router_data.pack()

        return data

    def routers_neigh_update(self, data_pack):
        """ unpacks the PACK_ROUTER_NEIGHBORS, adding them in leader_dict """
        # key is MAC for each router
        # value is pair (age, rloc, neigh_num, (age, mac, rloc16, role, rssi))
        router = RouterData(data_pack)
        self.leader_data.add_router(router)
        return

    def leader_dict_cleanup(self):
        """ cleanup the leader_dict for old entries """
        #print("Leader Data before cleanup: %s"%self.leader_data.to_string())
        self.leader_data.cleanup()
        print("Leader Data : %s" % self.leader_data.to_string())

    def routers_rloc_list(self, age_min, resolve_mac=None):
        """ return list of all routers IPv6 RLOC16
            if mac parameter is present, then returns just the RLOC16 of that mac, if found
        """
        mac_ip = None
        data = self.mesh.routers()
        print("Routers Table: ", data)
        '''>>> print(lora.cli('router table'))
        | ID | RLOC16 | Next Hop | Path Cost | LQ In | LQ Out | Age | Extended MAC     |
        +----+--------+----------+-----------+-------+--------+-----+------------------+
        | 12 | 0x3000 |       63 |         0 |     0 |      0 |   0 | 0000000000000002 |'''

        if data is None:
            # bad read
            return ()

        net_addr = self.net_addr
        routers_list = []
        for line in data:
            # line = (mac=123456, rloc16=20480, id=20, path_cost=0, age=7)
            age = line.age
            if age > 300:
                continue  # shouldn't add/resolve very old Routers
            rloc16 = line.rloc16

            # check if it's own rloc16
            if rloc16 == self.rloc16:
                continue

            if resolve_mac is not None:
                if resolve_mac == line.mac:
                    mac_ip = rloc16
                    break

            # look for this router in Leader Data
            # if doesn't exist, add it to routers_list with max ts
            # if it exists, just add it with its ts
            last_ts = self.leader_data.get_mac_ts(line.mac)
            if time.time() - last_ts < age_min:
                continue  # shouldn't add/resolve very "recent" Routers

            ipv6 = net_addr + hex(rloc16)[2:]
            routers_list.append((last_ts, ipv6))

        if resolve_mac is not None:
            print("Mac found in Router %s" % str(mac_ip))
            return mac_ip

        # sort the list in the ascending values of timestamp
        routers_list.sort()

        print("Routers list %s" % str(routers_list))
        return routers_list

    def leader_data_pack(self):
        """ creates packet with all Leader data, leader_dict """
        self.leader_data.rloc16 = self.rloc16
        data = self.leader_data.pack()
        return data

    def leader_data_unpack(self, data):
        self.leader_data = LeaderData(data)
        print("Leader Data : %s" % self.leader_data.to_string())
        return self.leader_data.ok

    def neighbor_resolve_mac(self, mac):
        mac_ip = self.router_data.resolve_mac(mac)
        return mac_ip

    def resolve_mac_from_leader_data(self, mac):
        mac_ip = self.leader_data.resolve_mac(mac)
        print("Mac %x found as IP %s" % (mac, str(mac_ip)))
        return mac_ip

    def macs_get(self):
        """ returns the set of the macs, hopefully it was received from Leader """
        #print("Macs: %s"%(str(self.macs)))
        return (self.macs, self.macs_ts)

    def macs_set(self, data):
        MACS_FMT = '!H'
        field_size = calcsize(MACS_FMT)
        #print("Macs pack: %s"%(str(data)))
        n, = unpack(MACS_FMT, data)
        #print("Macs pack(%d): %s"%(n, str(data)))
        index = field_size
        self.macs = set()

        for _ in range(n):
            mac, = unpack(MACS_FMT, data[index:])
            self.macs.add(mac)
            #print("Macs %d, %d: %s"%(index, mac, str(self.macs)))
            index = index + field_size

        self.macs_ts = time.time()
        pass

    def connections_get(self):
        """ returns the list of all connections inside Mesh, hopefully it was received from Leader """
        return (self.connections, self.connections_ts)

    def connections_set(self, data):
        CONNECTIONS_FMT = '!HHb'
        field_size = calcsize(CONNECTIONS_FMT)
        n, = unpack('!H', data)
        index = calcsize('!H')
        self.connections = list()
        for _ in range(n):
            #(mac1, mac2, rssi)
            record = unpack(CONNECTIONS_FMT, data[index:])
            self.connections.append(record)
            index = index + field_size
        self.connections_ts = time.time()
        pass

    def node_info_get(self, mac):
        """ returns the RouterData or NeighborData for the specified mac """
        #try to find it as router or a neighbor of a router
        node, role = self.leader_data.node_info_mac(mac)
        if node is None:
            return {}
        # try to create dict for RPC answer
        data = {}
        data['ip'] = node.rloc16
        data['r'] = node.role
        if role is self.STATE_CHILD:
            data['a'] = node.age
        elif role is self.STATE_ROUTER:
            data['a'] = time.time() - node.ts
            data['l'] = {'lat': node.coord[0], 'lng': node.coord[1]}
            data['nn'] = node.neigh_num()
            nei_macs = node.get_macs_set()
            data['nei'] = list()
            for nei_mac in nei_macs:
                nei = node.dict[nei_mac]
                data['nei'].append(
                    (nei.mac, nei.rloc16, nei.role, nei.rssi, nei.age))
        return data

    def node_info_set(self, data):
        (role, ) = unpack('!B', data)

        if role is self.STATE_ROUTER:
            router = RouterData(data[1:])
            self.leader_data.add_router(router)
            print("Added as router %s" % router.to_string())
        elif role is self.STATE_CHILD:
            node = NeighborData(data[1:])
            router = RouterData(node)
            self.leader_data.add_router(router)
            print("Added as Router-Neigh %s" % router.to_string())
        pass
Example #13
0

def send_datatoLWGW(socket, dataString):
    print("Send data to the LWGW")
    data = dataString
    taille = str(len(data)) + 's'
    databytes = struct.pack(taille, data)
    socket.send(databytes)


lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)
app_eui = binascii.unhexlify('70 B3 D5 7E F0 00 49 E1'.replace(' ', ''))
app_key = binascii.unhexlify(
    '30 4C 99 26 3E A5 E6 43 B5 A0 8C B3 25 4A 61 FA'.replace(' ', ''))
dev_eui = binascii.unhexlify(
    (binascii.hexlify(lora.mac()).decode('ascii')).upper())
#dev_addr = struct.unpack(">l", binascii.unhexlify('00 00 00 05'.replace(' ','')))[0]
lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0)
while not lora.has_joined():
    time.sleep(2.5)
    print('Not yet joined...')
print('connected to Objenious LoRaWAN!')
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)
s.setblocking(True)
changetoLoRa(lora)
changetoLW()
send_datatoLWGW(s, "toto,23:")
changetoLoRa(lora)
s.setblocking(False)
Example #14
0
from network import LoRa
import socket
import time
import ubinascii  # micropython module
import struct  # for ABP
import pycom
pycom.heartbeat(False)
pycom.rgbled(0xECEB1A)

# create LoRa asia region
lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.AS923, device_class=LoRa.CLASS_C)
print('Device EUI:', ubinascii.hexlify(lora.mac()).upper().decode('utf-8'))


################
#     OTAA
################
app_eui = ubinascii.unhexlify('D8DF149D1DA65EF9')
app_key = ubinascii.unhexlify('E8F1B92F79A72A8C2AA8AE182ADF2B35')
lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)
while not lora.has_joined():
    time.sleep(2.5)
    print('Not yet joined...')
pycom.rgbled(0x27ED00)
print('Joined!')

# create a LoRa socket
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)
s.setblocking(False)
Example #15
0
import struct
import time
import pycom

# Configuration for India
LORA_FREQUENCY = 866000000
LORA_NODE_DR = 5

# Turn off WiFi see also https://forum.pycom.io/topic/156/disable-wifi-for-low-power-operation
wlan = WLAN()
wlan.deinit()
print('WiFi OFF')

# Initialize LoRa in LORAWAN mode.
lora = LoRa(mode=LoRa.LORAWAN)
print('Device ID: ' + binascii.hexlify(lora.mac()).lower().decode('utf-8'))

# create an OTA authentication params
# these settings can be found from TTN
dev_eui = binascii.unhexlify(' '.replace(' ', ''))
app_eui = binascii.unhexlify(' '.replace(' ', ''))
app_key = binascii.unhexlify(' '.replace(' ', ''))

# remove all the non-default channels
for i in range(3, 16):
    lora.remove_channel(i)

# set the 3 default channels to the same frequency
lora.add_channel(0, frequency=LORA_FREQUENCY, dr_min=0, dr_max=LORA_NODE_DR)
lora.add_channel(1, frequency=LORA_FREQUENCY, dr_min=0, dr_max=LORA_NODE_DR)
lora.add_channel(2, frequency=LORA_FREQUENCY, dr_min=0, dr_max=LORA_NODE_DR)
Example #16
0
        print('Lora packet received')
        data = s.recv(64)
        print(data)
    if events & LoRa.TX_PACKET_EVENT:
        print('Lora packet sent')


def flash_led_to(color):
    pycom.rgbled(color)


pycom.heartbeat(False)  # Disable the heartbeat LED

# Getting the LoRa MAC
lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)
print("Device LoRa MAC:", binascii.hexlify(lora.mac()))

flash_led_to(BLUE)
# joining TTN
join_lora(True)

# Type 0 = dht11
# Type 1 = dht22
dht11 = 0
dht22 = 1
dht_type = dht11

th = DTH(Pin('P23', mode=Pin.OPEN_DRAIN), dht_type)

# py = Pysense()
#tempHum = SI7006A20(py)
Example #17
0
        print('Lora packet sent')


lora.nvram_erase()
#lora.nvram_restore()
# remove all the channels the gateway doesn't use
for channel in range(16, 72):
    lora.remove_channel(channel)
for channel in range(0, 7):
    lora.remove_channel(channel)
#create an OTAA authentication parameters for test lopy
dev_eui = ubinascii.unhexlify(
    '70B3D54997802DF8')  # these settings can be found from TTN
app_eui = ubinascii.unhexlify('70B3D57ED0028A4F')
app_key = ubinascii.unhexlify('CE46C01958A612D102F0D106AB415862')

# create an OTAA authentication parameters for lopy with ring/ckt
#dev address  = 26012DBE
#dev_eui = ubinascii.unhexlify('70B3D549952757BF') # these settings can be found from TTN
#app_eui = ubinascii.unhexlify('70B3D57ED0028A4F')
#app_key = ubinascii.unhexlify('88397B010F71D34BEDF77DA003C3A54C')

# create an OTAA authentication parameters for no ring lopy
#dev address = 260125A9
#dev_eui = ubinascii.unhexlify('70B3D54990435DFE') # these settings can be found from TTN
#app_eui = ubinascii.unhexlify('70B3D57ED0028A4F')
#app_key = ubinascii.unhexlify('CE46C01958A612D102F0D106AB415862')

# join a network using OTAA (Over the Air Activation)
print(binascii.hexlify(lora.mac()).upper().decode('utf-8'))
Example #18
0
print("Acceleration: " + str(li.acceleration()))
print("Roll: " + str(li.roll()))
print("Pitch: " + str(li.pitch()))

print("Battery voltage: " + str(py.read_battery_voltage()))
###

from network import LoRa

import config

# initialize LORAWAN mode for EU region
lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)

# print DevEUI of the device, use this when provisioning it in your network server
print("DevEUI: " + binascii.hexlify(lora.mac()).decode('utf-8').upper())

# OTAA authentication parameters, replace these with your own

print("Joining network using OTAA (Over the Air Activation)")
lora.join(activation=LoRa.OTAA,
          auth=(config.app_eui, config.app_key),
          timeout=0)

# wait until the module has joined the network
while not lora.has_joined():
    time.sleep(2.5)
    print('Not yet joined...')

print("Joined network")
from network import LoRa
import socket
import time
import binascii
import pycom

from machine import I2C

i2c = I2C(0, I2C.MASTER, baudrate=400000)
print(i2c.scan())

bme = BME280.BME280(i2c=i2c)

lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)

print("devEUI {}".format(binascii.hexlify(lora.mac())))

app_eui = binascii.unhexlify('00 00 00 00 00 00 00 00'.replace(' ', ''))
app_key = binascii.unhexlify(
    '11 22 33 44 55 66 77 88 11 22 33 44 55 66 77 88'.replace(' ', ''))
lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)

pycom.heartbeat(False)
pycom.rgbled(0x111111)

while not lora.has_joined():
    time.sleep(2.5)
    print('Not yet joined...')

pycom.rgbled(0x000000)
Example #20
0
from loramesh import Loramesh
from Networkmesh import *

pycom.wifi_on_boot(False)
pycom.heartbeat(False)

lora = LoRa(mode=LoRa.LORA,
            region=LoRa.US915,
            tx_power=20,
            bandwidth=LoRa.BW_125KHZ,
            sf=11)
print(lora.tx_power())
#lora = LoRa(mode=LoRa.LORA, region=LoRa.US915, bandwidth=LoRa.BW_125KHZ, sf=11)
#lora = LoRa(mode=LoRa.LORA, region=LoRa.US915,frequency=903000000,tx_power=19, bandwidth=LoRa.BW_125KHZ, sf=12)
MAC = str(ubinascii.hexlify(lora.mac()))[2:-1]
print("LoRa MAC: %s" % MAC)

loram = Loramesh(lora)
mesh = NetworkMesh(loram, MAC, 1)
#--------------------------------------------------------------------------------
# waiting until it connected to Mesh network
# se queda intentando conectarse y muestra los vecinos
mesh.connect()
# create UDP socket
#creo un socket LoRa
mesh.createSocket(1234)
# infinite main loop
#funcion principal
mesh.listen()
Example #21
0
# Colors used for status LED
RGB_OFF = 0x000000
RGB_POS_UPDATE = 0x101000
RGB_POS_FOUND = 0x001000
RGB_POS_NFOUND = 0x100000
RGB_LORA = 0x000010
LED_TIMEOUT = 0.2
pycom.heartbeat(False)

# Set up the LoRa in longer range mode

lora = LoRa(mode=LoRa.LORA, region=LoRa.AS923)
s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setblocking(False)
DevEUI = ubinascii.hexlify(lora.mac()).decode('ascii')

# Enable garbage collection

time.sleep(2)
gc.enable()

# Set up GPS with modest timeout

py = Pytrack()
l76 = L76GNSS(py)

last_lat = 13.736717
last_lon = 100.523186
last_alt = 0
# see the Pycom Licence v1.0 document supplied with this file, or
# available at https://www.pycom.io/opensource/licensing
#

from network import LoRa
from machine import Pin
import binascii
import pycom
import os

EXPECTED_MAC_ADDRESS = b"{MAC_ADDRESS}"

red_led = Pin('P10', mode=Pin.OUT, value=0)
green_led = Pin('P11', mode=Pin.OUT, value=0)

lora = LoRa(mode=LoRa.LORA)

if binascii.hexlify(lora.mac()) == EXPECTED_MAC_ADDRESS and os.uname(
).release == "{FW_VERSION}" and 'LoPy' in os.uname().machine:
    pycom.heartbeat(False)
    pycom.rgbled(0x008000)  # green
    green_led(1)
    print('Test OK')
    while True:
        pass
else:
    pycom.heartbeat(False)
    pycom.rgbled(0x800000)  # red
    red_led(1)
    print('Test failed')
Example #23
0
import binascii
import sys
import ustruct
import json

from machine import PWM

from machine import UART
from machine import I2C
from adafruit_bus_device.i2c_device import I2CDevice
import drivers.adafruit_sht31d
import uhashlib

# Retrieve the dev_eui from the LoRa chip (Only needed for OTAA to retrieve once)
lora = LoRa(mode=LoRa.LORAWAN, adr=True, region=LoRa.EU868)
dev_eui = binascii.hexlify(lora.mac()).upper().decode('utf-8')
uart = UART(0, 115200)
uart.init(115200, bits=8, parity=None, stop=1)

try:
    f = open("preset", "r")
    exists = True
    f.close()
except:
    exists = False

if not exists:
    while True:
        value = uart.read()
        if value != None:
            if str(value, 'utf-8') == "dev":
Example #24
0
        # if net.ssid == 'iotakl':
        #     print(net.ssid + ' found!')
        #     wlan.connect(net.ssid, auth=(net.sec, 'iotworkshop'), timeout=5000)
        #     connectingToWiFi = True
        #     break
        #
        # # use john's router
        # if net.ssid == 'iotakl24':
        #     print(net.ssid + ' found!')
        #     wlan.connect(net.ssid, auth=(net.sec, 'iotakl17'), timeout=5000)
        #     connectingToWiFi = True
        #     break

    if connectingToWiFi:
        while not wlan.isconnected():
            pycom.rgbled(green)
            time.sleep(0.1)
            pycom.rgbled(off)
            time.sleep(2)
            machine.idle()  # save power while waiting
        print('WLAN connection succeeded!')

    # get the EUI
    lora = LoRa()
    print("LoRa EUI:", binascii.hexlify(lora.mac()))

    #get the IP on the WiFi
    print("IP:", wlan.ifconfig()[0])
    print("Try  typing a command like os.uname()")
    print("Or run the LoRa OTAA demo execfile(\"otaa.py\")")
Example #25
0
class Lora_Link_Layer:

    def __init__(self, receive_msg_cb):
        print("Initializing Link Layer...")

        self.receive_msg_cb = receive_msg_cb
        self.msg_buffer_list = []

        self.incoming_cts_key = -1
        self.wait = False #Use other name, e.g. wait_for_channel
        self.wait_time = 0
        #use int instead of boolean. If multiple cts/rts arrive sum.

        self.lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868)
        self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
        self.s.setblocking(False)
        self.lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT), handler=self.lora_cb)

        self.lora_mac_address_b = binascii.hexlify(self.lora.mac())
        self.lora_mac_address = str(self.lora_mac_address_b, "utf-8")

        #_thread.start_new_thread(self.process_msg_pipeline, ())


    def get_lora_mac(self):
        return self.lora_mac_address


    def lora_cb(self, lora):
        events = lora.events()
        if events & LoRa.RX_PACKET_EVENT:

            msg = self.s.recv(250)
            #print(msg)
            #unpack message and pass meta information (like mac address or protocol) as parameter
            #meta, data = self.unpack_frame(msg.decode("utf-8"))
            #msg_utf8 = data
            #msg_1 = msg.decode("utf-8")
            #print('Link Layer: Lora packet received. ' + str(msg_utf8, "utf-8"))

            #if (msg_1.startswith("cts")):
            #    self.handle_incoming_cts(msg_1)

            #elif (msg_1.startswith("rts")):
            #    self.handle_incoming_rts(msg_1)
                #send cts. what if cts gets lost? Ignore? CSMA sending messages
                #only one rts at a time. identify rts if it is repeated.
            #else:
            print('Link Layer: Passing received data to Network Layer')
            self.receive_msg_cb(msg)

        #if events & LoRa.TX_PACKET_EVENT:
            #print('Lora packet sent')


    def append_msg_to_pipeline(self, msg, use_ca):
        #self.msg_buffer_list.append([msg, use_ca])
        self.lora_send_csma_ca(msg, use_ca)

        #Buffer Länge definieren und Nachrichten verwerfen oder auf Teilpackete aufteilen.
        #Time on air -> vielfaches (zufällig) warten, falls Kanal nicht frei.

    def process_msg_pipeline(self):
        while True:
            if (len(self.msg_buffer_list) > 0):
                msg_and_ca = self.msg_buffer_list.pop(0)
                msg = msg_and_ca[0]
                use_ca = msg_and_ca[1]

                self.lora_send_csma_ca(msg, use_ca)

                time.sleep(1)


    def lora_send_csma_ca(self, msg, use_ca):
        if (use_ca):
            print("Link Layer: using CA")

            #do not send rts if wait = true
            rts_random_key_b = binascii.hexlify(os.urandom(2))
            rts_random_key = str(rts_random_key_b, "utf-8")
            rts = "rts." + rts_random_key

            while not (rts_random_key == self.incoming_cts_key): #and not wait. Probably?
                #maximum repetition
                if not self.wait:
                    self.lora_send_csma(rts)
                    print("Link Layer: Waiting for cts. expected: " + str(rts_random_key) + " received: " + str(self.incoming_cts_key))
                else:
                    print("Link Layer: Waiting..." + str(self.wait_time))
                #change delay randomly/exponential
                #Wie lange warten? cts soll nicht mit nächstem rts versuch überlagert werden?
                time.sleep(2)

        else:
            print("Link Layer: NOT using CA")

        #blocking function
        self.lora_send_csma(msg)


    def lora_send_csma(self, msg):
        #Semtech LoRa: High sensitivity  -111 to -148dBm (Datasheet: https://semtech.my.salesforce.com/sfc/p/#E0000000JelG/a/2R0000001OKs/Bs97dmPXeatnbdoJNVMIDaKDlQz8q1N_gxDcgqi7g2o)
        while not self.lora.ischannel_free(-100,100):
            #max rep.
            print("Link Layer: channel not free")

        print("Link Layer: channel free (CSMA). Sending data...")
        self.lora_send(msg)


    def lora_send(self, msg):
        #frame = self.pack_frame("c", msg)
        frame = msg
        print("Link Layer | Sending data: " + str(frame))
        self.s.send(frame)


    def handle_incoming_cts(self, incoming_cts):
        print("Link Layer: CTS received. Key=" + incoming_cts)
        self.incoming_cts_key = str(incoming_cts.split(".")[1], "utf-8")
        #Important: Wait also if CTS is for other lora. Use MAC adress as identifier
        #Combine with incoming RTS


    def handle_incoming_rts(self, incoming_rts):
        incoming_rts_key = str(incoming_rts.split(".")[1], "utf-8")
        print("Link Layer: RTS received. Key=" + incoming_rts_key)
        #send cts. what if cts gets lost? Ignore? CSMA sending messages
        #only one rts at a time. identify rts if it is repeated.
        #check if rts is new. Problem: other lora did not receive cts. Important: Waiting time
        if (not self.wait):
            _thread.start_new_thread(self.wait_timer, (5,))
            print("Link Layer: CTS other lora. Waiting for other lora...")
            #save mac address of other lora and wait until packet from this lora arrived or max
            cts = "cts." + incoming_rts_key
            #self.lora_send_csma(cts.encode("utf-8"))
            self.lora_send_csma(cts)


    def wait_timer(self, wait_time):
        self.wait_time = wait_time
        self.wait = True
        print("Wait timer")

        while self.wait_time > 0:
            time.sleep(1)
            self.wait_time = self.wait_time - 1
            print(str(self.wait_time))

        self.wait = False


    #This field states whether the frame is a data frame or it is used for control functions like error and flow control or link management etc.
    def pack_frame(self, type, data):
        #Use single bits for control and 8 bytes for MAC without delimiters. character delimiters can cause problems and need much space.
        frame = type + "::" + self.get_lora_mac() + "::" + data
        print("Link Layer:" + frame)
        return frame


    def unpack_frame(self, frame):
        meta = [frame.split("::")[0], frame.split("::")[1]]
        data = frame.split("::")[2]
        return meta, data
lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))

#wait until the module has joined the network
while not lora.has_joined():
    time.sleep(1.5)
    print('Not joined yet...')

print('Network joined!')

print("LoRa Ready")
print("Frequency: "+ str(lora.frequency()))
print("Spreading Factor: "+ str(lora.sf()))
print("Coding Rate: "+ str(lora.coding_rate()))
print("Bandwidth: "+ str(lora.bandwidth()))
print(lora.mac())


pycom.rgbled(0x00ff00)

s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
s.setsockopt(socket.SOL_LORA, socket.SO_DR, 0)
s.setblocking(True)

while True:
    print('Sending Packet...')
    pycom.rgbled(0x00ff00)
    s.send('0')
    print('Done sending')
    data = s.recv(64)
    time.sleep(2000)
Example #27
0
RM.addRule (rule_coap1)
RM.addRule (rule_coap2)

p = Parser()
comp = Compressor(RM)
dec  = Decompressor(RM)
coapC = CoAP.CoAPSM(p, comp, dec, IPv6_source, IPv6_dest, increase_delivary_chances_function)

app_eui = binascii.unhexlify('00 00 00 00 00 00 00 00'.replace(' ',''))
app_key = binascii.unhexlify('11 22 33 44 55 66 77 88 11 22 33 44 55 66 77 88'.replace(' ',''))

pycom.heartbeat(False)


if LORAWAN:
    mac = lora.mac()
    print ('MAC:')
    print(hex(mac[0]), end='-')
    print(hex(mac[1]), end='-')
    print(hex(mac[2]), end='-')
    print(hex(mac[3]), end='-')
    print(hex(mac[4]), end='-')
    print(hex(mac[5]), end='-')
    print(hex(mac[6]), end='-')
    print(hex(mac[7]))


    for i in range (0,  255):
        led = i<< 16| i <<8  | i
        pycom.rgbled(led)
        time.sleep(0.01)
Example #28
0
from network import LoRa
from machine import Pin
import binascii
import pycom
import os

EMPTY_MAC_ADDRESS = b'ffffffffffffffff'

red_led = Pin('P10', mode=Pin.OUT, value=0)
green_led = Pin('P11', mode=Pin.OUT, value=0)

lora = LoRa(mode=LoRa.LORA)
pycom.heartbeat(False)

try:
    if binascii.hexlify(lora.mac()) != EMPTY_MAC_ADDRESS and os.uname(
    ).release == "{FW_VERSION}" and 'LoPy' in os.uname().machine:
        pycom.rgbled(0x008000)  # green
        green_led(1)
        print('QA Test OK')
    else:
        pycom.rgbled(0x800000)  # red
        red_led(1)
        print('QA Test failed')
except Exception:
    pycom.rgbled(0x800000)  # red
    red_led(1)
    print('QA Test failed')

while True:
    pass
Example #29
0
def lora_task():
    with thread_list_mutex:
        thread_list[_thread.get_ident()] = 'LORA'

    # Initialise LoRa in LORAWAN mode.
    # Please pick the region that matches where you are using the device:
    # Asia = LoRa.AS923
    # Australia = LoRa.AU915
    # Europe = LoRa.EU868
    # United States = LoRa.US915
    lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868, tx_power=14)
    printt("DevEUI: %s" % (ubinascii.hexlify(lora.mac()).decode('ascii')))

    # create an OTAA authentication parameters
    app_eui = ubinascii.unhexlify(conf['lora']['app_eui'])
    app_key = ubinascii.unhexlify(conf['lora']['app_key'])

    printt("Joining LORAWAN with EUI: %s and KEY: %s" % (conf['lora']['app_eui'], conf['lora']['app_key']))

    # join a network using OTAA (Over the Air Activation)
    lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0)

    lora_setup_done = False
    while (True):
        # Set LORA battery state
        lora_set_battery()

        # wait until the module has joined the network
        if (not lora.has_joined()):
            pycom.rgbled(0x100000)
            printt('Joining network...')
            time.sleep(2.5)
        else:
            if (not lora_setup_done):
                # Succesfully joined
                pycom.rgbled(0x001000)

                # create a LoRa socket
                s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)

                # set the LoRaWAN data rate
                s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)

                lora_setup_done = True
            
            # make the socket blocking
            # (waits for the data to be sent and for the 2 receive windows to expire)
            s.setblocking(True)

            # send some data
            s.send(bytes([0x01, 0x02, 0x03]))

            # make the socket non-blocking
            # (because if there's no data received it will block forever...)
            s.setblocking(False)

            # get any data received (if any...)
            data = s.recv(64)
            print(data)

        time.sleep(0.1)
Example #30
0
    print(msg)
    if events & LoRa.TX_FAILED_EVENT:
        print("Warning: no ACK after {} attempts".format(stats[5]))

def flash_led(color=LED_RED, on=0.1, pause=0.2, repeat=1):
    """ flash RGB LED on LoPy """
    for _ in range(0, repeat):
        pycom.rgbled(color)
        utime.sleep(on)
        pycom.rgbled(LED_OFF)
        utime.sleep(pause)

# setup LoRaWAN stack with presets for Europe (868 MHz)
print("\nInit LoRaWAN stack on {} running {}...".format(uos.uname()[0], uos.uname()[2]))
lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868)
print("LoRa DevEUI: {}".format(ubinascii.hexlify(lora.mac()).upper().decode()))

# join network either using OTAA or ABP
if LORA_OTAA:
    app_eui = ubinascii.unhexlify(OTAA_APP_EUI)
    app_key = ubinascii.unhexlify(OTAA_APP_KEY)
    lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0, dr=LORA_DR_JOIN)
    print("Starting OTAA join...", end="")
    otaa_timer = 0
    start_join = utime.ticks_ms()
    while not lora.has_joined() and otaa_timer < OTAA_JOIN_TIMEOUT:
        otaa_timer = int(utime.ticks_diff(utime.ticks_ms(), start_join)/1000)
        print(".", end="")
        flash_led(LED_BLUE, 0.1, 0.9)
    if lora.has_joined():
        print("OK.")