init

Dependencies:   aconno_I2C Lis2dh12 WatchdogTimer

Revision:
41:07e41dbd5304
Parent:
40:4270e09e59f2
Child:
42:f482f4cdb319
--- a/main.cpp	Thu Jan 17 21:59:18 2019 +0000
+++ b/main.cpp	Thu Jan 17 23:40:03 2019 +0000
@@ -3,28 +3,7 @@
 //------------------------------------------------------------------------------
 //DEFINES
 //------------------------------------------------------------------------------ 
-#define FW_VERSION          21
-#define SKU                 "GPSPLUS"
-#define HW_MAJORREVISION    "001"
 
-//MODES
-#define USE_NRF_TEMP_SENSOR                 1
-
-//DEFAULT SETTINGS
-#define DEFAULT_SLEEP_FRAME                 60000
-#define DEFAULT_FORCE2G                     true
-#define DEFAULT_LOCATION_MODE               2
-#define DEFAULT_LOCATION_ACCURACY           2  // 0 = no location, 1 = cl only, 2 = gps then cl
-#define DEFAULT_LOCATION_TX_INTERVAL_MINS   1440
-#define DEFAULT_LOCATION_TX_FAILSAFE_HRS    168
-#define DEFAULT_LOCATION_TIMEOUT            180
-#define DEFAULT_MOTION_G                    11
-#define DEFAULT_MOTION_START_SECONDS        120
-#define DEFAULT_MOTION_STOP_SECONDS         120
-#define DEFAULT_IMPACT_G                    127
-#define DEFAULT_CONNECTION_ATTEMPTS         1
-#define DEFAULT_CONNECTION_TIMEOUT          180
-#define DEFAULT_BEACON_INTERVAL_SECONDS     10
 
 //------------------------------------------------------------------------------
 //FUNCTION PROTOTYPES - NEED TO ADD ALL OF THE MISSING ONES
@@ -34,7 +13,7 @@
 void buttonPress(void);
 void buttonRelease(void);
 void dumpSettings(void);
-void saveEventTimes(void);
+//void setEventTimes(void);
 
 //------------------------------------------------------------------------------
 // GLOBALS
@@ -81,6 +60,7 @@
 time_t           RET_buttonHoldTime;
 time_t           RET_SetupRunAt;
 time_t           RET_SettingsGotAt;
+bool             RET_setupInProgress;
 bool             RET_force2G;
 bool             RET_watchdogfired;
 //MOTION STATE
@@ -161,26 +141,6 @@
         debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_beacon_interval_seconds:%d", RET_setting_beacon_interval_seconds);debug_exe();
         debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_beacon_scan:%d", RET_setting_beacon_scan);debug_exe();
     }
