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
/*
 *
 *    Copyright (c) 2022-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.
 */

//! The Interaction Model as defined by the Matter Core spec: the interactions
//! (Read, Subscribe/Report, Write, Invoke, Timed) and their TLV-serde encoding
//! types, plus the engine - [`InteractionModel`] - that drives those
//! interactions against a [`crate::dm`] data model.
//!
//! It also contains a requestor-side IM client ([`client`]) and a very simple
//! responder - [`busy`] - which always returns a busy status code to all
//! incoming IM requests.

use core::num::NonZeroU8;
use core::pin::pin;

use embassy_futures::select::{select3, select4};
use embassy_time::{Instant, Timer};

use crate::acl::Accessor;
use crate::crypto::Crypto;
use crate::dm::clusters::net_comm::{
    NetCtl, NetworkType, Networks, NetworksAccess, SharedNetworks,
};
use crate::dm::clusters::wifi_diag::WirelessDiag;
use crate::dm::networks::eth::EthNetwork;
use crate::dm::networks::wireless::{NoopWirelessNetCtl, WirelessMgr, MAX_CREDS_SIZE};
use crate::dm::networks::NetChangeNotif;
use crate::dm::{
    AsyncHandler, AttrChangeNotifier, AttrDetails, Attribute, DataModel, EventEmitter,
    HandlerContext, MatchContextInstance, Metadata,
};
use crate::error::{Error, ErrorCode};
use crate::im::events::{EventReader, EventTLVWrite, Events, DEFAULT_MAX_EVENTS_BUF_SIZE};
use crate::im::invoker::HandlerInvoker;
use crate::im::subscriptions::{
    ReportContext, Subscriptions, SubscriptionsBuffers, DEFAULT_MAX_SUBSCRIPTIONS,
};
use crate::persist::{KvBlobStoreAccess, NETWORKS_KEY};
use crate::respond::ExchangeHandler;
use crate::tlv::{get_root_node_struct, FromTLV, Nullable, TLVElement, TLVTag, TLVWrite, ToTLV};
use crate::transport::exchange::{Exchange, ExchangeId, MAX_EXCHANGE_TX_BUF_SIZE};
use crate::utils::init::{init, Init};
use crate::utils::select::Coalesce;
use crate::utils::storage::pooled::Buffers;
use crate::utils::storage::WriteBuf;
use crate::Matter;

pub use encoding::*;
pub use expand::{expand_invoke, expand_read, expand_write};

pub mod busy;
pub mod client;
pub mod encoding;
pub mod events;
pub mod expand;
pub mod invoker;
pub mod subscriptions;

/// An `ExchangeHandler` implementation capable of handling responder exchanges for the Interaction Model protocol.
/// The mutable, owned-together state a [`InteractionModel`] operates on: the
/// subscriptions table, the events queue and the network store.
///
/// Allocating these as a single value (rather than three separate locals wired
/// up by hand at every call site) is the whole point: construct one
/// `InteractionModelState`, then hand a reference to it to [`InteractionModel::new`]. Each of
/// the three pieces keeps its own lock internally (the proven multi-lock model);
/// folding them behind a single mutex is a possible later refinement.
///
/// `N` is the (raw) [`Networks`] implementation — e.g.
/// [`EthNetwork`](crate::dm::networks::eth::EthNetwork) or
/// [`WirelessNetworks`](crate::dm::networks::wireless::WirelessNetworks); it is
/// wrapped internally in a [`SharedNetworks`] so the data model and (later) the
/// wireless manager can share it. `NS`/`NE` bound the subscription table and the
/// event-buffer size and default to [`DEFAULT_MAX_SUBSCRIPTIONS`] /
/// [`DEFAULT_MAX_EVENTS_BUF_SIZE`].
pub struct InteractionModelState<
    N,
    const NS: usize = DEFAULT_MAX_SUBSCRIPTIONS,
    const NE: usize = DEFAULT_MAX_EVENTS_BUF_SIZE,
> {
    subscriptions: Subscriptions<NS>,
    events: Events<NE>,
    networks: SharedNetworks<N>,
}

impl<N, const NS: usize, const NE: usize> InteractionModelState<N, NS, NE> {
    /// Create a new state instance backed by the given (raw) [`Networks`] store.
    pub const fn new(networks: N) -> Self {
        Self {
            subscriptions: Subscriptions::new(),
            events: Events::new(),
            networks: SharedNetworks::new(networks),
        }
    }

    /// Return an in-place initializer for the state (for large `NE`, to
    /// avoid a big temporary on the stack).
    pub fn init(networks: impl Init<N>) -> impl Init<Self> {
        init!(Self {
            subscriptions <- Subscriptions::init(),
            events <- Events::init(),
            networks <- SharedNetworks::init(networks),
        })
    }

    /// Reset this state's persisted contents to factory defaults - the
    /// events-queue epoch and the network store - removing both from `kv` using
    /// the scratch buffer provided by `kv`. Call once during a factory reset,
    /// with exclusive (`&mut`) access (i.e. before the state is shared with a
    /// [`InteractionModel`]).
    pub async fn reset_persist<K>(&mut self, kv: K) -> Result<(), Error>
    where
        K: KvBlobStoreAccess,
        N: Networks,
    {
        // We hold `&mut self`, so borrow the pieces directly - no locking.
        let Self {
            events, networks, ..
        } = self;

        let events = events.inner_mut();
        let networks = networks.get_mut().get_mut();

        kv.access(|store, buf| {
            // The event-number epoch.
            events.reset_persist(&mut *store, buf)?;

            // The network store.
            networks.reset()?;
            store.remove(NETWORKS_KEY, buf)?;

            Ok(())
        })
    }

    /// Re-hydrate this state's persisted contents - the events-queue epoch (so
    /// event numbers are not reused across reboots) and the network store - using
    /// the scratch buffer provided by `kv`. Call once at startup, before the
    /// state is shared with a [`InteractionModel`].
    pub async fn load_persist<K>(&mut self, kv: K) -> Result<(), Error>
    where
        K: KvBlobStoreAccess,
        N: Networks,
    {
        // We hold `&mut self`, so borrow the pieces directly - no locking
        // (the inner mutexes are only needed for shared, runtime access).
        let Self {
            events, networks, ..
        } = self;

        let events = events.inner_mut();
        let networks = networks.get_mut().get_mut();

        // The KV ops are sync, so do them all inside a single `access` closure.
        kv.access(|store, buf| {
            // The event-number epoch.
            events.load_persist(&mut *store, buf)?;

            // The network store.
            networks.reset()?;
            if let Some(data) = store.load(NETWORKS_KEY, buf)? {
                networks.load(data)?;
            }

            Ok(())
        })
    }

    /// The subscriptions table.
    pub const fn subscriptions(&self) -> &Subscriptions<NS> {
        &self.subscriptions
    }

    /// The events queue.
    pub const fn events(&self) -> &Events<NE> {
        &self.events
    }

    /// The network store (wrapped for shared, change-notifying access).
    pub const fn networks(&self) -> &SharedNetworks<N> {
        &self.networks
    }
}

/// The implementation needs a `DataModel` instance to interact with the underlying clusters of the data model.
///
/// `NC` is the network controller type driving the (optional) wireless connection
/// manager from [`InteractionModel::run`]. It defaults to [`NoopWirelessNetCtl`], which is
/// the right choice for Ethernet (and what the convenience [`InteractionModel::new`]
/// constructor wires up); wireless devices pass a real controller via
/// [`InteractionModel::new_with_net_ctl`].
pub struct InteractionModel<
    'a,
    C,
    B,
    T,
    K,
    N,
    NC = NoopWirelessNetCtl,
    const NS: usize = DEFAULT_MAX_SUBSCRIPTIONS,
    const NE: usize = DEFAULT_MAX_EVENTS_BUF_SIZE,
> where
    B: Buffers<IMBuffer>,
{
    matter: &'a Matter<'a>,
    crypto: C,
    buffers: &'a B,
    kv: K,
    net_ctl: NC,
    subscriptions_buffers: SubscriptionsBuffers<'a, B, NS>,
    state: &'a InteractionModelState<N, NS, NE>,
    handler: T,
}

/// A [`InteractionModelState`] for an Ethernet device: its network store is a fixed
/// [`EthNetwork`], so call sites need only the (defaulted) subscription/event
/// sizes. Pairs with [`EthInteractionModel`].
pub type EthInteractionModelState<
    const NS: usize = DEFAULT_MAX_SUBSCRIPTIONS,
    const NE: usize = DEFAULT_MAX_EVENTS_BUF_SIZE,
