brainwires-hardware 0.9.0

Hardware I/O for the Brainwires Agent Framework — audio, GPIO, Bluetooth, and network
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
/// Matter 1.3 device server — exposes a Brainwires agent as a Matter device.
///
/// Implements the Matter device stack using our own protocol implementation
/// (avoiding rs-matter due to an embassy-time links conflict with burn in the workspace).
///
/// Stack layers:
/// 1. mDNS advertisement via `mdns-sd` (DNS-SD for operational + commissionable discovery)
/// 2. UDP transport on port 5540 (the standard Matter port)
/// 3. PASE commissioning window (SPAKE2+ passcode verification)
/// 4. CASE session establishment (certificate-based operational sessions)
/// 5. Interaction Model dispatch (On/Off, Level Control, Color Control, Thermostat)
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;

use tokio::sync::Mutex;
use tracing::{debug, error, info, warn};

use super::data_model::{
    BasicInformationCluster, DataModelNode, GeneralCommissioningCluster,
    NetworkCommissioningCluster, OperationalCredentialsCluster,
};
use super::discovery::CommissionableAdvertiser;
use super::fabric::FabricManager;
use super::interaction_model::read::ReportData;
use super::interaction_model::{ImOpcode, InteractionStatus, InvokeResponse, InvokeResponseItem};
use super::secure_channel::{
    CaseResponder, EstablishedSession, PaseCommissionee, SECURE_CHANNEL_PROTOCOL_ID,
    SecureChannelOpcode,
};
use super::transport::message::{MatterMessage, MessageHeader, SessionType};
use super::transport::{SessionKeys, UdpTransport};
use super::types::MatterDeviceConfig;
use crate::homeauto::error::{HomeAutoError, HomeAutoResult};

// Cluster handler callback types
pub type OnOffHandler = Arc<dyn Fn(bool) + Send + Sync>;
pub type LevelHandler = Arc<dyn Fn(u8) + Send + Sync>;
pub type ColorTempHandler = Arc<dyn Fn(u16) + Send + Sync>;
pub type ThermostatHandler = Arc<dyn Fn(f32) + Send + Sync>;

// Matter protocol constants (used when binding the Matter server socket)
const _MATTER_PORT: u16 = 5540;
const _MATTER_MDNS_SERVICE_TYPE: &str = "_matter._tcp";

// IM protocol ID
const IM_PROTOCOL_ID: u16 = 0x0001;

// Well-known cluster IDs
const CLUSTER_ON_OFF: u32 = 0x0006;
const CLUSTER_LEVEL_CONTROL: u32 = 0x0008;
const CLUSTER_COLOR_CONTROL: u32 = 0x0300;
const CLUSTER_THERMOSTAT: u32 = 0x0201;

// Well-known OnOff command IDs
const CMD_OFF: u32 = 0x00;
const CMD_ON: u32 = 0x01;
const CMD_TOGGLE: u32 = 0x02;

// Well-known Level Control command IDs
const CMD_MOVE_TO_LEVEL: u32 = 0x00;
const CMD_MOVE_TO_LEVEL_WITH_ON_OFF: u32 = 0x04;

// Well-known Thermostat command IDs
const CMD_SETPOINT_RAISE_LOWER: u32 = 0x00;

struct ServerInner {
    on_off: Option<OnOffHandler>,
    level: Option<LevelHandler>,
    color_temp: Option<ColorTempHandler>,
    thermostat: Option<ThermostatHandler>,
    running: bool,
    /// Whether the device is commissioned (has an operational fabric).
    _commissioned: bool,
}

/// A Matter 1.3 device server.
///
/// Once started, this device:
/// 1. Advertises as a commissionable Matter device via mDNS (`_matterc._udp`).
/// 2. Opens UDP port 5540 and handles Matter commissioning (PASE).
/// 3. After commissioning, handles cluster commands via the registered callbacks.
///
/// # Example
/// ```rust,no_run
/// use brainwires_hardware::homeauto::matter::{MatterDeviceConfig, MatterDeviceServer};
///
/// # async fn run() -> anyhow::Result<()> {
/// let config = MatterDeviceConfig::builder()
///     .device_name("Brainwires Light")
///     .vendor_id(0xFFF1)
///     .product_id(0x8001)
///     .discriminator(3840)
///     .passcode(20202021)
///     .build();
///
/// let server = MatterDeviceServer::new(config).await?;
/// server.set_on_off_handler(|on| {
///     println!("On/Off: {on}");
/// });
/// server.start().await?;
/// # Ok(())
/// # }
/// ```
pub struct MatterDeviceServer {
    config: MatterDeviceConfig,
    inner: Arc<Mutex<ServerInner>>,
    qr_code: String,
    pairing_code: String,
}

