API Reference

This section provides detailed documentation for the UNA Watch SDK core interfaces, message system, and sensor layer.

Core SDK Interfaces

The following interfaces provide the primary abstraction layer between the application and the watch kernel.

class IKernel
class ISystem

Subclassed by SDK::Simulator::Mock::SystemGUI, SDK::Simulator::Mock::SystemService

Public Functions

virtual void exit(int status = 0) = 0

Terminates the application.

When this method is called, no additional events will be sent. After execution, the application is removed from memory.

Note

No return.

Parameters:

status – Exit status (0 for normal exit, < 0 for errors).

virtual uint32_t getTimeMs() = 0

Get the current time in milliseconds.

Return values:

The – current time in milliseconds.

virtual void delay(uint32_t ms) = 0

Delay for a specified amount of time.

Parameters:

ms – Number of milliseconds to delay.

virtual void yield() = 0

Yield execution to the kernel. back to the kernel.

class ILogger

Logger interface.

Subclassed by SDK::Simulator::Mock::Logger

Public Functions

virtual void printf(const char *format, ...) = 0

Log a formatted message.

This method allows the application to log messages in a formatted way.

Parameters:
  • format – Format string (printf-style).

  • ... – Additional arguments.

virtual void vprintf(const char *format, va_list args) = 0

Log a formatted message.

This method allows the application to log messages in a formatted way.

Parameters:
  • format – Format string (printf-style).

  • args – Variable argument list

virtual void mvprintf(const char *level, const char *module_name, const char *func, int line, const char *fmt, va_list args) = 0

Log a formatted message with metadata.

This method allows the application to log messages in a formatted way.

Parameters:
  • level – Log level string (e.g., β€œD”, β€œI”, β€œW”, β€œE”)

  • module_name – Module name, file name or other identifier

  • func – Function name (typically func)

  • line – Line number (typically LINE)

  • fmt – Format string (printf-style).

  • args – Variable argument list

class IFileSystem

Interface for the file system.

Provides an abstraction for creating files and directories, and performing operations such as removing and renaming.

Subclassed by SDK::Simulator::Mock::FileSystem

Public Functions

virtual bool mkdir(const char *path) = 0

Creates the directory (and sub directories) if it does not exist.

Return values:

'true' – if the directory was successfully created or existed, β€˜false’ otherwise.

virtual std::unique_ptr<IFile> file(const char *path) = 0

Creates a file object.

Parameters:

path – Path to the file.

Return values:

Unique – pointer to the created file object.

virtual std::unique_ptr<IDirectory> dir(const char *path) = 0

Creates a directory object.

Parameters:

path – Path to the directory.

Return values:

Unique – pointer to the created directory object.

virtual bool exist(const char *path) const = 0

Checks if a file/directory exists.

Parameters:

path – Path to the file.

Return values:

'true' – if the file exists, β€˜false’ otherwise.

virtual bool remove(const char *path) = 0

Removes a file or directory.

Parameters:

path – Path to the file or directory.

Return values:

'true' – if the item was successfully removed, β€˜false’ otherwise.

virtual bool rename(const char *oldPath, const char *newPath) = 0

Renames a file or directory.

Parameters:
  • oldPath – Current path of the item.

  • newPath – New path for the item.

Return values:

'true' – if the item was successfully renamed, β€˜false’ otherwise.

virtual bool copy(const char *oldPath, const char *newPath) = 0

Copy a file to another location.

Parameters:
  • oldPath – Current path of the item.

  • newPath – New path for the item.

Return values:

'true' – if the item was successfully moved, β€˜false’ otherwise.

virtual bool objectInfo(const char *path, ObjectInfo &item) const = 0

Get object info.

Parameters:
  • path – Path to the directory.

  • item – Reference to save item info.

Return values:

Execution – status. β€˜true’ - if success, β€˜false’ - otherwise.

Public Static Attributes

static constexpr size_t skMaxPathLen = 256

< Maximum length of a filesystem object path including β€˜\0’.

struct ObjectInfo

Structure to store directory item information.

Public Members

char name[skMaxPathLen]

Name of the item.

bool isDir

β€˜true’ if the item is a directory.

