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
use crate::resource::{self, Adjust, Alert, Effect};
use crate::Color;
use derive_setters::Setters;
use serde::{ser::SerializeStruct, Deserialize, Serialize, Serializer};

/// A group of lights.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Deserialize)]
pub struct Group {
    /// Identifier of the group.
    #[serde(skip)]
    pub id: String,
    /// Name of the group.
    pub name: String,
    /// Identifiers of lights that are in this group.
    pub lights: Vec<String>,
    /// Identifiers of sensors that are in this group.
    pub sensors: Vec<String>,
    /// Kind of the group.
    #[serde(rename = "type")]
    pub kind: Kind,
    /// Class of the group.
    ///
    /// Only used if [`kind`] is [`Room`].
    ///
    /// [`kind`]: #structfield.kind
    /// [`Room`]: enum.CreatableKind.html#variant.Room
    pub class: Option<Class>,
    /// State of the group.
    pub state: Option<State>,
    /// Model identifier of the group.
    ///
    /// Only present for automatically created luminaires.
    #[serde(rename = "modelid")]
    pub model_id: Option<String>,
    /// Unique identifier of the group.
    ///
    /// In AA:BB:CC:DD format for luminaire groups or AA:BB:CC:DD-XX format for
    /// lightsource groups, where XX is the lightsource position.
    #[serde(rename = "unique_id")]
    pub unique_id: Option<String>,
    /// Whether the group is automatically deleted when not referenced anymore.
    pub recycle: Option<bool>,
}

impl Group {
    pub(crate) fn with_id(self, id: String) -> Self {
        Self { id, ..self }
    }
}

impl resource::Resource for Group {}

/// Kind of a group.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Deserialize)]
#[serde(untagged)]
pub enum Kind {
    /// Kind of a group that can be manually created.
    Creatable(CreatableKind),
    /// Kind of a group that is automatically created by the bridge and cannot be manually created.
    Immutable(ImmutableKind),
}

/// Kind of a group that can be manually created.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub enum CreatableKind {
    /// A group of lights that can be controlled together.
    ///
    /// This the default group type that the bridge generates for user created groups. Default type
    /// when no type is given on creation.
    LightGroup,
    /// A group of lights that are physically located in the same place.
    ///
    /// Rooms behave similar as light groups, except: (1) A room can be empty and contain 0 lights,
    /// (2) a light is only allowed in one room and (3) a room is not automatically deleted when
    /// all lights in that room are deleted.
    Room,
    /// A group of lights that are used in an entertainment setup.
    ///
    /// Entertainment group behave in a similar way as light groups, with the exception: it can be
    /// empty and contain 0 lights. The group is also not automatically recycled when lights are
    /// deleted. The group of lights can be controlled together as in LightGroup.
    Entertainment,
    /// Zones describe a group of lights that can be controlled together.
    ///
    /// Zones can be empty and contain 0 lights. A light is allowed to be in multiple zones.
    Zone,
}

/// Kind of a group that is automatically created by the bridge and cannot be manually created.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Deserialize)]
pub enum ImmutableKind {
    /// A special group containing all lights in the system.
    ///
    /// This group is not returned by the `get_all_groups` function, and cannot be created,
    /// modified or deleted.
    Zero,
    /// A lighting installation of default groupings of hue lights.
    ///
    /// The bridge will pre-install these groups for ease of use. This type cannot be created
    /// manually. Also, a light can only be in a maximum of one luminaire group.
    Luminaire,
    /// A group of lights based on multisource luminaire attributes.
    ///
    /// This group is created by the bridge.
    #[serde(rename = "Lightsource")]
    LightSource,
}

/// Class of a group.
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub enum Class {
    Attic,
    Balcony,
    Barbecue,
    Bathroom,
    Bedroom,
    Carport,
    Closet,
    Computer,
    Dining,
    Downstairs,
    Driveway,
    #[serde(rename = "Front door")]
    FrontDoor,
    Garage,
    Garden,
    #[serde(rename = "Guest room")]
    GuestRoom,
    Gym,
    Hallway,
    Home,
    #[serde(rename = "Kids bedroom")]
    KidsBedroom,
    Kitchen,
    #[serde(rename = "Laundry room")]
    LaundryRoom,
    #[serde(rename = "Living room")]
    LivingRoom,
    Lounge,
    #[serde(rename = "Man cave")]
    ManCave,
    Music,
    Nursery,
    Office,
    Other,
    Pool,
    Porch,
    Reading,
    Recreation,
    Staircase,
    Storage,
    Studio,
    #[serde(rename = "TV")]
    Tv,
    Terrace,
    Toilet,
    #[serde(rename = "Top floor")]
    TopFloor,
    Upstairs,
}