> = InteractionModelState<EthNetwork<'static>, NS, NE>;

/// A [`InteractionModel`] for an Ethernet device (network store fixed to [`EthNetwork`]),
/// so the `N` generic disappears from call sites. Pairs with [`EthInteractionModelState`].
pub type EthInteractionModel<
    'a,
    C,
    B,
    T,
    K,
    NC = NoopWirelessNetCtl,
    const NS: usize = DEFAULT_MAX_SUBSCRIPTIONS,
    const NE: usize = DEFAULT_MAX_EVENTS_BUF_SIZE,
> = InteractionModel<'a, C, B, T, K, EthNetwork<'static>, NC, NS, NE>;

/// A [`InteractionModelState`] for a wireless device, parameterized by the concrete
/// wireless network store `N` (e.g. `WifiNetworks<3>` or a Thread store). Pairs
/// with [`WirelessInteractionModel`].
pub type WirelessInteractionModelState<
    N,
    const NS: usize = DEFAULT_MAX_SUBSCRIPTIONS,
    const NE: usize = DEFAULT_MAX_EVENTS_BUF_SIZE,
> = InteractionModelState<N, NS, NE>;

/// A [`InteractionModel`] for a wireless device (network store `N`, network controller
/// `NC`). Pairs with [`WirelessInteractionModelState`].
pub type WirelessInteractionModel<
    'a,
    C,
    B,
    T,
    K,
    N,
    NC,
    const NS: usize = DEFAULT_MAX_SUBSCRIPTIONS,
    const NE: usize = DEFAULT_MAX_EVENTS_BUF_SIZE,
> = InteractionModel<'a, C, B, T, K, N, NC, NS, NE>;

impl<'a, C, B, T, K, N, const NS: usize, const NE: usize>
    InteractionModel<'a, C, B, T, K, N, NoopWirelessNetCtl, NS, NE>
where
    C: Crypto,
    B: Buffers<IMBuffer>,
    T: DataModel,
    K: KvBlobStoreAccess,
    N: Networks,
{
    /// Create the data model for a device that does not need an operational
    /// wireless connection manager (typically an Ethernet device).
    ///
    /// This is a convenience wrapper around [`InteractionModel::new_with_net_ctl`] that
    /// fixes the network controller to an inert [`NoopWirelessNetCtl`], so
    /// [`InteractionModel::run`]'s connection-management branch stays dormant.
    ///
    /// # Arguments
    /// - `matter` - a reference to the `Matter` instance
    /// - `buffers` - a reference to an implementation of `Buffers<IMBuffer>` which is used for allocating RX and TX buffers on the fly, when necessary
    /// - `handler` - an instance of type `T` which implements the `DataModel` trait. This instance is used for interacting with the underlying
    ///   clusters of the data model. Note that the expectations is for the user to provide a handler that handles the Matter system clusters
    ///   as well (Endpoint 0), possibly by decorating her own clusters with the `rs_matter::dm::root_endpoint::with_` methods
    /// - `kv` - an instance of type `K` which implements the `KvBlobStoreAccess` trait
    ///   (obtain one via [`Matter::kv`]). This instance is used for interacting with the key-value blob store.
    /// - `state` - a reference to the [`InteractionModelState`] holding the subscriptions table, the
    ///   events queue and the network store (the latter parameterized by the `Networks`
    ///   implementation `N`).
    #[inline(always)]
    pub fn new(
        matter: &'a Matter<'a>,
        crypto: C,
        buffers: &'a B,
        handler: T,
        kv: K,
        state: &'a InteractionModelState<N, NS, NE>,
    ) -> Self {
        Self::new_with_net_ctl(
            matter,
            crypto,
            buffers,
            handler,
            kv,
            NoopWirelessNetCtl::new(NetworkType::Ethernet),
            state,
        )
    }
}

impl<'a, C, B, T, K, N, NC, const NS: usize, const NE: usize>
    InteractionModel<'a, C, B, T, K, N, NC, NS, NE>
