generic_camera/
property.rs

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
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
/*!
 * # Property
 * Encapsulates values and limits of a property.
 */
use std::time::Duration;

use crate::GenCamPixelBpp;
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// Result type for property operations
pub type PropertyResult<T> = Result<T, PropertyError>;

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
/// A property
pub struct Property {
    auto: bool,
    rdonly: bool,
    prop: PropertyLims,
    doc: Option<String>,
}

impl Property {
    /// Create a new property
    pub fn new(prop: PropertyLims, auto_supported: bool, rdonly: bool) -> Self {
        Property {
            auto: auto_supported,
            rdonly,
            prop,
            doc: None,
        }
    }

    /// Set an optional documentation string
    pub fn set_doc<T: Into<String>>(&mut self, doc: T) {
        self.doc = Some(doc.into());
    }

    /// Get the documentation string
    pub fn get_doc(&self) -> Option<&str> {
        self.doc.as_deref()
    }

    /// Get the type of the property
    pub fn get_type(&self) -> PropertyType {
        (&self.prop).into()
    }

    /// Check if the property supports auto mode
    pub fn supports_auto(&self) -> bool {
        self.auto
    }

    /// Validate a property value
    pub fn validate(&self, value: &PropertyValue) -> PropertyResult<()> {
        // 1. Check if value in enum
        match self.prop {
            PropertyLims::EnumStr { ref variants, .. } => {
                if let PropertyValue::EnumStr(ref val) = value {
                    if variants.contains(val) {
                        return Ok(());
                    } else {
                        return Err(PropertyError::ValueNotSupported);
                    }
                } else {
                    return Err(PropertyError::InvalidControlType {
                        expected: PropertyType::EnumStr,
                        received: value.get_type(),
                    });
                }
            }
            PropertyLims::EnumInt { ref variants, .. } => {
                if let PropertyValue::Int(ref val) = value {
                    if variants.contains(val) {
                        return Ok(());
                    } else {
                        return Err(PropertyError::ValueNotSupported);
                    }
                } else {
                    return Err(PropertyError::InvalidControlType {
                        expected: PropertyType::EnumInt,
                        received: value.get_type(),
                    });
                }
            }
            PropertyLims::EnumUnsigned { ref variants, .. } => {
                if let PropertyValue::Unsigned(ref val) = value {
                    if variants.contains(val) {
                        return Ok(());
                    } else {
                        return Err(PropertyError::ValueNotSupported);
                    }
                } else {
                    return Err(PropertyError::InvalidControlType {
                        expected: PropertyType::EnumUnsigned,
                        received: value.get_type(),
                    });
                }
            }
            PropertyLims::Duration { .. } => {
                if value.get_type() != PropertyType::Duration {
                    return Err(PropertyError::InvalidControlType {
                        expected: PropertyType::Duration,
                        received: value.get_type(),
                    });
                }
            }
            PropertyLims::Bool { .. } => {
                if value.get_type() != PropertyType::Bool {
                    return Err(PropertyError::InvalidControlType {
                        expected: PropertyType::Bool,
                        received: value.get_type(),
                    });
                }
            }
            PropertyLims::Int { .. } => {
                if value.get_type() != PropertyType::Int {
                    return Err(PropertyError::InvalidControlType {
                        expected: PropertyType::Int,
                        received: value.get_type(),
                    });
                }
            }
            PropertyLims::Float { .. } => {
                if value.get_type() != PropertyType::Float {
                    return Err(PropertyError::InvalidControlType {
                        expected: PropertyType::Float,
                        received: value.get_type(),
                    });
                }
            }
            PropertyLims::Unsigned { .. } => {
                if value.get_type() != PropertyType::Unsigned {
                    return Err(PropertyError::InvalidControlType {
                        expected: PropertyType::Unsigned,
                        received: value.get_type(),
                    });
                }
            }
            PropertyLims::PixelFmt { .. } => {
                if value.get_type() != PropertyType::PixelFmt {
                    return Err(PropertyError::InvalidControlType {
                        expected: PropertyType::PixelFmt,
                        received: value.get_type(),
                    });
                }
            }
        }
        // 2. Check if value is within limits
        match self.get_type() {
            PropertyType::Int
            | PropertyType::Unsigned
            | PropertyType::Float
            | PropertyType::Duration => {
                if &self.get_min()? <= value && value <= &self.get_max()? {
                    Ok(())
                } else {
                    Err(PropertyError::ValueOutOfRange {
                        value: value.clone(),
                        min: self.get_min().unwrap(), // safety: checked above
                        max: self.get_max().unwrap(), // safety: checked above
                    })
                }
            }
            PropertyType::Bool => Ok(()),
            PropertyType::Command
            | PropertyType::PixelFmt
            | PropertyType::EnumStr
            | PropertyType::EnumInt
            | PropertyType::EnumUnsigned => Err(PropertyError::NotNumber),
        }
    }

