bacnet-objects 0.11.0

BACnet object model: traits, database, and standard object types
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
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
//! Color (type 63) and Color Temperature (type 64) objects.
//!
//! Per ASHRAE 135-2020 Addendum bj, Clauses 12.55-12.56.
//!
//! Color objects represent CIE 1931 xy color coordinates.
//! Color Temperature objects represent correlated color temperature in Kelvin.
//! Both support fade transitions via Color_Command.

use bacnet_types::enums::{ObjectType, PropertyIdentifier};
use bacnet_types::error::Error;
use bacnet_types::primitives::{ObjectIdentifier, PropertyValue, StatusFlags};
use std::borrow::Cow;

use crate::common::{self, read_common_properties, read_property_list_property};
use crate::traits::BACnetObject;

// ---------------------------------------------------------------------------
// ColorObject (type 63) — CIE 1931 xy color
// ---------------------------------------------------------------------------

/// BACnet Color object (type 63).
///
/// Represents a color as CIE 1931 xy coordinates. Supports FADE_TO_COLOR
/// transitions via Color_Command. Non-commandable (no priority array).
pub struct ColorObject {
    oid: ObjectIdentifier,
    name: String,
    description: String,
    /// Present_Value: BACnetxyColor encoded as (x: REAL, y: REAL).
    /// Stored as two f32 values.
    present_value_x: f32,
    present_value_y: f32,
    /// Tracking_Value: current actual color (may differ during fade).
    tracking_value_x: f32,
    tracking_value_y: f32,
    /// Color_Command: last written command (opaque bytes for now).
    color_command: Vec<u8>,
    /// Default_Color: startup color (x, y).
    default_color_x: f32,
    default_color_y: f32,
    /// Default_Fade_Time: milliseconds (100-86400000). 0 = use device default.
    default_fade_time: u32,
    /// Transition: 0=NONE, 1=FADE.
    transition: u32,
    /// In_Progress: 0=idle, 1=fade-active.
    in_progress: u32,
    status_flags: StatusFlags,
    event_state: u32,
    out_of_service: bool,
    reliability: u32,
}

impl ColorObject {
    /// Create a new Color object with default white color (x=0.3127, y=0.3290 ≈ D65).
    pub fn new(instance: u32, name: impl Into<String>) -> Result<Self, Error> {
        let oid = ObjectIdentifier::new(ObjectType::COLOR, instance)?;
        Ok(Self {
            oid,
            name: name.into(),
            description: String::new(),
            present_value_x: 0.3127,
            present_value_y: 0.3290,
            tracking_value_x: 0.3127,
            tracking_value_y: 0.3290,
            color_command: Vec::new(),
            default_color_x: 0.3127,
            default_color_y: 0.3290,
            default_fade_time: 0,
            transition: 0,  // NONE
            in_progress: 0, // idle
            status_flags: StatusFlags::empty(),
            event_state: 0, // NORMAL
            out_of_service: false,
            reliability: 0,
        })
    }

    pub fn set_present_value(&mut self, x: f32, y: f32) {
        self.present_value_x = x;
        self.present_value_y = y;
        self.tracking_value_x = x;
        self.tracking_value_y = y;
    }
}

impl BACnetObject for ColorObject {
    fn object_identifier(&self) -> ObjectIdentifier {
        self.oid
    }

    fn object_name(&self) -> &str {
        &self.name
    }

    fn read_property(
        &self,
        property: PropertyIdentifier,
        array_index: Option<u32>,
    ) -> Result<PropertyValue, Error> {
        if let Some(result) = read_common_properties!(self, property, array_index) {
            return result;
        }
        match property {
            p if p == PropertyIdentifier::OBJECT_TYPE => {
                Ok(PropertyValue::Enumerated(ObjectType::COLOR.to_raw()))
            }
            p if p == PropertyIdentifier::PRESENT_VALUE => {
                // BACnetxyColor encoded as a list of two REALs
                Ok(PropertyValue::List(vec![
                    PropertyValue::Real(self.present_value_x),
                    PropertyValue::Real(self.present_value_y),
                ]))
            }
            p if p == PropertyIdentifier::TRACKING_VALUE => Ok(PropertyValue::List(vec![
                PropertyValue::Real(self.tracking_value_x),
                PropertyValue::Real(self.tracking_value_y),
            ])),
            p if p == PropertyIdentifier::COLOR_COMMAND => {
                Ok(PropertyValue::OctetString(self.color_command.clone()))
            }
            p if p == PropertyIdentifier::DEFAULT_COLOR => Ok(PropertyValue::List(vec![
                PropertyValue::Real(self.default_color_x),
                PropertyValue::Real(self.default_color_y),
            ])),
            p if p == PropertyIdentifier::DEFAULT_FADE_TIME => {
                Ok(PropertyValue::Unsigned(self.default_fade_time as u64))
            }
            p if p == PropertyIdentifier::TRANSITION => {
                Ok(PropertyValue::Enumerated(self.transition))
            }
            p if p == PropertyIdentifier::IN_PROGRESS => {
                Ok(PropertyValue::Enumerated(self.in_progress))
            }
            p if p == PropertyIdentifier::EVENT_STATE => {
                Ok(PropertyValue::Enumerated(self.event_state))
            }
            p if p == PropertyIdentifier::PROPERTY_LIST => {
                read_property_list_property(&self.property_list(), array_index)
            }
            _ => Err(common::unknown_property_error()),
        }
    }

