linkage-blaze 0.1.10

No-std 3D turtle graphics for animated jointed figures
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
//! A clock display example driven by a parameterized linkage.
//!
//! The public entry points are platform-neutral; a platform launcher supplies
//! the Device Envoy display and touch implementations.

use core::{fmt, iter};

use crate::{Error as LinkageError, linkage_file, render::Projection};
use device_envoy_core::{
    UnwrapInfallible,
    button::Button,
    clock_sync::{ClockSync, h12_m_s},
    cyd::{
        CydDisplay,
        display::{
            CydFrame, DrawItem, Image565Fixed, Image565View, Orientation, tga,
            tiling::max_rectangle_pixel_count,
        },
    },
};
use embassy_futures::select::{Either, select};
use embedded_graphics::{
    Drawable,
    mono_font::{MonoFont, MonoTextStyle, ascii::FONT_6X10},
    pixelcolor::Rgb565,
    pixelcolor::Rgb888,
    prelude::{Point, Size},
    primitives::Rectangle,
    text::{Alignment, Baseline, Text, TextStyle, TextStyleBuilder},
};
use log::info;
use profont::PROFONT_18_POINT;
use time::OffsetDateTime;

// ── Public constants ────────────────────────────────────────────────────────────────

/// Near-black blue clock background.
pub const BACKGROUND_COLOR: Rgb888 = Rgb888::new(3, 7, 14);
/// Dim-gold clock foreground.
pub const FOREGROUND_COLOR: Rgb888 = Rgb888::new(210, 160, 80);
/// Display orientation used by the clock renderer.
pub const ORIENTATION: Orientation = Orientation::Landscape;
/// Font used for Wi-Fi status text.
pub const WIFI_STATUS_FONT: MonoFont<'static> = FONT_6X10;
/// Rectangle reserved for Wi-Fi status text.
pub const WIFI_STATUS_RECTANGLE: Rectangle = Rectangle::new(Point::new(256, 5), Size::new(62, 10));
/// Maximum number of pixels drawn in one clock frame.
pub const MAX_FRAME_PIXEL_COUNT: usize =
    max_rectangle_pixel_count(WIFI_STATUS_RECTANGLE, TIME_RECTANGLE);

// ── Private constants ─────────────────────────────────────────────────────────

const TIME_RECTANGLE: Rectangle = Rectangle::new(Point::new(55, 0), Size::new(200, 22));
const TIME_COLOR: Rgb888 = Rgb888::new(255, 218, 118); // pale gold (255, 218, 118)
const TIME_FONT: MonoFont<'static> = PROFONT_18_POINT;
const TIME_TEXT_STYLE: TextStyle = TextStyleBuilder::new()
    .alignment(Alignment::Center)
    .baseline(Baseline::Top)
    .build();
const TIME_TEXT_CAPACITY: usize = 16;
const TIME_TEXT_TOP_PADDING: i32 = -1;

const CLOCK_BOUNDS: Rectangle = Rectangle::new(Point::new(50, 20), Size::new(220, 220));
const BACKGROUND_BITMAP: Image565Fixed<320, 240, { 320 * 240 }> =
    tga!("../assets/astronomy_window_background.tga").to_565();
const BACKGROUND_BITMAP_VIEW: Image565View = BACKGROUND_BITMAP.view();
const PROJECTION: Projection = Projection::top_orthographic(
    Point::new(160, 130), // target origin
    1.375,                // scale
);
const CLOCK_BACKGROUND_VIEW: Image565View = BACKGROUND_BITMAP.view_rect(CLOCK_BOUNDS);
const CLOCK_BACKGROUND_BITMAP: DrawItem = DrawItem::Bitmap {
    view: CLOCK_BACKGROUND_VIEW,
    top_left: CLOCK_BOUNDS.top_left,
};
linkage_file! {
    clock_linkage {
        file: "../assets/examples/clock.lb.rs",
    }
}
const LINKAGE: clock_linkage::View = clock_linkage::view();

