rust-ethernet-ip 0.7.0

High-performance EtherNet/IP communication library for Allen-Bradley CompactLogix and ControlLogix PLCs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
// lib.rs - Rust EtherNet/IP Driver Library with Comprehensive Documentation
// =========================================================================
//
// # Rust EtherNet/IP Driver Library
//
// A high-performance, production-ready EtherNet/IP communication library for
// Allen-Bradley CompactLogix and ControlLogix PLCs, written in pure Rust with
// comprehensive C# language bindings.
//
// ## Overview
//
// This library provides a complete implementation of the EtherNet/IP protocol
// and Common Industrial Protocol (CIP) for communicating with Allen-Bradley
// CompactLogix and ControlLogix series PLCs. It offers native Rust APIs, comprehensive
// language bindings, and production-ready features for enterprise deployment.
//
// ## Architecture
//
// ```text
// ┌─────────────────────────────────────────────────────────────────────────────────┐
// │                              Application Layer                                  │
// │  ┌─────────────┐  ┌─────────────────────────────────────────────────────────┐  │
// │  │    Rust     │  │                    C# Ecosystem                         │  │
// │  │   Native    │  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────────┐  │  │
// │  │             │  │  │     WPF     │  │  WinForms   │  │   ASP.NET Core  │  │  │
// │  │             │  │  │  Desktop    │  │  Desktop    │  │    Web API      │  │  │
// │  │             │  │  └─────────────┘  └─────────────┘  └─────────┬───────┘  │  │
// │  │             │  │                                               │           │  │
// │  │             │  │                                    ┌─────────┴───────┐  │  │
// │  │             │  │                                    │  TypeScript +   │  │  │
// │  │             │  │                                    │  React Frontend │  │  │
// │  │             │  │                                    │  (HTTP/REST)    │  │  │
// │  │             │  │                                    └─────────────────┘  │  │
// │  └─────────────┘  └─────────────────────────────────────────────────────────┘  │
// └─────────────────────┬─────────────────────────────────────────────────────────┘
//// ┌─────────────────────┴─────────────────────────────────────────────────────────┐
// │                        Language Wrappers                                      │
// │  ┌─────────────┐                                                              │
// │  │   C# FFI    │                                                              │
// │  │  Wrapper    │                                                              │
// │  │             │                                                              │
// │  │ • 22 funcs  │                                                              │
// │  │ • Type-safe │                                                              │
// │  │ • Cross-plat│                                                              │
// │  └─────────────┘                                                              │
// └─────────────────────┬─────────────────────────────────────────────────────────┘
//// ┌─────────────────────┴─────────────────────────────────────────────────────────┐
// │                         Core Rust Library                                     │
// │  ┌─────────────────────────────────────────────────────────────────────────┐  │
// │  │                           EipClient                                     │  │
// │  │  • Connection Management & Session Handling                            │  │
// │  │  • Advanced Tag Operations & Program-Scoped Tag Support                │  │
// │  │  • Complete Data Type Support (13 Allen-Bradley types)                 │  │
// │  │  • Advanced Tag Path Parsing (arrays, bits, UDTs, strings)             │  │
// │  │  • Real-Time Subscriptions with Event-Driven Notifications             │  │
// │  │  • High-Performance Batch Operations (2,000+ ops/sec)                  │  │
// │  └─────────────────────────────────────────────────────────────────────────┘  │
// │  ┌─────────────────────────────────────────────────────────────────────────┐  │
// │  │                    Protocol Implementation                              │  │
// │  │  • EtherNet/IP Encapsulation Protocol                                  │  │
// │  │  • CIP (Common Industrial Protocol)                                    │  │
// │  │  • Symbolic Tag Addressing with Advanced Parsing                       │  │
// │  │  • Comprehensive CIP Error Code Mapping                                │  │
// │  └─────────────────────────────────────────────────────────────────────────┘  │
// │  ┌─────────────────────────────────────────────────────────────────────────┐  │
// │  │                        Network Layer                                    │  │
// │  │  • TCP Socket Management with Connection Pooling                       │  │
// │  │  • Async I/O with Tokio Runtime                                        │  │
// │  │  • Robust Error Handling & Network Resilience                          │  │
// │  │  • Session Management & Automatic Reconnection                         │  │
// │  └─────────────────────────────────────────────────────────────────────────┘  │
// └─────────────────────────────────────────────────────────────────────────────────┘
// ```
//
// ## Integration Paths
//
// ### 🦀 **Native Rust Applications**
// Direct library usage with full async support and zero-overhead abstractions.
// Perfect for high-performance applications and embedded systems.
//
// ### 🖥️ **Desktop Applications (C#)**
// - **WPF**: Modern desktop applications with MVVM architecture
// - **WinForms**: Traditional Windows applications with familiar UI patterns
// - Uses C# FFI wrapper for seamless integration
//
// ### 🌐 **Web Applications**
// - **ASP.NET Core Web API**: RESTful backend service
// - **Scalable Architecture**: Backend handles PLC communication, frontend provides UI
//
// ### 🔧 **System Integration**
// - **C/C++ Applications**: Direct FFI integration
// - **Other .NET Languages**: VB.NET, F#, etc. via C# wrapper
// - **Microservices**: ASP.NET Core API as a service component
//
// ## Features
//
// ### Core Capabilities
// - **High Performance**: 2,000+ operations per second with batch operations
// - **Real-Time Subscriptions**: Event-driven notifications with 1ms-10s intervals
// - **Complete Data Types**: All Allen-Bradley native data types with type-safe operations
// - **Advanced Tag Addressing**: Program-scoped, arrays, bits, UDTs, strings
// - **Batch Operations**: High-performance multi-tag read/write with 2,000+ ops/sec
// - **Async I/O**: Built on Tokio for excellent concurrency and performance
// - **Error Handling**: Comprehensive CIP error code mapping and reporting
// - **Memory Safe**: Zero-copy operations where possible, proper resource cleanup
// - **Production Ready**: Enterprise-grade monitoring, health checks, and configuration
//
// ### Supported PLCs
// - **CompactLogix L1x, L2x, L3x, L4x, L5x series** (Primary focus)
// - **ControlLogix L6x, L7x, L8x series** (Full support)
// - Optimized for PC applications (Windows, Linux, macOS)
//
// ### Advanced Tag Addressing
// - **Program-scoped tags**: `Program:MainProgram.Tag1`
// - **Array element access**: `MyArray[5]`, `MyArray[1,2,3]`
// - **Bit-level operations**: `MyDINT.15` (access individual bits)
// - **UDT member access**: `MyUDT.Member1.SubMember`
// - **String operations**: `MyString.LEN`, `MyString.DATA[5]`
// - **Complex nested paths**: `Program:Production.Lines[2].Stations[5].Motor.Status.15`
//
// ### Complete Data Type Support
// - **BOOL**: Boolean values
// - **SINT, INT, DINT, LINT**: Signed integers (8, 16, 32, 64-bit)
// - **USINT, UINT, UDINT, ULINT**: Unsigned integers (8, 16, 32, 64-bit)
// - **REAL, LREAL**: Floating point (32, 64-bit IEEE 754)
// - **STRING**: Variable-length strings
// - **UDT**: User Defined Types with full nesting support
//
// ### Protocol Support
// - **EtherNet/IP**: Complete encapsulation protocol implementation
// - **CIP**: Common Industrial Protocol for tag operations
// - **Symbolic Addressing**: Direct tag name resolution with advanced parsing
// - **Session Management**: Proper registration/unregistration sequences
//
// ### Integration Options
// - **Native Rust**: Direct library usage with full async support
// - **C# Desktop Applications**: WPF and WinForms via C# FFI wrapper
// - **Web Applications**: ASP.NET Core API + TypeScript/React/Vue frontend
// - **C/C++ Integration**: Direct FFI functions for system integration
// - **Cross-Platform**: Windows, Linux, macOS support
//
// ## Performance Characteristics
//
// Benchmarked on typical industrial hardware:
//
// | Operation | Performance | Notes |
// |-----------|-------------|-------|
// | Read BOOL | 1,500+ ops/sec | Single tag operations |
// | Read DINT | 1,400+ ops/sec | 32-bit integer tags |
// | Read REAL | 1,300+ ops/sec | Floating point tags |
// | Write BOOL | 800+ ops/sec | Single tag operations |
// | Write DINT | 750+ ops/sec | 32-bit integer tags |
// | Write REAL | 700+ ops/sec | Floating point tags |
// | **Batch Read** | **2,000+ ops/sec** | **Multi-tag operations** |
// | **Batch Write** | **1,500+ ops/sec** | **Multi-tag operations** |
// | **Real-Time Subscriptions** | **1ms-10s intervals** | **Event-driven** |
// | Connection | <1 second | Initial session setup |
// | Tag Path Parsing | 10,000+ ops/sec | Advanced addressing |
//
// ## Security Considerations
//
// - **No Authentication**: EtherNet/IP protocol has limited built-in security
// - **Network Level**: Implement firewall rules and network segmentation
// - **PLC Protection**: Use PLC safety locks and access controls
// - **Data Validation**: Always validate data before writing to PLCs
//
// ## Thread Safety
//
// The `EipClient` struct is **NOT** thread-safe. For multi-threaded applications:
// - Use one client per thread, OR
// - Implement external synchronization (Mutex/RwLock), OR
// - Use a connection pool pattern
//
// ## Memory Usage
//
// - **Per Connection**: ~8KB base memory footprint
// - **Network Buffers**: ~2KB per active connection
// - **Tag Cache**: Minimal (tag names only when needed)
// - **Total Typical**: <10MB for most applications
//
// ## Error Handling Philosophy
//
// This library follows Rust's error handling principles:
// - All fallible operations return `Result<T, EtherNetIpError>`
// - Errors are propagated rather than panicking
// - Detailed error messages with CIP status code mapping
// - Network errors are distinguished from protocol errors
//
// ## Known Limitations
//
// The following operations are not supported due to PLC firmware restrictions.
// These limitations are inherent to the Allen-Bradley PLC firmware and cannot be
// bypassed at the library level.
//
// ### STRING Tag Writing
//
// **Cannot write directly to STRING tags** (e.g., `gTest_STRING`).
//
// **Root Cause:** PLC firmware limitation (CIP Error 0x2107). The PLC rejects
// direct write operations to STRING tags, regardless of the communication method used.
//
// **What Works:**
// - Reading STRING tags: `gTest_STRING` (read successfully)
// - Reading STRING members in UDTs: `gTestUDT.Member5_String` (read successfully)
//
// **What Doesn't Work:**
// - Writing simple STRING tags: `gTest_STRING` (write fails - PLC limitation)
// - Writing program-scoped STRING tags: `Program:TestProgram.gTest_STRING` (write fails)
// - Writing STRING members in UDTs directly: `gTestUDT.Member5_String` (write fails)
//
// **Workaround for STRING Members in UDTs:**
// If the STRING is part of a UDT structure, read the entire UDT, modify the STRING
// member in memory, then write the entire UDT back. For standalone STRING tags,
// there is no workaround at the communication library level.
//
// ### UDT Array Element Member Writing
//
// **Cannot write directly to members of UDT array elements** (e.g., `gTestUDT_Array[0].Member1_DINT`).
//
// **Root Cause:** PLC firmware limitation (CIP Error 0x2107). The PLC does not
// support direct write operations to individual members within UDT array elements.
//
// **What Works:**
// - Reading UDT array element members: `gTestUDT_Array[0].Member1_DINT` (read successfully)
// - Writing entire UDT array elements: `gTestUDT_Array[0]` (write full UDT structure)
// - Writing UDT members (non-array): `gTestUDT.Member1_DINT` (write individual members)
// - Writing simple array elements: `gArray[5]` (write elements of simple arrays)
//
// **What Doesn't Work:**
// - Writing UDT array element members: `gTestUDT_Array[0].Member1_DINT` (write fails)
// - Writing program-scoped UDT array element members: `Program:TestProgram.gTestUDT_Array[0].Member1_DINT` (write fails)
//
// **Workaround:**
// Use a read-modify-write pattern: Read the entire UDT array element, modify the
// member in memory, then write the entire UDT array element back.
//
// **Important Notes:**
// - These limitations are PLC firmware restrictions, not library bugs
// - The library correctly implements the EtherNet/IP and CIP protocols
// - All read operations work correctly for all tag types
// - Workarounds are available for UDT array element members and STRING members in UDTs
//
// ## Examples
//
// See the `examples/` directory for comprehensive usage examples, including:
// - Advanced tag addressing demonstrations
// - Complete data type showcase
// - Real-world industrial automation scenarios
// - Professional HMI/SCADA dashboard
// - Multi-language integration examples (C#)
//
// ## Changelog
//
// ### v0.6.3 (March 2026) - **CURRENT STABLE**
// - Critical protocol and type-system reliability fixes
// - Broader test coverage including simulator-backed scenarios
// - C# wrapper reliability fixes for route path + datatype handling
//
// ### v0.6.2 (January 2026)
// - **NEW: Stream Injection API** - `connect_with_stream()` for custom TCP transport
//   - Enables wrapping streams for metrics/observability (bytes in/out)
//   - Supports custom socket options (keepalive, timeouts, bind local address)
//   - Allows reusing pre-established tunnels/connections
//   - Supports in-memory streams for deterministic testing
// - **NEW: Test Configuration** - Environment variable support for PLC testing
//   - `TEST_PLC_ADDRESS` - Set PLC IP address for tests
//   - `TEST_PLC_SLOT` - Set CPU slot number
//   - `SKIP_PLC_TESTS` - Skip PLC-dependent tests
// - **FIXED: Nested UDT Member Access** - Fixed reading nested UDT members from array elements
//   - Correctly handles paths like `Cell_NestData[90].PartData.Member`
//   - Fixed array element detection to use TagPath::parse() for complex paths
//   - Now correctly builds full CIP paths instead of using array workaround

// ### v0.6.1 (January 2026)
// - **Repository Cleanup**: Removed Go and Python wrappers to focus on Rust library and C# integration
// - **Streamlined Examples**: Focused on Microsoft stack (WinForms, WPF, ASP.NET) and Rust native examples

// ### v0.6.0 (January 2026)
// - **NEW: Generic UDT Format** - `UdtData` struct with `symbol_id` and raw bytes
//   - Works with any UDT without requiring prior knowledge of member structure
//   - Enables parsing UDT members using UDT definitions when needed
//   - Supports reading and writing UDTs generically
// - **NEW: Library Health** - All 31 unit tests passing, production-ready core
// - **NEW: Comprehensive Examples** - All examples updated for new UDT API
// - **NEW: Integration Tests** - All tests updated for new UDT format
// - Enhanced UDT documentation with usage examples
// - Improved code quality and consistency

// ### v0.5.5 (December 2025)
// - **NEW: Array Element Access** - Full read/write support for array elements
// - **NEW: Array Element Writing** - Write individual array elements with automatic array modification
// - **NEW: BOOL Array Support** - Automatic DWORD bit extraction for BOOL arrays

// ### v0.5.4 (October 2025)
// - **NEW: UDT Definition Discovery from PLC** - Automatic UDT structure detection
// - **NEW: Enhanced Tag Discovery** - Full attribute support with permissions and scope
// - **NEW: Packet Size Negotiation** - Dynamic negotiation with firmware 20+
// - **NEW: Route Path Support** - Slot configuration and multi-hop routing
// - **NEW: CIP Service 0x03** - Get Attribute List implementation
// - **NEW: CIP Service 0x4C** - Read Tag Fragmented for large data
// - **NEW: UDT Template Management** - Caching and parsing of UDT templates
// - **NEW: Tag Attributes API** - Comprehensive tag metadata discovery
// - **NEW: Program-Scoped Tag Discovery** - Discover tags within specific programs
// - **NEW: Route Path API** - Support for remote racks and complex topologies
// - **NEW: Cache Management** - Clear and manage UDT/tag caches
// - **NEW: Comprehensive Unit Tests** - 15+ new test cases for UDT discovery
// - **NEW: UDT Discovery Demo** - Complete example showcasing new features
// - **NEW: Enhanced FFI Functions** - 3 new C# wrapper functions
// - Enhanced error handling for UDT operations
// - Improved performance with packet size optimization
// - Production-ready UDT support for industrial applications

// ### v0.5.3 (January 2025)
// - Enhanced safety documentation for all FFI functions
// - Comprehensive clippy optimizations and code quality improvements
// - Improved memory management and connection pool handling
// - Enhanced C# wrapper stability
// - Production-ready code quality with 0 warnings
//
// ### v0.5.0 (January 2025)
// - Professional HMI/SCADA production dashboard
// - Enterprise-grade monitoring and health checks
// - Production-ready configuration management
// - Comprehensive metrics collection and reporting
// - Enhanced error handling and recovery mechanisms
//
// ### v0.4.0 (January 2025)
// - Real-time subscriptions with event-driven notifications
// - High-performance batch operations (2,000+ ops/sec)
// - Complete data type support for all Allen-Bradley types
// - Advanced tag path parsing (program-scoped, arrays, bits, UDTs)
// - Enhanced error handling and documentation
// - Comprehensive test coverage (47+ tests)
// - Production-ready stability and performance
//
// =========================================================================

use crate::udt::UdtManager;
use lazy_static::lazy_static;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::TcpStream;

/// Trait for streams that can be used with EipClient
///
/// This trait combines the requirements for streams used with EtherNet/IP:
/// - `AsyncRead`: Read data from the stream
/// - `AsyncWrite`: Write data to the stream
/// - `Unpin`: Required for async operations
/// - `Send`: Required for cross-thread safety
///
/// Most tokio streams (like `TcpStream`, `UnixStream`, etc.) automatically
/// implement this trait. You can also implement it for custom stream wrappers
/// to add metrics, logging, or other functionality.
///
/// # Example
///
/// ```no_run
/// use rust_ethernet_ip::EtherNetIpStream;
/// use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
///
/// // Custom stream wrapper for metrics
/// struct MetricsStream<S> {
///     inner: S,
///     bytes_read: u64,
///     bytes_written: u64,
/// }
///
/// // Most tokio streams automatically implement EtherNetIpStream
/// // For example, TcpStream implements it:
/// use tokio::net::TcpStream;
/// // TcpStream: AsyncRead + AsyncWrite + Unpin + Send ✓
/// // Therefore: TcpStream implements EtherNetIpStream ✓
/// ```
pub trait EtherNetIpStream: AsyncRead + AsyncWrite + Unpin + Send {}

impl<S> EtherNetIpStream for S where S: AsyncRead + AsyncWrite + Unpin + Send {}
use tokio::runtime::Runtime;
use tokio::sync::Mutex;
use tokio::time::{timeout, Duration, Instant};

pub mod config; // Production-ready configuration management
pub mod error;
pub mod ffi;
pub mod monitoring; // Enterprise-grade monitoring and health checks
pub mod plc_manager;
pub mod subscription;
pub mod tag_group;
pub mod tag_manager;
pub mod tag_path;
pub mod tag_subscription; // Real-time subscription management
pub mod udt;
pub mod version;

// Re-export commonly used items
pub use config::{
    ConnectionConfig, LoggingConfig, MonitoringConfig, PerformanceConfig, PlcSpecificConfig,
    ProductionConfig, SecurityConfig,
};
pub use error::{EtherNetIpError, Result};
pub use monitoring::{
    ConnectionMetrics, ErrorMetrics, HealthMetrics, HealthStatus, MonitoringMetrics,
    OperationMetrics, PerformanceMetrics, ProductionMonitor,
};
pub use plc_manager::{PlcConfig, PlcConnection, PlcManager};
pub use subscription::{SubscriptionManager, SubscriptionOptions, TagSubscription};
pub use tag_group::{
    TagGroupConfig, TagGroupEvent, TagGroupEventKind, TagGroupFailureCategory,
    TagGroupFailureDiagnostic, TagGroupSnapshot, TagGroupSubscription, TagGroupValueResult,
};
pub use tag_manager::{TagCache, TagManager, TagMetadata, TagPermissions, TagScope};
pub use tag_path::TagPath;
pub use tag_subscription::{
    SubscriptionManager as RealTimeSubscriptionManager,
    SubscriptionOptions as RealTimeSubscriptionOptions, TagSubscription as RealTimeSubscription,
};
pub use udt::{TagAttributes, UdtDefinition, UdtMember, UdtTemplate};

/// Initialize tracing subscriber with environment-based filtering
///
/// This function sets up the tracing subscriber to use the `RUST_LOG` environment variable
/// for log level filtering. If not called, tracing events will be ignored.
///
/// # Examples
///
/// ```no_run
/// use rust_ethernet_ip::init_tracing;
///
/// // Initialize with default settings (reads RUST_LOG env var)
/// init_tracing();
///
/// // Or set RUST_LOG before calling:
/// // RUST_LOG=debug cargo run
/// ```
///
/// # Log Levels
///
/// Set the `RUST_LOG` environment variable to control logging:
/// - `RUST_LOG=trace` - Most verbose (all events)
/// - `RUST_LOG=debug` - Debug information
/// - `RUST_LOG=info` - Informational messages (default)
/// - `RUST_LOG=warn` - Warnings only
/// - `RUST_LOG=error` - Errors only
/// - `RUST_LOG=rust_ethernet_ip=debug` - Debug for this crate only
///
/// # Panics
///
/// This function will panic if called more than once. Use `try_init_tracing()` for
/// non-panicking initialization.
pub fn init_tracing() {
    use tracing_subscriber::fmt;
    use tracing_subscriber::EnvFilter;

    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));

    let subscriber = fmt::Subscriber::builder()
        .with_env_filter(filter)
        .with_target(false) // Don't show module paths by default
        .finish();

    tracing::subscriber::set_global_default(subscriber).expect("Failed to set tracing subscriber");
}

/// Try to initialize tracing subscriber (non-panicking version)
///
/// Returns `Ok(())` if initialization was successful, or an error if a subscriber
/// was already set.
pub fn try_init_tracing() -> std::result::Result<(), Box<dyn std::error::Error>> {
    use tracing_subscriber::fmt;
    use tracing_subscriber::EnvFilter;

    let filter = EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"));

    let subscriber = fmt::Subscriber::builder()
        .with_env_filter(filter)
        .with_target(false)
        .finish();

    tracing::subscriber::set_global_default(subscriber)
        .map_err(|e| Box::new(e) as Box<dyn std::error::Error>)?;
    Ok(())
}

/// Route path for PLC communication
#[derive(Debug, Clone)]
pub struct RoutePath {
    pub slots: Vec<u8>,
    pub ports: Vec<u8>,
    pub addresses: Vec<String>,
}

impl RoutePath {
    /// Creates a new route path
    pub fn new() -> Self {
        Self {
            slots: Vec::new(),
            ports: Vec::new(),
            addresses: Vec::new(),
        }
    }

    /// Adds a backplane slot to the route
    pub fn add_slot(mut self, slot: u8) -> Self {
        self.slots.push(slot);
        self
    }

    /// Adds a network port to the route
    pub fn add_port(mut self, port: u8) -> Self {
        self.ports.push(port);
        self
    }

    /// Adds a network address to the route
    pub fn add_address(mut self, address: String) -> Self {
        self.addresses.push(address);
        self
    }

    /// Builds CIP route path bytes
    ///
    /// Reference: EtherNetIP_Connection_Paths_and_Routing.md, Port Segment Encoding
    /// According to the examples: Port 1 (backplane), Slot X = [0x01, X]
    /// The 0x01 byte encodes both "Port Segment (8-bit link)" AND "Port 1 (backplane)"
    /// Examples from documentation:
    ///   - Slot 0: `01 00`
    ///   - Slot 1: `01 01`
    ///   - Slot 2: `01 02`
    pub fn to_cip_bytes(&self) -> Vec<u8> {
        let mut path = Vec::new();

        // Add backplane slots
        // Reference: EtherNetIP_Connection_Paths_and_Routing.md, Backplane Port Segment Examples
        // Format: [0x01, slot] where:
        //   - 0x01 = Port Segment (8-bit link) for Port 1 (backplane)
        //   - slot = Slot number (0-255)
        // Examples: Slot 0 = [0x01, 0x00], Slot 1 = [0x01, 0x01], etc.
        for &slot in &self.slots {
            path.push(0x01); // Port Segment (8-bit link) for Port 1 (backplane)
            path.push(slot); // Slot number
        }

        // Add network hops
        for (i, address) in self.addresses.iter().enumerate() {
            if i < self.ports.len() {
                path.push(self.ports[i]); // Port number
            } else {
                path.push(0x01); // Default port
            }

            // Parse IP address and add to path
            if let Ok(ip) = address.parse::<std::net::Ipv4Addr>() {
                let octets = ip.octets();
                path.extend_from_slice(&octets);
            }
        }

        path
    }
}

impl Default for RoutePath {
    fn default() -> Self {
        Self::new()
    }
}

// Static runtime and client management for FFI
lazy_static! {
    /// Global Tokio runtime for handling async operations in FFI context
    static ref RUNTIME: Runtime = Runtime::new().unwrap();

    /// Global storage for EipClient instances, indexed by client ID
    static ref CLIENTS: Mutex<HashMap<i32, EipClient>> = Mutex::new(HashMap::new());

    /// Counter for generating unique client IDs
    static ref NEXT_ID: Mutex<i32> = Mutex::new(1);
}

// =========================================================================
// BATCH OPERATIONS DATA STRUCTURES
// =========================================================================

/// Represents a single operation in a batch request
///
/// This enum defines the different types of operations that can be
/// performed in a batch. Each operation specifies whether it's a read
/// or write operation and includes the necessary parameters.
#[derive(Debug, Clone)]
pub enum BatchOperation {
    /// Read operation for a specific tag
    ///
    /// # Fields
    ///
    /// * `tag_name` - The name of the tag to read
    Read { tag_name: String },

    /// Write operation for a specific tag with a value
    ///
    /// # Fields
    ///
    /// * `tag_name` - The name of the tag to write
    /// * `value` - The value to write to the tag
    Write { tag_name: String, value: PlcValue },
}

/// Result of a single operation in a batch request
///
/// This structure contains the result of executing a single batch operation,
/// including success/failure status and the actual data or error information.
#[derive(Debug, Clone)]
pub struct BatchResult {
    /// The original operation that was executed
    pub operation: BatchOperation,

    /// The result of the operation
    pub result: std::result::Result<Option<PlcValue>, BatchError>,

    /// Execution time for this specific operation (in microseconds)
    pub execution_time_us: u64,
}

/// Specific error types that can occur during batch operations
///
/// This enum provides detailed error information for batch operations,
/// allowing for better error handling and diagnostics.
#[derive(Debug, Clone)]
pub enum BatchError {
    /// Tag was not found in the PLC
    TagNotFound(String),

    /// Data type mismatch between expected and actual
    DataTypeMismatch { expected: String, actual: String },

    /// Network communication error
    NetworkError(String),

    /// CIP protocol error with status code
    CipError { status: u8, message: String },

    /// Tag name parsing error
    TagPathError(String),

    /// Value serialization/deserialization error
    SerializationError(String),

    /// Operation timeout
    Timeout,

    /// Generic error for unexpected issues
    Other(String),
}

impl std::fmt::Display for BatchError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BatchError::TagNotFound(tag) => write!(f, "Tag not found: {tag}"),
            BatchError::DataTypeMismatch { expected, actual } => {
                write!(f, "Data type mismatch: expected {expected}, got {actual}")
            }
            BatchError::NetworkError(msg) => write!(f, "Network error: {msg}"),
            BatchError::CipError { status, message } => {
                write!(f, "CIP error (0x{status:02X}): {message}")
            }
            BatchError::TagPathError(msg) => write!(f, "Tag path error: {msg}"),
            BatchError::SerializationError(msg) => write!(f, "Serialization error: {msg}"),
            BatchError::Timeout => write!(f, "Operation timeout"),
            BatchError::Other(msg) => write!(f, "Error: {msg}"),
        }
    }
}

impl std::error::Error for BatchError {}

/// Configuration for batch operations
///
/// This structure controls the behavior and performance characteristics
/// of batch read/write operations. Proper tuning can significantly
/// improve throughput for applications that need to process many tags.
#[derive(Debug, Clone)]
pub struct BatchConfig {
    /// Maximum number of operations to include in a single CIP packet
    ///
    /// Larger values improve performance but may exceed PLC packet size limits.
    /// Typical range: 10-50 operations per packet.
    pub max_operations_per_packet: usize,

    /// Maximum packet size in bytes for batch operations
    ///
    /// Should not exceed the PLC's maximum packet size capability.
    /// Typical values: 504 bytes (default), up to 4000 bytes for modern PLCs.
    pub max_packet_size: usize,

    /// Timeout for individual batch packets (in milliseconds)
    ///
    /// This is per-packet timeout, not per-operation.
    /// Typical range: 1000-5000 milliseconds.
    pub packet_timeout_ms: u64,

    /// Whether to continue processing other operations if one fails
    ///
    /// If true, failed operations are reported but don't stop the batch.
    /// If false, the first error stops the entire batch processing.
    pub continue_on_error: bool,

    /// Whether to optimize packet packing by grouping similar operations
    ///
    /// If true, reads and writes are grouped separately for better performance.
    /// If false, operations are processed in the order provided.
    pub optimize_packet_packing: bool,
}

impl Default for BatchConfig {
    fn default() -> Self {
        Self {
            max_operations_per_packet: 20,
            max_packet_size: 504, // Conservative default for maximum compatibility
            packet_timeout_ms: 3000,
            continue_on_error: true,
            optimize_packet_packing: true,
        }
    }
}

/// Connected session information for Class 3 explicit messaging
///
/// Allen-Bradley PLCs often require connected sessions for certain operations
/// like STRING writes. This structure maintains the connection state.
#[derive(Debug, Clone)]
pub struct ConnectedSession {
    /// Connection ID assigned by the PLC
    pub connection_id: u32,

    /// Our connection ID (originator -> target)
    pub o_to_t_connection_id: u32,

    /// PLC's connection ID (target -> originator)
    pub t_to_o_connection_id: u32,

    /// Connection serial number for this session
    pub connection_serial: u16,

    /// Originator vendor ID (our vendor ID)
    pub originator_vendor_id: u16,

    /// Originator serial number (our serial number)
    pub originator_serial: u32,

    /// Connection timeout multiplier
    pub timeout_multiplier: u8,

    /// Requested Packet Interval (RPI) in microseconds
    pub rpi: u32,

    /// Connection parameters for O->T direction
    pub o_to_t_params: ConnectionParameters,

    /// Connection parameters for T->O direction
    pub t_to_o_params: ConnectionParameters,

    /// Timestamp when connection was established
    pub established_at: Instant,

    /// Whether this connection is currently active
    pub is_active: bool,

    /// Sequence counter for connected messages (increments with each message)
    pub sequence_count: u16,
}

/// Connection parameters for EtherNet/IP connections
#[derive(Debug, Clone)]
pub struct ConnectionParameters {
    /// Connection size in bytes
    pub size: u16,

    /// Connection type (0x02 = Point-to-point, 0x01 = Multicast)
    pub connection_type: u8,

    /// Priority (0x00 = Low, 0x01 = High, 0x02 = Scheduled, 0x03 = Urgent)
    pub priority: u8,

    /// Variable size flag
    pub variable_size: bool,
}

impl Default for ConnectionParameters {
    fn default() -> Self {
        Self {
            size: 500,             // 500 bytes default
            connection_type: 0x02, // Point-to-point
            priority: 0x01,        // High priority
            variable_size: false,
        }
    }
}

impl ConnectedSession {
    /// Creates a new connected session with default parameters
    pub fn new(connection_serial: u16) -> Self {
        Self {
            connection_id: 0,
            o_to_t_connection_id: 0,
            t_to_o_connection_id: 0,
            connection_serial,
            originator_vendor_id: 0x1337,   // Custom vendor ID
            originator_serial: 0x1234_5678, // Custom serial number
            timeout_multiplier: 0x05,       // 32 seconds timeout
            rpi: 100_000,                   // 100ms RPI
            o_to_t_params: ConnectionParameters::default(),
            t_to_o_params: ConnectionParameters::default(),
            established_at: Instant::now(),
            is_active: false,
            sequence_count: 0,
        }
    }

    /// Creates a connected session with alternative parameters for different PLCs
    pub fn with_config(connection_serial: u16, config_id: u8) -> Self {
        let mut session = Self::new(connection_serial);

        match config_id {
            1 => {
                // Config 1: Conservative Allen-Bradley parameters
                session.timeout_multiplier = 0x07; // 256 seconds timeout
                session.rpi = 200_000; // 200ms RPI (slower)
                session.o_to_t_params.size = 504; // Standard packet size
                session.t_to_o_params.size = 504;
                session.o_to_t_params.priority = 0x00; // Low priority
                session.t_to_o_params.priority = 0x00;
                tracing::debug!("CONFIG 1: Conservative: 504 bytes, 200ms RPI, low priority");
            }
            2 => {
                // Config 2: Compact parameters
                session.timeout_multiplier = 0x03; // 8 seconds timeout
                session.rpi = 50000; // 50ms RPI (faster)
                session.o_to_t_params.size = 256; // Smaller packet size
                session.t_to_o_params.size = 256;
                session.o_to_t_params.priority = 0x02; // Scheduled priority
                session.t_to_o_params.priority = 0x02;
                tracing::debug!("CONFIG 2: Compact: 256 bytes, 50ms RPI, scheduled priority");
            }
            3 => {
                // Config 3: Minimal parameters
                session.timeout_multiplier = 0x01; // 4 seconds timeout
                session.rpi = 1_000_000; // 1000ms RPI (very slow)
                session.o_to_t_params.size = 128; // Very small packets
                session.t_to_o_params.size = 128;
                session.o_to_t_params.priority = 0x03; // Urgent priority
                session.t_to_o_params.priority = 0x03;
                tracing::debug!("CONFIG 3: Minimal: 128 bytes, 1000ms RPI, urgent priority");
            }
            4 => {
                // Config 4: Standard Rockwell parameters (from documentation)
                session.timeout_multiplier = 0x05; // 32 seconds timeout
                session.rpi = 100_000; // 100ms RPI
                session.o_to_t_params.size = 500; // Standard size
                session.t_to_o_params.size = 500;
                session.o_to_t_params.connection_type = 0x01; // Multicast
                session.t_to_o_params.connection_type = 0x01;
                session.originator_vendor_id = 0x001D; // Rockwell vendor ID
                tracing::debug!(
                    "CONFIG 4: Rockwell standard: 500 bytes, 100ms RPI, multicast, Rockwell vendor"
                );
            }
            5 => {
                // Config 5: Large buffer parameters
                session.timeout_multiplier = 0x0A; // Very long timeout
                session.rpi = 500_000; // 500ms RPI
                session.o_to_t_params.size = 1024; // Large packets
                session.t_to_o_params.size = 1024;
                session.o_to_t_params.variable_size = true; // Variable size
                session.t_to_o_params.variable_size = true;
                tracing::debug!("CONFIG 5: Large buffer: 1024 bytes, 500ms RPI, variable size");
            }
            _ => {
                // Default config
                tracing::debug!("CONFIG 0: Default parameters");
            }
        }

        session
    }
}

