LoRaWAN demo.

Dependencies:   modem_ref_helper DebouncedInterrupt

main.cpp

Committer:
Jeej
Date:
2018-10-11
Revision:
13:b9420183fbfc
Parent:
12:18ab0181d584
Child:
15:86f6fa566d89

File content as of revision 13:b9420183fbfc:

// @autor: jeremie@wizzilab.com
// @date: 2017-09-21

#include "DebouncedInterrupt.h"
#include "modem_ref_helper.h"
#include "modem_callbacks.h"
#include "files.h"
#include "sensor.h"

// Minimum time between alarms
#define ALARM_COOLDOWN_TIME 10000 // ms
#define MIN_REPORT_PERIOD   (10) // Seconds

enum {
    MODEM_RESP_NO,
    MODEM_RESP_TERMINAL,
    MODEM_RESP_DONE,
};

Semaphore modem_ready[MAX_USER_NB];
Semaphore button_user(0);
sensor_config_t g_light_config;
Queue<void, 8> g_file_modified;
Queue<void, 8> modem_resp;

bool alarm_ready = false;

#define USE_WL_TTN
#ifdef USE_WL_TTN
    // This is WizziLab's The Things Network LoRaWAN configuration file
    // This device is already registered on WizziLab's APP
    //
    // You can create your own account to get custom app_id and app_key.
    // The device EUI is the modem's UID.
    // https://account.thethingsnetwork.org/register
    // https://console.thethingsnetwork.org/applications
    
    #define MY_APP_ID           {0x70, 0xB3, 0xD5, 0x7E, 0xF0, 0x00, 0x3A, 0xF1 }
    #define MY_APP_KEY          {0x73, 0x90, 0x54, 0x78, 0xB5, 0x0B, 0xA8, 0x9A, 0x78, 0x23, 0xB7, 0x12, 0xD5, 0x5C, 0x70, 0x99 }
#else
    // This is your APP_ID and APP_KEY, as defined on your own TTN account
    // https://account.thethingsnetwork.org/register
    // https://console.thethingsnetwork.org/applications
    
    #define MY_APP_ID           { 0x70, 0xB3, 0xD5, 0x7E, 0xD0, 0x00, 0xAC, 0xB2 }
    #define MY_APP_KEY          { 0xDF, 0xF7, 0x26, 0x21, 0x22, 0xAD, 0x9A, 0xD6, 0x16, 0x84, 0xD1, 0x95, 0xBA, 0x8C, 0xD1, 0x1E }

#endif

lwan_itf_cfg_t lwan_itf_ttn = {
        .type                   = ALP_ITF_TYPE_LWAN,
    // 0: NONE, 1: OTAA, 2: ABP
    .cfg.activation_mode    = 1, // XXX Only OTAA
    // LoRaWAN device class
    .cfg.dev_class          = LWAN_CLASS_A,
    .cfg.dev_address        = 0x700006BF, // For ABP Mode (Big Endian)
    .cfg.app_id             = MY_APP_ID,
    .cfg.app_key            = MY_APP_KEY,
    // State of adaptative Datarate
    .cfg.adr_enable         = 1,
    .cfg.app_skey           = {0}, // For ABP Mode
    .cfg.nw_skey            = {0}, // For ABP Mode
    .cfg.nw_id              = 0, //
    // Enable or disable a public network
    .cfg.nw_public          = 1,
    // Uplink datarate, if adr_enable is off
    .cfg.tx_datarate        = 0,
    // ISM Band
    .cfg.ism_band           = ISM_BAND_868,
};

// Interrupt Service Routine on button press.
void button_push_isr( void )
{
    if (alarm_ready)
    {
        button_user.release();
    }
    else
    {
        PRINT("YOU CAN'T SEND ALARM AGAIN SO SOON.\n");
    }
}

// Callback for id User
void my_main_callback(uint8_t terminal, int8_t err, uint8_t id)
{
    (void)id;
    
    if (ALP_ERR_NONE != err)
    {
        modem_print_error(ALP_ITF_TYPE_D7A, err);
    }
    
    if (terminal)
    {
        modem_ready[id].release();
    }
}

static bool report_ok(uint32_t last_report_time)
{
    // Do not send a report if it's been less than MIN_REPORT_PERIOD since the last report
    if ((last_report_time/1000) < MIN_REPORT_PERIOD)
    {
        PRINT("Report Skipped, next in %ds min\n", MIN_REPORT_PERIOD - (last_report_time/1000));
        return false;
    }
    
    return true;
}

