darra-ethercat-master 2.1.0

商业 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
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
//! SoE (Servo over EtherCAT) 完整实现
//!
//! 对齐 C# SoEInstance,提供:
//! - SoEInstance 结构体 (实例化方式)
//! - 原始字节读写 + 类型化读写 (i16/i32/u16/u32/f32/f64/string)
//! - 参数名称/单位/属性/最小值/最大值读取
//! - 程序命令执行 (SERCOS Procedure Command)
//! - IDN 列表/参数信息/AT/MDT 映射
//! - 通知监控 (启用/禁用/轮询)
//! - SoEParameter/SoEAttributes/SoEDataType 结构体
//!
//! 元素标志 (element_flags) 按 ETG.1000.6:
//!   0x01 = Data State, 0x02 = Name, 0x04 = Attribute, 0x08 = Unit,
//!   0x10 = Min, 0x20 = Max, 0x40 = Value, 0x80 = Default
//!
//! # 异步使用 (对齐 C# SoEInstance.ReadAsync / WriteAsync)
//!
//! 本 crate 提供**双轨**异步 API:
//!
//! ## 轨道 1: std::thread (无依赖, 默认启用)
//!
//! ```ignore
//! // 注: SoEInstance::new 为 pub(crate), 外部请用 Slave::soe() 获取后再转为关联函数
//! let handle = SoEInstance::read_blocking(master, slave, drive, 0x0040, 0x40, 500);
//! let data = handle.join().unwrap()?;
//! ```
//!
//! ## 轨道 2: tokio async (可选 feature `async-tokio`)
//!
//! ```ignore
//! let soe = slave.soe(drive_number);
//! let data = soe.read_async(0x0040, 0x40, 500).await?;
//! soe.write_async(0x0024, value_bytes, 0x40, 500).await?;
//! soe.execute_command_async(0x0127, 5000, 50).await?;
//! ```
//!
//! ## 超时与取消
//!
//! 使用 runtime 的 timeout 原语。DLL 调用无法中断, 超时只让 await 返回。
//! SoE 的 `timeout_ms` 参数是 DLL 内部的邮箱等待超时, 建议 await 侧
//! 至少留 1.5x 余量 (`tokio::time::timeout(1.5x * timeout_ms, ...)`)。

use crate::data::error::{DarraError, Result, SoEErrorCode};
use crate::utils::ffi;
use std::collections::HashMap;
use std::os::raw::c_int;
use std::sync::{Arc, Mutex};
use std::time::SystemTime;

/// SoE 元素标志:数据状态
pub const SOE_ELEM_DATA_STATE: u8 = 0x01;
/// SoE 元素标志:名称
pub const SOE_ELEM_NAME: u8 = 0x02;
/// SoE 元素标志:属性
pub const SOE_ELEM_ATTRIBUTE: u8 = 0x04;
/// SoE 元素标志:单位
pub const SOE_ELEM_UNIT: u8 = 0x08;
/// SoE 元素标志:最小值
pub const SOE_ELEM_MIN: u8 = 0x10;
/// SoE 元素标志:最大值
pub const SOE_ELEM_MAX: u8 = 0x20;
/// SoE 元素标志:当前值
pub const SOE_ELEM_VALUE: u8 = 0x40;
/// SoE 元素标志:默认值
pub const SOE_ELEM_DEFAULT: u8 = 0x80;

// ===================== SoE Element Flags (对齐 C# enum SoEElementFlags) =====================

/// SoE Element 位标志 (ETG.1000.6 §5.11 SoEHeader, 7 位位掩码).
///
/// 对齐 C# `SoEElementFlags`. 使用关联常量 + 位运算, 多个位可用 `|` 组合.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
pub struct SoEElementFlags(pub u8);

impl SoEElementFlags {
    pub const NONE:        Self = Self(0x00);
    pub const DATA_STATUS: Self = Self(0x01); // 数据状态字 (valid/invalid/busy)
    pub const NAME:        Self = Self(0x02); // IDN 名称
    pub const ATTRIBUTE:   Self = Self(0x04); // 属性 (类型/长度等)
    pub const UNIT:        Self = Self(0x08); // 单位字符串
    pub const MIN:         Self = Self(0x10); // 最小值
    pub const MAX:         Self = Self(0x20); // 最大值
    pub const VALUE:       Self = Self(0x40); // 操作数据值 (最常用)
    pub const DEFAULT:     Self = Self(0x80); // 默认值

    /// 内部位 -> 原始 u8 (供 DLL 调用)
    pub const fn bits(self) -> u8 { self.0 }

    /// 是否包含指定位
    pub const fn contains(self, other: Self) -> bool {
        (self.0 & other.0) == other.0
    }
}

impl std::ops::BitOr for SoEElementFlags {
    type Output = Self;
    fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) }
}

impl std::ops::BitAnd for SoEElementFlags {
    type Output = Self;
    fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) }
}

impl From<u8> for SoEElementFlags {
    fn from(v: u8) -> Self { Self(v) }
}

impl From<SoEElementFlags> for u8 {
    fn from(f: SoEElementFlags) -> u8 { f.0 }
}

// ===================== SERCOS IDN 编/解码 (对齐 DLL utils.c:SoEIdnEncode/Decode) =====================

/// 将 (Standard?, Set, Block) 三元组编码为 16 位 IDN.
///
/// 与 DLL `SoEIdnEncode` (utils.c:1438) 输出完全一致.
/// bit15 = 0 (标准) / 1 (厂商); bit14..12 = set; bit11..0 = block.
pub fn encode_idn(is_standard: bool, parameter_set: u8, data_block: u16) -> u16 {
    let mut idn: u16 = 0;
    if !is_standard {
        idn |= 0x8000;
    }
    idn |= ((parameter_set as u16) & 0x07) << 12;
    idn |= data_block & 0x0FFF;
    idn
}

/// 将 16 位 IDN 解码为 (is_standard, parameter_set, data_block) 三元组.
///
/// 与 DLL `SoEIdnDecode` (utils.c:1448) 输出完全一致.
pub fn decode_idn(idn: u16) -> (bool, u8, u16) {
    let is_standard = (idn & 0x8000) == 0;
    let parameter_set = ((idn >> 12) & 0x07) as u8;
    let data_block = idn & 0x0FFF;
    (is_standard, parameter_set, data_block)
}

/// 解析 SERCOS IDN 字符串 ("S-0-0040" / "P-1-0123") 为 16 位 IDN, 失败返回 `None`.
pub fn try_parse_sercos_idn(text: &str) -> Option<u16> {
    let parts: Vec<&str> = text.trim().split('-').collect();
    if parts.len() != 3 {
        return None;
    }
    let is_standard = match parts[0].to_ascii_uppercase().as_str() {
        "S" => true,
        "P" => false,
        _ => return None,
    };
    let set: u8 = parts[1].parse().ok()?;
    let block: u16 = parts[2].parse().ok()?;
    if set > 7 || block > 0x0FFF {
        return None;
    }
    Some(encode_idn(is_standard, set, block))
}