where
    C: Crypto,
    B: Buffers<IMBuffer>,
    T: DataModel,
    K: KvBlobStoreAccess,
    N: Networks,
{
    /// Create the data model with an explicit network controller `net_ctl`.
    ///
    /// Use this for wireless devices: `net_ctl` drives the operational connection
    /// manager run from [`InteractionModel::run`] (and is typically the same controller
    /// instance also wired into the `NetworkCommissioning` cluster handler). For
    /// Ethernet devices prefer the [`InteractionModel::new`] convenience constructor.
    ///
    /// # Arguments
    /// - `matter` - a reference to the `Matter` instance
    /// - `buffers` - a reference to an implementation of `Buffers<IMBuffer>` which is used for allocating RX and TX buffers on the fly, when necessary
    /// - `handler` - an instance of type `T` which implements the `DataModel` trait. This instance is used for interacting with the underlying
    ///   clusters of the data model. Note that the expectations is for the user to provide a handler that handles the Matter system clusters
    ///   as well (Endpoint 0), possibly by decorating her own clusters with the `rs_matter::dm::root_endpoint::with_` methods
    /// - `kv` - an instance of type `K` which implements the `KvBlobStoreAccess` trait
    ///   (obtain one via [`Matter::kv`]). This instance is used for interacting with the key-value blob store.
    /// - `net_ctl` - the network controller (`NetCtl` + `WirelessDiag` + `NetChangeNotif`) used by
    ///   the operational wireless connection manager driven from [`InteractionModel::run`].
    /// - `state` - a reference to the [`InteractionModelState`] holding the subscriptions table, the
    ///   events queue and the network store (the latter parameterized by the `Networks`
    ///   implementation `N`).
    #[inline(always)]
    pub fn new_with_net_ctl(
        matter: &'a Matter<'a>,
        crypto: C,
        buffers: &'a B,
        handler: T,
        kv: K,
        net_ctl: NC,
        state: &'a InteractionModelState<N, NS, NE>,
    ) -> Self {
        state.subscriptions.clear();

        Self {
            matter,
            crypto,
            buffers,
            kv,
            net_ctl,
            subscriptions_buffers: SubscriptionsBuffers::new(),
            state,
            handler,
        }
    }

    /// Get a reference to the `Matter` instance this data model is associated with.
    pub const fn matter(&self) -> &'a Matter<'a> {
        self.matter
    }

    pub const fn crypto(&self) -> &C {
        &self.crypto
    }

    /// Open the basic commissioning window.
    ///
    /// Equivalent to [`Matter::open_basic_comm_window`] but additionally
    /// bumps the data version of the `AdministratorCommissioning`
    /// cluster on the root endpoint and routes the change to
    /// subscribers — both happen automatically because this `InteractionModel`
    /// is itself the [`AttrChangeNotifier`] passed down.
    ///
    /// Prefer this entry point over the `Matter` one for any code path
    /// that has a `InteractionModel` available; `Matter::open_basic_comm_window`
    /// is the building block we delegate to and does not bump dataver
    /// (see its docs).
    pub fn open_basic_comm_window(&self, timeout_secs: u16) -> Result<(), Error> {
        self.matter
            .open_basic_comm_window(timeout_secs, &self.crypto, self)
    }

    /// Close the active commissioning window.
    ///
    /// Equivalent to [`Matter::close_comm_window`] but additionally
    /// bumps the `AdministratorCommissioning` dataver and routes
    /// subscribers via this `InteractionModel`'s [`AttrChangeNotifier`]. See
    /// `open_basic_comm_window` for the rationale.
    pub fn close_comm_window(&self) -> Result<bool, Error> {
        self.matter.close_comm_window(self)
    }

    /// Bump `BasicInformation::ConfigurationVersion` by one, persist
    /// the new value, and notify subscribers (which also bumps the
    /// `BasicInformation` cluster's dataver via this `InteractionModel`'s
    /// [`AttrChangeNotifier`]).
    ///
    /// Per Matter Core Spec, callers MUST invoke this
    /// whenever the node's exposed fixed-quality surface changes —
    /// typically after a firmware update that adds or removes
    /// functionality, after an internal reconfiguration that changes
    /// any `F`-quality attribute (Descriptor::ServerList,
    /// PartsList, …), or (for bridges) after a bridged node is added
    /// or removed. It is not invoked automatically by `rs-matter`
    /// because the library has no way to know about an application's
    /// reconfiguration events.
    ///
    /// Returns the new `ConfigurationVersion` value.
    pub fn bump_configuration_version(&self) -> Result<u32, Error> {
        // Delegate to `Matter::bump_configuration_version` for the
        // in-memory bump + persist; pass `self` as the
        // `AttrChangeNotifier` so the cluster's `Dataver` is bumped
        // too (the `Matter`-level call by itself only routes
        // subscribers and persists).
        self.matter.bump_configuration_version(&self.kv, self)
    }

    /// Run the Data Model instance.
    ///
    /// This drives the IM timeout checks, the data-model handler's own background
    /// job, the subscriptions reporting loop, and - for wireless devices - the
    /// operational connection manager (inert for Ethernet, where `net_ctl` is a
    /// [`NoopWirelessNetCtl`]).
    pub async fn run(&self) -> Result<(), Error>
    where
        NC: NetCtl + WirelessDiag + NetChangeNotif,
    {
        let mut timeouts = pin!(self.run_timeout_checks());
        let mut handler = pin!(self.handler.run(self));
        let mut subs = pin!(self.process_subscriptions(self.matter));
        let mut net = pin!(self.run_net_mgr());

        select4(&mut timeouts, &mut handler, &mut subs, &mut net)
            .coalesce()
            .await
    }

    /// Drive the operational wireless connection manager.
    ///
    /// For Ethernet devices (`net_ctl.net_type() == NetworkType::Ethernet`) there
    /// is nothing to manage, so this future simply pends forever. For wireless
    /// devices it runs a [`WirelessMgr`] over the network store, cycling through
    /// the registered networks and (re)connecting as needed once commissioned.
    async fn run_net_mgr(&self) -> Result<(), Error>
    where
        NC: NetCtl + WirelessDiag + NetChangeNotif,
    {
        if self.net_ctl.net_type() == NetworkType::Ethernet {
            // Nothing to manage for a wired device - just pend forever.
            return core::future::pending().await;
        }

        let mut buf = [0u8; MAX_CREDS_SIZE];
        let mut mgr = WirelessMgr::new(self.state.networks(), &self.net_ctl, &mut buf);

        mgr.run().await
    }

    /// Perform a single, one-shot connect to the wireless network with the given
    /// ID, immediately and regardless of the commissioning status.
    ///
    /// This drives the same [`WirelessMgr`] used by [`InteractionModel::run`]
    /// (over this model's network controller and the network store owned by its
    /// [`InteractionModelState`]), but calls [`WirelessMgr::connect_once`] rather
    /// than the operational loop. It exists so a stack performing **non-concurrent**
    /// (BLE-only) commissioning can replay the deferred `ConnectNetwork` once the
    /// operational radio is up but before commissioning completes - without having
    /// to own a `WirelessMgr` (or the networks) itself.
    pub async fn connect_once(&self, network_id: &[u8]) -> Result<(), Error>
    where
        NC: NetCtl + WirelessDiag + NetChangeNotif,
    {
        let mut buf = [0u8; MAX_CREDS_SIZE];
        let mut mgr = WirelessMgr::new(self.state.networks(), &self.net_ctl, &mut buf);

        mgr.connect_once(network_id).await
    }

    async fn run_timeout_checks(&self) -> Result<(), Error> {
        const CHECK_INTERVAL_SECS: u64 = 1;

        loop {
            Timer::after_secs(CHECK_INTERVAL_SECS).await;

            self.check_timeouts(None)?;
        }
    }

    fn check_timeouts(&self, exch_id: Option<ExchangeId>) -> Result<(), Error> {
        let mut notify_mdns = || self.matter.transport().notify_mdns_changed();
        let mut notify_change =
            |endpt_id, clust_id| self.notify_cluster_changed(endpt_id, clust_id);

        self.matter.with_state(|state| {
            let expire_sess_id = exch_id.and_then(|exch_id| {
                state
                    .sessions
                    .get(exch_id.session_id())
                    .map(|sess| sess.id())
            });

            // Disarm the failsafe on timeout
            state.failsafe.check_failsafe_timeout(
                &mut state.fabrics,
                &mut state.sessions,
                &self.state.networks,
                &self.kv,
                expire_sess_id,
                &mut notify_mdns,
                &mut notify_change,
            )?;

            // Close the commissioning window on timeout
            state
                .pase
                .check_comm_window_timeout(&mut notify_mdns, &mut notify_change)?;

            Ok(())
        })
    }

    /// Answer a responding exchange using the `DataModel` instance wrapped by this exchange handler.
    pub async fn handle(&self, exchange: &mut Exchange<'_>) -> Result<(), Error> {
        let fetch_meta = |exchange: &mut Exchange| {
            let meta = exchange.rx()?.meta();
            if meta.proto_id != PROTO_ID_INTERACTION_MODEL {
                Err(ErrorCode::InvalidProto)?;
            }

            Result::<_, Error>::Ok(meta)
        };

        if exchange.rx().is_err() {
            exchange.recv_fetch().await?;
        }

        let is_groupcast = exchange.is_groupcast()?;

        let mut meta = fetch_meta(exchange)?;

        let timeout_instant = if !is_groupcast && meta.opcode::<OpCode>()? == OpCode::TimedRequest {
            let timeout = self.timed(exchange).await?;

            exchange.recv_fetch().await?;
            meta = fetch_meta(exchange)?;

            Some(timeout)
        } else {
            None
        };

        self.check_timeouts(Some(exchange.id()))?;

        // TODO: Handle the cases where we receive a timeout request
        // before read and subscribe. This is probably not allowed.

        match meta.opcode::<OpCode>()? {
            OpCode::ReadRequest if is_groupcast => {
                error!("Received a groupcast message for opcode: ReadRequest")
            }
            OpCode::ReadRequest if !is_groupcast => self.read(exchange).await?,
            OpCode::WriteRequest => self.write(exchange, timeout_instant, is_groupcast).await?,
            OpCode::InvokeRequest => self.invoke(exchange, timeout_instant, is_groupcast).await?,
            OpCode::SubscribeRequest if is_groupcast => {
                error!("Received a groupcast message for opcode: SubscribeRequest")
            }
            OpCode::SubscribeRequest if !is_groupcast => self.subscribe(exchange).await?,
            OpCode::TimedRequest if !is_groupcast => {
                Self::send_status(exchange, IMStatusCode::InvalidAction).await?
            }
            _ if is_groupcast => {
                // Silently drop unsupported opcodes for group messages
            }
            opcode => {
                error!("Invalid opcode: {:?}", opcode);
                Err(ErrorCode::InvalidOpcode)?
            }
        }

        if !is_groupcast {
            exchange.acknowledge().await?;
        }

        Ok(())
    }

    /// Respond to a `ReadReq` request.
    async fn read(&self, exchange: &mut Exchange<'_>) -> Result<(), Error> {
        let Some((mut tx, rx)) = self.buffers(exchange).await? else {
            return Ok(());
        };

        let read_req = ReadReq::new(TLVElement::new(&rx));
        debug!("IM: Read request: {:?}", read_req);

        if let Err(err) = Self::validate_read(&read_req) {
            error!("Invalid read request: {:?}", err);
            return Self::send_status(exchange, err.code().into()).await;
        }

        let req = ReportDataReq::Read(&read_req);

        let mut wb = WriteBuf::new(&mut tx);

        // Honor the `fabricFiltered` flag on the originating Read request.
        // When set, fabric-sensitive events emitted on other fabrics are
        // dropped before they reach the wire (Matter Core spec).
        let fabric_filtered = req.fabric_filtered().unwrap_or(true);

        let mut resp = ReportDataResponder::new(
            &req,
            None,
            HandlerInvoker::new(exchange, self),
            EventReader::new(0, u64::MAX, fabric_filtered),
            &self.state.events,
        );

        resp.respond(&mut wb, true, true, &self.handler, |_, _, _| true)
            .await?;

        Ok(())
    }

    /// Validate a `ReadReq` request prior to processing.
    fn validate_read(req: &ReadReq<'_>) -> Result<(), Error> {
        if let Some(attr_requests) = req.attr_requests()? {
            for attr_req in attr_requests {
                Self::validate_attr_wildcard_path(&attr_req?)?;
            }
        }

        Ok(())
    }

    /// Per-spec validation of an `AttrPath` that may contain wildcards.
    ///
    /// Per Matter spec, when a path uses a wildcard cluster
    /// but specifies a concrete attribute id, that attribute id must be a
    /// global (system) attribute. Any other combination must be rejected with
    /// `INVALID_ACTION`.
    fn validate_attr_wildcard_path(path: &AttrPath) -> Result<(), Error> {
        if path.cluster.is_none() {
            if let Some(attr_id) = path.attr {
                if !Attribute::is_system_attr(attr_id) {
                    return Err(ErrorCode::InvalidAction.into());
                }
            }
        }

        Ok(())
    }

    /// Respond to a `WriteReq` request.
    ///
    /// Arguments:
    /// - `exchange` - the exchange to respond to
    /// - `timeout_instant` - an optional timeout instant, if the request is a timed request
    async fn write(
        &self,
        exchange: &mut Exchange<'_>,
        timeout_instant: Option<Instant>,
        is_groupcast: bool,
    ) -> Result<(), Error> {
        while exchange.rx().is_ok() {
            // Loop while there are more write request chunks to process

            let Some((mut tx, rx)) = self.buffers(exchange).await? else {
                break;
            };

            let req = WriteReq::new(TLVElement::new(&rx));
            debug!("IM: Write request: {:?}", req);

            let timed = req.timed_request()?;

            if self.timed_out(exchange, timeout_instant, timed).await? {
                break;
            }

            let mut wb = WriteBuf::new(&mut tx);

            let mut resp = WriteResponder::new(&req, HandlerInvoker::new(exchange, self));

            resp.respond(&mut wb, &self.handler, is_groupcast).await?;

            if req.more_chunks()? {
                // This write request is just one of the chunks, so we need to wait and process
                // the next chunk as well
                exchange.recv_fetch().await?;
            }
        }

        Ok(())
    }

    /// Respond to an `InvokeReq` request.
    ///
    /// Arguments:
    /// - `exchange` - the exchange to respond to
    /// - `timeout_instant` - an optional timeout instant, if the request is a timed request
    async fn invoke(
        &self,
        exchange: &mut Exchange<'_>,
        timeout_instant: Option<Instant>,
        is_groupcast: bool,
    ) -> Result<(), Error> {
        let Some((mut tx, rx)) = self.buffers(exchange).await? else {
            return Ok(());
        };

        let req = InvReq::new(TLVElement::new(&rx));
        debug!("IM: Invoke request: {:?}", req);

        let timed = req.timed_request()?;

        if self.timed_out(exchange, timeout_instant, timed).await? {
            return Ok(());
        }

        let max_paths = exchange.matter().dev_det().max_paths_per_invoke as usize;

        if let Some(reqs) = req.inv_requests()? {
            let mut count = 0;
            for r in &reqs {
                let _ = r?;
                count += 1;
            }

            if count > max_paths {
                return Self::send_status(exchange, IMStatusCode::InvalidAction).await;
            }

            // Per Matter Core spec: when an `InvokeRequestMessage`
            // carries multiple `CommandDataIB` entries, each MUST include a unique
            // `CommandRef` and the request paths SHALL be unique. `count` is bounded
            // by `max_paths_per_invoke` (typically a single-digit number), so the
            // O(n²) pairwise check below is cheaper than allocating buffers.
            if count > 1 {
                for (i, req_i) in reqs.iter().enumerate() {
                    let req_i = req_i?;
                    if req_i.command_ref.is_none() {
                        return Self::send_status(exchange, IMStatusCode::InvalidAction).await;
                    }
                    for req_j in reqs.iter().skip(i + 1) {
                        let req_j = req_j?;
                        if req_i.path == req_j.path || req_i.command_ref == req_j.command_ref {
                            return Self::send_status(exchange, IMStatusCode::InvalidAction).await;
                        }
                    }
                }
            }
        }

        let mut wb = WriteBuf::new(&mut tx);

        let mut resp = InvokeResponder::new(&req, HandlerInvoker::new(exchange, self));

        resp.respond(&mut wb, &self.handler, is_groupcast).await
    }

    /// Respond to a `SubscribeReq` request by priming the subscription (i.e. doing an initial data report)
    /// and if the priming is successful, sending a `SubscribeResp` response to the peer and registering
    /// the subscription details in the `Subscriptions` instance.
    async fn subscribe(&self, exchange: &mut Exchange<'_>) -> Result<(), Error> {
        let Some((mut tx, rx)) = self.buffers(exchange).await? else {
            return Ok(());
        };

        let req = SubscribeReq::new(TLVElement::new(&rx));
        debug!("IM: Subscribe request: {:?}", req);

        let accessor = exchange.accessor()?;

        if let Err(err) = self.validate_subscribe(&req, &accessor) {
            error!("Invalid subscribe request: {:?}", err);
            return Self::send_status(exchange, err.code().into()).await;
        }

        let (fab_idx, peer_node_id) = exchange.with_state(|state| {
            let sess = exchange.id().session(&mut state.sessions);

            let fab_idx = NonZeroU8::new(sess.get_local_fabric_idx()).ok_or(ErrorCode::Invalid)?;
            let peer_node_id = sess.get_peer_node_id().ok_or(ErrorCode::Invalid)?;

            Ok((fab_idx, peer_node_id))
        })?;

        if !req.keep_subs()? {
            self.state
                .subscriptions
                .remove(&self.subscriptions_buffers, |sub| {
                    (sub.ids().fab_idx == fab_idx && sub.ids().peer_node_id == peer_node_id)
                        .then_some("new subscription request")
                });
        }

        let max_int_secs = core::cmp::max(req.max_int_ceil()?, 40); // Say we need at least 4 secs for potential latencies
        let min_int_secs = req.min_int_floor()?;

        let now = Instant::now();

        let Some(mut rctx) = self.state.subscriptions.add(
            now,
            fab_idx,
            peer_node_id,
            exchange.id().session_id(),
            min_int_secs,
            max_int_secs,
            self.state.events.watermark(),
            rx,
            &self.subscriptions_buffers,
        ) else {
            return Self::send_status(exchange, IMStatusCode::ResourceExhausted).await;
        };

        let primed = self.report_data(&mut rctx, &mut tx, exchange, true).await?;

        if primed {
            exchange
                .send_with(|_, wb| {
                    SubscribeResp::write(wb, rctx.subscription().ids().id, max_int_secs)?;
                    Ok(Some(OpCode::SubscribeResponse.into()))
                })
                .await?;

            rctx.set_keep();

            info!("Subscription {:?} primed", rctx.subscription().ids());

            // Commit the subscription into the table now (its `report_complete`
            // runs on `Drop`) and then wake the reporter so it can account for
            // the new subscription's deadline.
            drop(rctx);
            self.state.subscriptions.notification.notify();
        }

        Ok(())
    }

    /// Validates the subscription request
    fn validate_subscribe(
        &self,
        req: &SubscribeReq<'_>,
        accessor: &Accessor<'_>,
    ) -> Result<(), Error> {
        // As per spec, we need to validate that the subscription request
        // contains existing endpoints, clusters and attributes, and if not
        // we should (a bit surprisingly) return InvalidAction

        self.handler.access(|node| {
            let mut has_attrs = false;
            let mut has_events = false;

            if let Some(attr_requests) = req.attr_requests()? {
                has_attrs = true;

                for attr_req in attr_requests {
                    let path = attr_req?;

                    if path.is_wildcard() {
                        Self::validate_attr_wildcard_path(&path)?;

                        if !node.has_accessible_attr(&path, accessor) {
                            return Err(ErrorCode::InvalidAction.into());
                        }
                    } else {
                        node.validate_attr_path(&path, false, false, accessor)
                            .map_err(|_| ErrorCode::InvalidAction)?;
                    }
                }
            }

            if let Some(event_reqs) = req.event_requests()? {
                has_events = true;

                for event_req in event_reqs {
                    let path = event_req?;

                    if !path.is_wildcard() {
                        node.validate_event_path(&path, accessor)
                            .map_err(|_| ErrorCode::InvalidAction)?;
                    }
                }
            }

            if !has_attrs && !has_events {
                // Empty subscribe requests are not allowed either
                return Err(ErrorCode::InvalidAction.into());
            }

            Ok(())
        })
    }

    /// Process all valid subscriptions in an endless loop, checking for changes
    /// and reporting them to the peers.
    async fn process_subscriptions(&self, matter: &Matter<'_>) -> Result<(), Error> {
        loop {
            // Sleep until the soonest subscription deadline: the end of a
            // `min_int` quiet period for a subscription holding back a change,
            // or the chosen liveness wake point. A change, event, removal, a torn
            // down session, or a newly accepted subscription (the accept path
            // notifies) all wake the loop early. With no subscription there is
            // no deadline, so just wait to be notified.
            let mut notification = pin!(self.state.subscriptions.notification.wait());
            let mut session_removed = pin!(matter.transport().wait_session_removed());

            // With no subscription (or none primed) the deadline is `Instant::MAX`,
            // so the timer effectively never fires and the loop just waits to be
            // notified.
            let deadline = self
                .state
                .subscriptions
                .next_report_at(self.state.events.watermark(), &self.subscriptions_buffers);
            let mut timeout = pin!(Timer::at(deadline));

            select3(&mut notification, &mut timeout, &mut session_removed).await;

            let now = Instant::now();

            // First remove all expired or no-longer valid subscriptions

            loop {
                let removed_any =
                    self.state
                        .subscriptions
                        .remove(&self.subscriptions_buffers, |sub| {
                            if sub.is_expired(now) {
                                return Some("expired");
                            }

                            matter.with_state(|state| {
                                if state.fabrics.get(sub.ids().fab_idx).is_none() {
                                    return Some("fabric removed");
                                }

                                // The session the subscription was accepted on was
                                // torn down (eviction, explicit close, peer-side
                                // CASE re-handshake, ...). Per Matter spec
                                // subscriptions are scoped to the session they
                                // were established on, and the publisher can no
                                // longer route reports to the subscriber. Drop
                                // immediately rather than waiting for `max_int`
                                // to expire and time-out the send.
                                if state.sessions.get(sub.session_id()).is_none() {
                                    return Some("session removed");
                                }

                                None
                            })
                        });

                if !removed_any {
                    break;
                }
            }

            // Now report while there are subscriptions which are due for reporting

            let event_numbers_watermark = self.state.events.watermark();

            loop {
                let Some(mut rctx) = self.state.subscriptions.report(
                    now,
                    event_numbers_watermark,
                    &self.subscriptions_buffers,
                ) else {
                    break;
                };

                let result = self.process_subscription(matter, &mut rctx).await;

                match result {
                    Ok(true) => rctx.set_keep(),
                    Ok(false) => (),
                    Err(e) => error!(
                        "Error processing subscription {:?}: {:?}",
                        rctx.subscription().ids(),
                        e
                    ),
                }
            }

            // Periodically trim changed-attr entries that have been reported by every
            // subscription, so the table does not accumulate stale promoted wildcards.
            self.state.subscriptions.purge_reported_changes();
        }
    }

    /// Process one valid subscription, reporting the data to the peer.
    ///
    /// Arguments:
    /// - `matter` - a reference to the `Matter` instance
    /// - `fabric_idx` - the fabric index of the peer
    /// - `peer_node_id` - the node ID of the peer
    /// - `session_id` - the session ID of the peer, if any
    /// - `sub` - the received and saved data for the subscription, when the subscription was primed
    /// - `min_event_number` - the subscription's current event watermark; updated
    ///   in place as events are emitted so the caller can persist it
    /// - `ctx` - the report context for this subscription
    #[allow(clippy::too_many_arguments)]
    async fn process_subscription(
        &self,
        matter: &Matter<'_>,
        rctx: &mut ReportContext<'_, '_, B, NS>,
    ) -> Result<bool, Error> {
        let mut exchange =
            Exchange::initiate_for_session(matter, rctx.subscription().session_id())?;

        if let Some(mut tx) = self.buffers.get().await {
            // Always safe as `IMBuffer` is defined to be `MAX_EXCHANGE_RX_BUF_SIZE`, which is bigger than `MAX_EXCHANGE_TX_BUF_SIZE`
            unwrap!(tx.resize_default(MAX_EXCHANGE_TX_BUF_SIZE));

            let primed = self
                .report_data(rctx, &mut tx, &mut exchange, false)
                .await?;

            exchange.acknowledge().await?;

            Ok(primed)
        } else {
            error!(
                "No TX buffer available for processing subscription {:?}",
                rctx.subscription().ids(),
            );

            Ok(false)
        }
    }

    /// Process a `TimedReq` request, which is used to set a timeout for the following Write/Invoke request.
    async fn timed(&self, exchange: &mut Exchange<'_>) -> Result<Instant, Error> {
        let req = TimedReq::from_tlv(&get_root_node_struct(exchange.rx()?.payload())?)?;
        debug!("IM: Timed request: {:?}", req);

        let timeout_instant = req.timeout_instant();

        Self::send_status(exchange, IMStatusCode::Success).await?;

        Ok(timeout_instant)
    }

    /// A utility to check whether a timed request has timed out, and if so, send a timeout status response
    async fn timed_out(
        &self,
        exchange: &mut Exchange<'_>,
        timeout_instant: Option<Instant>,
        timed_req: bool,
    ) -> Result<bool, Error> {
        let status = {
            if timed_req != timeout_instant.is_some() {
                Some(IMStatusCode::TimedRequestMisMatch)
            } else if timeout_instant
                .map(|timeout_instant| Instant::now() > timeout_instant)
                .unwrap_or(false)
            {
                Some(IMStatusCode::Timeout)
            } else {
                None
            }
        };

        if let Some(status) = status {
            Self::send_status(exchange, status).await?;

            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// A utility to respond with a `ReportData` response to a subscription request, which is used to report data to the peer.
    ///
    /// Arguments:
    /// - `id` - the subscription ID
    /// - `fabric_idx` - the fabric index of the peer
    /// - `peer_node_id` - the node ID of the peer
    /// - `min_event_number` - the minimum event number to report
    /// - `rx` - the received data for the subscription, when the subscription was primed
    /// - `tx` - the TX buffer to write the response to
    /// - `exchange` - the exchange to respond to
    /// - `with_dataver` - whether to include the data version in the response
    #[allow(clippy::too_many_arguments)]
    async fn report_data(
        &self,
        rctx: &mut ReportContext<'_, '_, B, NS>,
        tx: &mut [u8],
        exchange: &mut Exchange<'_>,
        with_dataver: bool,
    ) -> Result<bool, Error>
    where
        T: DataModel,
    {
        let mut wb = WriteBuf::new(tx);

        let sub_req = SubscribeReq::new(TLVElement::new(rctx.rx()));
        let req = if with_dataver {
            ReportDataReq::Subscribe(&sub_req)
        } else {
            ReportDataReq::SubscribeReport(&sub_req)
        };

        // Honor the `fabricFiltered` flag on the originating Subscribe request.
        // When set, fabric-sensitive events emitted on other fabrics are
        // dropped before they reach the wire (Matter Core spec).
        let fabric_filtered = req.fabric_filtered().unwrap_or(true);

        let mut resp = ReportDataResponder::new(
            &req,
            Some(rctx.subscription().ids().id),
            HandlerInvoker::new(exchange, self),
            EventReader::new(
                rctx.max_seen_event_number(),
                rctx.next_max_seen_event_number(),
                fabric_filtered,
            ),
            &self.state.events,
        );

        let sub_valid = resp
            .respond(
                &mut wb,
                false,
                rctx.should_send_if_empty(),
                &self.handler,
                |e, c, a| rctx.should_report_attr(e, c, a),
            )
            .await?;

        if !sub_valid {
            warn!(
                "Subscription {:?} removed during reporting",
                rctx.subscription().ids()
            );
        }

        Ok(sub_valid)
    }

    /// A utility to fetch a pair of TX/RX buffers for processing an Interaction Model request.
    ///
    /// If there are no free buffers available, this method will send a `Busy` status response to the peer.
    ///
    /// Upon returning:
    /// - The RX buffer will contain the payload of the received Interaction Model request
    /// - The TX buffer will be resized to `MAX_EXCHANGE_TX_BUF_SIZE` and will be ready to be written to
    ///
    /// Returns:
    /// - `Ok(Some((tx, rx)))` - if both TX and RX buffers are available
    /// - `Ok(None)` - if no buffers are available, and a `Busy` status response has been sent
    /// - `Err(Error)` - if an error occurred while fetching the buffers or sending the status response
    async fn buffers(
        &self,
        exchange: &mut Exchange<'_>,
    ) -> Result<Option<(B::Buffer<'a>, B::Buffer<'a>)>, Error> {
        if let Some(tx) = self.tx_buffer(exchange).await? {
            if let Some(rx) = self.rx_buffer(exchange).await? {
                return Ok(Some((tx, rx)));
            }
        }

        Ok(None)
    }

    /// A utility to fetch a RX buffer for processing an Interaction Model request.
    ///
    /// If there are no free buffers available, this method will send a `Busy` status response to the peer.
    ///
    /// Upon returning, the RX buffer will contain the payload of the received Interaction Model request.
    ///
    /// Returns:
    /// - `Ok(Some(rx))` - if a RX buffer is available
    /// - `Ok(None)` - if no RX buffer is available, and a `Busy` status response has been sent
    /// - `Err(Error)` - if an error occurred while fetching the buffer or sending the status response
    async fn rx_buffer(&self, exchange: &mut Exchange<'_>) -> Result<Option<B::Buffer<'a>>, Error> {
        if let Some(mut buffer) = self.buffer(exchange).await? {
            let rx = exchange.rx()?;

            buffer.clear();

            // Safe to unwrap, as `IMBuffer` is defined to be `MAX_EXCHANGE_RX_BUF_SIZE`, i.e. it cannot be overflown
            // by the payload of the received exchange.
            unwrap!(buffer.extend_from_slice(rx.payload()));

            exchange.rx_done()?;

            Ok(Some(buffer))
        } else {
            Ok(None)
        }
    }

    /// A utility to fetch a TX buffer for processing an Interaction Model request.
    ///
    /// If there are no free buffers available, this method will send a `Busy` status response to the peer.
    ///
    /// Upon returning, the TX buffer will be resized to `MAX_EXCHANGE_TX_BUF_SIZE` and will be ready to be written to.
    ///
    /// Returns:
    /// - `Ok(Some(tx))` - if a TX buffer is available
    /// - `Ok(None)` - if no TX buffer is available, and a `Busy` status response has been sent
    /// - `Err(Error)` - if an error occurred while fetching the buffer or sending the status response
    async fn tx_buffer(&self, exchange: &mut Exchange<'_>) -> Result<Option<B::Buffer<'a>>, Error> {
        if let Some(mut buffer) = self.buffer(exchange).await? {
            // Always safe as `IMBuffer` is defined to be `MAX_EXCHANGE_RX_BUF_SIZE`, which is bigger than `MAX_EXCHANGE_TX_BUF_SIZE`
            unwrap!(buffer.resize_default(MAX_EXCHANGE_TX_BUF_SIZE));

            Ok(Some(buffer))
        } else {
            Ok(None)
        }
    }

    /// A utility to fetch a buffer for processing an Interaction Model request.
    ///
    /// If there are no free buffers available, this method will send a `Busy` status response to the peer.
    ///
    /// Upon returning, the buffer will be UNINITIALIZED. I.e. it is up to the user to resize it appropriately
    /// if it is to be used for sending a response, or to fill it with data, if it is to be used for receiving data.
    ///
    /// Returns:
    /// - `Ok(Some(buffer))` - if a buffer is available
    /// - `Ok(None)` - if no buffer is available, and a `Busy` status response has been sent
    /// - `Err(Error)` - if an error occurred while fetching the buffer or sending the status response
    async fn buffer(&self, exchange: &mut Exchange<'_>) -> Result<Option<B::Buffer<'a>>, Error> {
        if let Some(buffer) = self.buffers.get().await {
            Ok(Some(buffer))
        } else {
            Self::send_status(exchange, IMStatusCode::Busy).await?;

            Ok(None)
        }
    }

    /// A utility to send a status response to the peer.
    async fn send_status(exchange: &mut Exchange<'_>, status: IMStatusCode) -> Result<(), Error> {
        exchange
            .send_with(|_, wb| {
                StatusResp::write(wb, status)?;

                Ok(Some(OpCode::StatusResponse.into()))
            })
            .await
    }
}

impl<C, B, T, K, N, NC, const NS: usize, const NE: usize> ExchangeHandler
    for InteractionModel<'_, C, B, T, K, N, NC, NS, NE>
where
    C: Crypto,
    B: Buffers<IMBuffer>,
    T: DataModel,
    K: KvBlobStoreAccess,
    N: Networks,
{
    async fn handle(&self, mut exchange: Exchange<'_>) -> Result<(), Error> {
        InteractionModel::handle(self, &mut exchange).await
    }
}

impl<C, B, T, K, N, NC, const NS: usize, const NE: usize> HandlerContext
    for InteractionModel<'_, C, B, T, K, N, NC, NS, NE>
where
    C: Crypto,
    B: Buffers<IMBuffer>,
    T: DataModel,
    K: KvBlobStoreAccess,
    N: Networks,
{
    fn matter(&self) -> &Matter<'_> {
        self.matter
    }

    fn crypto(&self) -> impl Crypto + '_ {
        &self.crypto
    }

    fn kv(&self) -> impl KvBlobStoreAccess + '_ {
        &self.kv
    }

    fn networks(&self) -> impl NetworksAccess + '_ {
        &self.state.networks
    }

    fn metadata(&self) -> impl Metadata + '_ {
        &self.handler
    }

    fn handler(&self) -> impl AsyncHandler + '_ {
        &self.handler
    }

    fn buffers(&self) -> impl Buffers<IMBuffer> + '_ {
        self.buffers
    }
}

