socit 0.4.0

Dynamically control inverter SoC settings
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
/* Copyright 2023-2025 Bruce Merry
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <https://www.gnu.org/licenses/>.
 */

use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use futures::StreamExt;
use log::{error, info, warn};
use radians::Deg64;
use std::cmp::min;
use std::collections::VecDeque;
use std::sync::Mutex;
use std::time::Instant;
use tokio::time::MissedTickBehavior;
use tokio_stream::StreamMap;
use tokio_util::sync::CancellationToken;

use crate::config::{CoilConfig, Config, InverterConfig, PanelConfig};
use crate::esp_api::{API, AreaResponse};
use crate::inverter::{Info, Inverter, Result};
use crate::monitoring::{CoilUpdate, Monitor, SocUpdate};
use crate::sun::solar_fraction;

pub struct State {
    pub response: AreaResponse,
    pub time: DateTime<Utc>,
}

pub async fn poll_esp(
    api: &API,
    area_id: &str,
    interval: std::time::Duration,
    state: &Mutex<Option<State>>,
    token: CancellationToken,
) {
    let mut interval = tokio::time::interval(interval);
    interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
    loop {
        tokio::select! {
            _ = interval.tick() => {},
            _ = token.cancelled() => { break; }
        }
        match api.area(area_id).await {
            Ok(response) => {
                let mut lock = state.lock().unwrap();
                *lock = Some(State {
                    response,
                    time: Utc::now(),
                });
                drop(lock);
                info!("Successfully updated area info from EskomSePush");
            }
            Err(err) => {
                warn!("Failed to update from EskomSePush: {err}");
            }
        }
    }
}

fn filter_state(state: &Option<State>, min_time: DateTime<Utc>) -> Option<&State> {
    state.as_ref().filter(|state| state.time >= min_time)
}

/// Number of (non-integer) hours in a duration
fn duration_hours(duration: Duration) -> f64 {
    (duration.num_milliseconds() as f64) / 3600000.0
}

fn panels_power(panels: &[PanelConfig], time: DateTime<Utc>) -> f64 {
    let mut power = 0.0;
    for panels in panels.iter() {
        power += panels.power
            * solar_fraction(
                Deg64::new(panels.latitude),
                Deg64::new(panels.longitude),
                Deg64::new(90.0 - panels.tilt),
                Deg64::new(panels.azimuth),
                &time,
            );
    }
    power
}

/// What to simulate when no load-shedding and not enough solar
enum SimMode {
    /// Power drains from battery
    Drain,
    /// Battery level held steady
    Hold,
    /// Charge battery as fast as possible
    Charge,
}

/// What to simulate when modelling export
enum ExportMode {
    /// Export first, including from the battery
    Drain,
    /// Export first, but do not export from battery
    Hold,
}

fn target_soc_helper(
    config: &InverterConfig,
    state: &State,
    info: &Info,
    now: DateTime<Utc>,
    mode: SimMode,
) -> (f64, DateTime<Utc>) {
    let step = Duration::seconds(60);
    let step_h = duration_hours(step);
    let depth = info.capacity - config.min_soc * 0.01 * info.capacity;

    let mut base_wh = 0.0;
    let mut worst = 0.0_f64;
    let mut floor = -depth;
    let mut worst_time = now;
    /* Project battery level forward for 24 hours, using optimistic
     * assumptions about solar PV and consumption. Whenever the
     * current point falls into load-shedding, check that there will
     * be enough to get to the end with pessimistic assumptions.
     */
    let goal = now + Duration::seconds(86400);
    let mut t = now;
    let mut observe = |wh, t| {
        if wh < worst {
            worst = wh;
            worst_time = t;
        }
    };
    while t < goal {
        let mut have_grid = true;
        for event in state.response.events.iter() {
            if t >= event.start && t < event.end {
                have_grid = false;
                let end_wh = base_wh - config.max_discharge_power * duration_hours(event.end - t);
                observe(end_wh.max(floor), t);
            }
        }
        let mut power = panels_power(&config.panels, t + step / 2);
        power = power.min(config.charge_power);
        power -= config.min_discharge_power;
        if have_grid {
            power = match mode {
                SimMode::Drain => power,
                SimMode::Hold => power.max(0.0),
                SimMode::Charge => config.charge_power,
            };
        }
        base_wh += power * step_h;
        t += step;

        floor = floor.max(base_wh - depth);
        observe(base_wh.max(floor), t);
    }

    let extra = -worst / info.capacity * 100.0;
    let target = config.min_soc + extra;
    let target = target.clamp(0.0, 100.0);
    (target, worst_time)
}

fn target_socs(
    config: &InverterConfig,
    state: Option<&State>,
    info: &Info,
    now: DateTime<Utc>,
) -> (f64, f64, f64) {
    match state {
        None => (config.fallback_soc, config.fallback_soc, config.min_soc),
        Some(state) => {
            for event in state.response.events.iter() {
                info!("Load-shedding from {} to {}", event.start, event.end);
            }
            let (target_high, _) = target_soc_helper(config, state, info, now, SimMode::Drain);
            let (target_low, _) = target_soc_helper(config, state, info, now, SimMode::Hold);
            let (alarm, _) = target_soc_helper(config, state, info, now, SimMode::Charge);
            (target_low, target_high, alarm)
        }
    }
}

