Pathfindr / Mbed OS mbed-os-PF-UWBBEACON_v1_dev

Dependencies:   aconno_I2C Lis2dh12 WatchdogTimer

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 #include "main.h"
00002 // MUST USE MBED 5.10.4   2fd0c5cfbd
00003 
00004 /*
00005 PRE DEPLOYMENT CHECKS!!
00006 • Ensure APP DATA address is correct
00007 */
00008 
00009 //------------------------------------------------------------------------------
00010 //FUNCTION PROTOTYPES - NEED TO ADD ALL OF THE MISSING ONES
00011 //------------------------------------------------------------------------------ 
00012 //should really add these - will just add as and when needed for now
00013 void bleShutdown();
00014 
00015 //------------------------------------------------------------------------------
00016 // VARS
00017 //------------------------------------------------------------------------------
00018 char             RET_pf_identifier[6];
00019 time_t           RET_RTCunixtime                                    = 0;
00020 bool             RET_debug                                          = true;
00021 time_t           RET_debug_offat                                    = 0;
00022 char             GLOBAL_debug_buffer[DEBUG_BUFFERSIZE];
00023 
00024 //SENSORS
00025 float            RET_voltage                                        = 0.0;
00026 float            RET_temperature                                    = 0.0;
00027 float            RET_humidity                                       = 0.0;
00028 bool             RET_motionState                                    = false;
00029 int8_t           RET_accX                                           = 0;
00030 int8_t           RET_accY                                           = 0;
00031 int8_t           RET_accZ                                           = 0;
00032 time_t           RET_motionLastDetected                             = 0;
00033 time_t           RET_InMotionSeconds                                = 0;
00034 time_t           RET_NoMotionSeconds                                = 0;
00035 bool             RET_impactState                                    = false;
00036 
00037 //STATE
00038 bool             RET_busy                                           = false;
00039 bool             RET_asleep                                         = false;
00040 bool             RET_coldBoot                                       = true;
00041 
00042 //BUTTON
00043 bool             RET_buttonPressed                                  = false;
00044 uint8_t          RET_buttonPressCount                               = 0;
00045 time_t           RET_buttonPressTime                                = 0;
00046 time_t           RET_buttonReleaseTime                              = 0;
00047 time_t           RET_buttonReleaseTime_prev                         = 0;
00048 time_t           RET_buttonHoldTime                                 = 0;
00049 
00050 //EVENTS
00051 bool             RET_haveEventsToRun                                = false;
00052 
00053 bool             EVENT_buttonPress                                  = false;
00054 
00055 bool             EVENT_battery                                      = false;
00056 time_t           EVENT_battery_interval                             = DEFAULT_INTERVAL_BATTERY;
00057 time_t           EVENT_battery_time                                 = 0;
00058 
00059 bool             EVENT_motionClear                                  = false;
00060 time_t           EVENT_motionClear_interval                         = DEFAULT_INTERVAL_MOTIONCLEAR;
00061 time_t           EVENT_motionClear_time                             = 0;
00062 
00063 bool             EVENT_buttonClear                                  = false;
00064 time_t           EVENT_buttonClear_interval                         = DEFAULT_INTERVAL_BUTTONCLEAR;
00065 time_t           EVENT_buttonClear_time                             = 0;
00066 
00067 bool             EVENT_temperature                                  = false;
00068 time_t           EVENT_temperature_interval                         = DEFAULT_INTERVAL_TEMPERATURE;
00069 time_t           EVENT_temperature_time                             = 0;
00070 
00071 bool             EVENT_humidity                                     = false;
00072 time_t           EVENT_humidity_interval                            = DEFAULT_INTERVAL_HUMIDITY;
00073 time_t           EVENT_humidity_time                                = 0;
00074 
00075 bool             EVENT_settingsScan                                 = false;
00076 time_t           EVENT_settingsScan_interval                        = DEFAULT_INTERVAL_SETTINGSSCAN;
00077 time_t           EVENT_settingsScan_time                            = 0;
00078 
00079 bool             EVENT_uwbScan                                      = false;
00080 time_t           EVENT_uwbScan_interval                             = 60;
00081 time_t           EVENT_uwbScan_time                                 = 0;
00082 
00083 bool             EVENT_resetACCInt                                  = false;
00084 time_t           EVENT_resetACCInt_interval                         = DEFAULT_INTERVAL_RESETACCINT;
00085 time_t           EVENT_resetACCInt_time                             = 0;
00086 
00087 
00088 //BLE
00089 uint16_t         RET_setting_beacon_interval_ms                     = DEFAULT_BEACON_INTERVAL_MS;
00090 uint16_t         RET_setting_beacon_interval_ms_active              = DEFAULT_BEACON_INTERVAL_MS;
00091 bool             RET_bleBroadcasting                                = false;
00092 uint8_t          RET_bleAdv_flags                                   = 0;
00093 bool             RET_UWBdetector_present                            = true; //BEN should be false
00094 bool             RET_BLEpacketUpdate                                = false;
00095 bool             RET_settingsReceived                               = false;
00096 const uint8_t    bleAdv_motion_flag                                 = 0x01; //motion detected
00097 const uint8_t    bleAdv_impact_flag                                 = 0x02; //impact detected
00098 const uint8_t    bleAdv_button_pressed_flag                         = 0x08; //button press detected
00099 const uint8_t    bleAdv_gap_connected_flag                          = 0x40; //device is connected
00100 #pragma pack(1)
00101 struct bleData_t {
00102     uint16_t applicationSpecificId;
00103     uint8_t firmware;
00104     uint8_t flags;
00105     uint16_t voltage;
00106     uint8_t buttonpresses;
00107     int16_t temperature;
00108     uint8_t humidity;
00109     uint8_t lux;
00110     int8_t accel_x;
00111     int8_t accel_y;
00112     int8_t accel_z;
00113 };
00114 #pragma pack()
00115     
00116 //------------------------------------------------------------------------------
00117 //GPIO
00118 //------------------------------------------------------------------------------ 
00119 InterruptIn button(PN_IN_BUTTON);
00120 InterruptIn accInt1(PN_ACC_INT1);
00121 //InterruptIn DW_irq(DW1000_IRQ);
00122 
00123 //------------------------------------------------------------------------------
00124 //PERIPHERALS
00125 //------------------------------------------------------------------------------ 
00126 BLE myble;
00127 WatchdogTimer watchdog;
00128 LowPowerTicker RTCticker;
00129 LowPowerTimer LPtimer;
00130 
00131 I2C i2c(PN_I2C_SDA,PN_I2C_SCL);
00132 SPI spi(PN_SPI_MOSI,PN_SPI_MISO,PN_SPI_CLK);
00133 Lis2dh12 acc(&i2c, 0x32);
00134 
00135 //------------------------------------------------------------------------------
00136 //SEMAPHORES
00137 //------------------------------------------------------------------------------ 
00138 Semaphore mainthread;
00139 
00140 //------------------------------------------------------------------------------
00141 // LOW LEVEL FUNCS
00142 //------------------------------------------------------------------------------
00143 void watchdogKick() {
00144     watchdog.kick();
00145 }
00146 void set_8bit_flag(uint8_t& flags, uint8_t flag) {
00147     flags |= flag;
00148 }
00149 bool get_8bit_flag(uint8_t& flags, uint8_t flag) {
00150     bool result = (flags & flag);
00151     return result;
00152 }
00153 void clr_8bit_flag(uint8_t& flags, uint8_t flag) {
00154     flags &= ~flag;
00155 }
00156 void nrf_configureForSleep(){
00157     //Disable SPI pins to reduce power
00158     //nrf_gpio_cfg_input(PN_SPI_MOSI, NRF_GPIO_PIN_NOPULL);  //Don't need this one
00159     nrf_gpio_cfg_input(PN_SPI_MISO, NRF_GPIO_PIN_NOPULL);
00160     
00161     //TWI0
00162     NRF_TWI0->ENABLE = TWI_ENABLE_ENABLE_Disabled << TWI_ENABLE_ENABLE_Pos;
00163     *(volatile uint32_t *)0x40003FFC = 0;
00164     *(volatile uint32_t *)0x40003FFC;
00165     *(volatile uint32_t *)0x40003FFC = 1;
00166     //TWI1
00167     NRF_TWI1->ENABLE=TWI_ENABLE_ENABLE_Disabled << TWI_ENABLE_ENABLE_Pos;
00168     *(volatile uint32_t *)0x40004FFC = 0;
00169     *(volatile uint32_t *)0x40004FFC;
00170     *(volatile uint32_t *)0x40004FFC = 1;
00171 }
00172 
00173 void recordFirmwareAsValid() {
00174     bleShutdown();
00175     read_app_data_from_flash(&app_data);
00176     bool write_app_data_to_flash_execute = false;
00177     if(get_flag(&app_data, app_execution_flag) == true) {
00178         clr_flag(&app_data, app_execution_flag);
00179         clr_flag(&app_data, first_run_flag);
00180         write_app_data_to_flash_execute = true;
00181     }
00182     if(app_data.current_firmware_version != FW_VERSION) {
00183         app_data.current_firmware_version = FW_VERSION;
00184         app_data.target_firmware_version = FW_VERSION;
00185         write_app_data_to_flash_execute = true;
00186     }
00187     if (write_app_data_to_flash_execute) {
00188         write_app_data_to_flash(&app_data);
00189         //read back to check
00190         ThisThread::sleep_for(200); //need this delay
00191         read_app_data_from_flash(&app_data);
00192         if (app_data.current_firmware_version == FW_VERSION) {
00193             debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "OK");debug_exe();
00194         } else {
00195             debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "FAIL - IS BLE SHUTDOWN?");debug_exe();
00196         }
00197     }
00198 }
00199 void updateBatteryV() {
00200     NRF52_SAADC batteryIn;
00201     batteryIn.addChannel (9); // vdd for battery
00202     batteryIn.calibrate();
00203     //get initial reading, first reading is always low
00204     batteryIn.updateData(); batteryIn.getData ()[0];
00205     float voltage_accumulator = 0.0;
00206     uint8_t readings = 0;
00207     for (uint8_t i = 1; i <= 50; i++) { // need to get it 2 times to get accurate data, first one is always low for some reason
00208         batteryIn.updateData();
00209         voltage_accumulator += (batteryIn.getData ()[0])*(1.0/1024.0)*3.60;
00210         readings ++;
00211     }
00212     RET_voltage = (voltage_accumulator / (float)readings);
00213 }
00214 
00215 
00216 
00217 //------------------------------------------------------------------------------
00218 // INTERUPTS
00219 //------------------------------------------------------------------------------ 
00220 void buttonPress() {
00221     RET_buttonPressTime = LPtimer.read_ms();
00222 }
00223 void buttonRelease() {
00224     //debounce catch
00225     RET_buttonReleaseTime = LPtimer.read_ms();
00226     if ((RET_buttonReleaseTime - RET_buttonReleaseTime_prev) > 100) { 
00227         RET_buttonPressCount ++;
00228         RET_buttonHoldTime = (RET_buttonReleaseTime - RET_buttonPressTime);
00229         //temporarily enable debugging
00230         RET_debug = true;
00231         RET_debug_offat = (RET_RTCunixtime + 3600); //debug on for 1hr
00232         EVENT_buttonPress = true;
00233         mainthread.release();
00234     }
00235     RET_buttonReleaseTime_prev = RET_buttonReleaseTime;
00236 }
00237 
00238 void accInt1ISR() {
00239     //led2 = !led2;
00240     RET_motionLastDetected = RET_RTCunixtime;
00241 }
00242 
00243 //------------------------------------------------------------------------------
00244 // RTC TICKER
00245 //------------------------------------------------------------------------------
00246 bool RET_flash_busy = false;
00247 void RTCtick() {
00248     //YOU MUST NOT CALL ANY OTHER FUNCTIONS OR DEBUG FROM INSIDE HERE!!! OR IT LOCKS UP THE DEVICE, just change vars & comparisons etc
00249     RET_RTCunixtime += 1;
00250     
00251     //CHECK FOR EVENTS
00252     if (RET_haveEventsToRun == false) {
00253         if (EVENT_motionClear_time > 0 && RET_RTCunixtime >= EVENT_motionClear_time) {
00254             RET_haveEventsToRun = true; EVENT_motionClear = true;
00255         }
00256         if (EVENT_buttonClear_time > 0 && RET_RTCunixtime >= EVENT_buttonClear_time) {
00257             RET_haveEventsToRun = true; EVENT_buttonClear = true;
00258         }
00259         if (EVENT_battery_time > 0 && RET_RTCunixtime >= EVENT_battery_time) {
00260             RET_haveEventsToRun = true; EVENT_battery = true;
00261         }
00262         if (EVENT_temperature_time > 0 && RET_RTCunixtime >= EVENT_temperature_time) {
00263             RET_haveEventsToRun = true; EVENT_temperature = true;
00264         }
00265         if (EVENT_humidity_time > 0 && RET_RTCunixtime >= EVENT_humidity_time) {
00266             RET_haveEventsToRun = true; EVENT_humidity = true;
00267         }
00268         if (EVENT_settingsScan_time > 0 && RET_RTCunixtime >= EVENT_settingsScan_time) {
00269             RET_haveEventsToRun = true; EVENT_settingsScan = true;
00270         }
00271         if (EVENT_uwbScan_time > 0 && RET_RTCunixtime >= EVENT_uwbScan_time) {
00272             RET_haveEventsToRun = true; EVENT_uwbScan = true;
00273         }
00274         if (EVENT_resetACCInt_time > 0 && RET_RTCunixtime >= EVENT_resetACCInt_time) {
00275             RET_haveEventsToRun = true; EVENT_resetACCInt = true;
00276         }
00277     }
00278     
00279     //CHECK FOR MOTION OPT 
00280     //Had motion in last 5 seconds?
00281     if (RET_motionLastDetected > 0 && (RET_RTCunixtime-RET_motionLastDetected) < 5) {
00282         EVENT_motionClear_time = (RET_RTCunixtime + EVENT_motionClear_interval);
00283         if (RET_motionState == 0) {
00284             RET_motionState = 1;
00285             RET_BLEpacketUpdate = true;
00286             RET_haveEventsToRun = true;
00287         }
00288     }
00289     led1 = !RET_motionState;
00290     
00291     //WAKE UP MAIN LOOP AND RUN ANY EVENTS
00292     if (RET_haveEventsToRun && RET_asleep) {
00293         mainthread.release();
00294     }
00295 }
00296 
00297 
00298 //------------------------------------------------------------------------------
00299 // BLE FUNCS
00300 //------------------------------------------------------------------------------
00301 void bleBuildData(bleData_t &bleData)
00302 {
00303     bleData.applicationSpecificId = BLE_SERVICEID_UWBBEACON;
00304     bleData.firmware = FW_VERSION;
00305     //set flags
00306     if (RET_motionState) {
00307         set_8bit_flag(RET_bleAdv_flags, bleAdv_motion_flag);
00308     } else {
00309         clr_8bit_flag(RET_bleAdv_flags, bleAdv_motion_flag);
00310     }
00311     
00312     if (RET_impactState) {
00313         set_8bit_flag(RET_bleAdv_flags, bleAdv_impact_flag);
00314     } else {
00315         clr_8bit_flag(RET_bleAdv_flags, bleAdv_impact_flag);
00316     }
00317     
00318     if(RET_buttonPressed) {
00319         set_8bit_flag(RET_bleAdv_flags, bleAdv_button_pressed_flag);
00320     } else {
00321         clr_8bit_flag(RET_bleAdv_flags, bleAdv_button_pressed_flag);
00322     }
00323     
00324     bleData.flags = RET_bleAdv_flags;
00325     bleData.voltage = RET_voltage;
00326     bleData.buttonpresses = RET_buttonPressCount;
00327     bleData.temperature = RET_temperature;
00328     bleData.humidity = 0xFF;
00329     bleData.lux = 0xFF;
00330     bleData.accel_x = 0xFF;
00331     bleData.accel_y = 0xFF;
00332     bleData.accel_z = 0xFF;
00333 }
00334 void bleUpdateAndAdvertise(void) 
00335 {
00336     bleData_t bleData;
00337     bleBuildData(bleData);
00338     myble.gap().stopAdvertising();
00339     myble.gap().setTxPower(DEFAULT_BEACON_POWER); // set tx power,valid values are -40, -20, -16, -12, -8, -4, 0, 4
00340     myble.gap().accumulateAdvertisingPayloadTxPower(DEFAULT_BEACON_POWER); // (accepted values are -40, -30, -20, -16, -12, -8, -4, 0, and 4 dBm)
00341     myble.gap().setAdvertisingInterval(RET_setting_beacon_interval_ms_active);
00342     myble.gap().updateAdvertisingPayload(GapAdvertisingData::SERVICE_DATA, (uint8_t *)&bleData, sizeof(bleData_t));
00343     //myble.gap().updateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, (uint8_t *)&bleData, sizeof(bleData_t));
00344     myble.gap().startAdvertising();
00345     RET_bleBroadcasting = true;
00346     RET_BLEpacketUpdate = false;
00347 }
00348 void bleSetupAdvertising(BLE::InitializationCompleteCallbackContext *params)
00349 {
00350     if (RET_pf_identifier[0] != 0x00 && RET_pf_identifier[1] != 0x00 && RET_pf_identifier[2] != 0x00) {
00351         bleData_t bleData;
00352         bleBuildData(bleData);
00353         char localname[6];
00354         memcpy(localname,RET_pf_identifier,6);
00355         myble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE );
00356         myble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)localname, sizeof(localname));
00357         myble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SERVICE_DATA, (uint8_t *)&bleData, sizeof(bleData_t));
00358         ////myble.gap().accumulateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, (uint8_t *)&bleData, sizeof(bleData_t));
00359         myble.gap().setAdvertisingType(GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED);
00360     }
00361 }
00362 void bleStopAdvertising(void)
00363 {
00364     myble.gap().stopAdvertising();
00365     RET_bleBroadcasting = false;
00366     if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "BLE Adv Stop");debug_exe();}
00367 }
00368 void bleAdvertisementCallback(const Gap::AdvertisementCallbackParams_t *params) {
00369     struct AdvertisingData_t {
00370         uint8_t                        length;
00371         GapAdvertisingData::DataType_t dataType;
00372         uint8_t                        data[0];
00373     } PACKED;
00374     struct bleData_t {
00375         uint16_t applicationSpecificId;
00376     } PACKED;
00377     
00378     //Search for the manufacturer specific data with matching application-ID
00379     AdvertisingData_t *pAdvData;
00380     for (size_t index = 0; index < params->advertisingDataLen; index += (pAdvData->length + 1)) {
00381         pAdvData = (AdvertisingData_t *)&params->advertisingData[index];
00382         const bleData_t *pbleData = (const bleData_t *)pAdvData->data;
00383         
00384         //BLE TYPE SWITCH
00385         switch(pbleData->applicationSpecificId) {
00386             case BLE_SERVICEID_PFDETECTOR2 :
00387             {
00388                 char ble_advdata[100];
00389                 snprintf(ble_advdata, sizeof(ble_advdata), "%02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x %02x",
00390                 params->advertisingData[0],
00391                 params->advertisingData[1],
00392                 params->advertisingData[2],
00393                 params->advertisingData[3],
00394                 params->advertisingData[4],
00395                 params->advertisingData[5],
00396                 params->advertisingData[6],
00397                 params->advertisingData[7],
00398                 params->advertisingData[8],
00399                 params->advertisingData[9],
00400                 params->advertisingData[10],
00401                 params->advertisingData[11],
00402                 params->advertisingData[12],
00403                 params->advertisingData[13],
00404                 params->advertisingData[14],
00405                 params->advertisingData[15],
00406                 params->advertisingData[16],
00407                 params->advertisingData[17],
00408                 params->advertisingData[18],
00409                 params->advertisingData[19],
00410                 params->advertisingData[20]);
00411                 //if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), " Mac: [%02x%02x%02x%02x%02x%02x], rssi: %d, AType: %u, Id: %s",params->peerAddr[5], params->peerAddr[4], params->peerAddr[3], params->peerAddr[2], params->peerAddr[1], params->peerAddr[0],params->rssi, pAdvData->dataType, ble_advdata);debug_exe();}
00412                 //if(RET_debug){debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "Detector @rssi: %d",params->rssi);debug_exe();}
00413                 if (params->rssi >= -75) {
00414                     
00415                 }
00416                 RET_settingsReceived = true;
00417                 break;
00418             }
00419         }
00420     }
00421 }
00422 void bleConfigureScan(void)
00423 {
00424     myble.gap().setScanParams(200,200); //scan interval //scan window
00425     myble.gap().startScan(bleAdvertisementCallback);
00426 }
00427 void bleStopScan(void)
00428 {
00429     myble.gap().stopScan();
00430 }
00431 void bleShutdown(void)
00432 {
00433     bleStopScan();
00434     bleStopAdvertising();
00435     myble.shutdown();
00436 }
00437 
00438 //------------------------------------------------------------------------------
00439 // FIRST RUN
00440 //------------------------------------------------------------------------------ 
00441 void firstRun() {
00442     //Set Serial Number
00443     RET_pf_identifier[0] = 'U';
00444     RET_pf_identifier[1] = 'W';
00445     RET_pf_identifier[2] = 'B';
00446     RET_pf_identifier[3] = '0';
00447     RET_pf_identifier[4] = '1';
00448     RET_pf_identifier[5] = 0x00;
00449     
00450     //GET INITITAL SENSORS
00451     updateBatteryV();
00452     //updateTemperature
00453     //updateHumidity
00454 
00455     //SET EVENT TIMES
00456     EVENT_battery_time = (RET_RTCunixtime + EVENT_battery_interval);
00457     EVENT_temperature_time = (RET_RTCunixtime + EVENT_temperature_interval);
00458     EVENT_humidity_time = (RET_RTCunixtime + EVENT_humidity_interval);
00459     EVENT_settingsScan_time = (RET_RTCunixtime + EVENT_settingsScan_interval);
00460     EVENT_uwbScan_time = (RET_RTCunixtime + EVENT_uwbScan_interval);
00461 }
00462 
00463 //------------------------------------------------------------------------------
00464 // BLE SETTINGS SCAN
00465 //------------------------------------------------------------------------------ 
00466 void settingsScan() {
00467     //LED1on(0);
00468     bleStopAdvertising();
00469     LowPowerTimer bleScan_t;
00470     bleScan_t.start();
00471     RET_settingsReceived = false;
00472     uint32_t bleScan_startmillis = bleScan_t.read_ms(); uint32_t bleScan_runtime = 0;
00473     if (!myble.hasInitialized()) {
00474         myble.init();
00475         while (!myble.hasInitialized() && bleScan_runtime < 1000) { 
00476             bleScan_runtime = (bleScan_t.read_ms() - bleScan_startmillis);
00477         }
00478     }
00479     if (myble.hasInitialized()) {
00480         bleConfigureScan();
00481         bleScan_startmillis = bleScan_t.read_ms();
00482         while (bleScan_runtime < DEFAULT_SETTINGSSCANTIME_MS && RET_settingsReceived == false) {
00483             bleScan_runtime = (bleScan_t.read_ms() - bleScan_startmillis);
00484             myble.waitForEvent(); // low power wait for event
00485         }
00486     }
00487     bleScan_t.stop();
00488     myble.gap().stopScan();
00489     //LED1off();
00490 }
00491 
00492 //------------------------------------------------------------------------------
00493 // UWB SCAN
00494 //------------------------------------------------------------------------------ 
00495 struct __attribute__((packed, aligned(1))) DistancesFrame {
00496         uint8_t source;
00497         uint8_t destination;
00498         uint8_t type;
00499         float dist[4];
00500     };
00501     
00502 DW1000 dw(PN_SPI_MOSI, PN_SPI_MISO, PN_SPI_CLK, DW1000_CS, DW1000_IRQ, DW1000_RST);   // Device driver instanceSPI pins: (MOSI, MISO, SCLK, CS, IRQ)
00503 //DW1000 dw(&spi,DW_irq,DW1000_CS,DW1000_RST);
00504 MM2WayRanging node(dw);
00505 
00506 void uwbScan() {
00507     
00508 }
00509 
00510 //------------------------------------------------------------------------------
00511 // ACC
00512 //------------------------------------------------------------------------------ 
00513 void acc_configForMotionInt() {
00514     acc.setMode(LOW_POWER);
00515     acc.enableAxes(X_axis);
00516     acc.enableAxes(Y_axis);
00517     acc.enableAxes(Z_axis);    
00518     acc.setODR(ODR_1Hz);
00519     acc.setScale(_8g);
00520     acc.int1Setup(0b01000000);       // IntActivity 1 driven to INT1 pad
00521     //acc.setCTRL_REG2(0b11001011);  //High pass filter active
00522     acc.setCTRL_REG2(0b00000000);    //High pass filter off
00523     acc.int1Latch(0b00000000);       //Dont latch
00524     acc.int1Threshold(7);
00525     acc.int1Duration(0x00);  
00526     acc.int1Config(0b01111111);     // INT2_CFG Enable XHigh, YHigh and ZHigh, triggers INT1 on any motion
00527     acc.clearIntFlag(); //reset int1 
00528 }
00529 
00530 void acc_updateOrientation() {
00531     //Divide by 16 to get range of +- 16 on each axis
00532     RET_accX = (acc.readXAxis() / 16);
00533     RET_accY = (acc.readYAxis() / 16);
00534     RET_accZ = (acc.readZAxis() / 16);
00535 }
00536 
00537 //------------------------------------------------------------------------------
00538 // STATE ENGINE
00539 //------------------------------------------------------------------------------ 
00540 void mainStateEngine() {
00541     if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "MainStateEngine");debug_exe();}
00542     
00543     if (EVENT_buttonPress) {
00544         if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_ButtonPress");debug_exe();}
00545         EVENT_buttonClear_time = (RET_RTCunixtime + EVENT_buttonClear_interval);
00546         RET_setting_beacon_interval_ms_active = DEFAULT_BEACON_INTERVAL_FAST_MS;
00547         RET_BLEpacketUpdate = true;
00548         EVENT_buttonPress = false;
00549     }
00550     
00551     if (EVENT_motionClear) {
00552         if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_MotionClear");debug_exe();}
00553         EVENT_motionClear_time = 0;
00554         EVENT_motionClear = false;
00555         RET_motionState = false;
00556         RET_impactState = false;
00557         acc_updateOrientation(); //update orientation data
00558         RET_BLEpacketUpdate = true;
00559     }
00560     
00561     if (EVENT_buttonClear) {
00562         if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_ButtonClear");debug_exe();}
00563         EVENT_buttonClear_time = 0;
00564         EVENT_buttonClear = false;
00565         RET_buttonPressed = false;
00566         RET_buttonPressCount = 0;
00567         RET_setting_beacon_interval_ms_active = RET_setting_beacon_interval_ms; //reset back to normal broadcast rate
00568         RET_BLEpacketUpdate = true;
00569     }
00570     
00571     if (EVENT_battery) {
00572         if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_Battery");debug_exe();}
00573         EVENT_battery_time = (RET_RTCunixtime + EVENT_battery_interval);
00574         EVENT_battery = false;
00575         updateBatteryV();
00576         RET_BLEpacketUpdate = true;
00577     }
00578     
00579     if (EVENT_temperature) {
00580         if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_Temperature");debug_exe();}
00581         EVENT_temperature_time = (RET_RTCunixtime + EVENT_temperature_interval);
00582         EVENT_temperature = false;
00583         //get temperature TODO - only update ble if different to last
00584         RET_BLEpacketUpdate = true;
00585     }
00586     
00587     if (EVENT_humidity) {
00588         if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_Humidity");debug_exe();}
00589         EVENT_humidity_time = (RET_RTCunixtime + EVENT_humidity_interval);
00590         EVENT_humidity = false;
00591         //get humidity TODO - only update ble if different to last
00592         RET_BLEpacketUpdate = true;
00593     }
00594     
00595     if (EVENT_settingsScan) {
00596         if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_SettingsScan");debug_exe();}
00597         EVENT_settingsScan_time = (RET_RTCunixtime + EVENT_settingsScan_interval);
00598         EVENT_settingsScan = false;
00599         settingsScan();
00600     }
00601     
00602     if (EVENT_uwbScan) {
00603         if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_uwbScan");debug_exe();}
00604         EVENT_uwbScan_time = (RET_RTCunixtime + EVENT_uwbScan_interval);
00605         EVENT_uwbScan = false;
00606     }
00607     
00608     /*if (EVENT_resetACCInt) {
00609         if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "EVENT_resetACCInt1");debug_exe();}
00610         EVENT_resetACCInt_time = 0;
00611         EVENT_resetACCInt = false;
00612         acc.clearIntFlag();
00613     }*/
00614         
00615     //BLE START OR UPDATE
00616     if (RET_bleBroadcasting == false) {
00617         myble.init(bleSetupAdvertising);
00618         if (myble.hasInitialized()) {
00619             if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "BLE Start");debug_exe();}
00620             bleUpdateAndAdvertise();
00621         }
00622     }
00623     if (RET_BLEpacketUpdate == true) {
00624         if(RET_debug) {debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer), "BLE Update only");debug_exe();}
00625         bleUpdateAndAdvertise(); //this function also sets RET_BLEpacketUpdate = false
00626     }
00627     
00628     //END
00629     RET_haveEventsToRun = false;
00630 }
00631 
00632 
00633 
00634 //------------------------------------------------------------------------------
00635 // MAIN
00636 //------------------------------------------------------------------------------ 
00637 int main() {
00638     //INIT
00639     LED1off();
00640     ThisThread::sleep_for(2000); //Initial pause, this is needed for softdevice to init, dont remove!! If we dont have this we get crashes
00641     watchdog.configure(400.0); //6.6 mins //Do not set to less than 4500ms or can cause issues with softdevice
00642     RTCticker.attach(&RTCtick, 1.0);
00643     LPtimer.start();
00644     button.fall(&buttonPress);
00645     button.rise(&buttonRelease);
00646     accInt1.rise(&accInt1ISR);
00647     //read_app_data_from_flash(&app_data);
00648     acc_configForMotionInt();
00649     firstRun();
00650     debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"Ready\n");debug_exe();
00651     
00652     //MAIN LOOP
00653     while(true) {
00654         RET_asleep = false;
00655         //LED2on(30);
00656         
00657         
00658         while(1) {
00659             debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"UWB SCAN START\n");debug_exe();
00660             uwbScan();
00661             debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"UWB SCAN END\n");debug_exe();
00662             nrf_configureForSleep();
00663             ThisThread::sleep_for(1000);
00664         }
00665         
00666         
00667         while(1) {
00668             acc_updateOrientation();
00669             debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"X:%d    Y:%d   D:%d\n",RET_accX,RET_accY,RET_accZ);debug_exe();
00670             ThisThread::sleep_for(20);
00671         }
00672         
00673         //STATE ENGINE
00674         mainStateEngine();
00675         
00676         //LOG FIRST RUN - BOOTLOADER COMMS
00677         if (RET_coldBoot) {
00678             //recordFirmwareAsValid();
00679             RET_coldBoot = 0;
00680         }
00681         
00682         //DEBUGGING OFF TIMER
00683         if(RET_debug){
00684             debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"TIME:%d\n",RET_RTCunixtime);debug_exe();
00685             if (RET_RTCunixtime > RET_debug_offat) {
00686                 debug_prep();snprintf(GLOBAL_debug_buffer, sizeof(GLOBAL_debug_buffer),"DEBUGGING OFF\n");debug_exe();
00687                 RET_debug = false;
00688             }
00689         }
00690                 
00691         //PRE-SLEEP ACTIONS
00692         acc_configForMotionInt();
00693         watchdogKick();
00694         //SLEEP
00695         nrf_configureForSleep();
00696         NRFuart_uninit();
00697         RET_asleep = true;
00698         //LED1off();
00699         mainthread.wait(DEFAULT_SLEEP_FRAME);
00700     }
00701 }