darra-ethercat-master 2.0.7

商业 EtherCAT 主站协议栈 · 实时内核驱动 · 抖动 1µs · Windows + Linux · 多编程语言 · 全协议 · 支持复杂拓扑 + 热插拔 · ethercat.darra.xyz · Commercial EtherCAT Master protocol stack · Real-time kernel driver · 1µs jitter · Multi-platform · Multi-language · Complex topology + hot-plug.
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
//! 事件系统
//!
//! 提供 MasterEvents 和 SlaveEvents 结构体,封装 DLL 回调事件。
//! 通过 `EtherCATMaster::events()` 获取主站事件集合。
//!
//! # 多 master 路由 + RT-safe 回调
//!
//! 全局回调表按 `master_index` 分桶 (`HashMap<u16, Vec<Arc<dyn Fn>>>`),
//! 由 `RwLock` 保护。PDO 1kHz 实时回调在 dispatcher 中只持读锁,
//! 多个用户回调并发触发时不互相阻塞 (RwLock read 开销 ~50ns)。
//!
//! 注册 / 清理走写锁, 仅在 `MasterEvents::on_*` 和 `Drop` 时短暂触发。
//!
//! `EtherCATMaster::drop()` 会调用 [`clear_master_callbacks`] 移除本 master
//! 的所有闭包, 释放它们捕获的引用, 防止 ghost 事件 + 内存泄漏。

use crate::utils::ffi;
use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, RwLock};

// ===================== 回调列表类型别名 =====================
//
// 每个 master_index 一个 Vec<Arc<dyn Fn>>; 回调必须 Send + Sync,
// 因为 dispatcher 在任意 DLL 线程触发, 而注册可能发生在其他线程。

/// 表内单条回调的类型 (按签名分别定义)
type CbPdoCyclic = Arc<dyn Fn(u16) + Send + Sync + 'static>;
type CbSlaveStateChange = Arc<dyn Fn(u16, u16, i32, i32) + Send + Sync + 'static>;
type CbEmergency = Arc<dyn Fn(u16, u16, u16, u16, u8, u16, u16) + Send + Sync + 'static>;
type CbSlaveDiscovery = Arc<dyn Fn(u16, u16, bool) + Send + Sync + 'static>;
type CbPdoFrameLoss = Arc<dyn Fn(u16, u8, u32, u32) + Send + Sync + 'static>;
type CbDcSyncLost = Arc<dyn Fn(u16, u16, i32) + Send + Sync + 'static>;
type CbRedundancyChanged = Arc<dyn Fn(u16, i32, i32) + Send + Sync + 'static>;
// 注意: *const u8 raw pointer 不是 Send/Sync, 但只在 Fn 签名上 (非闭包捕获),
// 所以闭包本身可以 Send + Sync — 用 ptr 转 usize 包一下避免 trait bound 失败。
type CbInputChanged = Arc<dyn Fn(u16, usize, u16) + Send + Sync + 'static>;
type CbPreOpReconfig = Arc<dyn Fn(u16, u16) + Send + Sync + 'static>;
type CbSlaveIdentityMismatch = Arc<dyn Fn(SlaveIdentityMismatch) + Send + Sync + 'static>;
type CbSlavePortLinkChanged = Arc<dyn Fn(u16, u16, u8, bool) + Send + Sync + 'static>;

/// 按 master_index 分桶的回调表
type Table<C> = RwLock<HashMap<u16, Vec<C>>>;

// ===================== 事件数据结构 =====================

/// 从站身份不符事件参数 (v2 热插拔自修复)
///
/// 触发时机: 断电重插从站后 ident FSM 读取到的 Vendor/Product 与配置不匹配,
/// 或 Revision 低于配置 (向后兼容: actual >= configured 视为匹配).
///
/// 去重: 进入 IDENT_REJECTED 状态时仅触发一次, 需调用
/// [`crate::master::core::EtherCATMaster::acknowledge_slave_replacement`]
/// 后才会重新探测并可能再次触发.
#[derive(Debug, Clone, Copy)]
pub struct SlaveIdentityMismatch {
    /// 主站索引
    pub master_index: u16,
    /// 从站索引 (1-based)
    pub slave_index: u16,
    /// 配置期望的厂商 ID
    pub expected_vendor: u32,
    /// 配置期望的产品代码
    pub expected_product: u32,
    /// 配置期望的最低修订号
    pub expected_revision: u32,
    /// 当前实测厂商 ID
    pub actual_vendor: u32,
    /// 当前实测产品代码
    pub actual_product: u32,
    /// 当前实测修订号
    pub actual_revision: u32,
}

