Compare commits
18 Commits
a84a325852
...
feature/mq
| Author | SHA1 | Date | |
|---|---|---|---|
| bd257b89f0 | |||
| 4debbfb39e | |||
| d83189417a | |||
| 3c92cf0c26 | |||
|
96023c8dc3
|
|||
|
7497a8c05d
|
|||
|
d3d8d829be
|
|||
|
6889ba4561
|
|||
|
18095349f3
|
|||
|
3d8fd893f5
|
|||
|
1bea7ef2f4
|
|||
|
f5b9674840
|
|||
|
6f22881007
|
|||
|
1d8af1b6c4
|
|||
|
2c532359fc
|
|||
|
53819484fb
|
|||
|
1151d099cf
|
|||
|
3feaacd460
|
@@ -17,12 +17,9 @@ use core::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
use core::str::FromStr;
|
||||
use core::sync::atomic::Ordering;
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_net::dns::DnsQueryType;
|
||||
use embassy_net::udp::{PacketMetadata, UdpSocket};
|
||||
use embassy_net::{DhcpConfig, IpAddress, Ipv4Cidr, Runner, Stack, StackResources, StaticConfigV4};
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_sync::mutex::{Mutex, MutexGuard};
|
||||
use embassy_sync::once_lock::OnceLock;
|
||||
use embassy_time::{Duration, Timer, WithTimeout};
|
||||
use embedded_storage::nor_flash::{check_erase, NorFlash, ReadNorFlash, RmwNorFlashStorage};
|
||||
use esp_bootloader_esp_idf::ota::OtaImageState::Valid;
|
||||
@@ -44,14 +41,10 @@ use esp_storage::FlashStorage;
|
||||
use littlefs2::fs::Filesystem;
|
||||
use littlefs2_core::{FileType, PathBuf, SeekFrom};
|
||||
use log::{info, warn, error};
|
||||
use mcutie::{
|
||||
Error, McutieBuilder, McutieReceiver, McutieTask, MqttMessage, PublishDisplay, Publishable,
|
||||
QoS, Topic,
|
||||
};
|
||||
use portable_atomic::AtomicBool;
|
||||
use sntpc::{NtpContext, NtpTimestampGenerator, NtpUdpSocket, get_time};
|
||||
|
||||
use super::shared_flash::MutexFlashStorage;
|
||||
use crate::network::{net_task, run_dhcp};
|
||||
|
||||
#[esp_hal::ram(unstable(rtc_fast), unstable(persistent))]
|
||||
static mut LAST_WATERING_TIMESTAMP: [i64; PLANT_COUNT] = [0; PLANT_COUNT];
|
||||
@@ -66,12 +59,6 @@ static mut LAST_CORROSION_PROTECTION_CHECK_DAY: i8 = -1;
|
||||
|
||||
|
||||
const CONFIG_FILE: &str = "config.json";
|
||||
const NTP_SERVER: &str = "pool.ntp.org";
|
||||
|
||||
static MQTT_CONNECTED_EVENT_RECEIVED: AtomicBool = AtomicBool::new(false);
|
||||
static MQTT_ROUND_TRIP_RECEIVED: AtomicBool = AtomicBool::new(false);
|
||||
pub static MQTT_STAY_ALIVE: AtomicBool = AtomicBool::new(false);
|
||||
static MQTT_BASE_TOPIC: OnceLock<String> = OnceLock::new();
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
pub struct FileInfo {
|
||||
@@ -86,11 +73,6 @@ pub struct FileList {
|
||||
files: Vec<FileInfo>,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Default)]
|
||||
struct Timestamp {
|
||||
stamp: DateTime<Utc>,
|
||||
}
|
||||
|
||||
// Minimal esp-idf equivalent for gpio_hold on esp32c6 via ROM functions
|
||||
extern "C" {
|
||||
fn gpio_pad_hold(gpio_num: u32);
|
||||
@@ -107,53 +89,6 @@ pub fn hold_disable(gpio_num: u8) {
|
||||
unsafe { gpio_pad_unhold(gpio_num as u32) }
|
||||
}
|
||||
|
||||
impl NtpTimestampGenerator for Timestamp {
|
||||
fn init(&mut self) {
|
||||
self.stamp = DateTime::default();
|
||||
}
|
||||
|
||||
fn timestamp_sec(&self) -> u64 {
|
||||
self.stamp.timestamp() as u64
|
||||
}
|
||||
|
||||
fn timestamp_subsec_micros(&self) -> u32 {
|
||||
self.stamp.timestamp_subsec_micros()
|
||||
}
|
||||
}
|
||||
struct EmbassyNtpSocket<'a, 'b> {
|
||||
socket: &'a UdpSocket<'b>,
|
||||
}
|
||||
|
||||
impl<'a, 'b> EmbassyNtpSocket<'a, 'b> {
|
||||
fn new(socket: &'a UdpSocket<'b>) -> Self {
|
||||
Self { socket }
|
||||
}
|
||||
}
|
||||
|
||||
impl NtpUdpSocket for EmbassyNtpSocket<'_, '_> {
|
||||
async fn send_to(&self, buf: &[u8], addr: SocketAddr) -> sntpc::Result<usize> {
|
||||
self.socket
|
||||
.send_to(buf, addr)
|
||||
.await
|
||||
.map_err(|_| sntpc::Error::Network)?;
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
async fn recv_from(&self, buf: &mut [u8]) -> sntpc::Result<(usize, SocketAddr)> {
|
||||
let (len, metadata) = self
|
||||
.socket
|
||||
.recv_from(buf)
|
||||
.await
|
||||
.map_err(|_| sntpc::Error::Network)?;
|
||||
let addr = match metadata.endpoint.addr {
|
||||
IpAddress::Ipv4(ip) => IpAddr::V4(ip),
|
||||
IpAddress::Ipv6(ip) => IpAddr::V6(ip),
|
||||
};
|
||||
Ok((len, SocketAddr::new(addr, metadata.endpoint.port)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub struct Esp<'a> {
|
||||
pub fs: Arc<Mutex<CriticalSectionRawMutex, Filesystem<'static, LittleFs2Filesystem>>>,
|
||||
pub rng: Rng,
|
||||
@@ -185,15 +120,6 @@ pub struct Esp<'a> {
|
||||
// CPU cores/threads, reconsider this.
|
||||
unsafe impl Send for Esp<'_> {}
|
||||
|
||||
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
|
||||
}};
|
||||
}
|
||||
|
||||
impl Esp<'_> {
|
||||
pub fn get_time(&self) -> DateTime<Utc> {
|
||||
DateTime::from_timestamp_micros(self.rtc.current_time_us() as i64)
|
||||
@@ -355,66 +281,6 @@ impl Esp<'_> {
|
||||
self.boot_button.is_low()
|
||||
}
|
||||
|
||||
pub(crate) async fn sntp(
|
||||
&mut self,
|
||||
_max_wait_ms: u32,
|
||||
stack: Stack<'_>,
|
||||
) -> FatResult<DateTime<Utc>> {
|
||||
println!("start sntp");
|
||||
let mut rx_meta = [PacketMetadata::EMPTY; 16];
|
||||
let mut rx_buffer = [0; 4096];
|
||||
let mut tx_meta = [PacketMetadata::EMPTY; 16];
|
||||
let mut tx_buffer = [0; 4096];
|
||||
|
||||
let mut socket = UdpSocket::new(
|
||||
stack,
|
||||
&mut rx_meta,
|
||||
&mut rx_buffer,
|
||||
&mut tx_meta,
|
||||
&mut tx_buffer,
|
||||
);
|
||||
socket.bind(123).context("Could not bind UDP socket")?;
|
||||
|
||||
let context = NtpContext::new(Timestamp::default());
|
||||
let ntp_socket = EmbassyNtpSocket::new(&socket);
|
||||
|
||||
let ntp_addrs = stack
|
||||
.dns_query(NTP_SERVER, DnsQueryType::A)
|
||||
.await
|
||||
.context("Failed to resolve DNS")?;
|
||||
|
||||
if ntp_addrs.is_empty() {
|
||||
bail!("No IP addresses found for NTP server");
|
||||
}
|
||||
let ntp = ntp_addrs[0];
|
||||
info!("NTP server: {ntp:?}");
|
||||
|
||||
let mut counter = 0;
|
||||
loop {
|
||||
let addr: IpAddr = ntp.into();
|
||||
let timeout = get_time(SocketAddr::from((addr, 123)), &ntp_socket, context)
|
||||
.with_timeout(Duration::from_millis((_max_wait_ms / 10) as u64))
|
||||
.await;
|
||||
|
||||
match timeout {
|
||||
Ok(result) => {
|
||||
let time = result?;
|
||||
info!("Time: {time:?}");
|
||||
return DateTime::from_timestamp(time.seconds as i64, 0)
|
||||
.context("Could not convert Sntp result");
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("sntp timeout, retry: {err:?}");
|
||||
counter += 1;
|
||||
if counter > 10 {
|
||||
bail!("Failed to get time from NTP server");
|
||||
}
|
||||
Timer::after(Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn wifi_scan(&mut self) -> FatResult<Vec<AccessPointInfo>> {
|
||||
info!("start wifi scan");
|
||||
let mut lock = self.controller.try_lock()?;
|
||||
@@ -472,160 +338,6 @@ impl Esp<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn wifi_ap(&mut self, spawner: Spawner) -> FatResult<Stack<'static>> {
|
||||
let ssid = match self.load_config().await {
|
||||
Ok(config) => config.network.ap_ssid.as_str().to_string(),
|
||||
Err(_) => "PlantCtrl Emergency Mode".to_string(),
|
||||
};
|
||||
|
||||
let device = self
|
||||
.interface_ap
|
||||
.take()
|
||||
.context("AP interface already taken")?;
|
||||
let gw_ip_addr = Ipv4Addr::new(192, 168, 71, 1);
|
||||
|
||||
let config = embassy_net::Config::ipv4_static(StaticConfigV4 {
|
||||
address: Ipv4Cidr::new(gw_ip_addr, 24),
|
||||
gateway: Some(gw_ip_addr),
|
||||
dns_servers: Default::default(),
|
||||
});
|
||||
|
||||
let seed = (self.rng.random() as u64) << 32 | self.rng.random() as u64;
|
||||
|
||||
println!("init secondary stack");
|
||||
// Init network stack
|
||||
let (stack, runner) = embassy_net::new(
|
||||
device,
|
||||
config,
|
||||
mk_static!(StackResources<4>, StackResources::<4>::new()),
|
||||
seed,
|
||||
);
|
||||
let stack = mk_static!(Stack, stack);
|
||||
|
||||
let client_config =
|
||||
Config::AccessPoint(AccessPointConfig::default().with_ssid(ssid.clone()));
|
||||
self.controller.lock().await.set_config(&client_config)?;
|
||||
|
||||
println!("start net task");
|
||||
spawner.spawn(net_task(runner)?);
|
||||
println!("run dhcp");
|
||||
spawner.spawn(run_dhcp(*stack, gw_ip_addr)?);
|
||||
|
||||
loop {
|
||||
if stack.is_link_up() {
|
||||
break;
|
||||
}
|
||||
Timer::after(Duration::from_millis(500)).await;
|
||||
}
|
||||
while !stack.is_config_up() {
|
||||
Timer::after(Duration::from_millis(100)).await
|
||||
}
|
||||
println!("Connect to the AP `${ssid}` and point your browser to http://{gw_ip_addr}/");
|
||||
stack
|
||||
.config_v4()
|
||||
.inspect(|c| println!("ipv4 config: {c:?}"));
|
||||
|
||||
Ok(*stack)
|
||||
}
|
||||
|
||||
pub(crate) async fn wifi(
|
||||
&mut self,
|
||||
network_config: &NetworkConfig,
|
||||
spawner: Spawner,
|
||||
) -> FatResult<Stack<'static>> {
|
||||
esp_radio::wifi_set_log_verbose();
|
||||
let ssid = match &network_config.ssid {
|
||||
Some(ssid) => {
|
||||
if ssid.is_empty() {
|
||||
bail!("Wifi ssid was empty")
|
||||
}
|
||||
ssid.to_string()
|
||||
}
|
||||
None => {
|
||||
bail!("Wifi ssid was empty")
|
||||
}
|
||||
};
|
||||
info!("attempting to connect wifi {ssid}");
|
||||
let password = match network_config.password {
|
||||
Some(ref password) => password.to_string(),
|
||||
None => "".to_string(),
|
||||
};
|
||||
let max_wait = network_config.max_wait;
|
||||
|
||||
let device = self
|
||||
.interface_sta
|
||||
.take()
|
||||
.context("STA interface already taken")?;
|
||||
let config = embassy_net::Config::dhcpv4(DhcpConfig::default());
|
||||
|
||||
let seed = (self.rng.random() as u64) << 32 | self.rng.random() as u64;
|
||||
|
||||
// Init network stack
|
||||
let (stack, runner) = embassy_net::new(
|
||||
device,
|
||||
config,
|
||||
mk_static!(StackResources<8>, StackResources::<8>::new()),
|
||||
seed,
|
||||
);
|
||||
let stack = mk_static!(Stack, stack);
|
||||
|
||||
let auth_method = if password.is_empty() {
|
||||
AuthenticationMethod::None
|
||||
} else {
|
||||
AuthenticationMethod::Wpa2Personal
|
||||
};
|
||||
let client_config = StationConfig::default()
|
||||
.with_ssid(ssid)
|
||||
.with_auth_method(auth_method)
|
||||
.with_scan_method(esp_radio::wifi::sta::ScanMethod::AllChannels)
|
||||
.with_listen_interval(10)
|
||||
.with_beacon_timeout(10)
|
||||
.with_failure_retry_cnt(3)
|
||||
.with_password(password);
|
||||
|
||||
self.controller
|
||||
.lock()
|
||||
.await
|
||||
.set_config(&Config::Station(client_config))?;
|
||||
spawner.spawn(net_task(runner)?);
|
||||
self.controller
|
||||
.lock()
|
||||
.await
|
||||
.connect_async()
|
||||
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
|
||||
.await
|
||||
.context("Timeout waiting for wifi sta connected")??;
|
||||
|
||||
let res = async {
|
||||
while !stack.is_link_up() {
|
||||
Timer::after(Duration::from_millis(500)).await;
|
||||
}
|
||||
Ok::<(), FatError>(())
|
||||
}
|
||||
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
|
||||
.await;
|
||||
|
||||
if res.is_err() {
|
||||
bail!("Timeout waiting for wifi link up")
|
||||
}
|
||||
|
||||
let res = async {
|
||||
while !stack.is_config_up() {
|
||||
Timer::after(Duration::from_millis(100)).await
|
||||
}
|
||||
Ok::<(), FatError>(())
|
||||
}
|
||||
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
|
||||
.await;
|
||||
|
||||
if res.is_err() {
|
||||
bail!("Timeout waiting for wifi config up")
|
||||
}
|
||||
|
||||
info!("Connected WIFI, dhcp: {:?}", stack.config_v4());
|
||||
Ok(*stack)
|
||||
}
|
||||
|
||||
pub fn deep_sleep_ms(&mut self, duration_in_ms: u64) -> ! {
|
||||
// Mark the current OTA image as valid if we reached here while in pending verify.
|
||||
if let Ok(cur) = self.ota.current_ota_state() {
|
||||
@@ -740,275 +452,4 @@ impl Esp<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn mqtt(
|
||||
&mut self,
|
||||
network_config: &'static NetworkConfig,
|
||||
stack: Stack<'static>,
|
||||
spawner: Spawner,
|
||||
) -> FatResult<()> {
|
||||
let base_topic = network_config
|
||||
.base_topic
|
||||
.as_ref()
|
||||
.context("missing base topic")?;
|
||||
if base_topic.is_empty() {
|
||||
bail!("Mqtt base_topic was empty")
|
||||
}
|
||||
MQTT_BASE_TOPIC
|
||||
.init(base_topic.to_string())
|
||||
.map_err(|_| FatError::String {
|
||||
error: "Error setting basetopic".to_string(),
|
||||
})?;
|
||||
|
||||
let mqtt_url = network_config
|
||||
.mqtt_url
|
||||
.as_ref()
|
||||
.context("missing mqtt url")?;
|
||||
if mqtt_url.is_empty() {
|
||||
bail!("Mqtt url was empty")
|
||||
}
|
||||
|
||||
let last_will_topic = format!("{base_topic}/state");
|
||||
let round_trip_topic = format!("{base_topic}/internal/roundtrip");
|
||||
let stay_alive_topic = format!("{base_topic}/stay_alive");
|
||||
|
||||
let mut builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 0> =
|
||||
McutieBuilder::new(stack, "plant ctrl", mqtt_url);
|
||||
if let (Some(mqtt_user), Some(mqtt_password)) = (
|
||||
network_config.mqtt_user.as_ref(),
|
||||
network_config.mqtt_password.as_ref(),
|
||||
) {
|
||||
builder = builder.with_authentication(mqtt_user, mqtt_password);
|
||||
info!("With authentification");
|
||||
}
|
||||
|
||||
let lwt = Topic::General(last_will_topic);
|
||||
let lwt = mk_static!(Topic<String>, lwt);
|
||||
let lwt = lwt.with_display("lost").retain(true).qos(QoS::AtLeastOnce);
|
||||
builder = builder.with_last_will(lwt);
|
||||
//TODO make configurable
|
||||
builder = builder.with_device_id("plantctrl");
|
||||
|
||||
let builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 2> = builder
|
||||
.with_subscriptions([
|
||||
Topic::General(round_trip_topic.clone()),
|
||||
Topic::General(stay_alive_topic.clone()),
|
||||
]);
|
||||
|
||||
let keep_alive = Duration::from_secs(60 * 60 * 2).as_secs() as u16;
|
||||
let (receiver, task) = builder.build(keep_alive);
|
||||
|
||||
spawner.spawn(mqtt_incoming_task(
|
||||
receiver,
|
||||
round_trip_topic.clone(),
|
||||
stay_alive_topic.clone(),
|
||||
)?);
|
||||
spawner.spawn(mqtt_runner(task)?);
|
||||
|
||||
log(LogMessage::StayAlive, 0, 0, "", &stay_alive_topic);
|
||||
|
||||
log(LogMessage::MqttInfo, 0, 0, "", mqtt_url);
|
||||
|
||||
let mqtt_timeout = 15000;
|
||||
let res = async {
|
||||
while !MQTT_CONNECTED_EVENT_RECEIVED.load(Ordering::Relaxed) {
|
||||
crate::hal::PlantHal::feed_watchdog();
|
||||
Timer::after(Duration::from_millis(100)).await;
|
||||
}
|
||||
Ok::<(), FatError>(())
|
||||
}
|
||||
.with_timeout(Duration::from_millis(mqtt_timeout as u64))
|
||||
.await;
|
||||
|
||||
if res.is_err() {
|
||||
bail!("Timeout waiting MQTT connect event")
|
||||
}
|
||||
|
||||
let _ = Topic::General(round_trip_topic.clone())
|
||||
.with_display("online_text")
|
||||
.publish()
|
||||
.await;
|
||||
|
||||
let res = async {
|
||||
while !MQTT_ROUND_TRIP_RECEIVED.load(Ordering::Relaxed) {
|
||||
crate::hal::PlantHal::feed_watchdog();
|
||||
Timer::after(Duration::from_millis(100)).await;
|
||||
}
|
||||
Ok::<(), FatError>(())
|
||||
}
|
||||
.with_timeout(Duration::from_millis(mqtt_timeout as u64))
|
||||
.await;
|
||||
|
||||
if res.is_err() {
|
||||
//ensure we do not further try to publish
|
||||
MQTT_CONNECTED_EVENT_RECEIVED.store(false, Ordering::Relaxed);
|
||||
bail!("Timeout waiting MQTT roundtrip")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn mqtt_inner(&mut self, subtopic: &str, message: &str) -> FatResult<()> {
|
||||
if !subtopic.starts_with("/") {
|
||||
bail!("Subtopic without / at start {}", subtopic);
|
||||
}
|
||||
if subtopic.len() > 192 {
|
||||
bail!("Subtopic exceeds 192 chars {}", subtopic);
|
||||
}
|
||||
let base_topic = MQTT_BASE_TOPIC
|
||||
.try_get()
|
||||
.context("missing base topic in static!")?;
|
||||
|
||||
let full_topic = format!("{base_topic}{subtopic}");
|
||||
|
||||
loop {
|
||||
let result = Topic::General(full_topic.as_str())
|
||||
.with_display(message)
|
||||
.retain(true)
|
||||
.publish()
|
||||
.await;
|
||||
match result {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(err) => {
|
||||
let retry = match err {
|
||||
Error::IOError => false,
|
||||
Error::TimedOut => true,
|
||||
Error::TooLarge => false,
|
||||
Error::PacketError => false,
|
||||
Error::Invalid => false,
|
||||
Error::Rejected => false,
|
||||
};
|
||||
if !retry {
|
||||
bail!(
|
||||
"Error during mqtt send on topic {} with message {:#?} error is {:?}",
|
||||
&full_topic,
|
||||
message,
|
||||
err
|
||||
);
|
||||
}
|
||||
info!(
|
||||
"Retransmit for {} with message {:#?} error is {:?} retrying {}",
|
||||
&full_topic, message, err, retry
|
||||
);
|
||||
Timer::after(Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) async fn mqtt_publish(&mut self, subtopic: &str, message: &str) {
|
||||
let online = MQTT_CONNECTED_EVENT_RECEIVED.load(Ordering::Relaxed);
|
||||
if !online {
|
||||
return;
|
||||
}
|
||||
let roundtrip_ok = MQTT_ROUND_TRIP_RECEIVED.load(Ordering::Relaxed);
|
||||
if !roundtrip_ok {
|
||||
info!("MQTT roundtrip not received yet, dropping message");
|
||||
return;
|
||||
}
|
||||
match self.mqtt_inner(subtopic, message).await {
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
info!(
|
||||
"Error during mqtt send on topic {subtopic} with message {message:#?} error is {err:?}"
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn mqtt_runner(
|
||||
task: McutieTask<'static, String, PublishDisplay<'static, String, &'static str>, 2>,
|
||||
) {
|
||||
task.run().await;
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn mqtt_incoming_task(
|
||||
receiver: McutieReceiver,
|
||||
round_trip_topic: String,
|
||||
stay_alive_topic: String,
|
||||
) {
|
||||
loop {
|
||||
let message = receiver.receive().await;
|
||||
match message {
|
||||
MqttMessage::Connected => {
|
||||
info!("Mqtt connected");
|
||||
MQTT_CONNECTED_EVENT_RECEIVED.store(true, Ordering::Relaxed);
|
||||
}
|
||||
MqttMessage::Publish(topic, payload) => match topic {
|
||||
Topic::DeviceType(_type_topic) => {}
|
||||
Topic::Device(_device_topic) => {}
|
||||
Topic::General(topic) => {
|
||||
let subtopic = topic.as_str();
|
||||
|
||||
if subtopic.eq(round_trip_topic.as_str()) {
|
||||
MQTT_ROUND_TRIP_RECEIVED.store(true, Ordering::Relaxed);
|
||||
} else if subtopic.eq(stay_alive_topic.as_str()) {
|
||||
let value = payload.eq_ignore_ascii_case("true".as_ref())
|
||||
|| payload.eq_ignore_ascii_case("1".as_ref());
|
||||
let a = match value {
|
||||
true => 1,
|
||||
false => 0,
|
||||
};
|
||||
log(LogMessage::MqttStayAliveRec, a, 0, "", "");
|
||||
MQTT_STAY_ALIVE.store(value, Ordering::Relaxed);
|
||||
} else {
|
||||
log(LogMessage::UnknownTopic, 0, 0, "", &topic);
|
||||
}
|
||||
}
|
||||
},
|
||||
MqttMessage::Disconnected => {
|
||||
MQTT_CONNECTED_EVENT_RECEIVED.store(false, Ordering::Relaxed);
|
||||
info!("Mqtt disconnected");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[embassy_executor::task(pool_size = 2)]
|
||||
async fn net_task(mut runner: Runner<'static, Interface<'static>>) {
|
||||
runner.run().await;
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn run_dhcp(stack: Stack<'static>, ip: Ipv4Addr) {
|
||||
use core::net::SocketAddrV4;
|
||||
|
||||
use edge_dhcp::{
|
||||
io::{self, DEFAULT_SERVER_PORT},
|
||||
server::{Server, ServerOptions},
|
||||
};
|
||||
use edge_nal::UdpBind;
|
||||
use edge_nal_embassy::{Udp, UdpBuffers};
|
||||
|
||||
let mut buf = [0u8; 1500];
|
||||
|
||||
let mut gw_buf = [Ipv4Addr::UNSPECIFIED];
|
||||
|
||||
let buffers = UdpBuffers::<3, 1024, 1024, 10>::new();
|
||||
let unbound_socket = Udp::new(stack, &buffers);
|
||||
let mut bound_socket = match unbound_socket
|
||||
.bind(SocketAddr::V4(SocketAddrV4::new(
|
||||
Ipv4Addr::UNSPECIFIED,
|
||||
DEFAULT_SERVER_PORT,
|
||||
)))
|
||||
.await
|
||||
{
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
error!("dhcp task failed to bind socket: {:?}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
loop {
|
||||
_ = io::server::run(
|
||||
&mut Server::<_, 64>::new_with_et(ip),
|
||||
&ServerOptions::new(ip, Some(&mut gw_buf)),
|
||||
&mut bound_socket,
|
||||
&mut buf,
|
||||
)
|
||||
.await
|
||||
.inspect_err(|e| warn!("DHCP server error: {e:?}"));
|
||||
Timer::after(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -282,14 +282,7 @@ pub struct FreePeripherals<'a> {
|
||||
pub adc1: ADC1<'a>,
|
||||
}
|
||||
|
||||
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
|
||||
}};
|
||||
}
|
||||
use crate::util::mk_static;
|
||||
|
||||
impl PlantHal {
|
||||
pub async fn create() -> Result<Mutex<CriticalSectionRawMutex, HAL<'static>>, FatError> {
|
||||
|
||||
244
rust/src/main.rs
244
rust/src/main.rs
@@ -17,8 +17,8 @@ use esp_backtrace as _;
|
||||
use hal::PROGRESS_ACTIVE;
|
||||
|
||||
use crate::config::{NetworkConfig, PlantConfig};
|
||||
use crate::fat_error::FatResult;
|
||||
use crate::hal::esp::MQTT_STAY_ALIVE;
|
||||
use crate::fat_error::{ContextExt, FatResult};
|
||||
|
||||
use crate::log::log;
|
||||
use crate::tank::{determine_tank_state, TankError, TankState, WATER_FROZEN_THRESH};
|
||||
use crate::webserver::http_server;
|
||||
@@ -67,8 +67,11 @@ mod config;
|
||||
mod fat_error;
|
||||
mod hal;
|
||||
mod log;
|
||||
mod mqtt;
|
||||
mod network;
|
||||
mod plant_state;
|
||||
mod tank;
|
||||
mod util;
|
||||
mod webserver;
|
||||
|
||||
extern crate alloc;
|
||||
@@ -83,12 +86,6 @@ enum WaitType {
|
||||
MqttConfig,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, PartialEq)]
|
||||
struct Solar {
|
||||
current_ma: u32,
|
||||
voltage_ma: u32,
|
||||
}
|
||||
|
||||
impl WaitType {
|
||||
fn blink_pattern(&self) -> u64 {
|
||||
match self {
|
||||
@@ -114,16 +111,6 @@ struct LightState {
|
||||
is_day: bool,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
|
||||
///mqtt struct to track pump activities
|
||||
struct PumpInfo {
|
||||
enabled: bool,
|
||||
pump_ineffective: bool,
|
||||
median_current_ma: u16,
|
||||
max_current_ma: u16,
|
||||
min_current_ma: u16,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct PumpResult {
|
||||
median_current_ma: u16,
|
||||
@@ -135,21 +122,7 @@ pub struct PumpResult {
|
||||
pump_time_s: u16,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, PartialEq)]
|
||||
enum SntpMode {
|
||||
OFFLINE,
|
||||
SYNC { current: DateTime<Utc> },
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, PartialEq)]
|
||||
enum NetworkMode {
|
||||
WIFI {
|
||||
sntp: SntpMode,
|
||||
mqtt: bool,
|
||||
ip_address: String,
|
||||
},
|
||||
OFFLINE,
|
||||
}
|
||||
|
||||
async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||
info!("Startup Rust");
|
||||
@@ -223,7 +196,12 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||
{
|
||||
info!("No wifi configured, starting initial config mode");
|
||||
|
||||
let stack = board.board_hal.get_esp().wifi_ap(spawner).await?;
|
||||
let esp = board.board_hal.get_esp();
|
||||
let ssid = esp.load_config().await
|
||||
.map(|config| config.network.ap_ssid.to_string())
|
||||
.unwrap_or_else(|_| String::from("PlantCtrl Emergency Mode"));
|
||||
let device = esp.interface_ap.take().context("AP interface already taken")?;
|
||||
let stack = network::wifi_ap(ssid, device, &esp.controller, &mut esp.rng, spawner).await?;
|
||||
|
||||
let reboot_now = Arc::new(AtomicBool::new(false));
|
||||
println!("starting webserver");
|
||||
@@ -234,20 +212,30 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||
|
||||
let mut stack: OptionLock<Stack> = OptionLock::empty();
|
||||
let network_mode = if board.board_hal.get_config().network.ssid.is_some() {
|
||||
try_connect_wifi_sntp_mqtt(&mut board, &mut stack, spawner).await
|
||||
network::try_connect_wifi_sntp_mqtt(&mut board, &mut stack, spawner).await
|
||||
} else {
|
||||
info!("No wifi configured");
|
||||
//the current sensors require this amount to stabilize, in the case of Wi-Fi this is already handled due to connect timings;
|
||||
Timer::after_millis(100).await;
|
||||
NetworkMode::OFFLINE
|
||||
network::NetworkMode::OFFLINE
|
||||
};
|
||||
|
||||
if matches!(network_mode, NetworkMode::OFFLINE) && to_config {
|
||||
if matches!(network_mode, network::NetworkMode::OFFLINE) && to_config {
|
||||
info!("Could not connect to station and config mode forced, switching to ap mode!");
|
||||
|
||||
let res = {
|
||||
let esp = board.board_hal.get_esp();
|
||||
esp.wifi_ap(spawner).await
|
||||
let ssid = esp.load_config().await
|
||||
.map(|config| config.network.ap_ssid.to_string())
|
||||
.unwrap_or_else(|_| String::from("PlantCtrl Emergency Mode"));
|
||||
let device = match esp.interface_ap.take() {
|
||||
Some(d) => d,
|
||||
None => {
|
||||
use crate::fat_error::FatError;
|
||||
return Err(FatError::String { error: "AP interface already taken".to_string() });
|
||||
}
|
||||
};
|
||||
network::wifi_ap(ssid, device, &esp.controller, &mut esp.rng, spawner).await
|
||||
};
|
||||
match res {
|
||||
Ok(ap_stack) => {
|
||||
@@ -276,23 +264,24 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||
timezone_time
|
||||
);
|
||||
|
||||
if let NetworkMode::WIFI { ref ip_address, .. } = network_mode {
|
||||
if let network::NetworkMode::WIFI { ref ip_address, .. } = network_mode {
|
||||
publish_firmware_info(&mut board, version, ip_address, &timezone_time.to_rfc3339()).await;
|
||||
publish_battery_state(&mut board).await;
|
||||
let _ = publish_mppt_state(&mut board).await;
|
||||
publish_config(&mut board).await;
|
||||
}
|
||||
|
||||
log(
|
||||
LogMessage::StartupInfo,
|
||||
matches!(network_mode, NetworkMode::WIFI { .. }) as u32,
|
||||
matches!(network_mode, network::NetworkMode::WIFI { .. }) as u32,
|
||||
matches!(
|
||||
network_mode,
|
||||
NetworkMode::WIFI {
|
||||
sntp: SntpMode::SYNC { .. },
|
||||
network::NetworkMode::WIFI {
|
||||
sntp: network::SntpMode::SYNC { .. },
|
||||
..
|
||||
}
|
||||
) as u32,
|
||||
matches!(network_mode, NetworkMode::WIFI { mqtt: true, .. })
|
||||
matches!(network_mode, network::NetworkMode::WIFI { mqtt: true, .. })
|
||||
.to_string()
|
||||
.as_str(),
|
||||
"",
|
||||
@@ -536,11 +525,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||
|
||||
match &serde_json::to_string(&light_state) {
|
||||
Ok(state) => {
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/light", state)
|
||||
.await;
|
||||
let _ = mqtt::publish("/light", state).await;
|
||||
}
|
||||
Err(err) => {
|
||||
info!("Error publishing lightstate {}", err);
|
||||
@@ -550,29 +535,16 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||
let deep_sleep_duration_minutes: u32 =
|
||||
// if battery soc is unknown assume battery has enough change
|
||||
if state_of_charge < 10.0 && !matches!(battery_state, BatteryState::Unknown) {
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/deepsleep", "low Volt 12h").await;
|
||||
let _ = mqtt::publish("/deepsleep", "low Volt 12h").await;
|
||||
12 * 60
|
||||
} else if is_day {
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/deepsleep", "normal 20m").await;
|
||||
let _ = mqtt::publish("/deepsleep", "normal 20m").await;
|
||||
20
|
||||
} else {
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/deepsleep", "night 1h").await;
|
||||
let _ = mqtt::publish("/deepsleep", "night 1h").await;
|
||||
60
|
||||
};
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/state", "sleep")
|
||||
.await;
|
||||
let _ = mqtt::publish("/state", "sleep").await;
|
||||
|
||||
info!("Go to sleep for {} minutes", deep_sleep_duration_minutes);
|
||||
//determine next event
|
||||
@@ -582,7 +554,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
|
||||
//TODO
|
||||
//mark_app_valid();
|
||||
|
||||
let stay_alive = MQTT_STAY_ALIVE.load(Ordering::Relaxed);
|
||||
let stay_alive = mqtt::is_stay_alive();
|
||||
info!("Check stay alive, current state is {}", stay_alive);
|
||||
|
||||
if stay_alive {
|
||||
@@ -737,7 +709,7 @@ async fn publish_tank_state(
|
||||
&tank_state.as_mqtt_info(&board.board_hal.get_config().tank, &water_temp),
|
||||
)
|
||||
.unwrap();
|
||||
let _ = board.board_hal.get_esp().mqtt_publish("/water", &*state);
|
||||
let _ = mqtt::publish("/water", &*state).await;
|
||||
}
|
||||
|
||||
async fn publish_plant_states(
|
||||
@@ -753,11 +725,7 @@ async fn publish_plant_states(
|
||||
let state =
|
||||
serde_json::to_string(&plant_state.to_mqtt_info(plant_conf, timezone_time)).unwrap();
|
||||
let plant_topic = format!("/plant{}", plant_id + 1);
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish(&plant_topic, &state)
|
||||
.await;
|
||||
let _ = mqtt::publish(&plant_topic, &state).await;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -767,92 +735,13 @@ async fn publish_firmware_info(
|
||||
ip_address: &str,
|
||||
timezone_time: &str,
|
||||
) {
|
||||
let esp = board.board_hal.get_esp();
|
||||
esp.mqtt_publish("/firmware/address", ip_address).await;
|
||||
esp.mqtt_publish("/firmware/state", format!("{:?}", &version).as_str())
|
||||
mqtt::publish("/firmware/address", ip_address).await;
|
||||
mqtt::publish("/firmware/state", format!("{:?}", &version).as_str())
|
||||
.await;
|
||||
esp.mqtt_publish("/firmware/last_online", timezone_time)
|
||||
mqtt::publish("/firmware/last_online", timezone_time)
|
||||
.await;
|
||||
esp.mqtt_publish("/state", "online").await;
|
||||
mqtt::publish("/state", "online").await;
|
||||
}
|
||||
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
|
||||
}};
|
||||
}
|
||||
async fn try_connect_wifi_sntp_mqtt(
|
||||
board: &mut MutexGuard<'static, CriticalSectionRawMutex, HAL<'static>>,
|
||||
stack_store: &mut OptionLock<Stack<'static>>,
|
||||
spawner: Spawner,
|
||||
) -> NetworkMode {
|
||||
let nw_conf = &board.board_hal.get_config().network.clone();
|
||||
match board.board_hal.get_esp().wifi(nw_conf, spawner).await {
|
||||
Ok(stack) => {
|
||||
stack_store.replace(stack);
|
||||
|
||||
let sntp_mode: SntpMode = match board.board_hal.get_esp().sntp(1000 * 10, stack).await {
|
||||
Ok(new_time) => {
|
||||
info!("Using time from sntp {}", new_time.to_rfc3339());
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_rtc_module()
|
||||
.set_rtc_time(&new_time)
|
||||
.await;
|
||||
SntpMode::SYNC { current: new_time }
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("sntp error: {err}");
|
||||
board.board_hal.general_fault(true).await;
|
||||
SntpMode::OFFLINE
|
||||
}
|
||||
};
|
||||
|
||||
let mqtt_connected = if board.board_hal.get_config().network.mqtt_url.is_some() {
|
||||
let nw_config = board.board_hal.get_config().network.clone();
|
||||
let nw_config = mk_static!(NetworkConfig, nw_config);
|
||||
match board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt(nw_config, stack, spawner)
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
info!("Mqtt connection ready");
|
||||
true
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("Could not connect mqtt due to {err}");
|
||||
false
|
||||
}
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
let ip = match stack.config_v4() {
|
||||
Some(config) => config.address.address().to_string(),
|
||||
None => match stack.config_v6() {
|
||||
Some(config) => config.address.address().to_string(),
|
||||
None => String::from("No IP"),
|
||||
},
|
||||
};
|
||||
NetworkMode::WIFI {
|
||||
sntp: sntp_mode,
|
||||
mqtt: mqtt_connected,
|
||||
ip_address: ip,
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
info!("Offline mode due to {err}");
|
||||
board.board_hal.general_fault(true).await;
|
||||
NetworkMode::OFFLINE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn pump_info(
|
||||
plant_id: usize,
|
||||
pump_active: bool,
|
||||
@@ -862,7 +751,7 @@ async fn pump_info(
|
||||
min_current_ma: u16,
|
||||
_error: bool,
|
||||
) {
|
||||
let pump_info = PumpInfo {
|
||||
let pump_info = mqtt::PumpInfo {
|
||||
enabled: pump_active,
|
||||
pump_ineffective,
|
||||
median_current_ma,
|
||||
@@ -873,15 +762,7 @@ async fn pump_info(
|
||||
|
||||
match serde_json::to_string(&pump_info) {
|
||||
Ok(state) => {
|
||||
BOARD_ACCESS
|
||||
.get()
|
||||
.await
|
||||
.lock()
|
||||
.await
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish(&pump_topic, &state)
|
||||
.await;
|
||||
let _ = mqtt::publish(&pump_topic, &state).await;
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("Error publishing pump state {}", err);
|
||||
@@ -894,15 +775,12 @@ async fn publish_mppt_state(
|
||||
) -> FatResult<()> {
|
||||
let current = board.board_hal.get_mptt_current().await?;
|
||||
let voltage = board.board_hal.get_mptt_voltage().await?;
|
||||
let solar_state = Solar {
|
||||
let solar_state = mqtt::Solar {
|
||||
current_ma: current.as_milliamperes() as u32,
|
||||
voltage_ma: voltage.as_millivolts() as u32,
|
||||
};
|
||||
if let Ok(serialized_solar_state_bytes) = serde_json::to_string(&solar_state) {
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/mppt", &serialized_solar_state_bytes);
|
||||
let _ = mqtt::publish("/mppt", &serialized_solar_state_bytes).await;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -923,14 +801,25 @@ async fn publish_battery_state(
|
||||
Err(_) => "error".to_owned(),
|
||||
};
|
||||
{
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_esp()
|
||||
.mqtt_publish("/battery", &*value)
|
||||
.await;
|
||||
let _ = mqtt::publish("/battery", &*value).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn publish_config(
|
||||
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'_>>,
|
||||
) {
|
||||
let config = board.board_hal.get_config();
|
||||
match serde_json::to_string(&config) {
|
||||
Ok(serialized) => {
|
||||
let _ = mqtt::publish("/config", &serialized).await;
|
||||
}
|
||||
Err(err) => {
|
||||
info!("Error serializing config: {}", err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async fn wait_infinity(
|
||||
board: MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
|
||||
wait_type: WaitType,
|
||||
@@ -1031,9 +920,8 @@ async fn wait_infinity(
|
||||
let cur = board.board_hal.get_time().await;
|
||||
let timezone_time = cur.with_timezone(&timezone);
|
||||
|
||||
let esp = board.board_hal.get_esp();
|
||||
esp.mqtt_publish("/state", "config").await;
|
||||
esp.mqtt_publish("/firmware/last_online", &timezone_time.to_rfc3339())
|
||||
mqtt::publish("/state", "config").await;
|
||||
mqtt::publish("/firmware/last_online", &timezone_time.to_rfc3339())
|
||||
.await;
|
||||
last_mqtt_update = Some(now);
|
||||
}
|
||||
@@ -1087,7 +975,7 @@ async fn wait_infinity(
|
||||
|
||||
hal::PlantHal::feed_watchdog();
|
||||
|
||||
if wait_type == WaitType::MqttConfig && !MQTT_STAY_ALIVE.load(Ordering::Relaxed) {
|
||||
if wait_type == WaitType::MqttConfig && !mqtt::is_stay_alive() {
|
||||
reboot_now.store(true, Ordering::Relaxed);
|
||||
}
|
||||
if reboot_now.load(Ordering::Relaxed) {
|
||||
|
||||
315
rust/src/mqtt.rs
Normal file
315
rust/src/mqtt.rs
Normal file
@@ -0,0 +1,315 @@
|
||||
use crate::bail;
|
||||
use crate::config::NetworkConfig;
|
||||
use crate::fat_error::{ContextExt, FatError, FatResult};
|
||||
use crate::hal::PlantHal;
|
||||
use crate::log::{log, LogMessage};
|
||||
use alloc::string::String;
|
||||
use alloc::{format, string::ToString, vec::Vec};
|
||||
use core::sync::atomic::Ordering;
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_net::Stack;
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_sync::mutex::Mutex;
|
||||
use embassy_sync::once_lock::OnceLock;
|
||||
use embassy_time::{Duration, Timer, WithTimeout};
|
||||
use log::info;
|
||||
use mcutie::{
|
||||
Error, McutieBuilder, McutieReceiver, McutieTask, MqttMessage, PublishDisplay, Publishable,
|
||||
QoS, Topic,
|
||||
};
|
||||
use portable_atomic::AtomicBool;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, PartialEq, Default)]
|
||||
pub struct PumpInfo {
|
||||
pub enabled: bool,
|
||||
pub pump_ineffective: bool,
|
||||
pub median_current_ma: u16,
|
||||
pub max_current_ma: u16,
|
||||
pub min_current_ma: u16,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, PartialEq)]
|
||||
pub struct Solar {
|
||||
pub current_ma: u32,
|
||||
pub voltage_ma: u32,
|
||||
}
|
||||
|
||||
static MQTT_CONNECTED_EVENT_RECEIVED: AtomicBool = AtomicBool::new(false);
|
||||
static MQTT_ROUND_TRIP_RECEIVED: AtomicBool = AtomicBool::new(false);
|
||||
pub static MQTT_STAY_ALIVE: AtomicBool = AtomicBool::new(false);
|
||||
static MQTT_BASE_TOPIC: OnceLock<String> = OnceLock::new();
|
||||
static MQTT_CONFIG_UPDATE_PAYLOAD: Mutex<CriticalSectionRawMutex, Option<String>> = Mutex::new(None);
|
||||
|
||||
pub fn is_stay_alive() -> bool {
|
||||
MQTT_STAY_ALIVE.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub async fn publish(subtopic: &str, message: &str) {
|
||||
let online = MQTT_CONNECTED_EVENT_RECEIVED.load(Ordering::Relaxed);
|
||||
if !online {
|
||||
return;
|
||||
}
|
||||
let roundtrip_ok = MQTT_ROUND_TRIP_RECEIVED.load(Ordering::Relaxed);
|
||||
if !roundtrip_ok {
|
||||
info!("MQTT roundtrip not received yet, dropping message");
|
||||
return;
|
||||
}
|
||||
match publish_inner(subtopic, message).await {
|
||||
Ok(()) => {}
|
||||
Err(err) => {
|
||||
info!(
|
||||
"Error during mqtt send on topic {subtopic} with message {message:#?} error is {err:?}"
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async fn publish_inner(subtopic: &str, message: &str) -> FatResult<()> {
|
||||
if !subtopic.starts_with("/") {
|
||||
bail!("Subtopic without / at start {}", subtopic);
|
||||
}
|
||||
if subtopic.len() > 192 {
|
||||
bail!("Subtopic exceeds 192 chars {}", subtopic);
|
||||
}
|
||||
let base_topic = MQTT_BASE_TOPIC
|
||||
.try_get()
|
||||
.context("missing base topic in static!")?;
|
||||
|
||||
let full_topic = format!("{base_topic}{subtopic}");
|
||||
|
||||
loop {
|
||||
let result = Topic::General(full_topic.as_str())
|
||||
.with_display(message)
|
||||
.retain(true)
|
||||
.publish()
|
||||
.await;
|
||||
match result {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(err) => {
|
||||
let retry = match err {
|
||||
Error::IOError => false,
|
||||
Error::TimedOut => true,
|
||||
Error::TooLarge => false,
|
||||
Error::PacketError => false,
|
||||
Error::Invalid => false,
|
||||
Error::Rejected => false,
|
||||
};
|
||||
if !retry {
|
||||
bail!(
|
||||
"Error during mqtt send on topic {} with message {:#?} error is {:?}",
|
||||
&full_topic,
|
||||
message,
|
||||
err
|
||||
);
|
||||
}
|
||||
info!(
|
||||
"Retransmit for {} with message {:#?} error is {:?} retrying {}",
|
||||
&full_topic, message, err, retry
|
||||
);
|
||||
Timer::after(Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
use crate::util::mk_static;
|
||||
|
||||
pub async fn mqtt_init(
|
||||
network_config: &'static NetworkConfig,
|
||||
stack: Stack<'static>,
|
||||
spawner: Spawner,
|
||||
) -> FatResult<()> {
|
||||
let base_topic = network_config
|
||||
.base_topic
|
||||
.as_ref()
|
||||
.context("missing base topic")?;
|
||||
if base_topic.is_empty() {
|
||||
bail!("Mqtt base_topic was empty")
|
||||
}
|
||||
MQTT_BASE_TOPIC
|
||||
.init(base_topic.to_string())
|
||||
.map_err(|_| FatError::String {
|
||||
error: "Error setting basetopic".to_string(),
|
||||
})?;
|
||||
|
||||
let mqtt_url = network_config
|
||||
.mqtt_url
|
||||
.as_ref()
|
||||
.context("missing mqtt url")?;
|
||||
if mqtt_url.is_empty() {
|
||||
bail!("Mqtt url was empty")
|
||||
}
|
||||
|
||||
let last_will_topic = format!("{base_topic}/state");
|
||||
let round_trip_topic = format!("{base_topic}/internal/roundtrip");
|
||||
let stay_alive_topic = format!("{base_topic}/stay_alive");
|
||||
let config_update_payload_topic = format!("{base_topic}/config/update_payload");
|
||||
let config_update_topic = format!("{base_topic}/config/update");
|
||||
|
||||
let mut builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 0> =
|
||||
McutieBuilder::new(stack, "plant ctrl", mqtt_url);
|
||||
if let (Some(mqtt_user), Some(mqtt_password)) = (
|
||||
network_config.mqtt_user.as_ref(),
|
||||
network_config.mqtt_password.as_ref(),
|
||||
) {
|
||||
builder = builder.with_authentication(mqtt_user, mqtt_password);
|
||||
info!("With authentification");
|
||||
}
|
||||
|
||||
let lwt = Topic::General(last_will_topic);
|
||||
let lwt = mk_static!(Topic<String>, lwt);
|
||||
let lwt = lwt.with_display("lost").retain(true).qos(QoS::AtLeastOnce);
|
||||
builder = builder.with_last_will(lwt);
|
||||
//TODO make configurable
|
||||
builder = builder.with_device_id("plantctrl");
|
||||
|
||||
let builder: McutieBuilder<'_, String, PublishDisplay<String, &str>, 4> = builder
|
||||
.with_subscriptions([
|
||||
Topic::General(round_trip_topic.clone()),
|
||||
Topic::General(stay_alive_topic.clone()),
|
||||
Topic::General(config_update_payload_topic.clone()),
|
||||
Topic::General(config_update_topic.clone()),
|
||||
]);
|
||||
|
||||
let keep_alive = Duration::from_secs(60 * 60 * 2).as_secs() as u16;
|
||||
let (receiver, task) = builder.build(keep_alive);
|
||||
|
||||
spawner.spawn(mqtt_incoming_task(
|
||||
receiver,
|
||||
round_trip_topic.clone(),
|
||||
stay_alive_topic.clone(),
|
||||
config_update_payload_topic.clone(),
|
||||
config_update_topic.clone(),
|
||||
)?);
|
||||
spawner.spawn(mqtt_runner(task)?);
|
||||
|
||||
log(LogMessage::StayAlive, 0, 0, "", &stay_alive_topic);
|
||||
|
||||
log(LogMessage::MqttInfo, 0, 0, "", mqtt_url);
|
||||
|
||||
let mqtt_timeout = 15000;
|
||||
let res = async {
|
||||
while !MQTT_CONNECTED_EVENT_RECEIVED.load(Ordering::Relaxed) {
|
||||
PlantHal::feed_watchdog();
|
||||
Timer::after(Duration::from_millis(100)).await;
|
||||
}
|
||||
Ok::<(), FatError>(())
|
||||
}
|
||||
.with_timeout(Duration::from_millis(mqtt_timeout as u64))
|
||||
.await;
|
||||
|
||||
if res.is_err() {
|
||||
bail!("Timeout waiting MQTT connect event")
|
||||
}
|
||||
|
||||
let _ = Topic::General(round_trip_topic.clone())
|
||||
.with_display("online_text")
|
||||
.publish()
|
||||
.await;
|
||||
|
||||
let res = async {
|
||||
while !MQTT_ROUND_TRIP_RECEIVED.load(Ordering::Relaxed) {
|
||||
PlantHal::feed_watchdog();
|
||||
Timer::after(Duration::from_millis(100)).await;
|
||||
}
|
||||
Ok::<(), FatError>(())
|
||||
}
|
||||
.with_timeout(Duration::from_millis(mqtt_timeout as u64))
|
||||
.await;
|
||||
|
||||
if res.is_err() {
|
||||
MQTT_CONNECTED_EVENT_RECEIVED.store(false, Ordering::Relaxed);
|
||||
bail!("Timeout waiting MQTT roundtrip")
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn mqtt_runner(
|
||||
task: McutieTask<'static, String, PublishDisplay<'static, String, &'static str>, 4>,
|
||||
) {
|
||||
task.run().await;
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
async fn mqtt_incoming_task(
|
||||
receiver: McutieReceiver,
|
||||
round_trip_topic: String,
|
||||
stay_alive_topic: String,
|
||||
config_update_payload_topic: String,
|
||||
config_update_topic: String,
|
||||
) {
|
||||
loop {
|
||||
let message = receiver.receive().await;
|
||||
match message {
|
||||
MqttMessage::Connected => {
|
||||
info!("Mqtt connected");
|
||||
MQTT_CONNECTED_EVENT_RECEIVED.store(true, Ordering::Relaxed);
|
||||
}
|
||||
MqttMessage::Publish(topic, payload) => match topic {
|
||||
Topic::DeviceType(_type_topic) => {}
|
||||
Topic::Device(_device_topic) => {}
|
||||
Topic::General(topic) => {
|
||||
let subtopic = topic.as_str();
|
||||
|
||||
if subtopic.eq(round_trip_topic.as_str()) {
|
||||
MQTT_ROUND_TRIP_RECEIVED.store(true, Ordering::Relaxed);
|
||||
} else if subtopic.eq(stay_alive_topic.as_str()) {
|
||||
let value = payload.eq_ignore_ascii_case("true".as_ref())
|
||||
|| payload.eq_ignore_ascii_case("1".as_ref());
|
||||
let a = match value {
|
||||
true => 1,
|
||||
false => 0,
|
||||
};
|
||||
log(LogMessage::MqttStayAliveRec, a, 0, "", "");
|
||||
MQTT_STAY_ALIVE.store(value, Ordering::Relaxed);
|
||||
} else if subtopic.eq(config_update_payload_topic.as_str()) {
|
||||
let payload_str = String::from_utf8_lossy(&payload[..]).to_string();
|
||||
let mut buffer = MQTT_CONFIG_UPDATE_PAYLOAD.lock().await;
|
||||
*buffer = Some(payload_str);
|
||||
info!("MQTT config update payload received");
|
||||
} else if subtopic.eq(config_update_topic.as_str()) {
|
||||
let update_requested = payload.eq_ignore_ascii_case("true".as_ref())
|
||||
|| payload.eq_ignore_ascii_case("1".as_ref());
|
||||
if update_requested {
|
||||
info!("MQTT config update requested");
|
||||
let payload_lock = MQTT_CONFIG_UPDATE_PAYLOAD.lock().await;
|
||||
if let Some(payload_str) = payload_lock.as_ref() {
|
||||
match serde_json::from_str::<crate::config::PlantControllerConfig>(payload_str) {
|
||||
Ok(config) => {
|
||||
info!("Deserialized config, applying...");
|
||||
let board_mutex = crate::BOARD_ACCESS.get().await;
|
||||
let mut board = board_mutex.lock().await;
|
||||
if let Err(e) = board.board_hal.get_esp().save_config(payload_str.as_bytes().to_vec()).await {
|
||||
info!("Error saving config to flash: {}", e);
|
||||
let _ = publish("/config/update", "false").await;
|
||||
} else {
|
||||
board.board_hal.set_config(config);
|
||||
info!("Config applied, rebooting");
|
||||
let _ = publish("/config/update", "false").await;
|
||||
board.board_hal.get_esp().deep_sleep_ms(0);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
info!("Error deserializing config: {}", e);
|
||||
let _ = publish("/config/update", "false").await;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
info!("No config update payload available");
|
||||
let _ = publish("/config/update", "false").await;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log(LogMessage::UnknownTopic, 0, 0, "", &topic);
|
||||
}
|
||||
}
|
||||
},
|
||||
MqttMessage::Disconnected => {
|
||||
MQTT_CONNECTED_EVENT_RECEIVED.store(false, Ordering::Relaxed);
|
||||
info!("Mqtt disconnected");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
419
rust/src/network.rs
Normal file
419
rust/src/network.rs
Normal file
@@ -0,0 +1,419 @@
|
||||
use crate::bail;
|
||||
use crate::config::NetworkConfig;
|
||||
use crate::fat_error::{ContextExt, FatError, FatResult};
|
||||
use crate::hal::{PlantHal, HAL};
|
||||
use crate::mqtt;
|
||||
use crate::util::mk_static;
|
||||
use alloc::string::{String, ToString};
|
||||
use alloc::sync::Arc;
|
||||
use chrono::{DateTime, Utc};
|
||||
use core::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
|
||||
use embassy_executor::Spawner;
|
||||
use embassy_net::dns::DnsQueryType;
|
||||
use embassy_net::udp::{PacketMetadata, UdpSocket};
|
||||
use embassy_net::{DhcpConfig, Runner, Stack, StackResources, StaticConfigV4};
|
||||
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
|
||||
use embassy_sync::mutex::{Mutex, MutexGuard};
|
||||
use embassy_time::{Duration, Timer, WithTimeout};
|
||||
use option_lock::OptionLock;
|
||||
use edge_dhcp::{
|
||||
io::{self, DEFAULT_SERVER_PORT},
|
||||
server::{Server, ServerOptions},
|
||||
};
|
||||
use edge_nal::UdpBind;
|
||||
use edge_nal_embassy::{Udp, UdpBuffers};
|
||||
use esp_hal::rng::Rng;
|
||||
use esp_println::println;
|
||||
use esp_radio::wifi::ap::AccessPointConfig;
|
||||
use esp_radio::wifi::sta::StationConfig;
|
||||
use esp_radio::wifi::{AuthenticationMethod, Config, Interface};
|
||||
use log::{info, warn, error};
|
||||
use serde::Serialize;
|
||||
use sntpc::{NtpContext, NtpTimestampGenerator, NtpUdpSocket, get_time};
|
||||
|
||||
const NTP_SERVER: &str = "pool.ntp.org";
|
||||
|
||||
#[derive(Copy, Clone, Default)]
|
||||
struct Timestamp {
|
||||
stamp: DateTime<Utc>,
|
||||
}
|
||||
|
||||
impl NtpTimestampGenerator for Timestamp {
|
||||
fn init(&mut self) {
|
||||
self.stamp = DateTime::default();
|
||||
}
|
||||
|
||||
fn timestamp_sec(&self) -> u64 {
|
||||
self.stamp.timestamp() as u64
|
||||
}
|
||||
|
||||
fn timestamp_subsec_micros(&self) -> u32 {
|
||||
self.stamp.timestamp_subsec_micros()
|
||||
}
|
||||
}
|
||||
|
||||
struct EmbassyNtpSocket<'a, 'b> {
|
||||
socket: &'a UdpSocket<'b>,
|
||||
}
|
||||
|
||||
impl<'a, 'b> EmbassyNtpSocket<'a, 'b> {
|
||||
fn new(socket: &'a UdpSocket<'b>) -> Self {
|
||||
Self { socket }
|
||||
}
|
||||
}
|
||||
|
||||
impl NtpUdpSocket for EmbassyNtpSocket<'_, '_> {
|
||||
async fn send_to(&self, buf: &[u8], addr: SocketAddr) -> sntpc::Result<usize> {
|
||||
self.socket
|
||||
.send_to(buf, addr)
|
||||
.await
|
||||
.map_err(|_| sntpc::Error::Network)?;
|
||||
Ok(buf.len())
|
||||
}
|
||||
|
||||
async fn recv_from(&self, buf: &mut [u8]) -> sntpc::Result<(usize, SocketAddr)> {
|
||||
let (len, metadata) = self
|
||||
.socket
|
||||
.recv_from(buf)
|
||||
.await
|
||||
.map_err(|_| sntpc::Error::Network)?;
|
||||
let addr = match metadata.endpoint.addr {
|
||||
embassy_net::IpAddress::Ipv4(ip) => IpAddr::V4(ip),
|
||||
embassy_net::IpAddress::Ipv6(ip) => IpAddr::V6(ip),
|
||||
};
|
||||
Ok((len, SocketAddr::new(addr, metadata.endpoint.port)))
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn sntp(max_wait_ms: u32, stack: Stack<'_>) -> FatResult<DateTime<Utc>> {
|
||||
println!("start sntp");
|
||||
let mut rx_meta = [PacketMetadata::EMPTY; 16];
|
||||
let mut rx_buffer = [0; 4096];
|
||||
let mut tx_meta = [PacketMetadata::EMPTY; 16];
|
||||
let mut tx_buffer = [0; 4096];
|
||||
|
||||
let mut socket = UdpSocket::new(
|
||||
stack,
|
||||
&mut rx_meta,
|
||||
&mut rx_buffer,
|
||||
&mut tx_meta,
|
||||
&mut tx_buffer,
|
||||
);
|
||||
socket.bind(123).context("Could not bind UDP socket")?;
|
||||
|
||||
let context = NtpContext::new(Timestamp::default());
|
||||
let ntp_socket = EmbassyNtpSocket::new(&socket);
|
||||
|
||||
let ntp_addrs = stack
|
||||
.dns_query(NTP_SERVER, DnsQueryType::A)
|
||||
.await
|
||||
.context("Failed to resolve DNS")?;
|
||||
|
||||
if ntp_addrs.is_empty() {
|
||||
bail!("No IP addresses found for NTP server");
|
||||
}
|
||||
let ntp = ntp_addrs[0];
|
||||
info!("NTP server: {ntp:?}");
|
||||
|
||||
let mut counter = 0;
|
||||
loop {
|
||||
let addr: IpAddr = ntp.into();
|
||||
let timeout = get_time(SocketAddr::from((addr, 123)), &ntp_socket, context)
|
||||
.with_timeout(Duration::from_millis((max_wait_ms / 10) as u64))
|
||||
.await;
|
||||
|
||||
match timeout {
|
||||
Ok(result) => {
|
||||
let time = result?;
|
||||
info!("Time: {time:?}");
|
||||
return DateTime::from_timestamp(time.seconds as i64, 0)
|
||||
.context("Could not convert Sntp result");
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("sntp timeout, retry: {err:?}");
|
||||
counter += 1;
|
||||
if counter > 10 {
|
||||
bail!("Failed to get time from NTP server");
|
||||
}
|
||||
Timer::after(Duration::from_millis(100)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, PartialEq)]
|
||||
pub enum SntpMode {
|
||||
OFFLINE,
|
||||
SYNC { current: DateTime<Utc> },
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, PartialEq)]
|
||||
pub enum NetworkMode {
|
||||
WIFI {
|
||||
sntp: SntpMode,
|
||||
mqtt: bool,
|
||||
ip_address: String,
|
||||
},
|
||||
OFFLINE,
|
||||
}
|
||||
|
||||
#[embassy_executor::task(pool_size = 2)]
|
||||
pub(crate) async fn net_task(mut runner: Runner<'static, Interface<'static>>) {
|
||||
runner.run().await;
|
||||
}
|
||||
|
||||
#[embassy_executor::task]
|
||||
pub(crate) async fn run_dhcp(stack: Stack<'static>, ip: Ipv4Addr) {
|
||||
let mut buf = [0u8; 1500];
|
||||
|
||||
let mut gw_buf = [Ipv4Addr::UNSPECIFIED];
|
||||
|
||||
let buffers = UdpBuffers::<3, 1024, 1024, 10>::new();
|
||||
let unbound_socket = Udp::new(stack, &buffers);
|
||||
let mut bound_socket = match unbound_socket
|
||||
.bind(SocketAddr::V4(SocketAddrV4::new(
|
||||
Ipv4Addr::UNSPECIFIED,
|
||||
DEFAULT_SERVER_PORT,
|
||||
)))
|
||||
.await
|
||||
{
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
error!("dhcp task failed to bind socket: {:?}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
loop {
|
||||
_ = io::server::run(
|
||||
&mut Server::<_, 64>::new_with_et(ip),
|
||||
&ServerOptions::new(ip, Some(&mut gw_buf)),
|
||||
&mut bound_socket,
|
||||
&mut buf,
|
||||
)
|
||||
.await
|
||||
.inspect_err(|e| warn!("DHCP server error: {e:?}"));
|
||||
Timer::after(Duration::from_millis(500)).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn wifi_ap(
|
||||
ssid: String,
|
||||
interface_ap: Interface<'static>,
|
||||
controller: &Arc<Mutex<CriticalSectionRawMutex, esp_radio::wifi::WifiController<'static>>>,
|
||||
rng: &mut Rng,
|
||||
spawner: Spawner,
|
||||
) -> FatResult<Stack<'static>> {
|
||||
let gw_ip_addr = Ipv4Addr::new(192, 168, 71, 1);
|
||||
|
||||
let config = embassy_net::Config::ipv4_static(StaticConfigV4 {
|
||||
address: embassy_net::Ipv4Cidr::new(gw_ip_addr, 24),
|
||||
gateway: Some(gw_ip_addr),
|
||||
dns_servers: Default::default(),
|
||||
});
|
||||
|
||||
let seed = (rng.random() as u64) << 32 | rng.random() as u64;
|
||||
|
||||
println!("init secondary stack");
|
||||
let (stack, runner) = embassy_net::new(
|
||||
interface_ap,
|
||||
config,
|
||||
mk_static!(StackResources<4>, StackResources::<4>::new()),
|
||||
seed,
|
||||
);
|
||||
let stack = mk_static!(Stack, stack);
|
||||
|
||||
let client_config =
|
||||
Config::AccessPoint(AccessPointConfig::default().with_ssid(ssid.clone()));
|
||||
controller.lock().await.set_config(&client_config)?;
|
||||
|
||||
println!("start net task");
|
||||
spawner.spawn(net_task(runner)?);
|
||||
println!("run dhcp");
|
||||
spawner.spawn(run_dhcp(*stack, gw_ip_addr)?);
|
||||
|
||||
loop {
|
||||
if stack.is_link_up() {
|
||||
break;
|
||||
}
|
||||
Timer::after(Duration::from_millis(500)).await;
|
||||
}
|
||||
while !stack.is_config_up() {
|
||||
Timer::after(Duration::from_millis(100)).await
|
||||
}
|
||||
println!("Connect to the AP `${ssid}` and point your browser to http://{gw_ip_addr}/");
|
||||
stack
|
||||
.config_v4()
|
||||
.inspect(|c| println!("ipv4 config: {c:?}"));
|
||||
|
||||
Ok(*stack)
|
||||
}
|
||||
|
||||
pub async fn wifi(
|
||||
network_config: &NetworkConfig,
|
||||
interface_sta: Interface<'static>,
|
||||
controller: &Arc<Mutex<CriticalSectionRawMutex, esp_radio::wifi::WifiController<'static>>>,
|
||||
rng: &mut Rng,
|
||||
spawner: Spawner,
|
||||
) -> FatResult<Stack<'static>> {
|
||||
esp_radio::wifi_set_log_verbose();
|
||||
let ssid = match &network_config.ssid {
|
||||
Some(ssid) => {
|
||||
if ssid.is_empty() {
|
||||
bail!("Wifi ssid was empty")
|
||||
}
|
||||
ssid.as_str().to_string()
|
||||
}
|
||||
None => {
|
||||
bail!("Wifi ssid was empty")
|
||||
}
|
||||
};
|
||||
info!("attempting to connect wifi {ssid}");
|
||||
let password = match network_config.password {
|
||||
Some(ref password) => password.as_str().to_string(),
|
||||
None => "".to_string(),
|
||||
};
|
||||
let max_wait = network_config.max_wait;
|
||||
|
||||
let config = embassy_net::Config::dhcpv4(DhcpConfig::default());
|
||||
|
||||
let seed = (rng.random() as u64) << 32 | rng.random() as u64;
|
||||
|
||||
let (stack, runner) = embassy_net::new(
|
||||
interface_sta,
|
||||
config,
|
||||
mk_static!(StackResources<8>, StackResources::<8>::new()),
|
||||
seed,
|
||||
);
|
||||
let stack = mk_static!(Stack, stack);
|
||||
|
||||
let auth_method = if password.is_empty() {
|
||||
AuthenticationMethod::None
|
||||
} else {
|
||||
AuthenticationMethod::Wpa2Personal
|
||||
};
|
||||
let client_config = StationConfig::default()
|
||||
.with_ssid(ssid)
|
||||
.with_auth_method(auth_method)
|
||||
.with_scan_method(esp_radio::wifi::sta::ScanMethod::AllChannels)
|
||||
.with_listen_interval(10)
|
||||
.with_beacon_timeout(10)
|
||||
.with_failure_retry_cnt(3)
|
||||
.with_password(password);
|
||||
|
||||
controller
|
||||
.lock()
|
||||
.await
|
||||
.set_config(&Config::Station(client_config))?;
|
||||
spawner.spawn(net_task(runner)?);
|
||||
controller
|
||||
.lock()
|
||||
.await
|
||||
.connect_async()
|
||||
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
|
||||
.await
|
||||
.context("Timeout waiting for wifi sta connected")??;
|
||||
|
||||
let res = async {
|
||||
while !stack.is_link_up() {
|
||||
Timer::after(Duration::from_millis(500)).await;
|
||||
}
|
||||
Ok::<(), FatError>(())
|
||||
}
|
||||
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
|
||||
.await;
|
||||
|
||||
if res.is_err() {
|
||||
bail!("Timeout waiting for wifi link up")
|
||||
}
|
||||
|
||||
let res = async {
|
||||
while !stack.is_config_up() {
|
||||
Timer::after(Duration::from_millis(100)).await
|
||||
}
|
||||
Ok::<(), FatError>(())
|
||||
}
|
||||
.with_timeout(Duration::from_millis(max_wait as u64 * 1000))
|
||||
.await;
|
||||
|
||||
if res.is_err() {
|
||||
bail!("Timeout waiting for wifi config up")
|
||||
}
|
||||
|
||||
info!("Connected WIFI, dhcp: {:?}", stack.config_v4());
|
||||
Ok(*stack)
|
||||
}
|
||||
|
||||
pub async fn try_connect_wifi_sntp_mqtt(
|
||||
board: &mut MutexGuard<'static, CriticalSectionRawMutex, HAL<'static>>,
|
||||
stack_store: &mut OptionLock<Stack<'static>>,
|
||||
spawner: Spawner,
|
||||
) -> NetworkMode {
|
||||
let nw_conf = &board.board_hal.get_config().network.clone();
|
||||
let esp = board.board_hal.get_esp();
|
||||
let device = match esp.interface_sta.take() {
|
||||
Some(d) => d,
|
||||
None => {
|
||||
info!("Offline mode due to STA interface already taken");
|
||||
board.board_hal.general_fault(true).await;
|
||||
return NetworkMode::OFFLINE;
|
||||
}
|
||||
};
|
||||
match wifi(nw_conf, device, &esp.controller, &mut esp.rng, spawner).await {
|
||||
Ok(stack) => {
|
||||
stack_store.replace(stack);
|
||||
|
||||
let sntp_mode: SntpMode = match sntp(1000 * 10, stack).await {
|
||||
Ok(new_time) => {
|
||||
info!("Using time from sntp {}", new_time.to_rfc3339());
|
||||
let _ = board
|
||||
.board_hal
|
||||
.get_rtc_module()
|
||||
.set_rtc_time(&new_time)
|
||||
.await;
|
||||
SntpMode::SYNC { current: new_time }
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("sntp error: {err}");
|
||||
board.board_hal.general_fault(true).await;
|
||||
SntpMode::OFFLINE
|
||||
}
|
||||
};
|
||||
|
||||
let mqtt_connected = if board.board_hal.get_config().network.mqtt_url.is_some() {
|
||||
let nw_config = board.board_hal.get_config().network.clone();
|
||||
let nw_config = mk_static!(NetworkConfig, nw_config);
|
||||
match mqtt::mqtt_init(nw_config, stack, spawner).await {
|
||||
Ok(_) => {
|
||||
info!("Mqtt connection ready");
|
||||
true
|
||||
}
|
||||
Err(err) => {
|
||||
warn!("Could not connect mqtt due to {err}");
|
||||
false
|
||||
}
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
let ip = match stack.config_v4() {
|
||||
Some(config) => config.address.address().to_string(),
|
||||
None => match stack.config_v6() {
|
||||
Some(config) => config.address.address().to_string(),
|
||||
None => String::from("No IP"),
|
||||
},
|
||||
};
|
||||
NetworkMode::WIFI {
|
||||
sntp: sntp_mode,
|
||||
mqtt: mqtt_connected,
|
||||
ip_address: ip,
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
info!("Offline mode due to {err}");
|
||||
board.board_hal.general_fault(true).await;
|
||||
NetworkMode::OFFLINE
|
||||
}
|
||||
}
|
||||
}
|
||||
10
rust/src/util.rs
Normal file
10
rust/src/util.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
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
|
||||
}};
|
||||
}
|
||||
|
||||
pub(crate) use mk_static;
|
||||
Reference in New Issue
Block a user