/// Represents the different data types supported by Allen-Bradley PLCs
///
/// These correspond to the CIP data type codes used in EtherNet/IP
/// communication. Each variant maps to a specific 16-bit type identifier
/// that the PLC uses to describe tag data.
///
/// # Supported Data Types
///
/// ## Integer Types
/// - **SINT**: 8-bit signed integer (-128 to 127)
/// - **INT**: 16-bit signed integer (-32,768 to 32,767)
/// - **DINT**: 32-bit signed integer (-2,147,483,648 to 2,147,483,647)
/// - **LINT**: 64-bit signed integer (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
///
/// ## Unsigned Integer Types
/// - **USINT**: 8-bit unsigned integer (0 to 255)
/// - **UINT**: 16-bit unsigned integer (0 to 65,535)
/// - **UDINT**: 32-bit unsigned integer (0 to 4,294,967,295)
/// - **ULINT**: 64-bit unsigned integer (0 to 18,446,744,073,709,551,615)
///
/// ## Floating Point Types
/// - **REAL**: 32-bit IEEE 754 float (±1.18 × 10^-38 to ±3.40 × 10^38)
/// - **LREAL**: 64-bit IEEE 754 double (±2.23 × 10^-308 to ±1.80 × 10^308)
///
/// ## Other Types
/// - **BOOL**: Boolean value (true/false)
/// - **STRING**: Variable-length string
/// - **UDT**: User Defined Type (structured data)
///
/// Represents raw UDT (User Defined Type) data
///
/// This structure stores UDT data in a generic format that works for any UDT
/// without requiring knowledge of member names. The `symbol_id` (template instance ID)
/// is required for writing UDTs back to the PLC, and the raw bytes can be parsed
/// later when the UDT definition is available.
///
/// # Usage
///
/// To write a UDT, you typically need to read it first to get the `symbol_id`.
/// While it's technically possible to calculate the symbol_id, it's much safer
/// to enforce a read of the UDT before writing to it.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct UdtData {
    /// The template instance ID (symbol_id) from the PLC
    /// This is required for writing UDTs back to the PLC
    pub symbol_id: i32,
    /// Raw UDT data bytes
    /// This can be parsed into member values when the UDT definition is known
    pub data: Vec<u8>,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum PlcValue {
    /// Boolean value (single bit)
    ///
    /// Maps to CIP type 0x00C1. In CompactLogix PLCs, BOOL tags
    /// are stored as single bits but transmitted as bytes over the network.
    Bool(bool),

    /// 8-bit signed integer (-128 to 127)
    ///
    /// Maps to CIP type 0x00C2. Used for small numeric values,
    /// status codes, and compact data storage.
    Sint(i8),

    /// 16-bit signed integer (-32,768 to 32,767)
    ///
    /// Maps to CIP type 0x00C3. Common for analog input/output values,
    /// counters, and medium-range numeric data.
    Int(i16),

    /// 32-bit signed integer (-2,147,483,648 to 2,147,483,647)
    ///
    /// Maps to CIP type 0x00C4. This is the most common integer type
    /// in Allen-Bradley PLCs, used for counters, setpoints, and numeric values.
    Dint(i32),

    /// 64-bit signed integer (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807)
    ///
    /// Maps to CIP type 0x00C5. Used for large counters, timestamps,
    /// and high-precision calculations.
    Lint(i64),

    /// 8-bit unsigned integer (0 to 255)
    ///
    /// Maps to CIP type 0x00C6. Used for byte data, small counters,
    /// and status flags.
    Usint(u8),

    /// 16-bit unsigned integer (0 to 65,535)
    ///
    /// Maps to CIP type 0x00C7. Common for analog values, port numbers,
    /// and medium-range unsigned data.
    Uint(u16),

    /// 32-bit unsigned integer (0 to 4,294,967,295)
    ///
    /// Maps to CIP type 0x00C8. Used for large counters, memory addresses,
    /// and unsigned calculations.
    Udint(u32),

    /// 64-bit unsigned integer (0 to 18,446,744,073,709,551,615)
    ///
    /// Maps to CIP type 0x00C9. Used for very large counters, timestamps,
    /// and high-precision unsigned calculations.
    Ulint(u64),

    /// 32-bit IEEE 754 floating point number
    ///
    /// Maps to CIP type 0x00CA. Used for analog values, calculations,
    /// and any data requiring decimal precision.
    /// Range: ±1.18 × 10^-38 to ±3.40 × 10^38
    Real(f32),

    /// 64-bit IEEE 754 floating point number
    ///
    /// Maps to CIP type 0x00CB. Used for high-precision calculations,
    /// scientific data, and extended-range floating point values.
    /// Range: ±2.23 × 10^-308 to ±1.80 × 10^308
    Lreal(f64),

    /// String value
    ///
    /// Maps to CIP type 0x00DA. Variable-length string data
    /// commonly used for product names, status messages, and text data.
    String(String),

    /// User Defined Type instance
    ///
    /// Maps to CIP type 0x00A0. Structured data type containing
    /// multiple members of different types.
    ///
    /// **v0.6.0**: Uses `UdtData` which stores the symbol_id (template instance ID)
    /// and raw bytes. This generic format works for any UDT without requiring
    /// knowledge of member names ahead of time. The raw bytes can be parsed
    /// into member values when the UDT definition is available using `UdtData::parse()`.
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// # let mut client = rust_ethernet_ip::EipClient::connect("192.168.1.100:44818").await?;
    /// use rust_ethernet_ip::PlcValue;
    /// let value = client.read_tag("MyUDT").await?;
    /// if let PlcValue::Udt(udt_data) = value {
    ///     let udt_def = client.get_udt_definition("MyUDT").await?;
    ///     // Convert UdtDefinition to UserDefinedType
    ///     let mut user_def = rust_ethernet_ip::udt::UserDefinedType::new(udt_def.name.clone());
    ///     for member in &udt_def.members {
    ///         user_def.add_member(member.clone());
    ///     }
    ///     let members = udt_data.parse(&user_def)?;
    ///     // Access members via HashMap
    /// }
    /// # Ok(())
    /// # }
    /// ```
    Udt(UdtData),
}

impl UdtData {
    /// Parses the raw UDT data into a HashMap of member values using the UDT definition
    ///
    /// **v0.6.0**: This method converts the generic `UdtData` format into a structured
    /// HashMap of member names to values. This requires a UDT definition to know the
    /// structure of the data.
    ///
    /// Use `EipClient::get_udt_definition()` to obtain the definition from the PLC first.
    ///
    /// # Arguments
    ///
    /// * `definition` - The UDT definition containing member information (offsets, types, etc.)
    ///
    /// # Returns
    ///
    /// A HashMap mapping member names to their parsed `PlcValue` values
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// # let mut client = rust_ethernet_ip::EipClient::connect("192.168.1.100:44818").await?;
    /// use rust_ethernet_ip::PlcValue;
    /// let udt_value = client.read_tag("MyUDT").await?;
    /// if let PlcValue::Udt(udt_data) = udt_value {
    ///     let udt_def = client.get_udt_definition("MyUDT").await?;
    ///     // Convert UdtDefinition to UserDefinedType
    ///     let mut user_def = rust_ethernet_ip::udt::UserDefinedType::new(udt_def.name.clone());
    ///     for member in &udt_def.members {
    ///         user_def.add_member(member.clone());
    ///     }
    ///     let members = udt_data.parse(&user_def)?;
    ///     
    ///     if let Some(PlcValue::Dint(value)) = members.get("Member1") {
    ///         println!("Member1 value: {}", value);
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn parse(
        &self,
        definition: &crate::udt::UserDefinedType,
    ) -> crate::error::Result<HashMap<String, PlcValue>> {
        definition.to_hash_map(&self.data)
    }

    /// Creates UdtData from a HashMap of member values and a UDT definition
    ///
    /// **v0.6.0**: This method serializes member values back into raw bytes according
    /// to the UDT definition. This is useful when you need to modify UDT members and
    /// write them back to the PLC.
    ///
    /// # Arguments
    ///
    /// * `members` - HashMap of member names to `PlcValue` values
    /// * `definition` - The UDT definition containing member information (offsets, types, etc.)
    /// * `symbol_id` - The template instance ID (symbol_id) for this UDT. Typically obtained
    ///   by reading the UDT first.
    ///
    /// # Returns
    ///
    /// `UdtData` containing the serialized bytes and symbol_id, ready to be written back
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// # let mut client = rust_ethernet_ip::EipClient::connect("192.168.1.100:44818").await?;
    /// use rust_ethernet_ip::{PlcValue, UdtData};
    /// // Read existing UDT to get symbol_id
    /// let udt_value = client.read_tag("MyUDT").await?;
    /// let udt_def = client.get_udt_definition("MyUDT").await?;
    ///
    /// if let PlcValue::Udt(mut udt_data) = udt_value {
    ///     // Convert UdtDefinition to UserDefinedType
    ///     let mut user_def = rust_ethernet_ip::udt::UserDefinedType::new(udt_def.name.clone());
    ///     for member in &udt_def.members {
    ///         user_def.add_member(member.clone());
    ///     }
    ///     // Parse to modify members
    ///     let mut members = udt_data.parse(&user_def)?;
    ///     members.insert("Member1".to_string(), PlcValue::Dint(42));
    ///
    ///     // Serialize back to UdtData
    ///     let modified_udt = UdtData::from_hash_map(&members, &user_def, udt_data.symbol_id)?;
    ///     client.write_tag("MyUDT", PlcValue::Udt(modified_udt)).await?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn from_hash_map(
        members: &HashMap<String, PlcValue>,
        definition: &crate::udt::UserDefinedType,
        symbol_id: i32,
    ) -> crate::error::Result<Self> {
        let data = definition.from_hash_map(members)?;
        Ok(UdtData { symbol_id, data })
    }
}

impl PlcValue {
    /// Converts the PLC value to its byte representation for network transmission
    ///
    /// This function handles the little-endian byte encoding required by
    /// the EtherNet/IP protocol. Each data type has specific encoding rules:
    ///
    /// - BOOL: Single byte (0x00 = false, 0xFF = true)
    /// - SINT: Single signed byte
    /// - INT: 2 bytes in little-endian format
    /// - DINT: 4 bytes in little-endian format
    /// - LINT: 8 bytes in little-endian format
    /// - USINT: Single unsigned byte
    /// - UINT: 2 bytes in little-endian format
    /// - UDINT: 4 bytes in little-endian format
    /// - ULINT: 8 bytes in little-endian format
    /// - REAL: 4 bytes IEEE 754 little-endian format
    /// - LREAL: 8 bytes IEEE 754 little-endian format
    ///
    /// # Returns
    ///
    /// A vector of bytes ready for transmission to the PLC
    pub fn to_bytes(&self) -> Vec<u8> {
        match self {
            PlcValue::Bool(val) => vec![if *val { 0xFF } else { 0x00 }],
            PlcValue::Sint(val) => val.to_le_bytes().to_vec(),
            PlcValue::Int(val) => val.to_le_bytes().to_vec(),
            PlcValue::Dint(val) => val.to_le_bytes().to_vec(),
            PlcValue::Lint(val) => val.to_le_bytes().to_vec(),
            PlcValue::Usint(val) => val.to_le_bytes().to_vec(),
            PlcValue::Uint(val) => val.to_le_bytes().to_vec(),
            PlcValue::Udint(val) => val.to_le_bytes().to_vec(),
            PlcValue::Ulint(val) => val.to_le_bytes().to_vec(),
            PlcValue::Real(val) => val.to_le_bytes().to_vec(),
            PlcValue::Lreal(val) => val.to_le_bytes().to_vec(),
            PlcValue::String(val) => {
                // Try minimal approach - just length + data without padding
                // Testing if the PLC accepts a simpler format

                let mut bytes = Vec::new();

                // Length field (4 bytes as DINT) - number of characters currently used
                let length = val.len().min(82) as u32;
                bytes.extend_from_slice(&length.to_le_bytes());

                // String data - just the actual characters, no padding
                let string_bytes = val.as_bytes();
                let data_len = string_bytes.len().min(82);
                bytes.extend_from_slice(&string_bytes[..data_len]);

                bytes
            }
            PlcValue::Udt(udt_data) => {
                // Return the raw UDT data bytes
                udt_data.data.clone()
            }
        }
    }

    /// Returns the CIP data type code for this value
    ///
    /// These codes are defined by the CIP specification and must match
    /// exactly what the PLC expects for each data type.
    ///
    /// # Returns
    ///
    /// The 16-bit CIP type code for this value type
    pub fn get_data_type(&self) -> u16 {
        match self {
            PlcValue::Bool(_) => 0x00C1,   // BOOL
            PlcValue::Sint(_) => 0x00C2,   // SINT (signed char)
            PlcValue::Int(_) => 0x00C3,    // INT (short)
            PlcValue::Dint(_) => 0x00C4,   // DINT (int)
            PlcValue::Lint(_) => 0x00C5,   // LINT (long long)
            PlcValue::Usint(_) => 0x00C6,  // USINT (unsigned char)
            PlcValue::Uint(_) => 0x00C7,   // UINT (unsigned short)
            PlcValue::Udint(_) => 0x00C8,  // UDINT (unsigned int)
            PlcValue::Ulint(_) => 0x00C9,  // ULINT (unsigned long long)
            PlcValue::Real(_) => 0x00CA,   // REAL (float)
            PlcValue::Lreal(_) => 0x00CB,  // LREAL (double)
            PlcValue::String(_) => 0x00CE, // Allen-Bradley STRING type
            PlcValue::Udt(_) => 0x00A0,    // UDT placeholder
        }
    }
}

/// High-performance EtherNet/IP client for PLC communication
///
/// This struct provides the core functionality for communicating with Allen-Bradley
/// PLCs using the EtherNet/IP protocol. It handles connection management, session
/// registration, and tag operations.
///
/// # Thread Safety
///
/// The `EipClient` is **NOT** thread-safe. For multi-threaded applications:
///
/// ```rust,no_run
/// use std::sync::Arc;
/// use tokio::sync::Mutex;
/// use rust_ethernet_ip::EipClient;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
///     // Create a thread-safe wrapper
///     let client = Arc::new(Mutex::new(EipClient::connect("192.168.1.100:44818").await?));
///
///     // Use in multiple threads
///     let client_clone = client.clone();
///     tokio::spawn(async move {
///         let mut client = client_clone.lock().await;
///         let _ = client.read_tag("Tag1").await?;
///         Ok::<(), Box<dyn std::error::Error + Send + Sync>>(())
///     });
///     Ok(())
/// }
/// ```
///
/// # Performance Characteristics
///
/// | Operation | Latency | Throughput | Memory |
/// |-----------|---------|------------|---------|
/// | Connect | 100-500ms | N/A | ~8KB |
/// | Read Tag | 1-5ms | 1,500+ ops/sec | ~2KB |
/// | Write Tag | 2-10ms | 600+ ops/sec | ~2KB |
/// | Batch Read | 5-20ms | 2,000+ ops/sec | ~4KB |
///
/// # Known Limitations
///
/// The following operations are **not supported** due to PLC firmware limitations:
///
/// ## UDT Array Element Member Writes
///
/// **Cannot write directly to UDT array element members** (e.g., `gTestUDT_Array[0].Member1_DINT`).
/// This is a PLC firmware limitation, not a library bug. The PLC returns CIP Error 0x2107
/// (Vendor Specific Error) when attempting to write to such paths.
///
/// ## STRING Tags and STRING Members in UDTs
///
/// **Cannot write directly to STRING tags or STRING members in UDTs**.
/// This is a PLC firmware limitation (CIP Error 0x2107). Both simple STRING tags
/// (e.g., `gTest_STRING`) and STRING members within UDTs (e.g., `gTestUDT.Member5_String`)
/// cannot be written directly. STRING values must be written as part of the entire UDT
/// structure, not as individual tags or members.
///
/// **What works:**
/// - ✅ Reading UDT array element members: `gTestUDT_Array[0].Member1_DINT` (read)
/// - ✅ Writing entire UDT array elements: `gTestUDT_Array[0]` (write full UDT)
/// - ✅ Writing UDT members (non-STRING): `gTestUDT.Member1_DINT` (write DINT/REAL/BOOL/INT members)
/// - ✅ Writing array elements: `gArray[5]` (write element of simple array)
/// - ✅ Reading STRING tags: `gTest_STRING` (read)
/// - ✅ Reading STRING members in UDTs: `gTestUDT.Member5_String` (read)
///
/// **What doesn't work:**
/// - ❌ Writing UDT array element members: `gTestUDT_Array[0].Member1_DINT` (write)
/// - ❌ Writing program-scoped UDT array element members: `Program:TestProgram.gTestUDT_Array[0].Member1_DINT` (write)
/// - ❌ Writing simple STRING tags: `gTest_STRING` (write) - PLC limitation
/// - ❌ Writing program-scoped STRING tags: `Program:TestProgram.gTest_STRING` (write) - PLC limitation
/// - ❌ Writing STRING members in UDTs: `gTestUDT.Member5_String` (write) - must write entire UDT
/// - ❌ Writing program-scoped STRING members: `Program:TestProgram.gTestUDT.Member5_String` (write) - must write entire UDT
///
/// **Workaround:**
/// To modify a UDT array element member, read the entire UDT array element, modify the member
/// in memory, then write the entire UDT array element back:
///
/// ```rust,no_run
/// # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
/// # let mut client = rust_ethernet_ip::EipClient::connect("192.168.1.100:44818").await?;
/// use rust_ethernet_ip::{PlcValue, UdtData};
///
/// // Read the entire UDT array element
/// let udt_value = client.read_tag("gTestUDT_Array[0]").await?;
/// if let PlcValue::Udt(mut udt_data) = udt_value {
///     let udt_def = client.get_udt_definition("gTestUDT_Array").await?;
///     // Convert UdtDefinition to UserDefinedType
///     let mut user_def = rust_ethernet_ip::udt::UserDefinedType::new(udt_def.name.clone());
///     for member in &udt_def.members {
///         user_def.add_member(member.clone());
///     }
///     let mut members = udt_data.parse(&user_def)?;
///     
///     // Modify the member
///     members.insert("Member1_DINT".to_string(), PlcValue::Dint(100));
///     
///     // Write the entire UDT array element back
///     let modified_udt = UdtData::from_hash_map(&members, &user_def, udt_data.symbol_id)?;
///     client.write_tag("gTestUDT_Array[0]", PlcValue::Udt(modified_udt)).await?;
/// }
/// # Ok(())
/// # }
/// ```
///
/// # Error Handling
///
/// All operations return `Result<T, EtherNetIpError>`. Common errors include:
///
/// ```rust,no_run
/// use rust_ethernet_ip::{EipClient, EtherNetIpError};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
///     let mut client = EipClient::connect("192.168.1.100:44818").await?;
///     match client.read_tag("Tag1").await {
///         Ok(value) => println!("Tag value: {:?}", value),
///         Err(EtherNetIpError::Protocol(_)) => println!("Tag does not exist"),
///         Err(EtherNetIpError::Connection(_)) => println!("Lost connection to PLC"),
///         Err(EtherNetIpError::Timeout(_)) => println!("Operation timed out"),
///         Err(e) => println!("Other error: {}", e),
///     }
///     Ok(())
/// }
/// ```
///
/// # Examples
///
/// Basic usage:
/// ```rust,no_run
/// use rust_ethernet_ip::{EipClient, PlcValue};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
///     let mut client = EipClient::connect("192.168.1.100:44818").await?;
///
///     // Read a boolean tag
///     let motor_running = client.read_tag("MotorRunning").await?;
///
///     // Write an integer tag
///     client.write_tag("SetPoint", PlcValue::Dint(1500)).await?;
///
///     // Read multiple tags in sequence
///     let tag1 = client.read_tag("Tag1").await?;
///     let tag2 = client.read_tag("Tag2").await?;
///     let tag3 = client.read_tag("Tag3").await?;
///     Ok(())
/// }
/// ```
///
/// Advanced usage with error recovery:
/// ```rust
/// use rust_ethernet_ip::{EipClient, PlcValue, EtherNetIpError};
/// use tokio::time::Duration;
///
/// async fn read_with_retry(client: &mut EipClient, tag: &str, retries: u32) -> Result<PlcValue, EtherNetIpError> {
///     for attempt in 0..retries {
///         match client.read_tag(tag).await {
///             Ok(value) => return Ok(value),
///             Err(EtherNetIpError::Connection(_)) => {
///                 if attempt < retries - 1 {
///                     tokio::time::sleep(Duration::from_secs(1)).await;
///                     continue;
///                 }
///                 return Err(EtherNetIpError::Protocol("Max retries exceeded".to_string()));
///             }
///             Err(e) => return Err(e),
///         }
///     }
///     Err(EtherNetIpError::Protocol("Max retries exceeded".to_string()))
/// }
/// ```
#[derive(Clone)]
pub struct EipClient {
    /// Stream for network communication (supports any AsyncRead + AsyncWrite + Unpin stream)
    stream: Arc<Mutex<Box<dyn EtherNetIpStream>>>,
    /// Session handle for the connection
    session_handle: u32,
    /// Connection ID for the session
    _connection_id: u32,
    /// Tag manager for handling tag operations
    tag_manager: Arc<Mutex<TagManager>>,
    /// UDT manager for handling UDT operations
    udt_manager: Arc<Mutex<UdtManager>>,
    /// Route path for PLC communication
    route_path: Option<RoutePath>,
    /// Whether the client is connected
    _connected: Arc<AtomicBool>,
    /// Maximum packet size for communication
    max_packet_size: u32,
    /// Last activity timestamp
    last_activity: Arc<Mutex<Instant>>,
    /// Session timeout duration
    _session_timeout: Duration,
    /// Configuration for batch operations
    batch_config: BatchConfig,
    /// Connected session management for Class 3 operations
    connected_sessions: Arc<Mutex<HashMap<String, ConnectedSession>>>,
    /// Connection sequence counter
    connection_sequence: Arc<Mutex<u32>>,
    /// Active tag subscriptions
    subscriptions: Arc<Mutex<Vec<TagSubscription>>>,
    /// Registered tag-group polling definitions
    tag_groups: Arc<Mutex<HashMap<String, TagGroupConfig>>>,
}

impl std::fmt::Debug for EipClient {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EipClient")
            .field("session_handle", &self.session_handle)
            .field("route_path", &self.route_path)
            .field("max_packet_size", &self.max_packet_size)
            .field("_session_timeout", &self._session_timeout)
            .field("batch_config", &self.batch_config)
            .field("stream", &"<stream>")
            .field("tag_manager", &"<tag_manager>")
            .field("udt_manager", &"<udt_manager>")
            .field("connected_sessions", &"<connected_sessions>")
            .field("subscriptions", &"<subscriptions>")
            .field("tag_groups", &"<tag_groups>")
            .finish()
    }
}

impl EipClient {
    /// Internal constructor that initializes an EipClient from any stream
    /// that implements AsyncRead + AsyncWrite + Unpin + Send
    async fn from_stream<S>(stream: S) -> Result<Self>
    where
        S: EtherNetIpStream + 'static,
    {
        let mut client = Self {
            stream: Arc::new(Mutex::new(Box::new(stream))),
            session_handle: 0,
            _connection_id: 0,
            tag_manager: Arc::new(Mutex::new(TagManager::new())),
            udt_manager: Arc::new(Mutex::new(UdtManager::new())),
            route_path: None,
            _connected: Arc::new(AtomicBool::new(false)),
            max_packet_size: 4000,
            last_activity: Arc::new(Mutex::new(Instant::now())),
            _session_timeout: Duration::from_secs(120),
            batch_config: BatchConfig::default(),
            connected_sessions: Arc::new(Mutex::new(HashMap::new())),
            connection_sequence: Arc::new(Mutex::new(1)),
            subscriptions: Arc::new(Mutex::new(Vec::new())),
            tag_groups: Arc::new(Mutex::new(HashMap::new())),
        };
        client.register_session().await?;
        client.negotiate_packet_size().await?;
        Ok(client)
    }

    pub async fn new(addr: &str) -> Result<Self> {
        let addr = addr
            .parse::<SocketAddr>()
            .map_err(|e| EtherNetIpError::Protocol(format!("Invalid address format: {e}")))?;
        let stream = TcpStream::connect(addr).await?;
        Self::from_stream(stream).await
    }

    /// Public async connect function for `EipClient`
    pub async fn connect(addr: &str) -> Result<Self> {
        Self::new(addr).await
    }

    /// Registers an EtherNet/IP session with the PLC
    ///
    /// This is an internal function that implements the EtherNet/IP session
    /// registration protocol. It sends a Register Session command and
    /// processes the response to extract the session handle.
    ///
    /// # Protocol Details
    ///
    /// The Register Session command consists of:
    /// - EtherNet/IP Encapsulation Header (24 bytes)
    /// - Registration Data (4 bytes: protocol version + options)
    ///
    /// The PLC responds with:
    /// - Same header format with assigned session handle
    /// - Status code indicating success/failure
    ///
    /// # Errors
    ///
    /// - Network timeout or disconnection
    /// - Invalid response format
    /// - PLC rejection (status code non-zero)
    async fn register_session(&mut self) -> crate::error::Result<()> {
        tracing::debug!("Starting session registration...");
        let packet: [u8; 28] = [
            0x65, 0x00, // Command: Register Session (0x0065)
            0x04, 0x00, // Length: 4 bytes
            0x00, 0x00, 0x00, 0x00, // Session Handle: 0 (will be assigned)
            0x00, 0x00, 0x00, 0x00, // Status: 0
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Sender Context (8 bytes)
            0x00, 0x00, 0x00, 0x00, // Options: 0
            0x01, 0x00, // Protocol Version: 1
            0x00, 0x00, // Option Flags: 0
        ];

        tracing::trace!("Sending Register Session packet: {:02X?}", packet);
        self.stream
            .lock()
            .await
            .write_all(&packet)
            .await
            .map_err(|e| {
                tracing::error!("Failed to send Register Session packet: {}", e);
                EtherNetIpError::Io(e)
            })?;

        let mut buf = [0u8; 1024];
        tracing::debug!("Waiting for Register Session response...");
        let n = match timeout(
            Duration::from_secs(5),
            self.stream.lock().await.read(&mut buf),
        )
        .await
        {
            Ok(Ok(n)) => {
                tracing::trace!("Received {} bytes in response", n);
                n
            }
            Ok(Err(e)) => {
                tracing::error!("Error reading response: {}", e);
                return Err(EtherNetIpError::Io(e));
            }
            Err(_) => {
                tracing::warn!("Timeout waiting for response");
                return Err(EtherNetIpError::Timeout(Duration::from_secs(5)));
            }
        };

        if n < 28 {
            tracing::error!("Response too short: {} bytes (expected 28)", n);
            return Err(EtherNetIpError::Protocol("Response too short".to_string()));
        }

        // Extract session handle from response
        self.session_handle = u32::from_le_bytes([buf[4], buf[5], buf[6], buf[7]]);
        tracing::debug!("Session handle: 0x{:08X}", self.session_handle);

        // Check status
        let status = u32::from_le_bytes([buf[8], buf[9], buf[10], buf[11]]);
        tracing::trace!("Status code: 0x{:08X}", status);

        if status != 0 {
            tracing::error!("Session registration failed with status: 0x{:08X}", status);
            return Err(EtherNetIpError::Protocol(format!(
                "Session registration failed with status: 0x{status:08X}"
            )));
        }

        tracing::info!("Session registration successful");
        Ok(())
    }

    /// Sets the maximum packet size for communication
    pub fn set_max_packet_size(&mut self, size: u32) {
        self.max_packet_size = size.min(4000);
    }

    /// Discovers all tags in the PLC (including hierarchical UDT members)
    pub async fn discover_tags(&mut self) -> crate::error::Result<()> {
        let response = self
            .send_cip_request(&self.build_list_tags_request())
            .await?;

        // Extract CIP data from response and check for errors
        let cip_data = self.extract_cip_from_response(&response)?;

        // Check for CIP errors before parsing
        if let Err(e) = self.check_cip_error(&cip_data) {
            return Err(crate::error::EtherNetIpError::Protocol(format!(
                "Tag discovery failed: {}. Some PLCs may not support tag discovery. Try reading tags directly by name.",
                e
            )));
        }

        let tags = {
            let tag_manager = self.tag_manager.lock().await;
            tag_manager.parse_tag_list(&cip_data)?
        };

        tracing::debug!("Initial tag discovery found {} tags", tags.len());

        // Perform recursive drill-down discovery (similar to TypeScript implementation)
        let hierarchical_tags = {
            let tag_manager = self.tag_manager.lock().await;
            tag_manager.drill_down_tags(&tags).await?
        };

        tracing::debug!(
            "After drill-down: {} total tags discovered",
            hierarchical_tags.len()
        );

        {
            let tag_manager = self.tag_manager.lock().await;
            let mut cache = tag_manager.cache.write().unwrap();
            for (name, metadata) in hierarchical_tags {
                cache.insert(name, metadata);
            }
        }
        Ok(())
    }

    /// Discovers UDT members for a specific structure
    pub async fn discover_udt_members(
        &mut self,
        udt_name: &str,
    ) -> crate::error::Result<Vec<(String, TagMetadata)>> {
        // Build CIP request to get UDT definition
        let cip_request = {
            let tag_manager = self.tag_manager.lock().await;
            tag_manager.build_udt_definition_request(udt_name)?
        };

        // Send the request
        let response = self.send_cip_request(&cip_request).await?;

        // Parse the UDT definition from response
        let definition = {
            let tag_manager = self.tag_manager.lock().await;
            tag_manager.parse_udt_definition_response(&response, udt_name)?
        };

        // Cache the definition
        {
            let tag_manager = self.tag_manager.lock().await;
            let mut definitions = tag_manager.udt_definitions.write().unwrap();
            definitions.insert(udt_name.to_string(), definition.clone());
        }

        // Create member metadata
        let mut members = Vec::new();
        for member in &definition.members {
            let member_name = member.name.clone();
            let full_name = format!("{}.{}", udt_name, member_name);

            let metadata = TagMetadata {
                data_type: member.data_type,
                scope: TagScope::Controller,
                permissions: TagPermissions {
                    readable: true,
                    writable: true,
                },
                is_array: false,
                dimensions: Vec::new(),
                last_access: std::time::Instant::now(),
                size: member.size,
                array_info: None,
                last_updated: std::time::Instant::now(),
            };

            members.push((full_name, metadata));
        }

        Ok(members)
    }

    /// Gets cached UDT definition
    pub async fn get_udt_definition_cached(&self, udt_name: &str) -> Option<UdtDefinition> {
        let tag_manager = self.tag_manager.lock().await;
        tag_manager.get_udt_definition_cached(udt_name)
    }

    /// Lists all cached UDT definitions
    pub async fn list_udt_definitions(&self) -> Vec<String> {
        let tag_manager = self.tag_manager.lock().await;
        tag_manager.list_udt_definitions()
    }

    /// Discovers all tags with full attributes
    /// This method queries the PLC for all available tags and their detailed attributes
    pub async fn discover_tags_detailed(&mut self) -> crate::error::Result<Vec<TagAttributes>> {
        // Build CIP request for tag list with attributes
        let request = self.build_tag_list_request()?;
        let response = self.send_cip_request(&request).await?;

        // Extract CIP data from response and check for errors
        let cip_data = self.extract_cip_from_response(&response)?;

        // Check for CIP errors before parsing
        if let Err(e) = self.check_cip_error(&cip_data) {
            return Err(crate::error::EtherNetIpError::Protocol(format!(
                "Tag discovery failed: {}. Some PLCs may not support tag discovery. Try reading tags directly by name.",
                e
            )));
        }

        // Parse response with all attributes
        self.parse_tag_list_response(&cip_data)
    }

    /// Discovers program-scoped tags
    /// This method discovers tags within a specific program scope
    pub async fn discover_program_tags(
        &mut self,
        program_name: &str,
    ) -> crate::error::Result<Vec<TagAttributes>> {
        // Build CIP request for program-scoped tag list
        let request = self.build_program_tag_list_request(program_name)?;
        let response = self.send_cip_request(&request).await?;

        // Extract CIP data from response and check for errors
        let cip_data = self.extract_cip_from_response(&response)?;

        // Check for CIP errors before parsing
        if let Err(e) = self.check_cip_error(&cip_data) {
            return Err(crate::error::EtherNetIpError::Protocol(format!(
                "Program tag discovery failed for '{}': {}. Some PLCs may not support tag discovery. Try reading tags directly by name.",
                program_name, e
            )));
        }

        // Parse response
        self.parse_tag_list_response(&cip_data)
    }

