17 Commits

Author SHA1 Message Date
6ffbf710d3 slight adjustments 2025-11-19 12:20:26 +01:00
f6767d1827 refactor: organize dependencies in Cargo.toml for clarity and consistency 2025-11-13 21:33:01 +01:00
3db71eea45 Merge branch 'goodby-espidf' of ssh://git.mannheim.ccc.de:1337/C3MA/PlantCtrl into goodby-espidf 2025-11-13 20:08:45 +01:00
576b81bb66 vcs config 2025-11-13 20:08:19 +01:00
8cd9e08e93 shared flash test 2025-11-02 02:30:21 +01:00
0519ca3efe read and write to nal 2025-10-31 23:39:10 +01:00
f366aace7f esp-hal release wip 2025-10-31 23:22:40 +01:00
8b0734d029 config for sensor 2025-10-31 14:01:43 +01:00
cafe1b264e refactor: unify moisture handling, update config structure, and add peer dependencies 2025-10-23 22:44:44 +02:00
1db3f7af64 chore: 📎 + fmt 2025-10-18 20:40:38 +02:00
6357ec773f Merge branch 'containerize-toolchains' into goodby-espidf 2025-10-18 19:03:13 +02:00
de83d7f4b0 fix containerized build environment for cargo 2025-10-18 18:42:02 +02:00
6c874fb852 updated node package lock 2025-10-18 18:41:47 +02:00
658efd30bb improve build scripts
- use shebang
- use pushd/popd
- add npm install to initialize node project dependencies
2025-10-18 18:40:27 +02:00
70df806a87 setup cargo run to use containerized build tools that are not rust tools 2025-10-18 18:19:03 +02:00
1423b246da install nodejs and npm 2025-10-18 18:15:53 +02:00
ad15eb7bf0 containerize c toolchain for filesystem 2025-10-18 18:15:48 +02:00
63 changed files with 36978 additions and 6060 deletions

View File

@@ -6037,7 +6037,7 @@
(descr "SOT, 3 Pin (JEDEC TO-236 Var AB https://www.jedec.org/document_search?search_api_views_fulltext=TO-236), generated with kicad-footprint-generator ipc_gullwing_generator.py")
(tags "SOT TO_SOT_SMD")
(property "Reference" "D6"
(at 0 -2.4 180)
(at -1.9875 -2.25 180)
(layer "F.SilkS")
(uuid "ba224372-284d-4e83-bdee-3dcc26b3a1ec")
(effects
@@ -18704,7 +18704,7 @@
(descr "SOT, 3 Pin (JEDEC TO-236 Var AB https://www.jedec.org/document_search?search_api_views_fulltext=TO-236), generated with kicad-footprint-generator ipc_gullwing_generator.py")
(tags "SOT TO_SOT_SMD")
(property "Reference" "D1"
(at 0 -2.4 0)
(at 0 2.3 0)
(layer "F.SilkS")
(uuid "9750a299-8bf6-4149-9d59-b90e672d444d")
(effects
@@ -22662,7 +22662,7 @@
(descr "SOT, 3 Pin (JEDEC TO-236 Var AB https://www.jedec.org/document_search?search_api_views_fulltext=TO-236), generated with kicad-footprint-generator ipc_gullwing_generator.py")
(tags "SOT TO_SOT_SMD")
(property "Reference" "D4"
(at 0 -2.4 0)
(at 2.9875 -0.25 0)
(layer "F.SilkS")
(uuid "f9abdc1a-0e87-4699-bd29-df7c0baae9cd")
(effects
@@ -27517,7 +27517,7 @@
)
)
(gr_text "Extension Module"
(at 212.58 97.67 0)
(at 212.516642 96.15145 0)
(layer "F.SilkS")
(uuid "e56a58c6-c9a0-4ac6-ae66-550392612e86")
(effects

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"board": {
"active_layer": 0,
"active_layer": 25,
"active_layer_preset": "",
"auto_track_width": true,
"hidden_netclasses": [],

View File

@@ -51,7 +51,13 @@
"min_clearance": 0.5
}
},
"diff_pair_dimensions": [],
"diff_pair_dimensions": [
{
"gap": 0.0,
"via_gap": 0.0,
"width": 0.0
}
],
"drc_exclusions": [],
"meta": {
"version": 2
@@ -95,8 +101,8 @@
"pth_inside_courtyard": "ignore",
"shorting_items": "error",
"silk_edge_clearance": "warning",
"silk_over_copper": "warning",
"silk_overlap": "warning",
"silk_over_copper": "ignore",
"silk_overlap": "ignore",
"skew_out_of_range": "error",
"solder_mask_bridge": "error",
"starved_thermal": "error",
@@ -133,7 +139,7 @@
"min_track_width": 0.0,
"min_via_annular_width": 0.1,
"min_via_diameter": 0.5,
"solder_mask_to_copper_clearance": 0.0,
"solder_mask_to_copper_clearance": 0.005,
"use_height_for_length_calcs": true
},
"teardrop_options": [
@@ -180,7 +186,12 @@
"td_width_to_size_filter_ratio": 0.9
}
],
"track_widths": [],
"track_widths": [
0.0,
0.2,
0.5,
1.0
],
"tuning_pattern_settings": {
"diff_pair_defaults": {
"corner_radius_percentage": 80,
@@ -207,7 +218,12 @@
"spacing": 0.6
}
},
"via_dimensions": [],
"via_dimensions": [
{
"diameter": 0.0,
"drill": 0.0
}
],
"zones_allow_external_fillets": false
},
"ipc2581": {
@@ -431,7 +447,7 @@
"pin_not_connected": "error",
"pin_not_driven": "error",
"pin_to_pin": "warning",
"power_pin_not_driven": "error",
"power_pin_not_driven": "ignore",
"same_local_global_label": "warning",
"similar_label_and_power": "warning",
"similar_labels": "warning",
@@ -818,6 +834,24 @@
"label": "#",
"name": "${ITEM_NUMBER}",
"show": false
},
{
"group_by": false,
"label": "LCSC_PART_NUMBER",
"name": "LCSC_PART_NUMBER",
"show": false
},
{
"group_by": false,
"label": "Sim.Device",
"name": "Sim.Device",
"show": false
},
{
"group_by": false,
"label": "Sim.Type",
"name": "Sim.Type",
"show": false
}
],
"filter_string": "",

File diff suppressed because it is too large Load Diff

View File

@@ -2,8 +2,9 @@
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
<mapping directory="$PROJECT_DIR$" vcs="Git" />
<mapping directory="$PROJECT_DIR$/../../website/themes/blowfish" vcs="Git" />
</component>
<component name="VcsProjectSettings">
<option name="detectVcsMappingsAutomatically" value="false" />
</component>
</project>

View File

@@ -51,3 +51,11 @@ strip = true # symbols are not flashed to the microcontroller, so don't strip
lto = true
debug = false
opt-level = "z" # Optimize for size.
[[bin]]
name = "sensor"
path = "src/main.rs"
test = false
bench = false
doctest = false

View File

@@ -3,26 +3,29 @@
extern crate alloc;
use crate::hal::peripherals::CAN1;
use core::fmt::Write as _;
use canapi::id::{classify, plant_id, MessageKind, IDENTIFY_CMD_OFFSET, MOISTURE_DATA_OFFSET};
use canapi::id::{plant_id, MessageKind, IDENTIFY_CMD_OFFSET, MOISTURE_DATA_OFFSET};
use canapi::SensorSlot;
use ch32_hal::gpio::{Level, Output, Speed};
use ch32_hal::adc::{Adc, SampleTime, ADC_MAX};
use ch32_hal::can;
use ch32_hal::can::{Can, CanFifo, CanFilter, CanFrame, CanMode};
use ch32_hal::mode::{NonBlocking};
use ch32_hal::gpio::{Flex, Level, Output, Pull, Speed};
use ch32_hal::mode::NonBlocking;
use ch32_hal::peripherals::USBD;
use embassy_executor::{Spawner, task};
use core::fmt::Write as _;
use embassy_executor::{task, Spawner};
use embassy_futures::yield_now;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::channel::Channel;
use embassy_time::{Delay, Duration, Instant, Timer};
use embassy_usb::class::cdc_acm::{CdcAcmClass, State};
use embassy_usb::{Builder, UsbDevice};
use embassy_futures::yield_now;
use hal::usbd::{Driver};
use hal::{bind_interrupts};
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::channel::{Channel};
use embassy_time::{Instant, Duration, Delay, Timer};
use embedded_can::{Id, StandardId};
use hal::bind_interrupts;
use hal::usbd::Driver;
use {ch32_hal as hal, panic_halt as _};
use embedded_alloc::LlffHeap as Heap;
use embedded_can::nb::Can as nb_can;
macro_rules! mk_static {
($t:ty,$val:expr) => {{
@@ -33,26 +36,18 @@ macro_rules! mk_static {
}};
}
bind_interrupts!(struct Irqs {
USB_LP_CAN1_RX0 => hal::usbd::InterruptHandler<hal::peripherals::USBD>;
});
use embedded_alloc::LlffHeap as Heap;
use embedded_can::nb::Can as nb_can;
use qingke::riscv::asm::delay;
use log::log;
bind_interrupts!(struct Irqs {
USB_LP_CAN1_RX0 => hal::usbd::InterruptHandler<hal::peripherals::USBD>;
});
#[global_allocator]
static HEAP: Heap = Heap::empty();
static LOG_CH: Channel<CriticalSectionRawMutex, heapless::String<128>, 8> = Channel::new();
#[embassy_executor::main(entry = "qingke_rt::entry")]
async fn main(spawner: Spawner) {
ch32_hal::pac::AFIO.pcfr1().write(|w| w.set_can1_rm(2));
//
unsafe {
static mut HEAP_SPACE: [u8; 4096] = [0; 4096]; // 4 KiB heap, adjust as needed
HEAP.init(HEAP_SPACE.as_ptr() as usize, HEAP_SPACE.len());
@@ -63,8 +58,6 @@ async fn main(spawner: Spawner) {
..Default::default()
});
// Build driver and USB stack using 'static buffers
let driver = Driver::new(p.USBD, Irqs, p.PA12, p.PA11);
@@ -84,83 +77,156 @@ async fn main(spawner: Spawner) {
let mut builder = Builder::new(
driver,
config,
mk_static!([u8;256], [0; 256]),
mk_static!([u8;256], [0; 256]),
mk_static!([u8; 256], [0; 256]),
mk_static!([u8; 256], [0; 256]),
&mut [], // no msos descriptors
mk_static!([u8;64], [0; 64]),
mk_static!([u8; 64], [0; 64]),
);
// Initialize CDC state and create CDC-ACM class
let class = mk_static!(CdcAcmClass<'static, Driver<'static, hal::peripherals::USBD>>,
CdcAcmClass::new(
&mut builder,
mk_static!(State, State::new()),
64
)
let class = mk_static!(
CdcAcmClass<'static, Driver<'static, hal::peripherals::USBD>>,
CdcAcmClass::new(&mut builder, mk_static!(State, State::new()), 64)
);
// Build USB device
let usb = mk_static!(UsbDevice<Driver<USBD>>, builder.build()) ;
let usb = mk_static!(UsbDevice<Driver<USBD>>, builder.build());
// Create GPIO for 555 Q output (PB0)
let q_out = Output::new(p.PB0, Level::Low, Speed::Low);
// Built-in LED on PB2 mirrors Q state
let led = Output::new(p.PB2, Level::Low, Speed::Low);
let mut info = Output::new(p.PB2, Level::Low, Speed::Low);
let info = Output::new(p.PA3, Level::Low, Speed::Low);
// Read configuration switches on PB3..PB7 at startup with floating detection
// PB3: Sensor A/B selector (Low=A, High=B)
// PB4..PB7: address bits (1,2,4,8)
let mut pb3 = Flex::new(p.PB3);
let mut pb4 = Flex::new(p.PB4);
let mut pb5 = Flex::new(p.PB5);
let mut pb6 = Flex::new(p.PB6);
let mut pb7 = Flex::new(p.PB7);
// Validate all config pins; if any is floating, stay in an error loop until fixed
// Try read PB3..PB7
let res_pb3 = detect_stable_pin(&mut pb3).await;
let res_pb4 = detect_stable_pin(&mut pb4).await;
let res_pb5 = detect_stable_pin(&mut pb5).await;
let res_pb6 = detect_stable_pin(&mut pb6).await;
let res_pb7 = detect_stable_pin(&mut pb7).await;
if res_pb3.is_none() || res_pb4.is_none() || res_pb5.is_none() || res_pb6.is_none() || res_pb7.is_none() {
// At least one floating: report and blink code for the first one found.
let mut msg: heapless::String<128> = heapless::String::new();
let code = if res_pb4.is_none() { 1 } else if res_pb5.is_none() { 2 } else if res_pb6.is_none() { 3 } else if res_pb7.is_none() { 4 } else { 5 }; // PB3 -> 5
let which = match code { 1 => "PB4", 2 => "PB5", 3 => "PB6", 4 => "PB7", _ => "PB3 (A/B)" };
let _ = core::fmt::Write::write_fmt(&mut msg, format_args!("Config pin floating detected on {} -> blinking code {}. Fix jumpers.\r\n", which, code));
log(msg);
blink_error(&mut info, code).await;
};
let slot = if res_pb3.unwrap() { SensorSlot::B } else { SensorSlot::A };
let mut addr: u8 = 0;
if res_pb4.unwrap() { addr |= 1; }
if res_pb5.unwrap() { addr |= 2; }
if res_pb6.unwrap() { addr |= 4; }
if res_pb7.unwrap() { addr |= 8; }
// Log startup configuration and derived CAN IDs
let moisture_id = plant_id(MOISTURE_DATA_OFFSET, slot, addr as u16);
let identify_id = plant_id(IDENTIFY_CMD_OFFSET, slot, addr as u16);
{
let mut msg: heapless::String<128> = heapless::String::new();
let slot_chr = match slot { SensorSlot::A => 'a', SensorSlot::B => 'b' };
let _ = core::fmt::Write::write_fmt(&mut msg, format_args!(
"Startup: slot={} addr={} moisture_id=0x{:03X} identity_id=0x{:03X}\r\n",
slot_chr, addr, moisture_id, identify_id
));
log(msg);
}
// Create ADC on ADC1 and use PA1 as analog input (Threshold/Trigger)
let adc = Adc::new(p.ADC1, Default::default());
let ain = p.PA1;
let config = can::can::Config::default();
let can: Can<CAN1, NonBlocking> = Can::new_nb(p.CAN1, p.PB8, p.PB9, CanFifo::Fifo0, CanMode::Normal, 125_000, config).expect("Valid");
let can: Can<CAN1, NonBlocking> = Can::new_nb(
p.CAN1,
p.PB8,
p.PB9,
CanFifo::Fifo0,
CanMode::Normal,
125_000,
config,
)
.expect("Valid");
ch32_hal::pac::AFIO.pcfr1().write(|w| w.set_can1_rm(2));
spawner.spawn(usb_task(usb)).unwrap();
spawner.spawn(usb_writer(class)).unwrap();
// move Q output, LED, ADC and analog input into worker task
spawner.spawn(worker(q_out, led, adc, ain, can)).unwrap();
spawner.spawn(worker(q_out, info, adc, ain, can, StandardId::new(moisture_id).unwrap(), StandardId::new(identify_id).unwrap())).unwrap();
// Prevent main from exiting
core::future::pending::<()>().await;
}
// Helper closure: detect stable pin by comparing readings under Pull::Down and Pull::Up
async fn detect_stable_pin(pin: &mut Flex<'static>) -> Option<bool> {
pin.set_as_input(Pull::Down);
Timer::after_millis(2).await;
let low_read = pin.is_high();
pin.set_as_input(Pull::Up);
Timer::after_millis(2).await;
let high_read = pin.is_high();
if low_read == high_read { Some(high_read) } else { None }
}
async fn blink_error(mut info_led: &mut Output<'static>, code: u8) -> !{
loop {
// code: 1-4 for PB4..PB7, 5 for PB3 (A/B)
for _ in 0..code {
info_led.set_high();
Timer::after_millis(200).await;
info_led.set_low();
Timer::after_millis(200).await;
}
// Pause between sequences
Timer::after_secs(2).await;
}
}
#[task]
async fn worker(
mut q: Output<'static>,
mut led: Output<'static>,
mut info: Output<'static>,
mut adc: Adc<'static, hal::peripherals::ADC1>,
mut ain: hal::peripherals::PA1,
mut can: Can<'static, CAN1, NonBlocking>,
moisture_id: StandardId,
identify_id: StandardId
) {
// 555 emulation state: Q initially Low
let mut q_high = false;
let low_th: u16 = (ADC_MAX as u16) / 3; // ~1/3 Vref
let low_th: u16 = (ADC_MAX as u16) / 3; // ~1/3 Vref
let high_th: u16 = ((ADC_MAX as u32 * 2) / 3) as u16; // ~2/3 Vref
let moisture_address = StandardId::new(plant_id(MOISTURE_DATA_OFFSET, SensorSlot::A, 0)).unwrap();
let identity_address = StandardId::new(plant_id(IDENTIFY_CMD_OFFSET, SensorSlot::A, 0)).unwrap();
let mut filter = CanFilter::new_id_list();
filter
.get(0)
.unwrap()
.set(identity_address.into(), Default::default());
.set(identify_id.into(), Default::default());
can.add_filter(filter);
//can.add_filter(CanFilter::accept_all());
loop {
// Count rising edges of Q in a 100 ms window
let start = Instant::now();
let mut pulses: u32 = 0;
let mut last_q = q_high;
while Instant::now().checked_duration_since(start).unwrap_or(Duration::from_millis(0))
while Instant::now()
.checked_duration_since(start)
.unwrap_or(Duration::from_millis(0))
< Duration::from_millis(1000)
{
// Sample the analog input (Threshold/Trigger on A1)
@@ -204,24 +270,16 @@ async fn worker(
);
log(msg);
let mut moisture = CanFrame::new(moisture_address, &[freq_hz as u8]).unwrap();
match can.transmit(&mut moisture){
let mut moisture = CanFrame::new(moisture_id, &[freq_hz as u8]).unwrap();
match can.transmit(&mut moisture) {
Ok(..) => {
let mut msg: heapless::String<128> = heapless::String::new();
let _ = write!(
&mut msg,
"Send to canbus"
);
let _ = write!(&mut msg, "Send to canbus");
log(msg);
}
Err(err) => {
let mut msg: heapless::String<128> = heapless::String::new();
let _ = write!(
&mut msg,
"err {:?}"
,err
);
let _ = write!(&mut msg, "err {:?}", err);
log(msg);
}
}
@@ -229,35 +287,31 @@ async fn worker(
loop {
yield_now().await;
match can.receive() {
Ok(frame) => {
match frame.id() {
Id::Standard(s_frame) => {
let mut msg: heapless::String<128> = heapless::String::new();
let _ = write!(
&mut msg,
"Received from canbus: {:?} ident is {:?} \r\n",
s_frame.as_raw(),
identity_address.as_raw()
);
log(msg);
if s_frame.as_raw() == identity_address.as_raw() {
for _ in 0..10 {
Timer::after_millis(250).await;
led.toggle();
}
led.set_low();
Ok(frame) => match frame.id() {
Id::Standard(s_frame) => {
let mut msg: heapless::String<128> = heapless::String::new();
let _ = write!(
&mut msg,
"Received from canbus: {:?} ident is {:?} \r\n",
s_frame.as_raw(),
identify_id.as_raw()
);
log(msg);
if s_frame.as_raw() == identify_id.as_raw() {
for _ in 0..10 {
Timer::after_millis(250).await;
info.toggle();
}
info.set_low();
}
Id::Extended(_) => {}
}
}
Id::Extended(_) => {}
},
_ => {
break;
}
}
}
}
}
@@ -275,10 +329,9 @@ async fn usb_task(usb: &'static mut UsbDevice<'static, Driver<'static, hal::peri
#[task]
async fn usb_writer(
class: &'static mut CdcAcmClass<'static, Driver<'static, hal::peripherals::USBD>>
class: &'static mut CdcAcmClass<'static, Driver<'static, hal::peripherals::USBD>>,
) {
loop {
class.wait_connection().await;
printer(class).await;
}

8
Software/MainBoard/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

11
Software/MainBoard/.idea/MainBoard.iml generated Normal file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="EMPTY_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/rust/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/rust/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

8
Software/MainBoard/.idea/modules.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/MainBoard.iml" filepath="$PROJECT_DIR$/.idea/MainBoard.iml" />
</modules>
</component>
</project>

7
Software/MainBoard/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
<mapping directory="$PROJECT_DIR$/../../website/themes/blowfish" vcs="Git" />
</component>
</project>

172
Software/MainBoard/d1.json Normal file
View File

@@ -0,0 +1,172 @@
{
"hardware": {
"board": "V4",
"battery": "Disabled"
},
"network": {
"max_wait": 10000,
"ap_ssid": "PlantCtrl Init",
"ssid": "private",
"password": "wertertzu",
"mqtt_url": "",
"mqtt_user": null,
"mqtt_password": null,
"base_topic": ""
},
"tank": {
"tank_allow_pumping_if_sensor_error": true,
"tank_empty_percent": 5,
"tank_full_percent": 95,
"tank_sensor_enabled": false,
"tank_useable_ml": 50000,
"tank_warn_percent": 40,
"ml_per_pulse": 0
},
"night_lamp": {
"night_lamp_hour_start": 19,
"night_lamp_hour_end": 2,
"night_lamp_only_when_dark": true,
"enabled": true,
"low_soc_cutoff": 30,
"low_soc_restore": 50
},
"plants": [
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_b": false,
"sensor_a": true,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
},
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_b": false,
"sensor_a": true,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
},
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_b": false,
"sensor_a": true,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
},
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_b": false,
"sensor_a": true,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
},
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_b": false,
"sensor_a": true,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
},
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_b": false,
"sensor_a": true,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
},
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_b": false,
"sensor_a": true,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
},
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_b": false,
"sensor_a": true,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
}
],
"timezone": "Europe/Berlin"
}

180
Software/MainBoard/d2.json Normal file
View File

@@ -0,0 +1,180 @@
{
"hardware": {
"board": "V4",
"battery": "Disabled"
},
"network": {
"ap_ssid": "PlantCtrl Init",
"ssid": "private",
"password": "wertertzu",
"mqtt_url": "",
"base_topic": "",
"mqtt_user": null,
"mqtt_password": null,
"max_wait": 10000
},
"tank": {
"tank_sensor_enabled": false,
"tank_allow_pumping_if_sensor_error": true,
"tank_useable_ml": 50000,
"tank_warn_percent": 40,
"tank_empty_percent": 5,
"tank_full_percent": 95,
"ml_per_pulse": 0.0
},
"night_lamp": {
"enabled": true,
"night_lamp_hour_start": 19,
"night_lamp_hour_end": 2,
"night_lamp_only_when_dark": true,
"low_soc_cutoff": 30,
"low_soc_restore": 50
},
"plants": [
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_limit_ml": 5000,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_a": true,
"sensor_b": false,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
},
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_limit_ml": 5000,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_a": true,
"sensor_b": false,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
},
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_limit_ml": 5000,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_a": true,
"sensor_b": false,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
},
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_limit_ml": 5000,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_a": true,
"sensor_b": false,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
},
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_limit_ml": 5000,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_a": true,
"sensor_b": false,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
},
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_limit_ml": 5000,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_a": true,
"sensor_b": false,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
},
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_limit_ml": 5000,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_a": true,
"sensor_b": false,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
},
{
"mode": "Off",
"target_moisture": 40,
"min_moisture": 30,
"pump_time_s": 30,
"pump_limit_ml": 5000,
"pump_cooldown_min": 60,
"pump_hour_start": 9,
"pump_hour_end": 20,
"sensor_a": true,
"sensor_b": false,
"max_consecutive_pump_count": 10,
"moisture_sensor_min_frequency": null,
"moisture_sensor_max_frequency": null,
"min_pump_current_ma": 10,
"max_pump_current_ma": 3000,
"ignore_current_error": true
}
],
"timezone": "Europe/Berlin"
}