// ===================== 全局回调表 (静态, RwLock 保护) =====================

macro_rules! table_static {
    ($name:ident, $cb_ty:ty) => {
        fn $name() -> &'static Table<$cb_ty> {
            use std::sync::OnceLock;
            static INSTANCE: OnceLock<Table<$cb_ty>> = OnceLock::new();
            INSTANCE.get_or_init(|| RwLock::new(HashMap::new()))
        }
    };
}

table_static!(pdo_cyclic_sync_table, CbPdoCyclic);
table_static!(pdo_cyclic_async_table, CbPdoCyclic);
table_static!(slave_state_change_table, CbSlaveStateChange);
table_static!(slave_state_change_async_table, CbSlaveStateChange);
table_static!(emergency_table, CbEmergency);
table_static!(slave_discovery_table, CbSlaveDiscovery);
table_static!(slave_discovery_async_table, CbSlaveDiscovery);
table_static!(pdo_frame_loss_table, CbPdoFrameLoss);
table_static!(dc_sync_lost_table, CbDcSyncLost);
table_static!(redundancy_changed_table, CbRedundancyChanged);
table_static!(input_changed_table, CbInputChanged);
table_static!(preop_reconfig_table, CbPreOpReconfig);
table_static!(slave_identity_mismatch_table, CbSlaveIdentityMismatch);
table_static!(slave_port_link_changed_table, CbSlavePortLinkChanged);

/// 离线从站追踪集合 (按 master_index 分桶, 与回调路由一致)
fn offline_slaves() -> &'static Mutex<HashMap<u16, HashSet<u16>>> {
    use std::sync::OnceLock;
    static INSTANCE: OnceLock<Mutex<HashMap<u16, HashSet<u16>>>> = OnceLock::new();
    INSTANCE.get_or_init(|| Mutex::new(HashMap::new()))
}

// ===================== DLL dispatcher 注册 (仅一次) =====================
//
// 用 AtomicBool 一次性 latch, 类似 C# `_dispatcherRegistered` 模式。
// initialize_callbacks() 可被多次调用 (每个 MasterEvents::new 都会调),
// 但 DLL 注册仅执行一次。

static DISPATCHER_REGISTERED: AtomicBool = AtomicBool::new(false);

/// 初始化 DLL 回调注册
///
/// 在首次创建 `MasterEvents` 时自动调用, 确保只注册一次。
/// 也可手动调用以提前注册。
pub fn initialize_callbacks() {
    // compare_exchange 防止两个线程同时进入注册区
    if DISPATCHER_REGISTERED
        .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
        .is_err()
    {
        return;
    }
    unsafe {
        ffi::RegisterProcessDataCyclicCallbackSync(on_pdo_cyclic_sync);
        ffi::RegisterProcessDataCyclicCallbackAsync(on_pdo_cyclic_async);
        ffi::RegisterSlaveStateChangeCallbackSync(on_slave_state_change);
        ffi::RegisterSlaveStateChangeCallbackAsync(on_slave_state_change_async);
        ffi::RegisterEmergencyEventCallback(on_emergency);
        ffi::RegisterSlaveDiscoveryCallbackSync(on_slave_discovery);
        ffi::RegisterSlaveDiscoveryCallbackAsync(on_slave_discovery_async);
        ffi::RegisterPDOFrameLossCallback(on_pdo_frame_loss);
        ffi::SetDCSyncLostCallback(on_dc_sync_lost);
        ffi::RegisterRedundancyModeChangedCallback(on_redundancy_changed);
        ffi::RegisterInputDataChangedCallback(on_input_changed);
        ffi::RegisterSlavePreOpReconfigCallback(on_preop_reconfig);
        ffi::RegisterSlaveIdentityMismatchCallback(on_slave_identity_mismatch);
        ffi::RegisterSlavePortLinkChangedCallback(on_slave_port_link_changed);
    }
}

// ===================== 回调注册/查询辅助 =====================

/// 把回调追加到指定 master 的桶里 (write lock, 仅在订阅时短暂触发)
fn push_cb<C: Clone>(table: &Table<C>, mi: u16, cb: C) {
    if let Ok(mut guard) = table.write() {
        guard.entry(mi).or_default().push(cb);
    }
}

