diff --git a/Lora/src/API.c b/Lora/src/API.c new file mode 100644 index 0000000..e931cd2 --- /dev/null +++ b/Lora/src/API.c @@ -0,0 +1,22 @@ +/* + * File: API.c + * Author: Fabien AMELINCK + * + * Created on 28 February 2023 + */ + +#include +#include +#include +#include +#include +#include +#include +#include "gpio_util.h" +#include "SX1272.h" +#include "RF_LoRa_868_SO.h" +#include "sendRecept.h" +#include "filecsv.h" + +#define debug 1 +#define useInit \ No newline at end of file diff --git a/Lora/src/Init.c b/Lora/src/Init.c index a0440a5..8ddef9d 100644 --- a/Lora/src/Init.c +++ b/Lora/src/Init.c @@ -29,32 +29,40 @@ int main(int argc, char *argv[]) { if (init_spi()) return -1; - // Configure the pin used for RESET of LoRa transceiver - // here: physical pin n°38 (GPIO20) - create_port(20); - set_port_direction(20, 1); + uint8_t error = 0; + do { + error = 0; + // Configure the pin used for RESET of LoRa transceiver + // here: physical pin n°38 (GPIO20) + create_port(20); + usleep(10000); + set_port_direction(20, 1); // switch direction to input (high impedance) + // Configure the pin used for RX_SWITCH of LoRa transceiver + // here: physical pin n°29 (GPIO5) + create_port(5); + usleep(10000); + set_port_direction(5, 0); + set_port_value(5, 0); - // Configure the pin used for RX_SWITCH of LoRa transceiver - // here: physical pin n°29 (GPIO5) - create_port(5); - set_port_direction(5, 0); - set_port_value(5, 0); + // Configure the pin used for TX_SWITCH of LoRa transceiver + // here: physical pin n°31 (GPIO6) + create_port(6); + usleep(10000); + set_port_direction(6, 0); + if (set_port_value(6, 0)) { + fprintf(stdout, "Bug in port openning, please retry\n"); + error = 1; + } else error = 0; - // Configure the pin used for TX_SWITCH of LoRa transceiver - // here: physical pin n°31 (GPIO6) - create_port(6); - set_port_direction(6, 0); - if (set_port_value(6, 0)) { - fprintf(stdout, "Bug in port openning, please retry\n"); - return -1; - } - // Configure the pin used for LED - // here: physical pin n°40 (GPIO21) - /*create_port(21); - set_port_direction(21, 0); - set_port_value(21, 0);*/ + // Configure the pin used for LED + // here: physical pin n°40 (GPIO21) + /*create_port(21); + usleep(1000); + set_port_direction(21, 0); + set_port_value(21, 0);*/ + } while (error); ResetModule(); @@ -73,9 +81,9 @@ int main(int argc, char *argv[]) { // memset(inbuf, 0, sizeof inbuf); // memset(outbuf, 0, sizeof outbuf); - //InitModule(freq, bw, sf, cr, sync, preamble, pout, gain, rxtimeout, hder, crc); + //InitModule(freq, bw, sf, cr, sync, preamble, pout, gain, rxtimeout, hder, crc); + InitModule(CH_17_868, BW_500, SF_7, CR_5, 0x12, 0x08, 2, G1, LONGT, HEADER_ON, CRC_ON); // InitModule(CH_17_868, BW_500, SF_12, CR_5, 0x12, 0x08, 2, G1, SHORTT, HEADER_ON, CRC_ON); - InitModule(CH_17_868, BW_500, SF_7, CR_5, 0x12, 0x08, 2, G1, SHORTT, HEADER_ON, CRC_ON); return 0; } // end main \ No newline at end of file diff --git a/Lora/src/Receive.c b/Lora/src/Receive.c index 6248514..65bcfc1 100644 --- a/Lora/src/Receive.c +++ b/Lora/src/Receive.c @@ -12,6 +12,7 @@ #include #include #include +#include #include "gpio_util.h" #include "SX1272.h" #include "RF_LoRa_868_SO.h" @@ -21,8 +22,6 @@ #define debug 1 #define useInit -//#define MY_ID ISEN_ID - int main(int argc, char *argv[]) { uint8_t NodeData[255]; // data sent by a node @@ -45,31 +44,38 @@ int main(int argc, char *argv[]) { if (init_spi()) return -1; - // Configure the pin used for RESET of LoRa transceiver - // here: physical pin n°38 (GPIO20) - create_port(20); - set_port_direction(20, 1); - - // Configure the pin used for RX_SWITCH of LoRa transceiver - // here: physical pin n°29 (GPIO5) - create_port(5); - set_port_direction(5, 0); - set_port_value(5, 0); - - // Configure the pin used for TX_SWITCH of LoRa transceiver - // here: physical pin n°31 (GPIO6) - create_port(6); - set_port_direction(6, 0); - if (set_port_value(6, 0)) { - fprintf(stdout, "Bug in port openning, please retry"); - return -1; - } - - // Configure the pin used for LED - // here: physical pin n°40 (GPIO21) - /*create_port(21); - set_port_direction(21, 0); - set_port_value(21, 0);*/ + uint8_t error = 0; + do { + // Configure the pin used for RESET of LoRa transceiver + // here: physical pin n°38 (GPIO20) + create_port(20); + usleep(10000); + set_port_direction(20, 1); // switch direction to input (high impedance) + + // Configure the pin used for RX_SWITCH of LoRa transceiver + // here: physical pin n°29 (GPIO5) + create_port(5); + usleep(10000); + set_port_direction(5, 0); + set_port_value(5, 0); + + // Configure the pin used for TX_SWITCH of LoRa transceiver + // here: physical pin n°31 (GPIO6) + create_port(6); + usleep(10000); + set_port_direction(6, 0); + if (set_port_value(6, 0)) { + fprintf(stdout, "Bug in port openning, please retry\n"); + error = 1; + } else error = 0; + + // Configure the pin used for LED + // here: physical pin n°40 (GPIO21) + /*create_port(21); + usleep(1000); + set_port_direction(21, 0); + set_port_value(21, 0);*/ + } while (error); #ifndef useInit ResetModule(); @@ -89,10 +95,12 @@ int main(int argc, char *argv[]) { // memset(inbuf, 0, sizeof inbuf); // memset(outbuf, 0, sizeof outbuf); - //InitModule(freq, bw, sf, cr, sync, preamble, pout, gain, rxtimeout, hder, crc); - InitModule(CH_17_868, BW_500, SF_12, CR_5, 0x12, 0x08, 2, G1, 0x00, HEADER_ON, CRC_ON); + //InitModule(freq, bw, sf, cr, sync, preamble, pout, gain, rxtimeout, hder, crc); + InitModule(CH_17_868, BW_500, SF_7, CR_5, 0x12, 0x08, 2, G1, LONGT, HEADER_ON, CRC_ON); #endif + setbuf(stdout, NULL); + if (argc > 1) { #if debug fprintf(stdout, "args %d", argc); // Printing all args passed during call @@ -107,9 +115,28 @@ int main(int argc, char *argv[]) { #endif uint8_t received = 0, loop = 0, maxLoop = 10; - if (argc == 3) maxLoop = atoi(argv[2]); + uint8_t noending = 0, halt = 0; + if (argc == 3) !atoi(argv[2]) ? (noending = 1) : (maxLoop = atoi(argv[2])); + + struct pollfd mypoll = { STDIN_FILENO, POLLIN|POLLPRI, POLLIN|POLLPRI }; + + while (loop < maxLoop || noending) { + if( poll(&mypoll, 1, 10) ) { + char stopCmd[10]; + scanf("%9s", stopCmd); + fprintf(stdout, "You have typed: %s\n", stopCmd); + if (!strcmp(stopCmd, "stop")) halt = 1; + else if (!strcmp(stopCmd, "exit")) return 0; + while (halt) { + if( poll(&mypoll, 1, 5000) ) { + char restartCmd[10]; + scanf("%9s", restartCmd); + fprintf(stdout, "You have typed: %s\n", restartCmd); + if (!strcmp(restartCmd, "restart")) halt = 0; + } else fprintf(stdout, "Waiting for restart command\n"); + }; + } - while (!received && loop < maxLoop) { if (argc == 3) CRCError = WaitIncomingMessageRXSingle(&TimeoutOccured); else CRCError = WaitIncomingMessageRXContinuous(); diff --git a/Lora/src/Transmit.c b/Lora/src/Transmit.c index a0433c4..f62d17b 100644 --- a/Lora/src/Transmit.c +++ b/Lora/src/Transmit.c @@ -106,8 +106,8 @@ int main(int argc, char *argv[]) { // memset(inbuf, 0, sizeof inbuf); // memset(outbuf, 0, sizeof outbuf); - //InitModule(freq, bw, sf, cr, sync, preamble, pout, gain, rxtimeout, hder, crc); - InitModule(CH_17_868, BW_500, SF_12, CR_5, 0x12, 0x08, 2, G1, 0x00, HEADER_ON, CRC_ON); + //InitModule(freq, bw, sf, cr, sync, preamble, pout, gain, rxtimeout, hder, crc); + InitModule(CH_17_868, BW_500, SF_7, CR_5, 0x12, 0x08, 2, G1, LONGT, HEADER_ON, CRC_ON); #endif //DeleteDataFile(); @@ -146,21 +146,21 @@ int main(int argc, char *argv[]) { } TxBuffer[DEST_ID_POS] = (uint8_t) atoi(argv[2]); TxBuffer[COMMAND_POS] = LED_OFF; - } else if (!strcmp(argv[1], "D")) { + } else if (!strcmp(argv[1], "D")) { // Discover if (argc != 4) { fprintf(stdout, "Error nb args, usage : D "); return -1; } TxBuffer[DEST_ID_POS] = (uint8_t) atoi(argv[2]); TxBuffer[COMMAND_POS] = DISCOVER; - } else if (!strcmp(argv[1], "P")) { + } else if (!strcmp(argv[1], "P")) { // Ping if (argc != 4) { fprintf(stdout, "Error nb args, usage : P "); return -1; } TxBuffer[DEST_ID_POS] = (uint8_t) atoi(argv[2]); TxBuffer[COMMAND_POS] = PING; - } else if (!strcmp(argv[1], "T")) { + } else if (!strcmp(argv[1], "T")) { // Transmit if (argc != 7) { fprintf(stdout, "Error nb args, usage : T "); return -1; @@ -171,7 +171,7 @@ int main(int argc, char *argv[]) { TxBuffer[T_POS] = (uint8_t) atoi(argv[5]); TxBuffer[O_POS] = (uint8_t) atoi(argv[6]); PayloadLength = TRANSMIT_LONG; - } else if (!strcmp(argv[1], "A")) { + } else if (!strcmp(argv[1], "A")) { // Acknowledge if (argc != 7) { fprintf(stdout, "Error nb args, usage : A "); return -1; diff --git a/Lora/src/filecsv.c b/Lora/src/filecsv.c index 305df2c..af8199e 100644 --- a/Lora/src/filecsv.c +++ b/Lora/src/filecsv.c @@ -129,7 +129,7 @@ void WriteResetInFile(void) fprintf(df, "%02d/%02d/%d; ", day, month, year); fprintf(df, "%02d:%02d:%02d; ", hour, min, sec); - fprintf(df, "LORa module reset\n"); + fprintf(df, "LoRa module reset\n"); fclose(df); } diff --git a/Rasp/raspb_Z1.py b/Rasp/raspb_Z1.py index 193c4dc..f1b620a 100644 --- a/Rasp/raspb_Z1.py +++ b/Rasp/raspb_Z1.py @@ -14,6 +14,9 @@ import subprocess # for lora transmit C call from threading import Thread # for lora receive thread +verbose = False +debug = False + # dictionnary of network adresses NETWORK= {"1":False, "2":False, "3":False} # possibility to discover the network to assign unique ID dict_request = {"ID":None, "T":None, "O":None, "NETD":None, "NETS":None} @@ -23,7 +26,7 @@ ser = serial.Serial( port = '/dev/ttyUSB0', baudrate = 115200, - timeout = 1 + timeout = 0.5 ) class Receive(Thread): @@ -34,11 +37,12 @@ def __init__(self, loop = 1): def run(self): try: - print("thread start", self.loraReceived) + if debug: print("thread start", self.loraReceived) proc = subprocess.Popen(["../Lora/Receive", myNet, str(self.loop)], shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE) # this function allows to start the sub-process - #print(proc) + if debug: print(proc) stdout, stderr = proc.communicate(timeout=300) - print("Output:\n", stdout.decode('utf-8'), stderr.decode('utf-8')) + if verbose: print("Output:\n", stdout.decode('utf-8'), stderr.decode('utf-8')) + if len(stdout.decode('utf-8').split("T")) > 1: # lora payload contain a transmission packet ? jsonLora = stdout.decode('utf-8').split("T")[len(stdout.decode('utf-8').split("T")) - 1].strip("\n").split(",") if len(jsonLora) == 5: @@ -66,7 +70,7 @@ def run(self): reachableNet[int(jsonLora[0]) - 1][0] = 1 # net is reachable reachableNet[int(jsonLora[0]) - 1][1] = int(jsonLora[1]) # save the RSSI self.loraReceived = "D" - print("thread end", self.loraReceived) + if debug: print("thread end", self.loraReceived) return except Exception as e: print(e) @@ -84,59 +88,74 @@ def my_debug_message(msg): debug_file.write("\n") myNet = str(input('Enter the network number : ')) -if myNet == "1": - NETWORK["1"] = True -elif myNet == "2": - NETWORK["2"] = True -elif myNet == "3": - NETWORK["3"] = True -else: - NETWORK["1"] = True -"""myNet = "" for key in NETWORK.keys(): - if NETWORK[key] == True: - myNet = key""" + if key == myNet: + NETWORK[key] = True print("Init LoRa Module") proc = subprocess.Popen(["../Lora/Init"], shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE) stdout, stderr = proc.communicate(timeout=10) -proc = subprocess.Popen(["../Lora/Init"], shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE) # bug at startup with the GPIO -print(proc) -stdout, stderr = proc.communicate(timeout=10) # -print("Output:\n", stdout.decode('utf-8'), stderr.decode('utf-8')) +if verbose: print("Output:\n", stdout.decode('utf-8'), stderr.decode('utf-8')) + + + + + +# genéraration de clé + +# phase de discover + + + -thread_1 = Receive() # loop = 10 by default + +for i in NETWORK.keys(): + if NETWORK.get(i) == False: + proc = subprocess.Popen(["../Lora/Transmit", "D", str(i), myNet], shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE) + stdout, stderr = proc.communicate(timeout=10) + print("Output:\n", stdout.decode('utf-8'), stderr.decode('utf-8')) + +thread_1 = Receive() # loop = 1 by default threadInitiated = True thread_1.start() # start thread timeTZigbee = 0 # recording the time of transfer while True: if thread_1.loraReceived: # thread's flag when valid lora packet received - print("Lora received") + if verbose: print("Lora received") if thread_1.loraReceived == "D": # received a discover packet print(reachableNet) + + + + + # ici pour la réception du message de discover + + + + else: if thread_1.loraReceived == "T": # received a transmission packet dump = json.dumps(dict_request).replace(" ","")+"\n" else: # received an acknowledge packet dump = json.dumps(dict_reqback).replace(" ","")+"\n" - print("Sending to Zolertia : ", dump) + if verbose: print("Sending to Zolertia : ", dump) ser.write(bytes(dump, "utf-8")) timeTZigbee = time.time() # ser.write((json.dumps(dict_lora).replace(" ","")+"\n").encode()) if threadInitiated and not thread_1.is_alive(): - #print("waiting end of thread") + if debug: print("waiting end of thread") thread_1.join() # need to join the thread before reinitializing it - #print("thread ended") + if debug: print("thread ended") threadInitiated = False if not threadInitiated: - thread_1 = Receive() # reset the thread + thread_1 = Receive(10) # reset the thread threadInitiated = True thread_1.start() # restart the thread - #print("Listening to the serial port.") + if debug: print("Listening to the serial port.") try: zolertia_info="" zolertia_info=str(ser.readline().decode("utf-8")) @@ -158,19 +177,19 @@ def my_debug_message(msg): if "ACK" in zolertiadicback.keys(): # return message processing if str(zolertiadicback["R"]) == "led_on" or zolertiadicback["R"] == 1: proc = subprocess.Popen(["../Lora/Transmit", "A", str(zolertiadicback["NETD"]), myNet, str(zolertiadicback["ID"]), str(zolertiadicback["ACK"]), "1"], shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE) - # ex : ../Lora/Transmit A NETD NETS SENDORID ACK R + # ex : ../Lora/Transmit A NETD NETS SENSORID ACK R # ex : ../Lora/Transmit A 1 2 1 1 1 elif str(zolertiadicback["R"]) == "led_off" or zolertiadicback["R"] == 0: proc = subprocess.Popen(["../Lora/Transmit", "A", str(zolertiadicback["NETD"]), myNet, str(zolertiadicback["ID"]), str(zolertiadicback["ACK"]), "0"], shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE) - # ex : ../Lora/Transmit A NETD NETS SENDORID ACK R + # ex : ../Lora/Transmit A NETD NETS SENSORID ACK R # ex : ../Lora/Transmit A 1 2 1 1 0 else: proc = subprocess.Popen(["../Lora/Transmit", "A", str(zolertiadicback["NETD"]), myNet, str(zolertiadicback["ID"]), "0", "0"], shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE) - # ex : ../Lora/Transmit A NETD NETS SENDORID ACK R + # ex : ../Lora/Transmit A NETD NETS SENSORID ACK R # ex : ../Lora/Transmit A 1 2 1 0 0 else: - proc = subprocess.Popen(["../Lora/Transmit", "T", str(network["NETD"]), myNet, str(network["ID"]), str(network["T"]), str(network["O"])], shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE) - # ex : ../Lora/Transmit T NETD NETS SENDORID T O + proc = subprocess.Popen(["../Lora/Transmit", "T", str(zolertiadicback["NETD"]), myNet, str(zolertiadicback["ID"]), str(zolertiadicback["T"]), str(zolertiadicback["O"])], shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE) + # ex : ../Lora/Transmit T NETD NETS SENSORID T O # ex : ../Lora/Transmit A 1 2 1 1 1 print(proc) stdout, stderr = proc.communicate(timeout=15) diff --git a/Rasp/raspb_Z1_new.py b/Rasp/raspb_Z1_new.py new file mode 100644 index 0000000..f6a685d --- /dev/null +++ b/Rasp/raspb_Z1_new.py @@ -0,0 +1,166 @@ +""" +This script gets the orders from the client and sends it to the zolertia C script. +It also gets messages from the network. + +authors : MAHRAZ Anasset and ROBYNS Jonathan +""" + +import time +import serial +import random +from datetime import datetime +import pytz +import json +import subprocess # for lora transmit C call +from threading import Thread # for lora receive thread +from fcntl import fcntl, F_GETFL, F_SETFL +from os import O_NONBLOCK, read + +# dictionnary of network adresses +NETWORK= {"1":False, "2":False, "3":False} # possibility to discover the network to assign unique ID +dict_request = {"ID":None, "T":None, "O":None, "NETD":None, "NETS":None} +dict_reqback = {"ID":None, "ACK":None, "R":None, "NETD":None, "NETS":None} +reachableNet = [[0]*2 for i in range(3)] # matrix of reachable network, 1 line/net contains the active flag and RSSI + +ser = serial.Serial( + port = '/dev/ttyUSB0', + baudrate = 115200, + timeout = 0.5 +) + +def my_debug_message(msg): + """ + msg (string) : debug message to write in infor_debug.txt + + This fonction has no return value. It simply writes msg in "info_debug.txt" + """ + with open("info_debug.txt",'a') as debug_file: + debug_file.write(msg) + debug_file.write("\n") + +myNet = str(input('Enter the network number : ')) +for key in NETWORK.keys(): + if key == myNet: + NETWORK[key] = True + +print("Init LoRa Module") +proc = subprocess.Popen(["../Lora/Init"], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) +stdout, stderr = proc.communicate(timeout=10) +print("Output:\n", stdout.decode(), stderr.decode()) + +timeTZigbee = 0 # recording the time of transfer +loop = 0 # 0 means infinit +loraReceived = "" +try: + proc = subprocess.Popen(["../Lora/Receive", myNet, str(loop)], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=0) # this function allows to start the sub-process + print(proc) + + flags = fcntl(proc.stdout, F_GETFL) # reading output of proc asynchronously + fcntl(proc.stdout, F_SETFL, flags | O_NONBLOCK) + + while True: + stdout, stderr = b'', b'' + stdout = proc.stdout.read() + # stderr = proc.stderr.read() # takes too much time + if stdout or stderr: print("Output:\n", stdout.decode(), stderr.decode()) + + if stdout: # interpretation of the LoRa program output + jsonLora = stdout.decode().split("T")[len(stdout.decode().split("T")) - 1].split("\n")[0].split(",") + if len(jsonLora) == 5 and len(jsonLora[0]) == 1: # lora payload contain a transmission packet ? + print(jsonLora) + dict_request["ID"] = int(jsonLora[0]) + dict_request["T"] = int(jsonLora[1]) + dict_request["O"] = int(jsonLora[2]) + dict_request["NETD"] = int(jsonLora[3]) + dict_request["NETS"] = int(jsonLora[4]) + loraReceived = "T" + jsonLora = stdout.decode().split("A")[len(stdout.decode().split("A")) - 1].split("\n")[0].split(",") + if len(jsonLora) == 5 and len(jsonLora[0]) == 1: # lora payload contain an acknowledge packet ? + print(jsonLora) + dict_reqback["ID"] = int(jsonLora[0]) + dict_reqback["ACK"] = int(jsonLora[1]) + dict_reqback["R"] = int(jsonLora[2]) + dict_reqback["NETD"] = int(jsonLora[3]) + dict_reqback["NETS"] = int(jsonLora[4]) + loraReceived = "A" + jsonLora = stdout.decode().split("D")[len(stdout.decode().split("D")) - 1].split("\n")[0].split(",") + if len(jsonLora) == 2 and len(jsonLora[0]) == 1: # lora payload contain a discover packet ? + print(jsonLora) + reachableNet[int(jsonLora[0]) - 1][0] = 1 # net is reachable + reachableNet[int(jsonLora[0]) - 1][1] = int(jsonLora[1]) # save the RSSI + loraReceived = "D" + + if loraReceived: #flag when valid lora packet received + print(f'Lora received, message type: {loraReceived}') + if loraReceived == "D": # received a discover packet + print(reachableNet) + else: + if loraReceived == "T" or loraReceived == "A": # received a transmission or an acknowledge packet + dump = json.dumps(dict_request).replace(" ","") + "\n" + print(f'Sending to Zolertia : {dump}') + ser.write(bytes(dump, "utf-8")) + timeTZigbee = time.time() + proc.stdin.write(b"restart\n") # restart the receive process + #ser.write((json.dumps(dict_lora).replace(" ","")+"\n").encode()) + loraReceived = "" + print("-------------------------------------\n") + + + try: + zolertia_info = ser.readline().decode() + if zolertia_info != "": + print(f'zolertia info = {zolertia_info}') + if zolertia_info[0] == "{": # zigbee json received + elapsed = time.time() - timeTZigbee + print(f'Time of Zigbee transmission : {elapsed:.2}ms') + zolertiadicback = json.loads(zolertia_info) # convertion into a dictionnary + if ( (str(zolertiadicback["NETD"]) in NETWORK ) and NETWORK[str(zolertiadicback["NETD"])] == True ) : + print("Publishing on the server ") + elif ( (str(zolertiadicback["NETD"]) in NETWORK ) and NETWORK[str(zolertiadicback["NETD"])] == False ): + print("Sending to the lora module") + # tell the receive process to stop + proc.stdin.write(b"stop\n") + + procTransmit = subprocess.Popen(["../Lora/Init"], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + TimeTLora = time.time() + if "ACK" in zolertiadicback.keys(): # return message processing + if str(zolertiadicback["R"]) == "led_on" or zolertiadicback["R"] == 1: + procTransmit = subprocess.Popen(["../Lora/Transmit", "A", str(zolertiadicback["NETD"]), myNet, str(zolertiadicback["ID"]), str(zolertiadicback["ACK"]), "1"], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + # ex : ../Lora/Transmit A NETD NETS SENDORID ACK R + # ex : ../Lora/Transmit A 1 2 1 1 1 + elif str(zolertiadicback["R"]) == "led_off" or zolertiadicback["R"] == 0: + procTransmit = subprocess.Popen(["../Lora/Transmit", "A", str(zolertiadicback["NETD"]), myNet, str(zolertiadicback["ID"]), str(zolertiadicback["ACK"]), "0"], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + # ex : ../Lora/Transmit A NETD NETS SENDORID ACK R + # ex : ../Lora/Transmit A 1 2 1 1 0 + else: + procTransmit = subprocess.Popen(["../Lora/Transmit", "A", str(zolertiadicback["NETD"]), myNet, str(zolertiadicback["ID"]), "0", "0"], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + # ex : ../Lora/Transmit A NETD NETS SENDORID ACK R + # ex : ../Lora/Transmit A 1 2 1 0 0 + else: + procTransmit = subprocess.Popen(["../Lora/Transmit", "T", str(zolertiadicback["NETD"]), myNet, str(zolertiadicback["ID"]), str(zolertiadicback["T"]), str(zolertiadicback["O"])], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + # ex : ../Lora/Transmit T NETD NETS SENDORID T O + # ex : ../Lora/Transmit A 1 2 1 1 1 + + stdout, stderr = procTransmit.communicate(timeout=15) + elapsed = time.time() - TimeTLora + print(f'Time of Lora : {elapsed:.2}ms') + print("Output:\n", stdout.decode(), stderr.decode()) + proc.stdin.write(b"restart\n") # restart the receive process + + else : # debug messages + now = datetime.now() + now = now.replace(tzinfo = pytz.utc) + now = now.astimezone(pytz.timezone("Europe/Paris")) + current_time = now.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] + my_debug_message(current_time + " " + zolertia_info) + + print("-------------------------------------\n") + + except Exception as e: + print(e) + #Tell the receive process to start again + proc.stdin.write(b"restart\n") # restart the receive process + +except Exception as e: + print(e) diff --git a/Rasp/raspb_ZN.py b/Rasp/raspb_ZN.py index e3f8eab..d8095c1 100644 --- a/Rasp/raspb_ZN.py +++ b/Rasp/raspb_ZN.py @@ -81,7 +81,7 @@ def my_action_device(id,val,NETD,NETS): id (int) : ID of the device we want to give an order to val (int) : value defining the order. It can have several meanings depending on the nature of the device - THis function has no return value. It is supposed to give an order to a device, for example, a led lamp. + This function has no return value. It is supposed to give an order to a device, for example, a led lamp. """ global order_back @@ -96,34 +96,34 @@ def my_action_device(id,val,NETD,NETS): order_back["ID"] = id order_back["R"] = setLeds(LED,id,val) if order_back["R"] != None: # an acknowledge is created if the order is executed - order_back["ACK"]=1 - order_back_json= json.dumps(order_back) - print("order_back_json = "+order_back_json+"\n") - ser.write(bytes(order_back_json+"\n",'utf-8')) + order_back["ACK"] = 1 + order_back_json = json.dumps(order_back) + print("order_back_json = " + order_back_json + "\n") + ser.write(bytes(order_back_json + "\n",'utf-8')) elif id == 24: order_back["ID"] = id order_back["R"] = setLeds(1,id,val) - order_back_json= json.dumps(order_back) - print("order_back_json = "+order_back_json+"\n") - ser.write(bytes(order_back_json+"\n",'utf-8')) + order_back_json = json.dumps(order_back) + print("order_back_json = " + order_back_json + "\n") + ser.write(bytes(order_back_json + "\n",'utf-8')) elif id == 102: order_back["ID"] = id order_back["ACK"] = setFans(0,id,val) order_back_json= json.dumps(order_back) - print("order_back_json = "+order_back_json+"\n") - ser.write(bytes(order_back_json+"\n",'utf-8')) + print("order_back_json = " + order_back_json + "\n") + ser.write(bytes(order_back_json + "\n",'utf-8')) elif id == 144: order_back["ID"] = id order_back["ACK"] = setFans(1,id,val) order_back_json= json.dumps(order_back) - print("order_back_json = "+order_back_json+"\n") - ser.write(bytes(order_back_json+"\n",'utf-8')) + print("order_back_json = " + order_back_json + "\n") + ser.write(bytes(order_back_json + "\n",'utf-8')) elif id == 182: order_back["ID"] = id order_back["R"] = setLeds(2,id,val) order_back_json= json.dumps(order_back) - print("order_back_json = "+order_back_json+"\n") - ser.write(bytes(order_back_json+"\n",'utf-8')) + print("order_back_json = " + order_back_json + "\n") + ser.write(bytes(order_back_json + "\n",'utf-8')) else: pass @@ -150,44 +150,44 @@ def my_read_sensor(id,NETD,NETS): order_back["ACK"] = 1 order_back["R"] = state order_back_json = json.dumps(order_back) # convert the message in JSON before sending it - print("order_back_json = "+order_back_json+"\n") - ser.write(bytes(order_back_json+"\n",'utf-8')) # the response is sent in the serial port + print("order_back_json = " + order_back_json + "\n") + ser.write(bytes(order_back_json + "\n",'utf-8')) # the response is sent in the serial port elif id == 24: order_back["ID"] = id order_back["R"] = state order_back_json = json.dumps(order_back) - print("order_back_json = "+order_back_json+"\n") - ser.write(bytes(order_back_json+"\n",'utf-8')) + print("order_back_json = " + order_back_json + "\n") + ser.write(bytes(order_back_json + "\n",'utf-8')) elif id == 102: order_back["ID"] = id order_back["R"] = fans[0] order_back_json = json.dumps(order_back) - print("order_back_json = "+order_back_json+"\n") - ser.write(bytes(order_back_json+"\n",'utf-8')) + print("order_back_json = " + order_back_json + "\n") + ser.write(bytes(order_back_json + "\n",'utf-8')) elif id == 144: order_back["ID"] = id order_back["R"] = fans[1] order_back_json = json.dumps(order_back) - print("order_back_json = "+order_back_json+"\n") - ser.write(bytes(order_back_json+"\n",'utf-8')) + print("order_back_json = " + order_back_json + "\n") + ser.write(bytes(order_back_json + "\n",'utf-8')) elif id == 182: order_back["ID"] = id order_back["R"] = leds[2] order_back_json = json.dumps(order_back) - print("order_back_json = "+order_back_json+"\n") - ser.write(bytes(order_back_json+"\n",'utf-8')) + print("order_back_json = " + order_back_json + "\n") + ser.write(bytes(order_back_json + "\n",'utf-8')) else: pass initLed(LED) while True: - zolertia_info=str(ser.readline().decode("utf-8")) - print("zolertia info = "+zolertia_info+"\n") - zolertia_info2=zolertia_info[29:-2] # JSON extracting frome loginfo + zolertia_info = ser.readline().decode() + print("zolertia info = " + zolertia_info + "\n") + zolertia_info2 = zolertia_info[:-1] # JSON extracting frome loginfo if len(zolertia_info2) != 0 and zolertia_info2[0] == "{": # verifying the JSON parsing - print("json = ", zolertia_info2, " len = ", len(zolertia_info2)) - zolertia_info_dic=json.loads(zolertia_info2) # convertion into a dictionnary + print(f'json = {zolertia_info2} len = {len(zolertia_info2)}') + zolertia_info_dic = json.loads(zolertia_info2) # convertion into a dictionnary if "T" in zolertia_info_dic: # T indicates if we must read or write on our device. NB: the ACKs have no "T" value if zolertia_info_dic["T"] == 0 : my_read_sensor(zolertia_info_dic["ID"], zolertia_info_dic["NETD"], zolertia_info_dic["NETS"]) @@ -199,8 +199,8 @@ def my_read_sensor(id,NETD,NETS): print("NO EXISTING SENSOR MATCHING THIS ID\n") else: # debug messages - now=datetime.utcnow() - now=now.replace(tzinfo=pytz.utc) - now=now.astimezone(pytz.timezone("Europe/Paris")) + now = datetime.utcnow() + now = now.replace(tzinfo=pytz.utc) + now = now.astimezone(pytz.timezone("Europe/Paris")) current_time = now.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3] - my_debug_message(current_time+zolertia_info) + my_debug_message(current_time + " " + zolertia_info) diff --git a/Zolertia/zolertia_Z1.c b/Zolertia/zolertia_Z1.c index 0abe15b..f25e8e1 100644 --- a/Zolertia/zolertia_Z1.c +++ b/Zolertia/zolertia_Z1.c @@ -78,8 +78,9 @@ This fonction is called when we get a message } ZN_network[identified_zolertia_count].table_id=ID_table; memcpy(&ZN_network[identified_zolertia_count].ip,sender_addr,sizeof(uip_ipaddr_t)); + LOG_INFO("Zn : "); LOG_INFO_6ADDR(&ZN_network[identified_zolertia_count].ip); - LOG_INFO(" detected.\n"); + LOG_INFO_(" detected.\n"); identified_zolertia_count++; } @@ -89,18 +90,18 @@ This fonction is called when we get a message snprintf(buffer_OK, sizeof(buffer_OK), "OK"); #if ENABLE_DEBUG_LOG - LOG_INFO("\nSending '%s'\n", buffer_OK); + LOG_INFO("Sending '%s'\n", buffer_OK); #endif simple_udp_sendto(&udp_conn, buffer_OK, strlen(buffer_OK), sender_addr); } else { // If the message is not an identification message #if ENABLE_DEBUG_LOG - LOG_INFO("\nReceived response '%.*s'\n", datalen, data); + LOG_INFO("Received response '%.*s'\n", datalen, data); #endif printf("%s\n", (char *) data); // transfer data to the raspberry #if ENABLE_DEBUG_LOG - printf("\n"); + //printf("\n"); #endif } } @@ -150,8 +151,10 @@ PROCESS_THREAD(udp_server_process, ev, data) { if (check_ID==1) { #if ENABLE_DEBUG_LOG - printf("\nSending %s to : ",(char *) data); + LOG_INFO("Sending "); + printf("%s to : ",(char *) data); LOG_INFO_6ADDR(&ipaddr); + LOG_INFO_("\n"); #endif snprintf(buffer_message, sizeof(buffer_message), "%s",(char *) data); simple_udp_sendto(&udp_conn, buffer_message, strlen(buffer_message)+1,&ipaddr); diff --git a/Zolertia/zolertia_ZN.c b/Zolertia/zolertia_ZN.c index 9788830..a633d96 100644 --- a/Zolertia/zolertia_ZN.c +++ b/Zolertia/zolertia_ZN.c @@ -64,7 +64,7 @@ This fonction is called when we get a message ctimer_set(&identification_timer, 85*CLOCK_SECOND, timeout, NULL); // If we get a message from Z1, we reset the identification timer #if ENABLE_DEBUG_LOG LOG_INFO("Received '%.*s'\n", datalen, (char *) data); - LOG_INFO("check = %d",check); + LOG_INFO("check = %d\n",check); #endif if (check==1){ printf("%s\n", (char *) data); // transfer data to the raspberry @@ -78,7 +78,7 @@ This fonction is called when we get a message #if LLSEC802154_CONF_ENABLED LOG_INFO_(" LLSEC LV:%d", uipbuf_get_attr(UIPBUF_ATTR_LLSEC_LEVEL)); #endif - LOG_INFO_("\n"); + //LOG_INFO_("\n"); #endif } diff --git a/script b/script index caa86bf..b18cbd0 100644 --- a/script +++ b/script @@ -6,15 +6,13 @@ sudo apt install -y libdbus-1-dev sudo apt install -y libglib2.0-dev sudo apt install -y libcairo2-dev sudo apt install -y libssl-dev +sudo apt install -y python3-pip pip3 install -U pip pip3 list -o | cut -f1 -d' ' | tr " " "\n" | awk '{if(NR>=3)print}' | cut -d' ' -f1 | xargs -n1 pip3 install -U > /dev/tty1 - - git clone https://github.com/contiki-ng/contiki-ng.git cd contiki-ng git submodule update --init -sudo apt install -y python3-pip sudo apt install -y gcc-arm-none-eabi sudo pip3 install pyserial sudo pip3 install intelhex @@ -22,11 +20,14 @@ sudo pip3 install python-magic sudo pip3 install grovepi sudo pip3 install pytz sudo chmod 666 /dev/ttyUSB0 -# cp ~/Zigbee-LoRa-Interconnection/Zolertia/zolertia_Z1.c ~/contiki-ng/examples/rpl-udp/ -cp ~/zolertia_Z1.c ~/contiki-ng/examples/rpl-udp/ + +git clone https://github.com/ELDiablO59152/Zigbee-LoRa-Interconnection.git +cp ~/Zigbee-LoRa-Interconnection/Zolertia/zolertia_Z1.c ~/contiki-ng/examples/rpl-udp/ cd ~/contiki-ng/examples/rpl-udp/ -sudo make BOARD=firefly TARGET=zoul zolertia_ZN.upload login +sudo make BOARD=firefly TARGET=zoul zolertia_Z1.upload login +cd ~/Zigbee-LoRa-Interconnection/Rasp/ +python raspb_Z1.py + # ../../tools/cc2538-bsl/cc2538-bsl.py -e -w -v -a 0x00202000 \ # ../../tools/serial-io/serialdump -b115200 /dev/ttyUSB0 -# {"ID":1,"T":1,"O":1,"NETD":2,"NETS":1} -# python raspb_Z1.py \ No newline at end of file +# {"ID":1,"T":1,"O":1,"NETD":2,"NETS":1} \ No newline at end of file