prosa-teleinfo 0.2.1

ProSA processor for Enedis (French electricity network) Teleinfo
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
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
use opentelemetry::{
    KeyValue,
    global::{BoxedSpan, BoxedTracer},
    trace::{Span, Tracer as _},
};

use prosa::core::proc::ProcConfig as _;
use tokio::sync::watch;

use crate::{
    proc::{TeleinfoProc, TeleinfoSettings},
    teleinfo::{OpTarif, RateColor, RatePeriod, TeleinfoFrame},
};

/// Teleinfo Data aggregation
#[derive(Debug)]
pub struct TeleinfoObservability {
    settings: TeleinfoSettings,
    tracer: BoxedTracer,

    /// Name of the counter use as address
    address: String,

    // Traces
    period_span: Option<BoxedSpan>,
    index_low_hour_span: [u32; 3],
    index_high_hour_span: [u32; 3],

    // Contract metrics
    tarif_option: watch::Sender<OpTarif>,
    subscribe_amps: watch::Sender<u8>,
    max_current: watch::Sender<[u16; 3]>,

    // Consumption
    index_base_hour: watch::Sender<u32>,
    index_low_hour: watch::Sender<[u32; 3]>,
    index_high_hour: watch::Sender<[u32; 3]>,

    // Instantaneous
    color: watch::Sender<RateColor>,
    tomorrow_color: watch::Sender<RateColor>,
    tarif_period: watch::Sender<RatePeriod>,
    instantaneous_voltage: watch::Sender<[u16; 3]>,
    instantaneous_current: watch::Sender<[u16; 3]>,
    instantaneous_power: watch::Sender<u32>,
    power_direction: watch::Sender<bool>,
}

