LoRaWAN_FAE_Training

Dependencies:   X_NUCLEO_IKS01A2

main.cpp

Committer:
SemBen
Date:
2019-03-12
Revision:
48:b02d43b5e90c
Parent:
45:96fe99f19cd0
Child:
49:2453a6404fbe

File content as of revision 48:b02d43b5e90c:

/**
 * 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 "lorawan/LoRaWANInterface.h"
#include "lorawan/system/lorawan_data_structures.h"
#include "events/EventQueue.h"

// Application helpers
#include "DummySensor.h"
#include "trace_helper.h"
#include "lora_radio_helper.h"

// sensor boards IKS01A2
#include "XNucleoIKS01A2.h"


/* Instantiate the expansion board */
static XNucleoIKS01A2 *mems_expansion_board = XNucleoIKS01A2::instance(D14, D15, D4, D5);

/* Retrieve the composing elements of the expansion board */
static LSM303AGRMagSensor *magnetometer = mems_expansion_board->magnetometer;
static HTS221Sensor *hum_temp = mems_expansion_board->ht_sensor;
static LPS22HBSensor *press_temp = mems_expansion_board->pt_sensor;
static LSM6DSLSensor *acc_gyro = mems_expansion_board->acc_gyro;
static LSM303AGRAccSensor *accelerometer = mems_expansion_board->accelerometer;

using namespace events;

// 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[30];
uint8_t rx_buffer[30];

/*
 * Sets up an application dependent transmission timer in ms. Used only when Duty Cycling is off for testing
 */
#define TX_TIMER                        10000

/**
 * 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     3

/**
 * 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 down the radio object.
 */
static LoRaWANInterface lorawan(radio);

/**
 * Application specific callbacks
 */
static lorawan_app_callbacks_t callbacks;

/**
 * Entry point for application
 */
int main (void)
{
    uint8_t id;
      
    // setup tracing
    setup_trace();
    
    // Init IKS01A2 Board
    printf("\r\n--- IKS01A2 conf start ---\r\n");
  
    /* Enable all sensors */
    hum_temp->enable();
    press_temp->enable();
    magnetometer->enable();
    accelerometer->enable();
    acc_gyro->enable_x();
    acc_gyro->enable_g();

    hum_temp->read_id(&id);
    printf("HTS221  humidity & temperature    = 0x%X\r\n", id);
    press_temp->read_id(&id);
    printf("LPS22HB  pressure & temperature   = 0x%X\r\n", id);
    magnetometer->read_id(&id);
    printf("LSM303AGR magnetometer            = 0x%X\r\n", id);
    accelerometer->read_id(&id);
    printf("LSM303AGR accelerometer           = 0x%X\r\n", id);
    acc_gyro->read_id(&id);
    printf("LSM6DSL accelerometer & gyroscope = 0x%X\r\n", id);
    
    // 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");

    // 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;
    }

    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, Temperature, Index=1;
    uint32_t Pressure, Humidity;
    int16_t retcode;
    float sensor_value;
    
    float value1, value2;
    char buffer1[32], buffer2[32];
    int32_t axes[3];

//    if (ds1820.begin()) {
//        ds1820.startConversion();
//        sensor_value = ds1820.read();
//        printf("\r\n Dummy Sensor Value = %3.1f \r\n", sensor_value);
//        ds1820.startConversion();
//    } else {
//        printf("\r\n No sensor found \r\n");
//        return;
//    }
    
//    packet_len = sprintf((char*) tx_buffer, "Dummy Sensor Value is %3.1f",
//                    sensor_value);
    
    hum_temp->get_temperature(&value1);
    hum_temp->get_humidity(&value2);
    printf("HTS221: [temp] %2.2f C,   [hum] %2.2f \r\n", value1, value2);
    Humidity = value2 * 100;

    /*Add Humidity*/
    tx_buffer[0]+=1;                                            // Add 1 Nbelment 
    tx_buffer[Index]=0x03;                                      // Humidity
    tx_buffer[Index+1]=0x03;                                    // Len
    tx_buffer[Index+2]=(uint8_t)(Humidity & 0xFF);              // Press LSB
    tx_buffer[Index+3]=(uint8_t)((Humidity >> 8) & 0xFF);       // Press MID
    tx_buffer[Index+4]=(uint8_t)((Humidity >> 16) & 0xFF);      // Press MSB
    Index+=5; 
    
    press_temp->get_temperature(&value1);
    press_temp->get_pressure(&value2);
    printf("LPS22HB: [temp] %2.2f C, [press] %4.2f mbar\r\n", value1, value2);
    
    
    Temperature = value1 * 100; // Convert for transmit
    Pressure = value2 * 100; // Convert for transmit
    
    /*Add Tempertaure*/
    tx_buffer[0]+=1;                                            // Add 1 Nbelment 
    tx_buffer[Index]=0x01;                                      // Temperature
    tx_buffer[Index+1]=0x02;                                    // Len
    tx_buffer[Index+2]=(uint8_t)(Temperature & 0xFF);           // Temp LSB
    tx_buffer[Index+3]=(uint8_t)((Temperature >> 8) & 0xFF);    // Temp MSB 
    Index+=4;                                                   // Update the Index
    
    /*Add Pressure*/
    tx_buffer[0]+=1;
    tx_buffer[Index]=0x02;                                      // Pressure
    tx_buffer[Index+1]=0x03;                                    // Len
    tx_buffer[Index+2]=(uint8_t)(Pressure & 0xFF);              // Press LSB
    tx_buffer[Index+3]=(uint8_t)((Pressure >> 8) & 0xFF);       // Press MID
    tx_buffer[Index+4]=(uint8_t)((Pressure >> 16) & 0xFF);      // Press MSB
    Index+=5; 

    printf("---\r\n");

