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
use std::fmt;

use async_trait::async_trait;
use erased_serde::serialize_trait_object;
use futures::future::BoxFuture;
use serde::{
    ser::{SerializeStruct, Serializer},
    Deserialize,
    Serialize,
};
use serde_json::json;

use crate::{event::Event, pointer, HapType, Result};

mod generated;

pub use generated::*;

/// A characteristic. A characteristic is a feature that represents data or an associated behavior of a service. The
/// characteristic is defined by a universally unique type, and has additional properties that determine how the value
/// of the characteristic can be accessed.
#[derive(Default)]
pub struct Characteristic<T: fmt::Debug + Default + Clone + Serialize + Send + Sync> {
    id: u64,
    accessory_id: u64,
    hap_type: HapType,
    format: Format,
    perms: Vec<Perm>,
    description: Option<String>,
    event_notifications: Option<bool>,

    value: T,
    unit: Option<Unit>,

    max_value: Option<T>,
    min_value: Option<T>,
    step_value: Option<T>,
    max_len: Option<u16>,
    max_data_len: Option<u32>,
    valid_values: Option<Vec<T>>,
    valid_values_range: Option<[T; 2]>,

    on_read: Option<Box<dyn OnReadFn<T>>>,
    on_update: Option<Box<dyn OnUpdateFn<T>>>,
    on_read_async: Option<Box<dyn OnReadFuture<T>>>,
    on_update_async: Option<Box<dyn OnUpdateFuture<T>>>,

    event_emitter: Option<pointer::EventEmitter>,
}

impl<T: fmt::Debug + Default + Clone + Serialize + Send + Sync> fmt::Debug for Characteristic<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Characteristic")
            .field("id", &self.id)
            .field("accessory_id", &self.accessory_id)
            .field("hap_type", &self.hap_type)
            .field("format", &self.format)
            .field("perms", &self.perms)
            .field("description", &self.description)
            .field("event_notifications", &self.event_notifications)
            .field("value", &self.value)
            .field("unit", &self.unit)
            .field("max_value", &self.max_value)
            .field("min_value", &self.min_value)
            .field("step_value", &self.step_value)
            .field("max_len", &self.max_len)
            .field("max_data_len", &self.max_data_len)
            .field("valid_values", &self.valid_values)
            .field("valid_values_range", &self.valid_values_range)
            .finish()
    }
}

