LoRaWAN demo.

Dependencies:   modem_ref_helper DebouncedInterrupt

main.cpp

Committer:
Jeej
Date:
2021-02-19
Revision:
21:f0aecd41db08
Parent:
20:49a8ecd1dda3

File content as of revision 21:f0aecd41db08:

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

#include "DebouncedInterrupt.h"
#include "modem_d7a.h"
#include "d7a_callbacks.h"
#include "lwan_callbacks.h"
#include "files.h"
#include "sensor.h"

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

Semaphore modem_urc(0);
Semaphore button_user(0);
sensor_config_t g_light_config;
Queue<uint8_t, 8> g_file_modified;
Queue<uint32_t, 8> g_urc;
int itf_busy;
Timer busy_tim;

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_cfg_t lwan_cfg = {
    // LoRaWAN device class
    .dev_class          = LWAN_CLASS_A,
    // State of adaptative Datarate
    .adr_enable         = 1,
    // Uplink datarate, if adr_enable is off
    .tx_datarate        = 0,
    // ISM Band
    .ism_band           = ISM_BAND_868,
    // maximum join attempts 
    .join_trials        = 2,
    // Rejoin period (hours)
    .rejoin_period      = 24
};

lwan_nls_t lwan_nls = {
    // Application identifier
    .app_id             = MY_APP_ID,
    // Application key
    .app_key            = MY_APP_KEY,
};

alp_d7a_itf_t report_itf = {
    .type                           = ALP_ITF_TYPE_D7A,
    .cfg.to                         = D7A_CTF(0),
    .cfg.te                         = D7A_CTF(0),
    .cfg.qos.bf.resp                = D7A_RESP_PREFERRED,
    .cfg.qos.bf.retry               = ALP_RPOL_ONESHOT,
    .cfg.addressee.ctrl.bf.nls      = D7A_NLS_AES_CCM_64,
    .cfg.addressee.ctrl.bf.idf      = D7A_ID_NBID,
    .cfg.addressee.xcl.bf           = {.m = 0x1, .s = 2},// XXX D7A_XCL_GW,
    .cfg.addressee.id               = { D7A_CTF_ENCODE(2) }
};

modem_ref_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,
    .itf_busy   = NULL,
};

modem_lwan_callbacks_t lwan_callbacks = {
    .packet_sent = lwan_packet_sent,
    .itf_busy    = lwan_busy,
    .join_failed = lwan_join_failed,
};


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

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)
{
    switch (config->report_type)
    {
        case REPORT_ALWAYS:
            // Send a report at each measure
            PRINT("Report always\r\n");
            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 on difference (last:%d new:%d max_diff:%d)\r\n", 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("Reporton threshold (last:%d new:%d th:%d tl:%d)\r\n", 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 on period (max_period:%d time:%d)\r\n", config->max_period, last_report_time);
        return report_ok(last_report_time);
    }

    return false;
}

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, (uint8_t*)&g_light_config, 0, SIZE_SENSOR_CONFIG);
                PRINT("Sensor configuration updated\r\n");
                break;
            default:
            break;
        }
    }
}