impl<C, B, T, K, N, NC, const NS: usize, const NE: usize> AttrChangeNotifier
    for InteractionModel<'_, C, B, T, K, N, NC, NS, NE>
where
    C: Crypto,
    B: Buffers<IMBuffer>,
    T: DataModel,
    K: KvBlobStoreAccess,
    N: Networks,
{
    fn notify_attr_changed(&self, endpoint_id: EndptId, cluster_id: ClusterId, attr_id: AttrId) {
        self.handler.bump_dataver(MatchContextInstance::new(
            Some(endpoint_id),
            Some(cluster_id),
        ));
        self.state
            .subscriptions
            .notify_attr_changed(endpoint_id, cluster_id, attr_id);
    }

    fn notify_cluster_changed(&self, endpoint_id: EndptId, cluster_id: ClusterId) {
        self.handler.bump_dataver(MatchContextInstance::new(
            Some(endpoint_id),
            Some(cluster_id),
        ));
        self.state
            .subscriptions
            .notify_cluster_changed(endpoint_id, cluster_id);
    }

    fn notify_endpoint_changed(&self, endpoint_id: EndptId) {
        self.handler
            .bump_dataver(MatchContextInstance::new(Some(endpoint_id), None));
        self.state
            .subscriptions
            .notify_endpoint_changed(endpoint_id)
    }

    fn notify_all_changed(&self) {
        self.handler
            .bump_dataver(MatchContextInstance::new(None, None));
        self.state.subscriptions.notify_all_changed()
    }
}

