init

Dependencies:   aconno_I2C Lis2dh12 WatchdogTimer

main.cpp

Committer:
pathfindr
Date:
2018-12-23
Revision:
25:7adeb1a53360
Parent:
24:c161db07557f
Child:
26:fa3579737329

File content as of revision 25:7adeb1a53360:

#include "main.h"

//------------------------------------------------------------------------------
//DEFINES
//------------------------------------------------------------------------------ 
#define FW_VERSION 1
#define SLEEP_FRAME 30000

//------------------------------------------------------------------------------
//FUNCTION PROTOTYPES
//------------------------------------------------------------------------------ 
static void mainStateEngine(void);
static void selftest(void);
static void buttonPress(void);
static void buttonRelease(void);
static void dumpSettings(void);
static void saveEventTimes(void);
static void event_location_tx(void);

//------------------------------------------------------------------------------
//GLOBAL VARS / CLEARED ON SLEEP (IF USING SOFT REBOOT HACK)
//------------------------------------------------------------------------------ 
char* GLOBAL_defaultApi = "b:gps2";
bool GLOBAL_accel_healthy = false;
bool GLOBAL_requireSoftReset = false;
bool GLOBAL_motionStopFlagTriggered = false;
bool GLOBAL_debugLED = true;
bool GLOBAL_needToConfigureLis3dh = false;
bool GLOBAL_registeredOnNetwork = false;
bool GLOBAL_modemOn = false;
time_t GLOBAL_RTCunixtime = 0;
time_t GLOBAL_wakeTime = 0;

//------------------------------------------------------------------------------
//RETAINED NOINIT RAM VARS
//------------------------------------------------------------------------------ 
#if defined ( __CC_ARM ) /** THIS IS THE MBED ONLINE COMPILER TOOLCHAIN*/ //MUST BE STATICS
//IDENTITY
static long long        RET_imei                                        __attribute__((section("noinit"),zero_init));
//SETTINGS
static int              RET_setting_firmware                            __attribute__((section("noinit"),zero_init)); //must be int to support negative value
static uint8_t          RET_setting_location_mode                       __attribute__((section("noinit"),zero_init));
static uint8_t          RET_setting_location_accuracy                   __attribute__((section("noinit"),zero_init));
static uint32_t         RET_setting_location_tx_interval_mins           __attribute__((section("noinit"),zero_init));
static uint32_t         RET_setting_location_tx_failsafe_hrs            __attribute__((section("noinit"),zero_init));
static uint16_t         RET_setting_location_timeout                    __attribute__((section("noinit"),zero_init));
static uint32_t         RET_setting_activity_tx_interval_hrs            __attribute__((section("noinit"),zero_init));
static uint32_t         RET_setting_environmental_tx_interval_mins      __attribute__((section("noinit"),zero_init));
static uint16_t         RET_setting_motion_g                            __attribute__((section("noinit"),zero_init));
static time_t           RET_setting_motion_start_seconds                __attribute__((section("noinit"),zero_init));
static time_t           RET_setting_motion_stop_seconds                 __attribute__((section("noinit"),zero_init));
static uint16_t         RET_setting_impact_g                            __attribute__((section("noinit"),zero_init));
static uint8_t          RET_setting_impact_alert                        __attribute__((section("noinit"),zero_init));
static uint16_t         RET_setting_connection_timeout                  __attribute__((section("noinit"),zero_init));
static uint16_t         RET_setting_beacon_interval_seconds             __attribute__((section("noinit"),zero_init));
static uint16_t         RET_setting_beacon_scan                         __attribute__((section("noinit"),zero_init));
//STATE
static uint16_t         RET_sleepToggle                                 __attribute__((section("noinit"),zero_init));
static uint8_t          RET_coldBoot                                    __attribute__((section("noinit"),zero_init));
static bool             RET_haveSettings                                __attribute__((section("noinit"),zero_init));
static uint8_t          RET_state                                       __attribute__((section("noinit"),zero_init));
static uint8_t          RET_state_prev                                  __attribute__((section("noinit"),zero_init));
static uint8_t          RET_buttonPressCount                            __attribute__((section("noinit"),zero_init));
static time_t           RET_buttonPressTime                             __attribute__((section("noinit"),zero_init));
static time_t           RET_buttonReleaseTime                           __attribute__((section("noinit"),zero_init));
static time_t           RET_buttonHoldTime                              __attribute__((section("noinit"),zero_init));
static time_t           RET_RTCunixtime                                 __attribute__((section("noinit"),zero_init));
static time_t           RET_SetupRunAt                                  __attribute__((section("noinit"),zero_init));
//MOTION STATE
static bool             RET_motionTriggered                             __attribute__((section("noinit"),zero_init));
static bool             RET_motionTriggeredInTXInterval                 __attribute__((section("noinit"),zero_init));
static time_t           RET_motionStartTime                             __attribute__((section("noinit"),zero_init));
static time_t           RET_motionStopTime                              __attribute__((section("noinit"),zero_init));
static bool             RET_motionPendingOnState                        __attribute__((section("noinit"),zero_init));
static bool             RET_motionPendingOffState                       __attribute__((section("noinit"),zero_init));
static bool             RET_motionState                                 __attribute__((section("noinit"),zero_init));
static float            RET_motionTotalActivityHours                    __attribute__((section("noinit"),zero_init));
static time_t           RET_motionFrameStart                            __attribute__((section("noinit"),zero_init));
static char             RET_activityData[140]                           __attribute__((section("noinit"),zero_init));
//IMPACT
static bool             RET_impactTriggered                             __attribute__((section("noinit"),zero_init));
//EVENTS LOGGING
static time_t           RET_eventTime_location_log                      __attribute__((section("noinit"),zero_init));
static time_t           RET_eventTime_environmental_log                 __attribute__((section("noinit"),zero_init));
//EVENTS TX
static time_t           RET_eventTime_location_tx                       __attribute__((section("noinit"),zero_init));
static time_t           RET_eventTime_location_failsafe_tx              __attribute__((section("noinit"),zero_init));
static time_t           RET_eventTime_environmental_tx                  __attribute__((section("noinit"),zero_init));
static time_t           RET_eventTime_activity_tx                       __attribute__((section("noinit"),zero_init));
static time_t           RET_eventTime_wakeFromDormant                   __attribute__((section("noinit"),zero_init));
//DUPLICATES MEM INIT CHECK
static time_t           RET_RTCunixtime_bu                                __attribute__((section("noinit"),zero_init));
static uint32_t         RET_memTest                                    __attribute__((section("noinit"),zero_init));
#elif defined ( __GNUC__ )
#elif defined ( __ICCARM__ )
#endif

