core-s3 0.5.3

Board support crate for the M5Stack CoreS3 ESP32-S3 kit.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
//! Framed CoreS3-to-Gateway-H2 transport helpers.
//!
//! This module provides protocol-neutral Gateway H2 framing plus traits for
//! OpenThread/Spinel integration in downstream firmware.
//!
//! The BSP does **not** implement Matter, Thread, Zigbee, OpenThread, or Spinel
//! protocol logic. Gateway H2 firmware must be explicitly selected and validated
//! by the application. If the attached ESP32-H2 runs OpenThread RCP firmware,
//! downstream code can implement [`GatewayH2SpinelTransport`] over the UART
//! using [`crate::gateway_h2::spinel`] for HDLC-lite byte-stuffing and FCS.

use heapless::Vec;

pub const SOF: u8 = 0xA5;
pub const MAX_PAYLOAD: usize = 128;

/// Default CoreS3 Gateway H2 UART baud rate.
pub const DEFAULT_GATEWAY_H2_BAUD: u32 = 115_200;
/// Conservative maximum Spinel frame payload size for application-owned buffers.
pub const DEFAULT_SPINEL_MAX_FRAME_SIZE: usize = 2048;
/// Stock Gateway H2 OpenThread RCP UART baud used by the CoreS3 host link.
pub const GATEWAY_H2_OPENTHREAD_BAUD: u32 = DEFAULT_GATEWAY_H2_BAUD;
/// Maximum decoded Spinel frame accepted by the transport contract.
pub const GATEWAY_H2_MAX_SPINEL_FRAME_SIZE: usize = DEFAULT_SPINEL_MAX_FRAME_SIZE;
/// Worst-case HDLC-lite bytes for one maximum frame, including FCS and flags.
pub const GATEWAY_H2_MAX_ENCODED_SPINEL_FRAME_SIZE: usize =
    (GATEWAY_H2_MAX_SPINEL_FRAME_SIZE + 2) * 2 + 2;
/// Minimum RX buffering: two worst-case encoded frames.
pub const GATEWAY_H2_MIN_RX_BUFFER_SIZE: usize = GATEWAY_H2_MAX_ENCODED_SPINEL_FRAME_SIZE * 2;
/// Minimum TX buffering: one worst-case encoded frame.
pub const GATEWAY_H2_MIN_TX_BUFFER_SIZE: usize = GATEWAY_H2_MAX_ENCODED_SPINEL_FRAME_SIZE;

/// Validate statically allocated OpenThread UART pipe capacities.
/// Return whether a wrapping 32-bit completion counter reached a target.
///
/// Valid when fewer than `2^31` operations can be outstanding.
pub const fn tx_sequence_reached(current: u32, target: u32) -> bool {
    current.wrapping_sub(target) < (1_u32 << 31)
}

pub const fn validate_openthread_buffer_capacities(
    rx: usize,
    tx: usize,
) -> Result<(), GatewayH2BufferCapacityError> {
    if rx < GATEWAY_H2_MIN_RX_BUFFER_SIZE {
        Err(GatewayH2BufferCapacityError::RxTooSmall)
    } else if tx < GATEWAY_H2_MIN_TX_BUFFER_SIZE {
        Err(GatewayH2BufferCapacityError::TxTooSmall)
    } else {
        Ok(())
    }
}

/// Invalid static UART pipe capacity.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GatewayH2BufferCapacityError {
    /// RX cannot retain two worst-case HDLC-lite frames.
    RxTooSmall,
    /// TX cannot retain one worst-case HDLC-lite frame.
    TxTooSmall,
}

#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FrameKind {
    Request = 0x01,
    Response = 0x02,
    Event = 0x03,
    Error = 0x7F,
}

impl FrameKind {
    const fn from_u8(value: u8) -> Option<Self> {
        match value {
            0x01 => Some(Self::Request),
            0x02 => Some(Self::Response),
            0x03 => Some(Self::Event),
            0x7F => Some(Self::Error),
            _ => None,
        }
    }
}

#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TransportError {
    PayloadTooLong,
    BufferTooSmall,
    InvalidStart,
    InvalidKind,
    InvalidLength,
    BadChecksum,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct H2Frame<const N: usize = MAX_PAYLOAD> {
    pub kind: FrameKind,
    pub id: u8,
    pub payload: Vec<u8, N>,
}

impl<const N: usize> H2Frame<N> {
    pub fn new(kind: FrameKind, id: u8, payload: &[u8]) -> Self {
        let mut data = Vec::new();
        for byte in payload.iter().copied().take(N) {
            let _ = data.push(byte);
        }
        Self {
            kind,
            id,
            payload: data,
        }
    }

