///---------------------------------------------------------------------------- /// Function Break ///---------------------------------------------------------------------------- void PowerOffTimerCallback(void) { debug("Power Off Timer callback: activated.\r\n"); // Handle and finish any processing StopMonitoring(g_triggerRecord.opMode, FINISH_PROCESSING); if (g_timerModeLastRun == YES) { debug("Timer Mode: Ending last session, now disabling...\r\n"); g_unitConfig.timerMode = DISABLED; // Save Unit Config (also covers LCD contrast change case) SaveRecordData(&g_unitConfig, DEFAULT_RECORD, REC_UNIT_CONFIG_TYPE); } else if (g_lcdContrastChanged == YES) { // Save Unit Config here to prevent constant saving on LCD contrast adjustment SaveRecordData(&g_unitConfig, DEFAULT_RECORD, REC_UNIT_CONFIG_TYPE); } OverlayMessage(getLangText(TIMER_MODE_TEXT), getLangText(POWERING_UNIT_OFF_NOW_TEXT), 3 * SOFT_SECS); // Power the unit off debug("Timer mode: Finished for the day, sleep time.\r\n"); PowerUnitOff(SHUTDOWN_UNIT); }
///---------------------------------------------------------------------------- /// Function Break ///---------------------------------------------------------------------------- void HandleUserPowerOffDuringTimerMode(void) { INPUT_MSG_STRUCT mn_msg; uint8 choice; // Simulate a keypress if the user pressed the off key, which doesn't register as a keypess KeypressEventMgr(); MessageBox(getLangText(STATUS_TEXT), getLangText(UNIT_IS_IN_TIMER_MODE_TEXT), MB_OK); choice = MessageBox(getLangText(WARNING_TEXT), getLangText(CANCEL_TIMER_MODE_Q_TEXT), MB_YESNO); // User decided to cancel Timer mode if (choice == MB_FIRST_CHOICE) { g_unitConfig.timerMode = DISABLED; // Disable the Power Off timer ClearSoftTimer(POWER_OFF_TIMER_NUM); // Save Unit Config SaveRecordData(&g_unitConfig, DEFAULT_RECORD, REC_UNIT_CONFIG_TYPE); OverlayMessage(getLangText(STATUS_TEXT), getLangText(TIMER_MODE_DISABLED_TEXT), 2 * SOFT_SECS); } else // User decided to stay in Timer mode { choice = MessageBox(getLangText(STATUS_TEXT), getLangText(POWER_UNIT_OFF_EARLY_Q_TEXT), MB_YESNO); if (choice == MB_FIRST_CHOICE) { MessageBox(getLangText(STATUS_TEXT), getLangText(POWERING_UNIT_OFF_NOW_TEXT), MB_OK); MessageBox(getLangText(STATUS_TEXT), getLangText(PLEASE_PRESS_ENTER_TEXT), MB_OK); // Turn unit off/sleep debug("Timer mode: Shutting down unit early due to user request. Powering off now...\r\n"); PowerUnitOff(SHUTDOWN_UNIT); // Return unnecessary } } SETUP_MENU_MSG(MAIN_MENU); JUMP_TO_ACTIVE_MENU(); }
///---------------------------------------------------------------------------- /// Function Break ///---------------------------------------------------------------------------- void RemoteCmdMessageProcessing() { // Check if there is a potentially fatal error. if (0xBADD != g_msgPool[s_msgReadIndex].overRunCheck) { g_msgPool[s_msgReadIndex].overRunCheck = 0xBADD; OverlayMessage(getLangText(STATUS_TEXT), getLangText(CRAFT_SERIAL_ERROR_TEXT), 0); } // NOTE: Need a different message if the command comming across contains // data or additional info other then the 3 char cmd field. Currently // assuming that only 3 char cmds are being sent. If data or a field is // sent with the incomming command we need to deal with it differently. RemoteCmdMessageHandler(&(g_msgPool[s_msgReadIndex])); memset(g_msgPool[s_msgReadIndex].msg, 0, sizeof(CMD_BUFFER_SIZE)); g_msgPool[s_msgReadIndex].size = 0; g_msgPool[s_msgReadIndex].readPtr = g_msgPool[s_msgReadIndex].msg; g_msgPool[s_msgReadIndex].writePtr = g_msgPool[s_msgReadIndex].msg; g_msgPool[s_msgReadIndex].overRunCheck = 0xBADD; s_msgReadIndex++; if (s_msgReadIndex >= CMD_MSG_POOL_SIZE) { s_msgReadIndex = 0; } // Are any more buffers filled? if (s_msgReadIndex != s_msgWriteIndex) { // Flag to indicate complete message to process raiseSystemEventFlag(CRAFT_PORT_EVENT); } return; }
///---------------------------------------------------------------------------- /// Function Break ///---------------------------------------------------------------------------- void ProcessTimerModeSettings(uint8 mode) { //uint8 dayOfWeek = 0; uint8 startDay = 0; uint8 startHour = 0; uint16 minutesLeft = 0; DATE_TIME_STRUCT currentTime = GetCurrentTime(); uint8 status = ValidateTimerModeSettings(); // Check if the timer mode settings check failed or if the timer mode setting has been disabled if ((status == FAILED) || (g_unitConfig.timerMode == DISABLED)) { g_unitConfig.timerMode = DISABLED; SaveRecordData(&g_unitConfig, DEFAULT_RECORD, REC_UNIT_CONFIG_TYPE); // Disable the Power Off timer in case it's set ClearSoftTimer(POWER_OFF_TIMER_NUM); if (mode == PROMPT) { sprintf((char*)g_spareBuffer, "%s %s", getLangText(TIMER_SETTINGS_INVALID_TEXT), getLangText(TIMER_MODE_DISABLED_TEXT)); MessageBox(getLangText(ERROR_TEXT), (char*)g_spareBuffer, MB_OK); } } else // status == PASSED || status == IN_PROGRESS { // Calculate timer mode active run time in minutes TimerModeActiveMinutes(); // Init start day based on the start date provided by the user startDay = g_unitConfig.timerStartDate.day; // Check if in progress, requiring extra logic to determine alarm settings if (status == IN_PROGRESS) { // Check if the stop time is greater than the start time if ((g_unitConfig.timerStopTime.hour > g_unitConfig.timerStartTime.hour) || ((g_unitConfig.timerStopTime.hour == g_unitConfig.timerStartTime.hour) && (g_unitConfig.timerStopTime.min > g_unitConfig.timerStartTime.min))) { // Advance the start day startDay++; // Check if the start day is beyond the total days in the current month if (startDay > g_monthTable[(uint8)(g_unitConfig.timerStartDate.month)].days) { // Set the start day to the first day of next month startDay = 1; } } } // Check for specialty case hourly mode and in progress, requiring extra logic to determine alarm settings if ((g_unitConfig.timerModeFrequency == TIMER_MODE_HOURLY) && (status == IN_PROGRESS)) { // Check if another hour time slot to run again today if (currentTime.hour != g_unitConfig.timerStopTime.hour) { // Start day remains the same startDay = g_unitConfig.timerStartDate.day; // Check if current hour time slot has not started if (currentTime.min < g_unitConfig.timerStartTime.min) { // Set alarm for the same hour startHour = currentTime.hour; } else { // Set alarm for the next hour startHour = currentTime.hour + 1; // Account for end of day boundary if (startHour > 23) { startHour = 0; // Advance the start day startDay++; // Check if the start day is beyond the total days in the current month if (startDay > g_monthTable[(uint8)(g_unitConfig.timerStartDate.month)].days) { // Set the start day to the first day of next month startDay = 1; } } } EnableExternalRtcAlarm(startDay, startHour, g_unitConfig.timerStartTime.min, 0); } else // This is the last hour time slot to run today, set alarm for next day { // startDay calculated correctly in above previous status == IN_PROGRESS logic EnableExternalRtcAlarm(startDay, g_unitConfig.timerStartTime.hour, g_unitConfig.timerStartTime.min, 0); } } else // All other timer modes { EnableExternalRtcAlarm(startDay, g_unitConfig.timerStartTime.hour, g_unitConfig.timerStartTime.min, 0); } if (status == PASSED) { if (mode == PROMPT) { sprintf((char*)g_spareBuffer, "%s %s", getLangText(TIMER_MODE_NOW_ACTIVE_TEXT), getLangText(PLEASE_POWER_OFF_UNIT_TEXT)); MessageBox(getLangText(STATUS_TEXT), (char*)g_spareBuffer, MB_OK); } // Check if start time is greater than the current time if (((g_unitConfig.timerStartTime.hour * 60) + g_unitConfig.timerStartTime.min) > ((currentTime.hour * 60) + currentTime.min)) { // Take the difference between start time and current time minutesLeft = (uint16)(((g_unitConfig.timerStartTime.hour * 60) + g_unitConfig.timerStartTime.min) - ((currentTime.hour * 60) + currentTime.min)); } else // Current time is after the start time, meaning the start time is the next day { // Take the difference between 24 hours and the current time plus the start time minutesLeft = (uint16)((24 * 60) - ((currentTime.hour * 60) + currentTime.min) + ((g_unitConfig.timerStartTime.hour * 60) + g_unitConfig.timerStartTime.min)); } // Check if the start time is within the next minute if (minutesLeft <= 1) { OverlayMessage(getLangText(WARNING_TEXT), getLangText(POWERING_UNIT_OFF_NOW_TEXT), 2 * SOFT_SECS); // Need to shutdown the unit now, otherwise the start time window will be missed PowerUnitOff(SHUTDOWN_UNIT); // Return unnecessary } else // More than 1 minute left before the start time { // Make sure the unit turns off one minute before the start time if the user forgets to turn the unit off minutesLeft -= 1; // Need to handle state where timer mode is going active but unit hasn't power cycled into timer mode yet g_allowQuickPowerOffForTimerModeSetup = YES; // Set the Power off soft timer to prevent the unit from staying on past the Timer mode start time AssignSoftTimer(POWER_OFF_TIMER_NUM, (uint32)(minutesLeft * 60 * 2), PowerOffTimerCallback); } } else // status == IN_PROGRESS { if (mode == PROMPT) { sprintf((char*)g_spareBuffer, "%s", getLangText(TIMER_MODE_NOW_ACTIVE_TEXT)); MessageBox(getLangText(STATUS_TEXT), (char*)g_spareBuffer, MB_OK); } // Check if specialty mode hourly if (g_unitConfig.timerModeFrequency == TIMER_MODE_HOURLY) { if (currentTime.min < g_unitConfig.timerStopTime.min) { minutesLeft = (g_unitConfig.timerStopTime.min - currentTime.min); } else { minutesLeft = (60 + g_unitConfig.timerStopTime.min - currentTime.min); } if (minutesLeft > 58) minutesLeft = 58; } // Check if the current time is greater than the stop time, indicating that midnight boundary was crossed else if (((currentTime.hour * 60) + currentTime.min) > ((g_unitConfig.timerStopTime.hour * 60) + g_unitConfig.timerStopTime.min)) { // Calculate the time left before powering off to be 24 + the stop time minus the current time minutesLeft = (uint16)(((24 * 60) + (g_unitConfig.timerStopTime.hour * 60) + g_unitConfig.timerStopTime.min) - ((currentTime.hour * 60) + currentTime.min)); } else // Current time is less than start time, operating within the same day { // Calculate the time left before powering off to be the stop time minus the current time minutesLeft = (uint16)(((g_unitConfig.timerStopTime.hour * 60) + g_unitConfig.timerStopTime.min) - ((currentTime.hour * 60) + currentTime.min)); } // Make sure timeout value is not zero if (minutesLeft == 0) minutesLeft = 1; debug("Timer Mode: In progress, minutes left before power off: %d (Expired secs this min: %d)\r\n", minutesLeft, currentTime.sec); // Setup soft timer to turn system off when timer mode is finished for the day AssignSoftTimer(POWER_OFF_TIMER_NUM, (uint32)((minutesLeft * 60 * 2) - (currentTime.sec * 2)), PowerOffTimerCallback); } } }
///---------------------------------------------------------------------------- /// Function Break ///---------------------------------------------------------------------------- BOOLEAN TimerModeActiveCheck(void) { BOOLEAN status = FALSE; DATE_TIME_STRUCT time = GetExternalRtcTime(); uint8 choice; if (g_unitConfig.validationKey == 0xA5A5) { // Check if timer mode is enabled if (g_unitConfig.timerMode == ENABLED) { debug("Timer Mode active\r\n"); // Check if the timer mode settings match the current hour and minute meaning the unit powered itself on if ((g_unitConfig.timerStartTime.hour == time.hour) && (g_unitConfig.timerStartTime.min == time.min)) { debug("Timer Mode Check: Matched Timer settings...\r\n"); status = TRUE; } // Check again if settings match current hour and near minute meaning unit powered itself on but suffered from long startup else if ((g_unitConfig.timerStartTime.hour == time.hour) && ((((g_unitConfig.timerStartTime.min + 1) == 60) && (time.min == 0)) || ((g_unitConfig.timerStartTime.min + 1) == time.min))) { debug("Timer Mode Check: Matched Timer settings (long startup)...\r\n"); status = TRUE; } // Check specialty hourly mode and if current minute matches and the current hour is within range else if ((g_unitConfig.timerModeFrequency == TIMER_MODE_HOURLY) && (g_unitConfig.timerStartTime.min == time.min) && // Check if the start and stop hours match meaning hourly mode runs every hour ((g_unitConfig.timerStartTime.hour == g_unitConfig.timerStopTime.hour) || // OR Check if hourly mode does not cross a 24 hour boundary and the current hour is within range ((g_unitConfig.timerStartTime.hour < g_unitConfig.timerStopTime.hour) && (time.hour >= g_unitConfig.timerStartTime.hour) && (time.hour <= g_unitConfig.timerStopTime.hour)) || // OR Check if the current hour is within range with an hourly mode that does cross a 24 hour boundary ((time.hour >= g_unitConfig.timerStartTime.hour) || (time.hour <= g_unitConfig.timerStopTime.hour)))) { debug("Timer Mode Check: Matched Timer settings (hourly)...\r\n"); status = TRUE; } else { MessageBox(getLangText(STATUS_TEXT), getLangText(UNIT_IS_IN_TIMER_MODE_TEXT), MB_OK); choice = MessageBox(getLangText(WARNING_TEXT), getLangText(CANCEL_TIMER_MODE_Q_TEXT), MB_YESNO); if (choice == MB_FIRST_CHOICE) { g_unitConfig.timerMode = DISABLED; // Save Unit Config SaveRecordData(&g_unitConfig, DEFAULT_RECORD, REC_UNIT_CONFIG_TYPE); OverlayMessage(getLangText(STATUS_TEXT), getLangText(TIMER_MODE_DISABLED_TEXT), 2 * SOFT_SECS); } else // User decided to stay in Timer mode { // TOD Alarm registers still set from previous run, TOD Alarm Mask re-enabled in rtc init // Clear TOD Alarm Mask to allow TOD Alarm interrupt to be generated // ADD CODE TO CLEAR ALARM OverlayMessage(getLangText(WARNING_TEXT), getLangText(POWERING_UNIT_OFF_NOW_TEXT), 2 * SOFT_SECS); // Turn unit off/sleep debug("Timer mode: Staying in Timer mode. Powering off now...\r\n"); PowerUnitOff(SHUTDOWN_UNIT); // Return unnecessary } } } } return (status); }
///---------------------------------------------------------------------------- /// Function Break ///---------------------------------------------------------------------------- void ProcessTimerMode(void) { DATE_TIME_STRUCT currTime = GetExternalRtcTime(); // Check if the Timer mode activated after stop date if (// First Check for past year (currTime.year > g_unitConfig.timerStopDate.year) || // Second check for equal year but past month ((currTime.year == g_unitConfig.timerStopDate.year) && (currTime.month > g_unitConfig.timerStopDate.month)) || // Third check for equal year, equal month, but past day ((currTime.year == g_unitConfig.timerStopDate.year) && (currTime.month == g_unitConfig.timerStopDate.month) && (currTime.day > g_unitConfig.timerStopDate.day))) { // Disable alarm output generation debug("Timer Mode: Activated after date...\r\n"); debug("Timer Mode: Disabling...\r\n"); g_unitConfig.timerMode = DISABLED; // Save Unit Config SaveRecordData(&g_unitConfig, DEFAULT_RECORD, REC_UNIT_CONFIG_TYPE); // Deactivate alarm interrupts DisableExternalRtcAlarm(); // Turn unit off/sleep debug("Timer mode: Powering unit off...\r\n"); PowerUnitOff(SHUTDOWN_UNIT); // Return unnecessary } // Check if the Timer mode activated before start date else if (// First Check for before year (currTime.year < g_unitConfig.timerStartDate.year) || // Second check for equal year but before month ((currTime.year == g_unitConfig.timerStartDate.year) && (currTime.month < g_unitConfig.timerStartDate.month)) || // Third check for equal year, equal month, but before day ((currTime.year == g_unitConfig.timerStartDate.year) && (currTime.month == g_unitConfig.timerStartDate.month) && (currTime.day < g_unitConfig.timerStartDate.day))) { debug("Timer Mode: Activated before date...\r\n"); ResetTimeOfDayAlarm(); // Turn unit off/sleep debug("Timer mode: Powering unit off...\r\n"); PowerUnitOff(SHUTDOWN_UNIT); // Return unnecessary } // Check if the Timer mode activated during active dates but on an off day else if ((g_unitConfig.timerModeFrequency == TIMER_MODE_WEEKDAYS) && ((currTime.weekday == SAT) || (currTime.weekday == SUN))) { debug("Timer Mode: Activated on an off day (weekday freq)...\r\n"); ResetTimeOfDayAlarm(); // Turn unit off/sleep debug("Timer mode: Powering unit off...\r\n"); PowerUnitOff(SHUTDOWN_UNIT); // Return unnecessary } // Check if the Timer mode activated during active dates but on an off day else if ((g_unitConfig.timerModeFrequency == TIMER_MODE_MONTHLY) && (currTime.day != g_unitConfig.timerStartDate.day)) { debug("Timer Mode: Activated on off day (monthly freq)...\r\n"); ResetTimeOfDayAlarm(); // Turn unit off/sleep debug("Timer mode: Powering unit off...\r\n"); PowerUnitOff(SHUTDOWN_UNIT); // Return unnecessary } // Check if the Timer mode activated on end date (and not hourly mode) else if ((g_unitConfig.timerModeFrequency != TIMER_MODE_HOURLY) && (currTime.year == g_unitConfig.timerStopDate.year) && (currTime.month == g_unitConfig.timerStopDate.month) && (currTime.day == g_unitConfig.timerStopDate.day)) { // Disable alarm output generation debug("Timer Mode: Activated on end date...\r\n"); // Signal the timer mode end of session timer to stop timer mode due to this being the last run g_timerModeLastRun = YES; // Deactivate alarm interrupts DisableExternalRtcAlarm(); } // Check if the Timer mode activated on end date and end hour (hourly mode) else if ((g_unitConfig.timerModeFrequency == TIMER_MODE_HOURLY) && (currTime.year == g_unitConfig.timerStopDate.year) && (currTime.month == g_unitConfig.timerStopDate.month) && (currTime.day == g_unitConfig.timerStopDate.day) && (currTime.hour == g_unitConfig.timerStopTime.hour)) { // Disable alarm output generation debug("Timer Mode: Activated on end date...\r\n"); // Signal the timer mode end of session timer to stop timer mode due to this being the last run g_timerModeLastRun = YES; // Deactivate alarm interrupts DisableExternalRtcAlarm(); } else // Timer mode started during the active dates on a day it's supposed to run { if (g_unitConfig.timerModeFrequency == TIMER_MODE_ONE_TIME) { // Signal the timer mode end of session timer to stop timer mode due to this being the last run g_timerModeLastRun = YES; // Deactivate alarm interrupts DisableExternalRtcAlarm(); } else // All other timer modes { // Reset the Time of Day Alarm to wake the unit up again ResetTimeOfDayAlarm(); } } OverlayMessage(getLangText(STATUS_TEXT), getLangText(TIMER_MODE_NOW_ACTIVE_TEXT), (2 * SOFT_SECS)); raiseTimerEventFlag(TIMER_MODE_TIMER_EVENT); // Setup soft timer to turn system off when timer mode is finished for the day (minus the expired secs in the current minute AssignSoftTimer(POWER_OFF_TIMER_NUM, ((g_unitConfig.TimerModeActiveMinutes * 60 * 2) - (currTime.sec * 2)), PowerOffTimerCallback); debug("Timer mode: running...\r\n"); }
///---------------------------------------------------------------------------- /// Function Break ///---------------------------------------------------------------------------- void ProcessCraftData() { uint8 newPoolBuffer = NO; // Halt all debugging message when recieving data. if (g_modemStatus.testingFlag == YES) g_disableDebugPrinting = NO; // Check status and then reset it to no error. if (CMD_MSG_OVERFLOW_ERR == g_isrMessageBufferPtr->status) { g_isrMessageBufferPtr->status = CMD_MSG_NO_ERR; OverlayMessage(getLangText(STATUS_TEXT), getLangText(MODEM_SYNC_FAILED_TEXT), 0); #if 1 // New return; #endif } // Check status and then reset it to no error. if (0xBADD != g_isrMessageBufferPtr->overRunCheck) { g_isrMessageBufferPtr->overRunCheck = 0xBADD; OverlayMessage(getLangText(STATUS_TEXT), getLangText(CRAFT_SERIAL_ERROR_TEXT), 0); #if 1 // New return; #endif } while (g_isrMessageBufferPtr->readPtr != g_isrMessageBufferPtr->writePtr) { debugRaw("<%c>",*g_isrMessageBufferPtr->readPtr); if ((*g_isrMessageBufferPtr->readPtr != 0x0A) && (*g_isrMessageBufferPtr->readPtr != 0x0D)) { *(g_msgPool[s_msgWriteIndex].writePtr) = *g_isrMessageBufferPtr->readPtr; g_msgPool[s_msgWriteIndex].writePtr++; g_msgPool[s_msgWriteIndex].size++; // The buffer is full, go to the next buffer pool. if (g_msgPool[s_msgWriteIndex].size >= (CMD_BUFFER_SIZE-2)) { #if 1 // New addition to add a null to the end of the message for those that get processed as a string *(g_msgPool[s_msgWriteIndex].writePtr) = '\0'; g_msgPool[s_msgWriteIndex].writePtr++; g_msgPool[s_msgWriteIndex].size++; #endif newPoolBuffer = YES; } } else { if (g_msgPool[s_msgWriteIndex].size > 0) { #if 1 // New addition to add a null to the end of the message for those that get processed as a string *(g_msgPool[s_msgWriteIndex].writePtr) = '\0'; g_msgPool[s_msgWriteIndex].writePtr++; g_msgPool[s_msgWriteIndex].size++; #endif newPoolBuffer = YES; } } if (YES == newPoolBuffer) { // The message is now complete so go to the next message pool buffer. s_msgWriteIndex++; if (s_msgWriteIndex >= CMD_MSG_POOL_SIZE) { s_msgWriteIndex = 0; } // Flag to indicate complete message to process raiseSystemEventFlag(CRAFT_PORT_EVENT); } *g_isrMessageBufferPtr->readPtr = 0x00; g_isrMessageBufferPtr->readPtr++; if (g_isrMessageBufferPtr->readPtr >= (g_isrMessageBufferPtr->msg + CMD_BUFFER_SIZE)) { g_isrMessageBufferPtr->readPtr = g_isrMessageBufferPtr->msg; } } if ((g_modemStatus.testingFlag == YES) && (g_modemStatus.testingPrintFlag == YES)) { g_disableDebugPrinting = YES; } return; }
void InitSoftwareSettings_NS8100(void) { INPUT_MSG_STRUCT mn_msg; debug("Init Software Settings...\r\n"); //------------------------------------------------------------------------- // Init version msg //------------------------------------------------------------------------- InitVersionMsg(); //------------------------------------------------------------------------- // Init time msg and update current time //------------------------------------------------------------------------- InitTimeMsg(); UpdateCurrentTime(); //------------------------------------------------------------------------- // Get the function address passed by the bootloader //------------------------------------------------------------------------- CheckBootloaderAppPresent(); debug("Bootloader check complete\r\n"); //------------------------------------------------------------------------- // Load the Unit Config //------------------------------------------------------------------------- LoadUnitConfig(); debug("Loading Unit Config record\r\n"); //------------------------------------------------------------------------- // Build the language table based on the user's last language choice //------------------------------------------------------------------------- BuildLanguageLinkTable(g_unitConfig.languageMode); debug("Language Tables built\r\n"); //------------------------------------------------------------------------- // Initialize Unit Config items such as contrast, timers //------------------------------------------------------------------------- ActivateUnitConfigOptions(); debug("Activated Unit Config Options\r\n"); //------------------------------------------------------------------------- // Display the Splash screen //------------------------------------------------------------------------- DisplaySplashScreen(); debug("Display Splash screen complete\r\n"); //------------------------------------------------------------------------- // Wait at least 3 seconds for the main screen to be displayed //------------------------------------------------------------------------- debug("Three second delay for Splash screen\r\n"); SoftUsecWait(3 * SOFT_SECS); //------------------------------------------------------------------------- // Display Smart Sensor information if found //------------------------------------------------------------------------- DisplaySmartSensorInfo(INFO_ON_INIT); //------------------------------------------------------------------------- // Bootloader entry check //------------------------------------------------------------------------- BootloaderEntryCheck(); //------------------------------------------------------------------------- // Load the Factory Setup Record //------------------------------------------------------------------------- LoadFactorySetupRecord(); debug("Factory setup record loaded\r\n"); //------------------------------------------------------------------------- // Load Default Trigger Record //------------------------------------------------------------------------- LoadDefaultTriggerRecord(); debug("Default Trigger record loaded\r\n"); //------------------------------------------------------------------------- // Load the Modem Setup Record //------------------------------------------------------------------------- LoadModemSetupRecord(); debug("Modem Setup record loaded\r\n"); //------------------------------------------------------------------------- // Add OnOff Log Timestamp //------------------------------------------------------------------------- AddOnOffLogTimestamp(ON); debug("On/Off Log timestamp appended\r\n"); #if 0 // Removed debug log file due to inducing system problems //------------------------------------------------------------------------- // Switch Debug Log file SwitchDebugLogFile(); #endif //------------------------------------------------------------------------- // Init Global Unique Event Number //------------------------------------------------------------------------- InitCurrentEventNumber(); debug("Current Event Number initialized\r\n"); //------------------------------------------------------------------------- // Init AutoDialout //------------------------------------------------------------------------- InitAutoDialout(); debug("Auto Dialout initialized\r\n"); //------------------------------------------------------------------------- // Init Monitor Log //------------------------------------------------------------------------- InitMonitorLog(); debug("Monitor Log initialized\r\n"); //------------------------------------------------------------------------- // Init the Sensor Parameters //------------------------------------------------------------------------- InitSensorParameters(g_factorySetupRecord.seismicSensorType, (uint8)g_triggerRecord.srec.sensitivity); debug("Sensor Parameters initialized\r\n"); //------------------------------------------------------------------------- // Init the Summary List file //------------------------------------------------------------------------- ManageEventsDirectory(); InitSummaryListFile(); debug("Summary List initialized\r\n"); //------------------------------------------------------------------------- // Update Flash Usage Stats //------------------------------------------------------------------------- OverlayMessage(getLangText(STATUS_TEXT), getLangText(CALCULATING_EVENT_STORAGE_SPACE_FREE_TEXT), 0); GetSDCardUsageStats(); debug("Flash Usage Stats updated (Cluster size: %d bytes)\r\n", g_sdCardUsageStats.clusterSizeInBytes); //------------------------------------------------------------------------- // Check for Timer mode activation //------------------------------------------------------------------------- if (TimerModeActiveCheck() == TRUE) { debug("--- Timer Mode Startup ---\r\n"); ProcessTimerMode(); } else // Normal startup { debug("--- Normal Startup ---\r\n"); } //------------------------------------------------------------------------- // Init the cmd message handling buffers before initialization of the ports. //------------------------------------------------------------------------- RemoteCmdMessageHandlerInit(); debug("Craft Message Handler initialized\r\n"); //------------------------------------------------------------------------- // Init the input buffers and status flags for input craft data. //------------------------------------------------------------------------- CraftInitStatusFlags(); debug("Craft Status flags initilaized\r\n"); //------------------------------------------------------------------------- // Signal remote end that RS232 Comm is available //------------------------------------------------------------------------- SET_RTS; SET_DTR; debug("Craft RTS and DTR enabled\r\n"); //------------------------------------------------------------------------- // Reset LCD timers //------------------------------------------------------------------------- ResetSoftTimer(LCD_BACKLIGHT_ON_OFF_TIMER_NUM); ResetSoftTimer(LCD_POWER_ON_OFF_TIMER_NUM); //------------------------------------------------------------------------- // Turn on the Green keypad LED when system init complete //------------------------------------------------------------------------- debug("Init complete, turning Kepypad LED Green...\r\n"); WriteMcp23018(IO_ADDRESS_KPD, GPIOA, ((ReadMcp23018(IO_ADDRESS_KPD, GPIOA) & 0xCF) | GREEN_LED_PIN)); //------------------------------------------------------------------------- // Assign a one second keypad led update timer //------------------------------------------------------------------------- AssignSoftTimer(KEYPAD_LED_TIMER_NUM, ONE_SECOND_TIMEOUT, KeypadLedUpdateTimerCallBack); debug("Keypad LED Timer initialized\r\n"); //------------------------------------------------------------------------- // Jump to the true main menu //------------------------------------------------------------------------- debug("Jumping to Main Menu\r\n"); SETUP_MENU_MSG(MAIN_MENU); JUMP_TO_ACTIVE_MENU(); //------------------------------------------------------------------------- // Enable Craft input (delayed to prevent serial input from locking unit) //------------------------------------------------------------------------- InitCraftInterruptBuffers(); Setup_8100_Usart1_RS232_ISR(); if (GET_HARDWARE_ID == HARDWARE_ID_REV_8_WITH_GPS_MOD) { EnableGps(); } //------------------------------------------------------------------------- // Enable keypad key input (delayed to prevent key input from locking unit) //------------------------------------------------------------------------- EnableMcp23018Interrupts(); debug("Mcp23018 interrupts enabled\r\n"); //------------------------------------------------------------------------- // Display last line of system init //------------------------------------------------------------------------- DisplayVersionToDebug(); }
///---------------------------------------------------------------------------- /// Function Break ///---------------------------------------------------------------------------- void LoadFactorySetupRecord(void) { DATE_TIME_STRUCT tempTime; char buff[50]; GetRecordData(&g_factorySetupRecord, DEFAULT_RECORD, REC_FACTORY_SETUP_TYPE); // Check if the Factory Setup Record is invalid if (g_factorySetupRecord.invalid) { // Warn the user debugWarn("Factory setup record not found.\r\n"); OverlayMessage(getLangText(ERROR_TEXT), getLangText(FACTORY_SETUP_DATA_COULD_NOT_BE_FOUND_TEXT), (2 * SOFT_SECS)); // Check if the Shadow Factory setup is valid if (!SHADOW_FACTORY_SETUP_CLEARED) { // Warn the user debugWarn("Factory setup shadow copy exists.\r\n"); if (MessageBox(getLangText(CONFIRM_TEXT), getLangText(RESTORE_FACTORY_SETUP_FROM_BACKUP_Q_TEXT), MB_YESNO) == MB_FIRST_CHOICE) { GetFlashUserPageFactorySetup(&g_factorySetupRecord); SaveRecordData(&g_factorySetupRecord, DEFAULT_RECORD, REC_FACTORY_SETUP_TYPE); } } } // Check if the Factory Setup Record is valid (in case shadow factory setup was copied over) if (!g_factorySetupRecord.invalid) { if (g_seismicSmartSensorMemory.version & SMART_SENSOR_OVERLAY_KEY) { g_factorySetupRecord.seismicSensorType = (pow(2, g_seismicSmartSensorMemory.sensorType) * SENSOR_2_5_IN); } if (g_acousticSmartSensorMemory.version & SMART_SENSOR_OVERLAY_KEY) { if ((g_acousticSmartSensorMemory.sensorType == SENSOR_MIC_148) || (g_acousticSmartSensorMemory.sensorType == SENSOR_MIC_160)) { g_factorySetupRecord.acousticSensorType = g_acousticSmartSensorMemory.sensorType; } } UpdateWorkingCalibrationDate(); // Print the Factory Setup Record to the console memset(&buff[0], 0, sizeof(buff)); ConvertCalDatetoDateTime(&tempTime, &g_currentCalibration.date); ConvertTimeStampToString(buff, &tempTime, REC_DATE_TYPE); if (g_factorySetupRecord.seismicSensorType > SENSOR_ACC_RANGE_DIVIDER) { strcpy((char*)&g_spareBuffer, "Acc"); } else { sprintf((char*)&g_spareBuffer, "%3.1f in", (float)g_factorySetupRecord.seismicSensorType / (float)204.8); } // Check if an older unit doesn't have the Analog Channel Config set if ((g_factorySetupRecord.analogChannelConfig != CHANNELS_R_AND_V_SCHEMATIC) && (g_factorySetupRecord.analogChannelConfig != CHANNELS_R_AND_V_SWAPPED)) { // Set the default g_factorySetupRecord.analogChannelConfig = CHANNELS_R_AND_V_SWAPPED; } debug("Factory Setup: Serial #: %s\r\n", g_factorySetupRecord.unitSerialNumber); debug("Factory Setup: Cal Date: %s\r\n", buff); debug("Factory Setup: Sensor Type: %s\r\n", (char*)g_spareBuffer); debug("Factory Setup: A-Weighting: %s\r\n", (g_factorySetupRecord.aWeightOption == YES) ? "Enabled" : "Disabled"); debug("Factory Setup: Analog Channel Config: %s\r\n", (g_factorySetupRecord.analogChannelConfig == CHANNELS_R_AND_V_SCHEMATIC) ? "Schematic" : "Swapped"); } }
///---------------------------------------------------------------------------- /// Function Break ///---------------------------------------------------------------------------- void MoveManualCalToFile(void) { uint16 i; uint16 sample; uint16 normalizedData; uint16 hiA = 0, hiR = 0, hiV = 0, hiT = 0; uint16 lowA = 0xFFFF, lowR = 0xFFFF, lowV = 0xFFFF, lowT = 0xFFFF; uint16* startOfEventPtr; uint16* endOfEventDataPtr; uint32 compressSize; int manualCalFileHandle = -1; uint16* aManualCalPeakPtr; uint16* rManualCalPeakPtr; uint16* vManualCalPeakPtr; uint16* tManualCalPeakPtr; debug("Processing Manual Cal to be saved\r\n"); if (g_freeEventBuffers < g_maxEventBuffers) { g_pendingEventRecord.summary.captured.eventTime = GetCurrentTime(); // Clear out A, R, V, T channel calculated data (in case the pending event record is reused) memset(&g_pendingEventRecord.summary.calculated.a, 0, (NUMBER_OF_CHANNELS_DEFAULT * sizeof(CHANNEL_CALCULATED_DATA_STRUCT))); startOfEventPtr = g_currentEventStartPtr; endOfEventDataPtr = g_currentEventStartPtr + g_wordSizeInCal; for (i = (uint16)g_samplesInCal; i != 0; i--) { if (g_bitShiftForAccuracy) AdjustSampleForBitAccuracy(); //========================================================= // First channel - A sample = *(g_currentEventSamplePtr + A_CHAN_OFFSET); if (sample > hiA) hiA = sample; if (sample < lowA) lowA = sample; normalizedData = FixDataToZero(sample); if (normalizedData > g_pendingEventRecord.summary.calculated.a.peak) { g_pendingEventRecord.summary.calculated.a.peak = normalizedData; aManualCalPeakPtr = (g_currentEventSamplePtr + A_CHAN_OFFSET); } //========================================================= // Second channel - R sample = *(g_currentEventSamplePtr + R_CHAN_OFFSET); if (sample > hiR) hiR = sample; if (sample < lowR) lowR = sample; normalizedData = FixDataToZero(sample); if (normalizedData > g_pendingEventRecord.summary.calculated.r.peak) { g_pendingEventRecord.summary.calculated.r.peak = normalizedData; rManualCalPeakPtr = (g_currentEventSamplePtr + R_CHAN_OFFSET); } //========================================================= // Third channel - V sample = *(g_currentEventSamplePtr + V_CHAN_OFFSET); if (sample > hiV) hiV = sample; if (sample < lowV) lowV = sample; normalizedData = FixDataToZero(sample); if (normalizedData > g_pendingEventRecord.summary.calculated.v.peak) { g_pendingEventRecord.summary.calculated.v.peak = normalizedData; vManualCalPeakPtr = (g_currentEventSamplePtr + V_CHAN_OFFSET); } //========================================================= // Fourth channel - T sample = *(g_currentEventSamplePtr + T_CHAN_OFFSET); if (sample > hiT) hiT = sample; if (sample < lowT) lowT = sample; normalizedData = FixDataToZero(sample); if (normalizedData > g_pendingEventRecord.summary.calculated.t.peak) { g_pendingEventRecord.summary.calculated.t.peak = normalizedData; tManualCalPeakPtr = (g_currentEventSamplePtr + T_CHAN_OFFSET); } g_currentEventSamplePtr += NUMBER_OF_CHANNELS_DEFAULT; } g_pendingEventRecord.summary.calculated.a.peak = (uint16)(hiA - lowA + 1); g_pendingEventRecord.summary.calculated.r.peak = (uint16)(hiR - lowR + 1); g_pendingEventRecord.summary.calculated.v.peak = (uint16)(hiV - lowV + 1); g_pendingEventRecord.summary.calculated.t.peak = (uint16)(hiT - lowT + 1); g_pendingEventRecord.summary.calculated.a.frequency = CalcSumFreq(aManualCalPeakPtr, SAMPLE_RATE_1K, startOfEventPtr, endOfEventDataPtr); g_pendingEventRecord.summary.calculated.r.frequency = CalcSumFreq(rManualCalPeakPtr, SAMPLE_RATE_1K, startOfEventPtr, endOfEventDataPtr); g_pendingEventRecord.summary.calculated.v.frequency = CalcSumFreq(vManualCalPeakPtr, SAMPLE_RATE_1K, startOfEventPtr, endOfEventDataPtr); g_pendingEventRecord.summary.calculated.t.frequency = CalcSumFreq(tManualCalPeakPtr, SAMPLE_RATE_1K, startOfEventPtr, endOfEventDataPtr); CompleteRamEventSummary(); CacheResultsEventInfo((EVT_RECORD*)&g_pendingEventRecord); if (g_fileAccessLock != AVAILABLE) { ReportFileSystemAccessProblem("Save Manual Cal"); } else // (g_fileAccessLock == AVAILABLE) { GetSpi1MutexLock(SDMMC_LOCK); nav_select(FS_NAV_ID_DEFAULT); // Get new event file handle manualCalFileHandle = GetEventFileHandle(g_pendingEventRecord.summary.eventNumber, CREATE_EVENT_FILE); if (manualCalFileHandle == -1) { ReleaseSpi1MutexLock(); debugErr("Failed to get a new file handle for the Manual Cal event\r\n"); } else // Write the file event to the SD card { sprintf((char*)g_spareBuffer, "%s %s #%d %s...", getLangText(CALIBRATION_TEXT), getLangText(EVENT_TEXT), g_pendingEventRecord.summary.eventNumber, getLangText(BEING_SAVED_TEXT)); OverlayMessage(getLangText(EVENT_COMPLETE_TEXT), (char*)g_spareBuffer, 0); // Write the event record header and summary write(manualCalFileHandle, &g_pendingEventRecord, sizeof(EVT_RECORD)); // Write the event data, containing the Pretrigger, event and cal write(manualCalFileHandle, g_currentEventStartPtr, (g_wordSizeInCal * 2)); SetFileDateTimestamp(FS_DATE_LAST_WRITE); // Update the remaining space left UpdateSDCardUsageStats(nav_file_lgt()); // Done writing the event file, close the file handle g_testTimeSinceLastFSWrite = g_lifetimeHalfSecondTickCount; close(manualCalFileHandle); //========================================================================================================== // Save compressed data file //---------------------------------------------------------------------------------------------------------- if (g_unitConfig.saveCompressedData != DO_NOT_SAVE_EXTRA_FILE_COMPRESSED_DATA) { // Get new event file handle g_globalFileHandle = GetERDataFileHandle(g_pendingEventRecord.summary.eventNumber, CREATE_EVENT_FILE); g_spareBufferIndex = 0; compressSize = lzo1x_1_compress((void*)g_currentEventStartPtr, (g_wordSizeInCal * 2), OUT_FILE); // Check if any remaining compressed data is queued if (g_spareBufferIndex) { // Finish writing the remaining compressed data write(g_globalFileHandle, g_spareBuffer, g_spareBufferIndex); g_spareBufferIndex = 0; } debug("Manual Cal Compressed Data length: %d (Matches file: %s)\r\n", compressSize, (compressSize == nav_file_lgt()) ? "Yes" : "No"); SetFileDateTimestamp(FS_DATE_LAST_WRITE); // Update the remaining space left UpdateSDCardUsageStats(nav_file_lgt()); // Done writing the event file, close the file handle g_testTimeSinceLastFSWrite = g_lifetimeHalfSecondTickCount; close(g_globalFileHandle); } //========================================================================================================== ReleaseSpi1MutexLock(); debug("Manual Cal Event file closed\r\n"); AddEventToSummaryList(&g_pendingEventRecord); // Don't log a monitor entry for Manual Cal //UpdateMonitorLogEntry(); // After event numbers have been saved, store current event number in persistent storage. StoreCurrentEventNumber(); // Now store the updated event number in the universal ram storage. g_pendingEventRecord.summary.eventNumber = g_nextEventNumberToUse; } if (++g_eventBufferReadIndex == g_maxEventBuffers) { g_eventBufferReadIndex = 0; g_currentEventSamplePtr = g_startOfEventBufferPtr; } else { g_currentEventSamplePtr = g_startOfEventBufferPtr + (g_eventBufferReadIndex * g_wordSizeInEvent); } clearSystemEventFlag(MANUAL_CAL_EVENT); // Set flag to display calibration results if not monitoring or monitoring in waveform if ((g_sampleProcessing == IDLE_STATE) || ((g_sampleProcessing == ACTIVE_STATE) && (g_triggerRecord.opMode == WAVEFORM_MODE))) { // Set printout mode to allow the results menu processing to know this is a manual cal pulse raiseMenuEventFlag(RESULTS_MENU_EVENT); } g_freeEventBuffers++; } } else { debugWarn("Manual Cal: No free buffers\r\n"); clearSystemEventFlag(MANUAL_CAL_EVENT); } }