it's alive

This commit is contained in:
2025-09-13 01:39:47 +02:00
parent 79087c9353
commit 9de85b6e37
19 changed files with 1567 additions and 1488 deletions

434
rust/scratch/v3_hal.rs Normal file
View File

@@ -0,0 +1,434 @@
use crate::hal::rtc::RTCModuleInteraction;
use crate::hal::water::TankSensor;
use crate::hal::{
deep_sleep, BoardInteraction, FreePeripherals, Sensor, PLANT_COUNT,
};
use crate::log::{log, LogMessage};
use crate::{
config::PlantControllerConfig,
hal::{battery::BatteryInteraction, esp::Esp},
};
use anyhow::{bail, Ok, Result};
use embedded_hal::digital::OutputPin;
use measurements::{Current, Voltage};
use plant_ctrl2::sipo::ShiftRegister40;
use core::result::Result::Ok as OkStd;
use alloc::string::ToString;
use alloc::boxed::Box;
use esp_hall::gpio::Pull;
const PUMP8_BIT: usize = 0;
const PUMP1_BIT: usize = 1;
const PUMP2_BIT: usize = 2;
const PUMP3_BIT: usize = 3;
const PUMP4_BIT: usize = 4;
const PUMP5_BIT: usize = 5;
const PUMP6_BIT: usize = 6;
const PUMP7_BIT: usize = 7;
const MS_0: usize = 8;
const MS_4: usize = 9;
const MS_2: usize = 10;
const MS_3: usize = 11;
const MS_1: usize = 13;
const SENSOR_ON: usize = 12;
const SENSOR_A_1: u8 = 7;
const SENSOR_A_2: u8 = 6;
const SENSOR_A_3: u8 = 5;
const SENSOR_A_4: u8 = 4;
const SENSOR_A_5: u8 = 3;
const SENSOR_A_6: u8 = 2;
const SENSOR_A_7: u8 = 1;
const SENSOR_A_8: u8 = 0;
const SENSOR_B_1: u8 = 8;
const SENSOR_B_2: u8 = 9;
const SENSOR_B_3: u8 = 10;
const SENSOR_B_4: u8 = 11;
const SENSOR_B_5: u8 = 12;
const SENSOR_B_6: u8 = 13;
const SENSOR_B_7: u8 = 14;
const SENSOR_B_8: u8 = 15;
const CHARGING: usize = 14;
const AWAKE: usize = 15;
const FAULT_3: usize = 16;
const FAULT_8: usize = 17;
const FAULT_7: usize = 18;
const FAULT_6: usize = 19;
const FAULT_5: usize = 20;
const FAULT_4: usize = 21;
const FAULT_1: usize = 22;
const FAULT_2: usize = 23;
const REPEAT_MOIST_MEASURE: usize = 1;
pub struct V3<'a> {
config: PlantControllerConfig,
battery_monitor: Box<dyn BatteryInteraction + Send>,
rtc_module: Box<dyn RTCModuleInteraction + Send>,
esp: Esp<'a>,
shift_register: ShiftRegister40<
PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
>,
_shift_register_enable_invert:
PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, esp_idf_hal::gpio::Output>,
tank_sensor: TankSensor<'a>,
solar_is_day: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, esp_idf_hal::gpio::Input>,
light: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
main_pump: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
general_fault: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
signal_counter: PcntDriver<'a>,
}
pub(crate) fn create_v3(
peripherals: FreePeripherals,
esp: Esp<'static>,
config: PlantControllerConfig,
battery_monitor: Box<dyn BatteryInteraction + Send>,
rtc_module: Box<dyn RTCModuleInteraction + Send>,
) -> Result<Box<dyn BoardInteraction<'static> + Send>> {
log::info!("Start v3");
let mut clock = PinDriver::input_output(peripherals.gpio15.downgrade())?;
clock.set_pull(Pull::Floating)?;
let mut latch = PinDriver::input_output(peripherals.gpio3.downgrade())?;
latch.set_pull(Pull::Floating)?;
let mut data = PinDriver::input_output(peripherals.gpio23.downgrade())?;
data.set_pull(Pull::Floating)?;
let shift_register = ShiftRegister40::new(clock, latch, data);
//disable all
for mut pin in shift_register.decompose() {
pin.set_low()?;
}
let awake = &mut shift_register.decompose()[AWAKE];
awake.set_high()?;
let charging = &mut shift_register.decompose()[CHARGING];
charging.set_high()?;
let ms0 = &mut shift_register.decompose()[MS_0];
ms0.set_low()?;
let ms1 = &mut shift_register.decompose()[MS_1];
ms1.set_low()?;
let ms2 = &mut shift_register.decompose()[MS_2];
ms2.set_low()?;
let ms3 = &mut shift_register.decompose()[MS_3];
ms3.set_low()?;
let ms4 = &mut shift_register.decompose()[MS_4];
ms4.set_high()?;
let one_wire_pin = peripherals.gpio18.downgrade();
let tank_power_pin = peripherals.gpio11.downgrade();
let flow_sensor_pin = peripherals.gpio4.downgrade();
let tank_sensor = TankSensor::create(
one_wire_pin,
peripherals.adc1,
peripherals.gpio5,
tank_power_pin,
flow_sensor_pin,
peripherals.pcnt1,
)?;
let mut signal_counter = PcntDriver::new(
peripherals.pcnt0,
Some(peripherals.gpio22),
Option::<AnyInputPin>::None,
Option::<AnyInputPin>::None,
Option::<AnyInputPin>::None,
)?;
signal_counter.channel_config(
PcntChannel::Channel0,
PinIndex::Pin0,
PinIndex::Pin1,
&PcntChannelConfig {
lctrl_mode: PcntControlMode::Keep,
hctrl_mode: PcntControlMode::Keep,
pos_mode: PcntCountMode::Increment,
neg_mode: PcntCountMode::Hold,
counter_h_lim: i16::MAX,
counter_l_lim: 0,
},
)?;
let mut solar_is_day = PinDriver::input(peripherals.gpio7.downgrade())?;
solar_is_day.set_pull(Pull::Floating)?;
let mut light = PinDriver::input_output(peripherals.gpio10.downgrade())?;
light.set_pull(Pull::Floating)?;
let mut main_pump = PinDriver::input_output(peripherals.gpio2.downgrade())?;
main_pump.set_pull(Pull::Floating)?;
main_pump.set_low()?;
let mut general_fault = PinDriver::input_output(peripherals.gpio6.downgrade())?;
general_fault.set_pull(Pull::Floating)?;
general_fault.set_low()?;
let mut shift_register_enable_invert = PinDriver::output(peripherals.gpio21.downgrade())?;
unsafe { gpio_hold_dis(shift_register_enable_invert.pin()) };
shift_register_enable_invert.set_low()?;
unsafe { gpio_hold_en(shift_register_enable_invert.pin()) };
Ok(Box::new(V3 {
config,
battery_monitor,
rtc_module,
esp,
shift_register,
_shift_register_enable_invert: shift_register_enable_invert,
tank_sensor,
solar_is_day,
light,
main_pump,
general_fault,
signal_counter,
}))
}
impl<'a> BoardInteraction<'a> for V3<'a> {
fn get_tank_sensor(&mut self) -> Option<&mut TankSensor<'a>> {
Some(&mut self.tank_sensor)
}
fn get_esp(&mut self) -> &mut Esp<'a> {
&mut self.esp
}
fn get_config(&mut self) -> &PlantControllerConfig {
&self.config
}
fn get_battery_monitor(&mut self) -> &mut Box<dyn BatteryInteraction + Send + 'static> {
&mut self.battery_monitor
}
fn get_rtc_module(&mut self) -> &mut Box<dyn RTCModuleInteraction + Send> {
&mut self.rtc_module
}
fn set_charge_indicator(&mut self, charging: bool) -> Result<()> {
Ok(self.shift_register.decompose()[CHARGING].set_state(charging.into())?)
}
fn deep_sleep(&mut self, duration_in_ms: u64) -> ! {
let _ = self.shift_register.decompose()[AWAKE].set_low();
deep_sleep(duration_in_ms)
}
fn is_day(&self) -> bool {
self.solar_is_day.get_level().into()
}
fn light(&mut self, enable: bool) -> Result<()> {
unsafe { gpio_hold_dis(self.light.pin()) };
self.light.set_state(enable.into())?;
unsafe { gpio_hold_en(self.light.pin()) };
Ok(())
}
fn pump(&mut self, plant: usize, enable: bool) -> Result<()> {
if enable {
self.main_pump.set_high()?;
}
let index = match plant {
0 => PUMP1_BIT,
1 => PUMP2_BIT,
2 => PUMP3_BIT,
3 => PUMP4_BIT,
4 => PUMP5_BIT,
5 => PUMP6_BIT,
6 => PUMP7_BIT,
7 => PUMP8_BIT,
_ => bail!("Invalid pump {plant}",),
};
self.shift_register.decompose()[index].set_state(enable.into())?;
if !enable {
self.main_pump.set_low()?;
}
Ok(())
}
fn pump_current(&mut self, _plant: usize) -> Result<Current> {
bail!("Not implemented in v3")
}
fn fault(&mut self, plant: usize, enable: bool) -> Result<()> {
let index = match plant {
0 => FAULT_1,
1 => FAULT_2,
2 => FAULT_3,
3 => FAULT_4,
4 => FAULT_5,
5 => FAULT_6,
6 => FAULT_7,
7 => FAULT_8,
_ => panic!("Invalid plant id {}", plant),
};
self.shift_register.decompose()[index].set_state(enable.into())?;
Ok(())
}
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> Result<f32> {
let mut results = [0_f32; REPEAT_MOIST_MEASURE];
for repeat in 0..REPEAT_MOIST_MEASURE {
self.signal_counter.counter_pause()?;
self.signal_counter.counter_clear()?;
//Disable all
self.shift_register.decompose()[MS_4].set_high()?;
let sensor_channel = match sensor {
Sensor::A => match plant {
0 => SENSOR_A_1,
1 => SENSOR_A_2,
2 => SENSOR_A_3,
3 => SENSOR_A_4,
4 => SENSOR_A_5,
5 => SENSOR_A_6,
6 => SENSOR_A_7,
7 => SENSOR_A_8,
_ => bail!("Invalid plant id {}", plant),
},
Sensor::B => match plant {
0 => SENSOR_B_1,
1 => SENSOR_B_2,
2 => SENSOR_B_3,
3 => SENSOR_B_4,
4 => SENSOR_B_5,
5 => SENSOR_B_6,
6 => SENSOR_B_7,
7 => SENSOR_B_8,
_ => bail!("Invalid plant id {}", plant),
},
};
let is_bit_set = |b: u8| -> bool { sensor_channel & (1 << b) != 0 };
let pin_0 = &mut self.shift_register.decompose()[MS_0];
let pin_1 = &mut self.shift_register.decompose()[MS_1];
let pin_2 = &mut self.shift_register.decompose()[MS_2];
let pin_3 = &mut self.shift_register.decompose()[MS_3];
if is_bit_set(0) {
pin_0.set_high()?;
} else {
pin_0.set_low()?;
}
if is_bit_set(1) {
pin_1.set_high()?;
} else {
pin_1.set_low()?;
}
if is_bit_set(2) {
pin_2.set_high()?;
} else {
pin_2.set_low()?;
}
if is_bit_set(3) {
pin_3.set_high()?;
} else {
pin_3.set_low()?;
}
self.shift_register.decompose()[MS_4].set_low()?;
self.shift_register.decompose()[SENSOR_ON].set_high()?;
let measurement = 100; //how long to measure and then extrapolate to hz
let factor = 1000f32 / measurement as f32; //scale raw cound by this number to get hz
//give some time to stabilize
self.esp.delay.delay_ms(10);
self.signal_counter.counter_resume()?;
self.esp.delay.delay_ms(measurement);
self.signal_counter.counter_pause()?;
self.shift_register.decompose()[MS_4].set_high()?;
self.shift_register.decompose()[SENSOR_ON].set_low()?;
self.esp.delay.delay_ms(10);
let unscaled = self.signal_counter.get_counter_value()? as i32;
let hz = unscaled as f32 * factor;
log(
LogMessage::RawMeasure,
unscaled as u32,
hz as u32,
&plant.to_string(),
&format!("{sensor:?}"),
);
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)
}
fn general_fault(&mut self, enable: bool) {
unsafe { gpio_hold_dis(self.general_fault.pin()) };
self.general_fault.set_state(enable.into()).unwrap();
unsafe { gpio_hold_en(self.general_fault.pin()) };
}
fn test(&mut self) -> Result<()> {
self.general_fault(true);
self.esp.delay.delay_ms(100);
self.general_fault(false);
self.esp.delay.delay_ms(100);
self.light(true)?;
self.esp.delay.delay_ms(500);
self.light(false)?;
self.esp.delay.delay_ms(500);
for i in 0..PLANT_COUNT {
self.fault(i, true)?;
self.esp.delay.delay_ms(500);
self.fault(i, false)?;
self.esp.delay.delay_ms(500);
}
for i in 0..PLANT_COUNT {
self.pump(i, true)?;
self.esp.delay.delay_ms(100);
self.pump(i, false)?;
self.esp.delay.delay_ms(100);
}
for plant in 0..PLANT_COUNT {
let a = self.measure_moisture_hz(plant, Sensor::A);
let b = self.measure_moisture_hz(plant, Sensor::B);
let aa = match a {
OkStd(a) => a as u32,
Err(_) => u32::MAX,
};
let bb = match b {
OkStd(b) => b as u32,
Err(_) => u32::MAX,
};
log(LogMessage::TestSensor, aa, bb, &plant.to_string(), "");
}
self.esp.delay.delay_ms(10);
Ok(())
}
fn set_config(&mut self, config: PlantControllerConfig) -> Result<()> {
self.config = config;
self.esp.save_config(&self.config)?;
anyhow::Ok(())
}
fn get_mptt_voltage(&mut self) -> Result<Voltage> {
//assuming module to work, these are the hardware set values
if self.is_day() {
Ok(Voltage::from_volts(15_f64))
} else {
Ok(Voltage::from_volts(0_f64))
}
}
fn get_mptt_current(&mut self) -> Result<Current> {
bail!("Board does not have current sensor")
}
}