impl<C, B, T, K, N, NC, const NS: usize, const NE: usize> EventEmitter
    for InteractionModel<'_, C, B, T, K, N, NC, NS, NE>
where
    C: Crypto,
    B: Buffers<IMBuffer>,
    T: DataModel,
    K: KvBlobStoreAccess,
    N: Networks,
{
    fn emit_event<F>(
        &self,
        endpoint_id: EndptId,
        cluster_id: ClusterId,
        event_id: EventId,
        priority: EventPriority,
        f: F,
    ) -> Result<u64, Error>
    where
        F: FnOnce(EventTLVWrite<'_>) -> Result<(), Error>,
    {
        let event_number =
            self.state
                .events
                .push(endpoint_id, cluster_id, event_id, priority, &self.kv, f)?;

        self.state
            .subscriptions
            .notify_event_emitted(endpoint_id, cluster_id, event_id);

        Ok(event_number)
    }
}

pub enum RespondOutcome {
    Accepted,
    Rejected,
    Empty,
}

/// This type responds with a `ReportData` response to all of:
/// - A `ReadReq`
/// - A `SubscribeReq`
/// - A `SubscribeReportReq` (i.e. once a valid recorded subscription is detected as in a need to be reported on)
///
/// The responder handles chunking as needed. I.e. if reported data is too large to fit into a single
/// Matter message, it will send the data in multiple chunks (i.e. with multiple Matter messages), waiting for
/// a `Success` response from the peer after each chunk, and then continuing to send the next chunk until all data is sent.
struct ReportDataResponder<'a, 'b, 'c, const NE: usize, C> {
    req: &'a ReportDataReq<'a>,
    subscription_id: Option<u32>,
    invoker: HandlerInvoker<'b, 'c, C>,
    event_reader: EventReader,
    events: &'a Events<NE>,
}

