Skip to content
This repository was archived by the owner on Aug 1, 2024. It is now read-only.

Commit a0a3fa5

Browse files
committed
Update to the latest esp-idf crates
1 parent 58b9ea6 commit a0a3fa5

File tree

2 files changed

+66
-62
lines changed

2 files changed

+66
-62
lines changed

Cargo.toml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
name = "rust-esp32-std-demo"
33
version = "0.30.0"
44
authors = ["ivmarkov"]
5-
edition = "2018"
5+
edition = "2021"
66
categories = ["embedded", "hardware-support"]
77
keywords = ["embedded", "svc", "idf", "esp-idf", "esp32"]
88
description = "A demo binary crate for the ESP32 and ESP-IDF, which connects to WiFi, Ethernet, drives a small HTTP server and draws on a LED screen"
@@ -19,6 +19,10 @@ opt-level = "z"
1919

2020
[patch.crates-io]
2121
crossbeam-utils = { git = "https://github.com/crossbeam-rs/crossbeam" }
22+
esp-idf-svc = { git = "https://github.com/esp-rs/esp-idf-svc" }
23+
embedded-svc = { git = "https://github.com/esp-rs/embedded-svc" }
24+
esp-idf-hal = { git = "https://github.com/esp-rs/esp-idf-hal" }
25+
esp-idf-sys = { git = "https://github.com/esp-rs/esp-idf-sys" }
2226

2327
[features]
2428
default = []

src/main.rs

Lines changed: 61 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ compile_error!(
2323
);
2424

2525
use core::cell::RefCell;
26-
use core::ffi;
26+
use core::ffi::{self, CStr};
27+
use core::fmt::{self, Debug};
2728
use core::sync::atomic::*;
2829

2930
use std::fs;
@@ -38,7 +39,7 @@ use anyhow::{bail, Result};
3839

3940
use async_io::{Async, Timer};
4041
use esp_idf_svc::http::server::{EspHttpConnection, Request};
41-
use esp_idf_svc::io::Write;
42+
use esp_idf_svc::io::{EspIOError, Write};
4243
use log::*;
4344