/// 格式化 16 位 IDN 为 "S-x-xxxx" / "P-x-xxxx" 字符串.
pub fn format_sercos_idn(idn: u16) -> String {
    let (is_standard, set, block) = decode_idn(idn);
    let prefix = if is_standard { "S" } else { "P" };
    format!("{}-{}-{:04}", prefix, set, block)
}

// ===================== SoE 数据类型 =====================

/// SoE 数据类型枚举
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u8)]
pub enum SoEDataType {
    /// 二进制
    Binary = 0,
    /// 无符号整数
    UInt = 1,
    /// 有符号整数
    Int = 2,
    /// 十六进制
    Hexadecimal = 3,
    /// 字符串
    String = 4,
    /// IDN 引用
    IDN = 5,
    /// 浮点数
    Float = 6,
    /// 参数
    Parameter = 7,
}

impl From<u8> for SoEDataType {
    fn from(v: u8) -> Self {
        match v {
            0 => Self::Binary,
            1 => Self::UInt,
            2 => Self::Int,
            3 => Self::Hexadecimal,
            4 => Self::String,
            5 => Self::IDN,
            6 => Self::Float,
            7 => Self::Parameter,
            _ => Self::Binary,
        }
    }
}

// ===================== SoE 属性结构体 =====================

/// SoE 属性解码结果
#[derive(Debug, Clone)]
pub struct SoEAttributes {
    /// 评价因子
    pub evaluation_factor: u16,
    /// 数据长度指数 (实际字节 = 1 << length)
    pub length: u8,
    /// 是否为列表类型
    pub is_list: bool,
    /// 是否为命令
    pub is_command: bool,
    /// 数据类型
    pub data_type: SoEDataType,
    /// 小数位数
    pub decimals: u8,
    /// PreOp 状态下写保护
    pub write_protected_preop: bool,
    /// SafeOp 状态下写保护
    pub write_protected_safeop: bool,
    /// Op 状态下写保护
    pub write_protected_op: bool,
}

impl SoEAttributes {
    /// 从 u32 属性位域解码
    fn decode(attrs: u32) -> Self {
        Self {
            evaluation_factor: (attrs & 0xFFFF) as u16,
            length: ((attrs >> 16) & 0x3) as u8,
            is_list: ((attrs >> 18) & 0x1) == 1,
            is_command: ((attrs >> 19) & 0x1) == 1,
            data_type: SoEDataType::from(((attrs >> 20) & 0x7) as u8),
            decimals: ((attrs >> 24) & 0xF) as u8,
            write_protected_preop: ((attrs >> 28) & 0x1) == 1,
            write_protected_safeop: ((attrs >> 29) & 0x1) == 1,
            write_protected_op: ((attrs >> 30) & 0x1) == 1,
        }
    }

    /// 是否只读
    pub fn is_read_only(&self) -> bool {
        self.write_protected_preop && self.write_protected_safeop && self.write_protected_op
    }

    /// 获取访问权限字符串 (对齐 C# AccessMode)
    ///
    /// 返回 "RO" (完全只读), "RW" (完全读写), "RW*" (部分状态可写)
    pub fn access_mode(&self) -> &'static str {
        if self.is_read_only() {
            "RO"
        } else if !self.write_protected_preop && !self.write_protected_safeop && !self.write_protected_op {
            "RW"
        } else {
            "RW*"
        }
    }
}

// ===================== SoE 参数信息 =====================

/// SoE IDN 参数完整信息
#[derive(Debug, Clone)]
pub struct SoEParameter {
    /// IDN 编号
    pub idn: u16,
    /// 参数名称
    pub name: String,
    /// 参数单位
    pub unit: String,
    /// 属性
    pub attributes: SoEAttributes,
    /// 当前值 (原始字节)
    pub value: Vec<u8>,
    /// 默认值
    pub default_value: Vec<u8>,
    /// 最小值
    pub min_value: Vec<u8>,
    /// 最大值
    pub max_value: Vec<u8>,
}

impl SoEParameter {
    /// 获取 SERCOS IDN 格式字符串 (S-x-xxxx 或 P-x-xxxx)
    pub fn sercos_idn(&self) -> String {
        let prefix = if self.idn < 0x8000 { "S" } else { "P" };
        let type_num = (self.idn >> 12) & 0x7;
        let number = self.idn & 0x0FFF;
        format!("{}-{}-{:04}", prefix, type_num, number)
    }

    /// IDN 类别
    pub fn category(&self) -> &'static str {
        if self.idn < 0x8000 { "Standard" }
        else if self.idn >= 0xC000 { "Vendor" }
        else { "Product" }
    }

    /// 是否只读
    pub fn is_read_only(&self) -> bool {
        self.attributes.is_read_only()
    }

    /// 获取访问权限字符串 (对齐 C# AccessMode)
    pub fn access_mode(&self) -> &'static str {
        self.attributes.access_mode()
    }
}

impl std::fmt::Display for SoEParameter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} {}", self.sercos_idn(), self.name)
    }
}

// ===================== SoE 映射信息 =====================

/// SoE IDN 映射条目
#[derive(Debug, Clone)]
pub struct ServoMappingEntry {
    /// IDN 编号
    pub idn: u16,
    /// 参数名称
    pub name: String,
    /// 数据长度 (位)
    pub bit_length: i32,
}

impl ServoMappingEntry {
    /// 数据长度 (字节)
    pub fn byte_length(&self) -> i32 {
        (self.bit_length + 7) / 8
    }
}

/// SoE AT/MDT 映射信息
#[derive(Debug, Clone)]
pub struct ServoMappingInfo {
    /// AT (输入) 映射列表
    pub at_mapping: Vec<ServoMappingEntry>,
    /// MDT (输出) 映射列表
    pub mdt_mapping: Vec<ServoMappingEntry>,
    /// AT 总位数
    pub at_bit_size: i32,
    /// MDT 总位数
    pub mdt_bit_size: i32,
}

impl ServoMappingInfo {
    /// AT 总字节数
    pub fn at_byte_size(&self) -> i32 { (self.at_bit_size + 7) / 8 }
    /// MDT 总字节数
    pub fn mdt_byte_size(&self) -> i32 { (self.mdt_bit_size + 7) / 8 }
}

// ===================== SoE 通知事件 =====================

/// SoE 通知事件参数
#[derive(Debug, Clone)]
pub struct SoENotificationEventArgs {
    /// 从站索引
    pub slave_index: u16,
    /// 驱动器编号
    pub drive_number: u8,
    /// 发生变化的 IDN
    pub idn: u16,
    /// 新值
    pub new_value: Option<Vec<u8>>,
    /// 旧值
    pub old_value: Option<Vec<u8>>,
}

