device-envoy-core 0.1.4

Shared traits and data types for device-envoy platform crates
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
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
use core::fmt::Write;

use crate::button::Button;
use crate::flash_block::FlashBlock;
#[cfg(not(test))]
use embassy_time::Timer;
use heapless::String;

use super::super::CydDisplay;
use super::calibration::{
    CALIBRATION_MAX_DRAW_ITEMS, CALIBRATION_TEXT_RECTANGLE, CalibrationConfig, CalibrationCorner,
    VERIFY_HIT_RADIUS_PIXELS, calibration_ack_dot_item, calibration_rejected_target_items,
    calibration_target_items, calibration_verify_target_center, calibration_verify_target_items,
    validate_calibration_points,
};
use super::flow::CalibrationFlow;
use super::flow::CalibrationFlowEvent;
use super::flow::{ReleaseTouchCapture, ReleaseTouchCaptureEvent};
use crate::cyd::backend::TouchUncalibrated;
use crate::cyd::display::{CydFrame, DrawItem};
use crate::cyd::{SCREEN_HEIGHT, SCREEN_WIDTH};
use embedded_graphics::{
    geometry::{Point, Size},
    primitives::Rectangle,
};

pub const CAPTURE_ACK_FRAME_COUNT: usize = 8;
pub const REJECTED_FRAME_COUNT: usize = 30;
pub const MAX_RAW_EVENTS_PER_FRAME: usize = 64;
const VERIFY_TIMEOUT_SECONDS: usize = 10;
// Verification is paced below so this frame budget remains a real-time
// timeout even when the display only needs to redraw a small text rectangle.
const CALIBRATION_DRAW_FRAMES_PER_SECOND: usize = 10;
pub const VERIFY_TIMEOUT_FRAMES: usize =
    VERIFY_TIMEOUT_SECONDS * CALIBRATION_DRAW_FRAMES_PER_SECOND;

/// Bounds for the target/dot geometry, streamed buffer-free via
/// [`CydDisplay::draw_items`]. Covers the whole screen so every redraw
/// erases any stale shape from the previous state before drawing the
/// current one; the text banner is drawn afterward so it always wins the
/// small overlap at the bottom of the screen.
const CALIBRATION_SHAPES_RECTANGLE: Rectangle = Rectangle::new(
    Point::zero(),
    Size::new(SCREEN_WIDTH as u32, SCREEN_HEIGHT as u32),
);

/// Error while loading or interactively creating touch calibration.
#[derive(Debug)]
pub enum Error<DeviceError, FlashError> {
    /// Reading or drawing through the platform touch/display backend failed.
    Device(DeviceError),
    /// Loading or saving calibration in persistent storage failed.
    Flash(FlashError),
}

#[derive(Clone, Copy, Debug)]
/// Tunable frame-budget settings for the shared calibration flow.
struct EnsureCalibrationSettings {
    verify_timeout_frames: usize,
}

impl EnsureCalibrationSettings {
    const DEFAULT: Self = Self {
        verify_timeout_frames: VERIFY_TIMEOUT_FRAMES,
    };

    #[must_use]
    const fn verify_timeout_frames(self) -> usize {
        self.verify_timeout_frames
    }
}