impl<'a, 'b, 'c, const NE: usize, C> ReportDataResponder<'a, 'b, 'c, NE, C>
where
    C: HandlerContext,
{
    // This is the amount of space we reserve for the structure/array closing TLVs
    // to be attached towards the end of long reads
    const LONG_READS_TLV_RESERVE_SIZE: usize = 24;

    /// Create a new `ReportDataResponder`.
    const fn new(
        req: &'a ReportDataReq<'a>,
        subscription_id: Option<u32>,
        invoker: HandlerInvoker<'b, 'c, C>,
        event_reader: EventReader,
        events: &'a Events<NE>,
    ) -> Self {
        Self {
            req,
            subscription_id,
            invoker,
            event_reader,
            events,
        }
    }

    /// Respond to the request with a `ReportData` response, possibly with more than one
    /// chunk if the data is too large to fit into a single Matter message.
    ///
    /// Arguments:
    /// - `wb` - the buffer to use while sending the response
    /// - `suppress_last_resp` - whether to suppress the response from the peer. When multiple Matter messages are
    ///   being sent due to chunking, this is valid for the last chunk only, as the others - by necessity need to have a
    ///   status response by the other peer
    async fn respond<M, F>(
        &mut self,
        wb: &mut WriteBuf<'_>,
        suppress_last_resp: bool,
        send_if_empty: bool,
        metadata: M,
        mut filter: F,
    ) -> Result<bool, Error>
    where
        M: Metadata,
        F: FnMut(EndptId, ClusterId, u32) -> bool,
    {
        let mut empty = true;

        self.start_reply(wb)?;

        if !self
            .report_attributes(wb, &mut empty, &metadata, &mut filter)
            .await?
        {
            return Ok(false);
        }

        if !self.report_events(wb, &mut empty, &metadata).await? {
            return Ok(false);
        }

        if send_if_empty || !empty {
            self.send(ReportDataChunkState::Done, suppress_last_resp, wb)
                .await
        } else {
            debug!("No data to report, skipping sending ReportData response");

            Ok(true)
        }
    }

    async fn report_attributes<M, F>(
        &mut self,
        wb: &mut WriteBuf<'_>,
        empty: &mut bool,
        metadata: M,
        mut filter: F,
    ) -> Result<bool, Error>
    where
        M: Metadata,
        F: FnMut(EndptId, ClusterId, u32) -> bool,
    {
        let accessor = self.invoker.exchange().accessor()?;

        if self.req.attr_requests()?.is_some() {
            wb.start_array(&TLVTag::Context(ReportDataRespTag::AttributeReports as u8))?;

            for item in expand_read(&metadata, self.req, &accessor, &mut filter)? {
                let item = item?;

                *empty = false;

                loop {
                    let result = self.invoker.process_read(&item, &mut *wb).await;

                    match result {
                        Ok(()) => break,
                        Err(err) if err.code() == ErrorCode::NoSpace => {
                            let array_attr = item.as_ref().ok().filter(|attr| {
                                attr.list_index.is_none()
                                    // The whole attribute is requested
                                    // Check if it is an array, and if so, send it as individual items instead
                                    && attr.array
                            });

                            if let Some(array_attr) = array_attr {
                                if self.send_array_items(array_attr, wb).await? {
                                    break;
                                } else {
                                    return Ok(false);
                                }
                            } else {
                                debug!("<<< No TX space, chunking >>>");
                                if !self
                                    .send(ReportDataChunkState::ChunkingAttributes, false, wb)
                                    .await?
                                {
                                    return Ok(false);
                                }
                            }
                        }
                        Err(err) => Err(err)?,
                    }
                }
            }

            wb.end_container()?;
        }

        Ok(true)
    }

    async fn report_events<M>(
        &mut self,
        wb: &mut WriteBuf<'_>,
        empty: &mut bool,
        metadata: M,
    ) -> Result<bool, Error>
    where
        M: Metadata,
    {
        let accessor = self.invoker.exchange().accessor()?;

        if let Some(event_reqs) = self.req.event_requests()? {
            wb.start_array(&TLVTag::Context(ReportDataRespTag::EventReports as _))?;

            // Validate concrete event paths against node metadata
            // and emit EventStatusIB for non-wildcard paths that don't match
            for event_req in event_reqs.iter() {
                let path = event_req?;

                if !path.is_wildcard() {
                    if let Err(status) =
                        metadata.access(|node| node.validate_event_path(&path, &accessor))
                    {
                        if matches!(status, IMStatusCode::UnsupportedEvent) {
                            // Event does not exist on this endpoint
                            // TODO: Look at TestEventsById.yaml
                            // Seems we should not error out in that case?
                            continue;
                        }

                        *empty = false;

                        let resp = EventResp::Status(EventStatus::new(path, status, None));

                        let mut result = resp.to_tlv(&TLVTag::Anonymous, &mut *wb);

                        if let Err(e) = &result {
                            if e.code() == ErrorCode::NoSpace {
                                debug!("<<< No TX space, chunking >>>");
                                if !self
                                    .send(ReportDataChunkState::ChunkingEvents, false, &mut *wb)
                                    .await?
                                {
                                    return Ok(false);
                                }

                                result = resp.to_tlv(&TLVTag::Anonymous, &mut *wb);
                            }
                        }

                        result?;
                    }
                }
            }

            let event_filters = self.req.event_filters()?;

            loop {
                let finished = self.events.fetch(|events| {
                    metadata.access(|node| {
                        for event in events {
                            let result = self.event_reader.process_read(
                                event,
                                &event_reqs,
                                &event_filters,
                                node,
                                &accessor,
                                &mut *wb,
                            );

                            if let Err(e) = &result {
                                if e.code() == ErrorCode::NoSpace {
                                    return Ok::<_, Error>(false);
                                }
                            }

                            if result? {
                                *empty = false;
                            }
                        }

                        Ok(true)
                    })
                })?;

                if finished {
                    break;
                }

                debug!("<<< No TX space, chunking >>>");
                if !self
                    .send(ReportDataChunkState::ChunkingEvents, false, wb)
                    .await?
                {
                    return Ok(false);
                }
            }

            wb.end_container()?;
        }

        Ok(true)
    }

    /// Send the items of an array attribute one by one, until the end of the array is reached.
    ///
    /// The data is potentially sent in multiple chunks if it cannot fit into a single Matter message.
    ///
    /// Arguments:
    /// - `attr` - the array attribute to send the items of
    /// - `wb` - the buffer to use while sending the items
    async fn send_array_items(
        &mut self,
        attr: &AttrDetails,
        wb: &mut WriteBuf<'_>,
    ) -> Result<bool, Error> {
        let mut attr = attr.clone();

        // First generate an empty array
        let mut list_index = None;
        attr.list_chunked = true;
        attr.list_index = Some(Nullable::new(list_index));

        loop {
            let pos = wb.get_tail();

            let result = self.invoker.read(&attr, &mut *wb).await;

            if result.is_err() {
                // If we got an error, we rewind to the position before the read
                // and handle it accordingly
                wb.rewind_to(pos);
            }

            match result {
                Ok(()) => {
                    // The empty array payload was sent
                    // Now iterate over the array and send each item one by one as separate payload

                    let new_list_index = if let Some(list_index) = list_index {
                        list_index + 1
                    } else {
                        0
                    };

                    list_index = Some(new_list_index);
                    attr.list_index = Some(Nullable::some(new_list_index));
                }
                Err(err) if err.code() == ErrorCode::NoSpace => {
                    debug!("<<< No TX space, chunking >>>");
                    if !self
                        .send(ReportDataChunkState::ChunkingAttributes, false, wb)
                        .await?
                    {
                        return Ok(false);
                    }
                }
                Err(err) if err.code() == ErrorCode::ConstraintError => break, // Got to the end of the array
                Err(err) => Err(err)?,
            }
        }

        Ok(true)
    }

    /// Send the reply to the peer, potentially opening another reply.
    ///
    /// Arguments:
    /// - `state`: tracks chunking state - are we just sending a chunk packet or are we done and wrapping up?
    /// - `suppress_last_resp`: whether to suppress the response from the peer, this is ignored if state is != Done
    /// - `wb`: the buffer containing the reply. Once the reply is sent, the buffer is re-initialized for a new reply if `more_chunks` is `true`
    async fn send(
        &mut self,
        state: ReportDataChunkState,
        suppress_last_resp: bool,
        wb: &mut WriteBuf<'_>,
    ) -> Result<bool, Error> {
        self.end_reply(state, suppress_last_resp, wb)?;

        self.invoker
            .exchange()
            .send(OpCode::ReportData, wb.as_slice())
            .await?;

        let cont = match state {
            ReportDataChunkState::ChunkingAttributes => {
                let cont = self.recv_status_success().await?;
                self.start_reply(wb)?;
                wb.start_array(&TLVTag::Context(ReportDataRespTag::AttributeReports as u8))?;
                cont
            }
            ReportDataChunkState::ChunkingEvents => {
                let cont = self.recv_status_success().await?;
                self.start_reply(wb)?;
                wb.start_array(&TLVTag::Context(ReportDataRespTag::EventReports as u8))?;
                cont
            }
            ReportDataChunkState::Done => {
                if !suppress_last_resp {
                    self.recv_status_success().await?
                } else {
                    false
                }
            }
        };

        Ok(cont)
    }

    /// Receive a status response from the peer
    ///
    /// If the response is not a status response, the method will fail with an `Invalid` error.
    ///
    /// Return `Ok(true)` if the response is a success response, `Ok(false)` if the response is not a success response.
    async fn recv_status_success(&mut self) -> Result<bool, Error> {
        let rx = self.invoker.exchange().recv().await?;
        let opcode = rx.meta().proto_opcode;

        if opcode != OpCode::StatusResponse as u8 {
            warn!(
                "Got opcode {:02x}, while expecting status code {:02x}",
                opcode,
                OpCode::StatusResponse as u8
            );

            return Err(ErrorCode::Invalid.into());
        }

        let resp = StatusResp::from_tlv(&get_root_node_struct(rx.payload())?)?;

        if resp.status == IMStatusCode::Success {
            Ok(true)
        } else {
            warn!(
                "Got status response {:?}, aborting interaction",
                resp.status
            );

            drop(rx);

            self.invoker.exchange().acknowledge().await?;

            Ok(false)
        }
    }

    /// Start a reply by initializing the `WriteBuf` and writing the initial TLVs.
    fn start_reply(&self, wb: &mut WriteBuf<'_>) -> Result<(), Error> {
        wb.reset();
        wb.shrink(Self::LONG_READS_TLV_RESERVE_SIZE)?;

        wb.start_struct(&TLVTag::Anonymous)?;

        if let Some(subscription_id) = self.subscription_id {
            assert!(matches!(
                self.req,
                ReportDataReq::Subscribe(_) | ReportDataReq::SubscribeReport(_)
            ));
            wb.u32(
                &TLVTag::Context(ReportDataRespTag::SubscriptionId as u8),
                subscription_id,
            )?;
        } else {
            assert!(matches!(self.req, ReportDataReq::Read(_)));
        }

        Ok(())
    }

    /// End a reply by writing the closing TLVs and potentially indicating that there are more chunks to send.
    fn end_reply(
        &self,
        state: ReportDataChunkState,
        suppress_resp: bool,
        wb: &mut WriteBuf<'_>,
    ) -> Result<(), Error> {
        wb.expand(Self::LONG_READS_TLV_RESERVE_SIZE)?;

        match state {
            ReportDataChunkState::ChunkingAttributes | ReportDataChunkState::ChunkingEvents => {
                wb.end_container()?;
                wb.bool(
                    &TLVTag::Context(ReportDataRespTag::MoreChunkedMsgs as u8),
                    true,
                )?;
            }
            ReportDataChunkState::Done => {
                if suppress_resp {
                    wb.bool(
                        &TLVTag::Context(ReportDataRespTag::SupressResponse as u8),
                        true,
                    )?;
                }
            }
        };

        // InteractionModelRevision is mandatory in all IM messages from
        // Matter 1.0 onward (TLV tag 0xFF). matter.js validates this
        // strictly and refuses to commission devices that omit it; the
        // reference chip-tool happens to tolerate the absence.
        wb.u8(
            &TLVTag::Context(crate::im::encoding::IM_REVISION_TAG),
            IM_REVISION,
        )?;

        wb.end_container()?;

        Ok(())
    }
}