    /// Lists all cached tag attributes
    pub async fn list_cached_tag_attributes(&self) -> Vec<String> {
        self.udt_manager.lock().await.list_tag_attributes()
    }

    /// Clears all caches (UDT definitions, templates, tag attributes)
    pub async fn clear_caches(&mut self) {
        self.udt_manager.lock().await.clear_cache();
    }

    /// Creates a new client with a specific route path
    pub async fn with_route_path(addr: &str, route: RoutePath) -> crate::error::Result<Self> {
        let mut client = Self::new(addr).await?;
        client.set_route_path(route);
        Ok(client)
    }

    /// Connect to a PLC using a custom stream
    ///
    /// This method allows you to provide your own stream implementation, enabling:
    /// - Wrapping streams for metrics/observability (bytes in/out)
    /// - Applying custom socket options (keepalive, timeouts, bind local address)
    /// - Reusing pre-established tunnels/connections
    /// - Using in-memory streams for deterministic testing
    ///
    /// # Arguments
    ///
    /// * `stream` - Any stream that implements `AsyncRead + AsyncWrite + Unpin + Send`
    ///
    /// # Example
    ///
    /// ```no_run
    /// use rust_ethernet_ip::EipClient;
    /// use std::net::SocketAddr;
    /// use tokio::net::TcpStream;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// // Create a custom stream with socket options
    /// let addr: SocketAddr = "192.168.1.100:44818".parse()?;
    /// let stream = TcpStream::connect(addr).await?;
    /// stream.set_nodelay(true)?;
    ///
    /// // Connect using the custom stream
    /// let client = EipClient::connect_with_stream(stream, None).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn connect_with_stream<S>(stream: S, route: Option<RoutePath>) -> Result<Self>
    where
        S: EtherNetIpStream + 'static,
    {
        let mut client = Self::from_stream(stream).await?;
        if let Some(route) = route {
            client.set_route_path(route);
        }
        Ok(client)
    }

    /// Sets the route path for the client
    pub fn set_route_path(&mut self, route: RoutePath) {
        self.route_path = Some(route);
    }

    /// Gets the current route path
    pub fn get_route_path(&self) -> Option<&RoutePath> {
        self.route_path.as_ref()
    }

    /// Removes the route path (uses direct connection)
    pub fn clear_route_path(&mut self) {
        self.route_path = None;
    }

    /// Gets metadata for a tag
    pub async fn get_tag_metadata(&self, tag_name: &str) -> Option<TagMetadata> {
        let tag_manager = self.tag_manager.lock().await;
        let cache = tag_manager.cache.read().unwrap();
        let result = cache.get(tag_name).cloned();
        result
    }

    /// Reads a tag value from the PLC
    ///
    /// This function performs a CIP read request for the specified tag.
    /// The tag's data type is automatically determined from the PLC's response.
    ///
    /// **v0.6.0**: For UDT tags, this returns `PlcValue::Udt(UdtData)` with `symbol_id`
    /// and raw bytes. Use `UdtData::parse()` with a UDT definition to access members.
    ///
    /// # Arguments
    ///
    /// * `tag_name` - The name of the tag to read
    ///
    /// # Returns
    ///
    /// The tag's value as a `PlcValue` enum. For UDTs, this is `PlcValue::Udt(UdtData)`.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use rust_ethernet_ip::{EipClient, PlcValue};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    ///     let mut client = EipClient::connect("192.168.1.100:44818").await?;
    ///
    ///     // Read different data types
    ///     let bool_val = client.read_tag("MotorRunning").await?;
    ///     let int_val = client.read_tag("Counter").await?;
    ///     let real_val = client.read_tag("Temperature").await?;
    ///
    ///     // Read a UDT (v0.6.0: returns UdtData)
    ///     let udt_val = client.read_tag("MyUDT").await?;
    ///     if let PlcValue::Udt(udt_data) = udt_val {
    ///         let udt_def = client.get_udt_definition("MyUDT").await?;
    ///         // Convert UdtDefinition to UserDefinedType
    ///         let mut user_def = rust_ethernet_ip::udt::UserDefinedType::new(udt_def.name.clone());
    ///         for member in &udt_def.members {
    ///             user_def.add_member(member.clone());
    ///         }
    ///         let members = udt_data.parse(&user_def)?;
    ///         println!("UDT has {} members", members.len());
    ///     }
    ///
    ///     // Handle the result
    ///     match bool_val {
    ///         PlcValue::Bool(true) => println!("Motor is running"),
    ///         PlcValue::Bool(false) => println!("Motor is stopped"),
    ///         _ => println!("Unexpected data type"),
    ///     }
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # Performance
    ///
    /// - Latency: 1-5ms typical
    /// - Throughput: 1,500+ ops/sec
    /// - Network: 1 request/response cycle
    ///
    /// # Error Handling
    ///
    /// Common errors:
    /// - `Protocol`: Tag doesn't exist or invalid format
    /// - `Connection`: Lost connection to PLC
    /// - `Timeout`: Operation timed out
    pub async fn read_tag(&mut self, tag_name: &str) -> crate::error::Result<PlcValue> {
        self.validate_session().await?;

        // Check if this is a simple array element access (e.g., "ArrayName[0]")
        // BUT NOT if it has member access after (e.g., "ArrayName[0].Member")
        // Complex paths like "gTestUDT_Array[0].Member1_DINT" should use TagPath::parse()
        if let Some((base_name, index)) = self.parse_array_element_access(tag_name) {
            // Only use workaround if there's no member access after the array brackets
            // Find the FIRST [ and ] pair to check for member access after it
            if let Some(bracket_start) = tag_name.find('[') {
                if let Some(bracket_end_rel) = tag_name[bracket_start..].find(']') {
                    let bracket_end_abs = bracket_start + bracket_end_rel;
                    let after_bracket = &tag_name[bracket_end_abs + 1..];
                    tracing::debug!(
                        "Array element detected for '{}': base='{}', index={}, after_bracket='{}'",
                        tag_name,
                        base_name,
                        index,
                        after_bracket
                    );
                    // If there's a dot after the bracket, it's a member access - use TagPath::parse() instead
                    if !after_bracket.starts_with('.') {
                        tracing::debug!(
                            "Detected simple array element access: {}[{}], using workaround",
                            base_name,
                            index
                        );
                        return self.read_array_element_workaround(&base_name, index).await;
                    } else {
                        tracing::debug!(
                            "Array element '{}[{}]' has member access after bracket ('{}'), using TagPath::parse()",
                            base_name,
                            index,
                            after_bracket
                        );
                    }
                }
            }
        }

        // For complex paths (with member access, nested arrays, etc.), use TagPath::parse()
        // This handles paths like "gTestUDT_Array[0].Member1_DINT" correctly
        // Standard tag reading uses build_read_request which uses TagPath::parse()
        let response = self
            .send_cip_request(&self.build_read_request(tag_name))
            .await?;
        let cip_data = self.extract_cip_from_response(&response)?;
        self.parse_cip_response(&cip_data)
    }

    /// Reads a single bit from a tag (e.g. a DINT used as a status word).
    ///
    /// Equivalent to `read_tag(&format!("{}.{}", tag_base, bit_index))` for bit paths.
    /// `bit_index` must be in 0..32 (Allen-Bradley DINT bits).
    ///
    /// # Example
    ///
    /// ```ignore
    /// let bit_5 = client.read_bit("StatusWord", 5).await?;
    /// ```
    pub async fn read_bit(&mut self, tag_base: &str, bit_index: u8) -> crate::error::Result<bool> {
        if bit_index >= 32 {
            return Err(crate::error::EtherNetIpError::Protocol(
                "bit_index must be 0..32 for DINT bit access".to_string(),
            ));
        }
        let path = format!("{}.{}", tag_base, bit_index);
        match self.read_tag(&path).await? {
            PlcValue::Bool(b) => Ok(b),
            PlcValue::Dint(n) => {
                // Some PLCs/simulators return the full DINT for bit paths; extract the bit
                Ok((n >> bit_index) & 1 != 0)
            }
            other => Err(crate::error::EtherNetIpError::DataTypeMismatch {
                expected: "BOOL or DINT".to_string(),
                actual: format!("{:?}", other),
            }),
        }
    }

    /// Writes a single bit to a tag (e.g. a DINT used as a control word).
    ///
    /// Equivalent to `write_tag(&format!("{}.{}", tag_base, bit_index), PlcValue::Bool(value))`.
    /// `bit_index` must be in 0..32.
    ///
    /// # Example
    ///
    /// ```ignore
    /// client.write_bit("ControlWord", 3, true).await?;
    /// ```
    pub async fn write_bit(
        &mut self,
        tag_base: &str,
        bit_index: u8,
        value: bool,
    ) -> crate::error::Result<()> {
        if bit_index >= 32 {
            return Err(crate::error::EtherNetIpError::Protocol(
                "bit_index must be 0..32 for DINT bit access".to_string(),
            ));
        }
        let path = format!("{}.{}", tag_base, bit_index);
        self.write_tag(&path, PlcValue::Bool(value)).await
    }

    /// Parses array element access syntax (e.g., "ArrayName[0]") and returns (base_name, index)
    fn parse_array_element_access(&self, tag_name: &str) -> Option<(String, u32)> {
        // Look for array bracket notation
        if let Some(bracket_pos) = tag_name.rfind('[') {
            if let Some(close_bracket_pos) = tag_name.rfind(']') {
                if close_bracket_pos > bracket_pos {
                    let base_name = tag_name[..bracket_pos].to_string();
                    let index_str = &tag_name[bracket_pos + 1..close_bracket_pos];
                    if let Ok(index) = index_str.parse::<u32>() {
                        // Make sure there are no more brackets after this (multi-dimensional arrays not supported yet)
                        if !tag_name[..bracket_pos].contains('[') {
                            return Some((base_name, index));
                        }
                    }
                }
            }
        }
        None
    }

    /// Reads a single array element using proper CIP element addressing
    ///
    /// This method uses element addressing (0x28/0x29/0x2A segments) in the Request Path
    /// to read directly from the specified array index, eliminating the need to read
    /// the entire array.
    ///
    /// Reference: 1756-PM020, Pages 603-611, 815-837 (Array Element Access Examples)
    ///
    /// # Arguments
    ///
    /// * `base_array_name` - Base name of the array (e.g., "MyArray" for "MyArray[5]")
    /// * `index` - Element index to read (0-based)
    async fn read_array_element_workaround(
        &mut self,
        base_array_name: &str,
        index: u32,
    ) -> crate::error::Result<PlcValue> {
        tracing::debug!(
            "Reading array element '{}[{}]' using element addressing",
            base_array_name,
            index
        );

        // First, detect if it's a BOOL array by reading with count=1 to check data type
        let test_response = self
            .send_cip_request(&self.build_read_request_with_count(base_array_name, 1))
            .await?;
        let test_cip_data = self.extract_cip_from_response(&test_response)?;

        // Check for errors in test read
        self.check_cip_error(&test_cip_data)?;

        // Check if it's a BOOL array (data type 0x00D3 = DWORD)
        if test_cip_data.len() >= 6 {
            let test_data_type = u16::from_le_bytes([test_cip_data[4], test_cip_data[5]]);
            if test_data_type == 0x00D3 {
                // BOOL array - use special workaround to extract the bit
                return self
                    .read_bool_array_element_workaround(base_array_name, index)
                    .await;
            }
        }

        // Use element addressing to read directly from the specified index
        // Reference: 1756-PM020, Pages 815-837 (Reading Array Element - Full Message)
        let request = self.build_read_array_request(base_array_name, index, 1);

        let response = self.send_cip_request(&request).await?;
        let cip_data = self.extract_cip_from_response(&response)?;

        // Check for errors (including extended errors)
        self.check_cip_error(&cip_data)?;

        // Parse response - should be consistent format now
        // Reference: 1756-PM020, Page 828-837 (Response format)
        self.parse_cip_response(&cip_data)
    }

    /// Special workaround for BOOL arrays: reads DWORD and extracts the specific bit
    ///
    /// Reference: 1756-PM020, Page 797-811 (BOOL Array Access)
    async fn read_bool_array_element_workaround(
        &mut self,
        base_array_name: &str,
        index: u32,
    ) -> crate::error::Result<PlcValue> {
        tracing::debug!(
            "BOOL array detected - reading DWORD and extracting bit [{}]",
            index
        );

        // Read just 1 element (the DWORD containing 32 BOOLs)
        // Reference: 1756-PM020, Page 797-811
        let response = self
            .send_cip_request(&self.build_read_request_with_count(base_array_name, 1))
            .await?;
        let cip_data = self.extract_cip_from_response(&response)?;

        // Parse the response
        if cip_data.len() < 6 {
            return Err(EtherNetIpError::Protocol(
                "BOOL array response too short".to_string(),
            ));
        }

        // Check for errors (including extended errors)
        self.check_cip_error(&cip_data)?;

        let service_reply = cip_data[0];
        if service_reply != 0xCC {
            return Err(EtherNetIpError::Protocol(format!(
                "Unexpected service reply: 0x{service_reply:02X}"
            )));
        }

        let data_type = u16::from_le_bytes([cip_data[4], cip_data[5]]);

        // Check response format - might have element count or just data
        // Reference: 1756-PM020, Page 828-837 (Response format)
        let value_data = if cip_data.len() >= 8 && data_type == 0x00D3 {
            // Check if there's an element count field (bytes 6-7)
            // For BOOL arrays with count=1, we should get just the DWORD data
            if cip_data.len() >= 12 {
                // Has element count field
                &cip_data[8..]
            } else if cip_data.len() >= 10 {
                // No element count, data starts at byte 6
                &cip_data[6..]
            } else {
                return Err(EtherNetIpError::Protocol(
                    "BOOL array response too short for data".to_string(),
                ));
            }
        } else {
            // Standard format with element count
            if cip_data.len() < 8 {
                return Err(EtherNetIpError::Protocol(
                    "BOOL array response too short".to_string(),
                ));
            }
            &cip_data[8..]
        };

        // For BOOL arrays, the data is a DWORD (4 bytes) containing 32 BOOLs
        if value_data.len() < 4 {
            return Err(EtherNetIpError::Protocol(format!(
                "BOOL array data too short: need 4 bytes (DWORD), got {} bytes",
                value_data.len()
            )));
        }

        let dword_value =
            u32::from_le_bytes([value_data[0], value_data[1], value_data[2], value_data[3]]);

        // Extract the specific bit
        // Each DWORD contains 32 BOOLs (bits 0-31)
        let bit_index = (index % 32) as u8;
        let bool_value = (dword_value >> bit_index) & 1 != 0;

        Ok(PlcValue::Bool(bool_value))
    }

    /// Helper function to read large arrays in chunks to avoid PLC response size limits
    ///
    /// This method uses element addressing to read specific ranges of array elements,
    /// allowing efficient reading of large arrays without reading from element 0 each time.
    ///
    /// Reference: 1756-PM020, Pages 276-315 (Read Tag Fragmented Service), 840-851 (Reading Multiple Array Elements)
    async fn read_array_in_chunks(
        &mut self,
        base_array_name: &str,
        data_type: u16,
        start_index: u32,
        target_element_count: u32,
    ) -> crate::error::Result<Vec<u8>> {
        // Determine element size and safe chunk size
        let element_size = match data_type {
            0x00C1 => 1, // BOOL
            0x00C2 => 1, // SINT
            0x00C3 => 2, // INT
            0x00C4 => 4, // DINT
            0x00C5 => 8, // LINT
            0x00C6 => 1, // USINT
            0x00C7 => 2, // UINT
            0x00C8 => 4, // UDINT
            0x00C9 => 8, // ULINT
            0x00CA => 4, // REAL
            0x00CB => 8, // LREAL
            _ => {
                return Err(EtherNetIpError::Protocol(format!(
                    "Unsupported array data type for chunked reading: 0x{:04X}",
                    data_type
                )));
            }
        };

        // Read in chunks - use 8 elements per chunk for 4-byte types to stay under 38-byte limit
        // For smaller types, we can read more elements per chunk
        let elements_per_chunk = match element_size {
            1 => 30, // 1-byte types: 30 elements = 30 bytes + 8 header = 38 bytes
            2 => 15, // 2-byte types: 15 elements = 30 bytes + 8 header = 38 bytes
            4 => 8, // 4-byte types: 8 elements = 32 bytes + 8 header = 40 bytes (may truncate to 38)
            8 => 4, // 8-byte types: 4 elements = 32 bytes + 8 header = 40 bytes
            _ => 8,
        };

        let end_index = start_index
            .checked_add(target_element_count)
            .ok_or_else(|| EtherNetIpError::Protocol("Array range overflow".to_string()))?;

        let mut all_data = Vec::new();
        let mut next_chunk_start = start_index;

        tracing::debug!(
            "Reading array '{}' in chunks: {} elements per chunk, target: {} elements",
            base_array_name,
            elements_per_chunk,
            target_element_count
        );

        while next_chunk_start < end_index {
            // Use element addressing to read specific range starting from next_chunk_start
            // Reference: 1756-PM020, Pages 840-851 (Reading Multiple Array Elements)
            let chunk_end = (next_chunk_start + elements_per_chunk as u32).min(end_index);
            let chunk_size = (chunk_end - next_chunk_start) as u16;

            tracing::trace!(
                "Reading chunk: elements {} to {} ({} elements) using element addressing",
                next_chunk_start,
                chunk_end - 1,
                chunk_size
            );

            // Use element addressing to read this specific range
            // Reference: 1756-PM020, Pages 840-851 (Reading Multiple Array Elements)
            let response = self
                .send_cip_request(&self.build_read_array_request(
                    base_array_name,
                    next_chunk_start,
                    chunk_size,
                ))
                .await?;
            let cip_data = self.extract_cip_from_response(&response)?;

            if cip_data.len() < 8 {
                // Response too short - might be an error or empty response
                // Check if it's a CIP error response
                if cip_data.len() >= 3 {
                    let general_status = cip_data[2];
                    if general_status != 0x00 {
                        let error_msg = self.get_cip_error_message(general_status);
                        return Err(EtherNetIpError::Protocol(format!(
                            "CIP Error {} when reading chunk (elements {} to {}): {}",
                            general_status,
                            next_chunk_start,
                            chunk_end - 1,
                            error_msg
                        )));
                    }
                }
                return Err(EtherNetIpError::Protocol(format!(
                    "Chunk response too short: got {} bytes, expected at least 8 (requested {} elements starting at {})",
                    cip_data.len(), chunk_size, next_chunk_start
                )));
            }

            // Check for CIP errors in the response
            if cip_data.len() >= 3 {
                let general_status = cip_data[2];
                if general_status != 0x00 {
                    let error_msg = self.get_cip_error_message(general_status);
                    return Err(EtherNetIpError::Protocol(format!(
                        "CIP Error {} when reading chunk (elements {} to {}): {}",
                        general_status,
                        next_chunk_start,
                        chunk_end - 1,
                        error_msg
                    )));
                }
            }

            // Check service reply
            if !cip_data.is_empty() && cip_data[0] != 0xCC {
                return Err(EtherNetIpError::Protocol(format!(
                    "Unexpected service reply in chunk: 0x{:02X} (expected 0xCC)",
                    cip_data[0]
                )));
            }

            if cip_data.len() < 6 {
                return Err(EtherNetIpError::Protocol(format!(
                    "Chunk response too short for data type: got {} bytes, expected at least 6",
                    cip_data.len()
                )));
            }

            let chunk_data_type = u16::from_le_bytes([cip_data[4], cip_data[5]]);
            if chunk_data_type != data_type {
                return Err(EtherNetIpError::Protocol(format!(
                    "Data type mismatch in chunk: expected 0x{:04X}, got 0x{:04X}",
                    data_type, chunk_data_type
                )));
            }

            // Parse response data - with element addressing, response contains the requested range
            // Reference: 1756-PM020, Page 828-837 (Response format)
            let value_data_start = if cip_data.len() >= 8 {
                // Standard format: [service][reserved][status][status_size][data_type(2)][element_count(2)][data...]
                8
            } else {
                6
            };

            let chunk_value_data = &cip_data[value_data_start..];
            let chunk_complete_bytes = (chunk_value_data.len() / element_size) * element_size;
            let chunk_data = &chunk_value_data[..chunk_complete_bytes];

            // With element addressing, the response directly contains the requested range
            // No need to extract a portion - use all the data we received
            if !chunk_data.is_empty() {
                all_data.extend_from_slice(chunk_data);
                let elements_received = chunk_data.len() / element_size;
                next_chunk_start += elements_received as u32;

                tracing::trace!(
                    "Chunk read: {} elements ({} bytes) starting at index {}, total so far: {} elements",
                    elements_received,
                    chunk_data.len(),
                    next_chunk_start - elements_received as u32,
                    all_data.len() / element_size
                );

                // Continue reading if we haven't reached our target yet
                if next_chunk_start >= end_index {
                    tracing::trace!(
                        "Reached target element count ({}), stopping chunked read",
                        target_element_count
                    );
                    break;
                }
            } else {
                // No data received, we're done
                break;
            }
        }

        let final_element_count = all_data.len() / element_size;
        tracing::debug!(
            "Chunked read complete: {} total elements ({} bytes), target was {} elements",
            final_element_count,
            all_data.len(),
            target_element_count
        );

        if final_element_count < target_element_count as usize {
            return Err(EtherNetIpError::Protocol(format!(
                "Incomplete array read: requested {} elements, received {}",
                target_element_count, final_element_count
            )));
        }

        Ok(all_data)
    }

    fn array_element_size(data_type: u16) -> Option<usize> {
        match data_type {
            0x00C1 => Some(1), // BOOL
            0x00C2 => Some(1), // SINT
            0x00C3 => Some(2), // INT
            0x00C4 => Some(4), // DINT
            0x00C5 => Some(8), // LINT
            0x00C6 => Some(1), // USINT
            0x00C7 => Some(2), // UINT
            0x00C8 => Some(4), // UDINT
            0x00C9 => Some(8), // ULINT
            0x00CA => Some(4), // REAL
            0x00CB => Some(8), // LREAL
            _ => None,
        }
    }

    fn decode_array_bytes(
        &self,
        data_type: u16,
        bytes: &[u8],
    ) -> crate::error::Result<Vec<PlcValue>> {
        let Some(element_size) = Self::array_element_size(data_type) else {
            return Err(EtherNetIpError::Protocol(format!(
                "Unsupported data type for array decoding: 0x{:04X}",
                data_type
            )));
        };

        if bytes.len() % element_size != 0 {
            return Err(EtherNetIpError::Protocol(format!(
                "Array payload length {} is not aligned to element size {}",
                bytes.len(),
                element_size
            )));
        }

        let mut values = Vec::with_capacity(bytes.len() / element_size);
        for chunk in bytes.chunks_exact(element_size) {
            let value = match data_type {
                0x00C1 => PlcValue::Bool(chunk[0] != 0),
                0x00C2 => PlcValue::Sint(chunk[0] as i8),
                0x00C3 => PlcValue::Int(i16::from_le_bytes([chunk[0], chunk[1]])),
                0x00C4 => {
                    PlcValue::Dint(i32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
                }
                0x00C5 => PlcValue::Lint(i64::from_le_bytes([
                    chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
                ])),
                0x00C6 => PlcValue::Usint(chunk[0]),
                0x00C7 => PlcValue::Uint(u16::from_le_bytes([chunk[0], chunk[1]])),
                0x00C8 => {
                    PlcValue::Udint(u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
                }
                0x00C9 => PlcValue::Ulint(u64::from_le_bytes([
                    chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
                ])),
                0x00CA => {
                    PlcValue::Real(f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]))
                }
                0x00CB => PlcValue::Lreal(f64::from_le_bytes([
                    chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
                ])),
                _ => unreachable!("validated by array_element_size"),
            };
            values.push(value);
        }

        Ok(values)
    }

    /// Read a range of elements from a basic-type PLC array.
    ///
    /// This method reads arrays in chunks under the hood to avoid PLC packet-size limits.
    /// It supports basic CIP scalar types:
    /// BOOL, SINT, INT, DINT, LINT, USINT, UINT, UDINT, ULINT, REAL, LREAL.
    ///
    /// # Arguments
    ///
    /// * `base_array_name` - Base array tag name without index (e.g., `"MyDintArray"`)
    /// * `start_index` - Starting element index
    /// * `element_count` - Number of elements to read
    ///
    /// # Returns
    ///
    /// A `Vec<PlcValue>` with one element per requested array entry.
    pub async fn read_array_range(
        &mut self,
        base_array_name: &str,
        start_index: u32,
        element_count: u32,
    ) -> crate::error::Result<Vec<PlcValue>> {
        if element_count == 0 {
            return Ok(Vec::new());
        }

        let probe_response = self
            .send_cip_request(&self.build_read_array_request(base_array_name, start_index, 1))
            .await?;
        let probe_cip = self.extract_cip_from_response(&probe_response)?;
        self.check_cip_error(&probe_cip)?;

        if probe_cip.len() < 6 {
            return Err(EtherNetIpError::Protocol(
                "Array probe response too short".to_string(),
            ));
        }

        let data_type = u16::from_le_bytes([probe_cip[4], probe_cip[5]]);
        let raw = self
            .read_array_in_chunks(base_array_name, data_type, start_index, element_count)
            .await?;
        let values = self.decode_array_bytes(data_type, &raw)?;

        if values.len() != element_count as usize {
            return Err(EtherNetIpError::Protocol(format!(
                "Array read count mismatch: requested {}, got {}",
                element_count,
                values.len()
            )));
        }

        Ok(values)
    }

    /// Writes to a single array element using direct element addressing
    ///
    /// This method uses element addressing (0x28/0x29/0x2A segments) in the Request Path
    /// to write directly to the specified array index, eliminating the need to read
    /// the entire array.
    ///
    /// Reference: 1756-PM020, Pages 855-867 (Writing to Array Element)
    ///
    /// # Arguments
    ///
    /// * `base_array_name` - Base name of the array (e.g., "MyArray" for "MyArray[10]")
    /// * `index` - Element index to write (0-based)
    /// * `value` - The value to write
    async fn write_array_element_workaround(
        &mut self,
        base_array_name: &str,
        index: u32,
        value: PlcValue,
    ) -> crate::error::Result<()> {
        tracing::debug!(
            "Writing to array element '{}[{}]' using element addressing",
            base_array_name,
            index
        );

        // First, detect if it's a BOOL array by reading with count=1
        let test_response = self
            .send_cip_request(&self.build_read_request_with_count(base_array_name, 1))
            .await?;
        let test_cip_data = self.extract_cip_from_response(&test_response)?;

        // Check for errors in the test read response
        if test_cip_data.len() < 3 {
            return Err(EtherNetIpError::Protocol(
                "Test read response too short".to_string(),
            ));
        }

        // Check for errors in test read (including extended errors)
        if let Err(e) = self.check_cip_error(&test_cip_data) {
            return Err(EtherNetIpError::Protocol(format!(
                "Cannot write to array element: Test read failed: {}",
                e
            )));
        }

        // Check if we have enough data to determine the data type
        if test_cip_data.len() < 6 {
            return Err(EtherNetIpError::Protocol(
                "Test read response too short to determine data type".to_string(),
            ));
        }

        let test_data_type = u16::from_le_bytes([test_cip_data[4], test_cip_data[5]]);

        // If it's a BOOL array (0x00D3 = DWORD), handle it specially
        if test_data_type == 0x00D3 {
            return self
                .write_bool_array_element_workaround(base_array_name, index, value)
                .await;
        }

        // Get the data type and convert value to bytes
        let data_type = test_data_type;
        let value_bytes = value.to_bytes();

        // Use element addressing to write directly to the specified index
        // Reference: 1756-PM020, Pages 855-867
        let request = self.build_write_array_request_with_index(
            base_array_name,
            index,
            1, // Write 1 element
            data_type,
            &value_bytes,
        )?;

        let response = self.send_cip_request(&request).await?;
        let cip_data = self.extract_cip_from_response(&response)?;

        // Check for errors (including extended errors)
        self.check_cip_error(&cip_data)?;

        tracing::info!("Array element write completed successfully");
        Ok(())
    }

    /// Special workaround for BOOL arrays: reads DWORD, modifies bit, writes back.
    ///
    /// Note: This is a read-modify-write operation. Callers must ensure exclusive
    /// access to the client for the entire duration (the `&mut self` requirement
    /// provides this guarantee in safe Rust; FFI callers are protected by the global mutex).
    ///
    /// Reference: 1756-PM020, Page 797-811 (BOOL Array Access)
    async fn write_bool_array_element_workaround(
        &mut self,
        base_array_name: &str,
        index: u32,
        value: PlcValue,
    ) -> crate::error::Result<()> {
        tracing::debug!(
            "BOOL array element write - reading DWORD, modifying bit [{}], writing back",
            index
        );

        // Read the DWORD
        let response = self
            .send_cip_request(&self.build_read_request_with_count(base_array_name, 1))
            .await?;
        let cip_data = self.extract_cip_from_response(&response)?;

        // BOOL array response format: [0]=service, [1]=reserved, [2]=status, [3]=additional_status_size,
        // [4-5]=data_type, [6-9]=data (DWORD, 4 bytes)
        // Minimum size is 10 bytes (no element count field when count=1)
        if cip_data.len() < 10 {
            return Err(EtherNetIpError::Protocol(
                "BOOL array response too short".to_string(),
            ));
        }

        // Check for errors (including extended errors)
        self.check_cip_error(&cip_data)?;

        let service_reply = cip_data[0];
        if service_reply != 0xCC {
            return Err(EtherNetIpError::Protocol(format!(
                "Unexpected service reply: 0x{service_reply:02X}"
            )));
        }

        let data_type = u16::from_le_bytes([cip_data[4], cip_data[5]]);

        // Extract DWORD data (4 bytes)
        // For BOOL arrays with count=1, data starts at byte 6 (no element count field)
        let value_data = if cip_data.len() >= 10 {
            &cip_data[6..10]
        } else {
            return Err(EtherNetIpError::Protocol(
                "BOOL array data too short".to_string(),
            ));
        };

        // Get the boolean value
        let bool_value = match value {
            PlcValue::Bool(b) => b,
            _ => {
                return Err(EtherNetIpError::Protocol(
                    "Expected BOOL value for BOOL array element".to_string(),
                ))
            }
        };

        // Modify the DWORD
        let mut dword_value =
            u32::from_le_bytes([value_data[0], value_data[1], value_data[2], value_data[3]]);

        let bit_index = (index % 32) as u8;
        if bool_value {
            dword_value |= 1u32 << bit_index;
        } else {
            dword_value &= !(1u32 << bit_index);
        }

        tracing::trace!(
            "Modified BOOL[{}] in DWORD: 0x{:08X} -> 0x{:08X} (bit {} = {})",
            index,
            u32::from_le_bytes([value_data[0], value_data[1], value_data[2], value_data[3]]),
            dword_value,
            bit_index,
            bool_value
        );

        // Write the DWORD back
        let write_request = self.build_write_request_with_data(
            base_array_name,
            data_type,
            1,
            &dword_value.to_le_bytes(),
        )?;
        let write_response = self.send_cip_request(&write_request).await?;
        let write_cip_data = self.extract_cip_from_response(&write_response)?;

        // Check for errors (including extended errors)
        self.check_cip_error(&write_cip_data)?;

        tracing::info!("BOOL array element write completed successfully");
        Ok(())
    }

    /// Builds a write request for an entire array (legacy method - writes from element 0)
    ///
    /// Reference: 1756-PM020, Page 318-357 (Write Tag Service)
    #[allow(dead_code)]
    fn build_write_array_request(
        &self,
        tag_name: &str,
        data_type: u16,
        element_count: u16,
        data: &[u8],
    ) -> crate::error::Result<Vec<u8>> {
        let mut cip_request = Vec::new();

        // Service: Write Tag Service (0x4D)
        // Reference: 1756-PM020, Page 318
        cip_request.push(0x4D);

        // Build the path
        let path = self.build_tag_path(tag_name);
        cip_request.push((path.len() / 2) as u8);
        cip_request.extend_from_slice(&path);

        // Data type and element count
        // Reference: 1756-PM020, Page 335-337 (Request Data format)
        cip_request.extend_from_slice(&data_type.to_le_bytes());
        cip_request.extend_from_slice(&element_count.to_le_bytes());

        // Array data
        cip_request.extend_from_slice(data);

        Ok(cip_request)
    }

    /// Builds a CIP Write Tag Service request for array elements with element addressing
    ///
    /// This method uses proper CIP element addressing (0x28/0x29/0x2A segments) in the
    /// Request Path to write to specific array elements or ranges.
    ///
    /// Reference: 1756-PM020, Pages 603-611, 855-867 (Writing to Array Element)
    ///
    /// # Arguments
    ///
    /// * `base_array_name` - Base name of the array (e.g., "MyArray" for "MyArray[10]")
    /// * `start_index` - Starting element index (0-based)
    /// * `element_count` - Number of elements to write
    /// * `data_type` - CIP data type code (e.g., 0x00C4 for DINT)
    /// * `data` - Raw bytes of the data to write
    ///
    /// # Example
    ///
    /// Writing value 0x12345678 to element 10 of array "MyArray":
    /// ```
    /// # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// # let mut client = rust_ethernet_ip::EipClient::connect("192.168.1.100:44818").await?;
    /// let data = 0x12345678u32.to_le_bytes();
    /// let request = client.build_write_array_request_with_index(
    ///     "MyArray", 10, 1, 0x00C4, &data
    /// )?;
    /// # Ok(())
    /// # }
    /// ```
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn build_write_array_request_with_index(
        &self,
        base_array_name: &str,
        start_index: u32,
        element_count: u16,
        data_type: u16,
        data: &[u8],
    ) -> crate::error::Result<Vec<u8>> {
        let mut cip_request = Vec::new();

        // Service: Write Tag Service (0x4D)
        // Reference: 1756-PM020, Page 318
        cip_request.push(0x4D);

        // Build base tag path (symbolic segment)
        // Reference: 1756-PM020, Page 894-909
        let mut full_path = self.build_base_tag_path(base_array_name);

        // Add element addressing segment
        // Reference: 1756-PM020, Pages 603-611, 870-890
        full_path.extend_from_slice(&self.build_element_id_segment(start_index));

        // Ensure path is word-aligned
        if full_path.len() % 2 != 0 {
            full_path.push(0x00);
        }

        // Path size (in words)
        let path_size = (full_path.len() / 2) as u8;
        cip_request.push(path_size);
        cip_request.extend_from_slice(&full_path);

        // Request Data: Data type, element count, and data
        // Reference: 1756-PM020, Page 855-867 (Writing to Array Element - Full Message)
        cip_request.extend_from_slice(&data_type.to_le_bytes());
        cip_request.extend_from_slice(&element_count.to_le_bytes());
        cip_request.extend_from_slice(data);

        Ok(cip_request)
    }

    /// Builds a write request with raw data
    fn build_write_request_with_data(
        &self,
        tag_name: &str,
        data_type: u16,
        element_count: u16,
        data: &[u8],
    ) -> crate::error::Result<Vec<u8>> {
        let mut cip_request = Vec::new();

        // Service: Write Tag Service (0x4D)
        cip_request.push(0x4D);

        // Build the path
        let path = self.build_tag_path(tag_name);
        cip_request.push((path.len() / 2) as u8);
        cip_request.extend_from_slice(&path);

        // Data type and element count
        cip_request.extend_from_slice(&data_type.to_le_bytes());
        cip_request.extend_from_slice(&element_count.to_le_bytes());

        // Data
        cip_request.extend_from_slice(data);

        Ok(cip_request)
    }

    /// Reads a UDT with advanced chunked reading to handle large structures
    ///
    /// **v0.6.0**: Returns `PlcValue::Udt(UdtData)` with `symbol_id` and raw bytes.
    /// Use `UdtData::parse()` with a UDT definition to access individual members.
    ///
    /// This method uses multiple strategies to handle large UDTs that exceed
    /// the maximum packet size, including intelligent chunking and member discovery.
    ///
    /// # Arguments
    ///
    /// * `tag_name` - The name of the UDT tag to read
    ///
    /// # Returns
    ///
    /// `PlcValue::Udt(UdtData)` containing the symbol_id and raw data bytes
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// # let mut client = rust_ethernet_ip::EipClient::connect("192.168.1.100:44818").await?;
    /// let udt_value = client.read_udt_chunked("Part_Data").await?;
    /// if let rust_ethernet_ip::PlcValue::Udt(udt_data) = udt_value {
    ///     println!("UDT symbol_id: {}, data size: {} bytes", udt_data.symbol_id, udt_data.data.len());
    ///     // Parse members if needed
    ///     let udt_def = client.get_udt_definition("Part_Data").await?;
    ///     // Convert UdtDefinition to UserDefinedType
    ///     let mut user_def = rust_ethernet_ip::udt::UserDefinedType::new(udt_def.name.clone());
    ///     for member in &udt_def.members {
    ///         user_def.add_member(member.clone());
    ///     }
    ///     let members = udt_data.parse(&user_def)?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn read_udt_chunked(&mut self, tag_name: &str) -> crate::error::Result<PlcValue> {
        self.validate_session().await?;

        tracing::debug!("[CHUNKED] Starting advanced UDT reading for: {}", tag_name);

        // Strategy 1: Try normal read first
        match self.read_tag(tag_name).await {
            Ok(value) => {
                tracing::debug!("[CHUNKED] Normal read successful");
                return Ok(value);
            }
            Err(crate::error::EtherNetIpError::Protocol(msg))
                if msg.contains("Partial transfer") =>
            {
                tracing::debug!("[CHUNKED] Partial transfer detected, using advanced chunking");
            }
            Err(e) => {
                tracing::warn!("[CHUNKED] Normal read failed: {}", e);
                return Err(e);
            }
        }

