Initial
This commit is contained in:
+244
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
#![no_std]
|
||||
Reference in New Issue
Block a user