impl MatterDeviceServer {
    /// Create a new Matter device server.
    pub async fn new(config: MatterDeviceConfig) -> HomeAutoResult<Self> {
        let qr_code = generate_qr_code_string(&config);
        let pairing_code = generate_pairing_code(&config);
        Ok(Self {
            config,
            inner: Arc::new(Mutex::new(ServerInner {
                on_off: None,
                level: None,
                color_temp: None,
                thermostat: None,
                running: false,
                _commissioned: false,
            })),
            qr_code,
            pairing_code,
        })
    }

    /// Start the Matter device server.
    ///
    /// Binds UDP, starts mDNS advertisement, loads/creates the fabric manager,
    /// builds the data model node with mandatory clusters, and runs the receive
    /// loop until `stop()` is called.
    pub async fn start(&self) -> HomeAutoResult<()> {
        {
            let mut inner = self.inner.lock().await;
            if inner.running {
                return Err(HomeAutoError::Matter("server already running".into()));
            }
            inner.running = true;
        }

        info!(
            "Matter device '{}' starting on UDP port {}",
            self.config.device_name, self.config.port
        );
        info!("QR code: {}", self.qr_code);
        info!("Manual pairing code: {}", self.pairing_code);
        info!("Discriminator: {}", self.config.discriminator);

        // 1. Start CommissionableAdvertiser
        let _mdns_handle = self.start_mdns_advertisement()?;

        // 2. Load/create FabricManager from config.storage_path
        let _fabric_manager = FabricManager::load(&self.config.storage_path)
            .await
            .map_err(|e| HomeAutoError::Matter(format!("FabricManager load: {e}")))?;

        // 3. Bind UdpTransport on config.port (default 5540)
        let transport = Arc::new(
            UdpTransport::new(self.config.port)
                .await
                .map_err(|e| HomeAutoError::Matter(format!("UDP bind: {e}")))?,
        );
        info!("Matter UDP transport bound on port {}", self.config.port);

        // 4. Build DataModelNode with mandatory clusters
        let mut data_model = DataModelNode::new();
        // Endpoint 0: mandatory commissioning clusters
        data_model.add_cluster(0, Box::new(BasicInformationCluster::new(&self.config)));
        data_model.add_cluster(0, Box::new(GeneralCommissioningCluster::new()));
        data_model.add_cluster(0, Box::new(OperationalCredentialsCluster::new()));
        data_model.add_cluster(0, Box::new(NetworkCommissioningCluster::new()));

        let data_model = Arc::new(data_model);

        // 5. Shared session state
        let pase_state: Arc<Mutex<Option<PaseCommissionee>>> = Arc::new(Mutex::new(None));
        let case_sessions: Arc<Mutex<HashMap<u16, CaseResponder>>> =
            Arc::new(Mutex::new(HashMap::new()));
        let established: Arc<Mutex<HashMap<u16, EstablishedSession>>> =
            Arc::new(Mutex::new(HashMap::new()));

        let passcode = self.config.passcode;

        // 6. Receive loop
        loop {
            let running = self.inner.lock().await.running;
            if !running {
                break;
            }

            match tokio::time::timeout(std::time::Duration::from_millis(100), transport.recv())
                .await
            {
                Ok(Ok((msg, peer))) => {
                    let session_id = msg.header.session_id;
                    debug!(
                        "Matter UDP from {peer}: session={session_id} payload_len={}",
                        msg.payload.len()
                    );

                    if session_id == 0 {
                        // Unencrypted commissioning — PASE
                        handle_commissioning_message(
                            msg,
                            peer,
                            &transport,
                            &pase_state,
                            &established,
                            passcode,
                        )
                        .await;
                    } else {
                        // Operational — CASE or IM dispatch
                        handle_operational_message(
                            msg,
                            peer,
                            &transport,
                            &case_sessions,
                            &established,
                            &data_model,
                            &self.inner,
                        )
                        .await;
                    }
                }
                Ok(Err(e)) => {
                    error!("Matter UDP recv error: {e}");
                    break;
                }
                Err(_) => {} // timeout — loop back and check running flag
            }
        }

        // Stop mDNS — already handled by CommissionableAdvertiser Drop
        drop(_mdns_handle);
        self.inner.lock().await.running = false;
        Ok(())
    }

