class Startiot: def __init__(self): self.dev_eui = binascii.unhexlify("**REMOVED**") self.app_eui = binascii.unhexlify("**REMOVED**") self.app_key = binascii.unhexlify("**REMOVED**") self.lora = LoRa(mode=LoRa.LORAWAN) def connect(self, blocking = False, timeout = 0, function = None): self.lora.join(activation=LoRa.OTAA, auth=(self.dev_eui, self.app_eui, self.app_key), timeout=0) if timeout == 0: while not self.lora.has_joined(): if function == None: time.sleep(2.5) else: function() else: for x in range(timeout): if self.lora.has_joined(): break if function == None: time.sleep(2.5) else: function() if not self.lora.has_joined(): return False self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) # make the socket non-blocking self.s.setblocking(blocking) return True def send(self, data): self.s.send(data) def recv(self, length): return self.s.recv(length)
class Comunication: def __init__(self): self.key = b'encriptaincendis' pass # Initialize LoRa in LORAWAN mode. def JoinLoraWan(self): self.lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) # create an OTA authentication params app_eui = ubinascii.unhexlify('70B3D57ED001C55E') dev_eui = ubinascii.unhexlify( '006D2D7767E7BAFE') # these settings can be found from TTN #app_eui = ubinascii.unhexlify('70B3D57ED0019255') # these settings can be found from TTN app_key = ubinascii.unhexlify('0A05862CEA15FC56C047FC03FBDF34DB' ) # these settings can be found from TTN # set the 3 default channels to the same frequency (must be before sending the OTAA join request) self.lora.add_channel(0, frequency=868100000, dr_min=0, dr_max=5) self.lora.add_channel(1, frequency=868100000, dr_min=0, dr_max=5) self.lora.add_channel(2, frequency=868100000, dr_min=0, dr_max=5) # join a network using OTAA self.lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0) # wait until the module has joined the network while not self.lora.has_joined(): time.sleep(5) print('Not joined yet...') # remove all the non-default channels for i in range(3, 16): self.lora.remove_channel(i) # create a LoRa socket self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) # make the socket non-blocking self.s.setblocking(False) time.sleep(5) """ Your own code can be written below! """ def savestate(self): self.lora.nvram_save() # def restorestate(self): # self.lora.nvram_restore() def Switch_to_LoraRaw(self): self.lora.nvram_save() self.lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868) self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.s.setblocking(False) #Aquesta instrucció igual sobra time.sleep(5) def Switch_to_LoraWan(self): self.lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) self.lora.nvram_restore() time.sleep(5) #Si no es reinicia el socket el missatge 3 no s'envia self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) def EnviarGateway(self, data): self.s.send(data) time.sleep(5) def RebreGateway(self): data, port = self.s.recvfrom(256) print(data) def sendData(self, misg): self.s.setblocking(True) iv = crypto.getrandbits( 128) # hardware generated random IV (never reuse it) cipher = AES(self.key, AES.MODE_CFB, iv) msg = iv + cipher.encrypt(misg) self.s.send(msg) self.s.setblocking(False) #print(msg) #print(len(msg)) time.sleep(5) def reciveData(self): self.s.setblocking(False) msg = self.s.recv(128) #Get any data recieved #If there's any data, decrypt if len(msg) > 0: print("encriptat: ", msg) cipher = AES(self.key, AES.MODE_CFB, msg[:16]) # on the decryption side original = cipher.decrypt(msg[16:]) print("original ", original) return (original) else: return
class LORA(object): 'Wrapper class for LoRa' # LoRa and socket instances lora = None s = None def connect(self, dev_eui, app_eui, app_key): """ Connect device to LoRa. Set the socket and lora instances. """ dev_eui = unhexlify(dev_eui) app_eui = unhexlify(app_eui) app_key = unhexlify(app_key) # Disable blue blinking and turn LED off LED.heartbeat(False) LED.off() # Initialize LoRa in LORAWAN mode self.lora = LoRa(mode=LoRa.LORAWAN) # Join a network using OTAA (Over the Air Activation) self.lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0) # Wait until the module has joined the network count = 0 while not self.lora.has_joined(): LED.blink(1, 2.5, 0xff0000) # print("Trying to join: " , count) count = count + 1 # Create a LoRa socket LED.blink(2, 0.1) self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # Set the LoRaWAN data rate self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) # Make the socket non-blocking self.s.setblocking(False) # print ("Joined! ", count) # print("Create LoRaWAN socket") # Create a raw LoRa socket self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.s.setblocking(False) def send(self, data): """ Send data over the network. """ try: self.s.send(data) LED.blink(2, 0.1, 0x00ff00) print("Sending data:") print(data) except OSError as e: if e.errno == 11: print("Caught exception while sending") print("errno: ", e.errno) LED.off() data = self.s.recv(64) print("Received data:", data) return data
for i in range(3): pycom.rgbled(green) time.sleep_ms(100) pycom.rgbled(0) time.sleep_ms(100) def lora_send(payload): print('Sending uplink message: ', payload) pycom.rgbled(pink) a = sock.send(payload) print('LoRa uplink complete') ack() while True: if(lora.has_joined()): n = len(data(10000, 'GyY')) if(n > 150): #ON lora_send("1" + "," + str(n)) time.sleep(60) else: #OFF lora_send("0" + "," + str(n)) time.sleep(60) else: # Join the network lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0) pycom.rgbled(red)
#wlan = WLAN(mode=WLAN.AP, ssid=lora_mac, auth=(WLAN.WPA2,'www.pycom.io'), # channel=7, antenna=WLAN.INT_ANT) # Display our device info & address print(sys_info) print(lora_mac) # join a network using OTAA sfdr = 5 sfdr_min = 0 # SF12 sfdr_max = 5 # SF7 pycom.rgbled(0x7f7f00) # yellow while not (lora.has_joined()): lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0, dr=sfdr) time.sleep(20) if not lora.has_joined() and sfdr != 0: sfdr -= 1 pycom.rgbled(0x007f00) # green s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate SF7=5 SF8=4 SF9=3 SF10=2 SF11=1 SF12=0 s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, True) # make the socket non-blocking s.setblocking(False)
class LoraNet: def __init__(self, frequency, dr, region, device_class=LoRa.CLASS_C, activation=LoRa.OTAA, auth=None): self.frequency = frequency self.dr = dr self.region = region self.device_class = device_class self.activation = activation self.auth = auth self.sock = None self._exit = False self.s_lock = _thread.allocate_lock() self.lora = LoRa(mode=LoRa.LORAWAN, region=self.region, device_class=self.device_class) self._msg_queue = [] self.q_lock = _thread.allocate_lock() self._process_ota_msg = None def stop(self): self._exit = True def init(self, process_msg_callback): self._process_ota_msg = process_msg_callback def receive_callback(self, lora): events = lora.events() if events & LoRa.RX_PACKET_EVENT: rx, port = self.sock.recvfrom(256) if rx: if '$OTA' in rx: print("OTA msg received: {}".format(rx)) self._process_ota_msg(rx.decode()) else: self.q_lock.acquire() self._msg_queue.append(rx) self.q_lock.release() def connect(self): if self.activation != LoRa.OTAA and self.activation != LoRa.ABP: raise ValueError("Invalid Lora activation method") if len(self.auth) < 3: raise ValueError("Invalid authentication parameters") self.lora.callback(trigger=LoRa.RX_PACKET_EVENT, handler=self.receive_callback) # set the 3 default channels to the same frequency self.lora.add_channel(0, frequency=self.frequency, dr_min=0, dr_max=5) self.lora.add_channel(1, frequency=self.frequency, dr_min=0, dr_max=5) self.lora.add_channel(2, frequency=self.frequency, dr_min=0, dr_max=5) # remove all the non-default channels for i in range(3, 16): self.lora.remove_channel(i) # authenticate with abp or ota if self.activation == LoRa.OTAA: self._authenticate_otaa(self.auth) else: self._authenticate_abp(self.auth) # create socket to server self._create_socket() def _authenticate_otaa(self, auth_params): # create an OTAA authentication params self.dev_eui = binascii.unhexlify(auth_params[0]) self.app_eui = binascii.unhexlify(auth_params[1]) self.app_key = binascii.unhexlify(auth_params[2]) self.lora.join(activation=LoRa.OTAA, auth=(self.dev_eui, self.app_eui, self.app_key), timeout=0, dr=self.dr) while not self.lora.has_joined(): time.sleep(2.5) print('Not joined yet...') def has_joined(self): return self.lora.has_joined() def _authenticate_abp(self, auth_params): # create an ABP authentication params self.dev_addr = struct.unpack(">l", binascii.unhexlify(auth_params[0]))[0] self.nwk_swkey = binascii.unhexlify(auth_params[1]) self.app_swkey = binascii.unhexlify(auth_params[2]) self.lora.join(activation=LoRa.ABP, auth=(self.dev_addr, self.nwk_swkey, self.app_swkey)) def _create_socket(self): # create a LoRa socket self.sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate self.sock.setsockopt(socket.SOL_LORA, socket.SO_DR, self.dr) # make the socket non blocking self.sock.setblocking(False) time.sleep(2) def send(self, packet): with self.s_lock: self.sock.send(packet) def receive(self, bufsize): with self.q_lock: if len(self._msg_queue) > 0: return self._msg_queue.pop(0) return '' def get_dev_eui(self): return binascii.hexlify(self.lora.mac()).decode('ascii') def change_to_multicast_mode(self, mcAuth): print('Start listening for firmware updates ...........') if self.device_class != LoRa.CLASS_C: self.lora = LoRa(mode=LoRa.LORAWAN, region=self.region, device_class=LoRa.CLASS_C) self.connect() mcAddr = struct.unpack(">l", binascii.unhexlify(mcAuth[0]))[0] mcNwkKey = binascii.unhexlify(mcAuth[1]) mcAppKey = binascii.unhexlify(mcAuth[2]) self.lora.join_multicast_group(mcAddr, mcNwkKey, mcAppKey)
def main(): print ("Main Execution") 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) lora = LoRa(mode=LoRa.LORAWAN) for i in range (0, 255): led = i<< 16| i <<8 | i pycom.rgbled(led) time.sleep(0.01) # join a network using OTAA (Over the Air Activation) lora.join(activation=LoRa.OTAA, auth=(app_eui, 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...') pycom.rgbled(0) # create a LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) s.bind(0x02); # set the LoRaWAN data rate s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, False) print("apres setsock") # make the socket blocking # (waits for the data to be sent and for the 2 receive windows to expire) f = Frag(s, MTU=50, rule=rule_frag)#, f.send ("""To be, or not to be: that is the question: Whether ’tis nobler in the mind to suffer The slings and arrows of outrageous fortune, Or to take arms against a sea of troubles, And by opposing end them? To die: to sleep; No more; and by a sleep to say we end The heart-ache and the thousand natural shocks That flesh is heir to, ’tis a consummation Devoutly to be wish’d. To die, to sleep; To sleep: perchance to dream: ay, there’s the rub; For in that sleep of death what dreams may come When we have shuffled off this mortal coil, Must give us pause: there’s the respect That makes calamity of so long life; For who would bear the whips and scorns of time, The oppressor’s wrong, the proud man’s contumely, The pangs of despised love, the law’s delay, The insolence of office and the spurns That patient merit of the unworthy takes, When he himself might his quietus make With a bare bodkin? who would fardels bear, To grunt and sweat under a weary life, But that the dread of something after death, The undiscover’d country from whose bourn No traveller returns, puzzles the will And makes us rather bear those ills we have Than fly to others that we know not of? Thus conscience does make cowards of us all; And thus the native hue of resolution Is sicklied o’er with the pale cast of thought, And enterprises of great pith and moment With this regard their currents turn awry, And lose the name of action.–Soft you now! The fair Ophelia! Nymph, in thy orisons Be all my sins remember’d.""") f.sleep()
print("Adicionando canais Australianos...") for i in range(0, 7): lora.add_channel(i, frequency=915200000 + i * 200000, dr_min=0, dr_max=5) lora.add_channel(65, frequency=917500000, dr_min=4, dr_max=4) # join a network using ABP (Activation By Personalization) lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey)) # join a network using OTAA #lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0) # wait until the module has joined the network join_wait = 0 while True: time.sleep(2.5) if not lora.has_joined(): print('Tentando join...') join_wait += 1 if join_wait == 5: print("Tente novamente.") lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey)) join_wait = 0 else: print("Join realizado!") break # create a LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate
class LoRaManager: """ """ def __init__(self, manager, settings): self.manager = manager self.settings = settings # LoRa settings. self.otaa_settings = self.settings.get('networking.lora.otaa') #self.generated_device_eui = binascii.hexlify(LoRa().mac()) def start(self): """ """ self.start_lora_join() self.wait_for_lora_join(42) time.sleep(2.5) if self.lora_joined: self.create_lora_socket() else: log.error("[LoRa] Could not join network") def start_lora_join(self): """ """ from network import LoRa #pycom.rgbled(0x0f0000) # red #self.lora = LoRa(mode=LoRa.LORAWAN, region=self.otaa_settings['region']) self.lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) # restore LoRa state from NVRAM after waking up from DEEPSLEEP. Rejoin otherwise if machine.reset_cause() == machine.DEEPSLEEP_RESET: self.lora.nvram_restore() log.info( '[LoRA] LoRaWAN state restored from NVRAM after deep sleep') else: self.lora.nvram_erase() log.info( '[LoRA] LoRaWAN state erased from NVRAM to let the device join the network' ) # Create LoRaWAN OTAA connection to TTN. app_eui = binascii.unhexlify(self.otaa_settings['application_eui']) app_key = binascii.unhexlify(self.otaa_settings['application_key']) # Remark: For Pycom Nanogateway. # Set the 3 default channels to the same frequency (must be before sending the otaa join request) #self.lora.add_channel(0, frequency=self.otaa_settings['frequency'], dr_min=0, dr_max=5) #self.lora.add_channel(1, frequency=self.otaa_settings['frequency'], dr_min=0, dr_max=5) #self.lora.add_channel(2, frequency=self.otaa_settings['frequency'], dr_min=0, dr_max=5) if not self.lora.has_joined(): if self.otaa_settings.get('device_eui') is None: self.lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) else: dev_eui = binascii.unhexlify(self.otaa_settings['device_eui']) self.lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0) def wait_for_lora_join(self, attempts): """ :param attempts: """ self.lora_joined = None for i in range(0, attempts): while not self.lora.has_joined(): time.sleep(2.5) #pycom.rgbled(0x0f0f00) # yellow time.sleep(0.1) log.info('[LoRA] Not joined yet...') #pycom.rgbled(0x000000) # off self.lora_joined = self.lora.has_joined() if self.lora_joined: log.info('[LoRA] joined...') # TODO: move nvram_save() to after payload send call self.lora.nvram_save() else: log.info('[LoRa] did not join in %s attempts', attempts) #for i in range(3, 16): # self.lora.remove_channel(i) return self.lora_joined def create_lora_socket(self): """ """ # create a lora socket self.lora_socket = None self.socket = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate #self.socket.setsockopt(socket.SOL_LORA, socket.SO_DR, self.otaa_settings['datarate']) self.socket.setsockopt(socket.SOL_LORA, socket.SO_DR, self.otaa_settings['datarate']) # make the socket non-blocking self.socket.setblocking(False) self.lora_socket = True log.info('[LoRa] socket created') for i in range(0, 2): #pycom.rgbled(0x000f00) # green time.sleep(0.1) #pycom.rgbled(0x000000) # off time.sleep(4.0) return self.lora_socket def lora_send(self, payload): """ :param payload: """ success = self.socket.send(payload) for i in range(0, 2): #pycom.rgbled(0x00000f) # green time.sleep(0.1) #pycom.rgbled(0x000000) # off return success def lora_receive(self): """ """ rx, port = self.socket.recvfrom(256) if rx: #pycom.rgbled(0x000f00) # green log.info('[LoRa] Received: {}, on port: {}'.format(rx, port)) #pycom.rgbled(0x000f00) # green time.sleep(6) return rx, port
import machine import config print('Main start') # LoRa details keys obtained from KPN dev_addr = struct.unpack(">l", binascii.unhexlify(config.DEV_ADDR))[0] nwks_key = binascii.unhexlify(config.NWKS_KEY) apps_key = binascii.unhexlify(config.APPS_KEY) # Setup LoRa lora = LoRa(mode=LoRa.LORAWAN, adr=True) # join a network using ABP lora.join(activation=LoRa.ABP, auth=(dev_addr, nwks_key, apps_key), timeout=0) print("LoRa active: ", lora.has_joined()) # create a LoRa socket lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate lora_sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) lora_sock.setblocking(False) def ack(): for i in range(3): pycom.rgbled(0x00ff00) time.sleep_ms(100) pycom.rgbled(0)
print("country", wlan.country()) except: pass print("ifconfig", wlan.ifconfig()) print('IP:', wlan.ifconfig()[0]) print("mode", wlan.mode(), end=' ') print_wifi_mode(wlan.mode()) print() try: print("===== lora =======================================") from network import LoRa lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) print("mac", binascii.hexlify(lora.mac())) print(lora.frequency()) print(lora.has_joined()) print(lora.tx_power()) print(lora.power_mode()) #print(lora.stats()) except: pass try: print("===== sigfox =====================================") from network import Sigfox sigfox = Sigfox(mode=Sigfox.SIGFOX, rcz=Sigfox.RCZ1) print("id", binascii.hexlify(sigfox.id())) print("mac", binascii.hexlify(sigfox.mac())) print("pac", binascii.hexlify(sigfox.pac())) print("frequencies", sigfox.frequencies()) except:
def start(my_ota_updater): from network import LoRa import socket import time import binascii import pycom # Turn the light red # blue pycom.heartbeat(False) pycom.rgbled(0x110000) # 0x000011 # Initialise LoRa in LORAWAN mode. lora = LoRa(mode=LoRa.LORAWAN) 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(' ', '')) # join a network using OTAA (Over the Air Activation) lora.join(activation=LoRa.OTAA, auth=(app_eui, 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...') # create a LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) #s.bind(5) # set the LoRaWAN data rate s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, False) timestamp = time.time() # setup for the data sending i2c = I2C(0, I2C.MASTER, baudrate=400000) print(i2c.scan()) bme = data_sensor.BME280(i2c=i2c) ob = 0 while True: # Turn the light green pycom.rgbled(0x001100) s.setblocking(True) s.settimeout(10) # reading data ar = bme.read_raw_temp() a = bme.read_temperature() br = bme.read_raw_pressure() b = bme.read_pressure() cr = bme.read_raw_humidity() c = bme.read_humidity() # print ("temp", ar, a, "° - hum", cr, c, "% - pres", br, # "pres", b, "hPa [delta", ob - br, "]" ) ob = br # for testing new code, remove try/except #message_to_send = "Temp : " + str(a) + "°C - Hum : " + str(c) + "%" # - Pres : " + str(b) + "hPa" message_to_send = { "temperature": str(a), "humidity": str(c), "pressure": str(b) } message_to_send = json.dumps(message_to_send) print(message_to_send) try: # send the data from the sensor s.send(message_to_send) except: print('timeout in sending') # Turn the light red pycom.rgbled(0x110000) try: data_received = s.recv(64) print(data_received) # Turn the light white pycom.rgbled(0x111111) except: print('nothing received') data_received = "" # Turn the light off pycom.rgbled(0x000000) # regularly check for a new update print("pre if") if data_received: data_received = str(data_received)[2:-1] print("data received : ", data_received, " type : ", type(data_received)) data_dict = json.loads(data_received) print(data_dict) if data_dict["version"] > VERSION: print("if before") my_ota_updater.check_for_update_to_install_during_next_reboot( WIFI_SSID, WIFI_PW) # turn wifi off print("if after") # s.setblocking(False) print("sleep") time.sleep(5)
class LoRa(OutputModule): """ Example of an output module that prints the output to the log. """ def __init__(self): super(LoRa, self).__init__() # check if safety variable is true if not self.config().get("antenna_connected"): raise Exception("configuration variable 'antenna_connected' is not true") # get the reset cause import machine reset_cause = machine.reset_cause() # initialize lora network from network import LoRa as LoRa_drv self.lora = LoRa_drv(mode=LoRa_drv.LORAWAN, region=LoRa_drv.EU868, adr=self.config().get("adr")) # try to load previous lora connection if waking up from deep sleep if reset_cause == machine.DEEPSLEEP_RESET: self.lora.nvram_restore() if reset_cause == machine.DEEPSLEEP_RESET and self.lora.has_joined(): log_info("Restored previous LoRaWAN join.") else: # get authentication parameters import ubinascii app_eui = ubinascii.unhexlify(self.config().get("app_eui")) app_key = ubinascii.unhexlify(self.config().get("app_key")) # join a network using OTAA (Over the Air Activation) self.lora.join(activation=LoRa_drv.OTAA, auth=(app_eui, app_key), timeout=0, dr=self.config().get("data_rate")) # wait until the module has joined the network log_debug("Waiting until LoRa has joined.") while not self.lora.has_joined(): time.sleep(2.5) log_debug("Not joined yet.") log_info("Joined LoRa network.") # create a lora socket to send data import socket self.socket = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate #self.socket.setsockopt(socket.SOL_LORA, socket.SO_DR, self.config().get("data_rate")) # timer variable for measuring time between send commands self.chrono = None def send(self, binary, base64, json, json_base64): # check minimum time between messages min = self.config().get("minimum_time") if min != 0: # first send call if self.chrono == None: log_debug("Starting LoRa sending timer.") # Import timer from machine import Timer import time self.chrono = Timer.Chrono() #Start timer self.chrono.start() else: if self.chrono.read() > min: self.chrono.reset() else: log_debug("Minimal time between LoRa sending not reached, skipping.") return try: # make the socket blocking # (waits for the data to be sent and for the 2 receive windows to expire) if self.config().get("blocking"): self.socket.setblocking(True) # send some data #s.send(bytes([0x01, 0x02, 0x03])) self.socket.send(binary) # make the socket non-blocking # (because if there's no data received it will block forever...) if self.config().get("blocking"): self.socket.setblocking(False) # get any data received (if any...) data = self.socket.recv(64) # TODO activate ota mode # save lora connection self.lora.nvram_save() except: log_error("LoRa send failed!") def test(self): pass def get_config_definition(): return ( "output_lora_otaa", "LoRaWAN output module using OTAA.", ( ("antenna_connected", "false", "This variable is for safety reasons to ensure a antenna is connected before LoRa is initialzed.\nWARNING: Setting this to true without an actual antenna connected can destroy your device!", ConfigFile.VariableType.bool), #("region", "EU868", "Pick the region that matches where you are using the device:\n\tAsia = 'AS923'\n\tAustralia = 'AU915'\n\tEurope = 'EU868'\n\tUnited States = 'US915'", ConfigFile.VariableType.string), ("app_eui", "UNSET", "app eui", ConfigFile.VariableType.string), ("app_key", "UNSET", "app key", ConfigFile.VariableType.string), ("data_rate", "5", "LoRa data rate. Use a value between 0 and 5.", ConfigFile.VariableType.uint), ("adr", "False", "Enables LoRa adaptive data rate. True / False", ConfigFile.VariableType.bool), ("blocking", "true", "Wait for data to be sent before continuing.", ConfigFile.VariableType.bool), ("minimum_time", "0", "Set minimum time between LoRa messages in seconds", ConfigFile.VariableType.uint) ) )
class Comunication: def __init__(self): self.key = b'encriptaincendis' pass # Initialize LoRa in LORAWAN mode. def JoinLoraWan(self): self.lora = LoRa(mode=LoRa.LORAWAN,region=LoRa.EU868) # create an OTA authentication params app_eui = ubinascii.unhexlify('70B3D57ED001C55E') dev_eui = ubinascii.unhexlify('006D2D7767E7BAFE') # these settings can be found from TTN #app_eui = ubinascii.unhexlify('70B3D57ED0019255') # these settings can be found from TTN app_key = ubinascii.unhexlify('0A05862CEA15FC56C047FC03FBDF34DB') # these settings can be found from TTN # set the 3 default channels to the same frequency (must be before sending the OTAA join request) self.lora.add_channel(0, frequency=868100000, dr_min=0, dr_max=5) self.lora.add_channel(1, frequency=868100000, dr_min=0, dr_max=5) self.lora.add_channel(2, frequency=868100000, dr_min=0, dr_max=5) # join a network using OTAA self.lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0) # wait until the module has joined the network while not self.lora.has_joined(): time.sleep(2.5) print('Not joined yet...') # remove all the non-default channels for i in range(3, 16): self.lora.remove_channel(i) # create a LoRa socket self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) # make the socket non-blocking self.s.setblocking(False) time.sleep(5) """ Your own code can be written below! """ def start_LoraRaw(self): self.lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868) self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.s.setblocking(False)#Aquesta instrucció igual sobra time.sleep(5) lora=self.lora #return(lora) def change_txpower(self,power): self.lora.tx_power(power) def savestate(self): self.lora.nvram_save() def Switch_to_LoraRaw(self): self.lora.nvram_save() self.lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868) self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.s.setblocking(False)#Aquesta instrucció igual sobra time.sleep(5) def Switch_to_LoraWan(self): self.lora = LoRa(mode=LoRa.LORAWAN,region=LoRa.EU868) self.lora.nvram_restore() time.sleep(5) #Si no es reinicia el socket el missatge 3 no s'envia self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) def EnviarGateway(self,data): self.s.send(data) time.sleep(5) def sendData(self,msg,rtc,f): f=open('msg_sent_middle2.txt','a') f.write("{}/{}/{} {}:{}:{} msg {} stats {}\n".format(rtc.now()[2],rtc.now()[1],rtc.now()[0],rtc.now()[3],rtc.now()[4],rtc.now()[5],msg,self.lora.stats())) f.close() self.s.setblocking(True) iv = crypto.getrandbits(128) # hardware generated random IV (never reuse it) cipher = AES(self.key, AES.MODE_CFB, iv) misg_crc=msg+" "+str(self.calculate_crc(msg)) msg = iv + cipher.encrypt(misg_crc) self.s.send(msg) self.s.setblocking(False) #print(msg) #print(len(msg)) #time.sleep(5) def reciveData(self,rtc,f): self.s.setblocking(False) msg=self.s.recv(128)#Get any data recieved #If there's any data, decrypt if (len(msg)>0): try: #print("encriptat: ",msg) cipher = AES(self.key, AES.MODE_CFB, msg[:16]) # on the decryption side original = cipher.decrypt(msg[16:]) print("original ",original) if "Config" in original or "stop" in original or "Discover" in original or "Hello" in original or "Info" in original or "Token" in original or "Alarm" in original or "Hay" in original: crc_OK,msg=self.check_crc(original) if crc_OK: f=open('msg_received_middle2.txt','a') f.write("{}/{}/{} {}:{}:{} msg {} stats {}\n".format(rtc.now()[2],rtc.now()[1],rtc.now()[0],rtc.now()[3],rtc.now()[4],rtc.now()[5],msg,self.lora.stats())) f.close() return(msg) else: print("CRC not OK") return("error") else: return("error") except Exception as e: print(e) return("error") else: return("error") def update_neighbours(self,pow,id_n,neighbours): if id_n in neighbours[0]: if pow < neighbours[1][neighbours[0].index(id_n)]: neighbours[1][neighbours[0].index(id_n)]=pow else: neighbours[0].append(id_n) neighbours[1].append(pow) #print("I have a friend ") print(neighbours) return neighbours def neighbours_min(self,neighbours,neighbours_aux): for id in neighbours[0]: if id in neighbours_aux[0]: neighbours[1][neighbours[0].index(id)]=min(neighbours[1][neighbours[0].index(id)],neighbours_aux[1][neighbours_aux[0].index(id)]) print(neighbours) return(neighbours) def ApplyFormat(self,splitmsg): packet_dust= ustruct.pack('f',int(splitmsg[3])) packet_tempC= ustruct.pack('f',int(splitmsg[4])) packet_Tht= ustruct.pack('f',int(splitmsg[5])) packet_Hht= ustruct.pack('H',round(int(splitmsg[6])*100)) packet_tbmp= ustruct.pack('f',int(splitmsg[7])) packet_val= ustruct.pack('H',int(splitmsg[8])) packet_dhi= ustruct.pack('b',int(splitmsg[9])) #+packet_TCam=ustruct.pack('f',int(splitmsg[10])) return(packet_dust+packet_tempC+packet_Tht+packet_Hht+packet_tbmp+packet_val+packet_dhi)#+packet_TCam) def calculate_crc(self,msg): """ Compute CRC """ if type(msg)==bytes: msg=bytes.decode(msg) crc = 0 data=bin(int(binascii.hexlify(msg),16)) data=str.encode(data) for i in range(len(data)): byte = data[i] for b in range(8): fb_bit = (crc ^ byte) & 0x01 if fb_bit == 0x01: crc = crc ^ 0x18 crc = (crc >> 1) & 0x7f if fb_bit == 0x01: crc = crc | 0x80 byte = byte >> 1 return crc def check_crc(self,msg): """ Check if CRC received is correct """ if type(msg)==bytes: msg=bytes.decode(msg) splitmsg=msg.split( ) crc_rcv=int(splitmsg[-1]) aux=" ".join(splitmsg[:-1]) #Not including the CRC received crc_new = self.calculate_crc(aux) return (crc_new==crc_rcv,aux)
class LoRaManager: """ """ def __init__(self, manager, settings): self.manager = manager self.settings = settings # LoRa settings. self.otaa_settings = self.settings.get('networking.lora.otaa') #self.generated_device_eui = binascii.hexlify(LoRa().mac()) def start(self): """ """ self.start_lora_join() def start_lora_join(self): """ """ from network import LoRa if self.otaa_settings['region'] == 'AS923': lora_region = LoRa.AS923 elif self.otaa_settings['region'] == 'AU915': lora_region = LoRa.AU915 elif self.otaa_settings['region'] == 'EU868': lora_region = LoRa.EU868 elif self.otaa_settings['region'] == 'US915': lora_region = LoRa.US915 lora_adr = self.otaa_settings['adr'] or False self.lora_socket = None self.lora = LoRa(mode=LoRa.LORAWAN, region=lora_region, adr=lora_adr) # restore LoRa state from NVRAM after waking up from DEEPSLEEP. Reset LoRa NVRAM and rejoin otherwise if machine.reset_cause() == machine.DEEPSLEEP_RESET: self.lora.nvram_restore() log.info( '[LoRa] LoRaWAN state restored from NVRAM after deep sleep') else: self.lora.nvram_erase() log.info('[LoRa] LoRaWAN state erased from NVRAM. Rejoin forced') # Create LoRaWAN OTAA connection to TTN. app_eui = binascii.unhexlify(self.otaa_settings['application_eui']) app_key = binascii.unhexlify(self.otaa_settings['application_key']) if not self.lora.has_joined(): log.info('[LoRa] joining the network...') if self.otaa_settings.get('device_eui') is None: self.lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) else: dev_eui = binascii.unhexlify(self.otaa_settings['device_eui']) self.lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0) def wait_for_lora_join(self, attempts): """ :param attempts: """ self.lora_joined = None for i in range(0, attempts): while not self.lora.has_joined(): log.info('[LoRa] Not joined yet...') time.sleep(2.5) self.lora_joined = self.lora.has_joined() if self.lora_joined: log.info('[LoRa] joined...') else: log.info('[LoRa] did not join in %s attempts', attempts) return self.lora_joined def create_lora_socket(self): """ """ # create a lora socket self.socket = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.socket.settimeout(6.0) self.lora_socket = True log.info('[LoRa] socket created') return self.lora_socket def lora_send(self, payload): """ :param payload: """ self.socket.setblocking(True) success = self.socket.send(payload) self.socket.setblocking(False) self.lora.nvram_save() return success def lora_receive(self): """ """ import binascii try: rx, port = self.socket.recvfrom(256) except socket.timeout: log.info('[LoRa] no packet received within receive window ') if rx: log.info('[LoRa] Received: {}, on port: {}'.format(rx, port)) return rx, port
class LoRaDriverPycom: """ LoRa driver for Pycom MicroPython """ def __init__(self, network_manager, settings): self.network_manager = network_manager self.settings = settings def start(self): """ Start driver """ from network import LoRa if self.settings.get('networking.lora.region') == 'AS923': lora_region = LoRa.AS923 elif self.settings.get('networking.lora.region') == 'AU915': lora_region = LoRa.AU915 elif self.settings.get('networking.lora.region') == 'EU868': lora_region = LoRa.EU868 elif self.settings.get('networking.lora.region') == 'US915': lora_region = LoRa.US915 lora_adr = self.settings.get('networking.lora.adr') or False self.lora_socket = None self.lora = LoRa(mode=LoRa.LORAWAN, region=lora_region, adr=lora_adr) # Restore LoRa state from NVRAM after waking up from DEEPSLEEP. # Otherwise, reset LoRa NVRAM and rejoin. if platform_info.vendor in [ platform_info.MICROPYTHON.Vanilla, platform_info.MICROPYTHON.Pycom ]: import machine # Restore LoRaWAN status after wake up from deep sleep if machine.reset_cause() == machine.DEEPSLEEP_RESET: self.lora.nvram_restore() log.info( '[LoRa] LoRaWAN state restored from NVRAM after deep sleep' ) # Otherwise reset LoRaWAN status and deep sleep interval from NVRAM else: self.lora.nvram_erase() log.info( '[LoRa] LoRaWAN state erased from NVRAM. Rejoin forced') if platform_info.vendor == platform_info.MICROPYTHON.Pycom: import pycom nvram_get = pycom.nvs_get nvram_erase = pycom.nvs_erase elif platform_info.vendor == platform_info.MICROPYTHON.Vanilla: import esp32 nvram_get = esp32.nvs_get nvram_erase = esp32.nvs_erase try: if nvram_get('deepsleep') is not None: nvram_erase('deepsleep') log.info( '[LoRa] Deep sleep interval erased from NVRAM. Return to settings value' ) except: pass if not self.lora.has_joined(): import binascii # Over-the-Air Activation (OTAA) if self.settings.get('networking.lora.activation') == 'otaa': app_eui = binascii.unhexlify( self.settings.get('networking.lora.otaa.application_eui')) app_key = binascii.unhexlify( self.settings.get('networking.lora.otaa.application_key')) log.info('[LoRa] Attaching to the LoRaWAN network using OTAA') if self.settings.get( 'networking.lora.otaa.device_eui') is None: self.lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) else: dev_eui = binascii.unhexlify( self.settings.get('networking.lora.otaa.device_eui')) self.lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0, dr=0) # Activation by Personalization (ABP) elif self.settings.get('networking.lora.activation') == 'abp': import struct dev_addr = struct.unpack( ">l", binascii.unhexlify( self.settings.get( 'networking.lora.abp.device_address')))[0] nwk_swkey = binascii.unhexlify( self.settings.get( 'networking.lora.abp.network_session_key')) app_swkey = binascii.unhexlify( self.settings.get('networking.lora.abp.app_session_key')) log.info('[LoRa] Attaching to the LoRaWAN network using ABP') self.lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey), timeout=0, dr=0) def ensure_connectivity(self): self.wait_for_join() if self.lora_joined: if self.lora_socket is None: try: self.create_socket() except: log.exception("[LoRa] Could not create LoRa socket") else: log.error("[LoRa] Could not join network") def wait_for_join(self): """ wait for device activation to complete """ self.lora_joined = None while not self.lora.has_joined(): log.info('[LoRa] Not joined yet...') time.sleep( self.settings.get('networking.lora.otaa.join_check_interval', 2.5)) self.lora_joined = self.lora.has_joined() if self.lora_joined: log.info('[LoRa] Joined successfully') else: log.info('[LoRa] Failed to join network') return self.lora_joined def create_socket(self): """ Create socket for LoRa communication """ # create a lora socket self.socket = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.socket.settimeout(6.0) self.lora_socket = True log.info('[LoRa] Socket created') return self.lora_socket def send(self, payload): """ Send a LoRa packet. :param payload: """ self.socket.setblocking(True) success = self.socket.send(payload) self.socket.setblocking(False) self.lora.nvram_save() return success def receive(self): """ Receive a LoRa packet. """ try: rx, port = self.socket.recvfrom(256) except socket.timeout: log.info('[LoRa] No packet received within receive window') if rx: log.info('[LoRa] Received: {} on port: {}'.format(rx, port)) return rx, port
class LoRaHelper: def __init__(self, app_eui_hexstr, app_key_hexstr, debug_led=True, debug_output=True): self._debug = debug_output self._led = debug_led if self._led: pycom.heartbeat(False) pycom.rgbled(0x500000) self._app_eui = binascii.unhexlify(app_eui_hexstr) self._app_key = binascii.unhexlify(app_key_hexstr) self._air_time_base = 0 tmp = pycom.nvs_get('air') if tmp is not None: self._air_time_base = tmp self._air_time = self._air_time_base self._sock = None self._lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) if self._led: pycom.rgbled(0x500000) if self._debug: print('LoRaHelper (debug): LoRa MAC: ' + str(binascii.hexlify(self._lora.mac()))) print('LoRaHelper (debug): Joining network ...') self._lora.join(activation=LoRa.OTAA, auth=(self._app_eui, self._app_key), timeout=0) tmp_on = True while not self._lora.has_joined(): if self._debug: print('LoRaHelper (debug): Joining ...') time.sleep(1) tmp_on = not tmp_on if self._led: if tmp_on: pycom.rgbled(0x502000) else: pycom.rgbled(0x000000) if self._led: pycom.rgbled(0x505000) if self._debug: print('LoRaHelper (debug): LoRaWan network joined!') if self._debug: print('LoRaHelper (debug): Creating socket') self._sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self._sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) if self._led: pycom.rgbled(0x005000) if self._debug: print('LoRaHelper (debug): Creating socket') def mac(self): return binascii.hexlify(self._lora.mac()).upper().decode('utf-8') def has_joined(self): return self._lora.has_joined() def air_time(self): self._air_time = self._air_time_base + self._lora.stats().tx_time_on_air pycom.nvs_set('air', self._air_time) return self._air_time def send(self, data: bytes): if self._sock is None: self._sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self._sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) self._sock.setblocking(True) self._sock.send(data) self._sock.setblocking(False) self._air_time = self._air_time_base + self._lora.stats().tx_time_on_air pycom.nvs_set('air', self._air_time) def recv(self): if self._sock is None: self._sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self._sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) self._sock.setblocking(False) data = self._sock.recv(128) return data
#Setting up channels for sub-band 2 for TTN for index in range(0, 8): lora.remove_channel(index) for index in range(16, 65): lora.remove_channel(index) for index in range(66, 72): lora.remove_channel(index) auth = (bytes([...]), bytes([...])) print("joining...") lora.join(activation=LoRa.OTAA, auth=auth, timeout=0) x = 0 # wait until the module has joined the network while (not lora.has_joined() and x < 10): time.sleep(2.5) print('Not yet joined...') x = x + 1 print(lora.has_joined()) if (lora.has_joined()): # create a LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) lora.remove_channel(65) #drop the 500khz channel for index in range(0, 20): s.send("test1234567")
class LORA(object): 'Wrapper class for LoRa' def __init__(self, dr=2): # LoRa and socket instances # Initialize LoRa in LORAWAN mode self.lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) self.callback = None self.sockets = [] self.dr = dr # socket dr self.LED = None self.debug = False def connect(self, method, ports=1, callback=None, myLED=None, dr=None, debug=False): """ Connect device to LoRa. Set the socket and lora instances. myLED is led object, on resume use lora nvram """ self.callback = callback # call back routine on LoRa reply callback(port,response) self.debug = debug self.LED = myLED if myLED: myLED.heartbeat(False) self.restore sleep_ms(100) if self.lora.has_joined() or self.status: # resume LoRa OTAA or ABP self.getPorts(ports) return True if self.debug: print("No previous LoRa join. Try to join.") if (not type(method) is dict): raise ValueError("No activation method defined.") fnd = False try: if not method['OTAA'][0]: raise ValueError() fnd = True except: try: # OTAA from Config import dev_eui except: from machine import unique_id from ubinascii import hexlify dev_eui = 'AAAA' + hexlify(unique_id()) # use dflt try: from Config import app_eui, app_key method['OTAA'] = (dev_eui, app_eui, app_key) fnd = True except: pass if not fnd: try: if not method['ABP'][0]: raise ValueError() fnd = True except: # ABP try: from Config import dev_addr, nwk_swkey, app_swkey method['ABP'] = (dev_addr, nwk_swkey, app_swkey) fnd = True except: pass if not fnd: raise ValueError("No LoRa keys defined") if self.debug: print("LoRa keys load from Config") count = 0 if self.debug: print("Try to join LoRa/%s" % str(method.keys())) if 'OTAA' in method.keys(): # first OTAA from ubinascii import unhexlify # Join a network using OTAA (Over the Air Activation) next code looks strange dev_eui = method['OTAA'][0] dev_eui = unhexlify(dev_eui) app_eui = method['OTAA'][1] app_eui = unhexlify(app_eui) app_key = method['OTAA'][2] app_key = unhexlify(app_key) self.lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0, dr=dr) # Wait until the module has joined the network if myLED: myLED.blink(4, 2.5, 0x04acf6) else: sleep_ms(10000) while not self.lora.has_joined(): if count > 15: break # machine.reset()? print("Wait for OTAA join: ", count) count += 1 if myLED: myLED.blink(2, 2.5, 0xff0000) else: sleep_ms(5000) if self.lora.has_joined(): count = 1 print("LoRa OTAA join.") else: count = 0 if not count: # if not ABP if not 'ABP' in method.keys(): print("No ABP TTN keys defined.") return False import struct from ubinascii import unhexlify # next code is strange. ABP method is not yet operational dev_addr = method['ABP'][0] dev_addr = unhexlify(dev_addr) dev_addr = struct.unpack('>l', dev_addr)[0] nwk_swkey = method['ABP'][1] nwk_swkey = unhexlify(nwk_swkey) app_swkey = method['ABP'][2] app_swkey = unhexlify(app_swkey) print("LoRa ABP join.") self.lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey)) self.getPorts(ports) if myLED: myLED.blink(2, 0.1, 0x009900) self.dump return True def getPorts(self, ports): # Create a LoRa sockets self.sockets = [] self.sockets.append(socket.socket(socket.AF_LORA, socket.SOCK_RAW)) # Set the LoRaWAN data rate self.sockets[0].setsockopt(socket.SOL_LORA, socket.SO_DR, self.dr) # Make the socket non-blocking self.sockets[0].setblocking(False) # Create a raw LoRa socket # default port 2 self.sockets.append(None) for nr in range(ports): self.sockets.append(socket.socket(socket.AF_LORA, socket.SOCK_RAW)) self.sockets[nr + 2].setblocking(False) if nr: self.sockets[nr + 2].bind(nr + 2) if self.debug: print("Installed LoRa port %d" % (nr + 2)) return True def send(self, data, port=2): """ Send data over the network. """ if (port < 2) or (port > len(self.sockets)): raise ValueError('Unknown LoRa port %d' % port) if not self.sockets[port]: raise OSError('No socket') rts = True try: self.sockets[port].send(data) if self.LED: self.LED.blink(2, 0.1, 0x0000ff) if self.debug: print("Sending data") # print(data) except OSError as e: if e.errno == 11: print("Caught exception while sending") print("errno: ", e.errno) else: print("Lora ERROR: %s" % e) rts = False if self.LED: self.LED.off data = self.sockets[port].recv(64) if self.debug: print("Received data:", data) if self.callback and data: self.callback(port, data) sleep_ms(1000) self.dump # save status return rts @property def dump(self): from time import sleep_ms sleep_ms(2000) if self.debug: print("Save LoRa keys") return self.lora.nvram_save() @property def restore(self): self.lora.nvram_restore() if self.debug: print("Restore LoRa keys") return self.lora.stats().tx_counter @property def status(self): return self.lora.stats().tx_counter @property def clear(self): if self.debug: print("Clear LoRa keys") self.lora.nvram_erase()
# remove all the channels for channel in range(0, 72): lora.remove_channel(channel) # set all channels to the same frequency (must be before sending the OTAA join request) for channel in range(0, 72): lora.add_channel(channel, frequency=config.LORA_FREQUENCY, dr_min=0, dr_max=3) # join a network using OTAA lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0, dr=config.LORA_NODE_DR) # wait until the module has joined the network join_wait = 0 while True: time.sleep(2.5) if not lora.has_joined(): print('Not joined yet...') join_wait += 1 if join_wait == 5: lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0, dr=config.LORA_NODE_DR) join_wait = 0 else: break # 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.LORA_NODE_DR) # make the socket blocking
mac = lora.mac() dev_eui = binascii.hexlify(mac) print ('devEUI: ', dev_eui) # create an OTAA authentication parameters app_eui = binascii.unhexlify('0000000000000000'.replace(' ','')) app_key = binascii.unhexlify('11223344556677881122334490345245'.replace(' ','')) # Acklio lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) pycom.heartbeat(False) # turn led to white pycom.rgbled(0x101010) # white connection_counter = 0 # wait until the module has joined the network while not lora.has_joined() and connection_counter <= 30: time.sleep(2.5) print('Not yet joined...') connection_counter+=1 pycom.rgbled(0x000000) # black s_lora = socket.socket(socket.AF_LORA, socket.SOCK_RAW) s_lora.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) s_lora.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, False) MTU = 200 # Maximun Transmission Unit, for DR 0 should be set to less than 50 # WIFI with IP address s_wifi = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) wlan = network.WLAN(mode=network.WLAN.STA)
print('Main start') # Setup LoRa lora = LoRa(mode=LoRa.LORAWAN, adr=True) app_eui = binascii.unhexlify(config.APP_EUI) app_key = binascii.unhexlify(config.APP_KEY) # join a LoRa network using OTAA lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) # wait until the module has joined the network print('Joining LoRa...') pycom.rgbled(0x0A0000) while not lora.has_joined(): time.sleep(2.5) pycom.rgbled(0) print("LoRa joined") print("LoRa active: ", lora.has_joined()) # create a LoRa socket lora_sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate lora_sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) lora_sock.setblocking(False)
app_eui = binascii.unhexlify(custom_var.app_eui_code2) app_key = binascii.unhexlify(custom_var.app_key_code2) # Imposta i 3 canali di default alla stessa frequenza (must be before sending the OTAA join request) # Non servirebbe con l'attivazione OTAA, inoltre su firmware 1.0.0.b1 getta l'errore "Missing argument(s) value" lora.add_channel(index=0, frequency=868100000, dr_min=0, dr_max=5) lora.add_channel(index=1, frequency=868100000, dr_min=0, dr_max=5) lora.add_channel(index=2, frequency=868100000, dr_min=0, dr_max=5) # Connessione alla rete utilizzando OTAA lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0) # Disattivo la pulsazione del led per poterlo fissare durante la connessione al gateway pycom.heartbeat(False) while not lora.has_joined(): # Riprovo finché non trovo un gateway time.sleep(2.5) print('Gateway... dove sei?') pycom.rgbled(0x7f7f00) # Giallo # Connessione avvenuta, riattivo la normale pulsazione blu pycom.heartbeat(True) # Rimuovo tutti i canali non-predefiniti for i in range(3, 16): lora.remove_channel(i) # Creo un socket LoRa s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate
class LoraController: def __init__(self, options, logger, eventLog, ledController): self.options = options self.logger = logger self.eventLog = eventLog self.led = ledController self.lora = LoRa(mode=LoRa.LORA, power_mode=LoRa.SLEEP) self.tx_runner = None # thread which sends events over lora self.lastJoin = 0 # when did we join the lora network self.isJoinLogged = False # did we log the initial LORA join self.lastEventId = 0 # last sent event id self.sendLock = _thread.allocate_lock() self.socketLock = _thread.allocate_lock() self.isAckingCounter = 0 self.noDownlinkCounter = 0 self.lastUplinkTime = 0 self.isAcking = False # logging def log(self, *text): self.logger.log("LORA", *text) # start lora connectivity def start(self): # setup lorawan self.lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868, device_class=LoRa.CLASS_A, tx_retries=3, adr=True, sf=12) self.lora.nvram_restore() self.lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT | LoRa.TX_FAILED_EVENT), handler=self.lora_callback) self.log('Lora DevEUI is', self.getDeviceEUI()) self.log('Lora AppEUI is', self.options['lora_app_eui']) if len(self.options['lora_app_eui']) != 16: self.log("ERROR", "Setting 'lora_app_eui' is invalid:", self.options['lora_app_eui']) return # issue join if self.options['lora_mode'] == "abp": self.join() elif self.lora.has_joined(): self.log("Lora network is already joined, re-joining anyway") else: self.join() def lora_callback(self, lora): events = lora.events() if events & LoRa.TX_FAILED_EVENT: self.log('Lora TX FAILED') # determines the LORA MAC address (string) def getDeviceEUI(self): return ubinascii.hexlify(self.lora.mac()).decode('ascii').upper() # joins the lora network via OTAA def joinOTAA(self): app_eui = ubinascii.unhexlify(self.options['lora_app_eui']) app_key = ubinascii.unhexlify(self.options['lora_app_key']) self.lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) self.log("Joining via OTAA") self.lastJoin = time.time() # joins the lora network via ABP def joinABP(self): net_key = ubinascii.unhexlify(self.options['lora_net_key']) app_key = ubinascii.unhexlify(self.options['lora_app_key']) # note: TTN seems to want the reverse bytes of this address device_address = ubinascii.unhexlify(self.options['lora_dev_adr']) self.lora.join(activation=LoRa.ABP, auth=(device_address, net_key, app_key)) self.log("Joining via ABP with device address", device_address) self.lastJoin = time.time() # joins the lora network via ABP or OTAA def join(self): if self.options['lora_mode'] == "abp": self.joinABP() else: self.joinOTAA() def hasJoined(self): return self.lora.has_joined() def stats(self): return self.lora.stats() def makePayload(self, event): payload = None command = event['Command'] idbytes = event['ID'].to_bytes(2, 'little') event_ts = event['Time'] try: if command == eventlog.CMD_TAG_DETECTED: # Tag with 4-Byte UID detected # <0x01> <Event ID 0..1> <Timestamp 0..3> <UID 0..3/6/9> timeBytes = event_ts.to_bytes(4, 'little') uid = event['Data'][0:10] # remove trailing 0x00 uid_size = 10 for i in range(uid_size - 1, 3, -1): if uid[i] != 0x00: break uid_size = uid_size - 1 uid = uid[:uid_size] payload = bytes([0x01]) + idbytes + timeBytes + uid uidText = ubinascii.hexlify(uid).decode() self.log("CMD 0x01 [NFC_DETECTED] SEQ#", event['ID'], ". uid =", uidText, ", ts =", event_ts) if command == eventlog.CMD_TIME_REQUEST2: # ask backend for current time (new) # <0x04> <ID 0..1> <Our Time 0..3> mytime = time.time().to_bytes(4, 'little') payload = bytes([command]) + idbytes + mytime self.log("CMD 0x04 [TIME_REQUEST] ID#", event['ID'], ". our_time =", time.time(), utime.gmtime(time.time())) if command == eventlog.CMD_TIME_CHANGED: # <0x05> <Event ID 0..1> <Our Time 0..3> <Old Time 0..3> mytime = event_ts.to_bytes(4, 'little') oldTime = event['Data'][0:4] payload = bytes([eventlog.CMD_TIME_CHANGED ]) + idbytes + mytime + oldTime self.log("CMD 0x05 [TIME_CHANGED] SEQ#", event['ID'], ". our_time =", event_ts, utime.gmtime(event_ts), ", old_time =", oldTime) except Exception as e: self.log("ERROR: Unable to prepare LORA payload:", e.args[0], e) return payload # attempts to send the given event def sendEvent(self, event): with self.sendLock: eventId = event['ID'] command = event['Command'] self.log("Preparing to send CMD =", command, ", SEQ_NO =", eventId) if self.lastEventId > 0 and eventId > self.lastEventId + 1: self.log("ERROR", "Event IDs are not in sequence - last:", self.lastEventId, ", current:", eventId) self.lastEventId = eventId # prepare lora payload for supported event log entries payload = self.makePayload(event) if payload == None: self.log( "WARN: Event payload is None and therefore ignored for lora transmission" ) return True # send payload return self.sendAndHandleResponse(payload) # sends the payload and handles the optional response def sendAndHandleResponse(self, payload): if not self.hasJoined(): self.log("ERROR", "Unable to send LORA payload because not joined") return False # send responseData = self.sendPayload(payload) if responseData == False: self.noDownlinkCounter = self.noDownlinkCounter + 1 return False # handle response if responseData != None and len(responseData) > 0: try: return True except Exception as e: self.log("ERROR: Unable to handle LORA payload: ", e.args[0], e) self.noDownlinkCounter = self.noDownlinkCounter + 1 else: self.noDownlinkCounter = self.noDownlinkCounter + 1 # the message has been sent return True def sendTimeRequest(self, clockSyncEvent, clockSyncRequests): clockSyncEvent['Command'] = eventlog.CMD_TIME_REQUEST2 payload = self.makePayload(clockSyncEvent) try: with self.sendLock: # send lora uplink responseData = self.sendPayload(payload, False) if responseData == False: return None except Exception as e: self.log("ERROR", "Unable to sync clock via LORA:", e.args[0], e) return None # send the specified payload def sendPayload(self, data, updateTime=True): try: with self.socketLock: self.log("> sending", len(data), "bytes:", binascii.hexlify(data)) responseData = None # create a LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) s.setblocking(False) try: """free_memory = gc.mem_free() allocated_memory = gc.mem_alloc() print("Free Memory: " + str(free_memory) + " -- Allocated Memory : " + str(allocated_memory))""" s.send(data) time.sleep(5) responseData = s.recv(64) except Exception as e: self.log("ERROR", "LORA Socket Exception", e) s.close() if responseData != None: responseLen = len(responseData) if responseLen > 0: self.log("< received", responseLen, "bytes:", binascii.hexlify(responseData)) else: self.log("< no downlink") # log if updateTime == True: self.lastUplinkTime = time.time() self.log(self.stats()) time.sleep_ms(10) # save frame counters self.lora.nvram_save() time.sleep_ms(5) return responseData except Exception as e: self.log("ERROR", "Unable to send payload", e.args[0], e) return False
class Node: _thread = None def __init__(self): self.lora = None self.s = None self.py = Pysense() # Instancia de Pysense self.acc = LIS2HH12(self.py) # Instancia del Acelerometro self.last = [0, 0, 0] # Último valor leído de aceleracion self.raw = [0, 0, 0] # Valor leído actual de aceleracion self.busy = 0 # Value has passed limit self.interval = 10 # Intervalo de toma de datos self.battery = None # Valor de la tensión de batería self.alarma = None # Alarma de toma de datos de aceleracion self.s_lock = _thread.allocate_lock() # Semaforo para envío #------------------------------------------------------------------------------# def connect(self, dev_eui, app_eui, app_key, dr=5): """ Connect device to LoRa. Set the socket and lora instances. """ # Disable blue blinking and turn LED off pycom.heartbeat(False) # Initialize LoRa in LORAWAN mode self.lora = LoRa(mode=LoRa.LORAWAN, device_class=LoRa.CLASS_A, region=LoRa.EU868) # Set the 3 default channels to the same frequency (must be before sending the # OTAA join request) self.lora.add_channel(0, frequency=868100000, dr_min=0, dr_max=5) self.lora.add_channel(1, frequency=868100000, dr_min=0, dr_max=5) self.lora.add_channel(2, frequency=868100000, dr_min=0, dr_max=5) # Join a network using OTAA (Over the Air Activation) self.lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0) #login for TheThingsNetwork see here: #https://www.thethingsnetwork.org/forum/t/lopy-otaa-example/4471 # Wait until the module has joined the network while not self.lora.has_joined(): print("Trying to join LoraWAN with OTAA") time.sleep(2.5) print("LoraWAN joined! ") print("Create LoRaWAN socket") self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # Set the LoRaWAN data rate self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, dr) # selecting confirmed type of messages self.s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, True) # Make the socket non-blocking self.s.setblocking(False) #Crea la alarma tras la conexion self.alarma = Timer.Alarm( self.readsens, self.interval, periodic=True) #Alarma de toma de datos de aceleracion #------------------------------------------------------------------------------# def send(self, datalast, dataraw): """ Send data over the network. """ self.s_lock.acquire( ) # Espera a que el semáforo esté disponible (tiempo indefinido) try: data = datalast, dataraw self.s.send(str(data)) time.sleep(2) #Espera para posible recepción rx = self.s.recv(128) #Recepción de datos self.receive(rx=rx) except OSError as e: if e.errno == 11: print("Caught exception while sending") print("errno: ", e.errno) self.s_lock.release() #Libera el semáforo _thread.exit() #Cierra el hilo #------------------------------------------------------------------------------# def receive(self, rx=None): if rx == None: pass else: if rx[0] == 73: #Orden de Cambio de intervalo (ASCII hex I=0x49 dec 73) print("Recibido cambio de intervalo %d" % (int.from_bytes(rx[1:], 'big'))) self.interval = int.from_bytes( rx[1:], 'big') #Decodifica el valor del nuevo intervalo self.alarma.cancel() #Cancela la alarma self.alarma = Timer.Alarm( self.readsens, self.interval, periodic=True ) #Vuelve a crear una alarma para el nuevo intervalo elif rx[0] == 67: #Orden de Cancelación de Lecturas (ASCII hex C=0x43 dec 67) print('Cancela las lecturas') self.alarma.cancel() elif rx[0] == 82: #Orden de Cambio Data Rate (ASCII hex R=0x52 dec 87) dr = int.from_bytes( rx[1:], 'big') #Decodifica el valor del nuevo data Rate self.connect(dr=dr) else: pass #------------------------------------------------------------------------------# #Función de lectura de medidas. El Acelerometro ya ha sido inicializado al #crear la instancia de la clase def readsens(self, alarma): self.raw = self.acc.acceleration( ) # Devuelve tuple con aceleracion en tres ejes (G) print("Aceleracion-> X:%fG Y:%fG Z:%fG" % (self.raw[0], self.raw[1], self.raw[2])) #Cálculos if (self.raw[2] > 1): print("Enviando datos") _thread.start_new_thread( self.send, (self.last, self.raw)) # Se crea un hilo para el envío de valores self._compare_update() self.battery = round(self.py.read_battery_voltage(), 2) if (self.battery < 3.3): print("Batería Crítica") _thread.start_new_thread( self.send, ("Batería", " Crítica" )) # Se crea un hilo para el envío de alarma de batería #------------------------------------------------------------------------------# def _compare_update(self): if self.raw is not self.last: self.last = self.raw else: pass
class LORA(object): 'Wrapper class for LoRa' # LoRa and socket instances lora = None s = None def connect(self, dev_eui, app_eui, app_key, ports=1, callback=None): """ Connect device to LoRa. Set the socket and lora instances. """ dev_eui = unhexlify(dev_eui) app_eui = unhexlify(app_eui) app_key = unhexlify(app_key) self.callback = callback # call back routine on LoRa reply callback(port,response) # Disable blue blinking and turn LED off LED.heartbeat(False) LED.off() # Initialize LoRa in LORAWAN mode self.lora = LoRa(mode=LoRa.LORAWAN) # Join a network using OTAA (Over the Air Activation) self.lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0) # Wait until the module has joined the network count = 0 while not self.lora.has_joined(): LED.blink(1, 2.5, 0xff0000) if count > 20: return False print("Trying to join: ", count) count += 1 # Create a LoRa socket LED.blink(2, 0.1, 0x009900) self.s = [] self.s.append(socket.socket(socket.AF_LORA, socket.SOCK_RAW)) # Set the LoRaWAN data rate self.s[0].setsockopt(socket.SOL_LORA, socket.SO_DR, 5) # Make the socket non-blocking self.s[0].setblocking(False) print("Success after %d tries" % count) # print("Create LoRaWAN socket") # Create a raw LoRa socket # default port 2 self.s.append(None) for nr in range(ports): print("Setting up port %d" % (nr + 2)) self.s.append(socket.socket(socket.AF_LORA, socket.SOCK_RAW)) self.s[nr + 2].setblocking(False) if nr: self.s[nr + 2].bind(nr + 2) LED.off() return True def send(self, data, port=2): """ Send data over the network. """ if (port < 2) or (port > len(self.s)): raise ValueError('Unknown LoRa port') if not self.s[port]: raise OSError('No socket') rts = True try: self.s[port].send(data) LED.blink(2, 0.1, 0x0000ff) # print("Sending data") # print(data) except OSError as e: if e.errno == 11: print("Caught exception while sending") print("errno: ", e.errno) rts = False LED.off() data = self.s[port].recv(64) # print("Received data:", data) if self.callback and data: self.callback(port, data) return rts
class Startiot: def __init__(self): self.dev_eui = binascii.unhexlify("YOUR DEV_EUI") self.app_eui = binascii.unhexlify("YOUR APP_EUI") self.app_key = binascii.unhexlify("YOUR APP_KEY") self.lora = LoRa(mode=LoRa.LORAWAN) def connect(self, timeout=0, function=None, blocking=False): self.lora.nvram_restore() if not self.lora.has_joined(): # No saved connetion state pycom.rgbled(0x0f0000) self.lora.join(activation=LoRa.OTAA, auth=( self.dev_eui, self.app_eui, self.app_key), timeout=0) if timeout == 0: while not self.lora.has_joined(): if function == None: sleep(2.5) else: function() else: for x in range(timeout): if self.lora.has_joined(): break if function == None: sleep(2.5) else: function() if not self.lora.has_joined(): return False pycom.rgbled(0x000000) else: # Connection state restored pycom.rgbled(0x0000ff) pass self.lora.nvram_save() self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) # set the LoRaWAN data rate self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) # make the socket non-blocking self.s.setblocking(blocking) pycom.rgbled(0x000000) return True def send(self, data): self.s.setblocking(True) self.s.send(data) def recv(self, length=64): self.s.setblocking(False) return self.s.recv(length)
def main(): pycom.heartbeat(False) # Sensor initializations with default params # bus = 1 # sda = P10 # scl = P11 # baud = 20000 # interval = 10 pm_sensor = sps30() if using_pm else None co2_sensor = scd30() if using_co2 else None # Start sensors in a separate thread pm_thread = _thread.start_new_thread(pm_sensor.start, ()) if using_pm else None co2_thread = _thread.start_new_thread(co2_sensor.start, ()) if using_co2 else None # Prepare LoRa channels lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.US915, device_class=LoRa.CLASS_C) prepare_channels(lora, LORA_FREQUENCY) #lora = LoRa(mode=LoRa.LORA, region=LoRa.US915, frequency=904600000, bandwidth=LoRa.BW_500KHZ, sf=8) # Join LoRa network with OTAA lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_key, nwk_key), timeout=0, dr=0) # wait until the module has joined the network print('Over the air network activation ... ', end='') while not lora.has_joined(): time.sleep(2.5) print('.', end='') print('') # Socket initializations lora_socket = socket.socket(socket.AF_LORA, socket.SOCK_RAW) lora_socket.setsockopt(socket.SOL_LORA, socket.SO_DR, LORA_DR) # msg are confirmed at the FMS level lora_socket.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, False) # make the socket non blocking by default lora_socket.setblocking(False) lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT | LoRa.TX_FAILED_EVENT), handler=lora_cb) time.sleep(4) # this timer is important and caused me some trouble ... # Send pm (payload=40bytes) and co2 (payload=12bytes) data every 5 minutes while True: # Poll data if using_pm: pm_data = pm_sensor.get_packed_msg() if using_co2: co2_data = co2_sensor.get_packed_msg() if using_pysense_sensor: py = Pysense() mp = MPL3115A2( py, mode=ALTITUDE ) # Returns height in meters. Mode may also be set to PRESSURE, returning a value in Pascals si = SI7006A20(py) lt = LTR329ALS01(py) li = LIS2HH12(py) # Send data if using_pm: send_pkt(lora_socket, pm_data, 8) if using_co2: send_pkt(lora_socket, co2_data, 9) if using_pysense_sensor: temp = si.temperature() rh = si.humidity() rlux = lt.light()[0] blux = lt.light()[1] pysense_pkt = struct.pack('<ffii', temp, rh, rlux, blux) send_pkt(lora_socket, pysense_pkt, 10) time.sleep(15 - using_pm * 5 - using_co2 * 5 - using_pysense_sensor * 5) # Stop polling and end threads if using_pm: pm_sensor.stop() if using_co2: co2_sensor.stop()
# set the LoRaWAN data rate s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) # selecting confirmed type of messages # s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, True) # Sets the socket timeout value in seconds. Accepts floating point values. #s.settimeout(60) # make the socket blocking # (waits for the data to be sent and for the 2 receive windows to expire) s.setblocking(True) #init_timer = time.time() if lora.has_joined() == True: print('LoRaWAN Joined...') else: print('LoRaWAN No Network Connection...') while (True): lpp = CayenneLPP() # time-counter configurations #final_timer = time.time() #diff = final_timer - init_timer print('\n\n** 3-Axis Accelerometer (LIS2HH12)') print('Acceleration', accelerometer.acceleration()) print('Roll', accelerometer.roll()) print('Pitch', accelerometer.pitch()) lpp.add_accelerometer(2, accelerometer.acceleration()[0], accelerometer.acceleration()[1], accelerometer.acceleration()[2])
# app_swkey = binascii.unhexlify("") # removed before uploading it to github app_eui = binascii.unhexlify('') # removed before uploading it to github app_key = binascii.unhexlify('') # removed before uploading it to github g_tx_power = 14 g_data_rate = 0 # sf = 12 g_coding_rate = 1 g_lambda_ = 1 g_pkt_length = 10 paq_bytes = None g_counter = -1 g_keep_alive_counter = 0 lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868, adr=False) lora.nvram_restore() if lora.has_joined(): print('Joining not required') lora.callback(trigger=LoRa.RX_PACKET_EVENT, handler=packet_received_hd) lora.nvram_save() else: print('Joining for the first time') lora = create_lora_adr(handler=packet_received_hd, app_eui=app_eui, app_key=app_key) lora.nvram_save() s = create_socket_adr() while True: set_tx_power(lora, tx_power=14) s.send(bytes([0x01, 0x02, 0x03, 0x04, 0x05]))
class LoRaNetwork: def __init__(self): # Turn off hearbeat LED pycom.heartbeat(False) # Initialize LoRaWAN radio self.lora = LoRa(mode=LoRa.LORAWAN) # Connect to sensors. #wlan = WLAN(mode=WLAN.STA) # Uncomment next line to disable wifi #wlan.deinit() # go for fixed IP settings (IP, Subnet, Gateway, DNS) # Set network keys app_eui = binascii.unhexlify('70B3D57EF0003F19') app_key = binascii.unhexlify('0EFCC322B67F7BC848E683AD0A27F64A') # Join the network self.lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) #pycom.rgbled(red) # Loop until joined while not self.lora.has_joined(): print('Not joined yet...') pycom.rgbled(off) time.sleep(0.1) #pycom.rgbled(red) pycom.rgbled(red) time.sleep(0.1) pycom.rgbled(green) time.sleep(0.1) pycom.rgbled(blue) time.sleep(0.1) pycom.rgbled(off) time.sleep(2) print('Joined') #pycom.rgbled(blue) self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) self.s.setblocking(True) self.bytesarraytemp = bytearray(2) #sensor addr = 0x20 #or 32 self.chirp = Chirp(addr) def convertbytes(self, data): self.bytesarraytemp[0] = (data & 0xFF00) >> 8 self.bytesarraytemp[1] = (data & 0x00FF) return self.bytesarraytemp def senddata(self): while True: print("temp") print(self.chirp.temp()) count = self.s.send(tempVar + self.convertbytes(self.chirp.temp())) #print(count) print("moist") globalMoist = self.chirp.moist() print(globalMoist) count = self.s.send(moistVar + self.convertbytes(self.chirp.moist())) #print(count) print("light") print(self.chirp.light()) count = self.s.send(lightVar + self.convertbytes(self.chirp.light()))
import pycom # Base library for Pycom devices import socket # Needed to connect two nodes on a network to communicate with each other import time # Allows use of time.sleep() for delays import binascii # Allows convertion between binary and various ASCII-encoded binary representations # Setting up Lora application lora = LoRa(mode=LoRa.LORAWAN) app_eui = binascii.unhexlify('70B3D57ED0026466') # application EUI app_key = binascii.unhexlify( '0866572ED4A888E46BE5B9BF0084118F') # application KEY lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0) # connect to the application # make a connection to TTN network while not lora.has_joined(): time.sleep(2.5) print('Not joined yet...') pycom.heartbeat( False) # Disable the on-board heartbeat (blue flash every 4 seconds) pycom.rgbled(0xffc0cb) # Sets RGB to a weird pink while not connected print('Network joined!') # Prints network joined when network is joined pycom.rgbled(0x00ff00) # Sets RGB to green when connected py = Pysense() mp = MPL3115A2( py, mode=ALTITUDE ) # Sensor returns height in meters. Mode may also be set to PRESSURE si = SI7006A20(py) # Sensor returns temperature in C lt = LTR329ALS01(py) # Sensor returns ambient light in lux
# create an OTA authentication params dev_eui = binascii.unhexlify('007FFD9B1D113123'.replace(' ','')) app_eui = binascii.unhexlify('70B3D57EF0005B3B'.replace(' ','')) app_key = binascii.unhexlify('950942111D56A3812CAE94A0DD5048D9'.replace(' ','')) # set the 3 default channels to the same frequency (must be before sending the OTAA join request) lora.add_channel(0, frequency=868100000, dr_min=0, dr_max=5) lora.add_channel(1, frequency=868100000, dr_min=0, dr_max=5) lora.add_channel(2, frequency=868100000, dr_min=0, dr_max=5) # join a network using OTAA lora.join(activation=LoRa.OTAA, auth=(dev_eui, app_eui, app_key), timeout=0) # wait until the module has joined the network while not lora.has_joined(): time.sleep(2.5) print('Not joined yet...') # remove all the non-default channels for i in range(3, 16): lora.remove_channel(i) # 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) # make the socket blocking s.setblocking(False)