cinnamon 2.0.0-alpha.1

A type-safe, async Nightscout client for Rust: API v3 with v1/v2 fallback, JWT auth, incremental sync and realtime streams.
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
//! The `devicestatus` collection: uploader, pump and closed-loop (Loop, OpenAPS/AAPS/Trio)
//! status reports.

use serde::{Deserialize, Serialize};
use serde_json::Value;

use super::{CollectionName, Extra, Meta, Timestamp, de, impl_document, time};

/// A status report from an uploader.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DeviceStatus {
    /// Bookkeeping fields.
    #[serde(flatten)]
    pub meta: Meta,
    /// Reporting device, e.g. `openaps://samsung SM-G970F` or `loop://iPhone`.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub device: Option<String>,
    /// When the report was made.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "time::iso")]
    pub created_at: Option<Timestamp>,
    /// Report time as epoch millis (API v3).
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        with = "time::millis"
    )]
    pub date: Option<Timestamp>,
    /// Phone / uploader battery.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de::tolerant"
    )]
    pub uploader: Option<Uploader>,
    /// Legacy top-level uploader battery percentage.
    #[serde(
        rename = "uploaderBattery",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::num"
    )]
    pub uploader_battery: Option<f64>,
    /// Whether the uploader is charging (AAPS).
    #[serde(
        rename = "isCharging",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::flag"
    )]
    pub is_charging: Option<bool>,
    /// Pump state.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de::tolerant"
    )]
    pub pump: Option<Pump>,
    /// OpenAPS / AAPS / Trio loop state.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de::tolerant"
    )]
    pub openaps: Option<OpenAps>,
    /// Loop (iOS) state.
    #[serde(
        rename = "loop",
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de::tolerant"
    )]
    pub loop_status: Option<LoopStatus>,
    /// Active Loop override.
    #[serde(
        rename = "override",
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de::tolerant"
    )]
    pub override_status: Option<Override>,
    /// xDrip-js / Lookout CGM transmitter state (untyped).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub xdripjs: Option<Value>,
    /// AAPS configuration snapshot (untyped).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub configuration: Option<Value>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

impl DeviceStatus {
    /// An empty report from `device`, dated now.
    #[must_use]
    pub fn new(device: impl Into<String>) -> Self {
        Self {
            meta: Meta::default(),
            device: Some(device.into()),
            created_at: Some(Timestamp::now()),
            date: None,
            uploader: None,
            uploader_battery: None,
            is_charging: None,
            pump: None,
            openaps: None,
            loop_status: None,
            override_status: None,
            xdripjs: None,
            configuration: None,
            extra: Extra::new(),
        }
    }

    /// When the report was made: `created_at`, falling back to `date`.
    #[must_use]
    pub fn time(&self) -> Option<Timestamp> {
        self.created_at.or(self.date)
    }

    /// Uploader battery percentage from wherever the uploader put it.
    #[must_use]
    pub fn uploader_battery_percent(&self) -> Option<f64> {
        self.uploader
            .as_ref()
            .and_then(|u| u.battery)
            .or(self.uploader_battery)
    }

    fn fill_defaults(&mut self, app: &str) {
        self.device.get_or_insert_with(|| app.to_owned());
        match (self.created_at, self.date) {
            (None, None) => {
                let now = Timestamp::now();
                self.created_at = Some(now);
                self.date = Some(now);
            }
            (Some(t), None) => self.date = Some(t),
            (None, Some(t)) => self.created_at = Some(t),
            (Some(_), Some(_)) => {}
        }
    }
}

impl_document!(
    DeviceStatus,
    CollectionName::DeviceStatus,
    timestamp = |s| s.time(),
    device = |s| s.device.as_deref()
);

/// Uploader (phone) state.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Uploader {
    /// Battery percentage.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub battery: Option<f64>,
    /// Battery voltage.
    #[serde(
        rename = "batteryVoltage",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::num"
    )]
    pub battery_voltage: Option<f64>,
    /// Uploader name.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub name: Option<String>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

/// Insulin pump state.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Pump {
    /// Pump clock (ISO).
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub clock: Option<String>,
    /// Insulin left in the reservoir, in units.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub reservoir: Option<f64>,
    /// Pump battery.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de::tolerant"
    )]
    pub battery: Option<PumpBattery>,
    /// Pump status flags.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de::tolerant"
    )]
    pub status: Option<PumpStatus>,
    /// Manufacturer.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub manufacturer: Option<String>,
    /// Model.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub model: Option<String>,
    /// Pump-reported insulin on board (shape varies by uploader).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub iob: Option<Value>,
    /// Extended, uploader-specific pump data.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extended: Option<Value>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

