tasmor_lib 0.6.0

Rust library to control Tasmota devices via MQTT and HTTP
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
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
// SPDX-License-Identifier: MPL-2.0
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

//! Parser for Tasmota SENSOR telemetry messages.

use serde::Deserialize;

use crate::error::ParseError;
use crate::state::StateChange;
use crate::types::TasmotaDateTime;

/// Parsed sensor data from a `tele/<topic>/SENSOR` message.
///
/// This struct represents sensor readings as reported in periodic
/// telemetry messages. Energy data is the most common, but temperature
/// and humidity sensors are also supported.
///
/// # Examples
///
/// ```
/// use tasmor_lib::telemetry::SensorData;
///
/// let json = r#"{"Time":"2024-01-01T12:00:00","ENERGY":{"Power":150,"Voltage":230,"Current":0.65}}"#;
/// let data: SensorData = serde_json::from_str(json).unwrap();
///
/// if let Some(energy) = data.energy() {
///     assert_eq!(energy.power, Some(150.0));
///     assert_eq!(energy.voltage, Some(230.0));
/// }
/// ```
#[derive(Debug, Clone, Default, Deserialize)]
pub struct SensorData {
    /// Timestamp of the reading.
    #[serde(rename = "Time", default)]
    time: Option<String>,

    /// Energy readings (power, voltage, current, etc.).
    #[serde(rename = "ENERGY", default)]
    energy: Option<EnergyReading>,

    /// Temperature reading (from various sensor types).
    #[serde(rename = "Temperature", default)]
    temperature: Option<f32>,

    /// Humidity reading.
    #[serde(rename = "Humidity", default)]
    humidity: Option<f32>,

    /// Pressure reading (in hPa).
    #[serde(rename = "Pressure", default)]
    pressure: Option<f32>,

    /// DS18B20 temperature sensor.
    #[serde(rename = "DS18B20", default)]
    ds18b20: Option<TemperatureSensor>,

    /// DHT11/DHT22 sensor.
    #[serde(rename = "DHT11", default)]
    dht11: Option<DhtSensor>,

    /// AM2301 sensor (same as DHT21).
    #[serde(rename = "AM2301", default)]
    am2301: Option<DhtSensor>,

    /// BME280 sensor.
    #[serde(rename = "BME280", default)]
    bme280: Option<Bme280Sensor>,
}

/// Energy readings from a power monitoring device.
///
/// Fields correspond to Tasmota's ENERGY telemetry output.
/// All fields are optional as not all devices report all values.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct EnergyReading {
    /// Timestamp when total energy counting started.
    ///
    /// Format: ISO 8601 datetime string (e.g., "2024-01-15T10:30:00").
    #[serde(rename = "TotalStartTime", default)]
    pub total_start_time: Option<String>,

    /// Total energy consumed today (in kWh).
    #[serde(rename = "Today", default)]
    pub today: Option<f32>,

    /// Total energy consumed yesterday (in kWh).
    #[serde(rename = "Yesterday", default)]
    pub yesterday: Option<f32>,

    /// Total energy consumed (in kWh).
    #[serde(rename = "Total", default)]
    pub total: Option<f32>,

    /// Current power consumption (in Watts).
    #[serde(rename = "Power", default)]
    pub power: Option<f32>,

    /// Apparent power (in VA).
    #[serde(rename = "ApparentPower", default)]
    pub apparent_power: Option<f32>,

    /// Reactive power (in `VAr`).
    #[serde(rename = "ReactivePower", default)]
    pub reactive_power: Option<f32>,

    /// Power factor (0-1).
    #[serde(rename = "Factor", default)]
    pub factor: Option<f32>,

    /// Voltage (in Volts).
    #[serde(rename = "Voltage", default)]
    pub voltage: Option<f32>,

    /// Current (in Amps).
    #[serde(rename = "Current", default)]
    pub current: Option<f32>,

    /// Frequency (in Hz).
    #[serde(rename = "Frequency", default)]
    pub frequency: Option<f32>,
}

/// Temperature sensor reading.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct TemperatureSensor {
    /// Temperature in configured units (C or F).
    #[serde(rename = "Temperature", default)]
    pub temperature: Option<f32>,

    /// Sensor ID (for multi-sensor setups).
    #[serde(rename = "Id", default)]
    id: Option<String>,
}

impl TemperatureSensor {
    /// Returns the temperature reading.
    #[must_use]
    pub fn temperature(&self) -> Option<f32> {
        self.temperature
    }

    /// Returns the sensor ID (for multi-sensor setups).
    #[must_use]
    pub fn id(&self) -> Option<&str> {
        self.id.as_deref()
    }
}