/// 取该 master 的回调快照 (read lock; clone Arc 列表后立即释放锁,
/// 用户回调执行不持锁, 避免长时间阻塞写者)
fn snapshot<C: Clone>(table: &Table<C>, mi: u16) -> Option<Vec<C>> {
    let guard = table.read().ok()?;
    guard.get(&mi).map(|v| v.clone())
}

// ===================== 静态 extern "C" 回调 (按 master_index 路由) =====================
// [2026-05-09] 用户 closure 跨 FFI panic 是 UB. 所有 dispatcher 用 catch_unwind 包.
//   闭包内的 panic 不会穿越 C 调用栈, 仅在 stderr 输出 + dispatcher 安全继续.
use std::panic::{catch_unwind, AssertUnwindSafe};

#[inline]
fn safe_invoke<F: FnOnce() + ::std::panic::UnwindSafe>(name: &'static str, f: F) {
    if let Err(_e) = catch_unwind(AssertUnwindSafe(f)) {
        eprintln!("[Darra events] callback {} panicked (caught at FFI boundary)", name);
    }
}

extern "C" fn on_pdo_cyclic_sync(master_index: u16) {
    if let Some(cbs) = snapshot(pdo_cyclic_sync_table(), master_index) {
        for cb in cbs.iter() {
            safe_invoke("on_pdo_cyclic_sync", || cb(master_index));
        }
    }
}

extern "C" fn on_pdo_cyclic_async(master_index: u16) {
    if let Some(cbs) = snapshot(pdo_cyclic_async_table(), master_index) {
        for cb in cbs.iter() {
            safe_invoke("dispatcher", || cb(master_index));
        }
    }
}

extern "C" fn on_slave_state_change(master_index: u16, slave_index: u16, old_state: i32, new_state: i32) {
    if let Some(cbs) = snapshot(slave_state_change_table(), master_index) {
        for cb in cbs.iter() {
            safe_invoke("state_change_dispatcher", || cb(master_index, slave_index, old_state, new_state));
        }
    }
}

extern "C" fn on_slave_state_change_async(master_index: u16, slave_index: u16, old_state: i32, new_state: i32) {
    if let Some(cbs) = snapshot(slave_state_change_async_table(), master_index) {
        for cb in cbs.iter() {
            safe_invoke("state_change_dispatcher", || cb(master_index, slave_index, old_state, new_state));
        }
    }
}

extern "C" fn on_emergency(
    master_index: u16, slave_index: u16,
    error_code: u16, error_reg: u16, b1: u8, w1: u16, w2: u16,
) {
    if let Some(cbs) = snapshot(emergency_table(), master_index) {
        for cb in cbs.iter() {
            safe_invoke("emergency", || cb(master_index, slave_index, error_code, error_reg, b1, w1, w2));
        }
    }
}

extern "C" fn on_slave_discovery(master_index: u16, slave_index: u16, is_found: i32) {
    let found = is_found != 0;

    // 更新本 master 的离线追踪集合 (按 master_index 分桶, 防止跨 master 串号)
    if let Ok(mut map) = offline_slaves().lock() {
        let set = map.entry(master_index).or_default();
        if found {
            set.remove(&slave_index);
        } else {
            set.insert(slave_index);
        }
    }

    if let Some(cbs) = snapshot(slave_discovery_table(), master_index) {
        for cb in cbs.iter() {
            safe_invoke("discovery", || cb(master_index, slave_index, found));
        }
    }
}

extern "C" fn on_slave_discovery_async(master_index: u16, slave_index: u16, is_found: i32) {
    let found = is_found != 0;
    if let Some(cbs) = snapshot(slave_discovery_async_table(), master_index) {
        for cb in cbs.iter() {
            safe_invoke("discovery", || cb(master_index, slave_index, found));
        }
    }
}

extern "C" fn on_pdo_frame_loss(master_index: u16, group: u8, consecutive: u32, total: u32) {
    if let Some(cbs) = snapshot(pdo_frame_loss_table(), master_index) {
        for cb in cbs.iter() {
            safe_invoke("pdo_frame_loss", || cb(master_index, group, consecutive, total));
        }
    }
}

extern "C" fn on_dc_sync_lost(master_index: u16, slave_index: u16, diff_ns: i32) {
    if let Some(cbs) = snapshot(dc_sync_lost_table(), master_index) {
        for cb in cbs.iter() {
            safe_invoke("dc_sync_lost", || cb(master_index, slave_index, diff_ns));
        }
    }
}

extern "C" fn on_redundancy_changed(master_index: u16, old_mode: i32, new_mode: i32) {
    if let Some(cbs) = snapshot(redundancy_changed_table(), master_index) {
        for cb in cbs.iter() {
            safe_invoke("redundancy_changed", || cb(master_index, old_mode, new_mode));
        }
    }
}

extern "C" fn on_input_changed(master_index: u16, changed_slave_bits: *const u8, changed_count: u16) {
    let bits_addr = changed_slave_bits as usize;
    if let Some(cbs) = snapshot(input_changed_table(), master_index) {
        for cb in cbs.iter() {
            safe_invoke("input_changed", || cb(master_index, bits_addr, changed_count));
        }
    }
}

extern "C" fn on_preop_reconfig(master_index: u16, slave_index: u16) {
    if let Some(cbs) = snapshot(preop_reconfig_table(), master_index) {
        for cb in cbs.iter() {
            safe_invoke("preop_reconfig", || cb(master_index, slave_index));
        }
    }
}

extern "C" fn on_slave_identity_mismatch(
    master_index: u16,
    slave_index: u16,
    expected_vendor: u32,
    expected_product: u32,
    expected_revision: u32,
    actual_vendor: u32,
    actual_product: u32,
    actual_revision: u32,
) {
    let args = SlaveIdentityMismatch {
        master_index,
        slave_index,
        expected_vendor,
        expected_product,
        expected_revision,
        actual_vendor,
        actual_product,
        actual_revision,
    };
    if let Some(cbs) = snapshot(slave_identity_mismatch_table(), master_index) {
        for cb in cbs.iter() {
            safe_invoke("identity_mismatch", || cb(args));
        }
    }
}

extern "C" fn on_slave_port_link_changed(master_index: u16, slave_index: u16, port: u8, is_up: i32) {
    let up = is_up != 0;
    if let Some(cbs) = snapshot(slave_port_link_changed_table(), master_index) {
        for cb in cbs.iter() {
            cb(master_index, slave_index, port, up);
        }
    }
}

// ===================== Drop 清理 (供 EtherCATMaster::drop 调用) =====================

/// 清空指定 master 的所有事件订阅
///
/// 由 `EtherCATMaster::drop` 调用, 释放本 master 的所有用户闭包,
/// 避免 ghost 事件 (master 已 dispose, 但闭包还活着) + 内存泄漏。
///
/// 跨 master 桶不影响, 其他 master 的订阅原样保留。
pub(crate) fn clear_master_callbacks(mi: u16) {
    macro_rules! clear {
        ($t:expr) => {
            if let Ok(mut g) = $t.write() {
                g.remove(&mi);
            }
        };
    }
    clear!(pdo_cyclic_sync_table());
    clear!(pdo_cyclic_async_table());
    clear!(slave_state_change_table());
    clear!(slave_state_change_async_table());
    clear!(emergency_table());
    clear!(slave_discovery_table());
    clear!(slave_discovery_async_table());
    clear!(pdo_frame_loss_table());
    clear!(dc_sync_lost_table());
    clear!(redundancy_changed_table());
    clear!(input_changed_table());
    clear!(preop_reconfig_table());
    clear!(slave_identity_mismatch_table());
    clear!(slave_port_link_changed_table());

    if let Ok(mut map) = offline_slaves().lock() {
        map.remove(&mi);
    }
}

// ===================== MasterEvents =====================

/// 主站事件集合
///
/// 通过 `EtherCATMaster::events()` 获取实例。
/// 提供所有 DLL 回调事件的注册接口。
///
/// # 示例
/// ```no_run
/// let master = EtherCATMaster::new().unwrap();
/// let events = master.events();
/// events.on_pdo_cyclic_async(|master_idx| {
///     // PDO 周期回调
/// });
/// events.on_slave_offline(|slave_idx| {
///     println!("从站 {} 离线", slave_idx);
/// });
/// ```
pub struct MasterEvents {
    master_index: u16,
}

impl MasterEvents {
    /// 创建主站事件集合 (内部使用)
    pub(crate) fn new(master_index: u16) -> Self {
        // 确保 DLL dispatcher 已注册 (一次性)
        initialize_callbacks();
        Self { master_index }
    }

