SleepHelper
Data Structures | Public Member Functions | Static Public Member Functions | Data Fields | Static Public Attributes | Protected Member Functions | Static Protected Member Functions | Protected Attributes | Static Protected Attributes
SleepHelper Class Reference

#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

SleepHelperwithSleepConfigurationFunction (std::function< bool(SystemSleepConfiguration &, SleepConfigurationParameters &)> fn)
 Register a function to be called to configure sleep. More...
 
SleepHelperwithWakeFunction (std::function< bool(const SystemSleepResult &)> fn)
 Register a function to be called on wake from sleep. More...
 
SleepHelperwithMinimumCellularOffTime (std::chrono::milliseconds timeMs)
 Sets the minimum time to disconnect from cellular. Default: 13 minutes. More...
 
SleepHelperwithMinimumSleepTimeMs (std::chrono::milliseconds timeMs)
 Sets the minimum time to sleep. Default is 10 seconds. More...
 
SleepHelperwithSetupFunction (std::function< bool()> fn)
 Adds a function to be called during setup() More...
 
SleepHelperwithLoopFunction (std::function< bool()> fn)
 Adds a function to be called on every call to loop() More...
 
SleepHelperwithDataCaptureFunction (std::function< bool(AppCallbackState &state)> fn)
 The data capture function is called on a schedule to capture data. More...
 
SleepHelperwithSleepReadyFunction (std::function< bool(AppCallbackState &, system_tick_t)> fn)
 Determine if it's OK to sleep now, when in connected state. More...
 
SleepHelperwithShouldConnectFunction (std::function< bool(int &connectConviction, int &noConnectConviction)> fn)
 Function to call to determine if a full wake should be done. More...
 
SleepHelperwithWakeOrBootFunction (std::function< bool(int)> fn)
 Called during setup, after sleep, or an aborted sleep because duration was too short. More...
 
SleepHelperwithWakeEventName (const char *eventName)
 Set the event name used for the wake event. Default: sleepHelper. More...
 
SleepHelperwithSleepOrResetFunction (std::function< bool(bool)> fn)
 Adds a function to be called right before sleep or reset. More...
 
SleepHelperwithMaximumTimeToConnectFunction (std::function< bool(system_tick_t ms)> fn)
 Adds a function to be called while connecting. More...
 
