Compare commits
10
Commits
aed54c7ab6
..
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b97bf144dc
|
||
|
|
27a280536e
|
||
|
|
4154bb8450
|
||
|
|
83b0b85fee
|
||
|
|
a4acfc0915
|
||
|
|
a45cb6efbd
|
||
|
|
cbcb5b0b5f
|
||
|
|
51a450dad4
|
||
|
|
15fad17fab
|
||
|
|
68412464ec
|
Generated
+246
-185
File diff suppressed because it is too large
Load Diff
+7
-2
@@ -34,7 +34,6 @@ esp-println = { version = "0.17.0", features = ["defmt-espflash", "esp32c6"] }
|
|||||||
embassy-sync = { version = "0.8.0", features = ["defmt"] }
|
embassy-sync = { version = "0.8.0", features = ["defmt"] }
|
||||||
embassy-futures = { version = "0.1.2", features = ["defmt"] }
|
embassy-futures = { version = "0.1.2", features = ["defmt"] }
|
||||||
embassy-embedded-hal = { version = "0.6.0", features = ["defmt", "time"] }
|
embassy-embedded-hal = { version = "0.6.0", features = ["defmt", "time"] }
|
||||||
embedded-rpc = "0.2.0"
|
|
||||||
|
|
||||||
critical-section = "1.2.0"
|
critical-section = "1.2.0"
|
||||||
static_cell = { version = "2.1.1", features = ["nightly"] }
|
static_cell = { version = "2.1.1", features = ["nightly"] }
|
||||||
@@ -64,9 +63,15 @@ picoserve = { version = "0.19", features = ["defmt", "embassy", "json"] }
|
|||||||
|
|
||||||
sequential-storage = "8.0"
|
sequential-storage = "8.0"
|
||||||
esp-storage = { version = "0.9", features = ["defmt", "esp32c6"] }
|
esp-storage = { version = "0.9", features = ["defmt", "esp32c6"] }
|
||||||
postcard = { version = "1.1", default-features = false }
|
postcard = { version = "1.1", default-features = false, features = [
|
||||||
|
"defmt",
|
||||||
|
"heapless",
|
||||||
|
] }
|
||||||
serde = { version = "1.0", default-features = false, features = ["derive"] }
|
serde = { version = "1.0", default-features = false, features = ["derive"] }
|
||||||
int-enum = "1.2.0"
|
int-enum = "1.2.0"
|
||||||
|
heapless = { version = "0.9.3", features = ["defmt", "serde"] }
|
||||||
|
thiserror = { version = "2.0.20", default-features = false }
|
||||||
|
oneshot = { version = "0.2.1", features = ["async"] }
|
||||||
|
|
||||||
|
|
||||||
# For fine tuning these settings, please refer to https://doc.rust-lang.org/cargo/reference/profiles.html
|
# For fine tuning these settings, please refer to https://doc.rust-lang.org/cargo/reference/profiles.html
|
||||||
|
|||||||
Generated
+22
-22
@@ -95,11 +95,11 @@
|
|||||||
},
|
},
|
||||||
"crane": {
|
"crane": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1777335812,
|
"lastModified": 1790899423,
|
||||||
"narHash": "sha256-bEg5xoAxAwsyfnGhkEX7RJViTIBIYPd8ISg4O1c0HFc=",
|
"narHash": "sha256-THGtz65UGJU+sonZidRboyCMk+9DclpMF7pwL4uDV4M=",
|
||||||
"owner": "ipetkov",
|
"owner": "ipetkov",
|
||||||
"repo": "crane",
|
"repo": "crane",
|
||||||
"rev": "5e0fb2f64edff2822249f21293b8304dedaaf676",
|
"rev": "47b6b27ed9a3a9181415e4367d0c30ab2a0e0250",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -113,11 +113,11 @@
|
|||||||
"nixpkgs-lib": "nixpkgs-lib"
|
"nixpkgs-lib": "nixpkgs-lib"
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1778716662,
|
"lastModified": 1790898470,
|
||||||
"narHash": "sha256-m1Yf0wZ8j1OHjTc2UwHwyQRSnNeSgLJOd7q5Y45hzi4=",
|
"narHash": "sha256-zTwuwezD0w3hpga6a6P8emidzAZFyWqlNeRBlpWOOl8=",
|
||||||
"owner": "hercules-ci",
|
"owner": "hercules-ci",
|
||||||
"repo": "flake-parts",
|
"repo": "flake-parts",
|
||||||
"rev": "f7c1a2d347e4c52d5fb8d10cb4d94b5884e546fb",
|
"rev": "024633cd702b10285db5cb19b40ad48d2399ba60",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -146,11 +146,11 @@
|
|||||||
},
|
},
|
||||||
"nixpkgs": {
|
"nixpkgs": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1780749050,
|
"lastModified": 1791260994,
|
||||||
"narHash": "sha256-3av0pIjlOWQ6rDbNOmpUSvbNnJkGORQKKjb4LtCZsIY=",
|
"narHash": "sha256-Miqqk/ammqnTUxaoCyvtwoPeLbI1ksFyLxi/CazZpWY=",
|
||||||
"owner": "nixos",
|
"owner": "nixos",
|
||||||
"repo": "nixpkgs",
|
"repo": "nixpkgs",
|
||||||
"rev": "a799d3e3886da994fa307f817a6bc705ae538eeb",
|
"rev": "151fa4e8ddfdd8dd25d945ad94ed54a13de9f6e4",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -162,11 +162,11 @@
|
|||||||
},
|
},
|
||||||
"nixpkgs-lib": {
|
"nixpkgs-lib": {
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1777168982,
|
"lastModified": 1790477367,
|
||||||
"narHash": "sha256-GOkGPcboWE9BmGCRMLX3worL4EMnsnG8MyKmXNeYuhQ=",
|
"narHash": "sha256-oujbxmVKDhci2E4EM3KyAbRUgp5/IsCoiA/LfEF7OOk=",
|
||||||
"owner": "nix-community",
|
"owner": "nix-community",
|
||||||
"repo": "nixpkgs.lib",
|
"repo": "nixpkgs.lib",
|
||||||
"rev": "f5901329dade4a6ea039af1433fb087bd9c1fe14",
|
"rev": "f7cd230690d9fc982d06129f9189b101fddcfa3b",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -238,11 +238,11 @@
|
|||||||
"treefmt-nix": "treefmt-nix"
|
"treefmt-nix": "treefmt-nix"
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1780887496,
|
"lastModified": 1791419199,
|
||||||
"narHash": "sha256-4mDOPU6Ey3SMsUsUeeNLkXC9uSdn0vpyzJIumw01HV8=",
|
"narHash": "sha256-eQx167Svp11qqWgwFrvV+tELtWZ+Wu2+zgKsAl8fx0M=",
|
||||||
"ref": "refs/heads/master",
|
"ref": "refs/heads/master",
|
||||||
"rev": "0d1a37eef3e3954cc698b577edbc37eaa736b859",
|
"rev": "00ab3b0148e915f22ef6815a9fe24de5d8dde295",
|
||||||
"revCount": 45,
|
"revCount": 51,
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://git.krantz.one/reed/project-templates"
|
"url": "https://git.krantz.one/reed/project-templates"
|
||||||
},
|
},
|
||||||
@@ -298,11 +298,11 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1780197589,
|
"lastModified": 1791276535,
|
||||||
"narHash": "sha256-FVCr2Ij/jKf59a4LW481eeOF6rJRreOBrVgW/aUBTrw=",
|
"narHash": "sha256-iwqAmHTX1IgzTumJR3JayNAQAo5xEmmOuGzB6b2pT/Q=",
|
||||||
"owner": "oxalica",
|
"owner": "oxalica",
|
||||||
"repo": "rust-overlay",
|
"repo": "rust-overlay",
|
||||||
"rev": "21632e942d89bf1cce4e5a63d7e58a215a0cbfcc",
|
"rev": "b962e5d0c8cd97196c6a882d659fe451b52ad989",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
@@ -334,11 +334,11 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"locked": {
|
"locked": {
|
||||||
"lastModified": 1775636079,
|
"lastModified": 1791203292,
|
||||||
"narHash": "sha256-pc20NRoMdiar8oPQceQT47UUZMBTiMdUuWrYu2obUP0=",
|
"narHash": "sha256-vuzVwvjeucSnwKwMBpyP8r5IzdrMKCHEdwTrRFwUN7I=",
|
||||||
"owner": "numtide",
|
"owner": "numtide",
|
||||||
"repo": "treefmt-nix",
|
"repo": "treefmt-nix",
|
||||||
"rev": "790751ff7fd3801feeaf96d7dc416a8d581265ba",
|
"rev": "03d8ee1bcbc8f9638907bb79edb9673151d0e22b",
|
||||||
"type": "github"
|
"type": "github"
|
||||||
},
|
},
|
||||||
"original": {
|
"original": {
|
||||||
|
|||||||
+3
-21
@@ -7,7 +7,7 @@
|
|||||||
)]
|
)]
|
||||||
#![deny(clippy::large_stack_frames)]
|
#![deny(clippy::large_stack_frames)]
|
||||||
|
|
||||||
use cover_theif::wifi::start_wifi;
|
use cover_theif::{clock::start_ntp_sync, http_api::start_http_api, wifi::start_wifi};
|
||||||
use defmt::info;
|
use defmt::info;
|
||||||
use embassy_executor::Spawner;
|
use embassy_executor::Spawner;
|
||||||
use embassy_time::{Duration, Timer};
|
use embassy_time::{Duration, Timer};
|
||||||
@@ -16,11 +16,6 @@ use esp_hal::clock::CpuClock;
|
|||||||
use esp_hal::timer::timg::TimerGroup;
|
use esp_hal::timer::timg::TimerGroup;
|
||||||
use esp_println as _;
|
use esp_println as _;
|
||||||
|
|
||||||
use cover_theif::{
|
|
||||||
clock,
|
|
||||||
http_api::{HttpApiProps, HttpApiService},
|
|
||||||
};
|
|
||||||
|
|
||||||
extern crate alloc;
|
extern crate alloc;
|
||||||
|
|
||||||
// This creates a default app-descriptor required by the esp-idf bootloader.
|
// This creates a default app-descriptor required by the esp-idf bootloader.
|
||||||
@@ -50,16 +45,8 @@ async fn main(spawner: Spawner) -> ! {
|
|||||||
|
|
||||||
let net_stack = start_wifi(spawner, peripherals.WIFI);
|
let net_stack = start_wifi(spawner, peripherals.WIFI);
|
||||||
|
|
||||||
spawner.spawn(clock::ntp_upkeep_service(net_stack).unwrap());
|
start_ntp_sync(spawner, net_stack);
|
||||||
|
start_http_api(spawner, net_stack);
|
||||||
spawner.spawn(
|
|
||||||
http_api_serve_task(HttpApiService::new(
|
|
||||||
net_stack,
|
|
||||||
Default::default(),
|
|
||||||
Default::default(),
|
|
||||||
))
|
|
||||||
.unwrap(),
|
|
||||||
);
|
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
info!("Hello world");
|
info!("Hello world");
|
||||||
@@ -68,8 +55,3 @@ async fn main(spawner: Spawner) -> ! {
|
|||||||
|
|
||||||
// for inspiration have a look at the examples at https://github.com/esp-rs/esp-hal/tree/esp-hal-v1.1.0/examples
|
// for inspiration have a look at the examples at https://github.com/esp-rs/esp-hal/tree/esp-hal-v1.1.0/examples
|
||||||
}
|
}
|
||||||
|
|
||||||
#[embassy_executor::task]
|
|
||||||
async fn http_api_serve_task(mut service: HttpApiService<'static, HttpApiProps>) {
|
|
||||||
service.run().await;
|
|
||||||
}
|
|
||||||
|
|||||||
+83
-35
@@ -1,5 +1,9 @@
|
|||||||
use core::net::SocketAddr;
|
use core::net::SocketAddr;
|
||||||
use embassy_net::udp::{PacketMetadata, UdpSocket};
|
use embassy_executor::Spawner;
|
||||||
|
use embassy_net::{
|
||||||
|
Stack,
|
||||||
|
udp::{PacketMetadata, UdpSocket},
|
||||||
|
};
|
||||||
use embassy_time::{Duration, Timer};
|
use embassy_time::{Duration, Timer};
|
||||||
use portable_atomic::{AtomicU64, Ordering};
|
use portable_atomic::{AtomicU64, Ordering};
|
||||||
use sntpc::{NtpContext, get_time};
|
use sntpc::{NtpContext, get_time};
|
||||||
@@ -9,43 +13,29 @@ use sntpc_time_embassy::EmbassyTimestampGenerator;
|
|||||||
// NTP server (pool.ntp.org is the usual choice)
|
// NTP server (pool.ntp.org is the usual choice)
|
||||||
const NTP_SERVER: &str = "pool.ntp.org";
|
const NTP_SERVER: &str = "pool.ntp.org";
|
||||||
const NTP_PORT: u16 = 123;
|
const NTP_PORT: u16 = 123;
|
||||||
|
// Unix epoch is 1900-01-01 + 70 years = 2_208_988_800 seconds.
|
||||||
|
const NTP_UNIX_OFFSET: u64 = 2_208_988_800;
|
||||||
|
|
||||||
static NTP_BOOT_OFFSET: AtomicU64 = AtomicU64::new(0);
|
static NTP_BOOT_OFFSET: AtomicU64 = AtomicU64::new(0);
|
||||||
|
|
||||||
pub async fn fetch_ntp_time(stack: embassy_net::Stack<'static>) -> Result<u64, &'static str> {
|
#[allow(
|
||||||
// Resolve the NTP server hostname
|
clippy::large_stack_frames,
|
||||||
let server_addr = stack
|
reason = "it's not unusual to allocate larger objects in service's start functions"
|
||||||
.dns_query(NTP_SERVER, embassy_net::dns::DnsQueryType::A)
|
)]
|
||||||
.await
|
pub fn start_ntp_sync(spawner: Spawner, net_stack: Stack<'static>) {
|
||||||
.map_err(|_| "DNS resolution failed")?
|
let service = crate::mk_static!(
|
||||||
.first()
|
NtpClient,
|
||||||
.copied()
|
NtpClient {
|
||||||
.ok_or("No DNS result")?;
|
net_stack,
|
||||||
|
|
||||||
let socket_addr = SocketAddr::new(server_addr.into(), NTP_PORT);
|
rx_meta: [PacketMetadata::EMPTY; 16],
|
||||||
|
rx_buf: [0u8; 48],
|
||||||
|
tx_meta: [PacketMetadata::EMPTY; 16],
|
||||||
|
tx_buf: [0u8; 48],
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
// Allocate UDP buffers (can be small — SNTP packets are tiny)
|
spawner.spawn(handler(service).unwrap());
|
||||||
let mut rx_meta = [PacketMetadata::EMPTY; 16];
|
|
||||||
let mut rx_buf = [0u8; 48];
|
|
||||||
let mut tx_meta = [PacketMetadata::EMPTY; 16];
|
|
||||||
let mut tx_buf = [0u8; 48];
|
|
||||||
|
|
||||||
let mut socket = UdpSocket::new(stack, &mut rx_meta, &mut rx_buf, &mut tx_meta, &mut tx_buf);
|
|
||||||
socket.bind(0).map_err(|_| "bind failed")?;
|
|
||||||
|
|
||||||
let wrapped = UdpSocketWrapper::from(socket);
|
|
||||||
let ctx = NtpContext::new(EmbassyTimestampGenerator::default());
|
|
||||||
|
|
||||||
let result = get_time(socket_addr, &wrapped, ctx)
|
|
||||||
.await
|
|
||||||
.map_err(|_| "SNTP request failed")?;
|
|
||||||
|
|
||||||
// result.sec is the NTP timestamp in seconds since 1900-01-01.
|
|
||||||
// Unix epoch is 1900-01-01 + 70 years = 2_208_988_800 seconds.
|
|
||||||
const NTP_UNIX_OFFSET: u64 = 2_208_988_800;
|
|
||||||
let unix_secs = result.sec().saturating_sub(NTP_UNIX_OFFSET);
|
|
||||||
|
|
||||||
Ok(unix_secs)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn now() -> embassy_time::Instant {
|
pub fn now() -> embassy_time::Instant {
|
||||||
@@ -53,9 +43,19 @@ pub fn now() -> embassy_time::Instant {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
pub async fn ntp_upkeep_service(stack: embassy_net::Stack<'static>) {
|
async fn handler(service: &'static mut NtpClient) {
|
||||||
|
let address = loop {
|
||||||
|
match service.fetch_ntp_address(NTP_SERVER, NTP_PORT).await {
|
||||||
|
Ok(addr) => break addr,
|
||||||
|
Err(err) => {
|
||||||
|
defmt::error!("Failed to get the NTP server's address: {}", err);
|
||||||
|
Timer::after(Duration::from_secs(10)).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
match fetch_ntp_time(stack).await {
|
match service.fetch_ntp_time(address).await {
|
||||||
Ok(unix_secs) => {
|
Ok(unix_secs) => {
|
||||||
NTP_BOOT_OFFSET.store(
|
NTP_BOOT_OFFSET.store(
|
||||||
unix_secs - embassy_time::Instant::now().as_secs(),
|
unix_secs - embassy_time::Instant::now().as_secs(),
|
||||||
@@ -70,3 +70,51 @@ pub async fn ntp_upkeep_service(stack: embassy_net::Stack<'static>) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct NtpClient {
|
||||||
|
net_stack: Stack<'static>,
|
||||||
|
|
||||||
|
rx_meta: [PacketMetadata; 16],
|
||||||
|
rx_buf: [u8; 48],
|
||||||
|
tx_meta: [PacketMetadata; 16],
|
||||||
|
tx_buf: [u8; 48],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NtpClient {
|
||||||
|
async fn fetch_ntp_address(&self, server: &str, port: u16) -> Result<SocketAddr, &'static str> {
|
||||||
|
// Resolve the NTP server hostname
|
||||||
|
let server_addr = self
|
||||||
|
.net_stack
|
||||||
|
.dns_query(server, embassy_net::dns::DnsQueryType::A)
|
||||||
|
.await
|
||||||
|
.map_err(|_| "DNS resolution failed")?
|
||||||
|
.first()
|
||||||
|
.copied()
|
||||||
|
.ok_or("No DNS result")?;
|
||||||
|
|
||||||
|
Ok(SocketAddr::new(server_addr.into(), port))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_ntp_time(&mut self, address: SocketAddr) -> Result<u64, &'static str> {
|
||||||
|
let mut socket = UdpSocket::new(
|
||||||
|
self.net_stack,
|
||||||
|
&mut self.rx_meta,
|
||||||
|
&mut self.rx_buf,
|
||||||
|
&mut self.tx_meta,
|
||||||
|
&mut self.tx_buf,
|
||||||
|
);
|
||||||
|
socket.bind(0).map_err(|_| "bind failed")?;
|
||||||
|
|
||||||
|
let wrapped = UdpSocketWrapper::from(socket);
|
||||||
|
let ctx = NtpContext::new(EmbassyTimestampGenerator::default());
|
||||||
|
|
||||||
|
let result = get_time(address, &wrapped, ctx)
|
||||||
|
.await
|
||||||
|
.map_err(|_| "SNTP request failed")?;
|
||||||
|
|
||||||
|
// result.sec is the NTP timestamp in seconds since 1900-01-01.
|
||||||
|
let unix_secs = result.sec().saturating_sub(NTP_UNIX_OFFSET);
|
||||||
|
|
||||||
|
Ok(unix_secs)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
+112
-34
@@ -1,25 +1,20 @@
|
|||||||
|
use defmt::error;
|
||||||
use embassy_embedded_hal::adapter::BlockingAsync;
|
use embassy_embedded_hal::adapter::BlockingAsync;
|
||||||
use embassy_executor::Spawner;
|
use embassy_executor::Spawner;
|
||||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, channel::Channel};
|
||||||
use embedded_rpc::RpcService;
|
|
||||||
use esp_hal::peripherals::FLASH;
|
use esp_hal::peripherals::FLASH;
|
||||||
|
use esp_radio::wifi::sta::StationConfig;
|
||||||
use esp_storage::FlashStorage;
|
use esp_storage::FlashStorage;
|
||||||
|
use heapless::String;
|
||||||
use int_enum::IntEnum;
|
use int_enum::IntEnum;
|
||||||
|
use oneshot::Sender;
|
||||||
|
use postcard::to_slice;
|
||||||
use sequential_storage::{
|
use sequential_storage::{
|
||||||
cache::{Cache, Uncached},
|
cache::{Cache, Uncached},
|
||||||
map::{Key, MapConfig, MapStorage, SerializationError},
|
map::{Key, MapConfig, MapStorage},
|
||||||
};
|
};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
pub enum ConfigCommand {
|
use thiserror::Error;
|
||||||
SetStationCreds(),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ConfigCommand {
|
|
||||||
pub async fn set_station_creds() {}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub static CONFIG_SERVICE: RpcService<CriticalSectionRawMutex, ConfigCommand, ()> =
|
|
||||||
RpcService::new();
|
|
||||||
|
|
||||||
pub async fn start_config(spawner: Spawner, flash: FLASH<'static>) {
|
pub async fn start_config(spawner: Spawner, flash: FLASH<'static>) {
|
||||||
let storage = MapStorage::<ConfigKey, _, _>::new(
|
let storage = MapStorage::<ConfigKey, _, _>::new(
|
||||||
@@ -28,26 +23,72 @@ pub async fn start_config(spawner: Spawner, flash: FLASH<'static>) {
|
|||||||
Cache::new_uncached(),
|
Cache::new_uncached(),
|
||||||
);
|
);
|
||||||
|
|
||||||
spawner.spawn(config_handler(storage).unwrap());
|
spawner.spawn(handler(storage).unwrap());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn set_wifi_creds(value: WifiCredentials) -> Result<(), ConfigError> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
CONFIG_CHANNEL
|
||||||
|
.send(ConfigOperationMessage::SetWifiCreds(value, send))
|
||||||
|
.await;
|
||||||
|
recv.await?
|
||||||
|
}
|
||||||
|
|
||||||
|
static CONFIG_CHANNEL: Channel<CriticalSectionRawMutex, ConfigOperationMessage, 5> = Channel::new();
|
||||||
|
|
||||||
|
enum ConfigOperationMessage {
|
||||||
|
SetWifiCreds(WifiCredentials, Sender<Result<(), ConfigError>>),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize, Serialize)]
|
||||||
|
pub struct WifiCredentials {
|
||||||
|
pub ssid: String<32>,
|
||||||
|
pub password: String<32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<WifiCredentials> for StationConfig {
|
||||||
|
fn from(value: WifiCredentials) -> Self {
|
||||||
|
Self::default()
|
||||||
|
.with_ssid(value.ssid.as_str())
|
||||||
|
.with_password(value.password.as_str().into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO: refactor this when try blocks are implemented
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
async fn config_handler(mut storage: MapStorage<ConfigKey, BlockingAsync<FlashStorage<'static>>, Cache<Uncached, Uncached, Uncached, ConfigKey>>) {
|
async fn handler(
|
||||||
|
mut storage: MapStorage<
|
||||||
|
ConfigKey,
|
||||||
|
BlockingAsync<FlashStorage<'static>>,
|
||||||
|
Cache<Uncached, Uncached, Uncached, ConfigKey>,
|
||||||
|
>,
|
||||||
|
) -> ! {
|
||||||
let mut data_buffer = [0u8; 256];
|
let mut data_buffer = [0u8; 256];
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
let (req, served) = CONFIG_SERVICE.serve().await;
|
let operation = CONFIG_CHANNEL.receive().await;
|
||||||
|
|
||||||
match req {
|
match operation {
|
||||||
ConfigCommand::SetStationCreds() => {
|
ConfigOperationMessage::SetWifiCreds(value, resp) => {
|
||||||
todo!()
|
let mut f = async || {
|
||||||
// if storage
|
let mut buf = [0u8; 256];
|
||||||
// .store_item(&mut data_buffer, &ConfigKey::Wifi, )
|
to_slice(&value, &mut buf)?;
|
||||||
// .await
|
|
||||||
// .is_ok()
|
storage
|
||||||
// {
|
.store_item(&mut data_buffer, &ConfigKey::Wifi, &buf)
|
||||||
// served.respond(());
|
.await?;
|
||||||
// }
|
|
||||||
|
// TODO: send the change to the wifi service
|
||||||
|
// WIFI_SERVICE
|
||||||
|
// .call(|s| s.set_station_config(esp_radio::wifi::Config::Station(value.into())))
|
||||||
|
// .await;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
};
|
||||||
|
if resp.send(f().await).is_err() {
|
||||||
|
// TODO: find a way to not hard-code symbols in a string
|
||||||
|
error!("ConfigOperationMessage::SetWifiCreds failed to respond")
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -60,18 +101,55 @@ enum ConfigKey {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Key for ConfigKey {
|
impl Key for ConfigKey {
|
||||||
fn get_len(_: &[u8]) -> Result<usize, SerializationError> {
|
fn get_len(_: &[u8]) -> Result<usize, sequential_storage::map::SerializationError> {
|
||||||
Ok(1)
|
Ok(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn serialize_into(&self, buffer: &mut [u8]) -> Result<usize, SerializationError> {
|
fn serialize_into(
|
||||||
let val = buffer.get_mut(0).ok_or(SerializationError::BufferTooSmall)?;
|
&self,
|
||||||
*val = self.clone().into();
|
buffer: &mut [u8],
|
||||||
|
) -> Result<usize, sequential_storage::map::SerializationError> {
|
||||||
|
let val = buffer
|
||||||
|
.get_mut(0)
|
||||||
|
.ok_or(sequential_storage::map::SerializationError::BufferTooSmall)?;
|
||||||
|
*val = (*self).into();
|
||||||
Ok(1)
|
Ok(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn deserialize_from(buffer: &[u8]) -> Result<(Self, usize), SerializationError> {
|
fn deserialize_from(
|
||||||
let val = *buffer.get(0).ok_or(SerializationError::BufferTooSmall)?;
|
buffer: &[u8],
|
||||||
Ok((val.try_into().map_err(|_| {SerializationError::InvalidData})?, 1))
|
) -> Result<(Self, usize), sequential_storage::map::SerializationError> {
|
||||||
|
let val = *buffer
|
||||||
|
.first()
|
||||||
|
.ok_or(sequential_storage::map::SerializationError::BufferTooSmall)?;
|
||||||
|
Ok((
|
||||||
|
val.try_into()
|
||||||
|
.map_err(|_| sequential_storage::map::SerializationError::InvalidData)?,
|
||||||
|
1,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Error, Debug)]
|
||||||
|
pub enum ConfigError {
|
||||||
|
#[error("Error serializing data: {0}")]
|
||||||
|
SerializationError(#[from] postcard::Error),
|
||||||
|
|
||||||
|
#[error("Error storing data on the flash: {0:?}")]
|
||||||
|
FlashError(sequential_storage::Error<esp_storage::FlashStorageError>),
|
||||||
|
|
||||||
|
#[error("Error receiving response: {0}")]
|
||||||
|
RecvError(oneshot::RecvError),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<sequential_storage::Error<esp_storage::FlashStorageError>> for ConfigError {
|
||||||
|
fn from(v: sequential_storage::Error<esp_storage::FlashStorageError>) -> Self {
|
||||||
|
Self::FlashError(v)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<oneshot::RecvError> for ConfigError {
|
||||||
|
fn from(v: oneshot::RecvError) -> Self {
|
||||||
|
Self::RecvError(v)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+30
-15
@@ -1,3 +1,4 @@
|
|||||||
|
use embassy_executor::Spawner;
|
||||||
use embassy_net::Stack;
|
use embassy_net::Stack;
|
||||||
use picoserve::routing::get;
|
use picoserve::routing::get;
|
||||||
use picoserve::{AppBuilder, AppRouter, Config};
|
use picoserve::{AppBuilder, AppRouter, Config};
|
||||||
@@ -13,6 +14,33 @@ impl AppBuilder for HttpApiProps {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[allow(
|
||||||
|
clippy::large_stack_frames,
|
||||||
|
reason = "it's not unusual to allocate larger objects in service's start functions"
|
||||||
|
)]
|
||||||
|
pub fn start_http_api(spawner: Spawner, net_stack: Stack<'static>) {
|
||||||
|
let service = crate::mk_static!(
|
||||||
|
HttpApiApp<'static, HttpApiProps>,
|
||||||
|
HttpApiApp {
|
||||||
|
config: Default::default(),
|
||||||
|
|
||||||
|
net_stack,
|
||||||
|
app: HttpApiProps.build_app(),
|
||||||
|
|
||||||
|
tcp_rx_buffer: [0; 1024],
|
||||||
|
tcp_tx_buffer: [0; 1024],
|
||||||
|
http_buffer: [0; 2048],
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
spawner.spawn(handler(service).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[embassy_executor::task]
|
||||||
|
async fn handler(service: &'static mut HttpApiApp<'static, HttpApiProps>) {
|
||||||
|
service.run().await;
|
||||||
|
}
|
||||||
|
|
||||||
pub struct HttpApiConfig {
|
pub struct HttpApiConfig {
|
||||||
pub port: u16,
|
pub port: u16,
|
||||||
pub web_serve_config: Config,
|
pub web_serve_config: Config,
|
||||||
@@ -27,7 +55,7 @@ impl Default for HttpApiConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct HttpApiService<'a, AB: AppBuilder> {
|
pub struct HttpApiApp<'a, AB: AppBuilder> {
|
||||||
config: HttpApiConfig,
|
config: HttpApiConfig,
|
||||||
|
|
||||||
net_stack: Stack<'a>,
|
net_stack: Stack<'a>,
|
||||||
@@ -38,20 +66,7 @@ pub struct HttpApiService<'a, AB: AppBuilder> {
|
|||||||
http_buffer: [u8; 2048],
|
http_buffer: [u8; 2048],
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, AB: AppBuilder> HttpApiService<'a, AB> {
|
impl<'a, AB: AppBuilder> HttpApiApp<'a, AB> {
|
||||||
pub fn new(net_stack: Stack<'a>, config: HttpApiConfig, app: AB) -> Self {
|
|
||||||
Self {
|
|
||||||
config: config,
|
|
||||||
|
|
||||||
net_stack: net_stack,
|
|
||||||
app: app.build_app(),
|
|
||||||
|
|
||||||
tcp_rx_buffer: [0; 1024],
|
|
||||||
tcp_tx_buffer: [0; 1024],
|
|
||||||
http_buffer: [0; 2048],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn run(&mut self) {
|
pub async fn run(&mut self) {
|
||||||
picoserve::Server::new(
|
picoserve::Server::new(
|
||||||
&self.app,
|
&self.app,
|
||||||
|
|||||||
@@ -7,6 +7,8 @@
|
|||||||
#![deny(clippy::large_stack_frames)]
|
#![deny(clippy::large_stack_frames)]
|
||||||
#![feature(impl_trait_in_assoc_type)]
|
#![feature(impl_trait_in_assoc_type)]
|
||||||
|
|
||||||
|
extern crate alloc;
|
||||||
|
|
||||||
pub mod http_api;
|
pub mod http_api;
|
||||||
|
|
||||||
pub mod clock;
|
pub mod clock;
|
||||||
|
|||||||
+59
-46
@@ -1,31 +1,21 @@
|
|||||||
|
use alloc::boxed::Box;
|
||||||
use defmt::{error, info};
|
use defmt::{error, info};
|
||||||
use embassy_executor::Spawner;
|
use embassy_executor::Spawner;
|
||||||
use embassy_futures::select::{Either, select};
|
use embassy_futures::select::{Either, select};
|
||||||
use embassy_net::{Runner, Stack};
|
use embassy_net::{Runner, Stack};
|
||||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||||
|
use embassy_sync::channel::Channel;
|
||||||
|
use embassy_sync::signal::Signal;
|
||||||
use embassy_time::{Duration, Timer};
|
use embassy_time::{Duration, Timer};
|
||||||
use embedded_rpc::{RequestDroppedError, RpcService};
|
|
||||||
use esp_hal::peripherals::WIFI;
|
use esp_hal::peripherals::WIFI;
|
||||||
use esp_radio::wifi::sta::StationConfig;
|
use esp_radio::wifi::sta::StationConfig;
|
||||||
use esp_radio::wifi::{ControllerConfig, Interface, WifiController};
|
use esp_radio::wifi::{ControllerConfig, Interface, WifiController};
|
||||||
|
use oneshot::{RecvError, Sender};
|
||||||
|
|
||||||
pub enum WifiCommand {
|
#[allow(
|
||||||
SetStationConfig(esp_radio::wifi::Config),
|
clippy::large_stack_frames,
|
||||||
SetDhcpConfig(embassy_net::DhcpConfig),
|
reason = "it's not unusual to allocate larger objects in service's start functions"
|
||||||
}
|
)]
|
||||||
|
|
||||||
impl WifiCommand {
|
|
||||||
pub async fn set_station_config(
|
|
||||||
config: esp_radio::wifi::Config,
|
|
||||||
) -> Result<(), RequestDroppedError> {
|
|
||||||
WIFI_SERVICE
|
|
||||||
.request(WifiCommand::SetStationConfig(config))
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub static WIFI_SERVICE: RpcService<CriticalSectionRawMutex, WifiCommand, ()> = RpcService::new();
|
|
||||||
|
|
||||||
pub fn start_wifi(spawner: Spawner, wifi: WIFI<'static>) -> Stack<'static> {
|
pub fn start_wifi(spawner: Spawner, wifi: WIFI<'static>) -> Stack<'static> {
|
||||||
let wifi_config = esp_radio::wifi::Config::Station(StationConfig::default());
|
let wifi_config = esp_radio::wifi::Config::Station(StationConfig::default());
|
||||||
|
|
||||||
@@ -52,40 +42,64 @@ pub fn start_wifi(spawner: Spawner, wifi: WIFI<'static>) -> Stack<'static> {
|
|||||||
seed,
|
seed,
|
||||||
);
|
);
|
||||||
|
|
||||||
spawner.spawn(net_task(net_runner).unwrap());
|
spawner.spawn(net_handler(net_runner).unwrap());
|
||||||
spawner.spawn(wifi_handler(wifi_controller).unwrap());
|
spawner.spawn(connection_handler(wifi_controller).unwrap());
|
||||||
spawner.spawn(ip_logger(net_stack).unwrap());
|
|
||||||
spawner.spawn(handler(net_stack).unwrap());
|
spawner.spawn(handler(net_stack).unwrap());
|
||||||
|
spawner.spawn(ip_logger(net_stack).unwrap());
|
||||||
|
|
||||||
net_stack
|
net_stack
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn set_station_config(config: Box<esp_radio::wifi::Config>) -> Result<(), RecvError> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
WIFI_CHANNEL
|
||||||
|
.send(WifiOperationMessage::SetStationConfig(config, send))
|
||||||
|
.await;
|
||||||
|
recv.await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_dhcp_config(config: Box<embassy_net::DhcpConfig>) -> Result<(), RecvError> {
|
||||||
|
let (send, recv) = oneshot::channel();
|
||||||
|
WIFI_CHANNEL
|
||||||
|
.send(WifiOperationMessage::SetDhcpConfig(config, send))
|
||||||
|
.await;
|
||||||
|
recv.await
|
||||||
|
}
|
||||||
|
|
||||||
|
static WIFI_CHANNEL: Channel<CriticalSectionRawMutex, WifiOperationMessage, 5> = Channel::new();
|
||||||
|
|
||||||
|
enum WifiOperationMessage {
|
||||||
|
SetStationConfig(Box<esp_radio::wifi::Config>, Sender<()>),
|
||||||
|
SetDhcpConfig(Box<embassy_net::DhcpConfig>, Sender<()>),
|
||||||
|
}
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
async fn handler(net_stack: Stack<'static>) {
|
async fn handler(net_stack: Stack<'static>) -> ! {
|
||||||
loop {
|
loop {
|
||||||
let (req, served) = WIFI_SERVICE.serve().await;
|
match WIFI_CHANNEL.receive().await {
|
||||||
|
WifiOperationMessage::SetStationConfig(config, resp) => {
|
||||||
match req {
|
WIFI_HANDLER_RPC.signal(*config);
|
||||||
WifiCommand::SetStationConfig(config) => {
|
if resp.send(()).is_err() {
|
||||||
if WIFI_HANDLER_RPC.request(config).await.is_err() {
|
// TODO: find a way to not hard-code symbols in a string
|
||||||
continue;
|
error!("WifiOperationMessage::SetStationConfig failed to respond")
|
||||||
|
};
|
||||||
|
}
|
||||||
|
WifiOperationMessage::SetDhcpConfig(config, resp) => {
|
||||||
|
net_stack.set_config_v4(embassy_net::ConfigV4::Dhcp(*config));
|
||||||
|
if resp.send(()).is_err() {
|
||||||
|
// TODO: find a way to not hard-code symbols in a string
|
||||||
|
error!("WifiOperationMessage::SetDhcpConfig failed to respond")
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
WifiCommand::SetDhcpConfig(dhcp_config) => {
|
|
||||||
net_stack.set_config_v4(embassy_net::ConfigV4::Dhcp(dhcp_config));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
served.respond(());
|
static WIFI_HANDLER_RPC: Signal<CriticalSectionRawMutex, esp_radio::wifi::Config> = Signal::new();
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static WIFI_HANDLER_RPC: RpcService<CriticalSectionRawMutex, esp_radio::wifi::Config, ()> =
|
|
||||||
RpcService::new();
|
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
async fn wifi_handler(mut controller: WifiController<'static>) {
|
async fn connection_handler(mut controller: WifiController<'static>) -> ! {
|
||||||
let connection = async |controller: &mut WifiController<'static>| {
|
async fn connection(controller: &mut WifiController<'static>) {
|
||||||
info!("Connecting to WiFi...");
|
info!("Connecting to WiFi...");
|
||||||
|
|
||||||
match controller.connect_async().await {
|
match controller.connect_async().await {
|
||||||
@@ -100,21 +114,20 @@ async fn wifi_handler(mut controller: WifiController<'static>) {
|
|||||||
error!("Failed to connect to wifi: {:?}", e);
|
error!("Failed to connect to wifi: {:?}", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
if let Either::First((req, served)) =
|
if let Either::First(req) =
|
||||||
select(WIFI_HANDLER_RPC.serve(), connection(&mut controller)).await
|
select(WIFI_HANDLER_RPC.wait(), connection(&mut controller)).await
|
||||||
|
&& let Some(err) = controller.set_config(&req).err()
|
||||||
{
|
{
|
||||||
if controller.set_config(&req).is_ok() {
|
error!("Wifi controller failed to set a new config: {:?}", err)
|
||||||
served.respond(());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
async fn ip_logger(net_stack: Stack<'static>) {
|
async fn ip_logger(net_stack: Stack<'static>) -> ! {
|
||||||
loop {
|
loop {
|
||||||
info!("Getting IP address...");
|
info!("Getting IP address...");
|
||||||
net_stack.wait_config_up().await;
|
net_stack.wait_config_up().await;
|
||||||
@@ -137,6 +150,6 @@ async fn ip_logger(net_stack: Stack<'static>) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[embassy_executor::task]
|
#[embassy_executor::task]
|
||||||
async fn net_task(mut runner: Runner<'static, Interface<'static>>) {
|
async fn net_handler(mut runner: Runner<'static, Interface<'static>>) -> ! {
|
||||||
runner.run().await
|
runner.run().await
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user