bool isHidden

β€˜true’ if the item is hidden.

bool isSystem

β€˜true’ if the item is a system file.

size_t size

Size of the item in bytes (for files).

time_t utc

UTC creation time.

class IAppMemory

Interface for the memory allocator of the user application.

Subclassed by SDK::Simulator::Mock::AppMemory

Public Functions

virtual void *malloc(size_t size) = 0

Allocates a block of memory.

Parameters:

size – The size of the memory block to allocate in bytes.

Returns:

A pointer to the allocated memory block, or nullptr if allocation failed.

virtual void free(void *ptr) = 0

Frees a previously allocated memory block.

Parameters:

ptr – A pointer to the memory block to free.

virtual void *realloc(void *ptr, size_t size) = 0

Reallocates a memory block.

Parameters:
  • ptr – Previously allocated pointer or nullptr.

  • size – New block size in bytes.

Application Communication (IPC)

These interfaces and classes manage inter-process communication between the Service and GUI processes.

class IAppComm

Application communication interface.

This pure virtual interface provides communication methods between application and kernel. Kernel creates concrete implementation and passes it to application during initialization.

Applications must NOT create instances directly - only use pointer provided by kernel.

Subclassed by SDK::App::DualAppComm::InternalAppComm

Public Functions

virtual uint32_t getProcessId() const = 0

Get process ID assigned by kernel.

Note

Process represents execution context (thread/task)

Note

Application may consist of multiple processes (e.g. GUI + Service)

Return values:

Unique – process identifier

virtual bool getMessage(MessageBase *&msg, uint32_t timeoutMs = 0xFFFFFFFF) = 0

Receive message from kernel.

Note

Application must call releaseMessage() after processing

Note

Reference counting managed automatically by kernel

Parameters:
  • msg – Reference to message pointer (output parameter)

  • timeoutMs – Timeout in milliseconds (0 for non-blocking)

Return values:
  • true – Message received successfully

  • false – Timeout or error occurred

virtual void sendResponse(MessageBase *msg) = 0

Send response back to kernel (for request-response pattern)

Note

Only valid for messages with needsResponse() == true

Note

Sets completion flag and signals waiting kernel task

Note

Does NOT release message - application must call releaseMessage()

Note

If message does not need response, this call has no effect

Parameters:

msg – Message with filled response fields

virtual void releaseMessage(MessageBase *msg) = 0

Release message object back to kernel pool.

Note

Decrements reference count

Note

Returns message to pool when reference count reaches zero

Note

After this call, message pointer becomes invalid

Note

Application must NOT access message after release

Parameters:

msg – Message to release

virtual bool sendMessage(MessageBase *msg, uint32_t timeoutMs = 0) = 0

Send message to kernel.

Note

Kernel automatically increments reference count when queuing

Note

Message type determines if response is expected

Parameters:
  • msg – Message to send (must be allocated via allocateMessage)

  • timeoutMs – Timeout in milliseconds (0 for non-blocking)

Return values:
  • true – Message sent successfully and if timeoutMs > 0 response received (check msg->getResult() for SUCCESS/ERROR)

  • false – Send failed (queue full or invalid message)

template<typename T>
inline T *allocateMessage()

Allocate typed message object from kernel pool.

Note

Template wrapper for type-safe allocation

Note

Calls placement new on allocated memory

Note

Pool determined automatically by address during deallocation

Note

Example: auto* msg = comm->allocateMessage<GpsRequestMsg>();

Return values:
  • Pointer – to typed message on success

  • nullptr – if allocation failed

class MessageBase

Base class for all messages.

Provides:

  • Type identification for message dispatch

  • Reference counting for safe shared ownership

  • Completion synchronization for request-response pattern

  • Result status tracking

Memory layout (4-byte aligned, 32 bytes total on 32-bit with vptr):

Offset

Size

Field

0

4

vptr (virtual table pointer)

4

4

mMsgType

8

1

mResult

9

1

mReserved1

10

1

mNeedsResponse

11

1

mCompleted (atomic<bool>, takes 1 bytes)

12

4

mCompletionSemaphore (pointer)

16

4

mRefCount (atomic<uint32_t>, takes 4 bytes)