impl<T: fmt::Debug + Default + Clone + Serialize + Send + Sync> Characteristic<T>
where
    for<'de> T: Deserialize<'de>,
{
    /// Returns the ID of a Characteristic.
    pub fn get_id(&self) -> u64 { self.id }

    /// Returns the `HapType` of a Characteristic.
    pub fn get_type(&self) -> HapType { self.hap_type }

    /// Returns the `Format` of a Characteristic.
    pub fn get_format(&self) -> Format { self.format }

    /// Returns the `Perm`s of a Characteristic.
    pub fn get_perms(&self) -> Vec<Perm> { self.perms.clone() }

    /// Sets the description of a Characteristic.
    pub fn set_description(&mut self, description: Option<String>) { self.description = description; }

    /// Returns the event notifications value of a Characteristic.
    pub fn get_event_notifications(&self) -> Option<bool> { self.event_notifications }

    /// Sets the event notifications value of a Characteristic.
    pub fn set_event_notifications(&mut self, event_notifications: Option<bool>) {
        self.event_notifications = event_notifications;
    }

    /// Returns the value of a Characteristic.
    pub async fn get_value(&mut self) -> Result<T> {
        let mut val = None;
        if let Some(ref on_read) = self.on_read {
            val = on_read();
        }
        if let Some(ref on_read_async) = self.on_read_async {
            val = on_read_async().await;
        }
        if let Some(v) = val {
            self.set_value(v).await?;
        }

        Ok(self.value.clone())
    }

    /// Sets the value of a Characteristic.
    pub async fn set_value(&mut self, val: T) -> Result<()> {
        // TODO: check for min/max on types implementing PartialOrd
        // if let Some(ref max) = self.inner.try_borrow()?.max_value {
        //     if &val > max {
        //         return Err(Error::from_str("value above max_value"));
        //     }
        // }
        // if let Some(ref min) = self.inner.try_borrow()?.min_value {
        //     if &val < min {
        //         return Err(Error::from_str("value below min_value"));
        //     }
        // }

        let old_val = self.value.clone();
        if let Some(ref on_update) = self.on_update {
            on_update(&old_val, &val);
        }
        if let Some(ref on_update_async) = self.on_update_async {
            on_update_async(old_val, val.clone()).await;
        }

        if self.event_notifications == Some(true) {
            if let Some(ref event_emitter) = self.event_emitter {
                event_emitter
                    .lock()
                    .await
                    .emit(&Event::CharacteristicValueChanged {
                        aid: self.accessory_id,
                        iid: self.id,
                        value: json!(&val),
                    })
                    .await;
            }
        }

        self.value = val;

        Ok(())
    }

    /// Returns the `Unit` of a Characteristic.
    pub fn get_unit(&self) -> Option<Unit> { self.unit }

    /// Returns the maximum value of a Characteristic.
    pub fn get_max_value(&self) -> Option<T> { self.max_value.clone() }

    /// Sets the maximum value of a Characteristic.
    pub fn set_max_value(&mut self, val: Option<T>) { self.max_value = val; }

    /// Returns the minimum value of a Characteristic.
    pub fn get_min_value(&self) -> Option<T> { self.min_value.clone() }

    /// Sets the minimum value of a Characteristic.
    pub fn set_min_value(&mut self, val: Option<T>) { self.min_value = val; }

    /// Returns the step value of a Characteristic.
    pub fn get_step_value(&self) -> Option<T> { self.step_value.clone() }

    /// Returns the step value of a Characteristic.
    pub fn set_step_value(&mut self, val: Option<T>) { self.step_value = val; }

    /// Returns the maximum length of a Characteristic.
    pub fn get_max_len(&self) -> Option<u16> { self.max_len }

    /// Sets a callback function on a characteristic that is called every time a controller attempts to read its value.
    /// Returning a `Some(T)` from this function changes the value of the `Characteristic` before the Controller reads
    /// it so the Controller reads the new value.
    pub fn on_read(&mut self, f: Option<impl OnReadFn<T>>) {
        self.on_read = f.map(|f| Box::new(f) as Box<dyn OnReadFn<T>>);
    }

    /// Sets a callback function on a characteristic that is called every time a controller attempts to update its
    /// value. The first argument is a reference to the current value of the characteristic and the second argument is a
    /// reference to the value the controller attempts to change the characteristic's to.
    pub fn on_update(&mut self, f: Option<impl OnUpdateFn<T>>) {
        self.on_update = f.map(|f| Box::new(f) as Box<dyn OnUpdateFn<T>>);
    }

    /// Sets an async callback function on a characteristic that is driven to completion by the async runtime driving
    /// the HAP server every time a controller attempts to read its value. Returning a `Some(T)` from this function
    /// changes the value of the characteristic before the controller reads it so the controller reads the new value.
    pub fn on_read_async(&mut self, f: Option<impl OnReadFuture<T>>) {
        self.on_read_async = f.map(|f| Box::new(f) as Box<dyn OnReadFuture<T>>);
    }

    /// Sets an async callback function on a characteristic that is driven to completion by the async runtime driving
    /// the HAP server every time a controller attempts to update its value. The first argument is a reference to the
    /// current value of the characteristic and the second argument is a reference to the value the controller attempts
    /// to change the characteristic's to.
    pub fn on_update_async(&mut self, f: Option<impl OnUpdateFuture<T>>) {
        self.on_update_async = f.map(|f| Box::new(f) as Box<dyn OnUpdateFuture<T>>);
    }

    /// Sets a `hap::event::pointer::EventEmitter` on the Characteristic.
    pub(crate) fn set_event_emitter(&mut self, event_emitter: Option<pointer::EventEmitter>) {
        self.event_emitter = event_emitter;
    }
}

impl<T: fmt::Debug + Default + Clone + Serialize + Send + Sync> Serialize for Characteristic<T> {
    fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
        let mut state = serializer.serialize_struct("Characteristic", 15)?;
        state.serialize_field("iid", &self.id)?;
        state.serialize_field("type", &self.hap_type)?;
        state.serialize_field("format", &self.format)?;
        state.serialize_field("perms", &self.perms)?;
        if let Some(ref description) = self.description {
            state.serialize_field("description", description)?;
        }
        if let Some(ref event_notifications) = self.event_notifications {
            state.serialize_field("ev", event_notifications)?;
        }