    /// Stop the Matter device server.
    pub async fn stop(&self) -> HomeAutoResult<()> {
        self.inner.lock().await.running = false;
        Ok(())
    }

    /// Register a callback for On/Off cluster state changes.
    pub fn set_on_off_handler(&self, f: impl Fn(bool) + Send + Sync + 'static) {
        let inner = self.inner.clone();
        tokio::spawn(async move {
            inner.lock().await.on_off = Some(Arc::new(f));
        });
    }

    /// Register a callback for Level Control cluster changes.
    pub fn set_level_handler(&self, f: impl Fn(u8) + Send + Sync + 'static) {
        let inner = self.inner.clone();
        tokio::spawn(async move {
            inner.lock().await.level = Some(Arc::new(f));
        });
    }

    /// Register a callback for Color Temperature changes.
    pub fn set_color_temp_handler(&self, f: impl Fn(u16) + Send + Sync + 'static) {
        let inner = self.inner.clone();
        tokio::spawn(async move {
            inner.lock().await.color_temp = Some(Arc::new(f));
        });
    }

    /// Register a callback for Thermostat setpoint changes.
    pub fn set_thermostat_handler(&self, f: impl Fn(f32) + Send + Sync + 'static) {
        let inner = self.inner.clone();
        tokio::spawn(async move {
            inner.lock().await.thermostat = Some(Arc::new(f));
        });
    }

    /// The QR code string for this device.
    pub fn qr_code(&self) -> &str {
        &self.qr_code
    }

    /// The 11-digit manual pairing code.
    pub fn pairing_code(&self) -> &str {
        &self.pairing_code
    }

    // ── Internal ──────────────────────────────────────────────────────────────

    fn start_mdns_advertisement(&self) -> HomeAutoResult<Option<CommissionableAdvertiser>> {
        CommissionableAdvertiser::start(&self.config)
            .map_err(|e| HomeAutoError::Matter(e.to_string()))
            .map(Some)
    }
}

// ── Payload header framing ────────────────────────────────────────────────────

/// Parse the Matter payload header (the exchange header that precedes IM/SecureChannel TLV).
///
/// Wire format:
/// ```text
/// Exchange Flags  (1 byte)
/// Protocol Opcode (1 byte)
/// Exchange ID     (2 bytes LE)
/// Protocol ID     (2 bytes LE)
/// [Ack Counter    (4 bytes LE)  — only if ACK flag set in Exchange Flags]
/// Application Payload (remaining bytes)
/// ```
///
/// Returns `(exchange_flags, opcode, exchange_id, protocol_id, app_payload)`.
pub fn parse_payload_header(payload: &[u8]) -> Option<(u8, u8, u16, u16, &[u8])> {
    if payload.len() < 6 {
        return None;
    }
    let exchange_flags = payload[0];
    let opcode = payload[1];
    let exchange_id = u16::from_le_bytes([payload[2], payload[3]]);
    let protocol_id = u16::from_le_bytes([payload[4], payload[5]]);

    const EXCHANGE_FLAG_ACK: u8 = 0x02;
    let base = if exchange_flags & EXCHANGE_FLAG_ACK != 0 {
        10
    } else {
        6
    };
    if payload.len() < base {
        return None;
    }
    Some((
        exchange_flags,
        opcode,
        exchange_id,
        protocol_id,
        &payload[base..],
    ))
}

/// Build a Matter payload header + application payload.
pub fn build_payload(
    opcode: u8,
    exchange_id: u16,
    protocol_id: u16,
    app_payload: &[u8],
) -> Vec<u8> {
    let mut out = Vec::with_capacity(6 + app_payload.len());
    out.push(0x00); // Exchange Flags: no ACK, no reliability
    out.push(opcode);
    out.extend_from_slice(&exchange_id.to_le_bytes());
    out.extend_from_slice(&protocol_id.to_le_bytes());
    out.extend_from_slice(app_payload);
    out
}