/// Pump battery.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PumpBattery {
    /// Percentage.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub percent: Option<f64>,
    /// Voltage.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub voltage: Option<f64>,
    /// Status string.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub status: Option<String>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

/// Pump status flags.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PumpStatus {
    /// Human-readable status (`normal`, `suspended`, …).
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub status: Option<String>,
    /// Whether a bolus is in progress.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::flag")]
    pub bolusing: Option<bool>,
    /// Whether delivery is suspended.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::flag")]
    pub suspended: Option<bool>,
    /// Status time.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub timestamp: Option<String>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

/// OpenAPS-family (OpenAPS, AAPS, Trio, iAPS) loop state.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct OpenAps {
    /// Insulin on board: an object, or an array of forecasts (shape varies by uploader).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub iob: Option<Value>,
    /// The latest recommendation.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de::tolerant"
    )]
    pub suggested: Option<ApsResult>,
    /// The latest recommendation that was actually applied.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de::tolerant"
    )]
    pub enacted: Option<ApsResult>,
    /// OpenAPS version.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub version: Option<String>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

impl OpenAps {
    /// Current IOB in units, from either the object or the first element of the array form.
    #[must_use]
    pub fn iob_units(&self) -> Option<f64> {
        let iob = match self.iob.as_ref()? {
            Value::Array(items) => items.first()?,
            other => other,
        };
        iob.get("iob").and_then(Value::as_f64)
    }
}

/// An OpenAPS `determine-basal` result (`suggested` / `enacted`).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ApsResult {
    /// When the result was computed.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub timestamp: Option<String>,
    /// Current glucose used for the decision.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub bg: Option<f64>,
    /// Temp basal type (`absolute`).
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub temp: Option<String>,
    /// Temp basal rate in U/h.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub rate: Option<f64>,
    /// Temp basal duration in minutes.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub duration: Option<f64>,
    /// SMB delivered, in units.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub units: Option<f64>,
    /// Human-readable reasoning.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub reason: Option<String>,
    /// Predicted eventual glucose.
    #[serde(
        rename = "eventualBG",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::num"
    )]
    pub eventual_bg: Option<f64>,
    /// IOB used for the decision.
    #[serde(
        rename = "IOB",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::num"
    )]
    pub iob: Option<f64>,
    /// COB used for the decision.
    #[serde(
        rename = "COB",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::num"
    )]
    pub cob: Option<f64>,
    /// Autosens ratio.
    #[serde(
        rename = "sensitivityRatio",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::num"
    )]
    pub sensitivity_ratio: Option<f64>,
    /// Insulin required.
    #[serde(
        rename = "insulinReq",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::num"
    )]
    pub insulin_req: Option<f64>,
    /// Whether the pump acknowledged the command (`received`; oref0 spells it `recieved`).
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::flag")]
    pub received: Option<bool>,
    /// Prediction curves.
    #[serde(
        rename = "predBGs",
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de::tolerant"
    )]
    pub pred_bgs: Option<PredBgs>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

/// OpenAPS prediction curves (5-minute steps, mg/dL).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PredBgs {
    /// Insulin-only prediction.
    #[serde(
        rename = "IOB",
        default,
        skip_serializing_if = "Vec::is_empty",
        with = "de::nums"
    )]
    pub iob: Vec<f64>,
    /// Prediction including carbs on board.
    #[serde(
        rename = "COB",
        default,
        skip_serializing_if = "Vec::is_empty",
        with = "de::nums"
    )]
    pub cob: Vec<f64>,
    /// Unannounced-meal prediction.
    #[serde(
        rename = "UAM",
        default,
        skip_serializing_if = "Vec::is_empty",
        with = "de::nums"
    )]
    pub uam: Vec<f64>,
    /// Zero-temp prediction.
    #[serde(
        rename = "ZT",
        default,
        skip_serializing_if = "Vec::is_empty",
        with = "de::nums"
    )]
    pub zt: Vec<f64>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

