mabi-bacnet 1.5.0

Mabinogion - BACnet/IP simulator
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
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
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
//! BACnet Schedule and Calendar object implementations.
//!
//! Per ASHRAE 135, Clause 12.24 (Schedule) and 12.5 (Calendar).
//!
//! ## Schedule
//! Provides time-based value switching via:
//! - **Weekly_Schedule**: 7-day time/value list (Mon→Sun)
//! - **Exception_Schedule**: date/date-range overrides (higher priority)
//! - **Effective_Period**: date range bounding when the schedule is active
//! - **Schedule_Default**: fallback when no entry matches
//!
//! ## Calendar
//! Represents a named collection of date entries:
//! - Individual dates
//! - Date ranges (start..end)
//! - Weekday/month patterns (using BACnet wildcard encoding)
//! Present_Value is `true` when the current date matches any entry.

use std::sync::atomic::{AtomicBool, Ordering};

use parking_lot::RwLock;

use super::property::{
    BACnetDate, BACnetTime, BACnetValue, PropertyError, PropertyId, PropertyStore, StatusFlags,
};
use super::traits::BACnetObject;
use super::types::{ObjectId, ObjectType};

// ── Schedule Types ──────────────────────────────────────────────────────────

/// A single time-value entry in a daily schedule.
///
/// At the specified `time`, the schedule output transitions to `value`.
#[derive(Debug, Clone, PartialEq)]
pub struct TimeValue {
    /// Time of day (hour, minute, second, hundredths).
    pub time: BACnetTime,
    /// Value to output at this time.
    pub value: BACnetValue,
}

impl TimeValue {
    pub fn new(hour: u8, minute: u8, value: BACnetValue) -> Self {
        Self {
            time: BACnetTime {
                hour,
                minute,
                second: 0,
                hundredths: 0,
            },
            value,
        }
    }

    pub fn with_seconds(hour: u8, minute: u8, second: u8, value: BACnetValue) -> Self {
        Self {
            time: BACnetTime {
                hour,
                minute,
                second,
                hundredths: 0,
            },
            value,
        }
    }
}

/// A daily schedule — ordered list of time/value transitions for a single day.
pub type DailySchedule = Vec<TimeValue>;

/// Date range for Effective_Period or exception schedule entries.
#[derive(Debug, Clone, PartialEq)]
pub struct DateRange {
    pub start: BACnetDate,
    pub end: BACnetDate,
}

impl DateRange {
    pub fn new(start: BACnetDate, end: BACnetDate) -> Self {
        Self { start, end }
    }

    /// Check if the given date falls within this range.
    pub fn contains(&self, date: &BACnetDate) -> bool {
        let d = date_to_ordinal(date);
        let s = date_to_ordinal(&self.start);
        let e = date_to_ordinal(&self.end);
        d >= s && d <= e
    }
}

/// Entry type for Calendar date lists and exception schedules.
#[derive(Debug, Clone, PartialEq)]
pub enum CalendarEntry {
    /// A specific date.
    Date(BACnetDate),
    /// A date range (inclusive).
    DateRange(DateRange),
    /// A BACnet date pattern with wildcards (month=255 means "any month", etc.).
    WeekNDay {
        /// Month (1-14, 255 = any).
        month: u8,
        /// Week of month (1-5, 6=last, 255 = any).
        week_of_month: u8,
        /// Day of week (1=Mon..7=Sun, 255 = any).
        day_of_week: u8,
    },
}

impl CalendarEntry {
    /// Check if the given date matches this entry.
    pub fn matches(&self, date: &BACnetDate) -> bool {
        match self {
            CalendarEntry::Date(d) => date_matches_pattern(date, d),
            CalendarEntry::DateRange(range) => range.contains(date),
            CalendarEntry::WeekNDay {
                month,
                week_of_month,
                day_of_week,
            } => {
                // Month check
                if *month != 255 && *month != date.month {
                    // Also handle odd/even months
                    if *month == 13 && date.month % 2 == 0 {
                        return false;
                    }
                    if *month == 14 && date.month % 2 != 0 {
                        return false;
                    }
                    if *month <= 12 && *month != date.month {
                        return false;
                    }
                }

                // Day of week check
                if *day_of_week != 255 && *day_of_week != date.day_of_week {
                    return false;
                }

                // Week of month check
                if *week_of_month != 255 {
                    let week = ((date.day - 1) / 7) + 1;
                    if *week_of_month == 6 {
                        // Last week of the month — approximate: day > 21
                        if date.day <= 21 {
                            return false;
                        }
                    } else if *week_of_month != week {
                        return false;
                    }
                }

                true
            }
        }
    }
}

/// Exception schedule entry — a date/date-range/calendar-reference with an
/// associated daily schedule that overrides the weekly schedule.
#[derive(Debug, Clone)]
pub struct SpecialEvent {
    /// When this exception applies.
    pub period: SpecialEventPeriod,
    /// Time-value transitions for this exception day.
    pub schedule: DailySchedule,
    /// Priority (1-16, lower = higher priority).
    pub priority: u8,
}

/// The period specifier for a SpecialEvent.
#[derive(Debug, Clone, PartialEq)]
pub enum SpecialEventPeriod {
    /// A single calendar entry (date, range, or pattern).
    CalendarEntry(CalendarEntry),
    /// Reference to a Calendar object by object identifier.
    CalendarReference(ObjectId),
}

// ── Helper functions ────────────────────────────────────────────────────────

/// Convert a BACnetDate to an ordinal day number for comparison.
/// Returns a u32 encoding as YYYYMMDD (actual year = year_field + 1900).
fn date_to_ordinal(d: &BACnetDate) -> u32 {
    let year = d.year as u32 + 1900;
    let month = d.month as u32;
    let day = d.day as u32;
    year * 10000 + month * 100 + day
}