        // Strategy 2: Advanced chunked reading with multiple approaches
        self.read_udt_advanced_chunked(tag_name).await
    }

    /// Advanced chunked UDT reading with multiple strategies
    async fn read_udt_advanced_chunked(
        &mut self,
        tag_name: &str,
    ) -> crate::error::Result<PlcValue> {
        tracing::debug!("[ADVANCED] Using multiple strategies for large UDT");

        // Strategy A: Try different chunk sizes
        let chunk_sizes = vec![512, 256, 128, 64, 32, 16, 8, 4];

        for chunk_size in chunk_sizes {
            tracing::trace!("[ADVANCED] Trying chunk size: {}", chunk_size);

            match self.read_udt_with_chunk_size(tag_name, chunk_size).await {
                Ok(udt_value) => {
                    tracing::debug!("[ADVANCED] Success with chunk size {}", chunk_size);
                    return Ok(udt_value);
                }
                Err(e) => {
                    tracing::trace!("[ADVANCED] Chunk size {} failed: {}", chunk_size, e);
                    continue;
                }
            }
        }

        // Strategy B: Try member-by-member discovery
        tracing::debug!("[ADVANCED] Trying member-by-member discovery");
        match self.read_udt_member_discovery(tag_name).await {
            Ok(udt_value) => {
                tracing::debug!("[ADVANCED] Member discovery successful");
                return Ok(udt_value);
            }
            Err(e) => {
                tracing::warn!("[ADVANCED] Member discovery failed: {}", e);
            }
        }

        // Strategy C: Try progressive reading
        tracing::debug!("[ADVANCED] Trying progressive reading");
        match self.read_udt_progressive(tag_name).await {
            Ok(udt_value) => {
                tracing::debug!("[ADVANCED] Progressive reading successful");
                return Ok(udt_value);
            }
            Err(e) => {
                tracing::warn!("[ADVANCED] Progressive reading failed: {}", e);
            }
        }

        // Strategy D: Fallback - try to get at least the symbol_id
        tracing::warn!("[ADVANCED] All strategies failed, using fallback");
        // Try to get tag attributes for symbol_id
        let symbol_id = self
            .get_tag_attributes(tag_name)
            .await
            .ok()
            .and_then(|attr| attr.template_instance_id)
            .unwrap_or(0) as i32;

        // Return empty UDT data with error indication
        Ok(PlcValue::Udt(UdtData {
            symbol_id,
            data: vec![], // Empty data indicates read failure
        }))
    }

    /// Try reading UDT with specific chunk size
    async fn read_udt_with_chunk_size(
        &mut self,
        tag_name: &str,
        mut chunk_size: usize,
    ) -> crate::error::Result<PlcValue> {
        let mut all_data = Vec::new();
        let mut offset = 0;
        let mut consecutive_failures = 0;
        const MAX_FAILURES: usize = 3;

        loop {
            match self
                .read_udt_chunk_advanced(tag_name, offset, chunk_size)
                .await
            {
                Ok(chunk_data) => {
                    if chunk_data.is_empty() {
                        break; // No more data
                    }

                    all_data.extend_from_slice(&chunk_data);
                    offset += chunk_data.len();
                    consecutive_failures = 0;

                    tracing::trace!(
                        "[CHUNK] Read {} bytes at offset {}, total: {}",
                        chunk_data.len(),
                        offset - chunk_data.len(),
                        all_data.len()
                    );

                    // If we got less data than requested, we might be done
                    if chunk_data.len() < chunk_size {
                        break;
                    }
                }
                Err(e) => {
                    consecutive_failures += 1;
                    tracing::warn!(
                        "[CHUNK] Chunk read failed (attempt {}): {}",
                        consecutive_failures,
                        e
                    );

                    if consecutive_failures >= MAX_FAILURES {
                        break;
                    }

                    // Try smaller chunk by reducing size and continuing
                    if chunk_size > 4 {
                        chunk_size /= 2;
                        continue;
                    }
                }
            }
        }

        if all_data.is_empty() {
            return Err(crate::error::EtherNetIpError::Protocol(
                "No data read from UDT".to_string(),
            ));
        }

        tracing::debug!("[CHUNK] Total data collected: {} bytes", all_data.len());

        // Get symbol_id from tag attributes
        let symbol_id = self
            .get_tag_attributes(tag_name)
            .await
            .ok()
            .and_then(|attr| attr.template_instance_id)
            .unwrap_or(0) as i32;

        // Return raw UDT data (generic approach - no parsing)
        Ok(PlcValue::Udt(UdtData {
            symbol_id,
            data: all_data,
        }))
    }

    /// Advanced chunk reading with better error handling
    async fn read_udt_chunk_advanced(
        &mut self,
        tag_name: &str,
        offset: usize,
        size: usize,
    ) -> crate::error::Result<Vec<u8>> {
        // Build a more sophisticated read request
        let mut request = Vec::new();

        // Service: Read Tag (0x4C)
        request.push(0x4C);

        // Use TagPath::parse() to correctly handle complex paths like Cell_NestData[90].PartData
        let tag_path = self.build_tag_path(tag_name);

        // Path size (in words)
        let path_size = (tag_path.len() / 2) as u8;
        request.push(path_size);

        // Path: use properly parsed tag path
        request.extend_from_slice(&tag_path);

        // For UDTs, we need to use a different approach than array indexing
        // Try to read as raw data with offset
        if offset > 0 {
            // Use element path for offset
            request.push(0x28); // Element symbol
            request.push(0x02); // 2 bytes for offset
            request.extend_from_slice(&(offset as u16).to_le_bytes());
        }

        // Element count
        request.push(0x28); // Element count symbol
        request.push(0x02); // 2 bytes for count
        request.extend_from_slice(&(size as u16).to_le_bytes());

        // Data type - try as raw bytes first
        request.push(0x00);
        request.push(0x01);

        // Send the request
        let response = self.send_cip_request(&request).await?;
        let cip_data = self.extract_cip_from_response(&response)?;

        // Parse the response
        if cip_data.len() < 2 {
            return Ok(Vec::new()); // No data
        }

        let _data_type = u16::from_le_bytes([cip_data[0], cip_data[1]]);
        let data = &cip_data[2..];

        Ok(data.to_vec())
    }

    /// Try to read UDT as raw data with symbol_id
    ///
    /// This is a generic approach that works for any UDT without requiring
    /// knowledge of member names. It reads the raw bytes and gets the
    /// symbol_id (template instance ID) from tag attributes.
    async fn read_udt_member_discovery(
        &mut self,
        tag_name: &str,
    ) -> crate::error::Result<PlcValue> {
        tracing::debug!("[DISCOVERY] Reading UDT as raw data for: {}", tag_name);

        // Get tag attributes to retrieve symbol_id (template_instance_id)
        let attributes = self.get_tag_attributes(tag_name).await?;

        let symbol_id = attributes.template_instance_id.ok_or_else(|| {
            crate::error::EtherNetIpError::Protocol(
                "UDT template instance ID not found in tag attributes".to_string(),
            )
        })?;

        // Read raw UDT data
        let raw_data = self.read_tag_raw(tag_name).await?;

        tracing::debug!(
            "[DISCOVERY] Read {} bytes of UDT data with symbol_id: {}",
            raw_data.len(),
            symbol_id
        );

        Ok(PlcValue::Udt(UdtData {
            symbol_id: symbol_id as i32,
            data: raw_data,
        }))
    }

    /// Progressive reading - try to read UDT in progressively smaller chunks
    async fn read_udt_progressive(&mut self, tag_name: &str) -> crate::error::Result<PlcValue> {
        tracing::debug!("[PROGRESSIVE] Starting progressive reading");

        // Start with a small chunk and gradually increase
        let mut chunk_size = 4;
        let mut all_data = Vec::new();
        let mut offset = 0;

        while chunk_size <= 512 {
            match self
                .read_udt_chunk_advanced(tag_name, offset, chunk_size)
                .await
            {
                Ok(chunk_data) => {
                    if chunk_data.is_empty() {
                        break;
                    }

                    all_data.extend_from_slice(&chunk_data);
                    offset += chunk_data.len();

                    tracing::trace!(
                        "[PROGRESSIVE] Read {} bytes with chunk size {}",
                        chunk_data.len(),
                        chunk_size
                    );

                    // If we got the full chunk, try a larger one next time
                    if chunk_data.len() == chunk_size {
                        chunk_size = (chunk_size * 2).min(512);
                    }
                }
                Err(_) => {
                    // Reduce chunk size and try again
                    chunk_size /= 2;
                    if chunk_size < 4 {
                        break;
                    }
                }
            }
        }

        if all_data.is_empty() {
            return Err(crate::error::EtherNetIpError::Protocol(
                "Progressive reading failed".to_string(),
            ));
        }

        tracing::debug!("[PROGRESSIVE] Collected {} bytes total", all_data.len());

        // Get symbol_id from tag attributes
        let symbol_id = self
            .get_tag_attributes(tag_name)
            .await
            .ok()
            .and_then(|attr| attr.template_instance_id)
            .unwrap_or(0) as i32;

        // Return raw UDT data (generic approach - no parsing)
        Ok(PlcValue::Udt(UdtData {
            symbol_id,
            data: all_data,
        }))
    }

    /// Reads a UDT in chunks to handle large structures
    #[allow(dead_code)]
    async fn read_udt_in_chunks(&mut self, tag_name: &str) -> crate::error::Result<PlcValue> {
        const MAX_CHUNK_SIZE: usize = 1000; // Conservative chunk size
        let mut all_data = Vec::new();
        let mut offset = 0;
        let mut chunk_size = MAX_CHUNK_SIZE;

        loop {
            // Try to read a chunk
            match self.read_udt_chunk(tag_name, offset, chunk_size).await {
                Ok(chunk_data) => {
                    all_data.extend_from_slice(&chunk_data);
                    offset += chunk_data.len();

                    // If we got less data than requested, we're done
                    if chunk_data.len() < chunk_size {
                        break;
                    }
                }
                Err(crate::error::EtherNetIpError::Protocol(msg))
                    if msg.contains("Partial transfer") =>
                {
                    // Reduce chunk size and try again
                    chunk_size /= 2;
                    if chunk_size < 100 {
                        return Err(crate::error::EtherNetIpError::Protocol(
                            "UDT too large even for smallest chunk size".to_string(),
                        ));
                    }
                    continue;
                }
                Err(e) => return Err(e),
            }
        }

        // Get symbol_id from tag attributes
        let symbol_id = self
            .get_tag_attributes(tag_name)
            .await
            .ok()
            .and_then(|attr| attr.template_instance_id)
            .unwrap_or(0) as i32;

        // Return raw UDT data (generic approach - no parsing)
        Ok(PlcValue::Udt(UdtData {
            symbol_id,
            data: all_data,
        }))
    }

    /// Reads a specific chunk of a UDT
    #[allow(dead_code)]
    async fn read_udt_chunk(
        &mut self,
        tag_name: &str,
        offset: usize,
        size: usize,
    ) -> crate::error::Result<Vec<u8>> {
        // Build a read request for a specific range
        let mut request = Vec::new();

        // Service: Read Tag (0x4C)
        request.push(0x4C);

        // Path size (in words) - tag name + array index
        let path_size = 2 + (tag_name.len() + 1) / 2; // Round up for word alignment
        request.push(path_size as u8);

        // Path: tag name
        request.extend_from_slice(tag_name.as_bytes());
        if tag_name.len() % 2 != 0 {
            request.push(0); // Pad to word boundary
        }

        // Array index for chunk reading
        request.push(0x28); // Array index symbol
        request.push(0x02); // 2 bytes for index
        request.extend_from_slice(&(offset as u16).to_le_bytes());

        // Element count
        request.push(0x28); // Element count symbol
        request.push(0x02); // 2 bytes for count
        request.extend_from_slice(&(size as u16).to_le_bytes());

        // Data type (assume DINT for raw data)
        request.push(0x00);
        request.push(0x01);

        // Send the request
        let response = self.send_cip_request(&request).await?;
        let cip_data = self.extract_cip_from_response(&response)?;

        // Parse the response to get raw data
        if cip_data.len() < 2 {
            return Err(crate::error::EtherNetIpError::Protocol(
                "Response too short".to_string(),
            ));
        }

        let _data_type = u16::from_le_bytes([cip_data[0], cip_data[1]]);
        let data = &cip_data[2..];

        Ok(data.to_vec())
    }

    /// Reads a specific UDT member by offset
    ///
    /// This method reads a specific member of a UDT by calculating its offset
    /// and reading only that portion of the UDT.
    ///
    /// # Arguments
    ///
    /// * `udt_name` - The name of the UDT tag
    /// * `member_offset` - The byte offset of the member in the UDT
    /// * `member_size` - The size of the member in bytes
    /// * `data_type` - The data type of the member (0x00C1 for BOOL, 0x00CA for REAL, etc.)
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// # let mut client = rust_ethernet_ip::EipClient::connect("192.168.1.100:44818").await?;
    /// let member_value = client.read_udt_member_by_offset("MyUDT", 0, 1, 0x00C1).await?;
    /// println!("Member value: {:?}", member_value);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn read_udt_member_by_offset(
        &mut self,
        udt_name: &str,
        member_offset: usize,
        member_size: usize,
        data_type: u16,
    ) -> crate::error::Result<PlcValue> {
        self.validate_session().await?;

        // Read the UDT data
        let udt_data = self.read_tag_raw(udt_name).await?;

        // Extract the member data
        if member_offset + member_size > udt_data.len() {
            return Err(crate::error::EtherNetIpError::Protocol(format!(
                "Member data incomplete: offset {} + size {} > UDT size {}",
                member_offset,
                member_size,
                udt_data.len()
            )));
        }

        let member_data = &udt_data[member_offset..member_offset + member_size];

        // Parse the member value using the data type
        let member = crate::udt::UdtMember {
            name: "temp".to_string(),
            data_type,
            offset: member_offset as u32,
            size: member_size as u32,
        };

        let udt = crate::udt::UserDefinedType::new(udt_name.to_string());
        udt.parse_member_value(&member, member_data)
    }

    /// Writes a specific UDT member by offset
    ///
    /// This method writes a specific member of a UDT by calculating its offset
    /// and writing only that portion of the UDT.
    ///
    /// # Arguments
    ///
    /// * `udt_name` - The name of the UDT tag
    /// * `member_offset` - The byte offset of the member in the UDT
    /// * `member_size` - The size of the member in bytes
    /// * `data_type` - The data type of the member (0x00C1 for BOOL, 0x00CA for REAL, etc.)
    /// * `value` - The value to write
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// # use rust_ethernet_ip::PlcValue;
    /// # let mut client = rust_ethernet_ip::EipClient::connect("192.168.1.100:44818").await?;
    /// client.write_udt_member_by_offset("MyUDT", 0, 1, 0x00C1, PlcValue::Bool(true)).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn write_udt_member_by_offset(
        &mut self,
        udt_name: &str,
        member_offset: usize,
        member_size: usize,
        data_type: u16,
        value: PlcValue,
    ) -> crate::error::Result<()> {
        self.validate_session().await?;

        // Read the current UDT data
        let mut udt_data = self.read_tag_raw(udt_name).await?;

        // Check bounds
        if member_offset + member_size > udt_data.len() {
            return Err(crate::error::EtherNetIpError::Protocol(format!(
                "Member data incomplete: offset {} + size {} > UDT size {}",
                member_offset,
                member_size,
                udt_data.len()
            )));
        }

        // Serialize the value
        let member = crate::udt::UdtMember {
            name: "temp".to_string(),
            data_type,
            offset: member_offset as u32,
            size: member_size as u32,
        };

        let udt = crate::udt::UserDefinedType::new(udt_name.to_string());
        let member_data = udt.serialize_member_value(&member, &value)?;

        // Update the UDT data
        let end_offset = member_offset + member_data.len();
        if end_offset <= udt_data.len() {
            udt_data[member_offset..end_offset].copy_from_slice(&member_data);
        } else {
            return Err(crate::error::EtherNetIpError::Protocol(format!(
                "Member data exceeds UDT size: {} > {}",
                end_offset,
                udt_data.len()
            )));
        }

        // Write the updated UDT data back
        self.write_tag_raw(udt_name, &udt_data).await
    }

    /// Gets UDT definition from the PLC
    /// This method queries the PLC for the UDT structure and caches it for future use
    pub async fn get_udt_definition(
        &mut self,
        udt_name: &str,
    ) -> crate::error::Result<UdtDefinition> {
        // Check cache first
        if let Some(cached) = self.udt_manager.lock().await.get_definition(udt_name) {
            return Ok(cached.clone());
        }

        // Get tag attributes to find template ID
        let attributes = self.get_tag_attributes(udt_name).await?;

        // If this is not a UDT, return error
        if attributes.data_type != 0x00A0 {
            return Err(crate::error::EtherNetIpError::Protocol(format!(
                "Tag '{}' is not a UDT (type: {})",
                udt_name, attributes.data_type_name
            )));
        }

        // Get template instance ID
        let template_id = attributes.template_instance_id.ok_or_else(|| {
            crate::error::EtherNetIpError::Protocol(
                "UDT template instance ID not found".to_string(),
            )
        })?;

        // Read UDT template
        let template_data = self.read_udt_template(template_id).await?;

        // Parse template
        let template = self
            .udt_manager
            .lock()
            .await
            .parse_udt_template(template_id, &template_data)?;

        // Convert template to definition
        let definition = UdtDefinition {
            name: udt_name.to_string(),
            members: template.members,
        };

        // Cache the definition
        self.udt_manager
            .lock()
            .await
            .add_definition(definition.clone());

        Ok(definition)
    }

    /// Gets tag attributes (type, size, dimensions, scope) from the PLC.
    ///
    /// Use this to introspect a tag before reading or writing: discover data type,
    /// size in bytes, array dimensions, and scope (controller vs program). Results
    /// are cached per tag for the lifetime of the client.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let attrs = client.get_tag_attributes("MyTag").await?;
    /// println!("Type: {}, size: {} bytes", attrs.data_type_name, attrs.size);
    /// if !attrs.dimensions.is_empty() {
    ///     println!("Array dimensions: {:?}", attrs.dimensions);
    /// }
    /// ```
    ///
    pub async fn get_tag_attributes(
        &mut self,
        tag_name: &str,
    ) -> crate::error::Result<TagAttributes> {
        // Check cache first
        if let Some(cached) = self.udt_manager.lock().await.get_tag_attributes(tag_name) {
            return Ok(cached.clone());
        }

        // Build CIP request for Get Attribute List (Service 0x03)
        let request = self.build_get_attributes_request(tag_name)?;

        // Send request and get response
        let response = self.send_cip_request(&request).await?;

        // Parse response
        let attributes = self.parse_attributes_response(tag_name, &response)?;

        // Cache the attributes
        self.udt_manager
            .lock()
            .await
            .add_tag_attributes(attributes.clone());

        Ok(attributes)
    }

    /// Reads UDT template data from the PLC
    async fn read_udt_template(&mut self, template_id: u32) -> crate::error::Result<Vec<u8>> {
        // Build CIP request for Read Tag Fragmented (Service 0x4C)
        let request = self.build_read_template_request(template_id)?;

        // Send request and get response
        let response = self.send_cip_request(&request).await?;

        // Parse response and extract template data
        self.parse_template_response(&response)
    }

    /// Builds CIP request for Get Attribute List (Service 0x03)
    fn build_get_attributes_request(&self, tag_name: &str) -> crate::error::Result<Vec<u8>> {
        let mut request = Vec::new();

        // Service: Get Attribute List (0x03)
        request.push(0x03);

        // Path: Tag name (ANSI extended symbolic segment)
        let tag_bytes = tag_name.as_bytes();
        request.push(0x91); // ANSI extended symbolic segment
        request.push(tag_bytes.len() as u8);
        request.extend_from_slice(tag_bytes);

        // Attribute count
        request.extend_from_slice(&[0x02, 0x00]); // 2 attributes

        // Attribute 1: Data Type (0x01)
        request.extend_from_slice(&[0x01, 0x00]);

        // Attribute 2: Template Instance ID (0x02)
        request.extend_from_slice(&[0x02, 0x00]);

        Ok(request)
    }

    /// Builds CIP request for Read Tag Fragmented (Service 0x4C)
    fn build_read_template_request(&self, template_id: u32) -> crate::error::Result<Vec<u8>> {
        let mut request = Vec::new();

        // Service: Read Tag Fragmented (0x4C)
        request.push(0x4C);

        // Path: Template instance
        request.push(0x20); // Class ID
        request.extend_from_slice(&[0x02, 0x00]); // Class 0x02 (Data Type)
        request.push(0x24); // Instance ID
        request.extend_from_slice(&template_id.to_le_bytes());

        // Offset and size (read entire template)
        request.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Offset 0
        request.extend_from_slice(&[0xFF, 0xFF, 0x00, 0x00]); // Size (max)

        Ok(request)
    }

    /// Parses attributes response from CIP
    fn parse_attributes_response(
        &self,
        tag_name: &str,
        response: &[u8],
    ) -> crate::error::Result<TagAttributes> {
        if response.len() < 8 {
            return Err(crate::error::EtherNetIpError::Protocol(
                "Attributes response too short".to_string(),
            ));
        }

        let mut offset = 0;

        // Parse data type
        let data_type = u16::from_le_bytes([response[offset], response[offset + 1]]);
        offset += 2;

        // Parse size
        let size = u32::from_le_bytes([
            response[offset],
            response[offset + 1],
            response[offset + 2],
            response[offset + 3],
        ]);
        offset += 4;

        // Parse template instance ID (if present)
        let template_instance_id = if response.len() > offset + 4 {
            Some(u32::from_le_bytes([
                response[offset],
                response[offset + 1],
                response[offset + 2],
                response[offset + 3],
            ]))
        } else {
            None
        };

        // Create attributes
        let attributes = TagAttributes {
            name: tag_name.to_string(),
            data_type,
            data_type_name: self.get_data_type_name(data_type),
            dimensions: Vec::new(), // Would need additional parsing
            permissions: udt::TagPermissions::ReadWrite, // Default assumption
            scope: if tag_name.contains(':') {
                let parts: Vec<&str> = tag_name.split(':').collect();
                if parts.len() >= 2 {
                    udt::TagScope::Program(parts[0].to_string())
                } else {
                    udt::TagScope::Controller
                }
            } else {
                udt::TagScope::Controller
            },
            template_instance_id,
            size,
        };

        Ok(attributes)
    }

    /// Parses template response from CIP
    fn parse_template_response(&self, response: &[u8]) -> crate::error::Result<Vec<u8>> {
        if response.len() < 4 {
            return Err(crate::error::EtherNetIpError::Protocol(
                "Template response too short".to_string(),
            ));
        }

        // Skip CIP header and return data portion
        let data_start = 4; // Skip status and other header bytes
        Ok(response[data_start..].to_vec())
    }

    /// Gets human-readable data type name
    fn get_data_type_name(&self, data_type: u16) -> String {
        match data_type {
            0x00C1 => "BOOL".to_string(),
            0x00C2 => "SINT".to_string(),
            0x00C3 => "INT".to_string(),
            0x00C4 => "DINT".to_string(),
            0x00C5 => "LINT".to_string(),
            0x00C6 => "USINT".to_string(),
            0x00C7 => "UINT".to_string(),
            0x00C8 => "UDINT".to_string(),
            0x00C9 => "ULINT".to_string(),
            0x00CA => "REAL".to_string(),
            0x00CB => "LREAL".to_string(),
            0x00CE => "STRING".to_string(),
            0x00A0 => "UDT".to_string(),
            _ => format!("UNKNOWN(0x{:04X})", data_type),
        }
    }

    /// Builds CIP request for tag list discovery
    fn build_tag_list_request(&self) -> crate::error::Result<Vec<u8>> {
        let mut request = Vec::new();

        // Service: Get Instance Attribute List (0x55)
        request.push(0x55);

        // Path: Symbol Object (Class 0x6B)
        request.push(0x20); // Class ID
        request.extend_from_slice(&[0x6B, 0x00]); // Class 0x6B (Symbol Object)
        request.push(0x25); // Instance ID (0x25 = all instances)
        request.extend_from_slice(&[0x00, 0x00]);

        // Attribute count
        request.extend_from_slice(&[0x02, 0x00]); // 2 attributes

        // Attribute 1: Symbol Name (0x01)
        request.extend_from_slice(&[0x01, 0x00]);

        // Attribute 2: Data Type (0x02)
        request.extend_from_slice(&[0x02, 0x00]);

        Ok(request)
    }

    /// Builds CIP request for program-scoped tag list discovery
    fn build_program_tag_list_request(&self, _program_name: &str) -> crate::error::Result<Vec<u8>> {
        let mut request = Vec::new();

        // Service: Get Instance Attribute List (0x55)
        request.push(0x55);

        // Path: Program Object (Class 0x6C)
        request.push(0x20); // Class ID
        request.extend_from_slice(&[0x6C, 0x00]); // Class 0x6C (Program Object)
        request.push(0x24); // Instance ID
        request.extend_from_slice(&[0x00, 0x00]); // Would need to resolve program name to ID

        // Attribute count
        request.extend_from_slice(&[0x02, 0x00]); // 2 attributes

        // Attribute 1: Symbol Name (0x01)
        request.extend_from_slice(&[0x01, 0x00]);

        // Attribute 2: Data Type (0x02)
        request.extend_from_slice(&[0x02, 0x00]);

        Ok(request)
    }

    /// Parses tag list response from CIP
    fn parse_tag_list_response(&self, response: &[u8]) -> crate::error::Result<Vec<TagAttributes>> {
        if response.len() < 4 {
            return Err(crate::error::EtherNetIpError::Protocol(
                "Tag list response too short".to_string(),
            ));
        }

        let mut offset = 0;
        let mut tags = Vec::new();

        // Skip CIP header
        offset += 4;

        // Parse each tag entry
        while offset < response.len() {
            if offset + 8 > response.len() {
                break; // Not enough data for another tag
            }

            // Parse tag name length
            let name_length = u16::from_le_bytes([response[offset], response[offset + 1]]) as usize;
            offset += 2;

            if offset
                .checked_add(name_length)
                .map_or(true, |end| end > response.len())
            {
                break; // Not enough data for tag name
            }

            // Parse tag name
            let name_bytes = &response[offset..offset + name_length];
            let tag_name = String::from_utf8_lossy(name_bytes).to_string();
            offset += name_length;

            // Align to 4-byte boundary
            offset = (offset + 3) & !3;

            if offset + 2 > response.len() {
                break; // Not enough data for data type
            }

            // Parse data type
            let data_type = u16::from_le_bytes([response[offset], response[offset + 1]]);
            offset += 2;

            // Create tag attributes
            let attributes = TagAttributes {
                name: tag_name,
                data_type,
                data_type_name: self.get_data_type_name(data_type),
                dimensions: Vec::new(), // Would need additional parsing
                permissions: udt::TagPermissions::ReadWrite, // Default assumption
                scope: udt::TagScope::Controller, // Default assumption
                template_instance_id: if data_type == 0x00A0 { Some(0) } else { None },
                size: 0, // Would need additional parsing
            };

            tags.push(attributes);
        }

        Ok(tags)
    }

    /// Negotiates packet size with the PLC
    /// This method queries the PLC for its maximum supported packet size
    /// and updates the client's configuration accordingly
    async fn negotiate_packet_size(&mut self) -> crate::error::Result<()> {
        // Build CIP request for Get Attribute List (Service 0x03)
        // Query the Message Router object (Class 0x02, Instance 1) for max packet size
        let mut request = vec![
            0x03, // Service: Get Attribute List
            0x02, // Path size: 2 words (4 bytes)
            0x20, 0x02, // 8-bit class segment: Class 0x02 (Message Router)
            0x24, 0x01, // 8-bit instance segment: Instance 1
        ];
        // Attribute count
        request.extend_from_slice(&[0x01, 0x00]); // 1 attribute
                                                  // Attribute: Max Packet Size (attribute 4 on the Message Router)
        request.extend_from_slice(&[0x04, 0x00]);

        // Send request and extract CIP from CPF response
        let response = self.send_cip_request(&request).await?;
        let cip_data = self.extract_cip_from_response(&response)?;

        // CIP response format: [Service Reply][Reserved][Status][AddtlStatusSize][...data...]
        // For Get Attribute List reply: after the 4-byte CIP header, we get:
        // [AttrCount(2)] [AttrID(2)] [Status(2)] [Value(2)]
        // The attribute value for max packet size is a UINT (2 bytes)
        if cip_data.len() >= 12 && cip_data[2] == 0x00 {
            // Skip CIP header (4 bytes) + attr count (2) + attr id (2) + attr status (2) = 10
            let max_packet_size = u16::from_le_bytes([cip_data[10], cip_data[11]]) as u32;

            // Update client's max packet size (with reasonable limits)
            self.max_packet_size = max_packet_size.clamp(504, 4000);
            tracing::debug!("Negotiated packet size: {} bytes", self.max_packet_size);
        } else {
            // If negotiation fails, use default size
            self.max_packet_size = 4000;
            tracing::debug!("Using default packet size: {} bytes", self.max_packet_size);
        }

        Ok(())
    }

    /// Writes a value to a PLC tag
    ///
    /// This method automatically determines the best communication method based on the data type:
    /// - STRING values use unconnected explicit messaging with proper AB STRING format
    /// - Other data types use standard unconnected messaging
    ///
    /// **v0.6.0**: For UDT tags, pass `PlcValue::Udt(UdtData)`. The `symbol_id` must be set
    /// (typically obtained by reading the UDT first). If `symbol_id` is 0, the method will
    /// attempt to read tag attributes to get the symbol_id automatically.
    ///
    /// # Arguments
    ///
    /// * `tag_name` - The name of the tag to write to
    /// * `value` - The value to write. For UDTs, use `PlcValue::Udt(UdtData)`.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// # let mut client = rust_ethernet_ip::EipClient::connect("192.168.1.100:44818").await?;
    /// use rust_ethernet_ip::{PlcValue, UdtData};
    ///
    /// // Write simple types
    /// client.write_tag("Counter", PlcValue::Dint(42)).await?;
    /// client.write_tag("Message", PlcValue::String("Hello PLC".to_string())).await?;
    ///
    /// // Write UDT (v0.6.0: read first to get symbol_id, then modify and write)
    /// let udt_value = client.read_tag("MyUDT").await?;
    /// if let PlcValue::Udt(mut udt_data) = udt_value {
    ///     let udt_def = client.get_udt_definition("MyUDT").await?;
    ///     // Convert UdtDefinition to UserDefinedType
    ///     let mut user_def = rust_ethernet_ip::udt::UserDefinedType::new(udt_def.name.clone());
    ///     for member in &udt_def.members {
    ///         user_def.add_member(member.clone());
    ///     }
    ///     let mut members = udt_data.parse(&user_def)?;
    ///     members.insert("Member1".to_string(), PlcValue::Dint(100));
    ///     let modified_udt = UdtData::from_hash_map(&members, &user_def, udt_data.symbol_id)?;
    ///     client.write_tag("MyUDT", PlcValue::Udt(modified_udt)).await?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn write_tag(&mut self, tag_name: &str, value: PlcValue) -> crate::error::Result<()> {
        tracing::debug!(
            "Writing '{}' to tag '{}'",
            match &value {
                PlcValue::String(s) => format!("\"{s}\""),
                _ => format!("{value:?}"),
            },
            tag_name
        );

        // For UDT writes, ensure we have a valid symbol_id
        // As noted by the contributor: "to write a UDT, you typically need to read it first to get the symbol_id"
        let value = if let PlcValue::Udt(udt_data) = &value {
            if udt_data.symbol_id == 0 {
                tracing::debug!("[UDT WRITE] symbol_id is 0, reading tag to get symbol_id");
                // Read tag attributes to get symbol_id
                let attributes = self.get_tag_attributes(tag_name).await?;
                let symbol_id = attributes.template_instance_id.ok_or_else(|| {
                    crate::error::EtherNetIpError::Protocol(
                        "UDT template instance ID not found. Cannot write UDT without symbol_id."
                            .to_string(),
                    )
                })? as i32;

                // Create new UdtData with the correct symbol_id
                PlcValue::Udt(UdtData {
                    symbol_id,
                    data: udt_data.data.clone(),
                })
            } else {
                value
            }
        } else {
            value
        };

        // Check if this is array element access (e.g., "ArrayName[0]")
        if let Some((base_name, index)) = self.parse_array_element_access(tag_name) {
            tracing::debug!(
                "Detected array element write: {}[{}], using workaround",
                base_name,
                index
            );
            return self
                .write_array_element_workaround(&base_name, index, value)
                .await;
        }

        // Use specialized AB STRING format for STRING writes (required for proper Allen-Bradley STRING handling)
        // All data types including strings now use the standard write path
        // The PlcValue::to_bytes() method handles the correct format for each type

        // Use standard unconnected messaging for other data types
        let cip_request = self.build_write_request(tag_name, &value)?;

        let response = self.send_cip_request(&cip_request).await?;

        // Check write response for errors - need to extract CIP response first
        let cip_response = self.extract_cip_from_response(&response)?;

        if cip_response.len() < 3 {
            return Err(EtherNetIpError::Protocol(
                "Write response too short".to_string(),
            ));
        }

        let service_reply = cip_response[0]; // Should be 0xCD (0x4D + 0x80) for Write Tag reply
        let general_status = cip_response[2]; // CIP status code

        tracing::trace!(
            "Write response - Service: 0x{:02X}, Status: 0x{:02X}",
            service_reply,
            general_status
        );

        // Check for errors (including extended errors)
        if let Err(e) = self.check_cip_error(&cip_response) {
            tracing::error!("[WRITE] CIP Error: {}", e);
            return Err(e);
        }

        tracing::info!("Write operation completed successfully");
        Ok(())
    }

    /// Builds a write request specifically for Allen-Bradley string format
    fn _build_ab_string_write_request(
        &self,
        tag_name: &str,
        value: &PlcValue,
    ) -> crate::error::Result<Vec<u8>> {
        if let PlcValue::String(string_value) = value {
            tracing::debug!(
                "Building correct Allen-Bradley string write request for tag: '{}'",
                tag_name
            );

            let mut cip_request = Vec::new();

            // Service: Write Tag Service (0x4D)
            cip_request.push(0x4D);

            // Request Path Size (in words)
            let tag_bytes = tag_name.as_bytes();
            let path_len = if tag_bytes.len() % 2 == 0 {
                tag_bytes.len() + 2
            } else {
                tag_bytes.len() + 3
            } / 2;
            cip_request.push(path_len as u8);

            // Request Path
            cip_request.push(0x91); // ANSI Extended Symbol
            cip_request.push(tag_bytes.len() as u8);
            cip_request.extend_from_slice(tag_bytes);

            // Pad to word boundary if needed
            if tag_bytes.len() % 2 != 0 {
                cip_request.push(0x00);
            }

            // Data Type: Allen-Bradley STRING (0x02A0)
            cip_request.extend_from_slice(&[0xA0, 0x02]);

            // Element Count (always 1 for single string)
            cip_request.extend_from_slice(&[0x01, 0x00]);

            // Build the correct AB STRING structure
            let string_bytes = string_value.as_bytes();
            let max_len: u16 = 82; // Standard AB STRING max length
            let current_len = string_bytes.len().min(max_len as usize) as u16;

            // AB STRING structure:
            // - Len (2 bytes) - number of characters used
            cip_request.extend_from_slice(&current_len.to_le_bytes());

            // - MaxLen (2 bytes) - maximum characters allowed (typically 82)
            cip_request.extend_from_slice(&max_len.to_le_bytes());

            // - Data[MaxLen] (82 bytes) - the character array, zero-padded
            let mut data_array = vec![0u8; max_len as usize];
            data_array[..current_len as usize]
                .copy_from_slice(&string_bytes[..current_len as usize]);
            cip_request.extend_from_slice(&data_array);

            tracing::trace!(
                "Built correct AB string write request ({} bytes): len={}, maxlen={}, data_len={}",
                cip_request.len(),
                current_len,
                max_len,
                string_bytes.len()
            );
            tracing::trace!(
                "First 32 bytes: {:02X?}",
                &cip_request[..std::cmp::min(32, cip_request.len())]
            );

            Ok(cip_request)
        } else {
            Err(EtherNetIpError::Protocol(
                "Expected string value for Allen-Bradley string write".to_string(),
            ))
        }
    }

    /// Builds a CIP Write Tag Service request
    ///
    /// This creates the CIP packet for writing a value to a tag.
    /// The request includes the service code, tag path, data type, and value.
    ///
    /// For UDT writes, the data type must be Structure Tag Type (0x02A0 + Structure Handle).
    /// The Structure Handle is the template_instance_id (symbol_id) from Template Attribute 1.
    ///
    /// Reference: 1756-PM020, Page 1080 (UDT Data Layout Considerations)
    fn build_write_request(
        &self,
        tag_name: &str,
        value: &PlcValue,
    ) -> crate::error::Result<Vec<u8>> {
        tracing::debug!("Building write request for tag: '{}'", tag_name);

        // Use Connected Explicit Messaging for consistency
        let mut cip_request = Vec::new();

        // Service: Write Tag Service (0x4D)
        cip_request.push(0x4D);

        // Use the same path building logic as read operations
        let path = self.build_tag_path(tag_name);

        // Request Path Size (in words)
        cip_request.push((path.len() / 2) as u8);

        // Request Path: Use the same path building as read operations
        cip_request.extend_from_slice(&path);

        // Add data type and element count
        // For UDTs, use Structure Tag Type (0x02A0 + Structure Handle) per 1756-PM020, Page 1080
        let data_type = if let PlcValue::Udt(udt_data) = value {
            // Structure Tag Type = 0x02A0 + Structure Handle (template_instance_id)
            // Reference: 1756-PM020, Page 1080 (UDT Data Layout Considerations)
            0x02A0u16.wrapping_add(udt_data.symbol_id as u16)
        } else {
            value.get_data_type()
        };
        let value_bytes = value.to_bytes();

        cip_request.extend_from_slice(&data_type.to_le_bytes()); // Data type
        cip_request.extend_from_slice(&[0x01, 0x00]); // Element count: 1
        cip_request.extend_from_slice(&value_bytes); // Value data

        tracing::trace!(
            "Built CIP write request ({} bytes): {:02X?}",
            cip_request.len(),
            cip_request
        );
        Ok(cip_request)
    }

    /// Builds a raw write request with pre-serialized data
    fn build_write_request_raw(
        &self,
        tag_name: &str,
        data: &[u8],
    ) -> crate::error::Result<Vec<u8>> {
        let mut request = Vec::new();

        // Write Tag Service
        request.push(0x4D);
        request.push(0x00);

        // Build tag path
        let tag_path = self.build_tag_path(tag_name);
        request.extend(tag_path);

        // Add raw data
        request.extend(data);

        Ok(request)
    }

    /// Serializes a `PlcValue` into bytes for transmission
    #[allow(dead_code)]
    fn serialize_value(&self, value: &PlcValue) -> crate::error::Result<Vec<u8>> {
        let mut data = Vec::new();

        match value {
            PlcValue::Bool(v) => {
                data.extend(&0x00C1u16.to_le_bytes()); // Data type
                data.push(if *v { 0xFF } else { 0x00 });
            }
            PlcValue::Sint(v) => {
                data.extend(&0x00C2u16.to_le_bytes()); // Data type
                data.extend(&v.to_le_bytes());
            }
            PlcValue::Int(v) => {
                data.extend(&0x00C3u16.to_le_bytes()); // Data type
                data.extend(&v.to_le_bytes());
            }
            PlcValue::Dint(v) => {
                data.extend(&0x00C4u16.to_le_bytes()); // Data type
                data.extend(&v.to_le_bytes());
            }
            PlcValue::Lint(v) => {
                data.extend(&0x00C5u16.to_le_bytes()); // Data type
                data.extend(&v.to_le_bytes());
            }
            PlcValue::Usint(v) => {
                data.extend(&0x00C6u16.to_le_bytes()); // Data type
                data.extend(&v.to_le_bytes());
            }
            PlcValue::Uint(v) => {
                data.extend(&0x00C7u16.to_le_bytes()); // Data type
                data.extend(&v.to_le_bytes());
            }
            PlcValue::Udint(v) => {
                data.extend(&0x00C8u16.to_le_bytes()); // Data type
                data.extend(&v.to_le_bytes());
            }
            PlcValue::Ulint(v) => {
                data.extend(&0x00C9u16.to_le_bytes()); // Data type
                data.extend(&v.to_le_bytes());
            }
            PlcValue::Real(v) => {
                data.extend(&0x00CAu16.to_le_bytes()); // Data type
                data.extend(&v.to_le_bytes());
            }
            PlcValue::Lreal(v) => {
                data.extend(&0x00CBu16.to_le_bytes()); // Data type
                data.extend(&v.to_le_bytes());
            }
            PlcValue::String(v) => {
                data.extend(&0x00CEu16.to_le_bytes()); // Data type - correct Allen-Bradley STRING CIP type

                // Length field (4 bytes as DINT) - number of characters currently used
                let length = v.len().min(82) as u32;
                data.extend_from_slice(&length.to_le_bytes());

                // String data - the actual characters (no MaxLen field)
                let string_bytes = v.as_bytes();
                let data_len = string_bytes.len().min(82);
                data.extend_from_slice(&string_bytes[..data_len]);

                // Padding to make total data area exactly 82 bytes after length
                let remaining_chars = 82 - data_len;
                data.extend(vec![0u8; remaining_chars]);
            }
            PlcValue::Udt(_) => {
                // UDT serialization is handled by the UdtManager
                // For now, just add placeholder data
                data.extend(&0x00A0u16.to_le_bytes()); // UDT type code
            }
        }

        Ok(data)
    }

    pub fn build_list_tags_request(&self) -> Vec<u8> {
        tracing::debug!("Building list tags request");

        // Build path array for Symbol Object Class (0x6B)
        let path_array = vec![
            // Class segment: Symbol Object Class (0x6B)
            0x20, // Class segment identifier
            0x6B, // Symbol Object Class
            // Instance segment: Start at Instance 0
            0x25, // Instance segment identifier with 0x00
            0x00, 0x00, 0x00,
        ];

        // Request data: 2 Attributes - Attribute 1 and Attribute 2
        let request_data = vec![0x02, 0x00, 0x01, 0x00, 0x02, 0x00];

        // Build CIP Message Router request
        let mut cip_request = Vec::new();

        // Service: Get Instance Attribute List (0x55)
        cip_request.push(0x55);

        // Request Path Size (in words)
        cip_request.push((path_array.len() / 2) as u8);

        // Request Path
        cip_request.extend_from_slice(&path_array);

        // Request Data
        cip_request.extend_from_slice(&request_data);

        tracing::trace!(
            "Built CIP list tags request ({} bytes): {:02X?}",
            cip_request.len(),
            cip_request
        );

        cip_request
    }

    /// Gets a human-readable error message for a CIP status code
    ///
    /// # Arguments
    ///
    /// * `status` - The CIP status code to look up
    ///
    /// # Returns
    ///
    /// A string describing the error
    /// Parses extended CIP error codes from response data
    ///
    /// When general_status is 0xFF, the error code is in the additional status field.
    /// Format: [0]=service, [1]=reserved, [2]=0xFF, [3]=additional_status_size (words), [4-5]=extended_error_code
    fn parse_extended_error(&self, cip_data: &[u8]) -> crate::error::Result<String> {
        if cip_data.len() < 6 {
            return Err(EtherNetIpError::Protocol(
                "Extended error response too short".to_string(),
            ));
        }

        let additional_status_size = cip_data[3] as usize; // Size in words
        if additional_status_size == 0 || cip_data.len() < 4 + (additional_status_size * 2) {
            return Ok("Extended error (no additional status)".to_string());
        }

        // Extended error code is in the additional status field (2 bytes)
        // Try both little-endian and big-endian interpretations
        let extended_error_code_le = u16::from_le_bytes([cip_data[4], cip_data[5]]);
        let extended_error_code_be = u16::from_be_bytes([cip_data[4], cip_data[5]]);

        // Map extended error codes (these are the same as regular error codes but in extended format)
        // Try little-endian first (standard CIP format)
        let error_msg = match extended_error_code_le {
            0x0001 => "Connection failure (extended)".to_string(),
            0x0002 => "Resource unavailable (extended)".to_string(),
            0x0003 => "Invalid parameter value (extended)".to_string(),
            0x0004 => "Path segment error (extended)".to_string(),
            0x0005 => "Path destination unknown (extended)".to_string(),
            0x0006 => "Partial transfer (extended)".to_string(),
            0x0007 => "Connection lost (extended)".to_string(),
            0x0008 => "Service not supported (extended)".to_string(),
            0x0009 => "Invalid attribute value (extended)".to_string(),
            0x000A => "Attribute list error (extended)".to_string(),
            0x000B => "Already in requested mode/state (extended)".to_string(),
            0x000C => "Object state conflict (extended)".to_string(),
            0x000D => "Object already exists (extended)".to_string(),
            0x000E => "Attribute not settable (extended)".to_string(),
            0x000F => "Privilege violation (extended)".to_string(),
            0x0010 => "Device state conflict (extended)".to_string(),
            0x0011 => "Reply data too large (extended)".to_string(),
            0x0012 => "Fragmentation of a primitive value (extended)".to_string(),
            0x0013 => "Not enough data (extended)".to_string(),
            0x0014 => "Attribute not supported (extended)".to_string(),
            0x0015 => "Too much data (extended)".to_string(),
            0x0016 => "Object does not exist (extended)".to_string(),
            0x0017 => "Service fragmentation sequence not in progress (extended)".to_string(),
            0x0018 => "No stored attribute data (extended)".to_string(),
            0x0019 => "Store operation failure (extended)".to_string(),
            0x001A => "Routing failure, request packet too large (extended)".to_string(),
            0x001B => "Routing failure, response packet too large (extended)".to_string(),
            0x001C => "Missing attribute list entry data (extended)".to_string(),
            0x001D => "Invalid attribute value list (extended)".to_string(),
            0x001E => "Embedded service error (extended)".to_string(),
            0x001F => "Vendor specific error (extended)".to_string(),
            0x0020 => "Invalid parameter (extended)".to_string(),
            0x0021 => "Write-once value or medium already written (extended)".to_string(),
            0x0022 => "Invalid reply received (extended)".to_string(),
            0x0023 => "Buffer overflow (extended)".to_string(),
            0x0024 => "Invalid message format (extended)".to_string(),
            0x0025 => "Key failure in path (extended)".to_string(),
            0x0026 => "Path size invalid (extended)".to_string(),
            0x0027 => "Unexpected attribute in list (extended)".to_string(),
            0x0028 => "Invalid member ID (extended)".to_string(),
            0x0029 => "Member not settable (extended)".to_string(),
            0x002A => "Group 2 only server general failure (extended)".to_string(),
            0x002B => "Unknown Modbus error (extended)".to_string(),
            0x002C => "Attribute not gettable (extended)".to_string(),
            // Try big-endian interpretation if little-endian doesn't match
            _ => {
                // Try big-endian interpretation
                match extended_error_code_be {
                    0x0001 => "Connection failure (extended, BE)".to_string(),
                    0x0002 => "Resource unavailable (extended, BE)".to_string(),
                    0x0003 => "Invalid parameter value (extended, BE)".to_string(),
                    0x0004 => "Path segment error (extended, BE)".to_string(),
                    0x0005 => "Path destination unknown (extended, BE)".to_string(),
                    0x0006 => "Partial transfer (extended, BE)".to_string(),
                    0x0007 => "Connection lost (extended, BE)".to_string(),
                    0x0008 => "Service not supported (extended, BE)".to_string(),
                    0x0009 => "Invalid attribute value (extended, BE)".to_string(),
                    0x000A => "Attribute list error (extended, BE)".to_string(),
                    0x000B => "Already in requested mode/state (extended, BE)".to_string(),
                    0x000C => "Object state conflict (extended, BE)".to_string(),
                    0x000D => "Object already exists (extended, BE)".to_string(),
                    0x000E => "Attribute not settable (extended, BE)".to_string(),
                    0x000F => "Privilege violation (extended, BE)".to_string(),
                    0x0010 => "Device state conflict (extended, BE)".to_string(),
                    0x0011 => "Reply data too large (extended, BE)".to_string(),
                    0x0012 => "Fragmentation of a primitive value (extended, BE)".to_string(),
                    0x0013 => "Not enough data (extended, BE)".to_string(),
                    0x0014 => "Attribute not supported (extended, BE)".to_string(),
                    0x0015 => "Too much data (extended, BE)".to_string(),
                    0x0016 => "Object does not exist (extended, BE)".to_string(),
                    0x0017 => "Service fragmentation sequence not in progress (extended, BE)".to_string(),
                    0x0018 => "No stored attribute data (extended, BE)".to_string(),
                    0x0019 => "Store operation failure (extended, BE)".to_string(),
                    0x001A => "Routing failure, request packet too large (extended, BE)".to_string(),
                    0x001B => "Routing failure, response packet too large (extended, BE)".to_string(),
                    0x001C => "Missing attribute list entry data (extended, BE)".to_string(),
                    0x001D => "Invalid attribute value list (extended, BE)".to_string(),
                    0x001E => "Embedded service error (extended, BE)".to_string(),
                    0x001F => "Vendor specific error (extended, BE)".to_string(),
                    0x0020 => "Invalid parameter (extended, BE)".to_string(),
                    0x0021 => "Write-once value or medium already written (extended, BE)".to_string(),
                    0x0022 => "Invalid reply received (extended, BE)".to_string(),
                    0x0023 => "Buffer overflow (extended, BE)".to_string(),
                    0x0024 => "Invalid message format (extended, BE)".to_string(),
                    0x0025 => "Key failure in path (extended, BE)".to_string(),
                    0x0026 => "Path size invalid (extended, BE)".to_string(),
                    0x0027 => "Unexpected attribute in list (extended, BE)".to_string(),
                    0x0028 => "Invalid member ID (extended, BE)".to_string(),
                    0x0029 => "Member not settable (extended, BE)".to_string(),
                    0x002A => "Group 2 only server general failure (extended, BE)".to_string(),
                    0x002B => "Unknown Modbus error (extended, BE)".to_string(),
                    0x002C => "Attribute not gettable (extended, BE)".to_string(),
                    // Check if it's a vendor-specific or composite error
                    _ if extended_error_code_le == 0x2107 || extended_error_code_be == 0x2107 => {
                        // 0x2107 might be a composite error or vendor-specific
                        // Bytes are [0x07, 0x21] - could be error 0x07 (Connection lost) with additional info 0x21
                        // Or could be a vendor-specific extended error
                        format!(
                            "Vendor-specific or composite extended error: 0x{extended_error_code_le:04X} (LE) / 0x{extended_error_code_be:04X} (BE). Raw bytes: [0x{:02X}, 0x{:02X}]. This may indicate the PLC does not support writing to UDT array element members directly.",
                            cip_data[4], cip_data[5]
                        )
                    }
                    _ => format!(
                        "Unknown extended CIP error code: 0x{extended_error_code_le:04X} (LE) / 0x{extended_error_code_be:04X} (BE). Raw bytes: [0x{:02X}, 0x{:02X}]",
                        cip_data[4], cip_data[5]
                    ),
                }
            }
        };

        Ok(error_msg)
    }

    /// Checks CIP response for errors, including extended error codes
    /// Returns Ok(()) if no error, Err with error message if error found
    fn check_cip_error(&self, cip_data: &[u8]) -> crate::error::Result<()> {
        if cip_data.len() < 3 {
            return Err(EtherNetIpError::Protocol(
                "CIP response too short for status check".to_string(),
            ));
        }

        let general_status = cip_data[2];

        if general_status == 0x00 {
            // Success
            return Ok(());
        }

        // Check for extended error (0xFF indicates extended error code)
        if general_status == 0xFF {
            let error_msg = self.parse_extended_error(cip_data)?;
            return Err(EtherNetIpError::Protocol(format!(
                "CIP Extended Error: {error_msg}"
            )));
        }

        // Regular error code
        let error_msg = self.get_cip_error_message(general_status);
        Err(EtherNetIpError::Protocol(format!(
            "CIP Error 0x{general_status:02X}: {error_msg}"
        )))
    }

    fn get_cip_error_message(&self, status: u8) -> String {
        match status {
            0x00 => "Success".to_string(),
            0x01 => "Connection failure".to_string(),
            0x02 => "Resource unavailable".to_string(),
            0x03 => "Invalid parameter value".to_string(),
            0x04 => "Path segment error".to_string(),
            0x05 => "Path destination unknown".to_string(),
            0x06 => "Partial transfer".to_string(),
            0x07 => "Connection lost".to_string(),
            0x08 => "Service not supported".to_string(),
            0x09 => "Invalid attribute value".to_string(),
            0x0A => "Attribute list error".to_string(),
            0x0B => "Already in requested mode/state".to_string(),
            0x0C => "Object state conflict".to_string(),
            0x0D => "Object already exists".to_string(),
            0x0E => "Attribute not settable".to_string(),
            0x0F => "Privilege violation".to_string(),
            0x10 => "Device state conflict".to_string(),
            0x11 => "Reply data too large".to_string(),
            0x12 => "Fragmentation of a primitive value".to_string(),
            0x13 => "Not enough data".to_string(),
            0x14 => "Attribute not supported".to_string(),
            0x15 => "Too much data".to_string(),
            0x16 => "Object does not exist".to_string(),
            0x17 => "Service fragmentation sequence not in progress".to_string(),
            0x18 => "No stored attribute data".to_string(),
            0x19 => "Store operation failure".to_string(),
            0x1A => "Routing failure, request packet too large".to_string(),
            0x1B => "Routing failure, response packet too large".to_string(),
            0x1C => "Missing attribute list entry data".to_string(),
            0x1D => "Invalid attribute value list".to_string(),
            0x1E => "Embedded service error".to_string(),
            0x1F => "Vendor specific error".to_string(),
            0x20 => "Invalid parameter".to_string(),
            0x21 => "Write-once value or medium already written".to_string(),
            0x22 => "Invalid reply received".to_string(),
            0x23 => "Buffer overflow".to_string(),
            0x24 => "Invalid message format".to_string(),
            0x25 => "Key failure in path".to_string(),
            0x26 => "Path size invalid".to_string(),
            0x27 => "Unexpected attribute in list".to_string(),
            0x28 => "Invalid member ID".to_string(),
            0x29 => "Member not settable".to_string(),
            0x2A => "Group 2 only server general failure".to_string(),
            0x2B => "Unknown Modbus error".to_string(),
            0x2C => "Attribute not gettable".to_string(),
            _ => format!("Unknown CIP error code: 0x{status:02X}"),
        }
    }

    fn describe_multiple_service_error(
        &self,
        general_status: u8,
        operations: &[BatchOperation],
    ) -> String {
        if general_status == 0x1E
            && operations.iter().any(|op| {
                matches!(
                    op,
                    BatchOperation::Write {
                        value: PlcValue::String(_),
                        ..
                    }
                )
            })
        {
            return "Multiple Service Response error: 0x1E (Embedded service error). On CompactLogix/ControlLogix this commonly indicates the controller rejected a direct STRING write in the batch request; treat it as a PLC firmware limitation, not a protocol bug.".to_string();
        }

        format!("Multiple Service Response error: 0x{general_status:02X}")
    }

    async fn validate_session(&mut self) -> crate::error::Result<()> {
        let time_since_activity = self.last_activity.lock().await.elapsed();

        // Send keep-alive if it's been more than 30 seconds since last activity
        if time_since_activity > Duration::from_secs(30) {
            self.send_keep_alive().await?;
        }

        Ok(())
    }

    async fn send_keep_alive(&mut self) -> crate::error::Result<()> {
        // Send NOP command (0x0000) — a valid 24-byte EtherNet/IP packet
        // that keeps the TCP connection alive without affecting session state.
        // NOP requires no response, so we don't read one.
        let packet = vec![0u8; 24];
        // Command: NOP (0x0000) — already zero
        // Length: 0 — already zero
        // Session handle, status, context, options — all zero for NOP

        let mut stream = self.stream.lock().await;
        stream.write_all(&packet).await?;
        *self.last_activity.lock().await = Instant::now();
        Ok(())
    }

    /// Quick connection health check (no I/O).
    ///
    /// Returns `true` if the session handle is valid and there has been activity
    /// within the last 150 seconds. Use this for cheap periodic checks; for a
    /// definitive check that the PLC is still responding, use [`check_health_detailed`](Self::check_health_detailed).
    pub async fn check_health(&self) -> bool {
        self.session_handle != 0
            && self.last_activity.lock().await.elapsed() < Duration::from_secs(150)
    }

    /// Verifies the connection by sending a keep-alive (and re-registering if needed).
    ///
    /// Use this when you need to confirm the PLC is still reachable (e.g. after
    /// a long idle or before a critical operation). On failure, consider
    /// reconnecting; check [`EtherNetIpError::is_retriable`](crate::error::EtherNetIpError::is_retriable) on errors.
    pub async fn check_health_detailed(&mut self) -> crate::error::Result<bool> {
        if self.session_handle == 0 {
            return Ok(false);
        }

        // Try sending a lightweight keep-alive command
        match self.send_keep_alive().await {
            Ok(()) => Ok(true),
            Err(_) => {
                // If keep-alive fails, try re-registering the session
                match self.register_session().await {
                    Ok(()) => Ok(true),
                    Err(_) => Ok(false),
                }
            }
        }
    }

    /// Reads raw data from a tag
    async fn read_tag_raw(&mut self, tag_name: &str) -> crate::error::Result<Vec<u8>> {
        let response = self
            .send_cip_request(&self.build_read_request(tag_name))
            .await?;
        self.extract_cip_from_response(&response)
    }

    /// Writes raw data to a tag
    #[allow(dead_code)]
    async fn write_tag_raw(&mut self, tag_name: &str, data: &[u8]) -> crate::error::Result<()> {
        let request = self.build_write_request_raw(tag_name, data)?;
        let response = self.send_cip_request(&request).await?;

        // Check write response for errors
        let cip_response = self.extract_cip_from_response(&response)?;

        if cip_response.len() < 3 {
            return Err(EtherNetIpError::Protocol(
                "Write response too short".to_string(),
            ));
        }

        let service_reply = cip_response[0]; // Should be 0xCD (0x4D + 0x80) for Write Tag reply
        let general_status = cip_response[2]; // CIP status code

        tracing::trace!(
            "Write response - Service: 0x{:02X}, Status: 0x{:02X}",
            service_reply,
            general_status
        );

        // Check for errors (including extended errors)
        if let Err(e) = self.check_cip_error(&cip_response) {
            tracing::error!("[WRITE] CIP Error: {}", e);
            return Err(e);
        }

        tracing::info!("Write completed successfully");
        Ok(())
    }

    /// Builds an Unconnected Send message wrapping a CIP request
    ///
    /// Reference: EtherNetIP_Connection_Paths_and_Routing.md
    /// The route path goes at the END of the Unconnected Send message, NOT in the CIP service request.
    ///
    /// Structure:
    /// - Service: 0x52 (Unconnected Send)
    /// - Request Path: Connection Manager (Class 0x06, Instance 1)
    /// - Priority/Time Tick: 0x0A
    /// - Timeout Ticks: 0xF0
    /// - Embedded Message Length
    /// - Embedded CIP Message (Read Tag, Write Tag, etc.) ← NO route path here
    /// - Pad byte (if message length is odd)
    /// - Route Path Size
    /// - Reserved byte
    /// - Route Path ← Route path goes HERE
    fn build_unconnected_send(&self, embedded_message: &[u8]) -> Vec<u8> {
        let mut ucmm = vec![
            // Service: Unconnected Send (0x52)
            0x52, // Request Path Size: 2 words (4 bytes) for Connection Manager
            0x02,
            // Request Path: Connection Manager (Class 0x06, Instance 1)
            0x20, // Logical Class segment
            0x06, // Class 0x06 (Connection Manager)
            0x24, // Logical Instance segment
            0x01, // Instance 1
            // Priority/Time Tick: 0x0A
            0x0A, // Timeout Ticks: 0xF0 (240 ticks)
            0xF0,
        ];

        // Embedded message length (16-bit, little-endian)
        let msg_len = embedded_message.len() as u16;
        ucmm.extend_from_slice(&msg_len.to_le_bytes());

        // The actual CIP message (Read Tag, Write Tag, etc.) - NO route path here!
        ucmm.extend_from_slice(embedded_message);

        // Pad byte if message length is odd
        if embedded_message.len() % 2 == 1 {
            ucmm.push(0x00);
        }

        // Route Path Size (in 16-bit words)
        // Get route path if configured
        let route_path_bytes = if let Some(route_path) = &self.route_path {
            route_path.to_cip_bytes()
        } else {
            Vec::new()
        };

        let route_path_words = if route_path_bytes.is_empty() {
            0
        } else {
            (route_path_bytes.len() / 2) as u8
        };
        ucmm.push(route_path_words);

        // Reserved byte
        ucmm.push(0x00);

        // Route Path - THIS IS WHERE [0x01, slot] GOES
        if !route_path_bytes.is_empty() {
            tracing::trace!(
                "Adding route path to Unconnected Send: {:02X?} ({} bytes, {} words)",
                route_path_bytes,
                route_path_bytes.len(),
                route_path_words
            );
            ucmm.extend_from_slice(&route_path_bytes);
        }

        ucmm
    }

    /// Sends a CIP request using EtherNet/IP SendRRData.
    ///
    /// Primary mode uses Unconnected Send (0x52) wrapping. For controllers that reject
    /// this pattern for specific services, a direct-CIP fallback is attempted when:
    /// - the Unconnected Send response is `0xD2` with non-zero general status, and
    /// - no route path is configured (direct mode cannot carry a route path).
    pub async fn send_cip_request(&self, cip_request: &[u8]) -> Result<Vec<u8>> {
        tracing::trace!(
            "Sending CIP request ({} bytes): {:02X?}",
            cip_request.len(),
            cip_request
        );

        // Build Unconnected Send message wrapping the CIP request
        // Route path goes at the END of Unconnected Send, NOT in the CIP request
        let ucmm_message = self.build_unconnected_send(cip_request);

        tracing::trace!(
            "Unconnected Send message ({} bytes): {:02X?}",
            ucmm_message.len(),
            &ucmm_message[..std::cmp::min(64, ucmm_message.len())]
        );

        let response_data = self.send_rr_data_item(&ucmm_message).await?;

        if let Ok(raw_cip_data) = self.extract_unconnected_data_item(&response_data) {
            let use_direct_fallback = raw_cip_data.len() >= 3
                && raw_cip_data[0] == 0xD2
                && raw_cip_data[2] != 0x00
                && self.route_path.is_none();

            if use_direct_fallback {
                tracing::warn!(
                    "Unconnected Send returned 0xD2 status 0x{:02X}; retrying with direct CIP SendRRData fallback",
                    raw_cip_data[2]
                );
                return self.send_rr_data_item(cip_request).await;
            }
        }

        Ok(response_data)
    }

    async fn send_rr_data_item(&self, item_data: &[u8]) -> Result<Vec<u8>> {
        // Calculate total packet size
        let item_data_size = item_data.len();
        let total_data_len = 4 + 2 + 2 + 8 + item_data_size; // Interface + Timeout + Count + Items + Data

        let mut packet = Vec::new();

        // EtherNet/IP header (24 bytes)
        packet.extend_from_slice(&[0x6F, 0x00]); // Command: Send RR Data (0x006F)
        packet.extend_from_slice(&(total_data_len as u16).to_le_bytes()); // Length
        packet.extend_from_slice(&self.session_handle.to_le_bytes()); // Session handle
        packet.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Status
        packet.extend_from_slice(&[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]); // Context
        packet.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Options

        // CPF (Common Packet Format) data
        packet.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Interface handle
        packet.extend_from_slice(&[0x05, 0x00]); // Timeout (5 seconds)
        packet.extend_from_slice(&[0x02, 0x00]); // Item count: 2

        // Item 1: Null Address Item (0x0000)
        packet.extend_from_slice(&[0x00, 0x00]); // Type: Null Address
        packet.extend_from_slice(&[0x00, 0x00]); // Length: 0

        // Item 2: Unconnected Data Item (0x00B2)
        packet.extend_from_slice(&[0xB2, 0x00]); // Type: Unconnected Data
        packet.extend_from_slice(&(item_data_size as u16).to_le_bytes()); // Length
        packet.extend_from_slice(item_data);

        tracing::trace!(
            "Built packet ({} bytes): {:02X?}",
            packet.len(),
            &packet[..std::cmp::min(64, packet.len())]
        );

        // Send packet with timeout
        let mut stream = self.stream.lock().await;
        stream
            .write_all(&packet)
            .await
            .map_err(EtherNetIpError::Io)?;

        // Read response header with timeout
        let mut header = [0u8; 24];
        match timeout(Duration::from_secs(10), stream.read_exact(&mut header)).await {
            Ok(Ok(_)) => {}
            Ok(Err(e)) => return Err(EtherNetIpError::Io(e)),
            Err(_) => return Err(EtherNetIpError::Timeout(Duration::from_secs(10))),
        }

        // Check EtherNet/IP command status
        let cmd_status = u32::from_le_bytes([header[8], header[9], header[10], header[11]]);
        if cmd_status != 0 {
            return Err(EtherNetIpError::Protocol(format!(
                "EIP Command failed. Status: 0x{cmd_status:08X}"
            )));
        }

        // Parse response length
        let response_length = u16::from_le_bytes([header[2], header[3]]) as usize;
        if response_length == 0 {
            return Ok(Vec::new());
        }

        // Read response data with timeout
        let mut response_data = vec![0u8; response_length];
        match timeout(
            Duration::from_secs(10),
            stream.read_exact(&mut response_data),
        )
        .await
        {
            Ok(Ok(_)) => {}
            Ok(Err(e)) => return Err(EtherNetIpError::Io(e)),
            Err(_) => return Err(EtherNetIpError::Timeout(Duration::from_secs(10))),
        }

        // Update last activity time
        *self.last_activity.lock().await = Instant::now();

        tracing::trace!(
            "Received response ({} bytes): {:02X?}",
            response_data.len(),
            &response_data[..std::cmp::min(32, response_data.len())]
        );

        Ok(response_data)
    }

    fn extract_unconnected_data_item(&self, response: &[u8]) -> crate::error::Result<Vec<u8>> {
        // Parse CPF (Common Packet Format) structure directly from response data
        // Response format: [Interface(4)] [Timeout(2)] [ItemCount(2)] [Items...]
        if response.len() < 8 {
            return Err(EtherNetIpError::Protocol(
                "Response too short for CPF header".to_string(),
            ));
        }

        // Skip interface handle (4 bytes) and timeout (2 bytes)
        let mut pos = 6;
        let item_count = u16::from_le_bytes([response[pos], response[pos + 1]]);
        pos += 2;

        for _ in 0..item_count {
            if pos + 4 > response.len() {
                return Err(EtherNetIpError::Protocol(
                    "Response truncated while parsing items".to_string(),
                ));
            }

            let item_type = u16::from_le_bytes([response[pos], response[pos + 1]]);
            let item_length = u16::from_le_bytes([response[pos + 2], response[pos + 3]]) as usize;
            pos += 4;

            if pos
                .checked_add(item_length)
                .map_or(true, |end| end > response.len())
            {
                return Err(EtherNetIpError::Protocol("Data item truncated".to_string()));
            }

            if item_type == 0x00B2 {
                return Ok(response[pos..pos + item_length].to_vec());
            }

            pos += item_length;
        }

        Err(EtherNetIpError::Protocol(
            "No Unconnected Data Item (0x00B2) found in response".to_string(),
        ))
    }

    fn unwrap_unconnected_send_reply(&self, cip_data: &[u8]) -> crate::error::Result<Vec<u8>> {
        if cip_data.is_empty() || cip_data[0] != 0xD2 {
            return Ok(cip_data.to_vec());
        }

        if cip_data.len() < 4 {
            return Err(EtherNetIpError::Protocol(
                "Unconnected Send reply too short".to_string(),
            ));
        }

        let general_status = cip_data[2];
        let additional_status_words = cip_data[3] as usize;
        let embedded_offset = 4 + (additional_status_words * 2);

        if general_status != 0x00 {
            let error_msg = self.get_cip_error_message(general_status);
            return Err(EtherNetIpError::Protocol(format!(
                "Unconnected Send failed (0xD2): CIP Error 0x{general_status:02X}: {error_msg}"
            )));
        }

        if embedded_offset >= cip_data.len() {
            return Err(EtherNetIpError::Protocol(
                "Unconnected Send succeeded but no embedded response payload was returned"
                    .to_string(),
            ));
        }

        Ok(cip_data[embedded_offset..].to_vec())
    }

    /// Extracts CIP data from EtherNet/IP response packet
    fn extract_cip_from_response(&self, response: &[u8]) -> crate::error::Result<Vec<u8>> {
        tracing::trace!(
            "Extracting CIP from response ({} bytes): {:02X?}",
            response.len(),
            &response[..std::cmp::min(32, response.len())]
        );
        let cip_data = self.extract_unconnected_data_item(response)?;
        tracing::trace!(
            "Found Unconnected Data Item, extracted CIP data ({} bytes)",
            cip_data.len()
        );
        tracing::trace!(
            "CIP data bytes: {:02X?}",
            &cip_data[..std::cmp::min(16, cip_data.len())]
        );
        self.unwrap_unconnected_send_reply(&cip_data)
    }

    /// Parses CIP response and converts to `PlcValue`
    fn parse_cip_response(&self, cip_response: &[u8]) -> crate::error::Result<PlcValue> {
        tracing::trace!(
            "Parsing CIP response ({} bytes): {:02X?}",
            cip_response.len(),
            cip_response
        );

        if cip_response.len() < 4 {
            return Err(EtherNetIpError::Protocol(
                "CIP response too short".to_string(),
            ));
        }

        let service_reply = cip_response[0]; // Should be 0xCC (0x4C + 0x80) for Read Tag reply
        let general_status = cip_response[2]; // CIP status code

        tracing::trace!(
            "Service reply: 0x{:02X}, Status: 0x{:02X}",
            service_reply,
            general_status
        );

        // Check for CIP errors (including extended errors)
        if let Err(e) = self.check_cip_error(cip_response) {
            tracing::error!("CIP Error: {}", e);
            return Err(e);
        }

        // For read operations, parse the returned data
        if service_reply == 0xCC {
            // Read Tag reply
            if cip_response.len() < 6 {
                return Err(EtherNetIpError::Protocol(
                    "Read response too short for data".to_string(),
                ));
            }

            let data_type = u16::from_le_bytes([cip_response[4], cip_response[5]]);
            let value_data = &cip_response[6..];

            tracing::trace!(
                "Data type: 0x{:04X}, Value data ({} bytes): {:02X?}",
                data_type,
                value_data.len(),
                value_data
            );

            // Parse based on data type
            match data_type {
                0x00C1 => {
                    // BOOL
                    if value_data.is_empty() {
                        return Err(EtherNetIpError::Protocol(
                            "No data for BOOL value".to_string(),
                        ));
                    }
                    let value = value_data[0] != 0;
                    tracing::trace!("Parsed BOOL: {}", value);
                    Ok(PlcValue::Bool(value))
                }
                0x00C2 => {
                    // SINT
                    if value_data.is_empty() {
                        return Err(EtherNetIpError::Protocol(
                            "No data for SINT value".to_string(),
                        ));
                    }
                    let value = value_data[0] as i8;
                    tracing::trace!("Parsed SINT: {}", value);
                    Ok(PlcValue::Sint(value))
                }
                0x00C3 => {
                    // INT
                    if value_data.len() < 2 {
                        return Err(EtherNetIpError::Protocol(
                            "Insufficient data for INT value".to_string(),
                        ));
                    }
                    let value = i16::from_le_bytes([value_data[0], value_data[1]]);
                    tracing::trace!("Parsed INT: {}", value);
                    Ok(PlcValue::Int(value))
                }
                0x00C4 => {
                    // DINT
                    if value_data.len() < 4 {
                        return Err(EtherNetIpError::Protocol(
                            "Insufficient data for DINT value".to_string(),
                        ));
                    }
                    let value = i32::from_le_bytes([
                        value_data[0],
                        value_data[1],
                        value_data[2],
                        value_data[3],
                    ]);
                    tracing::trace!("Parsed DINT: {}", value);
                    Ok(PlcValue::Dint(value))
                }
                0x00C5 => {
                    // LINT (64-bit signed integer)
                    if value_data.len() < 8 {
                        return Err(EtherNetIpError::Protocol(
                            "Insufficient data for LINT value".to_string(),
                        ));
                    }
                    let value = i64::from_le_bytes([
                        value_data[0],
                        value_data[1],
                        value_data[2],
                        value_data[3],
                        value_data[4],
                        value_data[5],
                        value_data[6],
                        value_data[7],
                    ]);
                    tracing::trace!("Parsed LINT: {}", value);
                    Ok(PlcValue::Lint(value))
                }
                0x00C6 => {
                    // USINT (8-bit unsigned integer)
                    if value_data.is_empty() {
                        return Err(EtherNetIpError::Protocol(
                            "No data for USINT value".to_string(),
                        ));
                    }
                    let value = value_data[0];
                    tracing::trace!("Parsed USINT: {}", value);
                    Ok(PlcValue::Usint(value))
                }
                0x00C7 => {
                    // UINT (16-bit unsigned integer)
                    if value_data.len() < 2 {
                        return Err(EtherNetIpError::Protocol(
                            "Insufficient data for UINT value".to_string(),
                        ));
                    }
                    let value = u16::from_le_bytes([value_data[0], value_data[1]]);
                    tracing::trace!("Parsed UINT: {}", value);
                    Ok(PlcValue::Uint(value))
                }
                0x00C8 => {
                    // UDINT (32-bit unsigned integer)
                    if value_data.len() < 4 {
                        return Err(EtherNetIpError::Protocol(
                            "Insufficient data for UDINT value".to_string(),
                        ));
                    }
                    let value = u32::from_le_bytes([
                        value_data[0],
                        value_data[1],
                        value_data[2],
                        value_data[3],
                    ]);
                    tracing::trace!("Parsed UDINT: {}", value);
                    Ok(PlcValue::Udint(value))
                }
                0x00C9 => {
                    // ULINT (64-bit unsigned integer)
                    if value_data.len() < 8 {
                        return Err(EtherNetIpError::Protocol(
                            "Insufficient data for ULINT value".to_string(),
                        ));
                    }
                    let value = u64::from_le_bytes([
                        value_data[0],
                        value_data[1],
                        value_data[2],
                        value_data[3],
                        value_data[4],
                        value_data[5],
                        value_data[6],
                        value_data[7],
                    ]);
                    tracing::trace!("Parsed ULINT: {}", value);
                    Ok(PlcValue::Ulint(value))
                }
                0x00CA => {
                    // REAL
                    if value_data.len() < 4 {
                        return Err(EtherNetIpError::Protocol(
                            "Insufficient data for REAL value".to_string(),
                        ));
                    }
                    let value = f32::from_le_bytes([
                        value_data[0],
                        value_data[1],
                        value_data[2],
                        value_data[3],
                    ]);
                    tracing::trace!("Parsed REAL: {}", value);
                    Ok(PlcValue::Real(value))
                }
                0x00CB => {
                    // LREAL (64-bit float)
                    if value_data.len() < 8 {
                        return Err(EtherNetIpError::Protocol(
                            "Insufficient data for LREAL value".to_string(),
                        ));
                    }
                    let value = f64::from_le_bytes([
                        value_data[0],
                        value_data[1],
                        value_data[2],
                        value_data[3],
                        value_data[4],
                        value_data[5],
                        value_data[6],
                        value_data[7],
                    ]);
                    tracing::trace!("Parsed LREAL: {}", value);
                    Ok(PlcValue::Lreal(value))
                }
                0x00CE => {
                    // Allen-Bradley STRING type (0x00CE)
                    // STRING format: 4-byte length (DINT) followed by string data (up to 82 bytes)
                    if value_data.len() < 4 {
                        return Err(EtherNetIpError::Protocol(
                            "Insufficient data for STRING length field".to_string(),
                        ));
                    }
                    let length = u32::from_le_bytes([
                        value_data[0],
                        value_data[1],
                        value_data[2],
                        value_data[3],
                    ]) as usize;

                    if value_data.len() < 4 || value_data.len() - 4 < length {
                        return Err(EtherNetIpError::Protocol(format!(
                            "Insufficient data for STRING value: need {} bytes, have {} bytes",
                            4 + length,
                            value_data.len()
                        )));
                    }
                    let string_data = &value_data[4..4 + length];
                    let value = String::from_utf8_lossy(string_data).to_string();
                    tracing::trace!(
                        "Parsed STRING (0x00CE): length={}, value='{}'",
                        length,
                        value
                    );
                    Ok(PlcValue::String(value))
                }
                0x00DA => {
                    // Alternative STRING format (0x00DA) - single byte length
                    if value_data.is_empty() {
                        return Ok(PlcValue::String(String::new()));
                    }
                    let length = value_data[0] as usize;
                    if value_data.len() < 1 + length {
                        return Err(EtherNetIpError::Protocol(
                            "Insufficient data for STRING value".to_string(),
                        ));
                    }
                    let string_data = &value_data[1..1 + length];
                    let value = String::from_utf8_lossy(string_data).to_string();
                    tracing::trace!("Parsed STRING (0x00DA): '{}'", value);
                    Ok(PlcValue::String(value))
                }
                0x02A0 => {
                    // Allen-Bradley UDT type (0x02A0)
                    // Note: symbol_id not available in parse_cip_response context
                    // For proper UDT handling with symbol_id, use read_tag() which gets tag attributes
                    tracing::trace!(
                        "Detected UDT structure (0x02A0) with {} bytes",
                        value_data.len()
                    );
                    Ok(PlcValue::Udt(UdtData {
                        symbol_id: 0, // Not available in this context
                        data: value_data.to_vec(),
                    }))
                }
                0x00D3 => {
                    // ULINT (64-bit unsigned integer) - sometimes returned for BOOL arrays
                    // BOOL arrays in Allen-Bradley are stored as DWORD arrays (32 bits per DWORD)
                    // The PLC may return 4 bytes (DWORD) for BOOL arrays
                    if value_data.len() >= 4 {
                        // Parse as DWORD (4 bytes) - BOOL arrays are often returned as DWORD
                        let dword_value = u32::from_le_bytes([
                            value_data[0],
                            value_data[1],
                            value_data[2],
                            value_data[3],
                        ]);
                        tracing::trace!(
                            "Parsed 0x00D3 as DWORD (BOOL array): {} (0x{:08X})",
                            dword_value,
                            dword_value
                        );
                        // Return as UDINT (DWORD) - this represents the first 32 BOOLs
                        Ok(PlcValue::Udint(dword_value))
                    } else if value_data.len() >= 8 {
                        // If we have 8 bytes, parse as ULINT
                        let value = u64::from_le_bytes([
                            value_data[0],
                            value_data[1],
                            value_data[2],
                            value_data[3],
                            value_data[4],
                            value_data[5],
                            value_data[6],
                            value_data[7],
                        ]);
                        tracing::trace!("Parsed ULINT: {}", value);
                        Ok(PlcValue::Ulint(value))
                    } else {
                        Err(EtherNetIpError::Protocol(
                            "Insufficient data for ULINT/DWORD value".to_string(),
                        ))
                    }
                }
                0x00A0 => {
                    // UDT (User Defined Type)
                    // Note: symbol_id will be 0 here since we don't have tag context
                    // For proper UDT handling with symbol_id, use read_tag() which
                    // gets tag attributes first
                    tracing::trace!(
                        "Parsed UDT ({} bytes) - note: symbol_id not available in this context",
                        value_data.len()
                    );
                    Ok(PlcValue::Udt(UdtData {
                        symbol_id: 0, // Will need to be set by caller if available
                        data: value_data.to_vec(),
                    }))
                }
                _ => {
                    tracing::warn!("Unknown data type: 0x{:04X}", data_type);
                    Err(EtherNetIpError::Protocol(format!(
                        "Unsupported data type: 0x{data_type:04X}"
                    )))
                }
            }
        } else if service_reply == 0xCD {
            // Write Tag reply - no data to parse
            tracing::debug!("Write operation successful");
            Ok(PlcValue::Bool(true)) // Indicate success
        } else {
            Err(EtherNetIpError::Protocol(format!(
                "Unknown service reply: 0x{service_reply:02X}"
            )))
        }
    }

    /// Unregisters the EtherNet/IP session with the PLC
    pub async fn unregister_session(&mut self) -> crate::error::Result<()> {
        tracing::info!("Unregistering session and cleaning up connections...");

        // Close all connected sessions first
        let _ = self.close_all_connected_sessions().await;

        let mut packet = Vec::new();

        // EtherNet/IP encapsulation header (24 bytes, no command-specific data)
        packet.extend_from_slice(&[0x66, 0x00]); // Command: Unregister Session
        packet.extend_from_slice(&[0x00, 0x00]); // Length: 0 (no data payload)
        packet.extend_from_slice(&self.session_handle.to_le_bytes()); // Session handle
        packet.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Status
        packet.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); // Sender context
        packet.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Options

        self.stream
            .lock()
            .await
            .write_all(&packet)
            .await
            .map_err(EtherNetIpError::Io)?;

        tracing::info!("Session unregistered and all connections closed");
        Ok(())
    }

    /// Builds a CIP Read Tag Service request
    fn build_read_request(&self, tag_name: &str) -> Vec<u8> {
        self.build_read_request_with_count(tag_name, 1)
    }

    /// Builds a CIP Read Tag Service request with specified element count
    ///
    /// Reference: 1756-PM020, Page 220-252 (Read Tag Service)
    fn build_read_request_with_count(&self, tag_name: &str, element_count: u16) -> Vec<u8> {
        tracing::debug!(
            "Building read request for tag: '{}' with count: {}",
            tag_name,
            element_count
        );

        let mut cip_request = Vec::new();

        // Service: Read Tag Service (0x4C)
        // Reference: 1756-PM020, Page 220
        cip_request.push(0x4C);

        // Build the path based on tag name format
        let path = self.build_tag_path(tag_name);

        // Request Path Size (in words)
        let path_size_words = (path.len() / 2) as u8;
        tracing::debug!(
            "Path size calculation: {} bytes / 2 = {} words for tag '{}'",
            path.len(),
            path_size_words,
            tag_name
        );
        cip_request.push(path_size_words);

        // Request Path
        cip_request.extend_from_slice(&path);

        // Element count (little-endian)
        // Reference: 1756-PM020, Page 241 (Request Data: Number of elements to read)
        cip_request.extend_from_slice(&element_count.to_le_bytes());

        tracing::debug!(
            "Built CIP read request ({} bytes) for tag '{}': {:02X?}",
            cip_request.len(),
            tag_name,
            cip_request
        );
        tracing::debug!(
            "Path bytes ({} bytes, {} words) for tag '{}': {:02X?}",
            path.len(),
            path_size_words,
            tag_name,
            path
        );

        cip_request
    }

    /// Builds an Element ID segment for array element addressing
    ///
    /// Reference: 1756-PM020, Pages 603-611, 870-890 (Element ID Segment Size Selection)
    ///
    /// Element ID segments use different sizes based on index value:
    /// - 0-255: 8-bit Element ID (0x28 + 1 byte value)
    /// - 256-65535: 16-bit Element ID (0x29 0x00 + 2 bytes low, high)
    /// - 65536+: 32-bit Element ID (0x2A 0x00 + 4 bytes lowest to highest)
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn build_element_id_segment(&self, index: u32) -> Vec<u8> {
        let mut segment = Vec::new();

        if index <= 255 {
            // 8-bit Element ID: 0x28 + index (2 bytes total)
            // Reference: 1756-PM020, Page 607, Example 1
            segment.push(0x28);
            segment.push(index as u8);
        } else if index <= 65535 {
            // 16-bit Element ID: 0x29, 0x00, low_byte, high_byte (4 bytes total)
            // Reference: 1756-PM020, Page 666-684, Example 3
            segment.push(0x29);
            segment.push(0x00); // Padding byte
            segment.extend_from_slice(&(index as u16).to_le_bytes());
        } else {
            // 32-bit Element ID: 0x2A, 0x00, byte0, byte1, byte2, byte3 (6 bytes total)
            // Reference: 1756-PM020, Page 144-146 (Element ID Segments table)
            segment.push(0x2A);
            segment.push(0x00); // Padding byte
            segment.extend_from_slice(&index.to_le_bytes());
        }

        segment
    }

    /// Builds base tag path without array element addressing
    ///
    /// Extracts the base tag name from array notation (e.g., "MyArray[5]" -> "MyArray")
    /// Reference: 1756-PM020, Page 894-909 (ANSI Extended Symbol Segment Construction)
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn build_base_tag_path(&self, tag_name: &str) -> Vec<u8> {
        // Parse tag path but strip array indices
        match TagPath::parse(tag_name) {
            Ok(path) => {
                // If it's an array path, get just the base
                let base_path = match &path {
                    TagPath::Array { base_path, .. } => base_path.as_ref(),
                    _ => &path,
                };
                base_path.to_cip_path().unwrap_or_else(|_| {
                    // Fallback: simple symbol segment
                    // Reference: 1756-PM020, Page 894-909
                    let mut path = Vec::new();
                    path.push(0x91); // ANSI Extended Symbol Segment
                    let name_bytes = tag_name.as_bytes();
                    path.push(name_bytes.len() as u8);
                    path.extend_from_slice(name_bytes);
                    // Pad to word boundary if odd length
                    if path.len() % 2 != 0 {
                        path.push(0x00);
                    }
                    path
                })
            }
            Err(_) => {
                // Fallback: simple symbol segment
                let mut path = Vec::new();
                path.push(0x91); // ANSI Extended Symbol Segment
                let name_bytes = tag_name.as_bytes();
                path.push(name_bytes.len() as u8);
                path.extend_from_slice(name_bytes);
                // Pad to word boundary if odd length
                if path.len() % 2 != 0 {
                    path.push(0x00);
                }
                path
            }
        }
    }

    /// Builds a CIP Read Tag Service request for array elements with element addressing
    ///
    /// This method uses proper CIP element addressing (0x28/0x29/0x2A segments) in the
    /// Request Path to read specific array elements or ranges.
    ///
    /// Reference: 1756-PM020, Pages 603-611, 815-851 (Array Element Addressing Examples)
    ///
    /// # Arguments
    ///
    /// * `base_array_name` - Base name of the array (e.g., "MyArray" for "MyArray[10]")
    /// * `start_index` - Starting element index (0-based)
    /// * `element_count` - Number of elements to read
    ///
    /// # Example
    ///
    /// Reading elements 10-14 of array "MyArray" (5 elements):
    /// ```
    /// # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// # let mut client = rust_ethernet_ip::EipClient::connect("192.168.1.100:44818").await?;
    /// let request = client.build_read_array_request("MyArray", 10, 5);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// This generates:
    /// - Request Path: [0x91] "MyArray" [0x28] [0x0A] (element 10)
    /// - Request Data: [0x05 0x00] (5 elements)
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn build_read_array_request(
        &self,
        base_array_name: &str,
        start_index: u32,
        element_count: u16,
    ) -> Vec<u8> {
        let mut cip_request = Vec::new();

        // Service: Read Tag Service (0x4C)
        // Reference: 1756-PM020, Page 220
        cip_request.push(0x4C);

        // Build base tag path (symbolic segment)
        // Reference: 1756-PM020, Page 894-909
        // NOTE: Route path does NOT go here - it goes at the end of Unconnected Send message
        // Reference: EtherNetIP_Connection_Paths_and_Routing.md
        let mut full_path = self.build_base_tag_path(base_array_name);

        tracing::trace!(
            "build_read_array_request: base_path for '{}' = {:02X?} ({} bytes)",
            base_array_name,
            full_path,
            full_path.len()
        );

        // Add element addressing segment
        // Reference: 1756-PM020, Pages 603-611, 870-890
        let element_segment = self.build_element_id_segment(start_index);
        tracing::trace!(
            "build_read_array_request: element_segment for index {} = {:02X?} ({} bytes)",
            start_index,
            element_segment,
            element_segment.len()
        );
        full_path.extend_from_slice(&element_segment);

        // Ensure path is word-aligned
        if full_path.len() % 2 != 0 {
            full_path.push(0x00);
        }

        // Path size (in words)
        let path_size = (full_path.len() / 2) as u8;
        cip_request.push(path_size);
        cip_request.extend_from_slice(&full_path);

        // Request Data: Element count (NOT in path, but in Request Data)
        // Reference: 1756-PM020, Page 840-851 (Reading Multiple Array Elements)
        cip_request.extend_from_slice(&element_count.to_le_bytes());

        tracing::trace!(
            "build_read_array_request: final request = {:02X?} ({} bytes), path_size = {} words ({} bytes)",
            cip_request, cip_request.len(), path_size, full_path.len()
        );

        cip_request
    }

    /// Builds the correct path for a tag name
    /// Uses TagPath parser to properly handle arrays, bits, UDTs, etc.
    ///
    /// For ControlLogix, prepends the route path (backplane routing) if configured.
    /// Reference: EtherNetIP_Connection_Paths_and_Routing.md
    fn build_tag_path(&self, tag_name: &str) -> Vec<u8> {
        // Build the application path (tag name)
        // NOTE: Route path does NOT go here - it goes at the end of Unconnected Send message
        // Reference: EtherNetIP_Connection_Paths_and_Routing.md
        let app_path = match TagPath::parse(tag_name) {
            Ok(tag_path) => {
                tracing::debug!("Parsed tag path for '{}': {:?}", tag_name, tag_path);
                // Generate CIP path using the proper parser
                match tag_path.to_cip_path() {
                    Ok(path) => {
                        tracing::debug!(
                            "TagPath generated {} bytes ({} words) for '{}': {:02X?}",
                            path.len(),
                            path.len() / 2,
                            tag_name,
                            path
                        );
                        path
                    }
                    Err(e) => {
                        tracing::warn!("TagPath.to_cip_path() failed for '{}': {}", tag_name, e);
                        // Fallback to old method if parsing fails
                        self.build_simple_tag_path_legacy(tag_name)
                    }
                }
            }
            Err(e) => {
                tracing::warn!("TagPath::parse() failed for '{}': {}", tag_name, e);
                // Fallback to old method if parsing fails
                self.build_simple_tag_path_legacy(tag_name)
            }
        };

        app_path
    }

    /// Builds a simple tag path (no program prefix) - legacy method for fallback
    fn build_simple_tag_path_legacy(&self, tag_name: &str) -> Vec<u8> {
        let mut path = Vec::new();
        path.push(0x91); // ANSI Extended Symbol Segment
        path.push(tag_name.len() as u8);
        path.extend_from_slice(tag_name.as_bytes());

        // Pad to even length if necessary
        if tag_name.len() % 2 != 0 {
            path.push(0x00);
        }

        path
    }

    // =========================================================================
    // BATCH OPERATIONS IMPLEMENTATION
    // =========================================================================

    /// Executes a batch of read and write operations
    ///
    /// This is the main entry point for batch operations. It takes a slice of
    /// `BatchOperation` items and executes them efficiently by grouping them
    /// into optimal CIP packets based on the current `BatchConfig`.
    ///
    /// # Arguments
    ///
    /// * `operations` - A slice of operations to execute
    ///
    /// # Returns
    ///
    /// A vector of `BatchResult` items, one for each input operation.
    /// Results are returned in the same order as the input operations.
    ///
    /// # Performance
    ///
    /// - **Throughput**: 5,000-15,000+ operations/second (vs 1,500 individual)
    /// - **Latency**: 5-20ms per batch (vs 1-3ms per individual operation)
    /// - **Network efficiency**: 1-5 packets vs N packets for N operations
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use rust_ethernet_ip::{EipClient, BatchOperation, PlcValue};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    ///     let mut client = EipClient::connect("192.168.1.100:44818").await?;
    ///
    ///     let operations = vec![
    ///         BatchOperation::Read { tag_name: "Motor1_Speed".to_string() },
    ///         BatchOperation::Read { tag_name: "Motor2_Speed".to_string() },
    ///         BatchOperation::Write {
    ///             tag_name: "SetPoint".to_string(),
    ///             value: PlcValue::Dint(1500)
    ///         },
    ///     ];
    ///
    ///     let results = client.execute_batch(&operations).await?;
    ///
    ///     for result in results {
    ///         match result.result {
    ///             Ok(Some(value)) => println!("Read value: {:?}", value),
    ///             Ok(None) => println!("Write successful"),
    ///             Err(e) => println!("Operation failed: {}", e),
    ///         }
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn execute_batch(
        &mut self,
        operations: &[BatchOperation],
    ) -> crate::error::Result<Vec<BatchResult>> {
        if operations.is_empty() {
            return Ok(Vec::new());
        }

        let start_time = Instant::now();
        tracing::debug!(
            "[BATCH] Starting batch execution with {} operations",
            operations.len()
        );

        // Group operations based on configuration
        let operation_groups = if self.batch_config.optimize_packet_packing {
            self.optimize_operation_groups(operations)
        } else {
            self.sequential_operation_groups(operations)
        };

        let mut all_results = Vec::with_capacity(operations.len());

        // Execute each group
        for (group_index, group) in operation_groups.iter().enumerate() {
            tracing::debug!(
                "[BATCH] Processing group {} with {} operations",
                group_index + 1,
                group.len()
            );

            match self.execute_operation_group(group).await {
                Ok(mut group_results) => {
                    all_results.append(&mut group_results);
                }
                Err(e) => {
                    if !self.batch_config.continue_on_error {
                        return Err(e);
                    }

                    // Create error results for this group
                    for op in group {
                        let error_result = BatchResult {
                            operation: op.clone(),
                            result: Err(BatchError::NetworkError(e.to_string())),
                            execution_time_us: 0,
                        };
                        all_results.push(error_result);
                    }
                }
            }
        }

        let total_time = start_time.elapsed();
        tracing::info!(
            "[BATCH] Completed batch execution in {:?} - {} operations processed",
            total_time,
            all_results.len()
        );

        Ok(all_results)
    }

    /// Reads multiple tags in a single batch operation
    ///
    /// This is a convenience method for read-only batch operations.
    /// It's optimized for reading many tags at once.
    ///
    /// # Arguments
    ///
    /// * `tag_names` - A slice of tag names to read
    ///
    /// # Returns
    ///
    /// A vector of tuples containing `(tag_name, result)` pairs
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use rust_ethernet_ip::EipClient;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    ///     let mut client = EipClient::connect("192.168.1.100:44818").await?;
    ///
    ///     let tags = ["Motor1_Speed", "Motor2_Speed", "Temperature", "Pressure"];
    ///     let results = client.read_tags_batch(&tags).await?;
    ///
    ///     for (tag_name, result) in results {
    ///         match result {
    ///             Ok(value) => println!("{}: {:?}", tag_name, value),
    ///             Err(e) => println!("{}: Error - {}", tag_name, e),
    ///         }
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn read_tags_batch(
        &mut self,
        tag_names: &[&str],
    ) -> crate::error::Result<Vec<(String, std::result::Result<PlcValue, BatchError>)>> {
        let operations: Vec<BatchOperation> = tag_names
            .iter()
            .map(|&name| BatchOperation::Read {
                tag_name: name.to_string(),
            })
            .collect();

        let results = self.execute_batch(&operations).await?;

        Ok(results
            .into_iter()
            .map(|result| {
                let tag_name = match &result.operation {
                    BatchOperation::Read { tag_name } => tag_name.clone(),
                    BatchOperation::Write { .. } => {
                        unreachable!("Should only have read operations")
                    }
                };

                let value_result = match result.result {
                    Ok(Some(value)) => Ok(value),
                    Ok(None) => Err(BatchError::Other(
                        "Unexpected None result for read operation".to_string(),
                    )),
                    Err(e) => Err(e),
                };

                (tag_name, value_result)
            })
            .collect())
    }

    /// Writes multiple tag values in a single batch operation
    ///
    /// This is a convenience method for write-only batch operations.
    /// It's optimized for writing many values at once.
    ///
    /// # Arguments
    ///
    /// * `tag_values` - A slice of `(tag_name, value)` tuples to write
    ///
    /// # Returns
    ///
    /// A vector of tuples containing `(tag_name, result)` pairs
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use rust_ethernet_ip::{EipClient, PlcValue};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    ///     let mut client = EipClient::connect("192.168.1.100:44818").await?;
    ///
    ///     let writes = vec![
    ///         ("SetPoint1", PlcValue::Bool(true)),
    ///         ("SetPoint2", PlcValue::Dint(2000)),
    ///         ("EnableFlag", PlcValue::Bool(true)),
    ///     ];
    ///
    ///     let results = client.write_tags_batch(&writes).await?;
    ///
    ///     for (tag_name, result) in results {
    ///         match result {
    ///             Ok(_) => println!("{}: Write successful", tag_name),
    ///             Err(e) => println!("{}: Write failed - {}", tag_name, e),
    ///         }
    ///     }
    ///
    ///     Ok(())
    /// }
    /// ```
    pub async fn write_tags_batch(
        &mut self,
        tag_values: &[(&str, PlcValue)],
    ) -> crate::error::Result<Vec<(String, std::result::Result<(), BatchError>)>> {
        let operations: Vec<BatchOperation> = tag_values
            .iter()
            .map(|(name, value)| BatchOperation::Write {
                tag_name: name.to_string(),
                value: value.clone(),
            })
            .collect();

        let results = self.execute_batch(&operations).await?;

        Ok(results
            .into_iter()
            .map(|result| {
                let tag_name = match &result.operation {
                    BatchOperation::Write { tag_name, .. } => tag_name.clone(),
                    BatchOperation::Read { .. } => {
                        unreachable!("Should only have write operations")
                    }
                };

                let write_result = match result.result {
                    Ok(None) => Ok(()),
                    Ok(Some(_)) => Err(BatchError::Other(
                        "Unexpected value result for write operation".to_string(),
                    )),
                    Err(e) => Err(e),
                };

                (tag_name, write_result)
            })
            .collect())
    }

    /// Configures batch operation settings
    ///
    /// This method allows fine-tuning of batch operation behavior,
    /// including performance optimizations and error handling.
    ///
    /// # Arguments
    ///
    /// * `config` - The new batch configuration to use
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use rust_ethernet_ip::{EipClient, BatchConfig};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    ///     let mut client = EipClient::connect("192.168.1.100:44818").await?;
    ///
    ///     let config = BatchConfig {
    ///         max_operations_per_packet: 50,
    ///         max_packet_size: 1500,
    ///         packet_timeout_ms: 5000,
    ///         continue_on_error: false,
    ///         optimize_packet_packing: true,
    ///     };
    ///
    ///     client.configure_batch_operations(config);
    ///
    ///     Ok(())
    /// }
    /// ```
    pub fn configure_batch_operations(&mut self, config: BatchConfig) {
        self.batch_config = config;
        tracing::debug!(
            "[BATCH] Updated batch configuration: max_ops={}, max_size={}, timeout={}ms",
            self.batch_config.max_operations_per_packet,
            self.batch_config.max_packet_size,
            self.batch_config.packet_timeout_ms
        );
    }

    /// Gets current batch operation configuration
    pub fn get_batch_config(&self) -> &BatchConfig {
        &self.batch_config
    }

    // =========================================================================
    // INTERNAL BATCH OPERATION HELPERS
    // =========================================================================

    /// Groups operations optimally for batch processing
    fn optimize_operation_groups(&self, operations: &[BatchOperation]) -> Vec<Vec<BatchOperation>> {
        let mut groups = Vec::new();
        let mut reads = Vec::new();
        let mut writes = Vec::new();

        // Separate reads and writes
        for op in operations {
            match op {
                BatchOperation::Read { .. } => reads.push(op.clone()),
                BatchOperation::Write { .. } => writes.push(op.clone()),
            }
        }

        // Group reads
        for chunk in reads.chunks(self.batch_config.max_operations_per_packet) {
            groups.push(chunk.to_vec());
        }

        // Group writes
        for chunk in writes.chunks(self.batch_config.max_operations_per_packet) {
            groups.push(chunk.to_vec());
        }

        groups
    }

    /// Groups operations sequentially (preserves order)
    fn sequential_operation_groups(
        &self,
        operations: &[BatchOperation],
    ) -> Vec<Vec<BatchOperation>> {
        operations
            .chunks(self.batch_config.max_operations_per_packet)
            .map(|chunk| chunk.to_vec())
            .collect()
    }

    /// Executes a single group of operations as a CIP Multiple Service Packet
    async fn execute_operation_group(
        &mut self,
        operations: &[BatchOperation],
    ) -> crate::error::Result<Vec<BatchResult>> {
        let start_time = Instant::now();
        let mut results = Vec::with_capacity(operations.len());

        // Build Multiple Service Packet request
        let cip_request = self.build_multiple_service_packet(operations)?;

        // Send request and get response
        let response = self.send_cip_request(&cip_request).await?;

        // Parse response and create results
        let parsed_results = self.parse_multiple_service_response(&response, operations)?;

        let execution_time = start_time.elapsed();

        // Create BatchResult objects
        for (i, operation) in operations.iter().enumerate() {
            let op_execution_time = execution_time.as_micros() as u64 / operations.len() as u64;

            let result = if i < parsed_results.len() {
                match &parsed_results[i] {
                    Ok(value) => Ok(value.clone()),
                    Err(e) => Err(e.clone()),
                }
            } else {
                Err(BatchError::Other(
                    "Missing result from response".to_string(),
                ))
            };

            results.push(BatchResult {
                operation: operation.clone(),
                result,
                execution_time_us: op_execution_time,
            });
        }

        Ok(results)
    }

    /// Builds a CIP Multiple Service Packet request
    fn build_multiple_service_packet(
        &self,
        operations: &[BatchOperation],
    ) -> crate::error::Result<Vec<u8>> {
        let mut packet = Vec::with_capacity(8 + (operations.len() * 2));

        // Multiple Service Packet service code
        packet.push(0x0A);

        // Request path (2 bytes for class 0x02, instance 1)
        packet.push(0x02); // Path size in words
        packet.push(0x20); // Class segment
        packet.push(0x02); // Class 0x02 (Message Router)
        packet.push(0x24); // Instance segment
        packet.push(0x01); // Instance 1

        // Number of services
        packet.extend_from_slice(&(operations.len() as u16).to_le_bytes());

        // Calculate offset table
        let mut service_requests = Vec::with_capacity(operations.len());
        let mut current_offset = 2 + (operations.len() * 2); // Start after offset table

        for operation in operations {
            // Build individual service request
            let service_request = match operation {
                BatchOperation::Read { tag_name } => self.build_read_request(tag_name),
                BatchOperation::Write { tag_name, value } => {
                    self.build_write_request(tag_name, value)?
                }
            };

            service_requests.push(service_request);
        }

        // Add offset table
        for service_request in &service_requests {
            packet.extend_from_slice(&(current_offset as u16).to_le_bytes());
            current_offset += service_request.len();
        }

        // Add service requests
        for service_request in service_requests {
            packet.extend_from_slice(&service_request);
        }

        tracing::trace!(
            "[BATCH] Built Multiple Service Packet ({} bytes, {} services)",
            packet.len(),
            operations.len()
        );

        Ok(packet)
    }

    /// Parses a Multiple Service Packet response
    fn parse_multiple_service_response(
        &self,
        response: &[u8],
        operations: &[BatchOperation],
    ) -> crate::error::Result<Vec<std::result::Result<Option<PlcValue>, BatchError>>> {
        if response.len() < 6 {
            return Err(crate::error::EtherNetIpError::Protocol(
                "Response too short for Multiple Service Packet".to_string(),
            ));
        }

        let mut results = Vec::new();

        tracing::trace!(
            "Raw Multiple Service Response ({} bytes): {:02X?}",
            response.len(),
            response
        );

        // First, extract the CIP data from the EtherNet/IP response
        let cip_data = match self.extract_cip_from_response(response) {
            Ok(data) => data,
            Err(e) => {
                tracing::error!("Failed to extract CIP data: {}", e);
                return Err(e);
            }
        };

        tracing::trace!(
            "Extracted CIP data ({} bytes): {:02X?}",
            cip_data.len(),
            cip_data
        );

        if cip_data.len() < 6 {
            return Err(crate::error::EtherNetIpError::Protocol(
                "CIP data too short for Multiple Service Response".to_string(),
            ));
        }

        // Parse Multiple Service Response header from CIP data:
        // [0] = Service Code (0x8A)
        // [1] = Reserved (0x00)
        // [2] = General Status (0x00 for success)
        // [3] = Additional Status Size (0x00)
        // [4-5] = Number of replies (little endian)

        let service_code = cip_data[0];
        let general_status = cip_data[2];
        let num_replies = u16::from_le_bytes([cip_data[4], cip_data[5]]) as usize;

        tracing::debug!(
            "Multiple Service Response: service=0x{:02X}, status=0x{:02X}, replies={}",
            service_code,
            general_status,
            num_replies
        );

        if general_status != 0x00 {
            return Err(crate::error::EtherNetIpError::Protocol(
                self.describe_multiple_service_error(general_status, operations),
            ));
        }

        if num_replies != operations.len() {
            return Err(crate::error::EtherNetIpError::Protocol(format!(
                "Reply count mismatch: expected {}, got {}",
                operations.len(),
                num_replies
            )));
        }

        // Read reply offsets (each is 2 bytes, little endian)
        let mut reply_offsets = Vec::new();
        let mut offset = 6; // Skip header

        for _i in 0..num_replies {
            if offset + 2 > cip_data.len() {
                return Err(crate::error::EtherNetIpError::Protocol(
                    "CIP data too short for reply offsets".to_string(),
                ));
            }
            let reply_offset =
                u16::from_le_bytes([cip_data[offset], cip_data[offset + 1]]) as usize;
            reply_offsets.push(reply_offset);
            offset += 2;
        }

        tracing::trace!("Reply offsets: {:?}", reply_offsets);

        // The reply data starts after all the offsets
        let reply_base_offset = 6 + (num_replies * 2);

        tracing::trace!("Reply base offset: {}", reply_base_offset);

        // Parse each reply
        for (i, &reply_offset) in reply_offsets.iter().enumerate() {
            // Reply offset is relative to position 4 (after service code, reserved, status, additional status size)
            let reply_start = 4 + reply_offset;

            if reply_start >= cip_data.len() {
                results.push(Err(BatchError::Other(
                    "Reply offset beyond CIP data".to_string(),
                )));
                continue;
            }

            // Calculate reply end position
            let reply_end = if i + 1 < reply_offsets.len() {
                // Not the last reply - use next reply's offset as boundary
                4 + reply_offsets[i + 1]
            } else {
                // Last reply - goes to end of CIP data
                cip_data.len()
            };

            if reply_end > cip_data.len() || reply_start >= reply_end {
                results.push(Err(BatchError::Other(
                    "Invalid reply boundaries".to_string(),
                )));
                continue;
            }

            let reply_data = &cip_data[reply_start..reply_end];

            tracing::trace!(
                "Reply {} at offset {}: start={}, end={}, len={}",
                i,
                reply_offset,
                reply_start,
                reply_end,
                reply_data.len()
            );
            tracing::trace!("Reply {} data: {:02X?}", i, reply_data);

            let result = self.parse_individual_reply(reply_data, &operations[i]);
            results.push(result);
        }

        Ok(results)
    }

    /// Parses an individual service reply within a Multiple Service Packet response
    fn parse_individual_reply(
        &self,
        reply_data: &[u8],
        operation: &BatchOperation,
    ) -> std::result::Result<Option<PlcValue>, BatchError> {
        if reply_data.len() < 4 {
            return Err(BatchError::SerializationError(
                "Reply too short".to_string(),
            ));
        }

        tracing::trace!(
            "Parsing individual reply ({} bytes): {:02X?}",
            reply_data.len(),
            reply_data
        );

        // Each individual reply in Multiple Service Response has the same format as standalone CIP response:
        // [0] = Service Code (0xCC for read response, 0xCD for write response)
        // [1] = Reserved (0x00)
        // [2] = General Status (0x00 for success)
        // [3] = Additional Status Size (0x00)
        // [4..] = Response data (for reads) or empty (for writes)

        let service_code = reply_data[0];
        let general_status = reply_data[2];

        tracing::trace!(
            "Service code: 0x{:02X}, Status: 0x{:02X}",
            service_code,
            general_status
        );

        if general_status != 0x00 {
            let error_msg = self.get_cip_error_message(general_status);
            return Err(BatchError::CipError {
                status: general_status,
                message: error_msg,
            });
        }

        match operation {
            BatchOperation::Write { .. } => {
                // Write operations return no data on success
                Ok(None)
            }
            BatchOperation::Read { .. } => {
                // Read operations return data starting at offset 4
                if reply_data.len() < 6 {
                    return Err(BatchError::SerializationError(
                        "Read reply too short for data".to_string(),
                    ));
                }

                // Parse the data directly (skip the 4-byte header)
                // Data format: [type_low, type_high, value_bytes...]
                let data = &reply_data[4..];
                tracing::trace!("Parsing data ({} bytes): {:02X?}", data.len(), data);

                if data.len() < 2 {
                    return Err(BatchError::SerializationError(
                        "Data too short for type".to_string(),
                    ));
                }

                let data_type = u16::from_le_bytes([data[0], data[1]]);
                let value_data = &data[2..];

                tracing::trace!(
                    "Data type: 0x{:04X}, Value data ({} bytes): {:02X?}",
                    data_type,
                    value_data.len(),
                    value_data
                );

                // Parse based on data type
                match data_type {
                    0x00C1 => {
                        // BOOL
                        if value_data.is_empty() {
                            return Err(BatchError::SerializationError(
                                "Missing BOOL value".to_string(),
                            ));
                        }
                        Ok(Some(PlcValue::Bool(value_data[0] != 0)))
                    }
                    0x00D3 => {
                        // CompactLogix BOOL arrays are often returned as packed DWORDs in batch reads.
                        if value_data.len() < 4 {
                            return Err(BatchError::SerializationError(
                                "Missing packed BOOL array DWORD value".to_string(),
                            ));
                        }

                        let packed_value = u32::from_le_bytes([
                            value_data[0],
                            value_data[1],
                            value_data[2],
                            value_data[3],
                        ]);

                        if let BatchOperation::Read { tag_name } = operation {
                            if let Some((_base_name, index)) =
                                self.parse_array_element_access(tag_name)
                            {
                                let bit_index = (index % 32) as u32;
                                let value = (packed_value >> bit_index) & 1 != 0;
                                tracing::trace!(
                                    "Parsed packed BOOL array element '{}' from DWORD 0x{:08X} using bit {} -> {}",
                                    tag_name,
                                    packed_value,
                                    bit_index,
                                    value
                                );
                                return Ok(Some(PlcValue::Bool(value)));
                            }
                        }

                        tracing::trace!(
                            "Parsed 0x00D3 batch read as UDINT fallback: {} (0x{:08X})",
                            packed_value,
                            packed_value
                        );
                        Ok(Some(PlcValue::Udint(packed_value)))
                    }
                    0x00C2 => {
                        // SINT
                        if value_data.is_empty() {
                            return Err(BatchError::SerializationError(
                                "Missing SINT value".to_string(),
                            ));
                        }
                        Ok(Some(PlcValue::Sint(value_data[0] as i8)))
                    }
                    0x00C3 => {
                        // INT
                        if value_data.len() < 2 {
                            return Err(BatchError::SerializationError(
                                "Missing INT value".to_string(),
                            ));
                        }
                        let value = i16::from_le_bytes([value_data[0], value_data[1]]);
                        Ok(Some(PlcValue::Int(value)))
                    }
                    0x00C4 => {
                        // DINT
                        if value_data.len() < 4 {
                            return Err(BatchError::SerializationError(
                                "Missing DINT value".to_string(),
                            ));
                        }
                        let value = i32::from_le_bytes([
                            value_data[0],
                            value_data[1],
                            value_data[2],
                            value_data[3],
                        ]);
                        tracing::trace!("Parsed DINT: {}", value);
                        Ok(Some(PlcValue::Dint(value)))
                    }
                    0x00C5 => {
                        // LINT
                        if value_data.len() < 8 {
                            return Err(BatchError::SerializationError(
                                "Missing LINT value".to_string(),
                            ));
                        }
                        let value = i64::from_le_bytes([
                            value_data[0],
                            value_data[1],
                            value_data[2],
                            value_data[3],
                            value_data[4],
                            value_data[5],
                            value_data[6],
                            value_data[7],
                        ]);
                        Ok(Some(PlcValue::Lint(value)))
                    }
                    0x00C6 => {
                        // USINT
                        if value_data.is_empty() {
                            return Err(BatchError::SerializationError(
                                "Missing USINT value".to_string(),
                            ));
                        }
                        Ok(Some(PlcValue::Usint(value_data[0])))
                    }
                    0x00C7 => {
                        // UINT
                        if value_data.len() < 2 {
                            return Err(BatchError::SerializationError(
                                "Missing UINT value".to_string(),
                            ));
                        }
                        let value = u16::from_le_bytes([value_data[0], value_data[1]]);
                        Ok(Some(PlcValue::Uint(value)))
                    }
                    0x00C8 => {
                        // UDINT
                        if value_data.len() < 4 {
                            return Err(BatchError::SerializationError(
                                "Missing UDINT value".to_string(),
                            ));
                        }
                        let value = u32::from_le_bytes([
                            value_data[0],
                            value_data[1],
                            value_data[2],
                            value_data[3],
                        ]);
                        Ok(Some(PlcValue::Udint(value)))
                    }
                    0x00C9 => {
                        // ULINT
                        if value_data.len() < 8 {
                            return Err(BatchError::SerializationError(
                                "Missing ULINT value".to_string(),
                            ));
                        }
                        let value = u64::from_le_bytes([
                            value_data[0],
                            value_data[1],
                            value_data[2],
                            value_data[3],
                            value_data[4],
                            value_data[5],
                            value_data[6],
                            value_data[7],
                        ]);
                        Ok(Some(PlcValue::Ulint(value)))
                    }
                    0x00CA => {
                        // REAL
                        if value_data.len() < 4 {
                            return Err(BatchError::SerializationError(
                                "Missing REAL value".to_string(),
                            ));
                        }
                        let bytes = [value_data[0], value_data[1], value_data[2], value_data[3]];
                        let value = f32::from_le_bytes(bytes);
                        tracing::trace!("Parsed REAL: {}", value);
                        Ok(Some(PlcValue::Real(value)))
                    }
                    0x00CB => {
                        // LREAL
                        if value_data.len() < 8 {
                            return Err(BatchError::SerializationError(
                                "Missing LREAL value".to_string(),
                            ));
                        }
                        let bytes = [
                            value_data[0],
                            value_data[1],
                            value_data[2],
                            value_data[3],
                            value_data[4],
                            value_data[5],
                            value_data[6],
                            value_data[7],
                        ];
                        let value = f64::from_le_bytes(bytes);
                        Ok(Some(PlcValue::Lreal(value)))
                    }
                    0x00DA => {
                        // STRING
                        if value_data.is_empty() {
                            return Ok(Some(PlcValue::String(String::new())));
                        }
                        let length = value_data[0] as usize;
                        if value_data.len() < 1 + length {
                            return Err(BatchError::SerializationError(
                                "Insufficient data for STRING value".to_string(),
                            ));
                        }
                        let string_data = &value_data[1..1 + length];
                        let value = String::from_utf8_lossy(string_data).to_string();
                        tracing::trace!("Parsed STRING: '{}'", value);
                        Ok(Some(PlcValue::String(value)))
                    }
                    0x02A0 => {
                        // Allen-Bradley UDT type (0x02A0) for batch operations
                        // Note: symbol_id not available in batch read context
                        tracing::trace!(
                            "Detected UDT structure (0x02A0) with {} bytes",
                            value_data.len()
                        );
                        Ok(Some(PlcValue::Udt(UdtData {
                            symbol_id: 0, // Not available in batch context
                            data: value_data.to_vec(),
                        })))
                    }
                    _ => Err(BatchError::SerializationError(format!(
                        "Unsupported data type: 0x{data_type:04X}"
                    ))),
                }
            }
        }
    }

    /// Writes a string value using Allen-Bradley UDT component access
    /// This writes to TestString.LEN and TestString.DATA separately
    pub async fn write_ab_string_components(
        &mut self,
        tag_name: &str,
        value: &str,
    ) -> crate::error::Result<()> {
        tracing::debug!(
            "[AB STRING] Writing string '{}' to tag '{}' using component access",
            value,
            tag_name
        );

        let string_bytes = value.as_bytes();
        let string_len = string_bytes.len() as i32;

        // Step 1: Write the length to TestString.LEN
        let len_tag = format!("{tag_name}.LEN");
        tracing::debug!("Step 1: Writing length {} to {}", string_len, len_tag);

        match self.write_tag(&len_tag, PlcValue::Dint(string_len)).await {
            Ok(_) => tracing::debug!("Length written successfully"),
            Err(e) => {
                tracing::error!("Length write failed: {}", e);
                return Err(e);
            }
        }

        // Step 2: Write the string data to TestString.DATA using array access
        tracing::debug!("Step 2: Writing string data to {}.DATA", tag_name);

        // We need to write each character individually to the DATA array
        for (i, &byte) in string_bytes.iter().enumerate() {
            let data_element = format!("{tag_name}.DATA[{i}]");
            match self
                .write_tag(&data_element, PlcValue::Sint(byte as i8))
                .await
            {
                Ok(_) => print!("."),
                Err(e) => {
                    tracing::error!("Failed to write byte {} to position {}: {}", byte, i, e);
                    return Err(e);
                }
            }
        }

        // Step 3: Clear remaining bytes (null terminate)
        if string_bytes.len() < 82 {
            let null_element = format!("{}.DATA[{}]", tag_name, string_bytes.len());
            match self.write_tag(&null_element, PlcValue::Sint(0)).await {
                Ok(_) => tracing::debug!("String null-terminated successfully"),
                Err(e) => tracing::warn!("Could not null-terminate: {}", e),
            }
        }

        tracing::info!("AB STRING component write completed!");
        Ok(())
    }

    /// Writes a string using a single UDT write with proper AB STRING format
    pub async fn write_ab_string_udt(
        &mut self,
        tag_name: &str,
        value: &str,
    ) -> crate::error::Result<()> {
        tracing::debug!(
            "[AB STRING UDT] Writing string '{}' to tag '{}' as UDT",
            value,
            tag_name
        );

        let string_bytes = value.as_bytes();
        if string_bytes.len() > 82 {
            return Err(EtherNetIpError::Protocol(
                "String too long for Allen-Bradley STRING (max 82 chars)".to_string(),
            ));
        }

        // Build a CIP request that writes the complete AB STRING structure
        let mut cip_request = Vec::new();

        // Service: Write Tag Service (0x4D)
        cip_request.push(0x4D);

        // Request Path
        let tag_path = self.build_tag_path(tag_name);
        cip_request.push((tag_path.len() / 2) as u8); // Path size in words
        cip_request.extend_from_slice(&tag_path);

        // Data Type: Allen-Bradley STRING (0x02A0) - but write as UDT components
        cip_request.extend_from_slice(&[0xA0, 0x00]); // UDT type
        cip_request.extend_from_slice(&[0x01, 0x00]); // Element count

        // AB STRING UDT structure:
        // - DINT .LEN (4 bytes)
        // - SINT .DATA[82] (82 bytes)

        // Write .LEN field (current string length)
        let len = string_bytes.len() as u32;
        cip_request.extend_from_slice(&len.to_le_bytes());

        // Write .DATA field (82 bytes total)
        cip_request.extend_from_slice(string_bytes); // Actual string data

        // Pad with zeros to reach 82 bytes
        let padding_needed = 82 - string_bytes.len();
        cip_request.extend_from_slice(&vec![0u8; padding_needed]);

        tracing::trace!("Built UDT write request: {} bytes total", cip_request.len());

        let response = self.send_cip_request(&cip_request).await?;

        if response.len() >= 3 {
            let general_status = response[2];
            if general_status == 0x00 {
                tracing::info!("AB STRING UDT write successful!");
                Ok(())
            } else {
                let error_msg = self.get_cip_error_message(general_status);
                Err(EtherNetIpError::Protocol(format!(
                    "AB STRING UDT write failed - CIP Error 0x{general_status:02X}: {error_msg}"
                )))
            }
        } else {
            Err(EtherNetIpError::Protocol(
                "Invalid AB STRING UDT write response".to_string(),
            ))
        }
    }

    /// Establishes a Class 3 connected session for STRING operations
    ///
    /// Connected sessions are required for certain operations like STRING writes
    /// in Allen-Bradley PLCs. This implements the Forward Open CIP service.
    /// Will try multiple connection parameter configurations until one succeeds.
    async fn establish_connected_session(
        &mut self,
        session_name: &str,
    ) -> crate::error::Result<ConnectedSession> {
        tracing::debug!(
            "[CONNECTED] Establishing connected session: '{}'",
            session_name
        );
        tracing::debug!("[CONNECTED] Will try multiple parameter configurations...");

        // Generate unique connection parameters
        *self.connection_sequence.lock().await += 1;
        let connection_serial = (*self.connection_sequence.lock().await & 0xFFFF) as u16;

        // Try different configurations until one works
        for config_id in 0..=5 {
            tracing::debug!(
                "[ATTEMPT {}] Trying configuration {}:",
                config_id + 1,
                config_id
            );

            let mut session = if config_id == 0 {
                ConnectedSession::new(connection_serial)
            } else {
                ConnectedSession::with_config(connection_serial, config_id)
            };

            // Generate unique connection IDs for this attempt
            session.o_to_t_connection_id =
                0x2000_0000 + *self.connection_sequence.lock().await + (config_id as u32 * 0x1000);
            session.t_to_o_connection_id =
                0x3000_0000 + *self.connection_sequence.lock().await + (config_id as u32 * 0x1000);

            // Build Forward Open request with this configuration
            let forward_open_request = self.build_forward_open_request(&session)?;

            tracing::debug!(
                "[ATTEMPT {}] Sending Forward Open request ({} bytes)",
                config_id + 1,
                forward_open_request.len()
            );

            // Send Forward Open request
            match self.send_cip_request(&forward_open_request).await {
                Ok(response) => {
                    // Try to parse the response - DON'T clone, modify the session directly!
                    match self.parse_forward_open_response(&mut session, &response) {
                        Ok(()) => {
                            // Success! Store the session and return
                            tracing::info!("[SUCCESS] Configuration {} worked!", config_id);
                            tracing::debug!("Connection ID: 0x{:08X}", session.connection_id);
                            tracing::debug!("O->T ID: 0x{:08X}", session.o_to_t_connection_id);
                            tracing::debug!("T->O ID: 0x{:08X}", session.t_to_o_connection_id);
                            tracing::debug!(
                                "Using Connection ID: 0x{:08X} for messaging",
                                session.connection_id
                            );

                            session.is_active = true;
                            let mut sessions = self.connected_sessions.lock().await;
                            sessions.insert(session_name.to_string(), session.clone());
                            return Ok(session);
                        }
                        Err(e) => {
                            tracing::warn!(
                                "[ATTEMPT {}] Configuration {} failed: {}",
                                config_id + 1,
                                config_id,
                                e
                            );

                            // If it's a specific status error, log it
                            if e.to_string().contains("status: 0x") {
                                tracing::debug!("Status indicates: parameter incompatibility or resource conflict");
                            }
                        }
                    }
                }
                Err(e) => {
                    tracing::warn!(
                        "[ATTEMPT {}] Network error with config {}: {}",
                        config_id + 1,
                        config_id,
                        e
                    );
                }
            }

            // Small delay between attempts
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        }

        // If we get here, all configurations failed
        Err(EtherNetIpError::Protocol(
            "All connection parameter configurations failed. PLC may not support connected messaging or has reached connection limits.".to_string()
        ))
    }

    /// Builds a Forward Open CIP request for establishing connected sessions
    fn build_forward_open_request(
        &self,
        session: &ConnectedSession,
    ) -> crate::error::Result<Vec<u8>> {
        let mut request = Vec::with_capacity(50);

        // CIP Forward Open Service (0x54)
        request.push(0x54);

        // Request path length (Connection Manager object)
        request.push(0x02); // 2 words

        // Class ID: Connection Manager (0x06)
        request.push(0x20); // Logical Class segment
        request.push(0x06);

        // Instance ID: Connection Manager instance (0x01)
        request.push(0x24); // Logical Instance segment
        request.push(0x01);

        // Forward Open parameters

        // Connection Timeout Ticks (1 byte) + Timeout multiplier (1 byte)
        request.push(0x0A); // Timeout ticks (10)
        request.push(session.timeout_multiplier);

        // Originator -> Target Connection ID (4 bytes, little-endian)
        request.extend_from_slice(&session.o_to_t_connection_id.to_le_bytes());

        // Target -> Originator Connection ID (4 bytes, little-endian)
        request.extend_from_slice(&session.t_to_o_connection_id.to_le_bytes());

        // Connection Serial Number (2 bytes, little-endian)
        request.extend_from_slice(&session.connection_serial.to_le_bytes());

        // Originator Vendor ID (2 bytes, little-endian)
        request.extend_from_slice(&session.originator_vendor_id.to_le_bytes());

        // Originator Serial Number (4 bytes, little-endian)
        request.extend_from_slice(&session.originator_serial.to_le_bytes());

        // Connection Timeout Multiplier (1 byte) - repeated for target
        request.push(session.timeout_multiplier);

        // Reserved bytes (3 bytes)
        request.extend_from_slice(&[0x00, 0x00, 0x00]);

        // Originator -> Target RPI (4 bytes, little-endian, microseconds)
        request.extend_from_slice(&session.rpi.to_le_bytes());

        // Originator -> Target connection parameters (4 bytes)
        let o_to_t_params = self.encode_connection_parameters(&session.o_to_t_params);
        request.extend_from_slice(&o_to_t_params.to_le_bytes());

        // Target -> Originator RPI (4 bytes, little-endian, microseconds)
        request.extend_from_slice(&session.rpi.to_le_bytes());

        // Target -> Originator connection parameters (4 bytes)
        let t_to_o_params = self.encode_connection_parameters(&session.t_to_o_params);
        request.extend_from_slice(&t_to_o_params.to_le_bytes());

        // Transport type/trigger (1 byte) - Class 3, Application triggered
        request.push(0xA3);

        // Connection Path Size (1 byte)
        request.push(0x02); // 2 words for Message Router path

        // Connection Path - Target the Message Router
        request.push(0x20); // Logical Class segment
        request.push(0x02); // Message Router class (0x02)
        request.push(0x24); // Logical Instance segment
        request.push(0x01); // Message Router instance (0x01)

        Ok(request)
    }

    /// Encodes connection parameters into a 32-bit value
    fn encode_connection_parameters(&self, params: &ConnectionParameters) -> u32 {
        let mut encoded = 0u32;

        // Connection size (bits 0-15)
        encoded |= params.size as u32;

        // Variable flag (bit 25)
        if params.variable_size {
            encoded |= 1 << 25;
        }

        // Connection type (bits 29-30)
        encoded |= (params.connection_type as u32) << 29;

        // Priority (bits 26-27)
        encoded |= (params.priority as u32) << 26;

        encoded
    }

    /// Parses Forward Open response and updates session with connection info
    fn parse_forward_open_response(
        &self,
        session: &mut ConnectedSession,
        response: &[u8],
    ) -> crate::error::Result<()> {
        if response.len() < 2 {
            return Err(EtherNetIpError::Protocol(
                "Forward Open response too short".to_string(),
            ));
        }

        let service = response[0];
        let status = response[1];

        // Check if this is a Forward Open Reply (0xD4)
        if service != 0xD4 {
            return Err(EtherNetIpError::Protocol(format!(
                "Unexpected service in Forward Open response: 0x{service:02X}"
            )));
        }

        // Check status
        if status != 0x00 {
            let error_msg = match status {
                0x01 => "Connection failure - Resource unavailable or already exists",
                0x02 => "Invalid parameter - Connection parameters rejected",
                0x03 => "Connection timeout - PLC did not respond in time",
                0x04 => "Connection limit exceeded - Too many connections",
                0x08 => "Invalid service - Forward Open not supported",
                0x0C => "Invalid attribute - Connection parameters invalid",
                0x13 => "Path destination unknown - Target object not found",
                0x26 => "Invalid parameter value - RPI or size out of range",
                _ => &format!("Unknown status: 0x{status:02X}"),
            };
            return Err(EtherNetIpError::Protocol(format!(
                "Forward Open failed with status 0x{status:02X}: {error_msg}"
            )));
        }

        // Parse successful response
        if response.len() < 16 {
            return Err(EtherNetIpError::Protocol(
                "Forward Open response data too short".to_string(),
            ));
        }

        // CRITICAL FIX: The Forward Open response contains the actual connection IDs assigned by the PLC
        // Use the IDs returned by the PLC, not our requested ones
        let actual_o_to_t_id =
            u32::from_le_bytes([response[2], response[3], response[4], response[5]]);
        let actual_t_to_o_id =
            u32::from_le_bytes([response[6], response[7], response[8], response[9]]);

        // Update session with the actual assigned connection IDs
        session.o_to_t_connection_id = actual_o_to_t_id;
        session.t_to_o_connection_id = actual_t_to_o_id;
        session.connection_id = actual_o_to_t_id; // Use O->T as the primary connection ID

        tracing::info!("[FORWARD OPEN] Success!");
        tracing::debug!(
            "O->T Connection ID: 0x{:08X} (PLC assigned)",
            session.o_to_t_connection_id
        );
        tracing::debug!(
            "T->O Connection ID: 0x{:08X} (PLC assigned)",
            session.t_to_o_connection_id
        );
        tracing::debug!(
            "Using Connection ID: 0x{:08X} for messaging",
            session.connection_id
        );

        Ok(())
    }

    /// Writes a string using connected explicit messaging
    pub async fn write_string_connected(
        &mut self,
        tag_name: &str,
        value: &str,
    ) -> crate::error::Result<()> {
        let session_name = format!("string_write_{tag_name}");
        let mut sessions = self.connected_sessions.lock().await;

        if !sessions.contains_key(&session_name) {
            drop(sessions); // Release the lock before calling establish_connected_session
            self.establish_connected_session(&session_name).await?;
            sessions = self.connected_sessions.lock().await;
        }

        let session = sessions.get(&session_name).unwrap().clone();
        let request = self.build_connected_string_write_request(tag_name, value, &session)?;

        drop(sessions); // Release the lock before sending the request
        let response = self
            .send_connected_cip_request(&request, &session, &session_name)
            .await?;

        // Check if write was successful
        if response.len() >= 2 {
            let status = response[1];
            if status == 0x00 {
                Ok(())
            } else {
                let error_msg = self.get_cip_error_message(status);
                Err(EtherNetIpError::Protocol(format!(
                    "CIP Error 0x{status:02X}: {error_msg}"
                )))
            }
        } else {
            Err(EtherNetIpError::Protocol(
                "Invalid connected string write response".to_string(),
            ))
        }
    }

    /// Builds a string write request for connected messaging
    fn build_connected_string_write_request(
        &self,
        tag_name: &str,
        value: &str,
        _session: &ConnectedSession,
    ) -> crate::error::Result<Vec<u8>> {
        let mut request = Vec::new();

        // For connected messaging, use direct CIP Write service
        // The connection is already established, so we can send the request directly

        // CIP Write Service Code
        request.push(0x4D);

        // Tag path - use simple ANSI format for connected messaging
        let tag_bytes = tag_name.as_bytes();
        let path_size_words = (2 + tag_bytes.len() + 1) / 2; // +1 for potential padding, /2 for word count
        request.push(path_size_words as u8);

        request.push(0x91); // ANSI symbol segment
        request.push(tag_bytes.len() as u8); // Length of tag name
        request.extend_from_slice(tag_bytes);

        // Add padding byte if needed to make path even length
        if (2 + tag_bytes.len()) % 2 != 0 {
            request.push(0x00);
        }

        // Data type for AB STRING
        request.extend_from_slice(&[0xCE, 0x0F]); // AB STRING data type (4046)

        // Number of elements (always 1 for a single string)
        request.extend_from_slice(&[0x01, 0x00]);

        // Build the AB STRING structure payload
        let string_bytes = value.as_bytes();
        let max_len: u16 = 82; // Standard AB STRING max length
        let current_len = string_bytes.len().min(max_len as usize) as u16;

        // STRING structure:
        // - Len (2 bytes) - number of characters used
        request.extend_from_slice(&current_len.to_le_bytes());

        // - MaxLen (2 bytes) - maximum characters allowed (typically 82)
        request.extend_from_slice(&max_len.to_le_bytes());

        // - Data[MaxLen] (82 bytes) - the character array, zero-padded
        let mut data_array = vec![0u8; max_len as usize];
        data_array[..current_len as usize].copy_from_slice(&string_bytes[..current_len as usize]);
        request.extend_from_slice(&data_array);

        tracing::trace!(
            "Built connected string write request ({} bytes) for '{}' = '{}' (len={}, maxlen={})",
            request.len(),
            tag_name,
            value,
            current_len,
            max_len
        );
        tracing::trace!("Request: {:02X?}", request);

        Ok(request)
    }

    /// Sends a CIP request using connected messaging
    async fn send_connected_cip_request(
        &mut self,
        cip_request: &[u8],
        session: &ConnectedSession,
        session_name: &str,
    ) -> crate::error::Result<Vec<u8>> {
        tracing::debug!(
            "[CONNECTED] Sending connected CIP request ({} bytes) using T->O connection ID 0x{:08X}",
            cip_request.len(), session.t_to_o_connection_id
        );

        // Build EtherNet/IP header for connected data (Send RR Data)
        let mut packet = Vec::new();

        // EtherNet/IP Header
        packet.extend_from_slice(&[0x6F, 0x00]); // Command: Send RR Data (0x006F) - correct for connected messaging
        packet.extend_from_slice(&[0x00, 0x00]); // Length (fill in later)
        packet.extend_from_slice(&self.session_handle.to_le_bytes()); // Session handle
        packet.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Status
        packet.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]); // Context
        packet.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]); // Options

        // CPF (Common Packet Format) data starts here
        let cpf_start = packet.len();

        // Interface handle (4 bytes)
        packet.extend_from_slice(&[0x00, 0x00, 0x00, 0x00]);

        // Timeout (2 bytes) - 5 seconds
        packet.extend_from_slice(&[0x05, 0x00]);

        // Item count (2 bytes) - 2 items: Address + Data
        packet.extend_from_slice(&[0x02, 0x00]);

        // Item 1: Connected Address Item (specifies which connection to use)
        packet.extend_from_slice(&[0xA1, 0x00]); // Type: Connected Address Item (0x00A1)
        packet.extend_from_slice(&[0x04, 0x00]); // Length: 4 bytes
                                                 // Use T->O connection ID (Target to Originator) for addressing
        packet.extend_from_slice(&session.t_to_o_connection_id.to_le_bytes());

        // Item 2: Connected Data Item (contains the CIP request + sequence)
        packet.extend_from_slice(&[0xB1, 0x00]); // Type: Connected Data Item (0x00B1)
        let data_length = cip_request.len() + 2; // +2 for sequence count
        packet.extend_from_slice(&(data_length as u16).to_le_bytes()); // Length

        // Clone session_name and session before acquiring the lock
        let session_name_clone = session_name.to_string();
        let _session_clone = session.clone();

        // Get the current session mutably to increment sequence counter
        let mut sessions = self.connected_sessions.lock().await;
        let current_sequence = if let Some(session_mut) = sessions.get_mut(&session_name_clone) {
            session_mut.sequence_count += 1;
            session_mut.sequence_count
        } else {
            1 // Fallback if session not found
        };

        // Drop the lock before sending the request
        drop(sessions);

        // Sequence count (2 bytes) - incremental counter for this connection
        packet.extend_from_slice(&current_sequence.to_le_bytes());

        // CIP request data
        packet.extend_from_slice(cip_request);

        // Update packet length in header (total CPF data size)
        let cpf_length = packet.len() - cpf_start;
        packet[2..4].copy_from_slice(&(cpf_length as u16).to_le_bytes());

        tracing::trace!(
            "[CONNECTED] Sending packet ({} bytes) with sequence {}",
            packet.len(),
            current_sequence
        );

        // Send packet
        let mut stream = self.stream.lock().await;
        stream
            .write_all(&packet)
            .await
            .map_err(EtherNetIpError::Io)?;

        // Read response header
        let mut header = [0u8; 24];
        stream
            .read_exact(&mut header)
            .await
            .map_err(EtherNetIpError::Io)?;

        // Check EtherNet/IP command status
        let cmd_status = u32::from_le_bytes([header[8], header[9], header[10], header[11]]);
        if cmd_status != 0 {
            return Err(EtherNetIpError::Protocol(format!(
                "Connected message failed with status: 0x{cmd_status:08X}"
            )));
        }

        // Read response data
        let response_length = u16::from_le_bytes([header[2], header[3]]) as usize;
        let mut response_data = vec![0u8; response_length];
        stream
            .read_exact(&mut response_data)
            .await
            .map_err(EtherNetIpError::Io)?;

        let mut last_activity = self.last_activity.lock().await;
        *last_activity = Instant::now();

        tracing::trace!(
            "[CONNECTED] Received response ({} bytes)",
            response_data.len()
        );

        // Extract connected CIP response
        self.extract_connected_cip_from_response(&response_data)
    }

    /// Extracts CIP data from connected response
    fn extract_connected_cip_from_response(
        &self,
        response: &[u8],
    ) -> crate::error::Result<Vec<u8>> {
        tracing::trace!(
            "[CONNECTED] Extracting CIP from connected response ({} bytes): {:02X?}",
            response.len(),
            response
        );

        if response.len() < 12 {
            return Err(EtherNetIpError::Protocol(
                "Connected response too short for CPF header".to_string(),
            ));
        }

        // Parse CPF (Common Packet Format) structure
        // [0-3]: Interface handle
        // [4-5]: Timeout
        // [6-7]: Item count
        let item_count = u16::from_le_bytes([response[6], response[7]]) as usize;
        tracing::trace!("[CONNECTED] CPF item count: {}", item_count);

        let mut pos = 8; // Start after CPF header

        // Look for Connected Data Item (0x00B1)
        for _i in 0..item_count {
            if pos + 4 > response.len() {
                return Err(EtherNetIpError::Protocol(
                    "Response truncated while parsing items".to_string(),
                ));
            }

            let item_type = u16::from_le_bytes([response[pos], response[pos + 1]]);
            let item_length = u16::from_le_bytes([response[pos + 2], response[pos + 3]]) as usize;
            pos += 4; // Skip item header

            tracing::trace!(
                "[CONNECTED] Found item: type=0x{:04X}, length={}",
                item_type,
                item_length
            );

            if pos
                .checked_add(item_length)
                .map_or(true, |end| end > response.len())
            {
                return Err(EtherNetIpError::Protocol(
                    "Connected data item truncated".to_string(),
                ));
            }

            if item_type == 0x00B1 {
                // Connected Data Item
                // Connected Data Item contains [sequence_count(2)][cip_data]
                if item_length < 2 {
                    return Err(EtherNetIpError::Protocol(
                        "Connected data item too short for sequence".to_string(),
                    ));
                }

                let sequence_count = u16::from_le_bytes([response[pos], response[pos + 1]]);
                tracing::trace!("[CONNECTED] Sequence count: {}", sequence_count);

                // Extract CIP data (skip 2-byte sequence count)
                let cip_data = response[pos + 2..pos + item_length].to_vec();
                tracing::trace!(
                    "[CONNECTED] Extracted CIP data ({} bytes): {:02X?}",
                    cip_data.len(),
                    cip_data
                );

                return Ok(cip_data);
            } else {
                // Skip this item's data
                pos += item_length;
            }
        }

        Err(EtherNetIpError::Protocol(
            "Connected Data Item (0x00B1) not found in response".to_string(),
        ))
    }

    /// Closes a specific connected session
    async fn close_connected_session(&mut self, session_name: &str) -> crate::error::Result<()> {
        if let Some(session) = self.connected_sessions.lock().await.get(session_name) {
            let session = session.clone(); // Clone to avoid borrowing issues

            // Build Forward Close request
            let forward_close_request = self.build_forward_close_request(&session)?;

            // Send Forward Close request
            let _response = self.send_cip_request(&forward_close_request).await?;

            tracing::info!("[CONNECTED] Session '{}' closed successfully", session_name);
        }

        // Remove session from our tracking
        let mut sessions = self.connected_sessions.lock().await;
        sessions.remove(session_name);

        Ok(())
    }

    /// Builds a Forward Close CIP request for terminating connected sessions
    fn build_forward_close_request(
        &self,
        session: &ConnectedSession,
    ) -> crate::error::Result<Vec<u8>> {
        let mut request = Vec::with_capacity(21);

        // CIP Forward Close Service (0x4E)
        request.push(0x4E);

        // Request path length (Connection Manager object)
        request.push(0x02); // 2 words

        // Class ID: Connection Manager (0x06)
        request.push(0x20); // Logical Class segment
        request.push(0x06);

        // Instance ID: Connection Manager instance (0x01)
        request.push(0x24); // Logical Instance segment
        request.push(0x01);

        // Forward Close parameters

        // Connection Timeout Ticks (1 byte) + Timeout multiplier (1 byte)
        request.push(0x0A); // Timeout ticks (10)
        request.push(session.timeout_multiplier);

        // Connection Serial Number (2 bytes, little-endian)
        request.extend_from_slice(&session.connection_serial.to_le_bytes());

        // Originator Vendor ID (2 bytes, little-endian)
        request.extend_from_slice(&session.originator_vendor_id.to_le_bytes());

        // Originator Serial Number (4 bytes, little-endian)
        request.extend_from_slice(&session.originator_serial.to_le_bytes());

        // Connection Path Size (1 byte)
        request.push(0x02); // 2 words for Message Router path

        // Connection Path - Target the Message Router
        request.push(0x20); // Logical Class segment
        request.push(0x02); // Message Router class (0x02)
        request.push(0x24); // Logical Instance segment
        request.push(0x01); // Message Router instance (0x01)

        Ok(request)
    }

    /// Closes all connected sessions (called during disconnect)
    async fn close_all_connected_sessions(&mut self) -> crate::error::Result<()> {
        let session_names: Vec<String> = self
            .connected_sessions
            .lock()
            .await
            .keys()
            .cloned()
            .collect();

        for session_name in session_names {
            let _ = self.close_connected_session(&session_name).await; // Ignore errors during cleanup
        }

        Ok(())
    }

    /// Writes a string using unconnected explicit messaging with proper AB STRING format
    ///
    /// This method uses standard unconnected messaging instead of connected messaging
    /// and implements the proper Allen-Bradley STRING structure as described in the
    /// provided information about `Len`, `MaxLen`, and `Data[82]` format.
    pub async fn write_string_unconnected(
        &mut self,
        tag_name: &str,
        value: &str,
    ) -> crate::error::Result<()> {
        tracing::debug!(
            "[UNCONNECTED] Writing string '{}' to tag '{}' using unconnected messaging",
            value,
            tag_name
        );

        self.validate_session().await?;

        let string_bytes = value.as_bytes();
        if string_bytes.len() > 82 {
            return Err(EtherNetIpError::Protocol(
                "String too long for Allen-Bradley STRING (max 82 chars)".to_string(),
            ));
        }

        // Build the CIP request with proper AB STRING structure
        let mut cip_request = Vec::new();

        // Service: Write Tag Service (0x4D)
        cip_request.push(0x4D);

        // Request Path Size (in words)
        let tag_bytes = tag_name.as_bytes();
        let path_len = if tag_bytes.len() % 2 == 0 {
            tag_bytes.len() + 2
        } else {
            tag_bytes.len() + 3
        } / 2;
        cip_request.push(path_len as u8);

        // Request Path: ANSI Extended Symbol Segment for tag name
        cip_request.push(0x91); // ANSI Extended Symbol Segment
        cip_request.push(tag_bytes.len() as u8); // Tag name length
        cip_request.extend_from_slice(tag_bytes); // Tag name

        // Pad to even length if necessary
        if tag_bytes.len() % 2 != 0 {
            cip_request.push(0x00);
        }

        // For write operations, we don't include data type and element count
        // The PLC infers the data type from the tag definition

        // Build Allen-Bradley STRING structure based on what we see in read responses:
        // Looking at read response: [CE, 0F, 01, 00, 00, 00, 31, 00, ...]
        // Structure appears to be:
        // - Some header/identifier (2 bytes): 0xCE, 0x0F
        // - Length (2 bytes): number of characters
        // - MaxLength or padding (2 bytes): 0x00, 0x00
        // - Data array (variable length, null terminated)

        let _current_len = string_bytes.len().min(82) as u16;

        // Build the correct Allen-Bradley STRING structure to match what the PLC expects
        // Analysis of read response: [CE, 0F, 01, 00, 00, 00, 31, 00, 00, 00, ...]
        // Structure appears to be:
        // - Header (2 bytes): 0xCE, 0x0F (Allen-Bradley STRING identifier)
        // - Length (4 bytes, DINT): Number of characters currently used
        // - Data (variable): Character data followed by padding to complete the structure

        let current_len = string_bytes.len().min(82) as u32;

        // AB STRING header/identifier - this appears to be required
        cip_request.extend_from_slice(&[0xCE, 0x0F]);

        // Length (4 bytes) - number of characters used as DINT
        cip_request.extend_from_slice(&current_len.to_le_bytes());

        // Data bytes - the actual string content
        cip_request.extend_from_slice(&string_bytes[..current_len as usize]);

        // Add padding if the total structure needs to be a specific size
        // Based on reads, it looks like there might be additional padding after the data

        tracing::trace!(
            "Built Allen-Bradley STRING write request ({} bytes) for '{}' = '{}' (len={})",
            cip_request.len(),
            tag_name,
            value,
            current_len
        );
        tracing::trace!(
            "Request structure: Service=0x4D, Path={} bytes, Header=0xCE0F, Len={} (4 bytes), Data",
            path_len * 2,
            current_len
        );

        // Send the request using standard unconnected messaging
        let response = self.send_cip_request(&cip_request).await?;

        // Extract CIP response from EtherNet/IP wrapper
        let cip_response = self.extract_cip_from_response(&response)?;

        // Check if write was successful - use correct CIP response format
        if cip_response.len() >= 3 {
            let service_reply = cip_response[0]; // Should be 0xCD (0x4D + 0x80) for Write Tag reply
            let _additional_status_size = cip_response[1]; // Additional status size (usually 0)
            let status = cip_response[2]; // CIP status code at position 2

            tracing::trace!(
                "Write response - Service: 0x{:02X}, Status: 0x{:02X}",
                service_reply,
                status
            );

            if status == 0x00 {
                tracing::info!("[UNCONNECTED] String write completed successfully");
                Ok(())
            } else {
                let error_msg = self.get_cip_error_message(status);
                tracing::error!(
                    "[UNCONNECTED] String write failed: {} (0x{:02X})",
                    error_msg,
                    status
                );
                Err(EtherNetIpError::Protocol(format!(
                    "CIP Error 0x{status:02X}: {error_msg}"
                )))
            }
        } else {
            Err(EtherNetIpError::Protocol(
                "Invalid unconnected string write response - too short".to_string(),
            ))
        }
    }

    /// Write a string value to a PLC tag using unconnected messaging
    ///
    /// # Arguments
    ///
    /// * `tag_name` - The name of the tag to write to
    /// * `value` - The string value to write (max 82 characters)
    ///
    /// # Returns
    ///
    /// * `Ok(())` if the write was successful
    /// * `Err(EtherNetIpError)` if the write failed
    ///
    /// # Errors
    ///
    /// * `StringTooLong` - If the string is longer than 82 characters
    /// * `InvalidString` - If the string contains invalid characters
    /// * `TagNotFound` - If the tag doesn't exist
    /// * `WriteError` - If the write operation fails
    pub async fn write_string(&mut self, tag_name: &str, value: &str) -> crate::error::Result<()> {
        // Validate string length
        if value.len() > 82 {
            return Err(crate::error::EtherNetIpError::StringTooLong {
                max_length: 82,
                actual_length: value.len(),
            });
        }

        // Validate string content (ASCII only)
        if !value.is_ascii() {
            return Err(crate::error::EtherNetIpError::InvalidString {
                reason: "String contains non-ASCII characters".to_string(),
            });
        }

        // Build the string write request
        let request = self.build_string_write_request(tag_name, value)?;

        // Send the request and get the response
        let response = self.send_cip_request(&request).await?;

        // Parse the response
        let cip_response = self.extract_cip_from_response(&response)?;

        // Check for errors in the response
        if cip_response.len() < 2 {
            return Err(crate::error::EtherNetIpError::InvalidResponse {
                reason: "Response too short".to_string(),
            });
        }

        let status = cip_response[0];
        if status != 0 {
            return Err(crate::error::EtherNetIpError::WriteError {
                status,
                message: self.get_cip_error_message(status),
            });
        }

        Ok(())
    }

    /// Build a string write request packet
    fn build_string_write_request(
        &self,
        tag_name: &str,
        value: &str,
    ) -> crate::error::Result<Vec<u8>> {
        let mut request = Vec::new();

        // CIP Write Service (0x4D)
        request.push(0x4D);

        // Tag path
        let tag_path = self.build_tag_path(tag_name);
        request.extend_from_slice(&tag_path);

        // AB STRING data structure
        request.extend_from_slice(&(value.len() as u16).to_le_bytes()); // Len
        request.extend_from_slice(&82u16.to_le_bytes()); // MaxLen

        // Data[82] with padding
        let mut data = [0u8; 82];
        let bytes = value.as_bytes();
        data[..bytes.len()].copy_from_slice(bytes);
        request.extend_from_slice(&data);

        Ok(request)
    }

    /// Subscribes to a tag for real-time updates.
    ///
    /// The returned [`TagSubscription`] can be used to:
    /// - [`wait_for_update()`](TagSubscription::wait_for_update) for the next value
    /// - [`get_last_value()`](TagSubscription::get_last_value) for the latest cached value
    /// - [`into_stream()`](TagSubscription::into_stream) for an async `Stream` of updates
    ///
    /// This API validates the tag with an initial read before returning so invalid or
    /// inaccessible tags fail fast instead of surfacing only through background polling logs.
    ///
    /// The background poll loop uses [`SubscriptionOptions::update_rate`] (milliseconds) between reads.
    pub async fn subscribe_to_tag(
        &self,
        tag_path: &str,
        options: SubscriptionOptions,
    ) -> Result<TagSubscription> {
        let subscription = TagSubscription::new(tag_path.to_string(), options.clone());
        let mut validation_client = self.clone();
        let initial_value = validation_client.read_tag(tag_path).await?;
        subscription.update_value(&initial_value).await?;

        let mut subscriptions = self.subscriptions.lock().await;
        let update_rate_ms = options.update_rate;
        subscriptions.push(subscription.clone());
        drop(subscriptions);

        let tag_path = tag_path.to_string();
        let mut client = self.clone();
        tokio::spawn(async move {
            let interval = std::time::Duration::from_millis(update_rate_ms as u64);
            loop {
                match client.read_tag(&tag_path).await {
                    Ok(value) => {
                        if let Err(e) = client.update_subscription(&tag_path, &value).await {
                            tracing::error!("Error updating subscription: {}", e);
                            break;
                        }
                    }
                    Err(e) => {
                        tracing::error!("Error reading tag {}: {}", tag_path, e);
                        break;
                    }
                }
                tokio::time::sleep(interval).await;
            }
        });
        Ok(subscription)
    }

    /// Subscribes to multiple tags. Returns one [`TagSubscription`] per tag in order.
    pub async fn subscribe_to_tags(
        &self,
        tags: &[(&str, SubscriptionOptions)],
    ) -> Result<Vec<TagSubscription>> {
        let mut subs = Vec::with_capacity(tags.len());
        for (tag_name, options) in tags {
            subs.push(self.subscribe_to_tag(tag_name, options.clone()).await?);
        }
        Ok(subs)
    }

    /// Registers or replaces a named tag group for grouped polling.
    ///
    /// Tag groups are useful for HMI/SCADA-style scan classes where multiple tags
    /// share a polling interval and should be read together.
    pub async fn upsert_tag_group(
        &self,
        group_name: &str,
        tags: &[&str],
        update_rate_ms: u32,
    ) -> Result<()> {
        if group_name.trim().is_empty() {
            return Err(EtherNetIpError::Protocol(
                "Tag group name cannot be empty".to_string(),
            ));
        }
        if tags.is_empty() {
            return Err(EtherNetIpError::Protocol(
                "Tag group must contain at least one tag".to_string(),
            ));
        }
        if update_rate_ms == 0 {
            return Err(EtherNetIpError::Protocol(
                "Tag group update rate must be greater than 0 ms".to_string(),
            ));
        }

        let config = TagGroupConfig {
            name: group_name.to_string(),
            tags: tags.iter().map(|s| (*s).to_string()).collect(),
            update_rate_ms,
        };

        let mut groups = self.tag_groups.lock().await;
        groups.insert(group_name.to_string(), config);
        Ok(())
    }

    /// Removes a named tag group.
    pub async fn remove_tag_group(&self, group_name: &str) -> bool {
        let mut groups = self.tag_groups.lock().await;
        groups.remove(group_name).is_some()
    }

    /// Lists all currently registered tag groups.
    pub async fn list_tag_groups(&self) -> Vec<TagGroupConfig> {
        let groups = self.tag_groups.lock().await;
        groups.values().cloned().collect()
    }

    /// Reads all tags in a group once and returns a snapshot.
    pub async fn read_tag_group_once(&self, group_name: &str) -> Result<TagGroupSnapshot> {
        let config = {
            let groups = self.tag_groups.lock().await;
            groups.get(group_name).cloned().ok_or_else(|| {
                EtherNetIpError::Protocol(format!("Tag group '{}' is not registered", group_name))
            })?
        };

        let mut client = self.clone();
        let tag_refs: Vec<&str> = config.tags.iter().map(String::as_str).collect();
        let values = client.read_tags_batch(&tag_refs).await?;

        let mapped = values
            .into_iter()
            .map(|(tag_name, result)| match result {
                Ok(value) => TagGroupValueResult {
                    tag_name,
                    value: Some(value),
                    error: None,
                },
                Err(e) => TagGroupValueResult {
                    tag_name,
                    value: None,
                    error: Some(e.to_string()),
                },
            })
            .collect();

        Ok(TagGroupSnapshot {
            group_name: config.name,
            sampled_at: std::time::SystemTime::now(),
            values: mapped,
        })
    }

    /// Starts background polling for a registered tag group.
    ///
    /// Use the returned subscription to await snapshots and to stop polling.
    pub async fn subscribe_tag_group(&self, group_name: &str) -> Result<TagGroupSubscription> {
        let config = {
            let groups = self.tag_groups.lock().await;
            groups.get(group_name).cloned().ok_or_else(|| {
                EtherNetIpError::Protocol(format!("Tag group '{}' is not registered", group_name))
            })?
        };

        let subscription = TagGroupSubscription::new(config.name.clone(), config.update_rate_ms);
        let subscription_task = subscription.clone();
        let mut client = self.clone();
        let tags = config.tags.clone();
        let interval = std::time::Duration::from_millis(config.update_rate_ms as u64);
        let group_name_owned = config.name.clone();

        tokio::spawn(async move {
            while subscription_task.is_active() {
                let tag_refs: Vec<&str> = tags.iter().map(String::as_str).collect();
                match client.read_tags_batch(&tag_refs).await {
                    Ok(values) => {
                        let has_errors = values.iter().any(|(_, result)| result.is_err());
                        let snapshot = TagGroupSnapshot {
                            group_name: group_name_owned.clone(),
                            sampled_at: std::time::SystemTime::now(),
                            values: values
                                .into_iter()
                                .map(|(tag_name, result)| match result {
                                    Ok(value) => TagGroupValueResult {
                                        tag_name,
                                        value: Some(value),
                                        error: None,
                                    },
                                    Err(e) => TagGroupValueResult {
                                        tag_name,
                                        value: None,
                                        error: Some(e.to_string()),
                                    },
                                })
                                .collect(),
                        };

                        let event = TagGroupEvent {
                            kind: if has_errors {
                                TagGroupEventKind::PartialError
                            } else {
                                TagGroupEventKind::Data
                            },
                            snapshot,
                            error: None,
                            failure: None,
                        };

                        if let Err(e) = subscription_task.publish_event(event).await {
                            tracing::error!(
                                "Tag group '{}' publish failed: {}",
                                group_name_owned,
                                e
                            );
                            break;
                        }
                    }
                    Err(e) => {
                        tracing::error!(
                            "Tag group '{}' polling read failed: {}",
                            group_name_owned,
                            e
                        );
                        let failure_event = TagGroupEvent {
                            kind: TagGroupEventKind::ReadFailure,
                            snapshot: TagGroupSnapshot {
                                group_name: group_name_owned.clone(),
                                sampled_at: std::time::SystemTime::now(),
                                values: Vec::new(),
                            },
                            error: Some(e.to_string()),
                            failure: Some(TagGroupFailureDiagnostic::from_error(&e)),
                        };
                        if let Err(publish_error) =
                            subscription_task.publish_event(failure_event).await
                        {
                            tracing::error!(
                                "Tag group '{}' failure-event publish failed: {}",
                                group_name_owned,
                                publish_error
                            );
                            break;
                        }
                    }
                }
                tokio::time::sleep(interval).await;
            }
        });

        Ok(subscription)
    }

    async fn update_subscription(&self, tag_name: &str, value: &PlcValue) -> Result<()> {
        let subscriptions = self.subscriptions.lock().await;
        for subscription in subscriptions.iter() {
            if subscription.tag_path == tag_name && subscription.is_active() {
                subscription.update_value(value).await?;
            }
        }
        Ok(())
    }

    async fn _get_connected_session(
        &mut self,
        session_name: &str,
    ) -> crate::error::Result<ConnectedSession> {
        // First check if we already have a session
        {
            let sessions = self.connected_sessions.lock().await;
            if let Some(session) = sessions.get(session_name) {
                return Ok(session.clone());
            }
        }

        // If we don't have a session, establish a new one
        let session = self.establish_connected_session(session_name).await?;

        // Store the new session
        let mut sessions = self.connected_sessions.lock().await;
        sessions.insert(session_name.to_string(), session.clone());

        Ok(session)
    }

    /// Enhanced UDT structure parser - tries multiple parsing strategies
    #[allow(dead_code)]
    fn parse_udt_structure(&self, data: &[u8]) -> crate::error::Result<PlcValue> {
        tracing::debug!("Parsing UDT structure with {} bytes", data.len());

        // Strategy 1: Try to parse as TestTagUDT structure (DINT, DINT, REAL)
        if data.len() >= 12 {
            let _offset = 0;

            // Try different byte alignments and interpretations
            for alignment in 0..4 {
                if alignment + 12 <= data.len() {
                    let aligned_data = &data[alignment..];

                    // Parse first DINT
                    if aligned_data.len() >= 4 {
                        let dint1_bytes = [
                            aligned_data[0],
                            aligned_data[1],
                            aligned_data[2],
                            aligned_data[3],
                        ];
                        let dint1_value = i32::from_le_bytes(dint1_bytes);

                        // Parse second DINT
                        if aligned_data.len() >= 8 {
                            let dint2_bytes = [
                                aligned_data[4],
                                aligned_data[5],
                                aligned_data[6],
                                aligned_data[7],
                            ];
                            let dint2_value = i32::from_le_bytes(dint2_bytes);

                            // Parse REAL
                            if aligned_data.len() >= 12 {
                                let real_bytes = [
                                    aligned_data[8],
                                    aligned_data[9],
                                    aligned_data[10],
                                    aligned_data[11],
                                ];
                                let real_value = f32::from_le_bytes(real_bytes);

                                tracing::trace!(
                                    "Alignment {}: DINT1={}, DINT2={}, REAL={}",
                                    alignment,
                                    dint1_value,
                                    dint2_value,
                                    real_value
                                );

                                // Check if this looks like reasonable values
                                if self.is_reasonable_udt_values(
                                    dint1_value,
                                    dint2_value,
                                    real_value,
                                ) {
                                    // Legacy parsing - return raw data with symbol_id=0
                                    // Note: These methods are deprecated in favor of generic UdtData approach
                                    tracing::debug!(
                                        "Found reasonable UDT values at alignment {}",
                                        alignment
                                    );
                                    return Ok(PlcValue::Udt(UdtData {
                                        symbol_id: 0, // Not available in this context
                                        data: data.to_vec(),
                                    }));
                                }
                            }
                        }
                    }
                }
            }
        }

        // Strategy 2: Try to parse as simple packed structure
        if data.len() >= 4 {
            // Try different interpretations of the data
            let interpretations = vec![
                ("DINT_at_start", 0, 4),
                ("DINT_at_end", data.len().saturating_sub(4), data.len()),
                ("DINT_middle", data.len() / 2, data.len() / 2 + 4),
            ];

            for (name, start, end) in interpretations {
                if end <= data.len() && end > start {
                    let bytes = &data[start..end];
                    if bytes.len() == 4 {
                        let dint_value =
                            i32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
                        tracing::trace!("{}: DINT = {}", name, dint_value);

                        if self.is_reasonable_value(dint_value) {
                            // Legacy parsing - return raw data with symbol_id=0
                            return Ok(PlcValue::Udt(UdtData {
                                symbol_id: 0, // Not available in this context
                                data: data.to_vec(),
                            }));
                        }
                    }
                }
            }
        }

        Err(crate::error::EtherNetIpError::Protocol(
            "Could not parse UDT structure".to_string(),
        ))
    }

    /// Simple UDT parser fallback
    /// Note: This is a legacy method. New code should use generic UdtData approach.
    #[allow(dead_code)]
    fn parse_udt_simple(&self, data: &[u8]) -> crate::error::Result<PlcValue> {
        // Legacy parsing - return raw data with symbol_id=0
        Ok(PlcValue::Udt(UdtData {
            symbol_id: 0, // Not available in this context
            data: data.to_vec(),
        }))
    }

    /// Check if UDT values look reasonable
    #[allow(dead_code)]
    fn is_reasonable_udt_values(&self, dint1: i32, dint2: i32, real: f32) -> bool {
        // Check for reasonable ranges
        let dint1_reasonable = (-1000..=1000).contains(&dint1);
        let dint2_reasonable = (-1000..=1000).contains(&dint2);
        let real_reasonable = (-1000.0..=1000.0).contains(&real) && real.is_finite();

        tracing::trace!(
            "Reasonableness check: DINT1={} ({}), DINT2={} ({}), REAL={} ({})",
            dint1,
            dint1_reasonable,
            dint2,
            dint2_reasonable,
            real,
            real_reasonable
        );

        dint1_reasonable && dint2_reasonable && real_reasonable
    }

    /// Check if a single value looks reasonable
    #[allow(dead_code)]
    fn is_reasonable_value(&self, value: i32) -> bool {
        (-1000..=1000).contains(&value)
    }
}

/*
===============================================================================
END OF LIBRARY DOCUMENTATION

This file provides a complete, production-ready EtherNet/IP communication
library for Allen-Bradley PLCs. The library includes:

- Native Rust API with async support
- C FFI exports for cross-language integration
- Comprehensive error handling and validation
- Detailed documentation and examples
- Performance optimizations
- Memory safety guarantees

For usage examples, see the main.rs file or the C# integration samples.

For technical details about the EtherNet/IP protocol implementation,
refer to the inline documentation above.

Version: 1.0.0
Compatible with: CompactLogix L1x-L5x series PLCs
License: As specified in Cargo.toml
===============================================================================_
*/