-    
-    /*DEBUG("RET_RTCunixtime:%u",RET_RTCunixtime);
-    DEBUG("RET_setting_firmware:%d",RET_setting_firmware);
-    DEBUG("RET_setting_minimumupdate_hrs:%d",RET_setting_minimumupdate_hrs);
-    DEBUG("RET_state:%d",RET_state);
-    DEBUG("RET_setting_location_mode:%d",RET_setting_location_mode);
-    DEBUG("RET_setting_location_accuracy:%d",RET_setting_location_accuracy);
-    DEBUG("RET_setting_location_tx_interval_mins:%d",RET_setting_location_tx_interval_mins);
-    DEBUG("RET_setting_location_tx_failsafe_hrs:%d",RET_setting_location_tx_failsafe_hrs);
-    DEBUG("RET_setting_location_timeout:%d",RET_setting_location_timeout);
-    DEBUG("RET_setting_activity_tx_interval_hrs:%d",RET_setting_activity_tx_interval_hrs);
-    DEBUG("RET_setting_environmental_tx_interval_mins:%d",RET_setting_environmental_tx_interval_mins);
-    DEBUG("RET_setting_motion_g:%d",RET_setting_motion_g);
-    DEBUG("RET_setting_motion_start_seconds:%d",RET_setting_motion_start_seconds);
-    DEBUG("RET_setting_motion_stop_seconds:%d",RET_setting_motion_stop_seconds);
-    DEBUG("RET_setting_impact_g:%d",RET_setting_impact_g);
-    DEBUG("RET_setting_impact_alert:%d",RET_setting_impact_alert);
-    DEBUG("RET_setting_connection_timeout:%d",RET_setting_connection_timeout);
-    DEBUG("RET_setting_beacon_interval_seconds:%d",RET_setting_beacon_interval_seconds);
-    DEBUG("RET_setting_beacon_scan:%d",RET_setting_beacon_scan);*/
 }
 float getBatteryV() {
     NRF52_SAADC batteryIn;
@@ -255,22 +215,16 @@
             if((RET_RTCunixtime - RET_buttonPressTime) > 1) {
                 switch (RET_buttonPressCount) {   
                     case 1 :
-                        if (RET_state == STATE_NORMAL) {
-                            RET_state = STATE_BUTTONPRESS1;
-                            mainthread.release();
-                        }
+                        RET_state = STATE_BUTTONPRESS1;
+                        mainthread.release();
                         break;
                     case 3 :
-                        if (RET_state == STATE_NORMAL) {
-                            RET_state = STATE_BUTTONPRESS2;
-                            mainthread.release();
-                        }
+                        RET_state = STATE_BUTTONPRESS2;
+                        mainthread.release();
                         break;
                     case 5 :
-                        if (RET_state == STATE_NORMAL) {
-                            RET_state = STATE_BUTTONPRESS3;
-                            mainthread.release();
-                        }
+                        RET_state = STATE_BUTTONPRESS3;
+                        mainthread.release();
                         break;
                     default :
                         //do nothing
@@ -280,7 +234,7 @@
             }
         }
         //SETUP STATE VISUALISE
-        if (!GLOBAL_LEDSequenceinProgress && RET_state == STATE_SETUP) {
+        if (!GLOBAL_LEDSequenceinProgress && RET_setupInProgress) {
             led1 = !led1; 
         }
     }
@@ -291,24 +245,41 @@
     memset(GLOBAL_exceptionString,0x00,sizeof(GLOBAL_exceptionString));
 }
 void healthCheck() {
-    //check clock
-    if(RET_haveSettings == 1) {
-        if (RET_RTCunixtime < 1547678732) {
-            //go dormant for 72hrs and then resetup
-            RET_haveSettings = 0; 
-            setState(STATE_DORMANT);
-        }
-    }
     //check for watchdog fire
     if (RET_watchdogfired == true) {
         addToExceptionString("WD");
         RET_watchdogfired = false;
     }
+    //check clock
+    if(RET_haveSettings == true) {
+        if (RET_RTCunixtime < 1547678732) {
+            //go dormant for 72hrs and then resetup
+            RET_haveSettings = false; 
+            setState(STATE_DORMANT);
+        }
+    }
+    //check that we have a reasonable time to loc
+    if(RET_haveSettings == true) {
+        //check location tx delta is set
+        if (RET_eventTime_location_tx == 0) {
+            if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "ERR:eventTime_location_tx is 0");debug_exe();}
+            RET_haveSettings = false;
+        }
+        //check location failsafe tx delta is less that 2 weeks
+        long location_failsafe_tx_delta = (RET_eventTime_location_failsafe_tx - RET_RTCunixtime);
+        if (location_failsafe_tx_delta > TENDAYSINSECONDS) {
+            if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "ERR:location_failsafe_tx_delta too small");debug_exe();}
+            RET_haveSettings = false;
+        }
+    }
+    if (RET_haveSettings == false) {
+        setState(STATE_SETUP);
+    }
 }
 void setDefaults() {
     //STATE
     RET_asleep = false;
-    RET_haveSettings = 0;
+    RET_haveSettings = false;
     RET_state = STATE_SETUP;
     RET_state_prev = RET_state;
     RET_RTCunixtime = 0;
@@ -316,6 +287,7 @@
     RET_SettingsGotAt = 0;
     RET_force2G = DEFAULT_FORCE2G;
     RET_watchdogfired = false;
+    RET_setupInProgress = false;
     //SETTINGS
     RET_setting_firmware = 0;
     RET_setting_minimumupdate_hrs = 0;
@@ -427,11 +399,12 @@
     //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
+        time_t inMotionForSeconds = (RET_RTCunixtime - RET_motionStartTime) + 5; //Plus 5 to account for rounding and non exact clocks
+        if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "IN MOTION FOR:%d",inMotionForSeconds);debug_exe();}
         if (inMotionForSeconds >= RET_setting_motion_start_seconds && RET_motionState == false) {
             RET_motionState = true;
             RET_motionTriggeredInTXInterval = true;
-            if (GLOBAL_debugLED) LED1blink(1,50);
+            //if (GLOBAL_debugLED) LED1blink(1,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);
@@ -439,14 +412,15 @@
         }
     }
     if (RET_motionPendingOffState) {
-        time_t noMotionForSeconds = (RET_RTCunixtime - RET_motionStopTime) + 2; //Plus 2 to account for rounding and non exact clocks
+        time_t noMotionForSeconds = (RET_RTCunixtime - RET_motionStopTime) + 5; //Plus 5 to account for rounding and non exact clocks
+        if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "STOPPED FOR:%d",noMotionForSeconds);debug_exe();}
         if (noMotionForSeconds >= RET_setting_motion_stop_seconds && RET_motionState == true) {
+            //if (GLOBAL_debugLED) LED1blink(2,50);
             RET_motionPendingOffState = false;
             RET_motionState = false;
             GLOBAL_motionStopFlagTriggered = true;
-            RET_motionTotalActivityHours += (float(RET_motionStopTime - RET_motionStartTime) / 3600.0f); 
-            if (GLOBAL_debugLED) LED1blink(2,50);
             if (RET_setting_location_tx_failsafe_hrs > 0) {
+                RET_motionTotalActivityHours += (float(RET_motionStopTime - RET_motionStartTime) / 3600.0f);
                 time_t epochOffsetMins = ((RET_RTCunixtime - RET_motionFrameStart) / 60);
                 sprintf(RET_activityData+strlen(RET_activityData),"0.%u!",epochOffsetMins);
             }
@@ -464,45 +438,38 @@
     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,"a:%d,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_a,&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("FROMSERVER: a:%d,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_a,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);*/
