Ejemplo n.º 1
0
def create_lora_abp(tx_power = 14, coding_rate = 1):
    assert 2 <= tx_power <= 14
    assert 1 <= coding_rate <= 4

    lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868, adr = False)
    lora.tx_power(tx_power)    # from 2 to 14
    lora.coding_rate(coding_rate) # 1 = 4/5, 2 = 4/6, 3 = 4/7, 4 = 4/8
    lora.callback(trigger=LoRa.RX_PACKET_EVENT, handler=update_tx_params_cb)
    lora.join(activation=LoRa.ABP, auth=(dev_addr, nwk_swkey, app_swkey))
    return lora
Ejemplo n.º 2
0
def create_lora(handler, app_eui, app_key, tx_power = 14, coding_rate = 1):
    assert 2 <= tx_power <= 14
    assert 1 <= coding_rate <= 4

    lora = LoRa(mode=LoRa.LORAWAN, region=LoRa.EU868, adr = False)
    lora.tx_power(tx_power)    # from 2 to 14
    lora.coding_rate(coding_rate) # 1 = 4/5, 2 = 4/6, 3 = 4/7, 4 = 4/8
    lora.callback(trigger=LoRa.RX_PACKET_EVENT, handler=handler)
    lora.join(activation=LoRa.OTAA, auth=(app_eui, app_key), timeout=0, dr=0)

    while not lora.has_joined():
        time.sleep(2.5)
        print("Waiting for lora to join")

    return lora
Ejemplo n.º 3
0
import ubinascii
import pycom
import machine

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
Ejemplo n.º 4
0
class Comunication:
    def __init__(self):
        self.key = b'encriptaincendis'
        self.node_list = ""
        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. DR5 means 5470 bits/s ans max payload=230
        self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)

        # make the socket non-blocking
        self.s.setblocking(False)

        time.sleep(5)

    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(2.5)
        #Si no es reinicia el socket
        self.s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)
        self.s.setsockopt(socket.SOL_LORA, socket.SO_DR, 5)
        self.s.setsockopt(socket.SOL_LORA, socket.SO_CONFIRMED, False)

    def EnviarGateway(self, data):
        self.s.bind(2)
        self.s.send(data)
        time.sleep(10)

    def sendData(self, msg, rtc, f):
        if "Hay" not in msg:
            f = open('msg_sent_final.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)
        #print("missatge amb crc", 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:
                        if "Hay" not in msg:
                            f = open('msg_received_final.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")
                    print("Keyword not in msg")
            except:
                return ("error")
                print("Exception")
        else:
            return ("error")
            print("Empty msg")

    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, id):
        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('H',
                                   int(splitmsg[3]))  #Unsigned short 2 bytes
        packet_tempC = ustruct.pack('H', int(splitmsg[4]))
        packet_Tht = ustruct.pack('H', int(splitmsg[5]))
        packet_Hht = ustruct.pack(
            'B', round(int(splitmsg[6]) *
                       100))  #Form 0 to 1 -> 0% to 100% #Unsigned char 1 byte
        packet_tbmp = ustruct.pack('H', 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]))
        #id=splitmsg[1].encode('utf-8')
        id_aux = ustruct.pack('>Q', int(splitmsg[1], 16))  #long long: 8 bytes
        return (packet_dust + packet_tempC + packet_Tht + packet_Hht +
                packet_tbmp + packet_val + packet_dhi + id_aux)  #+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)

    def get_node_list(self, list):
        self.node_list = list
