This commit is contained in:
Dimitris
2026-05-25 08:52:47 +02:00
commit 7e49bdba66
9 changed files with 2672 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
[target.xtensa-esp32-none-elf]
runner = "espflash flash --monitor --chip esp32"
[env]
[build]
rustflags = [
"-C", "link-arg=-nostartfiles",
]
target = "xtensa-esp32-none-elf"
[unstable]
build-std = ["alloc", "core"]
+1
View File
@@ -0,0 +1 @@
stack-size-threshold = 1024
+26
View File
@@ -0,0 +1,26 @@
# will have compiled files and executables
debug/
target/
# Editor configuration
.vscode/
.zed/
.helix/
.nvim.lua
# These are backup files generated by rustfmt
**/*.rs.bk
# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb
# RustRover
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# Ignore .DS_Store file in mac
**/.DS_Store
Generated
+2219
View File
File diff suppressed because it is too large Load Diff
+94
View File
@@ -0,0 +1,94 @@
[package]
edition = "2024"
name = "https"
rust-version = "1.88"
version = "0.1.0"
# https://esp32.implrust.com/wifi/web-server/wifi.html
[[bin]]
name = "mqtt-master"
path = "./src/bin/main.rs"
[dependencies]
esp-hal = { version = "1.0.0", features = ["defmt", "esp32", "unstable"] }
esp-rtos = { version = "0.2.0", features = [
"defmt",
"embassy",
"esp-alloc",
"esp-radio",
"esp32",
] }
defmt = "1.0.1"
esp-bootloader-esp-idf = { version = "0.4.0", features = ["defmt", "esp32"] }
embassy-net = { version = "0.7.1", features = [
"defmt",
"dhcpv4",
"medium-ethernet",
"tcp",
"udp",
#addition:
"dns",
] }
embedded-io = { version = "0.7.1", features = ["defmt"] }
embedded-io-async = { version = "0.7.0", features = ["defmt"] }
esp-alloc = { version = "0.9.0", features = ["defmt"] }
esp-println = { version = "0.16.1", features = ["defmt-espflash", "esp32"] }
# for more networking protocol support see https://crates.io/crates/edge-net
embassy-executor = { version = "0.9.1", features = ["defmt"] }
embassy-time = { version = "0.5.0", features = ["defmt"] }
esp-radio = { version = "0.17.0", features = [
"defmt",
"esp-alloc",
"esp32",
"smoltcp",
"unstable",
"wifi",
] }
smoltcp = { version = "0.12.0", default-features = false, features = [
"defmt",
"medium-ethernet",
"multicast",
"proto-dhcpv4",
"proto-dns",
"proto-ipv4",
"socket-dns",
"socket-icmp",
"socket-raw",
"socket-tcp",
"socket-udp",
# addition:
"dns-max-server-count-4",
] }
critical-section = "1.2.0"
static_cell = "2.1.1"
reqwless = { version = "0.13.0", default-features = false, features = [
"embedded-tls",
] }
embedded-dht-rs = { version = "0.5.0", features = ["dht22"] }
[profile.dev]
# Rust debug is too slow.
# For debug builds always builds with some optimization
opt-level = "s"
[profile.release]
codegen-units = 1 # LLVM can perform better optimizations using a single thread
debug = 2
debug-assertions = false
incremental = false
lto = 'fat'
opt-level = 's'
overflow-checks = false
# cargo build
# espflash flash target/xtensa-esp32-none-elf/debug/https --monitor
# cargo build -release
# cargo run -release
# espflash flash target/xtensa-esp32-none-elf/release/https --monitor
+71
View File
@@ -0,0 +1,71 @@
fn main() {
linker_be_nice();
println!("cargo:rustc-link-arg=-Tdefmt.x");
// make sure linkall.x is the last linker script (otherwise might cause problems with flip-link)
println!("cargo:rustc-link-arg=-Tlinkall.x");
}
fn linker_be_nice() {
let args: Vec<String> = std::env::args().collect();
if args.len() > 1 {
let kind = &args[1];
let what = &args[2];
match kind.as_str() {
"undefined-symbol" => match what.as_str() {
what if what.starts_with("_defmt_") => {
eprintln!();
eprintln!(
"💡 `defmt` not found - make sure `defmt.x` is added as a linker script and you have included `use defmt_rtt as _;`"
);
eprintln!();
}
"_stack_start" => {
eprintln!();
eprintln!("💡 Is the linker script `linkall.x` missing?");
eprintln!();
}
what if what.starts_with("esp_rtos_") => {
eprintln!();
eprintln!(
"💡 `esp-radio` has no scheduler enabled. Make sure you have initialized `esp-rtos` or provided an external scheduler."
);
eprintln!();
}
"embedded_test_linker_file_not_added_to_rustflags" => {
eprintln!();
eprintln!(
"💡 `embedded-test` not found - make sure `embedded-test.x` is added as a linker script for tests"
);
eprintln!();
}
"free"
| "malloc"
| "calloc"
| "get_free_internal_heap_size"
| "malloc_internal"
| "realloc_internal"
| "calloc_internal"
| "free_internal" => {
eprintln!();
eprintln!(
"💡 Did you forget the `esp-alloc` dependency or didn't enable the `compat` feature on it?"
);
eprintln!();
}
_ => (),
},
// we don't have anything helpful for "missing-lib" yet
_ => {
std::process::exit(1);
}
}
std::process::exit(0);
}
println!(
"cargo:rustc-link-arg=-Wl,--error-handling-script={}",
std::env::current_exe().unwrap().display()
);
}
+2
View File
@@ -0,0 +1,2 @@
[toolchain]
channel = "esp"
+244
View File
@@ -0,0 +1,244 @@
#![no_std]
#![no_main]
#![deny(
clippy::mem_forget,
reason = "mem::forget is generally not safe to do with esp_hal types, especially those \
holding buffers for the duration of a data transfer."
)]
use alloc::string::ToString;
use defmt::info;
use embassy_executor::Spawner;
use embassy_net::{
DhcpConfig, Runner, Stack, StackResources,
dns::DnsSocket,
tcp::client::{TcpClient, TcpClientState},
};
use embassy_time::{Duration, Timer};
use esp_hal::{
clock::CpuClock,
delay::Delay,
gpio::{DriveMode, Flex, OutputConfig, Pull},
rng::Rng,
timer::timg::TimerGroup,
};
use esp_println::{self as _, println};
use esp_radio::wifi::{
ClientConfig, ModeConfig, WifiController, WifiDevice, WifiEvent, WifiStaState,
};
use reqwless::client::{HttpClient, TlsConfig};
use embedded_dht_rs::dht22::Dht22;
#[panic_handler]
fn panic(_: &core::panic::PanicInfo) -> ! {
loop {}
}
extern crate alloc;
// This creates a default app-descriptor required by the esp-idf bootloader.
// For more information see: <https://docs.espressif.com/projects/esp-idf/en/stable/esp32/api-reference/system/app_image_format.html#application-description>
esp_bootloader_esp_idf::esp_app_desc!();
// If you are okay with using a nightly compiler, you can use the macro provided by the static_cell crate: https://docs.rs/static_cell/latest/static_cell/macro.make_static.html
macro_rules! mk_static {
($t:ty,$val:expr) => {{
static STATIC_CELL: static_cell::StaticCell<$t> = static_cell::StaticCell::new();
#[deny(unused_attributes)]
let x = STATIC_CELL.uninit().write(($val));
x
}};
}
//const SSID: &str = "FRITZ!Box 7590 FP DK";
//const PASSWORD: &str = "68897925266250323867";
const SSID: &str = "COSMOTE-C90C60";
const PASSWORD: &str = "xPeRD7RytKyrXTE6";
const MQTT_URL: &str = "https://kouros-online.de/gin/mqtt/eo7sbjyWpmjSVFyELgbfrryqJ6ddNeq9";
const TOPIC: &str = "kefalovryso";
#[esp_rtos::main]
async fn main(spawner: Spawner) -> ! {
// generator version: 1.0.0
let config = esp_hal::Config::default().with_cpu_clock(CpuClock::max());
let peripherals = esp_hal::init(config);
esp_alloc::heap_allocator!(#[unsafe(link_section = ".dram2_uninit")] size: 98767);
let timg0 = TimerGroup::new(peripherals.TIMG0);
esp_rtos::start(timg0.timer0);
// DHT22 sensor setup (GPIO26)
let mut dht22_pin = Flex::new(peripherals.GPIO26);
dht22_pin.apply_output_config(
&OutputConfig::default()
.with_drive_mode(DriveMode::OpenDrain)
.with_pull(Pull::None),
);
dht22_pin.set_output_enable(true);
dht22_pin.set_input_enable(true);
dht22_pin.set_high();
let mut dht22 = Dht22::new(dht22_pin, Delay::new());
// let radio_init = esp_radio::init().expect("Failed to initialize Wi-Fi/BLE controller");
let radio_init = &*mk_static!(
esp_radio::Controller<'static>,
esp_radio::init().expect("Failed to initialize Wi-Fi/BLE controller")
);
let (wifi_controller, interfaces) =
esp_radio::wifi::new(&radio_init, peripherals.WIFI, Default::default())
.expect("Failed to initialize Wi-Fi controller");
let wifi_interface = interfaces.sta;
let rng = Rng::new();
let net_seed = rng.random() as u64 | ((rng.random() as u64) << 32);
let tls_seed = rng.random() as u64 | ((rng.random() as u64) << 32);
let dhcp_config = DhcpConfig::default();
let config = embassy_net::Config::dhcpv4(dhcp_config);
// Init network stack
let (stack, runner) = embassy_net::new(
wifi_interface,
config,
mk_static!(StackResources<3>, StackResources::<3>::new()),
net_seed,
);
spawner.spawn(connection(wifi_controller)).ok();
spawner.spawn(net_task(runner)).ok();
wait_for_connection(stack).await;
let delay = Delay::new();
loop {
match dht22.read() {
Ok(sensor_reading) => {
esp_println::println!(
"DHT 22 Sensor - Temperature: {} °C, humidity: {} %",
sensor_reading.temperature,
sensor_reading.humidity
);
publish_mqtt(
stack,
tls_seed,
sensor_reading.temperature,
sensor_reading.humidity,
)
.await;
}
Err(error) => {
esp_println::dbg!("An error occurred while trying to read sensor: {:?}", error);
}
}
delay.delay_millis(30000);
}
}
async fn wait_for_connection(stack: Stack<'_>) {
println!("Waiting for link to be up");
loop {
if stack.is_link_up() {
break;
}
Timer::after(Duration::from_millis(500)).await;
}
println!("Waiting to get IP address...");
loop {
if let Some(config) = stack.config_v4() {
println!("Got IP: {}", config.address);
break;
}
Timer::after(Duration::from_millis(100)).await;
}
}
#[embassy_executor::task]
async fn connection(mut controller: WifiController<'static>) {
println!("Start connection task");
println!("Device capabilities: {:?}", controller.capabilities());
loop {
match esp_radio::wifi::sta_state() {
WifiStaState::Connected => {
// wait until we're no longer connected
controller.wait_for_event(WifiEvent::StaDisconnected).await;
Timer::after(Duration::from_millis(5000)).await
}
_ => {}
}
if !matches!(controller.is_started(), Ok(true)) {
let client_config = ModeConfig::Client(
ClientConfig::default()
.with_ssid(SSID.into())
.with_password(PASSWORD.into()),
);
controller.set_config(&client_config).unwrap();
println!("Starting wifi");
controller.start_async().await.unwrap();
println!("Wifi started!");
}
println!("About to connect...");
match controller.connect_async().await {
Ok(_) => println!("Wifi connected!"),
Err(e) => {
println!("Failed to connect to wifi: {:?}", e);
Timer::after(Duration::from_millis(5000)).await
}
}
}
}
#[embassy_executor::task]
async fn net_task(mut runner: Runner<'static, WifiDevice<'static>>) {
runner.run().await
}
async fn publish_mqtt(stack: Stack<'_>, tls_seed: u64, temperature: f32, humidity: f32) {
let mut rx_buffer = [0; 4096];
let mut tx_buffer = [0; 4096];
let dns = DnsSocket::new(stack);
let tcp_state = TcpClientState::<1, 4096, 4096>::new();
let tcp = TcpClient::new(stack, &tcp_state);
let tls = TlsConfig::new(
tls_seed,
&mut rx_buffer,
&mut tx_buffer,
reqwless::client::TlsVerify::None,
);
let mut client = HttpClient::new_with_tls(&tcp, &dns, tls);
let mut buffer = [0u8; 4096];
let url = [
MQTT_URL,
TOPIC,
temperature.to_string().as_str(),
humidity.to_string().as_str(),
]
.join("/");
println!("url: {:?}", url);
let mut http_req = client
.request(reqwless::request::Method::GET, &url)
.await
.unwrap();
let response = http_req.send(&mut buffer).await.unwrap();
info!("Got response");
let res = response.body().read_to_end().await.unwrap();
let content = core::str::from_utf8(res).unwrap();
println!("{}", content);
}
+1
View File
@@ -0,0 +1 @@
#![no_std]