// ── Helper: send a bare Matter response message (session 0, unencrypted) ─────

fn make_response_message(session_id: u16, message_counter: u32, payload: Vec<u8>) -> MatterMessage {
    MatterMessage {
        header: MessageHeader {
            version: 0,
            session_id,
            session_type: SessionType::Unicast,
            source_node_id: None,
            dest_node_id: None,
            message_counter,
            security_flags: 0x00,
        },
        payload,
    }
}

// ── PASE dispatch ─────────────────────────────────────────────────────────────

async fn handle_commissioning_message(
    msg: MatterMessage,
    peer: SocketAddr,
    transport: &Arc<UdpTransport>,
    pase_state: &Arc<Mutex<Option<PaseCommissionee>>>,
    established: &Arc<Mutex<HashMap<u16, EstablishedSession>>>,
    passcode: u32,
) {
    let counter = msg.header.message_counter;

    let (exchange_flags, opcode, exchange_id, protocol_id, app_payload) =
        match parse_payload_header(&msg.payload) {
            Some(v) => v,
            None => {
                warn!("PASE: malformed payload header from {peer}");
                return;
            }
        };

    debug!(
        "PASE proto={protocol_id:#06x} opcode={opcode:#04x} exch={exchange_id} flags={exchange_flags:#04x} from {peer}"
    );

    if protocol_id != SECURE_CHANNEL_PROTOCOL_ID {
        debug!("PASE: ignoring non-SecureChannel protocol {protocol_id:#06x}");
        return;
    }

    match opcode {
        // PBKDFParamRequest (0x20) — start PASE, send PBKDFParamResponse
        x if x == SecureChannelOpcode::PbkdfParamRequest as u8 => {
            let mut commissionee = PaseCommissionee::new(passcode);
            let resp_payload = match commissionee.handle_param_request(app_payload) {
                Ok(p) => p,
                Err(e) => {
                    error!("PASE: PBKDFParamRequest error: {e}");
                    return;
                }
            };

            *pase_state.lock().await = Some(commissionee);

            let wire_payload = build_payload(
                SecureChannelOpcode::PbkdfParamResponse as u8,
                exchange_id,
                SECURE_CHANNEL_PROTOCOL_ID,
                &resp_payload,
            );
            let resp = make_response_message(0, counter.wrapping_add(1), wire_payload);
            if let Err(e) = transport.send(&resp, peer).await {
                error!("PASE: send PBKDFParamResponse error: {e}");
            } else {
                debug!("PASE: sent PBKDFParamResponse to {peer}");
            }
        }

        // Pake1 (0x22) — process pA, send Pake2
        x if x == SecureChannelOpcode::Pake1 as u8 => {
            let mut guard = pase_state.lock().await;
            let commissionee = match guard.as_mut() {
                Some(c) => c,
                None => {
                    warn!("PASE: received Pake1 but no PASE state, ignoring");
                    return;
                }
            };

            let pake2_payload = match commissionee.handle_pake1(app_payload) {
                Ok(p) => p,
                Err(e) => {
                    error!("PASE: Pake1 error: {e}");
                    *guard = None;
                    return;
                }
            };

            let wire_payload = build_payload(
                SecureChannelOpcode::Pake2 as u8,
                exchange_id,
                SECURE_CHANNEL_PROTOCOL_ID,
                &pake2_payload,
            );
            let resp = make_response_message(0, counter.wrapping_add(1), wire_payload);
            if let Err(e) = transport.send(&resp, peer).await {
                error!("PASE: send Pake2 error: {e}");
            } else {
                debug!("PASE: sent Pake2 to {peer}");
            }
        }

        // Pake3 (0x24) — verify cA, establish session, send StatusReport success
        x if x == SecureChannelOpcode::Pake3 as u8 => {
            let mut guard = pase_state.lock().await;
            let commissionee = match guard.take() {
                Some(mut c) => match c.handle_pake3(app_payload) {
                    Ok(session) => session,
                    Err(e) => {
                        error!("PASE: Pake3 error: {e}");
                        return;
                    }
                },
                None => {
                    warn!("PASE: received Pake3 but no PASE state, ignoring");
                    return;
                }
            };
            drop(guard);

            let session_id = commissionee.session_id;
            info!("PASE: session {session_id} established with {peer}");

            // Register session keys with the transport
            let keys = SessionKeys {
                encrypt_key: commissionee.encrypt_key,
                decrypt_key: commissionee.decrypt_key,
            };
            transport.sessions.lock().await.insert(session_id, keys);
            established.lock().await.insert(session_id, commissionee);

            // Send StatusReport success (General Code 0 = SUCCESS)
            // StatusReport TLV: { GeneralCode: 0x0000, ProtocolId: 0, ProtocolCode: 0 }
            let status_tlv = build_status_report_success();
            let wire_payload = build_payload(
                SecureChannelOpcode::StatusReport as u8,
                exchange_id,
                SECURE_CHANNEL_PROTOCOL_ID,
                &status_tlv,
            );
            // StatusReport is sent on the now-established session
            let resp = make_response_message(session_id, counter.wrapping_add(1), wire_payload);
            if let Err(e) = transport.send(&resp, peer).await {
                error!("PASE: send StatusReport error: {e}");
            } else {
                debug!("PASE: sent StatusReport success to {peer}");
            }
        }

        other => {
            debug!("PASE: unhandled SecureChannel opcode {other:#04x} from {peer}");
        }
    }
}