/// Used to avoid duplicating the chunking logic for events and attributes; they both
/// share the same write path when the current packet fills up, and use this to determine
/// which field they should be setting up an array in for more output in the next packet
#[derive(Clone, Copy)]
enum ReportDataChunkState {
    ChunkingAttributes,
    ChunkingEvents,
    Done,
}

/// This type responds to a `WriteReq` by invoking the
/// corresponding handlers for each write attribute in the request.
///
/// The responser assumes that all response data can fit in a single Matter message,
/// which is a fair assumption and as per the Matter spec, in that the response of a
/// write request is always shorter than the write request itself, so given that the
/// write request fits in a single Matter message, the write reponse should as well.
///
/// With that said, the write request might itself be just one out of many chunks that
/// the other peers is sending, but processing all of those chunks is not done here,
/// but is rather - a responsibility of the caller who should call in a loop `WriteResponder::respond`
/// for all the chunks of the write request, until the `WriteReq::more_chunks()` returns `false`.
struct WriteResponder<'a, 'b, 'c, C> {
    req: &'a WriteReq<'a>,
    invoker: HandlerInvoker<'b, 'c, C>,
}

impl<'a, 'b, 'c, C> WriteResponder<'a, 'b, 'c, C>
where
    C: HandlerContext,
{
    /// Create a new `WriteResponder`.
    const fn new(req: &'a WriteReq<'a>, invoker: HandlerInvoker<'b, 'c, C>) -> Self {
        Self { req, invoker }
    }

    /// Respond to the write request by processing each write attribute in the request
    /// and sending a response back.
    async fn respond<M>(
        &mut self,
        wb: &mut WriteBuf<'_>,
        metadata: M,
        suppress_resp: bool,
    ) -> Result<(), Error>
    where
        M: Metadata,
    {
        let accessor = self.invoker.exchange().accessor()?;

        wb.reset();

        wb.start_struct(&TLVTag::Anonymous)?;
        wb.start_array(&TLVTag::Context(WriteRespTag::WriteResponses as u8))?;

        for item in expand_write(metadata, self.req, &accessor)? {
            self.invoker.process_write(&item?, &mut *wb).await?;
        }

        if suppress_resp {
            return Ok(());
        }

        wb.end_container()?;
        // Mandatory `interactionModelRevision` (tag 0xFF); see note in
        // the ReportData emitter above.
        wb.u8(
            &TLVTag::Context(crate::im::encoding::IM_REVISION_TAG),
            IM_REVISION,
        )?;
        wb.end_container()?;

        self.invoker
            .exchange()
            .send(OpCode::WriteResponse, wb.as_slice())
            .await
    }
}

