Pular para o conteúdo
ThingFace

Referência do binding Rust (devui)

O binding para Rust no ESP-IDF (bindings/rust/devui): uma camada fina e segura sobre as funções do devui.h (a referência em C); o que ele ainda não cobre está na abertura do crate, logo abaixo. O texto de cada item é o /// dele, em inglês, como o código.

O 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.

Constantes

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.

Tipos

Error

pub enum Error

The errors of devui.h (its table), one per code. Error::VersionMismatch is the binding's own.

VarianteDescrição
InvalidArgESP_ERR_INVALID_ARG: a session out of 1..0x7FFF, an unknown option bit, reply to what is not a request.
InvalidStateESP_ERR_INVALID_STATE: not now (stopped, already running, send offline, no button window, no entropy source).
NoMemESP_ERR_NO_MEM: the send queue is full (wait for Event::TxReady), or no memory at start.
InvalidSizeESP_ERR_INVALID_SIZE: above the largest message.
NotFoundESP_ERR_NOT_FOUND: no such session open.
NotSupportedESP_ERR_NOT_SUPPORTED: a feature of a later phase (local, a reserved field).
TimeoutESP_ERR_TIMEOUT: the SDK's task did not take the call in time (a bug).
FailESP_FAIL: start could not set up its key, its storage or its task (its stack out of the DRAM included).
OverQuotaDEVUI_ERR_OVER_QUOTA: above the plan's quota; the next send in a moment goes through.
HasOwnerDEVUI_ERR_HAS_OWNER: pair_begin on a device that has an owner.
StaleRequestDEVUI_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).
VersionMismatchThe 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.

VarianteDescrição
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.

VarianteDescrição
BrowserA person's tab, in the portal or the product's page (DEVUI_SESSION_BROWSER, 0).
ApiA 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.
DeviceAnother 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.

CampoDescrição
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: u32OPT_*.
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: boolThe SDK's task in the Task WDT (off by default).
pub host: &'static CStrTests 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<()>
  1. The answer to this request, to the tab that asked only (devui_reply); Error::StaleRequest when 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.

CampoDescrição
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.

VarianteDescrição
UnknownA cause this SDK did not see.
NetworkThe Wi-Fi fell, or the connection dropped with no close frame (TCP, TLS).
CloudThe cloud closed it (the close code says why).
DeviceThe SDK closed it (the close code says why).
SilentNo sign of the connection past the ping interval plus the pong timeout.
SendStalledA send found no room in the socket for 10 s.
Stoppedstop 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.

VarianteDescrição
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).

CampoDescrição
pub open: bool—
pub role: Role—
pub kind: SessionKind—

Status

pub enum Status

Stopped, connecting or online.

VarianteDescrição
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.

VarianteDescrição
OkThe callee answered: CallResult::data.
Offlineoffline: 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).
NoReplysem_resposta: no answer in time; the callee MAY have acted.
NotLinkednao_ligado: no link with this alias on this device.
Forbiddenproibido: blocked, the link's role refused, or the callee's firmware refused it.
Limitlimite: 60 calls a minute per link, 4 at once, or a quota (CallResult::retry_after_ms).
Unsupportedfirmware_sem_suporte: the callee's SDK takes no call of a device.
Busyocupado: the callee's sessions are full.
TooLargegrande_demais: the call or the answer above what the other side takes.
NotSentThe connection ended before the call left: nothing was done.
ErrorAn 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.

CampoDescrição
pub status: CallStatus—
pub result: u8The 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: boolThe answer came as text.
pub retry_after_ms: u32CallStatus::Limit: the wait the cloud asks for (0: none said).
pub error_code: u16CallStatus::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).

Funções

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<()>
  1. Creates or loads the key and starts connecting (devui_start). First, the C library must be the version the binding was generated from: Error::VersionMismatch otherwise, and the C is never called.

stop

pub fn stop() -> Result<()>
  1. Closes the connection and stops the SDK (the key stays).

reply

pub fn reply(req: &Request, data: &[u8]) -> Result<()>
  1. 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>>)
  1. The callback of the pages' messages (devui_on_message); None removes it. It runs in the SDK's task: short, never blocking. Set it before start, 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 next on_message made 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 with devui_on_* that calls this is not supported.

on_event

pub fn on_event(cb: Option<Box<EvFn>>)
  1. The callback of the events (devui_on_event); None removes it. As on_message.

send

pub fn send(session: u16, data: &[u8], flags: u32) -> Result<()>
  1. Copies to the SDK's bounded queue and returns at once (devui_send). session: a tab's, or ALL; flags: TEXT, STATE.

session_info

pub fn session_info(session: u16) -> Result<SessionInfo>
  1. devui_session_info: Error::NotFound when 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
  1. devui_status.

pair_begin

pub fn pair_begin() -> Result<()>
  1. A new pairing code, told in Event::PairCode (devui_pair_begin).

pair_confirm

pub fn pair_confirm() -> Result<()>
  1. One press of the button, after Event::PairButton (devui_pair_confirm).

factory_reset

pub fn factory_reset() -> Result<()>
  1. 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<()>
  1. The local mode: the board serves its UI on the LAN behind its login (devui_local); Error::NotSupported in a build without CONFIG_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.