example using mbed loramac with GPS in application layer

Dependencies:   lib_gps

This repository can work on NAmote72.

This main.cpp generates Cayenne LPP GPS payload.

See mbed documentation for provisioning instructions.

main.cpp

Committer:
Wayne Roberts
Date:
2019-01-03
Revision:
0:2e040cc7f7b8

File content as of revision 0:2e040cc7f7b8:

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

#include "mbed.h"
// Application helpers
#include "gps.h"
#include "trace_helper.h"
#include "lora_radio_helper.h"

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;

#ifdef TARGET_MOTE_L152RC
    GPS gps(PB_6, PB_7, PB_11);    // on-board GPS pins (tx, rx, en)
#elif defined(TARGET_FF_MORPHO)
    /*    https://www.sparkfun.com/products/13740   */
    #ifdef TARGET_DISCO_L072CZ_LRWAN1
        GPS gps(PA_9, PA_10, NC);
    #else
        GPS gps(PC_10, PC_11, NC);
    #endif
#endif

void gps_service()
{
    //int alt;

    gps.service();

    //alt = atoi( gps.NmeaGpsData.NmeaAltitude );
    //printf("lat:%f lon:%f alt:%d\r\n", gps.Latitude, gps.Longitude, alt);
}

#ifdef TARGET_MOTE_L152RC
typedef enum
{
    BOARD_VERSION_NONE = 0,
    BOARD_VERSION_2,
    BOARD_VERSION_3,
}BoardVersion_t;

DigitalOut Pc7( PC_7 );
DigitalIn Pc1( PC_1 );
BoardVersion_t BoardGetVersion( void )
{
    Pc7 = 1;
    char first = Pc1;
    Pc7 = 0;

    if( first && !Pc1 )
    {
        return BOARD_VERSION_2;
    }
    else
    {
        return BOARD_VERSION_3;
    }
}
AnalogIn *Battery;
#endif /* TARGET_MOTE_L152RC */

/**
 * Entry point for application
 */
int main (void)
{
    // setup tracing
    setup_trace();

    // stores the status of a call to LoRaWAN protocol
    lorawan_status_t retcode;

#ifdef TARGET_MOTE_L152RC
    switch( BoardGetVersion( ) )
    {
        case BOARD_VERSION_2:
            Battery = new AnalogIn( PA_0 );
            gps.en_invert = true;
            printf("v2-mote\r\n");
            break;
        case BOARD_VERSION_3:
            Battery = new AnalogIn( PA_1 );
            gps.en_invert = false;
            printf("v3-mote\r\n");
            break;
        default:
            break;
    }
#endif /* TARGET_MOTE_L152RC */
    gps.init();
    gps.enable(1);
    gps.m_uart.baud(9600);  // override platform serial baud rate

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

#define LPP_DIGITAL_INPUT       0       // 1 byte
#define LPP_DIGITAL_OUTPUT      1       // 1 byte
#define LPP_ANALOG_INPUT        2       // 2 bytes, 0.01 signed
#define LPP_ANALOG_OUTPUT       3       // 2 bytes, 0.01 signed
#define LPP_LUMINOSITY          101     // 2 bytes, 1 lux unsigned
#define LPP_PRESENCE            102     // 1 byte, 1
#define LPP_TEMPERATURE         103     // 2 bytes, 0.1°C signed
#define LPP_RELATIVE_HUMIDITY   104     // 1 byte, 0.5% unsigned
#define LPP_ACCELEROMETER       113     // 2 bytes per axis, 0.001G
#define LPP_BAROMETRIC_PRESSURE 115     // 2 bytes 0.1 hPa Unsigned
#define LPP_GYROMETER           134     // 2 bytes per axis, 0.01 °/s
#define LPP_GPS                 136     // 3 byte lon/lat 0.0001 °, 3 bytes alt 0.01m


// Data ID + Data Type + Data Size
#define LPP_DIGITAL_INPUT_SIZE       3
#define LPP_DIGITAL_OUTPUT_SIZE      3
#define LPP_ANALOG_INPUT_SIZE        4
#define LPP_ANALOG_OUTPUT_SIZE       4
#define LPP_LUMINOSITY_SIZE          4
#define LPP_PRESENCE_SIZE            3
#define LPP_TEMPERATURE_SIZE         4
#define LPP_RELATIVE_HUMIDITY_SIZE   3
#define LPP_ACCELEROMETER_SIZE       8
#define LPP_BAROMETRIC_PRESSURE_SIZE 4
#define LPP_GYROMETER_SIZE           8
#define LPP_GPS_SIZE                 11

#define CAYENNE_CH_GPS      5


/**
 * Sends a message to the Network Server
 */
static void send_message()
{
    int32_t lat, lon, alt;
    uint16_t packet_len;
    int16_t retcode;

    lat = gps.Latitude * 10000;
    lon = gps.Longitude * 10000;
    alt = atoi(gps.NmeaGpsData.NmeaAltitude) * 100;

    packet_len = 0;
    tx_buffer[packet_len++] = CAYENNE_CH_GPS;
    tx_buffer[packet_len++] = LPP_GPS;
    tx_buffer[packet_len++] = lat >> 16;
    tx_buffer[packet_len++] = lat >> 8;
    tx_buffer[packet_len++] = lat;
    tx_buffer[packet_len++] = lon >> 16;
    tx_buffer[packet_len++] = lon >> 8;
    tx_buffer[packet_len++] = lon;
    tx_buffer[packet_len++] = alt >> 16;
    tx_buffer[packet_len++] = alt >> 8;
    tx_buffer[packet_len++] = alt;

    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;
    }
    for (alt = 0; alt < packet_len; alt++) {
        printf("%02x", tx_buffer[alt]);
    }

    alt = atoi( gps.NmeaGpsData.NmeaAltitude );
    printf("\r\n %d bytes scheduled for tx\tlat:%f lon:%f alt:%d\r\n", retcode, gps.Latitude, gps.Longitude, (int)alt);
    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);

    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 ");
            ev_queue.call_every(1000, gps_service);
            if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
                printf("DUTY_ON\r\n");
                send_message();
            } else {
                printf("(duty off)\r\n");
                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:
            printf("\r\nTX_TIMEOUT\r\n");
            // try again
            /*if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
                send_message();
            }*/
            break;
        case TX_ERROR:
            // no ack was received after enough retries
            printf("\r\nTX_ERROR\r\n");
            // try again
            /*if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
                send_message();
            }*/
            break;
        case TX_CRYPTO_ERROR:
            printf("\r\nTX_CRYPTO_ERROR\r\n");
            // try again
            /*if (MBED_CONF_LORA_DUTY_CYCLE_ON) {
                send_message();
            }*/
            break;
        case TX_SCHEDULING_ERROR:
            printf("\r\nTX_SCHEDULING_ERROR\r\n");
            // 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