/// Check if a concrete date matches a pattern date (supports BACnet wildcards).
fn date_matches_pattern(concrete: &BACnetDate, pattern: &BACnetDate) -> bool {
    // Year
    if pattern.year != 255 && pattern.year != concrete.year {
        return false;
    }
    // Month
    if pattern.month != 255 {
        match pattern.month {
            13 => {
                if concrete.month % 2 == 0 {
                    return false;
                }
            }
            14 => {
                if concrete.month % 2 != 0 {
                    return false;
                }
            }
            m => {
                if m != concrete.month {
                    return false;
                }
            }
        }
    }
    // Day
    if pattern.day != 255 {
        match pattern.day {
            33 => {
                if concrete.day % 2 == 0 {
                    return false;
                }
            }
            34 => {
                if concrete.day % 2 != 0 {
                    return false;
                }
            }
            // 32 = last day of month — trust that concrete.day is correct
            32 => {}
            d => {
                if d != concrete.day {
                    return false;
                }
            }
        }
    }
    // Day of week
    if pattern.day_of_week != 255 && pattern.day_of_week != concrete.day_of_week {
        return false;
    }
    true
}

/// Evaluate a daily schedule for a given time.
///
/// Returns the value from the last entry whose time is <= the given time.
/// If no entry matches (time is before the first entry), returns None.
fn evaluate_daily_schedule(schedule: &[TimeValue], now: &BACnetTime) -> Option<BACnetValue> {
    let now_secs = time_to_seconds(now);
    let mut result = None;

    for entry in schedule {
        let entry_secs = time_to_seconds(&entry.time);
        if entry_secs <= now_secs {
            result = Some(entry.value.clone());
        } else {
            break;
        }
    }

    result
}

/// Convert BACnetTime to seconds since midnight.
fn time_to_seconds(t: &BACnetTime) -> u32 {
    (t.hour as u32) * 3600 + (t.minute as u32) * 60 + (t.second as u32)
}

/// Get the day-of-week index (0=Monday..6=Sunday) for BACnet weekly schedule.
/// BACnet day_of_week: 1=Monday..7=Sunday.
fn bacnet_day_of_week_to_index(day_of_week: u8) -> Option<usize> {
    if day_of_week >= 1 && day_of_week <= 7 {
        Some((day_of_week - 1) as usize)
    } else {
        None
    }
}

// ── Schedule Object ─────────────────────────────────────────────────────────

/// BACnet Schedule object per ASHRAE 135, Clause 12.24.
///
/// Computes a present value based on weekly and exception schedules:
/// 1. Check exception schedule entries (highest priority matching entry wins)
/// 2. If no exception matches, use the weekly schedule for today's day-of-week
/// 3. If neither produces a value, use the schedule default
///
/// Effective_Period bounds when the schedule is active.
pub struct Schedule {
    id: ObjectId,
    name: String,
    description: String,
    properties: PropertyStore,
    /// Weekly schedule — 7 daily schedules indexed [0]=Monday..[6]=Sunday.
    weekly_schedule: RwLock<[DailySchedule; 7]>,
    /// Exception schedule entries (sorted by priority, lowest number = highest priority).
    exception_schedule: RwLock<Vec<SpecialEvent>>,
    /// Effective period (date range when schedule is active).
    effective_period: RwLock<Option<DateRange>>,
    /// Schedule default value (fallback when no entry matches).
    schedule_default: RwLock<BACnetValue>,
    /// List of object property references that this schedule writes to.
    list_of_object_property_references: RwLock<Vec<ObjectPropertyReference>>,
    /// Priority for writing (1-16).
    priority_for_writing: RwLock<u8>,
    /// Out of service flag.
    out_of_service: AtomicBool,
    /// Reliability.
    reliability: RwLock<u32>,
    /// Present value (cached, updated by evaluate()).
    present_value: RwLock<BACnetValue>,
}

/// Object property reference for schedule output targets.
#[derive(Debug, Clone, PartialEq)]
pub struct ObjectPropertyReference {
    pub object_id: ObjectId,
    pub property_id: PropertyId,
    pub array_index: Option<u32>,
}

impl Schedule {
    /// Create a new Schedule object.
    pub fn new(instance: u32, name: impl Into<String>) -> Self {
        Self {
            id: ObjectId::new(ObjectType::Schedule, instance),
            name: name.into(),
            description: String::new(),
            properties: PropertyStore::new(),
            weekly_schedule: RwLock::new(Default::default()),
            exception_schedule: RwLock::new(Vec::new()),
            effective_period: RwLock::new(None),
            schedule_default: RwLock::new(BACnetValue::Null),
            list_of_object_property_references: RwLock::new(Vec::new()),
            priority_for_writing: RwLock::new(16),
            out_of_service: AtomicBool::new(false),
            reliability: RwLock::new(0),
            present_value: RwLock::new(BACnetValue::Null),
        }
    }

