@typecad/hal 1.0.0-alpha.3 → 1.0.0-alpha.7

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/src/http.ts ADDED
@@ -0,0 +1,144 @@
1
+ import {
2
+ httpBegin,
3
+ httpReset,
4
+ httpSetHeader,
5
+ httpSetTimeout,
6
+ httpSetMaxBody,
7
+ httpSetBody,
8
+ httpSetInsecure,
9
+ httpSetCaCert,
10
+ httpSend,
11
+ httpStatus,
12
+ httpOk,
13
+ httpBody,
14
+ httpContentLength,
15
+ httpResponseHeader,
16
+ } from './emit.js';
17
+
18
+ export enum HttpMethod {
19
+ GET = 0,
20
+ POST = 1,
21
+ PUT = 2,
22
+ DELETE = 3,
23
+ HEAD = 4,
24
+ PATCH = 5,
25
+ }
26
+
27
+ /**
28
+ * Fluent HTTP/S request builder, lowered to native ESP-IDF
29
+ * `esp_http_client` by framework-esp32 (TLS via esp-tls / mbedTLS bundle).
30
+ * Response fields are read from this object after send() — mirrors
31
+ * `await WiFi.connect(); WiFi.localIP()`.
32
+ *
33
+ * No `include()` calls here — ESP-IDF headers are framework-owned and added
34
+ * via forcedIncludes when the program uses http.* ops.
35
+ */
36
+ export class HttpRequest {
37
+ private _method: string;
38
+ private _url: string;
39
+
40
+ constructor(method: string, url: string) {
41
+ this._method = method;
42
+ this._url = url;
43
+ }
44
+
45
+ header(name: string, value: string): this {
46
+ httpSetHeader(name, value);
47
+ return this;
48
+ }
49
+
50
+ timeout(ms: number): this {
51
+ httpSetTimeout(ms);
52
+ return this;
53
+ }
54
+
55
+ maxBody(bytes: number): this {
56
+ httpSetMaxBody(bytes);
57
+ return this;
58
+ }
59
+
60
+ body(data: string): this {
61
+ httpSetBody(data, false);
62
+ return this;
63
+ }
64
+
65
+ jsonBody(json: string): this {
66
+ httpSetBody(json, true);
67
+ return this;
68
+ }
69
+
70
+ /** Skip TLS certificate verification (development only). */
71
+ insecure(): this {
72
+ httpSetInsecure();
73
+ return this;
74
+ }
75
+
76
+ caCert(pem: string): this {
77
+ httpSetCaCert(pem);
78
+ return this;
79
+ }
80
+
81
+ /** Blocking at top level; cooperatively awaitable inside async functions. */
82
+ send(): Promise<boolean> {
83
+ httpBegin(this._method, this._url);
84
+ httpSend();
85
+ return Promise.resolve(false);
86
+ }
87
+
88
+ status(): number {
89
+ return httpStatus();
90
+ }
91
+
92
+ ok(): boolean {
93
+ return httpOk();
94
+ }
95
+
96
+ /** Response body as a C string (valid until the next request). */
97
+ text(): string {
98
+ return httpBody();
99
+ }
100
+
101
+ contentLength(): number {
102
+ return httpContentLength();
103
+ }
104
+
105
+ responseHeader(name: string): string {
106
+ return httpResponseHeader(name);
107
+ }
108
+ }
109
+
110
+ export class HttpClass {
111
+ static readonly __instance_name = "Http";
112
+
113
+ get(url: string): HttpRequest {
114
+ httpReset();
115
+ return new HttpRequest("GET", url);
116
+ }
117
+
118
+ post(url: string): HttpRequest {
119
+ httpReset();
120
+ return new HttpRequest("POST", url);
121
+ }
122
+
123
+ put(url: string): HttpRequest {
124
+ httpReset();
125
+ return new HttpRequest("PUT", url);
126
+ }
127
+
128
+ del(url: string): HttpRequest {
129
+ httpReset();
130
+ return new HttpRequest("DELETE", url);
131
+ }
132
+
133
+ head(url: string): HttpRequest {
134
+ httpReset();
135
+ return new HttpRequest("HEAD", url);
136
+ }
137
+
138
+ patch(url: string): HttpRequest {
139
+ httpReset();
140
+ return new HttpRequest("PATCH", url);
141
+ }
142
+ }
143
+
144
+ export const Http = new HttpClass();
package/src/i2c.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { i2cBegin, i2cEnd, i2cSetClock, i2cBeginTx, i2cWrite, i2cWriteBuffer, i2cEndTx, i2cRequestFrom, i2cAvailable, i2cRead, rawCpp } from './emit.js';
1
+ import { i2cBegin, i2cEnd, i2cSetClock, i2cBeginTx, i2cWrite, i2cWriteBuffer, i2cEndTx, i2cRequestFrom, i2cAvailable, i2cRead, i2cReadBuffer, rawCpp } from './emit.js';
2
2
  import { include } from './include.js';