-        
         if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "FROMSERVER: a:%d,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_a,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);debug_exe();}
         
-        //FAILUREMODE need to be checking these against checksums
-        char changed;
-        
-        if(TEMP_a != -1) { RET_setting_minimumupdate_hrs = TEMP_a;                 changed = 'Y'; } else { changed = 'N'; }; DEBUG("RET_setting_minimumupdate_hrs:%u..%c\n",RET_setting_minimumupdate_hrs,changed);
-        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 { setState(STATE_NORMAL); changed = 'N'; }; 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_a != -1) { RET_setting_minimumupdate_hrs = TEMP_a;                      }
+        if(TEMP_b != 0)  { RET_RTCunixtime = TEMP_b;                                    } else { critical_fail_count++; }
+        if(TEMP_c != -1) { RET_setting_firmware = TEMP_c;                               } else { RET_setting_firmware = -1;}
+        if(TEMP_d != -1) { setState(TEMP_d);                                            } else { setState(STATE_NORMAL);}
+        if(TEMP_e != -1) { RET_setting_location_mode = TEMP_e;                          }
             if(RET_setting_location_mode > 3) {RET_setting_location_mode = DEFAULT_LOCATION_MODE;}
-        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_f != -1) { RET_setting_location_accuracy = TEMP_f;                      }
             if(RET_setting_location_accuracy > 3) {RET_setting_location_accuracy = DEFAULT_LOCATION_ACCURACY;}