void d7a_thread()
{
    light_value_t light_level;
    light_value_t light_level_old = 0;
    alp_payload_t* alp = NULL;
    revision_t rev;
    
    // To force a first report
    uint32_t last_report_time = 0xFFFFFFFF;
    
    // Add files to local file system
    ram_fs_new(FID_SENSOR_CONFIG, (uint8_t*)&h_sensor_config, (uint8_t*)&f_sensor_config);
    ram_fs_new(FID_ALARM, (uint8_t*)&h_alarm, (uint8_t*)&f_alarm);
    
    DPRINT("D7A: Register Files\n");
    // Allow remote access.
    modem_declare_file(FID_SENSOR_CONFIG, (alp_file_header_t*)&h_sensor_config);
    modem_declare_file(FID_ALARM, (alp_file_header_t*)&h_alarm);
    
    PRINT("D7A: Notify Revision\n");
    modem_d7a_enable_itf();
    
    // Host revision file is in the modem. Update it.
    modem_write_file(FID_HOST_REV, &f_rev, 0, sizeof(revision_t));
    
    // Retrieve modem revision
    modem_read_file(FID_WM_REV, &rev, 0, sizeof(revision_t));
    
    // Send both to the server
    // Build payload
    alp = NULL;
    alp = alp_payload_rsp_f_data(alp, FID_WM_REV, &rev, 0, sizeof(revision_t));
    alp = alp_payload_rsp_f_data(alp, FID_HOST_REV, &f_rev, 0, sizeof(revision_t));
    // Send
    modem_remote_raw_alp((void*)&report_itf, alp, NULL, 10000);
    
    // Get the sensor configuration
    ram_fs_read(FID_SENSOR_CONFIG, (uint8_t*)&g_light_config, 0, SIZE_SENSOR_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))
        {
            PRINT("D7A: Light report %d\r\n", light_level);
                    
            // Build payload
            alp = NULL;
            alp = alp_payload_rsp_f_data(alp, FID_SENSOR_LIGHT, &light_level, 0, SIZE_SENSOR_LIGHT);
            // Send
            modem_remote_raw_alp((void*)&report_itf, alp, NULL, 1000);
        
            // Update 
            light_level_old = light_level;
            last_report_time = 0;
        }
        
        // Update last report time
        last_report_time += g_light_config.read_period;
        
        ThisThread::sleep_for(g_light_config.read_period);
    }
}

void lwan_thread()
{
    alarm_t alarm;
    alp_payload_t* alp = NULL;
        
    DebouncedInterrupt user_interrupt(DEBUG_BUTTON);
    user_interrupt.attach(button_push_isr, IRQ_FALL, 500, true);
    
    // Load alarm value
    ram_fs_read(FID_ALARM, (uint8_t*)&alarm, 0, SIZE_ALARM);
        
    PRINT("LoRaWAN: Update parameters\n");
    modem_lwan_set_cfg(&lwan_cfg);
    modem_lwan_set_nls(&lwan_nls);

    PRINT("LoRaWAN: Start (first join)\n");
    modem_lwan_open(&lwan_callbacks);
    
    while (true)
    {
        // Wait for button press
        PRINT("PRESS BUTTON TO SEND LORAWAN ALARM...\r\n");
        alarm_ready = true;
        button_user.acquire();
        alarm_ready = false;
        
        itf_busy -= (int32_t)busy_tim.read();
        
        if (itf_busy > 0)
        {
            PRINT("LoRaWAN: Still busy for %ds.\r\n", itf_busy);
            busy_tim.reset();
            
            lwan_status_t lwan;
            
            modem_lwan_get_status(&lwan);
            
            PRINT(
                "LoRaWAN: Joined            :%d\r\n"
                "         NetID             :%d\r\n"
                "         IsmBand           :%d\r\n"
                "         PublicNetwork     :%d\r\n"
                "         UpLinkCounter     :%d\r\n"
                "         DownLinkCounter   :%d\r\n"
                "         TxDr              :%d\r\n",
                lwan.IsNetworkJoined,
                lwan.NetID,
                lwan.IsmBand,
                lwan.PublicNetwork,
                lwan.UpLinkCounter,
                lwan.DownLinkCounter,
                lwan.TxDr
            );
        }
        else
        {
            busy_tim.stop();
            
            // load/save value to keep choerency in case of remote access...
            ram_fs_read(FID_ALARM, (uint8_t*)&alarm, 0, SIZE_ALARM);

            // Toggle alarm state
            alarm = !alarm;
            
            ram_fs_write(FID_ALARM, &alarm, 0, SIZE_ALARM);
            
            PRINT("BUTTON ALARM %d\r\n", alarm);
            
            // Build payload
            alp = NULL;
            alp = alp_payload_rsp_f_data(alp, FID_ALARM, &alarm, 0, sizeof(alarm_t));
            
            // Send
            modem_lwan_send(alp);
        }
    }
}


/*** 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");
              
    modem_open(&callbacks);

    // 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(d7a_thread);
    ASSERT(status == osOK, "Failed to start d7a_thread (err: %d)\r\n", status);
    
    Thread but_th(osPriorityNormal, 1024, NULL);
    status = but_th.start(lwan_thread);
    ASSERT(status == osOK, "Failed to start but thread (err: %d)\r\n", status);

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