impl SoENotificationEventArgs {
    /// 获取 SERCOS IDN 格式字符串
    pub fn sercos_idn(&self) -> String {
        let prefix = if self.idn < 0x8000 { "S" } else { "P" };
        let type_num = (self.idn >> 12) & 0x7;
        let number = self.idn & 0x0FFF;
        format!("{}-{}-{:04}", prefix, type_num, number)
    }
}

// ===================== SoE Notification / Emergency 回调 (对齐 C# SoEInstance.Add*Callback) =====================

/// SoE 通知事件 (对齐 C# `SoEInstance.NotificationEvent`).
///
/// 实时语义: 由用户回调注册后, DLL 监控到 IDN 变化 / 推送 Notification 服务时触发.
#[derive(Debug, Clone)]
pub struct SoENotificationEvent {
    /// 主站索引
    pub master_index: u16,
    /// 从站索引
    pub slave_index: u16,
    /// 驱动器编号
    pub drive_number: u8,
    /// 发生变化的 IDN
    pub idn: u16,
    /// 新值 (Element Value)
    pub new_value: Option<Vec<u8>>,
    /// 旧值 (上次 poll 读到的)
    pub old_value: Option<Vec<u8>>,
    /// 触发时刻
    pub timestamp: SystemTime,
}

impl SoENotificationEvent {
    /// SERCOS IDN 格式 "S-0-0016" / "P-1-0100"
    pub fn sercos_idn(&self) -> String {
        let prefix = if self.idn < 0x8000 { "S" } else { "P" };
        let type_num = (self.idn >> 12) & 0x7;
        let number = self.idn & 0x0FFF;
        format!("{}-{}-{:04}", prefix, type_num, number)
    }
}

/// SoE Emergency 事件 (对齐 C# `SoEInstance.EmergencyEvent`, ETG.5003).
#[derive(Debug, Clone)]
pub struct SoEEmergencyEvent {
    /// 主站索引
    pub master_index: u16,
    /// 从站索引
    pub slave_index: u16,
    /// 驱动器编号
    pub drive_number: u8,
    /// IDN (Emergency 关联的参数)
    pub idn: u16,
    /// SoE 错误码 (ETG.5003)
    pub error_code: SoEErrorCode,
    /// Emergency 附加数据 (原始字节)
    pub data: Vec<u8>,
    /// 触发时刻
    pub timestamp: SystemTime,
}

/// SoE 通知回调类型别名 (对齐 Z-4 FSoE 分发器模式).
///
/// 使用 `Arc<dyn Fn(...) + Send + Sync>` 支持多订阅者共享且线程安全.
pub type SoENotificationCallback = Arc<dyn Fn(&SoENotificationEvent) + Send + Sync>;

/// SoE Emergency 回调类型别名.
pub type SoEEmergencyCallback = Arc<dyn Fn(&SoEEmergencyEvent) + Send + Sync>;

// ===================== SoE 标准 IDN 常量 =====================

/// SoE 标准 IDN 常量
pub mod standard_idn {
    /// IDN 列表 (S-0-0000)
    pub const IDN_LIST: u16 = 0x0000;
    /// AT 配置 - 输入映射 (S-0-0016)
    pub const AT_CONFIG: u16 = 0x0010;
    /// MDT 配置 - 输出映射 (S-0-0024)
    pub const MDT_CONFIG: u16 = 0x0018;
    /// 通信周期时间 (S-0-0001)
    pub const CYCLE_TIME: u16 = 0x0001;
    /// 通知请求 (S-0-0127)
    pub const NOTIFICATION_REQUEST: u16 = 0x007F;
}

// ===================== SoEInstance 实例 =====================

/// SoE 实例 - 对齐 C# SoEInstance
///
/// 为单个从站/驱动器提供完整的 SoE 参数读写功能。
/// 通过 `Slave::soe()` 获取。
pub struct SoEInstance {
    master_index: u16,
    slave_index: u16,
    drive_number: u8,
    /// 已监控的 IDN 及其上次值 (用于轮询检测)
    monitored_idns: Mutex<HashMap<u16, Option<Vec<u8>>>>,
    /// 最近一次 SoE 错误码
    last_soe_error: Option<SoEErrorCode>,
    /// SoE 通知回调列表 (对齐 C# `event NotificationReceived`)
    notification_callbacks: Arc<Mutex<Vec<SoENotificationCallback>>>,
    /// SoE Emergency 回调列表 (对齐 C# `event EmergencyReceived`)
    emergency_callbacks: Arc<Mutex<Vec<SoEEmergencyCallback>>>,
}

impl SoEInstance {
    /// 创建 SoE 实例
    pub(crate) fn new(master_index: u16, slave_index: u16, drive_number: u8) -> Self {
        Self {
            master_index,
            slave_index,
            drive_number,
            monitored_idns: Mutex::new(HashMap::new()),
            last_soe_error: None,
            notification_callbacks: Arc::new(Mutex::new(Vec::new())),
            emergency_callbacks: Arc::new(Mutex::new(Vec::new())),
        }
    }

    /// 主站索引
    pub fn master_index(&self) -> u16 { self.master_index }

    /// 从站索引
    pub fn slave_index(&self) -> u16 { self.slave_index }

    /// 驱动器编号
    pub fn drive_number(&self) -> u8 { self.drive_number }

    /// 从站是否支持 SoE 邮箱协议 (对齐 C# SoEInstance.IsSupported).
    ///
    /// 读取 SII mbx_proto bit 4 (ECT_MBXPROT_SOE = 0x10) 判断支持情况.
    /// DLL 调用失败时保守返回 true (未知能力视为支持).
    pub fn is_supported(&self) -> bool {
        let proto = unsafe { ffi::GetSlaveMailboxProto(self.master_index, self.slave_index) };
        (proto & 0x10) != 0
    }

    /// 获取最近一次 SoE 错误码
    pub fn last_soe_error(&self) -> Option<SoEErrorCode> { self.last_soe_error }

    // ==================== Notification / Emergency 回调 ====================

    /// 注册 SoE 通知回调 (对齐 C# `SoEInstance.NotificationReceived` 事件 +=).
    ///
    /// 支持多订阅者; 同一 Arc 多次注册会被多次调用. 使用 `Arc::ptr_eq`
    /// 判等, 若需移除请保留 `Arc` 的克隆用于后续 `remove_notification_callback`.
    pub fn add_notification_callback(&self, cb: SoENotificationCallback) {
        if let Ok(mut list) = self.notification_callbacks.lock() {
            list.push(cb);
        }
    }

    /// 移除 SoE 通知回调 (按 `Arc::ptr_eq` 匹配).
    pub fn remove_notification_callback(&self, cb: &SoENotificationCallback) {
        if let Ok(mut list) = self.notification_callbacks.lock() {
            list.retain(|c| !Arc::ptr_eq(c, cb));
        }
    }