/// DHT temperature/humidity sensor reading.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct DhtSensor {
    /// Temperature in configured units (C or F).
    #[serde(rename = "Temperature", default)]
    temperature: Option<f32>,

    /// Relative humidity (0-100%).
    #[serde(rename = "Humidity", default)]
    humidity: Option<f32>,

    /// Dew point temperature.
    #[serde(rename = "DewPoint", default)]
    dew_point: Option<f32>,
}

impl DhtSensor {
    /// Returns the temperature reading.
    #[must_use]
    pub fn temperature(&self) -> Option<f32> {
        self.temperature
    }

    /// Returns the humidity reading (0-100%).
    #[must_use]
    pub fn humidity(&self) -> Option<f32> {
        self.humidity
    }

    /// Returns the dew point temperature.
    #[must_use]
    pub fn dew_point(&self) -> Option<f32> {
        self.dew_point
    }
}

/// BME280 environmental sensor reading.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Bme280Sensor {
    /// Temperature in configured units (C or F).
    #[serde(rename = "Temperature", default)]
    temperature: Option<f32>,

    /// Relative humidity (0-100%).
    #[serde(rename = "Humidity", default)]
    humidity: Option<f32>,

    /// Dew point temperature.
    #[serde(rename = "DewPoint", default)]
    dew_point: Option<f32>,

    /// Atmospheric pressure (in hPa).
    #[serde(rename = "Pressure", default)]
    pressure: Option<f32>,
}

impl Bme280Sensor {
    /// Returns the temperature reading.
    #[must_use]
    pub fn temperature(&self) -> Option<f32> {
        self.temperature
    }

    /// Returns the humidity reading (0-100%).
    #[must_use]
    pub fn humidity(&self) -> Option<f32> {
        self.humidity
    }

    /// Returns the dew point temperature.
    #[must_use]
    pub fn dew_point(&self) -> Option<f32> {
        self.dew_point
    }

    /// Returns the atmospheric pressure (in hPa).
    #[must_use]
    pub fn pressure(&self) -> Option<f32> {
        self.pressure
    }
}

impl SensorData {
    /// Returns the timestamp of the sensor reading.
    #[must_use]
    pub fn time(&self) -> Option<&str> {
        self.time.as_deref()
    }

    /// Returns the energy reading if present.
    #[must_use]
    pub fn energy(&self) -> Option<&EnergyReading> {
        self.energy.as_ref()
    }

    /// Returns the temperature from any available sensor.
    ///
    /// Checks in order: direct temperature field, DS18B20, DHT11, AM2301, BME280.
    #[must_use]
    pub fn temperature(&self) -> Option<f32> {
        self.temperature
            .or_else(|| {
                self.ds18b20
                    .as_ref()
                    .and_then(TemperatureSensor::temperature)
            })
            .or_else(|| self.dht11.as_ref().and_then(DhtSensor::temperature))
            .or_else(|| self.am2301.as_ref().and_then(DhtSensor::temperature))
            .or_else(|| self.bme280.as_ref().and_then(Bme280Sensor::temperature))
    }

    /// Returns the humidity from any available sensor.
    ///
    /// Checks in order: direct humidity field, DHT11, AM2301, BME280.
    #[must_use]
    pub fn humidity(&self) -> Option<f32> {
        self.humidity
            .or_else(|| self.dht11.as_ref().and_then(DhtSensor::humidity))
            .or_else(|| self.am2301.as_ref().and_then(DhtSensor::humidity))
            .or_else(|| self.bme280.as_ref().and_then(Bme280Sensor::humidity))
    }

    /// Returns the pressure from any available sensor.
    ///
    /// Checks in order: direct pressure field, BME280.
    #[must_use]
    pub fn pressure(&self) -> Option<f32> {
        self.pressure
            .or_else(|| self.bme280.as_ref().and_then(Bme280Sensor::pressure))
    }

    /// Returns the DS18B20 temperature sensor reading if present.
    #[must_use]
    pub fn ds18b20(&self) -> Option<&TemperatureSensor> {
        self.ds18b20.as_ref()
    }

    /// Returns the DHT11 sensor reading if present.
    #[must_use]
    pub fn dht11(&self) -> Option<&DhtSensor> {
        self.dht11.as_ref()
    }

    /// Returns the AM2301 sensor reading if present.
    #[must_use]
    pub fn am2301(&self) -> Option<&DhtSensor> {
        self.am2301.as_ref()
    }