/// This type responds to an `InvRequest` by invoking the
/// corresponding handlers for each command in the invoke request.
///
/// NOTE: In future, this responder should support chunking in that
/// if the reply to all the commands in the invoke request is too large to fit
/// into a single Matter message, it should send the response in multiple chunks.
///
/// The simplest strategy for chunking would be to simply - and unconditionally - send each individual
/// command response in a separate Matter message, i.e. if the invoke request contains 3 commands,
/// the responder will send 3 Matter messages, each containing a single command response.
struct InvokeResponder<'a, 'b, 'c, C> {
    req: &'a InvReq<'a>,
    invoker: HandlerInvoker<'b, 'c, C>,
}

impl<'a, 'b, 'c, C> InvokeResponder<'a, 'b, 'c, C>
where
    C: HandlerContext,
{
    /// Create a new `InvokeResponder`.
    const fn new(req: &'a InvReq<'a>, invoker: HandlerInvoker<'b, 'c, C>) -> Self {
        Self { req, invoker }
    }

    /// Respond to the invoke request by processing each command in the request
    /// and sending one or more reponses back.
    async fn respond<M>(
        &mut self,
        wb: &mut WriteBuf<'_>,
        metadata: M,
        suppress_resp: bool,
    ) -> Result<(), Error>
    where
        M: Metadata,
    {
        wb.reset();

        wb.start_struct(&TLVTag::Anonymous)?;

        // Suppress Response -> TODO: Need to revisit this for cases where we send a command back
        wb.bool(
            &TLVTag::Context(InvRespTag::SupressResponse as u8),
            suppress_resp,
        )?;

        let has_requests = self.req.inv_requests()?.is_some();

        if has_requests {
            wb.start_array(&TLVTag::Context(InvRespTag::InvokeResponses as u8))?;
        }

        let accessor = self.invoker.exchange().accessor()?;

        for item in expand_invoke(metadata, self.req, &accessor)? {
            self.invoker.process_invoke(&item?, &mut *wb).await?;
        }

        if suppress_resp {
            return Ok(());
        }

        if has_requests {
            wb.end_container()?;
        }

        // Mandatory `interactionModelRevision` (tag 0xFF) at the end of
        // every IM message — see the matching note in the ReportData
        // emitter above.
        wb.u8(
            &TLVTag::Context(crate::im::encoding::IM_REVISION_TAG),
            IM_REVISION,
        )?;
        wb.end_container()?;

        self.invoker
            .exchange()
            .send(OpCode::InvokeResponse, wb.as_slice())
            .await?;

        Ok(())
    }
}