    /// 注册 SoE Emergency 回调.
    pub fn add_emergency_callback(&self, cb: SoEEmergencyCallback) {
        if let Ok(mut list) = self.emergency_callbacks.lock() {
            list.push(cb);
        }
    }

    /// 移除 SoE Emergency 回调 (按 `Arc::ptr_eq` 匹配).
    pub fn remove_emergency_callback(&self, cb: &SoEEmergencyCallback) {
        if let Ok(mut list) = self.emergency_callbacks.lock() {
            list.retain(|c| !Arc::ptr_eq(c, cb));
        }
    }

    /// 触发 Notification 事件 (内部使用: 由 `poll_notifications` 或外部桥接层调用).
    ///
    /// 快照回调列表后释放锁再调用, 避免回调中注册 / 注销时死锁.
    /// 用 `catch_unwind` 吞掉 panic, 防止影响调用方.
    pub fn fire_notification(&self, ev: &SoENotificationEvent) {
        let snapshot: Vec<SoENotificationCallback> = match self.notification_callbacks.lock() {
            Ok(list) => list.clone(),
            Err(_) => return,
        };
        for cb in &snapshot {
            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| cb(ev)));
        }
    }

    /// 触发 Emergency 事件 (内部使用).
    pub fn fire_emergency(&self, ev: &SoEEmergencyEvent) {
        let snapshot: Vec<SoEEmergencyCallback> = match self.emergency_callbacks.lock() {
            Ok(list) => list.clone(),
            Err(_) => return,
        };
        for cb in &snapshot {
            let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| cb(ev)));
        }
    }

    // ==================== 原始字节读写 ====================

    /// 读取 IDN 参数 (原始字节)
    pub fn read(&self, idn: u16, element_flags: u8, timeout_ms: i32) -> Result<Vec<u8>> {
        soe_read_raw(self.master_index, self.slave_index, idn, self.drive_number, element_flags, timeout_ms * 1000)
    }

    /// 写入 IDN 参数 (原始字节)
    pub fn write(&self, idn: u16, data: &[u8], element_flags: u8, timeout_ms: i32) -> Result<()> {
        soe_write_raw(self.master_index, self.slave_index, idn, self.drive_number, element_flags, data, timeout_ms * 1000)
    }

    // ==================== 类型化读取 ====================

    /// 读取 i16 值
    pub fn read_i16(&self, idn: u16, timeout_ms: i32) -> Result<i16> {
        soe_read_i16(self.master_index, self.slave_index, idn, self.drive_number, timeout_ms * 1000)
    }

    /// 读取 i32 值
    pub fn read_i32(&self, idn: u16, timeout_ms: i32) -> Result<i32> {
        soe_read_i32(self.master_index, self.slave_index, idn, self.drive_number, timeout_ms * 1000)
    }

    /// 读取 u16 值
    pub fn read_u16(&self, idn: u16, timeout_ms: i32) -> Result<u16> {
        soe_read_u16(self.master_index, self.slave_index, idn, self.drive_number, timeout_ms * 1000)
    }

    /// 读取 u32 值
    pub fn read_u32(&self, idn: u16, timeout_ms: i32) -> Result<u32> {
        soe_read_u32(self.master_index, self.slave_index, idn, self.drive_number, timeout_ms * 1000)
    }

    /// 读取 f32 值
    pub fn read_f32(&self, idn: u16, timeout_ms: i32) -> Result<f32> {
        soe_read_f32(self.master_index, self.slave_index, idn, self.drive_number, timeout_ms * 1000)
    }

    /// 读取 f64 值
    pub fn read_f64(&self, idn: u16, timeout_ms: i32) -> Result<f64> {
        soe_read_f64(self.master_index, self.slave_index, idn, self.drive_number, timeout_ms * 1000)
    }

    /// 读取字符串值
    pub fn read_string(&self, idn: u16, timeout_ms: i32) -> Result<String> {
        soe_read_string(self.master_index, self.slave_index, idn, self.drive_number, timeout_ms * 1000)
    }

    // ==================== 类型化写入 ====================

    /// 写入 i16 值
    pub fn write_i16(&self, idn: u16, value: i16, timeout_ms: i32) -> Result<()> {
        soe_write_i16(self.master_index, self.slave_index, idn, self.drive_number, value, timeout_ms * 1000)
    }

    /// 写入 i32 值
    pub fn write_i32(&self, idn: u16, value: i32, timeout_ms: i32) -> Result<()> {
        soe_write_i32(self.master_index, self.slave_index, idn, self.drive_number, value, timeout_ms * 1000)
    }

    /// 写入 u16 值
    pub fn write_u16(&self, idn: u16, value: u16, timeout_ms: i32) -> Result<()> {
        soe_write_u16(self.master_index, self.slave_index, idn, self.drive_number, value, timeout_ms * 1000)
    }

    /// 写入 u32 值
    pub fn write_u32(&self, idn: u16, value: u32, timeout_ms: i32) -> Result<()> {
        soe_write_u32(self.master_index, self.slave_index, idn, self.drive_number, value, timeout_ms * 1000)
    }

    // ==================== 扩展读取 ====================

    /// 读取 IDN 参数名称 (Element 0x02)
    ///
    /// [2026-05-08 修复乱码] SoE IDN 名走多编码兜底 (UTF-8/ASCII/Latin-1).
    pub fn read_name(&self, idn: u16, timeout_ms: i32) -> Result<String> {
        let data = self.read(idn, SOE_ELEM_NAME, timeout_ms)?;
        let end = data.iter().position(|&b| b == 0).unwrap_or(data.len());
        Ok(crate::utils::help::decode_ethercat_string(&data[..end]))
    }

    /// 读取 IDN 参数单位 (Element 0x08)
    ///
    /// [2026-05-08 修复乱码] SoE IDN 单位走多编码兜底 (UTF-8/ASCII/Latin-1).
    pub fn read_unit(&self, idn: u16, timeout_ms: i32) -> Result<String> {
        let data = self.read(idn, SOE_ELEM_UNIT, timeout_ms)?;
        let end = data.iter().position(|&b| b == 0).unwrap_or(data.len());
        Ok(crate::utils::help::decode_ethercat_string(&data[..end]))
    }

    /// 读取 IDN 参数属性
    pub fn read_attributes(&self, idn: u16, timeout_ms: i32) -> Result<SoEAttributes> {
        let attrs = soe_read_attributes(self.master_index, self.slave_index, idn, self.drive_number, timeout_ms * 1000)?;
        Ok(SoEAttributes::decode(attrs))
    }

    /// 读取最小值 (Element 0x10)
    pub fn read_min_value(&self, idn: u16, timeout_ms: i32) -> Result<Vec<u8>> {
        self.read(idn, SOE_ELEM_MIN, timeout_ms)
    }

    /// 读取最大值 (Element 0x20)
    pub fn read_max_value(&self, idn: u16, timeout_ms: i32) -> Result<Vec<u8>> {
        self.read(idn, SOE_ELEM_MAX, timeout_ms)
    }

    /// 读取默认值 (Element 0x80)
    pub fn read_default_value(&self, idn: u16, timeout_ms: i32) -> Result<Vec<u8>> {
        self.read(idn, SOE_ELEM_DEFAULT, timeout_ms)
    }

    /// 读取 Data State (Element 0x01)
    pub fn read_data_state(&self, idn: u16, timeout_ms: i32) -> Result<u16> {
        let data = self.read(idn, SOE_ELEM_DATA_STATE, timeout_ms)?;
        if data.len() < 2 { return Err(DarraError::SoeFailed(idn)); }
        Ok(u16::from_le_bytes([data[0], data[1]]))
    }

    // ==================== 程序命令执行 ====================

    /// 执行 SoE 程序命令 (SERCOS Procedure Command)
    ///
    /// 写入 Data State bit 0 = 1 启动命令,轮询等待 bit 0 = 0 完成。
    pub fn execute_command(&self, idn: u16, timeout_ms: i32, poll_interval_ms: i32) -> Result<()> {
        // 读取当前 Data State
        let current = self.read_data_state(idn, timeout_ms)?;
        // 设置 bit 0 = 1, 清除 bit 1
        let start_value = (current & 0xFFFC) | 0x0001;
        self.write(idn, &start_value.to_le_bytes(), SOE_ELEM_DATA_STATE, timeout_ms)?;

        // 轮询等待
        let start = std::time::Instant::now();
        let timeout = std::time::Duration::from_millis(timeout_ms as u64);
        let interval = std::time::Duration::from_millis(poll_interval_ms as u64);

        while start.elapsed() < timeout {
            std::thread::sleep(interval);
            if let Ok(state) = self.read_data_state(idn, timeout_ms) {
                if (state & 0x0002) != 0 {
                    return Err(DarraError::SoeFailed(idn)); // bit 1 = 错误
                }
                if (state & 0x0001) == 0 {
                    return Ok(()); // bit 0 = 0, 完成
                }
            }
        }
        Err(DarraError::Timeout)
    }

    // ==================== IDN 列表/参数信息 ====================

    /// 获取支持的 IDN 列表 (对齐 C# GetAvailableIDNs)
    pub fn get_available_idns(&self, timeout_ms: i32) -> Result<Vec<u16>> {
        self.available_idns(timeout_ms)
    }

    /// 获取 IDN 完整参数信息 (对齐 C# GetParameterInfo)
    pub fn get_parameter_info(&self, idn: u16, timeout_ms: i32) -> SoEParameter {
        self.parameter_info(idn, timeout_ms)
    }

    /// 获取 AT/MDT 映射配置 (对齐 C# GetIDNMapping)
    pub fn get_idn_mapping(&self, timeout_ms: i32) -> ServoMappingInfo {
        self.idn_mapping(timeout_ms)
    }

    /// 获取正在监控的 IDN 列表 (对齐 C# GetMonitoredIDNs)
    pub fn get_monitored_idns(&self) -> Vec<u16> {
        self.monitored_idns()
    }

    /// 获取所有驱动器的 AT/MDT 映射 (对齐 C# GetAllDriveMappings)
    ///
    /// 遍历最多 8 个驱动器, 返回每个驱动器的映射信息
    pub fn get_all_drive_mappings(&self, timeout_ms: i32) -> HashMap<u8, ServoMappingInfo> {
        let mut result = HashMap::new();
        for drive_no in 0u8..8 {
            let temp = SoEInstance::new(self.master_index, self.slave_index, drive_no);
            let mapping = temp.idn_mapping(timeout_ms);
            if !mapping.at_mapping.is_empty() || !mapping.mdt_mapping.is_empty() {
                result.insert(drive_no, mapping);
            }
        }
        result
    }

    /// 读取单个 SoE 参数 (对齐 C# SoE manager ReadParameter)
    ///
    /// 读取 IDN 的名称、单位、属性和当前值
    pub fn read_parameter(&self, idn: u16, timeout_ms: i32) -> SoEParameter {
        self.parameter_info(idn, timeout_ms)
    }

    /// 批量读取常见 SoE 参数 (对齐 C# SoE manager ReadAllParameters)
    ///
    /// 读取标准 Sercos IDN 子集的参数信息, 跳过读取失败的条目
    pub fn read_all_parameters(&self, timeout_ms: i32) -> Vec<SoEParameter> {
        let standard_idns: &[u16] = &[
            0x0000, // IDN of all IDNs
            0x0001, // Control unit cycle time
            0x0002, // Position data scaling type
            0x0003, // Position data scaling factor
            0x0004, // Position data scaling exponent
            0x0010, // Drive status
            0x0011, // Position feedback value 1
            0x0012, // Position command value
            0x0013, // Velocity feedback value
            0x0014, // Velocity command value
            0x0015, // Torque/force feedback value
            0x0016, // Torque/force command value
            0x0021, // Positioning window
            0x0024, // Maximum velocity
            0x0032, // Drive control
            0x0033, // Position command value from interpolator
            0x0040, // Drive control word
            0x0047, // Drive status word
        ];

        let mut params = Vec::new();
        for &idn in standard_idns {
            // 尝试读取, 跳过失败的 IDN
            let param = self.parameter_info(idn, timeout_ms);
            // 只添加成功读取到值的参数
            if !param.name.is_empty() || !param.value.is_empty() {
                params.push(param);
            }
        }
        params
    }

    /// 写入 SoE 参数 (对齐 C# SoE manager WriteParameter)
    pub fn write_parameter(&self, idn: u16, data: &[u8], timeout_ms: i32) -> Result<()> {
        if data.is_empty() {
            return Err(DarraError::InvalidParameter("数据不能为空".to_string()));
        }
        self.write(idn, data, SOE_ELEM_VALUE, timeout_ms)
    }

    /// 获取支持的 IDN 列表 (内部实现)
    pub fn available_idns(&self, timeout_ms: i32) -> Result<Vec<u16>> {
        soe_list_idns(self.master_index, self.slave_index, self.drive_number, timeout_ms * 1000)
    }

    /// 获取 IDN 完整参数信息
    pub fn parameter_info(&self, idn: u16, timeout_ms: i32) -> SoEParameter {
        let mut param = SoEParameter {
            idn,
            name: String::new(),
            unit: String::new(),
            attributes: SoEAttributes::decode(0),
            value: Vec::new(),
            default_value: Vec::new(),
            min_value: Vec::new(),
            max_value: Vec::new(),
        };

        // 读取名称
        if let Ok(name) = self.read_name(idn, timeout_ms) {
            param.name = name;
        }
        // 读取单位
        if let Ok(unit) = self.read_unit(idn, timeout_ms) {
            param.unit = unit;
        }
        // 读取属性
        if let Ok(attrs) = self.read_attributes(idn, timeout_ms) {
            param.attributes = attrs;
        }
        // 读取当前值
        if let Ok(value) = self.read(idn, SOE_ELEM_VALUE, timeout_ms) {
            param.value = value;
        }
        // 读取最小/最大值
        if let Ok(min) = self.read_min_value(idn, timeout_ms) {
            param.min_value = min;
        }
        if let Ok(max) = self.read_max_value(idn, timeout_ms) {
            param.max_value = max;
        }
        // 读取默认值
        if let Ok(def) = self.read_default_value(idn, timeout_ms) {
            param.default_value = def;
        }

        param
    }

    // ==================== AT/MDT 映射 ====================

    /// 读取 AT/MDT 映射配置
    pub fn idn_mapping(&self, timeout_ms: i32) -> ServoMappingInfo {
        let timeout_us = timeout_ms * 1000;
        let mut mapping = ServoMappingInfo {
            at_mapping: Vec::new(),
            mdt_mapping: Vec::new(),
            at_bit_size: 16, // 状态字始终映射
            mdt_bit_size: 16, // 命令字始终映射
        };

        // 读取 AT 配置 (IDN 0x0010)
        if let Ok(at_data) = self.read(standard_idn::AT_CONFIG, SOE_ELEM_VALUE, timeout_ms) {
            self.parse_mapping(&at_data, &mut mapping.at_mapping, &mut mapping.at_bit_size, timeout_us);
        }

        // 读取 MDT 配置 (IDN 0x0018)
        if let Ok(mdt_data) = self.read(standard_idn::MDT_CONFIG, SOE_ELEM_VALUE, timeout_ms) {
            self.parse_mapping(&mdt_data, &mut mapping.mdt_mapping, &mut mapping.mdt_bit_size, timeout_us);
        }

        mapping
    }

    /// 解析映射数据
    fn parse_mapping(&self, data: &[u8], entries: &mut Vec<ServoMappingEntry>, total_bits: &mut i32, timeout_us: i32) {
        if data.len() < 4 { return; }
        let current_length = u16::from_le_bytes([data[0], data[1]]) as usize;
        let idn_count = current_length / 2;

        for i in 0..idn_count {
            let offset = 4 + i * 2;
            if offset + 1 >= data.len() { break; }
            let mapped_idn = u16::from_le_bytes([data[offset], data[offset + 1]]);

            let mut entry = ServoMappingEntry {
                idn: mapped_idn,
                name: format!("IDN 0x{:04X}", mapped_idn),
                bit_length: 0,
            };

            // 读取属性获取长度
            if let Ok(attrs) = soe_read_attributes(self.master_index, self.slave_index, mapped_idn, self.drive_number, timeout_us) {
                let decoded = SoEAttributes::decode(attrs);
                if !decoded.is_list {
                    entry.bit_length = 8 << decoded.length;
                    *total_bits += entry.bit_length;
                }
            }

            // 尝试读取名称
            if let Ok(name) = self.read_name(mapped_idn, 500) {
                entry.name = name;
            }

            entries.push(entry);
        }
    }

    // ==================== 通知管理 ====================

    /// 启用指定 IDN 的变化通知
    ///
    /// 将 IDN 加入轮询监控列表,并尝试通过 S-0-0127 启用硬件通知。
    pub fn enable_notification(&self, idn: u16, timeout_ms: i32) -> bool {
        // 尝试硬件通知
        let hardware = self.write(standard_idn::NOTIFICATION_REQUEST, &idn.to_le_bytes(), 0, timeout_ms).is_ok();

        // 读取当前值作为基线
        let current = self.read(idn, SOE_ELEM_VALUE, timeout_ms).ok();
        if let Ok(mut map) = self.monitored_idns.lock() {
            map.insert(idn, current);
        }

        hardware
    }

    /// 禁用指定 IDN 的变化通知
    pub fn disable_notification(&self, idn: u16) {
        if let Ok(mut map) = self.monitored_idns.lock() {
            map.remove(&idn);
        }
    }

    /// 禁用所有通知
    pub fn disable_all_notifications(&self) {
        if let Ok(mut map) = self.monitored_idns.lock() {
            map.clear();
        }
    }

    /// 获取正在监控的 IDN 列表
    pub fn monitored_idns(&self) -> Vec<u16> {
        self.monitored_idns.lock().map(|m| m.keys().copied().collect()).unwrap_or_default()
    }

    /// 轮询检测所有已监控 IDN 的变化
    ///
    /// 返回 (变化数量, 变化事件列表)
    pub fn poll_notifications(&self, timeout_ms: i32) -> Vec<SoENotificationEventArgs> {
        let idns: Vec<u16> = self.monitored_idns.lock()
            .map(|m| m.keys().copied().collect())
            .unwrap_or_default();

        let mut changes = Vec::new();
        for idn in idns {
            if let Ok(new_value) = self.read(idn, SOE_ELEM_VALUE, timeout_ms) {
                let old_value = self.monitored_idns.lock().ok()
                    .and_then(|m| m.get(&idn).cloned())
                    .flatten();

                let changed = match (&old_value, &Some(new_value.clone())) {
                    (None, Some(_)) => true,
                    (Some(a), Some(b)) => a != b,
                    _ => false,
                };

                if changed {
                    if let Ok(mut map) = self.monitored_idns.lock() {
                        map.insert(idn, Some(new_value.clone()));
                    }
                    // 通知回调 (若有注册)
                    let ev = SoENotificationEvent {
                        master_index: self.master_index,
                        slave_index: self.slave_index,
                        drive_number: self.drive_number,
                        idn,
                        new_value: Some(new_value.clone()),
                        old_value: old_value.clone(),
                        timestamp: SystemTime::now(),
                    };
                    self.fire_notification(&ev);

                    changes.push(SoENotificationEventArgs {
                        slave_index: self.slave_index,
                        drive_number: self.drive_number,
                        idn,
                        new_value: Some(new_value),
                        old_value,
                    });
                }
            }
        }
        changes
    }
}