/// State of a group.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Deserialize)]
pub struct State {
    /// Whether any light in a group is on.
    pub any_on: bool,
    /// Whether all lights in a group are on.
    pub all_on: bool,
}

/// Struct for creating a group.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Setters)]
#[setters(strip_option, prefix = "with_")]
pub struct Creator {
    /// Sets the name of the group.
    #[setters(skip)]
    pub name: String,
    /// Sets the light identifiers of the group.
    #[setters(skip)]
    pub lights: Vec<String>,
    /// Sets the sensor identifiers of the group.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sensors: Option<Vec<String>>,
    /// Sets the kind of the group.
    #[serde(skip_serializing_if = "Option::is_none", rename = "type")]
    pub kind: Option<CreatableKind>,
    /// Sets the class of the group.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub class: Option<Class>,
    /// Sets whether the group is automatically deleted when not referenced anymore.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub recycle: Option<bool>,
}

impl Creator {
    /// Creates a new [`Creator`].
    pub fn new(name: String, lights: Vec<String>) -> Self {
        Self {
            name,
            lights,
            sensors: None,
            kind: None,
            class: None,
            recycle: None,
        }
    }
}

impl resource::Creator for Creator {
    fn url_suffix() -> String {
        "groups".to_owned()
    }
}

/// Struct for modifying group attributes.
#[derive(Clone, Debug, Default, Eq, PartialEq, Hash, Serialize, Setters)]
#[setters(strip_option, prefix = "with_")]
pub struct AttributeModifier {
    /// Sets the name of the group.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Sets the identifiers of the lights of the group.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lights: Option<Vec<String>>,
    /// Sets the identifiers of the sensors of the group.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sensors: Option<Vec<String>>,
    /// Sets the class of the group.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub class: Option<Class>,
}

impl AttributeModifier {
    /// Creates a new [`AttributeModifier`].
    pub fn new() -> Self {
        Self::default()
    }
}

impl resource::Modifier for AttributeModifier {
    type Id = String;
    fn url_suffix(id: Self::Id) -> String {
        format!("groups/{}", id)
    }
}

/// Struct for modifying the group state.
#[derive(Clone, Debug, Default, PartialEq, Setters)]
#[setters(strip_option, prefix = "with_")]
pub struct StateModifier {
    /// Turns the lights on or off.
    pub on: Option<bool>,
    /// Sets the brightness of the lights.
    pub brightness: Option<Adjust<u8>>,
    /// Sets the hue of the lights.
    pub hue: Option<Adjust<u16>>,
    /// Sets the saturation of the lights.
    pub saturation: Option<Adjust<u8>>,
    /// Sets the color space coordinates of the lights.
    pub color_space_coordinates: Option<Adjust<(f32, f32)>>,
    /// Sets the color temperature of the lights.
    pub color_temperature: Option<Adjust<u16>>,
    /// Sets the alert effect of the lights.
    pub alert: Option<Alert>,
    /// Sets the dynamic effect of the lights.
    pub effect: Option<Effect>,
    /// Sets the transition duration of state changes.
    ///
    /// This is given as a multiple of 100ms.
    pub transition_time: Option<u16>,
    /// Sets the scene identifier of the group.
    pub scene: Option<String>,
}

impl StateModifier {
    /// Creates a new [`StateModifier`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Convenient method to set the [`color_space_coordinates`] and [`brightness`] fields.
    ///
    /// [`color_space_coordinates`]: Self::color_space_coordinates
    /// [`brightness`]: Self::brightness
    pub fn with_color(self, value: Color) -> Self {
        let mut modifier = Self {
            color_space_coordinates: Some(Adjust::Override(value.space_coordinates)),
            ..self
        };
        if let Some(brightness) = value.brightness {
            modifier.brightness = Some(Adjust::Override(brightness));
        }
        modifier
    }
}

