Factory firmware for the MultiTech Dotbox (MTDOT-BOX) and EVB (MTDOT-EVB) products.

Dependencies:   NCP5623B GpsParser ISL29011 libmDot-mbed5 MTS-Serial MMA845x DOGS102 MPL3115A2

MTDOT-BOX/EVB Firmware Description

This Firmware is what ships on DotBox and EVB devices. It is intended to be used as a proof of concept and site survey tool for planning LoRa deployments. The firmware provides a number of different modes of operation:

  • Configuration - Use AT commands to configure network credentials, TX power, TX data rate, view the survey data file, etc.
  • Survey Single - Test network connectivity at current location at a specific TX power and TX data rate. Uplink information, downlink information, and GPS information are saved to the survey data file and can also be sent to the gateway.
  • Survey Sweep - Test network connectivity at current location across a range of TX powers and TX data rates. Uplink information, downlink information, and GPS information for each survey in the sweep are saved to the survey data file and can also be sent to the gateway.
  • LoRa Demo - Gather data from onboard sensors and display it on the screen in real time. Send packets containing sensor data to the gateway either on an interval or when triggered by the user. GPS data is not transmitted.
  • Survey GPS - Gather sensor and GPS data and transmit it to the gateway either on an interval or when triggered by the user. Add padding to packets, switch frequency sub bands, TX power, TX data rate, and more all without exiting Survey GPS Mode.
  • View Data - View the survey data file on the screen one survey at a time.

Additional documentation and information for the MTDOT-BOX/EVB Factory Firmware can be found here.


Dot Libraries

Dot Library Limitations

The commit messages in libmDot-mbed5 and libmDot-dev-mbed5 specify the version of the Dot library the commit contains and the version of mbed-os it was compiled against. We recommend building your application with the version of mbed-os specified in the commit message of the version of the Dot library you're using. This will ensure that you don't run into any runtime issues caused by differences in the mbed-os versions.

Development library for mDot.

[Repository '/teams/MultiTech/code/libmDot-dev-mbed5/' not found]

Stable library for mDot.

Import librarylibmDot-mbed5

Stable version of the mDot library for mbed 5. This version of the library is suitable for deployment scenarios. See lastest commit message for version of mbed-os library that has been tested against.

Files at this revision

API Documentation at this revision

Comitter:
jenkins@jenkinsdm1
Date:
Tue Oct 09 13:49:30 2018 -0500
Parent:
11:19ce32436b9b
Child:
13:20bdea8bb997
Commit message:
dotbox-firmware revision 3.1.1

Changed in this revision

CommandTerminal/CmdDisplayConfig.cpp Show annotated file Show diff for this revision Revisions of this file
CommandTerminal/CmdFactoryDefault.cpp Show annotated file Show diff for this revision Revisions of this file
CommandTerminal/CmdFrequencyBand.cpp Show annotated file Show diff for this revision Revisions of this file
CommandTerminal/CmdFrequencyBand.h Show annotated file Show diff for this revision Revisions of this file
CommandTerminal/CmdPublicNetwork.cpp Show annotated file Show diff for this revision Revisions of this file
CommandTerminal/CmdTxDataRate.cpp Show annotated file Show diff for this revision Revisions of this file
CommandTerminal/Command.h Show annotated file Show diff for this revision Revisions of this file
CommandTerminal/Commands.h Show annotated file Show diff for this revision Revisions of this file
Layout/Layout.h Show annotated file Show diff for this revision Revisions of this file
Layout/LayoutJoin.cpp Show annotated file Show diff for this revision Revisions of this file
Layout/LayoutScrollSelect.cpp Show annotated file Show diff for this revision Revisions of this file
Layout/LayoutStartup.cpp Show annotated file Show diff for this revision Revisions of this file
Layout/LayoutStartup.h Show annotated file Show diff for this revision Revisions of this file
Layout/LayoutSurveyFailure.cpp Show annotated file Show diff for this revision Revisions of this file
Layout/LayoutSurveyGps.cpp Show annotated file Show diff for this revision Revisions of this file
Layout/LayoutSurveySuccess.cpp Show annotated file Show diff for this revision Revisions of this file
LoRaHandler/LoRaHandler.cpp Show annotated file Show diff for this revision Revisions of this file
LoRaHandler/LoRaHandler.h Show annotated file Show diff for this revision Revisions of this file
Mode/Mode.cpp Show annotated file Show diff for this revision Revisions of this file
Mode/Mode.h Show annotated file Show diff for this revision Revisions of this file
Mode/ModeConfig.cpp Show annotated file Show diff for this revision Revisions of this file
Mode/ModeDemo.cpp Show annotated file Show diff for this revision Revisions of this file
Mode/ModeGps.cpp Show annotated file Show diff for this revision Revisions of this file
Mode/ModeJoin.cpp Show annotated file Show diff for this revision Revisions of this file
Mode/ModeSingle.cpp Show annotated file Show diff for this revision Revisions of this file
Mode/ModeSweep.cpp Show annotated file Show diff for this revision Revisions of this file
Mode/ModeSweep.h Show annotated file Show diff for this revision Revisions of this file
SensorHandler/SensorHandler.cpp Show annotated file Show diff for this revision Revisions of this file
SensorHandler/SensorHandler.h Show annotated file Show diff for this revision Revisions of this file
dotbox_version.h Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
--- a/CommandTerminal/CmdDisplayConfig.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/CommandTerminal/CmdDisplayConfig.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -38,10 +38,22 @@
     _serial.writef("%s\r\n", mts::Text::bin2hexString(_dot->getDeviceId(), ":").c_str());
 
     _serial.writef("Frequency Band:\t\t%s\r\n", mDot::FrequencyBandStr(_dot->getFrequencyBand()).c_str());
-    if (_dot->getFrequencyBand() == mDot::FB_US915)
+    if (lora::ChannelPlan::IsPlanFixed(_dot->getFrequencyBand()))
 	_serial.writef("Frequency Sub Band:\t%u\r\n", _dot->getFrequencySubBand());
 
-    _serial.writef("Public Network:\t\t%s\r\n", _dot->getPublicNetwork() ? "on" : "off");
+    std::string network_mode("Undefined");
+    uint8_t network_type = _dot->getPublicNetwork();
+    if (network_type == lora::PRIVATE_MTS)
+        network_mode = "Private MTS";
+    else if (network_type == lora::PUBLIC_LORAWAN)
+        network_mode = "Public LoRaWAN";
+    else if (network_type == lora::PRIVATE_LORAWAN)
+        network_mode = "Private LoRaWAN";
+    else if (network_type == lora::PEER_TO_PEER)
+        network_mode = "Peer to Peer";
+    _serial.writef("Public Network:\t\t%s\r\n", network_mode.c_str());
+
+    _serial.writef("Join Delay:\t\t%u seconds\r\n", _dot->getJoinDelay());
 
     _serial.writef("Network Address:\t%s\r\n", mts::Text::bin2hexString(_dot->getNetworkAddress()).c_str());
 
@@ -65,8 +77,7 @@
 
     _serial.writef("Tx Data Rate:\t\t%s\r\n", mDot::DataRateStr(_dot->getTxDataRate()).c_str());
     _serial.writef("Tx Power:\t\t%u\r\n", _dot->getTxPower());
-    //_serial.writef("Log Level:\t\t%ld\r\n", _dot->getLogLevel());
-    _serial.writef("Log Level:\t\t%ld\r\n", mts::MTSLog::TRACE_LEVEL);
+    _serial.writef("Log Level:\t\t%u\r\n", _dot->getLogLevel());
 
     _serial.writef("Maximum Size:\t\t%u\r\n",	_dot->getWakeDelay());		//DotBox +MaxSize is stored here.
     _serial.writef("Minimum Size:\t\t%u\r\n",	_dot->getWakeInterval());	//DotBox +MinSize is stored here.
--- a/CommandTerminal/CmdFactoryDefault.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/CommandTerminal/CmdFactoryDefault.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -42,7 +42,7 @@
     _dot->setJoinMode(mDot::OTA);
     _dot->setNetworkName("MultiTech");
     _dot->setNetworkPassphrase("MultiTech");
-	
+    _dot->deleteUserFile("ChannelPlan");
     _dot->resetNetworkSession();
     return 0;
 }