    fn write_property(
        &mut self,
        property: PropertyIdentifier,
        _array_index: Option<u32>,
        value: PropertyValue,
        _priority: Option<u8>,
    ) -> Result<(), Error> {
        if let Some(result) =
            common::write_out_of_service(&mut self.out_of_service, property, &value)
        {
            return result;
        }
        if let Some(result) = common::write_description(&mut self.description, property, &value) {
            return result;
        }
        match property {
            p if p == PropertyIdentifier::COLOR_COMMAND => {
                if let PropertyValue::OctetString(data) = value {
                    self.color_command = data;
                    Ok(())
                } else {
                    Err(common::invalid_data_type_error())
                }
            }
            p if p == PropertyIdentifier::DEFAULT_FADE_TIME => {
                if let PropertyValue::Unsigned(v) = value {
                    if v > 86_400_000 {
                        return Err(common::value_out_of_range_error());
                    }
                    self.default_fade_time = v as u32;
                    Ok(())
                } else {
                    Err(common::invalid_data_type_error())
                }
            }
            _ => Err(common::write_access_denied_error()),
        }
    }

    fn property_list(&self) -> Cow<'static, [PropertyIdentifier]> {
        static PROPS: &[PropertyIdentifier] = &[
            PropertyIdentifier::OBJECT_IDENTIFIER,
            PropertyIdentifier::OBJECT_NAME,
            PropertyIdentifier::DESCRIPTION,
            PropertyIdentifier::OBJECT_TYPE,
            PropertyIdentifier::PRESENT_VALUE,
            PropertyIdentifier::TRACKING_VALUE,
            PropertyIdentifier::COLOR_COMMAND,
            PropertyIdentifier::IN_PROGRESS,
            PropertyIdentifier::DEFAULT_COLOR,
            PropertyIdentifier::DEFAULT_FADE_TIME,
            PropertyIdentifier::TRANSITION,
            PropertyIdentifier::STATUS_FLAGS,
            PropertyIdentifier::EVENT_STATE,
            PropertyIdentifier::OUT_OF_SERVICE,
            PropertyIdentifier::RELIABILITY,
        ];
        Cow::Borrowed(PROPS)
    }

    fn supports_cov(&self) -> bool {
        true
    }
}

// ---------------------------------------------------------------------------
// ColorTemperatureObject (type 64) — Correlated Color Temperature
// ---------------------------------------------------------------------------

/// BACnet Color Temperature object (type 64).
///
/// Represents correlated color temperature in Kelvin (typically 1000-30000).
/// Supports FADE, RAMP, and STEP transitions via Color_Command.
pub struct ColorTemperatureObject {
    oid: ObjectIdentifier,
    name: String,
    description: String,
    /// Present_Value: Unsigned (Kelvin).
    present_value: u32,
    /// Tracking_Value: current actual color temperature.
    tracking_value: u32,
    /// Color_Command: last written command.
    color_command: Vec<u8>,
    /// Default_Color_Temperature: startup value.
    default_color_temperature: u32,
    /// Default_Fade_Time: milliseconds.
    default_fade_time: u32,
    /// Default_Ramp_Rate: Kelvin per second.
    default_ramp_rate: u32,
    /// Default_Step_Increment: Kelvin per step.
    default_step_increment: u32,
    /// Transition: 0=NONE, 1=FADE, 2=RAMP.
    transition: u32,
    /// In_Progress: 0=idle, 1=fade-active, 2=ramp-active.
    in_progress: u32,
    /// Min/Max present value bounds.
    min_pres_value: Option<u32>,
    max_pres_value: Option<u32>,
    status_flags: StatusFlags,
    event_state: u32,
    out_of_service: bool,
    reliability: u32,
}

