Compare commits
4
Commits
master
..
b84d4f3b31
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b84d4f3b31
|
||
|
|
f92bd04c73
|
||
|
|
4435691a73
|
||
|
|
9b80ca757c
|
@@ -1,8 +1,5 @@
|
||||
name: "Flake.lock: update Nix dependencies for development environment only"
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
on:
|
||||
workflow_dispatch: # allows manual triggering
|
||||
schedule:
|
||||
|
||||
Generated
+242
-401
File diff suppressed because it is too large
Load Diff
+4
-25
@@ -18,7 +18,7 @@ esp-rtos = { version = "0.3.0", features = [
|
||||
"esp32c6",
|
||||
] }
|
||||
|
||||
defmt = "1.1.1"
|
||||
defmt = "1.1.0"
|
||||
esp-bootloader-esp-idf = { version = "0.5.0", features = ["defmt", "esp32c6"] }
|
||||
|
||||
embassy-executor = { version = "0.10.0", features = ["defmt"] }
|
||||
@@ -31,14 +31,10 @@ esp-backtrace = { version = "0.19.0", features = [
|
||||
] }
|
||||
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"] }
|
||||
|
||||
critical-section = "1.2.0"
|
||||
static_cell = { version = "2.1.1", features = ["nightly"] }
|
||||
static_cell = "2.1.1"
|
||||
|
||||
embassy-net = { version = "0.9.1", features = [
|
||||
embassy-net = { version = "0.9.0", features = [
|
||||
"defmt",
|
||||
"dhcpv4-hostname",
|
||||
"medium-ethernet",
|
||||
@@ -54,24 +50,7 @@ esp-radio = { version = "0.18.0", features = [
|
||||
"wifi",
|
||||
] }
|
||||
|
||||
sntpc = { version = "0.11", default-features = false }
|
||||
sntpc-net-embassy = { version = "0.11", default-features = false }
|
||||
sntpc-time-embassy = { version = "0.6" }
|
||||
portable-atomic = "1.15.0"
|
||||
|
||||
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, 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"] }
|
||||
picoserve = { version = "0.18", features = ["defmt", "embassy", "json"] }
|
||||
|
||||
|
||||
# For fine tuning these settings, please refer to https://doc.rust-lang.org/cargo/reference/profiles.html
|
||||
|
||||
+7
-7
@@ -20,9 +20,8 @@ def build_drive_shaft_mount():
|
||||
screw_head_depth = 5
|
||||
screw_body_diameter = 5
|
||||
|
||||
track_width = 6.1
|
||||
track_height = 1.4
|
||||
track_angle = 30
|
||||
track_width = 6.2
|
||||
track_height = 1.7
|
||||
|
||||
assert (bearing_offset - bearing_diameter / 2) > 0
|
||||
assert (core_width - bearing_diameter) > 0
|
||||
@@ -85,8 +84,9 @@ def build_drive_shaft_mount():
|
||||
extrude(amount=-((thickness / 2) + (bearing_height / 2)), mode=Mode.SUBTRACT)
|
||||
|
||||
with BuildPart() as track:
|
||||
Box(core_width + (screw_blocks_width * 2), track_width + ((sin(radians(track_angle))/sin(radians(90-track_angle))) * track_height * 2) - 0.012, track_height, (90, 0, 0), (Align.CENTER, Align.CENTER, Align.MIN))
|
||||
chamfer(track.edges().filter_by(Axis.X).sort_by(Axis.Y)[:2], track_height - 0.01, angle=track_angle)
|
||||
angle = 30
|
||||
Box(core_width + (screw_blocks_width * 2), track_width + ((sin(radians(angle))/sin(radians(90-angle))) * track_height * 2), track_height, (90, 0, 0), (Align.CENTER, Align.CENTER, Align.MIN))
|
||||
chamfer(track.edges().filter_by(Axis.X).sort_by(Axis.Y)[:2], track_height - 0.01, angle=angle)
|
||||
|
||||
with Locations(drive_shaft_mount.faces().filter_by(Plane.XZ).sort_by(Axis.Y)[-2:]):
|
||||
CounterBoreHole(screw_body_diameter / 2, screw_head_diameter / 2, screw_head_depth)
|
||||
@@ -94,7 +94,7 @@ def build_drive_shaft_mount():
|
||||
return drive_shaft_mount
|
||||
|
||||
def build_drive_shaft_bar_adapter():
|
||||
ext_size = 20.2
|
||||
ext_size = 20.3
|
||||
ext_track_width = 6.2
|
||||
ext_track_height = 1.8
|
||||
|
||||
@@ -120,7 +120,7 @@ def build_drive_shaft_bar_adapter():
|
||||
with BuildPart() as drive_shaft_bar_adapter:
|
||||
Cylinder((ext_size / 2) + thickness, height, align=(Align.CENTER, Align.CENTER, Align.MIN))
|
||||
|
||||
# cut out space for the extrusion
|
||||
# hollow the box
|
||||
with BuildSketch(Plane((0, 0, thickness))):
|
||||
Rectangle(ext_size, ext_size)
|
||||
with PolarLocations(ext_size / 2, 4):
|
||||
|
||||
Generated
+22
-22
@@ -95,11 +95,11 @@
|
||||
},
|
||||
"crane": {
|
||||
"locked": {
|
||||
"lastModified": 1790899423,
|
||||
"narHash": "sha256-THGtz65UGJU+sonZidRboyCMk+9DclpMF7pwL4uDV4M=",
|
||||
"lastModified": 1777335812,
|
||||
"narHash": "sha256-bEg5xoAxAwsyfnGhkEX7RJViTIBIYPd8ISg4O1c0HFc=",
|
||||
"owner": "ipetkov",
|
||||
"repo": "crane",
|
||||
"rev": "47b6b27ed9a3a9181415e4367d0c30ab2a0e0250",
|
||||
"rev": "5e0fb2f64edff2822249f21293b8304dedaaf676",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -113,11 +113,11 @@
|
||||
"nixpkgs-lib": "nixpkgs-lib"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1790898470,
|
||||
"narHash": "sha256-zTwuwezD0w3hpga6a6P8emidzAZFyWqlNeRBlpWOOl8=",
|
||||
"lastModified": 1778716662,
|
||||
"narHash": "sha256-m1Yf0wZ8j1OHjTc2UwHwyQRSnNeSgLJOd7q5Y45hzi4=",
|
||||
"owner": "hercules-ci",
|
||||
"repo": "flake-parts",
|
||||
"rev": "024633cd702b10285db5cb19b40ad48d2399ba60",
|
||||
"rev": "f7c1a2d347e4c52d5fb8d10cb4d94b5884e546fb",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -146,11 +146,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1791260994,
|
||||
"narHash": "sha256-Miqqk/ammqnTUxaoCyvtwoPeLbI1ksFyLxi/CazZpWY=",
|
||||
"lastModified": 1780749050,
|
||||
"narHash": "sha256-3av0pIjlOWQ6rDbNOmpUSvbNnJkGORQKKjb4LtCZsIY=",
|
||||
"owner": "nixos",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "151fa4e8ddfdd8dd25d945ad94ed54a13de9f6e4",
|
||||
"rev": "a799d3e3886da994fa307f817a6bc705ae538eeb",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -162,11 +162,11 @@
|
||||
},
|
||||
"nixpkgs-lib": {
|
||||
"locked": {
|
||||
"lastModified": 1790477367,
|
||||
"narHash": "sha256-oujbxmVKDhci2E4EM3KyAbRUgp5/IsCoiA/LfEF7OOk=",
|
||||
"lastModified": 1777168982,
|
||||
"narHash": "sha256-GOkGPcboWE9BmGCRMLX3worL4EMnsnG8MyKmXNeYuhQ=",
|
||||
"owner": "nix-community",
|
||||
"repo": "nixpkgs.lib",
|
||||
"rev": "f7cd230690d9fc982d06129f9189b101fddcfa3b",
|
||||
"rev": "f5901329dade4a6ea039af1433fb087bd9c1fe14",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -238,11 +238,11 @@
|
||||
"treefmt-nix": "treefmt-nix"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1791419199,
|
||||
"narHash": "sha256-eQx167Svp11qqWgwFrvV+tELtWZ+Wu2+zgKsAl8fx0M=",
|
||||
"lastModified": 1780887496,
|
||||
"narHash": "sha256-4mDOPU6Ey3SMsUsUeeNLkXC9uSdn0vpyzJIumw01HV8=",
|
||||
"ref": "refs/heads/master",
|
||||
"rev": "00ab3b0148e915f22ef6815a9fe24de5d8dde295",
|
||||
"revCount": 51,
|
||||
"rev": "0d1a37eef3e3954cc698b577edbc37eaa736b859",
|
||||
"revCount": 45,
|
||||
"type": "git",
|
||||
"url": "https://git.krantz.one/reed/project-templates"
|
||||
},
|
||||
@@ -298,11 +298,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1791276535,
|
||||
"narHash": "sha256-iwqAmHTX1IgzTumJR3JayNAQAo5xEmmOuGzB6b2pT/Q=",
|
||||
"lastModified": 1780197589,
|
||||
"narHash": "sha256-FVCr2Ij/jKf59a4LW481eeOF6rJRreOBrVgW/aUBTrw=",
|
||||
"owner": "oxalica",
|
||||
"repo": "rust-overlay",
|
||||
"rev": "b962e5d0c8cd97196c6a882d659fe451b52ad989",
|
||||
"rev": "21632e942d89bf1cce4e5a63d7e58a215a0cbfcc",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -334,11 +334,11 @@
|
||||
]
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1791203292,
|
||||
"narHash": "sha256-vuzVwvjeucSnwKwMBpyP8r5IzdrMKCHEdwTrRFwUN7I=",
|
||||
"lastModified": 1775636079,
|
||||
"narHash": "sha256-pc20NRoMdiar8oPQceQT47UUZMBTiMdUuWrYu2obUP0=",
|
||||
"owner": "numtide",
|
||||
"repo": "treefmt-nix",
|
||||
"rev": "03d8ee1bcbc8f9638907bb79edb9673151d0e22b",
|
||||
"rev": "790751ff7fd3801feeaf96d7dc416a8d581265ba",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
+107
-5
@@ -6,15 +6,20 @@
|
||||
holding buffers for the duration of a data transfer."
|
||||
)]
|
||||
#![deny(clippy::large_stack_frames)]
|
||||
#![feature(impl_trait_in_assoc_type)]
|
||||
|
||||
use cover_theif::{clock::start_ntp_sync, http_api::start_http_api, wifi::start_wifi};
|
||||
use defmt::info;
|
||||
use defmt::{error, info};
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_net::Runner;
|
||||
use embassy_time::{Duration, Timer};
|
||||
use esp_backtrace as _;
|
||||
use esp_hal::clock::CpuClock;
|
||||
use esp_hal::timer::timg::TimerGroup;
|
||||
use esp_println as _;
|
||||
use esp_radio::wifi::sta::StationConfig;
|
||||
use esp_radio::wifi::{ControllerConfig, Interface, WifiController};
|
||||
use picoserve::routing::get;
|
||||
use picoserve::{AppBuilder, AppRouter};
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
@@ -22,6 +27,29 @@ extern crate alloc;
|
||||
// For more information see: <https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/app_image_format.html#application-description>
|
||||
esp_bootloader_esp_idf::esp_app_desc!();
|
||||
|
||||
// When you are okay with using a nightly compiler it's better to use https://docs.rs/static_cell/2.1.0/static_cell/macro.make_static.html
|
||||
macro_rules! mk_static {
|
||||
($t:ty,$val:expr) => {{
|
||||
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
|
||||
#[deny(unused_attributes)]
|
||||
let x = STATIC_CELL.uninit().write($val);
|
||||
x
|
||||
}};
|
||||
}
|
||||
|
||||
const SSID: &str = env!("SSID");
|
||||
const PASSWORD: &str = env!("PASSWORD");
|
||||
|
||||
struct AppProps;
|
||||
|
||||
impl AppBuilder for AppProps {
|
||||
type PathRouter = impl picoserve::routing::PathRouter;
|
||||
|
||||
fn build_app(self) -> picoserve::Router<Self::PathRouter> {
|
||||
picoserve::Router::new().route("/", get(|| async move { "Hello World" }))
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(
|
||||
clippy::large_stack_frames,
|
||||
reason = "it's not unusual to allocate larger buffers etc. in main"
|
||||
@@ -43,10 +71,55 @@ async fn main(spawner: Spawner) -> ! {
|
||||
|
||||
info!("Embassy initialized!");
|
||||
|
||||
let net_stack = start_wifi(spawner, peripherals.WIFI);
|
||||
let wifi_config = esp_radio::wifi::Config::Station(
|
||||
StationConfig::default()
|
||||
.with_ssid(SSID)
|
||||
.with_password(PASSWORD.into()),
|
||||
);
|
||||
|
||||
start_ntp_sync(spawner, net_stack);
|
||||
start_http_api(spawner, net_stack);
|
||||
let (wifi_controller, wifi_interfaces) = esp_radio::wifi::new(
|
||||
peripherals.WIFI,
|
||||
ControllerConfig::default().with_initial_config(wifi_config),
|
||||
)
|
||||
.expect("Failed to initialize Wi-Fi controller");
|
||||
|
||||
let mut dhcp_config = embassy_net::DhcpConfig::default();
|
||||
dhcp_config.hostname = Some("cover-theif".try_into().unwrap());
|
||||
let net_config = embassy_net::Config::dhcpv4(dhcp_config);
|
||||
|
||||
let rng = esp_hal::rng::Rng::new();
|
||||
let seed = (rng.random() as u64) << 32 | rng.random() as u64;
|
||||
|
||||
let (net_stack, net_runner) = embassy_net::new(
|
||||
wifi_interfaces.station,
|
||||
net_config,
|
||||
mk_static!(
|
||||
embassy_net::StackResources<3>,
|
||||
embassy_net::StackResources::<3>::new()
|
||||
),
|
||||
seed,
|
||||
);
|
||||
|
||||
spawner.spawn(connection(wifi_controller).unwrap());
|
||||
spawner.spawn(net_task(net_runner).unwrap());
|
||||
|
||||
net_stack.wait_config_up().await;
|
||||
|
||||
if let Some(config) = net_stack.config_v4() {
|
||||
info!("Got IP: {}", config.address);
|
||||
}
|
||||
|
||||
let app = mk_static!(AppRouter<AppProps>, AppProps.build_app());
|
||||
|
||||
let port = 80;
|
||||
let mut tcp_rx_buffer = [0; 1024];
|
||||
let mut tcp_tx_buffer = [0; 1024];
|
||||
let mut http_buffer = [0; 2048];
|
||||
let web_serve_config = picoserve::Config::const_default().keep_connection_alive();
|
||||
|
||||
picoserve::Server::new(app, &web_serve_config, &mut http_buffer)
|
||||
.listen_and_serve(0, net_stack, port, &mut tcp_rx_buffer, &mut tcp_tx_buffer)
|
||||
.await;
|
||||
|
||||
loop {
|
||||
info!("Hello world");
|
||||
@@ -55,3 +128,32 @@ 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 connection(mut controller: WifiController<'static>) {
|
||||
info!("start connection task");
|
||||
|
||||
loop {
|
||||
info!("About to connect...");
|
||||
|
||||
match controller.connect_async().await {
|
||||
Ok(info) => {
|
||||
info!("Wifi connected to {:?}", info);
|
||||
|
||||
// wait until we're no longer connected
|
||||
let info = controller.wait_for_disconnect_async().await.ok();
|
||||
info!("Disconnected: {:?}", info);
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to connect to wifi: {:?}", e);
|
||||
}
|
||||
}
|
||||
|
||||
Timer::after(Duration::from_millis(5000)).await
|
||||
}
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn net_task(mut runner: Runner<'static, Interface<'static>>) {
|
||||
runner.run().await
|
||||
}
|
||||
|
||||
-120
@@ -1,120 +0,0 @@
|
||||
use core::net::SocketAddr;
|
||||
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};
|
||||
use sntpc_net_embassy::UdpSocketWrapper;
|
||||
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);
|
||||
|
||||
#[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,
|
||||
|
||||
rx_meta: [PacketMetadata::EMPTY; 16],
|
||||
rx_buf: [0u8; 48],
|
||||
tx_meta: [PacketMetadata::EMPTY; 16],
|
||||
tx_buf: [0u8; 48],
|
||||
}
|
||||
);
|
||||
|
||||
spawner.spawn(handler(service).unwrap());
|
||||
}
|
||||
|
||||
pub fn now() -> embassy_time::Instant {
|
||||
embassy_time::Instant::now() + Duration::from_secs(NTP_BOOT_OFFSET.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
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 service.fetch_ntp_time(address).await {
|
||||
Ok(unix_secs) => {
|
||||
NTP_BOOT_OFFSET.store(
|
||||
unix_secs - embassy_time::Instant::now().as_secs(),
|
||||
portable_atomic::Ordering::Relaxed,
|
||||
);
|
||||
Timer::after(Duration::from_secs(6 * 60 * 60)).await
|
||||
}
|
||||
Err(err) => {
|
||||
defmt::error!("Failed to sync the clock from NTP: {}", err);
|
||||
Timer::after(Duration::from_secs(10)).await
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
-155
@@ -1,155 +0,0 @@
|
||||
use defmt::error;
|
||||
use embassy_embedded_hal::adapter::BlockingAsync;
|
||||
use embassy_executor::Spawner;
|
||||
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},
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
pub async fn start_config(spawner: Spawner, flash: FLASH<'static>) {
|
||||
let storage = MapStorage::<ConfigKey, _, _>::new(
|
||||
BlockingAsync::new(FlashStorage::new(flash)),
|
||||
const { MapConfig::new(0x3F_0000..0x40_0000) },
|
||||
Cache::new_uncached(),
|
||||
);
|
||||
|
||||
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 handler(
|
||||
mut storage: MapStorage<
|
||||
ConfigKey,
|
||||
BlockingAsync<FlashStorage<'static>>,
|
||||
Cache<Uncached, Uncached, Uncached, ConfigKey>,
|
||||
>,
|
||||
) -> ! {
|
||||
let mut data_buffer = [0u8; 256];
|
||||
|
||||
loop {
|
||||
let operation = CONFIG_CHANNEL.receive().await;
|
||||
|
||||
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")
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, IntEnum)]
|
||||
#[repr(u8)]
|
||||
enum ConfigKey {
|
||||
Wifi,
|
||||
}
|
||||
|
||||
impl Key for ConfigKey {
|
||||
fn get_len(_: &[u8]) -> Result<usize, sequential_storage::map::SerializationError> {
|
||||
Ok(1)
|
||||
}
|
||||
|
||||
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), 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)
|
||||
}
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_net::Stack;
|
||||
use picoserve::routing::get;
|
||||
use picoserve::{AppBuilder, AppRouter, Config};
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct HttpApiProps;
|
||||
|
||||
impl AppBuilder for HttpApiProps {
|
||||
type PathRouter = impl picoserve::routing::PathRouter;
|
||||
|
||||
fn build_app(self) -> picoserve::Router<Self::PathRouter> {
|
||||
picoserve::Router::new().route("/", get(|| async move { "Hello World" }))
|
||||
}
|
||||
}
|
||||
|
||||
#[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,
|
||||
}
|
||||
|
||||
impl Default for HttpApiConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
port: 80,
|
||||
web_serve_config: Config::const_default().keep_connection_alive(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct HttpApiApp<'a, AB: AppBuilder> {
|
||||
config: HttpApiConfig,
|
||||
|
||||
net_stack: Stack<'a>,
|
||||
app: AppRouter<AB>,
|
||||
|
||||
tcp_rx_buffer: [u8; 1024],
|
||||
tcp_tx_buffer: [u8; 1024],
|
||||
http_buffer: [u8; 2048],
|
||||
}
|
||||
|
||||
impl<'a, AB: AppBuilder> HttpApiApp<'a, AB> {
|
||||
pub async fn run(&mut self) {
|
||||
picoserve::Server::new(
|
||||
&self.app,
|
||||
&self.config.web_serve_config,
|
||||
&mut self.http_buffer,
|
||||
)
|
||||
.listen_and_serve(
|
||||
0,
|
||||
self.net_stack,
|
||||
self.config.port,
|
||||
&mut self.tcp_rx_buffer,
|
||||
&mut self.tcp_tx_buffer,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
-28
@@ -1,29 +1 @@
|
||||
#![no_std]
|
||||
#![deny(
|
||||
clippy::mem_forget,
|
||||
reason = "mem::forget is generally not safe to do with esp_hal types, especially those \
|
||||
holding buffers for the duration of a data transfer."
|
||||
)]
|
||||
#![deny(clippy::large_stack_frames)]
|
||||
#![feature(impl_trait_in_assoc_type)]
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
pub mod http_api;
|
||||
|
||||
pub mod clock;
|
||||
|
||||
pub mod wifi;
|
||||
|
||||
pub mod config;
|
||||
|
||||
// When you are okay with using a nightly compiler it's better to use https://docs.rs/static_cell/2.1.0/static_cell/macro.make_static.html
|
||||
#[macro_export]
|
||||
macro_rules! mk_static {
|
||||
($t:ty,$val:expr) => {{
|
||||
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
|
||||
#[deny(unused_attributes)]
|
||||
let x = STATIC_CELL.uninit().write($val);
|
||||
x
|
||||
}};
|
||||
}
|
||||
|
||||
-155
@@ -1,155 +0,0 @@
|
||||
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 esp_hal::peripherals::WIFI;
|
||||
use esp_radio::wifi::sta::StationConfig;
|
||||
use esp_radio::wifi::{ControllerConfig, Interface, WifiController};
|
||||
use oneshot::{RecvError, Sender};
|
||||
|
||||
#[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());
|
||||
|
||||
let (wifi_controller, wifi_interfaces) = esp_radio::wifi::new(
|
||||
wifi,
|
||||
ControllerConfig::default().with_initial_config(wifi_config),
|
||||
)
|
||||
.expect("Failed to initialize Wi-Fi controller");
|
||||
|
||||
let mut dhcp_config = embassy_net::DhcpConfig::default();
|
||||
dhcp_config.hostname = Some("cover-theif".try_into().unwrap());
|
||||
let net_config = embassy_net::Config::dhcpv4(dhcp_config);
|
||||
|
||||
let rng = esp_hal::rng::Rng::new();
|
||||
let seed = (rng.random() as u64) << 32 | rng.random() as u64;
|
||||
|
||||
let (net_stack, net_runner) = embassy_net::new(
|
||||
wifi_interfaces.station,
|
||||
net_config,
|
||||
crate::mk_static!(
|
||||
embassy_net::StackResources<3>,
|
||||
embassy_net::StackResources::<3>::new()
|
||||
),
|
||||
seed,
|
||||
);
|
||||
|
||||
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>) -> ! {
|
||||
loop {
|
||||
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")
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static WIFI_HANDLER_RPC: Signal<CriticalSectionRawMutex, esp_radio::wifi::Config> = Signal::new();
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn connection_handler(mut controller: WifiController<'static>) -> ! {
|
||||
async fn connection(controller: &mut WifiController<'static>) {
|
||||
info!("Connecting to WiFi...");
|
||||
|
||||
match controller.connect_async().await {
|
||||
Ok(info) => {
|
||||
info!("Wifi connected to {:?}", info);
|
||||
|
||||
// wait until we're no longer connected
|
||||
let info = controller.wait_for_disconnect_async().await.ok();
|
||||
info!("Disconnected: {:?}", info);
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to connect to wifi: {:?}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
loop {
|
||||
if let Either::First(req) =
|
||||
select(WIFI_HANDLER_RPC.wait(), connection(&mut controller)).await
|
||||
&& let Some(err) = controller.set_config(&req).err()
|
||||
{
|
||||
error!("Wifi controller failed to set a new config: {:?}", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn ip_logger(net_stack: Stack<'static>) -> ! {
|
||||
loop {
|
||||
info!("Getting IP address...");
|
||||
net_stack.wait_config_up().await;
|
||||
|
||||
match net_stack.config_v4() {
|
||||
Some(info) => {
|
||||
info!("Got IP: {:?}", info);
|
||||
|
||||
// wait until we're no longer connected
|
||||
net_stack.wait_config_down().await;
|
||||
info!("Address no longer configured");
|
||||
}
|
||||
None => {
|
||||
error!("Failed to configure an address");
|
||||
}
|
||||
}
|
||||
|
||||
Timer::after(Duration::from_millis(5000)).await
|
||||
}
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn net_handler(mut runner: Runner<'static, Interface<'static>>) -> ! {
|
||||
runner.run().await
|
||||
}
|
||||
Reference in New Issue
Block a user