-        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_g != -1) { RET_setting_location_tx_interval_mins = TEMP_g;              }
+        if(TEMP_h != -1) { RET_setting_location_tx_failsafe_hrs = TEMP_h;               }
             if(RET_setting_location_tx_failsafe_hrs > 504) {RET_setting_location_tx_failsafe_hrs = DEFAULT_LOCATION_TX_FAILSAFE_HRS;}
-        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_i != -1) { RET_setting_location_timeout = TEMP_i;                       }
             if(RET_setting_location_timeout < 60 || RET_setting_location_timeout > 300) {RET_setting_location_timeout = DEFAULT_LOCATION_TIMEOUT;}
-        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_j != -1) { RET_setting_activity_tx_interval_hrs = TEMP_j;               }
+        if(TEMP_k != -1) { RET_setting_environmental_tx_interval_mins = TEMP_k;         }
+        if(TEMP_l != -1) { RET_setting_motion_g = TEMP_l;                               }
             if(RET_setting_motion_g < 6 || RET_setting_motion_g > 127) {RET_setting_motion_g = DEFAULT_MOTION_G;}
-        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_m != -1) { RET_setting_motion_start_seconds = TEMP_m;                   }
+        if(TEMP_n != -1) { RET_setting_motion_stop_seconds = TEMP_n;                    }
+        if(TEMP_o != -1) { RET_setting_impact_g = TEMP_o;                               }
+        if(TEMP_p != -1) { RET_setting_impact_alert = TEMP_p;                           }
+        if(TEMP_q != -1) { RET_setting_connection_timeout = TEMP_q;                     }
             if(RET_setting_connection_timeout < 60 || RET_setting_connection_timeout > 240) { RET_setting_connection_timeout = DEFAULT_CONNECTION_TIMEOUT; }
-        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(TEMP_r != -1) { RET_setting_beacon_interval_seconds = TEMP_r;                }
+        if(TEMP_s != -1) { RET_setting_beacon_scan = TEMP_s;                            }
         
         if (critical_fail_count == 0) { 
             if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "GOT SETTINGS OK");debug_exe();}
             dumpSettings();
-            saveEventTimes();
             RET_haveSettings = true;
             GLOBAL_needToConfigureLis3dh = true;
             RET_SettingsGotAt = RET_RTCunixtime;
@@ -530,26 +497,38 @@
     }
 }
 
-void saveEventTimes() {
-    //SET EVENT TIMES
+//------------------------------------------------------------------------------
+// SET EVENT TIMES
+//------------------------------------------------------------------------------ 
+void setEventTime_Location() {
     if(RET_setting_location_tx_interval_mins > 0) { 
         RET_eventTime_location_tx = (RET_RTCunixtime + (RET_setting_location_tx_interval_mins * 60));
-        if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENTSET - LOCATION TX at %u, MODE %d\n",RET_eventTime_location_tx, RET_setting_location_mode);debug_exe();}
+        if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENTSET - LOCATION TX at %u, MODE %d",RET_eventTime_location_tx, RET_setting_location_mode);debug_exe();}
     }
     if(RET_setting_location_tx_failsafe_hrs > 0) { 
         RET_eventTime_location_failsafe_tx = (RET_RTCunixtime + (RET_setting_location_tx_failsafe_hrs * 3600));
-        if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENTSET - LOCATION FAILSAFE TX at %u\n",RET_eventTime_location_failsafe_tx);debug_exe();}
+        if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENTSET - LOCATION FAILSAFE TX at %u",RET_eventTime_location_failsafe_tx);debug_exe();}
     }
+}
+void setEventTime_Activity() {
     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));