440
rust/scratch/v4_hal.rs Normal file
View File

@@ -0,0 +1,440 @@
use crate::config::PlantControllerConfig;
use crate::hal::battery::BatteryInteraction;
use crate::hal::esp::Esp;
use crate::hal::rtc::RTCModuleInteraction;
use crate::hal::v4_sensor::SensorImpl;
use crate::hal::v4_sensor::SensorInteraction;
use crate::hal::water::TankSensor;
use crate::hal::{
deep_sleep, BoardInteraction, FreePeripherals, Sensor, I2C_DRIVER, PLANT_COUNT
};
use crate::log::{log, LogMessage};
use anyhow::bail;
use embedded_hal::digital::OutputPin;
use embedded_hal_bus::i2c::MutexDevice;
use ina219::address::{Address, Pin};
use ina219::calibration::UnCalibrated;
use ina219::configuration::{Configuration, OperatingMode};
use ina219::SyncIna219;
use measurements::{Current, Resistance, Voltage};
use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
use std::result::Result::Ok as OkStd;
use embedded_can::Frame;
use embedded_can::StandardId;
use alloc::string::ToString;
use alloc::boxed::Box;
use esp_hal::gpio::Pull;
pub enum Charger<'a> {
SolarMpptV1 {
mppt_ina: SyncIna219<MutexDevice<'a, I2cDriver<'a>>, UnCalibrated>,
solar_is_day: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, esp_idf_hal::gpio::Input>,
charge_indicator: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
},
ErrorInit {},
}
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
);
});
}
_ => {}
}
}
fn set_charge_indicator(&mut self, charging: bool) -> anyhow::Result<()> {
match self {
Self::SolarMpptV1 {
charge_indicator, ..
} => {
charge_indicator.set_state(charging.into())?;
}
_ => {}
}
Ok(())
}
fn is_day(&self) -> bool {
match self {
Charger::SolarMpptV1 { solar_is_day, .. } => solar_is_day.get_level().into(),
_ => true,
}
}
fn get_mptt_voltage(&mut self) -> anyhow::Result<Voltage> {
let voltage = match self {
Charger::SolarMpptV1 { mppt_ina, .. } => mppt_ina
.bus_voltage()
.map(|v| Voltage::from_millivolts(v.voltage_mv() as f64))?,
_ => {
bail!("hardware error during init")
}
};
Ok(voltage)
}
fn get_mptt_current(&mut self) -> anyhow::Result<Current> {
let current = match self {
Charger::SolarMpptV1 { mppt_ina, .. } => mppt_ina.shunt_voltage().map(|v| {
let shunt_voltage = Voltage::from_microvolts(v.shunt_voltage_uv().abs() as f64);
let shut_value = Resistance::from_ohms(0.05_f64);
let current = shunt_voltage.as_volts() / shut_value.as_ohms();
Current::from_amperes(current)
})?,
_ => {
bail!("hardware error during init")
}
};
Ok(current)
}
}
pub struct V4<'a> {
esp: Esp<'a>,
tank_sensor: TankSensor<'a>,
charger: Charger<'a>,
rtc_module: Box<dyn RTCModuleInteraction + Send>,
battery_monitor: Box<dyn BatteryInteraction + Send>,
config: PlantControllerConfig,
awake: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, Output>,
light: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
general_fault: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, InputOutput>,
pump_expander: Pca9535Immediate<MutexDevice<'a, I2cDriver<'a>>>,
pump_ina: Option<SyncIna219<MutexDevice<'a, I2cDriver<'a>>, UnCalibrated>>,
sensor: SensorImpl<'a>,
extra1: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, Output>,
extra2: PinDriver<'a, esp_idf_hal::gpio::AnyIOPin, Output>,
}
pub(crate) fn create_v4(
peripherals: FreePeripherals,
esp: Esp<'static>,
config: PlantControllerConfig,
battery_monitor: Box<dyn BatteryInteraction + Send>,
rtc_module: Box<dyn RTCModuleInteraction + Send>,
) -> anyhow::Result<Box<dyn BoardInteraction<'static> + Send + 'static>> {
log::info!("Start v4");
let mut awake = PinDriver::output(peripherals.gpio21.downgrade())?;
awake.set_high()?;
let mut general_fault = PinDriver::input_output(peripherals.gpio23.downgrade())?;
general_fault.set_pull(Pull::Floating)?;
general_fault.set_low()?;
let mut extra1 = PinDriver::output(peripherals.gpio6.downgrade())?;
extra1.set_low()?;
let mut extra2 = PinDriver::output(peripherals.gpio15.downgrade())?;
extra2.set_low()?;
let one_wire_pin = peripherals.gpio18.downgrade();
let tank_power_pin = peripherals.gpio11.downgrade();
let flow_sensor_pin = peripherals.gpio4.downgrade();
let tank_sensor = TankSensor::create(
one_wire_pin,
peripherals.adc1,
peripherals.gpio5,
tank_power_pin,
flow_sensor_pin,
peripherals.pcnt1,
)?;
let mut sensor_expander = Pca9535Immediate::new(MutexDevice::new(&I2C_DRIVER), 34);
let sensor = match sensor_expander.pin_into_output(GPIOBank::Bank0, 0) {
Ok(_) => {
log::info!("SensorExpander answered");
//pulse counter version
let mut signal_counter = PcntDriver::new(
peripherals.pcnt0,
Some(peripherals.gpio22),
Option::<AnyInputPin>::None,
Option::<AnyInputPin>::None,
Option::<AnyInputPin>::None,
)?;
signal_counter.channel_config(
PcntChannel::Channel0,
PinIndex::Pin0,
PinIndex::Pin1,
&PcntChannelConfig {
lctrl_mode: PcntControlMode::Keep,
hctrl_mode: PcntControlMode::Keep,
pos_mode: PcntCountMode::Increment,
neg_mode: PcntCountMode::Hold,
counter_h_lim: i16::MAX,
counter_l_lim: 0,
},
)?;
for pin in 0..8 {
let _ = sensor_expander.pin_into_output(GPIOBank::Bank0, pin);
let _ = sensor_expander.pin_into_output(GPIOBank::Bank1, pin);
let _ = sensor_expander.pin_set_low(GPIOBank::Bank0, pin);
let _ = sensor_expander.pin_set_low(GPIOBank::Bank1, pin);
}
SensorImpl::PulseCounter {
signal_counter,
sensor_expander,
}
}
Err(_) => {
log::info!("Can bus mode ");
let timing = can::config::Timing::B25K;
let config = can::config::Config::new().timing(timing);
let can = can::CanDriver::new(peripherals.can, peripherals.gpio0, peripherals.gpio2, &config).unwrap();
let frame = StandardId::new(0x042).unwrap();
let tx_frame = Frame::new(frame, &[0, 1, 2, 3, 4, 5, 6, 7]).unwrap();
can.transmit(&tx_frame, 1000).unwrap();
if let Ok(rx_frame) = can.receive(1000) {
log::info!("rx {:}:", rx_frame);
}
//can bus version
SensorImpl::CanBus {
can
}
}
};
let mut solar_is_day = PinDriver::input(peripherals.gpio7.downgrade())?;
solar_is_day.set_pull(Pull::Floating)?;
let mut light = PinDriver::input_output(peripherals.gpio10.downgrade())?;
light.set_pull(Pull::Floating)?;
let mut charge_indicator = PinDriver::input_output(peripherals.gpio3.downgrade())?;
charge_indicator.set_pull(Pull::Floating)?;
charge_indicator.set_low()?;
let mut pump_expander = Pca9535Immediate::new(MutexDevice::new(&I2C_DRIVER), 32);
for pin in 0..8 {
let _ = pump_expander.pin_into_output(GPIOBank::Bank0, pin);
let _ = pump_expander.pin_into_output(GPIOBank::Bank1, pin);
let _ = pump_expander.pin_set_low(GPIOBank::Bank0, pin);
let _ = pump_expander.pin_set_low(GPIOBank::Bank1, pin);
}
let mppt_ina = SyncIna219::new(
MutexDevice::new(&I2C_DRIVER),
Address::from_pins(Pin::Vcc, Pin::Gnd),
);
let charger = match mppt_ina {
Ok(mut mppt_ina) => {
mppt_ina.set_configuration(Configuration {
reset: Default::default(),
bus_voltage_range: Default::default(),
shunt_voltage_range: Default::default(),
bus_resolution: Default::default(),
shunt_resolution: ina219::configuration::Resolution::Avg128,
operating_mode: Default::default(),
})?;
Charger::SolarMpptV1 {
mppt_ina,
solar_is_day,
charge_indicator,
}
}
Err(_) => Charger::ErrorInit {},
};
let pump_ina = match SyncIna219::new(
MutexDevice::new(&I2C_DRIVER),
Address::from_pins(Pin::Gnd, Pin::Sda),
) {
Ok(pump_ina) => Some(pump_ina),
Err(err) => {
log::info!("Error creating pump ina: {:?}", err);
None
}
};
let v = V4 {
rtc_module,
esp,
awake,
tank_sensor,
light,
general_fault,
pump_ina,
pump_expander,
config,
battery_monitor,
charger,
extra1,
extra2,
sensor,
};
Ok(Box::new(v))
}
impl<'a> BoardInteraction<'a> for V4<'a> {
fn get_tank_sensor(&mut self) -> Option<&mut TankSensor<'a>> {
Some(&mut self.tank_sensor)
}
fn get_esp(&mut self) -> &mut Esp<'a> {
&mut self.esp
}
fn get_config(&mut self) -> &PlantControllerConfig {
&self.config
}
fn get_battery_monitor(&mut self) -> &mut Box<dyn BatteryInteraction + Send> {
&mut self.battery_monitor
}
fn get_rtc_module(&mut self) -> &mut Box<dyn RTCModuleInteraction + Send> {
&mut self.rtc_module
}
fn set_charge_indicator(&mut self, charging: bool) -> anyhow::Result<()> {
self.charger.set_charge_indicator(charging)
}
fn deep_sleep(&mut self, duration_in_ms: u64) -> ! {
self.awake.set_low().unwrap();
self.charger.power_save();
deep_sleep(duration_in_ms);
}
fn is_day(&self) -> bool {
self.charger.is_day()
}
fn light(&mut self, enable: bool) -> anyhow::Result<()> {
unsafe { gpio_hold_dis(self.light.pin()) };
self.light.set_state(enable.into())?;
unsafe { gpio_hold_en(self.light.pin()) };
anyhow::Ok(())
}
fn pump(&mut self, plant: usize, enable: bool) -> anyhow::Result<()> {
if enable {
self.pump_expander
.pin_set_high(GPIOBank::Bank0, plant.try_into()?)?;
} else {
self.pump_expander
.pin_set_low(GPIOBank::Bank0, plant.try_into()?)?;
}
anyhow::Ok(())
}
fn pump_current(&mut self, _plant: usize) -> anyhow::Result<Current> {
//sensore is shared for all pumps, ignore plant id
match self.pump_ina.as_mut() {
None => {
bail!("pump current sensor not available");
}
Some(pump_ina) => {
let v = pump_ina.shunt_voltage().map(|v| {
let shunt_voltage = Voltage::from_microvolts(v.shunt_voltage_uv().abs() as f64);
let shut_value = Resistance::from_ohms(0.05_f64);
let current = shunt_voltage.as_volts() / shut_value.as_ohms();
Current::from_amperes(current)
})?;
Ok(v)
}
}
}
fn fault(&mut self, plant: usize, enable: bool) -> anyhow::Result<()> {
if enable {
self.pump_expander
.pin_set_high(GPIOBank::Bank1, plant.try_into()?)?
} else {
self.pump_expander
.pin_set_low(GPIOBank::Bank1, plant.try_into()?)?
}
anyhow::Ok(())
}
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32> {
self.sensor.measure_moisture_hz(plant, sensor)
}
fn general_fault(&mut self, enable: bool) {
unsafe { gpio_hold_dis(self.general_fault.pin()) };
self.general_fault.set_state(enable.into()).unwrap();
unsafe { gpio_hold_en(self.general_fault.pin()) };
}
fn test(&mut self) -> anyhow::Result<()> {
self.general_fault(true);
self.esp.delay.delay_ms(100);
self.general_fault(false);
self.esp.delay.delay_ms(500);
self.light(true)?;
self.esp.delay.delay_ms(500);
self.light(false)?;
self.esp.delay.delay_ms(500);
for i in 0..PLANT_COUNT {
self.fault(i, true)?;
self.esp.delay.delay_ms(500);
self.fault(i, false)?;
self.esp.delay.delay_ms(500);
}
for i in 0..PLANT_COUNT {
self.pump(i, true)?;
self.esp.delay.delay_ms(100);
self.pump(i, false)?;
self.esp.delay.delay_ms(100);
}
for plant in 0..PLANT_COUNT {
let a = self.measure_moisture_hz(plant, Sensor::A);
let b = self.measure_moisture_hz(plant, Sensor::B);
let aa = match a {
OkStd(a) => a as u32,
Err(_) => u32::MAX,
};
let bb = match b {
OkStd(b) => b as u32,
Err(_) => u32::MAX,
};
log(LogMessage::TestSensor, aa, bb, &plant.to_string(), "");
}
self.esp.delay.delay_ms(10);
anyhow::Ok(())
}
fn set_config(&mut self, config: PlantControllerConfig) -> anyhow::Result<()> {
self.config = config;
self.esp.save_config(&self.config)?;
anyhow::Ok(())
}
fn get_mptt_voltage(&mut self) -> anyhow::Result<Voltage> {
self.charger.get_mptt_voltage()
}
fn get_mptt_current(&mut self) -> anyhow::Result<Current> {
self.charger.get_mptt_current()
}
}

