#corresponding real values dev_addr = struct.unpack(">l", binascii.unhexlify('00000000'))[0] nwk_swkey = binascii.unhexlify('00000000000000000000000000000000') app_swkey = binascii.unhexlify('00000000000000000000000000000000') 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)
from network import LoRa import socket import machine import time import messageLoRa from messageLoRa import messageLoRa from machine import Timer lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868) s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) s.setblocking(False) print(lora.frequency()) lora.frequency(868000000) print(lora.frequency())
class IN: global isListening id=1 timer=0 data=42 tryDiscover=0 tryRegister=0 discovered=False registered=False ack_Data=False frequency=1.0 slot=10 myLoRa=-1 tryDataReq=-1 clock=None sock=None listeningTime=10.0 def __init__(self,id,frequency,slot): # create an OTAA authentication parameters self.lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868) self.sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.sock.setblocking(False) self.id=id self.timer=0 self.data=42 self.tryDiscover=0 self.tryRegister=0 self.discovered=False self.registered=False self.ack_Data=False self.frequency=1.0 self.slot=slot self.myLoRa=-1 self.tryDataReq=0 self.isListening=True self.listeningTime=10.0 pycom.heartbeat(False) pycom.rgbled(0xff00) def start(self): #ecrire le maion global isListening while True: if isListening: #print("I am awake : my LoRaGW is "+str(myLoRa)+" and my slot is "+str(slot)) pycom.rgbled(0x007f00) # green try: #We are not discovered yet while not self.discovered: self.notDiscovered() rnd=self.Random() print("Try Discover in "+str(rnd)) time.sleep(rnd) while not self.registered and self.discovered: self.notRegistered() rnd=self.Random() print("Try Register in "+str(rnd)) time.sleep(rnd) dataR=self.sock.recv(128) msg =messageLoRa() msg.fillMessage(dataR) if msg.kind=="4" and msg.id_dest == str(self.id): self.sendData() print("I sent my data") print("I try to change my slot and listening time") self.slot=float(msg.slots) self.listeningTime=float(msg.listeningtime) #slot d'une duree de 40 seconde isListening=False #if self.clock = None : # del self.clock self.clock = TimerL(self.slot,1) toto=False except OSError as err: print("OS error: {0}".format(err)) #except err: # print("EAGAIN error: {0}".format(err)) else: pycom.rgbled(0x7f0000) #red try: print("my slot is :"+str(self.slot)) print("I am sleeping") time.sleep(self.slot) del self.clock self.clock = TimerL(self.listeningTime,2) isListening=True except OSError as err: print("OS error: {0}".format(err)) except err: print("EAGAIN error: {0}".format(err)) def Random(self): result = ((uos.urandom(1)[0] / 256 )*3)+2 return result def change_frequency(self,frequency_d): current_frequency=self.lora.frequency() if current_frequency != frequency_d: print("FREQUENCY WAS CHANGED FROM :"+str(current_frequency)+" TO= ") if frequency_d == 1: self.lora.frequency(868000000) print("868000000") if frequency_d == 2: self.lora.frequency(868100000) print("868100000") if frequency_d == 3: self.lora.frequency(868300000) print("868300000") if frequency_d == 4: self.lora.frequency(868500000) print("868500000") if frequency_d == 5: self.lora.frequency(864100000) print("864100000") if frequency_d == 6: self.lora.frequency(864300000) print("864300000") if frequency_d == 7: self.lora.frequency(864500000) print("864500000") class TimerL: def __init__(self,timing,kind): self.seconds = 0 if kind == 1: self.__alarm = Timer.Alarm(self._first_handler, timing, periodic=True) else: self.__alarm = Timer.Alarm(self._seconds_handler, timing, periodic=True) def _first_handler(self, alarm): global isListening alarm.cancel() # stop it isListening=True def _seconds_handler(self, alarm): global isListening alarm.cancel() # stop it isListening=False def notDiscovered(self): #print("PHASE NOT DISCOVERED STARTED "+str(tryDiscover)) self.sock.send('Discover,'+str(1)+','+str(self.frequency)+','+str(self.slot)+','+str(self.id)+','+str(-1)+','+str(-1)+','+str(-1)) print("Discover sent by "+str(self.id)) data=self.sock.recv(128) msg =messageLoRa() msg.fillMessage(data) #print("dest ==="+str(msg.get_dest())) if msg.messageName == "Accept" and msg.id_dest == str(self.id): self.myLoRa=msg.id_src self.frequency=msg.frequency self.change_frequency(msg.frequency) print("Receive ACCEPT msg") self.discovered=True else: time.sleep(1) self.tryDiscover+=1 #print("PHASE NOT DISCOVERED ENDED\n") def notRegistered(self): #send some data #print("PHASE NOT REGISTERED STARTED\n") self.sock.send('Register,'+str(3)+','+str(self.frequency)+','+str(self.slot)+','+str(self.id)+','+str(self.myLoRa)+','+str(-1)+','+str(-1)) print("Register sent") # get any data received... data=self.sock.recv(128) msg =messageLoRa() msg.fillMessage(data) if msg.messageName == "DataReq" and msg.id_src== self.myLoRa and msg.id_dest == str(self.id): self.registered=True else: self.tryRegister+=1 #print("PHASE NOT REGISTERED ENDED\n") def sendData(self): #send some data #print("PHASE SEND DATA STARTED\n") #print('DataRes,'+str(5)+','+str(frequency)+','+str(slot)+','+str(id)+','+str(myLoRa)+','+str(data)+','+str(70)) self.sock.send('DataRes,'+str(5)+','+str(self.frequency)+','+str(self.slot)+','+str(self.id)+','+str(self.myLoRa)+','+str(self.data)+','+str(70)) #time.sleep(20) print("DataResponse sent")
from network import LoRa import socket import binascii import struct import pycom import time import config import machine from machine import Pin pycom.heartbeat(False) pycom.rgbled(0x1f0000) # red # initialize LoRa in LORAWAN mode. lora = LoRa(mode=LoRa.LORAWAN) lora.frequency(915000000) lora.bandwidth(LoRa.BW_125KHZ) # create an OTA authentication params dev_eui = binascii.unhexlify('11 AA BB 22 33 44 FF 88'.replace(' ', '')) app_eui = binascii.unhexlify('70 B3 D5 7E D0 00 7C 77'.replace(' ', '')) app_key = binascii.unhexlify( '77 E5 80 10 2E 70 5D 1D 59 AA AF 62 4E F7 98 72'.replace(' ', '')) # set the 3 default channels to the same frequency (must be before sending the OTAA join request) #lora.add_channel(0, frequency=915000000, dr_min=0, dr_max=3) #lora.add_channel(1, frequency=915000000, dr_min=0, dr_max=3) #lora.add_channel(2, frequency=915000000, dr_min=0, dr_max=3) # remove all the channels for channel in range(0, 72):
from network import LoRa import socket import machine import time # initialise LoRa in LORA 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 # more params can also be given, like frequency, tx power and spreading factor lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868) lora.frequency(868100000) lora.coding_rate(LoRa.CODING_4_5) lora.sf(7) lora.bandwidth(LoRa.BW_125KHZ) # create a raw LoRa socket s = socket.socket(socket.AF_LORA, socket.SOCK_RAW) while True: # send some data s.setblocking(True) s.send('Hello') # get any data received... s.setblocking(False) data = s.recv(64) print(data)
try: 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())
class LGW: lora = None sock = None app_eui = None app_key = None dev_eui = None id = -1 timer = 0 NbIN = 0 idRegistered = [] isRegistered = [] frequency = 1 discovered = False slot = 10 MyLW = 0 nb_harvest = 0 listeningTime = 10.0 data = 666 def __init__(self,app_eui,app_key,dev_eui,id,frequency,slot): # create an OTAA authentication parameters self.app_eui=binascii.unhexlify(app_eui) self.app_key=binascii.unhexlify(app_key) self.dev_eui=binascii.unhexlify(dev_eui) self.lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) self.id=id self.frequency=frequency self.slot=slot #self.isListening=True pycom.heartbeat(False) pycom.rgbled(0xff00) def start(self): global isListening # join a network using OTAA (Over the Air Activation) self.lora.join(activation=LoRa.OTAA, auth=(self.dev_eui,self.app_eui,self.app_key), timeout=0) # wait until the module has joined the network while not self.lora.has_joined(): time.sleep(2.5) print('Not yet joined...') print('Connected to Objenious LoRaWAN!') self.sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) self.sock.setblocking(True) # send some data self.sock.send(bytes([0x01, 0x02, 0x03])) # make the socket non-blocking # (because if there's no data received it will block forever...) self.sock.setblocking(False) self.changetoLoRa() time.sleep(2.5) clock = TimerL(self.slot,2) while True: if isListening: try: pycom.rgbled(0x007f00) # green data = self.sock.recv(128) self.handle_message(data) time.sleep(1.500) self.handle_message(data) time.sleep(1.500) recolte=self.standard() time.sleep(1.500) if recolte !="" : #[BEGIN] sending data from IN attached to me deveui_custom=[] data_custom=[] print("first split") devices=recolte.split(":") for deviceIN in devices: print(deviceIN) print("second split") device_custom,data_custom=deviceIN.split(",") print(device_custom) print(data_custom) self.change_AND_send_toLW(device_custom, data_custom) #[END] sending data from IN attached to me time.sleep(1.500) self.changetoLW() time.sleep(1.500) self.sock.setblocking(True) #print(recolte) time.sleep(2) self.send_datatoLWGW(str(self.data)) self.changetoLoRa() self.sock.setblocking(False) except OSError as err: print("OS error: {0}".format(err)) #except EAGAIN as err: # print("EAGAIN error: {0}".format(err)) else: pycom.rgbled(0x7f0000) #red try: print("I am sleeping") time.sleep(self.slot) del clock clock = TimerL(self.listeningTime,2) isListening=True except OSError as err: print("OS error: {0}".format(err)) #except EAGAIN as err: # print("EAGAIN error: {0}".format(err)) def Random(self): result = ((uos.urandom(1)[0] / 256 )*3)+2 return result def change_frequency(self,frequency_d): current_frequency=self.lora.frequency() if current_frequency != frequency_d: print("FREQUENCY WAS CHANGED FROM :"+str(current_frequency)+" TO= ") if frequency_d == 1: self.lora.frequency(868000000) print("868000000") if frequency_d == 2: self.lora.frequency(868100000) print("868100000") if frequency_d == 3: self.lora.frequency(868300000) print("868300000") if frequency_d == 4: self.lora.frequency(868500000) print("868500000") if frequency_d == 5: self.lora.frequency(864100000) print("864100000") if frequency_d == 6: self.lora.frequency(864300000) print("864300000") if frequency_d == 7: self.lora.frequency(864500000) print("864500000") else: print("FREQUENCY ALREADY CHANGED") def change_AND_send_toLW(self, devEUI_custom, data_custom): #print("FONCTION CHANGE TO LW 1") self.lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) #print("FONCTION CHANGE TO LW 2 "+str(app_eui)+str(app_key)+str(dev_eui)) self.lora.join(activation=LoRa.OTAA, auth=(binascii.unhexlify(devEUI_custom), self.app_eui, self.app_key), timeout=0) #print("FONCTION CHANGE TO LW 3") while not self.lora.has_joined(): print('CtLW : Not yet joined... as '+str(devEUI_custom)) time.sleep(2.5) print('Connected to Objenious LoRaWAN again ! as '+str(devEUI_custom)) self.sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) data=data_custom taille=str(len(data))+'s' databytes = struct.pack(taille, data) self.sock.setblocking(True) self.sock.send(databytes) self.sock.setblocking(False) data="" time.sleep(1.5) def changetoLW(self): #print("FONCTION CHANGE TO LW 1") self.lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868) #print("FONCTION CHANGE TO LW 2 "+str(app_eui)+str(app_key)+str(dev_eui)) self.lora.join(activation=LoRa.OTAA, auth=(self.dev_eui, self.app_eui, self.app_key), timeout=0) #print("FONCTION CHANGE TO LW 3") while not self.lora.has_joined(): print('LGW : Not yet joined...') time.sleep(2.5) print('Connected to Objenious LoRaWAN again !') self.sock = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.sock.setsockopt(socket.SOL_LORA, socket.SO_DR, 5) def changetoLoRa(self): self.lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868) print('Radio mode is LoRa now !') time.sleep(5) def send_datatoLWGW(self,dataString): data=dataString taille=str(len(data))+'s' databytes = struct.pack(taille, data) self.sock.send(databytes) data="" time.sleep(1.500) def pairing_phase(self,msg): #print("PAIRING PHASE WITH "+str(msg.id_src)+" STARTED") self.sock.send('Accept,'+str(2)+','+str(self.frequency)+','+str(self.slot)+','+str(self.id)+','+str(msg.id_src)+','+str(-1)+','+str(self.slot*3)) if msg.id_src in self.idRegistered: print("Added before") else: self.idRegistered.append(msg.id_src) #print("PAIRING PHASE WITH "+str(msg.id_src)+" ENDED") def registering_phase(self,msg): #print("REGISTERING PHASE WITH "+str(msg.id_src)+" STARTED") if msg.id_src in self.idRegistered: self.sock.send('DataReq,'+str(4)+','+str(self.frequency)+','+str(self.slot)+','+str(self.id)+','+str(msg.id_src)+','+str(-1)+','+str(self.slot*3)) if msg.id_src in self.isRegistered: print("Added before") else: self.isRegistered.append(msg.id_src) #print("REGISTERING PHASE WITH "+str(msg.id_src)+" ENDED") def ack_data(self,msg): #print("STANDARD PHASE STARTED") #global slot print("I received data : "+str(msg.data)) self.sock.send('ack,'+str(4)+','+str(self.frequency)+','+str(self.slot)+','+str(id)+','+str(self.msg.id_src)+','+str(-1)+','+str(self.slot*3)) #print("STANDARD PHASE ENDED") def standard(self): print("STANDARD PHASE STARTED") data_sum="" for idDest in self.isRegistered: print(idDest) print('DataReq,'+str(4)+','+str(self.frequency)+','+str(self.slot)+','+str(self.id)+','+str(idDest)+','+str(-1)+','+str(self.slot*3)) self.sock.send('DataReq,'+str(4)+','+str(self.frequency)+','+str(self.slot)+','+str(self.id)+','+str(idDest)+','+str(-1)+','+str(self.slot*3)) dataHarvested = self.sock.recv(128) msgH =messageLoRa() msgH.fillMessage(dataHarvested) rnd=self.Random() print("[FIRST Send] for "+str(idDest)+" Request data in "+str(rnd)) print(dataHarvested) time.sleep(rnd) while msgH.id_src != str(idDest) or msgH.id_dest != str(self.id) or msgH.kind != "5" or msgH.messageName != "DataRes": rnd=self.Random() print("[Try] for "+str(idDest)+" send Request data in "+str(rnd)) time.sleep(rnd) self.sock.send('DataReq,'+str(4)+','+str(self.frequency)+','+str(self.slot)+','+str(self.id)+','+str(idDest)+','+str(-1)+','+str(self.slot*3)) dataHarvested = self.sock.recv(128) msgH =messageLoRa() msgH.fillMessage(dataHarvested) print("msg data =========>"+dataHarvested.decode()) data_sum=data_sum+str(idDest)+","+str(msgH.data)+":" data_sum=data_sum[:-1] print("STANDARD PHASE ENDED") return data_sum def handle_message(self,data): msg =messageLoRa() msg.fillMessage(data) print(data) #time.sleep(5) if msg.kind == "1": self.pairing_phase(msg) else: print(msg.kind ) if msg.kind == "3" and msg.id_dest == str(self.id): self.registering_phase(msg) if msg.kind == "3" and msg.id_dest != str(self.id): if msg.id_src in idRegistered: self.idRegistered.remove(msg.id_src) print("Delete ID:"+str(msg.id_src)+"from the table idRegistered")
# Set AU ISM 915 channel plan for TTN Australia for index in range(0, 7): lora.add_channel(index, frequency=923300000 + index * 600000, dr_min=0, dr_max=3) for index in range(8, 15): lora.add_channel(index, frequency=915200000 + index * 200000, dr_min=0, dr_max=3) lora.add_channel(65, frequency=917500000, dr_min=4, dr_max=4) lora.frequency(config.LORA_FREQUENCY) #Join TTN Network via 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(): pycom.rgbled(0x0f0f00) #yellow time.sleep(5) print('Trying to join TTN Network!') pass print('Network joined!') pycom.rgbled(0x000f00) #green #setup i2c internface
class LORAWAN(object): """ Class to sent messages via LORAWAN network. """ def __init__(self, mode=LoRa.LORAWAN, activation=LoRa.OTAA, region=LoRa.EU868, data_rate=5, join_timeout=0, tx_retries=3, adr=True, public=True, device_class=LoRa.CLASS_A, app_eui=None, app_key=None, dev_addr=None, nwk_swkey=None, app_swkey=None): # OTAA authentication parameters if activation == LoRa.OTAA: if app_eui: self.__app_eui = binascii.unhexlify(app_eui.replace(' ', '')) if app_key: self.__app_key = binascii.unhexlify(app_key.replace(' ', '')) # ABP authentication parameters if activation == LoRa.ABP: if dev_addr: self.__dev_addr = binascii.unhexlify(dev_addr.replace(' ', '')) if nwk_swkey: self.__nwk_swkey = binascii.unhexlify( nwk_swkey.replace(' ', '')) if app_swkey: self.__nwk_appkey = binascii.unhexlify( app_swkey.replace(' ', '')) self.__join_timeout = join_timeout * 1000 self.__data_rate = data_rate self.__activation = activation self.__lora = None self.__socket = None self.__mode = mode self.__lora = LoRa(mode=mode, region=region, adr=adr, public=public, tx_retries=tx_retries, device_class=device_class) # Restore self.__lora.nvram_restore() time.sleep(1) log.debug('Device EUI: {}', binascii.hexlify(self.__lora.mac()).upper().decode('utf-8')) log.debug('Frequency: {}', self.__lora.frequency()) def start(self): """ Start the LORAWAN connection """ try: # When device isn't joined if not self.__lora.has_joined(): # Join network using OTAA if self.__activation == LoRa.OTAA: log.debug('Join network using OTAA') self.__lora.join(activation=LoRa.OTAA, auth=(self.__app_eui, self.__app_key), timeout=self.__join_timeout) while not self.__lora.has_joined(): log.debug('Wait for joining LoRa network...') time.sleep(2.5) # Join network using ABP if self.__activation == LoRa.ABP: log.debug('Join network using ABP') self.__lora.join(activation=LoRa.ABP, auth=(self.__dev_addr, self.__nwk_swkey, self.__nwk_appkey), timeout=self.__join_timeout) except Exception as e: log.error('Exception {} accesssing or joining LoRa network', e) def send_str(self, message=None): 'Send the message' self.__socket = socket.socket(socket.AF_LORA, socket.SOCK_RAW) self.__socket.setsockopt(socket.SOL_LORA, socket.SO_DR, self.__data_rate) if self.__lora and self.__socket: # make the socket blocking # (waits for the data to be sent and for the 2 receive windows to expire) self.__socket.setblocking(True) try: if message: log.debug('Send: ', message) self.__socket.send(message) self.__lora.nvram_save() time.sleep(1) except OSError as e: log.error('OSError {}', e) self.__lora.nvram_erase() time.sleep(1) # make the socket non-blocking # (because if there's no data received it will block forever...) self.__socket.setblocking(False) def receive(self): 'Receive a message' if self.__socket: # get any data received (if any...) data = self.__socket.recv(64) return data def stop(self): ' Stop the LORAWAN connection' log.debug('Stop the LORAWAN connection') if self.__socket: self.__socket.close() self.__socket = None