-        if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENTSET - ACTIVITY TX at %u\n",RET_eventTime_activity_tx);debug_exe();}
+        if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENTSET - ACTIVITY TX at %u",RET_eventTime_activity_tx);debug_exe();}
     }
+}
+void setEventTime_Environmental() {
     if(RET_eventTime_environmental_tx > 0) { 
         RET_eventTime_environmental_tx = (RET_RTCunixtime + (RET_setting_environmental_tx_interval_mins * 60));
-        if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENTSET - ENVIRONMENTAL TX at %u\n",RET_eventTime_environmental_tx);debug_exe();}
+        if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENTSET - ENVIRONMENTAL TX at %u",RET_eventTime_environmental_tx);debug_exe();}
     }
 }
+void setEventTimes() {
+    //SET EVENT TIMES
+    setEventTime_Location();
+    setEventTime_Activity();
+    setEventTime_Environmental();
+}
 
 //------------------------------------------------------------------------------
 // ERROR LOG
@@ -568,6 +547,7 @@
 // SETUP
 //------------------------------------------------------------------------------ 
 bool setup() {
+    RET_setupInProgress = true;
     bool pass = true;
     float temperature = getTemperature();
     float voltage = getBatteryV();
@@ -583,7 +563,6 @@
             char result[200];
             snprintf(result,sizeof(result),"%s",modem.USSDmessage(bytestosend, true, 2, GLOBAL_defaultApi));
             if (strcmp(result, "err") != 0) {
-                //DEBUG("\nfromserver: %s \n",result);
                 if (!saveSettings(result)) {
                     //something went critically wrong getting settings 
                     pass = false;
@@ -597,14 +576,12 @@
             }
         } else {
             //FAILUREMODE modem failed to register on network
-            DEBUG("NET REGISTER FAIL",false);
             modem.off(false);
             if(GLOBAL_debugLED) LED1errorCode(3,10); //ERROR 3
             pass = false;
         }
     } else {
         //FAILUREMODE Modem failed to turn on  
-        DEBUG("MODEM ON FAIL",false);
         modem.off(false);
         if(GLOBAL_debugLED) LED1errorCode(2,10); //ERROR 2
         pass = false;
@@ -614,6 +591,11 @@
     //LOG RUN TIME - THIS MUST GO AT END AFTER WE HAVE GOT SERVER TIMESTAMP
     RET_SetupRunAt = RET_RTCunixtime;
     
+    //SET ALL EVENT TIMES
+    setEventTimes();
+    
+    RET_setupInProgress = false; //this turns off the flashing led
+    
     //RESULT
     return pass;
 }
