This program connects to the The Things Network backend in OTAA Mode. It logs sensor values from a BME 280 to the backend. Tried adding support for Grove GPS using SerialGPS library but it is not working - conflicting with mbed-rtos, so it commented. Deep Sleep for mDot implemented BUT avoiding reprogramming of the mDot config is NOT working.

Dependencies:   BME280 SerialGPS libmDot mbed-rtos mbed

main.cpp

Committer:
AshuJoshi
Date:
2016-07-08
Revision:
8:c17b68b03791
Parent:
7:9e2454b0318a
Child:
10:8071e1ae92ac

File content as of revision 8:c17b68b03791:

/******************************************************
 * A Program to interface the Grove Base Shielf V2
 * to the mDot UDK.
 * Additionally sample code to compress the data
 * for use with LPWANs such as LoRa
*****************************************************/
 
 #include "mbed.h"
 #include "mDot.h"
 #include "MTSLog.h"
 #include "MTSText.h"
 #include <string>

 #include "BME280.h"
 //#include "SerialGPS.h"
 
using namespace mts;
 
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))

// >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

// Values as used by The Things Network
// Application session key
uint8_t AppSKey[16]= { 0x91, 0x5F, 0xCD, 0x2A, 0xED, 0x8E, 0x0C, 0x2B, 0x30, 0xEF, 0x35, 0x8D, 0xF7, 0xE7, 0x89, 0x0A };
// Network session key
uint8_t NwkSKey[16]= { 0x60, 0xBF, 0x44, 0xA9, 0x56, 0x0A, 0x4C, 0xB4, 0xF2, 0xEB, 0xB1, 0x6B, 0x9A, 0x2C, 0x57, 0x32 };

// App Key 1DD7BB3D3E43ED13029996BEC25BF190
uint8_t AppKey[16] = {0x1D, 0xD7, 0xBB, 0x3D, 0x3E, 0x43, 0xED, 0x13, 0x02, 0x99, 0x96, 0xBE, 0xC2, 0x5B, 0xF1, 0x90};
// App EUI 70B3D57ED00005D5
uint8_t AppEUI[8] = {0x70, 0xB3, 0xD5, 0x7E, 0xD0, 0x00, 0x05, 0xD5};

 
// Network Address - Get your own address range at http://thethingsnetwork.org/wiki/AddressSpace
//uint8_t NetworkAddr[4]= {0x02,0x01,0x6C,0x02};      // Our Network address or Node ID
uint8_t NetworkAddr[4] = { 0x08, 0xBE, 0xAB, 0x8A }; 
 
// Some defines for the LoRa configuration
#define LORA_ACK 0
#define LORA_TXPOWER 20
 
//Ignoring sub band for EU modules.
static uint8_t config_frequency_sub_band = 7;

// <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<


 
// mDot UDK Specific
// MDot Pinout: https://developer.mbed.org/platforms/MTS-mDot-F411/#pinout-diagram
// Uncomment this line if using a full sized UDK2.0 instead of a Micro UDK

#define UDK2 1
#ifdef UDK2
DigitalOut led(LED1);
#else
DigitalOut led(XBEE_RSSI);
#endif

//SerialGPS gps(PA_2, PA_3);
//BME280 sensor(I2C_SDA, I2C_SCL)
// MDot UDK - I2C_SDA and I2C_SCL connected to PC_9/PA_*
BME280 b280(PC_9, PA_8);
AnalogIn light(PB_0); // This corresponds to A1 Connector on the Grove Shield

// Serial via USB for debugging only
//Serial pc(USBTX,USBRX);

// Function Declarations
void endLessTestLoop();
void setUpLEDBlink();
void blink();
void readandprintBME280();
float readLightSensor();
void mDotConfig();
void mDotGotoDeepSleep(int seconds);
void mDotConfigPrint();
void initSerialGPS();
void setupNetwork();
void joinNetwork();
void sendData();

// Globals
Ticker tick;
mDot* dot;
float llevel;

