device-envoy-esp 0.1.0

Build ESP32 applications with composable device abstractions
Documentation
// @generated by cargo xtask generate-board-examples
//!
//! Wiring:
//! - I2C LCD SDA -> GPIO4
//! - I2C LCD SCL -> GPIO5
//! - I2C LCD VCC -> 5V (most backpack modules; use 3.3V only if your module supports it)
//! - I2C LCD GND -> GND (shared with ESP32 GND)
//! - Force-portal button -> GPIO0 to GND (`PressedTo::Ground`)
#![no_std]
#![no_main]

use core::{convert::Infallible, fmt};

use device_envoy_example_common::clock_ui::{ClockUiEvent, run_clock_ui};
use embassy_executor::Spawner;
use esp_backtrace as _;
use log::info;

use device_envoy_esp::{
    Error, Result,
    button::PressedTo,
    button_watch,
    clock_sync::{ClockSyncEsp, ClockSyncStaticEsp, ONE_SECOND},
    flash_block::FlashBlockEsp,
    init_and_start, lcd_text,
    lcd_text::LcdText as _,
    wifi_auto::{
        WifiAuto as _, WifiAutoEsp, WifiAutoEvent,
        fields::{TimezoneField, TimezoneFieldStatic},
    },
};

esp_bootloader_esp_idf::esp_app_desc!();

button_watch! {
    ForcePortalButtonWatch {
        pin: GPIO0,
    }
}

lcd_text! {
    i2c: I2C0,
    sda_pin: GPIO4,
    scl_pin: GPIO5,
    LcdTextClock {
        width: 16,
        height: 2,
        address: 0x27
    }
}

#[esp_rtos::main]
async fn main(spawner: Spawner) -> ! {
    let err = inner_main(spawner).await.unwrap_err();
    panic!("{err:?}");
}

async fn inner_main(spawner: Spawner) -> Result<Infallible> {
    init_and_start!(p);
    esp_println::logger::init_logger(log::LevelFilter::Info);

    info!("Starting LCD clock with WiFi");

    let lcd_text_clock = LcdTextClock::new(p.I2C0, p.GPIO4, p.GPIO5, spawner)?;
    lcd_text_clock.write_text("Booting...\nLCD Clock");

    let [wifi_auto_flash_block, mut timezone_flash_block] = FlashBlockEsp::new_array::<2>(p.FLASH)?;

    static TIMEZONE_FIELD_STATIC: TimezoneFieldStatic = TimezoneField::new_static();
    let timezone_field = TimezoneField::new(&TIMEZONE_FIELD_STATIC, timezone_flash_block);
    let button_watch6 = ForcePortalButtonWatch::new(p.GPIO0, PressedTo::Ground, spawner).await?;

    let wifi_auto = WifiAutoEsp::new(
        p.WIFI,
        wifi_auto_flash_block,
        "DeviceEnvoyClock",
        [timezone_field],
        spawner,
    )?;

    let lcd_text_clock_ref = lcd_text_clock;
    let stack = wifi_auto
        .connect(&mut *button_watch6, |wifi_auto_event| {
            let lcd_text_clock_ref = lcd_text_clock_ref;
            async move {
                match wifi_auto_event {
                    WifiAutoEvent::CaptivePortalReady => {
                        lcd_text_clock_ref.write_text("Join WiFi:\nDeviceEnvoyClock");
                    }
                    WifiAutoEvent::Connecting { .. } => {
                        lcd_text_clock_ref.write_text("Connecting...\nPlease wait");
                    }
                    WifiAutoEvent::ConnectionFailed => {
                        lcd_text_clock_ref.write_text("WiFi failed\nRetry setup");
                    }
                }
                Ok(())
            }
        })
        .await?;

    let timezone_offset_minutes = timezone_field
        .offset_minutes()?
        .ok_or(Error::MissingCustomWifiAutoField)?;
    static CLOCK_SYNC_STATIC: ClockSyncStaticEsp = ClockSyncEsp::new_static();
    let clock_sync = ClockSyncEsp::new(
        &CLOCK_SYNC_STATIC,
        stack,
        timezone_offset_minutes,
        Some(ONE_SECOND),
        spawner,
    )?;

    info!("Entering main event loop");
    lcd_text_clock.write_text("WiFi connected\nWaiting NTP");

    let lcd_text_clock_ref = lcd_text_clock;
    run_clock_ui(
        &clock_sync,
        &mut *button_watch6,
        &mut timezone_flash_block,
        |clock_ui_event| async move {
            let text = event_text(clock_ui_event).map_err(|_| Error::FormatError)?;
            lcd_text_clock_ref.write_text(text.as_str());
            Ok(())
        },
    )
    .await
}

fn event_text(clock_ui_event: ClockUiEvent) -> Result<heapless::String<32>, fmt::Error> {
    let mut text = heapless::String::<32>::new();
    match clock_ui_event {
        ClockUiEvent::RenderHoursMinutes { hours, minutes } => {
            fmt::Write::write_fmt(
                &mut text,
                format_args!("{:>2}:{:02} HH:MM\nshort for MM:SS", hours, minutes),
            )?;
        }
        ClockUiEvent::RenderMinutesSeconds { minutes, seconds } => {
            fmt::Write::write_fmt(
                &mut text,
                format_args!("{:02}:{:02} MM:SS\nshort for FAST", minutes, seconds),
            )?;
        }
        ClockUiEvent::RenderHoursMinutesEdit { hours, minutes } => {
            fmt::Write::write_fmt(
                &mut text,
                format_args!("{:>2}:{:02} TZ EDIT\nshort +1h long OK", hours, minutes),
            )?;
        }
    }
    Ok(text)
}