// ===================== 模块级自由函数 (保持兼容) =====================

/// 读取 SoE IDN 的 i16 值
pub fn soe_read_i16(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, timeout_us: i32,
) -> Result<i16> {
    let data = soe_read_raw(master_index, slave_index, idn, drive_no, SOE_ELEM_VALUE, timeout_us)?;
    if data.len() < 2 { return Err(DarraError::SoeFailed(idn)); }
    Ok(i16::from_le_bytes([data[0], data[1]]))
}

/// 读取 SoE IDN 的 i32 值
pub fn soe_read_i32(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, timeout_us: i32,
) -> Result<i32> {
    let data = soe_read_raw(master_index, slave_index, idn, drive_no, SOE_ELEM_VALUE, timeout_us)?;
    if data.len() < 4 { return Err(DarraError::SoeFailed(idn)); }
    Ok(i32::from_le_bytes([data[0], data[1], data[2], data[3]]))
}

/// 读取 SoE IDN 的 u16 值
pub fn soe_read_u16(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, timeout_us: i32,
) -> Result<u16> {
    let data = soe_read_raw(master_index, slave_index, idn, drive_no, SOE_ELEM_VALUE, timeout_us)?;
    if data.len() < 2 { return Err(DarraError::SoeFailed(idn)); }
    Ok(u16::from_le_bytes([data[0], data[1]]))
}

