Docs / Modules / Reference
Reference
This is a compact map of the current public surface.
For behavior and rationale, use the dedicated module/protocol pages. For exact declarations, the source remains authoritative.
Umbrella headers#
#include <NightMare.h>
Compatibility umbrella:
#include <NightMareNetwork.h>
The latter currently includes NightMare.h.
Config-only include:
#include <NightMare/Config.h>
Config#
Supported types are the built-in NetCodec<T> types: bool, integral types,
floating-point types, std::string, TimeType, and ColourType.
template <typename T>
class Config
{
public:
using WriteRequestHandler =
bool (*)(Config<T> &config, const T &requested);
Config(
const std::string &name,
const T &defaultValue,
bool requireReboot = false);
WriteRequestHandler onWrite;
const T &value() const;
bool set(const T &value);
};
The firmware default is required and becomes the runtime value at construction.
Construction also registers the object with configManager(); destruction
unregisters it. Reboot metadata is the third argument, which keeps
Config<bool> unambiguous. A successful startup restore replaces the default
with a valid saved value.
ConfigManager invokes onWrite with the decoded proposed value after the
optional global change handler and before committing. Returning false
rejects the write. Direct local set() calls bypass both ingress handlers.
Both paths persist before changing the runtime value and fail without changing
that value if storage cannot be updated.
Metadata available through ConfigBase:
const std::string &name() const;
bool requiresReboot() const;
NetValueType type() const;
Manager and handler:
using ConfigChangeHandler =
bool (*)(const std::string &key, const std::string &value);
ConfigManager &configManager();
bool bind(ConfigBase *config);
bool unbind(ConfigBase *config);
bool restore();
bool restored() const;
std::string handle(const std::string &command);
void setChangeHandler(ConfigChangeHandler handler);
bool buildManifestMsgPack(uint8_t *buffer, size_t capacity, size_t &written) const;
std::string buildManifestBase64() const;
bind() and unbind() remain available for explicit runtime use and retain
their duplicate pointer/name and capacity checks. restore() initializes the
settings backend, restores all currently bound Configs, and is idempotent after
success. A Config bound after successful restoration is restored individually
before bind() returns; registration is rolled back if that initialization
cannot complete.
handle("list") returns JSON objects with name, type, require_reboot,
and value. value is the Config's current canonical NetCodec<T> std::string
encoding. The binary manifest remains declaration-only.
Limits and manifest versions:
ConfigManagerMaxConfigs = 64
ConfigManifestEncodingVersion = 1
ConfigManifestVersion = 1
The binary manifest is [encodingVersion, manifestVersion, configs[]]; each
entry is [name, NetValueType, requireReboot]. handle("manifest") returns
Base64 of those exact MessagePack bytes.
Config persistence uses reserved _config:<name> keys in
PersistentSettings and canonical NetCodec<T> text. This storage mapping is
an implementation detail and does not add a manifest field or version change.
NM_ENABLE_SETTINGS=0 is rejected at compile time because Config<T> is
always persistent. Local set() rejects values whose encoded representation
cannot be decoded again.
DeviceIdentity#
Global:
extern DeviceIdentity gDeviceIdentity;
Main methods:
bool begin();
const std::string &getDeviceName();
const std::string &getDeviceId();
const std::string &getHardwareSignature();
const std::string &getTimezone();
bool isDevice(const std::string &topic);
bool relativeTopic(const std::string &topic, std::string &relative);
std::string topic(const std::string &relative);
void lockAddress();
static bool validDeviceName(const std::string &name);
static bool validTimezone(const std::string &timezone);
bool setTimezone(const std::string &timezone);
bool beginAdoption(const std::string &newName);
bool hasPendingIdentityCleanup();
bool getPendingIdentityCleanup(PendingIdentityCleanup &cleanup);
bool markIdentityCleanupComplete(IdentityCleanupFlags flag);
Cleanup flags:
CLEANUP_RESOURCES
CLEANUP_STATUS
Resource types#
Base model:
NetResource
NetValueResource
NetValue<T>
NetActionResource
NetEventResource
NetEvent<T>
Normal application wrappers:
ManagedSensor<T>
RemoteSensor<T>
ManagedState<T>
RemoteState<T>
ManagedAction
RemoteAction
ManagedEvent<T>
RemoteEvent<T>
Kinds (NetResource::kind()), appended and never renumbered. The numbers are the
leading kind element of the compact manifests:
enum class NetResourceType : uint8_t
{
VALUE, // 0
ACTION, // 1
EVENT // 2
};
Roles:
enum class ResourceRole
{
MANAGED,
REMOTE
};
Access:
enum class AccessPolicy
{
READ,
READ_WRITE
};
Freshness:
enum class ResourceFreshness
{
UNKNOWN,
FRESH,
STALE
};
Remote synchronization:
enum class NetSyncStrategy
{
OPTIMISTIC,
STRICT
};
Authoritative value mirroring (one per Sensor, last call wins):
ManagedSensor<T> &dependsOn(NetValueResource &source);
Read back from any Value:
const NetValueResource *dependency() const;
NetValue<T>#
Common Value metadata:
NetValueType type() const;
bool available() const;
ResourceFreshness freshness() const;
uint32_t lastUpdateMs() const;
const NetValueResource *dependency() const;
ManagedSensor and ManagedState expose:
const T &getValue() const;
bool setValue(const T &value);
bool setAvailable(bool available);
bool setHardwarePolicy(const HardwarePolicy &policy);
int32_t hardwarePollMs() const;
bool hardwareEnabled() const;
bool setHardwareConnected(bool connected);
bool hardwareConnected() const;
RemoteSensor and RemoteState expose getValue(), hasValue(), and isStale();
RemoteState also exposes setValue().
Hardware declarations and Resource limits:
enum HardwarePolicyFlag : uint8_t {
REPORT_HW_CONNECTION = 1 << 0,
CONFIGURABLE_POLL = 1 << 1,
CAN_DISABLE = 1 << 2,
};
struct HardwarePolicy {
int32_t pollMs = 0;
uint8_t flags = 0;
std::string note;
};
NetResourceHardwareNoteMaxLength = 64
NetResourceDefaultAdvertisementPeriodMs = 300000
NetResourceAdvertisementDisabled = -1
NetResourceAdvertisementRetryMs = 1000
NetResourceManifestRetryMs = 1000
Advertisement policy is manager-owned and intentionally absent from the public Resource API.
Remote Value source selection#
RemoteSensor and RemoteState expose:
bool setSource(
const std::string &deviceName,
const std::string &resourceName);
bool clearSource();
The constructor taking one std::string declares the stable local name. Sources are
stored by that name in /remoteresources.json and restored by
startNightMareESP() before networking starts.
ManagedState<T>#
Handler:
using WriteRequestHandler =
bool (*)(ManagedState<T> &state, const T &requested);
Field:
WriteRequestHandler onWrite;
Returning true accepts the requested value as authoritative state.
NetValueType#
Wire taxonomy:
enum class NetValueType : uint8_t
{
STRING,
BOOLEAN,
INTEGER,
FLOAT,
STRUCT,
TIME,
COLOUR
};
Built-in NetCodec<T> support:
std::string
bool
integral types except bool
floating-point types
TimeType
ColourType
TimeType API:
TimeType();
TimeType(uint8_t hour, uint8_t minute, uint8_t second = 0);
uint8_t hour() const;
uint8_t minute() const;
uint8_t second() const;
std::string toString() const;
Out-of-range constructor components produce 00:00:00; decodeTime() instead
reports failure and leaves its output unchanged.
ColourType stores 0xRRGGBBAA and exposes:
ColourType();
explicit ColourType(uint32_t value);
ColourType(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255);
uint32_t rawValue() const;
NightMare::RGB toRGB() const;
NightMare::RGBA toRGBA() const;
NightMare::HSV toHSV() const;
static ColourType fromHSV(const NightMare::HSV &hsv);
The RGB, RGBA, and HSV component structs belong to the NightMare
namespace.
Action metadata#
struct ActionArgMetadata
{
const char *name;
NetValueType type;
bool required;
};
Constructor:
ActionArgMetadata(
const char *argName,
NetValueType argType,
bool argRequired = true);
ActionResult#
struct ActionResult
{
bool success;
std::string result;
};
ManagedAction#
Constructors:
ManagedAction(const std::string &resourceName);
template <size_t N>
ManagedAction(
const std::string &resourceName,
const ActionArgMetadata (&args)[N]);
ManagedAction(
const std::string &resourceName,
const ActionArgMetadata *args,
size_t argCount);
Handler:
using Handler =
ActionResult (*)(ManagedAction &action, const std::string &payload);
Handler onInvoke;
Execution:
ActionResult execute(const std::string &payload) override;
RemoteAction#
Common constructors:
RemoteAction(const std::string &localName);
RemoteAction(
const std::string &resourceName,
const NetDeviceIdentity &owner);
template <size_t N>
RemoteAction(
const std::string &resourceName,
const NetDeviceIdentity &owner,
const ActionArgMetadata (&args)[N]);
It also has pointer/count forms for an expected schema.
Methods:
bool setSource(
const std::string &deviceName,
const std::string &resourceName);
bool clearSource();
bool invoke(const std::string &payload = std::string());
NetEvent<T>#
NetEventResource is the non-template boundary and does not derive from
NetValueResource. It holds the payload wire type and one timestamp:
uint32_t lastUpdateMs() const;
NetEvent<T> is a non-instantiable implementation base that applies
NetCodec<T> at the wire boundary. The two leaf types below are the application
API; an Event has no current value, availability, freshness, advertisement,
hardware policy, dependency, write or invoke path, so those members are absent
rather than present and rejected.
ManagedEvent<T>#
template <typename T>
class ManagedEvent
{
public:
explicit ManagedEvent(const std::string &resourceName);
using EventHandler =
void (*)(ManagedEvent<T> &event, const T &payload);
EventHandler onEvent = nullptr;
bool fire(const T &payload);
uint32_t lastUpdateMs() const;
};
fire() publishes <device>/resource/<name>/event with retain false. It
returns true only when the connection accepted the publication; it returns
false when unbound, when the payload encodes to an empty or over-2048-byte
std::string, or when publication is refused. Equal payloads are separate occurrences.
onEvent is a local listener: fire() calls it once for every valid occurrence
after attempting the publication, whatever the publication's outcome and even
while unbound. A payload that cannot be encoded is not an occurrence and does not
call it. It runs synchronously inside fire().
lastUpdateMs() is the millis() timestamp of the latest occurrence the
transport accepted, or 0 before the first.
RemoteEvent<T>#
template <typename T>
class RemoteEvent
{
public:
explicit RemoteEvent(const std::string &localName);
RemoteEvent(
const std::string &resourceName,
const NetDeviceIdentity &owner);
using EventHandler =
void (*)(RemoteEvent<T> &event, const T &payload);
EventHandler onEvent = nullptr;
uint32_t lastUpdateMs() const;
bool setSource(
const std::string &deviceName,
const std::string &resourceName);
bool clearSource();
};
onEvent is called once for every valid live occurrence, including consecutive
identical payloads. A malformed payload neither calls it nor changes
lastUpdateMs(). The payload is not retained and there is no getValue(),
lastEvent(), hasEvent(), available(), freshness() or isStale().
lastUpdateMs() is the millis() timestamp of the most recent valid live
occurrence, 0 before the first and again after setSource() or
clearSource() changes the source. Sources use the same
/remoteresources.json persistence as the other Remote Resources.
Resource topic helpers#
const std::string &resolveResourceOwner(
const NetResource &resource);
std::string resolveResourceManifestTopic(
const std::string &deviceName,
DocumentFormat format);
std::string resolveDocumentTopic(
const std::string &deviceName,
const std::string &documentRoot,
DocumentFormat format);
std::string resolveResourceTopic(
const NetResource &resource,
ResourceTopicOperation operation);
std::string resolveResourceTopic(
const std::string &deviceName,
const std::string &resourceName,
ResourceTopicOperation operation);
Operations:
STATE // <device>/resource/<name>/state retained
SET // <device>/resource/<name>/set transient
INVOKE // <device>/resource/<name>/invoke transient
EVENT // <device>/resource/<name>/event transient
ResourcesManager#
Global:
extern ResourcesManager gResourcesManager;
Capacity:
ResourcesManager::MaxResources == 100
Project-facing methods:
Resource construction enlists the object; startNightMareESP() calls
bindEnlisted() in declaration order. Explicit bindResource() remains
available for Resources created after startup.
bool bindResource(NetResource *resource);
bool bindEnlisted();
void unbindResource(NetResource *resource);
bool loadRemoteSources();
bool loadResourceSettings();
void tick();
bool announceAll();
bool publishManifest();
bool publishConsumeManifest();
bool publishResourceStates();
void subscribeAll();
bool needsSubscription(
const std::string &topicFilter) const;
bool handleIngressMessage(
const std::string &topic,
const std::string &message,
bool retained = false);
using ManifestHandler =
void (*)(const std::string &deviceName, const std::string &manifest);
void setManifestHandler(ManifestHandler handler);
using EncodedManifestHandler =
void (*)(const std::string &deviceName, const std::string &encoded);
void setEncodedManifestHandler(
EncodedManifestHandler handler);
static bool decodeManifest(
const std::string &encoded,
JsonDocument &into);
static bool decodeConsumeManifest(
const std::string &encoded,
JsonDocument &into);
constexpr uint8_t ConsumeManifestEncodingVersion = 3;
constexpr uint8_t ConsumeManifestVersion = 4;
constexpr uint8_t ManifestEncodingVersion = 3;
constexpr uint8_t ResourceManifestVersion = 6;
std::string resolveResourceConsumeManifestTopic(
const std::string &deviceName,
DocumentFormat format);
ActionResult executeAction(
NetActionResource &action,
const std::string &canonicalPayload);
ActionResult executeCommand(
const std::string &expression);
// Resource command grammar:
// >list
// >manifest [publish] [json|msgpack]
// >drop <name|owner/name>
// >raw <topic> [payload]
// > <name|owner/name> [get|set|invoke|source|advertise|poll] [payload]
bool withdrawIdentity(const std::string &oldDeviceName);
Connection boundary:
class ResourcePublisher
{
public:
virtual bool publish(
const std::string &topic,
const std::string &payload,
bool retained) = 0;
};
class ResourceSubscriber
{
public:
virtual bool subscribe(
const std::string &topicFilter) = 0;
virtual bool unsubscribe(
const std::string &topicFilter) = 0;
};
Resource limits#
Current limits:
Resources per manager: 100
Resource/topic segment: 64 characters
Value/Action/Event payload: 2048 bytes
Resource manifest payload limit: 16384 bytes
Resource command expression: 16640 bytes
Scheduler#
Global:
extern Scheduler gScheduler;
Capacity:
Scheduler::MaxJobs == 30
Clocks:
enum class SchedulerClock
{
Wall,
Monotonic
};
Run modes:
enum class SchedulerRunMode
{
TASK,
MANUAL
};
Scopes:
enum class SchedulerJobScope
{
MANAGED,
USER
};
Callback type:
using SchedulerCallback = void (*)();
Startup:
bool begin(
SchedulerRunMode mode = SchedulerRunMode::TASK);
SchedulerRunMode runMode() const;
void tick();
Scheduling:
int32_t atWall(
const std::string &label,
const std::string &command,
uint32_t epochSeconds,
SchedulerJobScope scope = SchedulerJobScope::MANAGED);
int32_t atWall(
const std::string &label,
SchedulerCallback callback,
uint32_t epochSeconds);
int32_t after(
const std::string &label,
const std::string &command,
uint32_t delayMs,
SchedulerJobScope scope = SchedulerJobScope::MANAGED);
int32_t after(
const std::string &label,
SchedulerCallback callback,
uint32_t delayMs);
int32_t everyWall(
const std::string &label,
const std::string &command,
uint32_t intervalSeconds,
SchedulerJobScope scope = SchedulerJobScope::MANAGED);
int32_t everyWall(
const std::string &label,
SchedulerCallback callback,
uint32_t intervalSeconds);
int32_t everyMonotonic(
const std::string &label,
const std::string &command,
uint32_t intervalMs,
SchedulerJobScope scope = SchedulerJobScope::MANAGED);
int32_t everyMonotonic(
const std::string &label,
SchedulerCallback callback,
uint32_t intervalMs);
int32_t timer(
const std::string &label,
SchedulerCallback callback,
uint32_t intervalMs);
int32_t setTimeout(
SchedulerCallback callback,
uint32_t delayMs);
Management:
bool remove(
const std::string &label,
SchedulerJobScope scope = SchedulerJobScope::MANAGED);
bool remove(
uint32_t id,
SchedulerJobScope scope = SchedulerJobScope::MANAGED);
bool clear(SchedulerJobScope scope);
std::string list(SchedulerJobScope scope);
Scheduler implementation constants:
max jobs: 30
max label length: 64
max command length: NM_MAX_MESSAGE_LEN
max interval: 0x7fffffff
task poll: 100 ms
default stack: 8192 bytes
default priority: 1
storage retry: 5000 ms
persistent file: /jobs.json
Command types#
Sources:
enum CommandSource
{
NM_CMD_SRC_UNKNOWN,
NM_CMD_SRC_MQTT,
NM_CMD_SRC_SERIAL,
NM_CMD_SRC_HTTP,
NM_CMD_SRC_WEBSOCKET,
NM_CMD_SRC_JOB,
NM_CMD_SRC_ESPNOW, // console topic delivered by the ESP-NOW gateway
NM_CMD_ANS_DO_NOT_RESPOND = 0xFF
};
Console topics are labelled by the connection that delivered them:
NM_CMD_SRC_MQTT for either MQTT broker profile and NM_CMD_SRC_ESPNOW for
ESP-NOW.
Context:
struct NightmareContext
{
CommandSource msgSource;
std::string sourceIdentifier;
void *userContext;
};
Result:
struct NightMareResults
{
bool result;
std::string response;
NightmareContext context;
};
Parsed message:
struct NightMareMessage
{
std::string command;
std::string subcommand;
std::string args[NM_MAX_ARGS];
uint8_t argc;
bool valid;
std::string error;
};
Limits:
NM_MAX_ARGS 5
NM_MAX_MESSAGE_LEN 512
Command API#
void setCommandResolver(
NightMareResults (*resolver)(
const NightMareMessage &message));
NightMareMessage parseNightMareMessage(
const std::string &message);
NightMareMessage parseNightMareMessage2(
const std::string &message);
bool ensureSize(
const std::string &str,
size_t maxLength,
std::string &error);
NightMareResults handleNightMareCommand(
const std::string &message,
NightmareContext context = NightmareContext());
When serial console is enabled:
void NightMareCommand_SerialResolver();
RuntimeState#
Capacity:
RuntimeState::MaxEntries == 128
The 128-entry store reserves capacity for all 64 Config slots plus 64 entries of framework/application settings headroom.
Methods:
bool set(
const std::string &key,
const std::string &value);
std::string get(
const std::string &key,
const std::string &defaultValue = "") const;
bool setFlag(
const std::string &key,
bool value);
bool getFlag(
const std::string &key) const;
bool exists(
const std::string &key) const;
bool remove(
const std::string &key);
void clear();
size_t size() const;
std::string toJson() const;
SystemState#
enum class SystemFlag : uint16_t
{
OtaRunning = 0,
TimeSynced,
PersistentStorageReady,
Count
};
enum class SystemRequest : uint16_t
{
PublishStatus = 0,
PublishManifest,
PublishConsumeManifest,
PublishResourceStates,
PublishInfo,
PublishHardware,
Count
};
class SystemStateStore
{
public:
bool get(SystemFlag flag) const;
void set(SystemFlag flag);
void clear(SystemFlag flag);
void request(SystemRequest request);
bool pending(SystemRequest request) const;
bool take(SystemRequest request);
};
extern SystemStateStore SystemState;
The implementation uses fixed bit banks derived from each Count. Operations
are task-safe and allocation-free; there is no ISR-safe API.
Deferred publication processing defaults to:
NM_SYSTEM_REQUEST_RETRY_MS == 1000UL
NM_SYSTEM_REQUEST_MAX_RETRY_MS == 300000UL
After a failure, the delay doubles from the initial retry interval up to the five-minute cap. The request moves behind other ready work and remains eligible for future retries. A new request for the same work clears its existing delay and runs as fresh work. No retry is attempted while MQTT is offline; a delay that elapsed during the outage is ready after reconnect.
StateStore#
When Settings are enabled:
extern StateStore PersistentSettings;
Constructor:
explicit StateStore(bool persistent = true);
Methods:
bool begin();
bool load();
bool save();
bool set(
const std::string &key,
const std::string &value) override;
std::string get(
const std::string &key,
const std::string &defaultValue = "") const override;
bool exists(
const std::string &key) const override;
bool remove(
const std::string &key) override;
void clear() override;
void clear(bool saveChanges);
size_t size() const override;
std::string toJson() const override;
Current persistent file:
/configs.json
save() writes and verifies /configs.tmp before atomically renaming it over
the live file, preserving the previous durable document when the temporary
write fails.
Settings loading uses a dynamically sized ArduinoJson 7 JsonDocument;
there is no fixed JSON load capacity.
Persistent set() rolls back its in-memory mutation when saving fails.
ConfigManager uses this store for reserved _config:<name> entries.
Time#
Namespace:
NightMare::Time
constexpr time_t SecondsPerMinute = 60;
constexpr time_t SecondsPerHour = 60 * SecondsPerMinute;
enum TimeStampFormat
{
DateAndTime,
OnlyDate,
SmallDate,
OnlyTime,
OnlyTimeWithSeconds,
OnlyTimeLive,
DowDate,
TimeSinceStamp,
CountdownFromTimestamp
};
Clock API:
time_t now();
bool valid();
bool setEpoch(time_t epoch);
int second(time_t epoch = now());
int minute(time_t epoch = now());
int hour(time_t epoch = now());
int day(time_t epoch = now());
int month(time_t epoch = now());
int year(time_t epoch = now());
The component accessors are UTC.
Local/human formatting:
std::string timestampToDateString(time_t timestamp, TimeStampFormat format = DateAndTime);
std::string timeString(time_t timestamp = now());
std::string fullTimeString(time_t timestamp = now());
std::string dateString(time_t timestamp = now());
time_t timestampOfNextOccurrence(const std::string &timeString);
See Time.
Time synchronization#
Canonical synchronization API:
bool startSntpTimeSync();
void manualSyncTime(unsigned long timestamp);
void onTimeSync(void (*callback)(void));
void processTimeSyncEvents();
startSntpTimeSync() starts asynchronous ESP32 SNTP. processTimeSyncEvents() is normally called by tickNightMareESP().
The active source currently also contains a deprecated autoSyncTime() compatibility alias; new code should use startSntpTimeSync().
Telemetry#
Global:
extern TelemetryService Telemetry;
extern Config<bool> HeartbeatEnabled; // heartbeat:enable, default true
extern Config<int> HeartbeatPeriod; // heartbeat:period, seconds, default 15
constexpr int HeartbeatMinPeriodSeconds = 15;
constexpr int HeartbeatMaxPeriodSeconds = 86400;
Types:
enum class InfoType
{
INVALID,
INFO,
IDENTITY,
HARDWARE,
BUILD,
BOOT,
SYSTEM,
NETWORK,
HEARTBEAT
};
struct TelemetryResult
{
bool valid;
std::string data;
};
API:
InfoType getInfoType(const std::string &type);
bool Telemetry.start();
TelemetryResult Telemetry.getInfo(
InfoType type = InfoType::INFO) const;
TelemetryResult Telemetry.getInfo(
const std::string &type) const;
bool Telemetry.publishInfo(
InfoType type = InfoType::INFO);
bool Telemetry.publishInfo(
const std::string &type);
TelemetryResult Telemetry.getHardware() const;
TelemetryResult Telemetry.getHardwareMessagePack() const;
static bool TelemetryService::decodeHardware(
const std::string &encoded,
JsonDocument &into);
bool Telemetry.publishHardware();
bool Telemetry.publishAll();
Network connection#
namespace NightMare
{
enum class ConnectionType : uint8_t
{
AUTO = 0,
MQTT = 1,
ESP_NOW = 3
};
enum class MqttProfile : uint8_t
{
REMOTE = 0,
LOCAL = 1
};
enum class ConnectionState : uint8_t
{
STOPPED,
DISCOVERING,
CONNECTING,
CONNECTED,
ERROR
};
enum class ConnectivityState : uint8_t
{
STOPPED,
STARTING,
READY,
CONNECTING,
CONNECTED,
SUSPENDED,
ERROR
};
struct ConnectivityStatus
{
bool supported;
bool enabled;
ConnectivityState state;
};
extern Config<int> preferredConnection;
using MessageHandler =
void (*)(const char *topic,
const uint8_t *payload,
size_t length,
bool retained);
using ConnectHandler = void (*)();
bool Publish(const char *topic,
const uint8_t *payload,
size_t length,
bool retained = false);
bool Subscribe(const char *topicFilter);
bool Unsubscribe(const char *topicFilter);
void OnConnect(ConnectHandler handler);
void OnMessage(MessageHandler handler);
bool SelectConnection(ConnectionType connection);
ConnectionType GetActiveConnection();
ConnectionType GetPreferredConnection();
ConnectionState GetConnectionState();
const char *ConnectionTypeName(ConnectionType connection);
const char *ConnectionStateName(ConnectionState state);
}
MQTT means Remote MQTT/TLS. The payload pointer and explicit length make the
generic boundary binary-safe. ESP_NOW is available when built with
NM_NETWORK_ESPNOW; AUTO uses the base failover order (ESP-NOW, MQTT).
Local versus remote MQTT is an MqttProfile, not another transport. Selection changes only the preferred routing transport. Active
routing is restricted to an enabled, connected service.
OnConnect() replaces the single firmware connection handler, or unregisters
it when passed nullptr. Register it before framework startup and install
firmware-owned topic filters from that callback. Subscribe() and
Unsubscribe() act only on the active connected transport and do not retain
filters for reconnect.
OnMessage() replaces the single application message handler, or unregisters
it when passed nullptr. The handler receives messages left unconsumed by
enabled framework routes, plus every other device's manifest, /state and
/event the Resource Manager reads, which includes topics the manager
subscribed itself for a Remote Resource. Requests addressed to this device
(/set, /invoke, console) are never delivered. Its topic and payload
pointers remain valid for the duration of the callback.
MQTT service and implementation limits#
When NM_ENABLE_MQTT:
bool NightMare::Mqtt_enable(MqttProfile profile);
bool NightMare::Mqtt_disable();
bool NightMare::Mqtt_enabled();
ConnectivityState NightMare::Mqtt_state();
MqttProfile NightMare::Mqtt_profile();
MQTT enable requires WiFiIP enabled and never starts it. The selected broker profile is MQTT-owned service state. Current implementation limits are:
queued reconnect messages: 5
topic filter length: 192
incoming MQTT payload: 32768 bytes
MQTT QoS: 0
WiFi radio#
When NM_ENABLE_WIFI_RADIO (derived: NM_ENABLE_WIFI || NM_NETWORK_ESPNOW):
// ESP-IDF driver (Network/WiFiRadio/NmWifiRadio.h): the radio and nothing above it.
bool WiFiRadio_start(); // driver init, STA mode, esp_wifi_start; no AP. Idempotent.
void WiFiRadio_stop(); // stop + deinit; the station and ESP-NOW stop with it
bool WiFiRadio_running();
esp_netif_t *WiFiRadio_stationNetif(); // nullptr unless NM_ENABLE_WIFI
uint8_t WiFiRadio_channel(); // 0 while not running
typedef void (*WiFiRadioStateCallback)(bool running);
void WiFiRadio_onState(WiFiRadioStateCallback callback);
// NightMare integration (Network/WiFiRadio/NmWifiRadioService.h)
bool NightMare::WiFiRadioBegin(); // start + report; startNightMareESP() calls it
void NightMare::WiFiRadioEnd(); // stops the station (if any), then the radio
bool NightMare::WiFiRadio_supported();
bool NightMare::WiFiRadio_enabled();
ConnectivityState NightMare::WiFiRadio_state();
The radio is what ESP-NOW and WiFiIP need; it never configures or joins an AP.
It reports READY while running but does not start either dependent. The station netif is created with
the driver, before esp_wifi_start, because it follows the driver's STA events
and one created later misses STA_START.
WiFi IP station#
When NM_ENABLE_WIFI:
// ESP-IDF driver (Network/WiFiIP/NmWifiEsp.h): no Arduino, storage or identity.
bool WiFi_start(const NightMare::WiFiProfile &profile, const char *hostname = nullptr);
bool WiFi_changeProfile(const NightMare::WiFiProfile &profile);
void WiFi_stop();
NightMare::WiFiState WiFi_state(); // STOPPED, CONNECTING, CONNECTED, DISCONNECTED
NightMare::WiFiInfo WiFi_info(); // state, ssid, ip, txPower, txPowerDbm, rssi, channel
typedef void (*WiFiStateCallback)(NightMare::WiFiState state);
void WiFi_onState(WiFiStateCallback callback);
bool WiFi_startScan();
bool WiFi_scanInProgress();
int WiFi_scanCount();
bool WiFi_scanComplete();
bool WiFi_scanResult(size_t index, NightMare::WiFiScanResult &result);
void WiFi_clearScanResults();
void WiFi_abortScan();
const char *WiFi_getAuthTypeName(wifi_auth_mode_t authType);
const char *WiFi_stateName(NightMare::WiFiState state);
bool WiFi_isValidTxPower(int quarterDbm);
// NightMare integration (Network/WiFiIP/NmWifiService.h)
typedef void (*WiFiConnectedCallback)(bool firstConnection);
void WiFi_onConnected(WiFiConnectedCallback callback);
NightMare::WiFiProfile NightMare::WiFiStoredProfile();
bool NightMare::WiFiBegin();
bool NightMare::WiFiIP_enable();
bool NightMare::WiFiIP_disable();
bool NightMare::WiFiIP_enabled();
ConnectivityState NightMare::WiFiIP_state();
bool NightMare::WiFiApplyProfile(const NightMare::WiFiProfile &profile);
The station is ESP-IDF only, runs on the radio without owning it, and has three actions and a state.
WiFi_start()starts the radio if needed, then joins the AP in the profile it is given and keeps a recovery task running: it retries every 15 seconds while cycling through the ESP32 driver's supported transmit-power levels.WiFi_changeProfile()connects to a new network or applies a TX power. It tries the profile for up to 15 seconds and restores the previous one on failure. It persists nothing and fails while stopped.WiFi_stop()stops the station only: it disconnects, clears the station config (so ESP-NOW may hop channels again) and ends the recovery task. The radio stays up;WiFiRadio_stop()turns it off.WiFi_state()isSTOPPED, or running asCONNECTING,CONNECTEDorDISCONNECTED.WiFi_info()adds SSID, IP, TX power (including a fallback level the driver settled on), RSSI and channel.WiFi_onState()fires on every change, from the caller or the station's monitor task -- never the ESP event task.WiFi_startScan()needs the radio, not a station.
Storage, hostname and first-connection services live in NmWifiService.
WiFiBegin() starts the radio through WiFiRadioBegin() (so it is reported),
loads the stored profile (defaulting to creds.h), uses the device name as
hostname, starts the station, and on connection starts OTA and SNTP once,
persists a fallback TX power and then calls the WiFi_onConnected() callback.
Every station state change updates WiFiIP, notifies an already-enabled MQTT
service, refreshes network telemetry, and asks NmConnection to reevaluate
routing. It does not enable MQTT or change the transport preference.
WiFiApplyProfile() changes the running station and persists on success, or
only persists while stopped.
ESP-NOW service#
When NM_NETWORK_ESPNOW:
enum class ConnectivitySuspendReason : uint8_t { WIFI_SCAN };
bool NightMare::EspNow_enable();
bool NightMare::EspNow_disable();
bool NightMare::EspNow_enabled();
ConnectivityState NightMare::EspNow_state();
bool NightMare::EspNow_suspend(ConnectivitySuspendReason reason);
bool NightMare::EspNow_resume(ConnectivitySuspendReason reason);
ESP-NOW requires WiFiRadio READY and never changes WiFiIP or MQTT. A Wi-Fi
scan uses the runtime-only WIFI_SCAN suspension; enabled stays true while
the service reports SUSPENDED.
The implementation is under Network/WiFiIP/ and uses esp_wifi directly.
ESP lifecycle#
void startNightMareESP();
void tickNightMareESP();
Normal application structure:
void setup()
{
// Declare Configs and Resources; register handlers first.
startNightMareESP();
// Application hardware/services.
}
void loop()
{
tickNightMareESP();
// Application cooperative work.
}
HardwareProfile#
namespace NMHardware
{
constexpr uint8_t HwConfigVersion = 2;
constexpr uint8_t HardwareEncodingVersion = 1;
enum class AssemblyKind
{
CustomBoard, MarketBoard, Module, SensorProbe,
Panel, Enclosure, External, Generic
};
enum class ConnectorKind
{
Header, ScrewTerminal, Jst, Usb, Terminal,
DirectPin, DirectWire, Generic
};
enum class CanonicalNet
{
None, Gnd, Vcc, V3v3, V5v,
AcPhase, AcNeutral, ProtectiveEarth
};
struct Terminal { const char *id; CanonicalNet canonicalNet; const char *name; };
struct ConnectorContact { const char *id; CanonicalNet canonicalNet; const char *name; };
struct Device
{
const char *id;
const Terminal *terminals;
size_t terminalCount;
const char *name;
const char *kind;
const char *model;
const char *manufacturer;
};
struct Connector
{
const char *id;
const ConnectorContact *contacts;
size_t contactCount;
const char *name;
ConnectorKind kind;
const char *model;
const char *manufacturer;
};
enum class EndpointKind { DeviceTerminal, ConnectorContact };
struct EndpointRef
{
const char *assembly;
EndpointKind kind;
const char *owner;
const char *endpoint;
};
struct WireMetadata
{
const char *color;
const char *gauge;
const char *label;
uint32_t lengthMm;
};
struct Connection
{
EndpointRef a;
EndpointRef b;
WireMetadata wire;
};
struct Assembly;
struct AssemblyMembers
{
const Assembly *assemblies;
size_t assemblyCount;
const Device *devices;
size_t deviceCount;
const Connector *connectors;
size_t connectorCount;
const Connection *connections;
size_t connectionCount;
};
struct Assembly
{
const char *id;
const char *definition;
const char *name;
AssemblyKind kind;
const char *model;
const char *manufacturer;
const char *serialNumber;
const char *location;
AssemblyMembers members;
};
struct HardwareDefinition
{
const char *id;
AssemblyKind kind;
const char *name;
const char *model;
const char *manufacturer;
AssemblyMembers members;
};
struct ValidationResult;
struct TopologyGraph;
struct InferredNets;
struct Profile
{
const char *hostAssembly;
const HardwareDefinition *definitions;
size_t definitionCount;
const Assembly *roots;
size_t rootCount;
const Connection *connections;
size_t connectionCount;
};
ValidationResult validateHwConfig(const Profile &config);
bool buildTopologyGraph(const Profile &config, TopologyGraph &graph,
ValidationResult *diagnostics = nullptr);
bool inferNets(const TopologyGraph &graph, InferredNets &nets);
const char *assemblyModel(const Profile &config, const char *absolutePath);
Profile getProfile();
const HardwareDefinition &esp32C3SuperMiniRev1();
const HardwareDefinition &mycroftYControllerRev1();
const HardwareDefinition &ds18b20ProbeDefinition();
const HardwareDefinition &genericRelayModule1Ch();
const HardwareDefinition *standardDefinitions(size_t &count);
}
startNightMareESP() initializes persistent settings through DeviceIdentity
and immediately restores all currently bound Configs before Scheduler,
telemetry, WiFi, or MQTT startup. Before this restore, Configs contain their
firmware defaults.
The complete declarations, constructors, diagnostic codes, and fixed graph
capacities are in NightMare/HardwareProfile.h. The normative semantics and
JSON field contract are in Hardware configuration v2.
Canonical identities are exact; VCC is not a wildcard for an unknown positive
rail. Effective assemblies receive graph indices, and GraphNode::assembly
stores that index rather than a copied path.
A consuming project may provide NightMareHardware.h with:
NMHardware::Profile projectProfile();
Logging#
Levels:
NM_LOG_LEVEL_OFF 0
NM_LOG_LEVEL_ERROR 1
NM_LOG_LEVEL_WARNING 2
NM_LOG_LEVEL_INFO 3
NM_LOG_LEVEL_DEBUG 4
NM_LOG_LEVEL_TRACE 5
Configure:
#define NM_LOG_LEVEL NM_LOG_LEVEL_DEBUG
#define NM_LOG_OUTPUT NM_LOG_OUTPUT_ARDUINO
NM_LOG_LEVEL defaults to OFF, so log calls compile out. Choose one
compile-time output (NM_LOG_OUTPUT defaults to NM_LOG_OUTPUT_PRINTF):
| Output | Destination |
|---|---|
NM_LOG_OUTPUT_PRINTF |
ESP-IDF stdout console, through printf |
NM_LOG_OUTPUT_ARDUINO |
Arduino Serial, through Serial.printf |
Arduino output requires an Arduino build, and the application must initialize
Serial before expecting logs. The Arduino header is included only when
NM_LOG_OUTPUT_ARDUINO is selected and NM_LOG_LEVEL is above OFF.
Log lines use [timestamp] [level] [module] message. The timestamp defaults to
monotonic milliseconds. Set NM_LOG_USE_TIME_OF_DAY=1 to use local HH:MM:SS
after time synchronization, with monotonic milliseconds until then.
ANSI formatting:
#define NM_LOG_USE_ANSI 1
ANSI colors default on for both outputs.
Configuration belongs in NightMareConfig.h or build flags so library source
files use the same settings.
Macros:
LOG_ERROR(module, ...)
LOG_WARNING(module, ...)
LOG(module, ...)
LOG_DEBUG(module, ...)
LOG_TRACE(module, ...)
OK_LOG(value)
Feature defaults#
Current defaults:
NM_ENABLE_SETTINGS 1
NM_ENABLE_RESOURCES 1
NM_ENABLE_NETWORK 1
NM_ENABLE_CONSOLE 1
NM_ENABLE_WIFI 1
NM_ENABLE_MQTT 1
NM_ENABLE_TELEMETRY 1
NM_ENABLE_JSON_WIRE 0
NM_ENABLE_SCHEDULER 1
NM_ENABLE_JOBS 1
NM_ENABLE_TIME_SYNC 1
NM_TIMEZONE "UTC0"
NM_NTP_SERVER_1 "pool.ntp.org"
NM_NTP_SERVER_2 "time.nist.gov"
NM_NTP_SERVER_3 "time.google.com"
NM_ENABLE_OTA 0
NM_ENABLE_HTTP 0
NM_ENABLE_WEBSOCKET 0
NM_ENABLE_LVGL 0
NM_ENABLE_ACTION_PAYLOAD_ASSERTION 0
NM_DEFAULT_MANIFEST_FORMAT msgpack
NM_SCHEDULER_OWN_TASK 1
NM_CONSOLE_BUILTINS 1
NM_CONSOLE_SERIAL 0
NM_PLATFORM_ESP32 1
NM_ENABLE_GATEWAY 0
NM_GATEWAY_ESPNOW NM_ENABLE_GATEWAY
NM_GATEWAY_MQTT NM_ENABLE_GATEWAY
NM_GATEWAY_OWN_TASK 1
NM_GATEWAY_TASK_STACK 12288
NM_GATEWAY_TASK_PRIORITY 5
NM_GATEWAY_TICK_MS 50
Other defaults:
NM_TELEMETRY_INTERVAL_MS 60000UL
NM_NETWORK_TELEMETRY_INTERVAL_MS 300000UL
NM_IDENTITY_CLEANUP_RETRY_MS 60000UL
NM_FIRMWARE_VERSION "unspecified"
NM_LOG_LEVEL 0
NM_LOG_OUTPUT NM_LOG_OUTPUT_PRINTF
NM_LOG_USE_ANSI 1
NM_LOG_USE_TIME_OF_DAY 0
Compile-time dependency graph#
Current enforced dependencies:
MQTT -> NETWORK
NETWORK -> RESOURCES
TELEMETRY -> SCHEDULER
TELEMETRY -> NETWORK
JOBS -> SCHEDULER
SCHEDULER -> SETTINGS
SCHEDULER -> CONSOLE
CONSOLE -> SETTINGS
TIME_SYNC -> WIFI
TIME_SYNC -> SETTINGS
WIFI -> SETTINGS
OTA -> WIFI
OTA -> SETTINGS
HTTP -> NETWORK
HTTP -> CONSOLE
WEBSOCKET -> HTTP
CONSOLE_SERIAL -> CONSOLE
GATEWAY -> GATEWAY_ESPNOW or GATEWAY_MQTT
GATEWAY_ESPNOW, GATEWAY_MQTT -> GATEWAY
GATEWAY -> RESOURCES
GATEWAY -> CONSOLE
GATEWAY -> not NETWORK
GATEWAY -> not SCHEDULER
GATEWAY_ESPNOW -> not NETWORK_ESPNOW
See Known gaps for current couplings that may later be separated.
Current library version#
At the documentation revision used for this page, library.json reports:
1.0.0-alpha.1
Use the MCP get_version tool when you need the version and exact revision currently being served rather than relying on a static page.