    /// Builder: set description.
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = desc.into();
        self
    }

    /// Builder: set schedule default.
    pub fn with_schedule_default(self, value: BACnetValue) -> Self {
        *self.schedule_default.write() = value;
        self
    }

    /// Builder: set effective period.
    pub fn with_effective_period(self, range: DateRange) -> Self {
        *self.effective_period.write() = Some(range);
        self
    }

    /// Builder: set priority for writing.
    pub fn with_priority(self, priority: u8) -> Self {
        *self.priority_for_writing.write() = priority.min(16).max(1);
        self
    }

    // ── Public API ──

    /// Set the daily schedule for a specific day (0=Monday..6=Sunday).
    pub fn set_daily_schedule(&self, day_index: usize, schedule: DailySchedule) {
        if day_index < 7 {
            self.weekly_schedule.write()[day_index] = schedule;
        }
    }

    /// Get the daily schedule for a specific day.
    pub fn get_daily_schedule(&self, day_index: usize) -> Option<DailySchedule> {
        if day_index < 7 {
            Some(self.weekly_schedule.read()[day_index].clone())
        } else {
            None
        }
    }

    /// Add an exception schedule entry.
    pub fn add_exception(&self, event: SpecialEvent) {
        let mut exceptions = self.exception_schedule.write();
        exceptions.push(event);
        // Keep sorted by priority (ascending = highest priority first)
        exceptions.sort_by_key(|e| e.priority);
    }

    /// Clear all exception schedule entries.
    pub fn clear_exceptions(&self) {
        self.exception_schedule.write().clear();
    }

    /// Get exception count.
    pub fn exception_count(&self) -> usize {
        self.exception_schedule.read().len()
    }

    /// Set the schedule default value.
    pub fn set_schedule_default(&self, value: BACnetValue) {
        *self.schedule_default.write() = value;
    }

    /// Get the schedule default value.
    pub fn schedule_default(&self) -> BACnetValue {
        self.schedule_default.read().clone()
    }

    /// Set the effective period.
    pub fn set_effective_period(&self, range: Option<DateRange>) {
        *self.effective_period.write() = range;
    }

    /// Add an object property reference.
    pub fn add_output_reference(&self, reference: ObjectPropertyReference) {
        self.list_of_object_property_references
            .write()
            .push(reference);
    }

    /// Get the list of output references.
    pub fn output_references(&self) -> Vec<ObjectPropertyReference> {
        self.list_of_object_property_references.read().clone()
    }

    /// Evaluate the schedule for the given date/time and update the present value.
    ///
    /// This is the core scheduling algorithm:
    /// 1. Check if within the effective period (if set)
    /// 2. Check exception schedule entries (priority order, first match wins)
    /// 3. Fall back to the weekly schedule for the given day of week
    /// 4. If no entry applies, use the schedule default
    pub fn evaluate(&self, date: &BACnetDate, time: &BACnetTime) -> BACnetValue {
        // Check effective period
        if let Some(ref period) = *self.effective_period.read() {
            if !period.contains(date) {
                let default = self.schedule_default.read().clone();
                *self.present_value.write() = default.clone();
                return default;
            }
        }

        // Check exception schedule (priority-sorted, first match wins)
        let exceptions = self.exception_schedule.read();
        for event in exceptions.iter() {
            let matches = match &event.period {
                SpecialEventPeriod::CalendarEntry(entry) => entry.matches(date),
                SpecialEventPeriod::CalendarReference(_) => {
                    // Calendar references would need external resolution;
                    // for the simulator, we skip these (or they can be pre-resolved)
                    false
                }
            };

            if matches {
                if let Some(value) = evaluate_daily_schedule(&event.schedule, time) {
                    *self.present_value.write() = value.clone();
                    return value;
                }
            }
        }
        drop(exceptions);

        // Weekly schedule
        if let Some(day_idx) = bacnet_day_of_week_to_index(date.day_of_week) {
            let weekly = self.weekly_schedule.read();
            if let Some(value) = evaluate_daily_schedule(&weekly[day_idx], time) {
                *self.present_value.write() = value.clone();
                return value;
            }
        }

        // Fallback to schedule default
        let default = self.schedule_default.read().clone();
        *self.present_value.write() = default.clone();
        default
    }

    /// Get the current present value (last evaluated).
    pub fn get_present_value(&self) -> BACnetValue {
        self.present_value.read().clone()
    }

    /// Manually set the present value (e.g., for testing or out-of-service mode).
    pub fn set_present_value(&self, value: BACnetValue) {
        *self.present_value.write() = value;
    }
}

impl BACnetObject for Schedule {
    fn object_identifier(&self) -> ObjectId {
        self.id
    }

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

    fn description(&self) -> Option<&str> {
        if self.description.is_empty() {
            None
        } else {
            Some(&self.description)
        }
    }

    fn read_property(&self, property_id: PropertyId) -> Result<BACnetValue, PropertyError> {
        match property_id {
            PropertyId::ObjectIdentifier => Ok(BACnetValue::ObjectIdentifier(self.id)),
            PropertyId::ObjectName => Ok(BACnetValue::CharacterString(self.name.clone())),
            PropertyId::ObjectType => Ok(BACnetValue::Enumerated(ObjectType::Schedule as u32)),
            PropertyId::Description => Ok(BACnetValue::CharacterString(self.description.clone())),
            PropertyId::PresentValue => Ok(self.present_value.read().clone()),
            PropertyId::StatusFlags => {
                let flags = self.status_flags();
                Ok(BACnetValue::BitString(vec![
                    flags.in_alarm,
                    flags.fault,
                    flags.overridden,
                    flags.out_of_service,
                ]))
            }
            PropertyId::EventState => Ok(BACnetValue::Enumerated(0)), // normal
            PropertyId::Reliability => Ok(BACnetValue::Enumerated(*self.reliability.read())),
            PropertyId::OutOfService => Ok(BACnetValue::Boolean(
                self.out_of_service.load(Ordering::Acquire),
            )),
            PropertyId::ScheduleDefault => Ok(self.schedule_default.read().clone()),
            PropertyId::PriorityForWriting => Ok(BACnetValue::Unsigned(
                *self.priority_for_writing.read() as u32,
            )),
            PropertyId::EffectivePeriod => match &*self.effective_period.read() {
                Some(range) => Ok(BACnetValue::Array(vec![
                    BACnetValue::Date(range.start.clone()),
                    BACnetValue::Date(range.end.clone()),
                ])),
                None => Ok(BACnetValue::Null),
            },
            PropertyId::WeeklySchedule => {
                let weekly = self.weekly_schedule.read();
                let days: Vec<BACnetValue> = weekly
                    .iter()
                    .map(|day| {
                        let entries: Vec<BACnetValue> = day
                            .iter()
                            .map(|tv| {
                                BACnetValue::Array(vec![
                                    BACnetValue::Time(tv.time.clone()),
                                    tv.value.clone(),
                                ])
                            })
                            .collect();
                        BACnetValue::List(entries)
                    })
                    .collect();
                Ok(BACnetValue::Array(days))
            }
            PropertyId::ExceptionSchedule => {
                let exceptions = self.exception_schedule.read();
                let entries: Vec<BACnetValue> = exceptions
                    .iter()
                    .map(|_e| BACnetValue::Unsigned(1)) // Simplified encoding
                    .collect();
                Ok(BACnetValue::Array(entries))
            }
            PropertyId::ListOfObjectPropertyReferences => {
                let refs = self.list_of_object_property_references.read();
                let entries: Vec<BACnetValue> = refs
                    .iter()
                    .map(|r| BACnetValue::ObjectIdentifier(r.object_id))
                    .collect();
                Ok(BACnetValue::Array(entries))
            }
            _ => self
                .properties
                .get(property_id)
                .ok_or(PropertyError::NotFound(property_id)),
        }
    }