View File

@@ -23,6 +23,7 @@ target = "riscv32imac-unknown-none-elf"
CHRONO_TZ_TIMEZONE_FILTER = "UTC|America/New_York|America/Chicago|America/Los_Angeles|Europe/London|Europe/Berlin|Europe/Paris|Asia/Tokyo|Asia/Shanghai|Asia/Kolkata|Australia/Sydney|America/Sao_Paulo|Africa/Johannesburg|Asia/Dubai|Pacific/Auckland"
CARGO_WORKSPACE_DIR = { value = "", relative = true }
ESP_LOG = "info"
PATH = { value = "../../../bin:/usr/bin:/usr/local/bin", force = true, relative = true }

View File

@@ -1,7 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../../.." vcs="Git" />
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
<mapping directory="$PROJECT_DIR$/../website/themes/blowfish" vcs="Git" />
<mapping directory="$PROJECT_DIR$/../../../website/themes/blowfish" vcs="Git" />
</component>
</project>

View File

@@ -37,19 +37,27 @@ partition_table = "partitions.csv"
[dependencies]
# Shared CAN API
# Project/Shared
canapi = { path = "../../Shared/canapi" }
#ESP stuff
esp-bootloader-esp-idf = { version = "0.2.0", features = ["esp32c6"] }
esp-hal = { version = "=1.0.0-rc.0", features = [
"esp32c6",
"log-04",
"unstable",
"rt"
] }
log = "0.4.27"
embassy-net = { version = "0.7.1", default-features = false, features = [
# Platform and ESP-specific runtime/boot/runtime utilities
log = "0.4.28"
esp-bootloader-esp-idf = { version = "0.4.0", features = ["esp32c6", "log-04"] }
esp-hal = { version = "1.0.0", features = ["esp32c6", "log-04"] }
esp-rtos = { version = "0.2.0", features = ["esp32c6", "embassy", "esp-radio"] }
esp-backtrace = { version = "0.18.1", features = ["esp32c6", "panic-handler", "println", "colors", "custom-halt"] }
esp-println = { version = "0.16.1", features = ["esp32c6", "log-04", "auto"] }
esp-storage = { version = "0.8.1", features = ["esp32c6"] }
esp-radio = { version = "0.17.0", features = ["esp32c6", "log-04", "smoltcp", "wifi", "unstable"] }
esp-alloc = { version = "0.9.0", features = ["esp32c6", "internal-heap-stats"] }
# Async runtime (Embassy core)
embassy-executor = { version = "0.9.1", features = ["log", "nightly"] }
embassy-time = { version = "0.5.0", features = ["log"], default-features = false }
embassy-sync = { version = "0.7.2", features = ["log"] }
# Networking and protocol stacks
embassy-net = { version = "0.7.1", features = [
"dhcpv4",
"log",
"medium-ethernet",
@@ -58,36 +66,6 @@ embassy-net = { version = "0.7.1", default-features = false, features = [
"proto-ipv4",
"dns"
] }
embedded-io = "0.6.1"
embedded-io-async = "0.6.1"
esp-alloc = "0.8.0"
esp-backtrace = { version = "0.17.0", features = [
"esp32c6",
"exception-handler",
"panic-handler",
"println",
"colors",
"custom-halt"
] }
esp-println = { version = "0.15.0", features = ["esp32c6", "log-04"] }
# for more networking protocol support see https://crates.io/crates/edge-net
embassy-executor = { version = "0.7.0", features = [
"log",
"task-arena-size-64",
"nightly"
] }
embassy-time = { version = "0.5.0", features = ["log"], default-features = false }
esp-hal-embassy = { version = "0.9.0", features = ["esp32c6", "log-04"] }
esp-storage = { version = "0.7.0", features = ["esp32c6"] }
esp-wifi = { version = "0.15.0", features = [
"builtin-scheduler",
"esp-alloc",
"esp32c6",
"log-04",
"smoltcp",
"wifi",
] }
smoltcp = { version = "0.12.0", default-features = false, features = [
"alloc",
"log",
@@ -103,60 +81,59 @@ smoltcp = { version = "0.12.0", default-features = false, features = [
"socket-tcp",
"socket-udp",
] }
#static_cell = "2.1.1"
embedded-hal = "1.0.0"
embedded-hal-bus = { version = "0.3.0" }
#Hardware additional driver
#bq34z100 = { version = "0.3.0", default-features = false }
onewire = "0.4.0"
#strum = { version = "0.27.0", default-feature = false, features = ["derive"] }
measurements = "0.11.0"
ds323x = "0.6.0"
#json
serde = { version = "1.0.219", features = ["derive", "alloc"], default-features = false }
serde_json = { version = "1.0.143", default-features = false, features = ["alloc"] }
chrono = { version = "0.4.42", default-features = false, features = ["iana-time-zone", "alloc", "serde"] }
chrono-tz = { version = "0.10.4", default-features = false, features = ["filter-by-regex"] }
eeprom24x = "0.7.2"
crc = "3.2.1"
strum_macros = "0.27.0"
unit-enum = "1.4.1"
pca9535 = { version = "2.0.0" }
ina219 = { version = "0.2.0" }
embedded-storage = "=0.3.1"
portable-atomic = "1.11.1"
embassy-sync = { version = "0.7.2", features = ["log"] }
async-trait = "0.1.89"
bq34z100 = { version = "0.4.0", default-features = false }
sntpc = { version = "0.6.1", default-features = false, features = ["log", "embassy-socket", "embassy-socket-ipv6"] }
edge-dhcp = "0.6.0"
edge-nal = "0.5.0"
edge-nal-embassy = "0.6.0"
static_cell = "2.1.1"
edge-http = { version = "0.6.1", features = ["log"] }
littlefs2 = { version = "0.6.1", features = ["c-stubs", "alloc"] }
littlefs2-core = "0.1.1"
bytemuck = { version = "1.23.2", features = ["derive", "min_const_generics", "pod_saturating", "extern_crate_alloc"] }
deranged = "0.5.3"
# Hardware abstraction traits and HAL adapters
embedded-hal = "1.0.0"
embedded-storage = "0.3.1"
embassy-embedded-hal = "0.5.0"
bincode = { version = "2.0.1", default-features = false, features = ["derive"] }
sntpc = { version = "0.6.0", default-features = false, features = ["log", "embassy-socket", "embassy-socket-ipv6"] }
option-lock = { version = "0.3.1", default-features = false }
#stay in sync with mcutie version here!
heapless = { version = "0.7.17", features = ["serde"] }
mcutie = { version = "0.3.0", default-features = false, features = ["log", "homeassistant"] }
nb = "1.1.0"
embedded-can = "0.4.1"
nb = "1.1.0"
# Concrete hardware drivers and sensors/IO expanders
onewire = "0.4.0"
ds323x = "0.7.0"
eeprom24x = "0.7.2"
pca9535 = { version = "2.0.0" }
ina219 = { version = "0.2.0" }
bq34z100 = { version = "0.4.0", default-features = false }
# Storage and filesystem
littlefs2 = { version = "0.6.1", features = ["c-stubs", "alloc"] }
littlefs2-core = "0.1.2"
# Serialization / codecs
serde = { version = "1.0.228", features = ["derive", "alloc"], default-features = false }
serde_json = { version = "1.0.145", default-features = false, features = ["alloc"] }
bincode = { version = "2.0.1", default-features = false, features = ["derive"] }
# Time and time zones
chrono = { version = "0.4.42", default-features = false, features = ["iana-time-zone", "alloc", "serde"] }
chrono-tz = { version = "0.10.4", default-features = false, features = ["filter-by-regex"] }
# Utilities and pure functional code (no hardware I/O)
heapless = { version = "0.7.17", features = ["serde"] } # stay in sync with mcutie version
static_cell = "2.1.1"
portable-atomic = "1.11.1"
crc = "3.3.0"
bytemuck = { version = "1.24.0", features = ["derive", "min_const_generics", "pod_saturating", "extern_crate_alloc"] }
deranged = "0.5.5"
strum_macros = "0.27.2"
unit-enum = "1.4.3"
async-trait = "0.1.89"
option-lock = { version = "0.3.1", default-features = false }
measurements = "0.11.1"
# Project-specific
mcutie = { version = "0.3.0", default-features = false, features = ["log", "homeassistant"] }
[patch.crates-io]
mcutie = { git = 'https://github.com/empirephoenix/mcutie.git' }
#bq34z100 = { path = "../../bq34z100_rust" }
[build-dependencies]
vergen = { version = "8.2.6", features = ["build", "git", "gitcl"] }
vergen = { version = "8.3.2", features = ["build", "git", "gitcl"] }

View File

@@ -1,11 +1,15 @@
#!/usr/bin/env bash
rm ./src/webserver/index.html.gz
rm ./src/webserver/bundle.js.gz
set -e
cd ./src_webpack/
pushd ./src_webpack/
npm install
npx webpack build
cp index.html.gz ../src/webserver/index.html.gz
cp bundle.js.gz ../src/webserver/bundle.js.gz
cd ../
popd
cargo build --release
espflash save-image --bootloader bootloader.bin --partition-table partitions.csv --chip esp32c6 target/riscv32imac-unknown-none-elf/release/plant-ctrl2 image.bin

View File

@@ -1,11 +1,20 @@
#!/usr/bin/env bash
rm ./src/webserver/index.html.gz
rm ./src/webserver/bundle.js.gz
rm ./src_webpack/index.html.gz
rm ./src_webpack/bundle.js.gz
rm ./src_webpack/index.html
rm ./src_webpack/bundle.js
set -e
cd ./src_webpack/
pushd ./src_webpack/
npm install
npx webpack build
cp index.html.gz ../src/webserver/index.html.gz
cp bundle.js.gz ../src/webserver/bundle.js.gz
cd ../
popd
cargo build --release
espflash flash --monitor --bootloader bootloader.bin --chip esp32c6 --baud 921600 --partition-table partitions.csv target/riscv32imac-unknown-none-elf/release/plant-ctrl2

View File

@@ -1,12 +1,16 @@
#!/usr/bin/env bash
rm image.bin
rm ./src/webserver/index.html.gz
rm ./src/webserver/bundle.js.gz
set -e
cd ./src_webpack/
pushd ./src_webpack/
npm install
npx webpack build
cp index.html.gz ../src/webserver/index.html.gz
cp bundle.js.gz ../src/webserver/bundle.js.gz
cd ../
popd
set -e
cargo build --release

View File

@@ -89,7 +89,7 @@ pub enum BatteryBoardVersion {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Default)]
pub enum BoardVersion {
#[default]
INITIAL,
Initial,
V3,
V4,
}
@@ -115,8 +115,8 @@ pub struct PlantControllerConfig {
#[serde(default)]
pub struct PlantConfig {
pub mode: PlantWateringMode,
pub target_moisture: f32,
pub min_moisture: f32,
pub target_moisture: u8,
pub min_moisture: u8,
pub pump_time_s: u16,
pub pump_limit_ml: u16,
pub pump_cooldown_min: u16,
@@ -125,8 +125,8 @@ pub struct PlantConfig {
pub sensor_a: bool,
pub sensor_b: bool,
pub max_consecutive_pump_count: u8,
pub moisture_sensor_min_frequency: Option<f32>, // Optional min frequency
pub moisture_sensor_max_frequency: Option<f32>, // Optional max frequency
pub moisture_sensor_min_frequency: Option<u16>, // Optional min frequency
pub moisture_sensor_max_frequency: Option<u16>, // Optional max frequency
pub min_pump_current_ma: u16,
pub max_pump_current_ma: u16,
pub ignore_current_error: bool,
@@ -135,9 +135,9 @@ pub struct PlantConfig {
impl Default for PlantConfig {
fn default() -> Self {
Self {
mode: PlantWateringMode::OFF,
target_moisture: 40.,
min_moisture: 30.,
mode: PlantWateringMode::Off,
target_moisture: 40,
min_moisture: 30,
pump_time_s: 30,
pump_limit_ml: 5000,
pump_cooldown_min: 60,

View File

@@ -10,7 +10,7 @@ use embedded_storage::nor_flash::NorFlashErrorKind;
use esp_hal::i2c::master::ConfigError;
use esp_hal::pcnt::unit::{InvalidHighLimit, InvalidLowLimit};
use esp_hal::twai::EspTwaiError;
use esp_wifi::wifi::WifiError;
use esp_radio::wifi::WifiError;
use ina219::errors::{BusVoltageReadError, ShuntVoltageReadError};
use littlefs2_core::PathError;
use onewire::Error;
@@ -78,28 +78,28 @@ impl fmt::Display for FatError {
FatError::SpawnError { error } => {
write!(f, "SpawnError {:?}", error.to_string())
}
FatError::OneWireError { error } => write!(f, "OneWireError {:?}", error),
FatError::String { error } => write!(f, "{}", error),
FatError::LittleFSError { error } => write!(f, "LittleFSError {:?}", error),
FatError::PathError { error } => write!(f, "PathError {:?}", error),
FatError::TryLockError { error } => write!(f, "TryLockError {:?}", error),
FatError::WifiError { error } => write!(f, "WifiError {:?}", error),
FatError::SerdeError { error } => write!(f, "SerdeError {:?}", error),
FatError::PreconditionFailed { error } => write!(f, "PreconditionFailed {:?}", error),
FatError::OneWireError { error } => write!(f, "OneWireError {error:?}"),
FatError::String { error } => write!(f, "{error}"),
FatError::LittleFSError { error } => write!(f, "LittleFSError {error:?}"),
FatError::PathError { error } => write!(f, "PathError {error:?}"),
FatError::TryLockError { error } => write!(f, "TryLockError {error:?}"),
FatError::WifiError { error } => write!(f, "WifiError {error:?}"),
FatError::SerdeError { error } => write!(f, "SerdeError {error:?}"),
FatError::PreconditionFailed { error } => write!(f, "PreconditionFailed {error:?}"),
FatError::PartitionError { error } => {
write!(f, "PartitionError {:?}", error)
write!(f, "PartitionError {error:?}")
}
FatError::NoBatteryMonitor => {
write!(f, "No Battery Monitor")
}
FatError::I2CConfigError { error } => write!(f, "I2CConfigError {:?}", error),
FatError::DS323 { error } => write!(f, "DS323 {:?}", error),
FatError::Eeprom24x { error } => write!(f, "Eeprom24x {:?}", error),
FatError::ExpanderError { error } => write!(f, "ExpanderError {:?}", error),
FatError::I2CConfigError { error } => write!(f, "I2CConfigError {error:?}"),
FatError::DS323 { error } => write!(f, "DS323 {error:?}"),
FatError::Eeprom24x { error } => write!(f, "Eeprom24x {error:?}"),
FatError::ExpanderError { error } => write!(f, "ExpanderError {error:?}"),
FatError::CanBusError { error } => {
write!(f, "CanBusError {:?}", error)
write!(f, "CanBusError {error:?}")
}
FatError::SNTPError { error } => write!(f, "SNTPError {:?}", error),
FatError::SNTPError { error } => write!(f, "SNTPError {error:?}"),
}
}
}
@@ -197,7 +197,7 @@ impl From<Utf8Error> for FatError {
impl<E: core::fmt::Debug> From<edge_http::io::Error<E>> for FatError {
fn from(value: edge_http::io::Error<E>) -> Self {
FatError::String {
error: format!("{:?}", value),
error: format!("{value:?}"),
}
}
}
@@ -205,7 +205,7 @@ impl<E: core::fmt::Debug> From<edge_http::io::Error<E>> for FatError {
impl<E: core::fmt::Debug> From<ds323x::Error<E>> for FatError {
fn from(value: ds323x::Error<E>) -> Self {
FatError::DS323 {
error: format!("{:?}", value),
error: format!("{value:?}"),
}
}
}
@@ -213,7 +213,7 @@ impl<E: core::fmt::Debug> From<ds323x::Error<E>> for FatError {
impl<E: core::fmt::Debug> From<eeprom24x::Error<E>> for FatError {
fn from(value: eeprom24x::Error<E>) -> Self {
FatError::Eeprom24x {
error: format!("{:?}", value),
error: format!("{value:?}"),
}
}
}
@@ -221,7 +221,7 @@ impl<E: core::fmt::Debug> From<eeprom24x::Error<E>> for FatError {
impl<E: core::fmt::Debug> From<ExpanderError<I2cDeviceError<E>>> for FatError {
fn from(value: ExpanderError<I2cDeviceError<E>>) -> Self {
FatError::ExpanderError {
error: format!("{:?}", value),
error: format!("{value:?}"),
}
}
}
@@ -229,7 +229,7 @@ impl<E: core::fmt::Debug> From<ExpanderError<I2cDeviceError<E>>> for FatError {
impl From<bincode::error::DecodeError> for FatError {
fn from(value: bincode::error::DecodeError) -> Self {
FatError::Eeprom24x {
error: format!("{:?}", value),
error: format!("{value:?}"),
}
}
}
@@ -237,7 +237,7 @@ impl From<bincode::error::DecodeError> for FatError {
impl From<bincode::error::EncodeError> for FatError {
fn from(value: bincode::error::EncodeError) -> Self {
FatError::Eeprom24x {
error: format!("{:?}", value),
error: format!("{value:?}"),
}
}
}
@@ -251,7 +251,7 @@ impl From<ConfigError> for FatError {
impl<E: core::fmt::Debug> From<I2cDeviceError<E>> for FatError {
fn from(value: I2cDeviceError<E>) -> Self {
FatError::String {
error: format!("{:?}", value),
error: format!("{value:?}"),
}
}
}
@@ -259,14 +259,14 @@ impl<E: core::fmt::Debug> From<I2cDeviceError<E>> for FatError {
impl<E: core::fmt::Debug> From<BusVoltageReadError<I2cDeviceError<E>>> for FatError {
fn from(value: BusVoltageReadError<I2cDeviceError<E>>) -> Self {
FatError::String {
error: format!("{:?}", value),
error: format!("{value:?}"),
}
}
}
impl<E: core::fmt::Debug> From<ShuntVoltageReadError<I2cDeviceError<E>>> for FatError {
fn from(value: ShuntVoltageReadError<I2cDeviceError<E>>) -> Self {
FatError::String {
error: format!("{:?}", value),
error: format!("{value:?}"),
}
}
}
@@ -280,14 +280,14 @@ impl From<Infallible> for FatError {
impl From<InvalidLowLimit> for FatError {
fn from(value: InvalidLowLimit) -> Self {
FatError::String {
error: format!("{:?}", value),
error: format!("{value:?}"),
}
}
}
impl From<InvalidHighLimit> for FatError {
fn from(value: InvalidHighLimit) -> Self {
FatError::String {
error: format!("{:?}", value),
error: format!("{value:?}"),
}
}
}

View File

@@ -105,7 +105,7 @@ impl BatteryInteraction for BQ34Z100G1 {
.state_of_charge()
.map(|v| v as f32)
.map_err(|e| FatError::String {
error: alloc::format!("{:?}", e),
error: alloc::format!("{e:?}"),
})
}
@@ -113,7 +113,7 @@ impl BatteryInteraction for BQ34Z100G1 {
self.battery_driver
.remaining_capacity()
.map_err(|e| FatError::String {
error: alloc::format!("{:?}", e),
error: alloc::format!("{e:?}"),
})
}
@@ -121,7 +121,7 @@ impl BatteryInteraction for BQ34Z100G1 {
self.battery_driver
.full_charge_capacity()
.map_err(|e| FatError::String {
error: alloc::format!("{:?}", e),
error: alloc::format!("{e:?}"),
})
}
@@ -129,13 +129,13 @@ impl BatteryInteraction for BQ34Z100G1 {
self.battery_driver
.design_capacity()
.map_err(|e| FatError::String {
error: alloc::format!("{:?}", e),
error: alloc::format!("{e:?}"),
})
}
async fn voltage_milli_volt(&mut self) -> FatResult<u16> {
self.battery_driver.voltage().map_err(|e| FatError::String {
error: alloc::format!("{:?}", e),
error: alloc::format!("{e:?}"),
})
}
@@ -143,7 +143,7 @@ impl BatteryInteraction for BQ34Z100G1 {
self.battery_driver
.average_current()
.map_err(|e| FatError::String {
error: alloc::format!("{:?}", e),
error: alloc::format!("{e:?}"),
})
}
@@ -151,7 +151,7 @@ impl BatteryInteraction for BQ34Z100G1 {
self.battery_driver
.cycle_count()
.map_err(|e| FatError::String {
error: alloc::format!("{:?}", e),
error: alloc::format!("{e:?}"),
})
}
@@ -159,7 +159,7 @@ impl BatteryInteraction for BQ34Z100G1 {
self.battery_driver
.state_of_health()
.map_err(|e| FatError::String {
error: alloc::format!("{:?}", e),
error: alloc::format!("{e:?}"),
})
}
@@ -167,7 +167,7 @@ impl BatteryInteraction for BQ34Z100G1 {
self.battery_driver
.temperature()
.map_err(|e| FatError::String {
error: alloc::format!("{:?}", e),
error: alloc::format!("{e:?}"),
})
}
@@ -190,16 +190,16 @@ pub fn print_battery_bq34z100(
) -> FatResult<()> {
log::info!("Try communicating with battery");
let fwversion = battery_driver.fw_version().unwrap_or_else(|e| {
log::info!("Firmware {:?}", e);
log::info!("Firmware {e:?}");
0
});
log::info!("fw version is {}", fwversion);
log::info!("fw version is {fwversion}");
let design_capacity = battery_driver.design_capacity().unwrap_or_else(|e| {
log::info!("Design capacity {:?}", e);
log::info!("Design capacity {e:?}");
0
});
log::info!("Design Capacity {}", design_capacity);
log::info!("Design Capacity {design_capacity}");
if design_capacity == 1000 {
log::info!("Still stock configuring battery, readouts are likely to be wrong!");
}
@@ -219,39 +219,39 @@ pub fn print_battery_bq34z100(
cf: false,
ocv_taken: false,
});
log::info!("Flags {:?}", flags);
log::info!("Flags {flags:?}");
let chem_id = battery_driver.chem_id().unwrap_or_else(|e| {
log::info!("Chemid {:?}", e);
log::info!("Chemid {e:?}");
0
});
let bat_temp = battery_driver.internal_temperature().unwrap_or_else(|e| {
log::info!("Bat Temp {:?}", e);
log::info!("Bat Temp {e:?}");
0
});
let temp_c = Temperature::from_kelvin(bat_temp as f64 / 10_f64).as_celsius();
let voltage = battery_driver.voltage().unwrap_or_else(|e| {
log::info!("Bat volt {:?}", e);
log::info!("Bat volt {e:?}");
0
});
let current = battery_driver.current().unwrap_or_else(|e| {
log::info!("Bat current {:?}", e);
log::info!("Bat current {e:?}");
0
});
let state = battery_driver.state_of_charge().unwrap_or_else(|e| {
log::info!("Bat Soc {:?}", e);
log::info!("Bat Soc {e:?}");
0
});
let charge_voltage = battery_driver.charge_voltage().unwrap_or_else(|e| {
log::info!("Bat Charge Volt {:?}", e);
log::info!("Bat Charge Volt {e:?}");
0
});
let charge_current = battery_driver.charge_current().unwrap_or_else(|e| {
log::info!("Bat Charge Current {:?}", e);
log::info!("Bat Charge Current {e:?}");
0
});
log::info!("ChemId: {} Current voltage {} and current {} with charge {}% and temp {} CVolt: {} CCur {}", chem_id, voltage, current, state, temp_c, charge_voltage, charge_current);
log::info!("ChemId: {chem_id} Current voltage {voltage} and current {current} with charge {state}% and temp {temp_c} CVolt: {charge_voltage} CCur {charge_current}");
let _ = battery_driver.unsealed();
let _ = battery_driver.it_enable();
Ok(())

View File

@@ -7,6 +7,7 @@ use serde::Serialize;
use crate::fat_error::{ContextExt, FatError, FatResult};
use crate::hal::little_fs2storage_adapter::LittleFs2Filesystem;
use crate::hal::shared_flash::MutexFlashStorage;
use alloc::string::ToString;
use alloc::sync::Arc;
use alloc::{format, string::String, vec, vec::Vec};
@@ -22,8 +23,8 @@ use embassy_sync::once_lock::OnceLock;
use embassy_time::{Duration, Timer, WithTimeout};
use embedded_storage::nor_flash::{check_erase, NorFlash, ReadNorFlash};
use esp_bootloader_esp_idf::ota::OtaImageState::Valid;
use esp_bootloader_esp_idf::ota::{Ota, OtaImageState, Slot};
use esp_bootloader_esp_idf::partitions::FlashRegion;
use esp_bootloader_esp_idf::ota::{Ota, OtaImageState};
use esp_bootloader_esp_idf::partitions::{AppPartitionSubType, FlashRegion};
use esp_hal::gpio::{Input, RtcPinWithResistors};
use esp_hal::rng::Rng;
use esp_hal::rtc_cntl::{
@@ -32,10 +33,9 @@ use esp_hal::rtc_cntl::{
};
use esp_hal::system::software_reset;
use esp_println::println;
use esp_storage::FlashStorage;
use esp_wifi::wifi::{
AccessPointConfiguration, AccessPointInfo, AuthMethod, ClientConfiguration, Configuration,
ScanConfig, ScanTypeConfig, WifiController, WifiDevice, WifiState,
use esp_radio::wifi::{
AccessPointConfig, AccessPointInfo, AuthMethod, ClientConfig, ModeConfig, ScanConfig,
ScanTypeConfig, WifiController, WifiDevice, WifiStaState,
};
use littlefs2::fs::Filesystem;
use littlefs2_core::{FileType, PathBuf, SeekFrom};
@@ -49,13 +49,13 @@ use smoltcp::socket::udp::PacketMetadata;
use smoltcp::wire::DnsQueryType;
use sntpc::{get_time, NtpContext, NtpTimestampGenerator};
#[esp_hal::ram(rtc_fast, persistent)]
#[esp_hal::ram(unstable(rtc_fast), unstable(persistent))]
static mut LAST_WATERING_TIMESTAMP: [i64; PLANT_COUNT] = [0; PLANT_COUNT];
#[esp_hal::ram(rtc_fast, persistent)]
#[esp_hal::ram(unstable(rtc_fast), unstable(persistent))]
static mut CONSECUTIVE_WATERING_PLANT: [u32; PLANT_COUNT] = [0; PLANT_COUNT];
#[esp_hal::ram(rtc_fast, persistent)]
#[esp_hal::ram(unstable(rtc_fast), unstable(persistent))]
static mut LOW_VOLTAGE_DETECTED: i8 = 0;
#[esp_hal::ram(rtc_fast, persistent)]
#[esp_hal::ram(unstable(rtc_fast), unstable(persistent))]
static mut RESTART_TO_CONF: i8 = 0;
const CONFIG_FILE: &str = "config.json";
@@ -127,9 +127,9 @@ pub struct Esp<'a> {
// RTC-capable GPIO used as external wake source (store the raw peripheral)
pub wake_gpio1: esp_hal::peripherals::GPIO1<'static>,
pub ota: Ota<'static, FlashStorage>,
pub ota_target: &'static mut FlashRegion<'static, FlashStorage>,
pub current: Slot,
pub ota: Ota<'static, MutexFlashStorage>,
pub ota_target: &'static mut FlashRegion<'static, MutexFlashStorage>,
pub current: AppPartitionSubType,
pub slot0_state: OtaImageState,
pub slot1_state: OtaImageState,
}
@@ -146,7 +146,7 @@ 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));
let x = STATIC_CELL.uninit().write($val);
x
}};
}
@@ -155,7 +155,7 @@ impl Esp<'_> {
pub(crate) async fn delete_file(&self, filename: String) -> FatResult<()> {
let file = PathBuf::try_from(filename.as_str())?;
let access = self.fs.lock().await;
access.remove(&*file)?;
access.remove(&file)?;
Ok(())
}
pub(crate) async fn write_file(
@@ -168,7 +168,7 @@ impl Esp<'_> {
let access = self.fs.lock().await;
access.open_file_with_options_and_then(
|options| options.read(true).write(true).create(true),
&*file,
&file,
|file| {
file.seek(SeekFrom::Start(offset))?;
file.write(buf)?;
@@ -181,7 +181,7 @@ impl Esp<'_> {
pub async fn get_size(&mut self, filename: String) -> FatResult<usize> {
let file = PathBuf::try_from(filename.as_str())?;
let access = self.fs.lock().await;
let data = access.metadata(&*file)?;
let data = access.metadata(&file)?;
Ok(data.len())
}
pub(crate) async fn get_file(
@@ -198,7 +198,7 @@ impl Esp<'_> {
let offset = chunk * buf.len() as u32;
access.open_file_with_options_and_then(
|options| options.read(true),
&*file,
&file,
|file| {
let length = file.len()? as u32;
if length == 0 {
@@ -226,7 +226,7 @@ impl Esp<'_> {
self.ota_target.write(offset, buf)?;
self.ota_target.read(offset, read_back)?;
if buf != read_back {
info!("Expected {:?} but got {:?}", buf, read_back);
info!("Expected {buf:?} but got {read_back:?}");
bail!(
"Flash error, read back does not match write buffer at offset {:x}",
offset
@@ -236,21 +236,24 @@ impl Esp<'_> {
}
pub(crate) async fn finalize_ota(&mut self) -> Result<(), FatError> {
let current = self.ota.current_slot()?;
if self.ota.current_ota_state()? != OtaImageState::Valid {
info!(
"Validating current slot {:?} as it was able to ota",
current
);
let current = self.ota.current_app_partition()?;
if self.ota.current_ota_state()? != Valid {
info!("Validating current slot {current:?} as it was able to ota");
self.ota.set_current_ota_state(Valid)?;
}
self.ota.set_current_slot(current.next())?;
let next = match current {
AppPartitionSubType::Ota0 => AppPartitionSubType::Ota1,
AppPartitionSubType::Ota1 => AppPartitionSubType::Ota0,
_ => {
bail!("Invalid current slot {current:?} for ota");
}
};
self.ota.set_current_app_partition(next)?;
info!("switched slot");
self.ota.set_current_ota_state(OtaImageState::New)?;
info!("switched state for new partition");
let state_new = self.ota.current_ota_state()?;
info!("state on new partition now {:?}", state_new);
info!("state on new partition now {state_new:?}");
//determine nextslot crc
self.set_restart_to_conf(true);
@@ -290,7 +293,7 @@ impl Esp<'_> {
if ntp_addrs.is_empty() {
bail!("Failed to resolve DNS");
}
info!("NTP server: {:?}", ntp_addrs);
info!("NTP server: {ntp_addrs:?}");
let mut counter = 0;
loop {
@@ -302,12 +305,12 @@ impl Esp<'_> {
match timeout {
Ok(result) => {
let time = result?;
info!("Time: {:?}", time);
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);
warn!("sntp timeout, retry: {err:?}");
counter += 1;
if counter > 10 {
bail!("Failed to get time from NTP server");
@@ -322,16 +325,10 @@ impl Esp<'_> {
info!("start wifi scan");
let mut lock = self.controller.try_lock()?;
info!("start wifi scan lock");
let scan_config = ScanConfig {
ssid: None,
bssid: None,
channel: None,
show_hidden: false,
scan_type: ScanTypeConfig::Active {
min: Default::default(),
max: Default::default(),
},
};
let scan_config = ScanConfig::default().with_scan_type(ScanTypeConfig::Active {
min: Default::default(),
max: Default::default(),
});
let rv = lock.scan_with_config_async(scan_config).await?;
info!("end wifi scan lock");
Ok(rv)
@@ -381,14 +378,12 @@ impl Esp<'_> {
}
}
pub(crate) async fn wifi_ap(&mut self) -> FatResult<Stack<'static>> {
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 spawner = Spawner::for_current_executor().await;
let device = self.interface_ap.take().unwrap();
let gw_ip_addr_str = "192.168.71.1";
let gw_ip_addr = Ipv4Addr::from_str(gw_ip_addr_str).expect("failed to parse gateway ip");
@@ -411,22 +406,16 @@ impl Esp<'_> {
);
let stack = mk_static!(Stack, stack);
let client_config = Configuration::AccessPoint(AccessPointConfiguration {
ssid: ssid.clone(),
..Default::default()
});
self.controller
.lock()
.await
.set_configuration(&client_config)?;
let client_config =
ModeConfig::AccessPoint(AccessPointConfig::default().with_ssid(ssid.clone()));
self.controller.lock().await.set_config(&client_config)?;
println!("start new");
self.controller.lock().await.start()?;
println!("start net task");
spawner.spawn(net_task(runner)).ok();
println!("run dhcp");
spawner.spawn(run_dhcp(stack.clone(), gw_ip_addr_str)).ok();
spawner.spawn(run_dhcp(*stack, gw_ip_addr_str)).ok();
loop {
if stack.is_link_up() {
@@ -442,14 +431,15 @@ impl Esp<'_> {
.config_v4()
.inspect(|c| println!("ipv4 config: {c:?}"));
Ok(stack.clone())
Ok(*stack)
}
pub(crate) async fn wifi(
&mut self,
network_config: &NetworkConfig,
spawner: Spawner,
) -> FatResult<Stack<'static>> {
esp_wifi::wifi_set_log_verbose();
esp_radio::wifi_set_log_verbose();
let ssid = network_config.ssid.clone();
match &ssid {
Some(ssid) => {
@@ -469,8 +459,6 @@ impl Esp<'_> {
};
let max_wait = network_config.max_wait;
let spawner = Spawner::for_current_executor().await;
let device = self.interface_sta.take().unwrap();
let config = embassy_net::Config::dhcpv4(DhcpConfig::default());
@@ -485,17 +473,15 @@ impl Esp<'_> {
);
let stack = mk_static!(Stack, stack);
let client_config = Configuration::Client(ClientConfiguration {
ssid,
bssid: None,
auth_method: AuthMethod::WPA2Personal, //FIXME read from config, fill via scan
password,
channel: None,
});
let client_config = ClientConfig::default()
.with_ssid(ssid)
.with_auth_method(AuthMethod::Wpa2Personal)
.with_password(password);
self.controller
.lock()
.await
.set_configuration(&client_config)?;
.set_config(&ModeConfig::Client(client_config))?;
spawner.spawn(net_task(runner)).ok();
self.controller.lock().await.start_async().await?;
@@ -504,13 +490,10 @@ impl Esp<'_> {
guard.current_time_us()
} + max_wait as u64 * 1000;
loop {
let state = esp_wifi::wifi::sta_state();
match state {
WifiState::StaStarted => {
self.controller.lock().await.connect()?;
break;
}
_ => {}
let state = esp_radio::wifi::sta_state();
if state == WifiStaState::Started {
self.controller.lock().await.connect()?;
break;
}
if {
let guard = TIME_ACCESS.get().await.lock().await;
@@ -526,12 +509,9 @@ impl Esp<'_> {
guard.current_time_us()
} + max_wait as u64 * 1000;
loop {
let state = esp_wifi::wifi::sta_state();
match state {
WifiState::StaConnected => {
break;
}
_ => {}
let state = esp_radio::wifi::sta_state();
if state == WifiStaState::Connected {
break;
}
if {
let guard = TIME_ACCESS.get().await.lock().await;
@@ -572,7 +552,7 @@ impl Esp<'_> {
}
info!("Connected WIFI, dhcp: {:?}", stack.config_v4());
Ok(stack.clone())
Ok(*stack)
}
pub fn deep_sleep(
@@ -611,12 +591,12 @@ impl Esp<'_> {
}
let data = self.fs.lock().await.read::<4096>(&cfg)?;
let config: PlantControllerConfig = serde_json::from_slice(&data)?;
return Ok(config);
Ok(config)
}
pub(crate) async fn save_config(&mut self, config: Vec<u8>) -> FatResult<()> {
let filesystem = self.fs.lock().await;
let cfg = PathBuf::try_from(CONFIG_FILE)?;
filesystem.write(&cfg, &*config)?;
filesystem.write(&cfg, &config)?;
Ok(())
}
pub(crate) async fn list_files(&self) -> FatResult<FileList> {
@@ -690,19 +670,15 @@ impl Esp<'_> {
"",
)
.await;
for i in 0..PLANT_COUNT {
log::info!(
"LAST_WATERING_TIMESTAMP[{}] = UTC {}",
i,
LAST_WATERING_TIMESTAMP[i]
);
// is executed before main, no other code will alter these values during printing
#[allow(static_mut_refs)]
for (i, time) in LAST_WATERING_TIMESTAMP.iter().enumerate() {
log::info!("LAST_WATERING_TIMESTAMP[{i}] = UTC {time}");
}
for i in 0..PLANT_COUNT {
log::info!(
"CONSECUTIVE_WATERING_PLANT[{}] = {}",
i,
CONSECUTIVE_WATERING_PLANT[i]
);
// is executed before main, no other code will alter these values during printing
#[allow(static_mut_refs)]
for (i, item) in CONSECUTIVE_WATERING_PLANT.iter().enumerate() {
log::info!("CONSECUTIVE_WATERING_PLANT[{i}] = {item}");
}
}
}
@@ -712,6 +688,7 @@ impl Esp<'_> {
&mut self,
network_config: &'static NetworkConfig,
stack: Stack<'static>,
spawner: Spawner,
) -> FatResult<()> {
let base_topic = network_config
.base_topic
@@ -734,9 +711,9 @@ impl Esp<'_> {
bail!("Mqtt url was empty")
}
let last_will_topic = format!("{}/state", base_topic);
let round_trip_topic = format!("{}/internal/roundtrip", base_topic);
let stay_alive_topic = format!("{}/stay_alive", base_topic);
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);
@@ -764,7 +741,6 @@ impl Esp<'_> {
let keep_alive = Duration::from_secs(60 * 60 * 2).as_secs() as u16;
let (receiver, task) = builder.build(keep_alive);
let spawner = Spawner::for_current_executor().await;
spawner.spawn(mqtt_incoming_task(
receiver,
round_trip_topic.clone(),
@@ -879,8 +855,7 @@ impl Esp<'_> {
Ok(()) => {}
Err(err) => {
info!(
"Error during mqtt send on topic {} with message {:#?} error is {:?}",
subtopic, message, err
"Error during mqtt send on topic {subtopic} with message {message:#?} error is {err:?}"
);
}
};
@@ -932,7 +907,7 @@ async fn mqtt_incoming_task(
LOG_ACCESS
.lock()
.await
.log(LogMessage::UnknownTopic, 0, 0, "", &*topic)
.log(LogMessage::UnknownTopic, 0, 0, "", &topic)
.await;
}
}

View File

@@ -121,7 +121,6 @@ impl<'a> BoardInteraction<'a> for Initial<'a> {
bail!("Please configure board revision")
}
async fn general_fault(&mut self, enable: bool) {
self.general_fault.set_level(enable.into());
}

View File

@@ -1,6 +1,6 @@
use crate::hal::shared_flash::MutexFlashStorage;
use embedded_storage::nor_flash::{check_erase, NorFlash, ReadNorFlash};
use esp_bootloader_esp_idf::partitions::FlashRegion;
use esp_storage::FlashStorage;
use littlefs2::consts::U4096 as lfsCache;
use littlefs2::consts::U512 as lfsLookahead;
use littlefs2::driver::Storage as lfs2Storage;
@@ -9,7 +9,7 @@ use littlefs2::io::Result as lfs2Result;
use log::error;
pub struct LittleFs2Filesystem {
pub(crate) storage: &'static mut FlashRegion<'static, FlashStorage>,
pub(crate) storage: &'static mut FlashRegion<'static, MutexFlashStorage>,
}
impl lfs2Storage for LittleFs2Filesystem {
@@ -24,7 +24,7 @@ impl lfs2Storage for LittleFs2Filesystem {
fn read(&mut self, off: usize, buf: &mut [u8]) -> lfs2Result<usize> {
let read_size: usize = Self::READ_SIZE;
if off % read_size != 0 {
error!("Littlefs2Filesystem read error: offset not aligned to read size offset: {} read_size: {}", off, read_size);
error!("Littlefs2Filesystem read error: offset not aligned to read size offset: {off} read_size: {read_size}");
return Err(lfs2Error::IO);
}
if buf.len() % read_size != 0 {
@@ -34,7 +34,7 @@ impl lfs2Storage for LittleFs2Filesystem {
match self.storage.read(off as u32, buf) {
Ok(..) => Ok(buf.len()),
Err(err) => {
error!("Littlefs2Filesystem read error: {:?}", err);
error!("Littlefs2Filesystem read error: {err:?}");
Err(lfs2Error::IO)
}
}
@@ -43,7 +43,7 @@ impl lfs2Storage for LittleFs2Filesystem {
fn write(&mut self, off: usize, data: &[u8]) -> lfs2Result<usize> {
let write_size: usize = Self::WRITE_SIZE;
if off % write_size != 0 {
error!("Littlefs2Filesystem write error: offset not aligned to write size offset: {} write_size: {}", off, write_size);
error!("Littlefs2Filesystem write error: offset not aligned to write size offset: {off} write_size: {write_size}");
return Err(lfs2Error::IO);
}
if data.len() % write_size != 0 {
@@ -53,7 +53,7 @@ impl lfs2Storage for LittleFs2Filesystem {
match self.storage.write(off as u32, data) {
Ok(..) => Ok(data.len()),
Err(err) => {
error!("Littlefs2Filesystem write error: {:?}", err);
error!("Littlefs2Filesystem write error: {err:?}");
Err(lfs2Error::IO)
}
}
@@ -62,25 +62,25 @@ impl lfs2Storage for LittleFs2Filesystem {
fn erase(&mut self, off: usize, len: usize) -> lfs2Result<usize> {
let block_size: usize = Self::BLOCK_SIZE;
if off % block_size != 0 {
error!("Littlefs2Filesystem erase error: offset not aligned to block size offset: {} block_size: {}", off, block_size);
error!("Littlefs2Filesystem erase error: offset not aligned to block size offset: {off} block_size: {block_size}");
return lfs2Result::Err(lfs2Error::IO);
}
if len % block_size != 0 {
error!("Littlefs2Filesystem erase error: length not aligned to block size length: {} block_size: {}", len, block_size);
error!("Littlefs2Filesystem erase error: length not aligned to block size length: {len} block_size: {block_size}");
return lfs2Result::Err(lfs2Error::IO);
}
match check_erase(self.storage, off as u32, (off+len) as u32) {
match check_erase(self.storage, off as u32, (off + len) as u32) {
Ok(_) => {}
Err(err) => {
error!("Littlefs2Filesystem check erase error: {:?}", err);
error!("Littlefs2Filesystem check erase error: {err:?}");
return lfs2Result::Err(lfs2Error::IO);
}
}
match self.storage.erase(off as u32, (off + len) as u32) {
Ok(..) => lfs2Result::Ok(len),
Err(err) => {
error!("Littlefs2Filesystem erase error: {:?}", err);
error!("Littlefs2Filesystem erase error: {err:?}");
lfs2Result::Err(lfs2Error::IO)
}
}

View File

@@ -4,11 +4,13 @@ pub mod esp;
mod initial_hal;
mod little_fs2storage_adapter;
pub(crate) mod rtc;
mod shared_flash;
mod v3_hal;
mod v3_shift_register;
mod v4_hal;
pub(crate) mod v4_sensor;
mod water;
use crate::alloc::string::ToString;
use crate::hal::rtc::{DS3231Module, RTCModuleInteraction};
use esp_hal::peripherals::Peripherals;
@@ -27,14 +29,8 @@ use esp_hal::peripherals::GPIO2;
use esp_hal::peripherals::GPIO21;
use esp_hal::peripherals::GPIO22;
use esp_hal::peripherals::GPIO23;
use esp_hal::peripherals::GPIO24;
use esp_hal::peripherals::GPIO25;
use esp_hal::peripherals::GPIO26;
use esp_hal::peripherals::GPIO27;
use esp_hal::peripherals::GPIO28;
use esp_hal::peripherals::GPIO29;
use esp_hal::peripherals::GPIO3;
use esp_hal::peripherals::GPIO30;
use esp_hal::peripherals::GPIO4;
use esp_hal::peripherals::GPIO5;
use esp_hal::peripherals::GPIO6;
@@ -58,9 +54,9 @@ use alloc::sync::Arc;
use async_trait::async_trait;
use bincode::{Decode, Encode};
use bq34z100::Bq34z100g1Driver;
use canapi::SensorSlot;
use chrono::{DateTime, FixedOffset, Utc};
use core::cell::RefCell;
use canapi::SensorSlot;
use ds323x::ic::DS3231;
use ds323x::interface::I2cInterface;
use ds323x::{DateTimeAccess, Ds323x};
@@ -85,13 +81,13 @@ use crate::hal::water::TankSensor;
use crate::log::LOG_ACCESS;
use embassy_sync::mutex::Mutex;
use embassy_sync::once_lock::OnceLock;
use embedded_storage::nor_flash::ReadNorFlash;
use embedded_storage::ReadStorage;
use esp_alloc as _;
use esp_backtrace as _;
use esp_bootloader_esp_idf::ota::{Ota, OtaImageState};
use esp_bootloader_esp_idf::ota::{Slot as ota_slot, Slot};
use esp_hal::delay::Delay;
use esp_hal::i2c::master::{BusTimeout, Config, I2c};
use esp_hal::interrupt::software::SoftwareInterruptControl;
use esp_hal::pcnt::unit::Unit;
use esp_hal::pcnt::Pcnt;
use esp_hal::rng::Rng;
@@ -100,14 +96,14 @@ use esp_hal::system::reset_reason;
use esp_hal::time::Rate;
use esp_hal::timer::timg::TimerGroup;
use esp_hal::Blocking;
use esp_radio::{init, Controller};
use esp_storage::FlashStorage;
use esp_wifi::{init, EspWifiController};
use littlefs2::fs::{Allocation, Filesystem as lfs2Filesystem};
use littlefs2::object_safe::DynStorage;
use log::{error, info, warn};
use portable_atomic::AtomicBool;
use serde::Serialize;
use shared_flash::MutexFlashStorage;
pub static TIME_ACCESS: OnceLock<Mutex<CriticalSectionRawMutex, Rtc>> = OnceLock::new();
@@ -127,9 +123,9 @@ pub enum Sensor {
B,
}
impl Into<SensorSlot> for Sensor {
fn into(self) -> SensorSlot {
match self {
impl From<Sensor> for SensorSlot {
fn from(val: Sensor) -> Self {
match val {
Sensor::A => SensorSlot::A,
Sensor::B => SensorSlot::B,
}
@@ -138,6 +134,7 @@ impl Into<SensorSlot> for Sensor {
pub struct PlantHal {}
#[allow(clippy::upper_case_acronyms)]
pub struct HAL<'a> {
pub board_hal: Box<dyn BoardInteraction<'a> + Send>,
}
@@ -177,17 +174,17 @@ pub trait BoardInteraction<'a> {
let current = counter % PLANT_COUNT as u32;
for led in 0..PLANT_COUNT {
if let Err(err) = self.fault(led, current == led as u32).await {
warn!("Fault on plant {}: {:?}", led, err);
warn!("Fault on plant {led}: {err:?}");
}
}
let even = counter % 2 == 0;
let _ = self.general_fault(even.into()).await;
let _ = self.general_fault(even).await;
}
async fn clear_progress(&mut self) {
for led in 0..PLANT_COUNT {
if let Err(err) = self.fault(led, false).await {
warn!("Fault on plant {}: {:?}", led, err);
warn!("Fault on plant {led}: {err:?}");
}
}
let _ = self.general_fault(false).await;
@@ -221,13 +218,7 @@ pub struct FreePeripherals<'a> {
pub gpio21: GPIO21<'a>,
pub gpio22: GPIO22<'a>,
pub gpio23: GPIO23<'a>,
pub gpio24: GPIO24<'a>,
pub gpio25: GPIO25<'a>,
pub gpio26: GPIO26<'a>,
pub gpio27: GPIO27<'a>,
pub gpio28: GPIO28<'a>,
pub gpio29: GPIO29<'a>,
pub gpio30: GPIO30<'a>,
pub twai: TWAI0<'a>,
pub pcnt0: Unit<'a, 0>,
pub pcnt1: Unit<'a, 1>,
@@ -238,7 +229,7 @@ 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));
let x = STATIC_CELL.uninit().write($val);
x
}};
}
@@ -258,7 +249,9 @@ impl PlantHal {
error: "Init error rct".to_string(),
})?;
let systimer = SystemTimer::new(peripherals.SYSTIMER);
let timg0 = TimerGroup::new(peripherals.TIMG0);
let sw_int = SoftwareInterruptControl::new(peripherals.SW_INTERRUPT);
esp_rtos::start(timg0.timer0, sw_int.software_interrupt0);
let boot_button = Input::new(
peripherals.GPIO9,
@@ -268,21 +261,15 @@ impl PlantHal {
// Reserve GPIO1 for deep sleep wake (configured just before entering sleep)
let wake_gpio1 = peripherals.GPIO1;
let rng = Rng::new(peripherals.RNG);
let timg0 = TimerGroup::new(peripherals.TIMG0);
let rng = Rng::new();
let esp_wifi_ctrl = &*mk_static!(
EspWifiController<'static>,
init(timg0.timer0, rng.clone()).expect("Could not init wifi controller")
Controller<'static>,
init().expect("Could not init wifi controller")
);
let (controller, interfaces) =
esp_wifi::wifi::new(&esp_wifi_ctrl, peripherals.WIFI).expect("Could not init wifi");
use esp_hal::timer::systimer::SystemTimer;
esp_hal_embassy::init(systimer.alarm0);
//let mut adc1 = Adc::new(peripherals.ADC1, adc1_config);
//
esp_radio::wifi::new(esp_wifi_ctrl, peripherals.WIFI, Default::default())
.expect("Could not init wifi");
let pcnt_module = Pcnt::new(peripherals.PCNT);
@@ -311,13 +298,7 @@ impl PlantHal {
gpio21: peripherals.GPIO21,
gpio22: peripherals.GPIO22,
gpio23: peripherals.GPIO23,
gpio24: peripherals.GPIO24,
gpio25: peripherals.GPIO25,
gpio26: peripherals.GPIO26,
gpio27: peripherals.GPIO27,
gpio28: peripherals.GPIO28,
gpio29: peripherals.GPIO29,
gpio30: peripherals.GPIO30,
twai: peripherals.TWAI0,
pcnt0: pcnt_module.unit0,
pcnt1: pcnt_module.unit1,
@@ -328,9 +309,18 @@ impl PlantHal {
[u8; esp_bootloader_esp_idf::partitions::PARTITION_TABLE_MAX_LEN],
[0u8; esp_bootloader_esp_idf::partitions::PARTITION_TABLE_MAX_LEN]
);
let storage_ota = mk_static!(FlashStorage, FlashStorage::new());
let bullshit = MutexFlashStorage {
inner: Arc::new(CriticalSectionMutex::new(RefCell::new(FlashStorage::new(
peripherals.FLASH,
)))),
};
let flash_storage = mk_static!(MutexFlashStorage, bullshit.clone());
let flash_storage_2 = mk_static!(MutexFlashStorage, bullshit.clone());
let flash_storage_3 = mk_static!(MutexFlashStorage, bullshit.clone());
let pt =
esp_bootloader_esp_idf::partitions::read_partition_table(storage_ota, tablebuffer)?;
esp_bootloader_esp_idf::partitions::read_partition_table(flash_storage, tablebuffer)?;
let ota_data = mk_static!(
PartitionEntry,
@@ -341,42 +331,41 @@ impl PlantHal {
);
let ota_data = mk_static!(
FlashRegion<FlashStorage>,
ota_data.as_embedded_storage(storage_ota)
FlashRegion<MutexFlashStorage>,
ota_data.as_embedded_storage(flash_storage_2)
);
let state_0 = ota_state(ota_slot::Slot0, ota_data);
let state_1 = ota_state(ota_slot::Slot1, ota_data);
let mut ota = Ota::new(ota_data)?;
let state_0 = ota_state(AppPartitionSubType::Ota0, ota_data);
let state_1 = ota_state(AppPartitionSubType::Ota1, ota_data);
let mut ota = Ota::new(ota_data, 2)?;
let running = get_current_slot_and_fix_ota_data(&mut ota, state_0, state_1)?;
let target = running.next();
let target = next_partition(running)?;
info!("Currently running OTA slot: {:?}", running);
info!("Slot0 state: {:?}", state_0);
info!("Slot1 state: {:?}", state_1);
info!("Currently running OTA slot: {running:?}");
info!("Slot0 state: {state_0:?}");
info!("Slot1 state: {state_1:?}");
//obtain current_state and next_state here!
let ota_target = match target {
Slot::None => {
panic!("No OTA slot active?");
}
Slot::Slot0 => pt
AppPartitionSubType::Ota0 => pt
.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::App(
AppPartitionSubType::Ota0,
))?
.context("Partition table invalid no ota0")?,
Slot::Slot1 => pt
AppPartitionSubType::Ota1 => pt
.find_partition(esp_bootloader_esp_idf::partitions::PartitionType::App(
AppPartitionSubType::Ota1,
))?
.context("Partition table invalid no ota1")?,
_ => {
bail!("Invalid target partition");
}
};
let ota_target = mk_static!(PartitionEntry, ota_target);
let storage_ota = mk_static!(FlashStorage, FlashStorage::new());
let ota_target = mk_static!(
FlashRegion<FlashStorage>,
ota_target.as_embedded_storage(storage_ota)
FlashRegion<MutexFlashStorage>,
ota_target.as_embedded_storage(flash_storage)
);
let data_partition = pt
@@ -386,10 +375,9 @@ impl PlantHal {
.expect("Data partition with littlefs not found");
let data_partition = mk_static!(PartitionEntry, data_partition);
let storage_data = mk_static!(FlashStorage, FlashStorage::new());
let data = mk_static!(
FlashRegion<FlashStorage>,
data_partition.as_embedded_storage(storage_data)
FlashRegion<MutexFlashStorage>,
data_partition.as_embedded_storage(flash_storage_3)
);
let lfs2filesystem = mk_static!(LittleFs2Filesystem, LittleFs2Filesystem { storage: data });
let alloc = mk_static!(Allocation<LittleFs2Filesystem>, lfs2Filesystem::allocate());
@@ -401,11 +389,12 @@ impl PlantHal {
log::info!("Littlefs2 filesystem is formatted");
}
Err(err) => {
error!("Littlefs2 filesystem could not be formatted: {:?}", err);
error!("Littlefs2 filesystem could not be formatted: {err:?}");
}
}
}
#[allow(clippy::arc_with_non_send_sync)]
let fs = Arc::new(Mutex::new(
lfs2Filesystem::mount(alloc, lfs2filesystem).expect("Could not mount lfs2 filesystem"),
));
@@ -498,8 +487,8 @@ impl PlantHal {
I2C_DRIVER.init(i2c_bus).expect("Could not init i2c driver");
let i2c_bus = I2C_DRIVER.get().await;
let rtc_device = I2cDevice::new(&i2c_bus);
let eeprom_device = I2cDevice::new(&i2c_bus);
let rtc_device = I2cDevice::new(i2c_bus);
let eeprom_device = I2cDevice::new(i2c_bus);
let mut rtc: Ds323x<
I2cInterface<I2cDevice<CriticalSectionRawMutex, I2c<Blocking>>>,
@@ -511,10 +500,10 @@ impl PlantHal {
let rtc_time = rtc.datetime();
match rtc_time {
Ok(tt) => {
log::info!("Rtc Module reports time at UTC {}", tt);
log::info!("Rtc Module reports time at UTC {tt}");
}
Err(err) => {
log::info!("Rtc Module could not be read {:?}", err);
log::info!("Rtc Module could not be read {err:?}");
}
}
@@ -566,7 +555,7 @@ impl PlantHal {
};
let board_hal: Box<dyn BoardInteraction + Send> = match config.hardware.board {
BoardVersion::INITIAL => {
BoardVersion::Initial => {
initial_hal::create_initial_board(free_pins, config, esp)?
}
BoardVersion::V3 => {
@@ -606,29 +595,29 @@ impl PlantHal {
}
}
fn ota_state(slot: ota_slot, ota_data: &mut FlashRegion<FlashStorage>) -> OtaImageState {
fn ota_state(
slot: AppPartitionSubType,
ota_data: &mut FlashRegion<MutexFlashStorage>,
) -> OtaImageState {
// Read and log OTA states for both slots before constructing Ota
// Each OTA select entry is 32 bytes: [seq:4][label:20][state:4][crc:4]
// Offsets within the OTA data partition: slot0 @ 0x0000, slot1 @ 0x1000
if slot == ota_slot::None {
return OtaImageState::Undefined;
}
let mut slot_buf = [0u8; 32];
if slot == ota_slot::Slot0 {
let _ = ota_data.read(0x0000, &mut slot_buf);
if slot == AppPartitionSubType::Ota0 {
let _ = ReadStorage::read(ota_data, 0x0000, &mut slot_buf);
} else {
let _ = ota_data.read(0x1000, &mut slot_buf);
let _ = ReadStorage::read(ota_data, 0x1000, &mut slot_buf);
}
let raw_state = u32::from_le_bytes(slot_buf[24..28].try_into().unwrap_or([0xff; 4]));
let state0 = OtaImageState::try_from(raw_state).unwrap_or(OtaImageState::Undefined);
state0
OtaImageState::try_from(raw_state).unwrap_or(OtaImageState::Undefined)
}
fn get_current_slot_and_fix_ota_data(
ota: &mut Ota<FlashStorage>,
ota: &mut Ota<MutexFlashStorage>,
state0: OtaImageState,
state1: OtaImageState,
) -> Result<ota_slot, FatError> {
) -> Result<AppPartitionSubType, FatError> {
let state = ota.current_ota_state().unwrap_or_default();
let swap = match state {
OtaImageState::Invalid => true,
@@ -639,11 +628,11 @@ fn get_current_slot_and_fix_ota_data(
}
_ => false,
};
let current = ota.current_slot()?;
let current = ota.current_app_partition()?;
if swap {
let other = match current {
ota_slot::Slot0 => state1,
ota_slot::Slot1 => state0,
AppPartitionSubType::Ota0 => state1,
AppPartitionSubType::Ota1 => state0,
_ => OtaImageState::Invalid,
};
@@ -666,17 +655,27 @@ fn get_current_slot_and_fix_ota_data(
}
_ => {}
}
info!(
"Current slot has state {:?} other state has {:?} swapping",
state, other
);
ota.set_current_slot(current.next())?;
info!("Current slot has state {state:?} other state has {other:?} swapping");
let next = next_partition(current)?;
ota.set_current_app_partition(next)?;
//we actually booted other slot, than partition table assumes
return Ok(ota.current_slot()?);
return Ok(ota.current_app_partition()?);
};
Ok(current)
}
pub fn next_partition(current: AppPartitionSubType) -> FatResult<AppPartitionSubType> {
let next = match current {
AppPartitionSubType::Ota0 => AppPartitionSubType::Ota1,
AppPartitionSubType::Ota1 => AppPartitionSubType::Ota0,
_ => {
bail!("Current slot is not ota0 or ota1");
}
};
Ok(next)
}
pub async fn esp_time() -> DateTime<Utc> {
let guard = TIME_ACCESS.get().await.lock().await;
DateTime::from_timestamp_micros(guard.current_time_us() as i64).unwrap()
@@ -699,17 +698,17 @@ pub async fn esp_set_time(time: DateTime<FixedOffset>) -> FatResult<()> {
}
#[derive(Debug, Clone, Copy, PartialEq, Default, Serialize)]
pub struct Moistures{
pub struct Moistures {
pub sensor_a_hz: [f32; PLANT_COUNT],
pub sensor_b_hz: [f32; PLANT_COUNT],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
pub struct DetectionResult {
plant: [DetectionSensorResult; crate::hal::PLANT_COUNT]
plant: [DetectionSensorResult; crate::hal::PLANT_COUNT],
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
pub struct DetectionSensorResult{
pub struct DetectionSensorResult {
sensor_a: bool,
sensor_b: bool,
}
}

View File

@@ -1,5 +1,5 @@
use crate::hal::Box;
use crate::fat_error::FatResult;
use crate::hal::Box;
use async_trait::async_trait;
use bincode::config::Configuration;
use bincode::{config, Decode, Encode};
@@ -65,7 +65,7 @@ impl RTCModuleInteraction for DS3231Module {
let (header, len): (BackupHeader, usize) =
bincode::decode_from_slice(&header_page_buffer[..], CONFIG)?;
log::info!("Raw header is {:?} with size {}", header_page_buffer, len);
log::info!("Raw header is {header_page_buffer:?} with size {len}");
Ok(header)
}
@@ -97,7 +97,7 @@ impl RTCModuleInteraction for DS3231Module {
async fn backup_config(&mut self, offset: usize, bytes: &[u8]) -> FatResult<()> {
//skip header and write after
self.storage
.write((BACKUP_HEADER_MAX_SIZE + offset) as u32, &bytes)?;
.write((BACKUP_HEADER_MAX_SIZE + offset) as u32, bytes)?;
Ok(())
}
@@ -113,11 +113,7 @@ impl RTCModuleInteraction for DS3231Module {
};
let config = config::standard();
let encoded = bincode::encode_into_slice(&header, &mut header_page_buffer, config)?;
log::info!(
"Raw header is {:?} with size {}",
header_page_buffer,
encoded
);
log::info!("Raw header is {header_page_buffer:?} with size {encoded}");
self.storage.write(0, &header_page_buffer)?;
Ok(())
}

View File

@@ -0,0 +1,63 @@
use alloc::sync::Arc;
use core::cell::RefCell;
use core::ops::{Deref, DerefMut};
use embassy_sync::blocking_mutex::CriticalSectionMutex;
use embedded_storage::nor_flash::{ErrorType, NorFlash, ReadNorFlash};
use embedded_storage::ReadStorage;
use esp_storage::{FlashStorage, FlashStorageError};
#[derive(Clone)]
pub struct MutexFlashStorage {
pub(crate) inner: Arc<CriticalSectionMutex<RefCell<FlashStorage<'static>>>>,
}
impl ReadStorage for MutexFlashStorage {
type Error = FlashStorageError;
fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), FlashStorageError> {
self.inner
.lock(|f| ReadStorage::read(f.borrow_mut().deref_mut(), offset, bytes))
}
fn capacity(&self) -> usize {
self.inner
.lock(|f| ReadStorage::capacity(f.borrow().deref()))
}
}
impl embedded_storage::Storage for MutexFlashStorage {
fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
NorFlash::write(self, offset, bytes)
}
}
impl ErrorType for MutexFlashStorage {
type Error = FlashStorageError;
}
impl ReadNorFlash for MutexFlashStorage {
const READ_SIZE: usize = 0;
fn read(&mut self, offset: u32, bytes: &mut [u8]) -> Result<(), Self::Error> {
ReadStorage::read(self, offset, bytes)
}
fn capacity(&self) -> usize {
ReadStorage::capacity(self)
}
}
impl NorFlash for MutexFlashStorage {
const WRITE_SIZE: usize = 0;
const ERASE_SIZE: usize = 0;
fn erase(&mut self, from: u32, to: u32) -> Result<(), Self::Error> {
self.inner
.lock(|f| NorFlash::erase(f.borrow_mut().deref_mut(), from, to))
}
fn write(&mut self, offset: u32, bytes: &[u8]) -> Result<(), Self::Error> {
self.inner
.lock(|f| NorFlash::write(f.borrow_mut().deref_mut(), offset, bytes))
}
}

View File

@@ -171,10 +171,13 @@ pub(crate) fn create_v3(
}
impl V3<'_> {
async fn inner_measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32, FatError> {
async fn inner_measure_moisture_hz(
&mut self,
plant: usize,
sensor: Sensor,
) -> Result<f32, FatError> {
let mut results = [0_f32; REPEAT_MOIST_MEASURE];
for repeat in 0..REPEAT_MOIST_MEASURE {
for sample in results.iter_mut() {
self.signal_counter.pause();
self.signal_counter.clear();
//Disable all
@@ -266,7 +269,7 @@ impl V3<'_> {
&format!("{sensor:?}"),
)
.await;
results[repeat] = hz;
*sample = hz;
}
results.sort_by(|a, b| a.partial_cmp(b).unwrap()); // floats don't seem to implement total_ord
@@ -386,12 +389,18 @@ impl<'a> BoardInteraction<'a> for V3<'a> {
for plant in 0..PLANT_COUNT {
let a = self.inner_measure_moisture_hz(plant, Sensor::A).await;
let b = self.inner_measure_moisture_hz(plant, Sensor::B).await;
let aa = a.unwrap_or_else(|_| u32::MAX as f32);
let bb = b.unwrap_or_else(|_| u32::MAX as f32);
let aa = a.unwrap_or(u32::MAX as f32);
let bb = b.unwrap_or(u32::MAX as f32);
LOG_ACCESS
.lock()
.await
.log(LogMessage::TestSensor, aa as u32, bb as u32, &plant.to_string(), "")
.log(
LogMessage::TestSensor,
aa as u32,
bb as u32,
&plant.to_string(),
"",
)
.await;
result.sensor_a_hz[plant] = aa;
result.sensor_b_hz[plant] = bb;
@@ -399,7 +408,6 @@ impl<'a> BoardInteraction<'a> for V3<'a> {
Ok(result)
}
async fn general_fault(&mut self, enable: bool) {
hold_disable(6);
if enable {

View File

@@ -6,7 +6,10 @@ use crate::hal::esp::{hold_disable, hold_enable, Esp};
use crate::hal::rtc::RTCModuleInteraction;
use crate::hal::v4_sensor::{SensorImpl, SensorInteraction};
use crate::hal::water::TankSensor;
use crate::hal::{BoardInteraction, DetectionResult, FreePeripherals, Moistures, I2C_DRIVER, PLANT_COUNT, TIME_ACCESS};
use crate::hal::{
BoardInteraction, DetectionResult, FreePeripherals, Moistures, I2C_DRIVER, PLANT_COUNT,
TIME_ACCESS,
};
use crate::log::{LogMessage, LOG_ACCESS};
use alloc::boxed::Box;
use alloc::string::ToString;
@@ -74,35 +77,29 @@ impl<'a> Charger<'a> {
impl Charger<'_> {
pub(crate) fn power_save(&mut self) {
match self {
Charger::SolarMpptV1 { mppt_ina, .. } => {
let _ = mppt_ina
.set_configuration(Configuration {
reset: Default::default(),
bus_voltage_range: Default::default(),
shunt_voltage_range: Default::default(),
bus_resolution: Default::default(),
shunt_resolution: Default::default(),
operating_mode: OperatingMode::PowerDown,
})
.map_err(|e| {
log::info!(
"Error setting ina mppt configuration during deep sleep preparation{:?}",
e
);
});
}
_ => {}
if let Charger::SolarMpptV1 { mppt_ina, .. } = self {
let _ = mppt_ina
.set_configuration(Configuration {
reset: Default::default(),
bus_voltage_range: Default::default(),
shunt_voltage_range: Default::default(),
bus_resolution: Default::default(),
shunt_resolution: Default::default(),
operating_mode: OperatingMode::PowerDown,
})
.map_err(|e| {
log::info!(
"Error setting ina mppt configuration during deep sleep preparation{e:?}"
);
});
}
}
fn set_charge_indicator(&mut self, charging: bool) -> FatResult<()> {
match self {
Self::SolarMpptV1 {
charge_indicator, ..
} => {
charge_indicator.set_level(charging.into());
}
_ => {}
if let Self::SolarMpptV1 {
charge_indicator, ..
} = self
{
charge_indicator.set_level(charging.into());
}
Ok(())
}
@@ -244,7 +241,7 @@ pub(crate) async fn create_v4(
Some(ina)
}
Err(err) => {
log::info!("Error creating mppt ina: {:?}", err);
log::info!("Error creating mppt ina: {err:?}");
None
}
};
@@ -253,7 +250,7 @@ pub(crate) async fn create_v4(
let pump_ina = match SyncIna219::new(pump_current_dev, Address::from_pins(Pin::Gnd, Pin::Sda)) {
Ok(ina) => Some(ina),
Err(err) => {
log::info!("Error creating pump ina: {:?}", err);
log::info!("Error creating pump ina: {err:?}");
None
}
};
@@ -362,7 +359,7 @@ impl<'a> BoardInteraction<'a> for V4<'a> {
let v = pump_ina
.shunt_voltage()
.map_err(|e| FatError::String {
error: alloc::format!("{:?}", e),
error: alloc::format!("{e:?}"),
})
.map(|v| {
let shunt_voltage =

View File

@@ -1,17 +1,16 @@
use canapi::id::{classify, plant_id, MessageKind, IDENTIFY_CMD_OFFSET};
use crate::bail;
use crate::fat_error::{ContextExt, FatError, FatResult};
use canapi::{SensorSlot};
use crate::hal::{DetectionResult, Moistures, Sensor};
use crate::fat_error::{ContextExt, FatResult};
use crate::hal::Box;
use crate::hal::{DetectionResult, Moistures, Sensor};
use crate::log::{LogMessage, LOG_ACCESS};
use alloc::format;
use alloc::string::ToString;
use async_trait::async_trait;
use bincode::config;
use canapi::id::{classify, plant_id, MessageKind, IDENTIFY_CMD_OFFSET};
use canapi::SensorSlot;
use embassy_embedded_hal::shared_bus::blocking::i2c::I2cDevice;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_time::{Duration, Instant, Timer, WithTimeout};
use embassy_time::{Duration, Timer, WithTimeout};
use embedded_can::{Frame, Id};
use esp_hal::gpio::Output;
use esp_hal::i2c::master::I2c;
@@ -23,8 +22,6 @@ use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
const REPEAT_MOIST_MEASURE: usize = 10;
#[async_trait(?Send)]
pub trait SensorInteraction {
async fn measure_moisture_hz(&mut self) -> FatResult<Moistures>;
@@ -59,11 +56,25 @@ impl SensorInteraction for SensorImpl {
..
} => {
let mut result = Moistures::default();
for plant in 0..crate::hal::PLANT_COUNT{
result.sensor_a_hz[plant] = Self::inner_pulse(plant, Sensor::A, signal_counter, sensor_expander).await?;
info!("Sensor {} {:?}: {}", plant, Sensor::A, result.sensor_a_hz[plant]);
result.sensor_b_hz[plant] = Self::inner_pulse(plant, Sensor::B, signal_counter, sensor_expander).await?;
info!("Sensor {} {:?}: {}", plant, Sensor::B, result.sensor_b_hz[plant]);
for plant in 0..crate::hal::PLANT_COUNT {
result.sensor_a_hz[plant] =
Self::inner_pulse(plant, Sensor::A, signal_counter, sensor_expander)
.await?;
info!(
"Sensor {} {:?}: {}",
plant,
Sensor::A,
result.sensor_a_hz[plant]
);
result.sensor_b_hz[plant] =
Self::inner_pulse(plant, Sensor::B, signal_counter, sensor_expander)
.await?;
info!(
"Sensor {} {:?}: {}",
plant,
Sensor::B,
result.sensor_b_hz[plant]
);
}
Ok(result)
}
@@ -74,36 +85,37 @@ impl SensorInteraction for SensorImpl {
} => {
can_power.set_high();
let config = twai_config.take().expect("twai config not set");
let mut twai = config.start();
let mut twai = config.into_async().start();
loop {
let rec = twai.receive();
match rec {
Ok(_) => {}
Err(err) => {
info!("Error receiving CAN message: {:?}", err);
info!("Error receiving CAN message: {err:?}");
break;
}
}
}
Timer::after_millis(10).await;
let can = Self::inner_can(&mut twai).await;
let mut moistures = Moistures::default();
let _ = Self::wait_for_can_measurements(&mut twai, &mut moistures)
.with_timeout(Duration::from_millis(5000))
.await;
can_power.set_low();
let config = twai.stop();
let config = twai.stop().into_blocking();
twai_config.replace(config);
let value = can?;
Ok(value)
Ok(moistures)
}
}
}
}
impl SensorImpl {
pub async fn autodetect(&mut self) -> FatResult<DetectionResult> {
match self {
@@ -124,187 +136,187 @@ impl SensorImpl {
// Send a few test messages per potential sensor node
for plant in 0..crate::hal::PLANT_COUNT {
for sensor in [Sensor::A, Sensor::B] {
let target = StandardId::new(plant_id(IDENTIFY_CMD_OFFSET, sensor.into(), plant as u16)).context(">> Could not create address for sensor! (plant: {}) <<")?;
let target = StandardId::new(plant_id(
IDENTIFY_CMD_OFFSET,
sensor.into(),
plant as u16,
))
.context(">> Could not create address for sensor! (plant: {}) <<")?;
let can_buffer = [0_u8; 0];
if let Some(frame) = EspTwaiFrame::new(target, &can_buffer) {
// Try a few times; we intentionally ignore rx here and rely on stub logic
let resu = as_async.transmit_async(&frame).await;
match resu {
Ok(_) => {
info!(
"Sent test message to plant {} sensor {:?}",
plant, sensor
);
info!("Sent test message to plant {plant} sensor {sensor:?}");
}
Err(err) => {
info!("Error sending test message to plant {} sensor {:?}: {:?}", plant, sensor, err);
info!(
"Error sending test message to plant {plant} sensor {sensor:?}: {err:?}"
);
}
}
} else {
info!("Error building CAN frame");
}
}
}
let mut result = DetectionResult::default();
// Wait for messages to arrive
let _ = Self::wait_for_can_measurements(&mut as_async, &mut result).with_timeout(Duration::from_millis(5000)).await;
let mut moistures = Moistures::default();
let _ = Self::wait_for_can_measurements(&mut as_async, &mut moistures)
.with_timeout(Duration::from_millis(5000))
.await;
let config = as_async.stop().into_blocking();
can_power.set_low();
twai_config.replace(config);
info!("Autodetection result: {:?}", result);
let result = moistures.into();
info!("Autodetection result: {result:?}");
Ok(result)
}
}
}
async fn wait_for_can_measurements(as_async: &mut Twai<'_, Async>, result: &mut DetectionResult) {
async fn wait_for_can_measurements(
as_async: &mut Twai<'_, Async>,
moistures: &mut Moistures,
) -> FatResult<()> {
loop {
match as_async.receive_async().await {
Ok(can_frame) => {
match can_frame.id() {
Id::Standard(id) => {
info!("Received CAN message: {:?}", id);
let rawid = id.as_raw();
match classify(rawid) {
None => {}
Some(msg) => {
info!("received message of kind {:?} (plant: {}, sensor: {:?})", msg.0, msg.1, msg.2);
if msg.0 == MessageKind::MoistureData {
let plant = msg.1 as usize;
let sensor = msg.2;
match sensor {
SensorSlot::A => {
result.plant[plant].sensor_a = true;
}
SensorSlot::B => {
result.plant[plant].sensor_b = true;
}
Ok(can_frame) => match can_frame.id() {
Id::Standard(id) => {
info!("Received CAN message: {id:?}");
let rawid = id.as_raw();
match classify(rawid) {
None => {}
Some(msg) => {
info!(
"received message of kind {:?} (plant: {}, sensor: {:?})",
msg.0, msg.1, msg.2
);
if msg.0 == MessageKind::MoistureData {
let plant = msg.1 as usize;
let sensor = msg.2;
let data = can_frame.data();
match sensor {
SensorSlot::A => {
moistures.sensor_a_hz[plant] = data[0] as f32;
}
SensorSlot::B => {
moistures.sensor_b_hz[plant] = data[0] as f32;
}
}
}
}
}
Id::Extended(ext) => {
warn!("Received extended ID: {:?}", ext);
}
}
}
Err(err) => {
error!("Error receiving CAN message: {:?}", err);
break;
}
}
}
}
pub async fn inner_pulse(plant: usize, sensor: Sensor, signal_counter: &mut Unit<'_, 0>, sensor_expander: &mut Pca9535Immediate<I2cDevice<'static, CriticalSectionRawMutex, I2c<'static, Blocking>>>) -> FatResult<f32> {
let mut results = [0_f32; REPEAT_MOIST_MEASURE];
for repeat in 0..REPEAT_MOIST_MEASURE {
signal_counter.pause();
signal_counter.clear();
//Disable all
sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
let sensor_channel = match sensor {
Sensor::A => plant as u32,
Sensor::B => (15 - plant) as u32,
};
let is_bit_set = |b: u8| -> bool { sensor_channel & (1 << b) != 0 };
if is_bit_set(0) {
sensor_expander.pin_set_high(GPIOBank::Bank0, MS0)?;
} else {
sensor_expander.pin_set_low(GPIOBank::Bank0, MS0)?;
}
if is_bit_set(1) {
sensor_expander.pin_set_high(GPIOBank::Bank0, MS1)?;
} else {
sensor_expander.pin_set_low(GPIOBank::Bank0, MS1)?;
}
if is_bit_set(2) {
sensor_expander.pin_set_high(GPIOBank::Bank0, MS2)?;
} else {
sensor_expander.pin_set_low(GPIOBank::Bank0, MS2)?;
}
if is_bit_set(3) {
sensor_expander.pin_set_high(GPIOBank::Bank0, MS3)?;
} else {
sensor_expander.pin_set_low(GPIOBank::Bank0, MS3)?;
}
sensor_expander.pin_set_low(GPIOBank::Bank0, MS4)?;
sensor_expander.pin_set_high(GPIOBank::Bank0, SENSOR_ON)?;
let measurement = 100; // TODO what is this scaling factor? what is its purpose?
let factor = 1000f32 / measurement as f32;
//give some time to stabilize
Timer::after_millis(10).await;
signal_counter.resume();
Timer::after_millis(measurement).await;
signal_counter.pause();
sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, SENSOR_ON)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, MS0)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, MS1)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, MS2)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, MS3)?;
Timer::after_millis(10).await;
let unscaled = 1337; //signal_counter.get_counter_value()? as i32;
let hz = unscaled as f32 * factor;
LOG_ACCESS
.lock()
.await
.log(
LogMessage::RawMeasure,
unscaled as u32,
hz as u32,
&plant.to_string(),
&format!("{sensor:?}"),
)
.await;
results[repeat] = hz;
}
results.sort_by(|a, b| a.partial_cmp(b).unwrap()); // floats don't seem to implement total_ord
let mid = results.len() / 2;
let median = results[mid];
Ok(median)
}
async fn inner_can(
twai: &mut Twai<'static, Blocking>,
) -> FatResult<Moistures> {
[0_u8; 8];
config::standard();
let timeout = Instant::now()
.checked_add(embassy_time::Duration::from_millis(100))
.context("Timeout")?;
loop {
let answer = twai.receive();
match answer {
Ok(answer) => {
info!("Received CAN message: {:?}", answer);
}
Err(error) => match error {
nb::Error::Other(error) => {
return Err(FatError::CanBusError { error });
}
nb::Error::WouldBlock => {
if Instant::now() > timeout {
bail!("Timeout waiting for CAN answer");
}
Timer::after_millis(10).await;
Id::Extended(ext) => {
warn!("Received extended ID: {ext:?}");
}
},
Err(err) => {
error!("Error receiving CAN message: {err:?}");
}
}
}
}
pub async fn inner_pulse(
plant: usize,
sensor: Sensor,
signal_counter: &mut Unit<'_, 0>,
sensor_expander: &mut Pca9535Immediate<
I2cDevice<'static, CriticalSectionRawMutex, I2c<'static, Blocking>>,
>,
) -> FatResult<f32> {
let mut results = [0_f32; REPEAT_MOIST_MEASURE];
for sample in results.iter_mut() {
signal_counter.pause();
signal_counter.clear();
//Disable all
sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
let sensor_channel = match sensor {
Sensor::A => plant as u32,
Sensor::B => (15 - plant) as u32,
};
let is_bit_set = |b: u8| -> bool { sensor_channel & (1 << b) != 0 };
if is_bit_set(0) {
sensor_expander.pin_set_high(GPIOBank::Bank0, MS0)?;
} else {
sensor_expander.pin_set_low(GPIOBank::Bank0, MS0)?;
}
if is_bit_set(1) {
sensor_expander.pin_set_high(GPIOBank::Bank0, MS1)?;
} else {
sensor_expander.pin_set_low(GPIOBank::Bank0, MS1)?;
}
if is_bit_set(2) {
sensor_expander.pin_set_high(GPIOBank::Bank0, MS2)?;
} else {
sensor_expander.pin_set_low(GPIOBank::Bank0, MS2)?;
}
if is_bit_set(3) {
sensor_expander.pin_set_high(GPIOBank::Bank0, MS3)?;
} else {
sensor_expander.pin_set_low(GPIOBank::Bank0, MS3)?;
}
sensor_expander.pin_set_low(GPIOBank::Bank0, MS4)?;
sensor_expander.pin_set_high(GPIOBank::Bank0, SENSOR_ON)?;
let measurement = 100; // TODO what is this scaling factor? what is its purpose?
let factor = 1000f32 / measurement as f32;
//give some time to stabilize
Timer::after_millis(10).await;
signal_counter.resume();
Timer::after_millis(measurement).await;
signal_counter.pause();
sensor_expander.pin_set_high(GPIOBank::Bank0, MS4)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, SENSOR_ON)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, MS0)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, MS1)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, MS2)?;
sensor_expander.pin_set_low(GPIOBank::Bank0, MS3)?;
Timer::after_millis(10).await;
let unscaled = 1337; //signal_counter.get_counter_value()? as i32;
let hz = unscaled as f32 * factor;
LOG_ACCESS
.lock()
.await
.log(
LogMessage::RawMeasure,
unscaled as u32,
hz as u32,
&plant.to_string(),
&format!("{sensor:?}"),
)
.await;
*sample = hz;
}
results.sort_by(|a, b| a.partial_cmp(b).unwrap()); // floats don't seem to implement total_ord
let mid = results.len() / 2;
let median = results[mid];
Ok(median)
}
}
impl From<Moistures> for DetectionResult {
fn from(value: Moistures) -> Self {
let mut result = DetectionResult::default();
for (plant, sensor) in value.sensor_a_hz.iter().enumerate() {
result.plant[plant].sensor_a = *sensor > 1.0_f32;
}
for (plant, sensor) in value.sensor_b_hz.iter().enumerate() {
result.plant[plant].sensor_b = *sensor > 1.0_f32;
}
result
}
}

View File

@@ -137,11 +137,11 @@ impl<'a> TankSensor<'a> {
Timer::after_millis(100).await;
let mut store = [0_u16; TANK_MULTI_SAMPLE];
for multisample in 0..TANK_MULTI_SAMPLE {
for sample in store.iter_mut() {
let value = self.tank_channel.read_oneshot(&mut self.tank_pin);
//force yield
Timer::after_millis(10).await;
store[multisample] = value.unwrap();
*sample = value.unwrap();
}
self.tank_power.set_low();

View File

@@ -7,14 +7,14 @@ use deranged::RangedU8;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::mutex::Mutex;
use esp_hal::Persistable;
use log::info;
use log::{info, warn};
use serde::Serialize;
use strum_macros::IntoStaticStr;
use unit_enum::UnitEnum;
const LOG_ARRAY_SIZE: u8 = 220;
const MAX_LOG_ARRAY_INDEX: u8 = LOG_ARRAY_SIZE - 1;
#[esp_hal::ram(rtc_fast, persistent)]
#[esp_hal::ram(unstable(rtc_fast), unstable(persistent))]
static mut LOG_ARRAY: LogArray = LogArray {
buffer: [LogEntryInner {
timestamp: 0,
@@ -26,8 +26,11 @@ static mut LOG_ARRAY: LogArray = LogArray {
}; LOG_ARRAY_SIZE as usize],
head: 0,
};
// this is the only reference that is created for LOG_ARRAY and the only way to access it
#[allow(static_mut_refs)]
pub static LOG_ACCESS: Mutex<CriticalSectionRawMutex, &'static mut LogArray> =
unsafe { Mutex::new(&mut *&raw mut LOG_ARRAY) };
unsafe { Mutex::new(&mut LOG_ARRAY) };
const TXT_SHORT_LENGTH: usize = 8;
const TXT_LONG_LENGTH: usize = 32;
@@ -138,7 +141,7 @@ impl LogArray {
template_string = template_string.replace("${txt_long}", txt_long);
template_string = template_string.replace("${txt_short}", txt_short);
info!("{}", template_string);
info!("{template_string}");
let to_modify = &mut self.buffer[head.get() as usize];
to_modify.timestamp = time;
@@ -147,10 +150,10 @@ impl LogArray {
to_modify.b = number_b;
to_modify
.txt_short
.clone_from_slice(&txt_short_stack.as_bytes());
.clone_from_slice(txt_short_stack.as_bytes());
to_modify
.txt_long
.clone_from_slice(&txt_long_stack.as_bytes());
.clone_from_slice(txt_long_stack.as_bytes());
head = head.wrapping_add(1);
self.head = head.get();
}
@@ -162,18 +165,38 @@ fn limit_length<const LIMIT: usize>(input: &str, target: &mut heapless::String<L
Ok(_) => {} //continue adding chars
Err(_) => {
//clear space for two asci chars
info!("pushing char {char} to limit {LIMIT} current value {target} input {input}");
while target.len() + 2 >= LIMIT {
target.pop().unwrap();
target.pop();
}
//add .. to shortened strings
target.push('.').unwrap();
target.push('.').unwrap();
match target.push('.') {
Ok(_) => {}
Err(_) => {
warn!(
"Error pushin . to limit {LIMIT} current value {target} input {input}"
)
}
}
match target.push('.') {
Ok(_) => {}
Err(_) => {
warn!(
"Error pushin . to limit {LIMIT} current value {target} input {input}"
)
}
}
return;
}
}
}
while target.len() < LIMIT {
target.push(' ').unwrap();
match target.push(' ') {
Ok(_) => {}
Err(_) => {
warn!("Error pushing space to limit {LIMIT} current value {target} input {input}")
}
}
}
}

View File

@@ -16,13 +16,13 @@ use esp_backtrace as _;
use crate::config::{NetworkConfig, PlantConfig};
use crate::fat_error::FatResult;
use crate::hal::esp::MQTT_STAY_ALIVE;
use crate::hal::{esp_time, TIME_ACCESS};
use crate::hal::PROGRESS_ACTIVE;
use crate::hal::{esp_time, TIME_ACCESS};
use crate::log::{log, LOG_ACCESS};
use crate::tank::{determine_tank_state, TankError, TankState, WATER_FROZEN_THRESH};
use crate::webserver::http_server;
use crate::{
config::BoardVersion::INITIAL,
config::BoardVersion::Initial,
hal::{PlantHal, HAL, PLANT_COUNT},
};
use ::log::{info, warn};
@@ -136,18 +136,18 @@ pub struct PumpResult {
#[derive(Serialize, Debug, PartialEq)]
enum SntpMode {
OFFLINE,
SYNC { current: DateTime<Utc> },
Offline,
Sync { current: DateTime<Utc> },
}
#[derive(Serialize, Debug, PartialEq)]
enum NetworkMode {
WIFI {
Wifi {
sntp: SntpMode,
mqtt: bool,
ip_address: String,
},
OFFLINE,
Offline,
}
async fn safe_main(spawner: Spawner) -> FatResult<()> {
@@ -172,7 +172,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
value
}
Err(err) => {
info!("rtc module error: {:?}", err);
info!("rtc module error: {err:?}");
board.board_hal.general_fault(true).await;
esp_time().await
}
@@ -187,7 +187,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
.log(LogMessage::YearInplausibleForceConfig, 0, 0, "", "")
.await;
}
info!("cur is {}", cur);
info!("cur is {cur}");
update_charge_indicator(&mut board).await;
if board.board_hal.get_esp().get_restart_to_conf() {
LOG_ACCESS
@@ -228,12 +228,12 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
info!("no mode override");
}
if board.board_hal.get_config().hardware.board == INITIAL
if board.board_hal.get_config().hardware.board == Initial
&& board.board_hal.get_config().network.ssid.is_none()
{
info!("No wifi configured, starting initial config mode");
let stack = board.board_hal.get_esp().wifi_ap().await?;
let stack = board.board_hal.get_esp().wifi_ap(spawner).await?;
let reboot_now = Arc::new(AtomicBool::new(false));
println!("starting webserver");
@@ -244,34 +244,34 @@ 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).await
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
NetworkMode::Offline
};
if matches!(network_mode, NetworkMode::OFFLINE) && to_config {
if matches!(network_mode, 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().await
esp.wifi_ap(spawner).await
};
match res {
Ok(ap_stack) => {
stack.replace(ap_stack);
info!("Started ap, continuing")
}
Err(err) => info!("Could not start config override ap mode due to {}", err),
Err(err) => info!("Could not start config override ap mode due to {err}"),
}
}
let tz = &board.board_hal.get_config().timezone;
let timezone = match tz {
Some(tz_str) => tz_str.parse::<Tz>().unwrap_or_else(|_| {
info!("Invalid timezone '{}', falling back to UTC", tz_str);
info!("Invalid timezone '{tz_str}', falling back to UTC");
UTC
}),
None => UTC, // Fallback to UTC if no timezone is set
@@ -286,7 +286,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
timezone_time
);
if let NetworkMode::WIFI { ref ip_address, .. } = network_mode {
if let 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;
@@ -297,15 +297,15 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
.await
.log(
LogMessage::StartupInfo,
matches!(network_mode, NetworkMode::WIFI { .. }) as u32,
matches!(network_mode, NetworkMode::Wifi { .. }) as u32,
matches!(
network_mode,
NetworkMode::WIFI {
sntp: SntpMode::SYNC { .. },
NetworkMode::Wifi {
sntp: SntpMode::Sync { .. },
..
}
) as u32,
matches!(network_mode, NetworkMode::WIFI { mqtt: true, .. })
matches!(network_mode, NetworkMode::Wifi { mqtt: true, .. })
.to_string()
.as_str(),
"",
@@ -356,7 +356,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
LogMessage::TankSensorValueRangeError,
min as u32,
max as u32,
&format!("{}", value),
&format!("{value}"),
"",
)
.await
@@ -402,14 +402,14 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
let moisture = board.board_hal.measure_moisture_hz().await?;
let plantstate: [PlantState; PLANT_COUNT] = [
PlantState::read_hardware_state(moisture,0, &mut board).await,
PlantState::read_hardware_state(moisture,1, &mut board).await,
PlantState::read_hardware_state(moisture,2, &mut board).await,
PlantState::read_hardware_state(moisture,3, &mut board).await,
PlantState::read_hardware_state(moisture,4, &mut board).await,
PlantState::read_hardware_state(moisture,5, &mut board).await,
PlantState::read_hardware_state(moisture,6, &mut board).await,
PlantState::read_hardware_state(moisture,7, &mut board).await,
PlantState::read_hardware_state(moisture, 0, &mut board).await,
PlantState::read_hardware_state(moisture, 1, &mut board).await,
PlantState::read_hardware_state(moisture, 2, &mut board).await,
PlantState::read_hardware_state(moisture, 3, &mut board).await,
PlantState::read_hardware_state(moisture, 4, &mut board).await,
PlantState::read_hardware_state(moisture, 5, &mut board).await,
PlantState::read_hardware_state(moisture, 6, &mut board).await,
PlantState::read_hardware_state(moisture, 7, &mut board).await,
];
publish_plant_states(&mut board, &timezone_time.clone(), &plantstate).await;
@@ -507,7 +507,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
.await
.unwrap_or(BatteryState::Unknown);
info!("Battery state is {:?}", battery_state);
info!("Battery state is {battery_state:?}");
let mut light_state = LightState {
enabled: board.board_hal.get_config().night_lamp.enabled,
..Default::default()
@@ -573,7 +573,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
board.board_hal.light(false).await?;
}
info!("Lightstate is {:?}", light_state);
info!("Lightstate is {light_state:?}");
}
match &serde_json::to_string(&light_state) {
@@ -585,7 +585,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
.await;
}
Err(err) => {
info!("Error publishing lightstate {}", err);
info!("Error publishing lightstate {err}");
}
};
@@ -616,7 +616,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
.mqtt_publish("/state", "sleep")
.await;
info!("Go to sleep for {} minutes", deep_sleep_duration_minutes);
info!("Go to sleep for {deep_sleep_duration_minutes} minutes");
//determine next event
//is light out of work trigger soon?
//is battery low ??
@@ -625,7 +625,7 @@ async fn safe_main(spawner: Spawner) -> FatResult<()> {
//mark_app_valid();
let stay_alive = MQTT_STAY_ALIVE.load(Ordering::Relaxed);
info!("Check stay alive, current state is {}", stay_alive);
info!("Check stay alive, current state is {stay_alive}");
if stay_alive {
let reboot_now = Arc::new(AtomicBool::new(false));
@@ -679,49 +679,45 @@ pub async fn do_secure_pump(
let current_ma = current.as_milliamperes() as u16;
current_collector[step] = current_ma;
let high_current = current_ma > plant_config.max_pump_current_ma;
if high_current {
if first_error {
log(
LogMessage::PumpOverCurrent,
plant_id as u32 + 1,
current_ma as u32,
plant_config.max_pump_current_ma.to_string().as_str(),
step.to_string().as_str(),
)
.await;
board.board_hal.general_fault(true).await;
board.board_hal.fault(plant_id, true).await?;
if !plant_config.ignore_current_error {
error = true;
break;
}
first_error = false;
if high_current && first_error {
log(
LogMessage::PumpOverCurrent,
plant_id as u32 + 1,
current_ma as u32,
plant_config.max_pump_current_ma.to_string().as_str(),
step.to_string().as_str(),
)
.await;
board.board_hal.general_fault(true).await;
board.board_hal.fault(plant_id, true).await?;
if !plant_config.ignore_current_error {
error = true;
break;
}
first_error = false;
}
let low_current = current_ma < plant_config.min_pump_current_ma;
if low_current {
if first_error {
log(
LogMessage::PumpOpenLoopCurrent,
plant_id as u32 + 1,
current_ma as u32,
plant_config.min_pump_current_ma.to_string().as_str(),
step.to_string().as_str(),
)
.await;
board.board_hal.general_fault(true).await;
board.board_hal.fault(plant_id, true).await?;
if !plant_config.ignore_current_error {
error = true;
break;
}
first_error = false;
if low_current && first_error {
log(
LogMessage::PumpOpenLoopCurrent,
plant_id as u32 + 1,
current_ma as u32,
plant_config.min_pump_current_ma.to_string().as_str(),
step.to_string().as_str(),
)
.await;
board.board_hal.general_fault(true).await;
board.board_hal.fault(plant_id, true).await?;
if !plant_config.ignore_current_error {
error = true;
break;
}
first_error = false;
}
}
Err(err) => {
if !plant_config.ignore_current_error {
info!("Error getting pump current: {}", err);
info!("Error getting pump current: {err}");
log(
LogMessage::PumpMissingSensorCurrent,
plant_id as u32,
@@ -744,10 +740,7 @@ pub async fn do_secure_pump(
board.board_hal.get_tank_sensor()?.stop_flow_meter();
let final_flow_value = board.board_hal.get_tank_sensor()?.get_flow_meter_value();
let flow_value_ml = final_flow_value as f32 * board.board_hal.get_config().tank.ml_per_pulse;
info!(
"Final flow value is {} with {} ml",
final_flow_value, flow_value_ml
);
info!("Final flow value is {final_flow_value} with {flow_value_ml} ml");
current_collector.sort();
Ok(PumpResult {
median_current_ma: current_collector[current_collector.len() / 2],
@@ -767,7 +760,8 @@ async fn update_charge_indicator(
if let Ok(current) = board.board_hal.get_mptt_current().await {
let _ = board
.board_hal
.set_charge_indicator(current.as_milliamperes() > 20_f64);
.set_charge_indicator(current.as_milliamperes() > 20_f64)
.await;
}
//fallback to battery controller and ask it instead
else if let Ok(charging) = board
@@ -776,10 +770,10 @@ async fn update_charge_indicator(
.average_current_milli_ampere()
.await
{
let _ = board.board_hal.set_charge_indicator(charging > 20);
let _ = board.board_hal.set_charge_indicator(charging > 20).await;
} else {
//who knows
let _ = board.board_hal.set_charge_indicator(false);
let _ = board.board_hal.set_charge_indicator(false).await;
}
}
@@ -792,7 +786,11 @@ 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);
board
.board_hal
.get_esp()
.mqtt_publish("/water", &state)
.await;
}
async fn publish_plant_states(
@@ -819,78 +817,83 @@ async fn publish_plant_states(
async fn publish_firmware_info(
board: &mut MutexGuard<'_, CriticalSectionRawMutex, HAL<'static>>,
version: VersionInfo,
ip_address: &String,
timezone_time: &String,
ip_address: &str,
timezone_time: &str,
) {
let esp = board.board_hal.get_esp();
let _ = esp.mqtt_publish("/firmware/address", ip_address).await;
let _ = esp
.mqtt_publish("/firmware/state", format!("{:?}", &version).as_str())
esp.mqtt_publish("/firmware/address", ip_address).await;
esp.mqtt_publish("/firmware/state", format!("{:?}", &version).as_str())
.await;
let _ = esp.mqtt_publish("/firmware/last_online", timezone_time);
let _ = esp.mqtt_publish("/state", "online").await;
esp.mqtt_publish("/firmware/last_online", timezone_time)
.await;
esp.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));
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).await {
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.clone())
.await
{
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);
SntpMode::SYNC { current: new_time }
let _ = board
.board_hal
.get_rtc_module()
.set_rtc_time(&new_time)
.await;
SntpMode::Sync { current: new_time }
}
Err(err) => {
warn!("sntp error: {}", err);
warn!("sntp error: {err}");
board.board_hal.general_fault(true).await;
SntpMode::OFFLINE
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).await {
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);
warn!("Could not connect mqtt due to {err}");
false
}
}
} else {
false
};
NetworkMode::WIFI {
NetworkMode::Wifi {
sntp: sntp_mode,
mqtt: mqtt_connected,
ip_address: stack.hardware_address().to_string(),
}
}
Err(err) => {
info!("Offline mode due to {}", err);
info!("Offline mode due to {err}");
board.board_hal.general_fault(true).await;
NetworkMode::OFFLINE
NetworkMode::Offline
}
}
}
@@ -926,7 +929,7 @@ async fn pump_info(
.await;
}
Err(err) => {
warn!("Error publishing pump state {}", err);
warn!("Error publishing pump state {err}");
}
};
}
@@ -941,10 +944,11 @@ async fn publish_mppt_state(
voltage_ma: voltage.as_millivolts() as u32,
};
if let Ok(serialized_solar_state_bytes) = serde_json::to_string(&solar_state) {
let _ = board
board
.board_hal
.get_esp()
.mqtt_publish("/mppt", &serialized_solar_state_bytes);
.mqtt_publish("/mppt", &serialized_solar_state_bytes)
.await;
}
Ok(())
}
@@ -968,7 +972,7 @@ async fn publish_battery_state(
let _ = board
.board_hal
.get_esp()
.mqtt_publish("/battery", &*value)
.mqtt_publish("/battery", &value)
.await;
}
}
@@ -1054,7 +1058,7 @@ async fn wait_infinity(
}
}
#[esp_hal_embassy::main]
#[esp_rtos::main]
async fn main(spawner: Spawner) -> ! {
// intialize embassy
logger::init_logger_from_env();

View File

@@ -1,9 +1,5 @@
use crate::hal::Moistures;
use crate::{
config::PlantConfig,
hal::HAL,
in_time_range,
};
use crate::{config::PlantConfig, hal::HAL, in_time_range};
use chrono::{DateTime, TimeDelta, Utc};
use chrono_tz::Tz;
use serde::{Deserialize, Serialize};
@@ -76,7 +72,7 @@ impl PumpState {
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq)]
pub enum PlantWateringMode {
OFF,
Off,
TargetMoisture,
MinMoisture,
TimerOnly,
@@ -115,20 +111,28 @@ fn map_range_moisture(
}
impl PlantState {
pub async fn read_hardware_state(moistures: Moistures, plant_id: usize, board: &mut HAL<'_>) -> Self {
pub async fn read_hardware_state(
moistures: Moistures,
plant_id: usize,
board: &mut HAL<'_>,
) -> Self {
let sensor_a = if board.board_hal.get_config().plants[plant_id].sensor_a {
let raw = moistures.sensor_a_hz[plant_id];
match map_range_moisture(
raw,
board.board_hal.get_config().plants[plant_id].moisture_sensor_min_frequency,
board.board_hal.get_config().plants[plant_id].moisture_sensor_max_frequency,
) {
Ok(moisture_percent) => MoistureSensorState::MoistureValue {
raw_hz: raw,
moisture_percent,
},
Err(err) => MoistureSensorState::SensorError(err),
}
board.board_hal.get_config().plants[plant_id]
.moisture_sensor_min_frequency
.map(|a| a as f32),
board.board_hal.get_config().plants[plant_id]
.moisture_sensor_max_frequency
.map(|b| b as f32),
) {
Ok(moisture_percent) => MoistureSensorState::MoistureValue {
raw_hz: raw,
moisture_percent,
},
Err(err) => MoistureSensorState::SensorError(err),
}
} else {
MoistureSensorState::Disabled
};
@@ -137,8 +141,12 @@ impl PlantState {
let raw = moistures.sensor_b_hz[plant_id];
match map_range_moisture(
raw,
board.board_hal.get_config().plants[plant_id].moisture_sensor_min_frequency,
board.board_hal.get_config().plants[plant_id].moisture_sensor_max_frequency,
board.board_hal.get_config().plants[plant_id]
.moisture_sensor_min_frequency
.map(|a| a as f32),
board.board_hal.get_config().plants[plant_id]
.moisture_sensor_max_frequency
.map(|b| b as f32),
) {
Ok(moisture_percent) => MoistureSensorState::MoistureValue {
raw_hz: raw,
@@ -161,13 +169,13 @@ impl PlantState {
},
};
if state.is_err() {
let _ = board.board_hal.fault(plant_id, true);
let _ = board.board_hal.fault(plant_id, true).await;
}
state
}
pub fn pump_in_timeout(&self, plant_conf: &PlantConfig, current_time: &DateTime<Tz>) -> bool {
if matches!(plant_conf.mode, PlantWateringMode::OFF) {
if matches!(plant_conf.mode, PlantWateringMode::Off) {
return false;
}
self.pump.previous_pump.is_some_and(|last_pump| {
@@ -186,7 +194,7 @@ impl PlantState {
pub fn plant_moisture(
&self,
) -> (
Option<f32>,
Option<u8>,
(Option<&MoistureSensorError>, Option<&MoistureSensorError>),
) {
match (
@@ -194,10 +202,14 @@ impl PlantState {
self.sensor_b.moisture_percent(),
) {
(Some(moisture_a), Some(moisture_b)) => {
(Some((moisture_a + moisture_b) / 2.), (None, None))
(Some(((moisture_a + moisture_b) / 2.) as u8), (None, None))
}
(Some(moisture_percent), _) => {
(Some(moisture_percent as u8), (None, self.sensor_b.is_err()))
}
(_, Some(moisture_percent)) => {
(Some(moisture_percent as u8), (self.sensor_a.is_err(), None))
}
(Some(moisture_percent), _) => (Some(moisture_percent), (None, self.sensor_b.is_err())),
(_, Some(moisture_percent)) => (Some(moisture_percent), (self.sensor_a.is_err(), None)),
_ => (None, (self.sensor_a.is_err(), self.sensor_b.is_err())),
}
}
@@ -208,7 +220,7 @@ impl PlantState {
current_time: &DateTime<Tz>,
) -> bool {
match plant_conf.mode {
PlantWateringMode::OFF => false,
PlantWateringMode::Off => false,
PlantWateringMode::TargetMoisture => {
let (moisture_percent, _) = self.plant_moisture();
if let Some(moisture_percent) = moisture_percent {
@@ -229,28 +241,8 @@ impl PlantState {
}
}
PlantWateringMode::MinMoisture => {
let (moisture_percent, _) = self.plant_moisture();
if let Some(_moisture_percent) = moisture_percent {
if self.pump_in_timeout(plant_conf, current_time) {
false
} else if !in_time_range(
current_time,
plant_conf.pump_hour_start,
plant_conf.pump_hour_end,
) {
false
} else if true {
//if not cooldown min and below max
true
} else if true {
//if below min disable cooldown min
true
} else {
false
}
} else {
false
}
// TODO
false
}
PlantWateringMode::TimerOnly => !self.pump_in_timeout(plant_conf, current_time),
}

View File

@@ -1,7 +1,7 @@
use crate::alloc::string::{String, ToString};
use crate::config::TankConfig;
use crate::hal::HAL;
use crate::fat_error::FatResult;
use crate::hal::HAL;
use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
use embassy_sync::mutex::MutexGuard;
use serde::Serialize;
@@ -161,7 +161,7 @@ pub async fn determine_tank_state(
match board
.board_hal
.get_tank_sensor()
.and_then(|f| core::prelude::v1::Ok(f.tank_sensor_voltage()))
.map(|f| f.tank_sensor_voltage())
{
Ok(raw_sensor_value_mv) => TankState::Present(raw_sensor_value_mv.await.unwrap()),
Err(err) => TankState::Error(TankError::BoardError(err.to_string())),

View File

@@ -6,7 +6,7 @@ use alloc::format;
use alloc::string::{String, ToString};
use chrono::DateTime;
use edge_http::io::server::Connection;
use embedded_io_async::{Read, Write};
use edge_nal::io::{Read, Write};
use log::info;
use serde::{Deserialize, Serialize};
@@ -51,11 +51,8 @@ where
conn.initiate_response(
409,
Some(
format!(
"Checksum mismatch expected {} got {}",
expected_crc, actual_crc
)
.as_str(),
format!("Checksum mismatch expected {expected_crc} got {actual_crc}")
.as_str(),
),
&[],
)
@@ -131,7 +128,7 @@ where
let mut board = BOARD_ACCESS.get().await.lock().await;
board.board_hal.progress(counter).await;
counter = counter + 1;
counter += 1;
board
.board_hal
.get_rtc_module()
@@ -139,7 +136,7 @@ where
.await?;
checksum.update(&buf[0..to_write]);
}
offset = offset + to_write;
offset += to_write;
}
let mut board = BOARD_ACCESS.get().await.lock().await;

View File

@@ -6,7 +6,7 @@ use alloc::format;
use alloc::string::String;
use edge_http::io::server::Connection;
use edge_http::Method;
use embedded_io_async::{Read, Write};
use edge_nal::io::{Read, Write};
use log::info;
pub(crate) async fn list_files<T, const N: usize>(
@@ -27,7 +27,7 @@ where
T: Read + Write,
{
let filename = &path[prefix.len()..];
info!("file request for {} with method {}", filename, method);
info!("file request for {filename} with method {method}");
Ok(match method {
Method::Delete => {
let mut board = BOARD_ACCESS.get().await.lock().await;
@@ -65,7 +65,7 @@ where
&[
("Content-Type", "application/octet-stream"),
("Content-Disposition", disposition.as_str()),
("Content-Length", &format!("{}", size)),
("Content-Length", &format!("{size}")),
("Access-Control-Allow-Origin", "*"),
("Access-Control-Allow-Headers", "*"),
("Access-Control-Allow-Methods", "*"),
@@ -84,16 +84,16 @@ where
.await?;
let length = read_chunk.1;
if length == 0 {
info!("file request for {} finished", filename);
info!("file request for {filename} finished");
break;
}
let data = &read_chunk.0[0..length];
conn.write_all(data).await?;
if length < read_chunk.0.len() {
info!("file request for {} finished", filename);
info!("file request for {filename} finished");
break;
}
chunk = chunk + 1;
chunk += 1;
}
BOARD_ACCESS
.get()
@@ -120,8 +120,8 @@ where
let mut chunk = 0;
loop {
let buf = read_up_to_bytes_from_request(conn, Some(4096)).await?;
if buf.len() == 0 {
info!("file request for {} finished", filename);
if buf.is_empty() {
info!("file request for {filename} finished");
break;
} else {
let mut board = BOARD_ACCESS.get().await.lock().await;
@@ -132,8 +132,8 @@ where
.write_file(filename.to_owned(), offset as u32, &buf)
.await?;
}
offset = offset + buf.len();
chunk = chunk + 1;
offset += buf.len();
chunk += 1;
}
BOARD_ACCESS
.get()

View File

@@ -1,4 +1,3 @@
use core::str::FromStr;
use crate::fat_error::{FatError, FatResult};
use crate::hal::{esp_time, PLANT_COUNT};
use crate::log::LogMessage;
@@ -9,8 +8,9 @@ use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use chrono_tz::Tz;
use core::str::FromStr;
use edge_http::io::server::Connection;
use embedded_io_async::{Read, Write};
use edge_nal::io::{Read, Write};
use log::info;
use serde::Serialize;
@@ -142,21 +142,15 @@ pub(crate) async fn get_time<T, const N: usize>(
let mut board = BOARD_ACCESS.get().await.lock().await;
let conf = board.board_hal.get_config();
let tz:Tz = match conf.timezone.as_ref(){
None => {
Tz::UTC
}
Some(tz_string) => {
match Tz::from_str(tz_string) {
Ok(tz) => {
tz
}
Err(err) => {
info!("failed parsing timezone {}", err);
Tz::UTC
}
let tz: Tz = match conf.timezone.as_ref() {
None => Tz::UTC,
Some(tz_string) => match Tz::from_str(tz_string) {
Ok(tz) => tz,
Err(err) => {
info!("failed parsing timezone {err}");
Tz::UTC
}
}
},
};
let native = esp_time().await.with_timezone(&tz).to_rfc3339();
@@ -164,7 +158,7 @@ pub(crate) async fn get_time<T, const N: usize>(
let rtc = match board.board_hal.get_rtc_module().get_rtc_time().await {
Ok(time) => time.with_timezone(&tz).to_rfc3339(),
Err(err) => {
format!("Error getting time: {}", err)
format!("Error getting time: {err}")
}
};

View File

@@ -1,7 +1,7 @@
use crate::fat_error::FatResult;
use crate::log::LOG_ACCESS;
use edge_http::io::server::Connection;
use embedded_io_async::{Read, Write};
use edge_nal::io::{Read, Write};
pub(crate) async fn get_log<T, const N: usize>(
conn: &mut Connection<'_, T, N>,

View File

@@ -1,6 +1,6 @@
use crate::fat_error::FatError;
use edge_http::io::server::Connection;
use embedded_io_async::{Read, Write};
use edge_nal::io::{Read, Write};
pub(crate) async fn serve_favicon<T, const N: usize>(
conn: &mut Connection<'_, T, { N }>,

View File

@@ -19,7 +19,7 @@ use crate::webserver::get_log::get_log;
use crate::webserver::get_static::{serve_bundle, serve_favicon, serve_index};
use crate::webserver::ota::ota_operations;
use crate::webserver::post_json::{
board_test, night_lamp_test, pump_test, set_config, wifi_scan, write_time, detect_sensors,
board_test, detect_sensors, night_lamp_test, pump_test, set_config, wifi_scan, write_time,
};
use crate::{bail, BOARD_ACCESS};
use alloc::borrow::ToOwned;
@@ -32,11 +32,11 @@ use core::result::Result::Ok;
use core::sync::atomic::{AtomicBool, Ordering};
use edge_http::io::server::{Connection, Handler, Server};
use edge_http::Method;
use edge_nal::io::{Read, Write};
use edge_nal::TcpBind;
use edge_nal_embassy::{Tcp, TcpBuffers};
use embassy_net::Stack;
use embassy_time::Instant;
use embedded_io_async::{Read, Write};
use log::{error, info};
struct HTTPRequestRouter {
@@ -64,7 +64,7 @@ impl Handler for HTTPRequestRouter {
file_operations(conn, method, &path, &prefix).await?
} else if path == "/ota" {
ota_operations(conn, method).await.map_err(|e| {
error!("Error handling ota: {}", e);
error!("Error handling ota: {e}");
e
})?
} else {
@@ -203,7 +203,7 @@ async fn handle_json<'a, T, const N: usize>(
) -> FatResult<u32>
where
T: Read + Write,
<T as embedded_io_async::ErrorType>::Error: Debug,
<T as edge_nal::io::ErrorType>::Error: Debug,
{
match chain {
Ok(answer) => match answer {
@@ -238,7 +238,7 @@ where
},
Err(err) => {
let error_text = err.to_string();
info!("error handling process {}", error_text);
info!("error handling process {error_text}");
conn.initiate_response(
500,
Some("OK"),

View File

@@ -3,7 +3,7 @@ use crate::webserver::read_up_to_bytes_from_request;
use crate::BOARD_ACCESS;
use edge_http::io::server::Connection;
use edge_http::Method;
use embedded_io_async::{Read, Write};
use edge_nal::io::{Read, Write};
use log::info;
pub(crate) async fn ota_operations<T, const N: usize>(
@@ -32,7 +32,7 @@ where
let mut chunk = 0;
loop {
let buf = read_up_to_bytes_from_request(conn, Some(4096)).await?;
if buf.len() == 0 {
if buf.is_empty() {
info!("file request for ota finished");
let mut board = BOARD_ACCESS.get().await.lock().await;
board.board_hal.get_esp().finalize_ota().await?;
@@ -45,11 +45,11 @@ where
board
.board_hal
.get_esp()
.write_ota(offset as u32, &*buf)
.write_ota(offset as u32, &buf)
.await?;
}
offset = offset + buf.len();
chunk = chunk + 1;
offset += buf.len();
chunk += 1;
}
BOARD_ACCESS
.get()

View File

@@ -7,7 +7,7 @@ use alloc::string::{String, ToString};
use alloc::vec::Vec;
use chrono::DateTime;
use edge_http::io::server::Connection;
use embedded_io_async::{Read, Write};
use edge_nal::io::{Read, Write};
use log::info;
use serde::{Deserialize, Serialize};
@@ -113,7 +113,7 @@ where
let mut board = BOARD_ACCESS.get().await.lock().await;
board.board_hal.get_esp().save_config(all).await?;
info!("Wrote config config {:?} with size {}", config, length);
info!("Wrote config config {config:?} with size {length}");
board.board_hal.set_config(config);
Ok(Some("Ok".to_string()))
}

View File

@@ -4565,6 +4565,7 @@
"integrity": "sha512-pIDJHIEI9LR0yxHXQ+Qh95k2EvXpWzZ5l+d+jIo+RdSm9MiHfzazIxwwni/p7+x4eJZuvG1AJwgC4TNQ7NRgsg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@discoveryjs/json-ext": "^0.5.0",
"@webpack-cli/configtest": "^2.1.1",

View File

@@ -84,7 +84,7 @@ export enum BatteryBoardVersion {
}
export enum BoardVersion {
INITIAL = "INITIAL",
Initial = "Initial",
V3 = "V3",
V4 = "V4"
}
@@ -112,6 +112,7 @@ export interface PlantConfig {
pump_cooldown_min: number,
pump_hour_start: number,
pump_hour_end: number,
pump_limit_ml: number,
sensor_a: boolean,
sensor_b: boolean,
max_consecutive_pump_count: number,
@@ -200,4 +201,4 @@ export interface TankInfo {
/// water temperature
water_temp: number | null,
temp_sensor_error: string | null
}
}

View File

@@ -12,7 +12,7 @@ export class HardwareConfigView {
Object.keys(BoardVersion).forEach(version => {
let option = document.createElement("option");
if (version == BoardVersion.INITIAL.toString()){
if (version == BoardVersion.Initial.toString()){
option.selected = true
}
option.innerText = version.toString();
@@ -42,4 +42,4 @@ export class HardwareConfigView {
battery : BatteryBoardVersion[this.hardware_battery_value.value as keyof typeof BatteryBoardVersion],
}
}
}
}

View File

@@ -296,6 +296,7 @@ export class Controller {
configChanged() {
const current = controller.getConfig();
var pretty = JSON.stringify(current, undefined, 0);
controller.submitView.setJson(pretty);

View File

@@ -53,7 +53,7 @@
Mode:
</div>
<select class="plantvalue" id="plant_${plantId}_mode">
<option value="OFF">Off</option>
<option value="Off">Off</option>
<option value="TargetMoisture">Target</option>
<option value="MinMoisture">Min Moisture</option>
<option value="TimerOnly">Timer</option>

View File

@@ -213,7 +213,7 @@ export class PlantView {
console.log("updateVisibility plantConfig: " + plantConfig.mode)
let showSensor = plantConfig.sensor_a || plantConfig.sensor_b
let showPump = plantConfig.mode !== "OFF"
let showPump = plantConfig.mode !== "Off"
let showTarget = plantConfig.mode === "TargetMoisture"
let showMin = plantConfig.mode === "MinMoisture"
@@ -299,6 +299,7 @@ export class PlantView {
target_moisture: this.targetMoisture.valueAsNumber,
min_moisture: this.minMoisture.valueAsNumber,
pump_time_s: this.pumpTimeS.valueAsNumber,
pump_limit_ml: 5000,
pump_cooldown_min: this.pumpCooldown.valueAsNumber,
pump_hour_start: +this.pumpHourStart.value,
pump_hour_end: +this.pumpHourEnd.value,

View File

@@ -10,7 +10,7 @@ console.log("Dev server is " + isDevServer);
var host;
if (isDevServer) {
//ensure no trailing /
host = 'http://10.23.44.186';
host = 'http://192.168.1.105';
} else {
host = '';
}

8
Software/Shared/canapi/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,8 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

11
Software/Shared/canapi/.idea/canapi.iml generated Normal file
View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="EMPTY_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<excludeFolder url="file://$MODULE_DIR$/target" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/canapi.iml" filepath="$PROJECT_DIR$/.idea/canapi.iml" />
</modules>
</component>
</project>

7
Software/Shared/canapi/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../../.." vcs="Git" />
<mapping directory="$PROJECT_DIR$/../../../website/themes/blowfish" vcs="Git" />
</component>
</project>

View File

@@ -44,7 +44,6 @@ pub mod id {
pub const MOISTURE_DATA_OFFSET: u16 = 0; // periodic data from sensor (sensor -> controller)
pub const IDENTIFY_CMD_OFFSET: u16 = 32; // identify LED command (controller -> sensor)
#[inline]
pub const fn plant_id(message_type_offset: u16, sensor: SensorSlot, plant: u16) -> u16 {
match sensor {
@@ -56,8 +55,8 @@ pub mod id {
/// Kinds of message spaces recognized by the addressing scheme.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MessageKind {
MoistureData, // sensor -> controller
IdentifyCmd, // controller -> sensor
MoistureData, // sensor -> controller
IdentifyCmd, // controller -> sensor
}
/// Try to classify a received 11-bit standard ID into a known message kind and extract plant and sensor slot.
@@ -72,11 +71,15 @@ pub mod id {
// Helper: decode within a given group offset
const fn decode_in_group(rel: u16, group_base: u16) -> Option<(u8, SensorSlot)> {
if rel < group_base { return None; }
if rel < group_base {
return None;
}
let inner = rel - group_base;
if inner < PLANTS_PER_GROUP { // A slot
if inner < PLANTS_PER_GROUP {
// A slot
Some((inner as u8, SensorSlot::A))
} else if inner >= B_OFFSET && inner < B_OFFSET + PLANTS_PER_GROUP { // B slot
} else if inner >= B_OFFSET && inner < B_OFFSET + PLANTS_PER_GROUP {
// B slot
Some(((inner - B_OFFSET) as u8, SensorSlot::B))
} else {
None
@@ -118,9 +121,9 @@ pub mod id {
/// Fits into 5 bytes with bincode-v2 (no varint): u8 + u8 + u16 = 4, alignment may keep 4.
#[derive(Debug, Clone, Copy, Encode, Decode)]
pub struct MoistureData {
pub plant: u8, // 0..MAX_PLANTS-1
pub plant: u8, // 0..MAX_PLANTS-1
pub sensor: SensorSlot, // A/B
pub hz: u16, // measured frequency of moisture sensor
pub hz: u16, // measured frequency of moisture sensor
}
/// Request a sensor to report immediately (controller -> sensor).

View File

@@ -0,0 +1,10 @@
#!/usr/bin/env bash
set -euo pipefail
CONTAINER_NAME="localhost/esp-plant-dev-tools:latest"
CONTAINER_TOOLS_BASEDIR="$(dirname "$(readlink -f "$0")")"
pushd "$CONTAINER_TOOLS_BASEDIR"
podman build -t "$CONTAINER_NAME" -f "esp-plant-dev-tools.Containerfile" .
popd

View File

@@ -0,0 +1,16 @@
FROM debian:latest
RUN apt update -y && apt upgrade -y && apt install unzip curl xz-utils nodejs -y
RUN cd /root && \
curl -L -o xpack-riscv-toolchain.tar.gz "https://github.com/xpack-dev-tools/riscv-none-elf-gcc-xpack/releases/download/v14.2.0-3/xpack-riscv-none-elf-gcc-14.2.0-3-linux-x64.tar.gz" && \
mkdir xpack-toolchain && \
tar -xvf xpack-riscv-toolchain.tar.gz -C xpack-toolchain --strip-components=1 && \
mv xpack-toolchain/bin/* /usr/local/bin && \
mv xpack-toolchain/lib/ /usr/local && \
mv xpack-toolchain/lib64/ /usr/local && \
mv xpack-toolchain/libexec /usr/local && \
mv xpack-toolchain/riscv-none-elf /usr/local && \
rm -rf xpack-toolchain xpack-riscv-toolchain.tar.gz
RUN apt install npm -y

29
bin/npm Executable file
View File

@@ -0,0 +1,29 @@
#!/usr/bin/env bash
set -euo pipefail
CONTAINER_IMAGE="localhost/esp-plant-dev-tools:latest"
CONTAINER_TOOLS_BASEDIR="$(dirname "$(readlink -f "$0")")"
PLANTCTL_PROJECT_DIR="$(readlink -f "$CONTAINER_TOOLS_BASEDIR/..")"
function _fatal {
echo -e "\e[31mERROR\e[0m $(</dev/stdin)$*" 1>&2
exit 1
}
declare -a PODMAN_ARGS=(
"--rm" "-i" "--log-driver=none"
"-v" "$PLANTCTL_PROJECT_DIR:$PLANTCTL_PROJECT_DIR:rw"
"-v" "$PWD:$PWD:rw"
"-w" "$PWD"
)
[[ -t 1 ]] && PODMAN_ARGS+=("-t")
if ! podman image exists "$CONTAINER_IMAGE"; then
#attempt to build container
"$CONTAINER_TOOLS_BASEDIR/build-esp-plant-dev-tools.sh" 1>&2 ||
_fatal "faild to build local image, cannot continue! … please ensure you have an internet connection"
fi
podman run "${PODMAN_ARGS[@]}" --entrypoint npm "$CONTAINER_IMAGE" "$@"

29
bin/npx Executable file
View File

@@ -0,0 +1,29 @@
#!/usr/bin/env bash
set -euo pipefail
CONTAINER_IMAGE="localhost/esp-plant-dev-tools:latest"
CONTAINER_TOOLS_BASEDIR="$(dirname "$(readlink -f "$0")")"
PLANTCTL_PROJECT_DIR="$(readlink -f "$CONTAINER_TOOLS_BASEDIR/..")"
function _fatal {
echo -e "\e[31mERROR\e[0m $(</dev/stdin)$*" 1>&2
exit 1
}
declare -a PODMAN_ARGS=(
"--rm" "-i" "--log-driver=none"
"-v" "$PLANTCTL_PROJECT_DIR:$PLANTCTL_PROJECT_DIR:rw"
"-v" "$PWD:$PWD:rw"
"-w" "$PWD"
)
[[ -t 1 ]] && PODMAN_ARGS+=("-t")
if ! podman image exists "$CONTAINER_IMAGE"; then
#attempt to build container
"$CONTAINER_TOOLS_BASEDIR/build-esp-plant-dev-tools.sh" 1>&2 ||
_fatal "faild to build local image, cannot continue! … please ensure you have an internet connection"
fi
podman run "${PODMAN_ARGS[@]}" --entrypoint npx "$CONTAINER_IMAGE" "$@"

29
bin/riscv32-unknown-elf-gcc Executable file
View File

@@ -0,0 +1,29 @@
#!/usr/bin/env bash
set -euo pipefail
CONTAINER_IMAGE="localhost/esp-plant-dev-tools:latest"
CONTAINER_TOOLS_BASEDIR="$(dirname "$(readlink -f "$0")")"
PLANTCTL_PROJECT_DIR="$(readlink -f "$CONTAINER_TOOLS_BASEDIR/..")"
function _fatal {
echo -e "\e[31mERROR\e[0m $(</dev/stdin)$*" 1>&2
exit 1
}
declare -a PODMAN_ARGS=(
"--rm" "-i" "--log-driver=none"
"-v" "$PLANTCTL_PROJECT_DIR:$PLANTCTL_PROJECT_DIR:rw"
"-v" "$PWD:$PWD:rw"
"-w" "$PWD"
)
[[ -t 1 ]] && PODMAN_ARGS+=("-t")
if ! podman image exists "$CONTAINER_IMAGE"; then
#attempt to build container
"$CONTAINER_TOOLS_BASEDIR/build-esp-plant-dev-tools.sh" 1>&2 ||
_fatal "faild to build local image, cannot continue! … please ensure you have an internet connection"
fi
podman run "${PODMAN_ARGS[@]}" --entrypoint riscv-none-elf-gcc "$CONTAINER_IMAGE" "$@"

124
rust/build.rs Normal file
View File

@@ -0,0 +1,124 @@
use std::{collections::VecDeque, env, process::Command};
use vergen::EmitBuilder;
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() {
"_defmt_timestamp" => {
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!();
}
"esp_wifi_preempt_enable"
| "esp_wifi_preempt_yield_task"
| "esp_wifi_preempt_task_create" => {
eprintln!();
eprintln!("💡 `esp-wifi` has no scheduler enabled. Make sure you have the `builtin-scheduler` feature enabled, or that you provide 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!();
}
_ => (),
},
// we don't have anything helpful for "missing-lib" yet
_ => {
std::process::exit(1);
}
}
std::process::exit(0);
}
println!(
"cargo:rustc-link-arg=--error-handling-script={}",
std::env::current_exe().unwrap().display()
);
}
fn main() {
if Command::new("podman").arg("--version").output().is_err() {
println!("Could not find `podman` installation, assuming the developer has setup all required tool for build manually! … ")
}
webpack();
linker_be_nice();
let _ = EmitBuilder::builder().all_git().all_build().emit();
}
fn webpack() {
//println!("cargo:rerun-if-changed=./src/src_webpack");
Command::new("rm")
.arg("./src/webserver/bundle.js.gz")
.output()
.unwrap();
match Command::new("cmd").spawn() {
Ok(_) => {
println!("Assuming build on windows");
let output = Command::new("cmd")
.arg("/K")
.arg("npx")
.arg("webpack")
.current_dir("./src_webpack")
.output()
.unwrap();
println!("status: {}", output.status);
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
assert!(output.status.success());
// move webpack results to rust webserver src
let _ = Command::new("cmd")
.arg("/K")
.arg("move")
.arg("./src_webpack/bundle.js.gz")
.arg("./src/webserver")
.output()
.unwrap();
let _ = Command::new("cmd")
.arg("/K")
.arg("move")
.arg("./src_webpack/index.html.gz")
.arg("./src/webserver")
.output()
.unwrap();
}
Err(_) => {
println!("Assuming build on linux");
let output = Command::new("npx")
.arg("webpack")
.current_dir("./src_webpack")
.output()
.unwrap();
println!("status: {}", output.status);
println!("stdout: {}", String::from_utf8_lossy(&output.stdout));
println!("stderr: {}", String::from_utf8_lossy(&output.stderr));
assert!(output.status.success());
// move webpack results to rust webserver src
let _ = Command::new("mv")
.arg("./src_webpack/bundle.js.gz")
.arg("./src/webserver")
.output()
.unwrap();
let _ = Command::new("mv")
.arg("./src_webpack/index.html.gz")
.arg("./src/webserver")
.output()
.unwrap();
}
}
}