impl ColorTemperatureObject {
    /// Create a new Color Temperature object with default 4000K (neutral white).
    pub fn new(instance: u32, name: impl Into<String>) -> Result<Self, Error> {
        let oid = ObjectIdentifier::new(ObjectType::COLOR_TEMPERATURE, instance)?;
        Ok(Self {
            oid,
            name: name.into(),
            description: String::new(),
            present_value: 4000,
            tracking_value: 4000,
            color_command: Vec::new(),
            default_color_temperature: 4000,
            default_fade_time: 0,
            default_ramp_rate: 100,     // 100K/s
            default_step_increment: 50, // 50K per step
            transition: 0,              // NONE
            in_progress: 0,             // idle
            min_pres_value: Some(1000),
            max_pres_value: Some(30000),
            status_flags: StatusFlags::empty(),
            event_state: 0,
            out_of_service: false,
            reliability: 0,
        })
    }

    pub fn set_present_value(&mut self, kelvin: u32) {
        self.present_value = kelvin;
        self.tracking_value = kelvin;
    }

    pub fn set_min_max(&mut self, min: u32, max: u32) {
        self.min_pres_value = Some(min);
        self.max_pres_value = Some(max);
    }
}

impl BACnetObject for ColorTemperatureObject {
    fn object_identifier(&self) -> ObjectIdentifier {
        self.oid
    }

    fn object_name(&self) -> &str {
        &self.name
    }

    fn read_property(
        &self,
        property: PropertyIdentifier,
        array_index: Option<u32>,
    ) -> Result<PropertyValue, Error> {
        if let Some(result) = read_common_properties!(self, property, array_index) {
            return result;
        }
        match property {
            p if p == PropertyIdentifier::OBJECT_TYPE => Ok(PropertyValue::Enumerated(
                ObjectType::COLOR_TEMPERATURE.to_raw(),
            )),
            p if p == PropertyIdentifier::PRESENT_VALUE => {
                Ok(PropertyValue::Unsigned(self.present_value as u64))
            }
            p if p == PropertyIdentifier::TRACKING_VALUE => {
                Ok(PropertyValue::Unsigned(self.tracking_value as u64))
            }
            p if p == PropertyIdentifier::COLOR_COMMAND => {
                Ok(PropertyValue::OctetString(self.color_command.clone()))
            }
            p if p == PropertyIdentifier::DEFAULT_COLOR_TEMPERATURE => Ok(PropertyValue::Unsigned(
                self.default_color_temperature as u64,
            )),
            p if p == PropertyIdentifier::DEFAULT_FADE_TIME => {
                Ok(PropertyValue::Unsigned(self.default_fade_time as u64))
            }
            p if p == PropertyIdentifier::DEFAULT_RAMP_RATE => {
                Ok(PropertyValue::Unsigned(self.default_ramp_rate as u64))
            }
            p if p == PropertyIdentifier::DEFAULT_STEP_INCREMENT => {
                Ok(PropertyValue::Unsigned(self.default_step_increment as u64))
            }
            p if p == PropertyIdentifier::TRANSITION => {
                Ok(PropertyValue::Enumerated(self.transition))
            }
            p if p == PropertyIdentifier::IN_PROGRESS => {
                Ok(PropertyValue::Enumerated(self.in_progress))
            }
            p if p == PropertyIdentifier::MIN_PRES_VALUE => match self.min_pres_value {
                Some(v) => Ok(PropertyValue::Unsigned(v as u64)),
                None => Err(common::unknown_property_error()),
            },
            p if p == PropertyIdentifier::MAX_PRES_VALUE => match self.max_pres_value {
                Some(v) => Ok(PropertyValue::Unsigned(v as u64)),
                None => Err(common::unknown_property_error()),
            },
            p if p == PropertyIdentifier::EVENT_STATE => {
                Ok(PropertyValue::Enumerated(self.event_state))
            }
            p if p == PropertyIdentifier::PROPERTY_LIST => {
                read_property_list_property(&self.property_list(), array_index)
            }
            _ => Err(common::unknown_property_error()),
        }
    }

    fn write_property(
        &mut self,
        property: PropertyIdentifier,
        _array_index: Option<u32>,
        value: PropertyValue,
        _priority: Option<u8>,
    ) -> Result<(), Error> {
        if let Some(result) =
            common::write_out_of_service(&mut self.out_of_service, property, &value)
        {
            return result;
        }
        if let Some(result) = common::write_description(&mut self.description, property, &value) {
            return result;
        }
        match property {
            p if p == PropertyIdentifier::PRESENT_VALUE => {
                if let PropertyValue::Unsigned(v) = value {
                    let v32 = common::u64_to_u32(v)?;
                    // Clamp to min/max if supported
                    if let Some(min) = self.min_pres_value {
                        if v32 < min {
                            return Err(common::value_out_of_range_error());
                        }
                    }
                    if let Some(max) = self.max_pres_value {
                        if v32 > max {
                            return Err(common::value_out_of_range_error());
                        }
                    }
                    self.present_value = v32;
                    self.tracking_value = v32;
                    Ok(())
                } else {
                    Err(common::invalid_data_type_error())
                }
            }
            p if p == PropertyIdentifier::COLOR_COMMAND => {
                if let PropertyValue::OctetString(data) = value {
                    self.color_command = data;
                    Ok(())
                } else {
                    Err(common::invalid_data_type_error())
                }
            }
            _ => Err(common::write_access_denied_error()),
        }
    }