//------------------------------------------------------------------------------
//GPIO
//------------------------------------------------------------------------------ 
InterruptIn button(PN_IN_BUTTON); //This causes wake from sleep
DigitalOut vreg_en(PN_VREG_EN);

//------------------------------------------------------------------------------
//PERIPHERALS
//------------------------------------------------------------------------------ 
//BLE myble;
WatchdogTimer watchdog(300.0); //Do not set to less than 4500ms or can cause issues with softdevice
void watchdogKick() {watchdog.kick();}
//SERIAL DEBUG?
#if CONSOLE_DEBUG
    Serial uart(PN_UART_TX, PN_UART_RX, 115200);
#endif
        
//------------------------------------------------------------------------------
//TIMERS
//-----------------------------------------------mi------------------------------- 
LowPowerTicker RTCticker; //no impact on power consumption

//------------------------------------------------------------------------------
//THREAD SEMAPHORES
//------------------------------------------------------------------------------ 
Semaphore mainthread;

//------------------------------------------------------------------------------
// LOW LEVEL FUNCS
//------------------------------------------------------------------------------ 
void turnOffEverything() {
    vreg_en = 0;
    LED1off();
}
void gotoSleep(long sleep_milliseconds) {
    /*
    turnOffEverything();
    watchdogKick();
    if (GLOBAL_requireSoftReset) { //dont need to clear this var as reset changes it back to false
        system_reset();
    }
    mainthread.wait(sleep_milliseconds);
    */
}
void setState(uint8_t state) {
    RET_state_prev = RET_state;
    RET_state = state;
    DEBUG("STATEREADBACK %d\n",RET_state)
}
bool memoryIntegrityCheck() {
    bool pass = true;
    //check memory is init correct
    if (RET_memTest != 12345) {
        pass = false;
    }
    //Check clocks match and are in range
    if (RET_RTCunixtime != RET_RTCunixtime || RET_RTCunixtime < 1545412457) {
        pass = false;
    }
    return pass;
}
void dumpSettings() {
    DEBUG("RET_RTCunixtime:%u \n",RET_RTCunixtime);
    DEBUG("RET_setting_firmware:%d \n",RET_setting_firmware);
    DEBUG("RET_state:%d \n",RET_state);
    DEBUG("RET_setting_location_mode:%d \n",RET_setting_location_mode);
    DEBUG("RET_setting_location_accuracy:%d \n",RET_setting_location_accuracy);
    DEBUG("RET_setting_location_tx_interval_mins:%d \n",RET_setting_location_tx_interval_mins);
    DEBUG("RET_setting_location_tx_failsafe_hrs:%d \n",RET_setting_location_tx_failsafe_hrs);
    DEBUG("RET_setting_location_timeout:%d \n",RET_setting_location_timeout);
    DEBUG("RET_setting_activity_tx_interval_hrs:%d \n",RET_setting_activity_tx_interval_hrs);
    DEBUG("RET_setting_environmental_tx_interval_mins:%d \n",RET_setting_environmental_tx_interval_mins);
    DEBUG("RET_setting_motion_g:%d \n",RET_setting_motion_g);
    DEBUG("RET_setting_motion_start_seconds:%d \n",RET_setting_motion_start_seconds);
    DEBUG("RET_setting_motion_stop_seconds:%d \n",RET_setting_motion_stop_seconds);
    DEBUG("RET_setting_impact_g:%d \n",RET_setting_impact_g);
    DEBUG("RET_setting_impact_alert:%d \n",RET_setting_impact_alert);
    DEBUG("RET_setting_connection_timeout:%d \n",RET_setting_connection_timeout);
    DEBUG("RET_setting_beacon_interval_seconds:%d \n",RET_setting_beacon_interval_seconds);
    DEBUG("RET_setting_beacon_scan:%d \n",RET_setting_beacon_scan);
}
float getBatteryV() { //this creates an extra 400ua of power usage!!!
    NRF52_SAADC batteryIn;
    batteryIn.addChannel(9); // vdd for battery
    batteryIn.calibrate();
    float voltage = 0.0;
    for (uint8_t i = 1; i <= 2; i++) { // need to get it 2 times to get accurate data, first one is always low for some reason
        batteryIn.updateData();
        voltage = (batteryIn.getData()[0])*(1.0/1024.0)*3.65;
    }
    return voltage;
}
float getTemperature() {
    SI7060 si7060(PN_I2C_SDA, PN_I2C_SCL);
    float temperature = si7060.getTemperature();
    DEBUG("Temperature:%.2f\n",temperature);
    return temperature;  
}
//------------------------------------------------------------------------------
// USER BUTTON HANDLING
//------------------------------------------------------------------------------ 
void buttonPress() {
    RET_buttonPressTime = RET_RTCunixtime;
}
void buttonRelease() {
    RET_buttonHoldTime = (RET_RTCunixtime - RET_buttonPressTime);
    RET_buttonPressCount ++;
}
//------------------------------------------------------------------------------
// RTC TICKER
//------------------------------------------------------------------------------ 
void RTCtick() {
    //YOU MUST NOT CALL ANY OTHER FUNCTIONS OR DEBUG FROM INSIDE HERE!!! OR IT LOCKS UP THE DEVICE, just change vars
    RET_RTCunixtime += 1;
    RET_RTCunixtime_bu += 1;
    
    GLOBAL_RTCunixtime = RET_RTCunixtime;
    
    //button logic - check for hold
    if (RET_buttonHoldTime > 4) {
        RET_buttonHoldTime = 0;
        RET_buttonPressCount = 0;
        RET_state_prev = RET_state;
        RET_state = STATE_BUTTONHOLD;
        mainthread.release();
    } else {
        if((RET_RTCunixtime - RET_buttonPressTime) > 1) {
            switch (RET_buttonPressCount) {   
                case 1 :
                    if (RET_state == STATE_NORMAL) {
                        RET_state = STATE_BUTTONPRESS1;
                        mainthread.release();
                    }
                    break;
                case 2 :
                    if (RET_state == STATE_NORMAL) {
                        RET_state = STATE_BUTTONPRESS2;
                        mainthread.release();
                    }
                    break;
                default :
                    //do nothing
                    break;
            }
            RET_buttonPressCount = 0;
        }
    }
    //SETUP STATE VISUALISE
    if (RET_state == STATE_SETUP) {
        led1 = !led1;
    }
}