    /// Returns the BME280 sensor reading if present.
    #[must_use]
    pub fn bme280(&self) -> Option<&Bme280Sensor> {
        self.bme280.as_ref()
    }

    /// Converts the sensor data into a list of state changes.
    #[must_use]
    pub fn to_state_changes(&self) -> Vec<StateChange> {
        let mut changes = Vec::new();

        if let Some(energy) = &self.energy {
            // Only emit energy change if at least one field is present
            if energy.has_power_data() || energy.has_consumption_data() {
                // Parse the total start time into a proper datetime type
                let total_start_time = energy
                    .total_start_time
                    .as_deref()
                    .and_then(TasmotaDateTime::parse);

                changes.push(StateChange::Energy {
                    power: energy.power,
                    voltage: energy.voltage,
                    current: energy.current,
                    apparent_power: energy.apparent_power,
                    reactive_power: energy.reactive_power,
                    power_factor: energy.factor,
                    energy_today: energy.today,
                    energy_yesterday: energy.yesterday,
                    energy_total: energy.total,
                    total_start_time,
                    frequency: energy.frequency,
                });
            }
        }

        changes
    }
}

impl EnergyReading {
    /// Returns true if any power-related field is present.
    #[must_use]
    pub fn has_power_data(&self) -> bool {
        self.power.is_some() || self.voltage.is_some() || self.current.is_some()
    }

    /// Returns true if any energy consumption data is present.
    #[must_use]
    pub fn has_consumption_data(&self) -> bool {
        self.today.is_some() || self.yesterday.is_some() || self.total.is_some()
    }
}

/// Parses a SENSOR telemetry JSON payload.
pub(crate) fn parse_sensor(payload: &str) -> Result<SensorData, ParseError> {
    serde_json::from_str(payload).map_err(ParseError::Json)
}

/// Response wrapper for `Status 10` command.
///
/// The `Status 10` command returns sensor data wrapped in a `StatusSNS` object:
/// ```json
/// {"StatusSNS":{"Time":"...","ENERGY":{"Power":150,...}}}
/// ```
#[derive(Debug, Clone, Default, Deserialize)]
pub struct StatusSnsResponse {
    /// The wrapped sensor data.
    #[serde(rename = "StatusSNS")]
    pub status_sns: Option<SensorData>,
}

impl StatusSnsResponse {
    /// Returns the sensor data if present.
    #[must_use]
    pub fn sensor_data(&self) -> Option<&SensorData> {
        self.status_sns.as_ref()
    }

    /// Converts to state changes.
    #[must_use]
    pub fn to_state_changes(&self) -> Vec<StateChange> {
        self.status_sns
            .as_ref()
            .map_or_else(Vec::new, SensorData::to_state_changes)
    }
}

#[cfg(test)]
mod tests {
    use approx::assert_abs_diff_eq;
    use chrono::Datelike;
    use chrono::Timelike;

    use super::*;

    #[test]
    fn parse_energy_basic() {
        let json = r#"{"Time":"2024-01-01T12:00:00","ENERGY":{"Power":150}}"#;
        let data: SensorData = serde_json::from_str(json).unwrap();

        let energy = data.energy().unwrap();
        assert_eq!(energy.power, Some(150.0));
    }

    #[test]
    fn parse_energy_full() {
        let json = r#"{
            "Time": "2024-01-01T12:00:00",
            "ENERGY": {
                "Today": 1.5,
                "Yesterday": 2.3,
                "Total": 1234.5,
                "Power": 150,
                "ApparentPower": 160,
                "ReactivePower": 20,
                "Factor": 0.95,
                "Voltage": 230,
                "Current": 0.65,
                "Frequency": 50.0
            }
        }"#;
        let data: SensorData = serde_json::from_str(json).unwrap();