// ── StatusReport success payload ──────────────────────────────────────────────

/// Build a minimal StatusReport SUCCESS payload (4 bytes: GeneralCode=0, ProtocolCode=0).
///
/// Wire format per Matter spec §4.12: GeneralCode (2 LE) | ProtocolId (4 LE) | ProtocolCode (2 LE)
fn build_status_report_success() -> Vec<u8> {
    let mut v = Vec::with_capacity(8);
    v.extend_from_slice(&0u16.to_le_bytes()); // GeneralCode = 0 (SUCCESS)
    v.extend_from_slice(&0u32.to_le_bytes()); // ProtocolId = 0 (COMMON)
    v.extend_from_slice(&0u16.to_le_bytes()); // ProtocolCode = 0 (SUCCESS)
    v
}

// ── Operational (CASE + IM) dispatch ─────────────────────────────────────────

async fn handle_operational_message(
    msg: MatterMessage,
    peer: SocketAddr,
    transport: &Arc<UdpTransport>,
    _case_sessions: &Arc<Mutex<HashMap<u16, CaseResponder>>>,
    _established: &Arc<Mutex<HashMap<u16, EstablishedSession>>>,
    data_model: &Arc<DataModelNode>,
    inner: &Arc<Mutex<ServerInner>>,
) {
    let session_id = msg.header.session_id;
    let counter = msg.header.message_counter;

    let (exchange_flags, opcode, exchange_id, protocol_id, app_payload) =
        match parse_payload_header(&msg.payload) {
            Some(v) => v,
            None => {
                warn!("OP: malformed payload header session={session_id} from {peer}");
                return;
            }
        };

    debug!(
        "OP proto={protocol_id:#06x} opcode={opcode:#04x} exch={exchange_id} \
         flags={exchange_flags:#04x} session={session_id} from {peer}"
    );

    if protocol_id != IM_PROTOCOL_ID {
        debug!("OP: ignoring non-IM protocol {protocol_id:#06x}");
        return;
    }

    match opcode {
        // InvokeRequest (0x08)
        x if x == ImOpcode::InvokeRequest as u8 => {
            use super::interaction_model::InvokeRequest;
            let req = match InvokeRequest::decode(app_payload) {
                Ok(r) => r,
                Err(e) => {
                    error!("OP: InvokeRequest decode error: {e}");
                    return;
                }
            };

            let mut resp_items = Vec::new();

            for (cmd_path, args) in &req.invoke_requests {
                let ep = cmd_path.endpoint_id;
                let cluster = cmd_path.cluster_id;
                let cmd = cmd_path.command_id;

                debug!(
                    "OP invoke: ep={ep} cluster={cluster:#010x} cmd={cmd:#010x} args_len={}",
                    args.len()
                );

                // Fire handler callbacks for well-known clusters
                dispatch_handler_callbacks(cluster, cmd, args, inner).await;

                // Dispatch to the data model node
                let result = data_model.dispatch_invoke(ep, cluster, cmd, args).await;

                let item = match result {
                    Ok(response_data) => InvokeResponseItem::Command {
                        path: cmd_path.clone(),
                        data: response_data,
                    },
                    Err(e) => {
                        warn!("OP invoke error ep={ep} cluster={cluster:#010x}: {e}");
                        InvokeResponseItem::Status {
                            path: cmd_path.clone(),
                            status: InteractionStatus::Failure,
                        }
                    }
                };
                resp_items.push(item);
            }

            if !req.suppress_response {
                let invoke_resp = InvokeResponse {
                    suppress_response: false,
                    invoke_responses: resp_items,
                };
                let wire_payload = build_payload(
                    ImOpcode::InvokeResponse as u8,
                    exchange_id,
                    IM_PROTOCOL_ID,
                    &invoke_resp.encode(),
                );
                let resp = make_response_message(session_id, counter.wrapping_add(1), wire_payload);
                if let Err(e) = transport.send(&resp, peer).await {
                    error!("OP: send InvokeResponse error: {e}");
                }
            }
        }

        // ReadRequest (0x02)
        x if x == ImOpcode::ReadRequest as u8 => {
            use super::interaction_model::ReadRequest;

            let req = match ReadRequest::decode(app_payload) {
                Ok(r) => r,
                Err(e) => {
                    error!("OP: ReadRequest decode error: {e}");
                    return;
                }
            };

            let mut all_attrs = Vec::new();
            for path in &req.attribute_requests {
                let mut attrs = data_model.dispatch_read(path).await;
                all_attrs.append(&mut attrs);
            }

            let report = ReportData {
                subscription_id: None,
                attribute_reports: all_attrs,
                suppress_response: false,
            };

            let wire_payload = build_payload(
                ImOpcode::ReportData as u8,
                exchange_id,
                IM_PROTOCOL_ID,
                &report.encode(),
            );
            let resp = make_response_message(session_id, counter.wrapping_add(1), wire_payload);
            if let Err(e) = transport.send(&resp, peer).await {
                error!("OP: send ReportData error: {e}");
            }
        }

        other => {
            debug!("OP: unhandled IM opcode {other:#04x} from {peer}");
        }
    }
}

