SleepHelper
|
#include <SleepHelper.h>
Data Structures | |
class | AppCallback |
Base class for a list of zero or more callback functions. More... | |
class | AppCallbackState |
State data for AppCallbackWithState. More... | |
class | AppCallbackWithState |
Works like AppCallback, but includes additional state data. More... | |
class | PublishData |
Class to hold data to be published by Particle.publish. More... | |
class | ShouldConnectAppCallback |
Class for ShouldConnect application callback. More... | |
class | SleepConfigurationParameters |
Structure of information about the next planned sleep. More... | |
class | SleepHelperRecursiveMutex |
This is a wrapper around a recursive mutex, similar to Device OS RecursiveMutex. More... | |
Public Member Functions | |
SleepHelper & | withSleepConfigurationFunction (std::function< bool(SystemSleepConfiguration &, SleepConfigurationParameters &)> fn) |
Register a function to be called to configure sleep. More... | |
SleepHelper & | withWakeFunction (std::function< bool(const SystemSleepResult &)> fn) |
Register a function to be called on wake from sleep. More... | |
SleepHelper & | withMinimumCellularOffTime (std::chrono::milliseconds timeMs) |
Sets the minimum time to disconnect from cellular. Default: 13 minutes. More... | |
SleepHelper & | withMinimumSleepTimeMs (std::chrono::milliseconds timeMs) |
Sets the minimum time to sleep. Default is 10 seconds. More... | |
SleepHelper & | withSetupFunction (std::function< bool()> fn) |
Adds a function to be called during setup() More... | |
SleepHelper & | withLoopFunction (std::function< bool()> fn) |
Adds a function to be called on every call to loop() More... | |
SleepHelper & | withDataCaptureFunction (std::function< bool(AppCallbackState &state)> fn) |
The data capture function is called on a schedule to capture data. More... | |
SleepHelper & | withSleepReadyFunction (std::function< bool(AppCallbackState &, system_tick_t)> fn) |
Determine if it's OK to sleep now, when in connected state. More... | |
SleepHelper & | withShouldConnectFunction (std::function< bool(int &connectConviction, int &noConnectConviction)> fn) |
Function to call to determine if a full wake should be done. More... | |
SleepHelper & | withWakeOrBootFunction (std::function< bool(int)> fn) |
Called during setup, after sleep, or an aborted sleep because duration was too short. More... | |
SleepHelper & | withWakeEventName (const char *eventName) |
Set the event name used for the wake event. Default: sleepHelper. More... | |
SleepHelper & | withSleepOrResetFunction (std::function< bool(bool)> fn) |
Adds a function to be called right before sleep or reset. More... | |
SleepHelper & | withMaximumTimeToConnectFunction (std::function< bool(system_tick_t ms)> fn) |
Adds a function to be called while connecting. More... | |
SleepHelper & | withMaximumTimeToConnect (system_tick_t timeMs) |
Sets the maximum time to connect to the cloud. If this limit is exceeded, the device will go to sleep. More... | |
SleepHelper & | withMaximumTimeToConnect (std::chrono::milliseconds timeMs) |
Sets the maximum time to connect to the cloud. If this limit is exceeded, the device will go to sleep. More... | |
SleepHelper & | withNoConnectionFunction (std::function< bool(AppCallbackState &state)> fn) |
Register a callback for when in the no connection state. More... | |
SleepHelper & | withMinimumConnectedTime (system_tick_t timeMs) |
Set the minimum amount of time to stay connected to the cloud (optional) More... | |
SleepHelper & | withMinimumConnectedTime (std::chrono::milliseconds timeMs) |
Set the minimum amount of time to stay connected to the cloud (optional) More... | |
SleepHelper & | withShouldConnectMinimumSoC (float minSoC, int conviction=100) |
Require a minimum battery SoC to connect to cellular. More... | |
SleepHelper & | withAB1805_WDT (AB1805 &ab1805) |
Stop and resume an AB1805 watchdog before sleep and reset. More... | |
SleepHelper & | withPublishQueuePosixRK (std::chrono::milliseconds maxTimeToPublish=0ms) |
Connect the PublishQueuePosixRK library with this library. More... | |
SleepHelper & | withTimeConfig (const char *tzConfig) |
Sets the time configuration string for local time calculations. More... | |
SleepHelper & | withEventsEnabledEnable (uint64_t flag) |
Enable an eventsEnable flag. These determine whether the add values to the wake event. More... | |
SleepHelper & | withEventsEnabledDisable (uint64_t flag) |
Disable an eventsEnable flag. These determine whether the add values to the wake event. More... | |
bool | eventsEnableEnabled (uint64_t flag) const |
Returns true if the eventsEnable flag is set. More... | |
SleepHelper & | withLogEnabledEnable (uint64_t flag) |
Enable logging for a specific type of log. More... | |
SleepHelper & | withLogEnabledDisable (uint64_t flag) |
Disable logging for a specific type of log. More... | |
bool | logEnableEnabled (uint64_t flag) const |
Returns true if the specified logging flag is set. More... | |
SleepHelper & | withSleepEnabled (bool sleepEnabled) |
Sets the sleep enabled flag. More... | |
bool | getSleepEnabled () const |
Get the sleep enabled flag value. Default is true. More... | |
void | setup () |
Perform setup operations; call this from global application setup() More... | |
void | loop () |
Perform application loop operations; call this from global application loop() More... | |
LocalTimeSchedule & | getScheduleQuick () |
Get the quick wake schedule. More... | |
LocalTimeSchedule & | getScheduleFull () |
Get the full wake schedule. More... | |
LocalTimeSchedule & | getScheduleDataCapture () |
The data capture schedule determines when to call the data capture callback. More... | |
Static Public Member Functions | |
static SleepHelper & | instance () |
Gets the singleton instance of this class, allocating it if necessary. More... | |
static void | JSONCopy (const char *src, JSONWriter &writer) |
Copies pre-formatted JSON into a writer. More... | |
static void | JSONCopy (const JSONValue &src, JSONWriter &writer) |
Copies pre-formatted JSON into a writer. More... | |
static int | eventsEnablePriority (uint64_t flag) |
Returns the priority value (0 - 100) for a given flag. More... | |
static const char * | eventsEnableName (uint64_t flag) |
Returns the event name (const c-string) for a given flag. More... | |
Data Fields | |
LocalTimeScheduleManager | scheduleManager |
Class for managing publish and wake schedules. | |
Static Public Attributes | |
static const uint64_t | eventsEnabledWakeReason = 0x0000000000000001ul |
"wr" wake reason (int) event | |
static const uint64_t | eventsEnabledTimeToConnect = 0x0000000000000002ul |
"ttc" time to connect event | |
static const uint64_t | eventsEnabledResetReason = 0x0000000000000004ul |
"rr" reset reason event | |
static const uint64_t | eventsEnabledBatterySoC = 0x0000000000000008ul |
"soc" report battery SoC on full wake | |
static const uint64_t | logEnabledNormal = 0x0000000000fffffful |
Enable all normal message (default) | |
static const uint64_t | logEnabledVerbose = 0x000000ffff000000ul |
Enable more verbose messages. | |
static const uint64_t | logEnabledDebugging = 0x00ffff0000000000ul |
Enable debugging message. | |
static const uint64_t | logEnabledAll = 0xfffffffffffffffful |
Enable all messages. | |
static const uint64_t | logEnabledPublish = 0x0000000000000001ul |
Log on each publish. | |
static const uint64_t | logEnabledPublishData = 0x0000010000000000ul |
Log the full publish data. | |
static const uint64_t | logEnabledHistoryData = 0x0000020000000000ul |
Log the full history data. | |
static const int | WAKEUP_REASON_SETUP = 0x10001 |
Wakeup reason used on reset or cold boot, from setup() | |
static const int | WAKEUP_REASON_NO_SLEEP = 0x10002 |
Wakeup reason when we didn't actually sleep because the period was too short. | |
Protected Member Functions | |
SleepHelper () | |
The constructor is protected because the class is a singleton. More... | |
virtual | ~SleepHelper () |
The destructor is protected because the class is a singleton and cannot be deleted. | |
SleepHelper (const SleepHelper &)=delete | |
SleepHelper & | operator= (const SleepHelper &)=delete |
void | systemEventHandler (system_event_t event, int param) |
A system event handler is so the code can be notified of things like firmware update started. More... | |
void | calculateSleepSettings (bool isConnected) |
Calculate sleep settings. More... | |
void | dataCaptureHandler () |
Calls the data capture handlers. More... | |
void | stateHandlerStart () |
Initial state at boot or after sleep. More... | |
void | stateHandlerConnectWait () |
Waits for the Particle cloud connection to be made. More... | |
void | stateHandlerTimeValidWait () |
Wait for time synchronization from the cloud. This normally occurs very quickly (under 1 second). More... | |
void | stateHandlerConnectedStart () |
Handles things after connecting to the cloud on a full wake. More... | |
void | stateHandlerConnectedWakeEvents () |
Prepares wake event data. More... | |
void | stateHandlerConnected () |
Handles things while connected to the cloud. More... | |
void | stateHandlerPublishWait () |
Wait for a publish to complete. More... | |
void | stateHandlerPublishRateLimit () |
Waits so publishes only occur once per second. More... | |
void | stateHandlerReconnectWait () |
If the cloud connection is lost, waits here. More... | |
void | stateHandlerNoConnection () |
Called on quick wake. More... | |
void | stateHandlerDisconnectBeforeSleep () |
Possibly disconnect from cellular before sleep. More... | |
void | stateHandlerDisconnectWait () |
Waits for Particle.disconnected() to be true. More... | |
void | stateHandlerWaitCellularDisconnected () |
Waits for Cellular.ready or WiFi.ready to be false. More... | |
void | stateHandlerWaitCellularOff () |
Waits until Cellular.isOff or WiFi.isOff to be true. More... | |
void | stateHandlerSleep () |
Handles sleep. More... | |
void | stateHandlerSleepDone () |
Handles wake operations. More... | |
void | stateHandlerSleepShort () |
Handles sleep periods less than minimumSleepTimeMs (default: 10 seconds) without actually sleeping. More... | |
Static Protected Member Functions | |
static void | systemEventHandlerStatic (system_event_t event, int param) |
A system event handler is so the code can be notified of things like firmware update started. More... | |
Protected Attributes | |
AppCallback< SystemSleepConfiguration &, SleepConfigurationParameters & > | sleepConfigurationFunctions |
Callback functions for adjusting sleep behavior. | |
AppCallback< const SystemSleepResult & > | wakeFunctions |
Callback functions called on wake from sleep. | |
SystemSleepConfiguration | sleepConfig |
Passed to sleep configuration functions. | |
SleepConfigurationParameters | sleepParams |
Passed to sleep configuration functions. | |
AppCallback | setupFunctions |
Callback functions called during setup() | |
AppCallback | loopFunctions |
Callback functions called during loop() | |
AppCallbackWithState | dataCaptureFunctions |
Callback functions called for data capture. | |
AppCallbackWithState< system_tick_t > | sleepReadyFunctions |
Callback functions to determine if it's time to sleep. | |
ShouldConnectAppCallback | shouldConnectFunctions |
Callback functions to determine whether to do a quick or full wake. | |
AppCallback< int > | wakeOrBootFunctions |
Called at either boot or after wake. | |
AppCallback< bool > | sleepOrResetFunctions |
Called right before sleep or before reset. | |
AppCallback< system_tick_t > | maximumTimeToConnectFunctions |
Callback to determine if the maximum time to connect has been exceeded. | |
AppCallbackWithState | noConnectionFunctions |
When in no connection (quick wake) mode, after the data capture functions are called the no connection functions are called. | |
String | wakeEventName = "sleepHelper" |
Event name for wake events. Default: "sleepHelper". | |
int | wakeReasonInt = 0 |
Wake reason after sleep. | |
std::vector< PublishData > | publishData |
Wake event data to publish (JSON strings) | |
uint64_t | eventsEnabled = 0xfffffffffffffffful |
Which event history events are enabled (default: all) More... | |
bool | sleepEnabled = true |
Flag to indicate if sleep is allowed (default) or if it has been disabled. | |
uint64_t | logEnabled = logEnabledNormal |
Which logging messages to enable. More... | |
system_tick_t | minimumCellularOffTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(13min).count() |
Default value for the minimum time to turn cellular off. | |
system_tick_t | minimumSleepTimeMs = std::chrono::duration_cast<std::chrono::milliseconds>(10s).count() |
Default value for the minimum time to sleep. | |
std::function< void(SleepHelper &)> | stateHandler = &SleepHelper::stateHandlerStart |
state handler function | |
system_tick_t | stateTime = 0 |
millis counter used in certain state handlers | |
system_tick_t | connectAttemptStartMillis = 0 |
millis value when Particle.connect was called | |
system_tick_t | reconnectAttemptStartMillis = 0 |
millis value when Particle.connected returned false after being connected | |
system_tick_t | networkConnectedMillis = 0 |
mills value when Cellular.connected returned true | |
system_tick_t | connectedStartMillis = 0 |
millis value when Particle.connected returned true | |
system_tick_t | lastEventHistoryCheckMillis = 0 |
millis value the last time the event history was checked | |
bool | outOfMemory = false |
Set to true if an out of memory system event occurs. | |
bool | dataCaptureActive = false |
True if data capture handlers are being called. More... | |
std::vector< String > | wakeEventPayload |
Wake events are stored in this vector to be published, rate limited, later. | |
Logger | appLog |
Used instead of Cellular.ready(), etc. More... | |
Static Protected Attributes | |
static SleepHelper * | _instance |
Singleton instance of this class. More... | |
This class is a singleton; you do not create one as a global, on the stack, or with new.
From global application setup you must call: SleepHelper::instance().setup();
From global application loop you must call: SleepHelper::instance().loop();
|
protected |
The constructor is protected because the class is a singleton.
Use SleepHelper::instance() to instantiate the singleton.
|
protecteddelete |
This class is a singleton and cannot be copied
|
protected |
Calculate sleep settings.
isConnected | True if currently connected to cellular |
This uses the last and future cellular connection times and the sleep configuration callbacks. It's a separate function because it's called from both stateHandlerNoConnection and stateHandlerDisconnectBeforeSleep.
|
protected |
Calls the data capture handlers.
This method is called continuously from loop(). This function determines if a capture is currently in progress (non-blocking) of if it's time to start a new capture.
|
inline |
Returns true if the eventsEnable flag is set.
flag | Flag bit value to test, such as eventsEnabledWakeReason |
|
static |
Returns the event name (const c-string) for a given flag.
flag | Flag bit to get the priority for, such as eventsEnabledWakeReason |
|
static |
Returns the priority value (0 - 100) for a given flag.
flag | Flag bit to get the priority for, such as eventsEnabledWakeReason |
|
inline |
The data capture schedule determines when to call the data capture callback.
|
inline |
Get the full wake schedule.
|
inline |
Get the quick wake schedule.
|
inline |
Get the sleep enabled flag value. Default is true.
|
static |
Gets the singleton instance of this class, allocating it if necessary.
Use SleepHelper::instance() to instantiate the singleton.
|
static |
Copies pre-formatted JSON into a writer.
src | Must be a valid JSON object or array as a string |
writer |
This is used because JSONWriter does not have a method to write pre-formatted JSON into a writer. It's a little inefficient but works. Note: The JSON that is inserted may not be identical to the original. This is especially true for JSON that contains double values because the decimal precision will likely change.
|
static |
Copies pre-formatted JSON into a writer.
src | Must be a JSONValue containing an object, array, or primitive |
writer |
This is used because JSONWriter does not have a method to write pre-formatted JSON into a writer. It's a little inefficient but works. Note: The JSON that is inserted may not be identical to the original. This is especially true for JSON that contains double values because the decimal precision will likely change.
|
inline |
Returns true if the specified logging flag is set.
flag | The flag bit such as logEnabledPublish. |
void SleepHelper::loop | ( | ) |
Perform application loop operations; call this from global application loop()
You typically use SleepHelper::instance().loop();
|
protecteddelete |
This class is a singleton and cannot be copied
void SleepHelper::setup | ( | ) |
Perform setup operations; call this from global application setup()
You typically use SleepHelper::instance().setup();
|
protected |
Handles things while connected to the cloud.
Attempts to publish all saved data. Once all data has been published, the sleep ready functions are called to see if all callbacks agree it's time to sleep.
Next state:
|
protected |
Handles things after connecting to the cloud on a full wake.
Steps include:
Next state:
|
protected |
Prepares wake event data.
Next state:
|
protected |
Waits for the Particle cloud connection to be made.
Previous state:
Next state:
|
protected |
Possibly disconnect from cellular before sleep.
Calls calculateSleepSettings() to calculate the sleep settings. A short wake cycle or a sleep configuration function can override the settings and use cellular standby mode instead.
If disconnecting, the Cellular.disconnect occurs while in this state.
Next state:
|
protected |
Waits for Particle.disconnected() to be true.
Once the cloud is disconnected, calls either Cellular.disconnect() or WiFi.disconnect().
Next state:
|
protected |
Called on quick wake.
Stays in this state until data capture is completed and all noConnectionFunctions return false.
Previous state:
Next state:
|
protected |
Waits so publishes only occur once per second.
Next state:
|
protected |
Wait for a publish to complete.
The state transition occurs from the background publish lambda implemented in stateHandlerConnected.
Previous state:
Next state:
|
protected |
If the cloud connection is lost, waits here.
Next state:
|
protected |
Handles sleep.
Next state:
|
protected |
Handles wake operations.
Next state:
|
protected |
Handles sleep periods less than minimumSleepTimeMs (default: 10 seconds) without actually sleeping.
Next state:
|
protected |
Initial state at boot or after sleep.
Next state:
|
protected |
Wait for time synchronization from the cloud. This normally occurs very quickly (under 1 second).
Next state:
|
protected |
Waits for Cellular.ready or WiFi.ready to be false.
Once disconnected, calls Cellular.off() or WiFi.off()
Next state:
|
protected |
Waits until Cellular.isOff or WiFi.isOff to be true.
Next state:
|
protected |
A system event handler is so the code can be notified of things like firmware update started.
event | system event code (uint64_t) |
param | data depending on the event code |
|
staticprotected |
A system event handler is so the code can be notified of things like firmware update started.
event | system event code (uint64_t) |
param | data depending on the event code |
The Device OS API doesn't take a class member and instance so this static function is used instead. Since the SleepHelper is a singleton, this is easy.
|
inline |
Stop and resume an AB1805 watchdog before sleep and reset.
ab1805 | A reference to the AB1805 object from the AB1805_RK library |
You must include AB1805_RK.h before SleepHelper.h to enable this method!
|
inline |
Disable an eventsEnable flag. These determine whether the add values to the wake event.
flag | Flag bit value to clear, such as eventsEnabledWakeReason. Can pass multiple flags bits to this function. |
|
inline |
Enable an eventsEnable flag. These determine whether the add values to the wake event.
flag | Flag bit value such as eventsEnabledWakeReason. Can pass multiple flags bits to this function. |
|
inline |
Disable logging for a specific type of log.
flag | The flag bit such as logEnabledPublish. Can specify multiple flags logically ORed together. |
|
inline |
Enable logging for a specific type of log.
flag | The flag bit such as logEnabledPublish. Can specify multiple flags logically ORed together. |
|
inline |
Sets the maximum time to connect to the cloud. If this limit is exceeded, the device will go to sleep.
timeMs | Time as a chrono literal, such as 5min for 5 minutes. |
Ideally this should be at least 11 minutes. If you need to conserve power you can set it as low as 5 minutes or so, however only do so if you use a sleep mode that will completely power down the modem. Otherwise, it's possible that then modem will never be fully reset.
|
inline |
Sets the maximum time to connect to the cloud. If this limit is exceeded, the device will go to sleep.
timeMs | Time in milliseconds |
Ideally this should be at least 11 minutes. If you need to conserve power you can set it as low as 5 minutes or so, however only do so if you use a sleep mode that will completely power down the modem. Otherwise, it's possible that then modem will never be fully reset.
|
inline |
Sets the minimum time to disconnect from cellular. Default: 13 minutes.
timeMs |
You can set this lower than 13 minutes, but beware of aggressive reconnection behavior.
|
inline |
Set the minimum amount of time to stay connected to the cloud (optional)
timeMs | Time as a chrono literal, such as 30s for 30 seconds. |
|
inline |
Set the minimum amount of time to stay connected to the cloud (optional)
timeMs | Time in milliseconds. There is also an overload that takes a chrono literal. |
|
inline |
Sets the minimum time to sleep. Default is 10 seconds.
timeMs |
If the time to sleep is less than that, we stay awake until the event occurs.
|
inline |
Connect the PublishQueuePosixRK library with this library.
maxTimeToPublish | The maximum time to allow PublishQueuePosixRK publishes before forcing sleep with unsent events. Default: send all queued events |
You must include PublishQueuePosixRK.h before SleepHelper.h to enable this method!
|
inline |
Require a minimum battery SoC to connect to cellular.
minSoC | The minimum required in the range of 0.0 to 100.0 |
conviction | The noConnect conviction level to use. If this is greater than the connection conviction form other should connect functions, then connection will be prevented. Default: 100 |
|
inline |
Sets the sleep enabled flag.
sleepEnabled |
The default is true (sleep is allowed). You can set it to false to prevent sleep.
|
inline |
Sets the time configuration string for local time calculations.
tzConfig | Timezone and daylight saving settings, POSIX timezone rule string |
If you do not call this, all time calculation will be done at UTC.
For the United States east coast, the configuration string is:
What this means is:
Some examples:
Location | Timezone Configuration |
---|---|
New York | "EST5EDT,M3.2.0/02:00:00,M11.1.0/02:00:00" |
Chicago | "CST6CDT,M3.2.0/2:00:00,M11.1.0/2:00:00" |
Denver | "MST7MDT,M3.2.0/2:00:00,M11.1.0/2:00:00" |
Phoenix | "MST7" |
Los Angeles | "PST8PDT,M3.2.0/2:00:00,M11.1.0/2:00:00" |
London | "BST0GMT,M3.5.0/1:00:00,M10.5.0/2:00:00" |
Sydney, Australia | "AEST-10AEDT,M10.1.0/02:00:00,M4.1.0/03:00:00" |
Adelaide, Australia | "ACST-9:30ACDT,M10.1.0/02:00:00,M4.1.0/03:00:00" |
|
inline |
Set the event name used for the wake event. Default: sleepHelper.
eventName |
|
staticprotected |
Singleton instance of this class.
The object pointer to this class is stored here. It's NULL at system boot.
|
protected |
Used instead of Cellular.ready(), etc.
Logger instance used by SleepHelper
All logging messages use the category app.sleep so you can control the level in your log handler instances.
Within this library, always use appLog.info() instead of Log.info(), for example.
|
protected |
True if data capture handlers are being called.
This goes true right before they are called and will remain true until the last one returns false. At this point, sleep can occur.
|
protected |
Which event history events are enabled (default: all)
See constants such as eventsEnabledWakeReason, eventsEnabledTimeToConnect for flag values
|
protected |
Which logging messages to enable.
Default: logEnabledNormal