![](/media/cache/profiles/2dd26bee3d25f4e22c3db125e415203a.jpg.50x50_q85.jpg)
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-13
- Revision:
- 13:22e11a02c7a3
- Parent:
- 11:3481e24747e2
File content as of revision 13:22e11a02c7a3:
/****************************************************** * 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 * Uses Standard Firmware from Multitech * *****************************************************/ #include "mbed.h" #include "mDot.h" #include "MTSLog.h" #include "MTSText.h" #include <string> #include "LoRa.h" #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)) // 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 // Function Declarations void endLessTestLoop(); void setUpLEDBlink(); void blink(); void readandprintBME280(); float readLightSensor(); void mDotConfig(); void mDotGotoDeepSleep(int seconds, bool sleepState); 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(); // Moved to mDotConfig 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; 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"); } // Goto Sleep, commenting out the osDelay since next Tx would be after waking up mDotGotoDeepSleep(60, false); // 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(); // Test if we've already saved the config logInfo("Checking Config"); std::string configNetworkName = dot->getNetworkName(); printf("Network Name is %s: \n", (char*)configNetworkName.c_str()); printf("Network Name is %s: \n", (char*)(config_network_name.c_str())); if (configNetworkName.compare(config_network_name) != 0) { logInfo("Setting Up Config"); setupNetwork(); } else { logInfo("Config is good, skipping setting up... "); } } void mDotGotoDeepSleep(int seconds, bool sleepState) { // 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, sleepState); } 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; //******************************************* // configuration //******************************************* 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(); //dot->setLogLevel(mts::MTSLog::INFO_LEVEL); dot->setLogLevel(mts::MTSLog::TRACE_LEVEL); logInfo("Setting Network name"); if ((ret = dot->setNetworkName(config_network_name)) != mDot::MDOT_OK) { logError("failed to set network name %d:%s", ret, mDot::getReturnCodeString(ret).c_str()); } logInfo("Setting Network password"); if ((ret = dot->setNetworkPassphrase(config_network_pass)) != mDot::MDOT_OK) { logError("failed to set network password %d:%s", ret, mDot::getReturnCodeString(ret).c_str()); } // Set byte order dot->setJoinByteOrder(mDot::LSB); // 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(); } 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"); } 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("Network Name: %s\n", (char *)(dot->getNetworkName()).c_str()); printf("Network Name: %s\n", (char *)(dot->getNetworkPassphrase()).c_str()); 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(); mDotGotoDeepSleep(60, true); //wait(10); } } // Callback function to change LED state void blink() { led = !led; }