impl resource::Modifier for StateModifier {
    type Id = String;
    fn url_suffix(id: Self::Id) -> String {
        format!("groups/{}/action", id)
    }
}

impl Serialize for StateModifier {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        custom_serialize! {
            serializer, "StateModifier";
            on => (&self.on),
            bri => (&self.brightness, to_override),
            bri_inc => (&self.brightness, to_increment, i16),
            hue => (&self.hue, to_override),
            hue_inc => (&self.hue, to_increment, i32),
            sat => (&self.saturation, to_override),
            sat_inc => (&self.saturation, to_increment, i16),
            xy => (&self.color_space_coordinates, to_override),
            xy_inc => (&self.color_space_coordinates, to_increment_tuple, f32),
            ct => (&self.color_temperature, to_override),
            ct_inc => (&self.color_temperature, to_increment, i32),
            alert => (&self.alert),
            effect => (&self.effect),
            transitiontime => (&self.transition_time),
            scene => (&self.scene),
        }
    }
}

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

    #[test]
    fn serialize_creator() {
        let creator = Creator::new("test".into(), vec!["1".into(), "2".into()]);
        let creator_json = serde_json::to_value(creator).unwrap();
        let expected_json = json!({
            "name": "test",
            "lights": ["1", "2"],
        });
        assert_eq!(creator_json, expected_json);

        let creator = Creator {
            name: "test".into(),
            lights: vec!["1".into(), "2".into()],
            sensors: Some(vec!["3".into()]),
            kind: Some(CreatableKind::Room),
            class: Some(Class::Office),
            recycle: Some(true),
        };
        let creator_json = serde_json::to_value(creator).unwrap();
        let expected_json = json!({
            "name": "test",
            "lights": ["1", "2"],
            "sensors": ["3"],
            "type": "Room",
            "class": "Office",
            "recycle": true
        });
        assert_eq!(creator_json, expected_json);
    }

    #[test]
    fn serialize_attribute_modifier() {
        let modifier = AttributeModifier::new();
        let modifier_json = serde_json::to_value(modifier).unwrap();
        let expected_json = json!({});
        assert_eq!(modifier_json, expected_json);

        let modifier = AttributeModifier {
            name: Some("test".into()),
            lights: Some(vec!["1".into(), "2".into()]),
            sensors: Some(vec!["3".into()]),
            class: Some(Class::Office),
        };
        let modifier_json = serde_json::to_value(modifier).unwrap();
        let expected_json = json!({
            "name": "test",
            "lights": ["1", "2"],
            "sensors": ["3"],
            "class": "Office"
        });
        assert_eq!(modifier_json, expected_json);
    }

    #[test]
    fn serialize_state_modifier() {
        let modifier = StateModifier::new();
        let modifier_json = serde_json::to_value(modifier).unwrap();
        let expected_json = json!({});
        assert_eq!(modifier_json, expected_json);

        let modifier = StateModifier {
            on: Some(true),
            brightness: Some(Adjust::Increment(1)),
            hue: Some(Adjust::Override(2)),
            saturation: Some(Adjust::Decrement(3)),
            color_space_coordinates: None,
            color_temperature: Some(Adjust::Override(4)),
            alert: Some(Alert::None),
            effect: Some(Effect::Colorloop),
            transition_time: Some(4),
            scene: Some("1".into()),
        };
        let modifier_json = serde_json::to_value(modifier).unwrap();
        let expected_json = json!({
            "on": true,
            "bri_inc": 1,
            "hue": 2,
            "sat_inc": -3,
            "ct": 4,
            "alert": "none",
            "effect": "colorloop",
            "transitiontime": 4,
            "scene": "1"
        });
        assert_eq!(modifier_json, expected_json);

        let modifier = StateModifier::new()
            .with_brightness(Adjust::Increment(1))
            .with_color(Color::from_rgb(0, 0, 0));
        let modifier_json = serde_json::to_value(modifier).unwrap();
        let expected_json = json!({
            "bri": 0,
            "xy": [0.0, 0.0]
        });
        assert_eq!(modifier_json, expected_json);
    }
}