@geastack/core 0.1.47 → 0.1.48

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -99,6 +99,188 @@ I/O. Missing, truncated or corrupt bundles are rejected until the next process
99
99
  start. Retain older content-addressed files when firmware rollback is required.
100
100
  Apps without this option continue embedding their assets in the executable.
101
101
 
102
+ ## Physical buttons
103
+
104
+ A board's buttons reach the app as key events named after the button:
105
+
106
+ ```tsx
107
+ <div onKeyDown={e => { if (e.code === 'Boot') openMenu() }}
108
+ onKeyUp={e => { if (e.code === 'Power') confirm() }} />
109
+ ```
110
+
111
+ `e.code` is the silkscreen name in PascalCase (`'Boot'`, `'Power'`). `e.key` and
112
+ `e.keyCode` are the button's default key alias (BOOT is `Escape`/27 and PWR is
113
+ `Enter`/13 on the Waveshare S3 boards), so an app that only handles keys still
114
+ works on every board. `Buttons` lists what the board has, before any press:
115
+
116
+ ```ts
117
+ import { Buttons } from '@geastack/core'
118
+ for (let i = 0; i < Buttons.count(); i++) console.log(Buttons.code(i), Buttons.key(i))
119
+ Buttons.pressed('Boot') // held right now?
120
+ Buttons.pin(0) // its GPIO, or -1 for a PMU power key
121
+ ```
122
+
123
+ Buttons are declared as JSON. A board lists its own under `buttons`, in its
124
+ `targets.json` entry, its composed board definition, or its alias in
125
+ `boards.json`:
126
+
127
+ ```json
128
+ "buttons": [
129
+ { "code": "Boot", "pin": 0, "activeLevel": 0, "key": "Escape" },
130
+ { "code": "Power", "source": "pmu", "key": "Enter" }
131
+ ]
132
+ ```
133
+
134
+ An app adds, changes or removes buttons by name in its `package.json`, for every
135
+ board (`gea.targets.esp32.buttons`) or for one
136
+ (`gea.targets.esp32.boards.<id>.buttons`). Use this, for example, for a button
137
+ wired onto a header pin:
138
+
139
+ ```json
140
+ "gea": { "targets": { "esp32": {
141
+ "buttons": [
142
+ { "code": "Fire", "pin": 14, "activeLevel": 0, "key": "Enter" },
143
+ { "code": "Power", "remove": true }
144
+ ]
145
+ } } }
146
+ ```
147
+
148
+ `pin` is a GPIO number. `activeLevel` is the level the pin reads while the button
149
+ is held (default 0); an active-low button gets the internal pull-up, an
150
+ active-high one the pull-down. `key` is the web key name the button stands in
151
+ for, which also sets `keyCode`; give `keyCode` only for a key outside the common
152
+ set. `"source": "pmu"` is the AXP2101 power key. The build checks every entry and
153
+ names the field that is wrong.
154
+
155
+ GPIO buttons are interrupt-driven: one task debounces every edge. A button is
156
+ polled only when its entry says `"poll": true`, for example a pin whose
157
+ interrupt something else owns. The AXP2101 power key is polled on boards that
158
+ leave the PMU's IRQ pin unconnected, because it has no interrupt to wait on. A
159
+ RESET key is the chip's enable line, which no software can see.
160
+
161
+ Presses join the ordered hardware-key queue the frame loop already drains. They
162
+ bubble through the UI tree, and focus and `preventDefault` work as for any key.
163
+ `code` and `key` are plain native strings on the event, so nothing is boxed.
164
+
165
+ ## Digital pins: `Gpio` and `Digital`
166
+
167
+ Two classes drive and read pins. Use whichever you prefer; they are two TS
168
+ front ends over one native backend (`host/gpio.h`, `host/gpio.cpp`) and behave
169
+ the same way underneath.
170
+
171
+ - `Gpio` is the GeaStack class: string options, boolean levels, and an
172
+ `onChange(value)` callback.
173
+ - `Digital` is the ECMA-419 Digital IO class with Moddable's mode numbers.
174
+ Code written for another ECMA-419 host runs unchanged.
175
+
176
+ ```ts
177
+ import { Digital, Gpio } from '@geastack/core'
178
+
179
+ // Gpio
180
+ const led = new Gpio(2, { mode: 'output' })
181
+ const key = new Gpio(14, {
182
+ pull: 'up',
183
+ onChange: (high) => led.write(!high), // pressed pulls the pin low
184
+ })
185
+
186
+ // ECMA-419 Digital
187
+ const button = new Digital({
188
+ pin: 15,
189
+ mode: Digital.InputPullUp,
190
+ edge: Digital.Rising | Digital.Falling,
191
+ onReadable() {
192
+ console.log(this.read()) // `this` is the Digital
193
+ },
194
+ })
195
+ ```
196
+
197
+ ### Interrupts by default
198
+
199
+ An input with a callback is interrupt-driven. The pin's edge interrupt does
200
+ nothing but mark the pin. The callback then runs on the app thread at the start
201
+ of the next frame: after pending microtasks, before `requestAnimationFrame`
202
+ callbacks. State it changes therefore renders in that same frame. Several
203
+ edges within one frame give one call. The callback reads the level at that
204
+ moment, so it always sees where the pin is now.
205
+
206
+ To poll instead, pass `poll: <milliseconds>`, for example for a noisy line you
207
+ would rather sample than interrupt on. Polling also covers a platform or pin
208
+ with no edge interrupt; such a pin is read once per frame.
209
+
210
+ ```ts
211
+ new Gpio(14, { pull: 'up', onChange, poll: 20 })
212
+ new Digital({ pin: 15, mode: Digital.Input, edge: Digital.Falling, onReadable, poll: 20 })
213
+ ```
214
+
215
+ There is no debouncing; the level is read when the callback runs.
216
+
217
+ - `Gpio` with both edges (the default whenever `onChange` is given) reports
218
+ only real changes, so a bounce that settles back where it started reports
219
+ nothing.
220
+ - A pin watching one edge reports when it has settled on that edge's level:
221
+ high for `rising`, low for `falling`.
222
+ - `Digital` calls `onReadable` once for each frame that saw an edge it asked
223
+ for, and `this.read()` gives the level.
224
+
225
+ ### `Gpio`
226
+
227
+ `new Gpio(pin, options?)` opens the pin and throws if it cannot be opened. That
228
+ happens for a pin the chip does not have, a pin that is already open, or a
229
+ target with no GPIO.
230
+
231
+ | Option | Values | Default |
232
+ | --- | --- | --- |
233
+ | `mode` | `'input'`, `'output'`, `'openDrain'` | `'input'` |
234
+ | `pull` | `'none'`, `'up'`, `'down'`, `'both'` (inputs) | `'none'` |
235
+ | `edge` | `'none'`, `'rising'`, `'falling'`, `'both'` | `'both'` when `onChange` is given, else `'none'` |
236
+ | `onChange` | `(value: boolean) => void` | none |
237
+ | `poll` | milliseconds | interrupts |
238
+
239
+ Methods:
240
+
241
+ - `read()` returns the level; for an output, the level it drives.
242
+ - `write(value)` drives an output. It throws on an input.
243
+ - `close()` releases the pin and its interrupt. Closing from inside the pin's
244
+ own callback is allowed.
245
+ - `pin` holds the pin number.
246
+
247
+ The older static calls `Gpio.configureOutput(pin)`, `Gpio.configureInput(pin,
248
+ pullUp)`, `Gpio.write(pin, level)` and `Gpio.read(pin)` still work. They answer
249
+ "did this board do it" with a boolean instead of throwing.
250
+
251
+ ### `Digital` (ECMA-419)
252
+
253
+ `new Digital({ pin, mode, edge?, onReadable?, target?, format?, poll? })`.
254
+
255
+ - **Modes:** `Digital.Input`, `InputPullUp`, `InputPullDown`,
256
+ `InputPullUpDown`, `Output` and `OutputOpenDrain`.
257
+ - **Edges:** `Digital.Rising` and `Digital.Falling`, OR'd together for both.
258
+ `edge` is required with `onReadable`, and an output takes no edge.
259
+ - **Methods:** `read()` returns 0 or 1, `write(0 | 1)` drives an output, and
260
+ `close()` releases the pin.
261
+ - **`target`:** kept as `this.target` for the callback. Its type comes from the
262
+ value you pass, so it stays native.
263
+ - **`format`:** only `'number'` is supported.
264
+ - **`poll`:** a GeaStack extension; see above.
265
+
266
+ Bad options throw `RangeError`, as the standard says. A pin that cannot be
267
+ opened throws `Error`.
268
+
269
+ ### Board buttons
270
+
271
+ A pin the board declares as a button (see above) can also be opened as an
272
+ input, for an app that wants levels rather than key events. The pin then keeps
273
+ the button's own setup and interrupt, so key events keep arriving.
274
+ `Buttons.pin(i)` tells you which GPIO a button is on. A polled button's pin is
275
+ polled by `Gpio`/`Digital` too.
276
+
277
+ ### Where pins work
278
+
279
+ ESP32 targets drive real pins through ESP-IDF, with up to 32 pins open at once.
280
+ On other targets (desktop, mobile, the simulator) there is no GPIO. There,
281
+ `new Gpio()` and `new Digital()` throw, and the static calls return false. An
282
+ app that wants to run on both should catch the error.
283
+
102
284
  ## Related packages