/// Run the clock render loop until the physical BOOT button requests a Wi-Fi
/// reset, driven by `clock_sync` ticks and drawn onto `cyd`.
pub async fn run<CydDisplayDevice, ClockSyncDevice>(
    display: &mut CydDisplayDevice,
    clock_sync: &ClockSyncDevice,
    button: &mut impl Button,
) -> Result<Exit, Error<CydDisplayDevice::Error>>
where
    CydDisplayDevice: CydDisplay,
    ClockSyncDevice: ClockSync,
{
    let background565 = Rgb565::from(BACKGROUND_COLOR);
    let time_color = Rgb565::from(TIME_COLOR);

    loop {
        // ── Wait for a tick and get the time. ────────────────────────────────────────
        let tick = match select(button.wait_for_press(), clock_sync.wait_for_tick()).await {
            Either::First(()) => return Ok(Exit::ResetWifi),
            Either::Second(tick) => tick,
        };
        let local_time = &tick.local_time;
        let time_text = text_12h(local_time)?;
        info!("tick {}", time_text.as_str());

        // ── Render the digital time strip (using embedded graphics methods). ─────────
        let mut time_frame = display.frame_mut(TIME_RECTANGLE);
        time_frame.fill(background565);
        Text::with_text_style(
            time_text.as_str(),
            TIME_RECTANGLE.top_left
                + Point::new(TIME_RECTANGLE.size.width as i32 / 2, TIME_TEXT_TOP_PADDING),
            MonoTextStyle::new(&TIME_FONT, time_color),
            TIME_TEXT_STYLE,
        )
        .draw(&mut time_frame)
        .unwrap_infallible();
        time_frame.flush().await.map_err(Error::Flush)?;
        drop(time_frame);

        // ── Stream the pixels of the updated clock ────────────────────────────────────────

        // Compute the time-dependent linkage parameters, then project the clock's
        // 3D draw items into pixel-space 2D draw items.
        let params = linkage_params(local_time);
        let draw_items_2d = LINKAGE
            .draw_items_3d(&params)?
            .map(|draw_item_3d| draw_item_3d.project(&PROJECTION));

        // Stream the pixels row-major straight to the display with no frame or
        // tile buffer, with the background_bitmap as the first pixel source.
        display
            .draw_items::<{ 1 + LINKAGE.draw_item_3d_count() }>(
                CLOCK_BOUNDS,
                background565, // color, but will be overridden by the background_bitmap
                iter::once(CLOCK_BACKGROUND_BITMAP).chain(draw_items_2d),
            )
            .map_err(Error::Flush)?;
    }
}

/// Draw the static full-screen clock background_bitmap.
pub async fn splash<CydDisplayDevice>(
    display: &mut CydDisplayDevice,
) -> Result<(), Error<CydDisplayDevice::Error>>
where
    CydDisplayDevice: CydDisplay,
{
    display
        .fill_contiguous_full(BACKGROUND_BITMAP_VIEW.rgb565_iter())
        .map_err(Error::Flush)?;
    Ok(())
}

/// Actions requested by the Clock's physical BOOT button.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Exit {
    /// Return to Wi-Fi setup before resuming the clock.
    ResetWifi,
}

/// Error from the generic clock loop, generic over the surface's flush error `FlushError`.
///
/// Both variants are converted explicitly at the call site (`.map_err(...)`),
/// the same flush-error convention as
/// [`skeleton_clock::Error`](crate::examples::skeleton_clock::Error).
#[derive(Debug, derive_more::From)]
pub enum Error<FlushError> {
    /// A runtime linkage parameter was invalid.
    Linkage(LinkageError),
    /// Formatting the time string failed.
    Text(fmt::Error),
    /// Flushing a frame to the display failed.
    #[from(ignore)]
    Flush(FlushError),
}

// ── Private helpers ───────────────────────────────────────────────────────────