impl TeleinfoObservability {
    /// Create new Teleinfo observability to monitor Teleinfo data
    pub fn new<M>(address: String, proc: &TeleinfoProc<M>) -> TeleinfoObservability
    where
        M: 'static
            + std::marker::Send
            + std::marker::Sync
            + std::marker::Sized
            + std::clone::Clone
            + std::fmt::Debug
            + prosa_utils::msg::tvf::Tvf
            + std::default::Default,
    {
        let meter = proc.get_proc_param().meter("teleinfo");

        // Teleinfo contract metrics
        let meter_address = address.clone();
        let (tarif_option, watch_tarif_option) = watch::channel(OpTarif::default());
        let (subscribe_amps, watch_subscribe_amps) = watch::channel(0u8);
        let (max_current, watch_max_current) = watch::channel([0u16; 3]);
        let _observable_contract_gauge = meter
            .u64_observable_gauge("prosa_teleinfo_contract")
            .with_description("Subscribed contract options")
            .with_callback(move |observer| {
                observer.observe(
                    (&(*watch_tarif_option.borrow())).into(),
                    &[
                        KeyValue::new("address", meter_address.clone()),
                        KeyValue::new("type", "tarif_opt"),
                    ],
                );

                let subscribe_amps = *watch_subscribe_amps.borrow();
                if subscribe_amps > 0 {
                    observer.observe(
                        subscribe_amps as u64,
                        &[
                            KeyValue::new("address", meter_address.clone()),
                            KeyValue::new("type", "subscribe_amps"),
                        ],
                    );
                }

                let max_current = *watch_max_current.borrow();
                if max_current[1] > 0 || max_current[2] > 0 {
                    (0..=2).for_each(|i| {
                        observer.observe(
                            max_current[i] as u64,
                            &[
                                KeyValue::new("address", meter_address.clone()),
                                KeyValue::new("type", "max_current"),
                                KeyValue::new("phase", (i + 1).to_string()),
                            ],
                        );
                    });
                } else {
                    observer.observe(
                        max_current[0] as u64,
                        &[
                            KeyValue::new("address", meter_address.clone()),
                            KeyValue::new("type", "max_current"),
                            KeyValue::new("phase", "1"),
                        ],
                    );
                }
            })
            .build();

        // Teleinfo consumption metrics
        let meter_address = address.clone();
        let (index_base_hour, watch_index_base_hour) = watch::channel(0u32);
        let (index_low_hour, watch_index_low_hour) = watch::channel([0u32; 3]);
        let (index_high_hour, watch_index_high_hour) = watch::channel([0u32; 3]);
        let _observable_consumption_counter = meter
            .u64_observable_counter("prosa_teleinfo_consumption")
            .with_description("Electricity consumption")
            .with_unit("watth")
            .with_callback(move |observer| {
                let index_base_hour = *watch_index_base_hour.borrow();
                if index_base_hour > 0 {
                    observer.observe(
                        index_base_hour as u64,
                        &[
                            KeyValue::new("address", meter_address.clone()),
                            KeyValue::new("type", "base"),
                        ],
                    );
                }

                let index_low_hour = *watch_index_low_hour.borrow();
                for color in RateColor::values() {
                    if index_low_hour[color as usize - 1] > 0 {
                        observer.observe(
                            index_low_hour[color as usize - 1] as u64,
                            &[
                                KeyValue::new("address", meter_address.clone()),
                                KeyValue::new("type", "hc"),
                                KeyValue::new("color", color.to_string().to_ascii_lowercase()),
                            ],
                        );
                    }
                }

                let index_high_hour = *watch_index_high_hour.borrow();
                for color in RateColor::values() {
                    if index_high_hour[color as usize - 1] > 0 {
                        observer.observe(
                            index_high_hour[color as usize - 1] as u64,
                            &[
                                KeyValue::new("address", meter_address.clone()),
                                KeyValue::new("type", "hp"),
                                KeyValue::new("color", color.to_string().to_ascii_lowercase()),
                            ],
                        );
                    }
                }
            })
            .build();

        // Teleinfo instantaneous metrics
        let meter_address = address.clone();
        let (color, watch_color) = watch::channel(RateColor::default());
        let (tomorrow_color, watch_tomorrow_color) = watch::channel(RateColor::default());
        let (tarif_period, watch_tarif_period) = watch::channel(RatePeriod::default());
        let (instantaneous_voltage, watch_instantaneous_voltage) = watch::channel([0u16; 3]);
        let (instantaneous_current, watch_instantaneous_current) = watch::channel([0u16; 3]);
        let (instantaneous_power, watch_instantaneous_power) = watch::channel(0u32);
        let (power_direction, watch_power_direction) = watch::channel(false);
        let _observable_contract_gauge = meter
            .u64_observable_gauge("prosa_teleinfo_instantaneous")
            .with_description("Instantaneous Teleinfo data")
            .with_callback(move |observer| {
                observer.observe(
                    *watch_color.borrow() as u64,
                    &[
                        KeyValue::new("address", meter_address.clone()),
                        KeyValue::new("type", "color"),
                    ],
                );

                observer.observe(
                    *watch_tomorrow_color.borrow() as u64,
                    &[
                        KeyValue::new("address", meter_address.clone()),
                        KeyValue::new("type", "tomorrow_color"),
                    ],
                );

                observer.observe(
                    *watch_tarif_period.borrow() as u64,
                    &[
                        KeyValue::new("address", meter_address.clone()),
                        KeyValue::new("type", "period"),
                        KeyValue::new(
                            "color",
                            watch_color.borrow().to_string().to_ascii_lowercase(),
                        ),
                    ],
                );

                let instantaneous_voltage = *watch_instantaneous_voltage.borrow();
                if instantaneous_voltage[1] > 0 || instantaneous_voltage[2] > 0 {
                    (0..=2).for_each(|i| {
                        observer.observe(
                            instantaneous_voltage[i] as u64,
                            &[
                                KeyValue::new("address", meter_address.clone()),
                                KeyValue::new("type", "voltage"),
                                KeyValue::new("phase", (i + 1).to_string()),
                            ],
                        );
                    });
                } else {
                    observer.observe(
                        instantaneous_voltage[0] as u64,
                        &[
                            KeyValue::new("address", meter_address.clone()),
                            KeyValue::new("type", "voltage"),
                            KeyValue::new("phase", "1"),
                        ],
                    );
                }

                let instantaneous_current = *watch_instantaneous_current.borrow();
                if instantaneous_current[1] > 0 || instantaneous_current[2] > 0 {
                    (0..=2).for_each(|i| {
                        observer.observe(
                            instantaneous_current[i] as u64,
                            &[
                                KeyValue::new("address", meter_address.clone()),
                                KeyValue::new("type", "current"),
                                KeyValue::new("phase", (i + 1).to_string()),
                            ],
                        );
                    });
                } else {
                    observer.observe(
                        instantaneous_current[0] as u64,
                        &[
                            KeyValue::new("address", meter_address.clone()),
                            KeyValue::new("type", "current"),
                            KeyValue::new("phase", "1"),
                        ],
                    );
                }

                let instantaneous_power = *watch_instantaneous_power.borrow();
                if instantaneous_power > 0 {
                    observer.observe(
                        instantaneous_power as u64,
                        &[
                            KeyValue::new("address", meter_address.clone()),
                            KeyValue::new("type", "power"),
                        ],
                    );
                }

                let power_direction = *watch_power_direction.borrow();
                observer.observe(
                    if power_direction { 1 } else { 0 },
                    &[
                        KeyValue::new("address", meter_address.clone()),
                        KeyValue::new("type", "power_direction"),
                    ],
                );
            })
            .build();

        TeleinfoObservability {
            settings: proc.settings.clone(),
            tracer: BoxedTracer::new(Box::new(proc.get_proc_param().tracer("teleinfo"))),
            address,
            period_span: None,
            index_low_hour_span: [0u32; 3],
            index_high_hour_span: [0u32; 3],
            tarif_option,
            subscribe_amps,
            max_current,
            index_base_hour,
            index_low_hour,
            index_high_hour,
            color,
            tomorrow_color,
            tarif_period,
            instantaneous_voltage,
            instantaneous_current,
            instantaneous_power,
            power_direction,
        }
    }