        let energy = data.energy().unwrap();
        assert_eq!(energy.today, Some(1.5));
        assert_eq!(energy.yesterday, Some(2.3));
        assert_eq!(energy.total, Some(1234.5));
        assert_eq!(energy.power, Some(150.0));
        assert_eq!(energy.apparent_power, Some(160.0));
        assert_eq!(energy.reactive_power, Some(20.0));
        assert_eq!(energy.factor, Some(0.95));
        assert_eq!(energy.voltage, Some(230.0));
        assert_eq!(energy.current, Some(0.65));
        assert_eq!(energy.frequency, Some(50.0));
    }

    #[test]
    fn parse_temperature_direct() {
        let json = r#"{"Time":"2024-01-01T12:00:00","Temperature":23.5}"#;
        let data: SensorData = serde_json::from_str(json).unwrap();

        assert_eq!(data.temperature(), Some(23.5));
    }

    #[test]
    fn parse_ds18b20() {
        let json = r#"{"Time":"2024-01-01T12:00:00","DS18B20":{"Temperature":22.5,"Id":"28-0123456789ab"}}"#;
        let data: SensorData = serde_json::from_str(json).unwrap();

        assert_eq!(data.temperature(), Some(22.5));
        assert_eq!(
            data.ds18b20().and_then(TemperatureSensor::id),
            Some("28-0123456789ab")
        );
    }

    #[test]
    fn parse_dht11() {
        let json = r#"{"Time":"2024-01-01T12:00:00","DHT11":{"Temperature":24.0,"Humidity":55.0}}"#;
        let data: SensorData = serde_json::from_str(json).unwrap();

        assert_eq!(data.temperature(), Some(24.0));
        assert_eq!(data.humidity(), Some(55.0));
    }

    #[test]
    fn parse_bme280() {
        let json = r#"{
            "Time": "2024-01-01T12:00:00",
            "BME280": {
                "Temperature": 21.5,
                "Humidity": 60.0,
                "DewPoint": 13.2,
                "Pressure": 1013.25
            }
        }"#;
        let data: SensorData = serde_json::from_str(json).unwrap();

        assert_eq!(data.temperature(), Some(21.5));
        assert_eq!(data.humidity(), Some(60.0));
        assert_eq!(data.pressure(), Some(1013.25));

        let bme = data.bme280().unwrap();
        assert_eq!(bme.dew_point(), Some(13.2));
    }

    #[test]
    fn energy_has_power_data() {
        let energy = EnergyReading {
            power: Some(100.0),
            ..Default::default()
        };
        assert!(energy.has_power_data());

        let empty = EnergyReading::default();
        assert!(!empty.has_power_data());
    }

    #[test]
    fn energy_has_consumption_data() {
        let energy = EnergyReading {
            total: Some(1234.5),
            ..Default::default()
        };
        assert!(energy.has_consumption_data());

        let empty = EnergyReading::default();
        assert!(!empty.has_consumption_data());
    }

    #[test]
    fn to_state_changes_with_energy() {
        let json = r#"{"ENERGY":{"Power":150,"Voltage":230,"Current":0.65}}"#;
        let data: SensorData = serde_json::from_str(json).unwrap();

        let changes = data.to_state_changes();
        assert_eq!(changes.len(), 1);
        if let StateChange::Energy {
            power,
            voltage,
            current,
            ..
        } = &changes[0]
        {
            assert_abs_diff_eq!(power.unwrap(), 150.0, epsilon = 1e-6);
            assert_abs_diff_eq!(voltage.unwrap(), 230.0, epsilon = 1e-6);
            assert_abs_diff_eq!(current.unwrap(), 0.65, epsilon = 0.001);
        } else {
            panic!("Expected StateChange::Energy");
        }
    }

    #[test]
    fn to_state_changes_empty() {
        let json = r#"{"Time":"2024-01-01T12:00:00"}"#;
        let data: SensorData = serde_json::from_str(json).unwrap();

        let changes = data.to_state_changes();
        assert!(changes.is_empty());
    }

    #[test]
    fn parse_sensor_function() {
        let json = r#"{"Time":"2024-01-01T12:00:00","ENERGY":{"Power":100}}"#;
        let result = parse_sensor(json);
        assert!(result.is_ok());

        let data = result.unwrap();
        assert_eq!(data.energy().unwrap().power, Some(100.0));
    }

    #[test]
    fn parse_sensor_invalid_json() {
        let result = parse_sensor("not json");
        assert!(result.is_err());
    }

    #[test]
    fn parse_status_sns_response() {
        // This is the format returned by Status 10 command
        let json = r#"{
            "StatusSNS": {
                "Time": "2024-01-01T12:00:00",
                "ENERGY": {
                    "Power": 182,
                    "Voltage": 224,
                    "Current": 0.706,
                    "Total": 1104.315
                }
            }
        }"#;

        let response: StatusSnsResponse = serde_json::from_str(json).unwrap();
        let sensor = response.sensor_data().unwrap();
        let energy = sensor.energy().unwrap();

        assert_eq!(energy.power, Some(182.0));
        assert_eq!(energy.voltage, Some(224.0));
        assert_abs_diff_eq!(energy.current.unwrap(), 0.706, epsilon = 0.001);
        assert_abs_diff_eq!(energy.total.unwrap(), 1104.315, epsilon = 0.01);
    }

    #[test]
    fn status_sns_to_state_changes() {
        let json = r#"{"StatusSNS":{"ENERGY":{"Power":150,"Voltage":230,"Current":0.65}}}"#;

        let response: StatusSnsResponse = serde_json::from_str(json).unwrap();
        let changes = response.to_state_changes();

        assert_eq!(changes.len(), 1);
        if let StateChange::Energy {
            power,
            voltage,
            current,
            ..
        } = &changes[0]
        {
            assert_abs_diff_eq!(power.unwrap(), 150.0, epsilon = 1e-6);
            assert_abs_diff_eq!(voltage.unwrap(), 230.0, epsilon = 1e-6);
            assert_abs_diff_eq!(current.unwrap(), 0.65, epsilon = 0.001);
        } else {
            panic!("Expected StateChange::Energy");
        }
    }

    #[test]
    fn to_state_changes_with_full_energy() {
        let json = r#"{
            "ENERGY": {
                "Power": 182,
                "Voltage": 224,
                "Current": 0.706,
                "ApparentPower": 195,
                "ReactivePower": 50,
                "Factor": 0.93,
                "Today": 1.5,
                "Yesterday": 2.3,
                "Total": 1104.315
            }
        }"#;
        let data: SensorData = serde_json::from_str(json).unwrap();

        let changes = data.to_state_changes();
        assert_eq!(changes.len(), 1);
        if let StateChange::Energy {
            power,
            voltage,
            current,
            apparent_power,
            reactive_power,
            power_factor,
            energy_today,
            energy_yesterday,
            energy_total,
            total_start_time,
            frequency,
        } = &changes[0]
        {
            assert_abs_diff_eq!(power.unwrap(), 182.0, epsilon = 1e-6);
            assert_abs_diff_eq!(voltage.unwrap(), 224.0, epsilon = 1e-6);
            assert_abs_diff_eq!(current.unwrap(), 0.706, epsilon = 0.001);
            assert_abs_diff_eq!(apparent_power.unwrap(), 195.0, epsilon = 1e-6);
            assert_abs_diff_eq!(reactive_power.unwrap(), 50.0, epsilon = 1e-6);
            assert_abs_diff_eq!(power_factor.unwrap(), 0.93, epsilon = 0.01);
            assert_abs_diff_eq!(energy_today.unwrap(), 1.5, epsilon = 0.01);
            assert_abs_diff_eq!(energy_yesterday.unwrap(), 2.3, epsilon = 0.01);
            assert_abs_diff_eq!(energy_total.unwrap(), 1104.315, epsilon = 0.01);
            assert!(total_start_time.is_none()); // Not in test JSON
            assert!(frequency.is_none()); // Not in test JSON
        } else {
            panic!("Expected StateChange::Energy");
        }
    }

    #[test]
    fn to_state_changes_with_total_start_time() {
        let json = r#"{
            "ENERGY": {
                "TotalStartTime": "2024-01-15T10:30:00",
                "Power": 100,
                "Voltage": 230,
                "Current": 0.5,
                "Total": 500.0
            }
        }"#;
        let data: SensorData = serde_json::from_str(json).unwrap();

        let changes = data.to_state_changes();
        assert_eq!(changes.len(), 1);
        if let StateChange::Energy {
            total_start_time, ..
        } = &changes[0]
        {
            let dt = total_start_time.as_ref().expect("Should have datetime");
            assert_eq!(dt.naive().year(), 2024);
            assert_eq!(dt.naive().month(), 1);
            assert_eq!(dt.naive().day(), 15);
            assert_eq!(dt.naive().hour(), 10);
            assert_eq!(dt.naive().minute(), 30);
            assert!(!dt.has_timezone()); // No timezone in input
        } else {
            panic!("Expected StateChange::Energy");
        }
    }

    #[test]
    fn to_state_changes_with_total_start_time_with_tz() {
        let json = r#"{
            "ENERGY": {
                "TotalStartTime": "2024-01-15T10:30:00+01:00",
                "Power": 100,
                "Voltage": 230,
                "Current": 0.5,
                "Total": 500.0
            }
        }"#;
        let data: SensorData = serde_json::from_str(json).unwrap();

        let changes = data.to_state_changes();
        assert_eq!(changes.len(), 1);
        if let StateChange::Energy {
            total_start_time, ..
        } = &changes[0]
        {
            let dt = total_start_time.as_ref().expect("Should have datetime");
            assert!(dt.has_timezone());
            let tz_dt = dt.to_datetime().expect("Should have timezone");
            assert_eq!(tz_dt.offset().local_minus_utc(), 3600); // +1 hour
        } else {
            panic!("Expected StateChange::Energy");
        }
    }
}