/*****************************************************
*                MAIN
*****************************************************/
int main(){

    // Simple Test Functions, "Hello World on UDK
    setUpLEDBlink();
    mDotConfig();
    setupNetwork();
    //wait(15);
    joinNetwork();
    sendData();
    // endLessTestLoop();
    
    return 0;
}

void sendData() {
    std::vector<uint8_t> data;
    std::string data_str = "hello!";
    char string_buffer[64];
    std::string separator_str = ",";
    std::string temp_cls = "TC";
    float temperature;
    float pressure;
    float humidity;
    int32_t ret;
 
    logInfo("Joined Network"); 

    
    while (true) {
        data.clear();
    
        // Temperature
        temperature = b280.getTemperature();
        sprintf(string_buffer, "%s%3.2f", "TC:", temperature);
        logInfo("The temperature is %s", string_buffer);
        for (int i = 0; i<strlen(string_buffer); i++)
        {
            data.push_back(((char*)string_buffer)[i]);
        }
            
        logDebug("Sending LoRa message, length: %d", data.size());
        logDebug("sending data: ");
        for(int i = 0; i < data.size(); i++)
        {
            printf("%c", data[i]);
        }
        printf("\n");
        
        // send the data to the gateway
        if ((ret = dot->send(data)) != mDot::MDOT_OK) {
            logError("failed to send", ret, mDot::getReturnCodeString(ret).c_str());
        } else {
            logInfo("successfully sent data to gateway");
        }

        // in the 868 (EU) frequency band, we need to wait until another channel is available before transmitting again
        osDelay(std::max((uint32_t)5000, (uint32_t)dot->getNextTxMs()));
        data.clear();    

        // Pressure
        pressure = b280.getPressure();
        sprintf(string_buffer, "%s%04.2f", "hPa:", pressure);
        logInfo("The pressure is %s", string_buffer);
        for (int i = 0; i<strlen(string_buffer); i++)
        {
            data.push_back(((char*)string_buffer)[i]);
        }
            
        logDebug("Sending LoRa message, length: %d", data.size());
        logDebug("sending data: ");
        for(int i = 0; i < data.size(); i++)
        {
            printf("%c", data[i]);
        }
        printf("\n");
        
        // send the data to the gateway
        if ((ret = dot->send(data)) != mDot::MDOT_OK) {
            logError("failed to send", ret, mDot::getReturnCodeString(ret).c_str());
        } else {
            logInfo("successfully sent data to gateway");
        }

        // in the 868 (EU) frequency band, we need to wait until another channel is available before transmitting again
        osDelay(std::max((uint32_t)5000, (uint32_t)dot->getNextTxMs()));        
        
        data.clear();        
        
        // Humidity
        humidity = b280.getHumidity();
        sprintf(string_buffer, "%s%03.2f", "H%:", humidity);
        logInfo("The humidty is %s", string_buffer);
    
        for (int i = 0; i<strlen(string_buffer); i++)
        {
            data.push_back(((char*)string_buffer)[i]);
        }
            
        logDebug("Sending LoRa message, length: %d", data.size());
        logDebug("sending data: ");
        for(int i = 0; i < data.size(); i++)
        {
            printf("%c", data[i]);
        }
        printf("\n");
        
        // send the data to the gateway
        if ((ret = dot->send(data)) != mDot::MDOT_OK) {
            logError("failed to send", ret, mDot::getReturnCodeString(ret).c_str());
        } else {
            logInfo("successfully sent data to gateway");
        }

        // in the 868 (EU) frequency band, we need to wait until another channel is available before transmitting again
        osDelay(std::max((uint32_t)5000, (uint32_t)dot->getNextTxMs()));

        data.clear();

        // Light Level
        llevel = readLightSensor();
        sprintf(string_buffer, "%s%5.1f", "LL:", llevel);
        for (int i = 0; i<strlen(string_buffer); i++)
        {
            data.push_back(((char*)string_buffer)[i]);
        }
        logDebug("Sending LoRa message, length: %d", data.size());
        logDebug("sending data: ");
        for(int i = 0; i < data.size(); i++)
        {
            printf("%c", data[i]);
        }
        printf("\n");
        
        // send the data to the gateway
        if ((ret = dot->send(data)) != mDot::MDOT_OK) {
            logError("failed to send", ret, mDot::getReturnCodeString(ret).c_str());
        } else {
            logInfo("successfully sent data to gateway");
        }

        // in the 868 (EU) frequency band, we need to wait until another channel is available before transmitting again
        osDelay(std::max((uint32_t)5000, (uint32_t)dot->getNextTxMs()));
        
    }
    
}