    /// 注册 PDO 周期同步回调 (在实时线程中直接执行, 必须快速返回)
    pub fn on_pdo_cyclic_sync<F>(&self, callback: F)
    where
        F: Fn(u16) + Send + Sync + 'static,
    {
        push_cb(pdo_cyclic_sync_table(), self.master_index, Arc::new(callback));
    }

    /// 注册 PDO 周期异步回调 (不阻塞实时线程, 推荐)
    pub fn on_pdo_cyclic_async<F>(&self, callback: F)
    where
        F: Fn(u16) + Send + Sync + 'static,
    {
        push_cb(pdo_cyclic_async_table(), self.master_index, Arc::new(callback));
    }

    /// 注册从站状态变化回调
    ///
    /// 回调参数: (master_index, slave_index, old_state, new_state)
    pub fn on_slave_state_changed<F>(&self, callback: F)
    where
        F: Fn(u16, u16, i32, i32) + Send + Sync + 'static,
    {
        push_cb(slave_state_change_table(), self.master_index, Arc::new(callback));
    }

    /// 注册从站状态变化异步回调 (不阻塞实时线程, 推荐)
    pub fn on_slave_state_changed_async<F>(&self, callback: F)
    where
        F: Fn(u16, u16, i32, i32) + Send + Sync + 'static,
    {
        push_cb(slave_state_change_async_table(), self.master_index, Arc::new(callback));
    }

    /// 注册紧急事件回调 (EMCY)
    pub fn on_emergency<F>(&self, callback: F)
    where
        F: Fn(u16, u16, u16, u16, u8, u16, u16) + Send + Sync + 'static,
    {
        push_cb(emergency_table(), self.master_index, Arc::new(callback));
    }

    /// 注册从站离线回调
    pub fn on_slave_offline<F>(&self, callback: F)
    where
        F: Fn(u16) + Send + Sync + 'static,
    {
        let cb: CbSlaveDiscovery = Arc::new(move |_master: u16, slave: u16, found: bool| {
            if !found {
                callback(slave);
            }
        });
        push_cb(slave_discovery_table(), self.master_index, cb);
    }

    /// 注册从站上线回调
    pub fn on_slave_online<F>(&self, callback: F)
    where
        F: Fn(u16) + Send + Sync + 'static,
    {
        let cb: CbSlaveDiscovery = Arc::new(move |_master: u16, slave: u16, found: bool| {
            if found {
                callback(slave);
            }
        });
        push_cb(slave_discovery_table(), self.master_index, cb);
    }

    /// 注册从站发现回调 (上线和离线)
    pub fn on_slave_discovery<F>(&self, callback: F)
    where
        F: Fn(u16, u16, bool) + Send + Sync + 'static,
    {
        push_cb(slave_discovery_table(), self.master_index, Arc::new(callback));
    }

    /// 注册从站发现异步回调 (上线和离线, 不阻塞实时线程, 推荐)
    pub fn on_slave_discovery_async<F>(&self, callback: F)
    where
        F: Fn(u16, u16, bool) + Send + Sync + 'static,
    {
        push_cb(slave_discovery_async_table(), self.master_index, Arc::new(callback));
    }

    /// 注册 PDO 丢帧回调
    pub fn on_pdo_frame_loss<F>(&self, callback: F)
    where
        F: Fn(u16, u8, u32, u32) + Send + Sync + 'static,
    {
        push_cb(pdo_frame_loss_table(), self.master_index, Arc::new(callback));
    }

    /// 注册 DC 同步丢失回调
    pub fn on_dc_sync_lost<F>(&self, callback: F)
    where
        F: Fn(u16, u16, i32) + Send + Sync + 'static,
    {
        push_cb(dc_sync_lost_table(), self.master_index, Arc::new(callback));
    }

    /// 注册冗余模式变化回调
    pub fn on_redundancy_mode_changed<F>(&self, callback: F)
    where
        F: Fn(u16, i32, i32) + Send + Sync + 'static,
    {
        push_cb(redundancy_changed_table(), self.master_index, Arc::new(callback));
    }