103
285
 
104
286
  - `@geastack/engine` renders the element tree, `@geastack/host` supplies the
package/gea_app_entry.cpp CHANGED
@@ -6,6 +6,7 @@
6
6
  #include "gea_perf_config.h" // GEA_EMBEDDED_PERF master + per-subsystem perf flags
7
7
  #include "gea/embedded.h"
8
8
  #include "host/backends.h"
9
+ #include "host/gpio.h"
9
10
  #include "host/worker.h"
10
11
  #include "ui/node_features.h"
11
12
  #include "ui/style.h"
@@ -41,7 +42,7 @@ void drainMicrotasks();
41
42
  #endif
42
43
  extern "C" void gea_cycle_collection_defer_begin() GEA_PROGRAM_HOOK;
43
44
  extern "C" void gea_cycle_collection_defer_end() GEA_PROGRAM_HOOK;
44
- extern "C" bool gea_embedded_assets_prepare() __attribute__((weak));
45
+ extern "C" bool gea_embedded_assets_prepare() GEA_PROGRAM_HOOK;
45
46
 
46
47
  namespace gea::framework::app {
47
48
 
@@ -281,6 +282,8 @@ void Application::frame(int timestampMs)
281
282
  #if defined(GEA_EMBEDDED_DIRECT_CANVAS_CONTEXT) && GEA_EMBEDDED_DIRECT_CANVAS_CONTEXT
282
283
  applicationFramePhaseSet(ApplicationFramePhase::DrainMicrotasks);
283
284
  generated::drainMicrotasks();
285
+ // Pin edges first, so state they change renders in this frame.
286
+ gea::host::gpio::runCallbacks();
284
287
  applicationFramePhaseSet(ApplicationFramePhase::AnimationFrameCallbacks);
285
288
  gea::host::runAnimationFrameCallbacks(timestampMs);
286
289
  generated::drainMicrotasks();
@@ -306,6 +309,10 @@ void Application::frame(int timestampMs)
306
309
  generated::drainMicrotasks();
307
310
  recordFramePhase(ApplicationFramePhase::DrainMicrotasks, phaseClockUs() - startUs);
308
311
 
312
+ // Pin edges (Gpio/Digital callbacks): after the microtasks, before rAF, so
313
+ // state they change renders in this frame. Their microtasks drain with rAF's.
314
+ gea::host::gpio::runCallbacks();
315
+
309
316
  startUs = phaseClockUs();
310
317
  applicationFramePhaseSet(ApplicationFramePhase::AnimationFrameCallbacks);
311
318
  gea::host::runAnimationFrameCallbacks(timestampMs);
package/gea_sources.mjs CHANGED
@@ -92,7 +92,9 @@ export function cxxSources(env = process.env) {
92
92
  ...cpp(join(host, 'host'), [
93
93
  'timers', 'worker', 'input', 'device', 'display', 'fetch', 'media', 'rtc', 'websocket', 'http', 'wifi',
94
94
  'ble', 'apps', 'audio', 'audio_worklet', 'audio_buffer_runtime', 'video', 'mjpeg', 'image', 'touch', 'imu', 'memory', 'camera', 'geolocation',
95
- 'tile_loader'
95
+ 'tile_loader',
96
+ // The no-GPIO backend; empty on ESP32, which builds host/gpio.cpp.
97
+ 'gpio_unavailable'
96
98
  ]),
97
99
  // framework services (built on the platform abstraction — no target-specific deps)
98
100
  ...cpp(join(host, 'services'), [
package/include/gpio.h CHANGED
@@ -24,6 +24,32 @@ public:
24
24
  // Reads low as false. A pin that was never configured, or a platform with no
25
25
  // GPIO, also reads false — callers that care must check configureInput().
26
26
  static bool read(int pin);
27
+
28
+ // The ECMA-419 Digital modes, with the same numbers Moddable uses, so the
29
+ // TS classes hand them straight through.
30
+ enum Mode : int {
31
+ Input = 0,
32
+ InputPullUp = 1,
33
+ InputPullDown = 2,
34
+ InputPullUpDown = 3,
35
+ Output = 8,
36
+ OutputOpenDrain = 9,
37
+ };
38
+ // Edge masks for watch().
39
+ static constexpr int kRising = 1;
40
+ static constexpr int kFalling = 2;
41
+
42
+ // configureInput/configureOutput for every mode above. False for a mode
43
+ // this chip cannot do on this pin.
44
+ static bool configure(int pin, int mode);
45
+
46
+ // Interrupts on an input's edges (kRising | kFalling). Each edge sets bit
47
+ // `slot` (0-31) of the mask takeEdges() returns and clears; nothing else
48
+ // runs in interrupt context. False when this platform or pin has no edge
49
+ // interrupt, and the caller then polls read() instead.
50
+ static bool watch(int pin, int edges, int slot);
51
+ static void unwatch(int pin);
52
+ static unsigned takeEdges();
27
53
  };
28
54
 
29
55
  // WS2812-family LED on one data pin: the "onboard RGB LED" of most ESP32-S3
package/include/input.h CHANGED
@@ -30,9 +30,42 @@ void queueKeyDown(int keyCode);
30
30
  // Queue a release in the same ordered stream as key presses.
31
31
  void queueKeyUp(int keyCode);
32
32
 
33
+ // Named physical buttons. A board declares each of its buttons once, by the
34
+ // name its silkscreen gives it; a press then reaches the app as a keydown/keyup
35
+ // whose `code` is that name ("Boot", "Power") and whose `key`/`keyCode` are the
36
+ // button's default key alias ("Escape"/27), so an app that only knows keys
37
+ // keeps working and one that cares can tell the buttons apart.
38
+ constexpr int kMaxButtons = 8;
39
+
40
+ // Returns the button's id, or -1 when the table is full or `code` is empty.
41
+ // Registering a code that is already registered returns its existing id. The
42
+ // strings must outlive the program (board tables are string literals). A
43
+ // button with no key alias passes key "" and keyCode 0: its events carry
44
+ // key "Unidentified". `pin` is its GPIO, -1 for one that is not a GPIO (a
45
+ // PMU's power key).
46
+ int registerButton(const char *code, const char *key, int keyCode, int pin = -1);
47
+
48
+ // Queues a press or release of a registered button, in the same ordered stream
49
+ // as queueKeyDown/queueKeyUp. Safe from any task (not from an ISR).
50
+ void queueButton(int id, bool pressed);
51
+
52
+ int buttonCount();
53
+ // "" for an id that is not registered.
54
+ const char *buttonCode(int id);
55
+ const char *buttonKey(int id);
56
+ int buttonKeyCode(int id);
57
+ // -1 for an id that is not registered or a button that is not a GPIO.
58
+ int buttonPin(int id);
59
+ // The id of a registered code, or -1.
60
+ int findButton(const char *code);
61
+ // The level the platform last reported, not what the app has consumed yet.
62
+ bool buttonPressed(int id);
63
+
33
64
  struct HardwareKeyEvent {
34
65
  int keyCode;
35
66
  bool pressed;
67
+ // The registered button that raised it, or -1 for a bare key code.
68
+ int button = -1;
36
69
  };
37
70
 
38
71
  // Consume the oldest press or release without changing their order.
@@ -27,8 +27,10 @@ struct AssetSegment {
27
27
  inline bool loadAssetBundle(const char *path, const AssetSegment *segments,
28
28
  std::size_t count, std::size_t bytes,
29
29
  std::uint32_t expectedCrc) {
30
- if (!ensureMounted())
30
+ if (!ensureMounted()) {
31
+ std::fprintf(stderr, "Gea asset bundle storage not mounted: %s\n", path);
31
32
  return false;
33
+ }
32
34
  auto *file = std::fopen(path, "rb");
33
35
  if (!file) {
34
36
  std::fprintf(stderr, "Gea asset bundle missing: %s\n", path);
package/index.d.ts CHANGED
@@ -1409,17 +1409,129 @@ export interface InputController {
1409
1409
 
1410
1410
  export declare const Input: InputController
1411
1411
 
1412
- export interface GpioController {
1413
- // Drive a pin. Returns whether this board did it: a pin the chip does not
1414
- // have, or a target with no GPIO at all, reports false rather than throwing,
1415
- // so an app written for one board degrades on another instead of crashing.
1416
- configureOutput(pin: number): boolean
1417
- configureInput(pin: number, pullUp: boolean): boolean
1418
- write(pin: number, level: boolean): boolean
1419
- read(pin: number): boolean
1412
+ export type GpioMode = 'input' | 'output' | 'openDrain'
1413
+ export type GpioPull = 'none' | 'up' | 'down' | 'both'
1414
+ export type GpioEdge = 'none' | 'rising' | 'falling' | 'both'
1415
+
1416
+ export interface GpioOptions {
1417
+ /** Defaults to 'input'. */
1418
+ mode?: GpioMode
1419
+ /** An input's internal pull resistor. Defaults to 'none'. */
1420
+ pull?: GpioPull
1421
+ /** Which edges call `onChange`. Defaults to 'both' when `onChange` is given. */
1422
+ edge?: GpioEdge
1423
+ /** Called on the app thread with the level after an edge. */
1424
+ onChange?: (value: boolean) => void
1425
+ /**
1426
+ * Poll every this many milliseconds instead of using the pin's edge
1427
+ * interrupt. Leave it out: inputs are interrupt-driven by default.
1428
+ */
1429
+ poll?: number
1430
+ }
1431
+
1432
+ /**
1433
+ * One digital pin. Inputs with an `onChange` are interrupt-driven: the edge
1434
+ * interrupt only marks the pin, and `onChange` runs on the app thread at the
1435
+ * start of the next frame. Throws when the pin cannot be opened in that mode
1436
+ * (a pin the chip does not have, a pin already open, a target with no GPIO).
1437
+ *
1438
+ * ```ts
1439
+ * const led = new Gpio(2, { mode: 'output' })
1440
+ * const key = new Gpio(14, { pull: 'up', onChange: (high) => led.write(!high) })
1441
+ * ```
1442
+ *
1443
+ * Shares its native backend with the ECMA-419 `Digital` class. The static
1444
+ * pin-number calls are the older API and keep working.
1445
+ */
1446
+ export declare class Gpio {
1447
+ constructor(pin: number, options?: GpioOptions)
1448
+ readonly pin: number
1449
+ /** The pin's level; for an output, the level it drives. */
1450
+ read(): boolean
1451
+ write(value: boolean): void
1452
+ /** Releases the pin and its interrupt. */
1453
+ close(): void
1454
+
1455
+ // Each answers "did this board do it": a pin the chip does not have, or a
1456
+ // target with no GPIO, reports false rather than throwing.
1457
+ static configureOutput(pin: number): boolean
1458
+ static configureInput(pin: number, pullUp: boolean): boolean
1459
+ static write(pin: number, level: boolean): boolean
1460
+ static read(pin: number): boolean
1461
+ }
1462
+
1463
+ export interface DigitalOptions<Target = undefined> {
1464
+ pin: number
1465
+ /** Digital.Input, InputPullUp, InputPullDown, InputPullUpDown, Output or OutputOpenDrain. */
1466
+ mode: number
1467
+ /** Digital.Rising, Digital.Falling, or both OR'd; required with onReadable. */
1468
+ edge?: number
1469
+ /** Called with `this` = the Digital after an edge. */
1470
+ onReadable?: (this: Digital<Target>) => void
1471
+ /** Any value, kept as `target` for the callback. */
1472
+ target?: Target
1473
+ /** GeaStack extension: poll every this many milliseconds instead of using the interrupt. */
1474
+ poll?: number
1475
+ /** Only 'number' is supported. */
1476
+ format?: string
1477
+ }
1478
+
1479
+ /**
1480
+ * ECMA-419 Digital IO class, as on Moddable: the same native backend as
1481
+ * `Gpio`, so an input with an `edge` is interrupt-driven and `onReadable`
1482
+ * runs on the app thread.
1483
+ *
1484
+ * ```ts
1485
+ * const button = new Digital({
1486
+ * pin: 0,
1487
+ * mode: Digital.InputPullUp,
1488
+ * edge: Digital.Rising | Digital.Falling,
1489
+ * onReadable() { console.log(this.read()) },
1490
+ * })
1491
+ * ```
1492
+ */
1493
+ export declare class Digital<Target = undefined> {
1494
+ static readonly Input: number
1495
+ static readonly InputPullUp: number
1496
+ static readonly InputPullDown: number
1497
+ static readonly InputPullUpDown: number
1498
+ static readonly Output: number
1499
+ static readonly OutputOpenDrain: number
1500
+ static readonly Rising: number
1501
+ static readonly Falling: number
1502
+ constructor(options: DigitalOptions<Target>)
1503
+ readonly target: Target | undefined
1504
+ format: string
1505
+ /** 0 or 1. */
1506
+ read(): number
1507
+ write(value: number): void
1508
+ close(): void
1509
+ }
1510
+
1511
+ /**
1512
+ * The board's named physical buttons. A press arrives as a `keydown`/`keyup`
1513
+ * whose `code` is the button's name and whose `key`/`keyCode` are its default
1514
+ * key alias, so `onKeyDown={e => { if (e.code === 'Boot') ... }}` listens to
1515
+ * one button, and an app that only knows `Escape`/`Enter` still works. Names
1516
+ * are the silkscreen's, in PascalCase: 'Boot', 'Power', 'Key1'. This lists
1517
+ * them; a board with no buttons reports count() 0.
1518
+ */
1519
+ export interface ButtonsController {
1520
+ count(): number
1521
+ /** The button's name ('Boot'), or '' past count(). */
1522
+ code(index: number): string
1523
+ /** Its default key alias ('Escape'), or '' when it has none. */
1524
+ key(index: number): string
1525
+ /**
1526
+ * Its GPIO, or -1 for a button that is not one (a PMU's power key). A
1527
+ * `Gpio` or `Digital` can open this pin as an input next to the key events.
1528
+ */
1529
+ pin(index: number): number
1530
+ /** Whether the named button is held right now; false for an unknown name. */
1531
+ pressed(code: string): boolean
1420
1532
  }
1421
1533
 
1422
- export declare const Gpio: GpioController
1534
+ export declare const Buttons: ButtonsController
1423
1535
 
1424
1536
  export interface UartOptions {
1425
1537
  tx: number
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/core",
3
- "version": "0.1.47",
3
+ "version": "0.1.48",
4
4
  "description": "GeaStack app API, reactivity headers, runtime sources, and type declarations.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -0,0 +1,216 @@
1
+ // Digital pins: two TS classes over one native backend.
2
+ //
3
+ // `Gpio` is the GeaStack class (string options, an `onChange(value)` callback,
4
+ // boolean levels). `Digital` is ECMA-419's Digital IO class (numeric modes, an
5
+ // `onReadable()` callback with `this` = the instance, levels 0 and 1), so code
6
+ // written for another ECMA-419 host runs unchanged. Both open the pin through
7
+ // `__gea_Gpio.open` (host/gpio.h, host/gpio.cpp): an input with edges is
8
+ // interrupt-driven, and its callback runs on the app thread at the start of
9
+ // the next frame. `poll: ms` opts a pin into polling instead; a platform or
10
+ // pin without an edge interrupt polls each frame on its own.
11
+
12
+ declare const __gea_Gpio: {
13
+ configureOutput(pin: number): boolean
14
+ configureInput(pin: number, pullUp: boolean): boolean
15
+ write(pin: number, level: boolean): boolean
16
+ read(pin: number): boolean
17
+ open(pin: number, mode: number, edges: number, pollMs: number, onEdge: () => void): number
18
+ get(handle: number): number
19
+ set(handle: number, level: number): boolean
20
+ close(handle: number): void
21
+ }
22
+
23
+ // gea::platform::gpio::Gpio::Mode, and the edge mask (Moddable's numbers).
24
+ const kInput = 0
25
+ const kInputPullUp = 1
26
+ const kInputPullDown = 2
27
+ const kInputPullUpDown = 3
28
+ const kOutput = 8
29
+ const kOutputOpenDrain = 9
30
+ const kRising = 1
31
+ const kFalling = 2
32
+
33
+ function isOutputMode(mode: number): boolean {
34
+ return mode === kOutput || mode === kOutputOpenDrain
35
+ }
36
+
37
+ export type GpioMode = 'input' | 'output' | 'openDrain'
38
+ export type GpioPull = 'none' | 'up' | 'down' | 'both'
39
+ export type GpioEdge = 'none' | 'rising' | 'falling' | 'both'
40
+
41
+ export interface GpioOptions {
42
+ /** Defaults to 'input'. */
43
+ mode?: GpioMode
44
+ /** An input's internal pull resistor. Defaults to 'none'. */
45
+ pull?: GpioPull
46
+ /** Which edges call `onChange`. Defaults to 'both' when `onChange` is given. */
47
+ edge?: GpioEdge
48
+ /** Called on the app thread with the level after an edge. */
49
+ onChange?: (value: boolean) => void
50
+ /** Poll every this many milliseconds instead of using the pin's interrupt. */
51
+ poll?: number
52
+ }
53
+
54
+ function noChange(value: boolean): void {
55
+ void value
56
+ }
57
+
58
+ export class Gpio {
59
+ readonly pin: number
60
+ private handle: number
61
+ private edges: number
62
+ private value: boolean
63
+ private onChange: (value: boolean) => void
64
+
65
+ constructor(pin: number, options: GpioOptions = {}) {
66
+ this.pin = pin
67
+ const kind = options.mode ?? 'input'
68
+ let mode = kInput
69
+ if (kind === 'output') mode = kOutput
70
+ else if (kind === 'openDrain') mode = kOutputOpenDrain
71
+ else if (options.pull === 'up') mode = kInputPullUp
72
+ else if (options.pull === 'down') mode = kInputPullDown
73
+ else if (options.pull === 'both') mode = kInputPullUpDown
74
+ const edge = options.edge ?? (options.onChange !== undefined ? 'both' : 'none')
75
+ let edges = 0
76
+ if (edge === 'rising') edges = kRising
77
+ else if (edge === 'falling') edges = kFalling
78
+ else if (edge === 'both') edges = kRising | kFalling
79
+ if (edges !== 0 && isOutputMode(mode)) throw new Error(`GPIO ${pin}: an output has no edges`)
80
+ this.edges = edges
81
+ this.value = false
82
+ this.onChange = options.onChange ?? noChange
83
+ this.handle = __gea_Gpio.open(pin, mode, edges, options.poll ?? 0, () => this.edge())
84
+ if (this.handle < 0) throw new Error(`GPIO ${pin} cannot be opened as ${kind}`)
85
+ if (edges !== 0) this.value = this.read()
86
+ }
87
+
88
+ /** The pin's level; for an output, the level it drives. */
89
+ read(): boolean {
90
+ if (this.handle < 0) throw new Error(`GPIO ${this.pin} is closed`)
91
+ return __gea_Gpio.get(this.handle) !== 0
92
+ }
93
+
94
+ write(value: boolean): void {
95
+ if (this.handle < 0) throw new Error(`GPIO ${this.pin} is closed`)
96
+ if (!__gea_Gpio.set(this.handle, value ? 1 : 0)) throw new Error(`GPIO ${this.pin} is not an output`)
97
+ }
98
+
99
+ /** Releases the pin and its interrupt; the object cannot be used again. */
100
+ close(): void {
101
+ if (this.handle < 0) return
102
+ __gea_Gpio.close(this.handle)
103
+ this.handle = -1
104
+ }
105
+
106
+ private edge(): void {
107
+ if (this.handle < 0) return
108
+ const value = this.read()
109
+ const changed = value !== this.value
110
+ this.value = value
111
+ // One edge filter reports every edge it was asked for (a rising-only pin
112
+ // never sees the falls between); both edges report changes, which drops a
113
+ // bounce that settled back to where it started.
114
+ if (this.edges === kRising) {
115
+ if (value) this.onChange(true)
116
+ } else if (this.edges === kFalling) {
117
+ if (!value) this.onChange(false)
118
+ } else if (changed) {
119
+ this.onChange(value)
120
+ }
121
+ }
122
+
123
+ // The pin-number calls that predate the class. Each answers "did this board
124
+ // do it": a pin the chip does not have reports false instead of throwing.
125
+ static configureOutput(pin: number): boolean {
126
+ return __gea_Gpio.configureOutput(pin)
127
+ }
128
+
129
+ static configureInput(pin: number, pullUp: boolean): boolean {
130
+ return __gea_Gpio.configureInput(pin, pullUp)
131
+ }
132
+
133
+ static write(pin: number, level: boolean): boolean {
134
+ return __gea_Gpio.write(pin, level)
135
+ }
136
+
137
+ static read(pin: number): boolean {
138
+ return __gea_Gpio.read(pin)
139
+ }
140
+ }
141
+
142
+ export interface DigitalOptions<Target = undefined> {
143
+ pin: number
144
+ /** Digital.Input, InputPullUp, InputPullDown, InputPullUpDown, Output or OutputOpenDrain. */
145
+ mode: number
146
+ /** Digital.Rising, Digital.Falling, or both OR'd; required with onReadable. */
147
+ edge?: number
148
+ /** Called with `this` = the Digital after an edge. */
149
+ onReadable?: (this: Digital<Target>) => void
150
+ /** Any value, kept as `target` for the callback. */
151
+ target?: Target
152
+ /** GeaStack extension: poll every this many milliseconds instead of using the interrupt. */
153
+ poll?: number
154
+ /** Only 'number' is supported. */
155
+ format?: string
156
+ }
157
+
158
+ function notReadable<Target>(this: Digital<Target>): void {}
159
+
160
+ // ECMA-419 (2nd edition) Digital IO class.
161
+ export class Digital<Target = undefined> {
162
+ static readonly Input = kInput
163
+ static readonly InputPullUp = kInputPullUp
164
+ static readonly InputPullDown = kInputPullDown
165
+ static readonly InputPullUpDown = kInputPullUpDown
166
+ static readonly Output = kOutput
167
+ static readonly OutputOpenDrain = kOutputOpenDrain
168
+ static readonly Rising = kRising
169
+ static readonly Falling = kFalling
170
+
171
+ readonly target: Target | undefined
172
+ private handle: number
173
+ private pin: number
174
+ private onReadable: (this: Digital<Target>) => void
175
+
176
+ constructor(options: DigitalOptions<Target>) {
177
+ const edge = options.edge ?? 0
178
+ if (options.format !== undefined && options.format !== 'number') throw new RangeError('Digital supports only format "number"')
179
+ if (options.onReadable !== undefined && edge === 0) throw new RangeError('onReadable requires edge')
180
+ if (edge !== 0 && isOutputMode(options.mode)) throw new RangeError('an output has no edge')
181
+ this.pin = options.pin
182
+ this.target = options.target
183
+ this.onReadable = options.onReadable ?? notReadable
184
+ this.handle = __gea_Gpio.open(options.pin, options.mode, edge, options.poll ?? 0, () => this.readable())
185
+ if (this.handle < 0) throw new Error(`Digital: pin ${options.pin} cannot be opened in mode ${options.mode}`)
186
+ }
187
+
188
+ get format(): string {
189
+ return 'number'
190
+ }
191
+
192
+ set format(value: string) {
193
+ if (value !== 'number') throw new RangeError('Digital supports only format "number"')
194
+ }
195
+
196
+ /** 0 or 1. */
197
+ read(): number {
198
+ if (this.handle < 0) throw new Error(`Digital: pin ${this.pin} is closed`)
199
+ return __gea_Gpio.get(this.handle)
200
+ }
201
+
202
+ write(value: number): void {
203
+ if (this.handle < 0) throw new Error(`Digital: pin ${this.pin} is closed`)
204
+ if (!__gea_Gpio.set(this.handle, value)) throw new Error(`Digital: pin ${this.pin} is not an output`)
205
+ }
206
+
207
+ close(): void {
208
+ if (this.handle < 0) return
209
+ __gea_Gpio.close(this.handle)
210
+ this.handle = -1
211
+ }
212
+
213
+ private readable(): void {
214
+ if (this.handle >= 0) this.onReadable()
215
+ }
216
+ }
package/runtime/host.ts CHANGED
@@ -346,15 +346,14 @@ declare const __gea_Input: {
346
346
  // their rAF loop and dismiss the overlay if visible.
347
347
  consumeBackButton(): boolean
348
348
  }
349
- declare const __gea_Gpio: {
350
- // Digital pins, for the wiring a board exposes that no other facade covers:
351
- // an LED, a relay, a button that is not the launcher button. Each call
352
- // answers "did this board do it" — a pin the chip does not have reports
353
- // false rather than throwing.
354
- configureOutput(pin: number): boolean
355
- configureInput(pin: number, pullUp: boolean): boolean
356
- write(pin: number, level: boolean): boolean
357
- read(pin: number): boolean
349
+ declare const __gea_Buttons: {
350
+ // The board's named physical buttons (presses arrive as key events whose
351
+ // `code` is the name). Index-based so a list reads without a boxed array.
352
+ count(): number
353
+ code(index: number): string
354
+ key(index: number): string
355
+ pin(index: number): number
356
+ pressed(code: string): boolean
358
357
  }
359
358
  declare const __gea_Magnetometer: {
360
359
  open(): boolean
@@ -1045,18 +1044,21 @@ export const Input = {
1045
1044
  return __gea_Input.consumeBackButton()
1046
1045
  },
1047
1046
  }
1048
- export const Gpio = {
1049
- configureOutput(pin: number): boolean {
1050
- return __gea_Gpio.configureOutput(pin)
1047
+ export const Buttons = {
1048
+ count(): number {
1049
+ return __gea_Buttons.count()
1050
+ },
1051
+ code(index: number): string {
1052
+ return __gea_Buttons.code(index)
1051
1053
  },
1052
- configureInput(pin: number, pullUp: boolean): boolean {
1053
- return __gea_Gpio.configureInput(pin, pullUp)
1054
+ key(index: number): string {
1055
+ return __gea_Buttons.key(index)
1054
1056
  },
1055
- write(pin: number, level: boolean): boolean {
1056
- return __gea_Gpio.write(pin, level)
1057
+ pin(index: number): number {
1058
+ return __gea_Buttons.pin(index)
1057
1059
  },
1058
- read(pin: number): boolean {
1059
- return __gea_Gpio.read(pin)
1060
+ pressed(code: string): boolean {
1061
+ return __gea_Buttons.pressed(code)
1060
1062
  },
1061
1063
  }
1062
1064
  export const Uart = {
@@ -6,6 +6,7 @@ export * from './runtime/host'
6
6
  export * from './runtime/ble'
7
7
  export * from './runtime/images'
8
8
  export * from './runtime/color'
9
+ export * from './runtime/gpio'
9
10
  export { mount } from './runtime/primitives'
10
11
  // The embedded/geatsc pipeline aliases '@geastack/core' to runtime.ts, so an
11
12
  // app's `import type { GeaCanvasElement, GeaEmbeddedImage } from
@@ -130,6 +131,7 @@ export type {
130
131
  ImageSource,
131
132
  IncomingMessage,
132
133
  InputController,
134
+ ButtonsController,
133
135
  InputElementProps,
134
136
  InputEvent,
135
137
  InputEventTarget,
package/runtime.cpp CHANGED
@@ -161,7 +161,8 @@ void dispatch_rotary_input()
161
161
  }
162
162
 
163
163
  // Hardware-button key presses (boards without touch — e.g. the e-paper's
164
- // BOOT/PWR buttons) queued via input::queueKeyDown. A focused <input> gets the
164
+ // BOOT/PWR buttons) queued via input::queueKeyDown, and named board buttons
165
+ // queued via input::queueButton. A focused <input> gets the
165
166
  // key first through its per-node keydown listener; then the document-level
166
167
  // keydown handler runs (hardware buttons / app-level shortcuts bound on a
167
168
  // non-input element), unless the input consumed it.
@@ -173,6 +174,12 @@ void dispatch_key_input()
173
174
  events::PointerEvent event{};
174
175
  event.type = key.pressed ? events::PointerEventType::KeyDown : events::PointerEventType::KeyUp;
175
176
  event.keyCode = key.keyCode;
177
+ // A board button names itself in `code`; `key` is its default alias.
178
+ if (key.button >= 0) {
179
+ event.code = input::buttonCode(key.button);
180
+ const char *alias = input::buttonKey(key.button);
181
+ event.key = *alias ? alias : "Unidentified";
182
+ }
176
183
  event.bubbles = true;
177
184
  event.cancelable = true;
178
185
 
@@ -26,7 +26,13 @@ export function fileAssetBundle(appDir, outCpp, kind, entries) {
26
26
  ? JSON.parse(fs.readFileSync(manifestFile, "utf8"))
27
27
  : {};
28
28
  const directory = fileAssetDirectory(manifest);
29
- if (!directory || !entries.length) return null;
29
+ const metadata = `${outCpp}.assets.json`;
30
+ if (!directory || !entries.length) {
31
+ // A manifest left from an earlier storage-backed build would still have
32
+ // deploy tooling push that bundle.
33
+ fs.rmSync(metadata, { force: true });
34
+ return null;
35
+ }
30
36
  const bytes = Buffer.concat(entries.map((entry) => Buffer.from(entry.data)));
31
37
  const hash = createHash("sha256").update(bytes).digest("hex");
32
38
  const id = String(manifest.gea?.id || path.basename(appDir)).replace(
@@ -43,7 +49,6 @@ export function fileAssetBundle(appDir, outCpp, kind, entries) {
43
49
  version: 1,
44
50
  files: [{ local, remote, bytes: bytes.length, sha256: hash }],
45
51
  };
46
- const metadata = `${outCpp}.assets.json`;
47
52
  const contents = JSON.stringify(deployment, null, 2) + "\n";
48
53
  if (
49
54
  !fs.existsSync(metadata) ||