/// 读取 SoE IDN 的 u32 值
pub fn soe_read_u32(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, timeout_us: i32,
) -> Result<u32> {
    let data = soe_read_raw(master_index, slave_index, idn, drive_no, SOE_ELEM_VALUE, timeout_us)?;
    if data.len() < 4 { return Err(DarraError::SoeFailed(idn)); }
    Ok(u32::from_le_bytes([data[0], data[1], data[2], data[3]]))
}

/// 读取 SoE IDN 的 f32 值
pub fn soe_read_f32(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, timeout_us: i32,
) -> Result<f32> {
    let bits = soe_read_u32(master_index, slave_index, idn, drive_no, timeout_us)?;
    Ok(f32::from_bits(bits))
}

/// 读取 SoE IDN 的 f64 值
pub fn soe_read_f64(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, timeout_us: i32,
) -> Result<f64> {
    let data = soe_read_raw(master_index, slave_index, idn, drive_no, SOE_ELEM_VALUE, timeout_us)?;
    if data.len() < 8 { return Err(DarraError::SoeFailed(idn)); }
    let bits = u64::from_le_bytes([
        data[0], data[1], data[2], data[3],
        data[4], data[5], data[6], data[7],
    ]);
    Ok(f64::from_bits(bits))
}

/// 读取 SoE IDN 的字符串值
///
/// [2026-05-08 修复乱码] SoE IDN 字符串值走多编码兜底 (UTF-8/ASCII/Latin-1).
pub fn soe_read_string(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, timeout_us: i32,
) -> Result<String> {
    let data = soe_read_raw(master_index, slave_index, idn, drive_no, SOE_ELEM_VALUE, timeout_us)?;
    let end = data.iter().position(|&b| b == 0).unwrap_or(data.len());
    Ok(crate::utils::help::decode_ethercat_string(&data[..end]))
}

