rs-matter 0.2.0

Native Rust implementation of the Matter (Smart-Home) ecosystem
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
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
/*
 *
 *    Copyright (c) 2025-2026 Project CHIP Authors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

//! Implementation of the Matter Level Control cluster.
//!
//! This module provides the core logic and state management for the LevelControl cluster as defined by the Matter specification v1.3.
//! It handles commands and attributes related to device level control, such as dimming lights or adjusting motor positions.
//! The implementation supports asynchronous transitions, step and move operations, and integration with the OnOff cluster.
//!
//! Key features:
//! - Validates cluster configuration and feature dependencies.
//! - Manages level transitions with optional timing and rate control.
//! - Supports quiet reporting of attribute changes according to specification rules.
//! - Provides hooks for device-specific logic via the `LevelControlHooks` trait.
//! - Designed for extensibility and integration with other clusters (e.g., OnOff).

use core::cell::Cell;
use core::future::{pending, ready, Future};
use core::ops::Mul;
use core::pin::pin;

use embassy_futures::select::{select, select3, Either, Either3};
use embassy_time::{Duration, Instant};

use crate::dm::clusters::app::on_off::{OnOffHooks, FULL_CLUSTER as ON_OFF_FULL_CLUSTER};
use crate::dm::clusters::app::{level_control, on_off::OnOffHandler};
pub use crate::dm::clusters::decl::level_control::*;
use crate::dm::clusters::decl::scenes_management::{
    AttributeValuePairStruct, AttributeValuePairStructArrayBuilder,
};
use crate::dm::clusters::scenes::{SceneClusterHandler, SceneInvalidator};
use crate::dm::{
    AttrId, Cluster, ClusterId, Dataver, EndptId, HandlerContext, InvokeContext, ReadContext,
    WriteContext,
};
use crate::error::{Error, ErrorCode};
use crate::tlv::{Nullable, TLVArray, TLVBuilderParent};
use crate::utils::cell::RefCell;
use crate::utils::sync::blocking::Mutex;
use crate::utils::sync::Signal;

/// Messages passed to the `notify` closure in `LevelControlHooks::run()` method.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum OutOfBandMessage {
    /// Indicates to the handler that the value of the current level has change and it should update the Matter state accordingly.
    /// Takes the new value of the CurrentLevel.
    Update(u8),
    /// Initiates a MoveToLevel command.
    /// This will change the state of the device if and when appropriate according to Matter logic.
    /// See Matter Application Clusters specification.
    MoveToLevel {
        with_on_off: bool,
        level: u8,
        transition_time: Option<u16>,
        options_mask: OptionsBitmap,
        options_override: OptionsBitmap,
    },
    /// Initiates a Move command.
    /// This will change the state of the device if and when appropriate according to Matter logic.
    /// See Matter Application Clusters specification.
    Move {
        with_on_off: bool,
        move_mode: MoveModeEnum,
        rate: Option<u8>,
        options_mask: OptionsBitmap,
        options_override: OptionsBitmap,
    },
    /// Initiates a Step command.
    /// This will change the state of the device if and when appropriate according to Matter logic.
    /// See Matter Application Clusters specification.
    Step {
        with_on_off: bool,
        step_mode: StepModeEnum,
        step_size: u8,
        transition_time: Option<u16>,
        options_mask: OptionsBitmap,
        options_override: OptionsBitmap,
    },
    /// Stop any running LevelControl transitions.
    Stop,
}

enum Task {
    MoveToLevel {
        with_on_off: bool,
        target: u8,
        transition_time: u16,
        /// When `true`, the transition was queued by a scene recall;
        /// `set_level` skips `notify_scenable_changed` so `SceneValid`
        /// is preserved.
        scene_apply: bool,
    },
    Move {
        with_on_off: bool,
        move_mode: MoveModeEnum,
        event_duration: Duration,
    },
    Stop,
    OnOffStateChange {
        on: bool,
    },
}

struct LevelControlState {
    on_level: Nullable<u8>,
    options: OptionsBitmap,
    remaining_time: u16,
    on_off_transition_time: u16,
    on_transition_time: Nullable<u16>,
    off_transition_time: Nullable<u16>,
    default_move_rate: Nullable<u8>,
    previous_current_level: Option<u8>,
    last_current_level_notification: Instant,
}

impl LevelControlState {
    fn new(attribute_defaults: AttributeDefaults) -> Self {
        Self {
            on_level: attribute_defaults.on_level,
            options: attribute_defaults.options,
            remaining_time: 0,
            on_off_transition_time: attribute_defaults.on_off_transition_time,
            on_transition_time: attribute_defaults.on_transition_time,
            off_transition_time: attribute_defaults.off_transition_time,
            default_move_rate: attribute_defaults.default_move_rate,
            previous_current_level: None,
            last_current_level_notification: Instant::from_millis(0),
        }
    }

    /// Updates the RemainingTime attribute and returns true if a Matter notification is required.
    /// Matter notifications, reporting changes to this attribute, are only required under specific conditions.
    ///
    /// # Arguments
    /// - `remaining_time` - The new remaining time.
    /// - `is_start_of_transition` - Indicates if this is the start of a transition.
    fn write_remaining_time_quietly(
        &mut self,
        remaining_time: Duration,
        is_start_of_transition: bool,
    ) -> bool {
        let remaining_time_ds = remaining_time.as_millis().div_ceil(100) as u16;

        // RemainingTime Quiet report conditions:
        // - When it changes to 0, or
        // - When it changes from 0 to any value higher than 10, or
        // - When it changes, with a delta larger than 10, caused by the invoke of a command.
        let previous_remaining_time = self.remaining_time;
        let changed_to_zero = remaining_time_ds == 0 && previous_remaining_time != 0;
        let changed_from_zero_gt_10 = previous_remaining_time == 0 && remaining_time_ds > 10;
        let changed_by_gt_10 =
            remaining_time_ds.abs_diff(previous_remaining_time) > 10 && is_start_of_transition;

        self.remaining_time = remaining_time_ds;

        if changed_to_zero || changed_from_zero_gt_10 || changed_by_gt_10 {
            return true;
        }

        false
    }
}

/// Implementation of the LevelControlHandler, providing functionality for the Matter Level Control cluster.
///
/// # Type Parameters
/// - `'a`: Lifetime for references held by the cluster.
/// - `H`: Handler implementing the LevelControlHooks trait, providing cluster-specific configuration and logic.
/// - `OH` : Handler implementing the OnOffHooks trait.
///
/// # Constants
/// - `MAXIMUM_LEVEL`: The maximum allowed level value (254).
///
/// # Panics
/// - Initialisation panics if the cluster configuration is invalid or required attributes/commands are missing.
///
/// # Notes
/// - This implementation follows version 1.3 of the Matter specification.
// TODO:
// #[derive(Clone, Debug)]
// #[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct LevelControlHandler<'a, H: LevelControlHooks, OH: OnOffHooks> {
    dataver: Dataver,
    endpoint_id: EndptId,
    hooks: H,
    on_off_handler: Mutex<Cell<Option<&'a OnOffHandler<'a, OH, H>>>>,
    /// See [`OnOffHandler::with_scene_invalidator`] — same role, fired
    /// when `CurrentLevel` mutates.
    scene_invalidator: Mutex<Cell<Option<&'a dyn SceneInvalidator>>>,
    state: Mutex<RefCell<LevelControlState>>,
    task_signal: Signal<Option<Task>>,
}

/// Default values for the attributes with manufacturer specific defaults.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub struct AttributeDefaults {
    pub on_level: Nullable<u8>,
    pub options: OptionsBitmap,
    pub on_off_transition_time: u16,
    pub on_transition_time: Nullable<u16>,
    pub off_transition_time: Nullable<u16>,
    pub default_move_rate: Nullable<u8>,
}

impl AttributeDefaults {
    /// Creates an `AttributeDefaults` instance with default values.
    ///
    /// # Default Values
    /// - `on_level`: `Nullable::none()` (not set)
    /// - `options`: 0 (no options set)
    /// - `on_off_transition_time`: 0 (no transition delay by default)
    /// - `on_transition_time`: `Nullable::none()` (not set)
    /// - `off_transition_time`: `Nullable::none()` (not set)
    /// - `default_move_rate`: `Nullable::none()` (not set)
    pub const fn new() -> Self {
        Self {
            on_level: Nullable::none(),
            options: OptionsBitmap::from_bits(0).unwrap(),
            on_off_transition_time: 0,
            on_transition_time: Nullable::none(),
            off_transition_time: Nullable::none(),
            default_move_rate: Nullable::none(),
        }
    }
}

impl Default for AttributeDefaults {
    fn default() -> Self {
        Self::new()
    }
}

impl<H: LevelControlHooks> LevelControlHandler<'_, H, NoOnOff> {
    /// Creates a new `LevelControlHandler` with the given hooks which is **not** coupled to an OnOff cluster.
    ///
    /// NOTE: This constructor automatically calls `init` with no coupled `OnOff` handler.
    ///
    /// # Arguments
    /// - `hooks` - A reference to the struct implementing the device-specific level control logic.
    pub fn new_standalone(
        dataver: Dataver,
        endpoint_id: EndptId,
        hooks: H,
        attribute_defaults: AttributeDefaults,
    ) -> Self {
        let this = Self::new(dataver, endpoint_id, hooks, attribute_defaults);

        this.init(None);

        this
    }
}

impl<'a, H: LevelControlHooks, OH: OnOffHooks> LevelControlHandler<'a, H, OH> {
    const MAXIMUM_LEVEL: u8 = 254;

    /// Creates a new `LevelControlHandler` with the given hooks.
    ///
    /// # Arguments
    /// - `hooks` - A reference to the struct implementing the device-specific level control logic.
    ///
    /// # Usage
    /// - Initialise and optionally couple with an OnOff handler via `init`.
    pub fn new(
        dataver: Dataver,
        endpoint_id: EndptId,
        hooks: H,
        attribute_defaults: AttributeDefaults,
    ) -> Self {
        Self {
            dataver,
            endpoint_id,
            hooks,
            on_off_handler: Mutex::new(Cell::new(None)),
            scene_invalidator: Mutex::new(Cell::new(None)),
            state: Mutex::new(RefCell::new(LevelControlState::new(attribute_defaults))),
            task_signal: Signal::new(None),
        }
    }

    /// Attach a [`SceneInvalidator`] — typically the
    /// [`crate::dm::clusters::scenes::ScenesState`] backing Scenes
    /// Management on the same endpoint — so command-driven
    /// `CurrentLevel` mutations flip `SceneValid → false` for any
    /// recalled scene. No-op when unset.
    pub fn with_scene_invalidator(self, invalidator: &'a dyn SceneInvalidator) -> Self {
        self.scene_invalidator
            .lock(|cell| cell.set(Some(invalidator)));
        self
    }

    fn notify_scenable_changed(&self) {
        if let Some(inv) = self.scene_invalidator.lock(|cell| cell.get()) {
            inv.scenable_attribute_changed(self.endpoint_id);
        }
    }

    /// Checks that the cluster is correctly configured, including required attributes, commands, and feature dependencies.
    ///
    /// # Panics
    ///
    /// panics with error message if the `state`'s `CLUSTER` is misconfigured.
    fn validate(&self) {
        if H::CLUSTER.revision != 6 {
            panic!(
                "LevelControl validation: incorrect version number: expected 6 got {}",
                H::CLUSTER.revision
            );
        }

        // Check for mandatory attributes
        if H::CLUSTER
            .attribute(AttributeId::CurrentLevel as _)
            .is_none()
            || H::CLUSTER.attribute(AttributeId::OnLevel as _).is_none()
            || H::CLUSTER.attribute(AttributeId::Options as _).is_none()
        {
            panic!("LevelControl validation: missing required attributes: CurrentLevel, OnLevel, or Options");
        }

        // Check for mandatory commands
        if H::CLUSTER.command(CommandId::MoveToLevel as _).is_none()
            || H::CLUSTER.command(CommandId::Move as _).is_none()
            || H::CLUSTER.command(CommandId::Step as _).is_none()
            || H::CLUSTER.command(CommandId::Stop as _).is_none()
            || H::CLUSTER
                .command(CommandId::MoveToLevelWithOnOff as _)
                .is_none()
            || H::CLUSTER.command(CommandId::MoveWithOnOff as _).is_none()
            || H::CLUSTER.command(CommandId::StepWithOnOff as _).is_none()
            || H::CLUSTER.command(CommandId::StopWithOnOff as _).is_none()
        {
            panic!("LevelControl validation: missing required commands: MoveToLevel, Move, Step, Stop, MoveToLevelWithOnOff, MoveWithOnOff, StepWithOnOff or StopWithOnOff");
        }

        // If the ON_OFF feature in enabled, check that an OnOff cluster is coupled.
        if H::CLUSTER.feature_map & level_control::Feature::ON_OFF.bits() != 0 {
            // Ideally we should confirm that they are on the same endpoint.
            if self.on_off_handler.lock(|h| h.get()).is_none() {
                panic!("LevelControl validation: a reference to the OnOff cluster must be set when the ON_OFF feature is enabled");
            }
        }

        if H::MAX_LEVEL > Self::MAXIMUM_LEVEL {
            panic!(
                "LevelControl validation: the MAX_LEVEL cannot be higher than {}",
                Self::MAXIMUM_LEVEL
            );
        }

        if H::CLUSTER.feature_map & level_control::Feature::LIGHTING.bits() != 0 {
            // From the spec
            // A value of 0x00 SHALL NOT be used.
            // A value of 0x01 SHALL indicate the minimum level that can be attained on a device.
            // A value of 0xFE SHALL indicate the maximum level that can be attained on a device.
            if H::MIN_LEVEL == 0 {
                panic!("LevelControl validation: MIN_LEVEL cannot be 0 when the LIGHTING feature is enabled");
            }

            // Check for required attributes when using this feature
            if H::CLUSTER
                .attribute(AttributeId::RemainingTime as _)
                .is_none()
                || H::CLUSTER
                    .attribute(AttributeId::StartUpCurrentLevel as _)
                    .is_none()
            {
                panic!("LevelControl validation: the RemainingTime and StartUpCurrentLevel attributes are required by the LIGHTING feature");
            }
        }
    }

    /// Initializes the cluster on startup;
    /// - wire coupled handlers
    /// - validate the handler setup with the configuration
    /// - set the CurrentLevel attribute according to the StartUpCurrentLevel attribute.
    ///
    /// # Parameters
    /// *on_off_handler: the OnOffHandler instance coupled with this LevelControlHandler, i.e. the OnOff cluster on the same endpoint. This should be set if the OnOff feature is set.
    ///
    /// # Panics
    ///
    /// panics if the `state`'s `CLUSTER` is misconfigured.
    pub fn init(&self, on_off_handler: Option<&'a OnOffHandler<'a, OH, H>>) {
        // 1.6.6.15. StartUpCurrentLevel Attribute
        // This attribute SHALL indicate the desired startup level for a device when it is supplied with power
        // and this level SHALL be reflected in the CurrentLevel attribute. The values of the
        // StartUpCurrentLevel attribute are listed below:
        // | Value        | Action on power up |
        // |--------------| -------------------|
        // | 0            | Set the CurrentLevel attribute to the minimum value permitted on the device |
        // | null         | Set the CurrentLevel attribute to its previous value |
        // | other values | Set the CurrentLevel attribute to this value |
        // todo: Implement checking the reason for reboot.
        // This behavior does not apply to reboots associated with OTA. After an OTA restart, the CurrentLevel
        // attribute SHALL return to its value prior to the restart.

        // Wire any coupled clusters
        self.on_off_handler.lock(|h| h.set(on_off_handler));

        self.validate();

        // `self.hooks` holds the previous current level as supplied by the SDK consumer.
        // Hence, if this process errors, we quietly abort resulting in the previous current level.
        if let Ok(Some(startup_current_level)) = self.hooks.start_up_current_level() {
            // The spec fails to mention the need for this bounding.
            let level = if startup_current_level < H::MIN_LEVEL {
                H::MIN_LEVEL
            } else if startup_current_level > H::MAX_LEVEL {
                H::MAX_LEVEL
            } else {
                startup_current_level
            };

            match self.hooks.set_device_level(level) {
                Ok(current_level) => self.hooks.set_current_level(current_level),
                Err(_) => error!("Failed to set Current Level to Start Up Current Level."),
            }
        }
    }

    /// Adapt the handler instance to the generic `rs-matter` `Handler` trait
    pub const fn adapt(self) -> HandlerAsyncAdaptor<Self> {
        HandlerAsyncAdaptor(self)
    }

    fn with_state<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&mut LevelControlState) -> R,
    {
        self.state.lock(|state| {
            let mut state = state.borrow_mut();

            f(&mut state)
        })
    }

    fn with_state_notify<F, R>(&self, ctx: impl WriteContext, f: F) -> R
    where
        F: FnOnce(&mut LevelControlState) -> R,
    {
        let result = self.with_state(f);

        ctx.notify_changed();

        result
    }

    /// Sets the CurrentLevel attribute.
    /// If `set_device` is true, this method sets the level of the device, via the `set_level` hook.
    /// This method calculates if a Matter notification is required according to the quiet reporting conditions described in the spec.
    ///
    /// # Arguments
    /// - `level` - The new current level.
    /// - `is_end_of_transition` - Indicates if this is the end of a transition.
    /// - `set_device` - Indicates if the state of the physical device should be changed.
    ///
    /// # Returns
    /// A tuple with the current level of the device, and a boolean signifying if a Matter notification is required.
    fn set_level(
        &self,
        state: &mut LevelControlState,
        level: u8,
        is_end_of_transition: bool,
        set_device: bool,
        scene_apply: bool,
    ) -> Result<(Option<u8>, bool), Error> {
        // Store the previous current level before updating, for quiet reporting logic.
        state.previous_current_level = self.hooks.current_level();
        let current_level = match set_device {
            true => self
                .hooks
                .set_device_level(level)
                .map_err(|_| ErrorCode::Failure)?,
            false => Some(level),
        };
        self.hooks.set_current_level(current_level);
        // Scene-recall transitions move *toward* the recalled state,
        // so they must not invalidate `SceneValid` on intermediate
        // steps. Scenes restores the bit after `apply` returns.
        if !scene_apply {
            self.notify_scenable_changed();
        }
        let last_notification = Instant::now() - state.last_current_level_notification;

        // CurrentLevel Quiet report conditions:
        // - At most once per second, or
        // - At the end of the movement/transition, or
        // - When it changes from null to any other value and vice versa.
        if last_notification.ge(&Duration::from_secs(1))
            || is_end_of_transition
            || state.previous_current_level.is_none()
            || current_level.is_none()
        {
            state.last_current_level_notification = Instant::now();
            return Ok((current_level, true));
        }

        Ok((current_level, false))
    }

    /// Checks if a command should proceed beyond the Options processing.
    /// Returns true if execution of the command should continue, false otherwise.
    //
    // From the spec
    // Command execution SHALL NOT continue beyond the Options processing if all of these criteria are true:
    // - The command is one of the ‘without On/Off’ commands: Move, Move to Level, Step, or Stop.
    // - The On/Off cluster exists on the same endpoint as this cluster.
    // - The OnOff attribute of the On/Off cluster, on this endpoint, is FALSE.
    // - The value of the ExecuteIfOff bit is 0.
    fn should_continue(
        &self,
        with_on_off: bool,
        options_mask: OptionsBitmap,
        options_override: OptionsBitmap,
    ) -> Result<bool, Error> {
        if with_on_off {
            return Ok(true);
        }

        let Some(on_off_handler) = self.on_off_handler.lock(|h| h.get()) else {
            // This should be sufficient to satisfy "The On/Off cluster exists on the same endpoint as this cluster"
            // if we can check the NODE configuration in validate.
            return Ok(true);
        };

        if on_off_handler.on_off() {
            return Ok(true);
        }

        // The OptionsMask and OptionsOverride fields SHALL both be present. Default values are provided
        // to interpret missing fields from legacy devices. A temporary Options bitmap SHALL be created from
        // the Options attribute, using the OptionsMask and OptionsOverride fields. Each bit of the temporary
        // Options bitmap SHALL be determined as follows:
        // Each bit in the Options attribute SHALL determine the corresponding bit in the temporary Options
        // bitmap, unless the OptionsMask field is present and has the corresponding bit set to 1, in which
        // case the corresponding bit in the OptionsOverride field SHALL determine the corresponding bit in
        // the temporary Options bitmap.
        if options_mask.contains(level_control::OptionsBitmap::EXECUTE_IF_OFF) {
            return Ok(options_override.contains(level_control::OptionsBitmap::EXECUTE_IF_OFF));
        }

        // TODO: Think if the whole method should instead be executed when the state lock is held
        Ok(self
            .with_state(|state| state.options)
            .contains(level_control::OptionsBitmap::EXECUTE_IF_OFF))
    }

    /// Handles asynchronous tasks for level transitions and moves.
    async fn task_manager(&self, ctx: impl HandlerContext, task: Task) {
        match task {
            Task::MoveToLevel {
                with_on_off,
                target,
                transition_time,
                scene_apply,
            } => {
                if let Err(e) = self
                    .move_to_level_transition(
                        ctx,
                        with_on_off,
                        target,
                        transition_time,
                        scene_apply,
                    )
                    .await
                {
                    error!("Task::MoveToLevel: {:?}", e);
                }
            }
            Task::Move {
                with_on_off,
                move_mode,
                event_duration,
            } => {
                if let Err(e) = self
                    .move_transition(ctx, with_on_off, move_mode, event_duration)
                    .await
                {
                    error!("Task::Move: {:?}", e);
                }
            }
            Task::Stop => (),
            Task::OnOffStateChange { on } => {
                if let Err(e) = self.handle_on_off_state_change(ctx, on).await {
                    error!("Task::OnOffStateChange: {:?}", e);
                }
            }
        }
    }

    /// This method is called by an OnOff cluster that is coupled with this LevelControl cluster.
    /// This method updates the CurrentLevel of the device when the state of the OnOff cluster changes.
    pub(crate) fn coupled_on_off_cluster_on_off_state_change(&self, on: bool) {
        self.task_signal.signal(Task::OnOffStateChange { on });
    }

    // From the spec
    // ## On
    // Temporarily store CurrentLevel.
    // Set CurrentLevel to the minimum level allowed for the device.
    // Change CurrentLevel to OnLevel, or to the stored level if OnLevel is not defined, over the time period OnOffTransitionTime.
    // ## off
    // Temporarily store CurrentLevel.
    // Change CurrentLevel to the minimum level allowed for the device over the time period OnOffTransitionTime.
    // If OnLevel is not defined, set the CurrentLevel to the stored level.
    async fn handle_on_off_state_change(
        &self,
        ctx: impl HandlerContext,
        on: bool,
    ) -> Result<(), Error> {
        info!("handle_on_off_state_change");

        let (target_level, transition_time, bitmap, temp_current_level) =
            self.with_state(|state| {
                let temp_current_level = self.hooks.current_level();

                // use of unwrap is justified since this will option is always valid.
                let bitmap = OptionsBitmap::from_bits(0).unwrap();

                let mut transition_time = state.on_off_transition_time;

                // 1.6.6.10. OnOffTransitionTime Attribute
                // This attribute SHALL indicate the time taken to move to or from the target level when On or Off
                // commands are received by an On/Off cluster on the same endpoint.
                if on {
                    // OnOff-coupling driven: user toggled OnOff and
                    // LC follows. Not a scene apply.
                    let (level, should_notify) =
                        self.set_level(state, H::MIN_LEVEL, false, true, false)?;
                    if should_notify {
                        ctx.notify_attr_changed(
                            self.endpoint_id,
                            Self::CLUSTER.id,
                            AttributeId::CurrentLevel as _,
                        );
                    }
                    if level.is_none() {
                        Err(ErrorCode::Failure)?;
                    }

                    let target_level = match state.on_level.as_opt_ref() {
                        Some(on_level) => *on_level,
                        None => temp_current_level.ok_or(ErrorCode::Failure)?,
                    };

                    // 1.6.6.12. OnTransitionTime Attribute
                    // This attribute SHALL indicate the time taken to move the current level from the minimum level to
                    // the maximum level when an On command is received by an On/Off cluster on the same endpoint.
                    // If this attribute is not implemented, or contains a null value, the
                    // OnOffTransitionTime SHALL be used instead.
                    if let Some(tt) = state.on_transition_time.as_opt_ref() {
                        transition_time = *tt;
                    }

                    Ok::<_, Error>((target_level, transition_time, bitmap, temp_current_level))
                } else {
                    // 1.6.6.13. OffTransitionTime Attribute
                    // This attribute SHALL indicate the time taken to move the current level from the maximum level to
                    // the minimum level when an Off command is received by an On/Off cluster on the same endpoint.
                    // If this attribute is not implemented, or contains a null value, the
                    // OnOffTransitionTime SHALL be used instead.
                    if let Some(tt) = state.off_transition_time.as_opt_ref() {
                        transition_time = *tt;
                    }

                    Ok((H::MIN_LEVEL, transition_time, bitmap, temp_current_level))
                }
            })?;

        self.move_to_level_blocking(
            &ctx,
            true,
            target_level,
            Some(transition_time),
            bitmap,
            bitmap,
        )
        .await?;

        if !on {
            let restored = self.with_state(|state| {
                if state.on_level.is_none() {
                    self.hooks.set_current_level(temp_current_level);
                    true
                } else {
                    false
                }
            });
            if restored {
                // CurrentLevel was restored to the pre-Off stored value
                ctx.notify_attr_changed(
                    self.endpoint_id,
                    Self::CLUSTER.id,
                    AttributeId::CurrentLevel as _,
                );
            }
        }

        Ok(())
    }

    /// Updates the OnOff attribute of the coupled OnOff cluster based on the current level and command type.
    //
    // From the spec
    // When the level is reduced to its minimum the OnOff attribute is automatically turned to FALSE,
    // and when the level is increased above its minimum the OnOff attribute is automatically turned to TRUE.
    fn update_coupled_on_off(&self, current_level: u8, with_on_off: bool) -> Result<(), Error> {
        // From the spec.
        // There are two sets of commands provided in the Level Control cluster. These are identical, except
        // that the first set (MoveToLevel, Move and Step commands) SHALL NOT affect the OnOff attribute,
        // whereas the second set ('with On/Off' variants) SHALL.
        if !with_on_off {
            return Ok(());
        }

        let new_on_off_value = current_level > H::MIN_LEVEL;

        // The `validate` method ensures that the on_off_handler is set if this function is called.
        if let Some(on_off) = self.on_off_handler.lock(|h| h.get()) {
            let current_on_off = on_off.on_off();
            if current_on_off != new_on_off_value {
                info!(
                    "Updating the OnOff cluster with on_off = {}",
                    new_on_off_value
                );
                on_off.coupled_cluster_set_on_off(new_on_off_value);
            }
        }

        Ok(())
    }

    // Helper method performing initial validation for the move-to-level command.
    // Used by move_to_level and move_to_level_blocking.
    // Return true if processing should continue. False otherwise.
    fn move_to_level_validation(
        &self,
        level: &mut u8,
        with_on_off: bool,
        options_mask: OptionsBitmap,
        options_override: OptionsBitmap,
    ) -> Result<bool, Error> {
        if *level > Self::MAXIMUM_LEVEL {
            return Err(ErrorCode::InvalidCommand.into());
        }

        if !self.should_continue(with_on_off, options_mask, options_override)? {
            return Ok(false);
        }

        if *level > H::MAX_LEVEL {
            *level = H::MAX_LEVEL;
            debug!("target level > MAX_LEVEL. level set to MAX_LEVEL")
        } else if *level < H::MIN_LEVEL {
            *level = H::MIN_LEVEL;
            debug!("target level < MIN_LEVEL. level set to MIN_LEVEL")
        }

        Ok(true)
    }

    /// Handles MoveToLevel commands, including validation, bounding, and transition logic.
    /// Note: This will try to update the OnOff cluster's OnOff attribute at the start and end of the transition.
    /// Note: If calling this from another Task, use the blocking version `move_to_level_blocking`, otherwise the calling Task will be halted.
    ///
    /// # Parameters
    ///
    /// * with_on_off: Is the LevelControl command calling this method one of the "WithOnOff" variant?
    /// * level: The target level to move to.
    /// * transition_time: The time for the transition in 1/10ts of a second.
    /// * options_mask: The options mask in the command attributes.
    /// * options_override: The options override in the command attributes.
    fn move_to_level(
        &self,
        with_on_off: bool,
        mut level: u8,
        transition_time: Option<u16>,
        options_mask: OptionsBitmap,
        options_override: OptionsBitmap,
        scene_apply: bool,
    ) -> Result<(), Error> {
        if let Ok(false) =
            self.move_to_level_validation(&mut level, with_on_off, options_mask, options_override)
        {
            return Ok(());
        }

        info!(
            "setting level to {} with transition time {:?}",
            level, transition_time
        );

        // Stop any ongoing transitions and check if we happen to be where we need to be.
        // If so, there is nothing to do.
        self.task_signal.signal(Task::Stop);
        if self.hooks.current_level() == Some(level) {
            self.update_coupled_on_off(level, with_on_off)?;
            return Ok(());
        }

        let t_time = transition_time.unwrap_or(0);

        self.task_signal.signal(Task::MoveToLevel {
            with_on_off,
            target: level,
            transition_time: t_time,
            scene_apply,
        });

        Ok(())
    }

    // This version does not call Task::Stop. If we are called from another Task, we shouldn't stop it.
    /// Handles MoveToLevel commands, including validation, bounding, and transition logic.
    /// Note: This will try to update the OnOff cluster's OnOff attribute at the start and end of the transition.
    /// Note: This will block until the transition completes.
    ///
    /// # Parameters
    ///
    /// * with_on_off: Is the LevelControl command calling this method one of the "WithOnOff" variant?
    /// * level: The target level to move to.
    /// * transition_time: The time for the transition in 1/10ts of a second.
    /// * options_mask: The options mask in the command attributes.
    /// * options_override: The options override in the command attributes.
    async fn move_to_level_blocking(
        &self,
        ctx: impl HandlerContext,
        with_on_off: bool,
        mut level: u8,
        transition_time: Option<u16>,
        options_mask: OptionsBitmap,
        options_override: OptionsBitmap,
    ) -> Result<(), Error> {
        if let Ok(false) =
            self.move_to_level_validation(&mut level, with_on_off, options_mask, options_override)
        {
            return Ok(());
        }

        info!(
            "setting level to {} with transition time {:?}",
            level, transition_time
        );

        if self.hooks.current_level() == Some(level) {
            self.update_coupled_on_off(level, with_on_off)?;
            return Ok(());
        }

        let t_time = transition_time.unwrap_or(0);

        // Command-driven only — never reached from scene apply.
        self.move_to_level_transition(ctx, with_on_off, level, t_time, false)
            .await?;

        Ok(())
    }

    /// Asynchronously transitions the current level to a target level over a specified time.
    /// Note: This will try to update the OnOff cluster's OnOff attribute at the start and end of the transition.
    async fn move_to_level_transition(
        &self,
        ctx: impl HandlerContext,
        with_on_off: bool,
        target_level: u8,
        transition_time: u16,
        scene_apply: bool,
    ) -> Result<(), Error> {
        let event_start_time = Instant::now();

        // Check if current_level is null. If so, return error.
        let mut current_level = match self.hooks.current_level() {
            Some(cl) => cl,
            None => return Err(ErrorCode::Failure.into()),
        };

        let increasing = current_level < target_level;

        let steps = target_level.abs_diff(current_level);

        if steps == 0 {
            return Ok(());
        }

        let mut remaining_time = Duration::from_millis(transition_time as u64 * 100);
        let event_duration = Duration::from_millis_floor(remaining_time.as_millis() / steps as u64);

        let startup_latency = Instant::now() - event_start_time;
        loop {
            let event_start_time = Instant::now();

            if transition_time == 0 {
                current_level = target_level;
            } else {
                match increasing {
                    true => current_level += 1,
                    false => current_level -= 1,
                }
            }

            let is_transition_start = remaining_time.as_millis() == (transition_time as u64 * 100);
            let is_transition_end = current_level == target_level;

            debug!(
                "move_to_level_transition: Setting current level: {}",
                current_level
            );
            let (current_level, should_notify) = self.with_state(|state| {
                self.set_level(state, current_level, is_transition_end, true, scene_apply)
            })?;
            let current_level = match current_level {
                Some(level) => level,
                None => return Err(ErrorCode::Failure.into()),
            };

            if is_transition_start || is_transition_end {
                self.update_coupled_on_off(current_level, with_on_off)?;
            }

            if is_transition_end {
                if should_notify
                    || self.with_state(|state| {
                        state.write_remaining_time_quietly(
                            Duration::from_millis(0),
                            is_transition_start,
                        )
                    })
                {
                    ctx.notify_attr_changed(
                        self.endpoint_id,
                        Self::CLUSTER.id,
                        AttributeId::CurrentLevel as _,
                    );
                }
                return Ok(());
            }

            match remaining_time > event_duration {
                true => remaining_time -= event_duration,
                false => {
                    warn!("remaining time is 0 before level reached target");
                    remaining_time = Duration::from_millis(0)
                }
            }

            if should_notify
                || self.with_state(|state| {
                    state.write_remaining_time_quietly(remaining_time, is_transition_start)
                })
            {
                ctx.notify_attr_changed(
                    self.endpoint_id,
                    Self::CLUSTER.id,
                    AttributeId::CurrentLevel as _,
                );
            }

            let latency = match is_transition_start {
                false => embassy_time::Instant::now() - event_start_time,
                true => (embassy_time::Instant::now() - event_start_time) + startup_latency,
            };
            match event_duration.checked_sub(latency) {
                Some(wait_time) => embassy_time::Timer::after(wait_time).await,
                None => warn!("no wait time. Consider dynamically adjusting the step size?"),
            }
        }
    }

    /// Handles Move commands, determining the rate and initiating transitions.
    fn move_command(
        &self,
        state: &mut LevelControlState,
        with_on_off: bool,
        move_mode: MoveModeEnum,
        rate: Option<u8>,
        options_mask: OptionsBitmap,
        options_override: OptionsBitmap,
    ) -> Result<(), Error> {
        // From the spec
        //
        // If the Rate field is null, then the value of the
        // DefaultMoveRate attribute SHALL be used if that attribute is supported and its value is not null. If
        // the Rate field is null and the DefaultMoveRate attribute is either not supported or set to null, then
        // the device SHOULD move as fast as it is able.
        let rate = match rate {
            // Move at a rate of zero is no move at all. Immediately succeed without touching anything.
            Some(0) => return Ok(()),
            Some(val) => val,
            None => match state.default_move_rate.as_opt_ref() {
                Some(val) => *val,
                None => H::FASTEST_RATE,
            },
        };

        // This will catch the case where H::FASTEST_RATE is 0.
        // The spec is not explicit about what should be done if this happens.
        // For now we error out if DefaultMoveRate is equal to 0 as this is invalid
        // until spec defines a behaviour.
        if rate == 0 {
            return Err(Error::new(ErrorCode::InvalidCommand));
        }

        if !self.should_continue(with_on_off, options_mask, options_override)? {
            return Ok(());
        }

        // Exit if we are already at the limit in the direct of movement.
        if let Some(current_level) = self.hooks.current_level() {
            if (current_level == H::MIN_LEVEL && move_mode == MoveModeEnum::Down)
                || (current_level == H::MAX_LEVEL && move_mode == MoveModeEnum::Up)
            {
                return Ok(());
            }
        }

        let event_duration = Duration::from_hz(rate as u64);

        info!("moving with rate {}", rate);

        self.task_signal.signal(Task::Move {
            with_on_off,
            move_mode,
            event_duration,
        });

        Ok(())
    }

    /// Asynchronously moves the current level up or down at a specified rate.
    async fn move_transition(
        &self,
        ctx: impl HandlerContext,
        with_on_off: bool,
        move_mode: MoveModeEnum,
        event_duration: Duration,
    ) -> Result<(), Error> {
        loop {
            let event_start_time = Instant::now();

            let current_level = match self.hooks.current_level() {
                Some(cl) => cl,
                None => return Err(ErrorCode::InvalidState.into()),
            };

            let new_level = match move_mode {
                MoveModeEnum::Up => current_level.checked_add(1),
                MoveModeEnum::Down => current_level.checked_sub(1),
            };

            let new_level = match new_level {
                Some(nl) => nl,
                None => return Ok(()),
            };

            // If we start at min and go up, we need to update the onoff cluster immediately in case this method is halted.
            if current_level == H::MIN_LEVEL && new_level > H::MIN_LEVEL {
                self.update_coupled_on_off(new_level, with_on_off)?;
            }

            let is_end_of_transition = (new_level == H::MAX_LEVEL) || (new_level == H::MIN_LEVEL);

            // `Move` command path is command-driven only — no scene
            // recall queues a `Move` task.
            let (new_level, should_notify) = self.with_state(|state| {
                self.set_level(state, new_level, is_end_of_transition, true, false)
            })?;
            if should_notify {
                ctx.notify_attr_changed(
                    self.endpoint_id,
                    Self::CLUSTER.id,
                    AttributeId::CurrentLevel as _,
                );
            }
            let new_level = match new_level {
                Some(level) => level,
                None => return Err(ErrorCode::Failure.into()),
            };

            if is_end_of_transition {
                self.update_coupled_on_off(new_level, with_on_off)?;
                return Ok(());
            }

            let latency = embassy_time::Instant::now() - event_start_time;
            match event_duration.checked_sub(latency) {
                Some(wait_time) => embassy_time::Timer::after(wait_time).await,
                None => warn!("no wait time. Consider dynamically adjusting the step size?"),
            }
        }
    }

    /// Handles Step commands, adjusting the level by a step size and managing transition time proportionally.
    fn step(
        &self,
        with_on_off: bool,
        step_mode: StepModeEnum,
        step_size: u8,
        transition_time: Option<u16>,
        options_mask: OptionsBitmap,
        options_override: OptionsBitmap,
    ) -> Result<(), Error> {
        // From the spec
        //
        // if the StepSize field has a value of zero, the command has no effect and
        // a response SHALL be returned with the status code set to INVALID_COMMAND.
        if step_size == 0 {
            return Err(ErrorCode::InvalidCommand.into());
        }

        if !self.should_continue(with_on_off, options_mask, options_override)? {
            return Ok(());
        }

        let current_level = match self.hooks.current_level() {
            Some(val) => val,
            None => return Err(ErrorCode::InvalidState.into()),
        };

        let new_level = match step_mode {
            StepModeEnum::Up => current_level.saturating_add(step_size).min(H::MAX_LEVEL),
            StepModeEnum::Down => current_level.saturating_sub(step_size).max(H::MIN_LEVEL),
        };

        // From the spec. Effect on Receipt
        // Increase/Decrease CurrentLevel by StepSize units, or until
        // it reaches the maximum/minimum level allowed for the
        // device if this reached in the process. In the latter
        // case, the transition time SHALL be
        // proportionally reduced.
        let transition_time = match transition_time {
            Some(val) => {
                if current_level.abs_diff(new_level) != step_size {
                    let new_step_size = current_level.abs_diff(new_level);
                    val.mul(new_step_size as u16).div_euclid(step_size as u16)
                } else {
                    val
                }
            }
            None => 0,
        };

        // This will run some extra unnecessary checks, they will all pass, but benefits
        // of code reuse and a single source of truth for this logic outweigh the minor
        // performance cost of a few extra checks.
        self.move_to_level(
            with_on_off,
            new_level,
            Some(transition_time),
            options_mask,
            options_override,
            false,
        )
    }

    /// Stops any ongoing transitions and resets the remaining time.
    fn stop(
        &self,
        ctx: impl HandlerContext,
        with_on_off: bool,
        options_mask: OptionsBitmap,
        options_override: OptionsBitmap,
    ) -> Result<(), Error> {
        if !self.should_continue(with_on_off, options_mask, options_override)? {
            return Ok(());
        }
        self.task_signal.signal(Task::Stop);
        if self
            .with_state(|state| state.write_remaining_time_quietly(Duration::from_millis(0), false))
        {
            ctx.notify_attr_changed(
                self.endpoint_id,
                Self::CLUSTER.id,
                AttributeId::RemainingTime as _,
            );
        }

        Ok(())
    }

    fn handle_out_of_band_message(&self, ctx: impl HandlerContext, message: OutOfBandMessage) {
        self.with_state(|state| {
            match message {
                OutOfBandMessage::Update(current_level) => {
                    self.task_signal.signal(Task::Stop);

                    // OOB "device level changed under us" — genuine
                    // drift, never a scene apply.
                    match self.set_level(state, current_level, true, false, false) {
                        Ok((_, should_notify)) => {
                            if should_notify
                                || state.write_remaining_time_quietly(Duration::from_millis(0), false)
                            {
                                ctx.notify_attr_changed(
                                    self.endpoint_id,
                                    Self::CLUSTER.id,
                                    AttributeId::CurrentLevel as _,
                                );
                            }
                        }
                        Err(e) => {
                            error!("OutOfBandMessage::Update failed: set_level failed unexpectedly with set_device == false: {}", e);
                        }
                    }
                }
                OutOfBandMessage::MoveToLevel {
                    with_on_off,
                    level,
                    transition_time,
                    options_mask,
                    options_override,
                } => {
                    if let Err(e) = self.move_to_level(
                        with_on_off,
                        level,
                        transition_time,
                        options_mask,
                        options_override,
                        false,
                    ) {
                        error!(
                            "Device initiated MoveToLevel failed: {} | with_on_off: {}, level: {}, transition_time: {:?}, options_mask: {:?}, options_override: {:?}",
                            e, with_on_off, level, transition_time, options_mask, options_override
                        );
                    }
                }
                OutOfBandMessage::Move {
                    with_on_off,
                    move_mode,
                    rate,
                    options_mask,
                    options_override,
                } => {
                    if let Err(e) =
                        self.move_command(state, with_on_off, move_mode, rate, options_mask, options_override)
                    {
                        error!(
                            "Device initiated Move failed: {} | with_on_off: {}, move_mode: {:?}, rate: {:?}, options_mask: {:?}, options_override: {:?}",
                            e, with_on_off, move_mode, rate, options_mask, options_override
                        );
                    }
                }
                OutOfBandMessage::Step {
                    with_on_off,
                    step_mode,
                    step_size,
                    transition_time,
                    options_mask,
                    options_override,
                } => {
                    if let Err(e) = self.step(
                        with_on_off,
                        step_mode,
                        step_size,
                        transition_time,
                        options_mask,
                        options_override,
                    ) {
                        error!(
                            "Device initiated Step failed: {} | with_on_off: {}, step_mode: {:?}, step_size: {}, transition_time: {:?}, options_mask: {:?}, options_override: {:?}",
                            e, with_on_off, step_mode, step_size, transition_time, options_mask, options_override
                        );
                    }
                }
                OutOfBandMessage::Stop => {
                    self.task_signal.signal(Task::Stop);
                    if state.write_remaining_time_quietly(Duration::from_millis(0), false) {
                        ctx.notify_attr_changed(
                            self.endpoint_id,
                            Self::CLUSTER.id,
                            AttributeId::RemainingTime as _,
                        );
                    }
                }
            }
        })
    }
}

impl<H: LevelControlHooks, OH: OnOffHooks> ClusterAsyncHandler for LevelControlHandler<'_, H, OH> {
    const CLUSTER: Cluster<'static> = H::CLUSTER;

    // Runs an async task manager for the cluster handler.
    async fn run(&self, ctx: impl HandlerContext) -> Result<(), Error> {
        let mut hooks_fut = pin!(self
            .hooks
            .run(|message| self.handle_out_of_band_message(&ctx, message)));

        loop {
            let mut task = match select(
                &mut hooks_fut,
                self.task_signal.wait_signalled(),
            ).await {
                Either::First(_) => panic!("LevelControlHooks::run returned; implementers MUST not return. Implementations should loop forever or await core::future::pending::<()>()."),
                Either::Second(task) => task,
            };

            loop {
                match select3(
                    &mut hooks_fut,
                    self.task_manager(&ctx, task),
                    self.task_signal.wait_signalled(),
                )
                .await
                {
                    Either3::First(_) => panic!("LevelControlHooks::run returned; implementers MUST not return. Implementations should loop forever or await core::future::pending::<()>()."),
                    Either3::Second(_) => break,
                    Either3::Third(new_task) => task = new_task,
                };
            }
        }
    }

    fn dataver(&self) -> u32 {
        self.dataver.get()
    }

    fn dataver_changed(&self) {
        self.dataver.changed();
    }

    fn current_level(
        &self,
        _ctx: impl ReadContext,
    ) -> impl Future<Output = Result<Nullable<u8>, Error>> {
        ready(match self.hooks.current_level() {
            Some(level) => Ok(Nullable::some(level)),
            None => Ok(Nullable::none()),
        })
    }

    fn on_level(
        &self,
        _ctx: impl ReadContext,
    ) -> impl Future<Output = Result<Nullable<u8>, Error>> {
        ready(Ok(self.with_state(|state| state.on_level.clone())))
    }

    fn set_on_level(
        &self,
        ctx: impl WriteContext,
        value: Nullable<u8>,
    ) -> impl Future<Output = Result<(), Error>> {
        ready('a: {
            if let Some(level) = value.clone().into_option() {
                if level > H::MAX_LEVEL || level < H::MIN_LEVEL {
                    break 'a Err(ErrorCode::ConstraintError.into());
                }
            }

            self.with_state_notify(ctx, |state| {
                state.on_level = value;
            });

            Ok(())
        })
    }

    fn options(
        &self,
        _ctx: impl ReadContext,
    ) -> impl Future<Output = Result<OptionsBitmap, Error>> {
        ready(Ok(self.with_state(|state| state.options)))
    }

    fn set_options(
        &self,
        ctx: impl WriteContext,
        value: OptionsBitmap,
    ) -> impl Future<Output = Result<(), Error>> {
        ready({
            self.with_state_notify(ctx, |state| {
                state.options = value;
            });

            Ok(())
        })
    }

    fn remaining_time(&self, _ctx: impl ReadContext) -> impl Future<Output = Result<u16, Error>> {
        ready(Ok(self.with_state(|state| state.remaining_time)))
    }

    fn max_level(&self, _ctx: impl ReadContext) -> impl Future<Output = Result<u8, Error>> {
        ready(Ok(H::MAX_LEVEL))
    }

    fn min_level(&self, _ctx: impl ReadContext) -> impl Future<Output = Result<u8, Error>> {
        ready(Ok(H::MIN_LEVEL))
    }

    fn on_off_transition_time(
        &self,
        _ctx: impl ReadContext,
    ) -> impl Future<Output = Result<u16, Error>> {
        ready(Ok(self.with_state(|state| state.on_off_transition_time)))
    }

    fn set_on_off_transition_time(
        &self,
        ctx: impl WriteContext,
        value: u16,
    ) -> impl Future<Output = Result<(), Error>> {
        ready({
            self.with_state_notify(ctx, |state| {
                state.on_off_transition_time = value;
            });

            Ok(())
        })
    }

    fn on_transition_time(
        &self,
        _ctx: impl ReadContext,
    ) -> impl Future<Output = Result<Nullable<u16>, Error>> {
        ready(Ok(self.with_state(|state| state.on_transition_time.clone())))
    }

    fn set_on_transition_time(
        &self,
        ctx: impl WriteContext,
        value: Nullable<u16>,
    ) -> impl Future<Output = Result<(), Error>> {
        ready({
            self.with_state_notify(ctx, |state| {
                state.on_transition_time = value;
            });

            Ok(())
        })
    }

    fn off_transition_time(
        &self,
        _ctx: impl ReadContext,
    ) -> impl Future<Output = Result<Nullable<u16>, Error>> {
        ready(Ok(
            self.with_state(|state| state.off_transition_time.clone())
        ))
    }

    fn set_off_transition_time(
        &self,
        ctx: impl WriteContext,
        value: Nullable<u16>,
    ) -> impl Future<Output = Result<(), Error>> {
        ready({
            self.with_state_notify(ctx, |state| {
                state.off_transition_time = value;
            });

            Ok(())
        })
    }

    fn default_move_rate(
        &self,
        _ctx: impl ReadContext,
    ) -> impl Future<Output = Result<Nullable<u8>, Error>> {
        ready(Ok(self.with_state(|state| state.default_move_rate.clone())))
    }

    fn set_default_move_rate(
        &self,
        ctx: impl WriteContext,
        value: Nullable<u8>,
    ) -> impl Future<Output = Result<(), Error>> {
        ready('a: {
            // The spec is not explicit about what should be done if this happens.
            // For now we error out if DefaultMoveRate is equal to 0 as this is invalid
            // until spec defines a behaviour.
            if Some(0) == value.clone().into_option() {
                break 'a Err(ErrorCode::InvalidData.into());
            }

            self.with_state_notify(ctx, |state| {
                state.default_move_rate = value;
            });

            Ok(())
        })
    }

    fn start_up_current_level(
        &self,
        _ctx: impl ReadContext,
    ) -> impl Future<Output = Result<Nullable<u8>, Error>> {
        ready(match self.hooks.start_up_current_level() {
            Ok(Some(val)) => Ok(Nullable::some(val)),
            Ok(None) => Ok(Nullable::none()),
            Err(e) => Err(e),
        })
    }

    fn set_start_up_current_level(
        &self,
        ctx: impl WriteContext,
        value: Nullable<u8>,
    ) -> impl Future<Output = Result<(), Error>> {
        ready('a: {
            // According to the current spec, this attribute does not have any constraints at this stage.
            // However, it's usage is bounded by min/max hence it makes sense to restrict the settable values to this range.
            if let Some(level) = value.clone().into_option() {
                if level > H::MAX_LEVEL || level < H::MIN_LEVEL {
                    break 'a Err(ErrorCode::ConstraintError.into());
                }
            }

            match self.hooks.set_start_up_current_level(value.into_option()) {
                Ok(()) => {
                    ctx.notify_changed();
                    Ok(())
                }
                Err(e) => Err(e),
            }
        })
    }

    fn handle_move_to_level(
        &self,
        _ctx: impl InvokeContext,
        request: MoveToLevelRequest<'_>,
    ) -> impl Future<Output = Result<(), Error>> {
        ready('a: {
            let level = match request.level() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            let transition_time = match request.transition_time() {
                Ok(v) => v.into_option(),
                Err(e) => break 'a Err(e),
            };
            let options_mask = match request.options_mask() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            let options_override = match request.options_override() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            self.move_to_level(
                false,
                level,
                transition_time,
                options_mask,
                options_override,
                false,
            )
        })
    }

    fn handle_move(
        &self,
        _ctx: impl InvokeContext,
        request: MoveRequest<'_>,
    ) -> impl Future<Output = Result<(), Error>> {
        ready(self.with_state(|state| {
            self.move_command(
                state,
                false,
                request.move_mode()?,
                request.rate()?.into_option(),
                request.options_mask()?,
                request.options_override()?,
            )
        }))
    }

    fn handle_step(
        &self,
        _ctx: impl InvokeContext,
        request: StepRequest<'_>,
    ) -> impl Future<Output = Result<(), Error>> {
        ready('a: {
            let step_mode = match request.step_mode() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            let step_size = match request.step_size() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            let transition_time = match request.transition_time() {
                Ok(v) => v.into_option(),
                Err(e) => break 'a Err(e),
            };
            let options_mask = match request.options_mask() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            let options_override = match request.options_override() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            self.step(
                false,
                step_mode,
                step_size,
                transition_time,
                options_mask,
                options_override,
            )
        })
    }

    fn handle_stop(
        &self,
        ctx: impl InvokeContext,
        request: StopRequest<'_>,
    ) -> impl Future<Output = Result<(), Error>> {
        ready('a: {
            let options_mask = match request.options_mask() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            let options_override = match request.options_override() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            self.stop(&ctx, false, options_mask, options_override)
        })
    }

    fn handle_move_to_level_with_on_off(
        &self,
        _ctx: impl InvokeContext,
        request: MoveToLevelWithOnOffRequest<'_>,
    ) -> impl Future<Output = Result<(), Error>> {
        ready('a: {
            let level = match request.level() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            let transition_time = match request.transition_time() {
                Ok(v) => v.into_option(),
                Err(e) => break 'a Err(e),
            };
            let options_mask = match request.options_mask() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            let options_override = match request.options_override() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            self.move_to_level(
                true,
                level,
                transition_time,
                options_mask,
                options_override,
                false,
            )
        })
    }

    fn handle_move_with_on_off(
        &self,
        _ctx: impl InvokeContext,
        request: MoveWithOnOffRequest<'_>,
    ) -> impl Future<Output = Result<(), Error>> {
        ready(self.with_state(|state| {
            self.move_command(
                state,
                true,
                request.move_mode()?,
                request.rate()?.into_option(),
                request.options_mask()?,
                request.options_override()?,
            )
        }))
    }

    fn handle_step_with_on_off(
        &self,
        _ctx: impl InvokeContext,
        request: StepWithOnOffRequest<'_>,
    ) -> impl Future<Output = Result<(), Error>> {
        ready('a: {
            let step_mode = match request.step_mode() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            let step_size = match request.step_size() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            let transition_time = match request.transition_time() {
                Ok(v) => v.into_option(),
                Err(e) => break 'a Err(e),
            };
            let options_mask = match request.options_mask() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            let options_override = match request.options_override() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            self.step(
                true,
                step_mode,
                step_size,
                transition_time,
                options_mask,
                options_override,
            )
        })
    }

    fn handle_stop_with_on_off(
        &self,
        ctx: impl InvokeContext,
        request: StopWithOnOffRequest<'_>,
    ) -> impl Future<Output = Result<(), Error>> {
        ready('a: {
            let options_mask = match request.options_mask() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            let options_override = match request.options_override() {
                Ok(v) => v,
                Err(e) => break 'a Err(e),
            };
            self.stop(&ctx, true, options_mask, options_override)
        })
    }

    fn handle_move_to_closest_frequency(
        &self,
        _ctx: impl InvokeContext,
        _request: MoveToClosestFrequencyRequest<'_>,
    ) -> impl Future<Output = Result<(), Error>> {
        ready(Err(ErrorCode::InvalidCommand.into()))
    }
}

pub trait LevelControlHooks {
    const MIN_LEVEL: u8;
    const MAX_LEVEL: u8;
    const FASTEST_RATE: u8;
    const CLUSTER: Cluster<'static>;

    /// Implements the business logic for setting the level of the device.
    /// Returns the level the device was set to.
    /// If this method returns Err, the `LevelControlHandler` will represent this as an error with `ImStatusCode` of `Failure`.
    /// Note: The above is the only responsibility of this method. There is no need to update Matter attributes.
    #[allow(clippy::result_unit_err)]
    fn set_device_level(&self, level: u8) -> Result<Option<u8>, ()>;

    // Raw accessors
    //  These methods should not perform any checks.
    //  They should simply get or set values.
    //  They should not error.

    /// Raw current_level getter.
    /// This value should persist across reboots.
    fn current_level(&self) -> Option<u8>;

    /// Raw current_level setter.
    /// This value should persist across reboots.
    fn set_current_level(&self, level: Option<u8>);

    /// Raw start_up_current_level getter.
    /// This value should persist across reboots.
    fn start_up_current_level(&self) -> Result<Option<u8>, Error> {
        Err(ErrorCode::AttributeNotFound.into())
    }
    /// Raw start_up_current_level setter.
    /// This value should persist across reboots.
    fn set_start_up_current_level(&self, _value: Option<u8>) -> Result<(), Error> {
        Err(ErrorCode::AttributeNotFound.into())
    }

    /// Background task for out-of-band notifications to the handler.
    ///
    /// This future MUST NOT return. Implementers should either loop forever or await
    /// core::future::pending::<()>(), so the SDK's task does not observe a completed future.
    ///
    /// # Panics
    /// The SDK will panic if this method returns.
    fn run<F: Fn(OutOfBandMessage)>(&self, _notify: F) -> impl Future<Output = ()> {
        pending::<()>()
    }
}

impl<T> LevelControlHooks for &T
where
    T: LevelControlHooks,
{
    const MIN_LEVEL: u8 = T::MIN_LEVEL;
    const MAX_LEVEL: u8 = T::MAX_LEVEL;
    const FASTEST_RATE: u8 = T::FASTEST_RATE;
    const CLUSTER: Cluster<'static> = T::CLUSTER;

    fn set_device_level(&self, level: u8) -> Result<Option<u8>, ()> {
        (*self).set_device_level(level)
    }

    fn current_level(&self) -> Option<u8> {
        (*self).current_level()
    }

    fn set_current_level(&self, level: Option<u8>) {
        (*self).set_current_level(level)
    }

    fn start_up_current_level(&self) -> Result<Option<u8>, Error> {
        (*self).start_up_current_level()
    }

    fn set_start_up_current_level(&self, value: Option<u8>) -> Result<(), Error> {
        (*self).set_start_up_current_level(value)
    }

    fn run<F: Fn(OutOfBandMessage)>(&self, notify: F) -> impl Future<Output = ()> {
        (*self).run(notify)
    }
}

/// This is a phantom type for when the LevelControl cluster is not coupled with an OnOff cluster.
/// This type should only be used for annotations and not for actual OnOff functionality.
/// All methods will panic.
pub struct NoOnOff;

impl OnOffHooks for NoOnOff {
    const CLUSTER: Cluster<'static> = ON_OFF_FULL_CLUSTER;

    fn on_off(&self) -> bool {
        panic!("NoOnOff: on_off called unexpectedly - this phantom type should not be used for OnOff functionality")
    }

    fn set_on_off(&self, _on: bool) {
        panic!("NoOnOff: set_on_off called unexpectedly - this phantom type should not be used for OnOff functionality")
    }

    fn start_up_on_off(&self) -> Nullable<super::on_off::StartUpOnOffEnum> {
        panic!("NoOnOff: start_up_on_off called unexpectedly - this phantom type should not be used for OnOff functionality")
    }

    fn set_start_up_on_off(
        &self,
        _value: Nullable<super::on_off::StartUpOnOffEnum>,
    ) -> Result<(), Error> {
        panic!("NoOnOff: set_start_up_on_off called unexpectedly - this method should not be called when LevelControl is not coupled with OnOff")
    }

    async fn handle_off_with_effect(&self, _effect: super::on_off::EffectVariantEnum) {
        panic!("NoOnOff: handle_off_with_effect called unexpectedly - this phantom type should not be used for OnOff functionality")
    }
}

/// Scenes Management integration for the LevelControl cluster. The
/// only scenable attribute is `CurrentLevel`; apply routes through
/// `MoveToLevel` with the scene's transition time.
impl<H, OH> SceneClusterHandler for LevelControlHandler<'_, H, OH>
where
    H: LevelControlHooks,
    OH: OnOffHooks,
{
    const CLUSTER_ID: ClusterId = FULL_CLUSTER.id;

    fn endpoint_id(&self) -> EndptId {
        self.endpoint_id
    }

    fn is_scenable_attribute(attribute_id: AttrId) -> bool {
        attribute_id == AttributeId::CurrentLevel as AttrId
    }

    fn capture<P: TLVBuilderParent>(
        &self,
        avp_array: AttributeValuePairStructArrayBuilder<P>,
    ) -> Result<AttributeValuePairStructArrayBuilder<P>, Error> {
        // `CurrentLevel` is nullable; null → skip the AVP entry.
        if let Some(level) = self.hooks.current_level() {
            avp_array.push_u8(AttributeId::CurrentLevel as _, level)
        } else {
            Ok(avp_array)
        }
    }

    async fn apply<C: HandlerContext>(
        &self,
        _ctx: &C,
        avp_list: &TLVArray<'_, AttributeValuePairStruct<'_>>,
        transition_time_ms: u32,
    ) -> Result<(), Error> {
        for avp in avp_list.iter() {
            let avp = avp?;
            if avp.attribute_id()? != AttributeId::CurrentLevel as _ {
                continue;
            }
            let Some(level) = avp.value_unsigned_8()? else {
                continue;
            };
            // Reuse the command-driven `MoveToLevel` pipeline with
            // `scene_apply=true` (suppresses `SceneValid` drift on
            // every step) and `with_on_off=false` (OnOff lands its own
            // AVP via `OnOffHandler::apply`). RecallScene transition
            // time is ms; MoveToLevel is deciseconds — convert with
            // saturation.
            let transition_ds = (transition_time_ms / 100).min(u16::MAX as u32) as u16;
            return self.move_to_level(
                false,
                level,
                Some(transition_ds),
                OptionsBitmap::empty(),
                OptionsBitmap::empty(),
                true,
            );
        }
        Ok(())
    }
}

pub mod test {
    use crate::dm::clusters::app::level_control::{
        AttributeId, CommandId, Feature, LevelControlHooks, FULL_CLUSTER,
    };
    use crate::dm::Cluster;
    use crate::error::Error;
    use crate::utils::cell::RefCell;
    use crate::utils::sync::blocking::Mutex;
    use crate::with;

    struct TestLevelControlState {
        current_level: Option<u8>,
        start_up_current_level: Option<u8>,
    }

    impl TestLevelControlState {
        const fn new() -> Self {
            Self {
                current_level: Some(1),
                start_up_current_level: None,
            }
        }
    }

    pub struct TestLevelControlDeviceLogic {
        state: Mutex<RefCell<TestLevelControlState>>,
    }

    impl TestLevelControlDeviceLogic {
        pub const fn new() -> Self {
            Self {
                state: Mutex::new(RefCell::new(TestLevelControlState::new())),
            }
        }
    }

    impl Default for TestLevelControlDeviceLogic {
        fn default() -> Self {
            Self::new()
        }
    }

    impl LevelControlHooks for TestLevelControlDeviceLogic {
        const MIN_LEVEL: u8 = 1;
        const MAX_LEVEL: u8 = 254;
        const FASTEST_RATE: u8 = 50;
        const CLUSTER: Cluster<'static> = FULL_CLUSTER
            .with_revision(6)
            .with_features(Feature::ON_OFF.bits())
            .with_attrs(with!(
                required;
                AttributeId::CurrentLevel
                | AttributeId::MinLevel
                | AttributeId::MaxLevel
                | AttributeId::OnLevel
                | AttributeId::Options
            ))
            .with_cmds(with!(
                CommandId::MoveToLevel
                    | CommandId::Move
                    | CommandId::Step
                    | CommandId::Stop
                    | CommandId::MoveToLevelWithOnOff
                    | CommandId::MoveWithOnOff
                    | CommandId::StepWithOnOff
                    | CommandId::StopWithOnOff
            ));

        fn set_device_level(&self, level: u8) -> Result<Option<u8>, ()> {
            // This is where business logic is implemented to physically change the level of the device.
            Ok(Some(level))
        }

        fn current_level(&self) -> Option<u8> {
            self.state.lock(|state| state.borrow().current_level)
        }

        fn set_current_level(&self, level: Option<u8>) {
            info!(
                "LevelControlDeviceLogic::set_current_level: setting level to {:?}",
                level
            );
            self.state
                .lock(|state| state.borrow_mut().current_level = level);
        }

        fn start_up_current_level(&self) -> Result<Option<u8>, Error> {
            Ok(self
                .state
                .lock(|state| state.borrow().start_up_current_level))
        }

        fn set_start_up_current_level(&self, value: Option<u8>) -> Result<(), Error> {
            self.state
                .lock(|state| state.borrow_mut().start_up_current_level = value);
            Ok(())
        }
    }
}

#[cfg(test)]
mod tests {
    use super::test::TestLevelControlDeviceLogic;
    use super::{AttributeDefaults, LevelControlHandler};
    use crate::dm::clusters::app::on_off::test::TestOnOffDeviceLogic;
    use crate::dm::clusters::app::on_off::OnOffHandler;
    use crate::dm::Dataver;

    /// Catches drift between `TestLevelControlDeviceLogic::CLUSTER` and
    /// `LevelControlHandler::validate()`.
    #[test]
    fn test_logic_passes_handler_validate() {
        let level_logic = TestLevelControlDeviceLogic::new();
        let on_off_logic = TestOnOffDeviceLogic::new(false);
        let level = LevelControlHandler::new(
            Dataver::new(1),
            1,
            &level_logic,
            AttributeDefaults::default(),
        );
        let on_off = OnOffHandler::new(Dataver::new(2), 1, &on_off_logic);
        on_off.init(Some(&level));
        level.init(Some(&on_off));
    }
}