fn export_soc_helper(
    config: &InverterConfig,
    info: &Info,
    now: DateTime<Utc>,
    mode: ExportMode,
) -> f64 {
    // TODO: take load shedding into account (can't export during load shedding)
    let step = Duration::seconds(60);
    let step_h = duration_hours(step);
    let goal = now + Duration::seconds(86400);
    let mut t = now;
    let mut cur = 0.0f64;
    let mut peak = 0.0f64;
    let mut entered = false;

    while t < goal {
        let power = panels_power(&config.panels, t + step / 2);
        let generating = power > 0.0;
        let power = power - config.min_discharge_power;
        let power = match mode {
            ExportMode::Drain => power - info.export_power,
            ExportMode::Hold => {
                if power < 0.0 {
                    power // Not generating enough - battery runs down
                } else {
                    (power - info.export_power).max(0.0) // Export, and charge battery with leftover
                }
            }
        };
        // TODO: also need to clamp rate at which battery can deliver power.
        // For now assume the battery can supply the maximum export power.
        let power = power.min(config.charge_power);
        cur += power * step_h;
        peak = peak.max(cur);
        t += step;
        if generating {
            entered = true;
        } else if entered {
            break; // Reached the end of production for the day
        }
    }

    (1.0 - peak / info.capacity) * 100.0
}

fn export_soc(config: &InverterConfig, info: &Info, now: DateTime<Utc>) -> (f64, f64) {
    (
        export_soc_helper(config, info, now, ExportMode::Hold),
        export_soc_helper(config, info, now, ExportMode::Drain),
    )
}

async fn update_soc(
    inverter: &mut dyn Inverter,
    config: &InverterConfig,
    monitor: &mut dyn Monitor,
    state: &Mutex<Option<State>>,
    esp_timeout: Duration,
) -> Result<()> {
    let now = Utc::now();
    let info = inverter.get_info().await?;
    let current_soc = inverter.get_soc().await?;
    let net_production = inverter.get_net_production().await?;
    let mut target;
    let update;
    let full_export;

    {
        let guard = &state.lock().unwrap();
        let state = filter_state(guard, now - esp_timeout);
        let est_start = Instant::now();
        let (target_soc_low, target_soc_high, alarm_soc) = target_socs(config, state, &info, now);
        let (target_soc_export_low, target_soc_export_high) = export_soc(config, &info, now);
        info!(
            "Target SoC range is {:.2} - {:.2} (alarm at {:.2}); export range is {:.2} - {:.2}; computed in {:.3} s",
            target_soc_low,
            target_soc_high,
            alarm_soc,
            target_soc_export_low,
            target_soc_export_high,
            est_start.elapsed().as_secs_f64()
        );
        target = current_soc.min(target_soc_high).max(target_soc_low);
        full_export = if info.export_enabled {
            let low = target_soc_export_low.max(target_soc_low);
            let high = target_soc_export_high.max(target_soc_high);
            // Turn off full-export when battery is full, because Sunsynk has
            // a bug where non-essential loads count against export limit when
            // full-export is enabled.
            if current_soc < 99.0
                && (current_soc >= high || (current_soc >= low && net_production > 0.0))
            {
                target = target.max(current_soc.min(high));
                Some(true)
            } else {
                Some(false)
            }
        } else {
            None
        };

        let mut is_loadshedding = false;
        let mut next_change = None;
        if let Some(state) = state {
            for event in state.response.events.iter() {
                if now >= event.start && now < event.end {
                    is_loadshedding = true;
                    next_change = Some(event.end);
                    break;
                } else if now < event.start {
                    next_change = Some(next_change.map_or(event.start, |t| min(t, event.start)));
                }
            }
        }

        update = SocUpdate {
            time: now,
            target_soc_low,
            target_soc_high,
            alarm_soc,
            target_soc_export_low,
            target_soc_export_high,
            current_soc,
            predicted_pv: panels_power(&config.panels, now),
            is_loadshedding,
            next_change,
        };
    }

    info!("Setting min SoC to {target:.2}");
    inverter.set_min_soc(target, config.fallback_soc).await?;
    if let Some(full_export) = full_export {
        info!("Setting full export to {full_export}");
        inverter.set_full_export(full_export).await?;
    }
    if let Err(err) = monitor.soc_update(update).await {
        warn!("Failed to update monitoring: {err}");
    }

    Ok(())
}

#[async_trait]
trait Controller: Send + Unpin {
    fn interval(&self) -> std::time::Duration;
    async fn update(&mut self, inverter: &mut dyn Inverter, monitor: &mut dyn Monitor);
    async fn shutdown(&mut self, inverter: &mut dyn Inverter);
}

