glowmarkt 0.5.3

Access to the Glowmarkt API for smart meter data.
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
//! API request and response structures.
#![allow(missing_docs)]

use std::{collections::HashMap, fmt};

use serde::{
    de::{self, MapAccess, Visitor},
    Deserialize, Deserializer, Serialize, Serializer,
};
use serde_json::{Map, Value};
use time::{format_description, OffsetDateTime, PrimitiveDateTime};

use crate::{Error, ErrorKind};

#[derive(Serialize, Debug)]
pub(super) struct AuthRequest {
    pub username: String,
    pub password: String,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub(super) struct ErrorResponse {
    pub message: String,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub(super) struct InvalidAuthResponse {
    pub error: ErrorResponse,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub(super) struct ValidAuthResponse {
    pub valid: bool,
    pub token: String,
    #[serde(rename = "exp", with = "time::serde::timestamp")]
    pub expiry: OffsetDateTime,
}

#[derive(Deserialize, Debug)]
#[serde(untagged)]
pub(super) enum AuthResponse {
    Invalid(InvalidAuthResponse),
    Valid(ValidAuthResponse),
}

impl AuthResponse {
    pub fn validate(self) -> Result<ValidAuthResponse, Error> {
        match self {
            AuthResponse::Valid(response) => {
                if response.valid {
                    Ok(response)
                } else {
                    Err(Error {
                        kind: ErrorKind::NotAuthenticated,
                        message: "Authentication error".to_string(),
                    })
                }
            }
            AuthResponse::Invalid(response) => Err(Error {
                kind: ErrorKind::NotAuthenticated,
                message: response.error.message,
            }),
        }
    }
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub(super) struct InvalidValidateResponse {
    pub error: ErrorResponse,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub(super) struct ValidValidateResponse {
    pub valid: bool,
    #[serde(rename = "exp", with = "time::serde::timestamp")]
    pub expiry: OffsetDateTime,
}

#[derive(Deserialize, Debug)]
#[serde(untagged)]
pub(super) enum ValidateResponse {
    Invalid(InvalidValidateResponse),
    Valid(ValidValidateResponse),
}

impl ValidateResponse {
    pub fn validate(self) -> Result<ValidValidateResponse, Error> {
        match self {
            ValidateResponse::Valid(response) => {
                if response.valid {
                    Ok(response)
                } else {
                    Err(Error {
                        kind: ErrorKind::NotAuthenticated,
                        message: "Authentication error".to_string(),
                    })
                }
            }
            ValidateResponse::Invalid(response) => Err(Error {
                kind: ErrorKind::NotAuthenticated,
                message: response.error.message,
            }),
        }
    }
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ResourceInfo {
    pub resource_id: String,
    pub resource_type_id: String,
}

#[derive(Deserialize, Serialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct VirtualEntity {
    #[serde(rename(deserialize = "veId"))]
    pub id: String,
    pub name: String,
    pub active: bool,
    #[serde(rename(deserialize = "veTypeId"))]
    pub type_id: String,
    pub owner_id: String,
    pub resources: Vec<ResourceInfo>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Sensor {
    pub protocol_id: String,
    pub resource_type_id: String,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Protocol {
    pub protocol: String,
    pub sensors: Vec<Sensor>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DeviceType {
    #[serde(rename(deserialize = "deviceTypeId"))]
    pub id: String,
    pub description: Option<String>,
    pub active: bool,
    pub protocol: Protocol,
    #[serde(default)]
    pub configuration: serde_json::Value,
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DeviceSensor {
    pub protocol_id: String,
    pub resource_id: String,
    pub resource_type_id: String,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DeviceProtocol {
    pub protocol: String,
    pub sensors: Vec<DeviceSensor>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Device {
    #[serde(rename(deserialize = "deviceId"))]
    pub id: String,
    pub description: Option<String>,
    pub active: bool,
    pub hardware_id: String,
    pub device_type_id: String,
    pub owner_id: String,
    pub hardware_id_names: Vec<String>,
    pub hardware_ids: HashMap<String, String>,
    pub parent_hardware_id: Vec<String>,
    pub tags: Vec<String>,
    pub protocol: DeviceProtocol,
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct DataSourceResourceTypeInfo {
    #[serde(rename = "type")]
    pub data_type: Option<String>,
    pub unit: Option<String>,
    pub range: Option<String>,
    pub is_cost: Option<bool>,
    pub method: Option<String>,
}

impl From<String> for DataSourceResourceTypeInfo {
    fn from(val: String) -> DataSourceResourceTypeInfo {
        DataSourceResourceTypeInfo {
            data_type: Some(val),
            unit: None,
            range: None,
            is_cost: None,
            method: None,
        }
    }
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Field {
    pub field_name: String,
    pub datatype: String,
    pub negative: bool,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Storage {
    #[serde(rename = "type")]
    pub storage_type: String,
    pub sampling: String,
    #[serde(default)]
    pub start: serde_json::Value,
    pub fields: Vec<Field>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ResourceType {
    #[serde(rename(deserialize = "resourceTypeId"))]
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub label: Option<String>,
    pub active: bool,
    pub classifier: Option<String>,
    pub base_unit: Option<String>,
    pub data_source_type: String,
    #[serde(default, deserialize_with = "ds_type_info_deserializer")]
    pub data_source_resource_type_info: Option<DataSourceResourceTypeInfo>,
    #[serde(default)]
    pub units: HashMap<String, String>,
    pub storage: Vec<Storage>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Resource {
    #[serde(rename(deserialize = "resourceId"))]
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub label: Option<String>,
    pub active: bool,
    #[serde(rename(deserialize = "resourceTypeId"))]
    pub type_id: String,
    pub owner_id: String,
    pub classifier: Option<String>,
    pub base_unit: Option<String>,
    pub data_source_type: String,
    #[serde(default, deserialize_with = "ds_type_info_deserializer")]
    pub data_source_resource_type_info: Option<DataSourceResourceTypeInfo>,
    pub data_source_unit_info: Option<serde_json::Value>,
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LatestTariffResponse {
    pub data: Vec<TariffData>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TariffData {
    pub plan: Vec<Plan>,
    pub cid: String,
    pub commodity: String,
    #[serde(
        deserialize_with = "deserialize_datetime",
        serialize_with = "serialize_datetime"
    )]
    pub from: PrimitiveDateTime,
    pub name: String,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TariffListResponse {
    pub data: Vec<TariffListData>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TariffListData {
    pub id: String,
    pub plan: Vec<Plan>,
    #[serde(
        default,
        deserialize_with = "deserialize_datetime_opt",
        serialize_with = "serialize_datetime_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub effective_date: Option<PrimitiveDateTime>,
    #[serde(
        default,
        deserialize_with = "deserialize_datetime_opt",
        serialize_with = "serialize_datetime_opt",
        skip_serializing_if = "Option::is_none"
    )]
    pub from: Option<PrimitiveDateTime>,
    #[serde(default)]
    pub display_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Plan {
    pub plan_detail: Vec<Map<String, Value>>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub week_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
}

type ReadingTuple = (i64, f32);

#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ReadingsResponse {
    pub data: Vec<ReadingTuple>,
}

fn deserialize_datetime<'de, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error>
where
    D: Deserializer<'de>,
{
    let s: &str = Deserialize::deserialize(deserializer)?;
    let format = format_description::parse("[year]-[month]-[day] [hour]:[minute]:[second]")
        .map_err(serde::de::Error::custom)?;

    PrimitiveDateTime::parse(s, &format).map_err(serde::de::Error::custom)
}

fn serialize_datetime<S>(datetime: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let format = format_description::parse("[year]-[month]-[day] [hour]:[minute]:[second]")
        .map_err(serde::ser::Error::custom)?;

    let formatted = datetime
        .format(&format)
        .map_err(serde::ser::Error::custom)?;
    serializer.serialize_str(&formatted)
}

fn deserialize_datetime_opt<'de, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error>
where
    D: Deserializer<'de>,
{
    let s: Option<&str> = Option::deserialize(deserializer)?;
    if let Some(s) = s {
        let format = format_description::parse("[year]-[month]-[day] [hour]:[minute]:[second]")
            .map_err(serde::de::Error::custom)?;

        let primitive_dt =
            PrimitiveDateTime::parse(s, &format).map_err(serde::de::Error::custom)?;

        Ok(Some(primitive_dt))
    } else {
        Ok(None)
    }
}

fn serialize_datetime_opt<S>(
    datetime: &Option<PrimitiveDateTime>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    if let Some(datetime) = datetime {
        // Define the same format used for deserialization
        let format = format_description::parse("[year]-[month]-[day] [hour]:[minute]:[second]")
            .map_err(serde::ser::Error::custom)?;

        let formatted = datetime
            .format(&format)
            .map_err(serde::ser::Error::custom)?;
        serializer.serialize_str(&formatted)
    } else {
        serializer.serialize_none()
    }
}

fn ds_type_info_deserializer<'de, D>(
    deserializer: D,
) -> Result<Option<DataSourceResourceTypeInfo>, D::Error>
where
    D: Deserializer<'de>,
{
    // This is a Visitor that forwards string types to T's `FromStr` impl and
    // forwards map types to T's `Deserialize` impl. The `PhantomData` is to
    // keep the compiler from complaining about T being an unused generic type
    // parameter. We need T in order to know the Value type for the Visitor
    // impl.
    struct StringOrStruct;

    impl<'de> Visitor<'de> for StringOrStruct {
        type Value = Option<DataSourceResourceTypeInfo>;

        fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
            formatter.write_str("string or object")
        }

        fn visit_none<E>(self) -> Result<Option<DataSourceResourceTypeInfo>, E>
        where
            E: de::Error,
        {
            Ok(None)
        }

        fn visit_str<E>(self, value: &str) -> Result<Option<DataSourceResourceTypeInfo>, E>
        where
            E: de::Error,
        {
            Ok(Some(value.to_owned().into()))
        }

        fn visit_string<E>(self, value: String) -> Result<Option<DataSourceResourceTypeInfo>, E>
        where
            E: de::Error,
        {
            Ok(Some(value.into()))
        }

        fn visit_map<M>(self, map: M) -> Result<Option<DataSourceResourceTypeInfo>, M::Error>
        where
            M: MapAccess<'de>,
        {
            // `MapAccessDeserializer` is a wrapper that turns a `MapAccess`
            // into a `Deserializer`, allowing it to be used as the input to T's
            // `Deserialize` implementation. T then deserializes itself using
            // the entries from the map visitor.
            Deserialize::deserialize(de::value::MapAccessDeserializer::new(map)).map(Some)
        }
    }

    deserializer.deserialize_any(StringOrStruct)
}