        if self.perms.contains(&Perm::PairedRead) {
            state.serialize_field("value", &self.value)?;
        }
        if let Some(ref unit) = self.unit {
            state.serialize_field("unit", unit)?;
        }
        if let Some(ref max_value) = self.max_value {
            state.serialize_field("maxValue", max_value)?;
        }
        if let Some(ref min_value) = self.min_value {
            state.serialize_field("minValue", min_value)?;
        }
        if let Some(ref step_value) = self.step_value {
            state.serialize_field("minStep", step_value)?;
        }
        if let Some(ref max_len) = self.max_len {
            state.serialize_field("maxLen", max_len)?;
        }
        if let Some(ref max_data_len) = self.max_data_len {
            state.serialize_field("maxDataLen", max_data_len)?;
        }
        if let Some(ref valid_values) = self.valid_values {
            state.serialize_field("valid-values", valid_values)?;
        }
        if let Some(ref valid_values_range) = self.valid_values_range {
            state.serialize_field("valid-values-range", valid_values_range)?;
        }
        state.end()
    }
}

/// Permission of a `Characteristic`.
#[derive(Debug, Copy, Clone, Serialize, PartialEq)]
pub enum Perm {
    #[serde(rename = "pr")]
    PairedRead,
    #[serde(rename = "pw")]
    PairedWrite,
    #[serde(rename = "ev")]
    Events,
    #[serde(rename = "aa")]
    AdditionalAuthorization,
    #[serde(rename = "tw")]
    TimedWrite,
    #[serde(rename = "hd")]
    Hidden,
}

/// Unit of a `Characteristic`.
#[derive(Debug, Copy, Clone, Serialize)]
pub enum Unit {
    #[serde(rename = "percentage")]
    Percentage,
    #[serde(rename = "arcdegrees")]
    ArcDegrees,
    #[serde(rename = "celsius")]
    Celsius,
    #[serde(rename = "lux")]
    Lux,
    #[serde(rename = "seconds")]
    Seconds,
}

/// Format (data type) of a `Characteristic`.
#[derive(Debug, Copy, Clone, PartialEq, Serialize, Deserialize)]
pub enum Format {
    #[serde(rename = "string")]
    String,
    #[serde(rename = "bool")]
    Bool,
    #[serde(rename = "float")]
    Float,
    #[serde(rename = "uint8")]
    UInt8,
    #[serde(rename = "uint16")]
    UInt16,
    #[serde(rename = "uint32")]
    UInt32,
    #[serde(rename = "uint64")]
    UInt64,
    #[serde(rename = "int32")]
    Int32,
    #[serde(rename = "tlv8")]
    Tlv8,
    #[serde(rename = "data")]
    Data,
}

impl Default for Format {
    fn default() -> Format { Format::String }
}

/// `HapCharacteristic` is implemented by every `Characteristic`.
#[async_trait]
pub trait HapCharacteristic: HapCharacteristicSetup + erased_serde::Serialize + Send + Sync {
    /// Returns the ID of a Characteristic.
    fn get_id(&self) -> u64;
    /// Returns the `HapType` of a Characteristic.
    fn get_type(&self) -> HapType;
    /// Returns the `Format` of a Characteristic.
    fn get_format(&self) -> Format;
    /// Returns the `Perm`s of a Characteristic.
    fn get_perms(&self) -> Vec<Perm>;
    /// Returns the event notifications value of a Characteristic.
    fn get_event_notifications(&self) -> Option<bool>;
    /// Sets the event notifications value of a Characteristic.
    fn set_event_notifications(&mut self, event_notifications: Option<bool>);
    /// Returns the value of a Characteristic.
    async fn get_value(&mut self) -> Result<serde_json::Value>;
    /// Sets the value of a Characteristic.
    async fn set_value(&mut self, value: serde_json::Value) -> Result<()>;
    /// Returns the `Unit` of a Characteristic.
    fn get_unit(&self) -> Option<Unit>;
    /// Returns the maximum value of a Characteristic.
    fn get_max_value(&self) -> Option<serde_json::Value>;
    /// Returns the minimum value of a Characteristic.
    fn get_min_value(&self) -> Option<serde_json::Value>;
    /// Returns the step value of a Characteristic.
    fn get_step_value(&self) -> Option<serde_json::Value>;
    /// Returns the maximum length of a Characteristic.
    fn get_max_len(&self) -> Option<u16>;
}

serialize_trait_object!(HapCharacteristic);

pub trait HapCharacteristicSetup {
    /// Sets a `hap::event::pointer::EventEmitter` on the characteristic.
    fn set_event_emitter(&mut self, event_emitter: Option<pointer::EventEmitter>);
}