--- a/CommandTerminal/CmdFrequencyBand.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/CommandTerminal/CmdFrequencyBand.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -1,96 +1,104 @@
-/* Copyright (c) <2016> <MultiTech Systems>, MIT License
- *
- * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
- * and associated documentation files (the "Software"), to deal in the Software without restriction, 
- * including without limitation the rights to use, copy, modify, merge, publish, distribute, 
- * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is 
- * furnished to do so, subject to the following conditions:
- *
- * The above copyright notice and this permission notice shall be included in all copies or 
- * substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING 
- * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 
- * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 
- * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- */
-
 #include "CmdFrequencyBand.h"
-
-CmdFrequencyBand::CmdFrequencyBand(mDot* dot, mts::MTSSerial& serial) :
-        Command(dot, "Frequency Band", "AT+FREQ", "Configured Frequency Band 'EU868', 'AU915' or 'US915'"), _serial(serial)
+#include "ChannelPlans.h"
+CmdFrequencyBand::CmdFrequencyBand(mDot* dot, mts::MTSSerial& serial)
+    : Command(dot,"Current Frequency Band", "AT+FREQ", "Select Frequency Band 'US915', 'AU915', 'EU868', 'AS923', 'AS923-JAPAN','KR920', or 'IN865'")
+    , _serial(serial)
 {
-    _help = std::string(text()) + ": " + std::string(desc());
-    _usage = "(EU868,AU915,US915)";
-    _queryable = true;
+      _help = std::string(text()) + ": " + std::string(desc());
+      _usage = "";
+      _queryable = true;
 }
 
 uint32_t CmdFrequencyBand::action(std::vector<std::string> args)