118
rust/scratch/v4_sensor.rs Normal file
View File

@@ -0,0 +1,118 @@
use crate::hal::Sensor;
use crate::log::{log, LogMessage};
use alloc::string::ToString;
use embedded_hal_bus::i2c::MutexDevice;
use esp_idf_hal::can::CanDriver;
use esp_idf_hal::delay::Delay;
use esp_idf_hal::i2c::I2cDriver;
use esp_idf_hal::pcnt::PcntDriver;
use pca9535::{GPIOBank, Pca9535Immediate, StandardExpanderInterface};
const REPEAT_MOIST_MEASURE: usize = 10;
pub trait SensorInteraction {
async fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32>;
}
const MS0: u8 = 1_u8;
const MS1: u8 = 0_u8;
const MS2: u8 = 3_u8;
const MS3: u8 = 4_u8;
const MS4: u8 = 2_u8;
const SENSOR_ON: u8 = 5_u8;
pub enum SensorImpl<'a> {
PulseCounter {
signal_counter: PcntDriver<'a>,
sensor_expander: Pca9535Immediate<MutexDevice<'a, I2cDriver<'a>>>,
},
CanBus {
can: CanDriver<'a>,
},
}
impl SensorInteraction for SensorImpl<'_> {
fn measure_moisture_hz(&mut self, plant: usize, sensor: Sensor) -> anyhow::Result<f32> {
match self {
SensorImpl::PulseCounter {
signal_counter,
sensor_expander,
..
} => {
let mut results = [0_f32; REPEAT_MOIST_MEASURE];
for repeat in 0..REPEAT_MOIST_MEASURE {
signal_counter.counter_pause()?;
signal_counter.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 delay = Delay::new_default();
let measurement = 100; // TODO what is this scaling factor? what is its purpose?
let factor = 1000f32 / measurement as f32;
//give some time to stabilize
delay.delay_ms(10);
signal_counter.counter_resume()?;
delay.delay_ms(measurement);
signal_counter.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)?;
delay.delay_ms(10);
let unscaled = signal_counter.get_counter_value()? as i32;
let hz = unscaled as f32 * factor;
log(
LogMessage::RawMeasure,
unscaled as u32,
hz as u32,
&plant.to_string(),
&format!("{sensor:?}"),
);
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];
anyhow::Ok(median)
}
SensorImpl::CanBus { .. } => {
todo!()
}
}
}
}

