yes Spada / Mbed 2 deprecated PS6_uplink

Dependencies:   mbed

Revision:
0:e73fe93596e9
Child:
2:b51532683489
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/main.cpp	Thu Mar 05 14:08:32 2020 +0000
@@ -0,0 +1,501 @@
+/**
+ * Copyright (c) 2017, Arm Limited and affiliates.
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#include "stdio.h"
+#include "mbed.h"
+#include "math.h"
+#include "stm32l0xx_hal_rcc.h"
+#include "lorawan/LoRaWANInterface.h"
+#include "lorawan/system/lorawan_data_structures.h"
+#include "events/EventQueue.h"
+#include "SX1276_LoRaRadio.h"
+// Application helpers
+#include "DummySensor.h"
+#include "lora_radio_helper.h"
+#include "trace_helper.h"
+
+//Init variable
+int countAck = 1;
+int countFailAck = 0;
+double moyESP = 4000.0;
+double nbrACK = 5.0;
+double greenLimit = 115.0;
+double blueLimit = 120.0;
+
+
+//init LED
+DigitalOut myled1(LED1);
+DigitalOut myled2(LED2);
+DigitalOut myled3(LED3);
+DigitalOut myled4(LED4);
+
+bool ledStatus = true; //Statut pour le toggle led
+
+int id = 0; //Id value to kill action
+
+//Start/stop led
+int ledStart = 0;
+static void StartLed1(){
+    myled1=1;
+    myled3=0;
+    myled4=0;
+    ledStart = 1;
+}
+static void StartLed3(){
+    myled1=0;
+    myled3=1;
+    myled4=0;
+    ledStart = 3;
+}
+static void StartLed4(){
+    myled1=0;
+    myled3=0;
+    myled4=1;
+    ledStart = 4;
+}
+
+static void toggleLed(DigitalOut led) {
+    if(ledStatus){
+     led = 1;
+     ledStatus = false;
+    }
+    else{
+     led = 0;
+     ledStatus = true;
+    }
+}
+
+using namespace events;
+
+//Button configuration
+InterruptIn mybutton(USER_BUTTON);
+
+// Max payload size can be LORAMAC_PHY_MAXPAYLOAD.
+// This example only communicates with much shorter messages (<30 bytes).
+// If longer messages are used, these buffers must be changed accordingly.
+uint8_t tx_buffer[128];
+uint8_t rx_buffer[128];
+uint8_t buttonVal = 0;
+/*
+ * Sets up an application dependent transmission timer in ms. Used only when Duty Cycling is off for testing
+ */
+#define TX_TIMER                        12000
+
+/**
+ * Maximum number of events for the event queue.
+ * 10 is the safe number for the stack events, however, if application
+ * also uses the queue for whatever purposes, this number should be increased.
+ */
+#define MAX_NUMBER_OF_EVENTS            10
+
+/**
+ * Maximum number of retries for CONFIRMED messages before giving up
+ */
+#define CONFIRMED_MSG_RETRY_COUNTER     2
+
+/**
+ * Dummy pin for dummy sensor
+ */
+#define PC_9                            0
+
+/**
+ * Dummy sensor class object
+ */
+DS1820  ds1820(PC_9);
+
+/**
+* This event queue is the global event queue for both the
+* application and stack. To conserve memory, the stack is designed to run
+* in the same thread as the application and the application is responsible for
+* providing an event queue to the stack that will be used for ISR deferment as
+* well as application information event queuing.
+*/
+static EventQueue ev_queue(MAX_NUMBER_OF_EVENTS *EVENTS_EVENT_SIZE);
+
+/**
+ * Event handler.
+ *
+ * This will be passed to the LoRaWAN stack to queue events for the
+ * application which in turn drive the application.
+ */
+static void lora_event_handler(lorawan_event_t event);
+
+/**
+ * Constructing Mbed LoRaWANInterface and passing it the radio object from lora_radio_helper.
+ */
+static LoRaWANInterface lorawan(radio);
+
+/**
+ * Application specific callbacks
+ */
+static lorawan_app_callbacks_t callbacks;
+
+/**
+ * Entry point for application
+ */
+
+ /* //Set the button for active or deactive ADR
+  static void mod_lowRecept(){
+     if(buttonVal == 0){
+         lorawan.disable_adaptive_datarate ();
+         lorawan.set_datarate(0);
+         buttonVal = 1;
+         printf("\r\n ADR disable \r\n");
+     }
+     else{
+        lorawan.enable_adaptive_datarate ();
+        buttonVal = 0;
+        printf("\r\n ADR enable \r\n");
+     }
+ }
+ */
+ //Change the settings for send more than 5 packet
+ static void modBigTest(){
+    if(buttonVal == 0){
+         nbrACK = 100;
+         printf("Mode big test activated");
+     }
+     else{
+         nbrACK = 5;
+         printf("Mode big test deactivitad");
+     }
+ }
+ //Do the ESP average and set led
+ static void testEnd(){
+     if(buttonVal !=1){
+        myled2 = 0;
+        moyESP/=nbrACK;
+        printf("Count ack = %d // CountfailAck = %d /// moyESP = %f", countAck, countFailAck, moyESP);
+    if(moyESP<=greenLimit){
+        StartLed1();
+     }
+    else if (moyESP<=blueLimit && moyESP>greenLimit){
+         StartLed3();
+     }
+    else{
+         StartLed4();
+     }
+    lorawan.disconnect();
+  }
+  moyESP = 0;
+}
+int main(void)
+{
+    // setup tracing
+    setup_trace();
+
+    // stores the status of a call to LoRaWAN protocol
+    lorawan_status_t retcode;
+
+    // Initialize LoRaWAN stack
+    if (lorawan.initialize(&ev_queue) != LORAWAN_STATUS_OK) {
+        printf("\r\n LoRa initialization failed! \r\n");
+        return -1;
+    }
+    printf("\r\n Mbed LoRaWANStack initialized \r\n");
+    id = ev_queue.call_every(200, &toggleLed, myled2);
+    // prepare application callbacks
+    callbacks.events = mbed::callback(lora_event_handler);
+    lorawan.add_app_callbacks(&callbacks);
+
+    // Set number of retries in case of CONFIRMED messages
+    if (lorawan.set_confirmed_msg_retries(CONFIRMED_MSG_RETRY_COUNTER)
+            != LORAWAN_STATUS_OK) {
+        printf("\r\n set_confirmed_msg_retries failed! \r\n\r\n");
+        return -1;
+    }
+
+    printf("\r\n CONFIRMED message retries : %d \r\n",
+           CONFIRMED_MSG_RETRY_COUNTER);
+    //Enable adaptive data rate
+    if (lorawan.enable_adaptive_datarate() != LORAWAN_STATUS_OK) {
+        printf("\r\n enable_adaptive_datarate failed! \r\n");
+        return -1;
+    }
+
+    printf("\r\n Adaptive data  rate (ADR) - Enabled \r\n");
+    retcode = lorawan.connect();
+
+    if (retcode == LORAWAN_STATUS_OK ||
+            retcode == LORAWAN_STATUS_CONNECT_IN_PROGRESS) {
+    } else {
+        printf("\r\n Connection error, code = %d \r\n", retcode);
+        return -1;
+    }
+    mybutton.rise(ev_queue.event(modBigTest));
+    printf("\r\n Connection - In Progress ...\r\n");
+
+    // make your event queue dispatching events forever
+    ev_queue.dispatch_forever();
+
+    return 0;
+}
+
+/**
+ * Sends a message to the Network Server
+ */
+static void send_message()
+{
+    uint16_t packet_len;
+    int16_t retcode;
+    int32_t sensor_value;
+
+    if (ds1820.begin()) {
+        ds1820.startConversion();
+        sensor_value = ds1820.read();
+        printf("\r\n Dummy Sensor Value = %d \r\n", sensor_value);
+        ds1820.startConversion();
+    } else {
+        printf("\r\n No sensor found \r\n");
+        return;
+    }
+
+    packet_len = sprintf((char *) tx_buffer, "ack");
+
+    retcode = lorawan.send(MBED_CONF_LORA_APP_PORT, tx_buffer, packet_len,
+                           MSG_CONFIRMED_FLAG);
+
+    if (retcode < 0) {
+        retcode == LORAWAN_STATUS_WOULD_BLOCK ? printf("send - WOULD BLOCK\r\n")
+        : printf("\r\n send() - Error code %d \r\n", retcode);
+
+        if (retcode == LORAWAN_STATUS_WOULD_BLOCK) {
+            //retry in 3 seconds
+            if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
+                ev_queue.call_in(3000, send_message);
+            }
+        }
+        return;
+    }
+    printf("\r\n %d bytes scheduled for transmission \r\n", retcode);
+    memset(tx_buffer, 0, sizeof(tx_buffer));
+}
+
+/**
+ * Receive a message from the Network Server
+ */
+static void receive_message()
+{
+    uint8_t port;
+    int flags;
+    int16_t retcode = lorawan.receive(rx_buffer, sizeof(rx_buffer), port, flags);
+
+    if (retcode < 0) {
+        printf("\r\n receive() - Error code %d \r\n", retcode);
+        return;
+    }
+    printf(" RX Data on port %u (%d bytes): ", port, retcode);
+
+    for (uint8_t i = 0; i < retcode; i++) {
+        printf("%02x ", rx_buffer[i]);
+    }
+    printf("\r\n");
+    memset(rx_buffer, 0, sizeof(rx_buffer));
+}
+/*
+* Set led after the test of the sent packet
+ */
+static void show(double esp){
+     if(esp<=120.0){ 
+        StartLed1();
+    }
+    else if(esp<125.0 && esp>120.0){
+        StartLed3();
+    }
+    else{
+        StartLed4();
+    }
+ }
+/*
+ * Calcul rx data
+ */
+   static void receive_data_calcul(int16_t rssi, int16_t snr){
+     //RSSI − 10∗LOG(1+10^(−SNR/100)).
+     //Convertie les valeurs pour effectuer les calculs
+     double s = (int) snr;
+     printf(" Original RSSI & SNR %d %f\n", rssi, s/10);
+     if(rssi>0){
+         rssi=-rssi;
+     }
+     //Algo II
+     switch(rssi) {
+              case -115:
+              case -116:
+              case -117: 
+                 rssi +=2;
+                 s +=20;
+                break;
+              case -118:
+              case -119: 
+                 rssi +=3;
+                 s +=20;
+                break;  
+              case -120:
+              case -121:
+                 rssi +=5;
+                 s +=20;
+                break;
+              case -122:
+              case -123:
+                     rssi +=6;
+                     s +=40;
+                    break;  
+              case -124:
+                     rssi +=8;
+                     s +=50;
+                    break; 
+              case -125:
+                     rssi +=8;
+                     s +=40;
+                    break;
+              case -126:
+                     rssi +=8;
+                     s +=40;
+                    break;
+              case -127:
+                     rssi +=8;
+                    break;
+              case -128:
+                     rssi +=8;
+                     s -=20;
+                    break;
+              case -129:
+              case -130:
+              case -131:
+              case -132:
+              case -133:
+              case -134:
+              case -135:
+                     rssi +=8;
+                     s -=40;
+                    break;
+            }
+     printf(" Filtred RSSI & SNR %d %f\n", rssi, s/10);
+     double rs = (int) rssi;
+     s = -s;
+     s /= 100.0;
+     double p = pow(10, s);
+     p+=1.0;
+     double snrLog = log10(p); 
+     double esp = rs - (10.0*snrLog);
+     printf(" ESP value %f\n", esp);
+     printf(" Numero de trame %d\r\n", countAck);
+     esp*=-1;
+     moyESP+=esp; //Fais la moyenne de ESP
+     printf(" moyenne esp %f\n", moyESP);
+     show(esp); //Envois la valeur de l'esp à la méthode qui va allumer les led correspondantes
+ }
+ /*
+ * get rx data
+ */
+ static void receive_data(){
+     lorawan_rx_metadata rxMetadata;
+     lorawan.get_rx_metadata(rxMetadata); //Get info of the downlink communcitation
+     receive_data_calcul(rxMetadata.rssi, rxMetadata.snr); //Send the value of RSSI & SNR to the next step
+ }
+/**
+ * Event handler
+ */
+static void lora_event_handler(lorawan_event_t event)
+{
+    switch (event) {
+        case CONNECTED:
+            /* Enable this for fix sf to 12
+            printf("\r\n ADR disable");
+            lorawan.disable_adaptive_datarate();
+            lorawan.set_datarate(0); */
+            printf("\r\n Connection - Successful \r\n");
+            ev_queue.cancel(id);
+            myled1 = 1;
+            myled2 = 1;
+            myled3 = 1;
+            myled4 = 1;
+            moyESP = 0; //Set la valeur de l'ESP à 0 pour commencer les test
+            if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
+                send_message();
+            } else {
+                ev_queue.call_every(TX_TIMER, send_message);
+            }
+            break;
+        case DISCONNECTED:
+            ev_queue.break_dispatch();
+            printf("\r\n Disconnected Successfully \r\n");
+            break;
+        case TX_DONE:
+            printf("\r\n Message Sent to Network Server \r\n");
+            receive_data();
+            ev_queue.cancel(id);
+            if(countAck==nbrACK){
+                testEnd();
+            }
+            countAck++;
+            if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
+                send_message();
+            }
+            break;
+        case TX_TIMEOUT:
+        case TX_ERROR:
+        case TX_CRYPTO_ERROR:
+        case TX_SCHEDULING_ERROR:
+            printf("\r\n Transmission Error - EventCode = %d \r\n", event);
+            if(countFailAck==5){ //IF more than 5 ackfail
+                moyESP = 4000; //Set esp in red
+                testEnd(); //end of the test
+            }
+            countFailAck++;
+            //Set blink led if ack fail
+            if(ledStart == 1){
+                ev_queue.cancel(id);
+                id = ev_queue.call_every(500, &toggleLed, myled1);
+            }
+            else if(ledStart == 3){
+                ev_queue.cancel(id);
+                id = ev_queue.call_every(500, &toggleLed, myled3);
+            }
+            else if(ledStart == 4){
+                ev_queue.cancel(id);
+                id = ev_queue.call_every(500, &toggleLed, myled4);
+            }
+            else{
+                ev_queue.cancel(id);
+                id = ev_queue.call_every(200, &toggleLed, myled4);
+            }
+            if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
+                send_message();
+            }
+            break;
+        case RX_DONE:
+            printf("\r\n Received message from Network Server \r\n");
+            receive_message();
+            break;
+        case RX_TIMEOUT:
+        case RX_ERROR:
+            printf("\r\n Error in reception - Code = %d \r\n", event);
+            break;
+        case JOIN_FAILURE:
+            printf("\r\n OTAA Failed - Check Keys \r\n");
+            testEnd();
+            break;
+        case UPLINK_REQUIRED:
+            printf("\r\n Uplink required by NS \r\n");
+            if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
+                send_message();
+            }
+            break;
+        default:
+            MBED_ASSERT("Unknown Event");
+    }
+}
\ No newline at end of file