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
use crate::{resource, util};
use chrono::NaiveDateTime;
use derive_setters::Setters;
use serde::{Deserialize, Serialize};
use serde_json::{Error as JsonError, Value as JsonValue};

/// A rule for resources on a bridge.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize)]
pub struct Rule {
    /// Identifier of the rule.
    #[serde(skip)]
    pub id: String,
    /// Name of the rule.
    pub name: String,
    /// Owner of the rule.
    #[serde(deserialize_with = "util::deserialize_option_string")]
    pub owner: Option<String>,
    /// When the rule was last triggered.
    #[serde(
        rename = "lasttriggered",
        deserialize_with = "util::deserialize_option_date_time"
    )]
    pub last_triggered: Option<NaiveDateTime>,
    /// How often the rule was triggered.
    #[serde(rename = "timestriggered")]
    pub times_triggered: usize,
    /// When the rule was created.
    pub created: NaiveDateTime,
    /// Status of the rule.
    pub status: Status,
    /// Conditions of the rule.
    pub conditions: Vec<Condition>,
    /// Actions of the rule.
    pub actions: Vec<Action>,
}

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

impl resource::Resource for Rule {}

/// Status of a rule.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Status {
    /// The rule is enabled.
    Enabled,
    /// The rule is disabled.
    Disabled,
    /// The rule was deleted.
    ResourceDeleted,
}

/// Condition of a rule.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub struct Condition {
    /// Address of an attribute of a sensor resource.
    pub address: String,
    /// Operator of the condition.
    pub operator: ConditionOperator,
    /// Value of the condition.
    ///
    /// The resource attribute is compared to this value using the given operator. The value is
    /// casted to the data type of the resource attribute. If the cast fails or the operator does
    /// not support the data type the value is casted to the rule is rejected.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value: Option<String>,
}

/// Condition operator of a rule.
#[derive(Clone, Debug, Eq, PartialEq, Hash, Deserialize, Serialize)]
pub enum ConditionOperator {
    /// Less than an int value.
    #[serde(rename = "lt")]
    LessThan,
    /// Greater than an int value.
    #[serde(rename = "gt")]
    GreaterThan,
    /// Equals an int or bool value.
    #[serde(rename = "eq")]
    Equals,
    /// Triggers when value of button event is changed or change of presence is detected.
    #[serde(rename = "dx")]
    Dx,
    /// Triggers when value of button event is changed or change of presence is detected.
    #[serde(rename = "ddx")]
    Ddx,
    /// An attribute has changed for a given time.
    #[serde(rename = "stable")]
    Stable,
    /// An attribute has not changed for a given time.
    #[serde(rename = "not stable")]
    NotStable,
    /// Current time is in given time interval.
    #[serde(rename = "in")]
    In,
    /// Current time is not in given time interval.
    #[serde(rename = "not in")]
    NotIn,
}

/// Action of a schedule or rule.
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Action {
    /// Address where the action will be executed.
    pub address: String,
    /// The HTTP method used to send the body to the given address.
    #[serde(rename = "method")]
    pub request_method: ActionRequestMethod,
    /// Body of the request that the action sends.
    pub body: JsonValue,
}

impl Action {
    /// Creates a new action from a [`Creator`].
    ///
    /// [`Creator`]: resource::Creator
    pub fn from_creator<C>(creator: &C) -> Result<Self, JsonError>
    where
        C: resource::Creator,
    {
        Ok(Self {
            address: format!("/{}", C::url_suffix()),
            request_method: ActionRequestMethod::Post,
            body: serde_json::to_value(creator)?,
        })
    }

    /// Creates a new action from a [`Modifier`].
    ///
    /// [`Modifier`]: resource::Modifier
    pub fn from_modifier<M>(modifier: &M, id: M::Id) -> Result<Self, JsonError>
    where
        M: resource::Modifier,
    {
        Ok(Self {
            address: format!("/{}", M::url_suffix(id)),
            request_method: ActionRequestMethod::Put,
            body: serde_json::to_value(modifier)?,
        })
    }

    /// Creates a new action from a [`Scanner`].
    ///
    /// [`Scanner`]: resource::Scanner
    pub fn from_scanner<S>(scanner: &S) -> Result<Self, JsonError>
    where
        S: resource::Scanner,
    {
        Ok(Self {
            address: format!("/{}", S::url_suffix()),
            request_method: ActionRequestMethod::Post,
            body: serde_json::to_value(scanner)?,
        })
    }
}