    /// 注册输入数据变化回调 (原始位图)
    ///
    /// 回调参数: (master_index, changed_slave_bits, changed_count)
    pub fn on_input_data_changed_raw<F>(&self, callback: F)
    where
        F: Fn(u16, *const u8, u16) + Send + Sync + 'static,
    {
        // bits_addr 是 usize, dispatch 时还原成 *const u8 交给用户
        let cb: CbInputChanged = Arc::new(move |master: u16, bits_addr: usize, count: u16| {
            callback(master, bits_addr as *const u8, count);
        });
        push_cb(input_changed_table(), self.master_index, cb);
    }

    /// 注册输入数据变化回调 (解析后的从站列表)
    ///
    /// 回调参数: (master_index, changed_slave_indices)
    /// 自动解析 DLL 位图, 返回变化的从站索引列表
    pub fn on_input_data_changed<F>(&self, callback: F)
    where
        F: Fn(u16, Vec<u16>) + Send + Sync + 'static,
    {
        let cb: CbInputChanged = Arc::new(move |master: u16, bits_addr: usize, count: u16| {
            let bits_ptr = bits_addr as *const u8;
            if bits_ptr.is_null() || count == 0 {
                return;
            }
            let mut slaves = Vec::with_capacity(count as usize);
            let mut found: u16 = 0;
            // 修复: 位图最大字节数 = (count + 7) / 8,防止无限循环越界读取
            let max_bytes = ((count as usize) + 7) / 8;
            let mut byte_idx: usize = 0;
            while found < count && byte_idx < max_bytes {
                let b = unsafe { *bits_ptr.add(byte_idx) };
                if b != 0 {
                    for bit_idx in 0..8u16 {
                        if found >= count {
                            break;
                        }
                        if (b & (1 << bit_idx)) != 0 {
                            slaves.push(byte_idx as u16 * 8 + bit_idx);
                            found += 1;
                        }
                    }
                }
                byte_idx += 1;
            }
            callback(master, slaves);
        });
        push_cb(input_changed_table(), self.master_index, cb);
    }

    /// 注册 PreOp 重配置回调 (热插拔恢复后重新应用启动参数)
    pub fn on_preop_reconfig<F>(&self, callback: F)
    where
        F: Fn(u16, u16) + Send + Sync + 'static,
    {
        push_cb(preop_reconfig_table(), self.master_index, Arc::new(callback));
    }

    /// 注册从站身份不符回调 (v2 热插拔自修复)
    pub fn on_slave_identity_mismatch<F>(&self, callback: F)
    where
        F: Fn(SlaveIdentityMismatch) + Send + Sync + 'static,
    {
        push_cb(slave_identity_mismatch_table(), self.master_index, Arc::new(callback));
    }

    /// 注册从站端口链路变化回调 (断线检测)
    pub fn on_slave_port_link_changed<F>(&self, callback: F)
    where
        F: Fn(u16, u16, u8, bool) + Send + Sync + 'static,
    {
        push_cb(slave_port_link_changed_table(), self.master_index, Arc::new(callback));
    }

    /// 清除本 master 的所有事件订阅, 防止内存泄漏
    ///
    /// 移除所有已注册的回调函数。适用于主站重新初始化或显式清理。
    /// 不影响其他 master 的订阅。
    pub fn clear_all(&self) {
        clear_master_callbacks(self.master_index);
    }

    /// 查询从站是否处于离线状态 (本 master 视角)
    pub fn is_slave_offline(&self, slave_index: u16) -> bool {
        if let Ok(map) = offline_slaves().lock() {
            map.get(&self.master_index)
                .map(|s| s.contains(&slave_index))
                .unwrap_or(false)
        } else {
            false
        }
    }

    /// 获取本 master 所有离线从站索引
    pub fn offline_slaves(&self) -> Vec<u16> {
        if let Ok(map) = offline_slaves().lock() {
            map.get(&self.master_index)
                .map(|s| s.iter().copied().collect())
                .unwrap_or_default()
        } else {
            Vec::new()
        }
    }

    /// 获取本 master 离线从站数量
    pub fn offline_slave_count(&self) -> usize {
        if let Ok(map) = offline_slaves().lock() {
            map.get(&self.master_index).map(|s| s.len()).unwrap_or(0)
        } else {
            0
        }
    }
}

// ===================== SlaveEvents =====================

/// 从站事件集合
///
/// 通过 `Slave::events()` 获取实例。
/// 事件自动过滤到当前从站, 回调参数不含 master_index/slave_index。
pub struct SlaveEvents {
    master_index: u16,
    slave_index: u16,
}