pub trait OnReadFn<T: Default + Clone + Serialize + Send + Sync>: Fn() -> Option<T> + 'static + Send + Sync {}
impl<F, T: Default + Clone + Serialize + Send + Sync> OnReadFn<T> for F where
    F: Fn() -> Option<T> + 'static + Send + Sync
{
}

pub trait OnUpdateFn<T: Default + Clone + Serialize + Send + Sync>: Fn(&T, &T) + 'static + Send + Sync {}
impl<F, T: Default + Clone + Serialize + Send + Sync> OnUpdateFn<T> for F where F: Fn(&T, &T) + 'static + Send + Sync {}

pub trait OnReadFuture<T: Default + Clone + Serialize + Send + Sync>:
    Fn() -> BoxFuture<'static, Option<T>> + 'static + Send + Sync
{
}
impl<F, T: Default + Clone + Serialize + Send + Sync> OnReadFuture<T> for F where
    F: Fn() -> BoxFuture<'static, Option<T>> + 'static + Send + Sync
{
}

pub trait OnUpdateFuture<T: Default + Clone + Serialize + Send + Sync>:
    Fn(T, T) -> BoxFuture<'static, ()> + 'static + Send + Sync
{
}
impl<F, T: Default + Clone + Serialize + Send + Sync> OnUpdateFuture<T> for F where
    F: Fn(T, T) -> BoxFuture<'static, ()> + 'static + Send + Sync
{
}

// Fn() -> impl Future<Output = Option<T>>
// Fn(&T, &T) -> Future<Output = ()>

pub trait CharacteristicCallbacks<T: fmt::Debug + Default + Clone + Serialize + Send + Sync> {
    /// Sets a callback function on a characteristic that is called every time a controller attempts to read its value.
    /// Returning a `Some(T)` from this function changes the value of the `Characteristic` before the Controller reads
    /// it so the Controller reads the new value.
    fn on_read(&mut self, f: Option<impl OnReadFn<T>>);
    /// Sets a callback function on a characteristic that is called every time a controller attempts to update its
    /// value. The first argument is a reference to the current value of the characteristic and the second argument is a
    /// reference to the value the controller attempts to change the characteristic's to.
    fn on_update(&mut self, f: Option<impl OnUpdateFn<T>>);
}

pub trait AsyncCharacteristicCallbacks<T: fmt::Debug + Default + Clone + Serialize + Send + Sync> {
    /// Sets an async callback function on a characteristic that is driven to completion by the async runtime driving
    /// the HAP server every time a controller attempts to read its value. Returning a `Some(T)` from this function
    /// changes the value of the characteristic before the controller reads it so the controller reads the new value.
    fn on_read_async(&mut self, f: Option<impl OnReadFuture<T>>);
    /// Sets an async callback function on a characteristic that is driven to completion by the async runtime driving
    /// the HAP server every time a controller attempts to update its value. The first argument is a reference to the
    /// current value of the characteristic and the second argument is a reference to the value the controller attempts
    /// to change the characteristic's to.
    fn on_update_async(&mut self, f: Option<impl OnUpdateFuture<T>>);
}

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

    #[test]
    fn test_json_serialization() {
        let characteristic = Characteristic::<u16> {
            id: 1,
            accessory_id: 1,
            hap_type: HapType::CurrentTiltAngle,
            format: Format::UInt16,
            perms: vec![Perm::PairedRead, Perm::Events],
            description: Some("Acme Tilt Angle".into()),
            event_notifications: Some(true),

            value: 123,
            unit: Some(Unit::ArcDegrees),

            max_value: Some(360),
            min_value: Some(0),
            step_value: Some(1),
            max_len: None,
            max_data_len: None,
            valid_values: None,
            valid_values_range: Some([0, 360]),

            on_read: None,
            on_update: None,
            on_read_async: None,
            on_update_async: None,

            event_emitter: None,
        };
        let json = serde_json::to_string(&characteristic).unwrap();
        assert_eq!(json, "{\"iid\":1,\"type\":\"C1\",\"format\":\"uint16\",\"perms\":[\"pr\",\"ev\"],\"description\":\"Acme Tilt Angle\",\"ev\":true,\"value\":123,\"unit\":\"arcdegrees\",\"maxValue\":360,\"minValue\":0,\"minStep\":1,\"valid-values-range\":[0,360]}".to_string());
    }
}