/// Request method of an action.
#[allow(missing_docs)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum ActionRequestMethod {
    Put,
    Post,
    Delete,
}

/// Struct for creating a rule.
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Setters)]
#[setters(strip_option, prefix = "with_")]
pub struct Creator {
    /// Sets the name of the rule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Sets the status of the rule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<Status>,
    /// Sets the conditions of the rule.
    #[setters(skip)]
    pub conditions: Vec<Condition>,
    /// Sets the actions of the rule.
    #[setters(skip)]
    pub actions: Vec<Action>,
}

impl Creator {
    /// Creates a new [`Creator`].
    pub fn new(conditions: Vec<Condition>, actions: Vec<Action>) -> Self {
        Self {
            name: None,
            status: None,
            conditions,
            actions,
        }
    }
}

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

/// Struct for modifying a rule.
#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Setters)]
#[setters(strip_option, prefix = "with_")]
pub struct Modifier {
    /// Sets the name of the modifier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Sets the status of the rule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status: Option<Status>,
    /// Sets the conditions of the rule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub conditions: Option<Vec<Condition>>,
    /// Sets the actions of the rule.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub actions: Option<Vec<Action>>,
}

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

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

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

    #[test]
    fn serialize_action() {
        let action = Action {
            address: "/lights/1/state".into(),
            request_method: ActionRequestMethod::Put,
            body: json!({"on": true}),
        };
        let action_json = serde_json::to_value(action).unwrap();
        let expected_json = json!({
            "address": "/lights/1/state",
            "method": "PUT",
            "body": {
                "on": true
            }
        });
        assert_eq!(action_json, expected_json);

        let creator = resource::group::Creator::new("test".into(), vec!["1".into()]);
        let action = Action::from_creator(&creator).unwrap();
        let action_json = serde_json::to_value(action).unwrap();
        let expected_json = json!({
            "address": "/groups",
            "method": "POST",
            "body": {
                "name": "test",
                "lights": ["1"]
            }
        });
        assert_eq!(action_json, expected_json);

        let modifier = resource::light::StateModifier::new().with_on(true);
        let action = Action::from_modifier(&modifier, "1".into()).unwrap();
        let action_json = serde_json::to_value(action).unwrap();
        let expected_json = json!({
            "address": "/lights/1/state",
            "method": "PUT",
            "body": {
                "on": true
            }
        });
        assert_eq!(action_json, expected_json);

        let scanner = resource::light::Scanner::new();
        let action = Action::from_scanner(&scanner).unwrap();
        let action_json = serde_json::to_value(action).unwrap();
        let expected_json = json!({
            "address": "/lights",
            "method": "POST",
            "body": {}
        });
        assert_eq!(action_json, expected_json);
    }

    #[test]
    fn serialize_creator() {
        let conditions = vec![Condition {
            address: "/sensors/2/state/lastupdated".into(),
            operator: ConditionOperator::Dx,
            value: None,
        }];
        let actions = vec![Action {
            address: "/lights/1/state".into(),
            request_method: ActionRequestMethod::Put,
            body: json!({}),
        }];

        let creator = Creator::new(conditions.clone(), actions.clone());
        let creator_json = serde_json::to_value(creator).unwrap();
        let expected_json = json!({
            "conditions": [
                {
                    "address": "/sensors/2/state/lastupdated",
                    "operator": "dx"
                }
            ],
            "actions": [
                {
                    "address": "/lights/1/state",
                    "method": "PUT",
                    "body": {}
                }
            ],
        });
        assert_eq!(creator_json, expected_json);

        let creator = Creator {
            name: Some("test".into()),
            status: Some(Status::Enabled),
            conditions,
            actions,
        };
        let creator_json = serde_json::to_value(creator).unwrap();
        let expected_json = json!({
            "name": "test",
            "status": "enabled",
            "conditions": [
                {
                    "address": "/sensors/2/state/lastupdated",
                    "operator": "dx"
                }
            ],
            "actions": [
                {
                    "address": "/lights/1/state",
                    "method": "PUT",
                    "body": {}
                }
            ],
        });
        assert_eq!(creator_json, expected_json);
    }

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

        let modifier = Modifier {
            name: Some("test".into()),
            status: Some(Status::Disabled),
            conditions: Some(vec![]),
            actions: Some(vec![]),
        };
        let modifier_json = serde_json::to_value(modifier).unwrap();
        let expected_json = json!({
            "name": "test",
            "status": "disabled",
            "conditions": [],
            "actions": []
        });
        assert_eq!(modifier_json, expected_json);
    }
}