SleepHelperwithMaximumTimeToConnect (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...
 
SleepHelperwithMaximumTimeToConnect (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...
 
SleepHelperwithNoConnectionFunction (std::function< bool(AppCallbackState &state)> fn)
 Register a callback for when in the no connection state. More...
 
SleepHelperwithMinimumConnectedTime (system_tick_t timeMs)
 Set the minimum amount of time to stay connected to the cloud (optional) More...
 
SleepHelperwithMinimumConnectedTime (std::chrono::milliseconds timeMs)
 Set the minimum amount of time to stay connected to the cloud (optional) More...
 
SleepHelperwithShouldConnectMinimumSoC (float minSoC, int conviction=100)
 Require a minimum battery SoC to connect to cellular. More...
 
SleepHelperwithAB1805_WDT (AB1805 &ab1805)
 Stop and resume an AB1805 watchdog before sleep and reset. More...
 
SleepHelperwithPublishQueuePosixRK (std::chrono::milliseconds maxTimeToPublish=0ms)
 Connect the PublishQueuePosixRK library with this library. More...
 
SleepHelperwithTimeConfig (const char *tzConfig)
 Sets the time configuration string for local time calculations. More...
 
SleepHelperwithEventsEnabledEnable (uint64_t flag)
 Enable an eventsEnable flag. These determine whether the add values to the wake event. More...
 
SleepHelperwithEventsEnabledDisable (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...
 
SleepHelperwithLogEnabledEnable (uint64_t flag)
 Enable logging for a specific type of log. More...
 
SleepHelperwithLogEnabledDisable (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...
 
SleepHelperwithSleepEnabled (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 SleepHelperinstance ()
 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
 
SleepHelperoperator= (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< PublishDatapublishData
 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...
 

Detailed Description

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();

Constructor & Destructor Documentation

◆ SleepHelper() [1/2]

SleepHelper::SleepHelper ( )
protected

The constructor is protected because the class is a singleton.

Use SleepHelper::instance() to instantiate the singleton.

◆ SleepHelper() [2/2]

SleepHelper::SleepHelper ( const SleepHelper )
protecteddelete

This class is a singleton and cannot be copied

Member Function Documentation

◆ calculateSleepSettings()

void SleepHelper::calculateSleepSettings ( bool  isConnected)
protected

Calculate sleep settings.

Parameters
isConnectedTrue 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.

◆ dataCaptureHandler()

void SleepHelper::dataCaptureHandler ( )
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.

◆ eventsEnableEnabled()

bool SleepHelper::eventsEnableEnabled ( uint64_t  flag) const
inline

Returns true if the eventsEnable flag is set.

Parameters
flagFlag bit value to test, such as eventsEnabledWakeReason
Returns
true
false

◆ eventsEnableName()

const char * SleepHelper::eventsEnableName ( uint64_t  flag)
static

Returns the event name (const c-string) for a given flag.

Parameters
flagFlag bit to get the priority for, such as eventsEnabledWakeReason
Returns
const char * event name, or empty string if an invalid flag name

◆ eventsEnablePriority()

int SleepHelper::eventsEnablePriority ( uint64_t  flag)
static

Returns the priority value (0 - 100) for a given flag.

Parameters
flagFlag bit to get the priority for, such as eventsEnabledWakeReason
Returns
int Priority value. Returns 0 for an invalid flag bit.

◆ getScheduleDataCapture()

LocalTimeSchedule & SleepHelper::getScheduleDataCapture ( )
inline

The data capture schedule determines when to call the data capture callback.

Returns
LocalTimeSchedule&

◆ getScheduleFull()

LocalTimeSchedule & SleepHelper::getScheduleFull ( )
inline

Get the full wake schedule.

Returns
LocalTimeSchedule&

◆ getScheduleQuick()

LocalTimeSchedule & SleepHelper::getScheduleQuick ( )
inline

Get the quick wake schedule.

Returns
LocalTimeSchedule&

◆ getSleepEnabled()

bool SleepHelper::getSleepEnabled ( ) const
inline

Get the sleep enabled flag value. Default is true.

Returns
true
false

◆ instance()

SleepHelper & SleepHelper::instance ( )
static

Gets the singleton instance of this class, allocating it if necessary.

Use SleepHelper::instance() to instantiate the singleton.

◆ JSONCopy() [1/2]

void SleepHelper::JSONCopy ( const char *  src,
JSONWriter &  writer 
)
static

Copies pre-formatted JSON into a writer.

Parameters
srcMust 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.

◆ JSONCopy() [2/2]

void SleepHelper::JSONCopy ( const JSONValue &  src,
JSONWriter &  writer 
)
static

Copies pre-formatted JSON into a writer.

Parameters
srcMust 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.

◆ logEnableEnabled()

bool SleepHelper::logEnableEnabled ( uint64_t  flag) const
inline

Returns true if the specified logging flag is set.

Parameters
flagThe flag bit such as logEnabledPublish.
Returns
true Logging enabled for this flag
false Logging disabled for this flag

◆ loop()

void SleepHelper::loop ( )

Perform application loop operations; call this from global application loop()

You typically use SleepHelper::instance().loop();

◆ operator=()

SleepHelper & SleepHelper::operator= ( const SleepHelper )
protecteddelete

This class is a singleton and cannot be copied

◆ setup()

void SleepHelper::setup ( )

Perform setup operations; call this from global application setup()

You typically use SleepHelper::instance().setup();

◆ stateHandlerConnected()

void SleepHelper::stateHandlerConnected ( )
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:

  • stateHandlerPublishWait if a publish is in progress
  • stateHandlerPublishRateLimit if a publish was successful and we need to wait before publishing more data
  • stateHandlerConnected stays in state if a publish failed
  • stateHandlerDisconnectBeforeSleep all data has been published and sleep ready function indicate time to sleep
  • stateHandlerReconnectWait if the cloud connection is lost

◆ stateHandlerConnectedStart()

void SleepHelper::stateHandlerConnectedStart ( )
protected

Handles things after connecting to the cloud on a full wake.

Steps include:

  • Recording the full wake time in the persistent data file
  • Storing the time to connect (ttc) wake event data (if enabled)
  • Storing the battery SoC (soc) wake event data (if enabled)

Next state:

  • stateHandlerConnectedWakeEvents

◆ stateHandlerConnectedWakeEvents()

void SleepHelper::stateHandlerConnectedWakeEvents ( )
protected

Prepares wake event data.

  • Waits for data capture to complete (should normally be done by now)
  • Set the sleepReady state handler states to start
  • Generate event payload from event history and wake events

Next state:

  • stateHandlerConnected

◆ stateHandlerConnectWait()

void SleepHelper::stateHandlerConnectWait ( )
protected

Waits for the Particle cloud connection to be made.

Previous state:

  • stateHandlerStart Cloud connections is started in stateHandlerStart.

Next state:

  • stateHandlerTimeValidWait Connected to the cloud, waiting for a valid RTC
  • stateHandlerDisconnectBeforeSleep Took too long to connect to the cloud, go into sleep mode instead

◆ stateHandlerDisconnectBeforeSleep()

void SleepHelper::stateHandlerDisconnectBeforeSleep ( )
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:

  • stateHandlerSleep Sleep with cellular one
  • stateHandlerDisconnectWait Wait for Cellular.disconnect to complete

◆ stateHandlerDisconnectWait()

void SleepHelper::stateHandlerDisconnectWait ( )
protected

Waits for Particle.disconnected() to be true.

Once the cloud is disconnected, calls either Cellular.disconnect() or WiFi.disconnect().

Next state:

  • stateHandlerWaitCellularDisconnected

◆ stateHandlerNoConnection()

void SleepHelper::stateHandlerNoConnection ( )
protected

Called on quick wake.

Stays in this state until data capture is completed and all noConnectionFunctions return false.

Previous state:

  • stateHandlerStart

Next state:

  • stateHandlerSleep

◆ stateHandlerPublishRateLimit()

void SleepHelper::stateHandlerPublishRateLimit ( )
protected

Waits so publishes only occur once per second.

Next state:

  • stateHandlerConnected

◆ stateHandlerPublishWait()

void SleepHelper::stateHandlerPublishWait ( )
protected

Wait for a publish to complete.

The state transition occurs from the background publish lambda implemented in stateHandlerConnected.

Previous state:

  • stateHandlerConnected

Next state:

  • stateHandlerPublishRateLimit

◆ stateHandlerReconnectWait()

void SleepHelper::stateHandlerReconnectWait ( )
protected

If the cloud connection is lost, waits here.

Next state:

  • stateHandlerConnected Successfully reconnected to the cloud
  • stateHandlerDisconnectBeforeSleep Timed out reconnecting to the cloud

◆ stateHandlerSleep()

void SleepHelper::stateHandlerSleep ( )
protected

Handles sleep.

  • Calls sleepOrResetFunctions
  • Adjust sleep time to account for the time to disconnect from the cloud and cellular (could be a couple seconds)
  • Uses System.sleep to sleep
  • Records the wakeup reason after wake

Next state:

  • stateHandlerSleepDone We've woken up
  • stateHandlerSleepShort After adjusting sleep duration, the duration was too short so not sleeping at all

◆ stateHandlerSleepDone()

void SleepHelper::stateHandlerSleepDone ( )
protected

Handles wake operations.

  • Calls wakeOrBootFunctions
  • Records the wake reason (wr) in the wake event

Next state:

  • stateHandlerStart

◆ stateHandlerSleepShort()

void SleepHelper::stateHandlerSleepShort ( )
protected

Handles sleep periods less than minimumSleepTimeMs (default: 10 seconds) without actually sleeping.

Next state:

  • stateHandlerSleepDone

◆ stateHandlerStart()

void SleepHelper::stateHandlerStart ( )
protected

Initial state at boot or after sleep.

Next state:

  • stateHandlerNoConnection if a quick wake cycle
  • stateHandlerConnectWait if a full wake cycle (cloud connection started before going into this state)

◆ stateHandlerTimeValidWait()

void SleepHelper::stateHandlerTimeValidWait ( )
protected

Wait for time synchronization from the cloud. This normally occurs very quickly (under 1 second).

Next state:

  • stateHandlerConnectedStart

◆ stateHandlerWaitCellularDisconnected()

void SleepHelper::stateHandlerWaitCellularDisconnected ( )
protected

Waits for Cellular.ready or WiFi.ready to be false.

Once disconnected, calls Cellular.off() or WiFi.off()

Next state:

  • stateHandlerWaitCellularOff

◆ stateHandlerWaitCellularOff()

void SleepHelper::stateHandlerWaitCellularOff ( )
protected

Waits until Cellular.isOff or WiFi.isOff to be true.

Next state:

  • stateHandlerSleep

◆ systemEventHandler()

void SleepHelper::systemEventHandler ( system_event_t  event,
int  param 
)
protected

A system event handler is so the code can be notified of things like firmware update started.

Parameters
eventsystem event code (uint64_t)
paramdata depending on the event code

◆ systemEventHandlerStatic()

void SleepHelper::systemEventHandlerStatic ( system_event_t  event,
int  param 
)
staticprotected

A system event handler is so the code can be notified of things like firmware update started.

Parameters
eventsystem event code (uint64_t)
paramdata 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.

◆ withAB1805_WDT()

SleepHelper & SleepHelper::withAB1805_WDT ( AB1805 &  ab1805)
inline

Stop and resume an AB1805 watchdog before sleep and reset.

Parameters
ab1805A reference to the AB1805 object from the AB1805_RK library
Returns
SleepHelper&

You must include AB1805_RK.h before SleepHelper.h to enable this method!

◆ withEventsEnabledDisable()

SleepHelper & SleepHelper::withEventsEnabledDisable ( uint64_t  flag)
inline

Disable an eventsEnable flag. These determine whether the add values to the wake event.

Parameters
flagFlag bit value to clear, such as eventsEnabledWakeReason. Can pass multiple flags bits to this function.
Returns
SleepHelper&

◆ withEventsEnabledEnable()

SleepHelper & SleepHelper::withEventsEnabledEnable ( uint64_t  flag)
inline

Enable an eventsEnable flag. These determine whether the add values to the wake event.

Parameters
flagFlag bit value such as eventsEnabledWakeReason. Can pass multiple flags bits to this function.
Returns
SleepHelper&

◆ withLogEnabledDisable()

SleepHelper & SleepHelper::withLogEnabledDisable ( uint64_t  flag)
inline

Disable logging for a specific type of log.

Parameters
flagThe flag bit such as logEnabledPublish. Can specify multiple flags logically ORed together.
Returns
SleepHelper&

◆ withLogEnabledEnable()

SleepHelper & SleepHelper::withLogEnabledEnable ( uint64_t  flag)
inline

Enable logging for a specific type of log.

Parameters
flagThe flag bit such as logEnabledPublish. Can specify multiple flags logically ORed together.
Returns
SleepHelper&

◆ withMaximumTimeToConnect() [1/2]

SleepHelper & SleepHelper::withMaximumTimeToConnect ( std::chrono::milliseconds  timeMs)
inline

Sets the maximum time to connect to the cloud. If this limit is exceeded, the device will go to sleep.

Parameters
timeMsTime as a chrono literal, such as 5min for 5 minutes.
Returns
SleepHelper&

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.

◆ withMaximumTimeToConnect() [2/2]

SleepHelper & SleepHelper::withMaximumTimeToConnect ( system_tick_t  timeMs)
inline

Sets the maximum time to connect to the cloud. If this limit is exceeded, the device will go to sleep.

Parameters
timeMsTime in milliseconds
Returns
SleepHelper&

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.

◆ withMinimumCellularOffTime()

SleepHelper & SleepHelper::withMinimumCellularOffTime ( std::chrono::milliseconds  timeMs)
inline

Sets the minimum time to disconnect from cellular. Default: 13 minutes.

Parameters
timeMs
Returns
SleepHelper&

You can set this lower than 13 minutes, but beware of aggressive reconnection behavior.

◆ withMinimumConnectedTime() [1/2]

SleepHelper & SleepHelper::withMinimumConnectedTime ( std::chrono::milliseconds  timeMs)
inline

Set the minimum amount of time to stay connected to the cloud (optional)

Parameters
timeMsTime as a chrono literal, such as 30s for 30 seconds.
Returns
SleepHelper&

◆ withMinimumConnectedTime() [2/2]

SleepHelper & SleepHelper::withMinimumConnectedTime ( system_tick_t  timeMs)
inline

Set the minimum amount of time to stay connected to the cloud (optional)

Parameters
timeMsTime in milliseconds. There is also an overload that takes a chrono literal.
Returns
SleepHelper&

◆ withMinimumSleepTimeMs()

SleepHelper & SleepHelper::withMinimumSleepTimeMs ( std::chrono::milliseconds  timeMs)
inline

Sets the minimum time to sleep. Default is 10 seconds.

Parameters
timeMs
Returns
SleepHelper&

If the time to sleep is less than that, we stay awake until the event occurs.

◆ withPublishQueuePosixRK()

SleepHelper & SleepHelper::withPublishQueuePosixRK ( std::chrono::milliseconds  maxTimeToPublish = 0ms)
inline

Connect the PublishQueuePosixRK library with this library.

Parameters
maxTimeToPublishThe maximum time to allow PublishQueuePosixRK publishes before forcing sleep with unsent events. Default: send all queued events
Returns
SleepHelper&

You must include PublishQueuePosixRK.h before SleepHelper.h to enable this method!

◆ withShouldConnectMinimumSoC()

SleepHelper & SleepHelper::withShouldConnectMinimumSoC ( float  minSoC,
int  conviction = 100 
)
inline

Require a minimum battery SoC to connect to cellular.

Parameters
minSoCThe minimum required in the range of 0.0 to 100.0
convictionThe 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
Returns
SleepHelper&

◆ withSleepEnabled()

SleepHelper & SleepHelper::withSleepEnabled ( bool  sleepEnabled)
inline

Sets the sleep enabled flag.

Parameters
sleepEnabled
Returns
SleepHelper&

The default is true (sleep is allowed). You can set it to false to prevent sleep.

◆ withTimeConfig()

SleepHelper & SleepHelper::withTimeConfig ( const char *  tzConfig)
inline

Sets the time configuration string for local time calculations.

Parameters
tzConfigTimezone and daylight saving settings, POSIX timezone rule string
Returns
SleepHelper&

If you do not call this, all time calculation will be done at UTC.

For the United States east coast, the configuration string is:

EST5EDT,M3.2.0/2:00:00,M11.1.0/2:00:00"

What this means is:

  • "EST" is the standard time timezone name
  • 5 is the offset from UTC in hours. Actually -5, as the sign is backwards from the way it's normally expressed. And it could be hours and minutes.
  • "EDT" is the daylight saving time timezone name
  • "M3.2.0" is when DST starts. Month 3 (March), 2nd week, 0 = Sunday
  • "2:00:00" transition to DST at 2:00 AM local time
  • "M11.1.0" transition back to standard time November, 1st week, on Sunday
  • "2:00:00" transition back to standard time at 2:00 AM local time

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"

◆ withWakeEventName()

SleepHelper & SleepHelper::withWakeEventName ( const char *  eventName)
inline

Set the event name used for the wake event. Default: sleepHelper.

Parameters
eventName
Returns
SleepHelper&

Field Documentation

◆ _instance

SleepHelper * SleepHelper::_instance
staticprotected

Singleton instance of this class.

The object pointer to this class is stored here. It's NULL at system boot.

◆ appLog

Logger SleepHelper::appLog
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.

◆ dataCaptureActive

bool SleepHelper::dataCaptureActive = false
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.

◆ eventsEnabled

uint64_t SleepHelper::eventsEnabled = 0xfffffffffffffffful
protected

Which event history events are enabled (default: all)

See constants such as eventsEnabledWakeReason, eventsEnabledTimeToConnect for flag values

◆ logEnabled

uint64_t SleepHelper::logEnabled = logEnabledNormal
protected

Which logging messages to enable.

Default: logEnabledNormal


The documentation for this class was generated from the following files: