LAPTOP-SNT8I5JK\Boounion
2025-06-10 452e31fbe5404d2ec8eb4c5b2e02138d837c146c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
// PerformanceMelsec.cpp: implementation of the CPerformanceMelsec class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "PerformanceMelsec.h"
#include <windows.h>
#include <iostream>
#include <fstream>
 
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#define new DEBUG_NEW
#endif
 
#ifdef _DEBUG
#define LOG_ERROR(msg) \
std::cerr << "[ERROR] " << __FILE__ << ":" << __LINE__ << " (" << __FUNCTION__ << ") - " << msg << std::endl;
#define LOG_DEBUG(msg) \
std::cout << "[DEBUG] " << __FILE__ << ":" << __LINE__ << " (" << __FUNCTION__ << ") - " << msg << std::endl;
#else
#define LOG_ERROR(msg)
#define LOG_DEBUG(msg)
#endif
 
// ³õʼ»¯¾²Ì¬³ÉÔ±±äÁ¿
std::unordered_map<int, std::string> CPerformanceMelsec::m_mapError = {
    // °å¿éSDK´íÎóÂë
    {0, "No error, communication successful."},
    {1, "Driver not started. The driver is not running."},
    {2, "Timeout error (board response error). Request not completed within timeout."},
    {66, "Already OPEN error. The specified channel is OPEN."},
    {68, "Path error. The specified path is invalid."},
    {69, "Unsupported function execution error."},
    {70, "Station number error. The specified station number is invalid."},
    {71, "No received data error (during RECV function)."},
    {77, "Memory allocation error / insufficient memory resources."},
    {85, "SEND/RECV channel number error."},
    {100, "Board H/W resource busy."},
    {101, "Routing exception."},
    {102, "Board driver I/F error: Failed to send request data to the board driver."},
    {103, "Board driver I/F error: Failed to receive response data from the board driver."},
    {130, "Initial software component No. Error."},
    {131, "Capacity error."},
    {133, "Parameter error."},
    {16385, "Specified target station number does not exist."},
    {16386, "Received a request that the target station cannot process."},
    {16418, "Failed to create the event history file."},
    {16420, "Failed to access the event history file."},
    {16421, "Another board driver is using the event history file."},
    {16432, "The specified soft component type does not exist."},
    {16433, "Soft component specification error: Out of range or invalid start I/O or block number."},
    {16512, "Request data exception: Invalid data or unsupported module."},
    {16685, "File association error: Failed to create the event history file."},
    {16837, "File association error: Event history file does not exist."},
    {18944, "Link association error: Network does not exist, unsupported CPU, or incorrect network No./station number."},
    {-1, "Invalid path. The specified function is not supported for this path."},
    {-2, "Start component No. error. The specified component is out of range."},
    {-3, "Capacity error. The capacity exceeds the component range."},
    {-6, "Component type error. The specified type during write is invalid."},
    {-8, "Channel No. error. The channel specified is invalid."},
    {-12, "Target path error. The specified path points to an invalid target."},
    {-13, "Write protection area error. The specified range is protected."},
    {-16, "Target path conflict. The path conflicts with write protection settings."},
    {-17, "Device not found or target not responding."},
    {-18, "Invalid target. The device does not support the operation."},
    {-19, "Invalid path operation. An unsupported path operation was executed."},
    {-31, "DLL library call failed or path not initialized."},
    {-32, "Resource timeout error. Communication timed out or exceeded resource limits."},
    {-33, "Communication timeout error. The target is not responding or timed out."},
    {-34, "Unsupported communication target error. The specified network No. or station No. points to an unsupported model."},
    {-35, "Registry access error."},
    {-36, "Registry access error."},
    {-37, "Communication initialization error. The settings for initializing the communication path are invalid."},
    {-42, "Key information error. Authentication failed."},
    {-43, "Marking event error. TC waiting event write was executed on the CPU."},
    {-61, "Marking event error. TC waiting event write was executed on the CPU."},
    {-62, "Event waiting timeout. The specified external event waiting timed out."},
    {-63, "Timeout value is out of range."},
    {-64, "Timeout value is out of range."},
    {-65, "Event waiting timeout. The specified external event waiting timed out."},
    {-66, "Timeout-induced resource shortage."},
    {-67, "Irrelevant file access execution error."},
    {-69, "Operation executed, but the module does not support the function."},
    {-70, "The target event processing module returned a rejection."},
    {-71, "The remote station did not return data correctly."},
    {-72, "Pointer error. The specified pointer value is invalid."},
    {-73, "Specified address error."},
    {-2174, "Buffer data queue exception occurred. Read/write exception to device."},
    {-7656, "Buffer data queue exception. Read/write exception to the device."},
    {-7672, "Buffer data queue exception. Read/write exception to the device."},
    {-11683, "Buffer data transfer error."},
    {-11717, "Network No. error."},
    {-11746, "Station No. error."},
    {-12128, "Buffer data send/response error."},
    {-18560, "Module mode setting error."},
    {-18572, "Communication method error."},
    {-25056, "Processor error."},
    {-26334, "Duplicate program call or illegal CPU operation."},
    {-26336, "Routing request error to a station without routing function support."},
    {-27902, "Event register timeout error."},
    {-28079, "Communication No. read error."},
    {-28080, "Communication No. incorrect error."},
    {-28136, "Unsupported function in fast mode error."},
    {-28139, "Link disconnection error."},
    {-28140, "Incorrect mode setting error."},
    {-28141, "System reboot error."},
    {-28142, "Mode error."},
    {-28143, "Hardware self-diagnosis error."},
    {-28144, "Hardware self-diagnosis error."},
    {-28150, "Data reception interruption at remote station error."},
    {-28151, "Data reception interruption at remote station error."},
    {-28153, "Data reception interruption at remote station error."},
    {-28154, "Abnormal data reception error."},
    {-28158, "Driver WDT error."},
    {-28160, "Hardware resource error."},
    {-28622, "Dedicated instruction channel in-use error."},
    {-28634, "Hardware self-diagnosis error."},
    {-28636, "Hardware self-diagnosis error."},
 
    // ×Ô¶¨Òå´íÎóÂë
    {ERROR_CODE_UNKNOWN, "Error: Unknown error code."},
    {ERROR_CODE_NOT_CONNECTED, "Error: Not connected to the device."},
    {ERROR_CODE_INVALID_PARAM, "Error: Invalid parameter."},
    {ERROR_CODE_INVALID_DATA, "Error: Invalid data provided."},
    {ERROR_CODE_STATION_OUT_OF_RANGE, "Error: Station number is out of range."},
    {ERROR_CODE_GROUP_OUT_OF_RANGE, "Error: Group number is out of range."},
    {ERROR_CODE_NETWORK_OUT_OF_RANGE, "Error: Network number is out of range."}
};
 
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CPerformanceMelsec::CPerformanceMelsec(const BoardType enBoardType) {
    m_nPath = 0;
    m_enBoardType = enBoardType;
    m_bConnected.store(false);
}
 
// Îö¹¹º¯Êý
CPerformanceMelsec::~CPerformanceMelsec() {
    Disconnect();
}
 
// »ñÈ¡×î½üµÄ´íÎóÐÅÏ¢
std::string CPerformanceMelsec::GetLastError() const {
    return m_strLastError;
}
 
// ±£´æ´íÎóÐÅÏ¢
bool CPerformanceMelsec::SaveErrorInfoToFile(const std::string& filename) {
    // ´ò¿ªÎļþ
    std::ofstream file(filename);
    if (!file.is_open()) {
        std::cerr << "Failed to open file for saving: " << filename << std::endl;
        return false;
    }
 
    // ±éÀú¾²Ì¬³ÉÔ±±äÁ¿ m_mapError ²¢½«Ã¿¸ö´íÎóÐÅϢдÈëÎļþ
    for (const auto& entry : m_mapError) {
        const int nCode = entry.first;
        const std::string& strMessage = entry.second;
        file << nCode << "|" << strMessage << "\n";
    }
    file.close();
 
    return true;
}
 
// ¼ÓÔØ´íÎóÐÅÏ¢
bool CPerformanceMelsec::LoadErrorInfoFromFile(const std::string& filename) {
    std::ifstream inFile(filename);
    if (!inFile.is_open()) {
        std::cerr << "Failed to open file for loading: " << filename << std::endl;
        return false;
    }
 
    m_mapError.clear();
    std::string line;
    while (std::getline(inFile, line)) {
        std::istringstream iss(line);
        int nCode = 0;
        std::string strToken;
        std::string strMessage;
 
        // Ê¹Ó÷ָô·û "|" ½âÎöÿһÐÐ
        if (std::getline(iss, strToken, '|')) {
            nCode = std::stoi(strToken);
        }
 
        if (std::getline(iss, strToken)) {
            strMessage = strToken;
        }
 
        if (!strMessage.empty()) {
            m_mapError[nCode] = strMessage;
        }
    }
 
    return true;
}
 
// Á¬½Óµ½PLC
int CPerformanceMelsec::Connect(const short nChannel, const short nMode) {
    std::lock_guard<std::mutex> lock(m_mtx);
 
    if (m_bConnected.load()) {
        return 0;
    }
 
    const BoardType enBoardType = FindBoardTypeByChannel(nChannel);
    if (enBoardType == BoardType::UNKNOWN || enBoardType != m_enBoardType) {
        UpdateLastError(ERROR_CODE_INVALID_PARAM);
        return ERROR_CODE_INVALID_PARAM;
    }
 
    // Á¬½ÓPLC£¬ÏÔʽÀàÐÍת»»ÒÔÆ¥Åä mdOpen µÄÇ©Ãû
    const short nRet = mdOpen(nChannel, nMode, &m_nPath);
    if (nRet == 0) {
        m_bConnected.store(true);
        m_enBoardType = enBoardType;
    }
    else {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// ¶Ï¿ªÁ¬½Ó
int CPerformanceMelsec::Disconnect() {
    std::lock_guard<std::mutex> lock(m_mtx);
 
    short nRet = 0;
    if (m_bConnected.load()) {
        nRet = mdClose(m_nPath);
        m_bConnected.store(false);
        m_nPath = 0;
    }
 
    UpdateLastError(nRet);
    LOG_DEBUG("Close connect.");
 
    return nRet;
}
 
// ¿É±à³Ì¿ØÖÆÆ÷ÈíÔª¼þÐÅÏ¢±íµÄ³õʼ»¯
int CPerformanceMelsec::InitializeController() {
    std::lock_guard<std::mutex> lock(m_mtx);
 
    if (!m_bConnected.load()) {
        UpdateLastError(ERROR_CODE_NOT_CONNECTED);
        return ERROR_CODE_NOT_CONNECTED;
    }
 
    const short nRet = mdInit(m_nPath);
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// »ñÈ¡°æ±¾ÐÅÏ¢
int CPerformanceMelsec::GetBoardVersion(BoardVersion& version) {
    if (!m_bConnected.load()) {
        UpdateLastError(ERROR_CODE_NOT_CONNECTED);
        return ERROR_CODE_NOT_CONNECTED;
    }
 
    // »ñÈ¡°æ±¾ÐÅÏ¢
    short buf[32] = { 0 };
    const short nRet = mdBdVerRead(m_nPath, buf);
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
        return nRet;
    }
 
    // Ìî³ä°æ±¾ÐÅÏ¢µ½½á¹¹Ìå
    version.fixedValue[0] = static_cast<char>(buf[0] & 0xFF);
    version.fixedValue[1] = static_cast<char>((buf[0] >> 8) & 0xFF);
 
    version.checksum[0] = static_cast<char>(buf[1] & 0xFF);
    version.checksum[1] = static_cast<char>((buf[1] >> 8) & 0xFF);
 
    version.swVersion[0] = static_cast<char>(buf[2] & 0xFF);
    version.swVersion[1] = static_cast<char>((buf[2] >> 8) & 0xFF);
 
    std::memcpy(version.date, &buf[3], 6);
 
    version.reserved = static_cast<uint32_t>(buf[6]) | (static_cast<uint32_t>(buf[7]) << 16);
 
    std::memcpy(version.swModel, &buf[8], 16);
    std::memcpy(version.hwModel, &buf[16], 16);
 
    version.twoPortMemory[0] = static_cast<char>(buf[18] & 0xFF);
    version.twoPortMemory[1] = static_cast<char>((buf[18] >> 8) & 0xFF);
 
    version.twoPortAttribute[0] = static_cast<char>(buf[19] & 0xFF);
    version.twoPortAttribute[1] = static_cast<char>((buf[19] >> 8) & 0xFF);
 
    version.availableBias[0] = static_cast<char>(buf[20] & 0xFF);
    version.availableBias[1] = static_cast<char>((buf[20] >> 8) & 0xFF);
 
    std::memcpy(version.moduleType, &buf[21], 10);
 
    return nRet;
}
 
// ¶ÁȡĿ±êÕ¾µãCPUÀàÐÍ
int CPerformanceMelsec::ReadCPUCode(const StationIdentifier& station, short& nCPUCode) {
    // ÑéÖ¤Õ¾µã²ÎÊýºÍÊý¾ÝÓÐЧÐÔ
    int nRet = ValidateStation(station);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    // È·±£Ḭ̈߳²È«µÄ×îÐ¡Ëø¶¨·¶Î§
    {
        nCPUCode = 0;
        std::lock_guard<std::mutex> lock(m_mtx);
        nRet = mdTypeRead(m_nPath, CombineStation(station), &nCPUCode);
    }
 
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// °åģʽÉèÖÃ
int CPerformanceMelsec::SetBoardMode(const short nMode) {
    // ¼ì²éÊÇ·ñÒѾ­Á¬½Ó
    if (!m_bConnected.load()) {
        UpdateLastError(ERROR_CODE_NOT_CONNECTED);
        return ERROR_CODE_NOT_CONNECTED;
    }
 
    // È·±£Ḭ̈߳²È«µÄ×îÐ¡Ëø¶¨·¶Î§
    short nRet = 0;
    {
        std::lock_guard<std::mutex> lock(m_mtx);
        nRet = mdBdModSet(m_nPath, nMode);
    }
 
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// »ñÈ¡°åģʽ
int CPerformanceMelsec::GetBoardMode(short& nMode) {
    // ¼ì²éÊÇ·ñÒѾ­Á¬½Ó
    if (!m_bConnected.load()) {
        UpdateLastError(ERROR_CODE_NOT_CONNECTED);
        return ERROR_CODE_NOT_CONNECTED;
    }
 
    short nRet = 0;
    {
        nMode = 0;
        std::lock_guard<std::mutex> lock(m_mtx);
        nRet = mdBdModRead(m_nPath, &nMode);
    }
 
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_DEBUG("Raw Mode: " << nMode);
        LOG_ERROR(m_strLastError);
    }
 
    return 0;
}
 
// °å¸´Î»
int CPerformanceMelsec::BoardReset() {
    std::lock_guard<std::mutex> lock(m_mtx);
    if (!m_bConnected.load()) {
        UpdateLastError(ERROR_CODE_NOT_CONNECTED);
        return ERROR_CODE_NOT_CONNECTED;
    }
 
    const short nRet = mdBdRst(m_nPath);
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// °åLED¶ÁÈ¡
int CPerformanceMelsec::ReadBoardLed(std::vector<short>& vecLedBuffer) {
    std::lock_guard<std::mutex> lock(m_mtx);
    if (!m_bConnected.load()) {
        UpdateLastError(ERROR_CODE_NOT_CONNECTED);
        return ERROR_CODE_NOT_CONNECTED;
    }
 
    // Çå¿Õ LED »º³åÇø
    vecLedBuffer.clear();
    vecLedBuffer.resize(16, 0);
 
    // µ÷ÓàSDK º¯Êý¶ÁÈ¡ LED Êý¾Ý
    const short nRet = mdBdLedRead(m_nPath, vecLedBuffer.data());
    if (nRet != 0) {
        UpdateLastError(ERROR_CODE_NOT_CONNECTED);
        LOG_ERROR("Error reading board LED, ErrorCode: " << nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// »ñÈ¡°å״̬
int CPerformanceMelsec::GetBoardStatus(BoardStatus& status) {
    std::lock_guard<std::mutex> lock(m_mtx);
    if (!m_bConnected) {
        UpdateLastError(ERROR_CODE_NOT_CONNECTED);
        return ERROR_CODE_NOT_CONNECTED;
    }
 
    short buf[6] = { 0 };
    const short nRet = mdBdSwRead(m_nPath, buf);
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    // ½« buf Ó³Éäµ½½á¹¹Ìå
    status = BoardStatus::fromBuffer(buf);
    return 0;
}
 
// Í¨ÓöÁÊý¾Ý
int CPerformanceMelsec::ReadData(const StationIdentifier& station, const long nDevType, const long nDevNo, long nSize, std::vector<short>& vecData) {
    // ÑéÖ¤Õ¾µã²ÎÊýºÍÊý¾ÝÓÐЧÐÔ
    int nRet = ValidateStationAndSize(station, nSize);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    // ³õʼ»¯¶ÁÈ¡»º³åÇø
    vecData.clear();
    vecData.resize(nSize, 0);
 
    // È·±£Ḭ̈߳²È«µÄ×îÐ¡Ëø¶¨·¶Î§
    {
        std::lock_guard<std::mutex> lock(m_mtx);
        short* pData = vecData.data();
        nSize *= sizeof(short);
        nRet = mdReceiveEx(m_nPath, station.nNetNo, station.nStNo, nDevType, (long)(unsigned short)nDevNo, &nSize, pData);
    }
 
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    if (nRet != 0) {
        vecData.clear(); // Èç¹û¶Áȡʧ°Ü£¬Çå¿Õ»º³åÇø
    }
 
    return nRet;
}
 
// ¶ÁȡλÊý¾Ý
int CPerformanceMelsec::ReadBitData(const StationIdentifier& station, const DeviceType enDevType, const short nDevNo, const short nBitCount, BitContainer& vecData) {
    // ÑéÖ¤Õ¾µã²ÎÊýºÍÊý¾ÝÓÐЧÐÔ
    int nRet = ValidateStationAndSize(station, nBitCount);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    if (nDevNo % 8 != 0) {
        nRet = -2;
        UpdateLastError(nRet);
        return nRet;
    }
 
    const short nDevType = CalculateDeviceType(station, enDevType);
    const auto nSize = static_cast<short>((static_cast<int>(nBitCount) + 15) / 16);  // ¼ÆËãÐèÒª¶ÁÈ¡µÄ×ÖÊýÁ¿£¨ÏòÉÏÈ¡Õû£©
 
    std::vector<short> vecTempBuffer(nSize, 0);
    nRet = ReadData(station, nDevType, nDevNo, nSize, vecTempBuffer);
 
    if (nRet == 0) {
        vecData.clear();
 
        // ½«×ÖÊý¾Ý½âÎöΪλÊý¾Ý
        for (short nIdx = 0; nIdx < nSize; ++nIdx) {
            const short nCurrentValue = vecTempBuffer[nIdx];
            // ±éÀúµ±Ç° short ÖеÄÿһλ
            for (int bitIdx = 0; bitIdx < 16; ++bitIdx) {
                bool bBit = (nCurrentValue & (1 << bitIdx)) != 0;
                vecData.push_back(bBit);
                if (vecData.size() >= nBitCount) {
                    return nRet;  // Èç¹ûÒѾ­¶ÁÈ¡ÍêËùÐèµÄλÊý£¬ÌáǰÍ˳ö
                }
            }
        }
    }
 
    return nRet;
}
 
// ¶ÁÈ¡×ÖÊý¾Ý
int CPerformanceMelsec::ReadWordData(const StationIdentifier& station, const DeviceType enDevType, const short nDevNo, const short nWordCount, WordContainer& vecData) {
    // ÑéÖ¤Õ¾µã²ÎÊýºÍÊý¾ÝÓÐЧÐÔ
    int nRet = ValidateStationAndSize(station, nWordCount);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    const short nDevType = CalculateDeviceType(station, enDevType);
    std::vector<short> vecTempBuffer(nWordCount, 0);
    nRet = ReadData(station, nDevType, nDevNo, nWordCount, vecTempBuffer);
 
    if (nRet == 0) {
        vecData.clear();
        vecData.assign(vecTempBuffer.begin(), vecTempBuffer.end());
    }
 
    return nRet;
}
 
// ¶Áȡ˫×ÖÊý¾Ý
int CPerformanceMelsec::ReadDWordData(const StationIdentifier& station, const DeviceType enDevType, const short nDevNo, const short nDWordCount, DWordContainer& vecData) {
    // ÑéÖ¤Õ¾µã²ÎÊýºÍÊý¾ÝÓÐЧÐÔ
    int nRet = ValidateStationAndSize(station, nDWordCount);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    const auto nSize = static_cast<short>(nDWordCount * 2); // Ã¿¸öË«×ÖÕ¼Á½¸ö×Ö£¨Ã¿¸öË«×ÖÕ¼ 4 ×Ö½Ú£©
    const short nDevType = CalculateDeviceType(station, enDevType);
    std::vector<short> vecTempBuffer(nSize, 0);
    nRet = ReadData(station, nDevType, nDevNo, nSize, vecTempBuffer);
 
    if (nRet == 0) {
        std::lock_guard<std::mutex> lock(m_mtx); // Ḭ̈߳²È«±£»¤
        ConvertShortToUint32(vecTempBuffer, vecData);
    }
 
    return nRet;
}
 
// Í¨ÓÃдÊý¾Ý
int CPerformanceMelsec::WriteData(const StationIdentifier& station, const long nDevType, const long nDevNo, long nSize, short* pData) {
    // ÑéÖ¤Õ¾µã²ÎÊý
    int nRet = ValidateStation(station);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    // Êý¾ÝÓÐЧÐÔ
    if (nSize < 0 || pData == nullptr) {
        UpdateLastError(ERROR_CODE_INVALID_PARAM);
        return ERROR_CODE_INVALID_PARAM;
    }
 
    // È·±£Ḭ̈߳²È«µÄ×îÐ¡Ëø¶¨·¶Î§
    {
        std::lock_guard<std::mutex> lock(m_mtx);
        nSize *= sizeof(short);
        nRet = mdSendEx(m_nPath, station.nNetNo, station.nStNo, nDevType, nDevNo, &nSize, pData);
    }
 
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// Ð´Î»Êý¾Ý
int CPerformanceMelsec::WriteBitData(const StationIdentifier& station, const DeviceType enDevType, const short nDevNo, const BitContainer& vecData) {
    // ÑéÖ¤Õ¾µã²ÎÊýºÍÊý¾ÝÓÐЧÐÔ
    int nRet = ValidateStationAndData(station, vecData);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    if (nDevNo % 8 != 0) {
        nRet = -2;
        UpdateLastError(nRet);
        return nRet;
    }
 
    const short nDevType = CalculateDeviceType(station, enDevType);
    const auto nSize = static_cast<short>((static_cast<int>(vecData.size()) + 15) / 16);  // ¼ÆËãÐèҪдÈëµÄ×ÖÊýÁ¿£¨ÏòÉÏÈ¡Õû£©
 
    // ×¼±¸ÁÙʱ»º³åÇøÀ´´æ´¢×ª»»ºóµÄ 16 Î»Êý¾Ý
    std::vector<short> vecTempBuffer(nSize, 0);
    {
        std::lock_guard<std::mutex> lock(m_mtx); // Ḭ̈߳²È«±£»¤
        // ½«Î»Êý¾Ý°´×Ö´ò°üµ½ÁÙʱ»º³åÇø
        for (int i = 0; i < vecData.size(); ++i) {
            if (vecData[i]) {
                // Ê¹Óà& 0xFFFF ±£Ö¤²»»á³¬¹ý 16 Î»£¬·ÀÖ¹Òç³ö
                vecTempBuffer[i / 16] |= static_cast<short>((1 << (i % 16)) & 0xFFFF);
            }
        }
    }
 
    return WriteData(station, nDevType, nDevNo, nSize, vecTempBuffer.data());
}
 
// Ð´×ÖÊý¾Ý
int CPerformanceMelsec::WriteWordData(const StationIdentifier& station, const DeviceType enDevType, const short nDevNo, const WordContainer& vecData) {
    // ÑéÖ¤Õ¾µã²ÎÊýºÍÊý¾ÝÓÐЧÐÔ
    const int nRet = ValidateStationAndData(station, vecData);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    // ¼ÆËãÐèҪдÈëµÄ×Ö½ÚÊý£¨Ã¿¸ö×ÖÕ¼ 2 ×Ö½Ú£©
    const short nDevType = CalculateDeviceType(station, enDevType);
    const auto nSize = static_cast<short>(vecData.size());
    const auto pData = const_cast<short*>(reinterpret_cast<const short*>(vecData.data()));
 
    return WriteData(station, nDevType, nDevNo, nSize, pData);
}
 
// Ð´Ë«×ÖÊý¾Ý
int CPerformanceMelsec::WriteDWordData(const StationIdentifier& station, const DeviceType enDevType, const short nDevNo, const DWordContainer& vecData) {
    // ÑéÖ¤Õ¾µã²ÎÊýºÍÊý¾ÝÓÐЧÐÔ
    const int nRet = ValidateStationAndData(station, vecData);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    // ¼ÆËãÐèҪдÈëµÄ×Ö½ÚÊý£¨Ã¿¸öË«×ÖÕ¼ 4 ×Ö½Ú£©
    const short nDevType = CalculateDeviceType(station, enDevType);
    const auto nSize = static_cast<short>(vecData.size() * sizeof(short));
    std::vector<short> vecBuffer(nSize, 0);
    {
        std::lock_guard<std::mutex> lock(m_mtx); // Ḭ̈߳²È«±£»¤
        ConvertUint32ToShort(vecData, vecBuffer);
    }
 
    return WriteData(station, nDevType, nDevNo, nSize, vecBuffer.data());
}
 
// À©Õ¹¶ÁÊý¾Ý
long CPerformanceMelsec::ReadDataEx(const StationIdentifier& station, long nDevType, long nDevNo, long nSize, std::vector<char>& vecData) {
    // ÑéÖ¤Õ¾µã²ÎÊýºÍ¶ÁÈ¡´óСÊÇ·ñÓÐЧ
    long nRet = ValidateStation(station);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    if (nSize < 0) {
        UpdateLastError(ERROR_CODE_INVALID_PARAM);
        return ERROR_CODE_INVALID_PARAM;
    }
 
    nSize = nSize % 2 != 0 ? nSize + 1 : nSize;
    std::vector<short> vecBuffer(nSize / 2, 0);
 
    {
        std::lock_guard<std::mutex> lock(m_mtx); // Ḭ̈߳²È«±£»¤
        nRet = mdReceiveEx(m_nPath, station.nNetNo, station.nStNo, nDevType, nDevNo, &nSize, vecBuffer.data());
    }
 
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
    else {
        std::lock_guard<std::mutex> lock(m_mtx); // Ḭ̈߳²È«±£»¤
        vecData.resize(nSize);
        ConvertShortToChar(vecBuffer, vecData);
    }
 
    return 0;
}
 
// À©Õ¹Ð´Êý¾Ý
long CPerformanceMelsec::WriteDataEx(const StationIdentifier& station, long nDevType, long nDevNo, const std::vector<char>& vecData) {
    // ÑéÖ¤Õ¾µã²ÎÊýºÍÊý¾ÝÓÐЧÐÔ
    long nRet = ValidateStationAndData(station, vecData);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    // ½« vecData ×ª»»Îª short ÀàÐ͵Ļº³åÇø
    long nSize = static_cast<long>(vecData.size());
    nSize = nSize % 2 != 0 ? nSize + 1 : nSize;
    std::vector<short> vecBuffer(nSize / 2, 0);
 
    {
        std::lock_guard<std::mutex> lock(m_mtx); // Ḭ̈߳²È«±£»¤
        ConvertCharToShort(vecData, vecBuffer);
        nRet = mdSendEx(m_nPath, station.nNetNo, station.nStNo, nDevType, nDevNo, &nSize, vecBuffer.data());
    }
 
    // ´íÎó´¦ÀíºÍÈÕÖ¾¼Ç¼
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// À©Õ¹ÈíÔª¼þËæ»ú¶ÁÈ¡
long CPerformanceMelsec::ReadRandomDataEx(const StationIdentifier& station, const std::vector<SoftElement>& vecSoftElements, std::vector<char>& vecData) {
    if (vecSoftElements.empty()) {
        UpdateLastError(ERROR_INVALID_PARAMETER);
        LOG_ERROR("Invalid parameters: soft elements are empty.");
        return ERROR_INVALID_PARAMETER;
    }
 
    // ×¼±¸ dev Êý¾Ý
    std::vector<short> devBuffer(vecSoftElements.size() * 3 + 1, 0); // Ã¿¸öÈíÔª¼þÐèÒª 3 ¸ö short£¬Íâ¼ÓÒ»¸ö¼ÆÊýÆ÷
    devBuffer[0] = static_cast<short>(vecSoftElements.size());                 // µÚÒ»¸öÔªËØÊÇÈíÔª¼þÊýÁ¿
    for (size_t i = 0; i < vecSoftElements.size(); ++i) {
        const SoftElement& element = vecSoftElements[i];
        devBuffer[i * 3 + 1] = element.nType;                        // ÈíÔª¼þÀàÐÍ
        devBuffer[i * 3 + 2] = static_cast<short>(element.nStartNo); // ÆðʼÈíÔª¼þ±àºÅ
        devBuffer[i * 3 + 3] = element.nElementCount;                // µãÊý
    }
 
    // ¼ÆËã¶ÁÈ¡Êý¾ÝËùÐ軺³åÇø´óС
    long nBufferSize = 0;
    for (const auto& element : vecSoftElements) {
        nBufferSize += element.nElementCount * 2; // Ã¿¸öµãÕ¼Óà2 ¸ö×Ö½Ú
    }
 
    // Ëø±£»¤¼°µ÷ÓàmdRandREx
    long nRet = 0;
    std::vector<short> vecBuffer(nBufferSize / 2, 0);
    {
        std::lock_guard<std::mutex> lock(m_mtx); // È·±£Ḭ̈߳²È«
        nRet = mdRandREx(m_nPath, station.nNetNo, station.nStNo, devBuffer.data(), vecBuffer.data(), nBufferSize);
    }
 
    // ´íÎó´¦ÀíºÍÈÕÖ¾¼Ç¼
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
        return nRet;
    }
 
    // ½«¶ÁÈ¡µ½µÄ short Êý¾Ýת»»Îª char Êý¾Ý
    vecData.resize(nBufferSize);
    for (size_t i = 0; i < vecBuffer.size(); ++i) {
        vecData[i * 2] = static_cast<char>(vecBuffer[i] & 0xFF);            // µÍ×Ö½Ú
        vecData[i * 2 + 1] = static_cast<char>((vecBuffer[i] >> 8) & 0xFF); // ¸ß×Ö½Ú
    }
 
    return nRet;
}
 
// À©Õ¹ÈíÔª¼þËæ»úдÈ루֧³Ö¶à¸öÈíÔª¼þ£©
long CPerformanceMelsec::WriteRandomDataEx(const StationIdentifier& station, const std::vector<SoftElement>& vecSoftElements, const std::vector<char>& vecData) {
    if (vecSoftElements.empty() || vecData.empty()) {
        UpdateLastError(ERROR_INVALID_PARAMETER);
        LOG_ERROR("Invalid parameters: soft elements or data is empty.");
        return ERROR_INVALID_PARAMETER;
    }
 
    // ×¼±¸ dev Êý¾Ý
    std::vector<long> devBuffer(vecSoftElements.size() * 3 + 1, 0); // Ã¿¸öÈíÔª¼þÐèÒª 3 ¸ö long£¬Íâ¼ÓÒ»¸ö¼ÆÊýÆ÷
    devBuffer[0] = static_cast<long>(vecSoftElements.size());                 // µÚÒ»¸öÔªËØÊÇÈíÔª¼þÊýÁ¿
    for (size_t i = 0; i < vecSoftElements.size(); ++i) {
        const SoftElement& element = vecSoftElements[i];
        devBuffer[i * 3 + 1] = static_cast<long>(element.nType);    // ÈíÔª¼þÀàÐÍ
        devBuffer[i * 3 + 2] = element.nStartNo;                    // ÆðʼÈíÔª¼þ±àºÅ£¨ÒѾ­ÊÇ long ÀàÐÍ£¬ÎÞÐèת»»£©
        devBuffer[i * 3 + 3] = static_cast<long>(element.nElementCount); // µãÊý
    }
 
    // Ëø±£»¤¼°µ÷ÓàmdRandWEx
    long nRet = 0;
    std::vector<short> vecBuffer(vecData.size() / 2, 0);
    {
        std::lock_guard<std::mutex> lock(m_mtx); // È·±£Ḭ̈߳²È«
        ConvertCharToShort(vecData, vecBuffer);
        nRet = mdRandWEx(m_nPath, station.nNetNo, station.nStNo, devBuffer.data(), vecBuffer.data(), static_cast<long>(vecBuffer.size()));
    }
 
    // ´íÎó´¦ÀíºÍÈÕÖ¾¼Ç¼
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// Ô¶³ÌÉ豸վ/Ô¶³ÌÕ¾µÄ»º³å´æ´¢Æ÷¶ÁÈ¡
long CPerformanceMelsec::ReadRemoteBuffer(const StationIdentifier& station, long nOffset, long nSize, std::vector<char>& vecData) {
    // ÑéÖ¤Õ¾µã²ÎÊýºÍÊý¾ÝÓÐЧÐÔ
    int nRet = ValidateStation(station);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    if (nSize < 0) {
        UpdateLastError(ERROR_CODE_INVALID_PARAM);
        return ERROR_CODE_INVALID_PARAM;
    }
 
    long nActualSize = (nSize + 1) / 2;
    std::vector<short> vecBuffer(nActualSize, 0);
    {
        std::lock_guard<std::mutex> lock(m_mtx); // Ḭ̈߳²È«±£»¤
        nRet = mdRemBufReadEx(m_nPath, station.nNetNo, station.nStNo, nOffset, &nActualSize, vecBuffer.data());
    }
 
    if (nRet != 0) {
        UpdateLastError(nRet); // ¸üдíÎóÂë
        LOG_ERROR(m_strLastError);
    }
    else {
        std::lock_guard<std::mutex> lock(m_mtx); // Ḭ̈߳²È«±£»¤
        ConvertShortToChar(vecBuffer, vecData);
    }
 
    return nRet;
}
 
// Ô¶³ÌÉ豸վ/Ô¶³ÌÕ¾µÄ»º³å´æ´¢Æ÷дÈë
long CPerformanceMelsec::WriteRemoteBuffer(const StationIdentifier& station, long nOffset, const std::vector<char>& vecData) {
    // ÑéÖ¤Õ¾µã²ÎÊýºÍÊý¾ÝÓÐЧÐÔ
    long nRet = ValidateStationAndData(station, vecData);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    // ½« vecData ×ª»»Îª short ÀàÐ͵Ļº³åÇø
    long nSize = static_cast<long>(vecData.size());
    std::vector<short> vecBuffer((nSize + 1) / 2, 0);
 
    {
        std::lock_guard<std::mutex> lock(m_mtx); // Ḭ̈߳²È«±£»¤
        ConvertCharToShort(vecData, vecBuffer);
        nRet = mdRemBufWriteEx(m_nPath, station.nNetNo, station.nStNo, nOffset, &nSize, vecBuffer.data());
    }
 
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// Ô¶³ÌÕ¾µÄ»º³å´æ´¢Æ÷¶ÁÈ¡ ¶ÔÏóÕ¾IPµØÖ·Ö¸¶¨
long CPerformanceMelsec::ReadRemoteBufferByIp(const std::string& strIP, long nOffset, long nSize, std::vector<char>& vecData) {
    uint32_t nAddress = 0;
    if (nSize < 0 || !ConvertIpStringToUint32(strIP, nAddress)) {
        UpdateLastError(ERROR_CODE_INVALID_PARAM);
        return ERROR_CODE_INVALID_PARAM;
    }
 
    // ½«»º³åÇø´óСµ÷ÕûΪ nSize
    vecData.resize(nSize, 0);
    std::vector<short> vecBuffer((nSize + 1) / 2, 0); // ×ª»»Îª short ÀàÐÍ
 
    // µ÷Óõײã SDK
    long nRet = 0;
    {
        std::lock_guard<std::mutex> lock(m_mtx); // Ḭ̈߳²È«±£»¤
        nRet = mdRemBufReadIPEx(m_nPath, static_cast<long>(nAddress), nOffset, &nSize, vecBuffer.data());
    }
 
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
    else {
        std::lock_guard<std::mutex> lock(m_mtx); // Ḭ̈߳²È«±£»¤
        ConvertShortToChar(vecBuffer, vecData);
    }
 
    return nRet;
}
 
// Ô¶³ÌÕ¾µÄ»º³å´æ´¢Æ÷дÈë ¶ÔÏóÕ¾IPµØÖ·Ö¸¶¨
long CPerformanceMelsec::WriteRemoteBufferByIp(const std::string& strIP, long nOffset, const std::vector<char>& vecData) {
    uint32_t nAddress = 0;
    if (vecData.empty() || !ConvertIpStringToUint32(strIP, nAddress)) {
        UpdateLastError(ERROR_CODE_INVALID_PARAM);
        return ERROR_CODE_INVALID_PARAM;
    }
 
    // ×ª»» vecData Îª short ÀàÐ͵Ļº³åÇø
    long nSize = static_cast<long>(vecData.size());
    std::vector<short> vecBuffer((nSize + 1) / 2, 0);
 
    long nRet = 0;
    {
        std::lock_guard<std::mutex> lock(m_mtx); // Ḭ̈߳²È«
        ConvertCharToShort(vecData, vecBuffer);
        nRet = mdRemBufWriteIPEx(m_nPath, static_cast<long>(nAddress), nOffset, &nSize, vecBuffer.data());
    }
 
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// ÉèÖÃ(ON)¶ÔÏóÕ¾µÄÖ¸¶¨Î»ÈíÔª¼þ
int CPerformanceMelsec::SetBitDevice(const StationIdentifier& station, const DeviceType enDevType, const short nDevNo) {
    // ÑéÖ¤Õ¾µã²ÎÊý
    int nRet = ValidateStation(station);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    // È·±£Ḭ̈߳²È«µÄ×îÐ¡Ëø¶¨·¶Î§
    {
        std::lock_guard<std::mutex> lock(m_mtx); // Ḭ̈߳²È«
        const short nDevType = CalculateDeviceType(station, enDevType);
        nRet = mdDevSet(m_nPath, CombineStation(station), nDevType, nDevNo);
    }
 
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// ¸´Î»(OFF)¶ÔÏóÕ¾µÄÖ¸¶¨Î»ÈíÔª¼þ
int CPerformanceMelsec::ResetBitDevice(const StationIdentifier& station, const DeviceType enDevType, const short enDevNo) {
    // ÑéÖ¤Õ¾µã²ÎÊý
    int nRet = ValidateStation(station);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    // È·±£Ḭ̈߳²È«µÄ×îÐ¡Ëø¶¨·¶Î§
    {
        std::lock_guard<std::mutex> lock(m_mtx);
        const short nDevType = CalculateDeviceType(station, enDevType);
        nRet = mdDevRst(m_nPath, CombineStation(station), nDevType, enDevNo);
    }
 
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// À©Õ¹Î»ÈíÔª¼þÉèÖÃ
long CPerformanceMelsec::SetBitDeviceEx(const StationIdentifier& station, long nDevType, long nDevNo) {
    std::lock_guard<std::mutex> lock(m_mtx);
 
    // ¼ì²é²ÎÊýÓÐЧÐÔ
    long nRet = ValidateStation(station);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    nRet = mdDevSetEx(m_nPath, station.nNetNo, station.nStNo, nDevType, nDevNo);
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// À©Õ¹Î»ÈíÔª¼þ¸´Î»
long CPerformanceMelsec::ResetBitDeviceEx(const StationIdentifier& station, long nDevType, long nDevNo) {
    std::lock_guard<std::mutex> lock(m_mtx);
 
    // ¼ì²é²ÎÊýÓÐЧÐÔ
    long nRet = ValidateStation(station);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    nRet = mdDevRstEx(m_nPath, station.nNetNo, station.nStNo, nDevType, nDevNo);
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// Ö´ÐжÔÏóÕ¾µÄCPU
int CPerformanceMelsec::ControlCPU(const StationIdentifier& station, ControlCode enControlCode) {
    // ÑéÖ¤Õ¾µã²ÎÊýºÍÊý¾ÝÓÐЧÐÔ
    int nRet = ValidateStation(station);
    if (nRet != 0) {
        UpdateLastError(nRet);
        return nRet;
    }
 
    // ÑéÖ¤¿ØÖÆÂëÊÇ·ñºÏ·¨
    const auto nControlCode = static_cast<short>(enControlCode);
    if (nControlCode < 0 || nControlCode > 2) {
        UpdateLastError(ERROR_CODE_INVALID_PARAM); // ²ÎÊý´íÎó
        return ERROR_CODE_INVALID_PARAM;
    }
 
    // È·±£Ḭ̈߳²È«µÄ×îÐ¡Ëø¶¨·¶Î§
    {
        std::lock_guard<std::mutex> lock(m_mtx);
        nRet = mdControl(m_nPath, CombineStation(station), nControlCode);
    }
 
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
// Ê¼þµÈ´ý
int CPerformanceMelsec::WaitForBoardEvent(std::vector<short> vecEventNumbers, const int nTimeoutMs, EventDetails& details) {
    std::lock_guard<std::mutex> lock(m_mtx);
 
    if (!m_bConnected.load()) {
        UpdateLastError(ERROR_CODE_NOT_CONNECTED);
        return ERROR_CODE_NOT_CONNECTED;
    }
 
    if (vecEventNumbers.empty() || vecEventNumbers.size() > 64) {
        UpdateLastError(ERROR_CODE_INVALID_PARAM);
        return ERROR_CODE_INVALID_PARAM;
    }
 
    // µÚ 0 ¸öÔªËØ´æ´¢ÊýÁ¿£¬×î´óÖ§³Ö 64 ¸öʼþ
    std::array<short, 65> eventno = { 0 };
    eventno[0] = static_cast<short>(vecEventNumbers.size());
    std::copy(vecEventNumbers.begin(), vecEventNumbers.end(), eventno.begin() + 1);
 
    // ³õʼ»¯Êä³ö²ÎÊý
    details.nEventNo = 0;
    details.details.fill(0);
 
    const int nRet = mdWaitBdEvent(m_nPath, eventno.data(), nTimeoutMs, &details.nEventNo, details.details.data());
    if (nRet != 0) {
        UpdateLastError(nRet);
        LOG_ERROR(m_strLastError);
    }
 
    return nRet;
}
 
//============================================¸¨Öúº¯Êý=======================================================
// ¸üÐÂ×î½üµÄ´íÎóÐÅÏ¢
void CPerformanceMelsec::UpdateLastError(const int nCode) {
    if (nCode == 0) {
        return;
    }
 
    // ¼ì²é´íÎóÂëÊÇ·ñ´æÔÚÓÚÓ³Éä±íÖÐ
    const auto it = m_mapError.find(nCode);
    if (it != m_mapError.end()) {
        // Èç¹ûÕÒµ½£¬Ö±½Ó·µ»Ø¶ÔÓ¦ÓïÑԵĴíÎóÐÅÏ¢
        m_strLastError = it->second;
    }
    else {
        // Èç¹ûδÕÒµ½£¬´¦ÀíÌØÊⷶΧ
        m_strLastError = "Unknown error.";
        if (nCode == -28611 || nCode == -28612) {
            // ÏµÍ³³ö´í
            m_strLastError = "System error.";
        }
 
        if (nCode >= -20480 && nCode <= -16384) {
            // CC-Link ÏµÍ³¼ì²â³öµÄ´íÎó
            m_strLastError = "Error detected in the CC-Link system.";
        }
 
        if (nCode >= -12288 && nCode <= -8193) {
            // CC-Link IE TSN ÏµÍ³¼ì²â³öµÄ´íÎó
            m_strLastError = "Error detected in the CC-Link IE TSN system.";
        }
 
        if (nCode >= -8192 && nCode <= -4097) {
            // CC-Link IE ¿ØÖÆÍøÂçϵͳ¼ì²â³öµÄ´íÎó
            m_strLastError = "Error detected in the CC-Link IE control network system.";
        }
 
        if (nCode >= -4096 && nCode <= -257) {
            // MELSECNET/10 »ò MELSECNET/ÍøÂçϵͳ´íÎó·¶Î§
            m_strLastError = "Errors detected in MELSECNET/10 or MELSECNET/network system.";
        }
 
        if (nCode >= 4096 && nCode <= 16383) {
            // MELSEC Êý¾ÝÁ´½Ó¿â·¶Î§
            m_strLastError = "Internal error detected by MELSEC Data Link Library.";
        }
 
        if (nCode == 18944 || nCode == 18945) {
            // Á´½Ó¹ØÁª³ö´í
            m_strLastError = "Link association error: Network does not exist, unsupported CPU, or incorrect network No./station number.";
        }
 
        if (nCode >= 16384 && nCode <= 20479) {
            // PLC CPU ¼ì²â·¶Î§
            m_strLastError = "Errors detected by the programmable controller CPU in the target station.";
        }
 
        if (nCode >= 28416 && nCode <= 28671) {
            // ÈßÓ๦ÄÜÄ£¿é·¶Î§
            m_strLastError = "Error detected in the redundancy module of the target station.";
        }
    }
}
 
// ¼ì²éÁ¬½Ó״̬ºÍÕ¾µã²ÎÊýÓÐЧÐÔ
int CPerformanceMelsec::ValidateStation(const StationIdentifier& station) const {
    // ¼ì²éÊÇ·ñÒÑÁ¬½Ó
    if (!m_bConnected.load()) {
        return ERROR_CODE_NOT_CONNECTED;
    }
 
    // ¼ì²éÍøÂçºÅºÍÕ¾µãºÅ·¶Î§
    if (station.nNetNo < 0 || station.nNetNo > 239 || station.nStNo < 0 || station.nStNo > 255) {
        return ERROR_CODE_INVALID_PARAM;
    }
 
    return 0; // ²ÎÊýÓÐЧ
}
 
// ÑéÖ¤Õ¾µã²ÎÊýºÍÊý¾ÝÓÐЧÐÔ
int CPerformanceMelsec::ValidateStationAndSize(const StationIdentifier& station, const short nCount) const {
    // ÑéÖ¤Õ¾µã²ÎÊý
    const int nRet = ValidateStation(station);
    if (nRet != 0) {
        return nRet; // Èç¹ûÕ¾µãÑé֤ʧ°Ü£¬·µ»Ø¶ÔÓ¦´íÎóÂë
    }
 
    if (nCount <= 0) {
        return ERROR_CODE_INVALID_PARAM;
    }
 
    return 0; // Ñé֤ͨ¹ý
}
 
// IP×Ö·û´®×ªuint32_t
bool CPerformanceMelsec::ConvertIpStringToUint32(const std::string& strIP, uint32_t& nIP) {
    nIP = 0;
    std::stringstream ss(strIP);
    std::string strSegment;
    int nShift = 24;
 
    while (std::getline(ss, strSegment, '.')) {
        const auto nByte = static_cast<uint32_t>(std::stoi(strSegment));
        if (nByte > 255) {
            return false;
        }
        nIP |= (nByte << nShift);
        nShift -= 8;
    }
 
    return true;
}
 
//============================================¾²Ì¬¸¨Öúº¯Êý====================================================
// ÑÓʱ£¬²¢ÇÒת·¢´°¿ÚÏûÏ¢
void CPerformanceMelsec::Delay(const unsigned int nDelayMs) {
    MSG message;
    // Èç¹ûÑÓ³Ùʱ¼äΪ 0£¬½ö´¦ÀíÒ»´ÎÏûÏ¢¶ÓÁÐ
    if (nDelayMs == 0) {
        // ·Ç×èÈûµÄ¼ì²éÏûÏ¢¶ÓÁÐ
        if (PeekMessage(&message, nullptr, 0, 0, PM_REMOVE)) {
            TranslateMessage(&message);  // ½«ÏûϢת»¯ÎªÓÐЧµÄ´°¿ÚÏûÏ¢
            DispatchMessage(&message);   // ÅÉ·¢ÏûÏ¢¸øÏàÓ¦µÄ´°¿Ú¹ý³Ì
        }
        return;
    }
 
    DWORD finish;
    const DWORD start = GetTickCount();  // »ñÈ¡µ±Ç°µÄʱ¼ä´Á£¨´ÓϵͳÆô¶¯ÒÔÀ´µÄºÁÃëÊý£©
    do {
        if (PeekMessage(&message, nullptr, 0, 0, PM_REMOVE)) {
            TranslateMessage(&message);  // ×ª»»ÏûÏ¢
            DispatchMessage(&message);   // ´¦ÀíÏûÏ¢
        }
        Sleep(1);   // ÔÝÍ£ 1 ºÁÃ룬·ÀÖ¹¹ý¶ÈÕ¼ÓàCPU
        finish = GetTickCount(); // »ñÈ¡µ±Ç°µÄʱ¼ä´Á
    } while ((finish - start) < nDelayMs);  // Ñ­»·Ö±µ½¾­¹ýµÄʱ¼ä´óÓÚÖ¸¶¨µÄÑÓ³Ùʱ¼ä
}
 
BoardType CPerformanceMelsec::FindBoardTypeByChannel(const int nChannel) {
    if (nChannel >= MELSECNET_CHANNEL(1) && nChannel <= MELSECNET_CHANNEL(4)) {
        return BoardType::MELSECNET_H;
    }
    else if (nChannel >= CC_LINK_CHANNEL(1) && nChannel <= CC_LINK_CHANNEL(4)) {
        return BoardType::CC_LINK_VER_2;
    }
    else if (nChannel >= CC_LINK_IE_CONTROL_CHANNEL(1) && nChannel <= CC_LINK_IE_CONTROL_CHANNEL(4)) {
        return BoardType::CC_LINK_IE_CONTROL;
    }
    else if (nChannel >= CC_LINK_IE_FIELD_CHANNEL(1) && nChannel <= CC_LINK_IE_FIELD_CHANNEL(4)) {
        return BoardType::CC_LINK_IE_FIELD;
    }
    else if (nChannel >= CC_LINK_IE_TSN_CHANNEL(1) && nChannel <= CC_LINK_IE_TSN_CHANNEL(4)) {
        return BoardType::CC_LINK_IE_TSN;
    }
    return BoardType::UNKNOWN;
}
 
// ºÏ²¢ÍøÂçºÅºÍÕ¾µãºÅ
short CPerformanceMelsec::CombineStation(const StationIdentifier& station) {
    return static_cast<short>(station.nStNo | ((station.nNetNo << 8) & 0xFF00));
}
 
// ¼ÆËãÈíÔª¼þÀàÐÍ
short CPerformanceMelsec::CalculateDeviceType(const StationIdentifier& station, DeviceType enDevType) {
    int nDevType = static_cast<int>(enDevType);
 
    // ¸ù¾ÝÈíÔª¼þÀàÐ͵ÄÌØ¶¨¹æÔò½øÐмÆËã
    if (enDevType == DeviceType::LX || enDevType == DeviceType::LY ||
        enDevType == DeviceType::LB || enDevType == DeviceType::LW ||
        enDevType == DeviceType::LSB || enDevType == DeviceType::LSW) {
        // ÍøÂçºÅ¼ÓÆ«ÒÆ
        nDevType += station.nNetNo;
    }
    else if (enDevType == DeviceType::ER) {
        // Îļþ¼Ä´æÆ÷µÄ¿éºÅ¼ÓÆ«ÒÆ
        nDevType += 0;
    }
    else if (enDevType == DeviceType::SPG) {
        // Æðʼ I/O No. ¡Â 16 µÄÖµ
        nDevType += 0 / 16;
    }
 
    return static_cast<short>(nDevType);
}
 
// std::vector<char>ת»»Îªstd::vector<short>
void CPerformanceMelsec::ConvertCharToShort(const std::vector<char>& vecChar, std::vector<short>& vecShort) {
    vecShort.resize((vecChar.size() + 1) / 2, 0); // µ÷Õû short ÈÝÆ÷´óС
    for (size_t i = 0; i < vecChar.size(); i++) {
        if (i % 2 == 0) {
            vecShort[i / 2] = static_cast<unsigned char>(vecChar[i]);       // µÍ×Ö½Ú
        }
        else {
            vecShort[i / 2] |= static_cast<unsigned char>(vecChar[i]) << 8; // ¸ß×Ö½Ú
        }
    }
}
 
// std::vector<short>ת»»Îªstd::vector<char>
void CPerformanceMelsec::ConvertShortToChar(const std::vector<short>& vecShort, std::vector<char>& vecChar) {
    vecChar.resize(vecShort.size() * 2); // µ÷Õû char ÈÝÆ÷´óС
    for (size_t i = 0; i < vecShort.size(); i++) {
        vecChar[i * 2] = static_cast<char>(vecShort[i] & 0xFF);             // µÍ×Ö½Ú
        vecChar[i * 2 + 1] = static_cast<char>((vecShort[i] >> 8) & 0xFF);  // ¸ß×Ö½Ú
    }
}
 
// std::vector<uint8_t>ת»»Îªstd::vector<short>
void CPerformanceMelsec::ConvertUint8ToShort(const std::vector<uint8_t>& vecUint8, std::vector<short>& vecShort) {
    vecShort.resize((vecUint8.size() + 1) / 2, 0); // µ÷Õû short ÈÝÆ÷´óС
    for (size_t i = 0; i < vecUint8.size(); i++) {
        if (i % 2 == 0) {
            vecShort[i / 2] = static_cast<short>(vecUint8[i]);          // µÍ×Ö½Ú
        }
        else {
            vecShort[i / 2] |= static_cast<short>(vecUint8[i] << 8);    // ¸ß×Ö½Ú
        }
    }
}
 
// std::vector<short>ת»»Îªstd::vector<uint8_t>
void CPerformanceMelsec::ConvertShortToUint8(const std::vector<short>& vecShort, std::vector<uint8_t>& vecUint8) {
    vecUint8.resize(vecShort.size() * 2); // µ÷Õû uint8_t ÈÝÆ÷´óС
    for (size_t i = 0; i < vecShort.size(); i++) {
        vecUint8[i * 2] = static_cast<uint8_t>(vecShort[i] & 0xFF);             // µÍ×Ö½Ú
        vecUint8[i * 2 + 1] = static_cast<uint8_t>((vecShort[i] >> 8) & 0xFF);  // ¸ß×Ö½Ú
    }
}
 
// std::vector<uint32_t>ת»»Îªstd::vector<short>
void CPerformanceMelsec::ConvertUint32ToShort(const std::vector<uint32_t>& vecUint32, std::vector<short>& vecShort) {
    vecShort.resize(vecUint32.size() * 2); // Ã¿¸ö uint32_t ×ª»»ÎªÁ½¸ö short
    for (size_t i = 0; i < vecUint32.size(); i++) {
        vecShort[i * 2] = static_cast<short>(vecUint32[i] & 0xFFFF);             // µÍ16λ
        vecShort[i * 2 + 1] = static_cast<short>((vecUint32[i] >> 16) & 0xFFFF); // ¸ß16λ
    }
}
 
// std::vector<short>ת»»Îªstd::vector<uint32_t>
void CPerformanceMelsec::ConvertShortToUint32(const std::vector<short>& vecShort, std::vector<uint32_t>& vecUint32) {
    vecUint32.resize((vecShort.size() + 1) / 2, 0); // Ã¿Á½¸ö short ºÏ²¢ÎªÒ»¸ö uint32_t
    for (size_t i = 0; i < vecUint32.size(); i++) {
        vecUint32[i] = (static_cast<uint32_t>(static_cast<uint16_t>(vecShort[i * 2 + 1])) << 16) | // ¸ß16λ
            static_cast<uint32_t>(static_cast<uint16_t>(vecShort[i * 2]));              // µÍ16λ
    }
}
 
//============================================Ä£°å¸¨Öúº¯Êý====================================================
// ÑéÖ¤Õ¾µã²ÎÊýºÍÊý¾ÝÓÐЧÐÔ
template <typename T>
int CPerformanceMelsec::ValidateStationAndData(const StationIdentifier& station, const std::vector<T>& vecData) {
    // ÑéÖ¤Õ¾µã²ÎÊý
    const int nRet = ValidateStation(station);
    if (nRet != 0) {
        return nRet; // Èç¹ûÕ¾µãÑé֤ʧ°Ü£¬·µ»Ø¶ÔÓ¦´íÎóÂë
    }
 
    // ÑéÖ¤Êý¾ÝÊÇ·ñΪ¿Õ
    if (vecData.empty()) {
        return ERROR_CODE_INVALID_PARAM;
    }
 
    return 0; // Ñé֤ͨ¹ý
}
 
// ÓɵÍת¸ßÈÝÆ÷µÄÄ£°å£¨ÕûÐÍ£©
template <typename T, typename U>
void CPerformanceMelsec::ConvertLowToHigh(const std::vector<T>& vecLow, std::vector<U>& vecHigh) {
    static_assert(std::is_integral<T>::value && std::is_integral<U>::value, "T and U must be integral types");
 
    // ×Ô¶¯¼ÆËã nGroupSize
    constexpr size_t nGroupSize = sizeof(U) / sizeof(T);
 
    // Èç¹û T ºÍ U µÄ´óСÏàµÈ£¬Ö±½Óת»»
    if (sizeof(T) == sizeof(U)) {
        vecHigh.assign(vecLow.begin(), vecLow.end());
        return;
    }
 
    // Èç¹û U µÄ´óСÊÇ T µÄ±¶Êý£¬Õý³£×éºÏ
    static_assert(sizeof(U) > sizeof(T), "Size of U must be greater than or equal to size of T");
 
    // ¼ÆËãÍêÕû×éµÄÊýÁ¿
    size_t nHighSize = (vecLow.size() + nGroupSize - 1) / nGroupSize; // ÏòÉÏÈ¡Õû
    vecHigh.resize(nHighSize, 0);
 
    // ºÏ²¢µÍλÊý¾Ýµ½¸ßλÊý¾Ý
    for (size_t i = 0; i < vecLow.size(); i++) {
        vecHigh[i / nGroupSize] |= (static_cast<U>(vecLow[i]) << ((i % nGroupSize) * CHAR_BIT * sizeof(T)));
    }
 
    return vecHigh;
}
 
// ÓɸßתµÍÈÝÆ÷µÄÄ£°å£¨ÕûÐÍ£©
template <typename T, typename U>
void CPerformanceMelsec::ConvertHighToLow(const std::vector<T>& vecHigh, std::vector<U>& vecLow) {
    static_assert(std::is_integral<T>::value && std::is_integral<U>::value, "T and U must be integral types");
 
    // ×Ô¶¯¼ÆËã nGroupSize
    constexpr size_t nGroupSize = sizeof(T) / sizeof(U);
 
    // Èç¹û T ºÍ U µÄ´óСÏàµÈ£¬Ö±½Óת»»
    if (sizeof(T) == sizeof(U)) {
        vecLow.assign(vecHigh.begin(), vecHigh.end());
        return;
    }
 
    // Èç¹û T µÄ´óСÊÇ U µÄ±¶Êý£¬Õý³£·Ö½â
    static_assert(sizeof(T) > sizeof(U), "Size of T must be greater than or equal to size of U");
 
    size_t nLowSize = vecHigh.size() * nGroupSize; // µÍÈÝÆ÷µÄ´óС
    vecLow.resize(nLowSize, 0);
 
    // ·Ö½â¸ßλÊý¾Ýµ½µÍλÊý¾Ý
    for (size_t i = 0; i < vecHigh.size(); i++) {
        for (size_t j = 0; j < nGroupSize; j++) {
            vecLow[i * nGroupSize + j] = static_cast<U>((vecHigh[i] >> (j * CHAR_BIT * sizeof(U))) & ((1ULL << (CHAR_BIT * sizeof(U))) - 1));
        }
    }
 
    return vecLow;
}