diff --git a/.cargo/config.toml b/.cargo/config.toml index 9e142e2..bc470c0 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,8 +1,8 @@ [target.xtensa-esp32s3-none-elf] -runner = "probe-rs run --chip=esp32s3" +runner = "espflash flash -c esp32s3 -s 16mb -m dio -f 80mhz --no-skip --monitor" [env] -DEFMT_LOG = "info" +ESP_LOG = "INFO" ESP_WIFI_COUNTRY_CODE = "DE" [build] @@ -12,8 +12,3 @@ target = "xtensa-esp32s3-none-elf" [unstable] build-std = ["alloc", "core"] - -[flash] -mode = "qio" -size = "16MB" -frequency = "80MHz" diff --git a/Cargo.lock b/Cargo.lock index 13709a1..74e65e9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -61,20 +61,6 @@ version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" -[[package]] -name = "bt-hci" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f377753756ec12e76b52d2dd657437be0448cc9736402ffadd0b8b8b9602c8a1" -dependencies = [ - "defmt", - "embassy-sync", - "embedded-io", - "embedded-io-async", - "futures-intrusive", - "heapless", -] - [[package]] name = "bytemuck" version = "1.22.0" @@ -143,48 +129,6 @@ dependencies = [ "syn", ] -[[package]] -name = "defmt" -version = "0.3.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86f6162c53f659f65d00619fe31f14556a6e9f8752ccc4a41bd177ffcf3d6130" -dependencies = [ - "bitflags 1.3.2", - "defmt-macros", -] - -[[package]] -name = "defmt-macros" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9d135dd939bad62d7490b0002602d35b358dce5fd9233a709d3c1ef467d4bde6" -dependencies = [ - "defmt-parser", - "proc-macro-error2", - "proc-macro2", - "quote", - "syn", -] - -[[package]] -name = "defmt-parser" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3983b127f13995e68c1e29071e5d115cd96f215ccb5e6812e3728cd6f92653b3" -dependencies = [ - "thiserror", -] - -[[package]] -name = "defmt-rtt" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bab697b3dbbc1750b7c8b821aa6f6e7f2480b47a99bc057a2ed7b170ebef0c51" -dependencies = [ - "critical-section", - "defmt", -] - [[package]] name = "delegate" version = "0.13.2" @@ -229,7 +173,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90327bcc66333a507f89ecc4e2d911b265c45f5c9bc241f98eee076752d35ac6" dependencies = [ "critical-section", - "defmt", "document-features", "embassy-executor-macros", ] @@ -251,9 +194,6 @@ name = "embassy-futures" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f878075b9794c1e4ac788c95b728f26aa6366d32eeb10c7051389f898f7d067" -dependencies = [ - "defmt", -] [[package]] name = "embassy-net" @@ -261,7 +201,6 @@ version = "0.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed041cc19a603d657124fddefdcbe5ef8bd60e77d972793ebb57de93394f5949" dependencies = [ - "defmt", "document-features", "embassy-net-driver", "embassy-sync", @@ -278,9 +217,6 @@ name = "embassy-net-driver" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "524eb3c489760508f71360112bca70f6e53173e6fe48fc5f0efd0f5ab217751d" -dependencies = [ - "defmt", -] [[package]] name = "embassy-sync" @@ -290,7 +226,6 @@ checksum = "8d2c8cdff05a7a51ba0087489ea44b0b1d97a296ca6b1d6d1a33ea7423d34049" dependencies = [ "cfg-if", "critical-section", - "defmt", "embedded-io-async", "futures-sink", "futures-util", @@ -305,7 +240,6 @@ checksum = "f820157f198ada183ad62e0a66f554c610cdcd1a9f27d4b316358103ced7a1f8" dependencies = [ "cfg-if", "critical-section", - "defmt", "document-features", "embassy-time-driver", "embedded-hal 0.2.7", @@ -367,7 +301,6 @@ checksum = "0649998afacf6d575d126d83e68b78c0ab0e00ca2ac7e9b3db11b4cbe8274ef0" dependencies = [ "az", "byteorder", - "defmt", "embedded-graphics-core", "float-cmp", "micromath", @@ -381,7 +314,6 @@ checksum = "ba9ecd261f991856250d2207f6d8376946cd9f412a2165d3b75bc87a0bc7a044" dependencies = [ "az", "byteorder", - "defmt", ] [[package]] @@ -399,9 +331,6 @@ name = "embedded-hal" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "361a90feb7004eca4019fb28352a9465666b24f840f5c3cddf0ff13920590b89" -dependencies = [ - "defmt", -] [[package]] name = "embedded-hal-async" @@ -417,9 +346,6 @@ name = "embedded-io" version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" -dependencies = [ - "defmt", -] [[package]] name = "embedded-io-async" @@ -427,7 +353,6 @@ version = "0.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ff09972d4073aa8c299395be75161d582e7629cd663171d62af73c8d50dba3f" dependencies = [ - "defmt", "embedded-io", ] @@ -535,7 +460,6 @@ version = "0.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4cd70abe47945c9116972781b5c05277ad855a5f5569fe2afd3e2e61a103cc0" dependencies = [ - "defmt", "esp-build", "esp-println", "semihosting", @@ -574,7 +498,6 @@ dependencies = [ "cfg-if", "chrono", "critical-section", - "defmt", "delegate", "document-features", "embassy-embedded-hal", @@ -594,15 +517,10 @@ dependencies = [ "esp-metadata", "esp-riscv-rt", "esp-synopsys-usb-otg", - "esp32", - "esp32c2", - "esp32c3", - "esp32c6", - "esp32h2", - "esp32s2", "esp32s3", "fugit", "instability", + "log", "nb 1.1.0", "paste", "portable-atomic", @@ -624,7 +542,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b27f41110117a9bf2be385b42535c686b301c8ce3b5ea0a07567e200a63a2239" dependencies = [ "critical-section", - "defmt", "document-features", "embassy-executor", "embassy-sync", @@ -675,8 +592,10 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "960703930f9f3c899ddedd122ea27a09d6a612c22323157e524af5b18876448e" dependencies = [ + "critical-section", "esp-build", "log", + "portable-atomic", ] [[package]] @@ -709,10 +628,8 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cd7d7ea0e2c374343a375758861e13cf618db619436bcb386dfe5529ef31e9d5" dependencies = [ - "bt-hci", "cfg-if", "critical-section", - "defmt", "document-features", "embassy-net-driver", "embassy-sync", @@ -727,13 +644,13 @@ dependencies = [ "esp-wifi-sys", "heapless", "libm", + "log", "num-derive", "num-traits", "portable-atomic", "portable_atomic_enum", "rand_core", "serde", - "smoltcp", "xtensa-lx-rt", ] @@ -744,26 +661,13 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6b5438361891c431970194a733415006fb3d00b6eb70b3dcb66fd58f04d9b39" dependencies = [ "anyhow", - "defmt", -] - -[[package]] -name = "esp32" -version = "0.36.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3d9b774d7a2c96550a5c25016c2abd33370ebac60e534484b7bca344ecb8a3d6" -dependencies = [ - "critical-section", - "defmt", - "vcell", + "log", ] [[package]] name = "esp32-homecontrol" version = "0.1.0" dependencies = [ - "defmt", - "defmt-rtt", "embassy-executor", "embassy-futures", "embassy-net", @@ -776,6 +680,7 @@ dependencies = [ "esp-backtrace", "esp-hal", "esp-hal-embassy", + "esp-println", "esp-wifi", "heapless", "mipidsi", @@ -786,61 +691,6 @@ dependencies = [ "static_cell", ] -[[package]] -name = "esp32c2" -version = "0.25.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6f7037cfa7c93574b0891062f980a75ae97e9d6c93dcaff3e060b37cf1281c59" -dependencies = [ - "critical-section", - "defmt", - "vcell", -] - -[[package]] -name = "esp32c3" -version = "0.28.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df1bbcfa3ab2979171263db80804dabc38bdd45450c7eb775ee3f81d552cf0ba" -dependencies = [ - "critical-section", - "defmt", - "vcell", -] - -[[package]] -name = "esp32c6" -version = "0.19.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ff2a4e1d1b0cb2517af20766004b8e8fb4612043f0b0569703cc90d1880ede4" -dependencies = [ - "critical-section", - "defmt", - "vcell", -] - -[[package]] -name = "esp32h2" -version = "0.15.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eee7512ae8da61338545804a76c5bc9816a9122abbf2f23d1195e3d45fab79af" -dependencies = [ - "critical-section", - "defmt", - "vcell", -] - -[[package]] -name = "esp32s2" -version = "0.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a22733ee6f4bb08e3113df6651b2c350f37c44314017476e354ec951a55465e9" -dependencies = [ - "critical-section", - "defmt", - "vcell", -] - [[package]] name = "esp32s3" version = "0.31.0" @@ -848,7 +698,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c6d20f119410092abfbc65e46f9362015a7110023528f0dbe855cab80c38ca8" dependencies = [ "critical-section", - "defmt", "vcell", ] @@ -873,7 +722,6 @@ version = "0.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "17186ad64927d5ac8f02c1e77ccefa08ccd9eaa314d5a4772278aa204a22f7e7" dependencies = [ - "defmt", "gcd", ] @@ -883,16 +731,6 @@ version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" -[[package]] -name = "futures-intrusive" -version = "0.5.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" -dependencies = [ - "futures-core", - "lock_api", -] - [[package]] name = "futures-sink" version = "0.3.31" @@ -944,7 +782,6 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bfb9eb618601c89945a70e254898da93b13be0388091d42117462b265bb3fad" dependencies = [ - "defmt", "hash32", "portable-atomic", "serde", @@ -1019,16 +856,6 @@ dependencies = [ "proc-macro2", ] -[[package]] -name = "lock_api" -version = "0.4.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17" -dependencies = [ - "autocfg", - "scopeguard", -] - [[package]] name = "log" version = "0.4.26" @@ -1088,9 +915,6 @@ name = "nb" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d5439c4ad607c3c23abf66de8c8bf57ba8adcd1f129e699851a6e43935d339d" -dependencies = [ - "defmt", -] [[package]] name = "num-derive" @@ -1286,7 +1110,6 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f71160765f368fd9a84e0955e2ddb6d64ac9018fee1c5323354d6d08c816b40" dependencies = [ - "defmt", "embedded-io", "embedded-io-async", "heapless", @@ -1305,12 +1128,6 @@ version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f" -[[package]] -name = "scopeguard" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" - [[package]] name = "semihosting" version = "0.1.19" @@ -1367,7 +1184,6 @@ dependencies = [ "bitflags 1.3.2", "byteorder", "cfg-if", - "defmt", "heapless", "managed", ] @@ -1457,26 +1273,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "thiserror" -version = "2.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708" -dependencies = [ - "thiserror-impl", -] - -[[package]] -name = "thiserror-impl" -version = "2.0.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] - [[package]] name = "toml" version = "0.8.20" diff --git a/Cargo.toml b/Cargo.toml index fdf3e34..4715479 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,16 +8,15 @@ esp-backtrace = { version = "0.15.0", features = [ "esp32s3", "exception-handler", "panic-handler", - "defmt", + "println", ] } -esp-hal = { version = "1.0.0-beta.0", features = ["esp32s3", "defmt", "unstable"] } +esp-hal = { version = "1.0.0-beta.0", features = ["esp32s3", "unstable"] } esp-alloc = { version = "0.7.0" } embassy-net = { version = "0.6.0", features = [ "tcp", "udp", "dns", "dhcpv4", - "defmt", "dhcpv4-hostname", ] } @@ -26,31 +25,26 @@ esp-wifi = { version = "0.13.0", features = [ "esp32s3", "serde", "wifi", - "defmt", + "log", ] } heapless = { version = "0.8.0", default-features = false } -defmt = "0.3.8" -defmt-rtt = "0.4.1" -embassy-executor = { version = "0.7.0", features = [ - "task-arena-size-163840", - "defmt", -] } -embassy-time = { version = "0.4.0", features = ["defmt"] } -esp-hal-embassy = { version = "0.7.0", features = ["esp32s3", "defmt"] } -rust-mqtt = { version = "0.3.0", default-features = false, features = [ - "defmt", -] } +esp-println = { version = "0.13.1", features = ["log", "esp32s3"] } +embassy-executor = { version = "0.7.0", features = ["task-arena-size-163840"] } +embassy-time = { version = "0.4.0", features = [] } +esp-hal-embassy = { version = "0.7.0", features = ["esp32s3"] } +rust-mqtt = { version = "0.3.0", default-features = false, features = [] } embedded-text = "0.7.2" -embedded-graphics = { version = "0.8.1", features = ["defmt"] } -embedded-hal = { version = "1.0.0", features = ["defmt-03"] } +embedded-graphics = { version = "0.8.1", features = [] } +embedded-hal = { version = "1.0.0", features = [] } serde = { version = "1.0.215", default-features = false, features = ["derive"] } serde_json = { version = "1.0.133", default-features = false, features = [ "alloc", ] } -embassy-futures = { version = "0.1.1", features = ["defmt"] } -embassy-sync = { version = "0.6.0", features = ["defmt"] } +embassy-futures = { version = "0.1.1", features = [] } +embassy-sync = { version = "0.6.0", features = [] } static_cell = "2.1.0" -nb = { version = "1.1.0", features = ["defmt-0-3"] } +nb = { version = "1.1.0", features = [] } + [profile.dev] # Rust debug is too slow. diff --git a/build.rs b/build.rs index bc59d47..5efe9c9 100644 --- a/build.rs +++ b/build.rs @@ -1,5 +1,3 @@ fn main() { println!("cargo:rustc-link-arg-bins=-Tlinkall.x"); - //println!("cargo:rustc-link-arg-bins=-Trom_functions.x"); - println!("cargo:rustc-link-arg-bins=-Tdefmt.x"); } diff --git a/src/display.rs b/src/display.rs index 24ef091..071fc71 100644 --- a/src/display.rs +++ b/src/display.rs @@ -1,4 +1,3 @@ -use defmt::Format; use embedded_graphics::draw_target::DrawTarget; use embedded_graphics::geometry::Dimensions; use embedded_graphics::mono_font::iso_8859_1::FONT_10X20 as FONT; @@ -150,11 +149,11 @@ pub enum Error { InitError, } -impl Format for Error { - fn format(&self, f: defmt::Formatter) { +impl core::fmt::Display for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { - Error::DisplayInterface(e) => defmt::write!(f, "Display error {}", e), - Error::InitError => defmt::write!(f, "Init error"), + Error::DisplayInterface(msg) => write!(f, "Display interface error: {}", msg), + Error::InitError => write!(f, "Display initialization error"), } } } diff --git a/src/domain.rs b/src/domain.rs index effd427..6629cee 100644 --- a/src/domain.rs +++ b/src/domain.rs @@ -1,6 +1,5 @@ use alloc::string::{String, ToString}; use core::fmt::{Display, Formatter, Result}; -use defmt::Format; use heapless::Vec; use serde::{Deserialize, Serialize}; @@ -29,7 +28,7 @@ impl Display for SensorData { } } -#[derive(Debug, Serialize, Deserialize, Format, PartialEq)] +#[derive(Debug, Serialize, Deserialize, PartialEq)] pub enum MoistureLevel { Wet, Moist, @@ -60,7 +59,7 @@ impl From for MoistureLevel { } } -#[derive(Debug, Serialize, Deserialize, Format)] +#[derive(Debug, Serialize, Deserialize)] pub enum WaterLevel { Full, Empty, diff --git a/src/main.rs b/src/main.rs index e80b677..3e541ff 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,7 +3,6 @@ use alloc::format; use config::{AWAKE_DURATION_SECONDS, DEEP_SLEEP_DURATION_SECONDS}; -use defmt::{error, info}; use display::{Display, DisplayPeripherals, DisplayTrait}; use domain::SensorData; use embassy_executor::Spawner; @@ -14,13 +13,15 @@ use embassy_sync::{ }; use embassy_time::{Delay, Duration, Timer}; use esp_alloc::heap_allocator; +use esp_backtrace as _; use esp_hal::{ - clock::CpuClock, gpio::{Level, Output, OutputConfig}, ram, + system::software_reset, timer::timg::TimerGroup, }; use esp_hal_embassy::main; +use esp_println::println; use esp_wifi::wifi::WifiError; use relay_task::relay_task; use sensors_task::{sensor_task, SensorPeripherals}; @@ -28,7 +29,6 @@ use sleep::enter_deep; use static_cell::StaticCell; use update_task::update_task; use wifi::{connect_to_wifi, STOP_WIFI_SIGNAL}; -use {defmt_rtt as _, esp_backtrace as _}; extern crate alloc; @@ -59,22 +59,19 @@ static mut DISCOVERY_MESSAGES_SENT: bool = false; #[main] async fn main(spawner: Spawner) { let boot_count = unsafe { BOOT_COUNT }; - info!("Current boot count = {}", &boot_count); + println!("Current boot count = {}", &boot_count); unsafe { BOOT_COUNT = boot_count + 1; } if let Err(error) = main_fallible(spawner, boot_count).await { - error!("Error while running firmware: {}", error); + println!("Error while running firmware: {:?}", error); + software_reset() } } async fn main_fallible(spawner: Spawner, boot_count: u32) -> Result<(), Error> { - let peripherals = esp_hal::init(esp_hal::Config::default().with_cpu_clock(CpuClock::_160MHz)); - - // This IO15 must be set to HIGH, otherwise nothing will be displayed when USB is not connected. - let mut power_pin = Output::new(peripherals.GPIO15, Level::Low, OutputConfig::default()); - power_pin.set_high(); + let peripherals = esp_hal::init(esp_hal::Config::default()); heap_allocator!(size: 72 * 1024); @@ -83,6 +80,10 @@ async fn main_fallible(spawner: Spawner, boot_count: u32) -> Result<(), Error> { esp_hal_embassy::init(timg0.timer0); + // This IO15 must be set to HIGH, otherwise nothing will be displayed when USB is not connected. + let mut power_pin = Output::new(peripherals.GPIO15, Level::Low, OutputConfig::default()); + power_pin.set_high(); + let stack = connect_to_wifi( peripherals.WIFI, timg1.timer0, @@ -120,10 +121,10 @@ async fn main_fallible(spawner: Spawner, boot_count: u32) -> Result<(), Error> { .as_str(), )?; } else { - error!("Failed to get stack config"); + println!("Failed to get stack config"); } - info!("Create channel"); + println!("Create channel"); let channel: &'static mut _ = CHANNEL.init(Channel::new()); let receiver = channel.receiver(); let sender = channel.sender(); @@ -148,26 +149,35 @@ async fn main_fallible(spawner: Spawner, boot_count: u32) -> Result<(), Error> { let awake_duration = Duration::from_secs(AWAKE_DURATION_SECONDS); - info!("Stay awake for {}s", awake_duration.as_secs()); + println!("Stay awake for {}s", awake_duration.as_secs()); Timer::after(awake_duration).await; - info!("Request to disconnect wifi"); + println!("Request to disconnect wifi"); STOP_WIFI_SIGNAL.signal(()); // set power pin to low to save power power_pin.set_low(); let deep_sleep_duration = Duration::from_secs(DEEP_SLEEP_DURATION_SECONDS); - info!("Enter deep sleep for {}s", DEEP_SLEEP_DURATION_SECONDS); + println!("Enter deep sleep for {}s", DEEP_SLEEP_DURATION_SECONDS); let mut wake_up_btn_pin = peripherals.GPIO14; enter_deep(&mut wake_up_btn_pin, peripherals.LPWR, deep_sleep_duration); } -#[derive(Debug, defmt::Format)] +#[derive(Debug)] enum Error { Wifi(WifiError), Display(display::Error), } +impl core::fmt::Display for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Error::Wifi(error) => write!(f, "Wifi error: {:?}", error), + Error::Display(error) => write!(f, "Display error: {}", error), + } + } +} + impl From for Error { fn from(error: WifiError) -> Self { Self::Wifi(error) diff --git a/src/relay_task.rs b/src/relay_task.rs index d09e52c..07fbd0d 100644 --- a/src/relay_task.rs +++ b/src/relay_task.rs @@ -1,6 +1,6 @@ -use defmt::info; use embassy_time::{Duration, Timer}; use esp_hal::gpio::{GpioPin, Level, Output, OutputConfig}; +use esp_println::println; use crate::ENABLE_PUMP; @@ -8,17 +8,17 @@ const PUMP_INTERVAL: Duration = Duration::from_secs(10); #[embassy_executor::task] pub async fn relay_task(pin: GpioPin<2>) { - info!("Created a relay task"); + println!("Created a relay task"); // Configure GPIO pin for relay (using GPIO2) let mut dht_pin = Output::new(pin, Level::Low, OutputConfig::default()); loop { let start_pump = ENABLE_PUMP.wait().await; if start_pump { - info!("Turning on pump"); + println!("Turning on pump"); dht_pin.set_high(); Timer::after(PUMP_INTERVAL).await; - info!("Turning off"); + println!("Turning off"); dht_pin.set_low(); } } diff --git a/src/sensors_task.rs b/src/sensors_task.rs index 728b259..f3a7656 100644 --- a/src/sensors_task.rs +++ b/src/sensors_task.rs @@ -1,4 +1,3 @@ -use defmt::{error, info, warn}; use embassy_sync::{blocking_mutex::raw::NoopRawMutex, channel::Sender}; use embassy_time::{Delay, Duration, Timer}; use esp_hal::{ @@ -10,6 +9,7 @@ use esp_hal::{ peripherals::{ADC1, ADC2}, Blocking, }; +use esp_println::println; use heapless::Vec; use crate::{ @@ -21,7 +21,8 @@ use crate::{ const USB_CHARGING_VOLTAGE: u16 = 4200; const DHT11_WARMUP_DELAY_MILLISECONDS: u64 = 2000; const SENSOR_WARMUP_DELAY_MILLISECONDS: u64 = 50; -const SENSOR_SAMPLE_COUNT: usize = 6; +// in this case we keep 3 samples for averaging - first and last are ignored +const SENSOR_SAMPLE_COUNT: usize = 5; pub struct SensorPeripherals { pub dht11_digital_pin: GpioPin<1>, @@ -39,7 +40,7 @@ pub async fn sensor_task( sender: Sender<'static, NoopRawMutex, SensorData, 3>, mut p: SensorPeripherals, ) { - info!("Create"); + println!("Create"); let mut adc2_config = AdcConfig::new(); let mut moisture_pin = adc2_config @@ -72,7 +73,7 @@ pub async fn sensor_task( let sampling_period = Duration::from_secs(AWAKE_DURATION_SECONDS); for i in 0..SENSOR_SAMPLE_COUNT { - info!("Reading sensor data {}/{}", (i + 1), SENSOR_SAMPLE_COUNT); + println!("Reading sensor data {}/{}", (i + 1), SENSOR_SAMPLE_COUNT); { let mut dht11_pin = Output::new( @@ -104,13 +105,13 @@ pub async fn sensor_task( .push(result) .expect("Too many samples"); } else { - warn!("Error reading soil moisture sensor"); + println!("Error reading soil moisture sensor"); } if let Some(value) = sample_adc(&mut adc2, &mut waterlevel_pin).await { water_level_samples.push(value).expect("Too many samples"); } else { - warn!("Error reading water level sensor"); + println!("Error reading water level sensor"); } if let Some(value) = sample_adc(&mut adc1, &mut battery_pin).await { @@ -120,13 +121,13 @@ pub async fn sensor_task( .push(value) .expect("Too many samples"); } else { - warn!( + println!( "Battery voltage too high - looks we are charging on USB: {}mV", value ); } } else { - warn!("Error reading battery voltage"); + println!("Error reading battery voltage"); } } @@ -134,26 +135,26 @@ pub async fn sensor_task( let mut sensor_data = SensorData::default(); if let Some(avg_air_humidity) = calculate_average(&mut air_humidity_samples) { - info!("Air humidity: {}%", avg_air_humidity); + println!("Air humidity: {}%", avg_air_humidity); sensor_data .data .push(Sensor::AirHumidity(avg_air_humidity)) .expect("Too many samples"); } else { - warn!( + println!( "Unable to generate average value of air humidity - we had {} samples", air_humidity_samples.len() ); } if let Some(avg_air_temperature) = calculate_average(&mut air_temperature_samples) { - info!("Air temperature: {}°C", avg_air_temperature); + println!("Air temperature: {}°C", avg_air_temperature); sensor_data .data .push(Sensor::AirTemperature(avg_air_temperature)) .expect("Too many samples"); } else { - warn!( + println!( "Unable to generate average value of air temperature, we had {} samples", air_temperature_samples.len() ); @@ -161,17 +162,17 @@ pub async fn sensor_task( if let Some(avg_water_level) = calculate_average(&mut water_level_samples) { let waterlevel: WaterLevel = avg_water_level.into(); - info!("Water level: {}", waterlevel); + println!("Water level: {}", waterlevel); sensor_data .data .push(Sensor::WaterLevel(avg_water_level.into())) .expect("Too many samples"); } else { - warn!("Unable to generate average value of water level"); + println!("Unable to generate average value of water level"); } if let Some(avg_soil_moisture) = calculate_average(&mut soil_moisture_samples) { - info!("Raw Moisture: {}", avg_soil_moisture); + println!("Raw Moisture: {}", avg_soil_moisture); sensor_data .data .push(Sensor::SoilMoistureRaw(avg_soil_moisture.into())) @@ -189,23 +190,23 @@ pub async fn sensor_task( .push(Sensor::PumpTrigger(moisture_level == MoistureLevel::Dry)) .expect("Too many samples"); } else { - warn!("Unable to generate average value of soil moisture"); + println!("Unable to generate average value of soil moisture"); } if let Some(avg_battery_voltage) = calculate_average(&mut battery_voltage_samples) { - info!("Battery voltage: {}mV", avg_battery_voltage); + println!("Battery voltage: {}mV", avg_battery_voltage); sensor_data .data .push(Sensor::BatteryVoltage(avg_battery_voltage)) .expect("Too many samples"); } else { - warn!("Error measuring battery voltage"); + println!("Error measuring battery voltage"); } if battery_voltage_samples.is_empty() { - warn!( - "No battery voltage samples collected - skipping this cycle {}", - defmt::Display2Format(&sensor_data) + println!( + "No battery voltage samples collected - skipping this cycle {:?}", + &sensor_data ); } else { sender.send(sensor_data).await; @@ -240,7 +241,7 @@ where match nb::block!(adc.read_oneshot(pin)) { Ok(value) => Some(value), Err(e) => { - error!("Error reading sensor: {}", defmt::Debug2Format(&e)); + println!("Error reading sensor: {:?}", &e); None } } diff --git a/src/sleep.rs b/src/sleep.rs index 978b895..a418ccf 100644 --- a/src/sleep.rs +++ b/src/sleep.rs @@ -1,9 +1,9 @@ -use defmt::info; use embassy_time::Duration; use esp_hal::gpio::RtcPin; use esp_hal::peripherals::LPWR; use esp_hal::rtc_cntl::sleep::{RtcSleepConfig, RtcioWakeupSource, TimerWakeupSource, WakeupLevel}; use esp_hal::rtc_cntl::Rtc; +use esp_println::println; /// Enter deep sleep mode for the specified duration. pub fn enter_deep(wakeup_pin: &mut dyn RtcPin, rtc_cntl: LPWR, interval: Duration) -> ! { @@ -17,7 +17,7 @@ pub fn enter_deep(wakeup_pin: &mut dyn RtcPin, rtc_cntl: LPWR, interval: Duratio let mut config = RtcSleepConfig::deep(); config.set_rtc_fastmem_pd_en(false); - info!("Entering deep sleep for {}", interval); + println!("Entering deep sleep for {}", interval); rtc.sleep(&config, &[&ext0, &wakeup_source_timer]); unreachable!(); } diff --git a/src/update_task.rs b/src/update_task.rs index cf0ccdf..8274c44 100644 --- a/src/update_task.rs +++ b/src/update_task.rs @@ -3,7 +3,6 @@ use alloc::{ string::{String, ToString}, }; use core::{num::ParseIntError, str}; -use defmt::{error, info}; use embassy_futures::select::{select, Either}; use embassy_net::{ dns::{DnsQueryType, Error as DnsError}, @@ -12,6 +11,7 @@ use embassy_net::{ }; use embassy_sync::{blocking_mutex::raw::NoopRawMutex, channel::Receiver}; use embassy_time::{Delay, Duration, Timer}; +use esp_println::println; use rust_mqtt::{ client::{ client::MqttClient, @@ -64,7 +64,7 @@ pub async fn update_task( let mut client = match initialize_mqtt_client(stack, resources).await { Ok(client) => client, Err(e) => { - error!("Error initializing MQTT client: {}", e); + println!("Error initializing MQTT client: {:?}", e); continue; } }; @@ -73,16 +73,16 @@ pub async fn update_task( .subscribe_to_topic("esp32_breadboard/pump/command") .await { - error!("Error subscribing to pump command topic: {}", e); + println!("Error subscribing to pump command topic: {}", e); continue; } - info!("Subscribed to pump command topic"); + println!("Subscribed to pump command topic"); match select(receiver.receive(), client.receive_message()).await { Either::First(sensor_data) => { if let Err(e) = handle_sensor_data(&mut client, &mut display, sensor_data).await { - error!("Error handling sensor data: {}", e); + println!("Error handling sensor data: {:?}", e); continue; } } @@ -91,7 +91,7 @@ pub async fn update_task( handle_mqtt_message(topic, data); } Err(e) => { - error!("Error handling MQTT message: {}", e); + println!("Error handling MQTT message: {}", e); continue; } }, @@ -115,11 +115,11 @@ async fn initialize_mqtt_client<'a>( let port = env!("MQTT_PORT").parse()?; let socket_addr = (host_addr, port); - info!("Connecting to MQTT server..."); + println!("Connecting to MQTT server..."); socket.connect(socket_addr).await?; - info!("Connected to MQTT server"); + println!("Connected to MQTT server"); - info!("Initializing MQTT connection"); + println!("Initializing MQTT connection"); let mut mqtt_config: ClientConfig<5, CountingRng> = ClientConfig::new(MQTTv5, CountingRng(20000)); mqtt_config.add_username(env!("MQTT_USERNAME")); @@ -137,7 +137,7 @@ async fn initialize_mqtt_client<'a>( client.connect_to_broker().await?; - info!("MQTT Broker connected"); + println!("MQTT Broker connected"); Ok(client) } @@ -149,7 +149,7 @@ async fn handle_sensor_data( ) -> Result<(), Error> { let discovery_messages_sent = unsafe { DISCOVERY_MESSAGES_SENT }; if !discovery_messages_sent { - info!("First run, sending discovery messages"); + println!("First run, sending discovery messages"); for s in &sensor_data.data { let (discovery_topic, message) = get_sensor_discovery(s); client @@ -176,20 +176,20 @@ async fn handle_sensor_data( DISCOVERY_MESSAGES_SENT = true; } } else { - info!("Discovery messages already sent"); + println!("Discovery messages already sent"); } // act on sensor data - turn pump on/off sensor_data.data.iter().for_each(|entry| { if let Sensor::WaterLevel(WaterLevel::Full) = entry { // Water level is full, stop the pump in any case if it's running - info!("Water level is full, stopping pump"); - ENABLE_PUMP.signal(false); + println!("Water level is full, stopping pump"); + update_pump_state(false); } else if let Sensor::PumpTrigger(enabled) = entry { // Pump trigger is enabled, start the pump if *enabled { - info!("Soil moisture is low, starting pump"); - ENABLE_PUMP.signal(true); + println!("Soil moisture is low, starting pump"); + update_pump_state(true); } } }); @@ -200,7 +200,7 @@ async fn handle_sensor_data( let message = json!({ "value": value }).to_string(); let topic_name = format!("{}/{}", DEVICE_ID, key); - info!( + println!( "Publishing to topic {}, message: {}", topic_name.as_str(), message.as_str() @@ -220,7 +220,7 @@ async fn handle_sensor_data( let pump_topic = format!("{}/pump/state", DEVICE_ID); let message = "OFF"; - info!( + println!( "Publishing to topic {}, message: {}", pump_topic.as_str(), message @@ -246,15 +246,23 @@ fn handle_mqtt_message(topic: &str, data: &[u8]) { let msg = str::from_utf8(data).ok(); if let Some(message) = msg { - info!("Received message: {} on topic {}", msg, topic); + println!("Received message: {:?} on topic {}", msg, topic); let state = message == "ON"; - info!("Pump state: {}", state); - ENABLE_PUMP.signal(state); + println!("Pump state: {}", state); + update_pump_state(state); } else { - info!("Invalid message received on topic {}", topic); + println!("Invalid message received on topic {}", topic); } } +pub fn update_pump_state(state: bool) { + // Use a scoped block so that the signal operation (which may internally acquire a mutex) + // does not accidentally span long-running operations. + { + ENABLE_PUMP.signal(state); + } // Critical section ends here immediately. +} + /// Get the MQTT discovery message for a sensor fn get_sensor_discovery(s: &Sensor) -> (String, String) { let topic = s.topic(); @@ -316,7 +324,7 @@ fn get_common_device_info(topic: &str, name: &str) -> Value { }) } -#[derive(Debug, defmt::Format)] +#[derive(Debug)] enum Error { Port, Dns(DnsError), @@ -325,6 +333,18 @@ enum Error { Display(display::Error), } +impl core::fmt::Display for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Error::Port => write!(f, "Port error"), + Error::Dns(e) => write!(f, "DNS error: {:?}", e), + Error::Connection(e) => write!(f, "Connection error: {:?}", e), + Error::Broker(e) => write!(f, "Broker error: {:?}", e), + Error::Display(e) => write!(f, "Display error: {:?}", e), + } + } +} + impl From for Error { fn from(error: embassy_net::dns::Error) -> Self { Self::Dns(error) diff --git a/src/wifi.rs b/src/wifi.rs index 245f313..10a61f0 100644 --- a/src/wifi.rs +++ b/src/wifi.rs @@ -1,5 +1,4 @@ use core::str::FromStr; -use defmt::{error, info}; use embassy_executor::Spawner; use embassy_net::{Runner, Stack, StackResources}; use embassy_sync::{blocking_mutex::raw::CriticalSectionRawMutex, signal::Signal}; @@ -8,6 +7,7 @@ use esp_hal::{ peripherals::{self, RNG}, rng::Rng, }; +use esp_println::println; use esp_wifi::wifi::{ ClientConfiguration, Configuration, WifiController, WifiDevice, WifiError, WifiEvent, WifiState, }; @@ -45,14 +45,14 @@ pub async fn connect_to_wifi( let seed = rng.random(); let config = embassy_net::Config::dhcpv4(dhcp_config); - info!("Initialize network stack"); + println!("Initialize network stack"); let stack_resources: &'static mut _ = STACK_RESOURCES.init(StackResources::new()); let (stack, runner) = embassy_net::new(wifi_interface, config, stack_resources, seed.into()); spawner.spawn(connection(controller)).ok(); spawner.spawn(net_task(runner)).ok(); - info!("Wait for network link"); + println!("Wait for network link"); loop { if stack.is_link_up() { break; @@ -60,10 +60,10 @@ pub async fn connect_to_wifi( Timer::after(Duration::from_millis(500)).await; } - info!("Wait for IP address"); + println!("Wait for IP address"); loop { if let Some(config) = stack.config_v4() { - info!("Connected to WiFi with IP address {}", config.address); + println!("Connected to WiFi with IP address {}", config.address); break; } Timer::after(Duration::from_millis(500)).await; @@ -83,15 +83,15 @@ async fn net_task(mut runner: Runner<'static, WifiDevice<'static>>) { #[embassy_executor::task] async fn connection(controller: WifiController<'static>) { if let Err(error) = connection_fallible(controller).await { - error!("Cannot connect to WiFi: {}", error); + println!("Cannot connect to WiFi: {:?}", error); } } async fn connection_fallible(mut controller: WifiController<'static>) -> Result<(), WifiError> { - info!("Start connection task, device capabilities:"); + println!("Start connection task, device capabilities:"); let caps = controller.capabilities().unwrap(); caps.iter().for_each(|o| { - info!("{}", o); + println!("{:?}", o); }); loop { @@ -104,34 +104,34 @@ async fn connection_fallible(mut controller: WifiController<'static>) -> Result< if !matches!(controller.is_started(), Ok(true)) { let ssid = env!("WIFI_SSID").try_into().unwrap(); let password = env!("WIFI_PSK").try_into().unwrap(); - info!("Connecting to wifi with SSID: {}", ssid); + println!("Connecting to wifi with SSID: {}", ssid); let client_config = Configuration::Client(ClientConfiguration { ssid, password, ..Default::default() }); controller.set_configuration(&client_config)?; - info!("Starting WiFi controller"); + println!("Starting WiFi controller"); controller.start_async().await?; - info!("WiFi controller started"); + println!("WiFi controller started"); } - info!("About to connect to {}...", env!("WIFI_SSID")); + println!("About to connect to {}...", env!("WIFI_SSID")); match controller.connect_async().await { Ok(()) => { - info!("Connected to WiFi network"); - info!("Wait for request to stop wifi"); + println!("Connected to WiFi network"); + println!("Wait for request to stop wifi"); STOP_WIFI_SIGNAL.wait().await; - info!("Received signal to stop wifi"); + println!("Received signal to stop wifi"); controller.stop_async().await?; break; } Err(error) => { - error!("Failed to connect to WiFi network: {}", error); + println!("Failed to connect to WiFi network: {:?}", error); Timer::after(Duration::from_millis(5000)).await; } } } - info!("Leave connection task"); + println!("Leave connection task"); Ok(()) }