glimta 0.1.0

A local-first Rust client for the classic IKEA TRADFRI gateway
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
use serde_json::{Map, Value};
use thiserror::Error;

use crate::protocol;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Method {
    Get,
    Put,
    Post,
}

#[derive(Debug, Clone, PartialEq)]
pub struct Command {
    pub method: Method,
    pub path: String,
    pub body: Option<Value>,
    pub observe: bool,
}

impl Command {
    #[must_use]
    pub fn get(path: impl Into<String>) -> Self {
        Self {
            method: Method::Get,
            path: path.into(),
            body: None,
            observe: false,
        }
    }

    #[must_use]
    pub fn put(path: impl Into<String>, body: Value) -> Self {
        Self {
            method: Method::Put,
            path: path.into(),
            body: Some(body),
            observe: false,
        }
    }

    #[must_use]
    pub fn post(path: impl Into<String>, body: Value) -> Self {
        Self {
            method: Method::Post,
            path: path.into(),
            body: Some(body),
            observe: false,
        }
    }

    #[must_use]
    pub fn observed(mut self) -> Self {
        self.observe = true;
        self
    }
}

#[derive(Debug, Error, PartialEq, Eq)]
pub enum CommandError {
    #[error("brightness {0} is outside the TRADFRI range 0..=254")]
    Brightness(u16),
    #[error("color temperature {0} is outside the TRADFRI range 250..=454 mired")]
    ColorTemperature(u16),
    #[error("hue {0} is outside the TRADFRI range 0..=65535")]
    Hue(u16),
    #[error("saturation {0} is outside the TRADFRI range 0..=65279")]
    Saturation(u16),
    #[error("x color coordinate {0} is outside the TRADFRI range 0..=65535")]
    ColorX(u16),
    #[error("y color coordinate {0} is outside the TRADFRI range 0..=65535")]
    ColorY(u16),
    #[error("blind position {0} is outside the TRADFRI range 0..=100")]
    BlindPosition(u8),
    #[error("air purifier fan speed {0} is outside the TRADFRI range 2..=50")]
    AirPurifierFanSpeed(u8),
    #[error("light color must be exactly six hexadecimal digits, got {0:?}")]
    HexColor(String),
}

#[must_use]
pub fn list_devices() -> Command {
    Command::get(protocol::ROOT_DEVICES)
}

#[must_use]
pub fn get_device(device_id: u32) -> Command {
    Command::get(protocol::device_path(device_id))
}

#[must_use]
pub fn observe_device(device_id: u32) -> Command {
    Command::get(protocol::device_path(device_id)).observed()
}

#[must_use]
pub fn list_groups() -> Command {
    Command::get(protocol::ROOT_GROUPS)
}

#[must_use]
pub fn get_group(group_id: u32) -> Command {
    Command::get(protocol::group_path(group_id))
}

#[must_use]
pub fn observe_group(group_id: u32) -> Command {
    Command::get(protocol::group_path(group_id)).observed()
}

/// Build the first-time credential provisioning request.
///
/// The transport layer must open this request using the gateway's printed
/// security code with the fixed `Client_identity` DTLS identity. The response
/// contains the long-lived PSK under attribute `9091`.
#[must_use]
pub fn provision_identity(identity: impl Into<String>) -> Command {
    let mut body = Map::new();
    body.insert(
        protocol::ATTR_CLIENT_IDENTITY.to_owned(),
        Value::String(identity.into()),
    );
    Command::post(protocol::auth_path(), Value::Object(body))
}

#[must_use]
pub fn set_light_state(device_id: u32, on: bool) -> Command {
    endpoint_put(
        protocol::device_path(device_id),
        protocol::ATTR_LIGHT_CONTROL,
        [(protocol::ATTR_DEVICE_STATE, Value::from(u8::from(on)))],
    )
}

/// Build a light brightness command.
///
/// # Errors
///
/// Returns an error when `brightness` is outside `0..=254`.
pub fn set_light_brightness(
    device_id: u32,
    brightness: u16,
    transition_time: Option<u16>,
) -> Result<Command, CommandError> {
    validate_u16(
        brightness,
        protocol::BRIGHTNESS_RANGE,
        CommandError::Brightness,
    )?;
    let mut values = vec![(protocol::ATTR_LIGHT_DIMMER, Value::from(brightness))];
    push_transition(&mut values, transition_time);
    Ok(endpoint_put(
        protocol::device_path(device_id),
        protocol::ATTR_LIGHT_CONTROL,
        values,
    ))
}

