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-futures = { version = "0.1.2", features = ["defmt"] }
|
||||
embassy-embedded-hal = { version = "0.6.0", features = ["defmt", "time"] }
|
||||
embedded-rpc = "0.2.0"
|
||||
|
||||
critical-section = "1.2.0"
|
||||
static_cell = { version = "2.1.1", features = ["nightly"] }
|
||||
@@ -64,9 +63,15 @@ picoserve = { version = "0.19", features = ["defmt", "embassy", "json"] }
|
||||
|
||||
sequential-storage = "8.0"
|
||||
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"] }
|
||||
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
|
||||
|
||||
Generated
+22
-22
@@ -95,11 +95,11 @@
|
||||
},
|
||||
"crane": {
|
||||
"locked": {
|
||||
"lastModified": 1777335812,
|
||||
"narHash": "sha256-bEg5xoAxAwsyfnGhkEX7RJViTIBIYPd8ISg4O1c0HFc=",
|
||||
"lastModified": 1790899423,
|
||||
"narHash": "sha256-THGtz65UGJU+sonZidRboyCMk+9DclpMF7pwL4uDV4M=",
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"rev": "5e0fb2f64edff2822249f21293b8304dedaaf676",
|
||||
"rev": "47b6b27ed9a3a9181415e4367d0c30ab2a0e0250",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -113,11 +113,11 @@
|
||||
"nixpkgs-lib": "nixpkgs-lib"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1778716662,
|
||||
"narHash": "sha256-m1Yf0wZ8j1OHjTc2UwHwyQRSnNeSgLJOd7q5Y45hzi4=",
|
||||
"lastModified": 1790898470,
|
||||
"narHash": "sha256-zTwuwezD0w3hpga6a6P8emidzAZFyWqlNeRBlpWOOl8=",
|
||||
"owner": "hercules-ci",
|
||||
"repo": "flake-parts",
|
||||
"rev": "f7c1a2d347e4c52d5fb8d10cb4d94b5884e546fb",
|
||||
"rev": "024633cd702b10285db5cb19b40ad48d2399ba60",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -146,11 +146,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1780749050,
|
||||
"narHash": "sha256-3av0pIjlOWQ6rDbNOmpUSvbNnJkGORQKKjb4LtCZsIY=",
|
||||
"lastModified": 1791260994,
|
||||
"narHash": "sha256-Miqqk/ammqnTUxaoCyvtwoPeLbI1ksFyLxi/CazZpWY=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "a799d3e3886da994fa307f817a6bc705ae538eeb",
|
||||
"rev": "151fa4e8ddfdd8dd25d945ad94ed54a13de9f6e4",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -162,11 +162,11 @@
|
||||
},
|
||||
"nixpkgs-lib": {
|
||||
"locked": {
|
||||
"lastModified": 1777168982,
|
||||
"narHash": "sha256-GOkGPcboWE9BmGCRMLX3worL4EMnsnG8MyKmXNeYuhQ=",
|
||||
"lastModified": 1790477367,
|
||||
"narHash": "sha256-oujbxmVKDhci2E4EM3KyAbRUgp5/IsCoiA/LfEF7OOk=",
|
||||
"owner": "nix-community",
|
||||
"repo": "nixpkgs.lib",
|
||||
"rev": "f5901329dade4a6ea039af1433fb087bd9c1fe14",
|
||||
"rev": "f7cd230690d9fc982d06129f9189b101fddcfa3b",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -238,11 +238,11 @@
|
||||
"treefmt-nix": "treefmt-nix"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1780887496,
|
||||
"narHash": "sha256-4mDOPU6Ey3SMsUsUeeNLkXC9uSdn0vpyzJIumw01HV8=",
|
||||
"lastModified": 1791419199,
|
||||
"narHash": "sha256-eQx167Svp11qqWgwFrvV+tELtWZ+Wu2+zgKsAl8fx0M=",
|
||||
"ref": "refs/heads/master",
|
||||
"rev": "0d1a37eef3e3954cc698b577edbc37eaa736b859",
|
||||
"revCount": 45,
|
||||
"rev": "00ab3b0148e915f22ef6815a9fe24de5d8dde295",
|
||||
"revCount": 51,
|
||||
"type": "git",
|
||||
"url": "https://git.krantz.one/reed/project-templates"
|
||||
},
|
||||
@@ -298,11 +298,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1780197589,
|
||||
"narHash": "sha256-FVCr2Ij/jKf59a4LW481eeOF6rJRreOBrVgW/aUBTrw=",
|
||||
"lastModified": 1791276535,
|
||||
"narHash": "sha256-iwqAmHTX1IgzTumJR3JayNAQAo5xEmmOuGzB6b2pT/Q=",
|
||||
"owner": "oxalica",
|
||||
"repo": "rust-overlay",
|
||||
"rev": "21632e942d89bf1cce4e5a63d7e58a215a0cbfcc",
|
||||
"rev": "b962e5d0c8cd97196c6a882d659fe451b52ad989",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -334,11 +334,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1775636079,
|
||||
"narHash": "sha256-pc20NRoMdiar8oPQceQT47UUZMBTiMdUuWrYu2obUP0=",
|
||||
"lastModified": 1791203292,
|
||||
"narHash": "sha256-vuzVwvjeucSnwKwMBpyP8r5IzdrMKCHEdwTrRFwUN7I=",
|
||||
"owner": "numtide",
|
||||
"repo": "treefmt-nix",
|
||||
"rev": "790751ff7fd3801feeaf96d7dc416a8d581265ba",
|
||||
"rev": "03d8ee1bcbc8f9638907bb79edb9673151d0e22b",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
+3
-21
@@ -7,7 +7,7 @@
|
||||
)]
|
||||
#![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 embassy_executor::Spawner;
|
||||
use embassy_time::{Duration, Timer};
|
||||
@@ -16,11 +16,6 @@ use esp_hal::clock::CpuClock;
|
||||
use esp_hal::timer::timg::TimerGroup;
|
||||
use esp_println as _;
|
||||
|
||||
use cover_theif::{
|
||||
clock,
|
||||
http_api::{HttpApiProps, HttpApiService},
|
||||
};
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
// 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);
|
||||
|
||||
spawner.spawn(clock::ntp_upkeep_service(net_stack).unwrap());
|
||||
|
||||
spawner.spawn(
|
||||
http_api_serve_task(HttpApiService::new(
|
||||
net_stack,
|
||||
Default::default(),
|
||||
Default::default(),
|
||||
))
|
||||
.unwrap(),
|
||||
);
|
||||
start_ntp_sync(spawner, net_stack);
|
||||
start_http_api(spawner, net_stack);
|
||||
|
||||
loop {
|
||||
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
|
||||
}
|
||||
|
||||
#[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 embassy_net::udp::{PacketMetadata, UdpSocket};
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_net::{
|
||||
Stack,
|
||||
udp::{PacketMetadata, UdpSocket},
|
||||
};
|
||||
use embassy_time::{Duration, Timer};
|
||||
use portable_atomic::{AtomicU64, Ordering};
|
||||
use sntpc::{NtpContext, get_time};
|
||||
@@ -9,43 +13,29 @@ use sntpc_time_embassy::EmbassyTimestampGenerator;
|
||||
// NTP server (pool.ntp.org is the usual choice)
|
||||
const NTP_SERVER: &str = "pool.ntp.org";
|
||||
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);
|
||||
|
||||
pub async fn fetch_ntp_time(stack: embassy_net::Stack<'static>) -> Result<u64, &'static str> {
|
||||
// Resolve the NTP server hostname
|
||||
let server_addr = stack
|
||||
.dns_query(NTP_SERVER, embassy_net::dns::DnsQueryType::A)
|
||||
.await
|
||||
.map_err(|_| "DNS resolution failed")?
|
||||
.first()
|
||||
.copied()
|
||||
.ok_or("No DNS result")?;
|
||||
#[allow(
|
||||
clippy::large_stack_frames,
|
||||
reason = "it's not unusual to allocate larger objects in service's start functions"
|
||||
)]
|
||||
pub fn start_ntp_sync(spawner: Spawner, net_stack: Stack<'static>) {
|
||||
let service = crate::mk_static!(
|
||||
NtpClient,
|
||||
NtpClient {
|
||||
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)
|
||||
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)
|
||||
spawner.spawn(handler(service).unwrap());
|
||||
}
|
||||
|
||||
pub fn now() -> embassy_time::Instant {
|
||||
@@ -53,9 +43,19 @@ pub fn now() -> embassy_time::Instant {
|
||||
}
|
||||
|
||||
#[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 {
|
||||
match fetch_ntp_time(stack).await {
|
||||
match service.fetch_ntp_time(address).await {
|
||||
Ok(unix_secs) => {
|
||||
NTP_BOOT_OFFSET.store(
|
||||
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_executor::Spawner;
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embedded_rpc::RpcService;
|
||||
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, channel::Channel};
|
||||
use esp_hal::peripherals::FLASH;
|
||||
use esp_radio::wifi::sta::StationConfig;
|
||||
use esp_storage::FlashStorage;
|
||||
use heapless::String;
|
||||
use int_enum::IntEnum;
|
||||
use oneshot::Sender;
|
||||
use postcard::to_slice;
|
||||
use sequential_storage::{
|
||||
cache::{Cache, Uncached},
|
||||
map::{Key, MapConfig, MapStorage, SerializationError},
|
||||
map::{Key, MapConfig, MapStorage},
|
||||
};
|
||||
|
||||
pub enum ConfigCommand {
|
||||
SetStationCreds(),
|
||||
}
|
||||
|
||||
impl ConfigCommand {
|
||||
pub async fn set_station_creds() {}
|
||||
}
|
||||
|
||||
pub static CONFIG_SERVICE: RpcService<CriticalSectionRawMutex, ConfigCommand, ()> =
|
||||
RpcService::new();
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
pub async fn start_config(spawner: Spawner, flash: FLASH<'static>) {
|
||||
let storage = MapStorage::<ConfigKey, _, _>::new(
|
||||
@@ -28,26 +23,72 @@ pub async fn start_config(spawner: Spawner, flash: FLASH<'static>) {
|
||||
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]
|
||||
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];
|
||||
|
||||
loop {
|
||||
let (req, served) = CONFIG_SERVICE.serve().await;
|
||||
let operation = CONFIG_CHANNEL.receive().await;
|
||||
|
||||
match req {
|
||||
ConfigCommand::SetStationCreds() => {
|
||||
todo!()
|
||||
// if storage
|
||||
// .store_item(&mut data_buffer, &ConfigKey::Wifi, )
|
||||
// .await
|
||||
// .is_ok()
|
||||
// {
|
||||
// served.respond(());
|
||||
// }
|
||||
match operation {
|
||||
ConfigOperationMessage::SetWifiCreds(value, resp) => {
|
||||
let mut f = async || {
|
||||
let mut buf = [0u8; 256];
|
||||
to_slice(&value, &mut buf)?;
|
||||
|
||||
storage
|
||||
.store_item(&mut data_buffer, &ConfigKey::Wifi, &buf)
|
||||
.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 {
|
||||
fn get_len(_: &[u8]) -> Result<usize, SerializationError> {
|
||||
fn get_len(_: &[u8]) -> Result<usize, sequential_storage::map::SerializationError> {
|
||||
Ok(1)
|
||||
}
|
||||
|
||||
fn serialize_into(&self, buffer: &mut [u8]) -> Result<usize, SerializationError> {
|
||||
let val = buffer.get_mut(0).ok_or(SerializationError::BufferTooSmall)?;
|
||||
*val = self.clone().into();
|
||||
fn serialize_into(
|
||||
&self,
|
||||
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)
|
||||
}
|
||||
|
||||
fn deserialize_from(buffer: &[u8]) -> Result<(Self, usize), SerializationError> {
|
||||
let val = *buffer.get(0).ok_or(SerializationError::BufferTooSmall)?;
|
||||
Ok((val.try_into().map_err(|_| {SerializationError::InvalidData})?, 1))
|
||||
fn deserialize_from(
|
||||
buffer: &[u8],
|
||||
) -> 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 picoserve::routing::get;
|
||||
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 port: u16,
|
||||
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,
|
||||
|
||||
net_stack: Stack<'a>,
|
||||
@@ -38,20 +66,7 @@ pub struct HttpApiService<'a, AB: AppBuilder> {
|
||||
http_buffer: [u8; 2048],
|
||||
}
|
||||
|
||||
impl<'a, AB: AppBuilder> HttpApiService<'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],
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, AB: AppBuilder> HttpApiApp<'a, AB> {
|
||||
pub async fn run(&mut self) {
|
||||
picoserve::Server::new(
|
||||
&self.app,
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
#![deny(clippy::large_stack_frames)]
|
||||
#![feature(impl_trait_in_assoc_type)]
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
pub mod http_api;
|
||||
|
||||
pub mod clock;
|
||||
|
||||
+59
-46
@@ -1,31 +1,21 @@
|
||||
use alloc::boxed::Box;
|
||||
use defmt::{error, info};
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_futures::select::{Either, select};
|
||||
use embassy_net::{Runner, Stack};
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_sync::channel::Channel;
|
||||
use embassy_sync::signal::Signal;
|
||||
use embassy_time::{Duration, Timer};
|
||||
use embedded_rpc::{RequestDroppedError, RpcService};
|
||||
use esp_hal::peripherals::WIFI;
|
||||
use esp_radio::wifi::sta::StationConfig;
|
||||
use esp_radio::wifi::{ControllerConfig, Interface, WifiController};
|
||||
use oneshot::{RecvError, Sender};
|
||||
|
||||
pub enum WifiCommand {
|
||||
SetStationConfig(esp_radio::wifi::Config),
|
||||
SetDhcpConfig(embassy_net::DhcpConfig),
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
#[allow(
|
||||
clippy::large_stack_frames,
|
||||
reason = "it's not unusual to allocate larger objects in service's start functions"
|
||||
)]
|
||||
pub fn start_wifi(spawner: Spawner, wifi: WIFI<'static>) -> Stack<'static> {
|
||||
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,
|
||||
);
|
||||
|
||||
spawner.spawn(net_task(net_runner).unwrap());
|
||||
spawner.spawn(wifi_handler(wifi_controller).unwrap());
|
||||
spawner.spawn(ip_logger(net_stack).unwrap());
|
||||
spawner.spawn(net_handler(net_runner).unwrap());
|
||||
spawner.spawn(connection_handler(wifi_controller).unwrap());
|
||||
spawner.spawn(handler(net_stack).unwrap());
|
||||
spawner.spawn(ip_logger(net_stack).unwrap());
|
||||
|
||||
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]
|
||||
async fn handler(net_stack: Stack<'static>) {
|
||||
async fn handler(net_stack: Stack<'static>) -> ! {
|
||||
loop {
|
||||
let (req, served) = WIFI_SERVICE.serve().await;
|
||||
|
||||
match req {
|
||||
WifiCommand::SetStationConfig(config) => {
|
||||
if WIFI_HANDLER_RPC.request(config).await.is_err() {
|
||||
continue;
|
||||
match WIFI_CHANNEL.receive().await {
|
||||
WifiOperationMessage::SetStationConfig(config, resp) => {
|
||||
WIFI_HANDLER_RPC.signal(*config);
|
||||
if resp.send(()).is_err() {
|
||||
// TODO: find a way to not hard-code symbols in a string
|
||||
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: RpcService<CriticalSectionRawMutex, esp_radio::wifi::Config, ()> =
|
||||
RpcService::new();
|
||||
static WIFI_HANDLER_RPC: Signal<CriticalSectionRawMutex, esp_radio::wifi::Config> = Signal::new();
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn wifi_handler(mut controller: WifiController<'static>) {
|
||||
let connection = async |controller: &mut WifiController<'static>| {
|
||||
async fn connection_handler(mut controller: WifiController<'static>) -> ! {
|
||||
async fn connection(controller: &mut WifiController<'static>) {
|
||||
info!("Connecting to WiFi...");
|
||||
|
||||
match controller.connect_async().await {
|
||||
@@ -100,21 +114,20 @@ async fn wifi_handler(mut controller: WifiController<'static>) {
|
||||
error!("Failed to connect to wifi: {:?}", e);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
loop {
|
||||
if let Either::First((req, served)) =
|
||||
select(WIFI_HANDLER_RPC.serve(), connection(&mut controller)).await
|
||||
if let Either::First(req) =
|
||||
select(WIFI_HANDLER_RPC.wait(), connection(&mut controller)).await
|
||||
&& let Some(err) = controller.set_config(&req).err()
|
||||
{
|
||||
if controller.set_config(&req).is_ok() {
|
||||
served.respond(());
|
||||
}
|
||||
error!("Wifi controller failed to set a new config: {:?}", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn ip_logger(net_stack: Stack<'static>) {
|
||||
async fn ip_logger(net_stack: Stack<'static>) -> ! {
|
||||
loop {
|
||||
info!("Getting IP address...");
|
||||
net_stack.wait_config_up().await;
|
||||
@@ -137,6 +150,6 @@ async fn ip_logger(net_stack: Stack<'static>) {
|
||||
}
|
||||
|
||||
#[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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user