The device APIs for WebAssembly
A WebAssembly module of ztcl::wasm gets the APIs of a phone that a Tcl script has: the battery, the network, vibration, and haptics (ztcl::device), the position (ztcl::location), the motion sensors (ztcl::motion), and sounds (ztcl::audio). A program in Rust, Zig, C, or another language that compiles to wasm calls them as imports.
Use these imports for a module that does the work of an app on a phone, such as a map, a game with tilt, or a tracker of walks. The Tcl commands give the same answers, so a script and a module can share the work.
The package is ztcl:device@0.1.0 in wit/device/, with four interfaces. Each interface is an import family of ztcl::wasm::host, with the common rules of its error codes, handles, and byte ranges.
| Family | Tcl command | Capability | Permission of the user |
|---|---|---|---|
info |
ztcl::device |
device |
none (Android: VIBRATE and ACCESS_NETWORK_STATE in the manifest, which Android grants at the install) |
location |
ztcl::location |
location |
a dialog of the OS: iOS needs NSLocationWhenInUseUsageDescription in its Info.plist; Android the fine and coarse location in its manifest |
motion |
ztcl::motion |
sensors |
none |
audio |
ztcl::audio |
audio |
none |
A capability lets a script ask; the OS asks the user. With no permission, a module gets no position: its handle gets the failure denied.
The grant
A module gets a family only when the host script gives it with -grant, and only when the interpreter has the capability of the family:
package require ztcl::wasm::host
proc log {ptr len} { puts [ztcl::wasm memory $::w string $ptr $len] }
set w [ztcl::wasm::host instantiate [ztcl::wasm load app.wasm] \
-grant {location {} motion {-handles 4}} -imports {tk {log log}}]
ztcl::wasm call $w app_init
vwait done
Each family has the option -handles N, the most handles that are live at once (16 by default), and audio has -max-bytes N, the most bytes of one sound (16 MiB by default). The import tk.log of these examples is a proc of the host script that prints the text of the module. An app of ztk gives the same import, so the same module runs in a ztk app on iOS and Android, where the line goes to the log of the app.
How a reading arrives
A function that watches, such as location.watch or motion.watch, takes a callback: a number that the module chooses. It gives a handle at once, with no reading. The sensor or the service of the phone then sends each reading, from a thread of the OS, to the event loop of the host script, and for each one the host calls the export app_event(callback) of the module. In that call, and only there, event_f64(key) gives a number of the reading and event_str(key, buf) its text.
So no reading arrives while the event loop of the host does not run: the host script needs vwait, or the event loop of Tk in an app of ztk, after app_init. A function that gives a state at once, such as info.battery_level or motion.has, needs no event. A callback of 0 gets no event.
The keys of a reading are those of the dict of the Tcl command, with the same units:
| Family | The keys of a reading | Where they are |
|---|---|---|
info |
level, state of the battery; connected, type, metered, constrained of the network |
ztcl::device |
location |
latitude, longitude, accuracy, altitude, vaccuracy, speed, course, time; permission of request; error of a failure |
ztcl::location |
motion |
x, y, z (and w of rotation); magnetic, accuracy, true of heading; time |
ztcl::motion |
audio |
status: done, stopped, or error |
ztcl::audio |
event_f64 gives NaN for a key with no number, such as latitude in a failure, which has the key error in its place; event_str gives the text of any key, such as state or error.
A handle of request, get, or play ends at its event, and a handle of a watch ends at a failure or at cancel. The module needs an export app_event for a callback that is not 0: else the function gives state. An embedder that calls the module from its own loop, such as ztk, sets ::ztcl::wasm::host::device::deliver to a command prefix that gets each event and calls ::ztcl::wasm::host::device::Deliver when the module can take it.
Examples
Each example is a crate with crate-type = ["cdylib"] and no dependency, built with cargo build --release --target wasm32-unknown-unknown. Each one starts with these helpers:
#[link(wasm_import_module = "tk")]
extern "C" {
fn log(ptr: *const u8, len: usize);
}
fn say(text: &str) {
unsafe { log(text.as_ptr(), text.len()) }
}
The output of each example is that of ztcl --allow package,file,channels,event,CAPABILITY --fake-device host.tcl, with the host script of the grant and the family of the example. The fake host of --fake-device gives the same answers in each run.
The battery
#[link(wasm_import_module = "info")]
extern "C" {
fn battery_level() -> i32;
fn watch(what: i32, cb: i32) -> i32;
fn event_f64(key: *const u8, len: usize) -> f64;
}
const BATTERY: i32 = 1;
#[no_mangle]
pub extern "C" fn app_init() {
let level = unsafe { battery_level() };
if level < 0 {
say("no battery level");
return;
}
say(&format!("now {level} %"));
// watched: battery = 0, network = 1
unsafe { watch(0, BATTERY) };
}
#[no_mangle]
pub extern "C" fn app_event(cb: i32) {
if cb == BATTERY {
let key = "level";
let level = unsafe { event_f64(key.as_ptr(), key.len()) };
say(&format!("changed to {level} %"));
}
}
now 80 %
changed to 80 %
changed to 81 %
changed to 82 %
The position
#[link(wasm_import_module = "location")]
extern "C" {
fn get(accuracy: i32, timeout_ms: u32, cb: i32) -> i32;
fn event_f64(key: *const u8, len: usize) -> f64;
fn event_str(key: *const u8, len: usize, buf: *mut u8, cap: usize) -> i32;
}
const FIX: i32 = 1;
fn number(key: &str) -> f64 {
unsafe { event_f64(key.as_ptr(), key.len()) }
}
fn text(key: &str) -> String {
let mut buf = [0u8; 64];
let n = unsafe { event_str(key.as_ptr(), key.len(), buf.as_mut_ptr(), buf.len()) };
if n < 0 {
return String::new();
}
String::from_utf8_lossy(&buf[..(n as usize).min(buf.len())]).into_owned()
}
#[no_mangle]
pub extern "C" fn app_init() {
// accuracy: best = 0; at most 10 s. The OS asks for the permission.
unsafe { get(0, 10_000, FIX) };
}
#[no_mangle]
pub extern "C" fn app_event(cb: i32) {
if cb != FIX {
return;
}
let lat = number("latitude");
if lat.is_nan() {
say(&format!("no position: {}", text("error")));
} else {
say(&format!("at {lat}, {}, within {} m", number("longitude"), number("accuracy")));
}
}
at 42.3314, -83.0458, within 5 m
The motion sensors
#[link(wasm_import_module = "motion")]
extern "C" {
fn has(kind: i32) -> i32;
fn watch(kind: i32, interval_ms: u32, cb: i32) -> i32;
fn cancel(h: i32) -> i32;
fn event_f64(key: *const u8, len: usize) -> f64;
}
// kind: accelerometer = 0, gyroscope = 1, rotation = 2, heading = 3
const HEADING: i32 = 3;
static mut WATCH: i32 = 0;
static mut COUNT: i32 = 0;
#[no_mangle]
pub extern "C" fn app_init() {
if unsafe { has(HEADING) } != 1 {
say("no compass");
return;
}
unsafe { WATCH = watch(HEADING, 100, 1) };
}
#[no_mangle]
pub extern "C" fn app_event(_cb: i32) {
let key = "magnetic";
let deg = unsafe { event_f64(key.as_ptr(), key.len()) };
say(&format!("heading {deg}°"));
unsafe {
COUNT += 1;
if COUNT == 3 {
cancel(WATCH);
}
}
}
heading 0°
heading 30°
heading 60°
A sound
#[link(wasm_import_module = "audio")]
extern "C" {
fn set_session(session: i32) -> i32;
fn play(data: *const u8, len: usize, volume: f64, plays: u32, cb: i32) -> i32;
fn event_str(key: *const u8, len: usize, buf: *mut u8, cap: usize) -> i32;
}
// A WAV file of the crate, in the module.
static DING: &[u8] = include_bytes!("ding.wav");
#[no_mangle]
pub extern "C" fn app_init() {
// session: ambient = 0, playback = 1, solo = 2
unsafe { set_session(0) };
let h = unsafe { play(DING.as_ptr(), DING.len(), 0.8, 1, 1) };
if h < 0 {
say("the sound did not play");
}
}
#[no_mangle]
pub extern "C" fn app_event(_cb: i32) {
let key = "status";
let mut buf = [0u8; 16];
let n = unsafe { event_str(key.as_ptr(), key.len(), buf.as_mut_ptr(), buf.len()) };
if n > 0 {
say(&format!("the sound ended: {}", String::from_utf8_lossy(&buf[..n as usize])));
}
}
the sound ended: done
On a desktop, with no fake host, each family gives unavailable: a module can test that at its start, as the battery example does with its level.
Reference
The tables come from the WIT files. The core type is that of ztcl::wasm: a pointer and a length are two i32. The error codes of each family are those of the rules of each family.
info
The interface info of wit/device/info.wit: each import is info.NAME of the module.
| Import | Core type | What it does |
|---|---|---|
last_error(buf) |
(i32 i32) -> i32 |
The text of the last error of the family, for the instance. |
battery_level() |
() -> i32 |
The charge of the battery in percent, 0 to 100. A phone with no level, such as the iOS Simulator, gives unavailable. |
battery_state() |
() -> i32 |
The state of the battery: a battery-status. |
network_type() |
() -> i32 |
The type of the network: a network-kind. |
network_flags() |
() -> i32 |
The state of the network as bits: 1 connected, 2 metered (a network that costs), 4 constrained (Low Data Mode of iOS, Data Saver of Android). |
vibrate(pattern) |
(i32 i32) -> i32 |
Vibrates: the times in milliseconds, on, off, on, and so on, 1 to 64 times of 0 to 10,000. |
haptic(kind) |
(i32) -> i32 |
A haptic feedback of the system. |
watch(what, cb) |
(i32 i32) -> i32 |
Follows the battery or the network. Each change is an event with the keys of ztcl::device battery (level, state) or network (connected, type, metered, constrained). The first one comes soon after the call. |
cancel(h) |
(i32) -> i32 |
Ends a handle. A handle that ended is no error. |
event_f64(key) |
(i32 i32) -> f64 |
In app_event: the number of the key of the reading, 1 or 0 for a flag, or NaN when the reading has no such number. |
event_str(key, buf) |
(i32 i32 i32 i32) -> i32 |
In app_event: the text of the key of the reading, such as state. Gives the full byte length, or args for no such key. |
| Enum | Values |
|---|---|
battery-status |
charging 0, full 1, unplugged 2, unknown 3 |
network-kind |
wifi 0, cellular 1, ethernet 2, none 3 |
haptic-kind |
light 0, medium 1, heavy 2, success 3, warning 4, error 5 |
watched |
battery 0, network 1 |
location
The interface location of wit/device/location.wit: each import is location.NAME of the module.
| Import | Core type | What it does |
|---|---|---|
last_error(buf) |
(i32 i32) -> i32 |
|
permission() |
() -> i32 |
The permission of the user, a permission-state. It shows no dialog. |
enabled() |
() -> i32 |
1 when the location service of the device is on. |
request(cb) |
(i32) -> i32 |
Shows the dialog of the OS when the permission is undetermined. One event: the key permission (granted or denied). |
get(acc, timeout_ms, cb) |
(i32 i32 i32) -> i32 |
One position: an event with the keys latitude, longitude (degrees), accuracy (meters), altitude, vaccuracy, speed, course, when the device has them, and time (milliseconds of the epoch). A failure is an event with the key error: denied, unavailable, or timeout. timeout-ms 0 waits with no limit. |
watch(acc, distance_m, interval_ms, cb) |
(i32 i32 i32 i32) -> i32 |
A position at each move, as get gives one. distance-m and interval-ms are the least move and the least time between two positions, or 0 for none. A failure ends the handle. |
cancel(h) |
(i32) -> i32 |
|
event_f64(key) |
(i32 i32) -> f64 |
|
event_str(key, buf) |
(i32 i32 i32 i32) -> i32 |
| Enum | Values |
|---|---|
permission-state |
granted 0, denied 1, undetermined 2 |
accuracy |
best 0, balanced 1, low 2 |
motion
The interface motion of wit/device/motion.wit: each import is motion.NAME of the module.
| Import | Core type | What it does |
|---|---|---|
last_error(buf) |
(i32 i32) -> i32 |
|
has(k) |
(i32) -> i32 |
1 when the device has the sensor, else 0. |
watch(k, interval_ms, cb) |
(i32 i32 i32) -> i32 |
A reading about each interval-ms milliseconds, 10 to 60,000: an event with the keys of ztcl::motion. accelerometer: x y z in m/s² with gravity (+9.81 on z with the phone flat and face up). gyroscope: x y z in rad/s. rotation: x y z w, a quaternion in the frame east, north, up. heading: magnetic and accuracy in degrees, and true while a location is known. Each reading has time, in milliseconds of the uptime of the device. |
cancel(h) |
(i32) -> i32 |
|
event_f64(key) |
(i32 i32) -> f64 |
|
event_str(key, buf) |
(i32 i32 i32 i32) -> i32 |
| Enum | Values |
|---|---|
kind |
accelerometer 0, gyroscope 1, rotation 2, heading 3 |
audio
The interface audio of wit/device/audio.wit: each import is audio.NAME of the module.
| Import | Core type | What it does |
|---|---|---|
last_error(buf) |
(i32 i32) -> i32 |
|
set_session(s) |
(i32) -> i32 |
Sets the audio session of the app. |
play(data, volume, plays, cb) |
(i32 i32 f64 i32 i32) -> i32 |
Plays the bytes of an audio file, such as WAV, MP3, or AAC, at most the -max-bytes of the grant (16 MiB by default). volume is 0 to 1, and plays is the count of plays, 1 to 1,000, or 0 to repeat until stop. The end is one event with the key status: done, stopped, or error. |
stop(h) |
(i32) -> i32 |
Stops a sound: its event has the status stopped. A sound that ended is no error. |
set_volume(h, volume) |
(i32 f64) -> i32 |
The volume of a sound that plays, 0 to 1. |
event_f64(key) |
(i32 i32) -> f64 |
|
event_str(key, buf) |
(i32 i32 i32 i32) -> i32 |
| Enum | Values |
|---|---|
session |
ambient 0, playback 1, solo 2 |