    fn property_list(&self) -> Cow<'static, [PropertyIdentifier]> {
        static PROPS: &[PropertyIdentifier] = &[
            PropertyIdentifier::OBJECT_IDENTIFIER,
            PropertyIdentifier::OBJECT_NAME,
            PropertyIdentifier::DESCRIPTION,
            PropertyIdentifier::OBJECT_TYPE,
            PropertyIdentifier::PRESENT_VALUE,
            PropertyIdentifier::TRACKING_VALUE,
            PropertyIdentifier::COLOR_COMMAND,
            PropertyIdentifier::IN_PROGRESS,
            PropertyIdentifier::DEFAULT_COLOR_TEMPERATURE,
            PropertyIdentifier::DEFAULT_FADE_TIME,
            PropertyIdentifier::DEFAULT_RAMP_RATE,
            PropertyIdentifier::DEFAULT_STEP_INCREMENT,
            PropertyIdentifier::TRANSITION,
            PropertyIdentifier::MIN_PRES_VALUE,
            PropertyIdentifier::MAX_PRES_VALUE,
            PropertyIdentifier::STATUS_FLAGS,
            PropertyIdentifier::EVENT_STATE,
            PropertyIdentifier::OUT_OF_SERVICE,
            PropertyIdentifier::RELIABILITY,
        ];
        Cow::Borrowed(PROPS)
    }

    fn supports_cov(&self) -> bool {
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bacnet_types::enums::{ErrorClass, ErrorCode};

    fn assert_property_error(error: Error, expected_code: ErrorCode) {
        match error {
            Error::Protocol { class, code } => {
                assert_eq!(class, ErrorClass::PROPERTY.to_raw() as u32);
                assert_eq!(code, expected_code.to_raw() as u32);
            }
            other => panic!("expected PROPERTY/{expected_code:?}, got {other:?}"),
        }
    }

    fn assert_present_and_tracking(object: &ColorTemperatureObject, expected: u64) {
        assert_eq!(
            object
                .read_property(PropertyIdentifier::PRESENT_VALUE, None)
                .unwrap(),
            PropertyValue::Unsigned(expected)
        );
        assert_eq!(
            object
                .read_property(PropertyIdentifier::TRACKING_VALUE, None)
                .unwrap(),
            PropertyValue::Unsigned(expected)
        );
    }

    #[test]
    fn color_temperature_rejects_overwide_present_value_without_mutation() {
        let mut object = ColorTemperatureObject::new(1, "CT-1").unwrap();

        let error = object
            .write_property(
                PropertyIdentifier::PRESENT_VALUE,
                None,
                PropertyValue::Unsigned(0x1_0000_03E8),
                None,
            )
            .expect_err("over-wide Present_Value must be rejected");

        assert_property_error(error, ErrorCode::VALUE_OUT_OF_RANGE);
        assert_present_and_tracking(&object, 4000);
    }

    #[test]
    fn color_temperature_preserves_present_value_boundaries() {
        let mut object = ColorTemperatureObject::new(1, "CT-1").unwrap();

        for value in [1000, 30000] {
            object
                .write_property(
                    PropertyIdentifier::PRESENT_VALUE,
                    None,
                    PropertyValue::Unsigned(value),
                    None,
                )
                .unwrap();
            assert_present_and_tracking(&object, value);
        }

        let error = object
            .write_property(
                PropertyIdentifier::PRESENT_VALUE,
                None,
                PropertyValue::Unsigned(u32::MAX as u64),
                None,
            )
            .expect_err("u32::MAX remains outside the configured range");
        assert_property_error(error, ErrorCode::VALUE_OUT_OF_RANGE);
        assert_present_and_tracking(&object, 30000);

        let error = object
            .write_property(
                PropertyIdentifier::PRESENT_VALUE,
                None,
                PropertyValue::Real(1000.0),
                None,
            )
            .expect_err("wrong datatype must be rejected");
        assert_property_error(error, ErrorCode::INVALID_DATA_TYPE);
        assert_present_and_tracking(&object, 30000);
    }
}