// ── Clock time ──────────────────────────────────────────────────────────────────

/// Format a 12-hour clock string with AM/PM.
fn text_12h(
    local_time: &OffsetDateTime,
) -> Result<heapless::String<TIME_TEXT_CAPACITY>, fmt::Error> {
    let (hour_12, minute, _) = h12_m_s(local_time);
    let meridiem = if local_time.hour() < 12 { "AM" } else { "PM" };
    let mut text = heapless::String::new();
    fmt::write(&mut text, format_args!("{hour_12}:{minute:02} {meridiem}"))?;
    Ok(text)
}

fn linkage_params(local_time: &OffsetDateTime) -> [f32; 2] {
    let (hour_12, minute, second) = h12_m_s(local_time);
    let second_turn = second as f32 / 60.0;
    let minute_turn = (minute as f32 + second_turn) / 60.0;
    let hour = ((hour_12 % 12) as f32 + minute_turn) / 12.0;
    let face_spin = (((second % 20) as f32) / 20.0 + 0.5) % 1.0;
    [hour, face_spin]
}

#[cfg(test)]
mod tests {
    use core::cell::Cell;

    use device_envoy_core::button::{__ButtonMonitor, Button};
    use device_envoy_core::clock_sync::{ClockSync, ClockSyncTick, UnixSeconds};
    use device_envoy_core::cyd::{CydDisplay, display::CydFrame};
    use device_envoy_core::memory::{CydMemory, assert_framebuffer_matches_expected_png};
    use futures_executor::block_on;
    use time::OffsetDateTime;

    use super::{
        BACKGROUND_COLOR, Exit, FOREGROUND_COLOR, ORIENTATION, WIFI_STATUS_FONT,
        WIFI_STATUS_RECTANGLE, run, splash,
    };

    /// A `ClockSync` test double that ticks instantly with a fixed time,
    /// rather than waiting on real NTP/timer infrastructure.
    struct FixedClockSync {
        local_time: OffsetDateTime,
    }

    impl ClockSync for FixedClockSync {
        async fn wait_for_tick(&self) -> ClockSyncTick {
            ClockSyncTick {
                local_time: self.local_time,
                since_last_sync: embassy_time::Duration::from_secs(0),
            }
        }

        fn now_local(&self) -> OffsetDateTime {
            self.local_time
        }

        fn set_offset_minutes(&self, _minutes: i32) {}

        fn offset_minutes(&self) -> i32 {
            0
        }

        fn set_tick_interval(&self, _interval: Option<embassy_time::Duration>) {}

        fn set_speed(&self, _speed_multiplier: f32) {}

        fn set_utc_time(&self, _unix_seconds: UnixSeconds) {}
    }

    struct ImmediateButton;

    impl __ButtonMonitor for ImmediateButton {
        fn is_pressed_raw(&self) -> bool {
            false
        }

        async fn wait_until_pressed_state(&mut self, _pressed: bool) {}
    }

    impl Button for ImmediateButton {
        async fn wait_for_press(&mut self) {}
    }

    #[test]
    fn boot_requests_wifi_reset_before_rendering_the_next_tick() {
        let memory_cyd = CydMemory::new(
            ORIENTATION.size(),
            BACKGROUND_COLOR,
            FOREGROUND_COLOR,
            &WIFI_STATUS_FONT,
        );
        let clock_sync = FixedClockSync {
            local_time: OffsetDateTime::from_unix_timestamp(1_700_003_415)
                .expect("valid fixed timestamp"),
        };
        let mut button = ImmediateButton;

        let result = {
            let mut display = memory_cyd.display();
            block_on(run(&mut display, &clock_sync, &mut button))
        };

        assert_eq!(
            result.expect("BOOT should be a typed exit"),
            Exit::ResetWifi
        );
    }