    pub fn encode<const OUT: usize>(&self) -> Result<Vec<u8, OUT>, TransportError> {
        if self.payload.len() > u8::MAX as usize {
            return Err(TransportError::PayloadTooLong);
        }
        let needed = 5 + self.payload.len();
        if OUT < needed {
            return Err(TransportError::BufferTooSmall);
        }
        let mut out = Vec::new();
        out.push(SOF).map_err(|_| TransportError::BufferTooSmall)?;
        out.push(self.kind as u8)
            .map_err(|_| TransportError::BufferTooSmall)?;
        out.push(self.id)
            .map_err(|_| TransportError::BufferTooSmall)?;
        out.push(self.payload.len() as u8)
            .map_err(|_| TransportError::BufferTooSmall)?;
        for byte in self.payload.iter().copied() {
            out.push(byte).map_err(|_| TransportError::BufferTooSmall)?;
        }
        out.push(checksum(&out[1..]))
            .map_err(|_| TransportError::BufferTooSmall)?;
        Ok(out)
    }

    pub fn decode(bytes: &[u8]) -> Result<Self, TransportError> {
        if bytes.len() < 5 {
            return Err(TransportError::InvalidLength);
        }
        if bytes[0] != SOF {
            return Err(TransportError::InvalidStart);
        }
        let kind = FrameKind::from_u8(bytes[1]).ok_or(TransportError::InvalidKind)?;
        let id = bytes[2];
        let len = usize::from(bytes[3]);
        if bytes.len() != len + 5 {
            return Err(TransportError::InvalidLength);
        }
        if checksum(&bytes[1..bytes.len() - 1]) != bytes[bytes.len() - 1] {
            return Err(TransportError::BadChecksum);
        }
        if len > N {
            return Err(TransportError::PayloadTooLong);
        }
        let mut payload = Vec::new();
        for byte in bytes[4..4 + len].iter().copied() {
            payload
                .push(byte)
                .map_err(|_| TransportError::PayloadTooLong)?;
        }
        Ok(Self { kind, id, payload })
    }
}

/// Gateway H2 firmware mode assumed by downstream OpenThread integration.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GatewayH2FirmwareMode {
    /// ESP32-H2 runs OpenThread Radio Co-Processor firmware and exposes Spinel.
    OpenThreadRcp,
    /// ESP32-H2 runs OpenThread Network Co-Processor firmware.
    OpenThreadNcp,
    /// ESP32-H2 runs a vendor/custom Thread coprocessor protocol.
    CustomThreadCoprocessor,
    /// ESP32-H2 runs a vendor/custom Matter bridge protocol.
    CustomMatterBridge,
    /// Firmware mode has not been identified by the application.
    Unknown,
}

/// Expected optional Gateway H2 routing selected by the caller.
///
/// This records software configuration only; the module's DIP positions cannot
/// be detected electrically by the CoreS3. H2 SPI is intentionally not modeled
/// as enabled because it is not coordinated by the LCD/TF-card SPI arbiter.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum GatewayH2OptionalRouting {
    /// Safe OpenThread RCP default: H2 SPI and PTA DIP routes are disconnected.
    #[default]
    UartOnly,
    /// Caller expects all three PTA routes and owns/configures them separately.
    PtaExpected,
}

/// Last operating mode requested through the Gateway H2 control API.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum GatewayH2ControlMode {
    /// BOOT/GPIO9 deasserted and EN asserted for normal firmware execution.
    #[default]
    Normal,
    /// BOOT/GPIO9 asserted while EN rises to request ROM serial download mode.
    Bootloader,
}

/// Pure control-line operation used to test the bounded EN/BOOT sequences.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum GatewayH2ControlStep {
    EnableLow,
    EnableHigh,
    BootLow,
    BootHigh,
    DelayMs(u32),
}