3
3
 
4
4
  export class I2CDevice {
@@ -10,6 +10,16 @@ export class I2CDevice {
10
10
  this._address = address;
11
11
  }
12
12
 
13
+ /** The 7-bit I2C address this accessor targets. Exposed so I2CDevice
14
+ * structurally satisfies the @typecad/simulator II2CDeviceAccessor contract
15
+ * (which declares `readonly address`), letting the same driver function be
16
+ * typed against the contract and accept either a real board device or a
17
+ * simulated one. The transpiler strips HAL class bodies to IR, so this
18
+ * getter carries no runtime cost in the generated C++. */
19
+ get address(): number {
20
+ return this._address;
21
+ }
22
+
13
23
  writeByte(register: number, value: number): void {
14
24
  include("<Wire.h>");
15
25
  i2cBeginTx(this._bus, this._address);
@@ -41,9 +51,11 @@ export class I2CDevice {
41
51
  i2cWrite(this._bus, register);
42
52
  i2cEndTx(this._bus, false);
43
53
  i2cRequestFrom(this._bus, this._address, count, true);
44
- rawCpp(`static uint8_t __buf[${count}];`);
45
- rawCpp(`for (int __i = 0; __i < ${count}; __i++) __buf[__i] = ${this._bus}.read();`);
46
- rawCpp(`return __buf;`);
54
+ // Drain the requested bytes into the caller's buffer (declared by the
55
+ // Uint8Array return marker as `uint8_t data[count]`). Using the semantic
56
+ // primitive — NOT rawCpp — keeps the buffer in user scope so it survives
57
+ // the return (no decayed pointer) and `data.length` / `data[i]` work.
58
+ i2cReadBuffer(this._bus, count, new Uint8Array(count));
47
59
  return new Uint8Array(count);
48
60
  }
49
61
  }
package/src/index.ts CHANGED
@@ -19,7 +19,7 @@ export type { SPIBitOrder, SPIMode, SPISettings } from './types.js';
19
19
  export { include } from './include.js';
20
20
  export { board } from './board.js';
21
21
  export { callback } from './callback.js';
22
- export { rawCpp, boardResolve } from './emit.js';
22
+ export { rawCpp, rawCppExpr, boardResolve } from './emit.js';
23
23
  export { HIGH, LOW, OUTPUT, INPUT, INPUT_PULLUP, INPUT_PULLDOWN, OUTPUT_OPEN_DRAIN, ANALOG, LED_BUILTIN, LSBFIRST, MSBFIRST, WDTO_15MS, WDTO_30MS, WDTO_60MS, WDTO_120MS, WDTO_250MS, WDTO_500MS, WDTO_1S, WDTO_2S, WDTO_4S, WDTO_8S } from './constants.js';
24
24
  export { delay, millis, micros, delayMicroseconds, map, constrain, TimingClass, Timing } from './timing.js';
25
25
  export { freeHeap, setInterval, setTimeout, clearInterval, clearTimeout } from './timing.js';
@@ -46,3 +46,11 @@ export { HardwareTimer, Timer0, Timer1, Timer2 } from './timer.js';
46
46
  export { FSClass, FS } from './fs.js';
47
47
  export { PowerClass, Power } from './power.js';
48
48
  export { AsyncClass, Async } from './async.js';
49
+ export { WiFiClass, WiFi, WiFiStatus, WiFiEncryption } from './wifi.js';
50
+ export { HttpClass, Http, HttpRequest, HttpMethod } from './http.js';
51
+ export {
52
+ BleClass, Ble, BleServer,
53
+ BleValueType, BlePerm, BleStatus, BleAdvertisingMode, GATT,
54
+ } from './ble.js';
55
+ export type { GattCharacteristicDef, CharValue } from './ble.js';
56
+ export { RmtChannel } from './rmt.js';
package/src/power.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { powerDeepSleep, powerLightSleep, powerSetCpuFrequency } from './emit.js';
1
+ import { powerDeepSleep, powerLightSleep, powerSetCpuFrequency, powerDeepSleepPin } from './emit.js';
2
2
 
3
3
  /**
4
4
  * PowerClass provides control over MCU power states and clock frequencies.
@@ -14,6 +14,16 @@ export class PowerClass {
14
14
  powerDeepSleep(ms);
15
15
  }
16
16
 
17
+ /** Enter deep sleep until `pin` reaches `level` (0 = low, 1 = high).
18
+ *
19
+ * Lowers to ext0 wakeup (Xtensa ESP32/S3, RTC pins only) or the gpio-wakeup
20
+ * variant (RISC-V C3/C6) depending on the target. `pin` must be RTC-capable;
21
+ * the framework flags non-RTC pins at compile time. Wakeup resets the chip,
22
+ * so this call never returns. */
23
+ deepSleepPin(pin: number, level: 0 | 1): void {
24
+ powerDeepSleepPin(pin, level);
25
+ }
26
+
17
27
  lightSleep(): void {
18
28
  powerLightSleep();
19
29
  }
@@ -1,57 +1,86 @@
1
- import { rawCpp } from './emit.js';
1
+ import {
2
+ preferencesBegin,
3
+ preferencesEnd,
4
+ preferencesClear,
5
+ preferencesRemove,
6
+ preferencesPutInt,
7
+ preferencesGetInt,
8
+ preferencesPutUInt,
9
+ preferencesGetUInt,
10
+ preferencesPutBool,
11
+ preferencesGetBool,
12
+ preferencesPutFloat,
13
+ preferencesGetFloat,
14
+ preferencesPutString,
15
+ preferencesGetString,
16
+ } from './emit.js';
2
17
 
18
+ /**
19
+ * Preferences — a persistent key/value store, lowered to native NVS
20
+ * (nvs_flash / nvs_open / nvs_set_* / nvs_get_*) by framework-esp32.
21
+ *
22
+ * No include() calls here — NVS headers are framework-owned and added via
23
+ * forcedIncludes when the program uses preferences.* ops. Method bodies pass
24
+ * parameters directly into semantic calls so the resolver can statically track
25
+ * every argument (matching the WiFi/HTTP HAL pattern).
26
+ */
3
27
  export class PreferencesClass {
4
28
  static readonly __instance_name = "Preferences";
5
- // NOTE: no __includes here. The transpiler emits singleton __includes on
6
- // every architecture with no filtering, and <Preferences.h> is ESP32-only —
7
- // adding it would break AVR builds. The class is ESP32-only by convention.
8
29
 
9
30
  begin(name: string, readOnly: boolean = false): void {
10
- rawCpp(`Preferences.begin(${name}.c_str(), ${readOnly});`);
31
+ preferencesBegin(name, readOnly);
11
32
  }
33
+
12
34
  end(): void {
13
- rawCpp(`Preferences.end();`);
35
+ preferencesEnd();
14
36
  }
37
+
15
38
  clear(): void {
16
- rawCpp(`Preferences.clear();`);
39
+ preferencesClear();
17
40
  }
41
+
18
42
  remove(key: string): void {
19
- rawCpp(`Preferences.remove(${key}.c_str());`);
43
+ preferencesRemove(key);
20
44
  }
45
+
21
46
  putInt(key: string, value: number): void {
22
- rawCpp(`Preferences.putInt(${key}.c_str(), ${value});`);
47
+ preferencesPutInt(key, value);
23
48
  }
49
+
24
50
  getInt(key: string, defaultValue: number = 0): number {
25
- rawCpp(`return Preferences.getInt(${key}.c_str(), ${defaultValue});`);
26
- return 0;
51
+ return preferencesGetInt(key, defaultValue);
27
52
  }
53
+
28
54
  putUInt(key: string, value: number): void {
29
- rawCpp(`Preferences.putUInt(${key}.c_str(), ${value});`);
55
+ preferencesPutUInt(key, value);
30
56
  }
57
+
31
58
  getUInt(key: string, defaultValue: number = 0): number {
32
- rawCpp(`return Preferences.getUInt(${key}.c_str(), ${defaultValue});`);
33
- return 0;
34
- }
35
- putFloat(key: string, value: number): void {
36
- rawCpp(`Preferences.putFloat(${key}.c_str(), ${value});`);
37
- }
38
- getFloat(key: string, defaultValue: number = 0): number {
39
- rawCpp(`return Preferences.getFloat(${key}.c_str(), ${defaultValue});`);
40
- return 0;
59
+ return preferencesGetUInt(key, defaultValue);
41
60
  }
61
+
42
62
  putBool(key: string, value: boolean): void {
43
- rawCpp(`Preferences.putBool(${key}.c_str(), ${value});`);
63
+ preferencesPutBool(key, value);
44
64
  }
65
+
45
66
  getBool(key: string, defaultValue: boolean = false): boolean {
46
- rawCpp(`return Preferences.getBool(${key}.c_str(), ${defaultValue});`);
47
- return false;
67
+ return preferencesGetBool(key, defaultValue);
68
+ }
69
+
70
+ putFloat(key: string, value: number): void {
71
+ preferencesPutFloat(key, value);
48
72
  }
73
+
74
+ getFloat(key: string, defaultValue: number = 0): number {
75
+ return preferencesGetFloat(key, defaultValue);
76
+ }
77
+
49
78
  putString(key: string, value: string): void {
50
- rawCpp(`Preferences.putString(${key}.c_str(), ${value}.c_str());`);
79
+ preferencesPutString(key, value);
51
80
  }
81
+
52
82
  getString(key: string, defaultValue: string = ""): string {
53
- rawCpp(`return Preferences.getString(${key}.c_str(), ${defaultValue}.c_str());`);
54
- return "";
83
+ return preferencesGetString(key, defaultValue);
55
84
  }
56
85
  }
57
86
 
package/src/register.ts CHANGED
@@ -27,9 +27,21 @@ export type Bit = 0 | 1;
27
27
  export type Bits<N extends number = number> = number;
28
28
 
29
29
  /** Class decorator marking a struct as a memory-mapped register at `address`.
30
- * Erased at transpile time — the class becomes a `volatile uint32_t*`. */
31
- export declare function register(address: number): ClassDecorator;
30
+ * Erased at transpile time — the class becomes a `volatile uint32_t*`.
31
+ *
32
+ * These carry real (inert) runtime bodies rather than `declare`, so the
33
+ * `export { register, bits }` re-export in index.ts resolves under Node's ESM
34
+ * loader, which validates that re-exported bindings exist at runtime. They are
35
+ * never invoked: the cuttlefish transpiler detects them by name and lowers the
36
+ * decorated struct away, so these stubs are only reached when the decorator
37
+ * source is imported without transpilation (e.g. host-side tests). */
38
+ export function register(_address: number): ClassDecorator {
39
+ return () => {};
40
+ }
32
41
 
33
42
  /** Property decorator carrying the bit range [lo, hi] (inclusive) of a field
34
- * within its register. Erased at transpile time. */
35
- export declare function bits(hi: number, lo: number): PropertyDecorator;
43
+ * within its register. Erased at transpile time. See `register` for why these
44
+ * have runtime bodies. */
45
+ export function bits(_hi: number, _lo: number): PropertyDecorator {
46
+ return () => {};
47
+ }
package/src/rmt.ts ADDED
@@ -0,0 +1,125 @@
1
+ // ---------------------------------------------------------------------------
2
+ // @typecad/hal — RMT (Remote Control Transceiver) ergonomic API
3
+ // ---------------------------------------------------------------------------
4
+ // Exposes RMT via a RmtChannel class, mirroring the I2CBus/I2CDevice pattern.
5
+ // The transpiler only resolves semantic calls made inside class-method bodies
6
+ // (free top-level calls emit verbatim), so every peripheral exposes its API
7
+ // through a class whose methods call the positional semantic primitives in
8
+ // emit.ts. The resolver collapses object literals, so HALOpIR fields must be
9
+ // scalars; these methods destructure `opts` at the call site before forwarding.
10
+ //
11
+ // Channel identity is the GPIO pin (like pwm.ts's LEDC channel-per-pin model).
12
+
13
+ import type { Pin } from './gpio.js';
14
+ import {
15
+ rmtTxInit,
16
+ rmtRxInit,
17
+ rmtTxWriteBytes,
18
+ rmtTxWriteSymbols,
19
+ rmtTxWaitDone,
20
+ rmtTxDeinit,
21
+ rmtRxOnReceived,
22
+ rmtRxStart,
23
+ rmtRxStop,
24
+ rmtRxRead,
25
+ rmtRxDeinit,
26
+ } from './emit.js';
27
+
28
+ /** Pin identifier accepted by RmtChannel: a Pin object, raw GPIO number, or port name. */
29
+ type RmtPin = Pin | number | string;
30
+
31
+ /**
32
+ * RMT transceiver channel bound to a GPIO pin. One channel per pin; TX and RX
33
+ * are independent roles on the same channel object.
34
+ *
35
+ * ```ts
36
+ * const led = new RmtChannel(LED);
37
+ * led.txInit({ resolutionHz: 10_000_000, bit0: [4, 9], bit1: [9, 4] });
38
+ * led.txWriteBytes([0, 16, 0]);
39
+ * led.txWaitDone();
40
+ * ```
41
+ */
42
+ export class RmtChannel {
43
+ private _pin: RmtPin;
44
+
45
+ constructor(pin: RmtPin) {
46
+ this._pin = pin;
47
+ }
48
+
49
+ // ── TX ─────────────────────────────────────────────────────────────────────
50
+ /** Initialize the channel for TX. Idempotent per pin. Bit timings are fixed
51
+ * at init — ESP-IDF bakes them into the bytes-encoder and exposes no public
52
+ * mutation API. Tick units are 1/resolutionHz seconds.
53
+ *
54
+ * Args are positional scalars (not an opts object) because the transpiler's
55
+ * method-body renderer folds scalar params but not property accesses on an
56
+ * object param (opts.resolutionHz would render as a collapsed object + dead
57
+ * property access). Mirrors how I2CBus.begin(address) takes a scalar. */
58
+ txInit(
59
+ resolutionHz: number,
60
+ bit0Hi: number, bit0Lo: number,
61
+ bit1Hi: number, bit1Lo: number,
62
+ msbFirst: boolean = false,
63
+ queueDepth: number = 4,
64
+ ): void {
65
+ rmtTxInit(
66
+ this._pin,
67
+ resolutionHz,
68
+ bit0Hi, bit0Lo,
69
+ bit1Hi, bit1Lo,
70
+ msbFirst,
71
+ queueDepth,
72
+ );
73
+ }
74
+
75
+ /** Write bytes via the channel's bytes-encoder (timings fixed at txInit). */
76
+ txWriteBytes(bytes: number[] | Uint8Array): void {
77
+ rmtTxWriteBytes(this._pin, bytes);
78
+ }
79
+
80
+ /** Write raw RMT symbols — arbitrary [hiTicks, loTicks] pairs. */
81
+ txWriteSymbols(symbols: [number, number][]): void {
82
+ rmtTxWriteSymbols(this._pin, symbols);
83
+ }
84
+
85
+ /** Block until the queued TX completes. */
86
+ txWaitDone(timeoutMs?: number): void {
87
+ rmtTxWaitDone(this._pin, timeoutMs);
88
+ }
89
+
90
+ /** Tear down the TX channel and release its slot. */
91
+ txDeinit(): void {
92
+ rmtTxDeinit(this._pin);
93
+ }
94
+
95
+ // ── RX ─────────────────────────────────────────────────────────────────────
96
+ /** Initialize the channel for RX. Idempotent per pin. */
97
+ rxInit(resolutionHz: number): void {
98
+ rmtRxInit(this._pin, resolutionHz);
99
+ }
100
+
101
+ /** Register a callback-by-name invoked when an RX burst completes. */
102
+ rxOnReceived(handler: string): void {
103
+ rmtRxOnReceived(this._pin, handler);
104
+ }
105
+
106
+ /** Start receiving. */
107
+ rxStart(): void {
108
+ rmtRxStart(this._pin);
109
+ }
110
+
111
+ /** Stop receiving. */
112
+ rxStop(): void {
113
+ rmtRxStop(this._pin);
114
+ }
115
+
116
+ /** Blocking read — returns flattened symbols [d0,l0,d1,l1,…] in ticks. */
117
+ rxRead(maxCount: number): number[] {
118
+ return rmtRxRead(this._pin, maxCount);
119
+ }
120
+
121
+ /** Tear down the RX channel and release its slot. */
122
+ rxDeinit(): void {
123
+ rmtRxDeinit(this._pin);
124
+ }
125
+ }
package/src/spi.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { spiBegin, spiEnd, spiTransfer, spiBeginTx, spiEndTx, spiCsLow, spiCsHigh, spiSetMode, spiSetBitOrder, rawCpp } from './emit.js';
1
+ import { spiBegin, spiEnd, spiTransfer, spiBeginTx, spiEndTx, spiCsLow, spiCsHigh, spiSetMode, spiSetBitOrder, spiReadBuffer, rawCpp } from './emit.js';
2
2
  import { include } from './include.js';
3
3
  import type { Pin } from './gpio.js';
4
4
  import type { SPIMode, SPISettings } from './types.js';
@@ -30,12 +30,15 @@ export class SPIDevice {
30
30
 
31
31
  readRegister(register: number, count: number): Uint8Array {
32
32
  include("<SPI.h>");
33
- rawCpp(`digitalWrite(${this._cs}, LOW);`);
34
- rawCpp(`${this._bus}.transfer(${register});`);
35
- rawCpp(`static uint8_t __spi_buf[${count}];`);
36
- rawCpp(`for (int i=0; i<${count}; i++) __spi_buf[i] = ${this._bus}.transfer(0x00);`);
37
- rawCpp(`digitalWrite(${this._cs}, HIGH);`);
38
- rawCpp(`return __spi_buf;`);
33
+ spiCsLow(this._cs);
34
+ spiTransfer(this._bus, register);
35
+ // Clock `count` dummy bytes and drain them into the caller's buffer
36
+ // (declared by the Uint8Array return marker as `uint8_t data[count]`).
37
+ // Using the semantic primitive — NOT rawCpp — keeps the buffer in user
38
+ // scope so it survives the return (no decayed pointer) and `data.length`
39
+ // / `data[i]` work, mirroring I2CDevice.readBytes.
40
+ spiReadBuffer(this._bus, count, new Uint8Array(count));
41
+ spiCsHigh(this._cs);
39
42
  return new Uint8Array(count);
40
43
  }
41
44