enum CalibrationDriverState {
    Capturing,
    ShowCaptured {
        calibration_corner: CalibrationCorner,
        frames_remaining: usize,
    },
    ShowRejected {
        worst_residual_pixels: Option<f32>,
        frames_remaining: usize,
    },
    Verifying {
        candidate_config: CalibrationConfig,
        release_touch_capture: ReleaseTouchCapture,
        polls_remaining: usize,
    },
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum CalibrationShape {
    Capturing(Option<CalibrationCorner>),
    ShowCaptured {
        calibration_corner: CalibrationCorner,
        next_corner: Option<CalibrationCorner>,
    },
    ShowRejected(Option<CalibrationCorner>),
    Verifying,
}

/// Load saved touch calibration or create it interactively during device construction.
///
/// Missing, corrupt, or invalid saved data starts the four-tap calibration flow and
/// saves the new configuration. Platform constructors keep the display in landscape
/// orientation during this process, then return the calibrated touch implementation
/// configured for `orientation`. Application code reads events through
/// [`CydTouch`](crate::cyd::CydTouch) instead.
pub async fn ensure_calibration<D, T, F, R>(
    display: &mut D,
    touch: T,
    calibration_flash_block: &mut F,
    recalibration_button: &mut R,
    confirmed_message: Option<&str>,
    orientation: crate::cyd::display::Orientation,
) -> Result<T::Calibrated, Error<D::Error, F::Error>>
where
    D: CydDisplay,
    T: TouchUncalibrated<Error = D::Error>,
    F: FlashBlock,
    R: Button,
{
    ensure_calibration_with_settings(
        display,
        touch,
        calibration_flash_block,
        recalibration_button,
        confirmed_message,
        EnsureCalibrationSettings::DEFAULT,
        orientation,
    )
    .await
}

async fn ensure_calibration_with_settings<D, T, F, R>(
    display: &mut D,
    mut touch: T,
    calibration_flash_block: &mut F,
    recalibration_button: &mut R,
    confirmed_message: Option<&str>,
    ensure_calibration_settings: EnsureCalibrationSettings,
    orientation: crate::cyd::display::Orientation,
) -> Result<T::Calibrated, Error<D::Error, F::Error>>
where
    D: CydDisplay,
    T: TouchUncalibrated<Error = D::Error>,
    F: FlashBlock,
    R: Button,
{
    if let Some(calibration_config) = calibration_flash_block
        .load::<CalibrationConfig>()
        .unwrap_or(None)
    {
        return Ok(touch.calibrate(calibration_config, orientation));
    }

    let mut calibration_flow = CalibrationFlow::new();
    let mut calibration_driver_state = CalibrationDriverState::Capturing;
    let mut last_calibration_shape = None;
    let mut calibration_button_released = true;

    loop {
        // A plain Button is intentional here: this loop does synchronous
        // per-frame polling, not cancelable button futures, so ButtonWatch
        // would add an ESP-only dependency without buying correctness.
        let calibration_button_pressed = recalibration_button.is_pressed();
        if calibration_button_pressed && calibration_button_released {
            calibration_flow.restart();
            calibration_driver_state = CalibrationDriverState::Capturing;
        }
        calibration_button_released = !calibration_button_pressed;

        let mut saw_idle = false;
        for _raw_event_index in 0..MAX_RAW_EVENTS_PER_FRAME {
            let raw_touch_event = match touch.read_raw_touch_event() {
                Ok(raw_touch_event) => raw_touch_event,
                Err(error) => {
                    return Err(Error::Device(error));
                }
            };
            let Some(raw_touch_event) = raw_touch_event else {
                saw_idle = true;
                break;
            };

            match &mut calibration_driver_state {
                CalibrationDriverState::Capturing => {
                    let Some(calibration_flow_event) =
                        calibration_flow.handle_raw_touch_event(Some(raw_touch_event))
                    else {
                        continue;
                    };

                    match calibration_flow_event {
                        CalibrationFlowEvent::PointCaptured {
                            calibration_corner,
                            raw_point: _raw_point,
                            next_corner: _next_corner,
                            usable_sample_count: _usable_sample_count,
                        } => {
                            calibration_driver_state = CalibrationDriverState::ShowCaptured {
                                calibration_corner,
                                frames_remaining: CAPTURE_ACK_FRAME_COUNT,
                            };
                        }
                        CalibrationFlowEvent::Completed {
                            raw_points,
                            calibration_corner: _calibration_corner,
                            usable_sample_count: _usable_sample_count,
                        } => match validate_calibration_points(raw_points) {
                            Ok(calibration_validation) => {
                                calibration_driver_state = CalibrationDriverState::Verifying {
                                    candidate_config: calibration_validation.calibration_config(),
                                    release_touch_capture: ReleaseTouchCapture::new(),
                                    polls_remaining: ensure_calibration_settings
                                        .verify_timeout_frames(),
                                };
                            }
                            Err(crate::Error::CalibrationResidualTooLarge {
                                worst_residual_pixels,
                            }) => {
                                calibration_flow.restart();
                                calibration_driver_state = CalibrationDriverState::ShowRejected {
                                    worst_residual_pixels: Some(worst_residual_pixels),
                                    frames_remaining: REJECTED_FRAME_COUNT,
                                };
                            }
                            Err(crate::Error::CalibrationDegenerateGeometry) => {
                                calibration_flow.restart();
                                calibration_driver_state = CalibrationDriverState::ShowRejected {
                                    worst_residual_pixels: None,
                                    frames_remaining: REJECTED_FRAME_COUNT,
                                };
                            }
                            Err(_) => {
                                calibration_flow.restart();
                                calibration_driver_state = CalibrationDriverState::ShowRejected {
                                    worst_residual_pixels: None,
                                    frames_remaining: REJECTED_FRAME_COUNT,
                                };
                            }
                        },
                    }
                }
                CalibrationDriverState::Verifying {
                    candidate_config,
                    release_touch_capture,
                    ..
                } => {
                    let Some(ReleaseTouchCaptureEvent::Captured { raw_point, .. }) =
                        release_touch_capture.handle_raw_touch_event(Some(raw_touch_event))
                    else {
                        continue;
                    };
                    let (mapped_x, mapped_y) =
                        candidate_config.map_raw_to_screen(raw_point.x, raw_point.y);
                    if hit_verify_target(mapped_x, mapped_y) {
                        if let Some(confirmed_message) = confirmed_message
                            && let Err(error) =
                                draw_message_screen(display, confirmed_message).await
                        {
                            return Err(Error::Device(error));
                        }
                        if let Err(error) = calibration_flash_block.save(candidate_config) {
                            return Err(Error::Flash(error));
                        }
                        let calibration_config = *candidate_config;
                        return Ok(touch.calibrate(calibration_config, orientation));
                    } else {
                        calibration_flow.restart();
                        calibration_driver_state = CalibrationDriverState::ShowRejected {
                            worst_residual_pixels: None,
                            frames_remaining: REJECTED_FRAME_COUNT,
                        };
                    }
                }
                CalibrationDriverState::ShowCaptured { .. }
                | CalibrationDriverState::ShowRejected { .. } => {}
            }
        }

        if saw_idle {
            advance_driver_state_after_idle(&mut calibration_flow, &mut calibration_driver_state);
        }

        if let Err(error) = draw_calibration_screen(
            display,
            &calibration_flow,
            &calibration_driver_state,
            &mut last_calibration_shape,
        )
        .await
        {
            return Err(Error::Device(error));
        }

        if saw_idle {
            pace_verification_frame(&calibration_driver_state).await;
        }
    }
}

#[cfg(not(test))]
async fn pace_verification_frame(calibration_driver_state: &CalibrationDriverState) {
    // The memory-backed tests intentionally use frame counts without waiting
    // for wall-clock time. Hardware and browser builds need the pause because
    // the optimized redraw path can otherwise consume all timeout frames in a
    // few milliseconds.
    if matches!(
        calibration_driver_state,
        CalibrationDriverState::Verifying { .. }
    ) {
        Timer::after_millis(100).await;
    }
}

#[cfg(test)]
async fn pace_verification_frame(_calibration_driver_state: &CalibrationDriverState) {}

async fn draw_message_screen<D>(display: &mut D, message: &str) -> Result<(), D::Error>
where
    D: CydDisplay,
{
    // Erase any leftover target geometry from the redraw just before this
    // one; buffer-free, so it costs nothing beyond the SPI transfer itself.
    display.clear()?;
    display
        .frame_mut(CALIBRATION_TEXT_RECTANGLE)
        .write_text(message)
        .flush()
        .await
}

fn advance_driver_state_after_idle(
    calibration_flow: &mut CalibrationFlow,
    calibration_driver_state: &mut CalibrationDriverState,
) {
    match calibration_driver_state {
        CalibrationDriverState::Capturing => {
            calibration_flow.handle_raw_touch_event(None);
        }
        CalibrationDriverState::ShowCaptured {
            frames_remaining, ..
        } => {
            if *frames_remaining > 0 {
                *frames_remaining -= 1;
            }
            if *frames_remaining == 0 {
                *calibration_driver_state = CalibrationDriverState::Capturing;
            }
        }
        CalibrationDriverState::ShowRejected {
            frames_remaining, ..
        } => {
            if *frames_remaining > 0 {
                *frames_remaining -= 1;
            }
            if *frames_remaining == 0 {
                *calibration_driver_state = CalibrationDriverState::Capturing;
            }
        }
        CalibrationDriverState::Verifying {
            release_touch_capture,
            polls_remaining,
            ..
        } => {
            release_touch_capture.handle_raw_touch_event(None);
            if *polls_remaining > 0 {
                *polls_remaining -= 1;
            }
            if *polls_remaining == 0 {
                calibration_flow.restart();
                *calibration_driver_state = CalibrationDriverState::ShowRejected {
                    worst_residual_pixels: None,
                    frames_remaining: REJECTED_FRAME_COUNT,
                };
            }
        }
    }
}

async fn draw_calibration_screen<D>(
    display: &mut D,
    calibration_flow: &CalibrationFlow,
    calibration_driver_state: &CalibrationDriverState,
    last_calibration_shape: &mut Option<CalibrationShape>,
) -> Result<(), D::Error>
where
    D: CydDisplay,
{
    let mut shape_items: heapless::Vec<DrawItem, CALIBRATION_MAX_DRAW_ITEMS> = heapless::Vec::new();
    let mut message = String::<48>::new();
    let calibration_shape;

    match calibration_driver_state {
        CalibrationDriverState::Capturing => {
            let next_corner = calibration_flow.next_corner();
            calibration_shape = CalibrationShape::Capturing(next_corner);
            if let Some(calibration_corner) = next_corner {
                push_calibration_items(
                    &mut shape_items,
                    calibration_target_items(calibration_corner),
                );
            }
            push_calibration_message(&mut message, "Tap target, then lift");
        }
        CalibrationDriverState::ShowCaptured {
            calibration_corner, ..
        } => {
            let next_corner = calibration_flow.next_corner();
            calibration_shape = CalibrationShape::ShowCaptured {
                calibration_corner: *calibration_corner,
                next_corner,
            };
            push_calibration_items(
                &mut shape_items,
                [calibration_ack_dot_item(*calibration_corner)],
            );
            if let Some(next_corner) = next_corner {
                push_calibration_items(&mut shape_items, calibration_target_items(next_corner));
            }
            push_calibration_message(&mut message, "Corner captured");
        }
        CalibrationDriverState::ShowRejected {
            worst_residual_pixels,
            ..
        } => {
            let next_corner = calibration_flow.next_corner();
            calibration_shape = CalibrationShape::ShowRejected(next_corner);
            if let Some(calibration_corner) = next_corner {
                push_calibration_items(
                    &mut shape_items,
                    calibration_rejected_target_items(calibration_corner),
                );
            }
            match worst_residual_pixels {
                Some(worst_residual_pixels) => {
                    match write!(&mut message, "Try again ({worst_residual_pixels:.1}px)") {
                        Ok(()) => {}
                        Err(_) => unreachable!("heapless message capacity is sufficient"),
                    }
                }
                None => push_calibration_message(&mut message, "Try again"),
            }
        }
        CalibrationDriverState::Verifying { .. } => {
            calibration_shape = CalibrationShape::Verifying;
            push_calibration_items(&mut shape_items, calibration_verify_target_items());
            push_calibration_message(&mut message, "Tap center to save");
        }
    }

    // Buffer-free: stream the shape only when it changes. Re-streaming a
    // full-screen background on every polling iteration makes the panel flash
    // between the background and the text frame.
    if *last_calibration_shape != Some(calibration_shape) {
        let background = display.background_565();
        display.draw_items::<CALIBRATION_MAX_DRAW_ITEMS>(
            CALIBRATION_SHAPES_RECTANGLE,
            background,
            shape_items,
        )?;
        *last_calibration_shape = Some(calibration_shape);
    }

    // The one buffered flush per redraw: small (`CALIBRATION_TEXT_RECTANGLE`
    // is `CALIBRATION_MIN_PIXEL_COUNT` pixels, not the full screen), drawn
    // after the shapes so it always wins the small overlap at the bottom.
    display
        .frame_mut(CALIBRATION_TEXT_RECTANGLE)
        .write_text(message.as_str())
        .flush()
        .await
}

fn push_calibration_items<const N: usize, const M: usize>(
    shape_items: &mut heapless::Vec<DrawItem, N>,
    items: [DrawItem; M],
) {
    for item in items {
        shape_items
            .push(item)
            .expect("calibration draw items fit CALIBRATION_MAX_DRAW_ITEMS");
    }
}

fn push_calibration_message(message: &mut String<48>, text: &str) {
    message
        .push_str(text)
        .expect("calibration message fits fixed buffer");
}

fn hit_verify_target(mapped_x: f32, mapped_y: f32) -> bool {
    let verify_target_center = calibration_verify_target_center();
    let delta_x = mapped_x - verify_target_center.x as f32;
    let delta_y = mapped_y - verify_target_center.y as f32;
    delta_x * delta_x + delta_y * delta_y <= VERIFY_HIT_RADIUS_PIXELS * VERIFY_HIT_RADIUS_PIXELS
}