From beb4068e5aa3518707a92dd275b1b9ade15f0414 Mon Sep 17 00:00:00 2001 From: EL_DiablO_59 Date: Mon, 27 Feb 2023 16:10:10 +0100 Subject: [PATCH 1/4] CRYPTO::ADD:Starting dev of diffiehellman --- Lora/src/Init.c | 4 ++-- Lora/src/Receive.c | 4 ++-- Lora/src/Transmit.c | 12 ++++++------ Rasp/raspb_Z1.py | 29 ++++++++++++++++++++++++----- Rasp/raspb_ZN.py | 2 +- 5 files changed, 35 insertions(+), 16 deletions(-) diff --git a/Lora/src/Init.c b/Lora/src/Init.c index a0440a5..7be8612 100644 --- a/Lora/src/Init.c +++ b/Lora/src/Init.c @@ -73,9 +73,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, SHORTT, 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..3cfee38 100644 --- a/Lora/src/Receive.c +++ b/Lora/src/Receive.c @@ -89,8 +89,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, SHORTT, HEADER_ON, CRC_ON); #endif if (argc > 1) { diff --git a/Lora/src/Transmit.c b/Lora/src/Transmit.c index a0433c4..451ff35 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, SHORTT, 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/Rasp/raspb_Z1.py b/Rasp/raspb_Z1.py index 193c4dc..a7ad1a0 100644 --- a/Rasp/raspb_Z1.py +++ b/Rasp/raspb_Z1.py @@ -105,6 +105,16 @@ def my_debug_message(msg): stdout, stderr = proc.communicate(timeout=10) # print("Output:\n", stdout.decode('utf-8'), stderr.decode('utf-8')) +# genéraration de clé + +# phase de discover + +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) + print(proc) + + thread_1 = Receive() # loop = 10 by default threadInitiated = True thread_1.start() # start thread @@ -115,6 +125,15 @@ def my_debug_message(msg): 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" @@ -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_ZN.py b/Rasp/raspb_ZN.py index e3f8eab..ec2517a 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 From db9e3f488cf79d1a723f4cc37eaf22df462975d5 Mon Sep 17 00:00:00 2001 From: EL_DiablO_59 Date: Wed, 1 Mar 2023 09:43:33 +0100 Subject: [PATCH 2/4] GPIO::FIX:Handling errors related to port opening --- Lora/src/Init.c | 52 ++++++++++++++++++++++++------------------ Lora/src/Receive.c | 15 +++++++++---- Lora/src/filecsv.c | 2 +- Rasp/raspb_Z1.py | 56 +++++++++++++++++++++++----------------------- 4 files changed, 70 insertions(+), 55 deletions(-) diff --git a/Lora/src/Init.c b/Lora/src/Init.c index 7be8612..6178752 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(); diff --git a/Lora/src/Receive.c b/Lora/src/Receive.c index 3cfee38..3c4bd19 100644 --- a/Lora/src/Receive.c +++ b/Lora/src/Receive.c @@ -45,31 +45,38 @@ int main(int argc, char *argv[]) { if (init_spi()) return -1; + uint8_t error = 0; + do { // Configure the pin used for RESET of LoRa transceiver // here: physical pin n°38 (GPIO20) create_port(20); - set_port_direction(20, 1); + 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"); - return -1; - } + 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(); 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 a7ad1a0..8af28eb 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} @@ -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,45 +88,41 @@ 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 + + + + 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) - print(proc) - + stdout, stderr = proc.communicate(timeout=10) + print("Output:\n", stdout.decode('utf-8'), stderr.decode('utf-8')) -thread_1 = Receive() # loop = 10 by default +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) @@ -139,23 +139,23 @@ def my_debug_message(msg): 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")) From aa66dffeb487ff0c1cd2b9db8a8b5bf6ad3e6272 Mon Sep 17 00:00:00 2001 From: EL_DiablO_59 Date: Wed, 1 Mar 2023 09:58:58 +0100 Subject: [PATCH 3/4] THREAD::DELETE:Replace the LoRa thread by a permanent subprocess --- Lora/src/Receive.c | 48 +++++++------ Rasp/raspb_Z1_new.py | 168 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 196 insertions(+), 20 deletions(-) create mode 100644 Rasp/raspb_Z1_new.py diff --git a/Lora/src/Receive.c b/Lora/src/Receive.c index 3c4bd19..ed5c56e 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 @@ -47,35 +46,35 @@ int main(int argc, char *argv[]) { uint8_t error = 0; do { - // Configure the pin used for RESET of LoRa transceiver - // here: physical pin n°38 (GPIO20) - create_port(20); + // 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); + // 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); + 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); + // 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)) { + 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); + // 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);*/ + set_port_direction(21, 0); + set_port_value(21, 0);*/ } while (error); #ifndef useInit @@ -116,7 +115,16 @@ int main(int argc, char *argv[]) { uint8_t received = 0, loop = 0, maxLoop = 10; if (argc == 3) maxLoop = atoi(argv[2]); + struct pollfd mypoll = { STDIN_FILENO, POLLIN|POLLPRI, POLLIN|POLLPRI }; + while (!received && loop < maxLoop) { + if( poll(&mypoll, 1, 1000) ) { + char string[10]; + scanf("%9s", string); + printf("You have typed: %s\n", string); + return 0; + } else printf("Read nothing\n"); + if (argc == 3) CRCError = WaitIncomingMessageRXSingle(&TimeoutOccured); else CRCError = WaitIncomingMessageRXContinuous(); diff --git a/Rasp/raspb_Z1_new.py b/Rasp/raspb_Z1_new.py new file mode 100644 index 0000000..b6465bf --- /dev/null +++ b/Rasp/raspb_Z1_new.py @@ -0,0 +1,168 @@ +""" +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 + +# 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 = 1 +) + +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, 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 = 10 by default +threadInitiated = True +thread_1.start() # start thread +timeTZigbee = 0 # recording the time of transfer''' + +loop=100 +loraReceived = "" +try: + print("Process receive") + proc = subprocess.Popen(["../Lora/Receive", myNet, str(loop)], shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE) # this function allows to start the sub-process + + while(True): + + stdout=proc.stdout.read().decode() + if(stdout!=""): + #Tell the receive process to stop + proc.stdin.write("Test ici") + stdout, stderr = proc.communicate(timeout=10) + 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: + 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" + if len(stdout.decode('utf-8').split("A")) > 1: # lora payload contain an acknowledge packet ? + jsonLora = stdout.decode('utf-8').split("A")[len(stdout.decode('utf-8').split("A")) - 1].strip("\n").split(",") + if len(jsonLora) == 5: + 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" + if len(stdout.decode('utf-8').split("D")) > 1: # lora payload contain a discover packet ? + jsonLora = stdout.decode('utf-8').split("D")[len(stdout.decode('utf-8').split("D")) - 1].strip("\n").split(",") + if len(jsonLora) == 2: + 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" + print("Message type received: ", loraReceived) + + + if loraReceived: #flag when valid lora packet received + print("Lora received") + + if loraReceived == "D": # received a discover packet + print(reachableNet) + else: + if 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) + ser.write(bytes(dump, "utf-8")) + timeTZigbee = time.time() + # ser.write((json.dumps(dict_lora).replace(" ","")+"\n").encode()) + + + try: + zolertia_info="" + zolertia_info=str(ser.readline().decode("utf-8")) + if zolertia_info != "": + print("zolertia info = "+zolertia_info+"\n") + 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") + proc = subprocess.Popen(["../Lora/Init"], shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE) + + TimeTLora = time.time() + 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 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 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 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 + # ex : ../Lora/Transmit A 1 2 1 1 1 + + stdout, stderr = proc.communicate(timeout=15) + elapsed = time.time() - TimeTLora + print(f'Time of Lora : {elapsed:.2}ms') + print("Output:\n", stdout.decode('utf-8'), stderr.decode('utf-8')) + + 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) + + except Exception as e: + print(e) + #Tell the receive process to start again + # + +except Exception as e: + print(e) + #self.loraReceived = False From 55a66531009b7a1842a114645f449ada274f76fe Mon Sep 17 00:00:00 2001 From: EL_DiablO_59 Date: Thu, 2 Mar 2023 13:10:35 +0100 Subject: [PATCH 4/4] THREAD::DELETE:Stdout is now unbuffered. Python can read it normally --- Lora/src/API.c | 22 ++++ Lora/src/Init.c | 2 +- Lora/src/Receive.c | 30 ++++-- Lora/src/Transmit.c | 2 +- Rasp/raspb_Z1.py | 2 +- Rasp/raspb_Z1_new.py | 230 ++++++++++++++++++++--------------------- Rasp/raspb_ZN.py | 64 ++++++------ Zolertia/zolertia_Z1.c | 13 ++- Zolertia/zolertia_ZN.c | 4 +- script | 17 +-- 10 files changed, 211 insertions(+), 175 deletions(-) create mode 100644 Lora/src/API.c 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 6178752..8ddef9d 100644 --- a/Lora/src/Init.c +++ b/Lora/src/Init.c @@ -82,7 +82,7 @@ int main(int argc, char *argv[]) { // memset(outbuf, 0, sizeof outbuf); //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, SHORTT, HEADER_ON, CRC_ON); + 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); return 0; diff --git a/Lora/src/Receive.c b/Lora/src/Receive.c index ed5c56e..65bcfc1 100644 --- a/Lora/src/Receive.c +++ b/Lora/src/Receive.c @@ -96,9 +96,11 @@ int main(int argc, char *argv[]) { // memset(outbuf, 0, sizeof outbuf); //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, SHORTT, HEADER_ON, CRC_ON); + 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 @@ -113,17 +115,27 @@ 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 (!received && loop < maxLoop) { - if( poll(&mypoll, 1, 1000) ) { - char string[10]; - scanf("%9s", string); - printf("You have typed: %s\n", string); - return 0; - } else printf("Read nothing\n"); + 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"); + }; + } if (argc == 3) CRCError = WaitIncomingMessageRXSingle(&TimeoutOccured); else CRCError = WaitIncomingMessageRXContinuous(); diff --git a/Lora/src/Transmit.c b/Lora/src/Transmit.c index 451ff35..f62d17b 100644 --- a/Lora/src/Transmit.c +++ b/Lora/src/Transmit.c @@ -107,7 +107,7 @@ int main(int argc, char *argv[]) { // memset(outbuf, 0, sizeof outbuf); //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, SHORTT, HEADER_ON, CRC_ON); + InitModule(CH_17_868, BW_500, SF_7, CR_5, 0x12, 0x08, 2, G1, LONGT, HEADER_ON, CRC_ON); #endif //DeleteDataFile(); diff --git a/Rasp/raspb_Z1.py b/Rasp/raspb_Z1.py index 8af28eb..f1b620a 100644 --- a/Rasp/raspb_Z1.py +++ b/Rasp/raspb_Z1.py @@ -26,7 +26,7 @@ ser = serial.Serial( port = '/dev/ttyUSB0', baudrate = 115200, - timeout = 1 + timeout = 0.5 ) class Receive(Thread): diff --git a/Rasp/raspb_Z1_new.py b/Rasp/raspb_Z1_new.py index b6465bf..f6a685d 100644 --- a/Rasp/raspb_Z1_new.py +++ b/Rasp/raspb_Z1_new.py @@ -13,6 +13,8 @@ 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 @@ -23,7 +25,7 @@ ser = serial.Serial( port = '/dev/ttyUSB0', baudrate = 115200, - timeout = 1 + timeout = 0.5 ) def my_debug_message(msg): @@ -42,127 +44,123 @@ def my_debug_message(msg): NETWORK[key] = True print("Init LoRa Module") -proc = subprocess.Popen(["../Lora/Init"], shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE) +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('utf-8'), stderr.decode('utf-8')) +print("Output:\n", stdout.decode(), stderr.decode()) -'''thread_1 = Receive() # loop = 10 by default -threadInitiated = True -thread_1.start() # start thread -timeTZigbee = 0 # recording the time of transfer''' - -loop=100 +timeTZigbee = 0 # recording the time of transfer +loop = 0 # 0 means infinit loraReceived = "" try: - print("Process receive") - proc = subprocess.Popen(["../Lora/Receive", myNet, str(loop)], shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE) # this function allows to start the sub-process - - while(True): - - stdout=proc.stdout.read().decode() - if(stdout!=""): - #Tell the receive process to stop - proc.stdin.write("Test ici") - stdout, stderr = proc.communicate(timeout=10) - 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: - 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" - if len(stdout.decode('utf-8').split("A")) > 1: # lora payload contain an acknowledge packet ? - jsonLora = stdout.decode('utf-8').split("A")[len(stdout.decode('utf-8').split("A")) - 1].strip("\n").split(",") - if len(jsonLora) == 5: - 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" - if len(stdout.decode('utf-8').split("D")) > 1: # lora payload contain a discover packet ? - jsonLora = stdout.decode('utf-8').split("D")[len(stdout.decode('utf-8').split("D")) - 1].strip("\n").split(",") - if len(jsonLora) == 2: - 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" - print("Message type received: ", loraReceived) - - - if loraReceived: #flag when valid lora packet received - print("Lora received") - - if loraReceived == "D": # received a discover packet - print(reachableNet) - else: - if 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) + 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() - # ser.write((json.dumps(dict_lora).replace(" ","")+"\n").encode()) - - - try: - zolertia_info="" - zolertia_info=str(ser.readline().decode("utf-8")) - if zolertia_info != "": - print("zolertia info = "+zolertia_info+"\n") - 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") - proc = subprocess.Popen(["../Lora/Init"], shell=False, stderr=subprocess.PIPE, stdout=subprocess.PIPE) - - TimeTLora = time.time() - 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 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 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 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 - # ex : ../Lora/Transmit A 1 2 1 1 1 - - stdout, stderr = proc.communicate(timeout=15) - elapsed = time.time() - TimeTLora - print(f'Time of Lora : {elapsed:.2}ms') - print("Output:\n", stdout.decode('utf-8'), stderr.decode('utf-8')) - - 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) - - except Exception as e: - print(e) - #Tell the receive process to start again - # + 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) - #self.loraReceived = False diff --git a/Rasp/raspb_ZN.py b/Rasp/raspb_ZN.py index ec2517a..d8095c1 100644 --- a/Rasp/raspb_ZN.py +++ b/Rasp/raspb_ZN.py @@ -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