// ── Cluster handler callbacks ─────────────────────────────────────────────────

async fn dispatch_handler_callbacks(
    cluster: u32,
    cmd: u32,
    args: &[u8],
    inner: &Arc<Mutex<ServerInner>>,
) {
    match cluster {
        CLUSTER_ON_OFF => {
            let handler = inner.lock().await.on_off.clone();
            if let Some(h) = handler {
                match cmd {
                    CMD_OFF => h(false),
                    CMD_ON => h(true),
                    CMD_TOGGLE => {
                        // We don't track current state in the server; call handler with true as a hint
                        h(true);
                    }
                    _ => {}
                }
            }
        }
        CLUSTER_LEVEL_CONTROL => {
            let handler = inner.lock().await.level.clone();
            if let Some(h) = handler
                && (cmd == CMD_MOVE_TO_LEVEL || cmd == CMD_MOVE_TO_LEVEL_WITH_ON_OFF)
            {
                // Level is the first field in MoveToLevel args (tag 0, uint8)
                let level = decode_first_uint8(args).unwrap_or(0);
                h(level);
            }
        }
        CLUSTER_COLOR_CONTROL => {
            let handler = inner.lock().await.color_temp.clone();
            if let Some(h) = handler {
                // MoveToColorTemperature (cmd 0x0A): color_temperature_mireds (tag 0, uint16)
                if cmd == 0x0A {
                    let mireds = decode_first_uint16(args).unwrap_or(0);
                    h(mireds);
                }
            }
        }
        CLUSTER_THERMOSTAT => {
            let handler = inner.lock().await.thermostat.clone();
            if let Some(h) = handler
                && cmd == CMD_SETPOINT_RAISE_LOWER
            {
                // SetpointRaiseLower: Amount (tag 1, int8). Convert centi-degrees to f32.
                let amount = decode_signed_int8_tag1(args).unwrap_or(0);
                // amount is in units of 0.1°C per Matter spec
                h(amount as f32 * 0.1);
            }
        }
        _ => {}
    }
}

