├── src ├── mqtt.rs ├── utils.rs ├── io.rs ├── lib.rs ├── log.rs ├── eth.rs ├── channel.rs ├── utils │ ├── io.rs │ └── http.rs ├── http.rs ├── ws.rs ├── storage.rs ├── mqtt │ └── client.rs ├── ota.rs ├── ipv4.rs ├── http │ ├── server.rs │ └── client.rs └── wifi.rs ├── .gitignore ├── .github └── workflows │ ├── issue_handler.yml │ ├── publish-dry-run.yml │ ├── publish.yml │ └── ci.yml ├── LICENSE-MIT ├── README.md ├── Cargo.toml ├── LICENSE-APACHE └── CHANGELOG.md /src/mqtt.rs: -------------------------------------------------------------------------------- 1 | pub mod client; 2 | -------------------------------------------------------------------------------- /src/utils.rs: -------------------------------------------------------------------------------- 1 | pub mod http; 2 | pub mod io; 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.vscode 2 | /.espressif 3 | /.embuild 4 | /target 5 | /Cargo.lock 6 | **/*.rs.bk 7 | -------------------------------------------------------------------------------- /src/io.rs: -------------------------------------------------------------------------------- 1 | pub use embedded_io::*; 2 | 3 | pub mod asynch { 4 | pub use embedded_io_async::*; 5 | } 6 | -------------------------------------------------------------------------------- /.github/workflows/issue_handler.yml: -------------------------------------------------------------------------------- 1 | name: Add new issues to project 2 | 3 | on: 4 | issues: 5 | types: 6 | - opened 7 | 8 | jobs: 9 | add-to-project: 10 | name: Add issue to project 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/add-to-project@v0.5.0 14 | with: 15 | project-url: https://github.com/orgs/esp-rs/projects/2 16 | github-token: ${{ secrets.PAT }} 17 | -------------------------------------------------------------------------------- /.github/workflows/publish-dry-run.yml: -------------------------------------------------------------------------------- 1 | name: PublishDryRun 2 | 3 | on: 4 | workflow_dispatch 5 | 6 | env: 7 | rust_toolchain: stable 8 | 9 | jobs: 10 | publishdryrun: 11 | name: Publish Dry Run 12 | runs-on: ubuntu-latest 13 | steps: 14 | - name: Setup | Checkout 15 | uses: actions/checkout@v3 16 | - name: Setup | Rust 17 | uses: dtolnay/rust-toolchain@v1 18 | with: 19 | toolchain: ${{ env.rust_toolchain }} 20 | components: rust-src 21 | - name: Build | Publish Dry Run 22 | run: cargo publish --dry-run 23 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![no_std] 2 | #![allow(async_fn_in_trait)] 3 | 4 | #[cfg(feature = "std")] 5 | #[allow(unused_imports)] 6 | #[macro_use] 7 | extern crate std; 8 | 9 | #[cfg(feature = "alloc")] 10 | #[allow(unused_imports)] 11 | #[macro_use] 12 | extern crate alloc; 13 | 14 | #[cfg(all(feature = "defmt", feature = "log"))] 15 | compile_error!("You must enable at most one of the following features: defmt, log"); 16 | 17 | pub mod channel; 18 | pub mod eth; 19 | pub mod http; 20 | pub mod io; 21 | pub mod ipv4; 22 | pub mod log; 23 | pub mod mqtt; 24 | pub mod ota; 25 | pub mod storage; 26 | pub mod utils; 27 | pub mod wifi; 28 | pub mod ws; 29 | -------------------------------------------------------------------------------- /src/log.rs: -------------------------------------------------------------------------------- 1 | //Based on smoltcp's macro_rules 2 | #[cfg(not(test))] 3 | #[cfg(feature = "log")] 4 | #[macro_export] 5 | macro_rules! svc_log { 6 | (debug, $($arg:expr),*) => { log::debug!($($arg),*) }; 7 | (info, $($arg:expr),*) => { log::info!($($arg),*) }; 8 | (warn, $($arg:expr),*) => { log::warn!($($arg),*) }; 9 | } 10 | 11 | #[cfg(test)] 12 | #[cfg(feature = "log")] 13 | #[macro_export] 14 | macro_rules! svc_log { 15 | (debug, $($arg:expr),*) => { println!($($arg),*) }; 16 | (info, $($arg:expr),*) => { println!($($arg),*) }; 17 | (warn, $($arg:expr),*) => { println!($($arg),*) }; 18 | } 19 | 20 | #[cfg(feature = "defmt")] 21 | #[macro_export] 22 | macro_rules! svc_log { 23 | (debug, $($arg:expr),*) => { defmt::debug!($($arg),*) }; 24 | (info, $($arg:expr),*) => { defmt::info!($($arg),*) }; 25 | (warn, $($arg:expr),*) => { defmt::warn!($($arg),*) }; 26 | } 27 | 28 | #[cfg(not(any(feature = "log", feature = "defmt")))] 29 | #[macro_export] 30 | macro_rules! svc_log { 31 | ($level:ident, $($arg:expr),*) => {{ $( let _ = $arg; )* }} 32 | } 33 | 34 | #[allow(unused)] 35 | pub(crate) use svc_log; 36 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright 2019-2020 Contributors to xtensa-lx6-rt 2 | 3 | Permission is hereby granted, free of charge, to any 4 | person obtaining a copy of this software and associated 5 | documentation files (the "Software"), to deal in the 6 | Software without restriction, including without 7 | limitation the rights to use, copy, modify, merge, 8 | publish, distribute, sublicense, and/or sell copies of 9 | the Software, and to permit persons to whom the Software 10 | is furnished to do so, subject to the following 11 | conditions: 12 | 13 | The above copyright notice and this permission notice 14 | shall be included in all copies or substantial portions 15 | of the Software. 16 | 17 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 18 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 19 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 20 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 21 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 22 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 23 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 24 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 25 | DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | workflow_dispatch 5 | 6 | env: 7 | rust_toolchain: stable 8 | crate_name: embedded-svc 9 | 10 | jobs: 11 | publish: 12 | name: Publish 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Setup | Checkout 16 | uses: actions/checkout@v3 17 | - name: Setup | Rust 18 | uses: dtolnay/rust-toolchain@v1 19 | with: 20 | toolchain: ${{ env.rust_toolchain }} 21 | components: rust-src 22 | - name: Login 23 | run: cargo login ${{ secrets.crates_io_token }} 24 | - name: Build | Publish 25 | run: cargo publish 26 | - name: Get the crate version from cargo 27 | run: | 28 | version=$(cargo metadata --format-version=1 --no-deps | jq -r ".packages[] | select(.name == \"${{env.crate_name}}\") | .version") 29 | echo "crate_version=$version" >> $GITHUB_ENV 30 | echo "${{env.crate_name}} version: $version" 31 | - name: Tag the new release 32 | uses: rickstaa/action-create-tag@v1 33 | with: 34 | tag: v${{env.crate_version}} 35 | message: "Release v${{env.crate_version}}" 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rust APIs and abstractions for embedded services 2 | 3 | [![CI](https://github.com/esp-rs/embedded-svc/actions/workflows/ci.yml/badge.svg)](https://github.com/esp-rs/embedded-svc/actions/workflows/ci.yml) 4 | ![crates.io](https://img.shields.io/crates/v/embedded-svc.svg) 5 | [![Documentation](https://docs.rs/embedded-svc/badge.svg)](https://docs.rs/embedded-svc) 6 | [![Matrix](https://img.shields.io/matrix/esp-rs:matrix.org?label=join%20matrix&color=BEC5C9&logo=matrix)](https://matrix.to/#/#esp-rs:matrix.org) 7 | 8 | This crate ships traits for embedded features such as wifi, networking, httpd, logging. 9 | The intended use is for concrete implementations to use the traits provided in this crate as a common base. 10 | This would eventually lead to a portable embedded ecosystem. The APIs currently have a single implementation for the [ESP32[-XX] / ESP-IDF](https://github.com/esp-rs/esp-idf-svc). 11 | However, they are meant to be portable and should be possible to implement for other boards too. 12 | 13 | For more information, check out: 14 | * The [Rust on ESP Book](https://esp-rs.github.io/book/) 15 | * The [esp-idf-svc](https://github.com/esp-rs/esp-idf-svc) project 16 | * The [esp-idf-template](https://github.com/esp-rs/esp-idf-template) project 17 | * The [esp-idf-sys](https://github.com/esp-rs/esp-idf-sys) project 18 | * The [esp-idf-hal](https://github.com/esp-rs/esp-idf-hal) project 19 | * The [Rust for Xtensa toolchain](https://github.com/esp-rs/rust-build) 20 | * The [Rust-with-STD demo](https://github.com/ivmarkov/rust-esp32-std-demo) project 21 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | schedule: 9 | - cron: '50 4 * * *' 10 | workflow_dispatch: 11 | 12 | env: 13 | rust_toolchain: nightly 14 | 15 | jobs: 16 | compile: 17 | name: Compile 18 | runs-on: ubuntu-latest 19 | steps: 20 | - name: Setup | Checkout 21 | uses: actions/checkout@v3 22 | - name: Setup | Rust 23 | uses: dtolnay/rust-toolchain@v1 24 | with: 25 | toolchain: ${{ env.rust_toolchain }} 26 | components: rustfmt, clippy, rust-src 27 | - name: Build | Fmt Check 28 | run: cargo fmt -- --check 29 | - name: Build | Clippy 30 | run: cargo clippy --features experimental -- -Dwarnings 31 | - name: Build | Experimental 32 | run: cargo build --features experimental 33 | - name: Build | Compile / no_std, alloc 34 | run: cargo build --no-default-features --features experimental,alloc,use_serde,use_strum,use_numenum,log 35 | - name: Build | Compile / no_std 36 | run: cargo build --no-default-features --features experimental,use_serde,use_strum,use_numenum,log 37 | - name: Build | Compile / no_std, no serde 38 | run: cargo build --no-default-features --features experimental,use_strum,use_numenum,log 39 | - name: Build | Compile / defmt 40 | run: cargo build --no-default-features --features std,experimental,use_serde,use_strum,use_numenum,defmt 41 | - name: Build | Compile / defmt, no_std 42 | run: cargo build --no-default-features --features experimental,use_serde,use_strum,use_numenum,defmt 43 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "embedded-svc" 3 | version = "0.28.1" 4 | authors = ["Ivan Markov "] 5 | edition = "2021" 6 | resolver = "2" 7 | categories = ["embedded", "hardware-support"] 8 | keywords = ["embedded", "svc", "hal"] 9 | description = "A set of traits for services higher level than embedded-hal and typically found in embedded microcontrollers with WiFi or BLE support." 10 | repository = "https://github.com/esp-rs/embedded-svc" 11 | license = "MIT OR Apache-2.0" 12 | readme = "README.md" 13 | rust-version = "1.77" 14 | 15 | [features] 16 | default = ["std", "use_serde", "use_strum", "use_numenum", "log"] 17 | 18 | std = ["alloc", "embedded-io/std", "embedded-io-async/std", "serde/std", "strum?/std", "num_enum?/std"] 19 | alloc = ["embedded-io/alloc", "embedded-io-async/alloc", "serde/alloc", "defmt?/alloc"] 20 | nightly = [] 21 | experimental = [] 22 | use_serde = ["dep:serde", "enumset/serde", "heapless/serde"] 23 | use_strum = ["strum", "strum_macros"] 24 | use_numenum = ["num_enum"] 25 | defmt = ["dep:defmt", "heapless/defmt-03", "embedded-io/defmt-03", "embedded-io-async/defmt-03"] 26 | 27 | [dependencies] 28 | heapless = { version = "0.8" } 29 | embedded-io = { version = "0.6", default-features = false } 30 | embedded-io-async = { version = "0.6", default-features = false } 31 | log = { version = "0.4", default-features = false, optional = true } 32 | serde = { version = "1", default-features = false, features = ["derive"], optional = true } 33 | enumset = { version = "1", default-features = false } 34 | strum = { version = "0.25", default-features = false, optional = true, features = ["derive"] } 35 | strum_macros = { version = "0.25", optional = true } 36 | num_enum = { version = "0.7", default-features = false, optional = true } 37 | defmt = { version = "0.3", optional = true } 38 | -------------------------------------------------------------------------------- /src/eth.rs: -------------------------------------------------------------------------------- 1 | use core::fmt::Debug; 2 | 3 | pub trait Eth { 4 | type Error: Debug; 5 | 6 | fn start(&mut self) -> Result<(), Self::Error>; 7 | fn stop(&mut self) -> Result<(), Self::Error>; 8 | 9 | fn is_started(&self) -> Result; 10 | fn is_connected(&self) -> Result; 11 | } 12 | 13 | impl Eth for &mut E 14 | where 15 | E: Eth, 16 | { 17 | type Error = E::Error; 18 | 19 | fn start(&mut self) -> Result<(), Self::Error> { 20 | (*self).start() 21 | } 22 | 23 | fn stop(&mut self) -> Result<(), Self::Error> { 24 | (*self).stop() 25 | } 26 | 27 | fn is_started(&self) -> Result { 28 | (**self).is_started() 29 | } 30 | 31 | fn is_connected(&self) -> Result { 32 | (**self).is_connected() 33 | } 34 | } 35 | 36 | pub mod asynch { 37 | use super::*; 38 | 39 | pub trait Eth { 40 | type Error: Debug; 41 | 42 | async fn start(&mut self) -> Result<(), Self::Error>; 43 | async fn stop(&mut self) -> Result<(), Self::Error>; 44 | 45 | async fn is_started(&self) -> Result; 46 | async fn is_connected(&self) -> Result; 47 | } 48 | 49 | impl Eth for &mut E 50 | where 51 | E: Eth, 52 | { 53 | type Error = E::Error; 54 | 55 | async fn start(&mut self) -> Result<(), Self::Error> { 56 | (**self).start().await 57 | } 58 | 59 | async fn stop(&mut self) -> Result<(), Self::Error> { 60 | (**self).stop().await 61 | } 62 | 63 | async fn is_started(&self) -> Result { 64 | (**self).is_started().await 65 | } 66 | 67 | async fn is_connected(&self) -> Result { 68 | (**self).is_connected().await 69 | } 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/channel.rs: -------------------------------------------------------------------------------- 1 | use core::fmt::Debug; 2 | 3 | pub trait ErrorType { 4 | type Error: Debug; 5 | } 6 | 7 | impl ErrorType for &E 8 | where 9 | E: ErrorType, 10 | { 11 | type Error = E::Error; 12 | } 13 | 14 | impl ErrorType for &mut E 15 | where 16 | E: ErrorType, 17 | { 18 | type Error = E::Error; 19 | } 20 | 21 | pub trait Sender: ErrorType { 22 | type Data<'a>; 23 | 24 | fn send(&mut self, value: Self::Data<'_>) -> Result<(), Self::Error>; 25 | } 26 | 27 | impl Sender for &mut S 28 | where 29 | S: Sender, 30 | { 31 | type Data<'a> = S::Data<'a>; 32 | 33 | fn send(&mut self, value: Self::Data<'_>) -> Result<(), Self::Error> { 34 | (**self).send(value) 35 | } 36 | } 37 | 38 | pub trait Receiver: ErrorType { 39 | type Data<'a> 40 | where 41 | Self: 'a; 42 | 43 | fn recv(&mut self) -> Result, Self::Error>; 44 | } 45 | 46 | impl Receiver for &mut R 47 | where 48 | R: Receiver, 49 | { 50 | type Data<'a> 51 | = R::Data<'a> 52 | where 53 | Self: 'a; 54 | 55 | fn recv(&mut self) -> Result, Self::Error> { 56 | (**self).recv() 57 | } 58 | } 59 | 60 | pub mod asynch { 61 | pub use super::ErrorType; 62 | 63 | pub trait Sender: ErrorType { 64 | type Data<'a>: Send; 65 | 66 | async fn send(&mut self, value: Self::Data<'_>) -> Result<(), Self::Error>; 67 | } 68 | 69 | impl Sender for &mut S 70 | where 71 | S: Sender, 72 | { 73 | type Data<'a> = S::Data<'a>; 74 | 75 | async fn send(&mut self, value: Self::Data<'_>) -> Result<(), Self::Error> { 76 | (**self).send(value).await 77 | } 78 | } 79 | 80 | pub trait Receiver: ErrorType { 81 | type Data<'a> 82 | where 83 | Self: 'a; 84 | 85 | async fn recv(&mut self) -> Result, Self::Error>; 86 | } 87 | 88 | impl Receiver for &mut R 89 | where 90 | R: Receiver, 91 | { 92 | type Data<'a> 93 | = R::Data<'a> 94 | where 95 | Self: 'a; 96 | 97 | async fn recv(&mut self) -> Result, Self::Error> { 98 | (**self).recv().await 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/utils/io.rs: -------------------------------------------------------------------------------- 1 | use embedded_io::Error; 2 | 3 | use crate::io::{Read, Write}; 4 | 5 | pub fn try_read_full(mut read: R, buf: &mut [u8]) -> Result { 6 | let mut offset = 0; 7 | let mut size = 0; 8 | 9 | loop { 10 | let size_read = read.read(&mut buf[offset..]).map_err(|e| (e, size))?; 11 | 12 | offset += size_read; 13 | size += size_read; 14 | 15 | if size_read == 0 || size == buf.len() { 16 | break; 17 | } 18 | } 19 | 20 | Ok(size) 21 | } 22 | 23 | #[derive(Debug)] 24 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 25 | pub enum CopyError { 26 | Read(R), 27 | Write(W), 28 | } 29 | 30 | impl core::fmt::Display for CopyError { 31 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 32 | write!(f, "{self:?}") 33 | } 34 | } 35 | 36 | #[cfg(feature = "std")] 37 | #[cfg_attr(docsrs, doc(cfg(feature = "std")))] 38 | impl std::error::Error for CopyError {} 39 | 40 | impl Error for CopyError 41 | where 42 | R: Error, 43 | W: Error, 44 | { 45 | fn kind(&self) -> embedded_io::ErrorKind { 46 | match self { 47 | Self::Read(e) => e.kind(), 48 | Self::Write(e) => e.kind(), 49 | } 50 | } 51 | } 52 | 53 | pub fn copy(read: R, write: W, buf: &mut [u8]) -> Result> 54 | where 55 | R: Read, 56 | W: Write, 57 | { 58 | copy_len(read, write, buf, u64::MAX) 59 | } 60 | 61 | pub fn copy_len( 62 | read: R, 63 | write: W, 64 | buf: &mut [u8], 65 | len: u64, 66 | ) -> Result> 67 | where 68 | R: Read, 69 | W: Write, 70 | { 71 | copy_len_with_progress(read, write, buf, len, |_, _| {}) 72 | } 73 | 74 | pub fn copy_len_with_progress( 75 | mut read: R, 76 | mut write: W, 77 | buf: &mut [u8], 78 | mut len: u64, 79 | progress: P, 80 | ) -> Result> 81 | where 82 | R: Read, 83 | W: Write, 84 | P: Fn(u64, u64), 85 | { 86 | let mut copied = 0; 87 | 88 | while len > 0 { 89 | progress(copied, len); 90 | 91 | let size_read = read.read(buf).map_err(CopyError::Read)?; 92 | if size_read == 0 { 93 | break; 94 | } 95 | 96 | write 97 | .write_all(&buf[0..size_read]) 98 | .map_err(CopyError::Write)?; 99 | 100 | copied += size_read as u64; 101 | len -= size_read as u64; 102 | } 103 | 104 | progress(copied, len); 105 | 106 | Ok(copied) 107 | } 108 | 109 | pub mod asynch { 110 | use crate::io::asynch::{Read, Write}; 111 | 112 | pub use super::CopyError; 113 | 114 | pub async fn try_read_full( 115 | mut read: R, 116 | buf: &mut [u8], 117 | ) -> Result { 118 | let mut offset = 0; 119 | let mut size = 0; 120 | 121 | loop { 122 | let size_read = read.read(&mut buf[offset..]).await.map_err(|e| (e, size))?; 123 | 124 | offset += size_read; 125 | size += size_read; 126 | 127 | if size_read == 0 || size == buf.len() { 128 | break; 129 | } 130 | } 131 | 132 | Ok(size) 133 | } 134 | 135 | pub async fn copy( 136 | read: R, 137 | write: W, 138 | buf: &mut [u8], 139 | ) -> Result> 140 | where 141 | R: Read, 142 | W: Write, 143 | { 144 | copy_len(read, write, buf, u64::MAX).await 145 | } 146 | 147 | pub async fn copy_len( 148 | read: R, 149 | write: W, 150 | buf: &mut [u8], 151 | len: u64, 152 | ) -> Result> 153 | where 154 | R: Read, 155 | W: Write, 156 | { 157 | copy_len_with_progress(read, write, buf, len, |_, _| {}).await 158 | } 159 | 160 | pub async fn copy_len_with_progress( 161 | mut read: R, 162 | mut write: W, 163 | buf: &mut [u8], 164 | mut len: u64, 165 | progress: P, 166 | ) -> Result> 167 | where 168 | R: Read, 169 | W: Write, 170 | P: Fn(u64, u64), 171 | { 172 | let mut copied = 0; 173 | 174 | while len > 0 { 175 | progress(copied, len); 176 | 177 | let size_read = read.read(buf).await.map_err(CopyError::Read)?; 178 | if size_read == 0 { 179 | break; 180 | } 181 | 182 | write 183 | .write_all(&buf[0..size_read]) 184 | .await 185 | .map_err(CopyError::Write)?; 186 | 187 | copied += size_read as u64; 188 | len -= size_read as u64; 189 | } 190 | 191 | progress(copied, len); 192 | 193 | Ok(copied) 194 | } 195 | } 196 | -------------------------------------------------------------------------------- /src/http.rs: -------------------------------------------------------------------------------- 1 | pub mod client; 2 | pub mod server; 3 | 4 | pub mod status { 5 | use core::ops::Range; 6 | 7 | pub const INFO: Range = 100..200; 8 | pub const OK: Range = 200..300; 9 | pub const REDIRECT: Range = 300..400; 10 | pub const CLIENT_ERROR: Range = 400..500; 11 | pub const SERVER_ERROR: Range = 500..600; 12 | } 13 | 14 | #[derive(Copy, Clone, Debug, PartialEq, Eq)] 15 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 16 | #[cfg_attr(feature = "std", derive(Hash))] 17 | pub enum Method { 18 | Delete, 19 | Get, 20 | Head, 21 | Post, 22 | Put, 23 | Connect, 24 | Options, 25 | Trace, 26 | Copy, 27 | Lock, 28 | MkCol, 29 | Move, 30 | Propfind, 31 | Proppatch, 32 | Search, 33 | Unlock, 34 | Bind, 35 | Rebind, 36 | Unbind, 37 | Acl, 38 | Report, 39 | MkActivity, 40 | Checkout, 41 | Merge, 42 | MSearch, 43 | Notify, 44 | Subscribe, 45 | Unsubscribe, 46 | Patch, 47 | Purge, 48 | MkCalendar, 49 | Link, 50 | Unlink, 51 | } 52 | 53 | pub trait Headers { 54 | fn header(&self, name: &str) -> Option<&'_ str>; 55 | 56 | fn content_type(&self) -> Option<&'_ str> { 57 | self.header("Content-Type") 58 | } 59 | 60 | fn content_len(&self) -> Option { 61 | self.header("Content-Length") 62 | .and_then(|v| v.parse::().ok()) 63 | } 64 | 65 | fn content_encoding(&self) -> Option<&'_ str> { 66 | self.header("Content-Encoding") 67 | } 68 | 69 | fn transfer_encoding(&self) -> Option<&'_ str> { 70 | self.header("Transfer-Encoding") 71 | } 72 | 73 | fn host(&self) -> Option<&'_ str> { 74 | self.header("Host") 75 | } 76 | 77 | fn connection(&self) -> Option<&'_ str> { 78 | self.header("Connection") 79 | } 80 | 81 | fn cache_control(&self) -> Option<&'_ str> { 82 | self.header("Cache-Control") 83 | } 84 | 85 | fn upgrade(&self) -> Option<&'_ str> { 86 | self.header("Upgrade") 87 | } 88 | } 89 | 90 | impl Headers for &H 91 | where 92 | H: Headers, 93 | { 94 | fn header(&self, name: &str) -> Option<&'_ str> { 95 | (*self).header(name) 96 | } 97 | } 98 | 99 | impl Headers for &mut H 100 | where 101 | H: Headers, 102 | { 103 | fn header(&self, name: &str) -> Option<&'_ str> { 104 | (**self).header(name) 105 | } 106 | } 107 | 108 | pub trait Status { 109 | fn status(&self) -> u16; 110 | 111 | fn status_message(&self) -> Option<&'_ str>; 112 | } 113 | 114 | impl Status for &S 115 | where 116 | S: Status, 117 | { 118 | fn status(&self) -> u16 { 119 | (*self).status() 120 | } 121 | 122 | fn status_message(&self) -> Option<&'_ str> { 123 | (*self).status_message() 124 | } 125 | } 126 | 127 | impl Status for &mut S 128 | where 129 | S: Status, 130 | { 131 | fn status(&self) -> u16 { 132 | (**self).status() 133 | } 134 | 135 | fn status_message(&self) -> Option<&'_ str> { 136 | (**self).status_message() 137 | } 138 | } 139 | 140 | pub trait Query { 141 | fn uri(&self) -> &'_ str; 142 | 143 | fn method(&self) -> Method; 144 | } 145 | 146 | impl Query for &Q 147 | where 148 | Q: Query, 149 | { 150 | fn uri(&self) -> &'_ str { 151 | (*self).uri() 152 | } 153 | 154 | fn method(&self) -> Method { 155 | (*self).method() 156 | } 157 | } 158 | 159 | impl Query for &mut Q 160 | where 161 | Q: Query, 162 | { 163 | fn uri(&self) -> &'_ str { 164 | (**self).uri() 165 | } 166 | 167 | fn method(&self) -> Method { 168 | (**self).method() 169 | } 170 | } 171 | 172 | pub mod headers { 173 | pub type ContentLenParseBuf = heapless::String<20>; 174 | 175 | pub fn content_type(ctype: &str) -> (&str, &str) { 176 | ("Content-Type", ctype) 177 | } 178 | 179 | pub fn content_len(len: u64, buf: &mut ContentLenParseBuf) -> (&str, &str) { 180 | *buf = ContentLenParseBuf::try_from(len).unwrap(); 181 | 182 | ("Content-Length", buf.as_str()) 183 | } 184 | 185 | pub fn content_encoding(encoding: &str) -> (&str, &str) { 186 | ("Content-Encoding", encoding) 187 | } 188 | 189 | pub fn transfer_encoding(encoding: &str) -> (&str, &str) { 190 | ("Transfer-Encoding", encoding) 191 | } 192 | 193 | pub fn transfer_encoding_chunked<'a>() -> (&'a str, &'a str) { 194 | transfer_encoding("Chunked") 195 | } 196 | 197 | pub fn host(host: &str) -> (&str, &str) { 198 | ("Host", host) 199 | } 200 | 201 | pub fn connection(connection: &str) -> (&str, &str) { 202 | ("Connection", connection) 203 | } 204 | 205 | pub fn connection_upgrade<'a>() -> (&'a str, &'a str) { 206 | connection("Upgrade") 207 | } 208 | 209 | pub fn connection_keepalive<'a>() -> (&'a str, &'a str) { 210 | connection("Keep-Alive") 211 | } 212 | 213 | pub fn connection_close<'a>() -> (&'a str, &'a str) { 214 | connection("Close") 215 | } 216 | 217 | pub fn cache_control(cache: &str) -> (&str, &str) { 218 | ("Cache-Control", cache) 219 | } 220 | 221 | pub fn cache_control_no_cache<'a>() -> (&'a str, &'a str) { 222 | cache_control("No-Cache") 223 | } 224 | 225 | pub fn location(location: &str) -> (&str, &str) { 226 | ("Location", location) 227 | } 228 | 229 | pub fn upgrade(upgrade: &str) -> (&str, &str) { 230 | ("Upgrade", upgrade) 231 | } 232 | 233 | pub fn upgrade_websocket<'a>() -> (&'a str, &'a str) { 234 | upgrade("websocket") 235 | } 236 | } 237 | 238 | pub mod asynch { 239 | pub use super::*; 240 | } 241 | -------------------------------------------------------------------------------- /src/ws.rs: -------------------------------------------------------------------------------- 1 | use core::fmt::Debug; 2 | 3 | pub trait ErrorType { 4 | type Error: Debug; 5 | } 6 | 7 | impl ErrorType for &E 8 | where 9 | E: ErrorType, 10 | { 11 | type Error = E::Error; 12 | } 13 | 14 | impl ErrorType for &mut E 15 | where 16 | E: ErrorType, 17 | { 18 | type Error = E::Error; 19 | } 20 | 21 | pub type Fragmented = bool; 22 | pub type Final = bool; 23 | 24 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] 25 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 26 | pub enum FrameType { 27 | Text(Fragmented), 28 | Binary(Fragmented), 29 | Ping, 30 | Pong, 31 | Close, 32 | SocketClose, 33 | Continue(Final), 34 | } 35 | 36 | impl FrameType { 37 | pub fn is_fragmented(&self) -> bool { 38 | match self { 39 | Self::Text(fragmented) | Self::Binary(fragmented) => *fragmented, 40 | Self::Continue(_) => true, 41 | _ => false, 42 | } 43 | } 44 | 45 | pub fn is_final(&self) -> bool { 46 | match self { 47 | Self::Text(fragmented) | Self::Binary(fragmented) => !*fragmented, 48 | Self::Continue(final_) => *final_, 49 | _ => true, 50 | } 51 | } 52 | } 53 | 54 | pub trait Receiver: ErrorType { 55 | fn recv(&mut self, frame_data_buf: &mut [u8]) -> Result<(FrameType, usize), Self::Error>; 56 | } 57 | 58 | impl Receiver for &mut R 59 | where 60 | R: Receiver, 61 | { 62 | fn recv(&mut self, frame_data_buf: &mut [u8]) -> Result<(FrameType, usize), Self::Error> { 63 | (*self).recv(frame_data_buf) 64 | } 65 | } 66 | 67 | pub trait Sender: ErrorType { 68 | fn send(&mut self, frame_type: FrameType, frame_data: &[u8]) -> Result<(), Self::Error>; 69 | } 70 | 71 | impl Sender for &mut S 72 | where 73 | S: Sender, 74 | { 75 | fn send(&mut self, frame_type: FrameType, frame_data: &[u8]) -> Result<(), Self::Error> { 76 | (*self).send(frame_type, frame_data) 77 | } 78 | } 79 | 80 | pub mod server { 81 | pub use super::*; 82 | 83 | pub trait Acceptor: ErrorType { 84 | type Connection<'a>: Sender + Receiver 85 | where 86 | Self: 'a; 87 | 88 | fn accept(&self) -> Result, Self::Error>; 89 | } 90 | 91 | impl Acceptor for &A 92 | where 93 | A: Acceptor, 94 | { 95 | type Connection<'a> 96 | = A::Connection<'a> 97 | where 98 | Self: 'a; 99 | 100 | fn accept(&self) -> Result, Self::Error> { 101 | (*self).accept() 102 | } 103 | } 104 | 105 | impl Acceptor for &mut A 106 | where 107 | A: Acceptor, 108 | { 109 | type Connection<'a> 110 | = A::Connection<'a> 111 | where 112 | Self: 'a; 113 | 114 | fn accept(&self) -> Result, Self::Error> { 115 | (**self).accept() 116 | } 117 | } 118 | } 119 | 120 | pub mod asynch { 121 | pub use super::{ErrorType, Fragmented, FrameType}; 122 | 123 | pub trait Receiver: ErrorType { 124 | async fn recv( 125 | &mut self, 126 | frame_data_buf: &mut [u8], 127 | ) -> Result<(FrameType, usize), Self::Error>; 128 | } 129 | 130 | impl Receiver for &mut R 131 | where 132 | R: Receiver, 133 | { 134 | async fn recv( 135 | &mut self, 136 | frame_data_buf: &mut [u8], 137 | ) -> Result<(FrameType, usize), Self::Error> { 138 | (*self).recv(frame_data_buf).await 139 | } 140 | } 141 | 142 | pub trait Sender: ErrorType { 143 | async fn send( 144 | &mut self, 145 | frame_type: FrameType, 146 | frame_data: &[u8], 147 | ) -> Result<(), Self::Error>; 148 | } 149 | 150 | impl Sender for &mut S 151 | where 152 | S: Sender, 153 | { 154 | async fn send( 155 | &mut self, 156 | frame_type: FrameType, 157 | frame_data: &[u8], 158 | ) -> Result<(), Self::Error> { 159 | (*self).send(frame_type, frame_data).await 160 | } 161 | } 162 | 163 | pub mod server { 164 | pub use super::*; 165 | 166 | pub trait Acceptor: ErrorType { 167 | type Sender<'a>: Sender 168 | where 169 | Self: 'a; 170 | type Receiver<'a>: Receiver 171 | where 172 | Self: 'a; 173 | 174 | async fn accept(&self) -> Result<(Self::Sender<'_>, Self::Receiver<'_>), Self::Error>; 175 | } 176 | 177 | impl Acceptor for &A 178 | where 179 | A: Acceptor, 180 | { 181 | type Sender<'a> 182 | = A::Sender<'a> 183 | where 184 | Self: 'a; 185 | type Receiver<'a> 186 | = A::Receiver<'a> 187 | where 188 | Self: 'a; 189 | 190 | async fn accept(&self) -> Result<(Self::Sender<'_>, Self::Receiver<'_>), Self::Error> { 191 | (*self).accept().await 192 | } 193 | } 194 | 195 | impl Acceptor for &mut A 196 | where 197 | A: Acceptor, 198 | { 199 | type Sender<'a> 200 | = A::Sender<'a> 201 | where 202 | Self: 'a; 203 | type Receiver<'a> 204 | = A::Receiver<'a> 205 | where 206 | Self: 'a; 207 | 208 | async fn accept(&self) -> Result<(Self::Sender<'_>, Self::Receiver<'_>), Self::Error> { 209 | (**self).accept().await 210 | } 211 | } 212 | } 213 | } 214 | -------------------------------------------------------------------------------- /src/storage.rs: -------------------------------------------------------------------------------- 1 | use core::any::Any; 2 | use core::fmt::{self, Debug}; 3 | 4 | #[cfg(feature = "use_serde")] 5 | use serde::{de::DeserializeOwned, Serialize}; 6 | 7 | pub trait StorageBase { 8 | type Error: Debug; 9 | 10 | fn contains(&self, name: &str) -> Result; 11 | fn remove(&mut self, name: &str) -> Result; 12 | } 13 | 14 | impl StorageBase for &mut S 15 | where 16 | S: StorageBase, 17 | { 18 | type Error = S::Error; 19 | 20 | fn contains(&self, name: &str) -> Result { 21 | (**self).contains(name) 22 | } 23 | 24 | fn remove(&mut self, name: &str) -> Result { 25 | (*self).remove(name) 26 | } 27 | } 28 | 29 | #[cfg(feature = "use_serde")] 30 | pub trait Storage: StorageBase { 31 | fn get(&self, name: &str) -> Result, Self::Error> 32 | where 33 | T: serde::de::DeserializeOwned; 34 | 35 | fn set(&mut self, name: &str, value: &T) -> Result 36 | where 37 | T: serde::Serialize; 38 | } 39 | 40 | #[cfg(feature = "use_serde")] 41 | impl Storage for &mut S 42 | where 43 | S: Storage, 44 | { 45 | fn get(&self, name: &str) -> Result, Self::Error> 46 | where 47 | T: serde::de::DeserializeOwned, 48 | { 49 | (**self).get(name) 50 | } 51 | 52 | fn set(&mut self, name: &str, value: &T) -> Result 53 | where 54 | T: serde::Serialize, 55 | { 56 | (*self).set(name, value) 57 | } 58 | } 59 | 60 | pub trait DynStorage<'a>: StorageBase { 61 | fn get(&self, name: &str) -> Result, Self::Error>; 62 | 63 | fn set(&mut self, name: &'a str, value: &'a dyn Any) -> Result; 64 | } 65 | 66 | impl<'a, D> DynStorage<'a> for &'a mut D 67 | where 68 | D: DynStorage<'a>, 69 | { 70 | fn get(&self, name: &str) -> Result, Self::Error> { 71 | (**self).get(name) 72 | } 73 | 74 | fn set(&mut self, name: &'a str, value: &'a dyn Any) -> Result { 75 | (*self).set(name, value) 76 | } 77 | } 78 | 79 | pub trait RawStorage: StorageBase { 80 | fn len(&self, name: &str) -> Result, Self::Error>; 81 | 82 | fn get_raw<'a>(&self, name: &str, buf: &'a mut [u8]) -> Result, Self::Error>; 83 | 84 | fn set_raw(&mut self, name: &str, buf: &[u8]) -> Result; 85 | } 86 | 87 | impl RawStorage for &mut R 88 | where 89 | R: RawStorage, 90 | { 91 | fn len(&self, name: &str) -> Result, Self::Error> { 92 | (**self).len(name) 93 | } 94 | 95 | fn get_raw<'a>(&self, name: &str, buf: &'a mut [u8]) -> Result, Self::Error> { 96 | (**self).get_raw(name, buf) 97 | } 98 | 99 | fn set_raw(&mut self, name: &str, buf: &[u8]) -> Result { 100 | (**self).set_raw(name, buf) 101 | } 102 | } 103 | 104 | #[cfg(feature = "use_serde")] 105 | pub trait SerDe { 106 | type Error: Debug; 107 | 108 | fn serialize<'a, T>(&self, slice: &'a mut [u8], value: &T) -> Result<&'a [u8], Self::Error> 109 | where 110 | T: Serialize; 111 | 112 | fn deserialize(&self, slice: &[u8]) -> Result 113 | where 114 | T: DeserializeOwned; 115 | } 116 | 117 | #[cfg(feature = "use_serde")] 118 | impl SerDe for &S 119 | where 120 | S: SerDe, 121 | { 122 | type Error = S::Error; 123 | 124 | fn serialize<'a, T>(&self, slice: &'a mut [u8], value: &T) -> Result<&'a [u8], Self::Error> 125 | where 126 | T: Serialize, 127 | { 128 | (*self).serialize(slice, value) 129 | } 130 | 131 | fn deserialize(&self, slice: &[u8]) -> Result 132 | where 133 | T: DeserializeOwned, 134 | { 135 | (*self).deserialize(slice) 136 | } 137 | } 138 | 139 | #[derive(Debug)] 140 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 141 | pub enum StorageError { 142 | RawStorageError(R), 143 | SerdeError(S), 144 | } 145 | 146 | impl fmt::Display for StorageError 147 | where 148 | R: fmt::Display, 149 | S: fmt::Display, 150 | { 151 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 152 | match self { 153 | Self::RawStorageError(e) => write!(f, "Storage error: {e}"), 154 | Self::SerdeError(e) => write!(f, "SerDe error: {e}"), 155 | } 156 | } 157 | } 158 | 159 | #[cfg(feature = "std")] 160 | impl std::error::Error for StorageError 161 | where 162 | R: std::error::Error, 163 | S: std::error::Error, 164 | { 165 | } 166 | 167 | #[cfg(feature = "use_serde")] 168 | pub struct StorageImpl { 169 | raw_storage: R, 170 | serde: S, 171 | } 172 | 173 | #[cfg(feature = "use_serde")] 174 | impl StorageImpl 175 | where 176 | R: RawStorage, 177 | S: SerDe, 178 | { 179 | pub const fn new(raw_storage: R, serde: S) -> Self { 180 | Self { raw_storage, serde } 181 | } 182 | 183 | pub fn raw_storage(&self) -> &R { 184 | &self.raw_storage 185 | } 186 | 187 | pub fn raw_storage_mut(&mut self) -> &mut R { 188 | &mut self.raw_storage 189 | } 190 | 191 | pub fn contains(&self, name: &str) -> Result> { 192 | self.raw_storage 193 | .contains(name) 194 | .map_err(StorageError::RawStorageError) 195 | } 196 | 197 | pub fn remove(&mut self, name: &str) -> Result> { 198 | self.raw_storage 199 | .remove(name) 200 | .map_err(StorageError::RawStorageError) 201 | } 202 | 203 | pub fn get(&self, name: &str) -> Result, StorageError> 204 | where 205 | T: DeserializeOwned, 206 | { 207 | let mut buf = [0_u8; N]; 208 | 209 | if let Some(buf) = self 210 | .raw_storage 211 | .get_raw(name, &mut buf) 212 | .map_err(StorageError::RawStorageError)? 213 | { 214 | Ok(Some( 215 | self.serde 216 | .deserialize(buf) 217 | .map_err(StorageError::SerdeError)?, 218 | )) 219 | } else { 220 | Ok(None) 221 | } 222 | } 223 | 224 | pub fn set( 225 | &mut self, 226 | name: &str, 227 | value: &T, 228 | ) -> Result> 229 | where 230 | T: Serialize, 231 | { 232 | let mut buf = [0_u8; N]; 233 | 234 | let buf = self 235 | .serde 236 | .serialize(&mut buf, value) 237 | .map_err(StorageError::SerdeError)?; 238 | 239 | self.raw_storage 240 | .set_raw(name, buf) 241 | .map_err(StorageError::RawStorageError) 242 | } 243 | } 244 | 245 | #[cfg(feature = "use_serde")] 246 | impl StorageBase for StorageImpl 247 | where 248 | R: RawStorage, 249 | S: SerDe, 250 | { 251 | type Error = StorageError; 252 | 253 | fn contains(&self, name: &str) -> Result { 254 | StorageImpl::contains(self, name) 255 | } 256 | 257 | fn remove(&mut self, name: &str) -> Result { 258 | StorageImpl::remove(self, name) 259 | } 260 | } 261 | 262 | #[cfg(feature = "use_serde")] 263 | impl Storage for StorageImpl 264 | where 265 | R: RawStorage, 266 | S: SerDe, 267 | { 268 | fn get(&self, name: &str) -> Result, Self::Error> 269 | where 270 | T: DeserializeOwned, 271 | { 272 | StorageImpl::get(self, name) 273 | } 274 | 275 | fn set(&mut self, name: &str, value: &T) -> Result 276 | where 277 | T: Serialize, 278 | { 279 | StorageImpl::set(self, name, value) 280 | } 281 | } 282 | -------------------------------------------------------------------------------- /src/mqtt/client.rs: -------------------------------------------------------------------------------- 1 | use core::fmt::{self, Debug, Display, Formatter}; 2 | 3 | #[cfg(feature = "alloc")] 4 | extern crate alloc; 5 | 6 | #[cfg(feature = "use_serde")] 7 | use serde::{Deserialize, Serialize}; 8 | 9 | pub trait ErrorType { 10 | type Error: Debug; 11 | } 12 | 13 | impl ErrorType for &E 14 | where 15 | E: ErrorType, 16 | { 17 | type Error = E::Error; 18 | } 19 | 20 | impl ErrorType for &mut E 21 | where 22 | E: ErrorType, 23 | { 24 | type Error = E::Error; 25 | } 26 | 27 | /// Quality of service 28 | #[repr(u8)] 29 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd)] 30 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 31 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 32 | pub enum QoS { 33 | AtMostOnce = 0, 34 | AtLeastOnce = 1, 35 | ExactlyOnce = 2, 36 | } 37 | 38 | pub type MessageId = u32; 39 | 40 | pub trait Event: ErrorType { 41 | fn payload(&self) -> EventPayload<'_, Self::Error>; 42 | } 43 | 44 | impl Event for &E 45 | where 46 | E: Event, 47 | { 48 | fn payload(&self) -> EventPayload<'_, Self::Error> { 49 | (*self).payload() 50 | } 51 | } 52 | 53 | impl Event for &mut E 54 | where 55 | E: Event, 56 | { 57 | fn payload(&self) -> EventPayload<'_, Self::Error> { 58 | (**self).payload() 59 | } 60 | } 61 | 62 | #[derive(Clone, PartialEq, Eq, Debug)] 63 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 64 | pub enum EventPayload<'a, E> { 65 | BeforeConnect, 66 | Connected(bool), 67 | Disconnected, 68 | Subscribed(MessageId), 69 | Unsubscribed(MessageId), 70 | Published(MessageId), 71 | Received { 72 | id: MessageId, 73 | topic: Option<&'a str>, 74 | data: &'a [u8], 75 | details: Details, 76 | }, 77 | Deleted(MessageId), 78 | Error(&'a E), 79 | } 80 | 81 | impl Display for EventPayload<'_, E> 82 | where 83 | E: Debug, 84 | { 85 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 86 | match self { 87 | Self::BeforeConnect => write!(f, "BeforeConnect"), 88 | Self::Connected(session_present) => write!(f, "Connected(session: {session_present})"), 89 | Self::Disconnected => write!(f, "Disconnected"), 90 | Self::Subscribed(message_id) => write!(f, "Subscribed({message_id})"), 91 | Self::Unsubscribed(message_id) => write!(f, "Unsubscribed({message_id})"), 92 | Self::Published(message_id) => write!(f, "Published({message_id})"), 93 | Self::Received { 94 | id, 95 | topic, 96 | data, 97 | details, 98 | } => write!( 99 | f, 100 | "Received {{ id: {id}, topic: {topic:?}, data: {:?}, details: {details:?} }}", 101 | core::str::from_utf8(data), 102 | ), 103 | Self::Deleted(message_id) => write!(f, "Deleted({message_id})"), 104 | Self::Error(error) => write!(f, "Error({error:?})"), 105 | } 106 | } 107 | } 108 | 109 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] 110 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 111 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 112 | pub enum Details { 113 | Complete, 114 | InitialChunk(InitialChunkData), 115 | SubsequentChunk(SubsequentChunkData), 116 | } 117 | 118 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] 119 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 120 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 121 | pub struct InitialChunkData { 122 | pub total_data_size: usize, 123 | } 124 | 125 | #[derive(Debug, Copy, Clone, PartialEq, Eq)] 126 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 127 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 128 | pub struct SubsequentChunkData { 129 | pub current_data_offset: usize, 130 | pub total_data_size: usize, 131 | } 132 | 133 | pub trait Client: ErrorType { 134 | fn subscribe<'a>(&'a mut self, topic: &'a str, qos: QoS) -> Result; 135 | 136 | fn unsubscribe<'a>(&'a mut self, topic: &'a str) -> Result; 137 | } 138 | 139 | impl Client for &mut C 140 | where 141 | C: Client, 142 | { 143 | fn subscribe<'a>(&'a mut self, topic: &'a str, qos: QoS) -> Result { 144 | (*self).subscribe(topic, qos) 145 | } 146 | 147 | fn unsubscribe<'a>(&'a mut self, topic: &'a str) -> Result { 148 | (*self).unsubscribe(topic) 149 | } 150 | } 151 | 152 | pub trait Publish: ErrorType { 153 | fn publish<'a>( 154 | &'a mut self, 155 | topic: &'a str, 156 | qos: QoS, 157 | retain: bool, 158 | payload: &'a [u8], 159 | ) -> Result; 160 | } 161 | 162 | impl

Publish for &mut P 163 | where 164 | P: Publish, 165 | { 166 | fn publish<'a>( 167 | &'a mut self, 168 | topic: &'a str, 169 | qos: QoS, 170 | retain: bool, 171 | payload: &'a [u8], 172 | ) -> Result { 173 | (*self).publish(topic, qos, retain, payload) 174 | } 175 | } 176 | 177 | pub trait Enqueue: ErrorType { 178 | fn enqueue<'a>( 179 | &'a mut self, 180 | topic: &'a str, 181 | qos: QoS, 182 | retain: bool, 183 | payload: &'a [u8], 184 | ) -> Result; 185 | } 186 | 187 | impl Enqueue for &mut E 188 | where 189 | E: Enqueue, 190 | { 191 | fn enqueue<'a>( 192 | &'a mut self, 193 | topic: &'a str, 194 | qos: QoS, 195 | retain: bool, 196 | payload: &'a [u8], 197 | ) -> Result { 198 | (*self).enqueue(topic, qos, retain, payload) 199 | } 200 | } 201 | 202 | pub trait Connection: ErrorType { 203 | type Event<'a>: Event 204 | where 205 | Self: 'a; 206 | 207 | fn next(&mut self) -> Result, Self::Error>; 208 | } 209 | 210 | impl Connection for &mut C 211 | where 212 | C: Connection, 213 | { 214 | type Event<'a> 215 | = C::Event<'a> 216 | where 217 | Self: 'a; 218 | 219 | fn next(&mut self) -> Result, Self::Error> { 220 | (*self).next() 221 | } 222 | } 223 | 224 | pub mod asynch { 225 | pub use super::{Details, ErrorType, Event, EventPayload, MessageId, QoS}; 226 | 227 | pub trait Client: ErrorType { 228 | async fn subscribe(&mut self, topic: &str, qos: QoS) -> Result; 229 | 230 | async fn unsubscribe(&mut self, topic: &str) -> Result; 231 | } 232 | 233 | impl Client for &mut C 234 | where 235 | C: Client, 236 | { 237 | async fn subscribe(&mut self, topic: &str, qos: QoS) -> Result { 238 | (*self).subscribe(topic, qos).await 239 | } 240 | 241 | async fn unsubscribe(&mut self, topic: &str) -> Result { 242 | (*self).unsubscribe(topic).await 243 | } 244 | } 245 | 246 | pub trait Publish: ErrorType { 247 | async fn publish( 248 | &mut self, 249 | topic: &str, 250 | qos: QoS, 251 | retain: bool, 252 | payload: &[u8], 253 | ) -> Result; 254 | } 255 | 256 | impl

Publish for &mut P 257 | where 258 | P: Publish, 259 | { 260 | async fn publish( 261 | &mut self, 262 | topic: &str, 263 | qos: QoS, 264 | retain: bool, 265 | payload: &[u8], 266 | ) -> Result { 267 | (*self).publish(topic, qos, retain, payload).await 268 | } 269 | } 270 | 271 | pub trait Connection: ErrorType { 272 | type Event<'a>: Event 273 | where 274 | Self: 'a; 275 | 276 | async fn next(&mut self) -> Result, Self::Error>; 277 | } 278 | 279 | impl Connection for &mut C 280 | where 281 | C: Connection, 282 | { 283 | type Event<'a> 284 | = C::Event<'a> 285 | where 286 | Self: 'a; 287 | 288 | async fn next(&mut self) -> Result, Self::Error> { 289 | (*self).next().await 290 | } 291 | } 292 | } 293 | -------------------------------------------------------------------------------- /src/ota.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "use_serde")] 2 | use serde::{Deserialize, Serialize}; 3 | 4 | use crate::io::{ErrorType, Read, Write}; 5 | use crate::utils::io::*; 6 | 7 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] 8 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 9 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 10 | pub struct Slot { 11 | pub label: heapless::String<32>, 12 | pub state: SlotState, 13 | pub firmware: Option, 14 | } 15 | 16 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] 17 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 18 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 19 | pub struct FirmwareInfo { 20 | pub version: heapless::String<24>, 21 | pub released: heapless::String<24>, 22 | pub description: Option>, 23 | pub signature: Option>, 24 | pub download_id: Option>, 25 | } 26 | 27 | #[derive(Clone, Debug)] 28 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 29 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 30 | pub struct UpdateProgress { 31 | pub progress: u32, 32 | pub operation: &'static str, 33 | } 34 | 35 | #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] 36 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 37 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 38 | pub enum LoadResult { 39 | ReloadMore, 40 | LoadMore, 41 | Loaded, 42 | } 43 | 44 | #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] 45 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 46 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 47 | pub enum SlotState { 48 | Factory, 49 | Valid, 50 | Invalid, 51 | Unverified, 52 | Unknown, 53 | } 54 | 55 | pub trait FirmwareInfoLoader: ErrorType { 56 | fn load(&mut self, buf: &[u8]) -> Result; 57 | 58 | fn is_loaded(&self) -> bool; 59 | 60 | fn get_info(&self) -> Result; 61 | } 62 | 63 | impl FirmwareInfoLoader for &mut F 64 | where 65 | F: FirmwareInfoLoader, 66 | { 67 | fn load(&mut self, buf: &[u8]) -> Result { 68 | (*self).load(buf) 69 | } 70 | 71 | fn is_loaded(&self) -> bool { 72 | (**self).is_loaded() 73 | } 74 | 75 | fn get_info(&self) -> Result { 76 | (**self).get_info() 77 | } 78 | } 79 | 80 | pub trait Ota: ErrorType { 81 | type Update<'a>: OtaUpdate 82 | where 83 | Self: 'a; 84 | 85 | fn get_boot_slot(&self) -> Result; 86 | 87 | fn get_running_slot(&self) -> Result; 88 | 89 | fn get_update_slot(&self) -> Result; 90 | 91 | fn is_factory_reset_supported(&self) -> Result; 92 | 93 | fn factory_reset(&mut self) -> Result<(), Self::Error>; 94 | 95 | fn initiate_update(&mut self) -> Result, Self::Error>; 96 | 97 | fn mark_running_slot_valid(&mut self) -> Result<(), Self::Error>; 98 | 99 | fn mark_running_slot_invalid_and_reboot(&mut self) -> Self::Error; 100 | } 101 | 102 | impl Ota for &mut O 103 | where 104 | O: Ota, 105 | { 106 | type Update<'a> 107 | = O::Update<'a> 108 | where 109 | Self: 'a; 110 | 111 | fn get_boot_slot(&self) -> Result { 112 | (**self).get_boot_slot() 113 | } 114 | 115 | fn get_running_slot(&self) -> Result { 116 | (**self).get_running_slot() 117 | } 118 | 119 | fn get_update_slot(&self) -> Result { 120 | (**self).get_update_slot() 121 | } 122 | 123 | fn is_factory_reset_supported(&self) -> Result { 124 | (**self).is_factory_reset_supported() 125 | } 126 | 127 | fn factory_reset(&mut self) -> Result<(), Self::Error> { 128 | (*self).factory_reset() 129 | } 130 | 131 | fn initiate_update(&mut self) -> Result, Self::Error> { 132 | (*self).initiate_update() 133 | } 134 | 135 | fn mark_running_slot_valid(&mut self) -> Result<(), Self::Error> { 136 | (*self).mark_running_slot_valid() 137 | } 138 | 139 | fn mark_running_slot_invalid_and_reboot(&mut self) -> Self::Error { 140 | (*self).mark_running_slot_invalid_and_reboot() 141 | } 142 | } 143 | 144 | pub trait OtaUpdate: Write { 145 | type OtaUpdateFinished: OtaUpdateFinished; 146 | 147 | fn finish(self) -> Result; 148 | 149 | fn complete(self) -> Result<(), Self::Error>; 150 | 151 | fn abort(self) -> Result<(), Self::Error>; 152 | 153 | fn update( 154 | mut self, 155 | read: R, 156 | progress: impl Fn(u64, u64), 157 | ) -> Result<(), CopyError> 158 | where 159 | R: Read, 160 | Self: Sized, 161 | { 162 | let mut buf = [0_u8; 64]; 163 | 164 | match copy_len_with_progress(read, &mut self, &mut buf, u64::MAX, progress) { 165 | Ok(_) => self.complete().map_err(CopyError::Write), 166 | Err(e) => { 167 | self.abort().map_err(CopyError::Write)?; 168 | 169 | Err(e) 170 | } 171 | } 172 | } 173 | } 174 | 175 | pub trait OtaUpdateFinished: ErrorType { 176 | fn activate(self) -> Result<(), Self::Error>; 177 | } 178 | 179 | pub mod asynch { 180 | use crate::io::asynch::{ErrorType, Read, Write}; 181 | use crate::utils::io::asynch::*; 182 | 183 | pub use super::{FirmwareInfo, FirmwareInfoLoader, LoadResult, Slot, SlotState}; 184 | 185 | pub trait Ota: ErrorType { 186 | type Update<'a>: OtaUpdate 187 | where 188 | Self: 'a; 189 | 190 | async fn get_boot_slot(&self) -> Result; 191 | 192 | async fn get_running_slot(&self) -> Result; 193 | 194 | async fn get_update_slot(&self) -> Result; 195 | 196 | async fn is_factory_reset_supported(&self) -> Result; 197 | 198 | async fn factory_reset(&mut self) -> Result<(), Self::Error>; 199 | 200 | async fn initiate_update(&mut self) -> Result, Self::Error>; 201 | 202 | async fn mark_running_slot_valid(&mut self) -> Result<(), Self::Error>; 203 | 204 | async fn mark_running_slot_invalid_and_reboot(&mut self) -> Self::Error; 205 | } 206 | 207 | impl Ota for &mut O 208 | where 209 | O: Ota, 210 | { 211 | type Update<'a> 212 | = O::Update<'a> 213 | where 214 | Self: 'a; 215 | 216 | async fn get_boot_slot(&self) -> Result { 217 | (**self).get_boot_slot().await 218 | } 219 | 220 | async fn get_running_slot(&self) -> Result { 221 | (**self).get_running_slot().await 222 | } 223 | 224 | async fn get_update_slot(&self) -> Result { 225 | (**self).get_update_slot().await 226 | } 227 | 228 | async fn is_factory_reset_supported(&self) -> Result { 229 | (**self).is_factory_reset_supported().await 230 | } 231 | 232 | async fn factory_reset(&mut self) -> Result<(), Self::Error> { 233 | (*self).factory_reset().await 234 | } 235 | 236 | async fn initiate_update(&mut self) -> Result, Self::Error> { 237 | (*self).initiate_update().await 238 | } 239 | 240 | async fn mark_running_slot_valid(&mut self) -> Result<(), Self::Error> { 241 | (*self).mark_running_slot_valid().await 242 | } 243 | 244 | async fn mark_running_slot_invalid_and_reboot(&mut self) -> Self::Error { 245 | (*self).mark_running_slot_invalid_and_reboot().await 246 | } 247 | } 248 | 249 | pub trait OtaUpdate: Write { 250 | type OtaUpdateFinished: OtaUpdateFinished; 251 | 252 | async fn finish(self) -> Result; 253 | 254 | async fn complete(self) -> Result<(), Self::Error>; 255 | 256 | async fn abort(self) -> Result<(), Self::Error>; 257 | 258 | async fn update( 259 | self, 260 | read: R, 261 | progress: impl Fn(u64, u64), 262 | ) -> Result<(), CopyError> 263 | where 264 | R: Read, 265 | Self: Sized; 266 | } 267 | 268 | pub trait OtaUpdateFinished: ErrorType { 269 | async fn activate(self) -> Result<(), Self::Error>; 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /src/ipv4.rs: -------------------------------------------------------------------------------- 1 | use core::fmt::Display; 2 | use core::str::FromStr; 3 | 4 | /// For backwards compatibility. Might be removed in future versions. 5 | pub use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6}; 6 | 7 | #[cfg(feature = "use_serde")] 8 | use serde::{Deserialize, Serialize}; 9 | 10 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 11 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 12 | #[cfg_attr(feature = "std", derive(Hash))] 13 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 14 | pub struct Mask(pub u8); 15 | 16 | impl FromStr for Mask { 17 | type Err = &'static str; 18 | 19 | fn from_str(s: &str) -> Result { 20 | s.parse::() 21 | .map_err(|_| "Invalid subnet mask") 22 | .map_or_else(Err, |mask| { 23 | if (1..=32).contains(&mask) { 24 | Ok(Mask(mask)) 25 | } else { 26 | Err("Mask should be a number between 1 and 32") 27 | } 28 | }) 29 | } 30 | } 31 | 32 | impl Display for Mask { 33 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 34 | write!(f, "{}", self.0) 35 | } 36 | } 37 | 38 | impl TryFrom for Mask { 39 | type Error = (); 40 | 41 | fn try_from(ip: Ipv4Addr) -> Result { 42 | let octets = ip.octets(); 43 | let addr: u32 = ((octets[0] as u32 & 0xff) << 24) 44 | | ((octets[1] as u32 & 0xff) << 16) 45 | | ((octets[2] as u32 & 0xff) << 8) 46 | | (octets[3] as u32 & 0xff); 47 | 48 | if addr.leading_ones() + addr.trailing_zeros() == 32 { 49 | Ok(Mask(addr.leading_ones() as u8)) 50 | } else { 51 | Err(()) 52 | } 53 | } 54 | } 55 | 56 | impl From for Ipv4Addr { 57 | fn from(mask: Mask) -> Self { 58 | let addr: u32 = ((1 << (32 - mask.0)) - 1) ^ 0xffffffffu32; 59 | 60 | let (a, b, c, d) = ( 61 | ((addr >> 24) & 0xff) as u8, 62 | ((addr >> 16) & 0xff) as u8, 63 | ((addr >> 8) & 0xff) as u8, 64 | (addr & 0xff) as u8, 65 | ); 66 | 67 | Ipv4Addr::new(a, b, c, d) 68 | } 69 | } 70 | 71 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 72 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 73 | #[cfg_attr(feature = "std", derive(Hash))] 74 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 75 | pub struct Subnet { 76 | #[cfg_attr(feature = "defmt", defmt(Debug2Format))] 77 | #[cfg_attr(feature = "use_serde", serde(serialize_with = "ipv4_serialize"))] 78 | #[cfg_attr(feature = "use_serde", serde(deserialize_with = "ipv4_deserialize"))] 79 | pub gateway: Ipv4Addr, 80 | pub mask: Mask, 81 | } 82 | 83 | impl Display for Subnet { 84 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 85 | write!(f, "{}/{}", self.gateway, self.mask) 86 | } 87 | } 88 | 89 | impl FromStr for Subnet { 90 | type Err = &'static str; 91 | 92 | fn from_str(s: &str) -> Result { 93 | let mut split = s.split('/'); 94 | if let Some(gateway_str) = split.next() { 95 | if let Some(mask_str) = split.next() { 96 | if split.next().is_none() { 97 | if let Ok(gateway) = gateway_str.parse::() { 98 | return mask_str.parse::().map(|mask| Self { gateway, mask }); 99 | } else { 100 | return Err("Invalid IP address format, expected XXX.XXX.XXX.XXX"); 101 | } 102 | } 103 | } 104 | } 105 | 106 | Err("Expected /") 107 | } 108 | } 109 | 110 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 111 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 112 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 113 | pub struct ClientSettings { 114 | #[cfg_attr(feature = "defmt", defmt(Debug2Format))] 115 | #[cfg_attr(feature = "use_serde", serde(serialize_with = "ipv4_serialize"))] 116 | #[cfg_attr(feature = "use_serde", serde(deserialize_with = "ipv4_deserialize"))] 117 | pub ip: Ipv4Addr, 118 | pub subnet: Subnet, 119 | #[cfg_attr(feature = "defmt", defmt(Debug2Format))] 120 | #[cfg_attr(feature = "use_serde", serde(serialize_with = "ipv4_opt_serialize"))] 121 | #[cfg_attr( 122 | feature = "use_serde", 123 | serde(deserialize_with = "ipv4_opt_deserialize") 124 | )] 125 | pub dns: Option, 126 | #[cfg_attr(feature = "defmt", defmt(Debug2Format))] 127 | #[cfg_attr(feature = "use_serde", serde(serialize_with = "ipv4_opt_serialize"))] 128 | #[cfg_attr( 129 | feature = "use_serde", 130 | serde(deserialize_with = "ipv4_opt_deserialize") 131 | )] 132 | pub secondary_dns: Option, 133 | } 134 | 135 | impl Default for ClientSettings { 136 | fn default() -> ClientSettings { 137 | ClientSettings { 138 | ip: Ipv4Addr::new(192, 168, 71, 200), 139 | subnet: Subnet { 140 | gateway: Ipv4Addr::new(192, 168, 71, 1), 141 | mask: Mask(24), 142 | }, 143 | dns: Some(Ipv4Addr::new(8, 8, 8, 8)), 144 | secondary_dns: Some(Ipv4Addr::new(8, 8, 4, 4)), 145 | } 146 | } 147 | } 148 | 149 | #[derive(Default, Clone, Debug, PartialEq, Eq)] 150 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 151 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 152 | pub struct DHCPClientSettings { 153 | pub hostname: Option>, 154 | } 155 | 156 | #[derive(Clone, Debug, PartialEq, Eq)] 157 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 158 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 159 | pub enum ClientConfiguration { 160 | DHCP(DHCPClientSettings), 161 | Fixed(ClientSettings), 162 | } 163 | 164 | impl ClientConfiguration { 165 | pub fn as_fixed_settings_ref(&self) -> Option<&ClientSettings> { 166 | match self { 167 | Self::Fixed(client_settings) => Some(client_settings), 168 | _ => None, 169 | } 170 | } 171 | 172 | pub fn as_fixed_settings_mut(&mut self) -> &mut ClientSettings { 173 | match self { 174 | Self::Fixed(client_settings) => client_settings, 175 | _ => { 176 | *self = ClientConfiguration::Fixed(Default::default()); 177 | self.as_fixed_settings_mut() 178 | } 179 | } 180 | } 181 | } 182 | 183 | impl Default for ClientConfiguration { 184 | fn default() -> ClientConfiguration { 185 | ClientConfiguration::DHCP(Default::default()) 186 | } 187 | } 188 | 189 | #[derive(Clone, Debug, Eq, PartialEq)] 190 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 191 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 192 | pub struct RouterConfiguration { 193 | pub subnet: Subnet, 194 | pub dhcp_enabled: bool, 195 | #[cfg_attr(feature = "defmt", defmt(Debug2Format))] 196 | #[cfg_attr(feature = "use_serde", serde(serialize_with = "ipv4_opt_serialize"))] 197 | #[cfg_attr( 198 | feature = "use_serde", 199 | serde(deserialize_with = "ipv4_opt_deserialize") 200 | )] 201 | pub dns: Option, 202 | #[cfg_attr(feature = "defmt", defmt(Debug2Format))] 203 | #[cfg_attr(feature = "use_serde", serde(serialize_with = "ipv4_opt_serialize"))] 204 | #[cfg_attr( 205 | feature = "use_serde", 206 | serde(deserialize_with = "ipv4_opt_deserialize") 207 | )] 208 | pub secondary_dns: Option, 209 | } 210 | 211 | impl Default for RouterConfiguration { 212 | fn default() -> RouterConfiguration { 213 | RouterConfiguration { 214 | subnet: Subnet { 215 | gateway: Ipv4Addr::new(192, 168, 71, 1), 216 | mask: Mask(24), 217 | }, 218 | dhcp_enabled: true, 219 | dns: Some(Ipv4Addr::new(8, 8, 8, 8)), 220 | secondary_dns: Some(Ipv4Addr::new(8, 8, 4, 4)), 221 | } 222 | } 223 | } 224 | 225 | #[derive(Clone, Debug, Eq, PartialEq)] 226 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 227 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 228 | pub enum Configuration { 229 | Client(ClientConfiguration), 230 | Router(RouterConfiguration), 231 | } 232 | 233 | impl Default for Configuration { 234 | fn default() -> Self { 235 | Self::Client(Default::default()) 236 | } 237 | } 238 | 239 | #[derive(Copy, Clone, Debug, Eq, PartialEq)] 240 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 241 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 242 | pub struct IpInfo { 243 | #[cfg_attr(feature = "defmt", defmt(Debug2Format))] 244 | #[cfg_attr(feature = "use_serde", serde(serialize_with = "ipv4_serialize"))] 245 | #[cfg_attr(feature = "use_serde", serde(deserialize_with = "ipv4_deserialize"))] 246 | pub ip: Ipv4Addr, 247 | pub subnet: Subnet, 248 | #[cfg_attr(feature = "defmt", defmt(Debug2Format))] 249 | #[cfg_attr(feature = "use_serde", serde(serialize_with = "ipv4_opt_serialize"))] 250 | #[cfg_attr( 251 | feature = "use_serde", 252 | serde(deserialize_with = "ipv4_opt_deserialize") 253 | )] 254 | pub dns: Option, 255 | #[cfg_attr(feature = "defmt", defmt(Debug2Format))] 256 | #[cfg_attr(feature = "use_serde", serde(serialize_with = "ipv4_opt_serialize"))] 257 | #[cfg_attr( 258 | feature = "use_serde", 259 | serde(deserialize_with = "ipv4_opt_deserialize") 260 | )] 261 | pub secondary_dns: Option, 262 | } 263 | 264 | pub trait Interface { 265 | type Error; 266 | 267 | fn get_iface_configuration(&self) -> Result; 268 | fn set_iface_configuration(&mut self, conf: &Configuration) -> Result<(), Self::Error>; 269 | 270 | fn is_iface_up(&self) -> bool; 271 | 272 | fn get_ip_info(&self) -> Result; 273 | } 274 | 275 | #[cfg(feature = "use_serde")] 276 | fn ipv4_serialize(ipv4: &Ipv4Addr, serializer: S) -> Result 277 | where 278 | S: serde::Serializer, 279 | { 280 | ipv4.octets().serialize(serializer) 281 | } 282 | 283 | #[cfg(feature = "use_serde")] 284 | fn ipv4_deserialize<'de, D>(deserializer: D) -> Result 285 | where 286 | D: serde::Deserializer<'de>, 287 | { 288 | <[u8; 4]>::deserialize(deserializer).map(Ipv4Addr::from) 289 | } 290 | 291 | #[cfg(feature = "use_serde")] 292 | fn ipv4_opt_serialize(ipv4: &Option, serializer: S) -> Result 293 | where 294 | S: serde::Serializer, 295 | { 296 | ipv4.map(|ip| ip.octets()).serialize(serializer) 297 | } 298 | 299 | #[cfg(feature = "use_serde")] 300 | fn ipv4_opt_deserialize<'de, D>(deserializer: D) -> Result, D::Error> 301 | where 302 | D: serde::Deserializer<'de>, 303 | { 304 | >::deserialize(deserializer).map(|octets| octets.map(Ipv4Addr::from)) 305 | } 306 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /src/http/server.rs: -------------------------------------------------------------------------------- 1 | use core::fmt::Debug; 2 | 3 | use crate::io::{Error, Read, Write}; 4 | 5 | pub use super::{Headers, Method, Query, Status}; 6 | pub use crate::io::ErrorType; 7 | 8 | #[derive(Debug)] 9 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 10 | pub struct Request(C); 11 | 12 | impl Request 13 | where 14 | C: Connection, 15 | { 16 | pub fn wrap(connection: C) -> Request { 17 | if connection.is_response_initiated() { 18 | panic!("connection is not in request phase"); 19 | } 20 | 21 | Request(connection) 22 | } 23 | 24 | pub fn split(&mut self) -> (&C::Headers, &mut C::Read) { 25 | self.0.split() 26 | } 27 | 28 | pub fn into_response<'b>( 29 | mut self, 30 | status: u16, 31 | message: Option<&'b str>, 32 | headers: &'b [(&'b str, &'b str)], 33 | ) -> Result, C::Error> { 34 | self.0.initiate_response(status, message, headers)?; 35 | 36 | Ok(Response(self.0)) 37 | } 38 | 39 | pub fn into_status_response(self, status: u16) -> Result, C::Error> { 40 | self.into_response(status, None, &[]) 41 | } 42 | 43 | pub fn into_ok_response(self) -> Result, C::Error> { 44 | self.into_response(200, Some("OK"), &[]) 45 | } 46 | 47 | pub fn connection(&mut self) -> &mut C { 48 | &mut self.0 49 | } 50 | 51 | pub fn release(self) -> C { 52 | self.0 53 | } 54 | 55 | pub fn uri(&self) -> &'_ str { 56 | self.0.uri() 57 | } 58 | 59 | pub fn method(&self) -> Method { 60 | self.0.method() 61 | } 62 | 63 | pub fn header(&self, name: &str) -> Option<&'_ str> { 64 | self.0.header(name) 65 | } 66 | 67 | pub fn read(&mut self, buf: &mut [u8]) -> Result { 68 | self.0.read(buf) 69 | } 70 | } 71 | 72 | impl ErrorType for Request 73 | where 74 | C: ErrorType, 75 | { 76 | type Error = C::Error; 77 | } 78 | 79 | impl Read for Request 80 | where 81 | C: Connection, 82 | { 83 | fn read(&mut self, buf: &mut [u8]) -> Result { 84 | Request::read(self, buf) 85 | } 86 | } 87 | 88 | impl Headers for Request 89 | where 90 | C: Connection, 91 | { 92 | fn header(&self, name: &str) -> Option<&'_ str> { 93 | Request::header(self, name) 94 | } 95 | } 96 | 97 | impl Query for Request 98 | where 99 | C: Connection, 100 | { 101 | fn uri(&self) -> &'_ str { 102 | Request::uri(self) 103 | } 104 | 105 | fn method(&self) -> Method { 106 | Request::method(self) 107 | } 108 | } 109 | 110 | #[derive(Debug)] 111 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 112 | pub struct Response(C); 113 | 114 | impl Response 115 | where 116 | C: Connection, 117 | { 118 | pub fn wrap(connection: C) -> Response { 119 | if !connection.is_response_initiated() { 120 | panic!("connection is not in response phase"); 121 | } 122 | 123 | Response(connection) 124 | } 125 | 126 | pub fn connection(&mut self) -> &mut C { 127 | &mut self.0 128 | } 129 | 130 | pub fn release(self) -> C { 131 | self.0 132 | } 133 | 134 | pub fn write(&mut self, buf: &[u8]) -> Result { 135 | self.0.write(buf) 136 | } 137 | 138 | pub fn flush(&mut self) -> Result<(), C::Error> { 139 | self.0.flush() 140 | } 141 | } 142 | 143 | impl ErrorType for Response 144 | where 145 | C: ErrorType, 146 | { 147 | type Error = C::Error; 148 | } 149 | 150 | impl Write for Response 151 | where 152 | C: Connection, 153 | { 154 | fn write(&mut self, buf: &[u8]) -> Result { 155 | Response::write(self, buf) 156 | } 157 | 158 | fn flush(&mut self) -> Result<(), Self::Error> { 159 | Response::flush(self) 160 | } 161 | } 162 | 163 | pub trait Connection: Query + Headers + Read + Write { 164 | type Headers: Query + Headers; 165 | 166 | type Read: Read; 167 | 168 | type RawConnectionError: Error; 169 | 170 | type RawConnection: Read 171 | + Write; 172 | 173 | fn split(&mut self) -> (&Self::Headers, &mut Self::Read); 174 | 175 | fn initiate_response<'a>( 176 | &'a mut self, 177 | status: u16, 178 | message: Option<&'a str>, 179 | headers: &'a [(&'a str, &'a str)], 180 | ) -> Result<(), Self::Error>; 181 | 182 | fn is_response_initiated(&self) -> bool; 183 | 184 | fn raw_connection(&mut self) -> Result<&mut Self::RawConnection, Self::Error>; 185 | } 186 | 187 | impl Connection for &mut C 188 | where 189 | C: Connection, 190 | { 191 | type Headers = C::Headers; 192 | 193 | type Read = C::Read; 194 | 195 | type RawConnectionError = C::RawConnectionError; 196 | 197 | type RawConnection = C::RawConnection; 198 | 199 | fn split(&mut self) -> (&Self::Headers, &mut Self::Read) { 200 | (*self).split() 201 | } 202 | 203 | fn initiate_response<'a>( 204 | &'a mut self, 205 | status: u16, 206 | message: Option<&'a str>, 207 | headers: &'a [(&'a str, &'a str)], 208 | ) -> Result<(), Self::Error> { 209 | (*self).initiate_response(status, message, headers) 210 | } 211 | 212 | fn is_response_initiated(&self) -> bool { 213 | (**self).is_response_initiated() 214 | } 215 | 216 | fn raw_connection(&mut self) -> Result<&mut Self::RawConnection, Self::Error> { 217 | (*self).raw_connection() 218 | } 219 | } 220 | 221 | pub trait Handler: Send 222 | where 223 | C: Connection, 224 | { 225 | type Error: Debug; 226 | 227 | fn handle(&self, connection: &mut C) -> Result<(), Self::Error>; 228 | } 229 | 230 | impl Handler for &H 231 | where 232 | C: Connection, 233 | H: Handler + Send + Sync, 234 | { 235 | type Error = H::Error; 236 | 237 | fn handle(&self, connection: &mut C) -> Result<(), Self::Error> { 238 | (*self).handle(connection) 239 | } 240 | } 241 | 242 | pub struct FnHandler(F); 243 | 244 | impl FnHandler { 245 | pub const fn new(f: F) -> Self 246 | where 247 | C: Connection, 248 | F: Fn(Request<&mut C>) -> Result<(), E> + Send, 249 | E: Debug, 250 | { 251 | Self(f) 252 | } 253 | } 254 | 255 | impl Handler for FnHandler 256 | where 257 | C: Connection, 258 | F: Fn(Request<&mut C>) -> Result<(), E> + Send, 259 | E: Debug, 260 | { 261 | type Error = E; 262 | 263 | fn handle(&self, connection: &mut C) -> Result<(), Self::Error> { 264 | self.0(Request::wrap(connection)) 265 | } 266 | } 267 | 268 | pub trait Middleware: Send 269 | where 270 | C: Connection, 271 | H: Handler, 272 | { 273 | type Error: Debug; 274 | 275 | fn handle(&self, connection: &mut C, handler: &H) -> Result<(), Self::Error>; 276 | 277 | fn compose(self, handler: H) -> CompositeHandler 278 | where 279 | Self: Sized, 280 | { 281 | CompositeHandler::new(self, handler) 282 | } 283 | } 284 | 285 | pub struct CompositeHandler { 286 | middleware: M, 287 | handler: H, 288 | } 289 | 290 | impl CompositeHandler { 291 | pub fn new(middleware: M, handler: H) -> Self { 292 | Self { 293 | middleware, 294 | handler, 295 | } 296 | } 297 | } 298 | 299 | impl Handler for CompositeHandler 300 | where 301 | M: Middleware, 302 | H: Handler, 303 | C: Connection, 304 | { 305 | type Error = M::Error; 306 | 307 | fn handle(&self, connection: &mut C) -> Result<(), Self::Error> { 308 | self.middleware.handle(connection, &self.handler) 309 | } 310 | } 311 | 312 | pub mod asynch { 313 | use core::fmt::Debug; 314 | 315 | use crate::io::{asynch::Read, asynch::Write}; 316 | 317 | pub use super::{Headers, Method, Query, Status}; 318 | pub use crate::io::{Error, ErrorType}; 319 | 320 | #[derive(Debug)] 321 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 322 | pub struct Request(C); 323 | 324 | impl Request 325 | where 326 | C: Connection, 327 | { 328 | pub fn wrap(connection: C) -> Request { 329 | if connection.is_response_initiated() { 330 | panic!("connection is not in request phase"); 331 | } 332 | 333 | Request(connection) 334 | } 335 | 336 | pub fn split(&mut self) -> (&C::Headers, &mut C::Read) { 337 | self.0.split() 338 | } 339 | 340 | pub async fn into_response<'b>( 341 | mut self, 342 | status: u16, 343 | message: Option<&'b str>, 344 | headers: &'b [(&'b str, &'b str)], 345 | ) -> Result, C::Error> { 346 | self.0.initiate_response(status, message, headers).await?; 347 | 348 | Ok(Response(self.0)) 349 | } 350 | 351 | pub async fn into_status_response(self, status: u16) -> Result, C::Error> { 352 | self.into_response(status, None, &[]).await 353 | } 354 | 355 | pub async fn into_ok_response(self) -> Result, C::Error> { 356 | self.into_response(200, Some("OK"), &[]).await 357 | } 358 | 359 | pub fn connection(&mut self) -> &mut C { 360 | &mut self.0 361 | } 362 | 363 | pub fn release(self) -> C { 364 | self.0 365 | } 366 | 367 | pub fn uri(&self) -> &'_ str { 368 | self.0.uri() 369 | } 370 | 371 | pub fn method(&self) -> Method { 372 | self.0.method() 373 | } 374 | 375 | pub fn header(&self, name: &str) -> Option<&'_ str> { 376 | self.0.header(name) 377 | } 378 | 379 | pub async fn read(&mut self, buf: &mut [u8]) -> Result { 380 | self.0.read(buf).await 381 | } 382 | } 383 | 384 | impl ErrorType for Request 385 | where 386 | C: ErrorType, 387 | { 388 | type Error = C::Error; 389 | } 390 | 391 | impl Read for Request 392 | where 393 | C: Connection, 394 | { 395 | async fn read(&mut self, buf: &mut [u8]) -> Result { 396 | Request::read(self, buf).await 397 | } 398 | } 399 | 400 | impl Query for Request 401 | where 402 | C: Connection, 403 | { 404 | fn uri(&self) -> &'_ str { 405 | Request::uri(self) 406 | } 407 | 408 | fn method(&self) -> Method { 409 | Request::method(self) 410 | } 411 | } 412 | 413 | impl Headers for Request 414 | where 415 | C: Connection, 416 | { 417 | fn header(&self, name: &str) -> Option<&'_ str> { 418 | Request::header(self, name) 419 | } 420 | } 421 | 422 | #[derive(Debug)] 423 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 424 | pub struct Response(C); 425 | 426 | impl Response 427 | where 428 | C: Connection, 429 | { 430 | pub fn wrap(connection: C) -> Response { 431 | if !connection.is_response_initiated() { 432 | panic!("connection is not in response phase"); 433 | } 434 | 435 | Response(connection) 436 | } 437 | 438 | pub fn connection(&mut self) -> &mut C { 439 | &mut self.0 440 | } 441 | 442 | pub fn release(self) -> C { 443 | self.0 444 | } 445 | 446 | pub async fn write(&mut self, buf: &[u8]) -> Result { 447 | self.0.write(buf).await 448 | } 449 | 450 | pub async fn flush(&mut self) -> Result<(), C::Error> { 451 | self.0.flush().await 452 | } 453 | } 454 | 455 | impl ErrorType for Response 456 | where 457 | C: ErrorType, 458 | { 459 | type Error = C::Error; 460 | } 461 | 462 | impl Write for Response 463 | where 464 | C: Connection, 465 | { 466 | async fn write(&mut self, buf: &[u8]) -> Result { 467 | Response::write(self, buf).await 468 | } 469 | 470 | async fn flush(&mut self) -> Result<(), Self::Error> { 471 | Response::flush(self).await 472 | } 473 | } 474 | 475 | pub trait Connection: Query + Headers + Read + Write { 476 | type Headers: Query + Headers; 477 | 478 | type Read: Read; 479 | 480 | type RawConnectionError: Error; 481 | 482 | type RawConnection: Read 483 | + Write; 484 | 485 | fn split(&mut self) -> (&Self::Headers, &mut Self::Read); 486 | 487 | async fn initiate_response( 488 | &mut self, 489 | status: u16, 490 | message: Option<&str>, 491 | headers: &[(&str, &str)], 492 | ) -> Result<(), Self::Error>; 493 | 494 | fn is_response_initiated(&self) -> bool; 495 | 496 | fn raw_connection(&mut self) -> Result<&mut Self::RawConnection, Self::Error>; 497 | } 498 | 499 | impl Connection for &mut C 500 | where 501 | C: Connection, 502 | { 503 | type Headers = C::Headers; 504 | 505 | type Read = C::Read; 506 | 507 | type RawConnectionError = C::RawConnectionError; 508 | 509 | type RawConnection = C::RawConnection; 510 | 511 | fn split(&mut self) -> (&Self::Headers, &mut Self::Read) { 512 | (*self).split() 513 | } 514 | 515 | async fn initiate_response( 516 | &mut self, 517 | status: u16, 518 | message: Option<&str>, 519 | headers: &[(&str, &str)], 520 | ) -> Result<(), Self::Error> { 521 | (*self).initiate_response(status, message, headers).await 522 | } 523 | 524 | fn is_response_initiated(&self) -> bool { 525 | (**self).is_response_initiated() 526 | } 527 | 528 | fn raw_connection(&mut self) -> Result<&mut Self::RawConnection, Self::Error> { 529 | (*self).raw_connection() 530 | } 531 | } 532 | 533 | pub trait Handler: Send 534 | where 535 | C: Connection, 536 | { 537 | type Error: Debug; 538 | 539 | async fn handle(&self, connection: &mut C) -> Result<(), Self::Error>; 540 | } 541 | 542 | impl Handler for &H 543 | where 544 | C: Connection, 545 | H: Handler + Send + Sync, 546 | { 547 | type Error = H::Error; 548 | 549 | async fn handle(&self, connection: &mut C) -> Result<(), Self::Error> { 550 | (*self).handle(connection).await 551 | } 552 | } 553 | 554 | pub trait Middleware: Send 555 | where 556 | C: Connection, 557 | H: Handler, 558 | { 559 | type Error: Debug; 560 | 561 | async fn handle(&self, connection: &mut C, handler: &H) -> Result<(), Self::Error>; 562 | 563 | fn compose(self, handler: H) -> CompositeHandler 564 | where 565 | Self: Sized, 566 | { 567 | CompositeHandler::new(self, handler) 568 | } 569 | } 570 | 571 | pub struct CompositeHandler { 572 | middleware: M, 573 | handler: H, 574 | } 575 | 576 | impl CompositeHandler { 577 | pub fn new(middleware: M, handler: H) -> Self { 578 | Self { 579 | middleware, 580 | handler, 581 | } 582 | } 583 | } 584 | 585 | impl Handler for CompositeHandler 586 | where 587 | M: Middleware, 588 | H: Handler, 589 | C: Connection, 590 | { 591 | type Error = M::Error; 592 | 593 | async fn handle(&self, connection: &mut C) -> Result<(), Self::Error> { 594 | self.middleware.handle(connection, &self.handler).await 595 | } 596 | } 597 | } 598 | -------------------------------------------------------------------------------- /src/http/client.rs: -------------------------------------------------------------------------------- 1 | use crate::io::{Error, ErrorType, Read, Write}; 2 | 3 | pub use super::{Headers, Method, Status}; 4 | 5 | #[derive(Debug)] 6 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 7 | pub struct Client(C); 8 | 9 | impl Client 10 | where 11 | C: Connection, 12 | { 13 | pub fn wrap(connection: C) -> Self { 14 | if connection.is_request_initiated() || connection.is_response_initiated() { 15 | panic!("connection is not in initial phase"); 16 | } 17 | 18 | Self(connection) 19 | } 20 | 21 | pub fn connection(&mut self) -> &mut C { 22 | &mut self.0 23 | } 24 | 25 | pub fn release(self) -> C { 26 | self.0 27 | } 28 | 29 | pub fn get<'a>(&'a mut self, uri: &'a str) -> Result, C::Error> { 30 | self.request(Method::Get, uri, &[]) 31 | } 32 | 33 | pub fn post<'a>( 34 | &'a mut self, 35 | uri: &'a str, 36 | headers: &'a [(&'a str, &'a str)], 37 | ) -> Result, C::Error> { 38 | self.request(Method::Post, uri, headers) 39 | } 40 | 41 | pub fn put<'a>( 42 | &'a mut self, 43 | uri: &'a str, 44 | headers: &'a [(&'a str, &'a str)], 45 | ) -> Result, C::Error> { 46 | self.request(Method::Put, uri, headers) 47 | } 48 | 49 | pub fn delete<'a>(&'a mut self, uri: &'a str) -> Result, C::Error> { 50 | self.request(Method::Delete, uri, &[]) 51 | } 52 | 53 | pub fn request<'a>( 54 | &'a mut self, 55 | method: Method, 56 | uri: &'a str, 57 | headers: &'a [(&'a str, &'a str)], 58 | ) -> Result, C::Error> { 59 | self.0.initiate_request(method, uri, headers)?; 60 | 61 | Ok(Request::wrap(&mut self.0)) 62 | } 63 | 64 | pub fn raw_connection(&mut self) -> Result<&mut C::RawConnection, C::Error> { 65 | self.0.raw_connection() 66 | } 67 | } 68 | 69 | impl ErrorType for Client 70 | where 71 | C: ErrorType, 72 | { 73 | type Error = C::Error; 74 | } 75 | 76 | #[derive(Debug)] 77 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 78 | pub struct Request(C); 79 | 80 | impl Request 81 | where 82 | C: Connection, 83 | { 84 | pub fn wrap(connection: C) -> Request { 85 | if !connection.is_request_initiated() { 86 | panic!("connection is not in request phase"); 87 | } 88 | 89 | Request(connection) 90 | } 91 | 92 | pub fn submit(mut self) -> Result, C::Error> { 93 | self.0.initiate_response()?; 94 | 95 | Ok(Response(self.0)) 96 | } 97 | 98 | pub fn connection(&mut self) -> &mut C { 99 | &mut self.0 100 | } 101 | 102 | pub fn release(self) -> C { 103 | self.0 104 | } 105 | 106 | pub fn write(&mut self, buf: &[u8]) -> Result { 107 | self.0.write(buf) 108 | } 109 | 110 | pub fn flush(&mut self) -> Result<(), C::Error> { 111 | self.0.flush() 112 | } 113 | } 114 | 115 | impl ErrorType for Request 116 | where 117 | C: ErrorType, 118 | { 119 | type Error = C::Error; 120 | } 121 | 122 | impl Write for Request 123 | where 124 | C: Connection, 125 | { 126 | fn write(&mut self, buf: &[u8]) -> Result { 127 | self.0.write(buf) 128 | } 129 | 130 | fn flush(&mut self) -> Result<(), Self::Error> { 131 | self.0.flush() 132 | } 133 | } 134 | 135 | #[derive(Debug)] 136 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 137 | pub struct Response(C); 138 | 139 | impl Response 140 | where 141 | C: Connection, 142 | { 143 | pub fn wrap(connection: C) -> Response { 144 | if !connection.is_response_initiated() { 145 | panic!("connection is not in response phase"); 146 | } 147 | 148 | Response(connection) 149 | } 150 | 151 | pub fn split(&mut self) -> (&C::Headers, &mut C::Read) { 152 | self.0.split() 153 | } 154 | 155 | pub fn connection(&mut self) -> &mut C { 156 | &mut self.0 157 | } 158 | 159 | pub fn release(self) -> C { 160 | self.0 161 | } 162 | 163 | pub fn status(&self) -> u16 { 164 | self.0.status() 165 | } 166 | 167 | pub fn status_message(&self) -> Option<&'_ str> { 168 | self.0.status_message() 169 | } 170 | 171 | pub fn header(&self, name: &str) -> Option<&'_ str> { 172 | self.0.header(name) 173 | } 174 | 175 | pub fn read(&mut self, buf: &mut [u8]) -> Result { 176 | self.0.read(buf) 177 | } 178 | } 179 | 180 | impl Status for Response 181 | where 182 | C: Connection, 183 | { 184 | fn status(&self) -> u16 { 185 | Response::status(self) 186 | } 187 | 188 | fn status_message(&self) -> Option<&'_ str> { 189 | Response::status_message(self) 190 | } 191 | } 192 | 193 | impl Headers for Response 194 | where 195 | C: Connection, 196 | { 197 | fn header(&self, name: &str) -> Option<&'_ str> { 198 | Response::header(self, name) 199 | } 200 | } 201 | 202 | impl ErrorType for Response 203 | where 204 | C: ErrorType, 205 | { 206 | type Error = C::Error; 207 | } 208 | 209 | impl Read for Response 210 | where 211 | C: Connection, 212 | { 213 | fn read(&mut self, buf: &mut [u8]) -> Result { 214 | Response::read(self, buf) 215 | } 216 | } 217 | 218 | pub trait Connection: Status + Headers + Read + Write { 219 | type Headers: Status + Headers; 220 | 221 | type Read: Read; 222 | 223 | type RawConnectionError: Error; 224 | 225 | type RawConnection: Read 226 | + Write; 227 | 228 | fn initiate_request<'a>( 229 | &'a mut self, 230 | method: Method, 231 | uri: &'a str, 232 | headers: &'a [(&'a str, &'a str)], 233 | ) -> Result<(), Self::Error>; 234 | 235 | fn is_request_initiated(&self) -> bool; 236 | 237 | fn initiate_response(&mut self) -> Result<(), Self::Error>; 238 | 239 | fn is_response_initiated(&self) -> bool; 240 | 241 | fn split(&mut self) -> (&Self::Headers, &mut Self::Read); 242 | 243 | fn raw_connection(&mut self) -> Result<&mut Self::RawConnection, Self::Error>; 244 | } 245 | 246 | impl Connection for &mut C 247 | where 248 | C: Connection, 249 | { 250 | type Headers = C::Headers; 251 | 252 | type Read = C::Read; 253 | 254 | type RawConnectionError = C::RawConnectionError; 255 | 256 | type RawConnection = C::RawConnection; 257 | 258 | fn initiate_request<'a>( 259 | &'a mut self, 260 | method: Method, 261 | uri: &'a str, 262 | headers: &'a [(&'a str, &'a str)], 263 | ) -> Result<(), Self::Error> { 264 | (*self).initiate_request(method, uri, headers) 265 | } 266 | 267 | fn is_request_initiated(&self) -> bool { 268 | (**self).is_request_initiated() 269 | } 270 | 271 | fn initiate_response(&mut self) -> Result<(), Self::Error> { 272 | (*self).initiate_response() 273 | } 274 | 275 | fn is_response_initiated(&self) -> bool { 276 | (**self).is_response_initiated() 277 | } 278 | 279 | fn split(&mut self) -> (&Self::Headers, &mut Self::Read) { 280 | (*self).split() 281 | } 282 | 283 | fn raw_connection(&mut self) -> Result<&mut Self::RawConnection, Self::Error> { 284 | (*self).raw_connection() 285 | } 286 | } 287 | 288 | pub mod asynch { 289 | use crate::io::{asynch::Read, asynch::Write, Error, ErrorType}; 290 | 291 | pub use crate::http::asynch::*; 292 | pub use crate::http::{Headers, Method, Status}; 293 | 294 | #[derive(Debug)] 295 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 296 | pub struct Client(C); 297 | 298 | impl Client 299 | where 300 | C: Connection, 301 | { 302 | pub fn wrap(connection: C) -> Self { 303 | if connection.is_request_initiated() || connection.is_response_initiated() { 304 | panic!("connection is not in initial phase"); 305 | } 306 | 307 | Self(connection) 308 | } 309 | 310 | pub fn connection(&mut self) -> &mut C { 311 | &mut self.0 312 | } 313 | 314 | pub fn release(self) -> C { 315 | self.0 316 | } 317 | 318 | pub async fn get<'a>(&'a mut self, uri: &'a str) -> Result, C::Error> { 319 | self.request(Method::Get, uri, &[]).await 320 | } 321 | 322 | pub async fn post<'a>( 323 | &'a mut self, 324 | uri: &'a str, 325 | headers: &'a [(&'a str, &'a str)], 326 | ) -> Result, C::Error> { 327 | self.request(Method::Post, uri, headers).await 328 | } 329 | 330 | pub async fn put<'a>( 331 | &'a mut self, 332 | uri: &'a str, 333 | headers: &'a [(&'a str, &'a str)], 334 | ) -> Result, C::Error> { 335 | self.request(Method::Put, uri, headers).await 336 | } 337 | 338 | pub async fn delete<'a>( 339 | &'a mut self, 340 | uri: &'a str, 341 | ) -> Result, C::Error> { 342 | self.request(Method::Delete, uri, &[]).await 343 | } 344 | 345 | pub async fn request<'a>( 346 | &'a mut self, 347 | method: Method, 348 | uri: &'a str, 349 | headers: &'a [(&'a str, &'a str)], 350 | ) -> Result, C::Error> { 351 | self.0.initiate_request(method, uri, headers).await?; 352 | 353 | Ok(Request::wrap(&mut self.0)) 354 | } 355 | 356 | pub fn raw_connection(&mut self) -> Result<&mut C::RawConnection, C::Error> { 357 | self.0.raw_connection() 358 | } 359 | } 360 | 361 | impl ErrorType for Client 362 | where 363 | C: ErrorType, 364 | { 365 | type Error = C::Error; 366 | } 367 | 368 | #[derive(Debug)] 369 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 370 | pub struct Request(C); 371 | 372 | impl Request 373 | where 374 | C: Connection, 375 | { 376 | pub fn wrap(connection: C) -> Request { 377 | if !connection.is_request_initiated() { 378 | panic!("connection is not in request phase"); 379 | } 380 | 381 | Request(connection) 382 | } 383 | 384 | pub async fn submit(mut self) -> Result, C::Error> { 385 | self.0.initiate_response().await?; 386 | 387 | Ok(Response(self.0)) 388 | } 389 | 390 | pub fn connection(&mut self) -> &mut C { 391 | &mut self.0 392 | } 393 | 394 | pub fn release(self) -> C { 395 | self.0 396 | } 397 | 398 | pub async fn write(&mut self, buf: &[u8]) -> Result { 399 | self.0.write(buf).await 400 | } 401 | 402 | pub async fn flush(&mut self) -> Result<(), C::Error> { 403 | self.0.flush().await 404 | } 405 | } 406 | 407 | impl ErrorType for Request 408 | where 409 | C: ErrorType, 410 | { 411 | type Error = C::Error; 412 | } 413 | 414 | impl Write for Request 415 | where 416 | C: Connection, 417 | { 418 | async fn write(&mut self, buf: &[u8]) -> Result { 419 | Request::write(self, buf).await 420 | } 421 | 422 | async fn flush(&mut self) -> Result<(), Self::Error> { 423 | Request::flush(self).await 424 | } 425 | } 426 | 427 | #[derive(Debug)] 428 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 429 | pub struct Response(C); 430 | 431 | impl Response 432 | where 433 | C: Connection, 434 | { 435 | pub fn wrap(connection: C) -> Response { 436 | if !connection.is_response_initiated() { 437 | panic!("connection is not in response phase"); 438 | } 439 | 440 | Response(connection) 441 | } 442 | 443 | pub fn split(&mut self) -> (&C::Headers, &mut C::Read) { 444 | self.0.split() 445 | } 446 | 447 | pub fn connection(&mut self) -> &mut C { 448 | &mut self.0 449 | } 450 | 451 | pub fn release(self) -> C { 452 | self.0 453 | } 454 | 455 | pub fn status(&self) -> u16 { 456 | self.0.status() 457 | } 458 | 459 | pub fn status_message(&self) -> Option<&'_ str> { 460 | self.0.status_message() 461 | } 462 | 463 | pub fn header(&self, name: &str) -> Option<&'_ str> { 464 | self.0.header(name) 465 | } 466 | 467 | pub async fn read(&mut self, buf: &mut [u8]) -> Result { 468 | self.0.read(buf).await 469 | } 470 | } 471 | 472 | impl Status for Response 473 | where 474 | C: Connection, 475 | { 476 | fn status(&self) -> u16 { 477 | Response::status(self) 478 | } 479 | 480 | fn status_message(&self) -> Option<&'_ str> { 481 | Response::status_message(self) 482 | } 483 | } 484 | 485 | impl Headers for Response 486 | where 487 | C: Connection, 488 | { 489 | fn header(&self, name: &str) -> Option<&'_ str> { 490 | Response::header(self, name) 491 | } 492 | } 493 | 494 | impl ErrorType for Response 495 | where 496 | C: ErrorType, 497 | { 498 | type Error = C::Error; 499 | } 500 | 501 | impl Read for Response 502 | where 503 | C: Connection, 504 | { 505 | async fn read(&mut self, buf: &mut [u8]) -> Result { 506 | Response::read(self, buf).await 507 | } 508 | } 509 | 510 | pub trait Connection: Status + Headers + Read + Write { 511 | type Headers: Status + Headers; 512 | 513 | type Read: Read; 514 | 515 | type RawConnectionError: Error; 516 | 517 | type RawConnection: Read 518 | + Write; 519 | 520 | async fn initiate_request( 521 | &mut self, 522 | method: Method, 523 | uri: &str, 524 | headers: &[(&str, &str)], 525 | ) -> Result<(), Self::Error>; 526 | 527 | fn is_request_initiated(&self) -> bool; 528 | 529 | async fn initiate_response(&mut self) -> Result<(), Self::Error>; 530 | 531 | fn is_response_initiated(&self) -> bool; 532 | 533 | fn split(&mut self) -> (&Self::Headers, &mut Self::Read); 534 | 535 | fn raw_connection(&mut self) -> Result<&mut Self::RawConnection, Self::Error>; 536 | } 537 | 538 | impl Connection for &mut C 539 | where 540 | C: Connection, 541 | { 542 | type Headers = C::Headers; 543 | 544 | type Read = C::Read; 545 | 546 | type RawConnectionError = C::RawConnectionError; 547 | 548 | type RawConnection = C::RawConnection; 549 | 550 | async fn initiate_request( 551 | &mut self, 552 | method: Method, 553 | uri: &str, 554 | headers: &[(&str, &str)], 555 | ) -> Result<(), Self::Error> { 556 | (*self).initiate_request(method, uri, headers).await 557 | } 558 | 559 | fn is_request_initiated(&self) -> bool { 560 | (**self).is_request_initiated() 561 | } 562 | 563 | async fn initiate_response(&mut self) -> Result<(), Self::Error> { 564 | (*self).initiate_response().await 565 | } 566 | 567 | fn is_response_initiated(&self) -> bool { 568 | (**self).is_response_initiated() 569 | } 570 | 571 | fn split(&mut self) -> (&Self::Headers, &mut Self::Read) { 572 | (*self).split() 573 | } 574 | 575 | fn raw_connection(&mut self) -> Result<&mut Self::RawConnection, Self::Error> { 576 | (*self).raw_connection() 577 | } 578 | } 579 | } 580 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), 6 | and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). 7 | 8 | ## [0.28.1] - 2025-01-02 9 | 10 | ### Deprecated 11 | 12 | ### Breaking 13 | 14 | ### Added 15 | - Add serde defaults for authentication method and password fields of ClientConfiguration struct (#82) 16 | 17 | ### Fixed 18 | - Remove `DynStorageImpl` as nobody used it BECAUSE it did not have a public constructor ANYWAY 19 | - Add serde defaults to the client configuration struct (#78) 20 | - Derive Equality traits for OTA slots (#79) 21 | 22 | ## [0.28.0] - 2024-06-23 23 | ### Breaking 24 | * Add configuration for Protected Management Frames and scan methods to `wifi::ClientConfiguration` 25 | * Removed the `no-std-net` dependency in favor of `core::net` which is stable since Rust 1.77 26 | * Due to the above, module `ipv4` no longer re-exports `ToSocketAddrs` with `feature = "std"` enabled as this trait is not available in `core::net` (and might completely stop re-exporting `core::net` types in future) 27 | 28 | ## [0.27.1] - 2024-02-21 29 | * Fix clippy duplicate imports warnings with latest 1.78 nightly 30 | 31 | ## [0.27.0] - 2024-01-26 32 | * MAJOR CLEANUP/REMOVAL of obscure/rarely used trait modules: 33 | * `sys_time` 34 | * `ping` 35 | * `timer` (as there is `embedded_hal::delay` and more importantly - `embedded_hal_async::delay`) 36 | * `event_bus` 37 | * `ws::callback_server` 38 | * COMPLETE REMOVAL of the following utility modules: 39 | * `asyncify` - all functionality which still made sense merged into `esp-idf-svc` 40 | * `utils::mutex` - this was a helper module for `asyncify`, so removed completely 41 | * New module: `channel`; similar to crate `channel-bridge` but with less constraints on the data being sent/received 42 | * Breaking change in modules `mqtt::client` and `utils::mqtt::client`: The `Event` structure, and its associated `Message` and `MessageImpl` traits simplified significantly, allowing for much more ergonomic event processing, thanks to GATs and async-fn-in-trait which are now stable: 43 | * Introduced a new single-method trait: `Event` with method `payload` returning `EventPayload` 44 | * Introduced a new enumeration - `EventPayload` - modeling all possible event types that can be received from the MQTT client 45 | * `Message` and `MessageImpl` retired 46 | * Breaking change in module `http::server`: `HandlerError` and `HandlerResult` are now gone. 47 | * The blocking and async versions of the `Handler` and `Middleware` traits now all have an associated `Error` type that the user can define however she wants (only requirement is for it to implement `Debug`) 48 | * Additionally, the blocking and async versions of `Middleware` are now generified by the `Handler` type, so that they have access 49 | to the Handler's error type and are therefore free to implement their error type in terms of a composition between the handler error type and the error types of other functions they are calling 50 | * Bumped the MSRV version to 1.75 and removed the `nightly` feature requirement from all async traits 51 | * The `serde` dependency is now optional 52 | * Update to `heapless` 0.8 53 | 54 | ## [0.26.4] - 2023-11-12 55 | * Updated changelog 56 | 57 | ## [0.26.3] - 2023-11-12 58 | * BREAKING CHANGE IN A PATCH RELEASE DUE TO DISCOVERED UB: Traits `EventBus` and `TimerService` no longer allow subscriptions with non-static callbacks, 59 | as these are impossible to implement safely on ESP IDF 60 | 61 | ## [0.26.2] - 2023-11-05 62 | * A temporary workaround for https://github.com/rust-lang/rust/issues/117602 63 | 64 | ## [0.26.1] - 2023-10-18 65 | * Rolled back a change where `event_bus::asynch::Sender` and `event_bus::asynch::Receiver` did no longer implement `ErrorType` and returned a `Result`; since these traits are rarely used (feature `nightly` only), and 0.26.0 was just released, no new major version was released, but instead 0.26.0 was yanked 66 | 67 | ## [0.26.0] - 2023-10-17 68 | * MSRV raised to 1.71 69 | * Breaking change: All traits converted to AFIT, except `Unblocker`, which needs to compile with stable Rust 70 | * Breaking change: Upgraded to `embedded-io` 0.5 and `embedded-io-async` 0.5 71 | * Upgraded `strum` and `strum-macros` to 0.25 72 | * OTA: New method: `Ota::finish` that allows to postpone/avoid setting the updated partition as a boot one 73 | * TimerService: `TimerService::timer` now takes `&self` instead of `&mut self` - for both blocking and async traits 74 | * Breaking change: TimerService: scoped handler: the timer callback now only needs to live as long as the `TimerService::Timer` associated type. Therefore, `TimerService::Timer` is now lifetimed: `TimerService::Timer<'a>` 75 | * Breaking change: TimerService: `TimerService::Timer` now borrows from `TimerService`. Therefore, that's another reason why `TimerService::Timer` is now lifetimed: `TimerService::Timer<'a>` 76 | * Breaking change: EventBus: scoped handler: the subscription callback now only needs to live as long as the `EventBus::Subscription` associated type. Therefore, `EventBus::Subscription` is now lifetimed: `EventBus::Subscription<'a>` 77 | * Breaking change: EventBus: `EventBus::Subscription` now borrows from `EventBus`. Therefore, that's another reason why `EventBus::Subscription` is now lifetimed: `EventBus::Subscription<'a>` 78 | * Breaking change: ws::Acceptor: the blocking as well as the async version now return `Connection` / `Sender` / `Receiver` instances which borrow from `Acceptor` 79 | * Breaking change: Unblocker: scoped handler: the callback now only needs to live as long as the `Unblocker::UnblockFuture` associated type. Therefore, `Unblocker::UnblockFuture` is now lifetimed: `Unblocker::UnblockFuture<'a, ...>` 80 | * Breaking change: Unblocker: `Unblocker::UnblockFuture` now borrows from `Unblocker::UnblockFuture`. Therefore, that's another reason why `Unblocker::UnblockFuture` is now lifetimed: `Unblocker::UnblockFuture<'a, ...>` 81 | * Breaking change: OTA: GAT `Ota::Update` now parametric over lifetime and no longer returned by `&mut` ref 82 | * Breaking change: OTA: `OtaUpdate::abort` and `OtaUpdate::complete` now take `self` instead of `&mut self` 83 | * Breaking change: MQTT: GAT `Connection::Message` now parametric over lifetime 84 | * Breaking change: Ping: Callback function of `Ping::ping_details` can now be `FnMut` but does require `Send` 85 | * Breaking change: All pub structs in `utils::asyncify` that implement the `Future` trait are now private and wrapped with async methods 86 | * Breaking change: Removed structs `Blocking` and `TrivialAsync`, as well as all trait implementations on them, because their usefulness was questionable 87 | * Breaking change: Removed the deprecated module `httpd` and the dependency on `anyhow` 88 | 89 | ## [0.25.3] - 2023-07-05 90 | * Compatibility with latest Rust nightly Clippy (fixes the "usage of `Arc` where `T` is not `Send` or `Sync`" error) 91 | 92 | ## [0.25.2] - 2023-07-05 93 | * Yanked; first attempt at ^^^ 94 | 95 | ## [0.25.1] - 2023-06-18 96 | * Compatibility with latest Rust nightly (fixes the `can't leak private types` error) 97 | 98 | ## [0.25.0] - 2023-05-13 99 | 100 | * MSRV 1.66 (but MSRV 1.70 necessary if `embedded-io-async` is enabled) 101 | * Remove the `experimental` status from all traits 102 | * Remove the `nightly` feature flag guard from all `asyncify` utilities as Rust GATs are stable now 103 | * Async `Wifi` and `Eth` traits 104 | * `defmt` support 105 | * Mask the SSID password in Wifi `ClientConfiguration` 106 | * Switch from `futures` to the `atomic_waker` crate in the `asyncify` utilities 107 | * Minor breaking change: `is_up` renamed to `is_connected` in the `Eth` trait 108 | * Upgrade to `embedded-io` 0.4 (but still stay away from switching the async traits to the `async` syntax) 109 | 110 | ## [0.24.0] - 2022-12-13 111 | 112 | HTTP server traits: 113 | * Change the signatures of `Handler`, `Middleware`, `asynch::Handler` and `asynch::Middleware` so that middleware implementations can use the HTTP connection after the handler has finished execution 114 | * Remove the `handler` utility method, as it was adding little value besides calling `FnHandler::new()` 115 | * Remove the `FnConnectionHandler` Fn `Handler` implementation, as it was confusing to have it in addition to the `FnHandler` implementation 116 | 117 | ## [0.23.2] - 2022-12-08 118 | 119 | * Const functions for strum_enums 120 | * Defmt support 121 | 122 | ## [0.23.1] - 2022-11-21 123 | 124 | Patch release to fix compilation errors under no_std. 125 | 126 | ## [0.23] - 2022-11-01 127 | 128 | Release 0.23 is a backwards-incompatible release where almost all traits were touched in one way or another. 129 | 130 | ### Major Changes 131 | 132 | The main themes of the 0.23 release are: 133 | * Lose weight - the `utils` module was reduced to the bare minimum necessary. After all, the main goal of this crate is to provide traits, not utilities 134 | * In addition to all traits being implementable in `no_std` environments, make sure they do **not** have explicit or implicit dependencies on an allocator being available (the Rust `alloc` module) 135 | * Improve the experimental HTTP client and server traits 136 | * Separate the notions of using a "nightly" compiler (which is a precondition for all async support) from "experimental" features, which might or might not be async-related 137 | 138 | ### Changes by module 139 | 140 | #### channel 141 | 142 | This module is now moved to a separate micro-crate: `channel-bridge`. The traits in `embedded-svc` no longer depend on the generic `Receiver` and `Sender` traits the `channel` module used to provide. 143 | 144 | #### errors 145 | 146 | This module is completely retired, as it used to provide utilities (`EitherErrorXX`) which were anyway used only by a handful of the traits in `embedded-svc`. 147 | Those traits now use their own custom error types. 148 | 149 | #### eth 150 | 151 | `TransitionalState` struct is retired. The `Eth` trait is redesigned to have explicit `start` and `stop` methods, as well as `is_started` and `is_up` methods that to some extent provide the functionality 152 | which used to be available via the now-retired `get_status` method. 153 | 154 | Furthermore, the `Eth` trait now no longer assumes that the driver implementing it is capable of operating above the OSI Layer-2. In other words, a driver implementing the `Eth` trait might, or might not bring up an IP-level stack. As such, all structures related to "IP" are retired or moved to the `ipv4` module. 155 | 156 | #### event_bus 157 | 158 | * All trait methods on the blocking traits now take `&self` instead of `&mut self`. Given that `EventBus` and `Postbox` are essentially a publish-subscribe channel in disguise this makes a lot of sense 159 | * Implement `EventBus` and `Postbox` for `& T` and `&mut T` 160 | * `PinnedEventBus` is now retired, as its usefulness was queztionable (it was only lifting the `Send` requirement on the subscription callback) 161 | * Async traits: remove the dependency on `channel::Receiver` and `channel::Sender` 162 | 163 | #### executor 164 | 165 | * All existing traits retired, as they cannot be implemented without an allocator being available (i.e. not implementable on top of the `embassy-executor` crate) 166 | * New traits (and utility structs around them): `Blocker` and `Unblocker`. Note that `Unblocker` is currently not possible to implement without an allocation either, but it was kept for completeness. 167 | 168 | #### http 169 | 170 | This module underwent complete refactoring. Major changes: 171 | * `Connection` trait: this is the major HTTP abstraction for both client code and server handlers. Amongst other reasons, introducing this trait solves the problem where the underlying TCP socket abstraction cannot be split into separate "reader" and "writer". Note that certain methods of the `Connection` trait can only be called when the connection is in a certain state (i.e. "client request submitted" phase vs "client request submitted" phase) and will panic otherwise. There are two safe, non-panicking wrappers of `Connection` for both HTTP client and server: `Request` and `Response`, where the recommendation for user code is to use the `Connection` trait via the `Request` wrapper (`Request` is automatically turned into `Response` once the request is submitted) 172 | * On error, the server `Handler` trait is now required to return a dedicated `HandlerError` structure, which is just a wrapper around an error message. `HandlerError` is expected to be turned into an HTTP 500 response by trait implementors. The generified `E: Debug` error that used to be returned by the `Handler` trait introduced a very complex lifetime handling in user code and was therefore retired. Note that since `HandlerError` does not allocate, the maximum error message that it can contain is 64 characters. Longer messages are automatically truncated. 173 | * The `registry` module is removed, as the `Registry` trait was impossible to implement without allocations. Instead, the new `utils::http::registry` utility is offered 174 | * `Query` trait, allowing user to retrive the HTTP method and URI 175 | * Implement traits on `& T` and `&mut T` where appropriate 176 | * `headers` module with utility functions for building a headers' array for submission 177 | * `Blocking` and `TrivialUnblocking` adaptors from async to blocking traits and vice versa 178 | * `Header` utility in `utils::http` 179 | * The `session` module is significantly simplified and moved to `utils::http::session` 180 | * The `cookies` module is moved to `utils::http::cookies` 181 | 182 | #### httpd 183 | 184 | This module is now marked as deprecated. The successor is the `http::server` module. 185 | 186 | #### io 187 | 188 | * Blocking and async utility methods like `read_max` and `copy` moved to `utils::io` 189 | 190 | #### ipv4 191 | 192 | * `Configuration` struct describing the IP-related configuration of network interfaces, along with an accopmanying `Interface` trait 193 | 194 | #### mqtt 195 | 196 | * `&mut T` traits implementations 197 | 198 | #### mutex 199 | 200 | * Retired as it used GATs. While GATs are stable in the meantime, this trait still had open questions around it, as in the "guard" pattern it standardizes is not really embraced by the embedded community. Use the raw `BlockingMutex` trait provided by the `embassy-sync` crate along with its ergonomic typed wrapper, or - for STD-only environments - the STD `Mutex` directly. 201 | 202 | #### ota 203 | 204 | * `OtaServer` retired. This trait had nothing to do with the capabilities of the device itself in terms of OTA support, and modeled a generic "OTA server". While perhaps a useful concept, it might had been too early for that 205 | * `Slot` trait turned into a structure, similar to `Firmware`. This enabled GAT-free blocking traits. While GATs are now getting stabilized, we still try to use those only for async traits, where they are absolute necessity 206 | * Implement `Ota` for `&mut T` 207 | 208 | #### ping 209 | 210 | * Implement `Ping` for `&mut T` 211 | 212 | #### storage 213 | 214 | * `StorageImpl` - out of the box `Storage` implementation based on `RawStorage` impl and `SerDe` impl provided by the user 215 | 216 | #### sys_time, timer 217 | 218 | * `& T` and `&mut T` impls where appropriate 219 | 220 | #### unblocker 221 | 222 | * Removed, see the `executor` module for a suitable replacement 223 | 224 | #### utils 225 | 226 | Retired copies of async utilities available in other crates: 227 | * `signal`, `mutex`, `channel` (were copied from the `embassy-sync` crate, which is now published on crates.io) 228 | * `yield_now`, `select` (were copied from the `embassy-futures` crate, which is now published on crates.io) 229 | * `forever` (were copied from the `static_cell` crate, which is now published on crates.io) 230 | 231 | Utilities moved to other crates: 232 | * `executor` - available as a separate `edge-executor` micro-crate now 233 | * `ghota` - available as a separate `ghota` micro-crate now 234 | * `captive` - available as part of the `edge-net` crate now 235 | * `role` - available as part of the `edge-frame` crate now 236 | 237 | Completely retired utilities: 238 | * `rest` 239 | * `json_io` 240 | 241 | ##### utils::mutex 242 | 243 | This is a module that provides mutex and condvar abstractions, but with the caveat that these abstractions are supposed to *only* be used by: 244 | * Other utilities in the `utils` module, namely the `utils::asyncify` module, and the helper `utils::mqtt` module (the latter can optionally be used by implementors of the synchronous `mqtt` traits) 245 | * Implementors of the `embedded-svc` traits 246 | 247 | It is *not* intended for general, public use. 248 | If users need a synchronous mutex or condvar abstractions for their application code, they are strongly encouraged to use one of the following options: 249 | * For STD-compatible environments, the mutex and condvar abstractions provided by the Rust STD library itself 250 | * For no_std environments, one of the following: 251 | * The synchronous mutex abstractions provided by the `embassy-sync` crate 252 | * The critical section provided by the `critical-section` crate 253 | * Note that the no_std options above only provide a mutex abstration. If users need a condvar abstraction (usually only the case for RTOS environments which provde a thread/task notion), they should use the native condvar facilities of their RTOS 254 | 255 | Furthermore: 256 | * When the `embedded-svc` utilities are used in a STD-compatible environment, the mutex and condvar abstractions of `utils::mutex` 257 | are already implemented in terms of Rust's STD mutex and condvar abstractions, and users should not be concerned with this module at all 258 | * When the `embedded-svc` utilities are used in a no_std environment (i.e., an RTOS that provides blocking synchronization primitives, as well as the notion of task/threads but these are not Rust STD compatible), users are required to provide implementations of the `RawMutex` and `RawCondvar` traits 259 | 260 | #### wifi 261 | 262 | `TransitionalState` struct is retired. The `Wifi` trait is redesigned to have explicit `start`, `stop`, `connect` and `disconnect` methods, as well as `is_started` and `is_connected` methods that to some extent provide the functionality 263 | which used to be available via the now-retired `get_status` method. 264 | 265 | Furthermore, the `Wifi` trait now no longer assumes that the driver implementing it is capable of operating above the OSI Layer-2. In other words, a driver implementing the `Wifi` trait might, or might not bring up an IP-level stack. As such, all structures related to "IP" are retired or moved to the `ipv4` module. 266 | -------------------------------------------------------------------------------- /src/utils/http.rs: -------------------------------------------------------------------------------- 1 | use core::str; 2 | 3 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] 4 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 5 | pub enum HeaderSetError { 6 | TooManyHeaders, 7 | } 8 | 9 | #[derive(Debug)] 10 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 11 | pub struct Headers<'b, const N: usize = 64>([(&'b str, &'b str); N]); 12 | 13 | impl<'b, const N: usize> Headers<'b, N> { 14 | pub const fn new() -> Self { 15 | Self([("", ""); N]) 16 | } 17 | 18 | pub fn content_len(&self) -> Option { 19 | self.get("Content-Length") 20 | .map(|content_len_str| content_len_str.parse::().unwrap()) 21 | } 22 | 23 | pub fn content_type(&self) -> Option<&str> { 24 | self.get("Content-Type") 25 | } 26 | 27 | pub fn content_encoding(&self) -> Option<&str> { 28 | self.get("Content-Encoding") 29 | } 30 | 31 | pub fn transfer_encoding(&self) -> Option<&str> { 32 | self.get("Transfer-Encoding") 33 | } 34 | 35 | pub fn host(&self) -> Option<&str> { 36 | self.get("Host") 37 | } 38 | 39 | pub fn connection(&self) -> Option<&str> { 40 | self.get("Connection") 41 | } 42 | 43 | pub fn cache_control(&self) -> Option<&str> { 44 | self.get("Cache-Control") 45 | } 46 | 47 | pub fn upgrade(&self) -> Option<&str> { 48 | self.get("Upgrade") 49 | } 50 | 51 | pub fn iter(&self) -> impl Iterator { 52 | self.0 53 | .iter() 54 | .filter(|header| !header.0.is_empty()) 55 | .map(|header| (header.0, header.1)) 56 | } 57 | 58 | pub fn get(&self, name: &str) -> Option<&str> { 59 | self.iter() 60 | .find(|(hname, _)| name.eq_ignore_ascii_case(hname)) 61 | .map(|(_, value)| value) 62 | } 63 | 64 | pub fn try_set(&mut self, name: &'b str, value: &'b str) -> Result<&mut Self, HeaderSetError> { 65 | for header in &mut self.0 { 66 | if header.0.is_empty() || header.0.eq_ignore_ascii_case(name) { 67 | *header = (name, value); 68 | return Ok(self); 69 | } 70 | } 71 | 72 | Err(HeaderSetError::TooManyHeaders) 73 | } 74 | 75 | pub fn set(&mut self, name: &'b str, value: &'b str) -> &mut Self { 76 | self.try_set(name, value).expect("No space left") 77 | } 78 | 79 | pub fn remove(&mut self, name: &str) -> &mut Self { 80 | let index = self 81 | .0 82 | .iter() 83 | .enumerate() 84 | .find(|(_, header)| header.0.eq_ignore_ascii_case(name)); 85 | 86 | if let Some((mut index, _)) = index { 87 | while index < self.0.len() - 1 { 88 | self.0[index] = self.0[index + 1]; 89 | 90 | index += 1; 91 | } 92 | 93 | self.0[index] = ("", ""); 94 | } 95 | 96 | self 97 | } 98 | 99 | pub fn set_content_len( 100 | &mut self, 101 | content_len: u64, 102 | buf: &'b mut heapless::String<20>, 103 | ) -> &mut Self { 104 | *buf = heapless::String::<20>::try_from(content_len).unwrap(); 105 | 106 | self.set("Content-Length", buf.as_str()) 107 | } 108 | 109 | pub fn set_content_type(&mut self, content_type: &'b str) -> &mut Self { 110 | self.set("Content-Type", content_type) 111 | } 112 | 113 | pub fn set_content_encoding(&mut self, content_encoding: &'b str) -> &mut Self { 114 | self.set("Content-Encoding", content_encoding) 115 | } 116 | 117 | pub fn set_transfer_encoding(&mut self, transfer_encoding: &'b str) -> &mut Self { 118 | self.set("Transfer-Encoding", transfer_encoding) 119 | } 120 | 121 | pub fn set_transfer_encoding_chunked(&mut self) -> &mut Self { 122 | self.set_transfer_encoding("Chunked") 123 | } 124 | 125 | pub fn set_host(&mut self, host: &'b str) -> &mut Self { 126 | self.set("Host", host) 127 | } 128 | 129 | pub fn set_connection(&mut self, connection: &'b str) -> &mut Self { 130 | self.set("Connection", connection) 131 | } 132 | 133 | pub fn set_connection_close(&mut self) -> &mut Self { 134 | self.set_connection("Close") 135 | } 136 | 137 | pub fn set_connection_keep_alive(&mut self) -> &mut Self { 138 | self.set_connection("Keep-Alive") 139 | } 140 | 141 | pub fn set_connection_upgrade(&mut self) -> &mut Self { 142 | self.set_connection("Upgrade") 143 | } 144 | 145 | pub fn set_cache_control(&mut self, cache: &'b str) -> &mut Self { 146 | self.set("Cache-Control", cache) 147 | } 148 | 149 | pub fn set_cache_control_no_cache(&mut self) -> &mut Self { 150 | self.set_cache_control("No-Cache") 151 | } 152 | 153 | pub fn set_upgrade(&mut self, upgrade: &'b str) -> &mut Self { 154 | self.set("Upgrade", upgrade) 155 | } 156 | 157 | pub fn set_upgrade_websocket(&mut self) -> &mut Self { 158 | self.set_upgrade("websocket") 159 | } 160 | 161 | pub fn as_slice(&self) -> &[(&'b str, &'b str)] { 162 | let index = self 163 | .0 164 | .iter() 165 | .enumerate() 166 | .find(|(_, header)| header.0.is_empty()) 167 | .map(|(index, _)| index) 168 | .unwrap_or(N); 169 | 170 | &self.0[..index] 171 | } 172 | 173 | pub fn release(self) -> [(&'b str, &'b str); N] { 174 | self.0 175 | } 176 | } 177 | 178 | impl Default for Headers<'_, N> { 179 | fn default() -> Self { 180 | Self::new() 181 | } 182 | } 183 | 184 | impl crate::http::Headers for Headers<'_, N> { 185 | fn header(&self, name: &str) -> Option<&'_ str> { 186 | self.get(name) 187 | } 188 | } 189 | 190 | pub mod cookies { 191 | use core::iter; 192 | use core::str::Split; 193 | 194 | pub struct Cookies<'a>(&'a str); 195 | 196 | impl<'a> Cookies<'a> { 197 | pub fn new(cookies_str: &'a str) -> Self { 198 | Self(cookies_str) 199 | } 200 | 201 | pub fn get(&self, name: &str) -> Option<&'a str> { 202 | Cookies::new(self.0) 203 | .into_iter() 204 | .find(|(key, _)| *key == name) 205 | .map(|(_, value)| value) 206 | } 207 | 208 | pub fn set<'b, I>( 209 | iter: I, 210 | name: &'b str, 211 | value: &'b str, 212 | ) -> impl Iterator 213 | where 214 | I: Iterator + 'b, 215 | { 216 | iter.filter(move |(key, _)| *key != name) 217 | .chain(core::iter::once((name, value))) 218 | } 219 | 220 | pub fn remove<'b, I>(iter: I, name: &'b str) -> impl Iterator 221 | where 222 | I: Iterator + 'b, 223 | { 224 | iter.filter(move |(key, _)| *key != name) 225 | } 226 | 227 | pub fn serialize<'b, I>(iter: I) -> impl Iterator 228 | where 229 | I: Iterator + 'b, 230 | { 231 | iter.flat_map(|(k, v)| { 232 | iter::once(";") 233 | .chain(iter::once(k)) 234 | .chain(iter::once("=")) 235 | .chain(iter::once(v)) 236 | }) 237 | .skip(1) 238 | } 239 | } 240 | 241 | impl<'a> IntoIterator for Cookies<'a> { 242 | type Item = (&'a str, &'a str); 243 | 244 | type IntoIter = CookieIterator<'a>; 245 | 246 | fn into_iter(self) -> Self::IntoIter { 247 | CookieIterator::new(self.0) 248 | } 249 | } 250 | 251 | pub struct CookieIterator<'a>(Split<'a, char>); 252 | 253 | impl<'a> CookieIterator<'a> { 254 | pub fn new(cookies: &'a str) -> Self { 255 | Self(cookies.split(';')) 256 | } 257 | } 258 | 259 | impl<'a> Iterator for CookieIterator<'a> { 260 | type Item = (&'a str, &'a str); 261 | 262 | fn next(&mut self) -> Option { 263 | self.0 264 | .next() 265 | .map(|cookie_pair| cookie_pair.split('=')) 266 | .and_then(|mut cookie_pair| { 267 | cookie_pair 268 | .next() 269 | .map(|name| cookie_pair.next().map(|value| (name, value))) 270 | }) 271 | .flatten() 272 | } 273 | } 274 | } 275 | 276 | pub mod server { 277 | pub mod registration { 278 | use crate::http::Method; 279 | 280 | pub struct ChainHandler { 281 | pub path: &'static str, 282 | pub method: Method, 283 | pub handler: H, 284 | pub next: N, 285 | } 286 | 287 | impl ChainHandler { 288 | pub fn get

( 289 | self, 290 | path: &'static str, 291 | handler: H2, 292 | ) -> ChainHandler> { 293 | self.request(path, Method::Get, handler) 294 | } 295 | 296 | pub fn post

( 297 | self, 298 | path: &'static str, 299 | handler: H2, 300 | ) -> ChainHandler> { 301 | self.request(path, Method::Post, handler) 302 | } 303 | 304 | pub fn put

( 305 | self, 306 | path: &'static str, 307 | handler: H2, 308 | ) -> ChainHandler> { 309 | self.request(path, Method::Put, handler) 310 | } 311 | 312 | pub fn delete

( 313 | self, 314 | path: &'static str, 315 | handler: H2, 316 | ) -> ChainHandler> { 317 | self.request(path, Method::Delete, handler) 318 | } 319 | 320 | pub fn request

( 321 | self, 322 | path: &'static str, 323 | method: Method, 324 | handler: H2, 325 | ) -> ChainHandler> { 326 | ChainHandler { 327 | path, 328 | method, 329 | handler, 330 | next: self, 331 | } 332 | } 333 | } 334 | 335 | pub struct ChainRoot; 336 | 337 | impl ChainRoot { 338 | pub fn get

(self, path: &'static str, handler: H2) -> ChainHandler { 339 | self.request(path, Method::Get, handler) 340 | } 341 | 342 | pub fn post

(self, path: &'static str, handler: H2) -> ChainHandler { 343 | self.request(path, Method::Post, handler) 344 | } 345 | 346 | pub fn put

(self, path: &'static str, handler: H2) -> ChainHandler { 347 | self.request(path, Method::Put, handler) 348 | } 349 | 350 | pub fn delete

( 351 | self, 352 | path: &'static str, 353 | handler: H2, 354 | ) -> ChainHandler { 355 | self.request(path, Method::Delete, handler) 356 | } 357 | 358 | pub fn request

( 359 | self, 360 | path: &'static str, 361 | method: Method, 362 | handler: H2, 363 | ) -> ChainHandler { 364 | ChainHandler { 365 | path, 366 | method, 367 | handler, 368 | next: ChainRoot, 369 | } 370 | } 371 | } 372 | } 373 | 374 | // TODO: Commented out as it needs a mutex, yet `embedded-svc` no longer has one 375 | // An option is to depend on `embassy-sync`, yet this decision would be deplayed until 376 | // we figure out in general what to do with the utility code in `embedded-svc`. 377 | // pub mod session { 378 | // use core::convert::TryInto; 379 | // use core::fmt; 380 | // use core::time::Duration; 381 | 382 | // use crate::http::server::*; 383 | 384 | // use crate::utils::http::cookies::*; 385 | // use crate::utils::mutex::{Mutex, RawMutex}; 386 | 387 | // #[derive(Debug)] 388 | // #[cfg_attr(feature = "defmt", derive(defmt::Format))] 389 | // pub enum SessionError { 390 | // MaxSessionsReachedError, 391 | // } 392 | 393 | // impl fmt::Display for SessionError { 394 | // fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 395 | // match self { 396 | // Self::MaxSessionsReachedError => { 397 | // write!(f, "Max number of sessions reached") 398 | // } 399 | // } 400 | // } 401 | // } 402 | 403 | // #[cfg(feature = "std")] 404 | // impl std::error::Error for SessionError {} 405 | 406 | // pub trait Session: Send { 407 | // type SessionData; 408 | 409 | // fn is_existing(&self, session_id: Option<&str>) -> bool; 410 | 411 | // fn with_existing(&self, session_id: Option<&str>, f: F) -> Option 412 | // where 413 | // F: FnOnce(&mut Self::SessionData) -> R; 414 | 415 | // fn with(&self, session_id: &str, f: F) -> Result 416 | // where 417 | // F: FnOnce(&mut Self::SessionData) -> R; 418 | 419 | // fn invalidate(&self, session_id: Option<&str>) -> bool; 420 | // } 421 | 422 | // #[derive(Debug, Default)] 423 | // #[cfg_attr(feature = "defmt", derive(defmt::Format))] 424 | // pub struct SessionData { 425 | // id: heapless::String<32>, 426 | // last_accessed: Duration, 427 | // timeout: Duration, 428 | // data: S, 429 | // } 430 | 431 | // pub struct SessionImpl 432 | // where 433 | // M: RawMutex, 434 | // S: Default + Send, 435 | // { 436 | // current_time: T, 437 | // data: Mutex; N]>, 438 | // default_session_timeout: Duration, 439 | // } 440 | 441 | // impl SessionImpl 442 | // where 443 | // M: RawMutex, 444 | // S: Default + Send, 445 | // { 446 | // fn cleanup(&self, current_time: Duration) { 447 | // let mut data = self.data.lock(); 448 | 449 | // for entry in &mut *data { 450 | // if entry.last_accessed + entry.timeout < current_time { 451 | // entry.id = heapless::String::new(); 452 | // } 453 | // } 454 | // } 455 | // } 456 | 457 | // impl Session for SessionImpl 458 | // where 459 | // M: RawMutex + Send + Sync, 460 | // S: Default + Send, 461 | // T: Fn() -> Duration + Send, 462 | // { 463 | // type SessionData = S; 464 | 465 | // fn is_existing(&self, session_id: Option<&str>) -> bool { 466 | // let current_time = (self.current_time)(); 467 | // self.cleanup(current_time); 468 | 469 | // if let Some(session_id) = session_id { 470 | // let mut data = self.data.lock(); 471 | 472 | // data.iter_mut() 473 | // .find(|entry| entry.id.as_str() == session_id) 474 | // .map(|entry| entry.last_accessed = current_time) 475 | // .is_some() 476 | // } else { 477 | // false 478 | // } 479 | // } 480 | 481 | // fn with_existing(&self, session_id: Option<&str>, f: F) -> Option 482 | // where 483 | // F: FnOnce(&mut Self::SessionData) -> R, 484 | // { 485 | // let current_time = (self.current_time)(); 486 | // self.cleanup(current_time); 487 | 488 | // if let Some(session_id) = session_id { 489 | // let mut data = self.data.lock(); 490 | 491 | // data.iter_mut() 492 | // .find(|entry| entry.id.as_str() == session_id) 493 | // .map(|entry| { 494 | // entry.last_accessed = current_time; 495 | // f(&mut entry.data) 496 | // }) 497 | // } else { 498 | // None 499 | // } 500 | // } 501 | 502 | // fn with<'b, R, F>(&self, session_id: &str, f: F) -> Result 503 | // where 504 | // F: FnOnce(&mut Self::SessionData) -> R, 505 | // { 506 | // let current_time = (self.current_time)(); 507 | // self.cleanup(current_time); 508 | 509 | // let mut data = self.data.lock(); 510 | 511 | // if let Some(entry) = data 512 | // .iter_mut() 513 | // .find(|entry| entry.id.as_str() == session_id) 514 | // .map(|entry| { 515 | // entry.last_accessed = current_time; 516 | 517 | // entry 518 | // }) 519 | // { 520 | // Ok(f(&mut entry.data)) 521 | // } else if let Some(entry) = data.iter_mut().find(|entry| entry.id == "") { 522 | // entry.id = session_id.try_into().unwrap(); 523 | // entry.data = Default::default(); 524 | // entry.timeout = self.default_session_timeout; 525 | // entry.last_accessed = current_time; 526 | 527 | // Ok(f(&mut entry.data)) 528 | // } else { 529 | // Err(SessionError::MaxSessionsReachedError) 530 | // } 531 | // } 532 | 533 | // fn invalidate(&self, session_id: Option<&str>) -> bool { 534 | // let current_time = (self.current_time)(); 535 | // self.cleanup(current_time); 536 | 537 | // if let Some(session_id) = session_id { 538 | // let mut data = self.data.lock(); 539 | 540 | // if let Some(entry) = data 541 | // .iter_mut() 542 | // .find(|entry| entry.id.as_str() == session_id) 543 | // { 544 | // entry.id = heapless::String::new(); 545 | // true 546 | // } else { 547 | // false 548 | // } 549 | // } else { 550 | // false 551 | // } 552 | // } 553 | // } 554 | 555 | // pub fn get_cookie_session_id(headers: &H) -> Option<&str> 556 | // where 557 | // H: Headers, 558 | // { 559 | // headers 560 | // .header("Cookie") 561 | // .and_then(|cookies_str| Cookies::new(cookies_str).get("SESSIONID")) 562 | // } 563 | 564 | // pub fn set_cookie_session_id<'a, const N: usize, H>( 565 | // headers: H, 566 | // session_id: &str, 567 | // cookies: &mut heapless::String, 568 | // ) where 569 | // H: Headers + 'a, 570 | // { 571 | // let cookies_str = headers.header("Cookie").unwrap_or(""); 572 | 573 | // for cookie in Cookies::serialize(Cookies::set( 574 | // Cookies::new(cookies_str).into_iter(), 575 | // "SESSIONID", 576 | // session_id, 577 | // )) { 578 | // cookies.push_str(cookie).unwrap(); // TODO 579 | // } 580 | // } 581 | // } 582 | } 583 | -------------------------------------------------------------------------------- /src/wifi.rs: -------------------------------------------------------------------------------- 1 | use core::fmt::Debug; 2 | use core::mem; 3 | 4 | #[cfg(feature = "alloc")] 5 | extern crate alloc; 6 | 7 | use enumset::*; 8 | 9 | #[cfg(feature = "use_serde")] 10 | use serde::{Deserialize, Serialize}; 11 | 12 | #[cfg(feature = "use_strum")] 13 | use strum_macros::{Display, EnumIter, EnumMessage, EnumString, EnumVariantNames, FromRepr}; 14 | 15 | #[cfg(feature = "use_numenum")] 16 | use num_enum::TryFromPrimitive; 17 | 18 | #[derive(EnumSetType, Debug, PartialOrd)] 19 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 20 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 21 | #[cfg_attr( 22 | feature = "use_strum", 23 | derive(EnumString, Display, EnumMessage, EnumIter, EnumVariantNames, FromRepr) 24 | )] 25 | #[cfg_attr(feature = "use_numenum", derive(TryFromPrimitive))] 26 | #[cfg_attr(feature = "use_numenum", repr(u8))] 27 | #[derive(Default)] 28 | pub enum AuthMethod { 29 | #[cfg_attr(feature = "use_strum", strum(serialize = "none", message = "None"))] 30 | None, 31 | #[cfg_attr(feature = "use_strum", strum(serialize = "wep", message = "WEP"))] 32 | WEP, 33 | #[cfg_attr(feature = "use_strum", strum(serialize = "wpa", message = "WPA"))] 34 | WPA, 35 | #[cfg_attr( 36 | feature = "use_strum", 37 | strum(serialize = "wpa2personal", message = "WPA2 Personal") 38 | )] 39 | #[default] 40 | WPA2Personal, 41 | #[cfg_attr( 42 | feature = "use_strum", 43 | strum(serialize = "wpawpa2personal", message = "WPA & WPA2 Personal") 44 | )] 45 | WPAWPA2Personal, 46 | #[cfg_attr( 47 | feature = "use_strum", 48 | strum(serialize = "wpa2enterprise", message = "WPA2 Enterprise") 49 | )] 50 | WPA2Enterprise, 51 | #[cfg_attr( 52 | feature = "use_strum", 53 | strum(serialize = "wpa3personal", message = "WPA3 Personal") 54 | )] 55 | WPA3Personal, 56 | #[cfg_attr( 57 | feature = "use_strum", 58 | strum(serialize = "wpa2wpa3personal", message = "WPA2 & WPA3 Personal") 59 | )] 60 | WPA2WPA3Personal, 61 | #[cfg_attr( 62 | feature = "use_strum", 63 | strum(serialize = "wapipersonal", message = "WAPI Personal") 64 | )] 65 | WAPIPersonal, 66 | } 67 | 68 | #[derive(EnumSetType, Debug, PartialOrd)] 69 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 70 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 71 | #[cfg_attr( 72 | feature = "use_strum", 73 | derive(EnumString, Display, EnumMessage, EnumIter, EnumVariantNames, FromRepr) 74 | )] 75 | #[cfg_attr(feature = "use_numenum", derive(TryFromPrimitive))] 76 | #[cfg_attr(feature = "use_numenum", repr(u8))] 77 | #[derive(Default)] 78 | pub enum Protocol { 79 | #[cfg_attr( 80 | feature = "use_strum", 81 | strum(serialize = "p802d11b", message = "802.11B") 82 | )] 83 | P802D11B, 84 | #[cfg_attr( 85 | feature = "use_strum", 86 | strum(serialize = "p802d11bg", message = "802.11BG") 87 | )] 88 | P802D11BG, 89 | #[cfg_attr( 90 | feature = "use_strum", 91 | strum(serialize = "p802d11bgn", message = "802.11BGN") 92 | )] 93 | #[default] 94 | P802D11BGN, 95 | #[cfg_attr( 96 | feature = "use_strum", 97 | strum(serialize = "p802d11bgnlr", message = "802.11BGNLR") 98 | )] 99 | P802D11BGNLR, 100 | #[cfg_attr( 101 | feature = "use_strum", 102 | strum(serialize = "p802d11lr", message = "802.11LR") 103 | )] 104 | P802D11LR, 105 | } 106 | 107 | #[derive(EnumSetType, Debug, PartialOrd)] 108 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 109 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 110 | #[cfg_attr( 111 | feature = "use_strum", 112 | derive(EnumString, Display, EnumMessage, EnumIter, EnumVariantNames, FromRepr) 113 | )] 114 | #[cfg_attr(feature = "use_numenum", derive(TryFromPrimitive))] 115 | #[cfg_attr(feature = "use_numenum", repr(u8))] 116 | #[derive(Default)] 117 | pub enum SecondaryChannel { 118 | // TODO: Need to extend that for 5GHz 119 | #[cfg_attr(feature = "use_strum", strum(serialize = "none", message = "None"))] 120 | #[default] 121 | None, 122 | #[cfg_attr(feature = "use_strum", strum(serialize = "above", message = "Above"))] 123 | Above, 124 | #[cfg_attr(feature = "use_strum", strum(serialize = "below", message = "Below"))] 125 | Below, 126 | } 127 | 128 | #[derive(Clone, Debug, Default, PartialEq, Eq)] 129 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 130 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 131 | pub struct AccessPointInfo { 132 | pub ssid: heapless::String<32>, 133 | pub bssid: [u8; 6], 134 | pub channel: u8, 135 | pub secondary_channel: SecondaryChannel, 136 | pub signal_strength: i8, 137 | #[cfg_attr(feature = "defmt", defmt(Debug2Format))] 138 | pub protocols: EnumSet, 139 | pub auth_method: Option, 140 | } 141 | 142 | #[derive(Clone, Debug, PartialEq, Eq)] 143 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 144 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 145 | pub struct AccessPointConfiguration { 146 | pub ssid: heapless::String<32>, 147 | pub ssid_hidden: bool, 148 | pub channel: u8, 149 | pub secondary_channel: Option, 150 | #[cfg_attr(feature = "defmt", defmt(Debug2Format))] 151 | pub protocols: EnumSet, 152 | pub auth_method: AuthMethod, 153 | pub password: heapless::String<64>, 154 | pub max_connections: u16, 155 | } 156 | 157 | impl Default for AccessPointConfiguration { 158 | fn default() -> Self { 159 | Self { 160 | ssid: "iot-device".try_into().unwrap(), 161 | ssid_hidden: false, 162 | channel: 1, 163 | secondary_channel: None, 164 | protocols: Protocol::P802D11B | Protocol::P802D11BG | Protocol::P802D11BGN, 165 | auth_method: AuthMethod::None, 166 | password: heapless::String::new(), 167 | max_connections: 255, 168 | } 169 | } 170 | } 171 | 172 | /// Configuration for wifi in STA mode 173 | #[derive(Clone, PartialEq, Eq)] 174 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 175 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 176 | pub struct ClientConfiguration { 177 | /// SSID of the target AP 178 | pub ssid: heapless::String<32>, 179 | /// BSSID of the target AP 180 | pub bssid: Option<[u8; 6]>, 181 | //pub protocol: Protocol, 182 | #[cfg_attr(feature = "use_serde", serde(default))] 183 | pub auth_method: AuthMethod, 184 | #[cfg_attr(feature = "use_serde", serde(default))] 185 | pub password: heapless::String<64>, 186 | /// The expected Channel of the target AP 187 | /// 188 | /// Connecting might be quicker when the client starts its scan 189 | /// at the channel the target AP is on. 190 | pub channel: Option, 191 | /// The scan method to use when searching for the target AP 192 | #[cfg_attr(feature = "use_serde", serde(default))] 193 | pub scan_method: ScanMethod, 194 | /// Protected Management Frame configuration 195 | #[cfg_attr(feature = "use_serde", serde(default))] 196 | pub pmf_cfg: PmfConfiguration, 197 | } 198 | 199 | impl Debug for ClientConfiguration { 200 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 201 | f.debug_struct("ClientConfiguration") 202 | .field("ssid", &self.ssid) 203 | .field("bssid", &self.bssid) 204 | .field("auth_method", &self.auth_method) 205 | .field("channel", &self.channel) 206 | .field("scan_method", &self.scan_method) 207 | .field("pmf_cfg", &self.pmf_cfg) 208 | .finish() 209 | } 210 | } 211 | 212 | impl Default for ClientConfiguration { 213 | fn default() -> Self { 214 | ClientConfiguration { 215 | ssid: heapless::String::new(), 216 | bssid: None, 217 | auth_method: Default::default(), 218 | password: heapless::String::new(), 219 | channel: None, 220 | scan_method: ScanMethod::default(), 221 | pmf_cfg: PmfConfiguration::default(), 222 | } 223 | } 224 | } 225 | 226 | /// Protected Management Frame configuration 227 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] 228 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 229 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 230 | #[cfg_attr( 231 | feature = "use_strum", 232 | derive(EnumString, Display, EnumMessage, EnumIter, EnumVariantNames) 233 | )] 234 | pub enum PmfConfiguration { 235 | /// No support for PMF will be advertized (default) 236 | #[default] 237 | #[cfg_attr( 238 | feature = "use_strum", 239 | strum( 240 | serialize = "not_capable", 241 | serialize = "pmf_disabled", 242 | to_string = "PMF Disabled", 243 | message = "Don't advertise PMF capabilities", 244 | ) 245 | )] 246 | NotCapable, 247 | /// Advertize PMF support and wether PMF is required or not 248 | #[cfg_attr( 249 | feature = "use_strum", 250 | strum( 251 | serialize = "capable", 252 | to_string = "PMF enabled", 253 | message = "Advertise PMF capabilities", 254 | ) 255 | )] 256 | Capable { required: bool }, 257 | } 258 | impl PmfConfiguration { 259 | /// PMF configuration with PMF strictly required 260 | pub fn new_required() -> Self { 261 | PmfConfiguration::Capable { required: true } 262 | } 263 | /// PMF configuration with PMF optional but available 264 | pub fn new_pmf_optional() -> Self { 265 | PmfConfiguration::Capable { required: true } 266 | } 267 | } 268 | 269 | /// The scan method to use when connecting to an AP 270 | #[derive(Debug, Clone, PartialEq, Eq)] 271 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 272 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 273 | #[cfg_attr( 274 | feature = "use_strum", 275 | derive(EnumString, Display, EnumMessage, EnumIter, EnumVariantNames) 276 | )] 277 | #[non_exhaustive] 278 | pub enum ScanMethod { 279 | /// Scan every channel and connect according to [ScanSortMethod] (default) 280 | #[cfg_attr( 281 | feature = "use_strum", 282 | strum( 283 | serialize = "complete_scan", 284 | to_string = "Complete Scan", 285 | message = "Do a complete scan", 286 | detailed_message = "Scan all APs and sort by a criteria" 287 | ) 288 | )] 289 | CompleteScan(ScanSortMethod), 290 | /// Connect to the first found AP and stop scanning 291 | #[cfg_attr( 292 | feature = "use_strum", 293 | strum( 294 | serialize = "fast_scan", 295 | to_string = "Fast Scan", 296 | message = "Do a fast scan", 297 | detailed_message = "Connect to the first matching AP" 298 | ) 299 | )] 300 | FastScan, 301 | } 302 | impl Default for ScanMethod { 303 | fn default() -> Self { 304 | Self::CompleteScan(ScanSortMethod::default()) 305 | } 306 | } 307 | 308 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] 309 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 310 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 311 | #[cfg_attr( 312 | feature = "use_strum", 313 | derive(EnumString, Display, EnumMessage, EnumIter, EnumVariantNames) 314 | )] 315 | #[non_exhaustive] 316 | pub enum ScanSortMethod { 317 | /// Sort by signal strength (default) 318 | #[default] 319 | #[cfg_attr( 320 | feature = "use_strum", 321 | strum( 322 | serialize = "signal_strength", 323 | serialize = "signal", 324 | to_string = "Signal Strength", 325 | message = "Sort by signal strength" 326 | ) 327 | )] 328 | Signal, 329 | /// Sort by Security 330 | #[cfg_attr( 331 | feature = "use_strum", 332 | strum( 333 | serialize = "security", 334 | to_string = "Security", 335 | message = "Sort by security" 336 | ) 337 | )] 338 | Security, 339 | } 340 | 341 | #[derive(EnumSetType, Debug, PartialOrd)] 342 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 343 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 344 | #[cfg_attr( 345 | feature = "use_strum", 346 | derive(EnumString, Display, EnumMessage, EnumIter, EnumVariantNames, FromRepr) 347 | )] 348 | #[cfg_attr(feature = "use_numenum", derive(TryFromPrimitive))] 349 | #[cfg_attr(feature = "use_numenum", repr(u8))] 350 | pub enum Capability { 351 | #[cfg_attr(feature = "use_strum", strum(serialize = "client", message = "Client"))] 352 | Client, 353 | #[cfg_attr( 354 | feature = "use_strum", 355 | strum(serialize = "ap", message = "Access Point") 356 | )] 357 | AccessPoint, 358 | #[cfg_attr( 359 | feature = "use_strum", 360 | strum(serialize = "mixed", message = "Client & Access Point") 361 | )] 362 | Mixed, 363 | } 364 | 365 | #[derive(Clone, Debug, PartialEq, Eq)] 366 | #[cfg_attr(feature = "defmt", derive(defmt::Format))] 367 | #[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] 368 | #[derive(Default)] 369 | pub enum Configuration { 370 | #[default] 371 | None, 372 | Client(ClientConfiguration), 373 | AccessPoint(AccessPointConfiguration), 374 | Mixed(ClientConfiguration, AccessPointConfiguration), 375 | } 376 | 377 | impl Configuration { 378 | pub fn as_client_conf_ref(&self) -> Option<&ClientConfiguration> { 379 | match self { 380 | Self::Client(client_conf) | Self::Mixed(client_conf, _) => Some(client_conf), 381 | _ => None, 382 | } 383 | } 384 | 385 | pub fn as_ap_conf_ref(&self) -> Option<&AccessPointConfiguration> { 386 | match self { 387 | Self::AccessPoint(ap_conf) | Self::Mixed(_, ap_conf) => Some(ap_conf), 388 | _ => None, 389 | } 390 | } 391 | 392 | pub fn as_client_conf_mut(&mut self) -> &mut ClientConfiguration { 393 | match self { 394 | Self::Client(client_conf) => client_conf, 395 | Self::Mixed(_, _) => { 396 | let prev = mem::replace(self, Self::None); 397 | match prev { 398 | Self::Mixed(client_conf, _) => { 399 | *self = Self::Client(client_conf); 400 | self.as_client_conf_mut() 401 | } 402 | _ => unreachable!(), 403 | } 404 | } 405 | _ => { 406 | *self = Self::Client(Default::default()); 407 | self.as_client_conf_mut() 408 | } 409 | } 410 | } 411 | 412 | pub fn as_ap_conf_mut(&mut self) -> &mut AccessPointConfiguration { 413 | match self { 414 | Self::AccessPoint(ap_conf) => ap_conf, 415 | Self::Mixed(_, _) => { 416 | let prev = mem::replace(self, Self::None); 417 | match prev { 418 | Self::Mixed(_, ap_conf) => { 419 | *self = Self::AccessPoint(ap_conf); 420 | self.as_ap_conf_mut() 421 | } 422 | _ => unreachable!(), 423 | } 424 | } 425 | _ => { 426 | *self = Self::AccessPoint(Default::default()); 427 | self.as_ap_conf_mut() 428 | } 429 | } 430 | } 431 | 432 | pub fn as_mixed_conf_mut( 433 | &mut self, 434 | ) -> (&mut ClientConfiguration, &mut AccessPointConfiguration) { 435 | match self { 436 | Self::Mixed(client_conf, ref mut ap_conf) => (client_conf, ap_conf), 437 | Self::AccessPoint(_) => { 438 | let prev = mem::replace(self, Self::None); 439 | match prev { 440 | Self::AccessPoint(ap_conf) => { 441 | *self = Self::Mixed(Default::default(), ap_conf); 442 | self.as_mixed_conf_mut() 443 | } 444 | _ => unreachable!(), 445 | } 446 | } 447 | Self::Client(_) => { 448 | let prev = mem::replace(self, Self::None); 449 | match prev { 450 | Self::Client(client_conf) => { 451 | *self = Self::Mixed(client_conf, Default::default()); 452 | self.as_mixed_conf_mut() 453 | } 454 | _ => unreachable!(), 455 | } 456 | } 457 | _ => { 458 | *self = Self::Mixed(Default::default(), Default::default()); 459 | self.as_mixed_conf_mut() 460 | } 461 | } 462 | } 463 | } 464 | 465 | pub trait Wifi { 466 | type Error: Debug; 467 | 468 | fn get_capabilities(&self) -> Result, Self::Error>; 469 | 470 | fn get_configuration(&self) -> Result; 471 | 472 | fn set_configuration(&mut self, conf: &Configuration) -> Result<(), Self::Error>; 473 | 474 | fn start(&mut self) -> Result<(), Self::Error>; 475 | fn stop(&mut self) -> Result<(), Self::Error>; 476 | 477 | fn connect(&mut self) -> Result<(), Self::Error>; 478 | fn disconnect(&mut self) -> Result<(), Self::Error>; 479 | 480 | fn is_started(&self) -> Result; 481 | fn is_connected(&self) -> Result; 482 | 483 | fn scan_n( 484 | &mut self, 485 | ) -> Result<(heapless::Vec, usize), Self::Error>; 486 | 487 | #[cfg(feature = "alloc")] 488 | fn scan(&mut self) -> Result, Self::Error>; 489 | } 490 | 491 | impl Wifi for &mut W 492 | where 493 | W: Wifi, 494 | { 495 | type Error = W::Error; 496 | 497 | fn get_capabilities(&self) -> Result, Self::Error> { 498 | (**self).get_capabilities() 499 | } 500 | 501 | fn get_configuration(&self) -> Result { 502 | (**self).get_configuration() 503 | } 504 | 505 | fn set_configuration(&mut self, conf: &Configuration) -> Result<(), Self::Error> { 506 | (*self).set_configuration(conf) 507 | } 508 | 509 | fn start(&mut self) -> Result<(), Self::Error> { 510 | (*self).start() 511 | } 512 | 513 | fn stop(&mut self) -> Result<(), Self::Error> { 514 | (*self).stop() 515 | } 516 | 517 | fn connect(&mut self) -> Result<(), Self::Error> { 518 | (*self).connect() 519 | } 520 | 521 | fn disconnect(&mut self) -> Result<(), Self::Error> { 522 | (*self).disconnect() 523 | } 524 | 525 | fn is_started(&self) -> Result { 526 | (**self).is_started() 527 | } 528 | 529 | fn is_connected(&self) -> Result { 530 | (**self).is_connected() 531 | } 532 | 533 | fn scan_n( 534 | &mut self, 535 | ) -> Result<(heapless::Vec, usize), Self::Error> { 536 | (*self).scan_n() 537 | } 538 | 539 | #[cfg(feature = "alloc")] 540 | fn scan(&mut self) -> Result, Self::Error> { 541 | (*self).scan() 542 | } 543 | } 544 | 545 | pub mod asynch { 546 | use super::*; 547 | 548 | pub trait Wifi { 549 | type Error: Debug; 550 | 551 | async fn get_capabilities(&self) -> Result, Self::Error>; 552 | 553 | async fn get_configuration(&self) -> Result; 554 | 555 | async fn set_configuration(&mut self, conf: &Configuration) -> Result<(), Self::Error>; 556 | 557 | async fn start(&mut self) -> Result<(), Self::Error>; 558 | async fn stop(&mut self) -> Result<(), Self::Error>; 559 | 560 | async fn connect(&mut self) -> Result<(), Self::Error>; 561 | async fn disconnect(&mut self) -> Result<(), Self::Error>; 562 | 563 | async fn is_started(&self) -> Result; 564 | async fn is_connected(&self) -> Result; 565 | 566 | async fn scan_n( 567 | &mut self, 568 | ) -> Result<(heapless::Vec, usize), Self::Error>; 569 | 570 | #[cfg(feature = "alloc")] 571 | async fn scan(&mut self) -> Result, Self::Error>; 572 | } 573 | 574 | impl Wifi for &mut W 575 | where 576 | W: Wifi, 577 | { 578 | type Error = W::Error; 579 | 580 | async fn get_capabilities(&self) -> Result, Self::Error> { 581 | (**self).get_capabilities().await 582 | } 583 | 584 | async fn get_configuration(&self) -> Result { 585 | (**self).get_configuration().await 586 | } 587 | 588 | async fn set_configuration(&mut self, conf: &Configuration) -> Result<(), Self::Error> { 589 | (**self).set_configuration(conf).await 590 | } 591 | 592 | async fn start(&mut self) -> Result<(), Self::Error> { 593 | (**self).start().await 594 | } 595 | 596 | async fn stop(&mut self) -> Result<(), Self::Error> { 597 | (**self).stop().await 598 | } 599 | 600 | async fn connect(&mut self) -> Result<(), Self::Error> { 601 | (**self).connect().await 602 | } 603 | 604 | async fn disconnect(&mut self) -> Result<(), Self::Error> { 605 | (**self).disconnect().await 606 | } 607 | 608 | async fn is_started(&self) -> Result { 609 | (**self).is_started().await 610 | } 611 | 612 | async fn is_connected(&self) -> Result { 613 | (**self).is_connected().await 614 | } 615 | 616 | async fn scan_n( 617 | &mut self, 618 | ) -> Result<(heapless::Vec, usize), Self::Error> { 619 | (**self).scan_n::().await 620 | } 621 | 622 | #[cfg(feature = "alloc")] 623 | async fn scan(&mut self) -> Result, Self::Error> { 624 | (**self).scan().await 625 | } 626 | } 627 | } 628 | --------------------------------------------------------------------------------