/// Build a light color-temperature command.
///
/// # Errors
///
/// Returns an error when `mireds` is outside `250..=454`.
pub fn set_light_color_temperature(
    device_id: u32,
    mireds: u16,
    transition_time: Option<u16>,
) -> Result<Command, CommandError> {
    validate_u16(
        mireds,
        protocol::MIRED_RANGE,
        CommandError::ColorTemperature,
    )?;
    let mut values = vec![(protocol::ATTR_LIGHT_MIREDS, Value::from(mireds))];
    push_transition(&mut values, transition_time);
    Ok(endpoint_put(
        protocol::device_path(device_id),
        protocol::ATTR_LIGHT_CONTROL,
        values,
    ))
}

/// Build a light hexadecimal-color command.
///
/// # Errors
///
/// Returns an error unless `color` contains exactly six hexadecimal digits.
pub fn set_light_hex_color(
    device_id: u32,
    color: &str,
    transition_time: Option<u16>,
) -> Result<Command, CommandError> {
    let color = normalize_hex_color(color)?;
    let mut values = vec![(protocol::ATTR_LIGHT_COLOR_HEX, Value::from(color))];
    push_transition(&mut values, transition_time);
    Ok(endpoint_put(
        protocol::device_path(device_id),
        protocol::ATTR_LIGHT_CONTROL,
        values,
    ))
}

/// Build a light XY-color command.
///
/// # Errors
///
/// Returns an error when either coordinate is outside the gateway range.
pub fn set_light_xy_color(
    device_id: u32,
    x: u16,
    y: u16,
    transition_time: Option<u16>,
) -> Result<Command, CommandError> {
    validate_u16(x, protocol::XY_RANGE, CommandError::ColorX)?;
    validate_u16(y, protocol::XY_RANGE, CommandError::ColorY)?;
    let mut values = vec![
        (protocol::ATTR_LIGHT_COLOR_X, Value::from(x)),
        (protocol::ATTR_LIGHT_COLOR_Y, Value::from(y)),
    ];
    push_transition(&mut values, transition_time);
    Ok(endpoint_put(
        protocol::device_path(device_id),
        protocol::ATTR_LIGHT_CONTROL,
        values,
    ))
}

/// Build a light HSB command.
///
/// # Errors
///
/// Returns an error when hue, saturation, or optional brightness is outside
/// its gateway range.
pub fn set_light_hsb(
    device_id: u32,
    hue: u16,
    saturation: u16,
    brightness: Option<u16>,
    transition_time: Option<u16>,
) -> Result<Command, CommandError> {
    validate_u16(hue, protocol::HUE_RANGE, CommandError::Hue)?;
    validate_u16(
        saturation,
        protocol::SATURATION_RANGE,
        CommandError::Saturation,
    )?;
    let mut values = vec![
        (protocol::ATTR_LIGHT_COLOR_HUE, Value::from(hue)),
        (
            protocol::ATTR_LIGHT_COLOR_SATURATION,
            Value::from(saturation),
        ),
    ];
    if let Some(brightness) = brightness {
        validate_u16(
            brightness,
            protocol::BRIGHTNESS_RANGE,
            CommandError::Brightness,
        )?;
        values.push((protocol::ATTR_LIGHT_DIMMER, Value::from(brightness)));
    }
    push_transition(&mut values, transition_time);
    Ok(endpoint_put(
        protocol::device_path(device_id),
        protocol::ATTR_LIGHT_CONTROL,
        values,
    ))
}

#[must_use]
pub fn set_socket_state(device_id: u32, on: bool) -> Command {
    endpoint_put(
        protocol::device_path(device_id),
        protocol::ATTR_SOCKET_CONTROL,
        [(protocol::ATTR_DEVICE_STATE, Value::from(u8::from(on)))],
    )
}

/// Build a blind-position command.
///
/// # Errors
///
/// Returns an error when `position` is outside `0..=100`.
pub fn set_blind_position(device_id: u32, position: u8) -> Result<Command, CommandError> {
    if !(protocol::BLIND_POSITION_RANGE.0..=protocol::BLIND_POSITION_RANGE.1).contains(&position) {
        return Err(CommandError::BlindPosition(position));
    }
    Ok(endpoint_put(
        protocol::device_path(device_id),
        protocol::ROOT_BLINDS,
        [(protocol::ATTR_BLIND_CURRENT_POSITION, Value::from(position))],
    ))
}

#[must_use]
pub fn trigger_blind(device_id: u32) -> Command {
    endpoint_put(
        protocol::device_path(device_id),
        protocol::ROOT_BLINDS,
        [(protocol::ATTR_BLIND_TRIGGER, Value::Bool(true))],
    )
}

#[must_use]
pub fn turn_air_purifier_off(device_id: u32) -> Command {
    air_purifier_put(device_id, protocol::ATTR_AIR_PURIFIER_MODE, Value::from(0))
}