    /// Function call when a new period begin
    fn new_period(&mut self, new_period: RatePeriod) {
        if let Some(span) = &mut self.period_span {
            span.set_attributes([KeyValue::new("address", self.address.clone())]);

            let mut consumption = 0;
            let mut price = 0f64;

            // HC
            let current_index_low_hour = self.index_low_hour.borrow();
            for color in RateColor::values() {
                let color_consumption = current_index_low_hour[color as usize - 1]
                    - self.index_low_hour_span[color as usize - 1];
                if color_consumption > 0 {
                    consumption += color_consumption;
                    price +=
                        (color_consumption as f64) * self.settings.get_price(color, RatePeriod::HC);
                }
            }

            // HP
            let current_index_high_hour = self.index_high_hour.borrow();
            for color in RateColor::values() {
                let color_consumption = current_index_high_hour[color as usize - 1]
                    - self.index_high_hour_span[color as usize - 1];
                if color_consumption > 0 {
                    consumption += color_consumption;
                    price +=
                        (color_consumption as f64) * self.settings.get_price(color, RatePeriod::HP);
                }
            }

            let span_consumption = consumption as f64 / 1000f64;
            span.add_event(
                format!("Consuption of the period: {span_consumption} kW/h"),
                vec![KeyValue::new("consumption", span_consumption.to_string())],
            );
            let span_price = price.round() / 100f64;
            span.add_event(
                format!("Price of the period: {span_price} €"),
                vec![KeyValue::new("price", span_price.to_string())],
            );

            span.end();
        }

        if new_period == RatePeriod::HP {
            let span = self.tracer.start("teleinfo/hp");
            self.period_span = Some(span);

            // Reset index for next period
            self.index_low_hour_span = [0u32; 3];
            self.index_high_hour_span = [0u32; 3];
        } else if new_period == RatePeriod::HC {
            let span = self.tracer.start("teleinfo/hc");
            self.period_span = Some(span);

            // Reset index for next period
            self.index_low_hour_span = [0u32; 3];
            self.index_high_hour_span = [0u32; 3];
        }
    }