/// EN/BOOT sequence for a normal hardware reset.
pub const GATEWAY_H2_RESET_SEQUENCE: [GatewayH2ControlStep; 5] = [
    GatewayH2ControlStep::BootHigh,
    GatewayH2ControlStep::EnableLow,
    GatewayH2ControlStep::DelayMs(10),
    GatewayH2ControlStep::EnableHigh,
    GatewayH2ControlStep::DelayMs(50),
];
/// EN/BOOT sequence that requests ESP32-H2 ROM serial download mode.
pub const GATEWAY_H2_ENTER_BOOTLOADER_SEQUENCE: [GatewayH2ControlStep; 7] = [
    GatewayH2ControlStep::EnableLow,
    GatewayH2ControlStep::DelayMs(10),
    GatewayH2ControlStep::BootLow,
    GatewayH2ControlStep::DelayMs(1),
    GatewayH2ControlStep::EnableHigh,
    GatewayH2ControlStep::DelayMs(50),
    GatewayH2ControlStep::BootLow,
];
/// EN/BOOT sequence that returns to normal RCP execution.
pub const GATEWAY_H2_LEAVE_BOOTLOADER_SEQUENCE: [GatewayH2ControlStep; 7] = [
    GatewayH2ControlStep::EnableLow,
    GatewayH2ControlStep::DelayMs(10),
    GatewayH2ControlStep::BootHigh,
    GatewayH2ControlStep::DelayMs(1),
    GatewayH2ControlStep::EnableHigh,
    GatewayH2ControlStep::DelayMs(50),
    GatewayH2ControlStep::BootHigh,
];

/// Static Gateway H2 OpenThread transport metadata.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct GatewayH2OpenThreadConfig {
    /// UART baud rate used by the host link.
    pub baud: u32,
    /// Maximum frame size downstream buffers should reserve.
    pub max_frame_size: usize,
    /// H2 firmware mode expected by the application.
    pub firmware_mode: GatewayH2FirmwareMode,
    /// Whether frames are expected to use Spinel HDLC-lite escaping/framing.
    pub hdlc_lite: bool,
    /// Whether CRC/FCS is provided by the host framing layer.
    pub has_crc: bool,
    /// Expected optional physical routing. This is not a DIP-position detector.
    pub optional_routing: GatewayH2OptionalRouting,
}

impl Default for GatewayH2OpenThreadConfig {
    fn default() -> Self {
        Self::OPENTHREAD_RCP
    }
}

impl GatewayH2OpenThreadConfig {
    /// Return whether this configuration is valid for the BSP UART RCP path.
    pub const fn is_valid(self) -> bool {
        self.baud != 0
            && self.max_frame_size != 0
            && self.max_frame_size <= GATEWAY_H2_MAX_SPINEL_FRAME_SIZE
            && matches!(self.firmware_mode, GatewayH2FirmwareMode::OpenThreadRcp)
            && self.hdlc_lite
            && self.has_crc
            && matches!(self.optional_routing, GatewayH2OptionalRouting::UartOnly)
    }

    /// Conservative defaults for an ESP32-H2 running OpenThread RCP firmware.
    pub const OPENTHREAD_RCP: Self = Self {
        baud: DEFAULT_GATEWAY_H2_BAUD,
        max_frame_size: DEFAULT_SPINEL_MAX_FRAME_SIZE,
        firmware_mode: GatewayH2FirmwareMode::OpenThreadRcp,
        hdlc_lite: true,
        has_crc: true,
        optional_routing: GatewayH2OptionalRouting::UartOnly,
    };
}

/// OpenThread device role as reported by an H2 Thread controller backend.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ThreadRole {
    Disabled,
    Detached,
    Child,
    Router,
    Leader,
    BorderRouter,
}

/// High-level Gateway H2 Thread event for custom/non-Spinel H2 firmware.
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GatewayH2Event {
    Ready,
    Attached(ThreadRole),
    Detached,
    DatasetAccepted,
    DatasetRejected,
    Error,
}

/// Async-friendly transport trait for application-owned UART implementations.
pub trait GatewayH2Transport {
    type Error;

    fn send<const N: usize>(&mut self, frame: &H2Frame<N>) -> Result<(), Self::Error>;
    fn poll_receive<const N: usize>(&mut self) -> Result<Option<H2Frame<N>>, Self::Error>;
}

/// Synchronous Spinel frame transport for OpenThread RCP/NCP firmware.
///
/// For standard OpenThread RCP UART use, implementations should pass unescaped
/// Spinel payloads through [`crate::gateway_h2::spinel`] before writing bytes to
/// UART and should feed UART bytes into the same codec before returning frames.
pub trait GatewayH2SpinelTransport {
    type Error;

    /// Send one Spinel frame or encoded HDLC-lite frame, depending on implementation docs.
    fn send_spinel_frame(&mut self, frame: &[u8]) -> Result<(), Self::Error>;

    /// Poll for one received Spinel frame into `out`.
    ///
    /// Returns `Ok(None)` when no complete frame is available yet. Returns
    /// `Ok(Some(len))` when `out[..len]` contains one complete frame.
    fn poll_spinel_frame(&mut self, out: &mut [u8]) -> Result<Option<usize>, Self::Error>;
}

/// Async Spinel frame transport for OpenThread RCP/NCP firmware.
pub trait AsyncGatewayH2SpinelTransport {
    type Error;