20

4

mProcessId

24

4

mReserved2

28

4

mReserved3

Memory lifecycle:

  1. Allocated from pool (refCount = 1)

  2. Retained when placed in queue (refCount++)

  3. Released after processing (refCount&#8212;)

  4. Returned to pool when refCount reaches 0

Subclassed by SDK::Message::CommandAppGuiResume, SDK::Message::CommandAppGuiSuspend, SDK::Message::CommandAppNewActivity, SDK::Message::CommandAppNotifGuiRun, SDK::Message::CommandAppNotifGuiStop, SDK::Message::CommandAppRun, SDK::Message::CommandAppStop, SDK::Message::EventButton, SDK::Message::EventGlanceStart, SDK::Message::EventGlanceStop, SDK::Message::EventGlanceTick, SDK::Message::EventGuiTick, SDK::Message::EventSystemPowerCritical, SDK::Message::EventSystemPowerLow, SDK::Message::RequestAppRunGui, SDK::Message::RequestAppTerminate, SDK::Message::RequestBacklightSet, SDK::Message::RequestBatteryStatus, SDK::Message::RequestBuzzerPlay, SDK::Message::RequestDisplayConfig, SDK::Message::RequestDisplayUpdate, SDK::Message::RequestGlanceConfig, SDK::Message::RequestGlanceUpdate, SDK::Message::RequestMemoryInfo, SDK::Message::RequestSetCapabilities, SDK::Message::RequestSystemInfo, SDK::Message::RequestSystemSettings, SDK::Message::RequestVibroPlay, SDK::Message::Sensor::EventData, SDK::Message::Sensor::RequestConnect, SDK::Message::Sensor::RequestDefault, SDK::Message::Sensor::RequestDisconnect, SDK::Message::Sensor::RequestGetDesc, SDK::Message::Sensor::RequestList, SDK::MessageID

Public Functions

inline MessageType::Type getType() const

Get message type.

Return values:

Message – type identifier

inline MessageResult getResult() const

Get processing result.

Return values:

Current – result status

inline const char *getResultStr() const

Get processing result as string.

Return values:

Current – result status

inline uint32_t getProcessId() const

Get process ID (owner or target)

Return values:

Process – identifier assigned by kernel

inline bool needsResponse() const

Check if message expects response.

Return values:
  • true – Response expected (request-response pattern)

  • false – Fire-and-forget message

inline bool isCompleted() const

Check if message processing completed.

Return values:
  • true – Processing completed (response ready or error occurred)

  • false – Still pending

inline uint32_t getRefCount() const

Get current reference count.

Note

For debugging purposes only

Return values:

Number – of active references to this message

inline void setResult(MessageResult result)

Set processing result.

Note

Called by message processor (kernel or application)

Parameters:

result – Result status

inline void setProcessId(uint32_t processId)

Set process ID.

Note

Called by AppComm::sendMessage() before routing

Parameters:

processId – Process identifier to set

Public Static Functions

static void *operator new(size_t) = delete

Delete direct heap allocation.

Note

Messages can only be allocated through kernel pools

static inline void *operator new(size_t size, void *ptr) noexcept

Allow placement new (used by kernel infrastructure)

Parameters:
  • size – Size of object

  • ptr – Pre-allocated memory pointer

Return values:

Pointer – to placement location

static inline void operator delete(void*) noexcept

Delete operator - no-op (memory managed by pool)

Note

Cannot delete messages directly, must use releaseMessage()

static inline void operator delete(void *ptr, void *place) noexcept

Placement delete operator (for exception safety)

Note

Called if placement new throws exception

Parameters:
  • ptr – Memory pointer

  • place – Placement pointer

template<typename T>
class MessageGuard

Sensor Layer

The Sensor Layer provides type-safe access to hardware sensors and data parsers.

Warning

doxygenclass: Cannot find class β€œSDK::Interface::ISensorManager” in doxygen xml output for project β€œSDK” from directory: _build/doxygen/xml

class Connection

High-level connection wrapper for sensor drivers.

The Connection class encapsulates IPC-based interaction with the SensorLayer. It is responsible for:

  • Resolving a sensor driver handle via RequestDefault

  • Establishing a connection via RequestConnect

  • Releasing the connection via RequestDisconnect

Internally, all communication is performed through Kernel IPC messages.

Public Functions

Connection(SDK::Sensor::Type id, float period = 0, uint32_t latency = 0)

Construct a connection wrapper using a sensor type identifier.

This constructor stores the sensor type and desired connection parameters. The actual sensor driver handle is resolved lazily during the first call to connect() using an IPC RequestDefault message.

Note

Use isValid() to check whether a driver handle has been resolved.

Parameters:
  • id – Sensor type used to resolve the default driver.

  • period – Desired sampling/update period (units defined by the driver).

  • latency – Maximum allowed reporting latency (units defined by the driver).

Connection(uint8_t handle, float period = 0, uint32_t latency = 0)

Construct a connection wrapper with an existing sensor handle.

This constructor is used when the sensor handle is already known (for example, restored from persistent state or provided externally). No driver resolution is performed.

Parameters:
  • handle – Existing sensor driver handle.

  • period – Desired sampling/update period.

  • latency – Maximum allowed reporting latency.

bool isValid()

Check whether a valid sensor handle is available.

Returns:

true If the internal handle is non-zero.

Returns:

false If no handle has been resolved yet.

bool connect()

Connect to the sensor using the stored parameters.

Connection procedure:

  1. If no valid handle is present:

    • Send RequestDefault to resolve the default sensor driver.

    • Store the returned handle.

  2. Send RequestConnect using the resolved handle and the configured period and latency.

  3. Mark the connection as active if the request succeeds.

Returns:

true If the connection was successfully established.

Returns:

false If handle resolution or connection request failed.

bool connect(float period, uint32_t latency = 0)

Update connection parameters and connect.

Stores the new period and latency, then delegates to connect().

Limitations:

  • If no valid handle is present, the function returns false.

  • If already connected, parameter updates are rejected.

Parameters:
  • period – New sampling/update period in ms.

  • latency – New maximum reporting latency in ms.

Returns:

true If the connection was successfully established.

Returns:

false If the update or connection failed.

bool isConnected()

Check whether the connection is currently active.

Returns:

true If the connection is active.

Returns:

false Otherwise.

void disconnect()

Disconnect from the sensor.

If a valid and active connection exists, a RequestDisconnect message is sent to the SensorLayer. The function is safe to call multiple times.

bool matchesDriver(uint16_t handle)

Check whether the given handle matches the connected sensor.

Parameters:

handle – Sensor driver handle to compare.

Returns:

true If the handles match and are valid.

Returns:

false Otherwise.

### Data Parsers

class Accelerometer

Helper class for parsing accelerometer sensor data from DataView.

Expected data layout:

  • [0] Acceleration on X axis

  • [1] Acceleration on Y axis

  • [2] Acceleration on Z axis

Public Types

enum Field

Indices of accelerometer data fields.

Values:

enumerator X

X axis.

enumerator Y

Y axis.

enumerator Z

Z axis.

enumerator COUNT

Total number of fields.

Public Functions

inline Accelerometer(const SDK::Sensor::DataView data)

Construct a new Accelerometer parser over the given sensor data.

Parameters:

data – Sensor data view containing 3 float values

inline bool isDataValid() const

Check whether the sensor data is structurally valid.

Validity conditions:

  • The number of fields matches the expected accelerometer layout.

Returns:

true if the data is valid, false otherwise

inline float getX() const

Get acceleration on X axis.

Returns:

Acceleration on X axis if data is valid, otherwise 0.0f

inline float getY() const

Get acceleration on Y axis.

Returns:

Acceleration on Y axis if data is valid, otherwise 0.0f

inline float getZ() const

Get acceleration on Z axis.

Returns:

Acceleration on Z axis if data is valid, otherwise 0.0f

inline bool getXYZ(float &x, float &y, float &z) const

Get acceleration values for all three axes.

Parameters:
  • x – Output value for X axis

  • y – Output value for Y axis

  • z – Output value for Z axis

Returns:

true if data is valid, false otherwise

inline uint32_t getTimestamp() const

Get data timestamp in milliseconds.

Returns:

Data timestamp in milliseconds, or 0 if data is invalid

inline uint64_t getTimestampUs() const

Get data timestamp in microseconds.

Returns:

Data timestamp in microseconds, or 0 if data is invalid

Public Static Functions

static inline constexpr uint8_t getFieldsNumber()

Get the number of expected accelerometer fields.

Returns:

Number of expected fields

class HeartRate

Helper class to parse heart rate sensor data from ISensorData.

Expected data layout:

  • [0] float heart rate (bpm)

Public Functions

inline HeartRate(const SDK::Sensor::DataView view)

Construct a new HeartRate parser over given ISensorData.

Parameters:

view – Reference to sensor data containing 1 float field

inline bool isDataValid() const

Check if data is valid (should contain exactly 1 field)

Returns:

true if valid

inline float getBpm() const

Get heart rate in beats per minute (bpm)

Returns:

Heart rate as float

inline float getTrustLevel() const

Get trust level.

Returns:

Trust level

inline uint32_t getTimestamp() const

Get data timestamp in ms.

Returns:

Data timestamp in ms (0 if invalid)

inline uint64_t getTimestampUs() const

Get data timestamp in us.

Returns:

Data timestamp in us (0 if invalid)

Public Static Functions

static inline constexpr uint8_t getFieldsNumber()

Get number of expected fields (always 1)

class GpsLocation

Helper class to parse GPS sensor data from ISensorData.

Expected data layout:

  • [0] float - precision

  • [1] bool - flag β€˜coordinates are valid’

  • [2] float - latitude

  • [3] float - longitude

  • [4] float - altitude

Validity of each field is checked via corresponding mask bit.

Public Functions

inline GpsLocation(const SDK::Sensor::DataView data)

Construct a new GPS parser over given ISensorData.

Parameters:

data – Reference to sensor data containing GPS fields

inline bool isDataValid() const

Check if datais valid.

Returns:

true if data length is Field::COUNT

inline float getPrecision() const

Get GPS time.

Returns:

Time as uint32_t (e.g., UNIX timestamp)

inline bool isCoordinatesValid() const

Check if Coordinates are valid.

Returns:

true if valide false otherwise

inline void getCoordinates(float &lat, float &lon, float &alt) const

Get GPS coordinates.

Parameters:
  • lat – [out] Latitude in decimal degrees

  • lon – [out] Longitude in decimal degrees

  • alt – [out] Altitude in meters

inline float getLatitude() const

Get latitude.

Returns:

Latitude in decimal degrees

inline float getLongitude() const

Get longitude.

Returns:

Longitude in decimal degrees

inline float getAltitude() const

Get altitude.

Returns:

Altitude in meters

inline uint32_t getTimestamp() const

Get data timestamp in ms.

Returns:

Data timestamp in ms (0 if invalid)

inline uint64_t getTimestampUs() const

Get data timestamp in us.

Returns:

Data timestamp in us (0 if invalid)

Public Static Functions

static inline constexpr uint8_t getFieldsNumber()

Get total number of expected fields.

Returns:

Field count (6)

class BatteryLevel

SensorData parser for the Battery Level sensor.

The parser only reads fields and provides type-safe accessors. It does not own the underlying storage.

Public Functions

inline explicit BatteryLevel(const SDK::Sensor::DataView data)

SensorData parser for the Battery Level sensor.

Parameters:

data – Reference to sensor data

inline bool isDataValid() const

SensorData parser for the Battery Level sensor.

The parser only reads fields and provides type-safe accessors. It does not own the underlying storage

inline float getCharge() const

SensorData parser for the Battery Level sensor.

The parser only reads fields and provides type-safe accessors. It does not own the underlying storage

inline uint32_t getTimestamp() const

Get timestamp of the data.

Returns:

Data timestamp in ms (0 if data pointer is null).

inline uint64_t getTimestampUs() const

Get data timestamp in us.

Returns:

Data timestamp in us (0 if invalid)

Public Static Functions

static inline constexpr uint8_t getFieldsNumber()

Returns the number of fields.

Returns:

The number of fields

UI Framework

Interfaces for building user interfaces using TouchGFX or the lightweight Glance system.

For detailed information on the TouchGFX port implementation, see TouchGFX Port Architecture.

class IApp

Interface for an user application interacting with the kernel.

This interface provides methods for managing the application’s lifecycle, handling display output, and processing user input events.

Subclassed by SDK::Simulator::Mock::App

Public Types

enum class LaunchReason

Reasons for application launch.

Values:

enumerator AUTO_START
enumerator ON_DEMAND
enum Button

External button definitions.

Values:

enumerator BUTTON_L1
enumerator BUTTON_L2
enumerator BUTTON_R1
enumerator BUTTON_R2
enumerator BUTTON_L1R2

Public Static Attributes

static constexpr const uint32_t kFrameRate = 10

Application frame rate for display updates.

Warning

doxygenclass: Cannot find class β€œSDK::Interface::IGlance” in doxygen xml output for project β€œSDK” from directory: _build/doxygen/xml

class TouchGFXCommandProcessor

Central TouchGFX command processor.

Singleton class that manages TouchGFX lifecycle and kernel commands.

Utilities

Common utility classes and helper functions.

template<typename T, size_t N>
class CircularBuffer

Public Functions

inline bool push(const T &item, uint32_t timeout = 0xFFFFFFFF)

Push a copy of an item to the back of the queue.

This overload copies the provided item into the queue. Use this when the caller still needs to keep and modify its own copy of the object after the call.

Example usage (caller keeps its own variable):

MyType msg{data};
queue.push(msg); // copy
// 'msg' and 'data' can still be used/modified

Parameters:
  • item – The item to copy into the queue.

  • timeout – Maximum wait time in ticks if the queue is full (default: infinite).

Returns:

true if the item was successfully pushed, false otherwise.

inline bool push(T &&item, uint32_t timeout = 0xFFFFFFFF)

Push an item to the back of the queue by moving it.

This overload moves the provided item into the queue. Use this when the item is no longer needed by the caller after the call. This avoids copying and can eliminate heap allocations (e.g. for vectors inside the item).

Example usage (one-shot event object):

MyType ev{data};
queue.push(std::move(ev)); // move
// 'ev' is now in a valid but unspecified state

Parameters:
  • item – The item to move into the queue.

  • timeout – Maximum wait time in ticks if the queue is full (default: infinite).

Returns:

true if the item was successfully pushed, false otherwise.

inline bool pop(T &item, uint32_t timeout = 0xFFFFFFFF)

Pop an item from the front of the queue.

Retrieves and removes the item at the head of the queue. The value is move-assigned into item to avoid unnecessary copies.

Parameters:
  • item – Reference where the popped item will be stored.

  • timeout – Maximum wait time in ticks if the queue is empty (default: infinite).

Returns:

true if an item was successfully popped, false if timeout expired.

inline bool pushToFront(const T &item, uint32_t timeout = 0xFFFFFFFF)

Push a copy of an item to the front of the queue.

Similar to push(const T&), but places the item at the front (head) of the queue, so it will be popped first.

Parameters:
  • item – The item to copy into the queue.

  • timeout – Maximum wait time in ticks if the queue is full (default: infinite).

Returns:

true if the item was successfully pushed, false otherwise.

inline bool pushToFront(T &&item, uint32_t timeout = 0xFFFFFFFF)

Push an item to the front of the queue by moving it.

Similar to push(T&&), but places the item at the front (head) of the queue. Use this for urgent, one-shot events that should be handled before other queued items.

Parameters:
  • item – The item to move into the queue.

  • timeout – Maximum wait time in ticks if the queue is full (default: infinite).

Returns:

true if the item was successfully pushed, false otherwise.

inline bool popFromBack(T &item, uint32_t timeout = 0xFFFFFFFF)

Pop an item from the back of the queue.

Retrieves and removes the item at the tail of the queue. The value is move-assigned into item to avoid unnecessary copies.

Parameters:
  • item – Reference where the popped item will be stored.

  • timeout – Maximum wait time in ticks if the queue is empty (default: infinite).

Returns:

true if an item was successfully popped, false if timeout expired.

Warning

doxygenclass: Cannot find class β€œSDK::SwTimer” in doxygen xml output for project β€œSDK” from directory: _build/doxygen/xml

Warning

doxygenclass: Cannot find class β€œCborStreamReader” in doxygen xml output for project β€œSDK” from directory: _build/doxygen/xml

class JsonStreamReader

A JSON deserializer that facilitates validating and extracting data from JSON buffers using coreJSON library.

This class provides functionality to validate JSON buffers and retrieve various types of data from them using query.

Query format: for details see description for JSON_Search() function.

For example, if the provided buffer contains {β€œfoo”:”abc”,”bar”:{β€œfoo”:”xyz”}}, then a search for β€˜foo’ would output abc, and a search for β€˜bar.foo’ would output xyz.

To get nested objects as string you can use method for retriveng strings get(const char *query, const char *&outValue, size_t &outLen) β€˜bar’ would output {β€œfoo”:”xyz”}

If the provided buffer contains [123,456,{β€œfoo”:”abc”,”bar”:[88,99]}], then a search for β€˜[1]’ would output 456, β€˜[2].foo’ would output abc, and β€˜[2].bar[0]’ would output 88.

Public Functions

JsonStreamReader()

Default constructor. Initializes an empty reader.

JsonStreamReader(const char *data, size_t len)

Constructor to initialize the reader with a JSON buffer.

Parameters:
  • data – Pointer to the JSON buffer.

  • len – Length of the JSON buffer.

void loadBuffer(const char *data, size_t len)

Load a new JSON buffer into the reader.

Parameters:
  • data – Pointer to the JSON buffer.

  • len – Length of the JSON buffer.

bool validate()

Validate the loaded JSON buffer.

Returns:

true if the buffer is a valid JSON, false otherwise.

bool isValid() const

Check if the JSON buffer is valid.

Returns:

true if the buffer is valid, false otherwise.

bool getNull(const char *query, bool &outValue) const

Retrieve a null value for a given query.

Parameters:
  • query – The object keys and array indexes to search for.

  • outValue – [out] true if the query contains null.

Returns:

true if the query is found, false otherwise.

bool get(const char *query, bool &outValue) const

Retrieve a boolean value.

Parameters:
  • query – The object keys and array indexes to search for.

  • outValue – [out] The boolean value retrieved.

Returns:

true if the query is found and the value is valid.

bool get(const char *query, int8_t &outValue) const

Retrieve an integer value.

Parameters:
  • query – The object keys and array indexes to search for.

  • outValue – [out] The value retrieved.

Returns:

true if the query is found and the value is valid.

bool get(const char *query, float &outValue) const

Retrieve an floating-point value.

Parameters:
  • query – The object keys and array indexes to search for.

  • outValue – [out] The value retrieved.

Returns:

true if the query is found and the value is valid.

bool get(const char *query, const char *&outValue, size_t &outLen) const

Retrieve a string value from the JSON buffer.

Note

The string is not null-terminated, so its length is also provided.

Parameters:
  • query – The object keys and array indexes to search for.

  • outValue – [out] Pointer to the start of the string value associated with the query.

  • outLen – [out] Length of the retrieved string value.

Returns:

true if the query is found and the value is successfully retrieved, false otherwise.

bool get(const char *query, std::string_view &outValue) const

Retrieve a string value from the JSON buffer.

Note

The string is not null-terminated, so its length is also provided.

Parameters:
  • query – The object keys and array indexes to search for.

  • outValue – [out] Reference to store the string value associated with the query.

Returns:

true if the query is found and the value is successfully retrieved, false otherwise.

bool getArrayLength(const char *query, size_t &outLength) const

Get the number of elements in an array specified by a query path.

This method searches the JSON structure using the provided query string (e.g., β€œ[2].bar”) and, if the located element is an array, counts the number of items in that array.

For example, if the JSON data represents: [123,456,{β€œfoo”:”abc”,”bar”:[88,99]}] a query of β€œ[2].bar” would locate the array [88,99] and return a length of 2.

Parameters:
  • query – The query path string specifying the location of the array.

  • outLength – [out] The number of elements in the resulting array.

Returns:

true if the query is successful and the array’s length is determined, false otherwise.