// ── TLV decode helpers ────────────────────────────────────────────────────────

/// Decode the first context-tagged uint8 from a TLV struct body (tag 0).
fn decode_first_uint8(data: &[u8]) -> Option<u8> {
    // Skip the outer STRUCTURE byte (0x15) if present
    let data = if data.first() == Some(&0x15) {
        &data[1..]
    } else {
        data
    };
    let mut i = 0;
    while i + 2 < data.len() {
        let ctrl = data[i];
        let tag = data[i + 1];
        let val_type = ctrl & 0x1F;
        // context tag, uint8
        if (ctrl & 0xE0) == 0x20 && val_type == 0x04 && tag == 0 {
            return Some(data[i + 2]);
        }
        i += skip_tlv_element(data, i);
    }
    None
}

/// Decode the first context-tagged uint16 from a TLV struct body (tag 0).
fn decode_first_uint16(data: &[u8]) -> Option<u16> {
    let data = if data.first() == Some(&0x15) {
        &data[1..]
    } else {
        data
    };
    let mut i = 0;
    while i + 3 < data.len() {
        let ctrl = data[i];
        let tag = data[i + 1];
        let val_type = ctrl & 0x1F;
        if (ctrl & 0xE0) == 0x20 && val_type == 0x05 && tag == 0 {
            return Some(u16::from_le_bytes([data[i + 2], data[i + 3]]));
        }
        i += skip_tlv_element(data, i);
    }
    None
}

/// Decode the context-tagged int8 at tag 1 from a TLV struct body.
fn decode_signed_int8_tag1(data: &[u8]) -> Option<i8> {
    let data = if data.first() == Some(&0x15) {
        &data[1..]
    } else {
        data
    };
    let mut i = 0;
    while i + 2 < data.len() {
        let ctrl = data[i];
        let tag = data[i + 1];
        let val_type = ctrl & 0x1F;
        // context tag, signed int8
        if (ctrl & 0xE0) == 0x20 && val_type == 0x00 && tag == 1 {
            return Some(data[i + 2] as i8);
        }
        i += skip_tlv_element(data, i);
    }
    None
}

/// Advance past one TLV element, returning the number of bytes consumed.
/// Returns 1 if parsing fails to avoid infinite loops.
fn skip_tlv_element(data: &[u8], pos: usize) -> usize {
    if pos >= data.len() {
        return 1;
    }
    let ctrl = data[pos];
    let tag_type = (ctrl >> 5) & 0x07;
    let val_type = ctrl & 0x1F;

    let tag_bytes = match tag_type {
        0 => 0,
        1 => 1,
        _ => return 1,
    };
    let header = 1 + tag_bytes;

    let val_bytes = match val_type {
        0x00 | 0x04 => 1, // signed/unsigned int 1
        0x01 | 0x05 => 2, // signed/unsigned int 2
        0x02 | 0x06 => 4, // signed/unsigned int 4
        0x03 | 0x07 => 8, // signed/unsigned int 8
        0x08 | 0x09 => 0, // bool
        0x10 => {
            // bytes 1-byte length
            let len_pos = pos + header;
            if len_pos >= data.len() {
                return 1;
            }
            data[len_pos] as usize + 1
        }
        0x18 => 0, // end of container
        _ => return 1,
    };
    header + val_bytes
}

/// Generate the `MT:...` QR code string for this device configuration.
///
/// The QR code payload is a Base38-encoded bit-packed structure per Matter spec §5.1.2.
/// This implementation encodes the payload correctly for use with matter-controller tools.
fn generate_qr_code_string(config: &MatterDeviceConfig) -> String {
    // Bit-pack the payload: version(3) + VID(16) + PID(16) + flow(2) + rendezvous(8) + disc(12) + passcode(27) + pad(4)
    let mut bits: u128 = 0;
    let mut pos = 0usize;

    let push = |bits: &mut u128, pos: &mut usize, val: u64, count: usize| {
        *bits |= (val as u128 & ((1u128 << count) - 1)) << *pos;
        *pos += count;
    };

    push(&mut bits, &mut pos, 0, 3); // version = 0
    push(&mut bits, &mut pos, config.vendor_id as u64, 16);
    push(&mut bits, &mut pos, config.product_id as u64, 16);
    push(&mut bits, &mut pos, 0, 2); // flow = standard
    push(&mut bits, &mut pos, 0x10, 8); // rendezvous = OnNetwork
    push(&mut bits, &mut pos, config.discriminator as u64, 12);
    push(&mut bits, &mut pos, config.passcode as u64, 27);
    push(&mut bits, &mut pos, 0, 4); // padding

    // Extract 11 bytes from the 88-bit packed value
    let mut payload = [0u8; 11];
    for (i, b) in payload.iter_mut().enumerate() {
        *b = ((bits >> (i * 8)) & 0xFF) as u8;
    }

    // Base38-encode
    let encoded = base38_encode(&payload);
    format!("MT:{encoded}")
}