/*****************************************************
 *         mDot Functions
 ****************************************************/


void mDotConfig() {
    // get a mDot handle
    dot = mDot::getInstance();
    //dot->setLogLevel(mts::MTSLog::INFO_LEVEL);
    dot->setLogLevel(mts::MTSLog::TRACE_LEVEL);
   
}

void mDotGotoDeepSleep(int seconds) {
    // logInfo("input to sleep routine %d", seconds);
    // Should  sleep here and wakeup after a set interval.
    uint32_t sleep_time = MAX((dot->getNextTxMs() / 1000), seconds);
    logInfo("going to sleep for %d seconds", sleep_time);
    // go to sleep and wake up automatically sleep_time seconds later
    //dot->sleep(sleep_time, mDot::RTC_ALARM, false);
    dot->sleep(sleep_time, mDot::RTC_ALARM);

}
void setupNetwork(){
    int32_t ret;
    std::vector<uint8_t> send_data;
    std::vector<uint8_t> recv_data;
    std::vector<uint8_t> nwkSKey;
    std::vector<uint8_t> appSKey;
    std::vector<uint8_t> nodeAddr;
    std::vector<uint8_t> networkAddr;
    // from OTAA
    std::vector<uint8_t> appEUI;
    std::vector<uint8_t> appKey;
    
    // get a mDot handle
    // dot = mDot::getInstance();
    
    //*******************************************
    // configuration
    //*******************************************
    
    //dot->setLogLevel(mts::MTSLog::INFO_LEVEL);
    //dot->setLogLevel(mts::MTSLog::TRACE_LEVEL);
    //logInfo("Checking Config");
 
    // Test if we've already saved the config
    std::string configNetworkName = dot->getNetworkName();
 
    uint8_t *it = NwkSKey;
    for (uint8_t i = 0; i<16; i++)
        nwkSKey.push_back((uint8_t) *it++);
    it = AppSKey;
    for (uint8_t i = 0; i<16; i++)
        appSKey.push_back((uint8_t) *it++);
        
        
    it = AppEUI;
    for (uint8_t i = 0; i<8; i++)
        appEUI.push_back((uint8_t) *it++);
    
    it = AppKey;
    for (uint8_t i = 0; i<16; i++)
        appKey.push_back((uint8_t) *it++);    
 
    it = NetworkAddr;
    for (uint8_t i = 0; i<4; i++)
        networkAddr.push_back((uint8_t) *it++);
 
    logInfo("Resetting Config");
    // reset to default config so we know what state we're in
    dot->resetConfig();
 
    // Set byte order - AEP less than 1.0.30
    //dot->setJoinByteOrder(mDot::MSB);       // This is default for > 1.0.30 Conduit
 
    // Set Spreading Factor, higher is lower data rate, smaller packets but longer range
    // Lower is higher data rate, larger packets and shorter range.
    logInfo("Set SF");
    //if((ret = dot->setTxDataRate( mDot::SF_10 )) != mDot::MDOT_OK) {
    if((ret = dot->setTxDataRate( mDot::SF_8 )) != mDot::MDOT_OK) { 
        logError("Failed to set SF %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
    }
 
    //logInfo("Set TxPower");
    //if((ret = dot->setTxPower( LORA_TXPOWER )) != mDot::MDOT_OK) {
    //    logError("Failed to set Tx Power %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
    //}
 
    logInfo("Set Public mode");
    if((ret = dot->setPublicNetwork(true)) != mDot::MDOT_OK) {
        logError("failed to set Public Mode %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
    }
 
    //logInfo("Set MANUAL Join mode");
    //if((ret = dot->setJoinMode(mDot::MANUAL)) != mDot::MDOT_OK) {
    //    logError("Failed to set MANUAL Join Mode %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
    //}
    
    logInfo("Set AUTO_OTA Join mode");
    if((ret = dot->setJoinMode(mDot::AUTO_OTA)) != mDot::MDOT_OK) {
        logError("Failed to set AUTO_OTA Join Mode %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
    }
 
    logInfo("Set Ack");
    // 1 retries on Ack, 0 to disable
    if((ret = dot->setAck( LORA_ACK)) != mDot::MDOT_OK) {
        logError("Failed to set Ack %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
    }
 
//    Not applicable for 868MHz in EU
    if ((ret = dot->setFrequencySubBand(config_frequency_sub_band)) != mDot::MDOT_OK) {
        logError("Failed to set frequency sub band %s", ret);
    }
 
    logInfo("Set Network Address");
    if ((ret = dot->setNetworkAddress(networkAddr)) != mDot::MDOT_OK) {
        logError("Failed to set Network Address %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
    }
 
    logInfo("Set Data Session Key");
    if ((ret = dot->setDataSessionKey(appSKey)) != mDot::MDOT_OK) {
        logError("Failed to set Data Session Key %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
    }
 
    logInfo("Set Network Session Key");
    if ((ret = dot->setNetworkSessionKey(nwkSKey)) != mDot::MDOT_OK) {
        logError("Failed to set Network Session Key %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
    }
    
    logInfo("Set Network Id");
    if ((ret = dot->setNetworkId(appEUI)) != mDot::MDOT_OK) {
        logError("Failed to set Network Id %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
    }
    logInfo("Set Network Key");
    if ((ret = dot->setNetworkKey(appKey)) != mDot::MDOT_OK) {
        logError("Failed to set Network Id %d:%s", ret, mDot::getReturnCodeString(ret).c_str());
    }
 
    logInfo("Saving Config");
    // Save config
    if (! dot->saveConfig()) {
        logError("failed to save configuration");
    }
 
     //*******************************************
    // end of configuration
    //*******************************************
    
    mDotConfigPrint();

    //char dataBuf[50];
    
    
    
    
}

void joinNetwork() {
    int32_t ret;
    logInfo("Joining Network");
    
    while ((ret = dot->joinNetwork()) != mDot::MDOT_OK) {
        logError("failed to join network [%d][%s]", ret, mDot::getReturnCodeString(ret).c_str());
        //wait_ms(dot->getNextTxMs() + 1);
        osDelay(std::max((uint32_t)1000, (uint32_t)dot->getNextTxMs()));
    }
    logInfo("Joined Network"); 
    wait(5);
    
}



void mDotConfigPrint() {

    // Display what is set
    printf("\r\n");
    printf(" **********  mDot Configuration ************ \n");
     // print library version information
    logInfo("Firmware Version: %s", dot->getId().c_str());
    
    std::vector<uint8_t> tmp = dot->getNetworkSessionKey();
    printf("Network Session Key: ");
    printf("%s\n", mts::Text::bin2hexString(tmp, " ").c_str());
    
    tmp = dot->getDataSessionKey();
    printf("Data Session Key: ");
    printf("%s\n", mts::Text::bin2hexString(tmp, " ").c_str());
    
    tmp = dot->getNetworkId();
    printf("App EUI: ");
    printf("%s\n", mts::Text::bin2hexString(tmp, " ").c_str());
        
    tmp = dot->getNetworkKey();
    printf("App Key: ");
    printf("%s\n", mts::Text::bin2hexString(tmp, " ").c_str());    
    
    printf("Device ID ");
    std::vector<uint8_t> deviceId;
    deviceId = dot->getDeviceId();
    for (std::vector<uint8_t>::iterator it = deviceId.begin() ; it != deviceId.end(); ++it)
        printf("%2.2x",*it );
    printf("\n");
    std::vector<uint8_t> netAddress;
 
    printf("Network Address ");
    netAddress = dot->getNetworkAddress();
    for (std::vector<uint8_t>::iterator it = netAddress.begin() ; it != netAddress.end(); ++it)
        printf("%2.2x",*it );
    printf("\n");
 
    // Display LoRa parameters
    // Display label and values in different colours, show pretty values not numeric values where applicable
    printf("Public Network: %s\n", (char*)(dot->getPublicNetwork() ? "Yes" : "No") );
    printf("Frequency: %s\n", (char*)mDot::FrequencyBandStr(dot->getFrequencyBand()).c_str() );
    printf("Sub Band: %s\n", (char*)mDot::FrequencySubBandStr(dot->getFrequencySubBand()).c_str() );
    printf("Join Mode: %s\n", (char*)mDot::JoinModeStr(dot->getJoinMode()).c_str() );
    printf("Join Retries: %d\n", dot->getJoinRetries() );
    printf("Join Byte Order: %s\n", (char*)(dot->getJoinByteOrder() == 0 ? "LSB" : "MSB") );
    printf("Link Check Count: %d\n", dot->getLinkCheckCount() );
    printf("Link Check Thold: %d\n", dot->getLinkCheckThreshold() );
    printf("Tx Data Rate: %s\n", (char*)mDot::DataRateStr(dot->getTxDataRate()).c_str() );
    printf("Tx Power: %d\n", dot->getTxPower() );
    printf("TxWait: %s, ", (dot->getTxWait() ? "Y" : "N" ));
    printf("CRC: %s, ", (dot->getCrc() ? "Y" : "N") );
    printf("Ack: %s\n", (dot->getAck() ? "Y" : "N")  );



}



/*****************************************************
 *         Sensor Functions
 ****************************************************/


void readandprintBME280() {
    float temperature;
    float pressure;
    float humidity;
    char string_buffer[64];
    //time_t secs;
    
    //secs = time(NULL);
    //printf("Seconds since January 1, 1970: %d\n", secs);
    //printf("Time as a basic string = %s", ctime(&secs));
    
    // Temperature
    temperature = b280.getTemperature();
    sprintf(string_buffer, "%s%3.2f", "TC:", temperature);
    logInfo("The temperature is %s", string_buffer);
    // Pressure
    pressure = b280.getPressure();
    sprintf(string_buffer, "%s%04.2f", "hPa:", pressure);
    logInfo("The pressure is %s", string_buffer);
    // Humidity
    humidity = b280.getHumidity();
    sprintf(string_buffer, "%s%03.2f", "H%:", humidity);
    logInfo("The humidty is %s", string_buffer);
    
    //printf("%2.2f degC, %04.2f hPa, %2.2f %%\n", temperature, pressure, humidity);
}

float readLightSensor() {
    float sensorValue;
    float rsensor; 
    sensorValue = light.read();
    rsensor = (float)(1023-sensorValue)*10/sensorValue;
    printf("Sensor reading: %2.2f - %2.2f\r\n", sensorValue, rsensor);
  
    return rsensor;

}

/*****************************************************
 *         FUNCTIONS for Simple Testing
 ****************************************************/

void setUpLEDBlink(){
    // configure the Ticker to blink the LED on 500ms interval
    tick.attach(&blink, 0.5);
}

void endLessTestLoop() {
    while(true) {
        // printf("Hello world!\r\n");
        //printf("BME280 Sensor: \n");
        readandprintBME280();
        
        wait(5);
        //mDotGotoDeepSleep(60);
        //wait(5);
       
    }
}

// Callback function to change LED state
void blink() {
    led = !led;
}