From daf6effe59800ff40fda3da399472f0ab47b64d7 Mon Sep 17 00:00:00 2001 From: Ivan Li Date: Mon, 12 Sep 2022 11:50:26 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=E5=85=85=E7=94=B5?= =?UTF-8?q?=E6=8E=A7=E5=88=B6=E5=80=92=E8=AE=A1=E6=97=B6=E4=B8=8A=E6=8A=A5?= =?UTF-8?q?=E5=88=B0=20MQTT=20=E8=83=BD=E5=8A=9B=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/charge_controller.rs | 31 ++++++++++++++++++++++++++----- 1 file changed, 26 insertions(+), 5 deletions(-) diff --git a/src/charge_controller.rs b/src/charge_controller.rs index 831e82f..9b58ee8 100644 --- a/src/charge_controller.rs +++ b/src/charge_controller.rs @@ -1,4 +1,7 @@ -use std::sync::{Arc, Mutex, MutexGuard}; +use std::{ + sync::{Arc, Mutex, MutexGuard}, + time::Duration, +}; use embedded_hal::digital::v2::{OutputPin, PinState}; use embedded_svc::event_bus::{EventBus, Postbox}; @@ -8,10 +11,13 @@ use esp_idf_svc::eventloop::{ EspSubscription, EspTypedEventDeserializer, EspTypedEventSerializer, EspTypedEventSource, User, }; use esp_idf_sys::c_types; -use log::{warn}; +use log::warn; use serde_json::json; -use crate::voltage_detection::{VoltageDetectionWorker, VOLTAGE_EVENTLOOP}; +use crate::{ + time::Time, + voltage_detection::{VoltageDetectionWorker, VOLTAGE_EVENTLOOP}, +}; pub static mut CHARGE_STATE_EVENT_LOOP: Option< EspEventLoop>, @@ -27,6 +33,7 @@ pub enum ChargeStatus { pub struct ChargeControllerState { pub status: ChargeStatus, pub pin_state: PinState, + pub charge_deadline_at: Duration, } impl ChargeControllerState { @@ -34,6 +41,7 @@ impl ChargeControllerState { Self { status: ChargeStatus::Charging, pin_state: PinState::Low, + charge_deadline_at: Duration::ZERO, } } @@ -46,7 +54,13 @@ impl ChargeControllerState { PinState::Low => "Low", PinState::High => "High", }; - json!({ "status": status, "pin_state": pin_state}).to_string() + let now = Time::new().get_time(); + let charging_count_down = if now > self.charge_deadline_at { + -1i64 + } else { + (self.charge_deadline_at - now).as_secs() as i64 + }; + json!({ "status": status, "pin_state": pin_state, "charging_count_down": charging_count_down}).to_string() } } @@ -112,7 +126,14 @@ impl ChargeController { if obj.battery_voltage < 12600 { state.status = ChargeStatus::Charging; } else { - state.status = ChargeStatus::Charged; + let now = Time::new().get_time(); + if state.charge_deadline_at == Duration::ZERO { + state.charge_deadline_at = now + Duration::from_secs(600); + } else if now > state.charge_deadline_at { + state.status = ChargeStatus::Charged; + } else { + state.status = ChargeStatus::Charging; + } } } ChargeStatus::Charged => {