Rust binding reference (devui)
The binding for Rust on ESP-IDF (bindings/rust/devui): a thin, safe layer over the functions of devui.h (the C reference); what it does not cover yet is in the crate's opening, right below. The text of each item is its ///.
The crate
ThingFace SDK (devui.1) for Rust on ESP-IDF: the internal binding.
The C SDK is the SDK: this crate builds it as an extra component of the ESP-IDF build of esp-idf-sys and wraps its functions (the twelve of the frozen v1 and most of those added since; the contract is the comment of each one in devui.h) in a thin safe layer: results instead of codes, slices and &'static CStr instead of pointers, closures instead of C callbacks. Nothing of the protocol lives here.
sys is generated from devui.h by bindings/rust/gen and carries a version mark. The build script fails when the headers changed after the generation, and start refuses to run a C library of another version than the one the binding was generated from (Error::VersionMismatch): the lesson of the "old C".
What it does not wrap yet, of the C functions added after the first twelve: the local password (devui_local_secret, devui_local_secret_renew), the simple database (devui_db_request, devui_db_insert, devui_db_update, devui_db_delete, devui_db_find, devui_db_aggregate, devui_db_queue), the owner account's preferences (devui_get_prefs; the DEVUI_EV_PREFS event comes as Event::Other) and the vault mode (devui_vault_psk_text, devui_vault_reset, devui_vault_enroll). start passes vault: false (the vault off, as an app of before it), manual_tz: false (the SDK applies the account's time zone to TZ, as the C does by default) and no provision_token (the device pairs by its code). A firmware that needs them calls the C through sys.
Constants
ALL
pub const ALL: u16 = sys::DEVUI_ALL as u16;
send to every open session (broadcast).
TEXT
pub const TEXT: u32 = sys::DEVUI_TEXT;
Flags of send and of Message::flags: the data is UTF-8 text (JSON, for the lib); without it, bytes.
STATE
pub const STATE: u32 = sys::DEVUI_STATE;
Flag of send: the data is the device's whole state; the page sees meta.state.
OPT_READER_DATA
pub const OPT_READER_DATA: u32 = sys::DEVUI_OPT_READER_DATA;
Config::options: the cloud delivers the DATA of reader sessions too.
OPT_OWNER_EVENT
pub const OPT_OWNER_EVENT: u32 = sys::DEVUI_OPT_OWNER_EVENT;
Config::options: the app handles Event::OwnerChanged (it erases there what it keeps of the old owner), so the portal no longer recommends a factory reset before a transfer.
AUDIT_MAX
pub const AUDIT_MAX: usize = sys::DEVUI_AUDIT_MAX as usize;
The longest text of audit, in bytes.
CALL_ALIAS_MAX
pub const CALL_ALIAS_MAX: usize = sys::DEVUI_CALL_ALIAS_MAX as usize;
The longest alias of a link, in bytes.
CALL_MAX_LEN
pub const CALL_MAX_LEN: usize = sys::DEVUI_CALL_MAX_LEN as usize;
The largest call, in bytes.
Types
Error
pub enum Error
The errors of devui.h (its table), one per code. Error::VersionMismatch is the binding's own.
| Variant | Description |
|---|---|
InvalidArg | ESP_ERR_INVALID_ARG: a session out of 1..0x7FFF, an unknown option bit, reply to what is not a request. |
InvalidState | ESP_ERR_INVALID_STATE: not now (stopped, already running, send offline, no button window, no entropy source). |
NoMem | ESP_ERR_NO_MEM: the send queue is full (wait for Event::TxReady), or no memory at start. |
InvalidSize | ESP_ERR_INVALID_SIZE: above the largest message. |
NotFound | ESP_ERR_NOT_FOUND: no such session open. |
NotSupported | ESP_ERR_NOT_SUPPORTED: a feature of a later phase (local, a reserved field). |
Timeout | ESP_ERR_TIMEOUT: the SDK's task did not take the call in time (a bug). |
Fail | ESP_FAIL: start could not set up its key, its storage or its task (its stack out of the DRAM included). |
OverQuota | DEVUI_ERR_OVER_QUOTA: above the plan's quota; the next send in a moment goes through. |
HasOwner | DEVUI_ERR_HAS_OWNER: pair_begin on a device that has an owner. |
StaleRequest | DEVUI_ERR_STALE_REQUEST: reply to a request of a connection that ended (offline, or reconnected since). Nothing was sent, and never will be: drop the answer (the page already failed the request with OFFLINE). |
VersionMismatch | The C library linked is not the version the binding was generated from (c_version against DEVUI_BINDING_SDK_VERSION): an old C, or an old binding. start refuses to run it. |
Esp(i32) | Another code of the ESP-IDF, passed on (an NVS error from start, for one). |
Result
pub type Result<T> = core::result::Result<T, Error>;
The result of the binding's functions: one Error per code of devui.h.
Role
pub enum Role
The role of a session.
| Variant | Description |
|---|---|
Owner | — |
Operator | — |
Reader | — |
Other(u8) | A value a later SDK may add. |
SessionKind
pub enum SessionKind
Who opened a session (DEVUI_SESSION_* of devui.h, the SESSION_KIND of the spec): a person's tab, or a call of the cloud's HTTP API with a device key the owner made. The SDK serves the API always: a firmware that serves only people refuses every kind but SessionKind::Browser (docs/api-de-dispositivos.md). Added after the v1 was frozen, in Event::SessionOpen and SessionInfo.
| Variant | Description |
|---|---|
Browser | A person's tab, in the portal or the product's page (DEVUI_SESSION_BROWSER, 0). |
Api | A call of POST /v1/devices/{id}/messages (DEVUI_SESSION_API, 2): a session that lives for one request, with the key's role and a pseudonym of the key, never a person's. |
Device | Another device, by a link its owner made (call on that device; DEVUI_SESSION_DEVICE, 3): a session that lives for one request, with the link's role and a pseudonym of the link's own. |
Other(u8) | A value a later SDK may add: not a person's tab either. |
Config
pub struct Config
The configuration of start. The C keeps the pointers, so everything it points to is 'static.
| Field | Description |
|---|---|
pub bundle: Option<(&'static [u8], &'static [u8])> | The UI: the DVU1 container and its manifest (tools/devui_pack.py). None: the one of devui_add_bundle in a C component, when there is one, or no UI. |
pub bundle_sig: Option<&'static [u8; 72]> | The bundle's signature, the 72 bytes devui_pack.py --sign-key writes next to it (bundle.sig), sent in the HELLO for the cloud to check with the product's keys. None: no signature (or, with bundle None, the one of devui_add_bundle when the build signed it). |
pub project_key: Option<&'static CStr> | Optional: the product's public key. |
pub fw_version: Option<&'static CStr> | Optional: the app's version, sent in the HELLO (shown at pairing). |
pub options: u32 | OPT_*. |
pub adc_hold: Option<fn(bool)> | Without a radio on, the ADC must be paused around the SDK's random draws: called with true, then false, from the SDK's task. None: no such source. |
pub task_wdt: bool | The SDK's task in the Task WDT (off by default). |
pub host: &'static CStr | Tests and self-host only: the gateway (as in its certificate), its port and its roots (PEM). |
pub port: u16 | — |
pub ca_pem: Option<&'static CStr> | — |
Message
pub struct Message<'a>
A message from a page, valid during the callback only (as in C): copy what is needed.
Message::session
pub fn session(&self) -> u16
The tab's session (1..0x7FFF): send to it answers that tab only.
Message::id
pub fn id(&self) -> u32
Per connection: valid on the connection Message::conn only; Message::reply uses it.
Message::conn
pub fn conn(&self) -> u32
The connection the message came on: a number the SDK counts at each connection, never 0. reply refuses a request of another one (Error::StaleRequest).
Message::flags
pub fn flags(&self) -> u8
TEXT, and the bits Message::is_request and Message::wants_ack read.
Message::data
pub fn data(&self) -> &[u8]
The message's bytes, valid during the callback only (as in C): copy what is needed.
Message::text
pub fn text(&self) -> Option<&str>
The data as text, when the page sent text that is valid UTF-8.
Message::is_request
pub fn is_request(&self) -> bool
The page asked: answer with Message::reply (or later, with Message::request).
Message::wants_ack
pub fn wants_ack(&self) -> bool
The cloud wants an ACK, which the SDK sends when the callback returns.
Message::reply
pub fn reply(&self, data: &[u8]) -> Result<()>
- The answer to this request, to the tab that asked only (
devui_reply);Error::StaleRequestwhen its connection ended.
Message::request
pub fn request(&self) -> Request
What reply needs, to answer after the callback.
Request
pub struct Request
A request kept after its callback (session, id, flags and the connection it came on). Take it from Message::request: the request is answered only on its own connection.
| Field | Description |
|---|---|
pub session: u16 | — |
pub id: u32 | — |
pub flags: u8 | — |
pub conn: u32 | — |
OfflineReason
pub enum OfflineReason
Why the connection ended (Event::Offline; devui_offline_reason_t): the first cause the SDK saw.
| Variant | Description |
|---|---|
Unknown | A cause this SDK did not see. |
Network | The Wi-Fi fell, or the connection dropped with no close frame (TCP, TLS). |
Cloud | The cloud closed it (the close code says why). |
Device | The SDK closed it (the close code says why). |
Silent | No sign of the connection past the ping interval plus the pong timeout. |
SendStalled | A send found no room in the socket for 10 s. |
Stopped | stop or factory_reset. |
Other(u8) | A value a later SDK adds. |
Event
pub enum Event<'a>
An event, valid during the callback only, its strings included.
| Variant | Description |
|---|---|
Online | — |
Offline { reason: OfflineReason, close_code: u16 } | Why, and the WebSocket close code received or sent (0 when none). |
SessionOpen { session: u16, role: Role, reopened: bool, user: Option<&'a [u8; 8]>, kind: SessionKind } | A tab opened, or a call of the API (kind): its session, role and pseudonym (user, 8 bytes), and whether it is a session kept across a reconnection (reopened). |
SessionClose { session: u16 } | — |
PairCode { code: &'a str, url: Option<&'a str>, ttl_s: u16 } | The 8 characters (show them as XXXX-XXXX), the pairing page's URL (once the cloud sent its base) and the seconds left. |
PairButton { window_s: u16 } | — |
Paired | — |
Unpaired | — |
BundleSynced | — |
BundleRejected { result: u8 } | 1 other hash, 2 too large, 3 invalid container, 4 blocked by the cloud, 5 the cloud could not store it now (it asks for it again). |
TxReady | — |
Duplicate | — |
ClockSet | — |
UpdateAdvised | — |
OwnerChanged { gen: u32 } | The device went to another owner (1.2): erase what the app keeps of the old owner before the callback returns, and say so with OPT_OWNER_EVENT. It may come again for the same change after a fall inside the callback (devui.h). gen is the generation of the new ownership, never 0: a number only, compared by equality. |
TrustOrder { event: u8, kind: u8, reason: u8, seq: u32 } | A trust order (1.2, devui.h): event is what happened (1 applied, 2 pending: the 7 days start, 3 refused, 4 due, 5 confirmed by the destination, 6 returned: back to the endpoint before, or an accepted order the NVS could not keep, spent), kind the order's (1 MOVE, 2 ROOTS, 3 KEYS, 4 CANCEL, 5 LIFE; 0 when a refused one did not get through its form), reason a refusal's (1 format to 10 last-root, in the order the SDK checks them; else 0) and seq its SEQ. The SDK applies it by itself. |
PairCodeAccepted { code: &'a str, url: Option<&'a str>, ttl_s: u16 } | The current pairing code is registered in the cloud (devui.h): the cloud's PAIR CODE_ACK of this code came on this connection. The same fields as Event::PairCode, ttl_s being what it has left. Hand out the code or its URL from here when it must already pair; it comes again at a reconnection's resend, so forget it at Event::Offline and at a new Event::PairCode. Never from a cloud without CODE_ACK. |
Other(u32) | A type a later SDK adds. |
SessionInfo
pub struct SessionInfo
Whether a session is open, its role, and who opened it (kind, added after the v1 was frozen).
| Field | Description |
|---|---|
pub open: bool | — |
pub role: Role | — |
pub kind: SessionKind | — |
Status
pub enum Status
Stopped, connecting or online.
| Variant | Description |
|---|---|
Stopped | — |
Connecting | — |
Online | — |
Other(u32) | — |
CallStatus
pub enum CallStatus
What a call gave (devui_call_result_t.status). The cloud's answers have the names of the device API's errors (docs/api-de-dispositivos.md); CallStatus::NotSent and CallStatus::Error are the SDK's.
| Variant | Description |
|---|---|
Ok | The callee answered: CallResult::data. |
Offline | offline: the callee is not connected, or dropped during the call; if it dropped after the call reached it, it MAY have acted (as the device API's 503). |
NoReply | sem_resposta: no answer in time; the callee MAY have acted. |
NotLinked | nao_ligado: no link with this alias on this device. |
Forbidden | proibido: blocked, the link's role refused, or the callee's firmware refused it. |
Limit | limite: 60 calls a minute per link, 4 at once, or a quota (CallResult::retry_after_ms). |
Unsupported | firmware_sem_suporte: the callee's SDK takes no call of a device. |
Busy | ocupado: the callee's sessions are full. |
TooLarge | grande_demais: the call or the answer above what the other side takes. |
NotSent | The connection ended before the call left: nothing was done. |
Error | An answer this version does not know (CallResult::result), or the cloud refused the call's frame (CallResult::error_code). |
Other(u8) | A value a later SDK may add. |
CallResult
pub struct CallResult<'a>
What a call gave, during its callback only.
| Field | Description |
|---|---|
pub status: CallStatus | — |
pub result: u8 | The cloud's answer as it came (0 for the SDK's own statuses). |
pub data: &'a [u8] | CallStatus::Ok: the callee's answer (empty when it answered nothing). |
pub text: bool | The answer came as text. |
pub retry_after_ms: u32 | CallStatus::Limit: the wait the cloud asks for (0: none said). |
pub error_code: u16 | CallStatus::Error: the code of the cloud's ERROR (0 for an unknown answer). |
CallFn
pub type CallFn = dyn FnOnce(&CallResult<'_>) + Send + 'static;
The callback of a call: once, in the SDK's task (short, never blocking).
Functions
c_version
pub fn c_version() -> &'static str
The version the C library was built as (devui_version()), the one its HELLO announces.
start
pub fn start(cfg: &Config) -> Result<()>
- Creates or loads the key and starts connecting (
devui_start). First, the C library must be the version the binding was generated from:Error::VersionMismatchotherwise, and the C is never called.
stop
pub fn stop() -> Result<()>
- Closes the connection and stops the SDK (the key stays).
reply
pub fn reply(req: &Request, data: &[u8]) -> Result<()>
- The answer to a request kept with
Message::request;Error::StaleRequest, with nothing sent, when the connection it came on ended (offline, or online again on a new one): its id would name another request.
on_message
pub fn on_message(cb: Option<Box<MsgFn>>)
- The callback of the pages' messages (
devui_on_message);Noneremoves it. It runs in the SDK's task: short, never blocking. Set it beforestart, or swap it at any time, from any task: as in C, once this returns the callback replaced is neither running nor called again, and the binding frees it then (with what it captured). From inside a callback (of either kind) the C does not wait, so the one replaced is freed later, by the nexton_messagemade outside a callback. Since it waits, never call it holding what the callback may wait for. The binding knows a callback of its own only: one set in C withdevui_on_*that calls this is not supported.
on_event
pub fn on_event(cb: Option<Box<EvFn>>)
- The callback of the events (
devui_on_event);Noneremoves it. Ason_message.
send
pub fn send(session: u16, data: &[u8], flags: u32) -> Result<()>
- Copies to the SDK's bounded queue and returns at once (
devui_send).session: a tab's, orALL;flags:TEXT,STATE.
session_info
pub fn session_info(session: u16) -> Result<SessionInfo>
devui_session_info:Error::NotFoundwhen no such session is open.
session_close
pub fn session_close(session: u16, reason: u16) -> Result<()>
The firmware closes a session (devui_session_close): a person's tab, an API call or a stream of events. reason is a code of the single registry (1000 to 4999), 0 for none; 4405 refuses a machine (the call gets 403 proibido, the stream ends with the event closed). The session is forgotten at once: session_info answers Error::NotFound, its messages still queued are dropped, and no Event::SessionClose comes for it; a message of the cloud to it still in flight is dropped, and a send to it afterwards is taken and dropped, as to any session closed. Error::InvalidArg session 0 or a reason outside the registry; Error::InvalidState stopped or offline; Error::NotFound no such session open; Error::NoMem the queue is full, try again. Added after the v1 was frozen.
status
pub fn status() -> Status
devui_status.
pair_begin
pub fn pair_begin() -> Result<()>
- A new pairing code, told in
Event::PairCode(devui_pair_begin).
pair_confirm
pub fn pair_confirm() -> Result<()>
- One press of the button, after
Event::PairButton(devui_pair_confirm).
factory_reset
pub fn factory_reset() -> Result<()>
- Factory reset: UNPAIR (signed with the device's key), then the key and the SDK's data are erased (
devui_factory_reset).
local
pub fn local() -> Result<()>
- The local mode: the board serves its UI on the LAN behind its login (
devui_local);Error::NotSupportedin a build withoutCONFIG_DEVUI_LOCAL. The local password (devui_local_secret,devui_local_secret_renew) has no wrapper yet, as the database, the preferences and the vault (the crate's opening).
trust_order_local
pub fn trust_order_local(order: &[u8]) -> Result<()>
A trust order brought by a local path (the serial, Improv, the maker's OTA), checked and kept as one from the cloud (devui_trust_order_local): Ok accepted; Error::InvalidArg refused or empty; Error::InvalidState with the SDK stopped or a build with no order keys. Added in 1.2.
audit
pub fn audit(text: &str) -> Result<()>
A business event for the device's log in the portal, "abriu o portão" (devui_audit): 1 to AUDIT_MAX bytes of UTF-8 with no control character. The cloud writes it with its own time and who had the UI open. Ok sent; Error::InvalidArg empty, too long, with a control character, a NUL, U+2028, U+2029, a bidirectional control or the BOM; Error::InvalidState stopped, offline or with no owner; Error::NotSupported a cloud that takes no business event; Error::OverQuota above the cloud's bucket of events; Error::NoMem the way out is full, try again. Added after the v1 was frozen.
call
pub fn call(alias: &str, data: &[u8], timeout_ms: u32, cb: Box<CallFn>) -> Result<()>
Calls another device by the alias of a link its owner made in the portal (devui_call): data goes through this device's own connection, and cb gets what came, once, in the SDK's task (CallStatus). timeout_ms 0 or above 10,000: 10,000. At most once: put a nonce in data. Error::InvalidArg an alias that is not 1 to 32 of a-z, 0-9 and '-'; Error::InvalidSize above 4,096 bytes; Error::InvalidState stopped or offline; Error::NoMem 4 calls wait, or the queue is full; Error::OverQuota above the plan's quota. With an error, cb is dropped and never called. Added after the v1 was frozen.
device_id
pub fn device_id() -> Option<String>
The device_id in base32 (26 characters), after start; outside the twelve, as in C. A copy: the C's buffer is rewritten by the next start, from the SDK's task. None before the first start.