void factoryReset() {
    //MEM CHECK
    RET_memTest = 12345;
    //IDENTITY 
    RET_imei = 0;
    //STATE
    RET_sleepToggle = 0;
    RET_coldBoot = 1;
    RET_haveSettings = 0;
    RET_state = STATE_SETUP;
    RET_state_prev = RET_state;
    RET_RTCunixtime = 0;
    RET_RTCunixtime_bu = 0;
    RET_SetupRunAt = 0;
    //SETTINGS
    RET_setting_firmware = 0;
    RET_setting_location_mode = 2;
    RET_setting_location_accuracy = 2; // 0 = no location, 1 = cl only, 2 = gps then cl
    RET_setting_location_tx_interval_mins = 1440;
    RET_setting_location_tx_failsafe_hrs = (7*24); //7 days
    RET_setting_location_timeout = 240;
    RET_setting_activity_tx_interval_hrs = 0;
    RET_setting_environmental_tx_interval_mins = 0;
    RET_setting_motion_g = 11;
    RET_setting_motion_start_seconds = 120;
    RET_setting_motion_stop_seconds = 120;
    RET_setting_impact_g = 0;
    RET_setting_impact_alert = 0;
    RET_setting_connection_timeout = 180;
    RET_setting_beacon_interval_seconds = 10;
    RET_setting_beacon_scan = 0;
    //RET_RTCmillis = 0;
    RET_buttonPressCount = 0;
    RET_buttonPressTime = 0;
    RET_buttonReleaseTime = 0;
    RET_buttonHoldTime = 0;
    //MOTION STATE
    RET_motionTriggered = 0;
    RET_motionTriggeredInTXInterval = 0;
    RET_motionStartTime = 0;
    RET_motionStopTime = 0;
    RET_motionPendingOnState = 0;
    RET_motionPendingOffState = 0;
    RET_motionState = 0;
    RET_motionTotalActivityHours = 0.0;
    RET_motionFrameStart = 0;
    memset(RET_activityData,0,sizeof(RET_activityData));
    //IMPACT
    RET_impactTriggered = 0;
    //EVENT HANDLING
    RET_eventTime_location_log = 0;
    RET_eventTime_location_tx = 0;
    RET_eventTime_location_failsafe_tx = 0;
    RET_eventTime_environmental_log = 0;
    RET_eventTime_environmental_tx = 0;
    RET_eventTime_activity_tx = 0;
    RET_eventTime_wakeFromDormant = 0;
    //OTHER LOCAL GLOBALS   
    GLOBAL_requireSoftReset = false;   
    
    //PERIPHERAL RESET
    lis3dh_configureForSleep(10,127);
}
bool selfTest() {
    int test_count = 0;
    int test_pass = 0;
    
    //Accelerometer
    test_count ++;
    LIS3DH lis3dh(PN_SPI_MOSI, PN_SPI_MISO, PN_SPI_CS0, PN_SPI_CLK);
    uint8_t lis3dh_id; 
    lis3dh.LIS3DH_GetWHO_AM_I(&lis3dh_id);
    if (lis3dh_id == 51) {test_pass ++;}
    
    //Temperature
    test_count ++;
    SI7060 si7060(PN_I2C_SDA, PN_I2C_SCL);
    float temperature;
    temperature = si7060.getTemperature();
    test_pass ++;
    
    //Result
    if (test_count == test_pass) {
        return true;
    } else {
        return false;   
    }
}