struct SocController<'a> {
    config: &'a InverterConfig,
    state: &'a Mutex<Option<State>>,
    esp_timeout: Duration,
}

impl<'a> SocController<'a> {
    fn new(
        config: &'a InverterConfig,
        state: &'a Mutex<Option<State>>,
        esp_timeout: Duration,
    ) -> Self {
        Self {
            config,
            state,
            esp_timeout,
        }
    }
}

#[async_trait]
impl Controller for SocController<'_> {
    fn interval(&self) -> std::time::Duration {
        std::time::Duration::from_secs(60)
    }

    async fn update(&mut self, inverter: &mut dyn Inverter, monitor: &mut dyn Monitor) {
        if let Err(err) =
            update_soc(inverter, self.config, monitor, self.state, self.esp_timeout).await
        {
            warn!("Failed to update inverter: {err}");
        }
    }

    async fn shutdown(&mut self, inverter: &mut dyn Inverter) {
        info!(
            "Shutting down, setting minimum SoC to {}",
            self.config.fallback_soc
        );
        match inverter
            .set_min_soc(self.config.fallback_soc, self.config.fallback_soc)
            .await
        {
            Ok(_) => {}
            Err(err) => {
                error!("Failed to set minimum SoC: {err}");
            }
        }
    }
}

struct CoilController<'a> {
    history: VecDeque<Option<f64>>,
    config: &'a CoilConfig,
    last_setting: Option<f64>,
}

impl<'a> CoilController<'a> {
    const CAPACITY: usize = 11;

    fn new(config: &'a CoilConfig) -> Self {
        Self {
            history: VecDeque::with_capacity(Self::CAPACITY),
            config,
            last_setting: None,
        }
    }

    async fn update_fallible(
        &mut self,
        inverter: &mut dyn Inverter,
        monitor: &mut dyn Monitor,
    ) -> Result<()> {
        let info = inverter.get_coil().await?;
        let mut target = None;
        if let Some(value) = &info {
            let ne = value.coil - value.inverter;
            if ne <= self.config.power_threshold {
                // It's fake power from misreading coil
                target = Some(ne + self.config.trickle);
            }
        }
        if self.history.len() == Self::CAPACITY {
            self.history.pop_front();
        }
        self.history.push_back(target);
        if self.history.len() != Self::CAPACITY {
            return Ok(());
        }
        // Compute the sum if all elements are not None
        let sum = self.history.iter().cloned().sum::<Option<f64>>();
        let mean = sum.map(|x| x / (self.history.len() as f64));
        let coil_active = info.is_some_and(|x| x.coil_active);
        if coil_active {
            if let Some(target) = mean {
                if self.last_setting.is_none_or(|x| (x - target).abs() >= 10.0) {
                    info!("Setting trickle to {target}.");
                    inverter.set_trickle(target).await?;
                    self.last_setting = Some(target);
                } else {
                    info!("Ideal trickle setting is {target}, but not setting due to hysteresis.");
                }
            } else {
                info!("Not adjusting trickle because there is no target information.")
            }
        } else {
            info!("Not adjusting trickle because coil is not active.");
        }
        let update = CoilUpdate {
            time: Utc::now(),
            active: coil_active,
            target: mean,
            setting: self.last_setting,
        };
        if let Err(err) = monitor.coil_update(update).await {
            warn!("Failed to update monitoring: {err}");
        }
        Ok(())
    }
}

#[async_trait]
impl Controller for CoilController<'_> {
    fn interval(&self) -> std::time::Duration {
        std::time::Duration::from_secs(10)
    }

    async fn update(&mut self, inverter: &mut dyn Inverter, monitor: &mut dyn Monitor) {
        match self.update_fallible(inverter, monitor).await {
            Ok(_) => {}
            Err(err) => {
                error!("Failed to update CT coil: {err}");
            }
        }
    }

    async fn shutdown(&mut self, _inverter: &mut dyn Inverter) {}
}

pub async fn control_inverter(
    inverter: &mut dyn Inverter,
    config: &Config,
    monitor: &mut dyn Monitor,
    state: &Mutex<Option<State>>,
    esp_timeout: Duration,
    token: CancellationToken,
) {
    let mut controllers: Vec<Box<dyn Controller>> = Vec::new();
    controllers.push(Box::new(SocController::new(
        &config.inverter,
        state,
        esp_timeout,
    )));
    if let Some(coil_config) = &config.coil {
        controllers.push(Box::new(CoilController::new(coil_config)));
    }
    let mut stream = StreamMap::new();
    for (i, controller) in controllers.iter().enumerate() {
        let mut interval = tokio::time::interval(controller.interval());
        interval.set_missed_tick_behavior(MissedTickBehavior::Delay);
        stream.insert(i, tokio_stream::wrappers::IntervalStream::new(interval));
    }

    loop {
        tokio::select! {
            Some((idx, _)) = stream.next() => { controllers[idx].update(inverter, monitor).await; }
            _ = token.cancelled() => { break; }
        }
    }

    for controller in controllers.iter_mut() {
        controller.shutdown(inverter).await;
    }
}