#[must_use]
pub fn set_air_purifier_auto(device_id: u32) -> Command {
    air_purifier_put(
        device_id,
        protocol::ATTR_AIR_PURIFIER_MODE,
        Value::from(protocol::AIR_PURIFIER_MODE_AUTO),
    )
}

/// Build an air-purifier fan-speed command.
///
/// # Errors
///
/// Returns an error when `speed` is outside `2..=50`.
pub fn set_air_purifier_fan_speed(device_id: u32, speed: u8) -> Result<Command, CommandError> {
    if !(protocol::AIR_PURIFIER_FAN_RANGE.0..=protocol::AIR_PURIFIER_FAN_RANGE.1).contains(&speed) {
        return Err(CommandError::AirPurifierFanSpeed(speed));
    }
    Ok(air_purifier_put(
        device_id,
        protocol::ATTR_AIR_PURIFIER_MODE,
        Value::from(speed),
    ))
}

#[must_use]
pub fn set_air_purifier_controls_locked(device_id: u32, locked: bool) -> Command {
    air_purifier_put(
        device_id,
        protocol::ATTR_AIR_PURIFIER_CONTROLS_LOCKED,
        Value::from(u8::from(locked)),
    )
}

#[must_use]
pub fn set_air_purifier_leds_off(device_id: u32, leds_off: bool) -> Command {
    air_purifier_put(
        device_id,
        protocol::ATTR_AIR_PURIFIER_LEDS_OFF,
        Value::from(u8::from(leds_off)),
    )
}

#[must_use]
pub fn set_group_state(group_id: u32, on: bool) -> Command {
    direct_put(
        protocol::group_path(group_id),
        [(protocol::ATTR_DEVICE_STATE, Value::from(u8::from(on)))],
    )
}

/// Build a group brightness command.
///
/// # Errors
///
/// Returns an error when `brightness` is outside `0..=254`.
pub fn set_group_brightness(
    group_id: u32,
    brightness: u16,
    transition_time: Option<u16>,
) -> Result<Command, CommandError> {
    validate_u16(
        brightness,
        protocol::BRIGHTNESS_RANGE,
        CommandError::Brightness,
    )?;
    let mut values = vec![(protocol::ATTR_LIGHT_DIMMER, Value::from(brightness))];
    push_transition(&mut values, transition_time);
    Ok(direct_put(protocol::group_path(group_id), values))
}

/// Build a group color-temperature command.
///
/// # Errors
///
/// Returns an error when `mireds` is outside `250..=454`.
pub fn set_group_color_temperature(
    group_id: u32,
    mireds: u16,
    transition_time: Option<u16>,
) -> Result<Command, CommandError> {
    validate_u16(
        mireds,
        protocol::MIRED_RANGE,
        CommandError::ColorTemperature,
    )?;
    let mut values = vec![(protocol::ATTR_LIGHT_MIREDS, Value::from(mireds))];
    push_transition(&mut values, transition_time);
    Ok(direct_put(protocol::group_path(group_id), values))
}

fn air_purifier_put(device_id: u32, key: &'static str, value: Value) -> Command {
    endpoint_put(
        protocol::device_path(device_id),
        protocol::ROOT_AIR_PURIFIER,
        [(key, value)],
    )
}

fn endpoint_put<I>(path: String, endpoint: &'static str, values: I) -> Command
where
    I: IntoIterator<Item = (&'static str, Value)>,
{
    let endpoint_values = object(values);
    let mut body = Map::new();
    body.insert(
        endpoint.to_owned(),
        Value::Array(vec![Value::Object(endpoint_values)]),
    );
    Command::put(path, Value::Object(body))
}

fn direct_put<I>(path: String, values: I) -> Command
where
    I: IntoIterator<Item = (&'static str, Value)>,
{
    Command::put(path, Value::Object(object(values)))
}

fn object<I>(values: I) -> Map<String, Value>
where
    I: IntoIterator<Item = (&'static str, Value)>,
{
    values
        .into_iter()
        .map(|(key, value)| (key.to_owned(), value))
        .collect()
}

fn push_transition(values: &mut Vec<(&'static str, Value)>, transition_time: Option<u16>) {
    if let Some(transition_time) = transition_time {
        values.push((protocol::ATTR_TRANSITION_TIME, Value::from(transition_time)));
    }
}

fn validate_u16(
    value: u16,
    range: (u16, u16),
    error: fn(u16) -> CommandError,
) -> Result<(), CommandError> {
    if (range.0..=range.1).contains(&value) {
        Ok(())
    } else {
        Err(error(value))
    }
}

fn normalize_hex_color(color: &str) -> Result<String, CommandError> {
    let normalized = color.strip_prefix('#').unwrap_or(color);
    if normalized.len() == 6 && normalized.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        Ok(normalized.to_ascii_lowercase())
    } else {
        Err(CommandError::HexColor(color.to_owned()))
    }
}