@@ -622,7 +604,6 @@
 // EVENTS
 //------------------------------------------------------------------------------ 
 void event_connectiontest_tx(int location_accuracy) {
-    DEBUG("TEST EVENT\n",false);
     float temperature = getTemperature();
     float voltage = getBatteryV();  
     int selftestresult = selfTest();
@@ -658,11 +639,10 @@
     modem.off(false);
     //RESETS
     RET_motionTriggeredInTXInterval = 0;
-    saveEventTimes();
+    setEventTimes();
 }
 
 void event_turnonofflog_tx(bool turnon) {
-    DEBUG("TEST EVENT\n",false);
     float temperature = getTemperature();
     float voltage = getBatteryV();
     if (modem.on(RET_force2G)) {
@@ -690,14 +670,12 @@
 }
 
 void event_location_tx() {
-    DEBUG("LOCATION TX\n",false);
     float temperature = getTemperature();
     float voltage = getBatteryV();
     int selfTestResult = selfTest();
     if (modem.on(RET_force2G)) {
         char locString[70];
         memcpy(locString, modem.getLocation(RET_setting_location_accuracy, RET_setting_location_timeout), 70);
-        //DEBUG("locString:%s-\n",locString);
         //SEND DATA
         if (modem.registerOnNetwork(DEFAULT_CONNECTION_ATTEMPTS,(RET_setting_connection_timeout*1000))) {
             int timetaken = (RET_RTCunixtime - GLOBAL_wakeTime) + 10; //add 10 for ussd response time 
@@ -709,7 +687,6 @@
             char result[180];
             snprintf(result,sizeof(result),"%s",modem.USSDmessage(bytesToSend, getSettings, 2, GLOBAL_defaultApi));
             if (result != "err") {
-                //DEBUG("\nfromserver: %s \n",result);
                 if (getSettings) {
                     saveSettings(result);
                 } else {
@@ -729,11 +706,10 @@
     modem.off(false);
     //RESETS
     RET_motionTriggeredInTXInterval = 0;
-    saveEventTimes();
+    setEventTime_Location();
 }
 
 void event_activity_tx() {
-    DEBUG("ACTIVITY TX\n",false);
     float temperature = getTemperature();
     float voltage = getBatteryV();
     if (modem.on(RET_force2G)) {
@@ -760,7 +736,7 @@
     modem.off(false);
     //RESETS
     RET_motionTriggeredInTXInterval = 0;
-    saveEventTimes();
+    setEventTime_Activity();
 }
 
 //------------------------------------------------------------------------------
@@ -771,21 +747,25 @@
     switch(RET_state) {
         case STATE_SETUP :
         { //need the curlies to avoid "transfer of control bypass init error warning"
-            DEBUG("STATE:SETUP\n",false);
-            if (setup()) {
-                // All good
-                setState(STATE_NORMAL);
+            //check that we havent run setup too recently
+            time_t setupRunAt_delta = (RET_RTCunixtime - RET_SetupRunAt);
+            if (RET_SetupRunAt == 0 || setupRunAt_delta > ONEDAYINSECONDS) {
+                if (setup()) {
+                    // All good
+                    setState(STATE_NORMAL);
+                } else {
+                    RET_eventTime_wakeFromDormant = (RET_RTCunixtime + ONEDAYINSECONDS);
+                    setState(STATE_DORMANT);
+                    if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"SETUP FAILED:DORMANT until %u\n",RET_eventTime_wakeFromDormant);debug_exe();}
+                }
             } else {
-                RET_eventTime_wakeFromDormant = (RET_RTCunixtime + (24*3600)); //24hrs
-                setState(STATE_DORMANT);
-                DEBUG("SETUP FAILED:DORMANT until %u\n",RET_eventTime_wakeFromDormant);
+                time_t setupCanRunAt = (RET_RTCunixtime + (ONEDAYINSECONDS - setupRunAt_delta));
+                if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"SETUP CAN RUN AGAIN @%u \n",setupCanRunAt);debug_exe();}
             }
             break;
         }
         case STATE_NORMAL :
-        {
-            DEBUG("STATE:NORMAL\n",false);
-            
+        {            
             //LOCATION EVENT
             bool run_location_tx = false;
             switch (RET_setting_location_mode) {
@@ -815,7 +795,7 @@
                 run_activity_tx = true;
             }
             if (strlen(RET_activityData) > 130) { run_activity_tx = true; }
-            if (run_activity_tx) { DEBUG("ACTIVITY TX...\n",false); event_activity_tx();}
+            if (run_activity_tx) { event_activity_tx();}
             
             break;
         }
@@ -827,22 +807,21 @@
                 } else {
                     setState(STATE_SETUP); 
                 }
-                DEBUG("WAKING UP FROM DORMANT\n",false);
             }
-            DEBUG("STATE:DORMANT until %u\n",RET_eventTime_wakeFromDormant);
+            if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"STATE:DORMANT until %u\n",RET_eventTime_wakeFromDormant);debug_exe();}
             break;
         }
         case STATE_BUTTONPRESS1 :
         {
             setState(STATE_NORMAL);
-            DEBUG("STATE:BUTTONPRESS1\n",false);
+            if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"BUTTON PRESS 1\n");debug_exe();}
             LED1blink(1,300);
             break;
         }
         case STATE_BUTTONPRESS2 :
         {
             setState(STATE_NORMAL);
-            DEBUG("STATE:BUTTONPRESS2\n",false);
+            if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"BUTTON PRESS 2\n");debug_exe();}
             LED1blink(2,300);
             LED1on(0);
             event_connectiontest_tx(1);