//    magnetometer->get_m_axes(axes);
//    printf("LSM303AGR [mag/mgauss]:  %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
//    
    accelerometer->get_x_axes(axes);
    printf("LSM303AGR [acc/mg]:  %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
    
    /*Add Accelerometer*/
    tx_buffer[0]+=1;
    tx_buffer[Index]=0x04;                                      // Accelerometer
    tx_buffer[Index+1]=0x03;                                    // Len
    /* x */
    tx_buffer[Index+2]=(uint8_t)(axes[0] & 0xFF);               // Press LSB
    tx_buffer[Index+3]=(uint8_t)((axes[0] >> 8) & 0xFF);        // Press MID
    tx_buffer[Index+4]=(uint8_t)((axes[0] >> 16) & 0xFF);       // Press MID
    tx_buffer[Index+5]=(uint8_t)((axes[0] >> 24) & 0xFF);       // Press MSB
    
    /* y */
    tx_buffer[Index+6]=(uint8_t)(axes[1] & 0xFF);               // Press LSB
    tx_buffer[Index+7]=(uint8_t)((axes[1] >> 8) & 0xFF);        // Press MID
    tx_buffer[Index+8]=(uint8_t)((axes[1] >> 16) & 0xFF);       // Press MID
    tx_buffer[Index+9]=(uint8_t)((axes[1] >> 24) & 0xFF);       // Press MSB
    
    /* z */
    tx_buffer[Index+10]=(uint8_t)(axes[2] & 0xFF);               // Press LSB
    tx_buffer[Index+11]=(uint8_t)((axes[2] >> 8) & 0xFF);        // Press MID
    tx_buffer[Index+12]=(uint8_t)((axes[2] >> 16) & 0xFF);       // Press MID
    tx_buffer[Index+13]=(uint8_t)((axes[2] >> 24) & 0xFF);       // Press MSB
    Index+=14; 
//
//    acc_gyro->get_x_axes(axes);
//    printf("LSM6DSL [acc/mg]:      %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]);
//
//    acc_gyro->get_g_axes(axes);
//    printf("LSM6DSL [gyro/mdps]:   %6ld, %6ld, %6ld\r\n", axes[0], axes[1], axes[2]); 
    
    packet_len = Index + 1; // Compute the final payload size  

    retcode = lorawan.send(MBED_CONF_LORA_APP_PORT, tx_buffer, packet_len,
                           MSG_UNCONFIRMED_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()
{
    int16_t retcode;
    retcode = lorawan.receive(MBED_CONF_LORA_APP_PORT, rx_buffer,
                              sizeof(rx_buffer),
                              MSG_CONFIRMED_FLAG|MSG_UNCONFIRMED_FLAG);

    if (retcode < 0) {
        printf("\r\n receive() - Error code %d \r\n", retcode);
        return;
    }

    printf(" Data:");

    for (uint8_t i = 0; i < retcode; i++) {
        printf("%x", rx_buffer[i]);
    }

    printf("\r\n Data Length: %d\r\n", retcode);
    
    if(rx_buffer[0] & 0x01 == 1)
    {
        printf("\r\n Board is in Wrong side !!!!! \r\n\r\n");    
    }
    if(((rx_buffer[0] & 0x02) >> 1) == 1)
    {
        printf("\r\n It's hot here !!!!! \r\n\r\n");    
    }
    if(((rx_buffer[0] & 0x04) >> 2) == 1)
    {
        printf("\r\n It's humid here !!!!! \r\n\r\n");   
    }

    memset(rx_buffer, 0, sizeof(rx_buffer));
}

/**
 * Event handler
 */
static void lora_event_handler(lorawan_event_t event)
{
    switch (event) {
        case CONNECTED:
            printf("\r\n Connection - Successful \r\n");
            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");
            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);
            // try again
            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");
            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");
    }
}

// EOF