    fn write_property(
        &self,
        property_id: PropertyId,
        value: BACnetValue,
    ) -> Result<(), PropertyError> {
        match property_id {
            PropertyId::ObjectIdentifier | PropertyId::ObjectType => {
                Err(PropertyError::ReadOnly(property_id))
            }
            PropertyId::ObjectName => {
                // Name is read-only at the BACnet level for Schedule
                Err(PropertyError::ReadOnly(property_id))
            }
            PropertyId::Description => {
                // Description is typically writable
                if let BACnetValue::CharacterString(_) = &value {
                    self.properties.set(property_id, value);
                    Ok(())
                } else {
                    Err(PropertyError::InvalidDataType(property_id))
                }
            }
            PropertyId::PresentValue => {
                *self.present_value.write() = value;
                Ok(())
            }
            PropertyId::OutOfService => {
                if let BACnetValue::Boolean(v) = value {
                    self.out_of_service.store(v, Ordering::Release);
                    Ok(())
                } else {
                    Err(PropertyError::InvalidDataType(property_id))
                }
            }
            PropertyId::ScheduleDefault => {
                *self.schedule_default.write() = value;
                Ok(())
            }
            PropertyId::PriorityForWriting => {
                if let BACnetValue::Unsigned(v) = value {
                    let p = (v as u8).min(16).max(1);
                    *self.priority_for_writing.write() = p;
                    Ok(())
                } else {
                    Err(PropertyError::InvalidDataType(property_id))
                }
            }
            PropertyId::Reliability => {
                if let BACnetValue::Enumerated(v) = value {
                    *self.reliability.write() = v;
                    Ok(())
                } else {
                    Err(PropertyError::InvalidDataType(property_id))
                }
            }
            _ => {
                self.properties.set(property_id, value);
                Ok(())
            }
        }
    }

    fn list_properties(&self) -> Vec<PropertyId> {
        vec![
            PropertyId::ObjectIdentifier,
            PropertyId::ObjectName,
            PropertyId::ObjectType,
            PropertyId::Description,
            PropertyId::PresentValue,
            PropertyId::StatusFlags,
            PropertyId::EventState,
            PropertyId::Reliability,
            PropertyId::OutOfService,
            PropertyId::EffectivePeriod,
            PropertyId::WeeklySchedule,
            PropertyId::ExceptionSchedule,
            PropertyId::ScheduleDefault,
            PropertyId::ListOfObjectPropertyReferences,
            PropertyId::PriorityForWriting,
        ]
    }

    fn has_property(&self, property_id: PropertyId) -> bool {
        self.list_properties().contains(&property_id) || self.properties.get(property_id).is_some()
    }

    fn status_flags(&self) -> StatusFlags {
        StatusFlags {
            in_alarm: false,
            fault: *self.reliability.read() != 0,
            overridden: false,
            out_of_service: self.out_of_service.load(Ordering::Acquire),
        }
    }

    fn is_out_of_service(&self) -> bool {
        self.out_of_service.load(Ordering::Acquire)
    }