// Check parameters to see if data should be send
static bool report_needed(sensor_config_t* config, int32_t value, int32_t last_value, uint32_t last_report_time, uint8_t id)
{
    switch (config->report_type)
    {
        case REPORT_ALWAYS:
            // Send a report at each measure
            PRINT("Report[%d] always\r\n", id);
            return report_ok(last_report_time);
        case REPORT_ON_DIFFERENCE:
            // Send a report when the difference between the last reported measure and the current mesure is greater than max_diff
            if (abs(last_value - value) >= config->max_diff && config->max_diff)
            {
                PRINT("Report[%d] on difference (last:%d new:%d max_diff:%d)\r\n", id, last_value, value, config->max_diff);
                return report_ok(last_report_time);
            }
            break;
        case REPORT_ON_THRESHOLD:
            // Send a report when crossing a threshold
            if (   (value >= config->threshold_high && last_value < config->threshold_high)
                || (value <= config->threshold_low  && last_value > config->threshold_low)
                || (value < config->threshold_high  && last_value >= config->threshold_high)
                || (value > config->threshold_low   && last_value <= config->threshold_low))
            {
                PRINT("Report[%d] on threshold (last:%d new:%d th:%d tl:%d)\r\n", id, last_value, value, config->threshold_high, config->threshold_low);
                return report_ok(last_report_time);
            }
            break;
        default:
            break;
    }
    
    // Send a report if it's been more than max_period since the last report
    if (((last_report_time/1000) >= config->max_period) && config->max_period)
    {
        PRINT("Report[%d] on period (max_period:%d time:%d)\r\n", id, config->max_period, last_report_time);
        return report_ok(last_report_time);
    }

    return false;
}

void thread_sensor_light()
{
    light_value_t light_level;
    light_value_t light_level_old = 0;
    uint8_t id = modem_get_id(my_main_callback);
    
    // To force a first report
    uint32_t last_report_time = 0xFFFFFFFF;
    
    FPRINT("(id:0x%08x)\r\n", osThreadGetId());
    
    // Get the sensor configuration
    ram_fs_read(FID_SENSOR_CONFIG, 0, SIZE_SENSOR_CONFIG, (uint8_t*)&g_light_config);
    
    while (true)
    {
        light_level = sensor_get_light();
        
        //PRINT("Light %d\r\n", light_level);
                
        if (report_needed(&g_light_config, light_level, light_level_old, last_report_time, id))
        {
            PRINT("Light report %d\r\n", light_level);
        
            // Send notification
            modem_write_file(FID_SENSOR_LIGHT, &light_level, 0, SIZE_SENSOR_LIGHT, id);
            modem_ready[id].wait();
        
            // Update 
            light_level_old = light_level;
            last_report_time = 0;
        }
        
        // Update last report time
        last_report_time += g_light_config.read_period;
        
        Thread::wait(g_light_config.read_period);
    }
}

void thread_file_modified()
{
    uint8_t fid;
    osEvent evt;
    
    while (true)
    {
        evt = g_file_modified.get();
        fid = (evt.status == osEventMessage)? (uint8_t)(uint32_t)evt.value.p : NULL;
        
        switch (fid)
        {
            case FID_SENSOR_CONFIG:
                // Update sensor configuration
                ram_fs_read(FID_SENSOR_CONFIG, 0, SIZE_SENSOR_CONFIG, (uint8_t*)&g_light_config);
                PRINT("Sensor configuration updated\r\n");
                break;
            default:
            break;
        }
    }
}

void button_user_thread()
{
    FPRINT("(id:0x%08x)\r\n", osThreadGetId());

    alarm_t alarm;
    uint8_t id = modem_get_id(my_main_callback);
        
    // Use LoRaWAN Interface for the alarm
    typedef uint8_t lwan_itf_t;
    lwan_itf_t alarm_itf = ALP_ITF_TYPE_LWAN;
    
    // Load alarm value
    ram_fs_read(FID_ALARM, 0, SIZE_ALARM, &alarm);
    
    while (true)
    {
        // Wait for button press
        PRINT("PRESS BUTTON TO SEND LORAWAN ALARM...\r\n");
        alarm_ready = true;
        button_user.wait();
        alarm_ready = false;
                
        // load/save value to keep choerency in case of remote access...
        ram_fs_read(FID_ALARM, 0, SIZE_ALARM, &alarm);

        // Toggle alarm state
        alarm = !alarm;
        
        ram_fs_write(FID_ALARM, 0, SIZE_ALARM, &alarm);
        
        PRINT("BUTTON ALARM %d\r\n", alarm);
                    
        modem_send_file_content((uint8_t*)&alarm_itf, sizeof(lwan_itf_t), NULL, FID_ALARM, &alarm, 0, SIZE_ALARM, id);
        modem_ready[id].wait();
        
        PRINT("BUTTON ALARM DONE\r\n");
        
        Thread::wait(ALARM_COOLDOWN_TIME);
    }
}