4445
use esp_idf_svc::sys::EspError;
@@ -584,7 +585,7 @@ fn test_tcp_bind() -> Result<()> {
584585

585586
fn test_timer(
586587
eventloop: EspBackgroundEventLoop,
587-
mut client: EspMqttClient<ConnState<MessageImpl, EspError>>,
588+
mut client: EspMqttClient<'static>,
588589
) -> Result<EspTimer> {
589590
info!("About to schedule a one-shot timer for after 2 seconds");
590591
let once_timer = EspTaskTimerService::new()?.timer(|| {
@@ -602,7 +603,9 @@ fn test_timer(
602603

603604
let now = EspSystemTime {}.now();
604605

605-
eventloop.post(&EventLoopMessage::new(now), None).unwrap();
606+
eventloop
607+
.post::<CustomEvent>(&CustomEvent::new(now), delay::NON_BLOCK)
608+
.unwrap();
606609

607610
client
608611
.publish(
@@ -621,35 +624,39 @@ fn test_timer(
621624
}
622625

623626
#[derive(Copy, Clone, Debug)]
624-
struct EventLoopMessage(Duration);
627+
struct CustomEvent(Duration);
625628

626-
impl EventLoopMessage {
629+
impl CustomEvent {
627630
pub fn new(duration: Duration) -> Self {
628631
Self(duration)
629632
}
630633
}
631634

632-
impl EspTypedEventSource for EventLoopMessage {
633-
fn source() -> *const ffi::c_char {
634-
b"DEMO-SERVICE\0".as_ptr() as *const _
635+
unsafe impl EspEventSource for CustomEvent {
636+
fn source() -> Option<&'static CStr> {
637+
// String should be unique across the whole project and ESP IDF
638+
Some(CStr::from_bytes_with_nul(b"DEMO-SERVICE\0").unwrap())
635639
}
636640
}
637641

638-
impl EspTypedEventSerializer<EventLoopMessage> for EventLoopMessage {
639-
fn serialize<R>(
640-
event: &EventLoopMessage,
641-
f: impl for<'a> FnOnce(&'a EspEventPostData) -> R,
642-
) -> R {
643-
f(&unsafe { EspEventPostData::new(Self::source(), Self::event_id(), event) })
642+
impl EspEventSerializer for CustomEvent {
643+
type Data<'a> = CustomEvent;
644+
645+
fn serialize<F, R>(event: &Self::Data<'_>, f: F) -> R
646+
where
647+
F: FnOnce(&EspEventPostData) -> R,
648+
{
649+
// Go the easy way since our payload implements Copy and is `'static`
650+
f(&unsafe { EspEventPostData::new(Self::source().unwrap(), Self::event_id(), event) })
644651
}
645652
}
646653

647-
impl EspTypedEventDeserializer<EventLoopMessage> for EventLoopMessage {
648-
fn deserialize<R>(
649-
data: &EspEventFetchData,
650-
f: &mut impl for<'a> FnMut(&'a EventLoopMessage) -> R,
651-
) -> R {
652-
f(unsafe { data.as_payload() })
654+
impl EspEventDeserializer for CustomEvent {
655+
type Data<'a> = CustomEvent;
656+
657+
fn deserialize<'a>(data: &EspEvent<'a>) -> Self::Data<'a> {
658+
// Just as easy as serializing
659+
*unsafe { data.as_payload::<CustomEvent>() }
653660
}
654661
}
655662

@@ -658,14 +665,14 @@ fn test_eventloop() -> Result<(EspBackgroundEventLoop, EspBackgroundSubscription
658665
let eventloop = EspBackgroundEventLoop::new(&Default::default())?;
659666

660667
info!("About to subscribe to the background event loop");
661-
let subscription = eventloop.subscribe(|message: &EventLoopMessage| {
668+
let subscription = eventloop.subscribe::<CustomEvent, _>(|message| {
662669
info!("Got message from the event loop: {:?}", message.0);
663670
})?;
664671

665672
Ok((eventloop, subscription))
666673
}
667674

668-
fn test_mqtt_client() -> Result<EspMqttClient<'static, ConnState<MessageImpl, EspError>>> {
675+
fn test_mqtt_client() -> Result<EspMqttClient<'static>> {
669676
info!("About to start MQTT client");
670677

671678
let conf = MqttClientConfiguration {
@@ -675,8 +682,7 @@ fn test_mqtt_client() -> Result<EspMqttClient<'static, ConnState<MessageImpl, Es
675682
..Default::default()
676683
};
677684

678-
let (mut client, mut connection) =
679-
EspMqttClient::new_with_conn("mqtts://broker.emqx.io:8883", &conf)?;
685+
let (mut client, mut connection) = EspMqttClient::new("mqtts://broker.emqx.io:8883", &conf)?;
680686

681687
info!("MQTT client started");
682688

@@ -690,11 +696,8 @@ fn test_mqtt_client() -> Result<EspMqttClient<'static, ConnState<MessageImpl, Es
690696
thread::spawn(move || {
691697
info!("MQTT Listening for messages");
692698

693-
while let Some(msg) = connection.next() {
694-
match msg {
695-
Err(e) => info!("MQTT Message ERROR: {}", e),
696-
Ok(msg) => info!("MQTT Message: {:?}", msg),
697-
}
699+
while let Ok(event) = connection.next() {
700+
info!("MQTT Event: {}", event.payload());
698701
}
699702

700703
info!("MQTT connection loop exit");
@@ -832,7 +835,7 @@ fn test_https_client() -> anyhow::Result<()> {
832835
let addr = "google.com:443".to_socket_addrs()?.next().unwrap();
833836
let socket = Async::<TcpStream>::connect(addr).await?;
834837

835-
let mut tls = esp_idf_svc::tls::AsyncEspTls::adopt(EspTlsSocket::new(socket))?;
838+
let mut tls = esp_idf_svc::tls::EspAsyncTls::adopt(EspTlsSocket::new(socket))?;
836839

837840
tls.negotiate("google.com", &esp_idf_svc::tls::Config::new())
838841
.await?;
@@ -1206,26 +1209,29 @@ fn httpd(
12061209
mutex: Arc<(Mutex<Option<u32>>, Condvar)>,
12071210
) -> Result<esp_idf_svc::http::server::EspHttpServer<'static>> {
12081211
use esp_idf_svc::http::server::{
1209-
fn_handler, Connection, EspHttpServer, Handler, HandlerResult, Method, Middleware,
1212+
fn_handler, Connection, EspHttpServer, Handler, Method, Middleware,
12101213
};
12111214

12121215
struct SampleMiddleware;
12131216

1214-
impl<'a> Middleware<EspHttpConnection<'a>> for SampleMiddleware {
1215-
fn handle<H>(&self, conn: &mut EspHttpConnection<'a>, handler: &H) -> HandlerResult
1216-
where
1217-
H: Handler<EspHttpConnection<'a>>,
1218-
{
1217+
impl<'a, H> Middleware<EspHttpConnection<'a>, H> for SampleMiddleware
1218+
where
1219+
H: Handler<EspHttpConnection<'a>>,
1220+
H::Error: Debug + fmt::Display + Send + Sync + 'static,
1221+
{
1222+
type Error = anyhow::Error;
1223+
1224+
fn handle(&self, conn: &mut EspHttpConnection<'a>, handler: &H) -> Result<(), Self::Error> {
12191225
info!("Middleware called with uri: {}", conn.uri());
12201226

12211227
if let Err(err) = handler.handle(conn) {
12221228
if !conn.is_response_initiated() {
12231229
let mut resp = Request::wrap(conn).into_status_response(500)?;
12241230

1225-
write!(&mut resp, "ERROR: {err}")?;
1231+
write!(&mut resp, "ERROR: {err:?}")?;
12261232
} else {
12271233
// Nothing can be done as the error happened after the response was initiated, propagate further
1228-
return Err(err);
1234+
Err(anyhow::Error::msg(err))?;
12291235
}
12301236
}
12311237

@@ -1235,11 +1241,13 @@ fn httpd(
12351241

12361242
struct SampleMiddleware2;
12371243

1238-
impl<'a> Middleware<EspHttpConnection<'a>> for SampleMiddleware2 {
1239-
fn handle<H>(&self, conn: &mut EspHttpConnection<'a>, handler: &H) -> HandlerResult
1240-
where
1241-
H: Handler<EspHttpConnection<'a>>,
1242-
{
1244+
impl<'a, H> Middleware<EspHttpConnection<'a>, H> for SampleMiddleware2
1245+
where
1246+
H: Handler<EspHttpConnection<'a>>,
1247+
{
1248+
type Error = H::Error;
1249+
1250+
fn handle(&self, conn: &mut EspHttpConnection<'a>, handler: &H) -> Result<(), H::Error> {
12431251
info!("Middleware2 called");
12441252

12451253
handler.handle(conn)
@@ -1253,33 +1261,25 @@ fn httpd(
12531261
req.into_ok_response()?
12541262
.write_all("Hello from Rust!".as_bytes())?;
12551263

1256-
Ok(())
1257-
})?
1258-
.fn_handler("/foo", Method::Get, |_| {
1259-
Result::Err("Boo, something happened!".into())
1264+
Result::<_, EspIOError>::Ok(())
12601265
})?
1266+
.fn_handler("/foo", Method::Get, |_| bail!("Boo, something happened!"))?
12611267
.fn_handler("/bar", Method::Get, |req| {
12621268
req.into_response(403, Some("No permissions"), &[])?
1263-
.write_all("You have no permissions to access this page".as_bytes())?;
1264-
1265-
Ok(())
1269+
.write_all("You have no permissions to access this page".as_bytes())
12661270
})?
1267-
.fn_handler("/panic", Method::Get, |_| panic!("User requested a panic!"))?
1271+
.fn_handler::<(), _>("/panic", Method::Get, |_| panic!("User requested a panic!"))?
12681272
.handler(
12691273
"/middleware",
12701274
Method::Get,
1271-
SampleMiddleware {}.compose(fn_handler(|_| {
1272-
Result::Err("Boo, something happened!".into())
1273-
})),
1275+
SampleMiddleware {}.compose(fn_handler(|_| bail!("Boo, something happened!"))),
12741276
)?
12751277
.handler(
12761278
"/middleware2",
12771279
Method::Get,
12781280
SampleMiddleware2 {}.compose(SampleMiddleware {}.compose(fn_handler(|req| {
12791281
req.into_ok_response()?
1280-
.write_all("Middleware2 handler called".as_bytes())?;
1281-
1282-
Ok(())
1282+
.write_all("Middleware2 handler called".as_bytes())
12831283
}))),
12841284
)?;
12851285

@@ -1420,13 +1420,13 @@ fn wifi(
14201420

14211421
wifi.set_configuration(&Configuration::Mixed(
14221422
ClientConfiguration {
1423-
ssid: SSID.into(),
1424-
password: PASS.into(),
1423+
ssid: SSID.try_into().unwrap(),
1424+
password: PASS.try_into().unwrap(),
14251425
channel,
14261426
..Default::default()
14271427
},
14281428
AccessPointConfiguration {
1429-
ssid: "aptest".into(),
1429+
ssid: "aptest".try_into().unwrap(),
14301430
channel: channel.unwrap_or(1),
14311431
..Default::default()
14321432
},

0 commit comments

Comments
 (0)