    /// Method to process incomming teleinfo frame and gather metrics from it
    pub fn process_teleinfo(&mut self, frame: &TeleinfoFrame) {
        match frame {
            TeleinfoFrame::OPTARIF(tarif) => {
                let _ = self.tarif_option.send(*tarif);
            }
            TeleinfoFrame::NGTF(contract_type) => {
                // FIXME Add other value for contract types
                if contract_type.contains("TEMPO") {
                    let _ = self.tarif_option.send(OpTarif::BBRx(0));
                } else {
                    let _ = self.tarif_option.send(OpTarif::BASE);
                }
            }
            TeleinfoFrame::ISOUSC(amps) => {
                let _ = self.subscribe_amps.send(*amps);
            }
            TeleinfoFrame::IMAX(phase, amps) => {
                let phase = if *phase > 0 && *phase <= 3 {
                    (phase - 1) as usize
                } else {
                    0
                };
                self.max_current.send_modify(|max| max[phase] = *amps);
            }
            TeleinfoFrame::BASE(wh) => {
                let _ = self.index_base_hour.send(*wh);
            }
            TeleinfoFrame::HCHC(wh) => {
                self.index_low_hour
                    .send_modify(|low_hour| low_hour[RateColor::BLUE as usize - 1] = *wh);
                if self.index_low_hour_span[RateColor::BLUE as usize - 1] == 0 {
                    self.index_low_hour_span[RateColor::BLUE as usize - 1] = *wh;
                }
            }
            TeleinfoFrame::HCHP(wh) => {
                self.index_high_hour
                    .send_modify(|high_hour| high_hour[RateColor::BLUE as usize - 1] = *wh);
                if self.index_high_hour_span[RateColor::BLUE as usize - 1] == 0 {
                    self.index_high_hour_span[RateColor::BLUE as usize - 1] = *wh;
                }
            }
            TeleinfoFrame::EJPHN(wh) => {
                self.index_low_hour
                    .send_modify(|low_hour| low_hour[RateColor::BLUE as usize - 1] = *wh);
                if self.index_low_hour_span[RateColor::BLUE as usize - 1] == 0 {
                    self.index_low_hour_span[RateColor::BLUE as usize - 1] = *wh;
                }
            }
            TeleinfoFrame::EJPHPM(wh) => {
                self.index_high_hour
                    .send_modify(|high_hour| high_hour[RateColor::RED as usize - 1] = *wh);
                if self.index_high_hour_span[RateColor::RED as usize - 1] == 0 {
                    self.index_high_hour_span[RateColor::RED as usize - 1] = *wh;
                }
            }
            TeleinfoFrame::BBRHCJB(wh) => {
                self.index_low_hour
                    .send_modify(|low_hour| low_hour[RateColor::BLUE as usize - 1] = *wh);
                if self.index_low_hour_span[RateColor::BLUE as usize - 1] == 0 {
                    self.index_low_hour_span[RateColor::BLUE as usize - 1] = *wh;
                }
            }
            TeleinfoFrame::BBRHPJB(wh) => {
                self.index_high_hour
                    .send_modify(|high_hour| high_hour[RateColor::BLUE as usize - 1] = *wh);
                if self.index_high_hour_span[RateColor::BLUE as usize - 1] == 0 {
                    self.index_high_hour_span[RateColor::BLUE as usize - 1] = *wh;
                }
            }
            TeleinfoFrame::BBRHCJW(wh) => {
                self.index_low_hour
                    .send_modify(|low_hour| low_hour[RateColor::WHITE as usize - 1] = *wh);
                if self.index_low_hour_span[RateColor::WHITE as usize - 1] == 0 {
                    self.index_low_hour_span[RateColor::WHITE as usize - 1] = *wh;
                }
            }
            TeleinfoFrame::BBRHPJW(wh) => {
                self.index_high_hour
                    .send_modify(|high_hour| high_hour[RateColor::WHITE as usize - 1] = *wh);
                if self.index_high_hour_span[RateColor::WHITE as usize - 1] == 0 {
                    self.index_high_hour_span[RateColor::WHITE as usize - 1] = *wh;
                }
            }
            TeleinfoFrame::BBRHCJR(wh) => {
                self.index_low_hour
                    .send_modify(|low_hour| low_hour[RateColor::RED as usize - 1] = *wh);
                if self.index_low_hour_span[RateColor::RED as usize - 1] == 0 {
                    self.index_low_hour_span[RateColor::RED as usize - 1] = *wh;
                }
            }
            TeleinfoFrame::BBRHPJR(wh) => {
                self.index_high_hour
                    .send_modify(|high_hour| high_hour[RateColor::RED as usize - 1] = *wh);
                if self.index_high_hour_span[RateColor::RED as usize - 1] == 0 {
                    self.index_high_hour_span[RateColor::RED as usize - 1] = *wh;
                }
            }
            TeleinfoFrame::EASF(index, wh) => {
                let tarif_option = self.tarif_option.borrow();
                match index {
                    1 => {
                        if *tarif_option == OpTarif::BASE {
                            let _ = self.index_base_hour.send(*wh);
                        } else {
                            self.index_low_hour.send_modify(|low_hour| {
                                low_hour[RateColor::BLUE as usize - 1] = *wh
                            });
                            if self.index_low_hour_span[RateColor::BLUE as usize - 1] == 0 {
                                self.index_low_hour_span[RateColor::BLUE as usize - 1] = *wh;
                            }
                        }
                    }
                    2 => {
                        if *tarif_option != OpTarif::EJP {
                            self.index_high_hour.send_modify(|high_hour| {
                                high_hour[RateColor::BLUE as usize - 1] = *wh
                            });
                            if self.index_high_hour_span[RateColor::BLUE as usize - 1] == 0 {
                                self.index_high_hour_span[RateColor::BLUE as usize - 1] = *wh;
                            }
                        } else {
                            self.index_high_hour.send_modify(|high_hour| {
                                high_hour[RateColor::RED as usize - 1] = *wh
                            });
                            if self.index_high_hour_span[RateColor::RED as usize - 1] == 0 {
                                self.index_high_hour_span[RateColor::RED as usize - 1] = *wh;
                            }
                        }
                    }
                    3 => {
                        if let OpTarif::BBRx(_) = *tarif_option {
                            self.index_low_hour.send_modify(|low_hour| {
                                low_hour[RateColor::WHITE as usize - 1] = *wh
                            });
                            if self.index_low_hour_span[RateColor::WHITE as usize - 1] == 0 {
                                self.index_low_hour_span[RateColor::WHITE as usize - 1] = *wh;
                            }
                        }
                    }
                    4 => {
                        if let OpTarif::BBRx(_) = *tarif_option {
                            self.index_high_hour.send_modify(|high_hour| {
                                high_hour[RateColor::WHITE as usize - 1] = *wh
                            });
                            if self.index_high_hour_span[RateColor::WHITE as usize - 1] == 0 {
                                self.index_high_hour_span[RateColor::WHITE as usize - 1] = *wh;
                            }
                        }
                    }
                    5 => {
                        if let OpTarif::BBRx(_) = *tarif_option {
                            self.index_low_hour.send_modify(|low_hour| {
                                low_hour[RateColor::RED as usize - 1] = *wh
                            });
                            if self.index_low_hour_span[RateColor::RED as usize - 1] == 0 {
                                self.index_low_hour_span[RateColor::RED as usize - 1] = *wh;
                            }
                        }
                    }
                    6 => {
                        if let OpTarif::BBRx(_) = *tarif_option {
                            self.index_high_hour.send_modify(|high_hour| {
                                high_hour[RateColor::RED as usize - 1] = *wh
                            });
                            if self.index_high_hour_span[RateColor::RED as usize - 1] == 0 {
                                self.index_high_hour_span[RateColor::RED as usize - 1] = *wh;
                            }
                        }
                    }
                    _ => {}
                }
            }
            TeleinfoFrame::PEJP(advice) => {
                if *advice == 30 {
                    let _ = self.tomorrow_color.send(RateColor::RED);
                } else {
                    let _ = self.tomorrow_color.send(RateColor::BLUE);
                }
            }
            TeleinfoFrame::DEMAIN(val) => {
                let _ = self.tomorrow_color.send(RateColor::from(val));
            }
            TeleinfoFrame::PTEC(val) => {
                let rate_period = RatePeriod::try_from(val).unwrap_or_default();
                if rate_period != *self.tarif_period.borrow() {
                    self.new_period(rate_period);
                }
                let _ = self.tarif_period.send(rate_period);
            }
            TeleinfoFrame::LTARF(val) => {
                let rate_period = RatePeriod::try_from(val).unwrap_or_default();
                let rate_color = RateColor::from(val);
                if rate_period != *self.tarif_period.borrow() {
                    self.new_period(rate_period);
                }
                let _ = self.tarif_period.send(rate_period);
                let _ = self.color.send(rate_color);
            }
            TeleinfoFrame::URMS(phase, volts) => {
                let phase = if *phase > 0 && *phase <= 3 {
                    (phase - 1) as usize
                } else {
                    0
                };
                self.instantaneous_voltage
                    .send_modify(|voltage| voltage[phase] = *volts);
            }
            TeleinfoFrame::IINST(phase, amps) => {
                let phase = if *phase > 0 && *phase <= 3 {
                    (phase - 1) as usize
                } else {
                    0
                };
                self.instantaneous_current
                    .send_modify(|current| current[phase] = *amps);
            }
            TeleinfoFrame::IRMS(phase, amps) => {
                let phase = if *phase > 0 && *phase <= 3 {
                    (phase - 1) as usize
                } else {
                    0
                };
                self.instantaneous_current
                    .send_modify(|current| current[phase] = *amps);
            }
            TeleinfoFrame::PAPP(va) => {
                let _ = self.instantaneous_power.send(*va);
            }
            TeleinfoFrame::SINSTS(va) => {
                let _ = self.instantaneous_power.send(*va);
            }
            TeleinfoFrame::STGE(registry) => {
                if registry.tempo_next_color != RateColor::NONE {
                    let _ = self.tomorrow_color.send(registry.tempo_next_color);
                }
                let _ = self.power_direction.send(registry.active_power_direction);
            }
            _ => {}
        }
    }
}