@@ -852,7 +831,7 @@
         case STATE_BUTTONPRESS3 :
         {
             setState(STATE_NORMAL);
-            DEBUG("STATE:BUTTONPRESS3\n",false);
+            if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"BUTTON PRESS 3\n");debug_exe();}
             LED1blink(3,300);
             LED1on(0);
             event_connectiontest_tx(2);
@@ -861,12 +840,12 @@
         }
         case STATE_BUTTONHOLD :
         {
-            DEBUG("STATE:BUTTONHOLD\n",false);
+            if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"BUTTON HOLD \n");debug_exe();}
             if (RET_state_prev == STATE_NORMAL) {
-                RET_eventTime_wakeFromDormant = (RET_RTCunixtime + (72*3600)); //72hrs
+                RET_eventTime_wakeFromDormant = (RET_RTCunixtime + THREEDAYSINSECONDS);
                 setState(STATE_DORMANT);
-                DEBUG("TURNING OFF\n",false);
-                DEBUG("STATE:DORMANT until %u\n",RET_eventTime_wakeFromDormant);
+                if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"TURNING OFF\n");debug_exe();}
+                if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"STATE:DORMANT until %u\n",RET_eventTime_wakeFromDormant);debug_exe();}
                 LED1on(5000);
                 event_turnonofflog_tx(false);
             } else {
@@ -875,7 +854,7 @@
                 } else {
                     setState(STATE_SETUP);
                 }
-                DEBUG("TURNING ON\n",false);
+                if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"TURNING ON\n");debug_exe();}
                 LED1blink(20,100);
                 event_turnonofflog_tx(true);
             }
@@ -894,7 +873,6 @@
         default :
         {
             setState(STATE_SETUP);
-            DEBUG("DEFAULT STATE\n",false);
         }
     }
 }
@@ -917,15 +895,15 @@
     if (NRF_POWER->RESETREAS != 0xffffffff) {
         switch(NRF_POWER->RESETREAS) {
             case 0x00000001  :
-                //DEBUG("0x%08x. Hard Reset ST:%d\n",NRF_POWER->RESETREAS, RET_state);
+                if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"0x%08x. Hard Reset ST:%d\n",NRF_POWER->RESETREAS, RET_state);debug_exe();}
                 RET_coldBoot = 1;
             break;
             case 0x00000002  :
-                //DEBUG("Watchdog ST:%d\n",RET_state);
+                if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"Watchdog ST:%d\n",RET_state);debug_exe();}
                 RET_watchdogfired = true;
             break;
             case 0x00000004  :
-                //DEBUG("Soft ST:%d\n",RET_state);
+                if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"Soft ST:%d\n",RET_state);debug_exe();}
             break;
         }
         NRF_POWER->RESETREAS = 0xffffffff;
@@ -950,7 +928,6 @@
     while(true) {
         //WATCHDOG
         watchdogKick();
-        LED1off();
         RET_asleep = false;
         
         //INIT
@@ -962,8 +939,6 @@
         if (RET_state == STATE_NORMAL) { checkMotion(); }
         
         //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);
         if(DEBUG_ON){
             if (RET_state != 99) {
                 debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "FW:%d,ST:%d, SET:%d, MOTFR:%d, MOTST: %d, RTC:%u, LOC:%u, LOCFS:%u, ACT:%u \n", FW_VERSION, RET_state, RET_haveSettings, RET_motionTriggeredinFrame, RET_motionState, RET_RTCunixtime,RET_eventTime_location_tx,RET_eventTime_location_failsafe_tx,RET_eventTime_activity_tx);debug_exe();