impl SlaveEvents {
    /// 创建从站事件集合 (内部使用)
    pub(crate) fn new(master_index: u16, slave_index: u16) -> Self {
        initialize_callbacks();
        Self { master_index, slave_index }
    }

    /// 注册从站状态变化回调
    pub fn on_state_changed<F>(&self, callback: F)
    where
        F: Fn(i32, i32) + Send + Sync + 'static,
    {
        let target_slave = self.slave_index;
        let cb: CbSlaveStateChange = Arc::new(move |_master, slave, old_state, new_state| {
            if slave == target_slave {
                callback(old_state, new_state);
            }
        });
        push_cb(slave_state_change_table(), self.master_index, cb);
    }

    /// 注册紧急事件回调 (EMCY)
    pub fn on_emergency<F>(&self, callback: F)
    where
        F: Fn(u16, u16, u8, u16, u16) + Send + Sync + 'static,
    {
        let target_slave = self.slave_index;
        let cb: CbEmergency = Arc::new(move |_master, slave, ec, er, b1, w1, w2| {
            if slave == target_slave {
                callback(ec, er, b1, w1, w2);
            }
        });
        push_cb(emergency_table(), self.master_index, cb);
    }

    /// 注册从站离线回调
    pub fn on_offline<F>(&self, callback: F)
    where
        F: Fn() + Send + Sync + 'static,
    {
        let target_slave = self.slave_index;
        let cb: CbSlaveDiscovery = Arc::new(move |_master, slave, found| {
            if slave == target_slave && !found {
                callback();
            }
        });
        push_cb(slave_discovery_table(), self.master_index, cb);
    }

    /// 注册从站上线回调
    pub fn on_online<F>(&self, callback: F)
    where
        F: Fn() + Send + Sync + 'static,
    {
        let target_slave = self.slave_index;
        let cb: CbSlaveDiscovery = Arc::new(move |_master, slave, found| {
            if slave == target_slave && found {
                callback();
            }
        });
        push_cb(slave_discovery_table(), self.master_index, cb);
    }

    /// 注册 DC 同步丢失回调
    pub fn on_dc_sync_lost<F>(&self, callback: F)
    where
        F: Fn(i32) + Send + Sync + 'static,
    {
        let target_slave = self.slave_index;
        let cb: CbDcSyncLost = Arc::new(move |_master, slave, diff_ns| {
            if slave == target_slave {
                callback(diff_ns);
            }
        });
        push_cb(dc_sync_lost_table(), self.master_index, cb);
    }

    /// [2026-05-09 修复] 之前调 `clear_master_callbacks` 把 master 自身订阅 (PDO cyclic / state change /
    ///   emergency / etc.) 也清掉, 用户预期只清 slave 相关却被无声破坏.
    /// 现版本: 此方法标记为 deprecated, 不再清理. SlaveEvents 在当前架构下没有独立的 slave-level 回调表
    /// (per-slave 闭包按 master_index 注册到 master 桶中), 因此无法精确只清 slave 部分.
    /// 如需完全清空本 master (包括 master 自身订阅), 请显式调 `MasterEvents::clear_all()`.
    #[deprecated(since = "1.99.6", note = "noop in current architecture; use MasterEvents::clear_all() to clear the whole master bucket")]
    pub fn clear_all(&self) {
        // 故意 noop — 避免误删 master 自身订阅. 用户应明确意图.
        log::warn!(
            "SlaveEvents::clear_all is a noop (deprecated). Use MasterEvents::clear_all() to clear master_index={}.",
            self.master_index
        );
    }

    /// 注册输入数据变化回调
    pub fn on_input_changed<F>(&self, callback: F)
    where
        F: Fn() + Send + Sync + 'static,
    {
        let target_slave = self.slave_index;
        let cb: CbInputChanged = Arc::new(move |_master, bits_addr, count| {
            let bits_ptr = bits_addr as *const u8;
            if bits_ptr.is_null() || count == 0 {
                return;
            }
            // 修复: 检查位图边界, 防止越界读取
            let byte_idx = (target_slave / 8) as usize;
            let max_bytes = ((count as usize) + 7) / 8;
            if byte_idx >= max_bytes {
                return;
            }
            let bit_idx = target_slave % 8;
            let b = unsafe { *bits_ptr.add(byte_idx) };
            if (b & (1 << bit_idx)) != 0 {
                callback();
            }
        });
        push_cb(input_changed_table(), self.master_index, cb);
    }
}