    /// Get the minimum value of the property
    pub fn get_min(&self) -> PropertyResult<PropertyValue> {
        use PropertyLims::*;
        match &self.prop {
            Bool { .. } => Err(PropertyError::NotNumber),
            Int { min, .. } => Ok((*min).into()),
            Float { min, .. } => Ok((*min).into()),
            Unsigned { min, .. } => Ok((*min).into()),
            Duration { min, .. } => Ok((*min).into()),
            PixelFmt { variants, .. } => {
                Ok((*variants.iter().min().ok_or(PropertyError::EmptyEnumList)?).into())
            }
            EnumStr { .. } => Err(PropertyError::NotNumber),
            EnumInt { variants, .. } => {
                Ok((*variants.iter().min().ok_or(PropertyError::EmptyEnumList)?).into())
            }
            EnumUnsigned { variants, .. } => {
                Ok((*variants.iter().min().ok_or(PropertyError::EmptyEnumList)?).into())
            }
        }
    }

    /// Get the maximum value of the property
    pub fn get_max(&self) -> PropertyResult<PropertyValue> {
        use PropertyLims::*;
        match &self.prop {
            Bool { .. } => Err(PropertyError::NotNumber),
            Int { max, .. } => Ok((*max).into()),
            Float { max, .. } => Ok((*max).into()),
            Unsigned { max, .. } => Ok((*max).into()),
            Duration { max, .. } => Ok((*max).into()),
            PixelFmt { variants, .. } => {
                Ok((*variants.iter().max().ok_or(PropertyError::EmptyEnumList)?).into())
            }
            EnumStr { .. } => Err(PropertyError::NotNumber),
            EnumInt { variants, .. } => {
                Ok((*variants.iter().max().ok_or(PropertyError::EmptyEnumList)?).into())
            }
            EnumUnsigned { variants, .. } => {
                Ok((*variants.iter().max().ok_or(PropertyError::EmptyEnumList)?).into())
            }
        }
    }

    /// Get the step value of the property
    pub fn get_step(&self) -> PropertyResult<PropertyValue> {
        use PropertyLims::*;
        match &self.prop {
            Bool { .. } => Err(PropertyError::NotNumber),
            Int { step, .. } => Ok((*step).into()),
            Float { step, .. } => Ok((*step).into()),
            Unsigned { step, .. } => Ok((*step).into()),
            Duration { step, .. } => Ok((*step).into()),
            PixelFmt { .. } => Err(PropertyError::IsEnum),
            EnumStr { .. } => Err(PropertyError::NotNumber),
            EnumInt { .. } => Err(PropertyError::IsEnum),
            EnumUnsigned { .. } => Err(PropertyError::IsEnum),
        }
    }