/// 写入 SoE IDN 的 i16 值
pub fn soe_write_i16(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, value: i16, timeout_us: i32,
) -> Result<()> {
    soe_write_raw(master_index, slave_index, idn, drive_no, SOE_ELEM_VALUE, &value.to_le_bytes(), timeout_us)
}

/// 写入 SoE IDN 的 i32 值
pub fn soe_write_i32(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, value: i32, timeout_us: i32,
) -> Result<()> {
    soe_write_raw(master_index, slave_index, idn, drive_no, SOE_ELEM_VALUE, &value.to_le_bytes(), timeout_us)
}

/// 写入 SoE IDN 的 u16 值
pub fn soe_write_u16(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, value: u16, timeout_us: i32,
) -> Result<()> {
    soe_write_raw(master_index, slave_index, idn, drive_no, SOE_ELEM_VALUE, &value.to_le_bytes(), timeout_us)
}

/// 写入 SoE IDN 的 u32 值
pub fn soe_write_u32(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, value: u32, timeout_us: i32,
) -> Result<()> {
    soe_write_raw(master_index, slave_index, idn, drive_no, SOE_ELEM_VALUE, &value.to_le_bytes(), timeout_us)
}

/// 写入 SoE IDN 的 f32 值
pub fn soe_write_f32(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, value: f32, timeout_us: i32,
) -> Result<()> {
    soe_write_raw(master_index, slave_index, idn, drive_no, SOE_ELEM_VALUE, &value.to_bits().to_le_bytes(), timeout_us)
}

/// 写入 SoE IDN 的 f64 值
pub fn soe_write_f64(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, value: f64, timeout_us: i32,
) -> Result<()> {
    soe_write_raw(master_index, slave_index, idn, drive_no, SOE_ELEM_VALUE, &value.to_bits().to_le_bytes(), timeout_us)
}

// ===================== 内部原始读写 =====================

/// 读取 SoE IDN 原始字节
pub fn soe_read_raw(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, element_flags: u8, timeout_us: i32,
) -> Result<Vec<u8>> {
    let mut data_ptr: *mut std::ffi::c_void = std::ptr::null_mut();
    let mut data_size: c_int = 0;
    let ok = unsafe {
        ffi::SoERead(master_index, slave_index, drive_no, element_flags, idn,
                     &mut data_ptr, &mut data_size, timeout_us)
    };
    if ok == 0 || data_ptr.is_null() || data_size <= 0 {
        if !data_ptr.is_null() { unsafe { ffi::FreeMemory(data_ptr) }; }
        return Err(DarraError::SoeFailed(idn));
    }
    let data = unsafe {
        std::slice::from_raw_parts(data_ptr as *const u8, data_size as usize).to_vec()
    };
    unsafe { ffi::FreeMemory(data_ptr) };
    Ok(data)
}

/// 写入 SoE IDN 原始字节
pub fn soe_write_raw(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, element_flags: u8, data: &[u8], timeout_us: i32,
) -> Result<()> {
    let ok = unsafe {
        ffi::SoEWrite(master_index, slave_index, drive_no, element_flags, idn,
                      data.as_ptr(), data.len() as c_int, timeout_us)
    };
    if ok != 0 { Ok(()) } else { Err(DarraError::SoeFailed(idn)) }
}

/// 读取 SoE IDN 属性字
pub fn soe_read_attributes(
    master_index: u16, slave_index: u16,
    idn: u16, drive_no: u8, timeout_us: i32,
) -> Result<u32> {
    let mut attrs: u32 = 0;
    let ok = unsafe {
        ffi::SoEReadAttributes(master_index, slave_index, drive_no, idn, &mut attrs, timeout_us)
    };
    if ok != 0 { Ok(attrs) } else { Err(DarraError::SoeFailed(idn)) }
}

/// 获取从站支持的所有 IDN 列表
pub fn soe_list_idns(
    master_index: u16, slave_index: u16,
    drive_no: u8, timeout_us: i32,
) -> Result<Vec<u16>> {
    let mut list_ptr: *mut u16 = std::ptr::null_mut();
    let mut list_count: c_int = 0;
    let ok = unsafe {
        ffi::SoEReadIDNList(master_index, slave_index, drive_no,
                            &mut list_ptr, &mut list_count, timeout_us)
    };
    if ok == 0 || list_ptr.is_null() || list_count <= 0 {
        if !list_ptr.is_null() { unsafe { ffi::FreeMemory(list_ptr as *mut _) }; }
        return Err(DarraError::SoeFailed(0));
    }
    let idns = unsafe {
        std::slice::from_raw_parts(list_ptr, list_count as usize).to_vec()
    };
    unsafe { ffi::FreeMemory(list_ptr as *mut _) };
    Ok(idns)
}