176
rust/scratch/water.rs Normal file
View File

@@ -0,0 +1,176 @@
use crate::hal::TANK_MULTI_SAMPLE;
use anyhow::{anyhow, bail};
use ds18b20::Ds18b20;
use esp_idf_hal::adc::oneshot::config::AdcChannelConfig;
use esp_idf_hal::adc::oneshot::{AdcChannelDriver, AdcDriver};
use esp_idf_hal::adc::{attenuation, Resolution, ADC1};
use esp_idf_hal::delay::Delay;
use esp_idf_hal::gpio::{AnyIOPin, AnyInputPin, Gpio5, InputOutput, PinDriver, Pull};
use esp_idf_hal::pcnt::{
PcntChannel, PcntChannelConfig, PcntControlMode, PcntCountMode, PcntDriver, PinIndex, PCNT1,
};
use esp_idf_sys::EspError;
use one_wire_bus::OneWire;
pub struct TankSensor<'a> {
// one_wire_bus: OneWire<PinDriver<'a, AnyIOPin, InputOutput>>,
// tank_channel: AdcChannelDriver<'a, Gpio5, AdcDriver<'a, ADC1>>,
// tank_power: PinDriver<'a, AnyIOPin, InputOutput>,
// flow_counter: PcntDriver<'a>,
// delay: Delay,
}
impl<'a> TankSensor<'a> {
pub(crate) fn create(
// one_wire_pin: AnyIOPin,
// adc1: ADC1,
// gpio5: Gpio5,
// tank_power_pin: AnyIOPin,
// flow_sensor_pin: AnyIOPin,
// pcnt1: PCNT1,
) -> anyhow::Result<TankSensor<'a>> {
// let mut one_wire_pin =
// PinDriver::input_output_od(one_wire_pin).expect("Failed to configure pin");
// one_wire_pin
// .set_pull(Pull::Floating)
// .expect("Failed to set pull");
//
// let adc_config = AdcChannelConfig {
// attenuation: attenuation::DB_11,
// resolution: Resolution::Resolution12Bit,
// calibration: esp_idf_hal::adc::oneshot::config::Calibration::Curve,
// };
// let tank_driver = AdcDriver::new(adc1).expect("Failed to configure ADC");
// let tank_channel = AdcChannelDriver::new(tank_driver, gpio5, &adc_config)
// .expect("Failed to configure ADC channel");
//
// let mut tank_power =
// PinDriver::input_output(tank_power_pin).expect("Failed to configure pin");
// tank_power
// .set_pull(Pull::Floating)
// .expect("Failed to set pull");
//
// let one_wire_bus =
// OneWire::new(one_wire_pin).expect("OneWire bus did not pull up after release");
//
// let mut flow_counter = PcntDriver::new(
// pcnt1,
// Some(flow_sensor_pin),
// Option::<AnyInputPin>::None,
// Option::<AnyInputPin>::None,
// Option::<AnyInputPin>::None,
// )?;
//
// flow_counter.channel_config(
// PcntChannel::Channel1,
// PinIndex::Pin0,
// PinIndex::Pin1,
// &PcntChannelConfig {
// lctrl_mode: PcntControlMode::Keep,
// hctrl_mode: PcntControlMode::Keep,
// pos_mode: PcntCountMode::Increment,
// neg_mode: PcntCountMode::Hold,
// counter_h_lim: i16::MAX,
// counter_l_lim: 0,
// },
// )?;
//
// Ok(TankSensor {
// one_wire_bus,
// tank_channel,
// tank_power,
// flow_counter,
// delay: Default::default(),
// })
bail!("Tank sensor not implemented");
}
pub fn reset_flow_meter(&mut self) {
// self.flow_counter.counter_pause().unwrap();
// self.flow_counter.counter_clear().unwrap();
}
pub fn start_flow_meter(&mut self) {
//self.flow_counter.counter_resume().unwrap();
}
pub fn get_flow_meter_value(&mut self) -> i16 {
//self.flow_counter.get_counter_value().unwrap()
5_i16
}
pub fn stop_flow_meter(&mut self) -> i16 {
//self.flow_counter.counter_pause().unwrap();
self.get_flow_meter_value()
}
pub async fn water_temperature_c(&mut self) -> anyhow::Result<f32> {
//multisample should be moved to water_temperature_c
let mut attempt = 1;
let water_temp: Result<f32, anyhow::Error> = loop {
let temp = self.single_temperature_c().await;
match &temp {
Ok(res) => {
log::info!("Water temp is {}", res);
break temp;
}
Err(err) => {
log::info!("Could not get water temp {} attempt {}", err, attempt)
}
}
if attempt == 5 {
break temp;
}
attempt += 1;
};
water_temp
}
async fn single_temperature_c(&mut self) -> anyhow::Result<f32> {
bail!("err");
// self.one_wire_bus
// .reset(&mut self.delay)
// .map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
// let first = self.one_wire_bus.devices(false, &mut self.delay).next();
// if first.is_none() {
// bail!("Not found any one wire Ds18b20");
// }
// let device_address = first
// .unwrap()
// .map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
// let water_temp_sensor = Ds18b20::new::<EspError>(device_address)
// .map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
//
// water_temp_sensor
// .start_temp_measurement(&mut self.one_wire_bus, &mut self.delay)
// .map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
// ds18b20::Resolution::Bits12.delay_for_measurement_time(&mut self.delay);
// let sensor_data = water_temp_sensor
// .read_data(&mut self.one_wire_bus, &mut self.delay)
// .map_err(|err| -> anyhow::Error { anyhow!("Missing attribute: {:?}", err) })?;
// if sensor_data.temperature == 85_f32 {
// bail!("Ds18b20 dummy temperature returned");
// }
//anyhow::Ok(sensor_data.temperature / 10_f32)
Ok(13_f32)
}
pub async fn tank_sensor_voltage(&mut self) -> anyhow::Result<f32> {
// self.tank_power.set_high()?;
// //let stabilize
// self.delay.delay_ms(100);
//
// let mut store = [0_u16; TANK_MULTI_SAMPLE];
// for multisample in 0..TANK_MULTI_SAMPLE {
// let value = self.tank_channel.read()?;
// store[multisample] = value;
// }
// self.tank_power.set_low()?;
//
// store.sort();
// let median_mv = store[6] as f32 / 1000_f32;
let median_mv = 10_f32;
anyhow::Ok(median_mv)
}
}