/// Loop (iOS) state.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LoopStatus {
    /// App name (`Loop`).
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub name: Option<String>,
    /// App version.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub version: Option<String>,
    /// When the loop ran.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub timestamp: Option<String>,
    /// Insulin on board.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de::tolerant"
    )]
    pub iob: Option<LoopValue>,
    /// Carbs on board.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de::tolerant"
    )]
    pub cob: Option<LoopValue>,
    /// Glucose prediction.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "de::tolerant"
    )]
    pub predicted: Option<LoopPrediction>,
    /// Last enacted temp basal / bolus.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub enacted: Option<Value>,
    /// Recommended bolus in units.
    #[serde(
        rename = "recommendedBolus",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::num"
    )]
    pub recommended_bolus: Option<f64>,
    /// Why the last loop failed, if it did.
    #[serde(
        rename = "failureReason",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::text"
    )]
    pub failure_reason: Option<String>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

/// A Loop IOB or COB value.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LoopValue {
    /// IOB in units (for `iob`).
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub iob: Option<f64>,
    /// COB in grams (for `cob`).
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub cob: Option<f64>,
    /// When the value was computed.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub timestamp: Option<String>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

/// A Loop glucose prediction.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LoopPrediction {
    /// Start of the prediction (ISO).
    #[serde(
        rename = "startDate",
        default,
        skip_serializing_if = "Option::is_none",
        with = "de::text"
    )]
    pub start_date: Option<String>,
    /// Predicted values in 5-minute steps (mg/dL).
    #[serde(default, skip_serializing_if = "Vec::is_empty", with = "de::nums")]
    pub values: Vec<f64>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

/// A Loop override (preset or custom).
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Override {
    /// Preset name.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub name: Option<String>,
    /// Whether it is active.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::flag")]
    pub active: Option<bool>,
    /// Insulin needs multiplier.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub multiplier: Option<f64>,
    /// Remaining duration in seconds.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::num")]
    pub duration: Option<f64>,
    /// When it started.
    #[serde(default, skip_serializing_if = "Option::is_none", with = "de::text")]
    pub timestamp: Option<String>,
    /// Fields cinnamon does not model.
    #[serde(flatten)]
    pub extra: Extra,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn loop_status_is_typed_not_lost() {
        let raw = serde_json::json!({
            "_id": "65f1c2a8e4b0a1b2c3d4e5f6",
            "device": "loop://iPhone",
            "created_at": "2024-05-01T12:00:00.000Z",
            "pump": {"clock": "2024-05-01T12:00:00Z", "reservoir": 104.5, "battery": {"percent": 75},
                     "status": {"status": "normal", "bolusing": false, "suspended": false}},
            "uploader": {"battery": 58, "name": "iPhone"},
            "loop": {"name": "Loop", "version": "3.4.0", "timestamp": "2024-05-01T12:00:00Z",
                     "iob": {"iob": 1.25, "timestamp": "2024-05-01T12:00:00Z"},
                     "cob": {"cob": 12, "timestamp": "2024-05-01T12:00:00Z"},
                     "predicted": {"startDate": "2024-05-01T12:00:00Z", "values": [110, 112, 115]},
                     "recommendedBolus": 0},
            "override": {"name": "Workout", "active": true, "multiplier": 0.5}
        });
        let ds: DeviceStatus =
            serde_json::from_value(raw.clone()).unwrap_or_else(|e| panic!("{e}"));
        let lp = ds
            .loop_status
            .as_ref()
            .unwrap_or_else(|| panic!("loop lost"));
        assert_eq!(lp.iob.as_ref().and_then(|i| i.iob), Some(1.25));
        assert_eq!(lp.predicted.as_ref().map(|p| p.values.len()), Some(3));
        assert_eq!(ds.uploader_battery_percent(), Some(58.0));
        assert_eq!(serde_json::to_value(&ds).ok(), Some(raw));
    }

    #[test]
    fn openaps_iob_array_form() {
        let ds: DeviceStatus = serde_json::from_value(serde_json::json!({
            "created_at": "2024-05-01T12:00:00Z",
            "openaps": {"iob": [{"iob": 2.1, "activity": 0.02}, {"iob": 1.9}],
                        "suggested": {"bg": 140, "eventualBG": 120, "predBGs": {"IOB": [140, 138], "ZT": [140]}}}
        }))
        .unwrap_or_else(|e| panic!("{e}"));
        let aps = ds.openaps.unwrap_or_default();
        assert_eq!(aps.iob_units(), Some(2.1));
        assert_eq!(
            aps.suggested.and_then(|s| s.pred_bgs).map(|p| p.iob),
            Some(vec![140.0, 138.0])
        );
    }
}