73 lines
include/power_state_machine.h
Declares PowerState enum, IPersistence interface, and PowerStateMachine.
// PowerStateMachine: manages device power transitions with durable state.
#pragma once
#include <cstdint>
 
// Device power states.
enum class PowerState : uint8_t {
  OFF       = 0,
  STANDBY   = 1,
  ACTIVE    = 2,
  HIBERNATE = 3,
};
 
// Abstract persistence backend for the current power state.
class IPersistence {
public:
  virtual ~IPersistence() = default;
  // Writes one byte to non-volatile storage.
  // Parameters:
  //   value - byte to persist
  // Returns: true on success; false on I/O or storage error
  virtual bool write(uint8_t value) = 0;
  // Reads one byte from non-volatile storage.
  // Parameters:
  //   value - reference filled with the stored byte
  // Returns: true on success; false if storage is unavailable or empty
  virtual bool read(uint8_t& value) = 0;
};
 
// Manages device power transitions according to a defined state graph.
//
// Valid transitions (all others are illegal):
//   OFF       -> STANDBY
//   STANDBY   -> ACTIVE, OFF
//   ACTIVE    -> STANDBY, HIBERNATE
//   HIBERNATE -> OFF
//   Note: HIBERNATE -> STANDBY is not a valid direct transition.
//         The required sequence is HIBERNATE -> OFF -> STANDBY.
//
class PowerStateMachine {
public:
  // Parameters:
  //   initial     - starting state for a fresh instance (before loadState is called)
  //   persistence - storage backend used by loadState() and transition()
  PowerStateMachine(PowerState initial, IPersistence* persistence);
 
  // Attempts to transition to newState.
  // The new state is persisted before the in-memory state is updated.
  // If persist fails, the in-memory state must remain at the current value.
  // Parameters:
  //   newState - target power state
  // Returns: true if the transition is valid and the persist succeeded; false otherwise
  bool transition(PowerState newState);
 
  // Loads the persisted state from storage and installs it as the current state.
  // The raw byte from storage must be validated as a known PowerState value.
  // Parameters: none
  // Returns: true if a valid state was loaded; false if storage failed or value is unrecognised
  bool loadState();
 
  // Returns the current in-memory power state.
  PowerState currentState() const { return current_; }
 
private:
  PowerState    current_;    // current in-memory power state
  IPersistence* persistence_;
 
  // Returns true if transitioning from 'from' to 'to' is permitted.
  // Parameters:
  //   from - source state
  //   to   - target state
  // Returns: true if the transition is in the allowed graph
  bool isValidTransition(PowerState from, PowerState to) const;
};