/// 字节数组格式化为十六进制字符串
///
/// 对应 C# FormatByteArray
pub fn format_byte_array(data: &[u8]) -> String {
    if data.is_empty() {
        return String::new();
    }
    data.iter()
        .map(|b| format!("{:02X}", b))
        .collect::<Vec<_>>()
        .join(" ")
}

/// 根据数据类型智能格式化字节数组
///
/// data_type: 0=Binary, 1=UInt, 2=Int, 3=Hex, 4=String, 6=Float
pub fn format_byte_array_typed(data: &[u8], data_type: u8) -> String {
    if data.is_empty() {
        return String::new();
    }
    match data_type {
        1 => { // UInt
            match data.len() {
                1 => format!("{}", data[0]),
                2 => format!("{}", u16::from_le_bytes([data[0], data[1]])),
                4 => format!("{}", u32::from_le_bytes([data[0], data[1], data[2], data[3]])),
                _ => format_byte_array(data),
            }
        }
        2 => { // Int
            match data.len() {
                1 => format!("{}", data[0] as i8),
                2 => format!("{}", i16::from_le_bytes([data[0], data[1]])),
                4 => format!("{}", i32::from_le_bytes([data[0], data[1], data[2], data[3]])),
                _ => format_byte_array(data),
            }
        }
        3 => { // Hex
            format!("0x{}", data.iter().map(|b| format!("{:02X}", b)).collect::<String>())
        }
        4 => { // String
            // [2026-05-08 修复乱码] 格式化分支 String 走多编码兜底 (UTF-8/ASCII/Latin-1)
            let trimmed_end = data.iter().rposition(|&b| b != 0).map(|i| i + 1).unwrap_or(0);
            crate::utils::help::decode_ethercat_string(&data[..trimmed_end])
        }
        6 => { // Float
            match data.len() {
                4 => format!("{}", f32::from_le_bytes([data[0], data[1], data[2], data[3]])),
                8 => format!("{}", f64::from_le_bytes([data[0], data[1], data[2], data[3],
                                                        data[4], data[5], data[6], data[7]])),
                _ => format_byte_array(data),
            }
        }
        _ => format_byte_array(data),
    }
}

// ===================== 异步 API (轨道 1: std::thread, 无依赖) =====================

impl SoEInstance {
    /// SoE 读 IDN (std::thread 异步包装)
    pub fn read_blocking(
        master_index: u16,
        slave_index: u16,
        drive_number: u8,
        idn: u16,
        element_flags: u8,
        timeout_ms: i32,
    ) -> std::thread::JoinHandle<Result<Vec<u8>>> {
        std::thread::spawn(move || {
            let soe = SoEInstance::new(master_index, slave_index, drive_number);
            soe.read(idn, element_flags, timeout_ms)
        })
    }

    /// SoE 写 IDN (std::thread 异步包装)
    pub fn write_blocking(
        master_index: u16,
        slave_index: u16,
        drive_number: u8,
        idn: u16,
        data: Vec<u8>,
        element_flags: u8,
        timeout_ms: i32,
    ) -> std::thread::JoinHandle<Result<()>> {
        std::thread::spawn(move || {
            let soe = SoEInstance::new(master_index, slave_index, drive_number);
            soe.write(idn, &data, element_flags, timeout_ms)
        })
    }

    /// SoE 执行 SERCOS Procedure Command (std::thread 异步包装)
    pub fn execute_command_blocking(
        master_index: u16,
        slave_index: u16,
        drive_number: u8,
        idn: u16,
        timeout_ms: i32,
        poll_interval_ms: i32,
    ) -> std::thread::JoinHandle<Result<()>> {
        std::thread::spawn(move || {
            let soe = SoEInstance::new(master_index, slave_index, drive_number);
            soe.execute_command(idn, timeout_ms, poll_interval_ms)
        })
    }
}

// ===================== 异步 API (轨道 2: tokio, feature 门控) =====================

#[cfg(feature = "async-tokio")]
impl SoEInstance {
    /// SoE 读 IDN (tokio async)
    pub async fn read_async(&self, idn: u16, element_flags: u8, timeout_ms: i32) -> Result<Vec<u8>> {
        let master = self.master_index;
        let slave = self.slave_index;
        let drive = self.drive_number;
        tokio::task::spawn_blocking(move || {
            let soe = SoEInstance::new(master, slave, drive);
            soe.read(idn, element_flags, timeout_ms)
        })
        .await
        .map_err(|e| DarraError::Other(format!("tokio join error: {}", e)))?
    }

    /// SoE 写 IDN (tokio async)
    pub async fn write_async(&self, idn: u16, data: Vec<u8>, element_flags: u8, timeout_ms: i32) -> Result<()> {
        let master = self.master_index;
        let slave = self.slave_index;
        let drive = self.drive_number;
        tokio::task::spawn_blocking(move || {
            let soe = SoEInstance::new(master, slave, drive);
            soe.write(idn, &data, element_flags, timeout_ms)
        })
        .await
        .map_err(|e| DarraError::Other(format!("tokio join error: {}", e)))?
    }

    /// SoE 执行 SERCOS Procedure Command (tokio async)
    pub async fn execute_command_async(&self, idn: u16, timeout_ms: i32, poll_interval_ms: i32) -> Result<()> {
        let master = self.master_index;
        let slave = self.slave_index;
        let drive = self.drive_number;
        tokio::task::spawn_blocking(move || {
            let soe = SoEInstance::new(master, slave, drive);
            soe.execute_command(idn, timeout_ms, poll_interval_ms)
        })
        .await
        .map_err(|e| DarraError::Other(format!("tokio join error: {}", e)))?
    }
}

// ===================== IMailboxProtocol trait impl (对齐 C# SoEInstance) =====================

impl crate::abstractions::MailboxProtocol for SoEInstance {
    fn protocol_type(&self) -> u8 { 0x05 }
    fn protocol_name(&self) -> &'static str { "SoE" }

    fn is_supported(&self) -> bool {
        SoEInstance::is_supported(self)
    }

    fn last_error_code(&self) -> u32 {
        match self.last_soe_error {
            Some(e) => e as u32,
            None => 0,
        }
    }

    fn statistics(&self) -> crate::abstractions::MailboxStatistics {
        let mut stats = ffi::EcMbxStatsC::default();
        let rc = unsafe {
            ffi::mbx_get_stats_by_master(
                self.master_index, self.slave_index, 0x05, &mut stats,
            )
        };
        if rc == 1 {
            stats.into()
        } else {
            crate::abstractions::MailboxStatistics::empty()
        }
    }

    fn reset_statistics(&self) {
        unsafe {
            ffi::mbx_reset_stats_by_master(self.master_index, self.slave_index, 0x05);
        }
    }
}