-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintel.rs
More file actions
872 lines (782 loc) · 31.3 KB
/
Copy pathintel.rs
File metadata and controls
872 lines (782 loc) · 31.3 KB
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
//! Intel page data endpoint.
//!
//! `GET /api/v1/intel` returns a single JSON object covering six analysis
//! domains: daemon system health, solar performance vs. irradiance, HVAC
//! operating stats, billing intelligence, heat-loss estimation, and anomaly
//! alerts.
//!
//! All sections are optional — a section is `null` in the response when the
//! required data source is unavailable (no weather connector, no Postgres,
//! no InfluxDB history, etc.).
use axum::{extract::State, Json};
use chrono::{Datelike, Local};
use serde::Serialize;
use crate::state::AppState;
use flux_core::{DeviceCategory, FieldValue};
use super::billing::fetch_rows_pub;
// ── Response types ────────────────────────────────────────────────────────────
/// Top-level response for `GET /api/v1/intel`.
#[derive(Serialize)]
pub struct IntelResponse {
pub system: Option<SystemStats>,
pub solar: Option<SolarPerformance>,
pub hvac: Option<HvacStats>,
pub billing: Option<BillingIntel>,
pub heat_loss: Option<HeatLoss>,
pub anomalies: Vec<Anomaly>,
}
/// Daemon process resource usage.
#[derive(Serialize)]
pub struct SystemStats {
/// CPU utilisation (0–100 %).
pub cpu_pct: f64,
/// RSS memory used by the daemon in MiB.
pub mem_used_mb: f64,
/// Total host memory in MiB.
pub mem_total_mb: f64,
/// Daemon uptime in seconds (since the process started, not the host).
pub uptime_secs: u64,
/// Number of distinct metric sources actively writing to the cache.
pub active_sources: usize,
/// Flux daemon version string.
pub version: String,
}
/// Building heat-loss coefficient (UA) estimated from HVAC runtime data.
///
/// Fitted by least-squares regression over the last 30 days of hourly
/// HVAC power vs. the indoor/outdoor temperature differential.
#[derive(Serialize)]
pub struct HeatLoss {
/// UA coefficient in BTU/hr/°F.
pub ua_btu_hr_f: f64,
/// Estimated design heat loss (BTU/hr) at 0°F outdoor, 70°F indoor.
pub design_heat_loss_btu_hr: f64,
/// Equivalent heat loss in kW at design conditions.
pub design_heat_loss_kw: f64,
/// Indoor setpoint used for ΔT calculation (°F).
pub indoor_setpoint_f: f64,
/// Number of hourly samples used in the fit.
pub sample_count: usize,
}
/// A single detected anomaly.
#[derive(Serialize)]
pub struct Anomaly {
/// Severity level: `"WARN"` or `"ALERT"`.
pub severity: &'static str,
/// System domain: `"ENERGY"`, `"SOLAR"`, `"HVAC"`, or `"SYSTEM"`.
pub domain: &'static str,
/// Human-readable description.
pub message: String,
}
/// Solar array performance vs. theoretical irradiance-based maximum.
#[derive(Serialize)]
pub struct SolarPerformance {
/// Current aggregate AC output in kW.
pub current_kw: f64,
/// Sum of nameplate ratings across all known inverters, in kW.
pub nameplate_kw: f64,
/// Theoretical output given current irradiance: `(gti / 1000) × nameplate`, if GTI available.
pub theoretical_kw: Option<f64>,
/// `current_kw / theoretical_kw`, clamped to `[0, 1]`, if GTI available.
pub performance_ratio: Option<f64>,
/// Accumulated production today in kWh.
pub today_kwh: f64,
/// Global tilted irradiance in W/m² from the weather connector, if available.
pub gti_wm2: Option<f64>,
}
/// Per-unit HVAC operating snapshot.
#[derive(Serialize)]
pub struct HvacUnitIntel {
pub name: String,
pub mode: String,
pub cop: Option<f64>,
pub total_power_w: Option<f64>,
pub ewt_f: Option<f64>,
pub lwt_f: Option<f64>,
pub zone_temp_f: Option<f64>,
pub setpoint_f: Option<f64>,
}
/// HVAC system snapshot.
#[derive(Serialize)]
pub struct HvacStats {
pub units: Vec<HvacUnitIntel>,
/// Weighted-average COP across all active units.
pub overall_cop: Option<f64>,
}
/// Billing intelligence derived from imported utility bills.
#[derive(Serialize)]
pub struct BillingIntel {
/// Total number of imported bill months.
pub total_months: usize,
/// Number of months with net kWh export (usage_kwh < 0).
pub export_months: usize,
/// Sum of all positive-usage months in kWh (net grid imports).
pub lifetime_import_kwh: f64,
/// Sum of absolute-value negative-usage months in kWh (net grid exports).
pub lifetime_export_kwh: f64,
/// `lifetime_import_kwh - lifetime_export_kwh` (positive = net importer).
pub net_kwh: f64,
/// Trailing-12-month average rate in ¢/kWh (import months only).
pub avg_cents_per_kwh: Option<f64>,
/// Projected current-month bill cost in USD.
///
/// Computed as `avg_daily_import_kwh × days_in_month × avg_rate / 100`.
/// Uses trailing-12-month average daily import usage.
pub projected_month_cost_usd: Option<f64>,
/// Trailing-12-month total cost in USD.
pub trailing_12mo_cost_usd: Option<f64>,
/// Trailing-12-month total net kWh.
pub trailing_12mo_kwh: Option<f64>,
}
// ── Field helpers (mirrors panels.rs) ────────────────────────────────────────
fn field_f64(fields: &std::collections::HashMap<String, FieldValue>, key: &str) -> f64 {
match fields.get(key) {
Some(FieldValue::Float(v)) => *v,
Some(FieldValue::Integer(v)) => *v as f64,
Some(FieldValue::UInteger(v)) => *v as f64,
_ => 0.0,
}
}
fn field_u64(fields: &std::collections::HashMap<String, FieldValue>, key: &str) -> u64 {
match fields.get(key) {
Some(FieldValue::UInteger(v)) => *v,
Some(FieldValue::Integer(v)) => (*v).max(0) as u64,
Some(FieldValue::Float(v)) => *v as u64,
_ => 0,
}
}
fn field_str<'a>(
fields: &'a std::collections::HashMap<String, FieldValue>,
key: &str,
default: &'a str,
) -> String {
match fields.get(key) {
Some(FieldValue::String(s)) => s.clone(),
_ => default.to_string(),
}
}
// ── Section builders ──────────────────────────────────────────────────────────
async fn build_system(state: &AppState) -> Option<SystemStats> {
let cache = state.cache.all().await;
let entry = cache
.values()
.find(|c| matches!(c.event.category, DeviceCategory::System))?;
// Count distinct non-system metric sources as a proxy for active connectors.
let active_sources = cache
.values()
.filter(|c| !matches!(c.event.category, DeviceCategory::System))
.map(|c| &c.event.source)
.collect::<std::collections::HashSet<_>>()
.len();
Some(SystemStats {
cpu_pct: field_f64(&entry.event.fields, "cpu_pct"),
mem_used_mb: field_f64(&entry.event.fields, "mem_used_mb"),
mem_total_mb: field_f64(&entry.event.fields, "mem_total_mb"),
uptime_secs: field_u64(&entry.event.fields, "uptime_secs"),
active_sources,
version: state.version.clone(),
})
}
async fn build_solar(state: &AppState) -> Option<SolarPerformance> {
let cache = state.cache.all().await;
// Sum AC power across all solar inverters.
let mut total_kw = 0.0_f64;
let mut inverter_count = 0usize;
for entry in cache.values() {
if matches!(entry.event.category, DeviceCategory::Solar)
&& entry.event.measurement == "ac_measurements"
{
total_kw += field_f64(&entry.event.fields, "power") / 1000.0;
inverter_count += 1;
}
}
if inverter_count == 0 {
return None;
}
// Nameplate: 5 kW per inverter (SMA Sunny Boy 5.0-US default).
let nameplate_kw = 5.0 * inverter_count as f64;
// Today's production from the production measurement.
let today_kwh: f64 = cache
.iter()
.filter(|(key, entry)| {
key.starts_with("production:") && matches!(entry.event.category, DeviceCategory::Solar)
})
.map(|(_, entry)| field_f64(&entry.event.fields, "current"))
.sum::<f64>()
/ 1000.0;
// GTI from the weather hourly measurement.
let gti_wm2 = cache
.values()
.find(|c| c.event.measurement == "weather_hourly")
.map(|c| field_f64(&c.event.fields, "gti_wm2"))
.filter(|v| *v > 0.0);
let theoretical_kw = gti_wm2.map(|gti| gti / 1000.0 * nameplate_kw);
let performance_ratio = theoretical_kw
.filter(|t| *t > 0.0)
.map(|t| (total_kw / t).clamp(0.0, 1.0));
Some(SolarPerformance {
current_kw: total_kw,
nameplate_kw,
theoretical_kw,
performance_ratio,
today_kwh,
gti_wm2,
})
}
async fn build_hvac(state: &AppState) -> Option<HvacStats> {
let cache = state.cache.all().await;
let units: Vec<HvacUnitIntel> = cache
.values()
.filter(|c| matches!(c.event.category, DeviceCategory::Hvac))
.map(|c| {
let f = &c.event.fields;
let cop_raw = field_f64(f, "cop");
let power_raw = field_f64(f, "total_power_w");
let ewt_raw = field_f64(f, "ewt_f");
let lwt_raw = field_f64(f, "lwt_f");
let zone_raw = field_f64(f, "zone_temp_f");
let setp_raw = field_f64(f, "setpoint_f");
HvacUnitIntel {
name: c.event.source.clone(),
mode: field_str(f, "mode", "IDLE"),
cop: (cop_raw != 0.0).then_some(cop_raw),
total_power_w: (power_raw != 0.0).then_some(power_raw),
ewt_f: (ewt_raw != 0.0).then_some(ewt_raw),
lwt_f: (lwt_raw != 0.0).then_some(lwt_raw),
zone_temp_f: (zone_raw != 0.0).then_some(zone_raw),
setpoint_f: (setp_raw != 0.0).then_some(setp_raw),
}
})
.collect();
if units.is_empty() {
return None;
}
// Weighted-average COP (same logic as panels.rs).
let weighted: Vec<(f64, f64)> = units
.iter()
.filter_map(|u| u.cop.zip(u.total_power_w))
.collect();
let overall_cop = if !weighted.is_empty() {
let total_w: f64 = weighted.iter().map(|(_, w)| w).sum();
if total_w > 0.0 {
Some(weighted.iter().map(|(c, w)| c * w).sum::<f64>() / total_w)
} else {
None
}
} else {
let cops: Vec<f64> = units.iter().filter_map(|u| u.cop).collect();
if cops.is_empty() {
None
} else {
Some(cops.iter().sum::<f64>() / cops.len() as f64)
}
};
let mut sorted = units;
sorted.sort_by(|a, b| a.name.cmp(&b.name));
Some(HvacStats {
units: sorted,
overall_cop,
})
}
async fn build_billing_intel(state: &AppState) -> Option<BillingIntel> {
let rows = fetch_rows_pub(state).await?;
if rows.is_empty() {
return None;
}
let total_months = rows.len();
let export_months = rows
.iter()
.filter(|r| r.usage_kwh.is_some_and(|k| k < 0.0))
.count();
let lifetime_import_kwh: f64 = rows
.iter()
.filter_map(|r| r.usage_kwh)
.filter(|k| *k > 0.0)
.sum();
let lifetime_export_kwh: f64 = rows
.iter()
.filter_map(|r| r.usage_kwh)
.filter(|k| *k < 0.0)
.map(|k| k.abs())
.sum();
let net_kwh = lifetime_import_kwh - lifetime_export_kwh;
// Trailing 12 months.
let trailing: Vec<_> = rows.iter().take(12).collect();
let trailing_12mo_kwh: Option<f64> = {
let v: f64 = trailing.iter().filter_map(|r| r.usage_kwh).sum();
if trailing.is_empty() {
None
} else {
Some(v)
}
};
let trailing_12mo_cost_usd: Option<f64> = {
let v: f64 = trailing.iter().filter_map(|r| r.cost_usd).sum();
if v == 0.0 {
None
} else {
Some(v)
}
};
// Average rate from import months in trailing 12.
let import_months: Vec<_> = trailing
.iter()
.filter(|r| r.usage_kwh.is_some_and(|k| k > 0.0))
.collect();
let avg_cents_per_kwh = if import_months.is_empty() {
None
} else {
let total_cost: f64 = import_months.iter().filter_map(|r| r.cost_usd).sum();
let total_kwh: f64 = import_months.iter().filter_map(|r| r.usage_kwh).sum();
if total_kwh > 0.0 {
Some(total_cost / total_kwh * 100.0)
} else {
None
}
};
// Projection: avg daily import × days in current month × avg rate.
let projected_month_cost_usd = avg_cents_per_kwh.and_then(|rate| {
let import_kwh: f64 = import_months.iter().filter_map(|r| r.usage_kwh).sum();
let import_count = import_months.len() as f64;
if import_count == 0.0 {
return None;
}
let avg_monthly_kwh = import_kwh / import_count;
let now = Local::now();
// Days in current month using last day.
let days_in_month = {
let y = now.year();
let m = now.month();
let next = if m == 12 {
chrono::NaiveDate::from_ymd_opt(y + 1, 1, 1)
} else {
chrono::NaiveDate::from_ymd_opt(y, m + 1, 1)
};
next.and_then(|d| d.pred_opt())
.map(|d| d.day() as f64)
.unwrap_or(30.0)
};
Some(avg_monthly_kwh / 30.0 * days_in_month * rate / 100.0)
});
Some(BillingIntel {
total_months,
export_months,
lifetime_import_kwh,
lifetime_export_kwh,
net_kwh,
avg_cents_per_kwh,
projected_month_cost_usd,
trailing_12mo_cost_usd,
trailing_12mo_kwh,
})
}
// ── Heat loss ─────────────────────────────────────────────────────────────────
/// Fit a UA heat-loss coefficient from 30 days of hourly InfluxDB history.
///
/// Pairs `hvac_kw` samples from `power_history` with outdoor `temp_f` samples
/// from `weather_current`, aligning them to the nearest hour. For each matched
/// pair where the system is actively heating (hvac_kw > 0.5) and ΔT > 5°F,
/// computes:
///
/// ```text
/// UA = (hvac_kw × 3412 BTU/hr/kW) / (setpoint_f − outdoor_temp_f)
/// ```
///
/// Uses forced-zero least-squares regression (sum(Q×ΔT) / sum(ΔT²)) which is
/// more robust than averaging per-sample UA ratios when load varies.
async fn build_heat_loss(state: &AppState) -> Option<HeatLoss> {
let influx = state.influx.as_ref()?;
const RANGE_S: u64 = 30 * 24 * 3600;
const WINDOW_S: u64 = 3600;
// Fetch hvac_kw and outdoor temp in parallel.
let (hvac_res, temp_res) = tokio::join!(
influx.query_field("power_history", "hvac_kw", RANGE_S, WINDOW_S),
influx.query_field("weather_current", "temp_f", RANGE_S, WINDOW_S),
);
let hvac_series = hvac_res
.map_err(|e| tracing::debug!("heat_loss hvac query: {e}"))
.ok()?;
let temp_series = temp_res
.map_err(|e| tracing::debug!("heat_loss temp query: {e}"))
.ok()?;
if hvac_series.is_empty() || temp_series.is_empty() {
return None;
}
// Get indoor setpoint from cache — average all valid HVAC setpoints for
// a deterministic result regardless of HashMap iteration order.
let cache = state.cache.all().await;
let (sp_sum, sp_count) = cache
.values()
.filter(|c| matches!(c.event.category, DeviceCategory::Hvac))
.fold((0.0_f64, 0usize), |(sum, n), c| {
let v = field_f64(&c.event.fields, "setpoint_f");
if v > 0.0 {
(sum + v, n + 1)
} else {
(sum, n)
}
});
let indoor_setpoint_f = if sp_count > 0 {
sp_sum / sp_count as f64
} else {
70.0
};
// Align temp samples into a lookup by hour bucket (ts_ms rounded to hour).
let hour_ms: i64 = WINDOW_S as i64 * 1000;
let temp_lookup: std::collections::HashMap<i64, f64> = temp_series
.iter()
.map(|s| (s.ts_ms / hour_ms * hour_ms, s.value))
.collect();
// Least-squares forced-zero regression: UA = Σ(Q × ΔT) / Σ(ΔT²)
let mut sum_q_dt = 0.0_f64;
let mut sum_dt_sq = 0.0_f64;
let mut count = 0usize;
for sample in &hvac_series {
let hvac_kw = sample.value;
if hvac_kw < 0.5 {
continue; // system not actively heating
}
let bucket = sample.ts_ms / hour_ms * hour_ms;
let outdoor_temp = match temp_lookup.get(&bucket) {
Some(&t) => t,
None => continue,
};
let delta_t = indoor_setpoint_f - outdoor_temp;
if delta_t < 5.0 {
continue; // ΔT too small — noisy estimate
}
let q_btu_hr = hvac_kw * 3412.0;
sum_q_dt += q_btu_hr * delta_t;
sum_dt_sq += delta_t * delta_t;
count += 1;
}
if count < 10 || sum_dt_sq == 0.0 {
return None; // too few data points for a reliable fit
}
let ua = sum_q_dt / sum_dt_sq;
let design_delta_t = indoor_setpoint_f - 0.0; // 0°F design outdoor temp
let design_heat_loss_btu_hr = ua * design_delta_t;
let design_heat_loss_kw = design_heat_loss_btu_hr / 3412.0;
Some(HeatLoss {
ua_btu_hr_f: ua,
design_heat_loss_btu_hr,
design_heat_loss_kw,
indoor_setpoint_f,
sample_count: count,
})
}
// ── Anomaly detection ─────────────────────────────────────────────────────────
/// Scan current cache and recent time-series for anomalous conditions.
///
/// Each rule is self-contained. Most rules emit at most one [`Anomaly`], but
/// per-unit HVAC rules (COP, loop flow) can emit one entry per active unit.
/// All rules are checked regardless — multiple anomalies can be active
/// simultaneously.
async fn build_anomalies(state: &AppState) -> Vec<Anomaly> {
let mut anomalies = Vec::new();
let cache = state.cache.all().await;
// ── Energy: load spike ───────────────────────────────────────────────────
// Alert when current home load exceeds 2× the 30-minute trailing average
// AND exceeds an absolute floor of 5 kW (avoids false positives at low load).
{
const THIRTY_MIN_MS: i64 = 30 * 60 * 1_000;
let ts = state.ts.snapshot_for_range(THIRTY_MIN_MS).await;
let energy = cache.values().find(|c| {
matches!(c.event.category, DeviceCategory::Energy)
&& c.event.fields.contains_key("home_kw")
});
if let Some(e) = energy {
let current_kw = field_f64(&e.event.fields, "home_kw");
if current_kw > 5.0 {
if let Some(samples) = ts.get("load_kw") {
let n = samples.len();
if n >= 4 {
let avg: f64 = samples.iter().map(|s| s.value).sum::<f64>() / n as f64;
if avg > 0.1 && current_kw > avg * 2.0 {
anomalies.push(Anomaly {
severity: "ALERT",
domain: "ENERGY",
message: format!(
"Load spike: {:.1} kW is {:.0}× the 30-min avg of {:.1} kW",
current_kw,
current_kw / avg,
avg
),
});
}
}
}
}
}
}
// ── Solar: underperformance ──────────────────────────────────────────────
// Warn when GTI is sufficient for production but performance ratio is low.
{
let solar_kw: f64 = cache
.values()
.filter(|c| {
matches!(c.event.category, DeviceCategory::Solar)
&& c.event.measurement == "ac_measurements"
})
.map(|c| field_f64(&c.event.fields, "power") / 1000.0)
.sum();
let inverter_count = cache
.values()
.filter(|c| {
matches!(c.event.category, DeviceCategory::Solar)
&& c.event.measurement == "ac_measurements"
})
.count();
let gti = cache
.values()
.find(|c| c.event.measurement == "weather_hourly")
.map(|c| field_f64(&c.event.fields, "gti_wm2"))
.unwrap_or(0.0);
if gti > 300.0 && inverter_count > 0 {
let nameplate_kw = 5.0 * inverter_count as f64;
let theoretical = gti / 1000.0 * nameplate_kw;
let ratio = if theoretical > 0.0 {
(solar_kw / theoretical).clamp(0.0, 1.0)
} else {
1.0
};
if ratio < 0.6 {
anomalies.push(Anomaly {
severity: "WARN",
domain: "SOLAR",
message: format!(
"Solar underperforming: {:.0}% of expected output \
({:.2} kW actual vs {:.2} kW theoretical at {:.0} W/m² GTI)",
ratio * 100.0,
solar_kw,
theoretical,
gti
),
});
}
}
}
// ── HVAC: low COP while active ───────────────────────────────────────────
// Warn when the system is running (power > 0) but COP is below 2.0,
// which may indicate refrigerant issues, fouled heat exchanger, or sensor error.
{
let hvac_entries: Vec<_> = cache
.values()
.filter(|c| matches!(c.event.category, DeviceCategory::Hvac))
.collect();
for entry in &hvac_entries {
let cop = field_f64(&entry.event.fields, "cop");
let power = field_f64(&entry.event.fields, "total_power_w");
if power > 200.0 && cop > 0.0 && cop < 2.0 {
anomalies.push(Anomaly {
severity: "WARN",
domain: "HVAC",
message: format!(
"{}: low COP {:.1} while drawing {:.0} W — check refrigerant or loop temps",
entry.event.source, cop, power
),
});
}
}
// Warn if EWT/LWT delta is large (> 10°F) while the system is running.
// Q = flow_gpm × 500 × ΔT, so a large ΔT at a given load means low flow —
// the pump isn't moving enough water through the ground loop. Normal operating
// range is 5–10°F; > 10°F suggests a flow restriction or failing loop pump.
// (A *small* ΔT is normal — it just means low compressor load or high flow.)
for entry in &hvac_entries {
let ewt = field_f64(&entry.event.fields, "ewt_f");
let lwt = field_f64(&entry.event.fields, "lwt_f");
let power = field_f64(&entry.event.fields, "total_power_w");
if power > 200.0 && ewt > 0.0 && lwt > 0.0 && (ewt - lwt).abs() > 10.0 {
anomalies.push(Anomaly {
severity: "WARN",
domain: "HVAC",
message: format!(
"{}: EWT/LWT delta {:.1}°F exceeds normal range — possible loop flow restriction or failing pump",
entry.event.source,
(ewt - lwt).abs()
),
});
}
}
}
// ── System: memory pressure ──────────────────────────────────────────────
{
if let Some(sys) = cache
.values()
.find(|c| matches!(c.event.category, DeviceCategory::System))
{
let used = field_f64(&sys.event.fields, "mem_used_mb");
let total = field_f64(&sys.event.fields, "mem_total_mb");
if total > 0.0 && used / total > 0.85 {
anomalies.push(Anomaly {
severity: "WARN",
domain: "SYSTEM",
message: format!(
"Memory pressure: {:.0}/{:.0} MiB used ({:.0}%)",
used,
total,
used / total * 100.0
),
});
}
}
}
anomalies
}
// ── Handler ───────────────────────────────────────────────────────────────────
/// `GET /api/v1/intel` — aggregated analysis data for the Intel page.
pub async fn get_intel(State(state): State<AppState>) -> Json<IntelResponse> {
let (system, solar, hvac, billing, heat_loss, anomalies) = tokio::join!(
build_system(&state),
build_solar(&state),
build_hvac(&state),
build_billing_intel(&state),
build_heat_loss(&state),
build_anomalies(&state),
);
Json(IntelResponse {
system,
solar,
hvac,
billing,
heat_loss,
anomalies,
})
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::Utc;
use flux_core::{DeviceCategory, FieldValue, MetricEvent};
use std::collections::HashMap;
fn sys_event(cpu: f64, mem_used: f64, mem_total: f64, uptime: u64) -> MetricEvent {
let mut fields = HashMap::new();
fields.insert("cpu_pct".into(), FieldValue::Float(cpu));
fields.insert("mem_used_mb".into(), FieldValue::Float(mem_used));
fields.insert("mem_total_mb".into(), FieldValue::Float(mem_total));
fields.insert("uptime_secs".into(), FieldValue::UInteger(uptime));
MetricEvent {
timestamp: Utc::now(),
source: "fluxd".into(),
category: DeviceCategory::System,
measurement: "process_metrics".into(),
tags: HashMap::new(),
fields,
}
}
#[test]
fn system_stats_field_extraction() {
let event = sys_event(23.5, 512.0, 4096.0, 3600);
let f = &event.fields;
assert!((field_f64(f, "cpu_pct") - 23.5).abs() < 0.001);
assert!((field_f64(f, "mem_used_mb") - 512.0).abs() < 0.001);
assert!((field_f64(f, "mem_total_mb") - 4096.0).abs() < 0.001);
assert_eq!(field_u64(f, "uptime_secs"), 3600);
}
#[test]
fn field_u64_from_integer_variant() {
let mut fields = HashMap::new();
fields.insert("x".into(), FieldValue::Integer(42));
assert_eq!(field_u64(&fields, "x"), 42);
}
#[test]
fn field_u64_missing_key_returns_zero() {
let fields: HashMap<String, FieldValue> = HashMap::new();
assert_eq!(field_u64(&fields, "missing"), 0);
}
// ── Heat loss UA fitting ──────────────────────────────────────────────────
/// Simulate the regression logic in `build_heat_loss` with known values.
///
/// Uses setpoint = 70°F, outdoor = 20°F → ΔT = 50°F, hvac_kw = 5.0
/// Q = 5.0 × 3412 = 17060 BTU/hr → UA = 17060 / 50 = 341.2 BTU/hr/°F
#[test]
fn ua_regression_known_values() {
let setpoint = 70.0_f64;
let outdoor = 20.0_f64;
let hvac_kw = 5.0_f64;
let delta_t = setpoint - outdoor; // 50
let q = hvac_kw * 3412.0; // 17060
// Regression with a single perfectly consistent point:
// UA = Σ(Q×ΔT) / Σ(ΔT²) = (Q × ΔT) / ΔT² = Q / ΔT
let sum_q_dt = q * delta_t;
let sum_dt_sq = delta_t * delta_t;
let ua = sum_q_dt / sum_dt_sq;
assert!((ua - 341.2).abs() < 0.1, "expected 341.2, got {ua}");
}
#[test]
fn ua_regression_averages_multiple_points() {
// Two points: same UA (200 BTU/hr/°F) at different loads.
// Point A: ΔT=40, hvac_kw=2.342 → Q=7991 → UA=200
// Point B: ΔT=60, hvac_kw=3.513 → Q=11987 → UA=200
let points = [(40.0_f64, 2.342_f64), (60.0_f64, 3.513_f64)];
let (mut sum_qdt, mut sum_dt2) = (0.0_f64, 0.0_f64);
for (dt, kw) in points {
let q = kw * 3412.0;
sum_qdt += q * dt;
sum_dt2 += dt * dt;
}
let ua = sum_qdt / sum_dt2;
assert!((ua - 200.0).abs() < 1.0, "expected ~200, got {ua}");
}
#[test]
fn design_heat_loss_scales_with_delta_t() {
let ua = 300.0_f64; // BTU/hr/°F
let setpoint = 70.0_f64;
let design_outdoor = 0.0_f64;
let design_dt = setpoint - design_outdoor; // 70
let design_btu_hr = ua * design_dt; // 21000
let design_kw = design_btu_hr / 3412.0;
assert!((design_btu_hr - 21_000.0).abs() < 0.1);
assert!((design_kw - 6.155).abs() < 0.01);
}
// ── Anomaly detection helpers ─────────────────────────────────────────────
#[test]
fn load_spike_detection_threshold() {
// Should alert: 12 kW current, 5 kW avg → 2.4× ratio, above 5 kW floor
let current_kw = 12.0_f64;
let avg_kw = 5.0_f64;
assert!(current_kw > 5.0 && avg_kw > 0.1 && current_kw > avg_kw * 2.0);
}
#[test]
fn load_spike_no_alert_below_floor() {
// Should NOT alert: 3 kW current is 3× avg but below the 5 kW absolute floor
let current_kw = 3.0_f64;
let avg_kw = 1.0_f64;
assert!(!(current_kw > 5.0 && avg_kw > 0.1 && current_kw > avg_kw * 2.0));
}
#[test]
fn solar_underperformance_threshold() {
// GTI 600 W/m², nameplate 10 kW → theoretical 6 kW, actual 2 kW → ratio 0.33 → alert
let gti = 600.0_f64;
let nameplate = 10.0_f64;
let actual = 2.0_f64;
let theoretical = gti / 1000.0 * nameplate;
let ratio = (actual / theoretical).clamp(0.0, 1.0);
assert!(gti > 300.0 && ratio < 0.6);
}
#[test]
fn low_cop_threshold() {
// COP 1.5 with 500 W draw → warn
let cop = 1.5_f64;
let power_w = 500.0_f64;
assert!(power_w > 200.0 && cop > 0.0 && cop < 2.0);
}
#[test]
fn loop_flow_restriction_fires_on_large_delta() {
// Large EWT/LWT delta → restricted flow (loop not moving enough water)
let ewt = 55.0_f64;
let lwt = 44.0_f64; // delta = 11°F — exceeds 10°F threshold
let power_w = 1500.0_f64;
assert!(power_w > 200.0 && ewt > 0.0 && lwt > 0.0 && (ewt - lwt).abs() > 10.0);
}
#[test]
fn loop_flow_restriction_silent_on_normal_delta() {
// 1.9°F delta (like the real 7-series case that prompted this fix) must not warn.
// Small delta = low load or high flow rate — both normal.
let ewt = 43.3_f64;
let lwt = 41.4_f64; // delta = 1.9°F
let power_w = 800.0_f64;
assert!(!(power_w > 200.0 && ewt > 0.0 && lwt > 0.0 && (ewt - lwt).abs() > 10.0));
}
}