    /// Send one Spinel frame or encoded HDLC-lite frame, depending on implementation docs.
    fn send_spinel_frame(
        &mut self,
        frame: &[u8],
    ) -> impl core::future::Future<Output = Result<(), Self::Error>>;

    /// Receive one complete Spinel frame into `out`, applying implementation-defined timeout policy.
    fn receive_spinel_frame(
        &mut self,
        out: &mut [u8],
    ) -> impl core::future::Future<Output = Result<usize, Self::Error>>;
}

/// Higher-level Thread controller trait for H2 firmware that does not expose Spinel.
pub trait GatewayH2ThreadController {
    type Error;

    fn is_ready(&mut self) -> Result<bool, Self::Error>;
    fn set_active_dataset(&mut self, dataset_tlv: &[u8]) -> Result<(), Self::Error>;
    fn attach(&mut self) -> Result<(), Self::Error>;
    fn detach(&mut self) -> Result<(), Self::Error>;
    fn role(&mut self) -> Result<ThreadRole, Self::Error>;
    fn poll_event(&mut self, out: &mut [u8]) -> Result<Option<GatewayH2Event>, Self::Error>;
}

pub const fn checksum(bytes: &[u8]) -> u8 {
    let mut sum = 0u8;
    let mut index = 0;
    while index < bytes.len() {
        sum = sum.wrapping_add(bytes[index]);
        index += 1;
    }
    !sum
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn encodes_and_decodes_frame() {
        let frame = H2Frame::<16>::new(FrameKind::Request, 7, b"state");
        let bytes = frame.encode::<16>().unwrap();
        let decoded = H2Frame::<16>::decode(&bytes).unwrap();
        assert_eq!(decoded, frame);
    }

    #[test]
    fn flush_sequence_comparison_is_wrap_safe() {
        assert!(tx_sequence_reached(10, 10));
        assert!(tx_sequence_reached(11, 10));
        assert!(!tx_sequence_reached(9, 10));
        assert!(tx_sequence_reached(1, u32::MAX));
    }

    #[test]
    fn validates_buffer_capacities() {
        assert_eq!(
            validate_openthread_buffer_capacities(
                GATEWAY_H2_MIN_RX_BUFFER_SIZE - 1,
                GATEWAY_H2_MIN_TX_BUFFER_SIZE
            ),
            Err(GatewayH2BufferCapacityError::RxTooSmall)
        );
        assert_eq!(
            validate_openthread_buffer_capacities(
                GATEWAY_H2_MIN_RX_BUFFER_SIZE,
                GATEWAY_H2_MIN_TX_BUFFER_SIZE - 1
            ),
            Err(GatewayH2BufferCapacityError::TxTooSmall)
        );
        assert_eq!(
            validate_openthread_buffer_capacities(
                GATEWAY_H2_MIN_RX_BUFFER_SIZE,
                GATEWAY_H2_MIN_TX_BUFFER_SIZE
            ),
            Ok(())
        );
        assert_eq!(
            GatewayH2OpenThreadConfig::default(),
            GatewayH2OpenThreadConfig::OPENTHREAD_RCP
        );
    }

    #[test]
    fn control_sequences_set_straps_before_enable_rises() {
        assert_eq!(
            GATEWAY_H2_ENTER_BOOTLOADER_SEQUENCE,
            [
                GatewayH2ControlStep::EnableLow,
                GatewayH2ControlStep::DelayMs(10),
                GatewayH2ControlStep::BootLow,
                GatewayH2ControlStep::DelayMs(1),
                GatewayH2ControlStep::EnableHigh,
                GatewayH2ControlStep::DelayMs(50),
                GatewayH2ControlStep::BootLow,
            ]
        );
        assert_eq!(
            GATEWAY_H2_LEAVE_BOOTLOADER_SEQUENCE[2],
            GatewayH2ControlStep::BootHigh
        );
        let config = GatewayH2OpenThreadConfig::default();
        assert_eq!(config.optional_routing, GatewayH2OptionalRouting::UartOnly);
        assert!(config.is_valid());
        assert!(
            !GatewayH2OpenThreadConfig {
                optional_routing: GatewayH2OptionalRouting::PtaExpected,
                ..config
            }
            .is_valid()
        );
    }

    #[test]
    fn rejects_bad_checksum() {
        let frame = H2Frame::<16>::new(FrameKind::Event, 1, b"x");
        let mut bytes = frame.encode::<16>().unwrap();
        let last = bytes.len() - 1;
        bytes[last] ^= 0x01;
        assert_eq!(
            H2Frame::<16>::decode(&bytes),
            Err(TransportError::BadChecksum)
        );
    }
}