modem_callbacks_t callbacks = {
    .read       = my_read,
    .write      = my_write,
    .read_fprop = my_read_fprop,
    .flush      = my_flush,
    .remove     = my_delete,
    .udata      = my_udata,
    .lqual      = my_lqual,
    .ldown      = my_ldown,
    .reset      = my_reset,
    .boot       = my_boot,
    .busy       = my_busy,
};

/*** Main function ------------------------------------------------------------- ***/
int main()
{
    // Start & initialize
#ifdef DEBUG_LED
    DBG_OPEN(DEBUG_LED);
#else
    DBG_OPEN(NC);
#endif
    PRINT("\n"
          "-----------------------------------------\n"
          "-------------- Demo LoRaWAN -------------\n"
          "-----------------------------------------\n");
          
    FPRINT("(id:0x%08x)\r\n", osThreadGetId());
    
    modem_helper_open(&callbacks);
    
    uint8_t id = modem_get_id(my_main_callback);
    
    DPRINT("Register Files\n");
    // Create report file on modem.
    modem_update_file(FID_SENSOR_LIGHT, (alp_file_header_t*)&h_sensor_light, NULL);

    // Allow remote access.
    modem_update_file(FID_SENSOR_CONFIG, (alp_file_header_t*)&h_sensor_config, (uint8_t*)&f_sensor_config);
    modem_update_file(FID_ALARM, (alp_file_header_t*)&h_alarm, (uint8_t*)&f_alarm);

    PRINT("Update LoRaWAN Interface file\n");
    modem_write_file(FID_LWAN_ITF0, &lwan_itf_ttn, 0, sizeof(lwan_itf_cfg_t), id);
    modem_ready[id].wait();

    // Configure URC: LQUAL on report file notification every 10 reports
    PRINT("Setup URCs\n");
    modem_enable_urc(ALP_URC_TYPE_LQUAL, IFID_REPORT, 10, true, id);
    modem_ready[id].wait();
    
    PRINT("Start D7A Stack\n");
    modem_activate_itf(ALP_ITF_TYPE_D7A, 24, 0, ALP_D7A_ISTAT_UNS | ALP_D7A_ISTAT_RESP | ALP_D7A_ISTAT_EOP, true, id);
    modem_ready[id].wait();
    
    PRINT("Start LoRaWAN Stack (Join)\n");
    modem_activate_itf(ALP_ITF_TYPE_LWAN, 1, FID_LWAN_ITF0, 0, true, id);
    modem_ready[id].wait();
    
    PRINT("Notify Modem Version\n");
    modem_notify_file(D7A_FID_FIRMWARE_VERSION, 0, SIZE_HOST_REV, id);
    modem_ready[id].wait();
    
    PRINT("Notify FW Version\n");
    uint8_t default_root_key[16] = DEFAULT_ROOT_KEY;
    modem_notify_host_rev(&f_rev, &h_rev, default_root_key);
    
    modem_free_id(id);
    
    // Start file modified thread
    Thread th_file_modified(osPriorityNormal, 1024, NULL);
    osStatus status = th_file_modified.start(thread_file_modified);
    ASSERT(status == osOK, "Failed to start thread_file_modified (err: %d)\r\n", status);
    
    // Start light measure thread
    Thread th_sensor_light(osPriorityNormal, 1024, NULL);
    status = th_sensor_light.start(thread_sensor_light);
    ASSERT(status == osOK, "Failed to start thread_sensor_light (err: %d)\r\n", status);
    
#ifdef DEBUG_BUTTON
    DebouncedInterrupt user_interrupt(DEBUG_BUTTON);
    user_interrupt.attach(button_push_isr, IRQ_FALL, 500, true);
    
    Thread but_th(osPriorityNormal, 1024, NULL);
    status = but_th.start(button_user_thread);
    ASSERT(status == osOK, "Failed to start but thread (err: %d)\r\n", status);
#endif

#ifdef DEBUG_LED
    DigitalOut my_led(DEBUG_LED);
#endif
    
    // Set main task to lowest priority
    osThreadSetPriority(osThreadGetId(), osPriorityIdle);
    while(true)
    {
        Thread::wait(500);
#ifdef DEBUG_LED
        my_led = !my_led;
#endif
    }
}