    #[test]
    fn boot_requests_wifi_reset_after_a_rendered_tick() {
        let mut memory_cyd = CydMemory::new(
            ORIENTATION.size(),
            BACKGROUND_COLOR,
            FOREGROUND_COLOR,
            &WIFI_STATUS_FONT,
        );
        memory_cyd.set_frame_budget(100);
        let clock_sync = OneTickClockSync {
            local_time: OffsetDateTime::from_unix_timestamp(1_700_003_415)
                .expect("valid fixed timestamp"),
            ticks: Cell::new(0),
        };
        let mut button = AfterTickButton {
            waits: Cell::new(0),
        };

        let result = {
            let mut display = memory_cyd.display();
            block_on(run(&mut display, &clock_sync, &mut button))
        };

        assert_eq!(
            result.expect("BOOT should exit after a rendered tick"),
            Exit::ResetWifi
        );
        assert!(memory_cyd.flush_count() > 0);
    }

    #[test]
    fn clock_renders_expected_frame() {
        let mut memory_cyd = CydMemory::new(
            ORIENTATION.size(),
            BACKGROUND_COLOR,
            FOREGROUND_COLOR,
            &WIFI_STATUS_FONT,
        );
        memory_cyd.set_frame_budget(3);
        let clock_sync = FixedClockSync {
            local_time: OffsetDateTime::from_unix_timestamp(1_700_003_415)
                .expect("valid fixed timestamp"),
        };
        let mut memory_button = NeverButton;

        {
            let mut display = memory_cyd.display();
            block_on(splash(&mut display))
                .expect("clock splash should draw the static background_bitmap");
            block_on(
                display
                    .frame_mut(WIFI_STATUS_RECTANGLE)
                    .clear()
                    .write_text("WiFi: OK")
                    .flush(),
            )
            .expect("wifi status frame should flush during setup");
        }

        let clock_result = {
            let mut display = memory_cyd.display();
            block_on(run(&mut display, &clock_sync, &mut memory_button))
        };
        clock_result.expect_err("the free-running loop should stop at the frame budget");

        assert_framebuffer_matches_expected_png(
            &memory_cyd,
            env!("CARGO_MANIFEST_DIR"),
            "clock.png",
        )
        .expect("rendered frame should match the golden image");
    }

    struct NeverButton;

    impl __ButtonMonitor for NeverButton {
        fn is_pressed_raw(&self) -> bool {
            false
        }

        async fn wait_until_pressed_state(&mut self, _pressed: bool) {}
    }

    impl Button for NeverButton {
        async fn wait_for_press(&mut self) {
            core::future::pending().await
        }
    }

    struct AfterTickButton {
        waits: Cell<u8>,
    }

    impl __ButtonMonitor for AfterTickButton {
        fn is_pressed_raw(&self) -> bool {
            false
        }

        async fn wait_until_pressed_state(&mut self, _pressed: bool) {}
    }

    impl Button for AfterTickButton {
        async fn wait_for_press(&mut self) {
            let wait_number = self.waits.get();
            self.waits.set(wait_number + 1);
            if wait_number == 0 {
                core::future::pending().await
            }
        }
    }

    struct OneTickClockSync {
        local_time: OffsetDateTime,
        ticks: Cell<u8>,
    }

    impl ClockSync for OneTickClockSync {
        async fn wait_for_tick(&self) -> ClockSyncTick {
            if self.ticks.replace(1) == 0 {
                ClockSyncTick {
                    local_time: self.local_time,
                    since_last_sync: embassy_time::Duration::from_secs(0),
                }
            } else {
                core::future::pending().await
            }
        }

        fn now_local(&self) -> OffsetDateTime {
            self.local_time
        }

        fn set_offset_minutes(&self, _minutes: i32) {}

        fn offset_minutes(&self) -> i32 {
            0
        }

        fn set_tick_interval(&self, _interval: Option<embassy_time::Duration>) {}

        fn set_speed(&self, _speed_multiplier: f32) {}

        fn set_utc_time(&self, _unix_seconds: UnixSeconds) {}
    }
}