-{
+                                  {
     if (args.size() == 1)
     {
-        if (_dot->getVerbose())
+        // using getChannelPlanName here instead of mDot::FrequencyBandStr allows AT firmware to properly display custom channel plan names
+        if(_dot->getVerbose())
             _serial.writef("Frequency Band: ");
 
-        _serial.writef("%s\r\n", mDot::FrequencyBandStr(_dot->getFrequencyBand()).c_str());
+        _serial.writef("%s\r\n", _dot->getChannelPlanName().c_str());
     }
-
-#ifdef DEBUG_MAC
-    else if (args.size() == 2)
+         
+     else if (args.size() == 2)
     {
-        int32_t code;
+        std::string band_str = mts::Text::toUpper(args[1]);
+        lora::ChannelPlan* plan = _dot->getChannelPlan();
+        mDot::mdot_file file = _dot->openUserFile("ChannelPlan", mDot::FM_RDWR);
+        _dot->seekUserFile(file, 0, SEEK_SET);
+        uint8_t cp[] = {0};
 
-        std::string text = mts::Text::toUpper(args[1]);
-
-        uint8_t band = mDot::FB_US915;
-
-
-        if (mDot::FrequencyBandStr(mDot::FB_EU868).find(text) != std::string::npos) {
-            band = mDot::FB_EU868;
+        if (mDot::FrequencyBandStr(lora::ChannelPlan::US915) == band_str) {
+            if(plan != NULL) delete plan;
+            plan = new lora::ChannelPlan_US915();
+            cp[0] = CP_US915;
+        }
+        else if (mDot::FrequencyBandStr(lora::ChannelPlan::AU915) == band_str) {
+            if(plan != NULL) delete plan;
+            plan = new lora::ChannelPlan_AU915();
+            cp[0] = CP_AU915;
+        }
+        else if (mDot::FrequencyBandStr(lora::ChannelPlan::EU868) == band_str) {
+            if(plan != NULL) delete plan;
+            plan = new lora::ChannelPlan_EU868();
+             cp[0] = CP_EU868;
+        }
+        else if (mDot::FrequencyBandStr(lora::ChannelPlan::AS923) == band_str) {
+            if(plan != NULL) delete plan;
+            plan = new lora::ChannelPlan_AS923();
+             cp[0] = CP_AS923;
+	}
+        else if (mDot::FrequencyBandStr(lora::ChannelPlan::KR920) == band_str) {
+            if(plan != NULL) delete plan;
+            plan = new lora::ChannelPlan_KR920();
+             cp[0] = CP_KR920;
+        }
+        else if (mDot::FrequencyBandStr(lora::ChannelPlan::IN865) == band_str) {
+            if(plan != NULL) delete plan;
+            plan = new lora::ChannelPlan_IN865();
+             cp[0] = CP_IN865;
+        }
+	else if (mDot::FrequencyBandStr(lora::ChannelPlan::AS923_JAPAN) == band_str) {
+            if(plan != NULL) delete plan;
+            plan = new lora::ChannelPlan_AS923_Japan();
+             cp[0] = CP_AS923_JAPAN;
         }
 
-        if (mDot::FrequencyBandStr(mDot::FB_AU915).find(text) != std::string::npos) {
-            band = mDot::FB_AU915;
+        if(cp[0] > 0) {
+            _dot->writeUserFile(file, cp, 1);
         }
+        _dot->closeUserFile(file);
 
-        if (mDot::FrequencyBandStr(mDot::FB_US915).find(text) != std::string::npos) {
-            band = mDot::FB_US915;
-        }
+        _serial.writef("Setting Plan \r\n");
 
-        if ((code = _dot->setFrequencyBand(band)) != mDot::MDOT_OK) {
-            std::string error = mDot::getReturnCodeString(code) + " - " + _dot->getLastError();
-            setErrorMessage(error);
+        if (_dot->setChannelPlan(plan) != mDot::MDOT_OK) {
+            setErrorMessage(_dot->getLastError());
             return 1;
         }
     }
-#endif
-
     return 0;
 }
 
 bool CmdFrequencyBand::verify(std::vector<std::string> args)
-{
+                              {
     if (args.size() == 1)
         return true;
 
-#ifdef DEBUG_MAC
     if (args.size() == 2)
     {
         std::string band = mts::Text::toUpper(args[1]);
 
-        if (mDot::FrequencyBandStr(mDot::FB_EU868).find(band) == std::string::npos &&
-            mDot::FrequencyBandStr(mDot::FB_US915).find(band) == std::string::npos &&
-            mDot::FrequencyBandStr(mDot::FB_AU915).find(band) == std::string::npos)
+        if (mDot::FrequencyBandStr(lora::ChannelPlan::US915) != band &&
+            mDot::FrequencyBandStr(lora::ChannelPlan::AU915) != band &&
+            mDot::FrequencyBandStr(lora::ChannelPlan::EU868) != band &&
+            mDot::FrequencyBandStr(lora::ChannelPlan::AS923) != band &&
+            mDot::FrequencyBandStr(lora::ChannelPlan::KR920) != band &&
+            mDot::FrequencyBandStr(lora::ChannelPlan::IN865) != band &&
+            mDot::FrequencyBandStr(lora::ChannelPlan::AS923_JAPAN) != band)
         {
-            setErrorMessage("Invalid parameter, expects (EU868,AU915,US915)");
+            setErrorMessage("Invalid parameter, expects (US915,AU915,EU868,AS923,AS923-JAPAN,KR920,IN865)");
             return false;
         }
-
-        return true;
+    return true;
     }
-#endif
-
-    setErrorMessage("Invalid arguments");
-    return false;
 }
--- a/CommandTerminal/CmdFrequencyBand.h	Thu Nov 10 22:10:58 2016 +0000
+++ b/CommandTerminal/CmdFrequencyBand.h	Tue Oct 09 13:49:30 2018 -0500
@@ -32,7 +32,6 @@
     virtual bool verify(std::vector<std::string> args);
     
 private:   
-
     mts::MTSSerial& _serial;
 };
 
--- a/CommandTerminal/CmdPublicNetwork.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/CommandTerminal/CmdPublicNetwork.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -18,11 +18,12 @@
 
 #include "CmdPublicNetwork.h"
 
-CmdPublicNetwork::CmdPublicNetwork(mDot* dot, mts::MTSSerial& serial) :
-        Command(dot, "Public Network", "AT+PN", "Enable/disable public network mode. (0: off, 1: on)"), _serial(serial)
+CmdPublicNetwork::CmdPublicNetwork(mDot* dot, mts::MTSSerial& serial)
+    : Command(dot, "Network Mode", "AT+PN", "Set public network mode (0: PRIVATE_MTS, 1: PUBLIC_LORAWAN, 2: PRIVATE_LORAWAN)")
+    , _serial(serial)
 {
     _help = std::string(text()) + ": " + std::string(desc());
-    _usage = "(0,1)";
+    _usage = "(0,2)";
     _queryable = true;
 }
 
@@ -38,9 +39,14 @@
     else if (args.size() == 2)
     {
         int32_t code;
-        bool enable = (args[1] == "1");
+        uint8_t mode = lora::PRIVATE_MTS;
 
-        if ((code = _dot->setPublicNetwork(enable)) != mDot::MDOT_OK) {
+        if (args[1] == "1")
+            mode = lora::PUBLIC_LORAWAN;
+        else if (args[1] == "2")
+            mode = lora::PRIVATE_LORAWAN;
+
+        if ((code = _dot->setPublicNetwork(mode)) != mDot::MDOT_OK) {
             std::string error = mDot::getReturnCodeString(code) + " - " + _dot->getLastError();
             setErrorMessage(error);
             return 1;
@@ -57,8 +63,8 @@
 
     if (args.size() == 2)
     {
-        if (args[1] != "1" && args[1] != "0") {
-            setErrorMessage("Invalid parameter, expects (0: off, 1: on)");
+        if (args[1] != "2" && args[1] != "1" && args[1] != "0") {
+            setErrorMessage("Invalid parameter, expects (0: PRIVATE_MTS, 1: PUBLIC_LORAWAN, 2: PRIVATE_LORAWAN)");
             return false;
         }
 
--- a/CommandTerminal/CmdTxDataRate.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/CommandTerminal/CmdTxDataRate.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -25,21 +25,13 @@
   _serial(serial)
 {
     _help = std::string(text()) + ": " + std::string(desc());
-
-    if (_dot->getFrequencyBand() == mDot::FB_EU868)
-        _usage = "(7-12|DR0-DR7)";
-    else
-        _usage = "(7-10|DR0-DR4|DR8-DR13)";
-
+    _usage = "7-10|DR0-DR15, Depends on Channel Plan";
     _queryable = true;
 }
 
 uint32_t CmdTxDataRate::action(std::vector<std::string> args) {
     if (args.size() == 1)
         {
-        if (_dot->getVerbose())
-            _serial.writef("Tx Data Rate: ");
-
         _serial.writef("DR%d - %s\r\n", _dot->getTxDataRate(), _dot->getDateRateDetails(_dot->getTxDataRate()).c_str());
     } else if (args.size() == 2) {
         std::string dr = mts::Text::toUpper(args[1]);
@@ -56,15 +48,6 @@
                     break;
                 }
             }
-        } else {
-            if (datarate > 6) {
-                // Convert SF to DR
-                if (_dot->getFrequencyBand() == mDot::FB_US915 || _dot->getFrequencyBand() == mDot::FB_AU915 ) {
-                    datarate = 10 - datarate;
-                } else {
-                    datarate = 12 - datarate;
-                }
-            }
         }
 
         if ((code = _dot->setTxDataRate(datarate)) != mDot::MDOT_OK) {
@@ -80,71 +63,8 @@
     if (args.size() == 1)
         return true;
 
-    if (args.size() == 2) {
-        std::string dr = mts::Text::toUpper(args[1]);
-
-        uint8_t i;
-        int datarate = -1;
-
-        int res = sscanf(dr.c_str(), "%d", &datarate);
-
-        if (res == 0) {
-            for (i = 0; i < 24; i++) {
-
-                if (mDot::DataRateStr(i).find(dr) != std::string::npos) {
-                    uint8_t _dr = i;
-
-                    if (_dr > 15) {
-                        _dr = 12 + (mDot::SF_12 - _dr);
-
-                        if (_dot->getFrequencyBand() == mDot::FB_EU868) {
-                            if (_dr == mDot::SF_7H) {
-                                _dr =  mDot::DR6;
-                            } else if (_dr ==  mDot::SF_FSK) {
-                                _dr =  mDot::DR7;
-                            } else {
-                                _dr = 12 - _dr;
-                            }
-                        } else {
-
-                            _dr = 10 - _dr;
-                        }
-                    }
-
-                    datarate = _dr;
-                    break;
-                }
-            }
-        } else {
-            if ((_dot->getFrequencyBand() == mDot::FB_US915 || _dot->getFrequencyBand() == mDot::FB_AU915) && datarate > 10) {
-                datarate = -1;
-            } else if (_dot->getFrequencyBand() == mDot::FB_EU868 && datarate > 12) {
-                datarate = -1;
-            } else if (datarate > 6) {
-                // Convert SF to DR
-                if (_dot->getFrequencyBand() == mDot::FB_US915 || _dot->getFrequencyBand() == mDot::FB_AU915 ) {
-                    datarate = 10 - datarate;
-                } else {
-                    datarate = 12 - datarate;
-                }
-            }
-        }
-
-        if (_dot->getFrequencyBand() == mDot::FB_US915 || _dot->getFrequencyBand() == mDot::FB_AU915 ) {
-            // DR8-13 used for P2P modes
-            if (datarate < 0 || datarate > 13 || (datarate >= 5 && datarate <= 7)) {
-                setErrorMessage("Invalid data rate, expects (7-10|DR0-DR4|DR8-DR13)");
-                return false;
-            }
-        } else {
-            if (datarate < 0 || datarate > 7) {
-                setErrorMessage("Invalid data rate, expects (7-12|DR0-DR7)");
-                return false;
-            }
-        }
-
+    if (args.size() == 2)
         return true;
-    }
 
     setErrorMessage("Invalid arguments");
     return false;
--- a/CommandTerminal/Command.h	Thu Nov 10 22:10:58 2016 +0000
+++ b/CommandTerminal/Command.h	Tue Oct 09 13:49:30 2018 -0500
@@ -58,6 +58,7 @@
 #include <string>
 #include <vector>
 #include "limits.h"
+#include "ChannelPlans.h"
 
 /* Define to prevent recursive inclusion -------------------------------------*/
 #ifndef __command_H
--- a/CommandTerminal/Commands.h	Thu Nov 10 22:10:58 2016 +0000
+++ b/CommandTerminal/Commands.h	Tue Oct 09 13:49:30 2018 -0500
@@ -27,6 +27,7 @@
 #include "CmdFrequencyBand.h"
 #include "CmdDeviceId.h"
 #include "CmdPublicNetwork.h"
+#include "CmdJoinDelay.h"
 #include "CmdNetworkAddress.h"
 #include "CmdNetworkSessionKey.h"
 #include "CmdDataSessionKey.h"
--- a/Layout/Layout.h	Thu Nov 10 22:10:58 2016 +0000
+++ b/Layout/Layout.h	Tue Oct 09 13:49:30 2018 -0500
@@ -21,6 +21,7 @@
 
 #include "DOGS102.h"
 #include <string>
+#include "ChannelPlans.h"
 
 class Label {
     public:
@@ -52,7 +53,7 @@
 class Layout {
     public:
         Layout(DOGS102* lcd);
-        ~Layout();
+        virtual ~Layout();
 
         virtual void display() = 0;
         
--- a/Layout/LayoutJoin.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/Layout/LayoutJoin.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -1,4 +1,4 @@
-/* /* Copyright (c) <2016> <MultiTech Systems>, MIT License
+/* Copyright (c) <2016> <MultiTech Systems>, MIT License
  *
  * Permission is hereby granted, free of charge, to any person obtaining a copy of this software 
  * and associated documentation files (the "Software"), to deal in the Software without restriction, 
@@ -47,7 +47,7 @@
 
     writeLabel(_lId);
     writeLabel(_lKey);
-    if (_band == mDot::FB_US915 || _band == mDot::FB_AU915) {
+    if (lora::ChannelPlan::IsPlanFixed(_band)) {
         writeLabel(_lFsb);
     }
     writeLabel(_lRate);
--- a/Layout/LayoutScrollSelect.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/Layout/LayoutScrollSelect.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -49,6 +49,8 @@
     writeLabel(_lInfo2);
     writeLabel(_lCursor);
 
+    _selected = 0;
+
     switch (_size) {
         case 0:
             // special case - no items
--- a/Layout/LayoutStartup.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/Layout/LayoutStartup.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -27,10 +27,9 @@
     _lName(0, 3, "DOT-BOX/EVB"),
     _lInfo(0, 4, "Factory Firmware"),
     _lVersion(0, 5, "Version"),
-    _fName(12, 3, 5),
     _fVersion(8, 5, 9),
+    _fGps(0, 6, 17),
     _fId(0, 7, 17),
-    _fGps(0, 6, 17),
     _iLogo(0, 0, MultiTech_Logo)
 {}
 
@@ -47,7 +46,6 @@
     writeLabel(_lName);
     writeLabel(_lInfo);
     writeLabel(_lVersion);
-    writeField(_fName, mDot::FrequencyBandStr(_dot->getFrequencyBand()));
     writeField(_fVersion, version);
     writeField(_fId, id);
 
--- a/Layout/LayoutStartup.h	Thu Nov 10 22:10:58 2016 +0000
+++ b/Layout/LayoutStartup.h	Tue Oct 09 13:49:30 2018 -0500
@@ -37,7 +37,6 @@
         Label _lInfo;
         Label _lVersion;
 
-        Field _fName;
         Field _fVersion;
         Field _fGps;
         Field _fId;
--- a/Layout/LayoutSurveyFailure.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/Layout/LayoutSurveyFailure.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -74,10 +74,10 @@
     size_t size;
 
     size = snprintf(buf, sizeof(buf), "%d %d %d.%03d %c",
-        abs(lat.degrees),
-        lat.minutes,
-        (lat.seconds * 6) / 1000,
-        (lat.seconds * 6) % 1000,
+        (int) abs(lat.degrees),
+        (int) lat.minutes,
+        (int) (lat.seconds * 6) / 1000,
+        (int) (lat.seconds * 6) % 1000,
         (lat.degrees > 0) ? 'N' : 'S');
     writeField(_fGpsLat, buf, size, true);
 }
@@ -91,10 +91,10 @@
     size_t size;
 
     size = snprintf(buf, sizeof(buf), "%d %d %d.%03d %c",
-        abs(lon.degrees),
-        lon.minutes,
-        (lon.seconds * 6) / 1000,
-        (lon.seconds * 6) % 1000,
+        (int) abs(lon.degrees),
+        (int) lon.minutes,
+        (int) (lon.seconds * 6) / 1000,
+        (int) (lon.seconds * 6) % 1000,
         (lon.degrees > 0) ? 'E' : 'W');
     writeField(_fGpsLon, buf, size, true);
 }
--- a/Layout/LayoutSurveyGps.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/Layout/LayoutSurveyGps.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -58,7 +58,7 @@
     writeLabel(_lPower);
     writeLabel(_lPadding);
      
-    if (_band == mDot::FB_US915 || _band == mDot::FB_AU915) {
+    if (lora::ChannelPlan::IsPlanFixed(_band)) {
         writeLabel(_lFSB);
     }
     if(success) {
@@ -80,7 +80,7 @@
     size = snprintf(buf, sizeof(buf), "%d", power);
     writeField(_fPower, buf, size, true);
     
-    if (_band == mDot::FB_US915 || _band == mDot::FB_AU915) {
+    if (lora::ChannelPlan::IsPlanFixed(_band)) {
         memset(buf, 0, sizeof(buf));
         size = snprintf(buf, sizeof(buf), "%d", fsb);
         writeField(_fFSB, buf, size, true);
@@ -131,19 +131,19 @@
 
     if(GPS) {
         size = snprintf(buf, sizeof(buf), "%d %d %d.%03d %c",
-                        abs(lon.degrees),
-                        lon.minutes,
-                        (lon.seconds * 6) / 1000,
-                        (lon.seconds * 6) % 1000,
+                        (int) abs(lon.degrees),
+                        (int)lon.minutes,
+                       (int)(lon.seconds * 6) / 1000,
+                        (int)(lon.seconds * 6) % 1000,
                         (lon.degrees > 0) ? 'E' : 'W');
         writeField(_fGpsLon, buf, size, true);
 
         memset(buf, 0, sizeof(buf));
         size = snprintf(buf, sizeof(buf), "%d %d %d.%03d %c",
-                        abs(lat.degrees),
-                        lat.minutes,
-                        (lat.seconds * 6) / 1000,
-                        (lat.seconds * 6) % 1000,
+                        (int)abs(lat.degrees),
+                        (int)lat.minutes,
+                        (int)(lat.seconds * 6) / 1000,
+                        (int)(lat.seconds * 6) % 1000,
                         (lat.degrees > 0) ? 'N' : 'S');
         writeField(_fGpsLat, buf, size, true);
 
--- a/Layout/LayoutSurveySuccess.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/Layout/LayoutSurveySuccess.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -100,11 +100,11 @@
     size_t size;
 
     size = snprintf(buf, sizeof(buf), "%d %d %d.%03d %c",
-        abs(lat.degrees),
-        lat.minutes,
-        (lat.seconds * 6) / 1000,
-        (lat.seconds * 6) % 1000,
-        (lat.degrees > 0) ? 'N' : 'S');
+            (int) abs(lat.degrees),
+            (int) lat.minutes,
+            (int) (lat.seconds * 6) / 1000,
+            (int) (lat.seconds * 6) % 1000,
+            (lat.degrees > 0) ? 'N' : 'S');
     writeField(_fGpsLat, buf, size, true);
 }
 
@@ -117,10 +117,10 @@
     size_t size;
 
     size = snprintf(buf, sizeof(buf), "%d %d %d.%03d %c",
-        abs(lon.degrees),
-        lon.minutes,
-        (lon.seconds * 6) / 1000,
-        (lon.seconds * 6) % 1000,
+        (int) abs(lon.degrees),
+        (int) lon.minutes,
+        (int) (lon.seconds * 6) / 1000,
+        (int) (lon.seconds * 6) % 1000,
         (lon.degrees > 0) ? 'E' : 'W');
     writeField(_fGpsLon, buf, size, true);
 }
--- a/LoRaHandler/LoRaHandler.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/LoRaHandler/LoRaHandler.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -34,7 +34,6 @@
     LoRaHandler* l = (LoRaHandler*)argument;
     osEvent e;
 
-    l->_dot = mDot::getInstance();
     int32_t ret;
     mDot::link_check lc;
     mDot::rssi_stats rs;
@@ -66,13 +65,15 @@
                     l->_tick.detach();
                     l->_activity_led = LoRaHandler::green;
                     break;
-                
+
                 case l_send:
                     l->_mutex.lock();
                     ret = l->_dot->send(send_data);
                     l->_mutex.unlock();
                     if (ret == mDot::MDOT_OK)
                         l->_status = LoRaHandler::send_success;
+                    else if(ret == mDot::MDOT_MAX_PAYLOAD_EXCEEDED)
+                        l->_status = LoRaHandler::send_failure_payload;
                     else
                         l->_status = LoRaHandler::send_failure;
                     osSignalSet(l->_main, loraSignal);
@@ -86,6 +87,15 @@
                     l->_join_attempts++;
                     l->_mutex.unlock();
                     if (ret == mDot::MDOT_OK) {
+                        send_data.clear();
+                        l->_mutex.lock();
+                        l->_dot->send(send_data);
+                        l->_dot->send(send_data);
+                        while(l->_dot->getDataPending()) {
+                            l->_dot->send(send_data);
+                        }
+                        l->_dot->send(send_data);
+                        l->_mutex.unlock();
                         l->_status = LoRaHandler::join_success;
                         osSignalSet(l->_main, loraSignal);
                         l->_tick.detach();
@@ -96,7 +106,7 @@
                         l->_tick.detach();
                         l->_activity_led = LoRaHandler::red;
                     }
-                
+
                     break;
 
                 default:
@@ -107,12 +117,13 @@
     }
 }
 
-LoRaHandler::LoRaHandler(osThreadId main)
-  : _main(main),
+LoRaHandler::LoRaHandler(osThreadId main, mDot* dot)
+    : _main(main),
     _thread(l_worker, (void*)this),
     _status(none),
     _join_attempts(1),
-    _activity_led(XBEE_DIO1, PIN_OUTPUT, PullNone, red)
+    _activity_led(XBEE_DIO1, PIN_OUTPUT, PullNone, red),
+    _dot(dot)
 {
     _link.status = false;
     _activity_led = red;
@@ -128,7 +139,7 @@
 }
 
 bool LoRaHandler::join() {
-        return action(l_join);
+    return action(l_join);
 }
 
 bool LoRaHandler::action(uint8_t c) {
--- a/LoRaHandler/LoRaHandler.h	Thu Nov 10 22:10:58 2016 +0000
+++ b/LoRaHandler/LoRaHandler.h	Tue Oct 09 13:49:30 2018 -0500
@@ -33,7 +33,8 @@
             join_success,
             link_check_failure,
             send_failure,
-            join_failure
+            join_failure,
+            send_failure_payload
         } LoRaStatus;
 
         typedef struct {
@@ -47,7 +48,7 @@
             red
         } LedColor;
 
-        LoRaHandler(osThreadId main);
+        LoRaHandler(osThreadId main, mDot* dot);
         ~LoRaHandler();
 
         bool linkCheck();
--- a/Mode/Mode.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/Mode/Mode.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -50,7 +50,7 @@
     _band(_dot->getFrequencyBand()),
     _sub_band(_dot->getFrequencySubBand()),
     _data_rate(mDot::DR0),
-    _power(2),
+    _power(20),
     _next_tx(0),
     _send_data(false),
     _gps_available(_gps->gpsDetected())
@@ -89,16 +89,16 @@
     // if we had GPS lock, format GPS data
     if (data.gps_lock) {
         snprintf(lat_buf, sizeof(lat_buf), "%d %d %d.%03d %c",
-            abs(data.gps_latitude.degrees),
-            data.gps_latitude.minutes,
-            (data.gps_latitude.seconds * 6) / 1000,
-            (data.gps_latitude.seconds * 6) % 1000,
+            (int) abs(data.gps_latitude.degrees),
+            (int) data.gps_latitude.minutes,
+            (int) (data.gps_latitude.seconds * 6) / 1000,
+            (int) (data.gps_latitude.seconds * 6) % 1000,
             (data.gps_latitude.degrees > 0) ? 'N' : 'S');
         snprintf(lon_buf, sizeof(lon_buf), "%d %d %d.%03d %c",
-            abs(data.gps_longitude.degrees),
-            data.gps_longitude.minutes,
-            (data.gps_longitude.seconds * 6) / 1000,
-            (data.gps_longitude.seconds * 6) % 1000,
+            (int) abs(data.gps_longitude.degrees),
+            (int) data.gps_longitude.minutes,
+            (int) (data.gps_longitude.seconds * 6) / 1000,
+            (int) (data.gps_longitude.seconds * 6) % 1000,
             (data.gps_longitude.degrees > 0) ? 'E' : 'W');
         snprintf(alt_buf, sizeof(alt_buf), "%d",
             data.gps_altitude);
@@ -116,7 +116,7 @@
         snprintf(stats_buf, sizeof(stats_buf), "%lu,%ld,%d,%2.1f",
             data.link.up.gateways,
             data.link.up.dBm,
-            abs(data.link.down.rssi),
+            (int)abs(data.link.down.rssi),
             down_snr);
     }
 
@@ -279,7 +279,7 @@
     send_data.push_back((data.link.down.snr/10) & 0xFF);
 
     // collect GPS data if GPS device detected
-    if (_gps->gpsDetected() && ((_data_rate != mDot::SF_10) || (_band == mDot::FB_EU868))){
+    if (_gps->gpsDetected() && ((_data_rate != lora::SF_10) || (lora::ChannelPlan::IsPlanDynamic(_band)))) {
 	    send_data.push_back(0x19);			// key for GPS Lock Status
 	    satfix = (_gps->getNumSatellites() << 4 ) | (_gps->getFixStatus() & 0x0F );
 	    send_data.push_back(satfix);
--- a/Mode/Mode.h	Thu Nov 10 22:10:58 2016 +0000
+++ b/Mode/Mode.h	Tue Oct 09 13:49:30 2018 -0500
@@ -29,6 +29,7 @@
 #include "MMA845x.h"
 #include "MPL3115A2.h"
 #include "FileName.h"
+#include "ChannelPlans.h"
 
 class Mode {
     public:
--- a/Mode/ModeConfig.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/Mode/ModeConfig.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -52,6 +52,7 @@
     addCommand(new CmdFrequencyBand(_dot, _serial));
     addCommand(new CmdFrequencySubBand(_dot, _serial));
     addCommand(new CmdPublicNetwork(_dot, _serial));
+    addCommand(new CmdJoinDelay(_dot, _serial));
     addCommand(new CmdDeviceId(_dot, _serial));
 
     addCommand(new CmdNetworkAddress(_dot, _serial));
@@ -174,10 +175,13 @@
             ButtonHandler::ButtonEvent _be = _buttons->getButtonEvent();
             switch (_be) {
                 case ButtonHandler::sw1_press:
+                    _band = _dot->getFrequencyBand();
                     break;
                 case ButtonHandler::sw2_press:
+                    _band = _dot->getFrequencyBand();
                     break;
                 case ButtonHandler::sw1_hold:
+                    _band = _dot->getFrequencyBand();
                     return true;
                 default:
                     break;
@@ -294,7 +298,8 @@
             printHelp();
             command.clear();
         } else if (args[0].find("AT+EXIT") == 0 && args[0].length() == 7) {
-            write(done);        
+            write(done); 
+            _band = _dot->getFrequencyBand();       
 	    return true;
         } else {
             bool found = false;
@@ -356,5 +361,6 @@
             history.pop_back();
 
     }
+        _band = _dot->getFrequencyBand();
 	return false;
 }
--- a/Mode/ModeDemo.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/Mode/ModeDemo.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -18,7 +18,6 @@
 
 #include "ModeDemo.h"
 #include "MTSLog.h"
-
 // 10 s, 30 s, 1 min, 5 min, 10 min, 15 min, 30 min 1 hour
 const uint32_t ModeDemo::_intervals[] = { 10, 30, 60, 5 * 60, 10 * 60, 15 * 60, 30 * 60 };
 
@@ -39,16 +38,12 @@
     osSignalClear(_main_id, buttonSignal | loraSignal);
 
     _initial_data_rate = _dot->getTxDataRate();
-
-    // use configured data rate and power if possible
-    if ((_band == mDot::FB_US915 || _band == mDot::FB_AU915) && (_initial_data_rate == mDot::DR0 || _initial_data_rate ==  mDot::SF_10)) {
-        if(_initial_data_rate == mDot::DR0){
-            logInfo("using DR1 instead of DR0 - DR0 max packet size is too small for data");
-            _dot->setTxDataRate(mDot::DR1);
-        }else{
-            logInfo("using SF_9 instead of SF_10 - SF_10 max packet size is too small for data");
-            _dot->setTxDataRate(mDot::SF_9);
-        }
+    std::vector<uint8_t> s_data = formatSensorData(_data);
+    for(int i = 0; i < _dot->getMaxDatarate(); i++) { 
+            _dot->setTxDataRate(i);  
+            if(s_data.size() < _dot->getMaxPacketLength()) {
+                i = _dot->getMaxDatarate();
+            }
     }
 
     _state = show_help;
@@ -108,7 +103,7 @@
                     case ButtonHandler::sw1_hold:
                         _send_timer.stop();
                         _send_timer.reset();
-                        if (_band == mDot::FB_US915 || _band == mDot::FB_AU915) {
+                        if (lora::ChannelPlan::IsPlanFixed(_band)) {
                             _dot->setTxDataRate(_initial_data_rate);
                         }
                         return true;
@@ -168,7 +163,8 @@
             }
         }
         if (send) {
-            std::vector<uint8_t> s_data = formatSensorData(_data);
+            s_data.clear();
+            s_data = formatSensorData(_data);
             logInfo("sending data %s %d", _dot->DataRateStr(_dot->getTxDataRate()).c_str(), _dot->getTxPower());
             _sam.updateInfo("Sending...");
             _sam.updateSw1("        ");
--- a/Mode/ModeGps.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/Mode/ModeGps.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -32,7 +32,7 @@
 {}
 
 string ModeGps::intToString(int num){
-   char buf[3];
+   char buf[4];
    snprintf(buf, sizeof(buf), "%d", num);
    return buf;
 }
@@ -48,14 +48,15 @@
     _link_check = false;
     _GPS = false;
     _sub_band = _dot->getFrequencySubBand();
-    _data_rate = mDot::DR0;
+    _data_rate = _dot->getMinDatarate();
+    _dot->setTxDataRate(_data_rate);
     _max_padding = _dot->getMaxPacketLength() - PACKETSIZE;
     _Sw2 = "Power";
     _Sw1 = intToString(_power);
     _help.display();
     osDelay(2000);
     
-    if(_band == mDot::FB_EU868){
+    if (lora::ChannelPlan::IsPlanDynamic(_band)) {
          _sem.display(_link_check, _snr, _rssi, _power, _sub_band, _padding, _data_rate);
          _sem.initial();
          _state = PARAMETERS;
@@ -67,9 +68,10 @@
 
 void ModeGps::drIncrement(){
     _data_rate++;
-    if ((_data_rate > mDot::DR4 && (_band == mDot::FB_US915 || _band == mDot::FB_AU915)) || _data_rate > mDot::DR6) {
+    //no fsk and japan data rates are different
+    if (_data_rate > _dot->getMaxDatarate() || _data_rate > mDot::DR6) {
         _drAll = true;
-        _data_rate = 0;
+        _data_rate = _dot->getMinDatarate();
     }
     _dot->setTxDataRate(_data_rate);
     logInfo("new data rate %s, POWER %lu", mDot::DataRateStr(_data_rate).c_str(), _power);
@@ -78,7 +80,7 @@
 
 void ModeGps::changeDataRate(){
     if(_drAll) {
-        _data_rate = -1;
+        _data_rate = _dot->getMinDatarate() - 1;
         _drAll = false;
     }
     drIncrement();
@@ -86,7 +88,7 @@
 
 void ModeGps::changeParameter(){
     _parameter++;
-    if(_band == mDot::FB_EU868 && _parameter == FSB){
+    if(lora::ChannelPlan::IsPlanDynamic(_band) && _parameter == FSB){
         _parameter++;
     }
     if(_parameter>INTERVAL){
@@ -239,12 +241,10 @@
 void ModeGps::send(){   
     _state = SENDING;
     _send_timer.stop();
-    if(_band == mDot::FB_EU868) {
-        while(_dot->getNextTxMs()>0) {
-            _sem.updateNextCh((int)(_dot->getNextTxMs()/1000));
-            osDelay(250);
-        }
-    }
+     while(_dot->getNextTxMs()>0) {
+         _sem.updateNextCh((int)(_dot->getNextTxMs()/1000));
+         osDelay(250);
+     }
     formatData();
     _sem.sending();
     _send_timer.reset();
@@ -257,21 +257,19 @@
     init();
     _button_timer.start();
     ButtonHandler::ButtonEvent be;
-    osSignalClear(_main_id, buttonSignal | loraSignal);
+    uint32_t e;
     while (true) {
         if(_state==PARAMETERS){
             updateScreen();
         }
-        osEvent e = Thread::signal_wait(0, 250);
-        if (e.status == osEventSignal) {
-            if (e.value.signals & buttonSignal) {
-                _button_timer.reset();
-                be = _buttons->getButtonEvent();
+        e = osThreadFlagsWait(loraSignal | buttonSignal, osFlagsWaitAny, 250);
+        if (e == buttonSignal) {
+            be = _buttons->getButtonEvent();
 
-                switch(be) {
-                    case ButtonHandler::sw1_press:
-                        switch(_state) {
-                            case BAND_CHANGE:
+            switch(be) {
+                case ButtonHandler::sw1_press:
+                    switch(_state) {
+                        case BAND_CHANGE:
                                 setBand();
                                 _sem_join.updateJoinFsb(_sub_band);
                                 break;
@@ -313,9 +311,8 @@
                     default:
                         break;
                 }
-            }
         }
-        if (e.value.signals & loraSignal) {
+        if (e == loraSignal) {
             _ls = _lora->getStatus();
             switch (_ls) {
 
@@ -344,7 +341,21 @@
                         drIncrement();
                     }
                     break;
-
+                 
+	        case LoRaHandler::send_failure_payload:
+                    _sem.sendResult("Payload too large");
+                    osDelay(1000);
+                    _sem.sendResult("Change Datarate");
+                    osDelay(1000);
+                    _link_check = false;
+                    _button_timer.reset();
+                    _state = PARAMETERS;
+                    _sem.display(_link_check, _snr, _rssi, _power, _sub_band, _padding, _data_rate);
+                     if(_drAll){
+                        drIncrement();
+                    }
+                    break;  
+                
                 default:
                     break;
             }
--- a/Mode/ModeJoin.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/Mode/ModeJoin.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -119,7 +119,7 @@
         _join.updateId(_dot->getNetworkName());
         _join.updateKey(_dot->getNetworkPassphrase());
     }
-    if (_band == mDot::FB_US915 || _band == mDot::FB_AU915) {
+    if (lora::ChannelPlan::IsPlanFixed(_band)) {
         _sub_band = _dot->getFrequencySubBand();
         _join.updateFsb(_sub_band);
     }
--- a/Mode/ModeSingle.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/Mode/ModeSingle.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -41,8 +41,10 @@
     // clear any stale signals
     osSignalClear(_main_id, buttonSignal | loraSignal);
 
-    _initial_data_rate = _dot->getTxDataRate();
+    _initial_data_rate = _dot->getTxDataRate() < _dot->getMinDatarate() ? _dot->getMinDatarate() : _dot->getTxDataRate();
     _initial_power = _dot->getTxPower();
+    _data_rate = _dot->getMinDatarate();
+
 
     // see if we're supposed to send the data packet after success
     // that item is stored in the mDot::StartUpMode config field
@@ -321,16 +323,14 @@
 }
 
 void ModeSingle::incrementRatePower() {
-    if (_power == 20) {
-        _power = 2;
+    if (_power <= 2) {
+        _power = 20;
         _data_rate++;        
-        if ((_band == mDot::FB_US915 && _data_rate > mDot::DR4) ||
-            (_band == mDot::FB_AU915 && _data_rate > mDot::DR4) ||
-            (_band == mDot::FB_EU868 && _data_rate > mDot::DR6)) {
-             _data_rate = mDot::DR0;       
+        if (_data_rate > _dot->getMaxDatarate()) {
+            _data_rate = _dot->getMinDatarate();       
         }
     } else {
-        _power += 3;
+        _power -= 3;
     }
 
     logInfo("new data rate %s, power %lu", mDot::DataRateStr(_data_rate).c_str(), _power);
--- a/Mode/ModeSweep.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/Mode/ModeSweep.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -261,7 +261,7 @@
         }
 
         // wait 5s in EU mode to compensate for potential "no free channel" situations on server
-        if ((_band != mDot::FB_EU868 && _display_timer.read_ms() > 2000) || _display_timer.read_ms() > 5000) {
+        if ((lora::ChannelPlan::IsPlanDynamic(_band) && _dot->getChannelPlanName() == "EU868" && _display_timer.read_ms() > 2000) || _display_timer.read_ms() > 5000) {
             _display_timer.stop();
             _display_timer.reset();
             if (_survey_current == _survey_total) {
@@ -361,41 +361,55 @@
     uint8_t min_rate;
     uint8_t max_rate;
 
-    max_rate = payloadToRate(_min_payload);
-    min_rate = payloadToRate(_max_payload);
+    max_rate = payloadToRate(_min_payload, false);
+    min_rate = payloadToRate(_max_payload, true);
 
-    for (int rate = min_rate; rate >= max_rate; rate--) {
+    for (int rate = max_rate; rate <= min_rate; rate++) {
         if (_max_power - _min_power < 4) {
-            for (uint32_t power = _min_power; power <= _max_power; power++)
+            for (uint32_t power = _max_power; power >= _min_power; power--)
                 p.push_back(std::make_pair(rate, power));
         } else {
-            p.push_back(std::make_pair(rate, _min_power));
+            p.push_back(std::make_pair(rate, _max_power));
+            p.push_back(std::make_pair(rate, (uint32_t)ceil( (float(_max_power) - float(_min_power)) * 0.66 + float(_min_power))));
             p.push_back(std::make_pair(rate, (uint32_t)ceil( (float(_max_power) - float(_min_power)) * 0.33 + float(_min_power))));
-            p.push_back(std::make_pair(rate, (uint32_t)ceil( (float(_max_power) - float(_min_power)) * 0.66 + float(_min_power))));
-            p.push_back(std::make_pair(rate, _max_power));
+            p.push_back(std::make_pair(rate, _min_power));
         }
     }
 
     return p;
 }
 
-uint8_t ModeSweep::payloadToRate(uint8_t payload) {
-    if (_band == mDot::FB_EU868) {
-        if (payload <= mDot::MaxLengths_868[mDot::DR0])
-            return mDot::DR0;
-        else if (payload <= mDot::MaxLengths_868[mDot::DR3])
-            return mDot::DR3;
-        else
-            return mDot::DR6;
+uint8_t ModeSweep::payloadToRate(uint8_t payload, bool max) {
+    uint8_t ret = 0;
+    uint8_t tmp = 0;
+    if(!max) {
+        for(uint8_t i = _dot->getMinDatarate(); i < _dot->getMaxDatarate(); i++) {
+            _dot->setTxDataRate(i);
+            if(payload <= _dot->getMaxPacketLength()) {
+                ret = i;
+                tmp = _dot->getMaxPacketLength();
+                i = _dot->getMaxDatarate();
+            }
+        }
     } else {
-        if (payload <= mDot::MaxLengths_915[mDot::DR0])
-            return mDot::DR0;
-        else if (payload <= mDot::MaxLengths_915[mDot::DR1])
-            return mDot::DR1;
-        else if (payload <= mDot::MaxLengths_915[mDot::DR2])
-            return mDot::DR2;
-        else
-            return mDot::DR4;
+        //This may or may not work for some channel plans
+        for(uint8_t i = _dot->getMaxDatarate(); i > _dot->getMinDatarate(); i--) {
+            _dot->setTxDataRate(i);
+            if(payload <= _dot->getMaxPacketLength()) {
+                ret = i;
+                tmp = _dot->getMaxPacketLength();
+            }
+        }
+        _dot->setTxDataRate(_dot->getMaxDatarate());
+        if(tmp == _dot->getMaxPacketLength()) {
+            for(uint8_t i = _dot->getMaxDatarate(); i > _dot->getMinDatarate(); i--) {
+                _dot->setTxDataRate(i);
+                if(_dot->getChannelPlan()->GetDatarate(i).SpreadingFactor != lora::SF_FSK) {
+                    return i;
+                }
+            }
+        }
     }
+    return ret;
 }
 
--- a/Mode/ModeSweep.h	Thu Nov 10 22:10:58 2016 +0000
+++ b/Mode/ModeSweep.h	Tue Oct 09 13:49:30 2018 -0500
@@ -41,7 +41,7 @@
         void displayHelp();
         void displaySuccess();
         std::vector<point> generatePoints();
-        uint8_t payloadToRate(uint8_t payload);
+        uint8_t payloadToRate(uint8_t payload, bool max);
 
         typedef enum {
             check_file = 0,
--- a/SensorHandler/SensorHandler.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/SensorHandler/SensorHandler.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -26,12 +26,11 @@
 
 #include "SensorHandler.h"
 
-SensorHandler::SensorHandler()
-  : _getSensorThread(&SensorHandler::startSensorThread, this),
-    _mDoti2c(PC_9,PA_8),
-	_accelerometer(_mDoti2c,MMA845x::SA0_VSS),
-	_barometricSensor(_mDoti2c),
-	_lightSensor(_mDoti2c)
+SensorHandler::SensorHandler(I2C& i2c)
+    : _getSensorThread(&SensorHandler::startSensorThread, this)
+    , _accelerometer(i2c, MMA845x::SA0_VSS)
+    , _barometricSensor(i2c)
+    , _lightSensor(i2c)
 {
     SensorHandler::initSensors();
     _getSensorThread.signal_set(START_THREAD);
@@ -63,7 +62,7 @@
     _accelerometer.activeMode();
 	 
     // Clear the min-max registers in the Barometric Sensor
-    _barometricSensor.clearMinMaxRegs();    
+    _barometricSensor.clearMinMaxRegs();
 }
 
 void SensorHandler::startSensorThread(void const *p)
@@ -130,7 +129,7 @@
                 _mutex.unlock();                 
             }
         } while (((result & MPL3115A2::PTDR) == 0 ) && (timer.read_ms() < 100));
-	 
+
         // Retrieve light level
         _mutex.lock();
         _light = _lightSensor.getData();
--- a/SensorHandler/SensorHandler.h	Thu Nov 10 22:10:58 2016 +0000
+++ b/SensorHandler/SensorHandler.h	Tue Oct 09 13:49:30 2018 -0500
@@ -41,7 +41,7 @@
 {
 public:
     enum Scale{CELSIUS, FAHRENHEIT};
-    SensorHandler(void);
+    SensorHandler(I2C& i2c);
     ~SensorHandler(void);
     MMA845x_DATA getAcceleration(void);
     float getLight(void);
@@ -57,7 +57,6 @@
     static void startSensorThread (void const *p);	
     void readSensors(void);
     void initSensors(void);	
-    I2C _mDoti2c;
     MMA845x _accelerometer;
     MPL3115A2 _barometricSensor;
     ISL29011 _lightSensor;
@@ -65,7 +64,7 @@
     MPL3115A2_DATA _barometerData;
     uint16_t _light;
     uint32_t _pressure;
-    Mutex _mutex;	
+    Mutex _mutex;
 };
 	
 #endif //SENSORHANDLER_H
--- a/dotbox_version.h	Thu Nov 10 22:10:58 2016 +0000
+++ b/dotbox_version.h	Tue Oct 09 13:49:30 2018 -0500
@@ -1,6 +1,6 @@
 #ifndef __VERSION_H__
 #define __VERSION_H__
 
-#define MTDOT_BOX_VERSION "2.1.2"
+#define MTDOT_BOX_VERSION "3.1.1"
 
 #endif
--- a/main.cpp	Thu Nov 10 22:10:58 2016 +0000
+++ b/main.cpp	Tue Oct 09 13:49:30 2018 -0500
@@ -43,19 +43,26 @@
 #include "ModeConfig.h"
 #include "ModeGps.h"
 #include "ModeData.h"
+#include "ModeRegion.h"
 // misc heders
 #include "FileName.h"
 #include <string>
 
+#ifndef CHANNEL_PLAN
+#define CHANNEL_PLAN  CP_US915
+#endif
+
 #define DISABLE_DUTY_CYCLE true
 
-
 // LCD and LED controllers
 SPI lcd_spi(SPI1_MOSI, SPI1_MISO, SPI1_SCK);
-I2C led_i2c(I2C_SDA, I2C_SCL);
 DigitalOut lcd_spi_cs(SPI1_CS, 1);
 DigitalOut lcd_cd(XBEE_ON_SLEEP, 1);
 DOGS102* lcd;
+
+I2C i2c(I2C_SDA, I2C_SCL);
+static const int i2c_freq = 400000;  // i2c bus frequency in Hz
+
 NCP5623B* led_cont;
 
 // Thread informaiton
@@ -67,11 +74,12 @@
 // LoRa controller
 LoRaHandler* lora_handler;
 
+lora::ChannelPlan* plan;
 mDot* dot;
 
 // GPS
 GPSPARSER* gps;
-MTSSerial gps_serial(XBEE_DOUT, XBEE_DIN, 256, 2048);
+MTSSerial  gps_serial(XBEE_DOUT, XBEE_DIN, 256, 2048);
 
 // Sensors
 SensorHandler* sensors;
@@ -84,43 +92,125 @@
 ModeConfig* modeConfig;
 ModeGps* modeGps;
 ModeData* modeData;
+ModeRegion* modeRegion;
 
 // Serial debug port
-Serial debug(USBTX, USBRX);
+Serial debug_port(USBTX, USBRX);
 
 // Survey Data File
 char file_name[] = "SurveyData.txt";
 
+// Channel plan file
+char file_cp[] = "ChannelPlan";
+
 // Prototypes
 void mainMenu();
 
 int main() {
-    debug.baud(115200);
+    debug_port.baud(115200);
+
+    i2c.frequency(i2c_freq);
 
     lcd = new DOGS102(lcd_spi, lcd_spi_cs, lcd_cd);
     // NCP5623B::LEDs 1 & 2 are the screen backlight - not used on default build
     // NCP5623B::LED3 is EVB LED2
-    led_cont = new NCP5623B(led_i2c);
+    led_cont = new NCP5623B(i2c);
+    gps = new GPSPARSER(&gps_serial, led_cont);
+    sensors = new SensorHandler(i2c);
 
     main_id = Thread::gettid();
     buttons = new ButtonHandler(main_id);
-    dot = mDot::getInstance();
-    lora_handler = new LoRaHandler(main_id);
+    MTSLog::setLogLevel(MTSLog::TRACE_LEVEL);
+
+    logDebug("Loading default plan");
+
+#if CHANNEL_PLAN == CP_AS923
+    plan = new lora::ChannelPlan_AS923();
+#elif CHANNEL_PLAN == CP_US915
+    plan = new lora::ChannelPlan_US915();
+#elif CHANNEL_PLAN == CP_AU915
+    plan = new lora::ChannelPlan_AU915();
+#elif CHANNEL_PLAN == CP_EU868
+    plan = new lora::ChannelPlan_EU868();
+#elif CHANNEL_PLAN == CP_KR920
+    plan = new lora::ChannelPlan_KR920();
+#elif CHANNEL_PLAN == CP_IN865
+    plan = new lora::ChannelPlan_IN865();
+#elif CHANNEL_PLAN == CP_AS923_JAPAN
+    plan = new lora::ChannelPlan_AS923_Japan();
+#endif
+    mDot* dot = mDot::getInstance(plan);
+
+    uint8_t cplan[] = { 0 };
+    mDot::mdot_file file;	
+    vector<mDot::mdot_file> files = dot->listUserFiles();
+
+    for (vector<mDot::mdot_file>::iterator it = files.begin(); it != files.end(); it++) {
+        if (strcmp(file_cp,it->name)==0) {
+            file = dot->openUserFile(it->name, mDot::FM_RDWR);
+            dot->seekUserFile(file, 0, SEEK_SET);
+            dot->readUserFile(file, cplan, 1); 
+            dot->closeUserFile(file);
+        }
+    }
+
+    if(cplan[0]) {
+        if(cplan[0] != CHANNEL_PLAN){
+            logDebug("Loading saved channel plan");
+            switch (cplan[0]){
+                case CP_AS923:
+                    delete plan;  
+                    plan = new lora::ChannelPlan_AS923();
+                    break;
+
+                case CP_US915:
+                    delete plan;
+                    plan = new lora::ChannelPlan_US915();
+                    break;
+
+                case CP_AU915:
+                    delete plan;
+                    plan = new lora::ChannelPlan_AU915();
+                    break;
+
+                case CP_EU868:
+                    delete plan;
+                    plan = new lora::ChannelPlan_EU868();
+                    break;
+
+                case CP_KR920:
+                    delete plan;
+                    plan = new lora::ChannelPlan_KR920();
+                    break;
+
+                case CP_AS923_JAPAN:
+                    delete plan;
+                    plan = new lora::ChannelPlan_AS923_Japan();
+                    break;
+
+                default:
+                    logInfo("Saved channel plan not valid Defaulting US915");
+                    delete plan;
+                    plan = new lora::ChannelPlan_US915();
+                    break;
+            }
+            dot->setChannelPlan(plan);   
+        }
+    } 
+    lora_handler = new LoRaHandler(main_id, dot);
 
     dot->setDisableDutyCycle(DISABLE_DUTY_CYCLE);
     dot->setLinkCheckThreshold(0);
     dot->setLinkCheckCount(0);
-
+    //Adr off to make sure modes work, auto sleep off seems to cause issues, haven't looked into it yet
+    dot->setAdr(false);
+    dot->setLogLevel(MTSLog::DEBUG_LEVEL);
+    dot->setAutoSleep(false); 
     // Seed the RNG
     srand(dot->getRadioRandom());
 
-    gps = new GPSPARSER(&gps_serial, led_cont);
-    sensors = new SensorHandler();
-
     led_cont->setLEDCurrent(16);
 
-    MTSLog::setLogLevel(MTSLog::TRACE_LEVEL);
-
     modeJoin = new ModeJoin(lcd, buttons, dot, lora_handler, gps, sensors);
     modeSingle = new ModeSingle(lcd, buttons, dot, lora_handler, gps, sensors);
     modeSweep = new ModeSweep(lcd, buttons, dot, lora_handler, gps, sensors);
@@ -128,17 +218,21 @@
     modeConfig = new ModeConfig(lcd, buttons, dot, lora_handler, gps, sensors);
     modeGps = new ModeGps(lcd, buttons, dot, lora_handler, gps, sensors, modeJoin);
     modeData = new ModeData(lcd, buttons, dot, lora_handler, gps, sensors);
-
+    modeRegion = new ModeRegion(lcd, buttons, dot, lora_handler, gps, sensors, file_cp);
 
     osDelay(1000);
     logInfo("%sGPS detected", gps->gpsDetected() ? "" : "no ");
 
+    if(!cplan[0]) {
+        dot->saveUserFile(file_cp, cplan, 1);    
+        modeRegion->start();
+    }
+
     // display startup screen for 3 seconds
     LayoutStartup ls(lcd, dot);
     ls.display();
     ls.updateGPS(gps->gpsDetected());
     osDelay(3000);
-
     logInfo("displaying main menu");
     mainMenu();
 
@@ -149,15 +243,15 @@
     bool mode_selected = false;
     std::string selected;
     std::string product;
-    
+
     typedef enum {
         demo = 1,
         config,
         single,
         sweep,
         gps,
-        data
-
+        data,
+        region
     } menu_items;
 
     std::string menu_strings[] = {
@@ -167,8 +261,10 @@
         "Survey Single",
         "Survey Sweep",
         "Survey GPS",
-        "View Data"
+        "View Data",
+        "Select Region"
     };
+
     std::vector<std::string> items;
     items.push_back(menu_strings[demo]);
     items.push_back(menu_strings[config]);
@@ -176,19 +272,21 @@
     items.push_back(menu_strings[sweep]);
     items.push_back(menu_strings[gps]);
     items.push_back(menu_strings[data]);
+    items.push_back(menu_strings[region]);
 
     while (true) {
-        product = "DOT-BOX/EVB ";
-        product += mDot::FrequencyBandStr(dot->getFrequencyBand());
-
         // reset session between modes
         dot->resetNetworkSession();
-        lora_handler->resetActivityLed();
-
+        selected = "";
+        //dot->getChannelPlanName causes hard faults, not sure why.
+        product = "DOT-BOX/EVB " + plan->GetPlanName();
+        if(product.size() > 17)
+            product = "DOT-BOX/EVB JAPAN";    
         LayoutScrollSelect menu(lcd, items, product, menu_strings[0]);
         menu.display();
 
         while (! mode_selected) {
+            lora_handler->resetActivityLed();
             osEvent e = Thread::signal_wait(buttonSignal);
             if (e.status == osEventSignal) {
                 ButtonHandler::ButtonEvent ev = buttons->getButtonEvent();
@@ -219,17 +317,19 @@
             if (modeJoin->start())
                 modeSweep->start();
         } else if (selected == menu_strings[gps]) {
-            if(dot->getFrequencyBand() == mDot::FB_EU868) {
-                modeJoin->start();
+            if (plan->IsPlanDynamic()) {
+                if(modeJoin->start())
+                    modeGps->start();
             }
-            modeGps->start();
+            else { 
+                modeGps->start();
+            }
         } else if (selected == menu_strings[data]) {
             modeData->start();
-        } 
-
+        } else if (selected == menu_strings[region]) {
+            modeRegion->start();
+        }
+        lora_handler->resetActivityLed();  
         mode_selected = false;
     }
 }
-
-
-