    fn present_value(&self) -> Result<BACnetValue, PropertyError> {
        Ok(self.present_value.read().clone())
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

// ── Calendar Object ─────────────────────────────────────────────────────────

/// BACnet Calendar object per ASHRAE 135, Clause 12.5.
///
/// A Calendar maintains a list of date entries (dates, ranges, patterns).
/// Its Present_Value is `true` when the current date matches any entry,
/// `false` otherwise. This enables Schedule objects to reference Calendar
/// objects for complex recurring date patterns.
pub struct Calendar {
    id: ObjectId,
    name: String,
    description: String,
    properties: PropertyStore,
    /// The date list — entries that define when the calendar is "active".
    date_list: RwLock<Vec<CalendarEntry>>,
    /// Cached present value (true = today matches an entry).
    present_value: RwLock<bool>,
}

impl Calendar {
    /// Create a new Calendar object.
    pub fn new(instance: u32, name: impl Into<String>) -> Self {
        Self {
            id: ObjectId::new(ObjectType::Calendar, instance),
            name: name.into(),
            description: String::new(),
            properties: PropertyStore::new(),
            date_list: RwLock::new(Vec::new()),
            present_value: RwLock::new(false),
        }
    }

    /// Builder: set description.
    pub fn with_description(mut self, desc: impl Into<String>) -> Self {
        self.description = desc.into();
        self
    }

    /// Builder: add a calendar entry.
    pub fn with_entry(self, entry: CalendarEntry) -> Self {
        self.date_list.write().push(entry);
        self
    }

    // ── Public API ──

    /// Add a date entry to the calendar.
    pub fn add_entry(&self, entry: CalendarEntry) {
        self.date_list.write().push(entry);
    }

    /// Remove all entries.
    pub fn clear_entries(&self) {
        self.date_list.write().clear();
    }

    /// Get entry count.
    pub fn entry_count(&self) -> usize {
        self.date_list.read().len()
    }

    /// Get all entries.
    pub fn entries(&self) -> Vec<CalendarEntry> {
        self.date_list.read().clone()
    }

    /// Evaluate the calendar for the given date and update the present value.
    pub fn evaluate(&self, date: &BACnetDate) -> bool {
        let entries = self.date_list.read();
        let active = entries.iter().any(|entry| entry.matches(date));
        *self.present_value.write() = active;
        active
    }

    /// Get the current present value (last evaluated).
    pub fn get_present_value(&self) -> bool {
        *self.present_value.read()
    }

    /// Manually set the present value.
    pub fn set_present_value(&self, value: bool) {
        *self.present_value.write() = value;
    }
}

impl BACnetObject for Calendar {
    fn object_identifier(&self) -> ObjectId {
        self.id
    }

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

    fn description(&self) -> Option<&str> {
        if self.description.is_empty() {
            None
        } else {
            Some(&self.description)
        }
    }

    fn read_property(&self, property_id: PropertyId) -> Result<BACnetValue, PropertyError> {
        match property_id {
            PropertyId::ObjectIdentifier => Ok(BACnetValue::ObjectIdentifier(self.id)),
            PropertyId::ObjectName => Ok(BACnetValue::CharacterString(self.name.clone())),
            PropertyId::ObjectType => Ok(BACnetValue::Enumerated(ObjectType::Calendar as u32)),
            PropertyId::Description => Ok(BACnetValue::CharacterString(self.description.clone())),
            PropertyId::PresentValue => Ok(BACnetValue::Boolean(*self.present_value.read())),
            PropertyId::StatusFlags => Ok(BACnetValue::BitString(vec![false, false, false, false])),
            PropertyId::DateList => {
                let entries = self.date_list.read();
                let encoded: Vec<BACnetValue> = entries
                    .iter()
                    .map(|entry| match entry {
                        CalendarEntry::Date(d) => BACnetValue::Date(d.clone()),
                        CalendarEntry::DateRange(range) => BACnetValue::Array(vec![
                            BACnetValue::Date(range.start.clone()),
                            BACnetValue::Date(range.end.clone()),
                        ]),
                        CalendarEntry::WeekNDay {
                            month,
                            week_of_month,
                            day_of_week,
                        } => BACnetValue::OctetString(vec![*month, *week_of_month, *day_of_week]),
                    })
                    .collect();
                Ok(BACnetValue::List(encoded))
            }
            _ => self
                .properties
                .get(property_id)
                .ok_or(PropertyError::NotFound(property_id)),
        }
    }

    fn write_property(
        &self,
        property_id: PropertyId,
        value: BACnetValue,
    ) -> Result<(), PropertyError> {
        match property_id {
            PropertyId::ObjectIdentifier | PropertyId::ObjectType => {
                Err(PropertyError::ReadOnly(property_id))
            }
            PropertyId::ObjectName => Err(PropertyError::ReadOnly(property_id)),
            PropertyId::Description => {
                if let BACnetValue::CharacterString(_) = &value {
                    self.properties.set(property_id, value);
                    Ok(())
                } else {
                    Err(PropertyError::InvalidDataType(property_id))
                }
            }
            PropertyId::PresentValue => {
                if let BACnetValue::Boolean(v) = value {
                    *self.present_value.write() = v;
                    Ok(())
                } else {
                    Err(PropertyError::InvalidDataType(property_id))
                }
            }
            _ => {
                self.properties.set(property_id, value);
                Ok(())
            }
        }
    }

    fn list_properties(&self) -> Vec<PropertyId> {
        vec![
            PropertyId::ObjectIdentifier,
            PropertyId::ObjectName,
            PropertyId::ObjectType,
            PropertyId::Description,
            PropertyId::PresentValue,
            PropertyId::StatusFlags,
            PropertyId::DateList,
        ]
    }

    fn has_property(&self, property_id: PropertyId) -> bool {
        self.list_properties().contains(&property_id) || self.properties.get(property_id).is_some()
    }

    fn status_flags(&self) -> StatusFlags {
        StatusFlags {
            in_alarm: false,
            fault: false,
            overridden: false,
            out_of_service: false,
        }
    }

    fn is_out_of_service(&self) -> bool {
        false
    }

    fn present_value(&self) -> Result<BACnetValue, PropertyError> {
        Ok(BACnetValue::Boolean(*self.present_value.read()))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

// ── Tests ───────────────────────────────────────────────────────────────────

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

    fn make_date(year: u16, month: u8, day: u8, dow: u8) -> BACnetDate {
        BACnetDate {
            year: (year - 1900) as u8,
            month,
            day,
            day_of_week: dow,
        }
    }

    fn make_time(hour: u8, minute: u8) -> BACnetTime {
        BACnetTime {
            hour,
            minute,
            second: 0,
            hundredths: 0,
        }
    }

    // ── Calendar Entry Matching ──

    #[test]
    fn test_calendar_entry_date_match() {
        let entry = CalendarEntry::Date(make_date(2025, 12, 25, 4)); // Thursday
        let date = make_date(2025, 12, 25, 4);
        assert!(entry.matches(&date));

        let other = make_date(2025, 12, 26, 5);
        assert!(!entry.matches(&other));
    }

    #[test]
    fn test_calendar_entry_date_range() {
        let entry = CalendarEntry::DateRange(DateRange::new(
            make_date(2025, 1, 1, 3),
            make_date(2025, 1, 31, 5),
        ));

        assert!(entry.matches(&make_date(2025, 1, 15, 3)));
        assert!(entry.matches(&make_date(2025, 1, 1, 3)));
        assert!(entry.matches(&make_date(2025, 1, 31, 5)));
        assert!(!entry.matches(&make_date(2025, 2, 1, 6)));
        assert!(!entry.matches(&make_date(2024, 12, 31, 2)));
    }

    #[test]
    fn test_calendar_entry_weeknday() {
        // Every Monday in any month
        let entry = CalendarEntry::WeekNDay {
            month: 255,
            week_of_month: 255,
            day_of_week: 1, // Monday
        };

        let monday = make_date(2025, 3, 10, 1);
        let tuesday = make_date(2025, 3, 11, 2);
        assert!(entry.matches(&monday));
        assert!(!entry.matches(&tuesday));
    }

    #[test]
    fn test_calendar_entry_weeknday_specific_month() {
        // Every Friday in December
        let entry = CalendarEntry::WeekNDay {
            month: 12,
            week_of_month: 255,
            day_of_week: 5, // Friday
        };

        let dec_friday = make_date(2025, 12, 5, 5);
        let jan_friday = make_date(2025, 1, 3, 5);
        assert!(entry.matches(&dec_friday));
        assert!(!entry.matches(&jan_friday));
    }

    #[test]
    fn test_date_pattern_wildcard_year() {
        let pattern = BACnetDate {
            year: 255,
            month: 12,
            day: 25,
            day_of_week: 255,
        };
        // Christmas any year
        assert!(date_matches_pattern(&make_date(2025, 12, 25, 4), &pattern));
        assert!(date_matches_pattern(&make_date(2030, 12, 25, 3), &pattern));
        assert!(!date_matches_pattern(&make_date(2025, 12, 26, 5), &pattern));
    }

    // ── Daily Schedule Evaluation ──

    #[test]
    fn test_evaluate_daily_schedule() {
        let schedule = vec![
            TimeValue::new(8, 0, BACnetValue::Real(72.0)),
            TimeValue::new(12, 0, BACnetValue::Real(70.0)),
            TimeValue::new(18, 0, BACnetValue::Real(65.0)),
        ];

        // Before first entry
        assert_eq!(evaluate_daily_schedule(&schedule, &make_time(7, 30)), None);

        // At first entry
        assert_eq!(
            evaluate_daily_schedule(&schedule, &make_time(8, 0)),
            Some(BACnetValue::Real(72.0))
        );

        // Between entries
        assert_eq!(
            evaluate_daily_schedule(&schedule, &make_time(10, 0)),
            Some(BACnetValue::Real(72.0))
        );

        // At second entry
        assert_eq!(
            evaluate_daily_schedule(&schedule, &make_time(12, 0)),
            Some(BACnetValue::Real(70.0))
        );

        // After last entry
        assert_eq!(
            evaluate_daily_schedule(&schedule, &make_time(23, 0)),
            Some(BACnetValue::Real(65.0))
        );
    }

    #[test]
    fn test_evaluate_empty_schedule() {
        let schedule: Vec<TimeValue> = vec![];
        assert_eq!(evaluate_daily_schedule(&schedule, &make_time(12, 0)), None);
    }

    // ── Schedule Object ──

    #[test]
    fn test_schedule_creation() {
        let schedule = Schedule::new(1, "Test Schedule");
        assert_eq!(
            schedule.object_identifier(),
            ObjectId::new(ObjectType::Schedule, 1)
        );
        assert_eq!(schedule.object_name(), "Test Schedule");
        assert_eq!(schedule.get_present_value(), BACnetValue::Null);
    }

    #[test]
    fn test_schedule_weekly_evaluation() {
        let schedule =
            Schedule::new(1, "HVAC Schedule").with_schedule_default(BACnetValue::Real(60.0));

        // Set Monday schedule
        schedule.set_daily_schedule(
            0,
            vec![
                TimeValue::new(8, 0, BACnetValue::Real(72.0)),
                TimeValue::new(18, 0, BACnetValue::Real(65.0)),
            ],
        );

        // Evaluate Monday 10:00 → should be 72.0
        let monday = make_date(2025, 3, 10, 1); // Monday
        let result = schedule.evaluate(&monday, &make_time(10, 0));
        assert_eq!(result, BACnetValue::Real(72.0));

        // Evaluate Monday 20:00 → should be 65.0
        let result = schedule.evaluate(&monday, &make_time(20, 0));
        assert_eq!(result, BACnetValue::Real(65.0));

        // Evaluate Tuesday (no schedule set) → should be schedule default
        let tuesday = make_date(2025, 3, 11, 2);
        let result = schedule.evaluate(&tuesday, &make_time(10, 0));
        assert_eq!(result, BACnetValue::Real(60.0));
    }

    #[test]
    fn test_schedule_exception_overrides_weekly() {
        let schedule =
            Schedule::new(1, "Holiday Schedule").with_schedule_default(BACnetValue::Real(60.0));

        // Normal Monday
        schedule.set_daily_schedule(0, vec![TimeValue::new(8, 0, BACnetValue::Real(72.0))]);

        // Exception for holiday: run at 55.0 all day
        schedule.add_exception(SpecialEvent {
            period: SpecialEventPeriod::CalendarEntry(CalendarEntry::Date(make_date(
                2025, 12, 25, 4,
            ))),
            schedule: vec![TimeValue::new(0, 0, BACnetValue::Real(55.0))],
            priority: 1,
        });

        // Holiday → exception wins
        let christmas = make_date(2025, 12, 25, 4);
        let result = schedule.evaluate(&christmas, &make_time(10, 0));
        assert_eq!(result, BACnetValue::Real(55.0));

        // Normal Monday → weekly schedule
        let monday = make_date(2025, 3, 10, 1);
        let result = schedule.evaluate(&monday, &make_time(10, 0));
        assert_eq!(result, BACnetValue::Real(72.0));
    }

    #[test]
    fn test_schedule_effective_period() {
        let schedule = Schedule::new(1, "Seasonal Schedule")
            .with_schedule_default(BACnetValue::Real(60.0))
            .with_effective_period(DateRange::new(
                make_date(2025, 6, 1, 255),
                make_date(2025, 8, 31, 255),
            ));

        // Set Monday schedule
        schedule.set_daily_schedule(0, vec![TimeValue::new(8, 0, BACnetValue::Real(72.0))]);

        // Within effective period → normal evaluation
        let july_monday = make_date(2025, 7, 7, 1);
        let result = schedule.evaluate(&july_monday, &make_time(10, 0));
        assert_eq!(result, BACnetValue::Real(72.0));

        // Outside effective period → schedule default
        let jan_monday = make_date(2025, 1, 6, 1);
        let result = schedule.evaluate(&jan_monday, &make_time(10, 0));
        assert_eq!(result, BACnetValue::Real(60.0));
    }

    #[test]
    fn test_schedule_exception_priority() {
        let schedule =
            Schedule::new(1, "Priority Test").with_schedule_default(BACnetValue::Real(60.0));

        // Low priority exception (runs at 65.0)
        schedule.add_exception(SpecialEvent {
            period: SpecialEventPeriod::CalendarEntry(CalendarEntry::Date(make_date(
                2025, 12, 25, 4,
            ))),
            schedule: vec![TimeValue::new(0, 0, BACnetValue::Real(65.0))],
            priority: 10,
        });

        // High priority exception (runs at 55.0) — this should win
        schedule.add_exception(SpecialEvent {
            period: SpecialEventPeriod::CalendarEntry(CalendarEntry::Date(make_date(
                2025, 12, 25, 4,
            ))),
            schedule: vec![TimeValue::new(0, 0, BACnetValue::Real(55.0))],
            priority: 1,
        });

        let christmas = make_date(2025, 12, 25, 4);
        let result = schedule.evaluate(&christmas, &make_time(10, 0));
        assert_eq!(result, BACnetValue::Real(55.0));
    }

    #[test]
    fn test_schedule_properties() {
        let schedule = Schedule::new(1, "Prop Test")
            .with_description("Test schedule")
            .with_schedule_default(BACnetValue::Real(68.0))
            .with_priority(8);

        let id = schedule
            .read_property(PropertyId::ObjectIdentifier)
            .unwrap();
        assert_eq!(
            id,
            BACnetValue::ObjectIdentifier(ObjectId::new(ObjectType::Schedule, 1))
        );

        let name = schedule.read_property(PropertyId::ObjectName).unwrap();
        assert_eq!(name, BACnetValue::CharacterString("Prop Test".into()));

        let obj_type = schedule.read_property(PropertyId::ObjectType).unwrap();
        assert_eq!(obj_type, BACnetValue::Enumerated(17));

        let default = schedule.read_property(PropertyId::ScheduleDefault).unwrap();
        assert_eq!(default, BACnetValue::Real(68.0));

        let priority = schedule
            .read_property(PropertyId::PriorityForWriting)
            .unwrap();
        assert_eq!(priority, BACnetValue::Unsigned(8));
    }

    #[test]
    fn test_schedule_write_properties() {
        let schedule = Schedule::new(1, "Write Test");

        // Write present value
        schedule
            .write_property(PropertyId::PresentValue, BACnetValue::Real(75.0))
            .unwrap();
        assert_eq!(schedule.get_present_value(), BACnetValue::Real(75.0));

        // Write schedule default
        schedule
            .write_property(PropertyId::ScheduleDefault, BACnetValue::Real(65.0))
            .unwrap();
        assert_eq!(schedule.schedule_default(), BACnetValue::Real(65.0));

        // Write out of service
        schedule
            .write_property(PropertyId::OutOfService, BACnetValue::Boolean(true))
            .unwrap();
        assert!(schedule.is_out_of_service());

        // Read-only rejection
        let result =
            schedule.write_property(PropertyId::ObjectIdentifier, BACnetValue::Unsigned(0));
        assert!(result.is_err());
    }

    #[test]
    fn test_schedule_list_properties() {
        let schedule = Schedule::new(1, "List Test");
        let props = schedule.list_properties();
        assert!(props.contains(&PropertyId::WeeklySchedule));
        assert!(props.contains(&PropertyId::ExceptionSchedule));
        assert!(props.contains(&PropertyId::ScheduleDefault));
        assert!(props.contains(&PropertyId::EffectivePeriod));
        assert!(props.contains(&PropertyId::PriorityForWriting));
    }

    #[test]
    fn test_schedule_output_references() {
        let schedule = Schedule::new(1, "Ref Test");
        assert_eq!(schedule.output_references().len(), 0);

        schedule.add_output_reference(ObjectPropertyReference {
            object_id: ObjectId::new(ObjectType::AnalogOutput, 1),
            property_id: PropertyId::PresentValue,
            array_index: None,
        });

        assert_eq!(schedule.output_references().len(), 1);
    }

    // ── Calendar Object ──

    #[test]
    fn test_calendar_creation() {
        let calendar = Calendar::new(1, "Holidays");
        assert_eq!(
            calendar.object_identifier(),
            ObjectId::new(ObjectType::Calendar, 1)
        );
        assert_eq!(calendar.object_name(), "Holidays");
        assert!(!calendar.get_present_value());
    }

    #[test]
    fn test_calendar_date_match() {
        let calendar = Calendar::new(1, "Test Calendar")
            .with_entry(CalendarEntry::Date(make_date(2025, 12, 25, 4)));

        assert!(calendar.evaluate(&make_date(2025, 12, 25, 4)));
        assert!(!calendar.evaluate(&make_date(2025, 12, 26, 5)));
    }

    #[test]
    fn test_calendar_date_range_match() {
        let calendar = Calendar::new(1, "Summer Holidays").with_entry(CalendarEntry::DateRange(
            DateRange::new(make_date(2025, 7, 1, 255), make_date(2025, 7, 31, 255)),
        ));

        assert!(calendar.evaluate(&make_date(2025, 7, 15, 2)));
        assert!(!calendar.evaluate(&make_date(2025, 8, 1, 5)));
    }

    #[test]
    fn test_calendar_weeknday_match() {
        let calendar = Calendar::new(1, "Weekends")
            .with_entry(CalendarEntry::WeekNDay {
                month: 255,
                week_of_month: 255,
                day_of_week: 6, // Saturday
            })
            .with_entry(CalendarEntry::WeekNDay {
                month: 255,
                week_of_month: 255,
                day_of_week: 7, // Sunday
            });

        let saturday = make_date(2025, 3, 8, 6);
        let sunday = make_date(2025, 3, 9, 7);
        let monday = make_date(2025, 3, 10, 1);

        assert!(calendar.evaluate(&saturday));
        assert!(calendar.evaluate(&sunday));
        assert!(!calendar.evaluate(&monday));
    }

    #[test]
    fn test_calendar_properties() {
        let calendar = Calendar::new(1, "Prop Calendar")
            .with_description("Test")
            .with_entry(CalendarEntry::Date(make_date(2025, 1, 1, 3)));

        let id = calendar
            .read_property(PropertyId::ObjectIdentifier)
            .unwrap();
        assert_eq!(
            id,
            BACnetValue::ObjectIdentifier(ObjectId::new(ObjectType::Calendar, 1))
        );

        let name = calendar.read_property(PropertyId::ObjectName).unwrap();
        assert_eq!(name, BACnetValue::CharacterString("Prop Calendar".into()));

        let obj_type = calendar.read_property(PropertyId::ObjectType).unwrap();
        assert_eq!(obj_type, BACnetValue::Enumerated(6)); // Calendar = 6

        let date_list = calendar.read_property(PropertyId::DateList).unwrap();
        if let BACnetValue::List(entries) = date_list {
            assert_eq!(entries.len(), 1);
        } else {
            panic!("Expected List for DateList");
        }

        let pv = calendar.read_property(PropertyId::PresentValue).unwrap();
        assert_eq!(pv, BACnetValue::Boolean(false));
    }

    #[test]
    fn test_calendar_write_present_value() {
        let calendar = Calendar::new(1, "Write Test");

        calendar
            .write_property(PropertyId::PresentValue, BACnetValue::Boolean(true))
            .unwrap();
        assert!(calendar.get_present_value());

        // Read-only rejection
        let result =
            calendar.write_property(PropertyId::ObjectIdentifier, BACnetValue::Unsigned(0));
        assert!(result.is_err());
    }

    #[test]
    fn test_calendar_list_properties() {
        let calendar = Calendar::new(1, "List Test");
        let props = calendar.list_properties();
        assert!(props.contains(&PropertyId::DateList));
        assert!(props.contains(&PropertyId::PresentValue));
        assert!(props.contains(&PropertyId::StatusFlags));
    }

    #[test]
    fn test_calendar_multiple_entries() {
        let calendar = Calendar::new(1, "Multi")
            .with_entry(CalendarEntry::Date(make_date(2025, 1, 1, 3)))
            .with_entry(CalendarEntry::Date(make_date(2025, 7, 4, 5)))
            .with_entry(CalendarEntry::Date(make_date(2025, 12, 25, 4)));

        assert_eq!(calendar.entry_count(), 3);
        assert!(calendar.evaluate(&make_date(2025, 7, 4, 5)));
        assert!(!calendar.evaluate(&make_date(2025, 7, 5, 6)));
    }

    #[test]
    fn test_calendar_clear_entries() {
        let calendar = Calendar::new(1, "Clear Test")
            .with_entry(CalendarEntry::Date(make_date(2025, 1, 1, 3)));

        assert_eq!(calendar.entry_count(), 1);
        calendar.clear_entries();
        assert_eq!(calendar.entry_count(), 0);
    }

    // ── Date Range ──

    #[test]
    fn test_date_range_contains() {
        let range = DateRange::new(make_date(2025, 6, 1, 255), make_date(2025, 8, 31, 255));

        assert!(range.contains(&make_date(2025, 7, 15, 2)));
        assert!(range.contains(&make_date(2025, 6, 1, 255)));
        assert!(range.contains(&make_date(2025, 8, 31, 255)));
        assert!(!range.contains(&make_date(2025, 5, 31, 6)));
        assert!(!range.contains(&make_date(2025, 9, 1, 1)));
    }

    // ── Time/Value ──

    #[test]
    fn test_time_to_seconds() {
        assert_eq!(time_to_seconds(&make_time(0, 0)), 0);
        assert_eq!(time_to_seconds(&make_time(1, 0)), 3600);
        assert_eq!(time_to_seconds(&make_time(12, 30)), 45000);
        assert_eq!(time_to_seconds(&make_time(23, 59)), 86340);
    }

    #[test]
    fn test_bacnet_day_of_week_to_index() {
        assert_eq!(bacnet_day_of_week_to_index(1), Some(0)); // Monday
        assert_eq!(bacnet_day_of_week_to_index(7), Some(6)); // Sunday
        assert_eq!(bacnet_day_of_week_to_index(0), None);
        assert_eq!(bacnet_day_of_week_to_index(8), None);
    }
}