    /// Get the default value of the property
    pub fn get_default(&self) -> PropertyResult<PropertyValue> {
        use PropertyLims::*;
        match self.prop.clone() {
            Bool { default } => Ok(default.into()),
            Int { default, .. } => Ok(default.into()),
            Float { default, .. } => Ok(default.into()),
            Unsigned { default, .. } => Ok(default.into()),
            Duration { default, .. } => Ok(default.into()),
            PixelFmt { default, .. } => Ok(default.into()),
            EnumStr { default, .. } => Ok(default.into()),
            EnumInt { default, .. } => Ok(default.into()),
            EnumUnsigned { default, .. } => Ok(default.into()),
        }
    }

    /// Get the variants of the property
    pub fn get_variants(&self) -> PropertyResult<Vec<PropertyValue>> {
        use PropertyLims::*;
        match &self.prop {
            Bool { .. } | Int { .. } | Float { .. } | Unsigned { .. } | Duration { .. } => {
                Err(PropertyError::NotEnum)
            }
            PixelFmt { variants, .. } => Ok(variants.iter().map(|x| (*x).into()).collect()),
            EnumStr { variants, .. } => Ok(variants.iter().map(|x| x.clone().into()).collect()),
            EnumInt { variants, .. } => Ok(variants.iter().map(|x| (*x).into()).collect()),
            EnumUnsigned { variants, .. } => Ok(variants.iter().map(|x| (*x).into()).collect()),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
/// A property with limits
pub enum PropertyLims {
    /// A boolean property
    Bool {
        /// The default value
        default: bool,
    },
    /// An integer property
    Int {
        /// The minimum value
        min: i64,
        /// The maximum value
        max: i64,
        /// The step size
        step: i64,
        /// The default value
        default: i64,
    },
    /// A floating point property
    Float {
        /// The minimum value
        min: f64,
        /// The maximum value
        max: f64,
        /// The step size
        step: f64,
        /// The default value
        default: f64,
    },
    /// An unsigned integer property
    Unsigned {
        /// The minimum value
        min: u64,
        /// The maximum value
        max: u64,
        /// The step size
        step: u64,
        /// The default value
        default: u64,
    },
    /// A duration property
    Duration {
        /// The minimum value
        min: Duration,
        /// The maximum value
        max: Duration,
        /// The step size
        step: Duration,
        /// The default value
        default: Duration,
    },
    /// A pixel format property
    PixelFmt {
        /// The variants of the property
        variants: Vec<GenCamPixelBpp>,
        /// The default value
        default: GenCamPixelBpp,
    },
    /// An enum string property
    EnumStr {
        /// The variants of the property
        variants: Vec<String>,
        /// The default value
        default: String,
    },
    /// An enum integer property
    EnumInt {
        /// The variants of the property
        variants: Vec<i64>,
        /// The default value
        default: i64,
    },
    /// An enum unsigned integer property
    EnumUnsigned {
        /// The variants of the property
        variants: Vec<u64>,
        /// The default value
        default: u64,
    },
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, PartialOrd)]
#[non_exhaustive]
/// A property value
pub enum PropertyValue {
    /// A command
    Command,
    /// A boolean value
    Bool(bool),
    /// An integer value
    Int(i64),
    /// A floating point value
    Float(f64),
    /// An unsigned integer value
    Unsigned(u64),
    /// A pixel format value
    PixelFmt(GenCamPixelBpp),
    /// A duration value
    Duration(Duration),
    /// An enum string value
    EnumStr(String),
}

impl PropertyValue {
    /// Get the type of the property value
    pub fn get_type(&self) -> PropertyType {
        self.into()
    }
}

impl From<()> for PropertyValue {
    fn from(_: ()) -> Self {
        PropertyValue::Command
    }
}

impl From<i64> for PropertyValue {
    fn from(val: i64) -> Self {
        PropertyValue::Int(val)
    }
}

impl From<u64> for PropertyValue {
    fn from(val: u64) -> Self {
        PropertyValue::Unsigned(val)
    }
}

impl From<f64> for PropertyValue {
    fn from(val: f64) -> Self {
        PropertyValue::Float(val)
    }
}

impl From<Duration> for PropertyValue {
    fn from(val: Duration) -> Self {
        PropertyValue::Duration(val)
    }
}

impl From<String> for PropertyValue {
    fn from(val: String) -> Self {
        PropertyValue::EnumStr(val)
    }
}

impl From<&str> for PropertyValue {
    fn from(val: &str) -> Self {
        PropertyValue::EnumStr(val.to_owned())
    }
}

impl From<bool> for PropertyValue {
    fn from(val: bool) -> Self {
        PropertyValue::Bool(val)
    }
}

impl From<GenCamPixelBpp> for PropertyValue {
    fn from(val: GenCamPixelBpp) -> Self {
        PropertyValue::PixelFmt(val)
    }
}

impl TryFrom<PropertyValue> for () {
    type Error = PropertyError;

    fn try_from(value: PropertyValue) -> Result<Self, Self::Error> {
        match value {
            PropertyValue::Command => Ok(()),
            _ => Err(PropertyError::InvalidControlType {
                expected: PropertyType::Command,
                received: value.get_type(),
            }),
        }
    }
}

impl TryFrom<&PropertyValue> for () {
    type Error = PropertyError;

    fn try_from(value: &PropertyValue) -> Result<Self, Self::Error> {
        match value {
            PropertyValue::Command => Ok(()),
            _ => Err(PropertyError::InvalidControlType {
                expected: PropertyType::Command,
                received: value.get_type(),
            }),
        }
    }
}

macro_rules! tryfrom_impl_propval {
    ($type:ty, $variant:ident) => {
        impl TryFrom<PropertyValue> for $type {
            type Error = PropertyError;

            fn try_from(value: PropertyValue) -> Result<Self, Self::Error> {
                match value {
                    PropertyValue::$variant(val) => Ok(val),
                    _ => Err(PropertyError::InvalidControlType {
                        expected: PropertyType::$variant,
                        received: value.get_type(),
                    }),
                }
            }
        }
    };
}

tryfrom_impl_propval!(bool, Bool);
tryfrom_impl_propval!(i64, Int);
tryfrom_impl_propval!(f64, Float);
tryfrom_impl_propval!(u64, Unsigned);
tryfrom_impl_propval!(Duration, Duration);
tryfrom_impl_propval!(String, EnumStr);
tryfrom_impl_propval!(GenCamPixelBpp, PixelFmt);

macro_rules! tryfrom_impl_propvalref {
    ($type:ty, $variant:ident) => {
        impl TryFrom<&PropertyValue> for $type {
            type Error = PropertyError;

            fn try_from(value: &PropertyValue) -> Result<Self, Self::Error> {
                match value {
                    PropertyValue::$variant(val) => Ok(val.clone()),
                    _ => Err(PropertyError::InvalidControlType {
                        expected: PropertyType::$variant,
                        received: value.get_type(),
                    }),
                }
            }
        }
    };
}

tryfrom_impl_propvalref!(bool, Bool);
tryfrom_impl_propvalref!(i64, Int);
tryfrom_impl_propvalref!(f64, Float);
tryfrom_impl_propvalref!(u64, Unsigned);
tryfrom_impl_propvalref!(Duration, Duration);
tryfrom_impl_propvalref!(String, EnumStr);
tryfrom_impl_propvalref!(GenCamPixelBpp, PixelFmt);

impl From<&PropertyValue> for PropertyType {
    fn from(prop: &PropertyValue) -> Self {
        use PropertyValue::*;
        match prop {
            Command => PropertyType::Command,
            Bool(_) => PropertyType::Bool,
            Int(_) => PropertyType::Int,
            Float(_) => PropertyType::Float,
            Unsigned(_) => PropertyType::Unsigned,
            PixelFmt(_) => PropertyType::PixelFmt,
            Duration(_) => PropertyType::Duration,
            EnumStr(_) => PropertyType::EnumStr,
        }
    }
}

impl PropertyValue {
    /// Get the value as a boolean
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            PropertyValue::Bool(val) => Some(*val),
            _ => None,
        }
    }
    /// Get the value as an integer
    pub fn as_i64(&self) -> Option<i64> {
        match self {
            PropertyValue::Int(val) => Some(*val),
            _ => None,
        }
    }
    /// Get the value as a floating point number
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            PropertyValue::Float(val) => Some(*val),
            _ => None,
        }
    }
    /// Get the value as an unsigned integer
    pub fn as_u64(&self) -> Option<u64> {
        match self {
            PropertyValue::Unsigned(val) => Some(*val),
            _ => None,
        }
    }
    /// Get the value as a duration
    pub fn as_duration(&self) -> Option<Duration> {
        match self {
            PropertyValue::Duration(val) => Some(*val),
            _ => None,
        }
    }
    /// Get the value as a pixel format
    pub fn as_pixel_fmt(&self) -> Option<GenCamPixelBpp> {
        match self {
            PropertyValue::PixelFmt(val) => Some(*val),
            _ => None,
        }
    }
    /// Get the value as an enum string
    pub fn as_enum_str(&self) -> Option<&str> {
        match self {
            PropertyValue::EnumStr(val) => Some(val),
            _ => None,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
/// The type of a property
pub enum PropertyType {
    /// A command property
    Command,
    /// A boolean property
    Bool,
    /// An integer property ([`i64`])
    Int,
    /// A floating point property ([`f64`])
    Float,
    /// An unsigned integer property ([`u64`])
    Unsigned,
    /// A pixel format property ([`GenCamPixelBpp`])
    PixelFmt,
    /// A duration property ([`Duration`])
    Duration,
    /// An enum string property ([`String`])
    EnumStr,
    /// An enum integer property ([`i64`])
    EnumInt,
    /// An enum unsigned integer property ([`u64`])
    EnumUnsigned,
}

impl From<&PropertyLims> for PropertyType {
    fn from(prop: &PropertyLims) -> Self {
        use PropertyLims::*;
        match prop {
            Bool { .. } => PropertyType::Bool,
            Int { .. } => PropertyType::Int,
            Float { .. } => PropertyType::Float,
            Unsigned { .. } => PropertyType::Unsigned,
            Duration { .. } => PropertyType::Duration,
            PixelFmt { .. } => PropertyType::PixelFmt,
            EnumStr { .. } => PropertyType::EnumStr,
            EnumInt { .. } => PropertyType::EnumInt,
            EnumUnsigned { .. } => PropertyType::EnumUnsigned,
        }
    }
}

#[derive(Error, Debug, Clone, PartialEq, Serialize, Deserialize)]
/// Property value error
pub enum PropertyError {
    /// Property not found.
    #[error("Property not found")]
    NotFound,
    /// Read only property.
    #[error("Property is read only")]
    ReadOnly,
    /// Property not an enum.
    #[error("Property is not an enum")]
    NotEnum,
    /// Property is not a number.
    #[error("Property is not a number")]
    NotNumber,
    #[error("Value out of range")]
    /// Value out of range.
    ValueOutOfRange {
        /// The minimum value.
        min: PropertyValue,
        /// The maximum value.
        max: PropertyValue,
        /// The supplied value.
        value: PropertyValue,
    },
    #[error("Value not supported")]
    /// Value not contained in the enum list.
    ValueNotSupported,
    /// Property is an enum, hence does not support min/max.
    #[error("Property is an enum")]
    IsEnum,
    /// Auto mode not supported.
    #[error("Auto mode not supported")]
    AutoNotSupported,
    #[error("Invalid control type: {expected:?} != {received:?}")]
    /// Invalid control type.
    InvalidControlType {
        /// The expected type.
        expected: PropertyType,
        /// The received type.
        received: PropertyType,
    },
    #[error("Empty enum list")]
    /// Empty enum list.
    EmptyEnumList,
}