//------------------------------------------------------------------------------
// MOTION FUNCS
//------------------------------------------------------------------------------ 
void checkMotion() {
    if (lis3dh_int2) {
        if (GLOBAL_debugLED) LED1blink(1,50);
        RET_motionTriggered = true;
        GLOBAL_needToConfigureLis3dh = true; //interrupt has fire so need to clear it
        if (!RET_motionPendingOnState) {
            RET_motionPendingOnState = true;
            RET_motionPendingOffState = false;
            // Log start motion time
            RET_motionStartTime = RET_RTCunixtime;
        }
    } else {
        RET_motionTriggered = false;
        RET_motionPendingOnState = false;
        if (!RET_motionPendingOffState) {
            RET_motionPendingOffState = true;
            //log stop motion time
            RET_motionStopTime = RET_RTCunixtime;
        }
    }
    //calculate motion state
    if (RET_motionPendingOnState) {
        //check if above threshold
        time_t inMotionForSeconds = (RET_RTCunixtime - RET_motionStartTime) + 2; //Plus 2 to account for rounding and non exact clocks
        if (inMotionForSeconds >= RET_setting_motion_start_seconds && RET_motionState == false) {
            RET_motionState = true;
            RET_motionTriggeredInTXInterval = true;
            if (GLOBAL_debugLED) LED1blink(5,50);
            if (RET_setting_location_tx_failsafe_hrs > 0) {
                time_t epochOffsetMins = ((RET_RTCunixtime - RET_motionFrameStart) / 60);
                sprintf(RET_activityData+strlen(RET_activityData),"1.%u!",epochOffsetMins);
            }
        }
    }
    if (RET_motionPendingOffState) {
        time_t noMotionForSeconds = (RET_RTCunixtime - RET_motionStopTime) + 2; //Plus 2 to account for rounding and non exact clocks
        if (noMotionForSeconds >= RET_setting_motion_stop_seconds && RET_motionState == true) {
            RET_motionPendingOffState = false;
            RET_motionState = false;
            GLOBAL_motionStopFlagTriggered = true;
            RET_motionTotalActivityHours += (float(RET_motionStopTime - RET_motionStartTime) / 3600.0); 
            if (GLOBAL_debugLED) LED1blink(3,400);
            if (RET_setting_location_tx_failsafe_hrs > 0) {
                time_t epochOffsetMins = ((RET_RTCunixtime - RET_motionFrameStart) / 60);
                sprintf(RET_activityData+strlen(RET_activityData),"0.%u!",epochOffsetMins);
            }
        }
    }
}