Ejemplo n.º 5
0
class Comunication:
    def __init__(self):
        self.key = b'encriptaincendis'
        pass

    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 sendData(self,msg,rtc,f):
        if "Hay" not in msg:
            f=open('/sd/msg_sent_middle1.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:
                        if "Hay" not in msg:
                            f=open('/sd/msg_received_middle1.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 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)
Ejemplo n.º 6
0
	def __init__(self,bandwidth=0, sf=7, buffersize=64, preamble=8, fichier='img.py',power=14,coding=1,timeout=0.5,maxretry=10):
		#super(Send, self).__init__()
		#self.arg = arg

		#buffersize=64 #taille  du  buffer  de récéption
		# lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868, bandwidth=LoRa.BW_500KHZ,preamble=5, sf=7)#définition dun truc
		lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868, bandwidth=bandwidth,preamble=preamble, sf=sf,tx_power=power,coding_rate=coding)#définition dun truc
		print(lora.stats())
		print("bandwidth="+str(bandwidth)+"preamble="+str(preamble)+"sf="+str(sf)+"tx_power="+str(power)+"coding_rate="+str(coding))
		print("bandtith"+str(lora.bandwidth())+"preamble"+str(lora.preamble())+"sf"+str(lora.sf())+"tx_power"+str(lora.tx_power())+"coding_rate"+str(lora.coding_rate()))

		s = socket.socket(socket.AF_LORA, socket.SOCK_RAW)#définition d'un socket réseaux de type lora
		f = open(fichier, 'rb')#on va ouvrire l'image qui port l'extention .py (pycom n'axepte pas  des fichier de format image)

		s.setblocking(True)#on dit que l'écoute ou l'envoit bloque le socket
		s.settimeout(timeout) #temps  a attendre avant de  considérer une trame  comme perdu ==> DOIT ETRE BC  PLUS COURT ! ! ! ! ! quelque  MS


		#purger les  sockete
		def purge():
			s.setblocking(False)
			purgetemp=s.recv(buffersize)
			while purgetemp!=b'':
				purgetemp=s.recv(buffersize)
			s.setblocking(True)

		#définition d'une fonction d'aquitement
		def sendACK(vara):
			s.settimeout(timeout)
			i=0
			while True:
				i+=1
				s.send(vara)
				print("ACK Envoit: "+str(vara))
				try:
					retour=s.recv(buffersize)
					#print("ack Reçus")
					break
				except OSError as socket :
					print("ACK timeout n° ",i)
					if(i==maxretry):
						exit("connexion  perdu")
			return retour

		def sendACKvrf(data, match):
			while True:
				mydata=sendACK(data)
				if(type(match)==bytes):
					#print("ACKvfr type  = bytes")
					if mydata == match:
						#print("ACKvfr break")
						break
					else:
						print("ACKvfr attendue :  ", match, " type byte reçus", mydata)
				if(type(match)==str):
					#print("ACKvfr type  = str")
					if mydata == match.encode() :
						#print("ACKvfr break")
						break
					else:
						print("ACKvfr attendue :  ", match.encode(), " type str reçus", mydata)
			return True

		#on va  utiliser la  trame  rentrée   est  la décomposer  est ajouter  les  numero
		def AddToIndexToSend(temp):
			#on va déduire le nombre de valeur a insere dans le tableaux par la longeur /2 car  coder sur 2 bite
			nbcase=int(len(temp)/2)
			#on parse  toute  les valeur reçus   de la  trame
			for i in range(nbcase):##on déduit le nombre de numero en  fonction de la  size de  trame  attention si malformer !
				#on  verrifie   si  la   valeur  existe  bien...
				pointeur=struct.unpack(str(nbcase)+'H',temp)[i]
				if(len(dataMap) >= pointeur):
					#on ajoute  la case  parser a un tableaux  principale
					indexToSend.append(pointeur)#  I n'a  pas a être la et on e st  sensermodifier les h
			#on affiche  la geule de la  trame entierre
			print("trame a renvoiller récéptioner :",indexToSend)
			#return True


		#initialisation de la map de donnée
		dataMap=[]
		f = open(fichier, 'rb')
		stringToHash=var=b''
		sizefile=os.stat(fichier)[6]

		#on déduit le type de  variable a  utiliser en fonction du  nombre de trame total
		if sizefile/(buffersize-1)<256:
			tVarIndex="B" #a  enlever qqd ça marhce
			stVarIndex="B"+str(buffersize-1)
			sVarIndex=1
		elif sizefile/(buffersize-2) < 65536:
			tVarIndex="H"
			stVarIndex="H"+str(buffersize-2)
			sVarIndex=2
		else:
			tVarIndex="L"
			stVarIndex="L"+str(buffersize-4)
			sVarIndex=4

		lenDatamap=os.stat(fichier)[6]//(buffersize-sVarIndex)+1


		#on génère notre dataMap
		while True:
			var=f.read(buffersize-sVarIndex)
			if (var==b''):
				break

			#pour que la fin  du fichier soit fill avec des 0 pour un checksum correct
			ajouter=(buffersize-sVarIndex)-len(var)
			if ajouter!=0:
				var+=ajouter*b'\x00'

			dataMap.append(var)
			stringToHash+=var

		if (len(dataMap)!=lenDatamap):
			print("Erreur  taille  datamap")
			print("len(dataMap)",str(len(dataMap)))
			print("lenDatamap",str(lenDatamap))


		#on va  hasher  datamap
		m = hashlib.sha256()
		m.update(stringToHash)



		# print("array contenant les data maper:")

		###initialisation d'un tableaux qui va lister tout les chunk de data
		#indexToSend[0,1,2,3,4,5,6,7,8,9]
		indexToSend=[]
		for number in range(lenDatamap):
			indexToSend.append(number)

		#send du nombre de trame
		print("send demande de communiquation et annonce de ",str(lenDatamap)," trame a envoiller")

		#on va  utiliser le smiller OwO  pour  taguer qu'on est bien  sur  une  trame qui  annonce la  longeur
		#on  verrifie que la valeur envoilkler est bien la  valleur recus

		purge() ##verifier si utile ?

					##pack('H3s32s'
				#utiliser  un  sendACKvrf ??
		# sendACK(pack('L3s32s',lenDatamap,b'OwO',m.digest()),str(lenDatamap))

		if (str(sendACK(pack('L3s32s',lenDatamap,b'OwO',m.digest())))==str(lenDatamap)):
			print("Nombre de trame OK")
		else:
			print("erreur de trame")

		print("sucès début de transmition")
		while len(indexToSend)!=0:
			chargement=len(indexToSend)
			for notrame in range(len(indexToSend)):
				#on map la trame en  utilisant un octée pour anoncer le nombre de tram est ensuite 63 suivant pour les data
				trame=pack(stVarIndex+"s",indexToSend[notrame], dataMap[indexToSend[notrame]])#buffersize = tl ?
				#j'envoit ma  trame
				s.send(trame)
				print("envoit trame num: "+str(notrame)+"/"+str(chargement)+" index data: "+ str(indexToSend[notrame]))#,"string pur",dataMap[indexToSend[notrame]])

			#on  flush  la  variable  qui stoque  la  précédante  session  d'index a  send
			indexToSend=[]
			#on verifi qu'il y a encore  des data
			indextrame=sendACK("STOP")
			if (indextrame == b'FinTransmition'):
				break

			#reception des trame manquante
			print("detection des trame manquante")

			while True:
				#on  va  décomposer la  trame est l'ajouter  a  la  bd
				AddToIndexToSend(indextrame)
				indextrame = sendACK("indexOKforNext")


				#avec un prochaine opti  doit plus exister
				if (indextrame == b'FinTransmition'):
					break



				#indextrame=s.recv(buffersize)
				# s.settimeout(timeout)###########  Besoin de désincroniser pour que A ecoute et B parle
				print("INFO TrameListe reçus",indextrame)# # DEBUGage

				if (indextrame == b'STOPliste'):
					print("Attente confirmation du  de stop  d'envoit trame")
					sendACKvrf("indexFIN","GO")
					print("SINKRO")
					break

		print("toute numero de  chunck a renvoiller recus:")
		print(indexToSend)
		print("sortie!")
Ejemplo n.º 7
0
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 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 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 change_txpower(self, power):
        self.lora.tx_power(power)

    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
Ejemplo n.º 8
0
    def __init__(bandwidth=0,
                 sf=7,
                 buffersize=64,
                 preamble=8,
                 fichier='azer.txt',
                 power=14,
                 coding=1,
                 timeout=0.5,
                 maxretry=10):

        # fichier='azer.txt'
        # buffersize=64
        #buffersize=64 #taille  du  buffer  de récéption
        # lora = LoRa(mode=LoRa.LORA, region=LoRa.EU868, bandwidth=LoRa.BW_500KHZ,preamble=5, sf=7)#définition dun truc
        lora = LoRa(mode=LoRa.LORA,
                    region=LoRa.EU868,
                    bandwidth=bandwidth,
                    preamble=preamble,
                    sf=sf,
                    tx_power=power,
                    coding_rate=coding)  #définition dun truc
        s = socket.socket(
            socket.AF_LORA,
            socket.SOCK_RAW)  #définition d'un socket réseaux de type lora
        print(lora.stats())
        print("bandwidth=" + str(bandwidth) + "preamble=" + str(preamble) +
              "sf=" + str(sf) + "tx_power=" + str(power) + "coding_rate=" +
              str(coding))
        print("bandtith" + str(lora.bandwidth()) + "preamble" +
              str(lora.preamble()) + "sf" + str(lora.sf()) + "tx_power" +
              str(lora.tx_power()) + "coding_rate" + str(lora.coding_rate()))

        # #ne pouvant avoir une résolution en  dessou de  la  seconde  sans passer  par des  tick ces mort
        # ltime=int()
        # def crono():
        # 	global ltime
        # 	b=time.time()
        # 	out=b-ltime
        # 	ltime=b
        # 	return out

        #fonction  permetant de vider  le buffer  qui peut poser  des soucis RArement mais  ça peut vite  être contrégniant dans le cas échéant
        def purge():
            #purger les  sockete
            s.setblocking(False)
            purgetemp = s.recv(buffersize)
            while purgetemp != b'':
                purgetemp = s.recv(buffersize)
            s.setblocking(True)

        #declaration
        startAt = 0
        nbtrame = 0
        indexManque = []
        indexRecieve = []
        stVarIndex = ""
        tVarIndex = ""
        playloadsize = 0  #autodetect

        arrayStat = []

        def unboxing(rawtram):

            #on verifie si on peut umpack la trame
            try:  #"H"+str(buffersize-2)
                unpackted = unpack(
                    stVarIndex + "s", rawtram
                )  #on stoque la data qui est dans un  tuple dans une variable

            except ValueError:  #OSError
                print("Unboxing: raw: " + str(rawtram))
            else:
                #pour le premier tour  on empege une division par zero
                totaltemp = time.time() - startAt
                if totaltemp == 0:
                    totaltemp = 1
                totaldata = (len(indexRecieve) + 1) * int(playloadsize)

                # arrayStat.append((unpackted[0], (totaldata/totaltemp), time.time(), gps.coord,lora.stats()[1], lora.stats()[2]))
                print("Unboxing: chunk " + str(unpackted[0]) + " Download: " +
                      str((len(indexRecieve) + 1) / nbtrame * 100) +
                      "% débit moyen: " + str(totaldata / totaltemp) +
                      "octée/s " + "position: " + str(gps.coord) +
                      " power reçus " + str(lora.stats()[1]) + "dBm, SNR: " +
                      str(lora.stats()[2]) + "dB ",
                      end='')

                #pour  verifier si  un  packet DOUBLON OU est malformer  on verifi  que l'index  existe  bien
                if unpackted[0] in indexManque:
                    #on vérifie si ces bien une trame  de data
                    #try  plus nécésaire ?
                    try:
                        #on archive le packet recus
                        indexRecieve.append(unpackted)
                        #caclule en%  des trame perdu #####peut être  opti
                        print("packet  perdu  " +
                              str(lostpacket(unpackted[0])) + "%")
                        #on  suprime  le  packet  de la  liste de  packet a  renvoiller
                        indexManque.remove(unpackted[0])
                    except ValueError:
                        #debug value
                        print("List des  packet a receptioner ",
                              str(indexManque))
                        # print("liste des packet déja  receptioner", str(indexRecieve))
                        print("chunk  a  suprimer :", unpackted[0])
                        print("packet unpackted", str(unpackted))
                        print("raw packet", str(rawtram))
                else:
                    #ajouter un compteur pour dire  q'uon a un packet  corrompu  pour les  packet  perdu !!
                    print(
                        "Unboxing: BAD INDEX Duplicate Packet or Malformed  packet ?"
                    )

        #définition d'une fonction d'aquitement
        def sendACK(vara):
            s.settimeout(timeout)
            i = 0
            while True:
                i += 1
                s.send(vara)
                print("ACK Envoit: " + str(vara))
                try:
                    retour = s.recv(buffersize)
                    #print("ack Reçus")
                    break
                except OSError as socket:
                    print("ACK timeout n° ", i)
                    time.sleep(0.1)
                    if (i == maxretry):
                        exit("connexion  perdu")
            #s.setblocking(True)
            return retour

        def sendACKvrf(data, match):
            while True:
                mydata = sendACK(data)
                if (type(match) == bytes):
                    if mydata == match:
                        break
                    else:
                        print("ACKvfr attendue :  ", match, "is byte  reçus",
                              mydata)
                if (type(match) == str):
                    if mydata == match.encode():
                        break
                    else:
                        print("ACKvfr attendue :  ", match.encode(),
                              "  is str  reçus", mydata)
            return True

        #fonction qui  va  calculer  les   packet perdu
        def lostpacket(id):
            indexlost = indexManque.index(id)
            for a in range(len(indexRecieve)):
                if (indexRecieve[a][0] == id):
                    indexadd = a
                    break
            #trame perdu +  trame  reception  =  nombre trame  totale
            totaltramesend = indexadd + indexlost + 1
            #raport  de perte
            return (indexlost + 1) / totaltramesend * 100

        def writeTo(name):
            # global indexRecieve #ABON ?
            #on essay suprime le fichier si il existe
            #flmee de  chercherune fonction  de  test  si  le fichier existe avant  de le suprimer
            name = str(name)
            try:
                #on  essaye  de le supprimer
                os.remove(name)
                print("fichier supprimer")
            except OSError as e:
                print("fichier inéxistant")

            #on  va  ouvrire  le fichiuer
            with open(
                    name, 'w'
            ) as fout:  #création de du fichier data.txt sur le module si il n'est pas present, ou sinon on l'ouvre en mode ajout de data.
                #on va  parser notre  tableaux de  tuple
                for truc in indexRecieve:
                    #on  va selecioner  la  2eme valeur de  notre tuple  (les data)
                    fout.write(truc[1])
                    # on referme le fichier proprement
            fout.close()

        print("Attente Trame Datalenght")
        #purge le buffer au  cas ou
        purge()

        s.settimeout(10)  ##EXPERIMENTAL POUR PAS BLOQUER
        #pour définire nbtrame  on va  accepter que les  trame  étant sur 1 octée en Long
        varnul = 0
        while True:
            try:
                nbtrame = unpack('L3s32s', s.recv(buffersize))
                if nbtrame[1] == b'OwO':
                    checksum = nbtrame[2]
                    nbtrame = nbtrame[0]
                    break
            except Exception as e:
                print("INITIALISATION: nombretrame err : Trame Non  attendue",
                      str(nbtrame))
                varnul += 1
                if (varnul == maxretry):
                    exit("connexion  perdu")
        print("nombre de trame", str(nbtrame))

        s.settimeout(timeout)

        #on déduit le type de  variable a  utiliser en fonction du  nombre de trame total
        if nbtrame < 256:
            tVarIndex = "B"
            stVarIndex = "B" + str(buffersize - 1)
            playloadsize = str(buffersize - 1)
        elif (nbtrame < 65536):
            tVarIndex = "H"
            stVarIndex = "H" + str(buffersize - 2)
            playloadsize = str(buffersize - 1)
        else:
            tVarIndex = "L"
            stVarIndex = "L" + str(buffersize - 4)
            playloadsize = str(buffersize - 1)

        #génération d'un  tableaux qui contien toute les trame
        for number in range(int(nbtrame)):
            indexManque.append(number)

        print("envoit d'un  ackitement")
        #Unboxing de la premierre trame de donnée qui fait office d'ackitment
        purge()
        startAt = time.time()
        unboxing(sendACK(str(nbtrame)))

        print("démarage reception")
        startAt = time.time()
        #je  demande explicitement d'écouter j'usqua se que je  recois une trame
        s.setblocking(True)
        while True:

            #tant que l'éméteur veux envoiller des donnée
            while True:
                #je  reçois ma trame
                ##experimentale
                s.settimeout(10)  ##
                trame = s.recv(buffersize)
                s.settimeout(timeout)  ##

                #quand l'éméteur  a fini ENvoit de  stop pour  passer a la partie suivante
                if trame == b'STOP':
                    print("fin de flux reçus  !")
                    #s.send("OK")
                    break
                #sinon on traite la trame normalement
                else:
                    #on va traiter la  trame  recus
                    unboxing(trame)

            print("Packet perdu" + str(
                len(indexManque) /
                (len(indexRecieve) + len(indexManque)) * 100) + "%")

            #si il  n'y a plus de trame manquante
            if (len(indexManque) == 0):
                print("plus de trame manquante.")
                #sendACK("STOP")
                #on va indiquer a l'éméteur que ces fini
                s.send("STOP")
                #on sort de toute mes boucle  affain  de  passer a  au  trie  des data
                break

            print("trame perdu/restant:")
            print(indexManque)

            #Envoit des trame a  retransmetre
            #+ ajout de la premierre trame reçus (data)

            #on copy explicitement le  précédant tableaux dans un  nouveaux
            indexManquetosend = indexManque.copy()

            time.sleep(0.250)

            #tant qu'il reste des trame dans la liste TEMPORAIRE des trame qui  manque
            while len(indexManquetosend):
                #vieux conmpeur
                i = 0
                #on initialise ma future  trame en déclarant que ça serat du  binaire
                temp = b''

                #je  crée  une  trame  qui  sera  égale  a la taille  du buffer ou inferieure  tant qu'il  me   reste des valeur  a y metre
                ##	  i<(buffersize/2) #mieux ? ###########################
                while i < 32 and len(indexManquetosend):
                    #je rajoute de nouveaux Idex de trame  manquante  a ma trame  éxistante
                    temp += pack('H', indexManquetosend[0])
                    #je  suprime  la valeur  ajouter
                    indexManquetosend.pop(0)
                    i += 1
                #je  m'assurt  que l'éméteur a  bien recus la  trame  qu'il  a recus  est qu'il n'es pas  perdu  [utile quand je chercherer a débusquer les trame  malformer]
                sendACKvrf(
                    temp, "indexOKforNext"
                )  #######a la place de indexOk peut metre un ckecksum
                print("INDEXE echangée  " + str(i) + " liste des chunck")
            #on envoit a  l'éméteur un  signial  indiquant qu'il n'y a plus  de  trame a  envoiller est on verifi qu'il  est bien sincro

            print("on STOP la l'émition")
            sendACKvrf("STOPliste", "indexFIN")
            print("liste  trame manquante bien  réceptioner"
                  )  ##  ligne 160  et  163 redondante ?
            print(indexManque)
            #on envoit une  trame  pour  trigguer l'éméteur pour qu'il  passe  en  mode émition  et on traite  la premierre valeur reçus
            ###metre  un  time  out a  l'éméteur

            #on commence  la  reception qqd  on est  sur d'avoir  du  binaire
            tmpp = b'indexFIN'
            while tmpp == b'indexFIN':
                print(tmpp)  #debug
                tmpp = sendACK("GO")
                print(tmpp)  #debug
            unboxing(tmpp)

            print("début de la rerectption")
####

        print("récéption terminer:")

        purge()
        s.setblocking(False)
        s.send("FinTransmition")
        s.send("FinTransmition")
        s.send("FinTransmition")

        stopAt = time.time()

        print("trie:")
        #on va trier  en fonction  du  1er élémenet du tuple du tableaux
        indexRecieve.sort(key=itemgetter(0))
        #print(indexRecieve)

        datafile = b''
        for truc in indexRecieve:
            if (truc[1] == b''):
                break
            datafile += truc[1]
        print("durée du transfer:",
              str(stopAt - startAt), "seconde débit moyen de",
              str(len(datafile) / (stopAt - startAt)), "octée/s")
        m = hashlib.sha256()
        m.update(datafile)

        print("################")
        if checksum == m.digest():
            print("Fichier intègre !")
        else:
            print("/!\ bad checksum ! /!\ ")
        print("################")

        print("Phase écriture:")

        writeTo(fichier)

        # print("durée du transfer:",str(stopAt-startAt),"débit moyen de", str(os.stat("imgOut.txt")[5]/(stopAt-startAt)))

        print("transfer  terminer")

        print(str(indexRecieve))