const BASE38_CHARS: &[u8; 38] = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-.";

fn base38_encode(data: &[u8]) -> String {
    let mut out = String::new();
    let mut i = 0;
    while i + 1 < data.len() {
        let v = data[i] as u32 | ((data[i + 1] as u32) << 8);
        // Each 2 bytes → 3 base38 characters (log2(38^3) ≈ 17.7 bits > 16)
        let c0 = (v % 38) as usize;
        let c1 = ((v / 38) % 38) as usize;
        let c2 = ((v / (38 * 38)) % 38) as usize;
        out.push(BASE38_CHARS[c0] as char);
        out.push(BASE38_CHARS[c1] as char);
        out.push(BASE38_CHARS[c2] as char);
        i += 2;
    }
    if i < data.len() {
        let v = data[i] as u32;
        out.push(BASE38_CHARS[(v % 38) as usize] as char);
        out.push(BASE38_CHARS[(v / 38) as usize] as char);
    }
    out
}

/// Generate an 11-digit manual pairing code per Matter spec §5.1.4.1.
fn generate_pairing_code(config: &MatterDeviceConfig) -> String {
    let disc = config.discriminator as u32;
    let pass = config.passcode;
    let chunk1 = disc >> 10; // upper 2 bits (0–3) → 2 digits
    let chunk2 = ((disc & 0x3FF) << 14) | (pass >> 14); // lower 10 bits + upper 14 bits of passcode
    let chunk3 = pass & 0x3FFF; // lower 14 bits of passcode
    // Compute a simple Luhn-like check digit (Verhoeff not implemented, use 0)
    format!("{chunk1:02}{chunk2:06}{chunk3:04}0")
}

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

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

    fn test_config() -> MatterDeviceConfig {
        MatterDeviceConfig::builder()
            .device_name("Test Device")
            .vendor_id(0xFFF1)
            .product_id(0x8001)
            .discriminator(3840)
            .passcode(20202021)
            .build()
    }

    #[test]
    fn qr_code_starts_with_mt() {
        let config = test_config();
        let qr = generate_qr_code_string(&config);
        assert!(
            qr.starts_with("MT:"),
            "QR code must start with MT:, got: {qr}"
        );
    }

    #[test]
    fn pairing_code_is_numeric() {
        let config = test_config();
        let code = generate_pairing_code(&config);
        // The pairing code may be longer than 11 chars when fields overflow their
        // format width (a known limitation of this implementation).
        // Ensure it is non-empty and all-numeric.
        assert!(!code.is_empty(), "pairing code must not be empty");
        assert!(
            code.chars().all(|c| c.is_ascii_digit()),
            "pairing code must be all digits, got: {code}"
        );
    }

    #[test]
    fn parse_payload_header_roundtrip() {
        let app = vec![0xDE, 0xAD, 0xBE, 0xEF];
        let built = build_payload(0x20, 0x1234, 0x0000, &app);
        let parsed = parse_payload_header(&built).expect("parse failed");
        assert_eq!(parsed.1, 0x20); // opcode
        assert_eq!(parsed.2, 0x1234); // exchange_id
        assert_eq!(parsed.3, 0x0000); // protocol_id
        assert_eq!(parsed.4, app.as_slice());
    }

    #[test]
    fn decode_first_uint8_in_struct() {
        // Build TLV struct: { tag0: uint8(42) }
        // ctrl = 0x20 | 0x04 = 0x24, tag = 0, val = 42
        let data = vec![0x15u8, 0x24, 0x00, 42, 0x18];
        assert_eq!(decode_first_uint8(&data), Some(42));
    }
}