//------------------------------------------------------------------------------
// UPDATE OPERATING SETTINGS
//------------------------------------------------------------------------------ 
bool saveSettings(char* settingsBuffer) {
    //process result
    int matchCount = 0;
    int critical_fail_count = 0;
    time_t TEMP_b = 0; int TEMP_c = -1; int TEMP_d = -1; int TEMP_e = -1; int TEMP_f = -1; int TEMP_g = -1; int TEMP_h = -1; int TEMP_i = -1; int TEMP_j = -1; 
    int TEMP_k = -1; int TEMP_l = -1; int TEMP_m = -1; int TEMP_n = -1; int TEMP_o = -1; int TEMP_p = -1; int TEMP_q = -1; int TEMP_r = -1; int TEMP_s = -1;
    if ( (matchCount = sscanf(settingsBuffer,"b:%u,c:%d,d:%d,e:%d,f:%d,g:%d,h:%d,i:%d,j:%d,k:%d,l:%d,m:%d,n:%d,o:%d,p:%d,q:%d,r:%d,s:%d",
    &TEMP_b,&TEMP_c,&TEMP_d,&TEMP_e,&TEMP_f,&TEMP_g,&TEMP_h,&TEMP_i,&TEMP_j,&TEMP_k,&TEMP_l,&TEMP_m,&TEMP_n,&TEMP_o,&TEMP_p,&TEMP_q,&TEMP_r,&TEMP_s) ) > 0 ) {
        DEBUG("VALUES: b:%u,c:%d,d:%d,e:%d,f:%d,g:%d,h:%d,i:%d,j:%d,k:%d,l:%d,m:%d,n:%d,o:%d,p:%d,q:%d,r:%d,s:%d\n",
        TEMP_b,TEMP_c,TEMP_d,TEMP_e,TEMP_f,TEMP_g,TEMP_h,TEMP_i,TEMP_j,TEMP_k,TEMP_l,TEMP_m,TEMP_n,TEMP_o,TEMP_p,TEMP_q,TEMP_r,TEMP_s);
        
        //FAILUREMODE need to be checking thse against checksums
        char changed;
        //FAILUREMODE need to verify the identifier against a reg exp or similar
        if(TEMP_b != 0) { RET_RTCunixtime = TEMP_b;                                changed = 'Y'; } else { changed = 'N'; critical_fail_count++; }; DEBUG("RET_RTCunixtime:%u..%c\n",RET_RTCunixtime,changed);
        if(TEMP_c != -1) { RET_setting_firmware = TEMP_c;                          changed = 'Y'; } else { changed = 'N'; RET_setting_firmware = -1;}; DEBUG("RET_setting_firmware:%d..%c\n",RET_setting_firmware,changed);
        if(TEMP_d != -1) { setState(TEMP_d);                                       changed = 'Y'; } else { changed = 'N'; critical_fail_count++; }; DEBUG("RET_state:%d..%c\n",RET_state,changed);
        if(TEMP_e != -1) { RET_setting_location_mode = TEMP_e;                     changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_location_mode:%d..%c\n",RET_setting_location_mode,changed);
        if(TEMP_f != -1) { RET_setting_location_accuracy = TEMP_f;                 changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_location_accuracy:%d..%c\n",RET_setting_location_accuracy,changed);
        if(TEMP_g != -1) { RET_setting_location_tx_interval_mins = TEMP_g;         changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_location_tx_interval_mins:%d..%c\n",RET_setting_location_tx_interval_mins,changed);
        if(TEMP_h != -1) { RET_setting_location_tx_failsafe_hrs = TEMP_h;          changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_location_tx_failsafe_hrs:%d..%c\n",RET_setting_location_tx_failsafe_hrs,changed);
        if(TEMP_i != -1) { RET_setting_location_timeout = TEMP_i;                  changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_location_timeout:%d..%c\n",RET_setting_location_timeout,changed);
        if(TEMP_j != -1) { RET_setting_activity_tx_interval_hrs = TEMP_j;          changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_activity_tx_interval_hrs:%d..%c\n",RET_setting_activity_tx_interval_hrs,changed);
        if(TEMP_k != -1) { RET_setting_environmental_tx_interval_mins = TEMP_k;    changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_environmental_tx_interval_mins:%d..%c\n",RET_setting_environmental_tx_interval_mins,changed);
        if(TEMP_l != -1) { RET_setting_motion_g = TEMP_l;                          changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_motion_g:%d..%c\n",RET_setting_motion_g,changed);
        if(TEMP_m != -1) { RET_setting_motion_start_seconds = TEMP_m;              changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_motion_start_seconds:%d..%c\n",RET_setting_motion_start_seconds,changed);
        if(TEMP_n != -1) { RET_setting_motion_stop_seconds = TEMP_n;               changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_motion_stop_seconds:%d..%c\n",RET_setting_motion_stop_seconds,changed);
        if(TEMP_o != -1) { RET_setting_impact_g = TEMP_o;                          changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_impact_g:%d..%c\n",RET_setting_impact_g,changed);
        if(TEMP_p != -1) { RET_setting_impact_alert = TEMP_p;                      changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_impact_alert:%d..%c\n",RET_setting_impact_alert,changed);
        if(TEMP_q != -1) { RET_setting_connection_timeout = TEMP_q;                changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_connection_timeout:%d..%c\n",RET_setting_connection_timeout,changed);
        if(TEMP_r != -1) { RET_setting_beacon_interval_seconds = TEMP_r;           changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_beacon_interval_seconds:%d..%c\n",RET_setting_beacon_interval_seconds,changed);
        if(TEMP_s != -1) { RET_setting_beacon_scan = TEMP_s;                       changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_beacon_scan:%d..%c\n",RET_setting_beacon_scan,changed);
        
        if (critical_fail_count == 0) { 
            DEBUG("GOT SETTINGS OK\n"); 
            saveEventTimes();
            RET_haveSettings = true;     
            return true;
        } else {
            DEBUG("CRITICAL FAILS:%d\n",critical_fail_count);
            RET_haveSettings = false; 
            return false;
        }
    } else {
        RET_haveSettings = false;
        return false;
    }
}

void saveEventTimes() {
    //SET EVENT TIMES
    if(RET_setting_location_tx_interval_mins > 0) { 
        RET_eventTime_location_tx = (RET_RTCunixtime + (RET_setting_location_tx_interval_mins * 60));
        DEBUG("EVENTSET - LOCATION TX at %u, MODE %d\n",RET_eventTime_location_tx, RET_setting_location_mode);
    }
    if(RET_setting_location_tx_failsafe_hrs > 0) { 
        RET_eventTime_location_failsafe_tx = (RET_RTCunixtime + (RET_setting_location_tx_failsafe_hrs * 3600));
        DEBUG("EVENTSET - LOCATION FAILSAFE TX at %u\n",RET_eventTime_location_failsafe_tx);
    }
    if(RET_setting_activity_tx_interval_hrs > 0) { 
        RET_motionFrameStart = RET_RTCunixtime; //SET START FRAME INITAL
        RET_eventTime_activity_tx = (RET_RTCunixtime + (RET_setting_activity_tx_interval_hrs * 3600));
        DEBUG("EVENTSET - ACTIVITY TX at %u\n",RET_eventTime_activity_tx);
    }
    if(RET_eventTime_environmental_tx > 0) { 
        RET_eventTime_environmental_tx = (RET_RTCunixtime + (RET_setting_environmental_tx_interval_mins * 60));
        DEBUG("EVENTSET - ENVIRONMENTAL TX at %u\n",RET_eventTime_environmental_tx);
    }   
}

//------------------------------------------------------------------------------
// SETUP
//------------------------------------------------------------------------------ 
bool setup() {
    bool pass = true;
    float voltage = getBatteryV();
    float temperature = getTemperature();
    bool selftestresult = selfTest();
    Modem modem(PN_UART_TX, PN_UART_RX, PN_UART_CTS, PN_UART_RTS, PN_GSM_PWR_KEY, PN_VREG_EN, PN_GSM_WAKE_DISABLE);
    if (modem.on()) {
        //RET_imei = modem.getIMEI();
        //DEBUG("imei: %lld \n",RET_imei);
        //char* modemModel = modem.getModemModel();
        if (modem.registerOnNetwork(2,180000)) {
            int timetaken = (RET_RTCunixtime - GLOBAL_wakeTime);
            char bytestosend[160];
            snprintf(bytestosend,sizeof(bytestosend),"(%s,a:setup,f:%d,v:%.2f,t:%.2f,e:%d,z:SETUP,c:1)\0",GLOBAL_defaultApi,FW_VERSION,voltage,timetaken);
            char result[180];
            snprintf(result,sizeof(result),"%s",modem.USSDmessage(bytestosend, true, 2, GLOBAL_defaultApi));
            if (result != "err") {
                DEBUG("\nfromserver: %s \n",result);
                if (!saveSettings(result)) { 
                    //something went critically wrong getting settings 
                    pass = false;
                }              
            }
        } else {
            //FAILUREMODE modem failed to register on network
            pass = false;
        }
    } else {
        //FAILUREMODE Modem failed to turn on  
        pass = false;
    }
    
    //LOG RUN TIME - THIS MUST GO AT END AFTER WE HAVE GOT SERVER TIMESTAMP
    RET_SetupRunAt = RET_RTCunixtime;
    
    //RESULT
    return pass;
}

//------------------------------------------------------------------------------
// EVENTS
//------------------------------------------------------------------------------ 
void event_shakertest_tx() {
    DEBUG("SHAKER TEST\n");
    float voltage = getBatteryV();  
    float temperature = getTemperature();
    bool selftestresult = selfTest();
    Modem modem(PN_UART_TX, PN_UART_RX, PN_UART_CTS, PN_UART_RTS, PN_GSM_PWR_KEY, PN_VREG_EN, PN_GSM_WAKE_DISABLE);
    if (modem.on()) {
        if (modem.registerOnNetwork(2,180000)) {
            int timetaken = (RET_RTCunixtime - GLOBAL_wakeTime);
            char bytestosend[160];
            snprintf(bytestosend,sizeof(bytestosend),"(%s,a:loc,f:%d,t:%.2f,v:%.2f,z:SHAKERTEST-%d,e:%d,c:1)\0",GLOBAL_defaultApi,FW_VERSION,temperature,voltage,selftestresult,timetaken);
            char result[180];
            bool getSettings = true;
            snprintf(result,sizeof(result),"%s",modem.USSDmessage(bytestosend, getSettings, 2, GLOBAL_defaultApi));
            if (result != "err") {
                DEBUG("\nfromserver: %s \n",result);
                if (getSettings) {
                    saveSettings(result);
                }
            }
        }
    }
    //RESETS
    RET_motionTriggeredInTXInterval = 0;
    saveEventTimes();
}

void event_location_tx() {
    DEBUG("LOCATION TX\n");
    float voltage = getBatteryV();
    float temperature = getTemperature();
    bool selftestresult = selfTest();
    Modem modem(PN_UART_TX, PN_UART_RX, PN_UART_CTS, PN_UART_RTS, PN_GSM_PWR_KEY, PN_VREG_EN, PN_GSM_WAKE_DISABLE);
    if (modem.on()) {
        char locString[70];
        if (RET_setting_location_accuracy > 0) { 
            memcpy(locString, modem.getLocation(RET_setting_location_accuracy, RET_setting_location_timeout), 70);
            //DEBUG("locString:%s-\n",locString);
        }
        //SEND DATA
        if (modem.registerOnNetwork(2,180000)) {
            int timetaken = (RET_RTCunixtime - GLOBAL_wakeTime);
            char bytesToSend[160];
            snprintf(bytesToSend,sizeof(bytesToSend),"(%s,a:loc,f:%d,t:%.2f,v:%.2f,z:OK%d,e:%d,c:1%s)\0",GLOBAL_defaultApi,FW_VERSION,temperature,voltage,selftestresult,timetaken,locString);
            char result[180];
            bool getSettings = true;
            snprintf(result,sizeof(result),"%s",modem.USSDmessage(bytesToSend, getSettings, 2, GLOBAL_defaultApi));
            if (result != "err") {
                //DEBUG("\nfromserver: %s \n",result);
                if (getSettings) {
                    saveSettings(result);
                }
            }
        }
    }
    //RESETS
    RET_motionTriggeredInTXInterval = 0;
    saveEventTimes();
}

void event_activity_tx() {
    DEBUG("ACTIVITY TX\n");
    float temperature = getTemperature();
    Modem modem(PN_UART_TX, PN_UART_RX, PN_UART_CTS, PN_UART_RTS, PN_GSM_PWR_KEY, PN_VREG_EN, PN_GSM_WAKE_DISABLE);
    if (modem.on()) {
        //SEND DATA
        if (modem.registerOnNetwork(2,180000)) {
            char bytesToSend[160];
            snprintf(bytesToSend,sizeof(bytesToSend),"(%s,a:act,e:%s,t:%u,r:%.2f,c:1)\0",GLOBAL_defaultApi,RET_activityData,RET_motionFrameStart,RET_motionTotalActivityHours);
            char result[180];
            bool getResponse = false;
            snprintf(result,sizeof(result),"%s",modem.USSDmessage(bytesToSend, getResponse, 2, GLOBAL_defaultApi));
            if (result != "err") {
                //RESET ACTIVITY FRAME
                memset(RET_activityData,0,sizeof(RET_activityData));
                if (RET_haveSettings) {RET_motionFrameStart = RET_RTCunixtime;}
            }
        }
    }
    //RESETS
    RET_motionTriggeredInTXInterval = 0;
    saveEventTimes();
}

//------------------------------------------------------------------------------
// STATE ENGINE
//------------------------------------------------------------------------------ 
void mainStateEngine() {
    switch(RET_state) {
        case STATE_SETUP :
            DEBUG("STATE:SETUP\n");
            factoryReset();
            if (setup()) {
                // All good
            } else {
                RET_eventTime_wakeFromDormant = (RET_RTCunixtime + (24*3600)); //24hrs
                setState(STATE_DORMANT);
                DEBUG("SETSTATE:DORMANT until %u\n",RET_eventTime_wakeFromDormant);
            }
            break;
        case STATE_NORMAL :
            DEBUG("STATE:NORMAL\n");
            //check and log motion
            checkMotion();
            
            //LOCATION EVENT
            bool run_location_tx = false;
            if(RET_RTCunixtime >= RET_eventTime_location_tx && RET_eventTime_location_tx > 0) { run_location_tx = true; }
            //Location Failsafe timer catchall
            if(RET_RTCunixtime >= RET_eventTime_location_failsafe_tx && RET_eventTime_location_failsafe_tx > 0) { run_location_tx = true; }
            if (run_location_tx) { DEBUG("INTERVAL LOC TX...\n"); event_location_tx(); }
            
            //ACTIVITY EVENT
            bool run_activity_tx = false;
            if(RET_RTCunixtime >= RET_eventTime_activity_tx && RET_eventTime_activity_tx > 0 && strlen(RET_activityData) > 1) { 
                run_activity_tx = true; 
                //event_shakertest_tx();
            }
            if (strlen(RET_activityData) > 130) { run_activity_tx = true; }
            if (run_activity_tx) { DEBUG("ACTIVITY TX...\n"); event_activity_tx();}
            
            break;
        case STATE_DORMANT :
            if (RET_RTCunixtime >= RET_eventTime_wakeFromDormant) {
                if (RET_haveSettings) {
                    setState(STATE_NORMAL); 
                } else {
                    setState(STATE_SETUP); 
                }
                
                DEBUG("WAKING UP FROM DORMANT\n");
            }
            DEBUG("STATE:DORMANT until %u\n",RET_eventTime_wakeFromDormant);
            break;
        case STATE_BUTTONPRESS1 :
            setState(STATE_NORMAL);
            DEBUG("STATE:BUTTONPRESS1\n");
            LED1blink(1,300);
            break; 
        case STATE_BUTTONPRESS2 :
            setState(STATE_NORMAL);
            DEBUG("STATE:BUTTONPRESS2\n");
            LED1blink(2,300);
            break;  
        case STATE_BUTTONHOLD :
            DEBUG("STATE:BUTTONHOLD\n");
            if (RET_state_prev == STATE_NORMAL) {
                setState(STATE_DORMANT);
                RET_eventTime_wakeFromDormant = (RET_RTCunixtime + (48*3600)); //48hrs
                DEBUG("TURNING OFF\n");
                DEBUG("STATE:DORMANT until %u\n",RET_eventTime_wakeFromDormant);
                LED1on(5000);
            } else {
                if (RET_haveSettings) {
                    setState(STATE_NORMAL);
                } else {
                    setState(STATE_SETUP);
                }
                DEBUG("TURNING ON\n");
                LED1blink(20,100);
            }
            break;
        default :
            setState(STATE_SETUP);
            DEBUG("DEFAULT STATE\n");
    }
}


//------------------------------------------------------------------------------
// MAIN
//------------------------------------------------------------------------------ 
int main() {
    //INIT
    turnOffEverything();
    if (!memoryIntegrityCheck()) { RET_coldBoot = 1;}
    RTCticker.attach(&RTCtick, 1.0);
    button.fall(&buttonPress); //does this affect power?
    button.rise(&buttonRelease);
    
    //CHECK IF THIS IS RESET
    //0x00000004 == soft reset  //0x00000002 == watchdog  //0x00000001 == button/hardreset 
    if (NRF_POWER->RESETREAS != 0xffffffff) {
        switch(NRF_POWER->RESETREAS) {
            case 0x00000001  :
                DEBUG("reset_reason: 0x%08x. Hard Reset STATE:%d\n",NRF_POWER->RESETREAS, RET_state);
                RET_coldBoot = 1;
            break;
            case 0x00000002  :
                DEBUG("Watchdog reset STATE:%d\n",RET_state);
            break;
            case 0x00000004  :
                DEBUG("Soft reset STATE:%d SLEEP:%d\n",RET_state, RET_sleepToggle);
            break;
        }
        NRF_POWER->RESETREAS = 0xffffffff;
    }
    
    dumpSettings();
    
    //CHECK FOR FIRST BOOT
    if (RET_coldBoot == 1) { factoryReset(); dumpSettings(); }
    
    //SHALL WE SLEEP
    if (RET_sleepToggle == 1) {
        RET_sleepToggle = 0; 
        NRF_UART0->TASKS_SUSPEND = 1;
        NRF_UART0->ENABLE = 0; //NO MORE SERIAL OR DEBUG OUTPUTS AFTER THIS
        mainthread.wait(SLEEP_FRAME);
        system_reset();
    }
    
    //while(true) {
        watchdogKick();
        //LOG START TIME
        GLOBAL_wakeTime = RET_RTCunixtime;
        
        //MAIN LOGIC
        DEBUG("STATE:%d, HAVESETTINGS:%d, MOTION: %d, RTC:%u, BOOTAT:%u, LOC:%u, LOCFS:%u, ACT:%u \n", RET_state, RET_haveSettings, RET_motionState, RET_RTCunixtime,RET_SetupRunAt,RET_eventTime_location_tx,RET_eventTime_location_failsafe_tx,RET_eventTime_activity_tx);
        DEBUG("ACTIVITY:%s\n",RET_activityData);
        float temperature = getTemperature();
        DEBUG("temp:%.2f\n",temperature);
        mainStateEngine();
        
        //PRE-SLEEP ACTIONS
        if (GLOBAL_needToConfigureLis3dh) { lis3dh_configureForSleep(10,127); }
        turnOffEverything();
        /*if (GLOBAL_modemOn) {
            DEBUG("SHUTTING DOWN MODEM\n");
            Modem modem(PN_UART_TX, PN_UART_RX, PN_UART_CTS, PN_UART_RTS, PN_GSM_PWR_KEY, PN_VREG_EN, PN_GSM_WAKE_DISABLE);
            modem.off(true);
        }*/
        
        
        //SLEEP DIFFERENT FOR THIS SHAKER TEST VERSION - AS IS WILL GIVE 450ua sleep if in motion
        /*
        NRF_UART0->TASKS_SUSPEND = 1;
        NRF_UART0->ENABLE = 0; //NO MORE SERIAL OR DEBUG OUTPUTS AFTER THIS
        mainthread.wait(SLEEP_FRAME);
        */
        
        RET_coldBoot = 0;
        RET_sleepToggle = 1;
        system_reset();
    //}
}