Compare commits

..

7 Commits

Author SHA1 Message Date
ce96dd0a4e Bumped updater version 2025-01-11 05:52:19 +01:00
7ee0ef0bad Removed reset endpoint 2025-01-11 05:25:31 +01:00
30eda090b1 Cleanup 2025-01-11 05:14:37 +01:00
85a4e4e7c5 Reworked to serve API using picoserve 2025-01-11 04:54:48 +01:00
719723565f Updated embassy and locked rust version 2024-03-27 02:50:08 +01:00
a81c17cbb1 Small tweaks 2023-09-16 03:58:06 +02:00
ad2ecdfa52 Verify that the url is https 2023-09-16 01:49:51 +02:00
7 changed files with 429 additions and 1203 deletions

169
bootloader/Cargo.lock generated
View File

@@ -26,15 +26,6 @@ dependencies = [
"term",
]
[[package]]
name = "atomic-polyfill"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3ff7eb3f316534d83a8a2c3d1674ace8a5a71198eba31e2e2b597833f699b28"
dependencies = [
"critical-section",
]
[[package]]
name = "atomic-polyfill"
version = "1.0.3"
@@ -62,7 +53,7 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5deb64efa5bd81e31fcd1938615a6d98c82eafcbcd787162b6f63b91d6bac5b3"
dependencies = [
"rustc_version 0.2.3",
"rustc_version",
]
[[package]]
@@ -308,6 +299,15 @@ dependencies = [
"winapi",
]
[[package]]
name = "document-features"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef5282ad69563b5fc40319526ba27e0e7363d552a896f0297d54f767717f9b95"
dependencies = [
"litrs",
]
[[package]]
name = "either"
version = "1.9.0"
@@ -316,8 +316,9 @@ checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07"
[[package]]
name = "embassy-boot"
version = "0.1.1"
source = "git+https://github.com/embassy-rs/embassy#f1f4943ca51e8827146daca950fdf88d5b1e046b"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e917a2dba10553ab6188fdafd81e971b0441953c663842285709eaf2a5de5e5b"
dependencies = [
"defmt",
"digest",
@@ -330,8 +331,9 @@ dependencies = [
[[package]]
name = "embassy-boot-rp"
version = "0.1.0"
source = "git+https://github.com/embassy-rs/embassy#f1f4943ca51e8827146daca950fdf88d5b1e046b"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d8a53abc2a101dd352794666370ec0a13c53715dbec788f9aafde799ec1f2c2"
dependencies = [
"cfg-if",
"cortex-m",
@@ -348,13 +350,14 @@ dependencies = [
[[package]]
name = "embassy-embedded-hal"
version = "0.1.0"
source = "git+https://github.com/embassy-rs/embassy#f1f4943ca51e8827146daca950fdf88d5b1e046b"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eca4a9380d03e61063067b8239f67d2fa9f108ede7c46b4273804f6b79e59a1d"
dependencies = [
"embassy-futures",
"embassy-sync",
"embassy-time",
"embedded-hal 0.2.7",
"embedded-hal 1.0.0-rc.1",
"embedded-hal 1.0.0",
"embedded-hal-async",
"embedded-storage",
"embedded-storage-async",
@@ -363,13 +366,15 @@ dependencies = [
[[package]]
name = "embassy-futures"
version = "0.1.0"
source = "git+https://github.com/embassy-rs/embassy#f1f4943ca51e8827146daca950fdf88d5b1e046b"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f878075b9794c1e4ac788c95b728f26aa6366d32eeb10c7051389f898f7d067"
[[package]]
name = "embassy-hal-internal"
version = "0.1.0"
source = "git+https://github.com/embassy-rs/embassy#f1f4943ca51e8827146daca950fdf88d5b1e046b"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a0ec47cf8bab914018d4bd2b4f0aaeb46e4f52ab1e7985df88aeef2c6eda5aed"
dependencies = [
"cortex-m",
"critical-section",
@@ -380,14 +385,16 @@ dependencies = [
[[package]]
name = "embassy-rp"
version = "0.1.0"
source = "git+https://github.com/embassy-rs/embassy#f1f4943ca51e8827146daca950fdf88d5b1e046b"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "438f170cbd97d4a870e8d57e1738ee815255028ad31dd409d891e2bf797dc531"
dependencies = [
"atomic-polyfill 1.0.3",
"atomic-polyfill",
"cfg-if",
"cortex-m",
"cortex-m-rt",
"critical-section",
"defmt",
"document-features",
"embassy-embedded-hal",
"embassy-futures",
"embassy-hal-internal",
@@ -395,8 +402,9 @@ dependencies = [
"embassy-time",
"embassy-usb-driver",
"embedded-hal 0.2.7",
"embedded-hal 1.0.0-rc.1",
"embedded-hal 1.0.0",
"embedded-hal-async",
"embedded-hal-nb",
"embedded-io",
"embedded-io-async",
"embedded-storage",
@@ -404,7 +412,6 @@ dependencies = [
"fixed",
"futures",
"nb 1.1.0",
"paste",
"pio",
"pio-proc",
"rand_core",
@@ -414,8 +421,9 @@ dependencies = [
[[package]]
name = "embassy-sync"
version = "0.3.0"
source = "git+https://github.com/embassy-rs/embassy#f1f4943ca51e8827146daca950fdf88d5b1e046b"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd938f25c0798db4280fcd8026bf4c2f48789aebf8f77b6e5cf8a7693ba114ec"
dependencies = [
"cfg-if",
"critical-section",
@@ -427,22 +435,42 @@ dependencies = [
[[package]]
name = "embassy-time"
version = "0.1.3"
source = "git+https://github.com/embassy-rs/embassy#f1f4943ca51e8827146daca950fdf88d5b1e046b"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9c844070d9f80dc66ee739299183312baee2e1cdeb6e90b4ea2af44f4676da5"
dependencies = [
"atomic-polyfill 1.0.3",
"cfg-if",
"critical-section",
"document-features",
"embassy-time-driver",
"embassy-time-queue-driver",
"embedded-hal 0.2.7",
"embedded-hal 1.0.0",
"embedded-hal-async",
"futures-util",
"heapless",
]
[[package]]
name = "embassy-time-driver"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e0c214077aaa9206958b16411c157961fb7990d4ea628120a78d1a5a28aed24"
dependencies = [
"document-features",
]
[[package]]
name = "embassy-time-queue-driver"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1177859559ebf42cd24ae7ba8fe6ee707489b01d0bf471f8827b7b12dcb0bc0"
[[package]]
name = "embassy-usb-driver"
version = "0.1.0"
source = "git+https://github.com/embassy-rs/embassy#f1f4943ca51e8827146daca950fdf88d5b1e046b"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4fc247028eae04174b6635104a35b1ed336aabef4654f5e87a8f32327d231970"
dependencies = [
"defmt",
]
@@ -459,45 +487,55 @@ dependencies = [
[[package]]
name = "embedded-hal"
version = "1.0.0-rc.1"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2894bc2f0457b8ca3d6b8ab8aad64d9337583672494013457f86c5a9146c0e22"
checksum = "361a90feb7004eca4019fb28352a9465666b24f840f5c3cddf0ff13920590b89"
[[package]]
name = "embedded-hal-async"
version = "1.0.0-rc.1"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "76a8a3517745342155b3b00895a0f78417a453fb800d97a8bf4777d5720acde9"
checksum = "0c4c685bbef7fe13c3c6dd4da26841ed3980ef33e841cddfa15ce8a8fb3f1884"
dependencies = [
"embedded-hal 1.0.0-rc.1",
"embedded-hal 1.0.0",
]
[[package]]
name = "embedded-hal-nb"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fba4268c14288c828995299e59b12babdbe170f6c6d73731af1b4648142e8605"
dependencies = [
"embedded-hal 1.0.0",
"nb 1.1.0",
]
[[package]]
name = "embedded-io"
version = "0.5.0"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "658bbadc628dc286b9ae02f0cb0f5411c056eb7487b72f0083203f115de94060"
checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d"
[[package]]
name = "embedded-io-async"
version = "0.5.0"
version = "0.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1394754ad749a560b25a0c70dcd2b66a450824a1311fc475bb2ccbfabe7f8414"
checksum = "3ff09972d4073aa8c299395be75161d582e7629cd663171d62af73c8d50dba3f"
dependencies = [
"embedded-io",
]
[[package]]
name = "embedded-storage"
version = "0.3.0"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "156d7a2fdd98ebbf9ae579cbceca3058cff946e13f8e17b90e3511db0508c723"
checksum = "a21dea9854beb860f3062d10228ce9b976da520a73474aed3171ec276bc0c032"
[[package]]
name = "embedded-storage-async"
version = "0.4.0"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "052997a894670d0cde873faa7405bc98e2fd29f569d2acd568561bc1c396b35a"
checksum = "1763775e2323b7d5f0aa6090657f5e21cfa02ede71f5dc40eead06d64dcd15cc"
dependencies = [
"embedded-storage",
]
@@ -662,9 +700,9 @@ dependencies = [
[[package]]
name = "hash32"
version = "0.2.1"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0c35f58762feb77d74ebe43bdbc3210f09be9fe6742234d573bacc26ed92b67"
checksum = "47d60b12902ba28e2730cd37e95b8c9223af2808df9e902d4df49588d1470606"
dependencies = [
"byteorder",
]
@@ -677,14 +715,11 @@ checksum = "2c6201b9ff9fd90a5a3bac2e56a830d0caa509576f0e503818ee82c181b3437a"
[[package]]
name = "heapless"
version = "0.7.16"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db04bc24a18b9ea980628ecf00e6c0264f3c1426dac36c00cb49b6fbad8b0743"
checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad"
dependencies = [
"atomic-polyfill 0.1.11",
"hash32",
"rustc_version 0.4.0",
"spin",
"stable_deref_trait",
]
@@ -767,6 +802,12 @@ version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a9bad9f94746442c783ca431b22403b519cd7fbeed0533fdd6328b2f2212128"
[[package]]
name = "litrs"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ce301924b7887e9d637144fdade93f9dfff9b60981d4ac161db09720d39aa5"
[[package]]
name = "lock_api"
version = "0.4.10"
@@ -1088,16 +1129,7 @@ version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a"
dependencies = [
"semver 0.9.0",
]
[[package]]
name = "rustc_version"
version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366"
dependencies = [
"semver 1.0.18",
"semver",
]
[[package]]
@@ -1134,12 +1166,6 @@ dependencies = [
"semver-parser",
]
[[package]]
name = "semver"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918"
[[package]]
name = "semver-parser"
version = "0.7.0"
@@ -1148,9 +1174,9 @@ checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
[[package]]
name = "signature"
version = "1.6.4"
version = "2.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74233d3b3b2f6d4b006dc19dee745e73e2a6bfb6f93607cd3b02bd5b00797d7c"
checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de"
[[package]]
name = "siphasher"
@@ -1164,15 +1190,6 @@ version = "1.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62bb4feee49fdd9f707ef802e22365a35de4b7b299de4763d44bfea899442ff9"
[[package]]
name = "spin"
version = "0.9.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"
dependencies = [
"lock_api",
]
[[package]]
name = "stable_deref_trait"
version = "1.2.0"

View File

@@ -7,27 +7,26 @@ edition = "2021"
defmt = { version = "0.3", optional = true }
defmt-rtt = { version = "0.4", optional = true }
embassy-boot = { version = "0.1", features = ["nightly"] }
embassy-boot-rp = { version = "0.1", features = ["nightly"] }
embassy-rp = { version = "0.1", features = ["nightly"] }
embassy-sync = { version = "0.3", features = ["nightly"] }
embassy-boot = { version = "0.2" }
embassy-boot-rp = { version = "0.2" }
embassy-rp = { version = "0.1" }
embassy-sync = { version = "0.5" }
cortex-m = { version = "0.7", features = [
"inline-asm",
"critical-section-single-core",
] }
cortex-m-rt = { version = "0.7" }
embedded-storage = "0.3.0"
[patch.crates-io]
# This is needed as embassy-rp is not on crates.io
embassy-boot = { git = "https://github.com/embassy-rs/embassy" }
embassy-boot-rp = { git = "https://github.com/embassy-rs/embassy" }
embassy-rp = { git = "https://github.com/embassy-rs/embassy" }
embassy-sync = { git = "https://github.com/embassy-rs/embassy" }
embedded-storage = "0.3"
[features]
defmt = ["dep:defmt", "embassy-boot/defmt", "embassy-boot-rp/defmt", "embassy-rp/defmt", "embassy-sync/defmt"]
defmt = [
"dep:defmt",
"embassy-boot/defmt",
"embassy-boot-rp/defmt",
"embassy-rp/defmt",
"embassy-sync/defmt",
]
debug = ["defmt-rtt", "defmt"]
[profile.release]

View File

@@ -1,3 +1,4 @@
[toolchain]
channel = "nightly"
channel = "nightly-2025-01-09"
components = ["rustfmt", "clippy", "rust-analyzer"]
targets = ["thumbv6m-none-eabi"]

962
updater/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,60 +1,30 @@
[package]
name = "updater"
version = "0.1.0"
version = "0.2.0"
edition = "2021"
[dependencies]
cortex-m = { version = "0.7", features = ["inline-asm"] }
cortex-m-rt = "0.7"
defmt = "0.3"
defmt-rtt = "0.4"
embassy-net = { version = "0.1", features = [
"tcp",
"dhcpv4",
"nightly",
"medium-ethernet",
"defmt",
"dns",
embassy-net = { version = "0.6", features = [
"tcp",
"dhcpv4",
"medium-ethernet",
"defmt",
"dns",
] }
embassy-boot = { version = "0.1", features = [
"nightly",
"defmt",
"ed25519-salty",
embassy-boot = { version = "0.4", features = ["defmt", "ed25519-salty"] }
embassy-time = { version = "0.4", features = [
"defmt",
"defmt-timestamp-uptime",
] }
embassy-time = { version = "0.1", features = [
"defmt",
"unstable-traits",
"defmt-timestamp-uptime",
"nightly",
] }
rand_core = "0.6.4"
embedded-io-async = { version = "0.5", features = ["defmt-03"] }
embedded-storage = "0.3.0"
rust-mqtt = { version = "0.1.5", features = [
"defmt",
"no_std",
"tls",
], default-features = false }
nourl = { version = "0.1.1", features = ["defmt"] }
heapless = { version = "0.7.16", features = ["defmt", "serde"] }
serde = { version = "1.0.188", default-features = false, features = ["derive"] }
serde-json-core = "0.5.1"
embedded-tls = { version = "0.15.0", default-features = false, features = [
"async",
"defmt",
] }
reqwless = { version = "0.5.0", features = ["defmt"] }
static_cell = { version = "1.2.0", features = ["nightly"] }
impl-tools = "0.10.0"
embassy-futures = { version = "0.1", features = ["defmt"] }
embedded-io-async = { version = "0.6", features = ["defmt-03"] }
embedded-storage = "0.3"
heapless = { version = "0.8", features = ["defmt-03", "serde"] }
serde = { version = "1.0", default-features = false, features = ["derive"] }
picoserve = { version = "0.13.3", features = ["defmt", "embassy"] }
embassy-sync = { version = "0.6.1", features = ["defmt"] }
[patch.crates-io]
embassy-net = { git = "https://github.com/embassy-rs/embassy" }
embassy-boot = { git = "https://github.com/embassy-rs/embassy" }
embassy-time = { git = "https://github.com/embassy-rs/embassy" }
# Updated to embedded-io 0.5.0
rust-mqtt = { git = "https://git.huizinga.dev/Dreaded_X/rust-mqtt" }
# Make mqtt:// and mqtts:// actually work
nourl = { git = "https://git.huizinga.dev/Dreaded_X/nourl" }
# Waiting for this to get updated to embedded-io 0.5 properly
reqwless = { path = "../../reqwless" }
picoserve = { git = "https://github.com/hodasemi/picoserve" }

View File

@@ -1,107 +0,0 @@
use core::fmt::{Display, Write};
use heapless::String;
use defmt::{Format, Formatter};
use embassy_boot::FirmwareUpdaterError;
use embassy_net::{dns, tcp::ConnectError};
use embedded_io_async::ReadExactError;
use embedded_storage::nor_flash::NorFlashError;
use embedded_tls::TlsError;
use rust_mqtt::packet::v5::reason_codes::ReasonCode;
impl_tools::impl_scope! {
#[derive(Debug)]
pub enum Error<FE: NorFlashError + defmt::Format> {
Mqtt(ReasonCode),
Dns(dns::Error),
Connect(ConnectError),
Tls(TlsError),
Reqwless(reqwless::Error),
FirmwareUpdater(FirmwareUpdaterError),
FlashError(FE),
UnexpectedEof,
}
impl Self {
pub fn string(&self) -> String<256> {
let mut error = String::new();
core::write!(error, "{}", self).expect("Formatting the error should not fail");
error
}
}
impl From<ReasonCode> for Self {
fn from(error: ReasonCode) -> Self {
Self::Mqtt(error)
}
}
impl From<dns::Error> for Self {
fn from(error: dns::Error) -> Self {
Self::Dns(error)
}
}
impl From<ConnectError> for Self {
fn from(error: ConnectError) -> Self {
Self::Connect(error)
}
}
impl From<TlsError> for Self {
fn from(error: TlsError) -> Self {
Self::Tls(error)
}
}
impl From<reqwless::Error> for Self {
fn from(error: reqwless::Error) -> Self {
Self::Reqwless(error)
}
}
impl From<FirmwareUpdaterError> for Self {
fn from(error: FirmwareUpdaterError) -> Self {
Self::FirmwareUpdater(error)
}
}
impl From<ReadExactError<reqwless::Error>> for Self {
fn from(error: ReadExactError<reqwless::Error>) -> Self {
match error {
ReadExactError::UnexpectedEof => Self::UnexpectedEof,
ReadExactError::Other(error) => Self::Reqwless(error),
}
}
}
impl Format for Self {
fn format(&self, f: Formatter) {
match self {
Error::Mqtt(error) => defmt::write!(f, "Mqtt: {}", error),
Error::Dns(error) => defmt::write!(f, "Dns: {}", error),
Error::Connect(error) => defmt::write!(f, "Connect: {}", error),
Error::Tls(error) => defmt::write!(f, "Tls: {}", error),
Error::Reqwless(error) => defmt::write!(f, "Reqwless: {}", error),
Error::FirmwareUpdater(error) => defmt::write!(f, "FirmwareUpdater: {}", error),
Error::FlashError(error) => defmt::write!(f, "FlashError: {:?}", error),
Error::UnexpectedEof => defmt::write!(f, "UnexpectedEof"),
}
}
}
impl Display for Self {
fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
match self {
Error::Mqtt(error) => core::write!(f, "Mqtt: {}", error),
Error::Dns(error) => core::write!(f, "Dns: {:?}", error),
Error::Connect(error) => core::write!(f, "Connect: {:?}", error),
Error::Tls(error) => core::write!(f, "Tls: {:?}", error),
Error::Reqwless(error) => core::write!(f, "Reqwless: {:?}", error),
Error::FirmwareUpdater(error) => core::write!(f, "FirmwareUpdater: {:?}", error),
Error::FlashError(error) => core::write!(f, "FlashError: {:?}", error),
Error::UnexpectedEof => core::write!(f, "UnexpectedEof"),
}
}
}
}

View File

@@ -1,245 +1,145 @@
#![no_std]
#![no_main]
#![feature(type_alias_impl_trait)]
#![feature(never_type)]
use defmt::*;
use embassy_boot::{AlignedBuffer, BlockingFirmwareUpdater};
use embassy_net::{dns::DnsQueryType, driver::Driver, tcp::TcpSocket, Stack};
use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, mutex::Mutex};
use embassy_time::{Duration, Timer};
use embedded_io_async::{Read, Write};
use embedded_io_async::Read;
use embedded_storage::nor_flash::NorFlash;
use embedded_tls::{Aes128GcmSha256, NoVerify, TlsConfig, TlsConnection, TlsContext};
use heapless::Vec;
use nourl::Url;
use rand_core::{CryptoRng, RngCore};
use reqwless::{
request::{Method, Request, RequestBuilder},
response::Response,
use picoserve::{
response::{self, IntoResponse, StatusCode},
routing::{get, put_service, PathRouter},
Router,
};
use rust_mqtt::{
client::{client::MqttClient, client_config::ClientConfig},
packet::v5::publish_packet::QualityOfService,
};
use serde::Serialize;
use static_cell::make_static;
mod error;
pub use crate::error::Error;
#[derive(Serialize)]
#[serde(rename_all = "snake_case", tag = "status")]
enum Status<'a> {
Connected { version: &'a str },
Disconnected,
PreparingUpdate,
Erasing,
Writing { progress: u32 },
Verifying,
UpdateFailed { error: &'a str },
UpdateComplete,
#[derive(Clone, Copy)]
struct UpdaterService<DFU, STATE>
where
DFU: NorFlash + 'static,
STATE: NorFlash + 'static,
DFU::Error: Format,
{
updater: &'static Mutex<CriticalSectionRawMutex, BlockingFirmwareUpdater<'static, DFU, STATE>>,
public_key: &'static [u8; 32],
}
impl Status<'_> {
fn json(&self) -> Vec<u8, 512> {
serde_json_core::to_vec(self)
.expect("This buffers size should be large enough to contain the serialized status")
}
}
// TODO: Make this the owner of the blocking firmware updater
// TODO: When fixed, use the async firmware updater
pub struct Updater<'a, DFU, STATE>
impl<DFU, STATE> UpdaterService<DFU, STATE>
where
DFU: NorFlash,
STATE: NorFlash,
DFU::Error: Format,
{
updater: BlockingFirmwareUpdater<'a, DFU, STATE>,
topic_status: &'static str,
topic_update: &'static str,
version: &'static str,
public_key: &'static [u8],
}
impl<'a, DFU, STATE> Updater<'a, DFU, STATE>
where
DFU: NorFlash,
STATE: NorFlash,
DFU::Error: Format,
{
pub fn new(
updater: BlockingFirmwareUpdater<'a, DFU, STATE>,
topic_status: &'static str,
topic_update: &'static str,
version: &'static str,
public_key: &'static [u8],
fn new(
updater: &'static Mutex<
CriticalSectionRawMutex,
BlockingFirmwareUpdater<'static, DFU, STATE>,
>,
public_key: &'static [u8; 32],
) -> Self {
Self {
updater,
topic_status,
topic_update,
version,
public_key,
}
}
}
pub fn add_will<const MAX_PROPERTIES: usize>(
impl<S, DFU, STATE> picoserve::routing::RequestHandlerService<S> for UpdaterService<DFU, STATE>
where
DFU: NorFlash + 'static,
STATE: NorFlash + 'static,
DFU::Error: Format,
{
async fn call_request_handler_service<
R: Read,
W: picoserve::response::ResponseWriter<Error = R::Error>,
>(
&self,
config: &mut ClientConfig<'_, MAX_PROPERTIES, impl RngCore>,
) {
let msg = make_static!(Status::Disconnected.json());
config.add_will(self.topic_status, msg, true);
}
pub async fn ready<const MAX_PROPERTIES: usize>(
&mut self,
client: &mut MqttClient<'_, impl Write + Read, MAX_PROPERTIES, impl RngCore>,
) -> Result<(), Error<DFU::Error>> {
let status = Status::Connected {
version: self.version,
}
.json();
client
.send_message(self.topic_status, &status, QualityOfService::QoS1, true)
.await?;
client.subscribe_to_topic(self.topic_update).await?;
self.updater.mark_booted()?;
Ok(())
}
pub async fn update<const MAX_PROPERTIES: usize>(
&mut self,
stack: &'static Stack<impl Driver>,
rng: &mut (impl RngCore + CryptoRng),
client: &mut MqttClient<'_, impl Write + Read, MAX_PROPERTIES, impl RngCore>,
url: Url<'_>,
) -> Result<!, Error<DFU::Error>> {
let result = self._update(stack, rng, client, url).await;
if let Err(err) = &result {
let status = Status::UpdateFailed {
error: &err.string(),
_state: &S,
_path_parameters: (),
mut request: picoserve::request::Request<'_, R>,
response_writer: W,
) -> Result<picoserve::ResponseSent, W::Error> {
let mut updater = self.updater.lock().await;
let writer = match updater.prepare_update() {
Ok(writer) => writer,
Err(err) => {
return response::Response::new(
StatusCode::INTERNAL_SERVER_ERROR,
format_args!("{err:?}"),
)
.write_to(request.body_connection.finalize().await?, response_writer)
.await;
}
.json();
};
client
.send_message(self.topic_status, &status, QualityOfService::QoS1, false)
.await?;
}
let mut reader = request.body_connection.body().reader();
result
}
async fn _update<const MAX_PROPERTIES: usize>(
&mut self,
stack: &'static Stack<impl Driver>,
rng: &mut (impl RngCore + CryptoRng),
client: &mut MqttClient<'_, impl Write + Read, MAX_PROPERTIES, impl RngCore>,
url: Url<'_>,
) -> Result<!, Error<DFU::Error>> {
info!("Preparing for OTA...");
let status = Status::PreparingUpdate.json();
client
.send_message(self.topic_status, &status, QualityOfService::QoS1, false)
.await?;
let ip = stack.dns_query(url.host(), DnsQueryType::A).await?[0];
let mut rx_buffer = [0; 1024];
let mut tx_buffer = [0; 1024];
let mut socket = TcpSocket::new(stack, &mut rx_buffer, &mut tx_buffer);
let addr = (ip, url.port_or_default());
debug!("Addr: {}", addr);
socket.connect(addr).await?;
let mut read_record_buffer = [0; 16384 * 2];
let mut write_record_buffer = [0; 16384];
let mut tls: TlsConnection<TcpSocket, Aes128GcmSha256> =
TlsConnection::new(socket, &mut read_record_buffer, &mut write_record_buffer);
tls.open::<_, NoVerify>(TlsContext::new(&TlsConfig::new(), rng))
.await?;
debug!("Path: {}", url.path());
Request::get(url.path())
.host(url.host())
.build()
.write(&mut tls)
.await?;
let mut headers = [0; 1024];
let resp = Response::read(&mut tls, Method::GET, &mut headers).await?;
let mut body = resp.body().reader();
debug!("Erasing flash...");
let status = Status::Erasing.json();
client
.send_message(self.topic_status, &status, QualityOfService::QoS1, false)
.await?;
let writer = self.updater.prepare_update()?;
debug!("Writing...");
let status = Status::Writing { progress: 0 }.json();
client
.send_message(self.topic_status, &status, QualityOfService::QoS1, false)
.await?;
// The first 64 bytes of the file contain the signature
let mut signature = [0; 64];
body.read_exact(&mut signature).await?;
if let Err(err) = reader.read_exact(&mut signature).await {
return response::Response::new(
StatusCode::INTERNAL_SERVER_ERROR,
format_args!("{err:?}"),
)
.write_to(request.body_connection.finalize().await?, response_writer)
.await;
}
trace!("Signature: {:?}", signature);
let mut buffer = AlignedBuffer([0; 4096]);
let mut size = 0;
while let Ok(read) = body.read(&mut buffer.0).await {
while let Ok(read) = reader.read(&mut buffer.0).await {
if read == 0 {
break;
}
debug!("Writing chunk: {}", read);
writer
.write(size, &buffer.0[..read])
.map_err(Error::FlashError)?;
if let Err(err) = writer.write(size, &buffer.0[..read]) {
return response::Response::new(
StatusCode::INTERNAL_SERVER_ERROR,
format_args!("{err:?}"),
)
.write_to(request.body_connection.finalize().await?, response_writer)
.await;
}
size += read as u32;
let status = Status::Writing { progress: size }.json();
client
.send_message(self.topic_status, &status, QualityOfService::QoS1, false)
.await?;
}
debug!("Total size: {}", size);
let status = Status::Verifying.json();
client
.send_message(self.topic_status, &status, QualityOfService::QoS1, false)
let public_key = self.public_key;
if let Err(err) = updater.verify_and_mark_updated(public_key, &signature, size) {
return response::Response::new(
StatusCode::INTERNAL_SERVER_ERROR,
format_args!("{err:?}"),
)
.write_to(request.body_connection.finalize().await?, response_writer)
.await;
}
"Update complete"
.write_to(request.body_connection.finalize().await?, response_writer)
.await?;
self.updater
.verify_and_mark_updated(self.public_key, &signature, size)?;
Timer::after(Duration::from_secs(1)).await;
// Update mqtt message should be send using retain
// TODO: Clear the message
let status = Status::UpdateComplete.json();
client
.send_message(self.topic_status, &status, QualityOfService::QoS1, false)
.await?;
client.disconnect().await?;
info!("Restarting in 5 seconds...");
Timer::after(Duration::from_secs(5)).await;
cortex_m::peripheral::SCB::sys_reset()
cortex_m::peripheral::SCB::sys_reset();
}
}
pub fn firmware_router<S, DFU, STATE>(
version: &'static str,
updater: &'static Mutex<CriticalSectionRawMutex, BlockingFirmwareUpdater<'static, DFU, STATE>>,
public_key: &'static [u8; 32],
) -> Router<impl PathRouter<S>, S>
where
DFU: NorFlash + 'static,
STATE: NorFlash + 'static,
DFU::Error: Format,
{
let updater_service = UpdaterService::new(updater, public_key);
Router::new()
.route("/update", put_service(updater_service))
.route("/version", get(move || async move { version }))
}