init
Dependencies: aconno_I2C Lis2dh12 WatchdogTimer
main.cpp
- Committer:
- pathfindr
- Date:
- 2019-01-20
- Revision:
- 45:6c7f5b556d74
- Parent:
- 44:061509d1b38c
- Child:
- 46:b95fe3484d88
File content as of revision 45:6c7f5b556d74:
#include "main.h" //------------------------------------------------------------------------------ //FUNCTION PROTOTYPES - NEED TO ADD ALL OF THE MISSING ONES //------------------------------------------------------------------------------ //should really add these - will just add as and when needed for now void event_activity_tx(uint8_t activity_mode); //------------------------------------------------------------------------------ // GLOBALS //------------------------------------------------------------------------------ char* GLOBAL_defaultApi = "b:gps2"; bool GLOBAL_accel_healthy = false; bool GLOBAL_motionStopFlagTriggered = false; bool GLOBAL_debugLED = true; bool GLOBAL_needToConfigureLis3dh = false; bool GLOBAL_registeredOnNetwork = false; bool GLOBAL_modemOn = false; bool GLOBAL_LEDSequenceinProgress = false; time_t GLOBAL_wakeTime = 0; char GLOBAL_exceptionString[30]; char GLOBAL_debug_buffer[200]; int RET_setting_firmware; uint32_t RET_setting_minimumupdate_hrs; uint8_t RET_setting_location_mode; uint8_t RET_setting_location_accuracy; uint32_t RET_setting_location_tx_interval_mins; uint32_t RET_setting_location_tx_failsafe_hrs; uint16_t RET_setting_location_timeout; uint32_t RET_setting_activity_tx_interval_hrs; uint8_t RET_setting_activity_mode; uint32_t RET_setting_environmental_tx_interval_mins; uint16_t RET_setting_motion_g; time_t RET_setting_motion_start_seconds; time_t RET_setting_motion_stop_seconds; uint16_t RET_setting_impact_g; uint8_t RET_setting_impact_alert; uint16_t RET_setting_connection_timeout; uint16_t RET_setting_beacon_interval_seconds; uint16_t RET_setting_beacon_scan; //STATE uint8_t RET_coldBoot = 1; bool RET_asleep = false; time_t RET_RTCunixtime; bool RET_haveSettings; uint8_t RET_state; uint8_t RET_state_prev; uint8_t RET_buttonPressCount; time_t RET_buttonPressTime; time_t RET_buttonHoldTime; time_t RET_SetupRunAt; time_t RET_SettingsGotAt; bool RET_setupInProgress; bool RET_force2G; bool RET_watchdogfired; bool RET_receivedNewSettings; //MOTION STATE bool RET_motionTriggeredinFrame; bool RET_motionTriggeredInLocTXInterval; time_t RET_motionStartTime; time_t RET_motionStopTime; bool RET_motionPendingOnState; bool RET_motionPendingOffState; bool RET_motionState; float RET_motionTotalActivityHours; float RET_motionTotalActivityHoursSincePost; time_t RET_motionFrameStart; char RET_activityData[ACTIVITY_BUFFERSIZE]; //IMPACT bool RET_impactTriggered; //EVENTS LOGGING time_t RET_eventTime_location_log; time_t RET_eventTime_environmental_log; //EVENTS TX time_t RET_eventTime_location_tx; time_t RET_eventTime_location_failsafe_tx; time_t RET_eventTime_environmental_tx; time_t RET_eventTime_activity_tx; time_t RET_eventTime_wakeFromDormant; //------------------------------------------------------------------------------ //GPIO //------------------------------------------------------------------------------ InterruptIn button(PN_IN_BUTTON); //------------------------------------------------------------------------------ //PERIPHERALS //------------------------------------------------------------------------------ //BLE myble; WatchdogTimer watchdog; //Do not set to less than 4500ms or can cause issues with softdevice void watchdogKick() {watchdog.kick();} SI7060 si7060(PN_I2C_SDA, PN_I2C_SCL); LIS3DH lis3dh(PN_SPI_MOSI, PN_SPI_MISO, PN_SPI_CS0, PN_SPI_CLK); Modem modem(PN_GSM_PWR_KEY, PN_VREG_EN, PN_GSM_WAKE_DISABLE); LowPowerTicker RTCticker; //------------------------------------------------------------------------------ //THREAD SEMAPHORES //------------------------------------------------------------------------------ Semaphore mainthread; //------------------------------------------------------------------------------ // LOW LEVEL FUNCS //------------------------------------------------------------------------------ void nrf_configureGPIOForSleep(){ nrf_gpio_cfg_input(PN_SPI_MOSI, NRF_GPIO_PIN_NOPULL); nrf_gpio_cfg_input(PN_SPI_MISO, NRF_GPIO_PIN_NOPULL); } void setState(uint8_t state) { RET_state_prev = RET_state; RET_state = state; } void dumpSettings() { if(DEBUG_ON){ debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_RTCunixtime:%u", RET_RTCunixtime);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_firmware:%d", RET_setting_firmware);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_minimumupdate_hrs:%d", RET_setting_minimumupdate_hrs);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_state:%d", RET_state);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_location_mode:%d", RET_setting_location_mode);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_location_accuracy:%d", RET_setting_location_accuracy);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_location_tx_interval_mins:%d", RET_setting_location_tx_interval_mins);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_location_tx_failsafe_hrs:%d", RET_setting_location_tx_failsafe_hrs);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_location_timeout:%d", RET_setting_location_timeout);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_activity_tx_interval_hrs:%d", RET_setting_activity_tx_interval_hrs);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_activity_mode:%d", RET_setting_activity_mode);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_environmental_tx_interval_mins:%d", RET_setting_environmental_tx_interval_mins);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_motion_g:%d", RET_setting_motion_g);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_motion_start_seconds:%d", RET_setting_motion_start_seconds);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_motion_stop_seconds:%d", RET_setting_motion_stop_seconds);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_impact_g:%d", RET_setting_impact_g);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_impact_alert:%d", RET_setting_impact_alert);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "RET_setting_connection_timeout:%d", RET_setting_connection_timeout);debug_exe(); 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(); } } void recordFirmwareAsValid() { read_app_data_from_flash(&app_data); bool write_app_data_to_flash_execute = false; if(get_flag(&app_data, app_execution_flag) == true) { clr_flag(&app_data, app_execution_flag); clr_flag(&app_data, first_run_flag); write_app_data_to_flash_execute = true; } if(app_data.current_firmware_version != FW_VERSION) { app_data.current_firmware_version = FW_VERSION; app_data.target_firmware_version = FW_VERSION; write_app_data_to_flash_execute = true; } if (write_app_data_to_flash_execute) { write_app_data_to_flash(&app_data); } } float getBatteryV() { 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 nrfTemperature() { //INTERNAL NRF52 TEMP SENSOR uint32_t safetycounter = 0; float temperature = 0.0; NRF_TEMP->TASKS_START=1; while (NRF_TEMP->EVENTS_DATARDY==0 && safetycounter < 10000) { safetycounter ++; }; NRF_TEMP->EVENTS_DATARDY=0; temperature = nrf_temp_read()/4.0; NRF_TEMP->TASKS_STOP=1; return temperature; } float getTemperature() { float temperature; if (USE_NRF_TEMP_SENSOR) { //INTERNAL NRF52 TEMP SENSOR temperature = nrfTemperature(); } else { temperature = si7060.getTemperature(); //currently disabled because its causing a high current 450ua sleep, most likely due to sensor not sleeping correctly, or i2c sleep issue } return temperature; } void addToExceptionString(char* value) { if(strstr(GLOBAL_exceptionString, value) == false){ snprintf(GLOBAL_exceptionString+strlen(GLOBAL_exceptionString),sizeof(GLOBAL_exceptionString),"%s.",value); } } //------------------------------------------------------------------------------ // USER BUTTON HANDLING //------------------------------------------------------------------------------ void buttonPress() { RET_buttonPressTime = RET_RTCunixtime; } void buttonRelease() { RET_buttonHoldTime = (RET_RTCunixtime - RET_buttonPressTime); RET_buttonPressCount ++; led1 = 1; //led off } //------------------------------------------------------------------------------ // 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; //button logic, only when device asleep if (RET_asleep == true) { //led indicator //if (RET_buttonPressTime > 0 && (RET_RTCunixtime - RET_buttonPressTime) > 4) led1 = 0; //if (RET_buttonPressTime > 0 && (RET_RTCunixtime - RET_buttonPressTime) > 14) led1 = 1; //hold check if (RET_buttonHoldTime > 4 && RET_buttonHoldTime < 10) { RET_buttonHoldTime = 0; RET_buttonPressCount = 0; RET_state_prev = RET_state; RET_state = STATE_BUTTONHOLD; mainthread.release(); } else if (RET_buttonHoldTime > 14 && RET_buttonHoldTime < 30) { RET_buttonHoldTime = 0; RET_buttonPressCount = 0; RET_state_prev = RET_state; RET_state = STATE_SCORCHEDEARTH; mainthread.release(); } else { if((RET_RTCunixtime - RET_buttonPressTime) > 1) { switch (RET_buttonPressCount) { case 1 : if(RET_state != STATE_DORMANT) { RET_state = STATE_BUTTONPRESS1; mainthread.release(); } break; case 3 : if(RET_state != STATE_DORMANT) { RET_state = STATE_BUTTONPRESS2; mainthread.release(); } break; case 5 : if(RET_state != STATE_DORMANT) { RET_state = STATE_BUTTONPRESS3; mainthread.release(); } break; default : //do nothing break; } RET_SetupRunAt = 0; //allow setup to run again RET_buttonPressCount = 0; } } //SETUP STATE VISUALISE if (!GLOBAL_LEDSequenceinProgress && RET_setupInProgress) { led1 = !led1; } } } void resetGlobals() { GLOBAL_accel_healthy = false; GLOBAL_motionStopFlagTriggered = false; memset(GLOBAL_exceptionString,0x00,sizeof(GLOBAL_exceptionString)); } void healthCheck() { //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 = false; RET_state = STATE_SETUP; RET_state_prev = RET_state; RET_RTCunixtime = 0; RET_SetupRunAt = 0; RET_SettingsGotAt = 0; RET_force2G = DEFAULT_FORCE2G; RET_watchdogfired = false; RET_setupInProgress = false; RET_receivedNewSettings = false; //SETTINGS RET_setting_firmware = 0; RET_setting_minimumupdate_hrs = 0; RET_setting_location_mode = DEFAULT_LOCATION_MODE; RET_setting_location_accuracy = DEFAULT_LOCATION_ACCURACY; RET_setting_location_tx_interval_mins = DEFAULT_LOCATION_TX_INTERVAL_MINS; RET_setting_location_tx_failsafe_hrs = DEFAULT_LOCATION_TX_FAILSAFE_HRS; RET_setting_location_timeout = DEFAULT_LOCATION_TIMEOUT; RET_setting_activity_tx_interval_hrs = 0; RET_setting_activity_mode = 1; RET_setting_environmental_tx_interval_mins = 0; RET_setting_motion_g = DEFAULT_MOTION_G; RET_setting_motion_start_seconds = DEFAULT_MOTION_START_SECONDS; RET_setting_motion_stop_seconds = DEFAULT_MOTION_STOP_SECONDS; RET_setting_impact_g = 0; RET_setting_impact_alert = 0; RET_setting_connection_timeout = DEFAULT_CONNECTION_TIMEOUT; RET_setting_beacon_interval_seconds = DEFAULT_BEACON_INTERVAL_SECONDS; RET_setting_beacon_scan = 0; RET_buttonPressCount = 0; RET_buttonPressTime = 0; RET_buttonHoldTime = 0; //MOTION STATE RET_motionTriggeredinFrame = false; RET_motionTriggeredInLocTXInterval = false; RET_motionStartTime = 0; RET_motionStopTime = 0; RET_motionPendingOnState = 0; RET_motionPendingOffState = 0; RET_motionState = 0; RET_motionTotalActivityHours = 0.0; RET_motionTotalActivityHoursSincePost = 0.0; RET_motionFrameStart = 0; memset(RET_activityData,0x00,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; //PERIPHERAL RESET lis3dh_configureForSleep(DEFAULT_MOTION_G,DEFAULT_IMPACT_G); } bool selfTest() { int test_count = 0; int test_pass = 0; //Accelerometer test_count ++; uint8_t lis3dh_id; lis3dh.LIS3DH_GetWHO_AM_I(&lis3dh_id); if (lis3dh_id == 51) { GLOBAL_accel_healthy = true; test_pass ++; } else { GLOBAL_accel_healthy = false; addToExceptionString("A"); } //Temperature test_count ++; float temperature; if (USE_NRF_TEMP_SENSOR) { //INTERNAL NRF52 TEMP SENSOR temperature = nrfTemperature(); } else { temperature = si7060.getTemperature(); } if (temperature > -40 && temperature < 60) { test_pass ++; } else { addToExceptionString("T"); } //Result if (test_count == test_pass) { addToExceptionString("OK"); return true; } else { addToExceptionString("FAIL"); return false; } } //------------------------------------------------------------------------------ // MOTION FUNCS //------------------------------------------------------------------------------ void checkMotion() { if (lis3dh_int2) { //if (GLOBAL_debugLED) LED1blink(1,50); RET_motionTriggeredinFrame = 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_motionTriggeredinFrame = 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) + (DEFAULT_SLEEP_FRAME / 1000)); //Plus DEFAULT_SLEEP_FRAME as it should include frame time if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "MOT:%u s",inMotionForSeconds);debug_exe();} if (inMotionForSeconds >= RET_setting_motion_start_seconds && RET_motionState == false) { RET_motionState = true; RET_motionTriggeredInLocTXInterval = true; //if (GLOBAL_debugLED) LED1blink(1,50); if (RET_setting_activity_mode == 2) { 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) + (DEFAULT_SLEEP_FRAME / 1000)); //Plus DEFAULT_SLEEP_FRAME as it should include frame time if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "MOTLESS:%u s",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; if (RET_setting_location_tx_failsafe_hrs > 0) { RET_motionTotalActivityHoursSincePost += ((float(RET_motionStopTime)-float(RET_motionStartTime)) / 3600.0f); RET_motionTotalActivityHours += RET_motionTotalActivityHoursSincePost; if (RET_setting_activity_mode == 2) { time_t epochOffsetMins = ((RET_RTCunixtime - RET_motionFrameStart) / 60); sprintf(RET_activityData+strlen(RET_activityData),"0.%u!",epochOffsetMins); } } } } } //------------------------------------------------------------------------------ // UPDATE OPERATING SETTINGS //------------------------------------------------------------------------------ bool saveSettings(char* settingsBuffer) { int matchCount = 0; int critical_fail_count = 0; int TEMP_a = -1; 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; int TEMP_t = -1; int varTotal = 19; //change this if var number changes!!!!!!!! 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,t:%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,&TEMP_t) ) > 0 ) { 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,t:%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,TEMP_t);debug_exe();} 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; } 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; } 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; } 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; } 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 < 4 || RET_setting_motion_g > 127) {RET_setting_motion_g = DEFAULT_MOTION_G;} 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; } if(TEMP_s != -1) { RET_setting_beacon_scan = TEMP_s; } if(TEMP_t != -1) { RET_setting_activity_mode = TEMP_t; } if (critical_fail_count == 0) { RET_receivedNewSettings = true; if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "SETTINGS OK");debug_exe();} dumpSettings(); RET_haveSettings = true; GLOBAL_needToConfigureLis3dh = true; RET_SettingsGotAt = RET_RTCunixtime; //check for firmware update if (RET_setting_firmware > 0 && RET_setting_firmware != FW_VERSION) { read_app_data_from_flash(&app_data); clr_flag(&app_data, app_execution_flag); clr_flag(&app_data, first_run_flag); app_data.current_firmware_version = FW_VERSION; app_data.target_firmware_version = RET_setting_firmware; write_app_data_to_flash(&app_data); if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "OTA\n");debug_exe();} ThisThread::sleep_for(250); system_reset(); } return true; } else { if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "CRITICAL FAILS:%d",critical_fail_count);debug_exe();} dumpSettings(); addToExceptionString("SCF"); //dont set RET_haveSettings = false; here, if we already have settings continue to use them return false; } } else { //dont set RET_haveSettings = false; here, if we already have settings continue to use them addToExceptionString("SPE"); return false; } } //------------------------------------------------------------------------------ // 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), "EVTSET - LOC TX @ %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), "EVTSET - LOC FS TX @ %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), "EVTSET - ACT TX @ %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), "EVTSET - ENV TX @ %u",RET_eventTime_environmental_tx);debug_exe();} } } void setEventTimes() { //SET ALL EVENT TIMES setEventTime_Location(); setEventTime_Activity(); setEventTime_Environmental(); } //------------------------------------------------------------------------------ // ERROR LOG //------------------------------------------------------------------------------ void sendErrorLog(char* error) { float voltage = getBatteryV(); int timetaken = (RET_RTCunixtime - GLOBAL_wakeTime); char bytestosend[100]; memset(bytestosend,0x00,sizeof(bytestosend)); snprintf(bytestosend,sizeof(bytestosend),"(%s,a:log,f:%d,v:%.2f,e:%d,z:%s.%s,c:1,s:0)\0",GLOBAL_defaultApi,FW_VERSION,voltage,timetaken,error,GLOBAL_exceptionString); if (modem.on(RET_force2G)) { if (modem.registerOnNetwork(DEFAULT_CONNECTION_ATTEMPTS,(RET_setting_connection_timeout*1000))) { modem.USSDmessage(bytestosend, false, 2, GLOBAL_defaultApi); } } ThisThread::sleep_for(250); } //------------------------------------------------------------------------------ // EVENTS //------------------------------------------------------------------------------ bool event_setup(bool manualrun) { RET_setupInProgress = true; bool pass = true; float temperature = getTemperature(); float voltage = getBatteryV(); bool selftestresult = selfTest(); if (selftestresult == false) { LED1errorCode(4,10); } //ERROR 4 int connectionStartTime = RET_RTCunixtime; if (modem.on(RET_force2G)) { char locString[70]; int gpsStartTime = RET_RTCunixtime; memcpy(locString, modem.getLocation(1, RET_setting_location_timeout), 70); int timetaken_gps = (RET_RTCunixtime - gpsStartTime); if (modem.registerOnNetwork(DEFAULT_CONNECTION_ATTEMPTS,(RET_setting_connection_timeout*1000))) { int timetaken_total = (RET_RTCunixtime - GLOBAL_wakeTime) + 10; //add 10 for ussd response time. int timetaken_connection = (RET_RTCunixtime - connectionStartTime); if (manualrun) addToExceptionString("MAN"); char bytestosend[160]; snprintf(bytestosend,sizeof(bytestosend),"(%s,a:setup,f:%d,v:%.2f,t:%.1f,e:%d,y:%d,x:%d,z:SETUP-%s,k:%s,m:%s,c:1,s:1%s)\0",GLOBAL_defaultApi,FW_VERSION,voltage,temperature,timetaken_total,timetaken_connection,timetaken_gps,GLOBAL_exceptionString,SKU,HW_MAJORREVISION,locString); char result[200]; snprintf(result,sizeof(result),"%s",modem.USSDmessage(bytestosend, true, 2, GLOBAL_defaultApi)); if (strcmp(result, "err") != 0) { if (saveSettings(result) == false) { //something went critically wrong getting settings pass = false; sendErrorLog("ERR:SU-IR"); } } else { //Response error sendErrorLog("ERR:SU-NR"); } } else { //FAILUREMODE modem failed to register on network modem.off(true); if(GLOBAL_debugLED) LED1errorCode(3,10); //ERROR 3 pass = false; } } else { //FAILUREMODE Modem failed to turn on modem.off(true); if(GLOBAL_debugLED) LED1errorCode(2,10); //ERROR 2 pass = false; } //SEND ANY ACTIVITY DATA event_activity_tx(RET_setting_activity_mode); modem.off(true); //LOG RUN TIME - THIS MUST GO AT END AFTER WE HAVE GOT SERVER TIMESTAMP RET_SetupRunAt = RET_RTCunixtime; setEventTimes(); RET_setupInProgress = false; //this turns off the flashing led //RESULT return pass; } void event_turnonofflog_tx(bool turnon) { float temperature = getTemperature(); float voltage = getBatteryV(); int connectionStartTime = RET_RTCunixtime; if (modem.on(RET_force2G)) { char locString[70]; int gpsStartTime = RET_RTCunixtime; memcpy(locString, modem.getLocation(1, RET_setting_location_timeout), 70); int timetaken_gps = (RET_RTCunixtime - gpsStartTime); if (modem.registerOnNetwork(DEFAULT_CONNECTION_ATTEMPTS,(RET_setting_connection_timeout*1000))) { int timetaken_total = (RET_RTCunixtime - GLOBAL_wakeTime); int timetaken_connection = (RET_RTCunixtime - connectionStartTime); char bytestosend[160]; if (turnon) { snprintf(bytestosend,sizeof(bytestosend),"(%s,a:log,f:%d,t:%.1f,v:%.2f,z:TURNON,e:%d,y:%d,x:%d,c:1,s:1%s)\0",GLOBAL_defaultApi,FW_VERSION,temperature,voltage,timetaken_total,timetaken_connection,timetaken_gps,locString); } else { snprintf(bytestosend,sizeof(bytestosend),"(%s,a:log,f:%d,t:%.1f,v:%.2f,z:TURNOFF,e:%d,y:%d,x:%d,c:1,s:1%s)\0",GLOBAL_defaultApi,FW_VERSION,temperature,voltage,timetaken_total,timetaken_connection,timetaken_gps,locString); } char result[180]; snprintf(result,sizeof(result),"%s",modem.USSDmessage(bytestosend, false, 2, GLOBAL_defaultApi)); } else { modem.off(true); } } else { modem.off(true); } modem.off(true); } void event_location_tx() { float temperature = getTemperature(); float voltage = getBatteryV(); int selfTestResult = selfTest(); int connectionStartTime = RET_RTCunixtime; if (RET_receivedNewSettings) {RET_receivedNewSettings = false; addToExceptionString("SR"); } if (modem.on(RET_force2G)) { char locString[70]; int gpsStartTime = RET_RTCunixtime; memcpy(locString, modem.getLocation(RET_setting_location_accuracy, RET_setting_location_timeout), 70); int timetaken_gps = (RET_RTCunixtime - gpsStartTime); //SEND DATA if (modem.registerOnNetwork(DEFAULT_CONNECTION_ATTEMPTS,(RET_setting_connection_timeout*1000))) { int timetaken_total = (RET_RTCunixtime - GLOBAL_wakeTime) + 10; //add 10 for ussd response time. int timetaken_connection = (RET_RTCunixtime - connectionStartTime); //Check if we should wait for settings back bool getSettings = true; //work out if we need to get settings back if ( ((RET_RTCunixtime - RET_SettingsGotAt)/3600) < RET_setting_minimumupdate_hrs ) { getSettings = false; timetaken_total -= 10;} //remove the extra 10 seconds from times char bytesToSend[160]; snprintf(bytesToSend,sizeof(bytesToSend),"(%s,a:loc,f:%d,t:%.1f,v:%.2f,z:LOC-%s,e:%d,y:%d,x:%d,c:1,s:%d%s)\0",GLOBAL_defaultApi,FW_VERSION,temperature,voltage,GLOBAL_exceptionString,timetaken_total,timetaken_connection,timetaken_gps,getSettings,locString); char result[180]; snprintf(result,sizeof(result),"%s",modem.USSDmessage(bytesToSend, getSettings, 2, GLOBAL_defaultApi)); if (result != "err") { if (getSettings) { if (saveSettings(result) == false){sendErrorLog("ERR:LOC-IR");} } } else { sendErrorLog("ERR:LOC-NR"); } } else { modem.off(true); if(GLOBAL_debugLED) LED1errorCode(3,10); //ERROR 3 } } else { modem.off(true); if(GLOBAL_debugLED) LED1errorCode(2,10); //ERROR 2 } modem.off(true); //RESETS RET_motionTriggeredInLocTXInterval = false; setEventTime_Location(); } void event_activity_tx(uint8_t activity_mode) { //SEND ACTIVITY DATA //check we have something to send... if (RET_motionTotalActivityHoursSincePost > 0.0 && activity_mode > 0) { float temperature = getTemperature(); float voltage = getBatteryV(); if (modem.on(RET_force2G)) { //SEND DATA if (modem.registerOnNetwork(DEFAULT_CONNECTION_ATTEMPTS,(RET_setting_connection_timeout*1000))) { char bytesToSend[160]; if (activity_mode == 1) { snprintf(bytesToSend,sizeof(bytesToSend),"(%s,a:act,t:%u,r:%.2f,h:%.2f,c:1)\0",GLOBAL_defaultApi,RET_motionFrameStart,RET_motionTotalActivityHoursSincePost,RET_motionTotalActivityHours); } else if (activity_mode == 2) { snprintf(bytesToSend,sizeof(bytesToSend),"(%s,a:act,e:%s,t:%u,r:%.2f,c:1)\0",GLOBAL_defaultApi,RET_activityData,RET_motionFrameStart,RET_motionTotalActivityHoursSincePost); } 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; } } } else { modem.off(true); if(GLOBAL_debugLED) LED1errorCode(3,10); //ERROR 3 } } else { modem.off(true); if(GLOBAL_debugLED) LED1errorCode(2,10); //ERROR 3 } modem.off(true); } //RESETS setEventTime_Activity(); } //------------------------------------------------------------------------------ // STATE ENGINE //------------------------------------------------------------------------------ void mainStateEngine() { switch(RET_state) { case STATE_SETUP : { //need the curlies to avoid "transfer of control bypass init error warning" //check that we havent run setup too recently time_t setupRunAt_delta = (RET_RTCunixtime - RET_SetupRunAt); if (RET_SetupRunAt == 0 || setupRunAt_delta > ONEDAYINSECONDS) { if (event_setup(false)) { // 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 { 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 : { //LOCATION EVENT bool run_location_tx = false; switch (RET_setting_location_mode) { case 1: //INTERVAL POST if(RET_RTCunixtime >= RET_eventTime_location_tx && RET_eventTime_location_tx > 0) { run_location_tx = true; } break; case 2: //INTERVAL POST WITH MOTION CHECK if(RET_RTCunixtime >= RET_eventTime_location_tx && RET_eventTime_location_tx > 0) { if (RET_motionTriggeredInLocTXInterval == true) { run_location_tx = true; } else { if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "Skip TX no mot\n");debug_exe();} } } break; case 3: //POST ON STOP MOTION if (GLOBAL_motionStopFlagTriggered) { run_location_tx = true; GLOBAL_motionStopFlagTriggered = false; } break; } if(RET_RTCunixtime >= RET_eventTime_location_failsafe_tx && RET_eventTime_location_failsafe_tx > 0) { run_location_tx = true; } if (run_location_tx) { event_location_tx(); } //ACTIVITY EVENT bool run_activity_tx = false; if(RET_RTCunixtime >= RET_eventTime_activity_tx && RET_eventTime_activity_tx > 0) { if (RET_setting_activity_mode == 1 && RET_motionTotalActivityHoursSincePost > 0.0) { run_activity_tx = true; } if (RET_setting_activity_mode == 2 && strlen(RET_activityData) > 1) { run_activity_tx = true; } } //If in sendevent mode, check if buffer is close to full, if so send if (RET_setting_activity_mode == 2 && strlen(RET_activityData) > (ACTIVITY_BUFFERSIZE-20)) { run_activity_tx = true; } if (run_activity_tx) { event_activity_tx(RET_setting_activity_mode); } break; } case STATE_DORMANT : { if (RET_RTCunixtime >= RET_eventTime_wakeFromDormant) { if (RET_haveSettings) { setState(STATE_NORMAL); } else { setState(STATE_SETUP); } } 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); 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); if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"BUTTON PRESS 2\n");debug_exe();} LED1blink(3,300); LED1on(0); event_setup(true); LED1off(); break; } case STATE_BUTTONPRESS3 : { setState(STATE_NORMAL); if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"BUTTON PRESS 3\n");debug_exe();} LED1blink(5,300); LED1on(0); event_location_tx(); LED1off(); break; } case STATE_BUTTONHOLD : { 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 + THREEDAYSINSECONDS); setState(STATE_DORMANT); 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 { if (RET_haveSettings) { setState(STATE_NORMAL); } else { setState(STATE_SETUP); } if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"TURNING ON\n");debug_exe();} LED1blink(20,100); } break; } case STATE_SCORCHEDEARTH : { LED1blink(40,50); if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"SCORCHED EARTH - RESETTING");debug_exe();} setState(STATE_SETUP); //this wont be used but just incase to kick it out of this state read_app_data_from_flash(&app_data); app_data.current_firmware_version = 0; app_data.target_firmware_version = 0; write_app_data_to_flash(&app_data); system_reset(); break; } default : { setState(STATE_SETUP); } } } //------------------------------------------------------------------------------ // MAIN //------------------------------------------------------------------------------ int main() { //INIT watchdog.configure(240.0); //4 mins LED1off(); modem.off(false); RTCticker.attach(&RTCtick, 1.0); button.fall(&buttonPress); button.rise(&buttonRelease); read_app_data_from_flash(&app_data); dumpSettings(); //CHECK IF THIS IS RESET //0x00000008 == lock up //0x00000004 == soft reset //0x00000002 == watchdog //0x00000001 == button/hardreset if (NRF_POWER->RESETREAS != 0xffffffff) { RET_coldBoot = 1; switch(NRF_POWER->RESETREAS) { case 0x00000001 : if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"RR:PI\n");debug_exe();} break; case 0x00000002 : if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"RR:WD\n");debug_exe();} break; case 0x00000004 : if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"RR:SW\n");debug_exe();} break; case 0x00000008 : if(DEBUG_ON){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"RR:LU\n");debug_exe();} break; } NRF_POWER->RESETREAS = 0xffffffff; } else { //if its not one of these reasons then its a power-on or a brown-out if(get_flag(&app_data, app_execution_flag) == false) { //THIS is a unexpected reset / brownout??? //THIS NEEDS TESTING } } //CHECK FOR FIRST BOOT if (RET_coldBoot == 1) { setDefaults(); //check battery float voltage = getBatteryV(); if (voltage > 2.5f) { //battery ok LED1errorCode(6,2); } else { //battery low LED1errorCode(10,2); } addToExceptionString("FR"); mainthread.wait(2000); } //MAIN LOOP while(true) { //WATCHDOG watchdogKick(); RET_asleep = false; //INIT resetGlobals(); healthCheck(); //this must be after resetGlobals GLOBAL_wakeTime = RET_RTCunixtime; //check and log motion if (RET_state == STATE_NORMAL) { checkMotion(); } //MAIN LOGIC if(DEBUG_ON){ if (RET_state != 99) { debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "F:%d, S:%d, SET:%d, MF:%d, MS:%d, MTX:%d, %u, L:%u, LFS:%u, A:%u", FW_VERSION, RET_state, RET_haveSettings, RET_motionTriggeredinFrame, RET_motionState, RET_motionTriggeredInLocTXInterval, RET_RTCunixtime,RET_eventTime_location_tx,RET_eventTime_location_failsafe_tx,RET_eventTime_activity_tx);debug_exe(); debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "ACT M:%d, HsP:%.2f, Ht:%.2f D:%s\n",RET_setting_activity_mode,RET_motionTotalActivityHoursSincePost,RET_motionTotalActivityHours,RET_activityData);debug_exe(); } else { debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "F:%d, S:%d, WAKE@:%u\n", FW_VERSION, RET_state, RET_eventTime_wakeFromDormant);debug_exe(); } } /* if (modem.on(RET_force2G)) { if (modem.registerOnNetwork(DEFAULT_CONNECTION_ATTEMPTS,(RET_setting_connection_timeout*1000))) { modem.USSDsend("(b:gps2,a:act,e:1.7!0.15!,t:1547937626,r:0.13,c:1)\0",2); } } */ //STATE ENGINE mainStateEngine(); //LOG FIRST RUN - BOOTLOADER COMMS if (RET_coldBoot) { recordFirmwareAsValid(); RET_coldBoot = 0; } //PRE-SLEEP ACTIONS LED1off(); modem.off(false); RET_motionTriggeredinFrame = false; if (GLOBAL_needToConfigureLis3dh) { lis3dh_configureForSleep(RET_setting_motion_g,RET_setting_impact_g); } nrf_configureGPIOForSleep(); NRFuart_uninit(); watchdogKick(); //SLEEP RET_asleep = true; mainthread.wait(DEFAULT_SLEEP_FRAME); } }