autocore-std 3.3.66

Standard library for AutoCore control programs - shared memory, IPC, and logging utilities
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
//! Stateful motion controller for CiA 402 servo drives.
//!
//! [`Axis`] manages the CiA 402 protocol state machine internally,
//! providing a clean high-level motion API. It owns an [`SdoClient`]
//! for SDO operations during homing.
//!
//! # Usage
//!
//! ```ignore
//! use autocore_std::motion::{Axis, AxisConfig};
//!
//! let config = AxisConfig::new(12_800).with_user_scale(360.0);
//! let mut axis = Axis::new(config, "ClearPath_0");
//!
//! // In your control loop:
//! axis.tick(&mut view, ctx.client);
//!
//! // Command the axis:
//! axis.enable(&mut view);              // start enable sequence
//! axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);
//! axis.home(&mut view, HomingMethod::CurrentPosition35); // AKD; CurrentPosition37 elsewhere
//! ```

use std::collections::VecDeque;
use std::time::{Duration, Instant};

use serde_json::json;
use strum_macros::FromRepr;

use super::axis_config::AxisConfig;
use super::axis_view::AxisView;
use super::cia402::{
    Cia402Control, Cia402State, Cia402Status, ModesOfOperation, RawControlWord, RawStatusWord,
};
use super::homing::HomingMethod;
use crate::command_client::CommandClient;
use crate::ethercat::{SdoClient, SdoResult};
use crate::fb::Ton;
use crate::motion::FbSetModeOfOperation;

// ──────────────────────────────────────────────
// Internal state machine
// ──────────────────────────────────────────────

#[derive(Debug, Clone, PartialEq)]
enum AxisOp {
    Idle,
    Enabling(u8),
    Disabling(u8),
    Moving(MoveKind, u8, bool, bool),
    Homing(u8),
    SoftHoming(u8),
    Halting(u8),
    FaultRecovery(u8),
}

/// Sub-steps of `AxisOp::Halting`.
///
/// The set-point queue is flushed by **toggling the mode of operation** (PP →
/// Homing → PP) rather than by the CiA-402 set-point-acknowledge cancel
/// handshake. A mode change resets the drive's positioning function
/// deterministically, so there is no `SP_ACK` to coax out of the drive — which
/// removed three separate drive-specific failure modes on the Kollmorgen AKD
/// (won't-ack-while-halted, won't-ack-with-bit-5, won't-ack-zero-velocity).
/// This is the same mechanism (and `FbSetModeOfOperation`, with SDO
/// write + 0x6061 read-back) that homing already uses.
#[repr(u8)]
#[derive(Debug, Clone, PartialEq, FromRepr)]
enum HaltState {
    /// Halt bit set + new_setpoint cleared. Polling position for stability
    /// before flushing the queue.
    WaitStopped = 0,
    /// Flushing the set-point queue via the shared mode toggle ([`FbFlushQueue`]).
    /// Halt stays asserted until the flush completes; then it is released.
    Flushing = 10,
}

// ──────────────────────────────────────────────
// Shared set-point-queue flush
// ──────────────────────────────────────────────

/// Phase of a [`FbFlushQueue`] mode toggle.
#[derive(Debug, Clone, Copy, PartialEq)]
enum FlushPhase {
    Idle,
    /// Switching the mode of operation AWAY from PP (to Homing).
    Away,
    /// Switching the mode of operation BACK to PP.
    Back,
    Done,
    Error,
}

/// The **one** way the FB flushes a CiA-402 drive's set-point queue: toggle the
/// mode of operation PP → Homing → PP. A mode change resets the positioning
/// function deterministically, so there is no set-point-acknowledge handshake to
/// coax out of the drive (which removed three drive-specific AKD failure modes).
/// Shared by the halt close-out and both soft-homing stops so there is a single
/// queue-flush mechanism rather than several near-identical ones.
///
/// Drive with [`start`](Self::start) then [`tick`](Self::tick) until
/// `!is_busy()`, then check [`is_error`](Self::is_error). The mode switch goes
/// over SDO (write 0x6060 + read-back 0x6061 via [`FbSetModeOfOperation`]), the
/// same path homing uses — required by drives that pin mode by SDO (the AKD).
#[derive(Debug, Clone)]
struct FbFlushQueue {
    phase: FlushPhase,
    mode_fb: FbSetModeOfOperation,
}

impl FbFlushQueue {
    fn new() -> Self {
        Self { phase: FlushPhase::Idle, mode_fb: FbSetModeOfOperation::new() }
    }

    /// Begin the flush: switch the mode AWAY from PP (to Homing).
    fn start(&mut self, view: &mut impl AxisView, client: &mut CommandClient, sdo: &mut SdoClient) {
        self.begin_switch(view, client, sdo, ModesOfOperation::Homing);
        self.phase = FlushPhase::Away;
    }

    fn begin_switch(
        &mut self,
        view: &mut impl AxisView,
        client: &mut CommandClient,
        sdo: &mut SdoClient,
        mode: ModesOfOperation,
    ) {
        view.set_modes_of_operation(mode.as_i8());
        self.mode_fb.reset();
        self.mode_fb.start(mode.as_i8());
        self.mode_fb.tick(client, sdo);
    }

    fn tick(&mut self, view: &mut impl AxisView, client: &mut CommandClient, sdo: &mut SdoClient) {
        match self.phase {
            FlushPhase::Away => {
                self.mode_fb.tick(client, sdo);
                if !self.mode_fb.is_busy() {
                    if self.mode_fb.is_error() {
                        self.phase = FlushPhase::Error;
                    } else {
                        // Queue flushed; switch BACK to PP.
                        self.begin_switch(view, client, sdo, ModesOfOperation::ProfilePosition);
                        self.phase = FlushPhase::Back;
                    }
                }
            }
            FlushPhase::Back => {
                self.mode_fb.tick(client, sdo);
                if !self.mode_fb.is_busy() {
                    self.phase = if self.mode_fb.is_error() {
                        FlushPhase::Error
                    } else {
                        FlushPhase::Done
                    };
                }
            }
            _ => {}
        }
    }

    fn is_busy(&self) -> bool {
        matches!(self.phase, FlushPhase::Away | FlushPhase::Back)
    }
    fn is_error(&self) -> bool {
        self.phase == FlushPhase::Error
    }
    fn error_code(&self) -> i32 {
        self.mode_fb.error_code()
    }
    fn error_message(&self) -> String {
        self.mode_fb.error_message()
    }
}

/// How long each halt sub-stage may take before we error out.
const HALT_STAGE_TIMEOUT: Duration = Duration::from_secs(3);

/// Raw-encoder-count window within which the axis is considered "stopped."
/// Sized to tolerate servo micro-oscillation during closed-loop hold.
/// On a 10 000 cnt/mm drive this is 0.005 mm — below any meaningful
/// motion but well above typical ±5 count hold jitter.
const HALT_STABLE_WINDOW: i32 = 50;

/// Velocity magnitude (in raw drive units, typically counts/s) at or
/// below which the axis is considered "not moving" for the purposes of
/// completing a halt. Used alongside position stability so we don't
/// require *both* perfect position and zero velocity — either reliable
/// indicator counts.
const HALT_STOPPED_VELOCITY: i32 = 100;

/// Consecutive ticks of stability required before issuing cancel_move.
/// At a 10 ms scan period, 5 ticks = ~50 ms dwell — long enough for the
/// drive to have actually settled, short enough not to stall the cycle.
const HALT_STABLE_TICKS_REQUIRED: u8 = 5;

#[repr(u8)]
#[derive(Debug, Clone, PartialEq, FromRepr)]
enum HomeState {
    EnsurePpMode = 0,
    WaitPpMode = 1,
    Search = 5,
    WaitSearching = 10,
    WaitFoundSensor = 20,
    WaitStoppedFoundSensor = 30,
    /// Flushing the set-point queue at the found-sensor stop (shared mode toggle).
    FlushingFound = 40,
    DebounceFoundSensor = 50,
    BackOff = 60,
    WaitBackingOff = 70,
    WaitLostSensor = 80,
    WaitStoppedLostSensor = 90,
    /// Flushing the set-point queue at the lost-sensor stop (shared mode toggle).
    FlushingLost = 100,
    /// Drive-side "set reference at present position" entry: write 0x607C =
    /// home_position, then run the drive's current-position homing method.
    WriteHomeOffset = 120,
    WaitHomeOffsetDone = 125,
    /// DIAGNOSTIC: read 0x607C straight back to confirm the drive stored it.
    WaitHomeOffsetReadback = 130,

    WriteHomingModeOp = 160,
    WaitWriteHomingModeOp = 165,

    WriteHomingMethod = 205,
    WaitWriteHomingMethodDone = 210,
    ClearHomingTrigger = 215,
    TriggerHoming = 217,
    WaitHomingStarted = 218,
    WaitHomingDone = 220,
    ResetHomingTrigger = 222,
    WaitHomingTriggerCleared = 223,
    /// After homing, before the PP-mode switch: align target (0x607A) with the
    /// just-homed actual (0x6064) and let one RxPDO cycle carry it to the drive,
    /// so PP re-entry has no demand/actual error to chase (the runaway).
    AlignTargetBeforePP = 225,
    WriteMotionModeOfOperation = 230,
    WaitWriteMotionModeOfOperation = 235,
    SendCurrentPositionTarget = 240,
    WaitCurrentPositionTargetSent = 245,
}

#[derive(Debug, Clone, PartialEq)]
enum MoveKind {
    Absolute,
    Relative,
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum SoftHomeSensor {
    PositiveLimit,
    NegativeLimit,
    HomeSensor,
}

#[derive(Debug, Clone, Copy, PartialEq)]
enum SoftHomeSensorType {
    /// PNP: sensor reads true when object detected (normally open)
    Pnp,
    /// NPN: sensor reads false when object detected (normally closed)
    Npn,
}

// ──────────────────────────────────────────────
// Axis
// ──────────────────────────────────────────────

/// Stateful motion controller for a CiA 402 servo drive.
///
/// Manages the CiA 402 protocol (state machine, PP handshake, homing)
/// internally. Call [`tick()`](Self::tick) every control cycle to progress
/// operations and update output fields.
/// How many control-word/status-word *transitions* the per-axis trace keeps.
/// Recorded only on change, so this is an event history, not a per-tick log —
/// 48 transitions comfortably covers an enable → move → halt → cancel sequence.
const CW_SW_TRACE_CAP: usize = 48;

/// One entry in the CiA-402 transition trace: the op-state and the
/// control/status words at the moment one of them changed.
#[derive(Clone)]
struct TraceEntry {
    seq: u32,
    op: AxisOp,
    cw: u16,
    sw: u16,
}

/// Decode the PP-relevant control-word bits into a compact `A|B|C` string.
fn decode_cw(cw: u16) -> String {
    const BITS: [(u16, &str); 9] = [
        (0, "SwOn"),
        (1, "EnVolt"),
        (2, "QStop"),
        (3, "EnOp"),
        (4, "NewSP"),
        (5, "ChgSet"),
        (6, "Rel"),
        (7, "FltRst"),
        (8, "HALT"),
    ];
    let f: Vec<&str> = BITS
        .iter()
        .filter(|(b, _)| cw & (1 << b) != 0)
        .map(|(_, n)| *n)
        .collect();
    if f.is_empty() {
        "-".to_string()
    } else {
        f.join("|")
    }
}

/// Decode the status word: the CiA-402 state plus the PP handshake bits.
fn decode_sw(sw: u16) -> String {
    let mut f = vec![format!("{}", RawStatusWord(sw).state())];
    for (bit, name) in [
        (10, "TgtReached"),
        (11, "IntLim"),
        (12, "SP_ACK"),
        (13, "FollowErr"),
    ] {
        if sw & (1 << bit) != 0 {
            f.push(name.to_string());
        }
    }
    f.join("|")
}

pub struct Axis {
    config: AxisConfig,
    sdo: SdoClient,

    // ── Internal state ──
    op: AxisOp,
    home_offset: i32,
    last_raw_position: i32,
    op_started: Option<Instant>,
    op_timeout: Duration,
    homing_timeout: Duration,
    move_start_timeout: Duration,
    pending_move_target: i32,
    pending_move_vel: u32,
    pending_move_accel: u32,
    pending_move_decel: u32,
    homing_method: i8,
    homing_sdo_tid: u32,
    soft_home_sensor: SoftHomeSensor,
    soft_home_sensor_type: SoftHomeSensorType,
    soft_home_direction: f64,
    halt_stable_count: u8,
    prev_positive_limit: bool,
    prev_negative_limit: bool,
    prev_home_sensor: bool,

    // ── CiA-402 transition trace (debugging aid) ──
    cw_sw_trace: VecDeque<TraceEntry>,
    trace_seq: u32,

    fb_mode_of_operation: FbSetModeOfOperation,
    /// Shared set-point-queue flush (mode toggle) used by the halt close-out
    /// and both soft-homing stops.
    flush: FbFlushQueue,

    // ── Outputs (updated every tick) ──
    /// True if a drive fault or operation timeout has occurred.
    pub is_error: bool,
    /// Drive error code (from status word or view error_code).
    pub error_code: u32,
    /// Human-readable error description.
    pub error_message: String,
    /// True when the drive is in Operation Enabled state.
    pub motor_on: bool,
    /// True when any operation is in progress (enable, move, home, fault recovery, etc.).
    ///
    /// Derived from the internal state machine — immediately true when a command
    /// is issued, false when the operation completes or a fault cancels it.
    /// Use this (not [`in_motion`](Self::in_motion)) to wait for operations to finish.
    pub is_busy: bool,
    /// True while a move operation specifically is active (subset of [`is_busy`](Self::is_busy)).
    pub in_motion: bool,
    /// True when velocity is positive.
    pub moving_positive: bool,
    /// True when velocity is negative.
    pub moving_negative: bool,
    /// Current position in user units (relative to home).
    pub position: f64,
    /// Current position in raw encoder counts (widened from i32).
    pub raw_position: i64,
    /// Current speed in user units/s (absolute value).
    pub speed: f64,
    /// True when position is at or beyond the maximum software limit.
    pub at_max_limit: bool,
    /// True when position is at or beyond the minimum software limit.
    pub at_min_limit: bool,
    /// True when the positive-direction hardware limit switch is active.
    pub at_positive_limit_switch: bool,
    /// True when the negative-direction hardware limit switch is active.
    pub at_negative_limit_switch: bool,
    /// True when the home reference sensor is active.
    pub home_sensor: bool,

    /// Timer used for delays between states.
    ton: Ton,
}

impl Axis {
    /// Create a new Axis with the given configuration.
    ///
    /// `device_name` must match the device name in `project.json`
    /// (used for SDO operations during homing).
    pub fn new(config: AxisConfig, device_name: &str) -> Self {
        let op_timeout = Duration::from_secs_f64(config.operation_timeout_secs);
        let homing_timeout = Duration::from_secs_f64(config.homing_timeout_secs);
        let move_start_timeout = op_timeout; // reuse operation timeout for move handshake
        Self {
            config,
            sdo: SdoClient::new(device_name),
            op: AxisOp::Idle,
            home_offset: 0,
            last_raw_position: 0,
            op_started: None,
            op_timeout,
            homing_timeout,
            move_start_timeout,
            pending_move_target: 0,
            pending_move_vel: 0,
            pending_move_accel: 0,
            pending_move_decel: 0,
            homing_method: 37,
            homing_sdo_tid: 0,
            soft_home_sensor: SoftHomeSensor::HomeSensor,
            soft_home_sensor_type: SoftHomeSensorType::Pnp,
            soft_home_direction: 1.0,
            halt_stable_count: 0,
            prev_positive_limit: false,
            prev_negative_limit: false,
            prev_home_sensor: false,
            cw_sw_trace: VecDeque::new(),
            trace_seq: 0,
            is_error: false,
            error_code: 0,
            error_message: String::new(),
            motor_on: false,
            is_busy: false,
            in_motion: false,
            moving_positive: false,
            moving_negative: false,
            position: 0.0,
            raw_position: 0,
            speed: 0.0,
            at_max_limit: false,
            at_min_limit: false,
            at_positive_limit_switch: false,
            at_negative_limit_switch: false,
            home_sensor: false,
            ton: Ton::new(),
            fb_mode_of_operation: FbSetModeOfOperation::new(),
            flush: FbFlushQueue::new(),
        }
    }

    /// Get a reference to the axis configuration.
    pub fn config(&self) -> &AxisConfig {
        &self.config
    }

    // ═══════════════════════════════════════════
    // Motion commands
    // ═══════════════════════════════════════════

    /// Start an absolute move to `target` in user units.
    ///
    /// The axis must be enabled (Operation Enabled) before calling this.
    /// If the target exceeds a software position limit, the move is rejected
    /// and [`is_error`](Self::is_error) is set.
    pub fn move_absolute(
        &mut self,
        view: &mut impl AxisView,
        target: f64,
        vel: f64,
        accel: f64,
        decel: f64,
    ) {
        if let Some(msg) = self.check_target_limit(target, view) {
            self.set_op_error(&msg);
            return;
        }

        let cpu = self.config.counts_per_user();
        let raw_target = self.config.to_counts(target).round() as i32 + self.home_offset;
        let raw_vel = (vel * cpu).round() as u32;
        let raw_accel = (accel * cpu).round() as u32;
        let raw_decel = (decel * cpu).round() as u32;

        // User-frame direction (consistent with sw_max/sw_min and hw_pos/hw_neg).
        let user_pos = target > self.position;
        let user_neg = target < self.position;

        self.start_move(
            view,
            raw_target,
            raw_vel,
            raw_accel,
            raw_decel,
            MoveKind::Absolute,
            user_pos,
            user_neg,
        );
    }

    /// Start a relative move by `distance` user units from the current position.
    ///
    /// The axis must be enabled (Operation Enabled) before calling this.
    /// If the resulting position would exceed a software position limit,
    /// the move is rejected and [`is_error`](Self::is_error) is set.
    pub fn move_relative(
        &mut self,
        view: &mut impl AxisView,
        distance: f64,
        vel: f64,
        accel: f64,
        decel: f64,
    ) {
        log::info!(
            "Axis: request to move relative dist {} vel {} accel {} decel {}",
            distance,
            vel,
            accel,
            decel
        );

        if let Some(msg) = self.check_target_limit(self.position + distance, view) {
            self.set_op_error(&msg);
            return;
        }

        let cpu = self.config.counts_per_user();
        let raw_distance = self.config.to_counts(distance).round() as i32;
        let raw_vel = (vel * cpu).round() as u32;
        let raw_accel = (accel * cpu).round() as u32;
        let raw_decel = (decel * cpu).round() as u32;

        log::info!("Axis starting relative move: request to move relative raw dist {} raw vel {} raw accel {} raw decel {}",
            raw_distance, raw_vel, raw_accel, raw_decel
        );

        // Make sure bit 4 is off so that a new move can be commanded.
        let mut cw = RawControlWord(view.control_word());
        cw.set_bit(4, false); // new set-point
        view.set_control_word(cw.raw());

        // User-frame direction is the sign of `distance` (which is in user units).
        let user_pos = distance > 0.0;
        let user_neg = distance < 0.0;

        self.start_move(
            view,
            raw_distance,
            raw_vel,
            raw_accel,
            raw_decel,
            MoveKind::Relative,
            user_pos,
            user_neg,
        );
    }

    fn start_move(
        &mut self,
        view: &mut impl AxisView,
        raw_target: i32,
        raw_vel: u32,
        raw_accel: u32,
        raw_decel: u32,
        kind: MoveKind,
        user_pos: bool,
        user_neg: bool,
    ) {
        self.pending_move_target = raw_target;
        self.pending_move_vel = raw_vel;
        self.pending_move_accel = raw_accel;
        self.pending_move_decel = raw_decel;

        // Set parameters on view
        view.set_target_position(raw_target);
        view.set_profile_velocity(raw_vel);
        view.set_profile_acceleration(raw_accel);
        view.set_profile_deceleration(raw_decel);

        // Set control word: relative bit + trigger (new set-point).
        // We also clear halt as belt-and-suspenders — limit-switch halts and
        // explicit halt() both flow through the Halting state machine, which
        // ends with halt already cleared, so this is normally a no-op.
        let mut cw = RawControlWord(view.control_word());
        cw.set_bit(6, kind == MoveKind::Relative);
        cw.set_bit(8, false); // clear halt
        cw.set_bit(4, true); // new set-point
        view.set_control_word(cw.raw());

        // pos/neg stored in AxisOp::Moving are USER-frame so that check_limits
        // can compare them directly against user-frame software limits and
        // the integrator's user-frame limit-switch wiring without an
        // axis-inversion swap.
        self.op = AxisOp::Moving(kind, 1, user_pos, user_neg);
        self.op_started = Some(Instant::now());
    }

    /// Halt the current move (decelerate to stop).
    ///
    /// This is a **multi-tick** operation. `halt()` starts the sequence:
    ///
    /// 1. Halt bit (CW 8) set, new_setpoint (CW 4) cleared.
    /// 2. Wait for motor position to stabilize for ~100 ms.
    /// 3. Issue cancel_move with current_position as target.
    /// 4. Wait for setpoint_ack (SW 12) + target_reached (SW 10).
    /// 5. Clear new_setpoint, set single_setpoint (CW 5).
    /// 6. Wait for setpoint_ack to drop.
    /// 7. Return to Idle.
    ///
    /// [`is_busy`](Self::is_busy) stays `true` for the whole sequence.
    /// Callers that wait on `!is_busy()` after `halt()` (e.g.
    /// [`super::move_to_load::MoveToLoad`]) will correctly block until
    /// the drive's PP handshake is fully cleaned up, preventing a
    /// "set-point not acknowledged" timeout on the *next* move.
    pub fn halt(&mut self, view: &mut impl AxisView) {
        self.command_halt(view);
        self.halt_stable_count = 0;
        self.last_raw_position = view.position_actual();
        self.op_started = Some(Instant::now());
        self.op = AxisOp::Halting(HaltState::WaitStopped as u8);
    }

    // ═══════════════════════════════════════════
    // Drive control
    // ═══════════════════════════════════════════

    /// Start the enable sequence (Shutdown → ReadyToSwitchOn → OperationEnabled).
    ///
    /// The sequence is multi-tick. Check [`motor_on`](Self::motor_on) for completion.
    pub fn enable(&mut self, view: &mut impl AxisView) {
        // Step 0: set PP mode + cmd_shutdown
        view.set_modes_of_operation(ModesOfOperation::ProfilePosition.as_i8());
        let mut cw = RawControlWord(view.control_word());
        cw.cmd_shutdown();
        view.set_control_word(cw.raw());

        self.op = AxisOp::Enabling(1);
        self.op_started = Some(Instant::now());
    }

    /// Start the disable sequence (OperationEnabled → ReadyToSwitchOn).
    ///
    /// Uses the CiA 402 Shutdown command (controlword 0x06) rather than
    /// Disable Operation (0x07). Per the spec, "Switched On" leaves motor
    /// energization vendor-defined — Teknic and Inovance happen to
    /// de-energize, Kollmorgen AKD keeps holding current. "Ready To
    /// Switch On" has the HV section *guaranteed* off, so torque drops
    /// on every compliant drive.
    pub fn disable(&mut self, view: &mut impl AxisView) {
        // Cancel any pending move BEFORE dropping to Ready-To-Switch-On: re-point
        // the profile target (0x607A) at the current actual position and clear the
        // new-setpoint request. On the AKD the setpoint-ack (SW bit 12) can survive
        // a Shutdown, so without this the drive finishes the *old* move when it is
        // re-enabled and returns to Operation Enabled — a dangerous uncommanded
        // resume of motion after an abort / e-stop / fault.
        let here = view.position_actual();
        view.set_target_position(here);
        self.pending_move_target = here;

        let mut cw = RawControlWord(view.control_word());
        cw.cmd_shutdown();
        cw.set_bit(4, false);
        cw.set_bit(8, false);
        cw.set_bit(7, false);
        cw.set_bit(2, true);
        view.set_control_word(cw.raw());

        self.op = AxisOp::Disabling(1);
        self.op_started = Some(Instant::now());
    }

    /// Clear the axis error state.
    ///
    /// Two paths depending on whether the drive itself is faulted:
    ///
    /// - **Drive in CiA 402 Fault / FaultReactionActive**: runs the full
    ///   reset sequence — clear bit 7, then assert it next tick (rising
    ///   edge on the drive's fault-reset bit), then wait for the drive to
    ///   leave the Fault state. `is_busy` stays true through this sequence.
    ///
    /// - **Drive healthy** (e.g. the `is_error` was set by a software
    ///   software-limit overshoot, an operation timeout, or a limit-switch
    ///   close-out timeout — the drive itself is still in OperationEnabled):
    ///   no CiA 402 handshake is needed. Just clears the software error
    ///   flags and returns the axis to Idle synchronously. `is_busy` goes
    ///   to false on the same call.
    pub fn reset_faults(&mut self, view: &mut impl AxisView) {
        let sw = RawStatusWord(view.status_word());
        let drive_in_fault = matches!(
            sw.state(),
            Cia402State::Fault | Cia402State::FaultReactionActive
        );

        self.is_error = false;
        self.error_code = 0;
        self.error_message.clear();

        if drive_in_fault {
            // Step 0: clear bit 7 first (so next step produces a rising edge).
            let mut cw = RawControlWord(view.control_word());
            cw.cmd_clear_fault_reset();
            view.set_control_word(cw.raw());
            self.op = AxisOp::FaultRecovery(1);
            self.op_started = Some(Instant::now());
        } else {
            // Software-only error — no drive handshake needed.
            self.op = AxisOp::Idle;
            self.op_started = None;
            self.is_busy = false;
            self.in_motion = false;
        }
    }

    /// Start a homing sequence with the given homing method.
    ///
    /// **Integrated** methods delegate to the drive's built-in CiA 402
    /// homing mode (SDO writes + homing trigger).
    ///
    /// **Software** methods are implemented by the Axis, which monitors
    /// [`AxisView`] sensor signals for edge triggers and captures home.
    pub fn home(&mut self, view: &mut impl AxisView, method: HomingMethod) {
        match method {
            // "Set reference at present position" (CiA 402 method 35 or 37).
            // Write the reference value to 0x607C and run the drive's
            // current-position homing, so the DRIVE owns the position — no
            // software offset. The method code comes straight from the variant
            // (35 = AKD, 37 = most others), replacing the former standalone
            // set_position_persistent and the soft_home_method indirection.
            HomingMethod::CurrentPosition35 | HomingMethod::CurrentPosition37 => {
                self.homing_method = method.cia402_code();
                self.op = AxisOp::SoftHoming(HomeState::WriteHomeOffset as u8);
                self.op_started = Some(Instant::now());
                let _ = view;
            }
            // Other drive-native (integrated) homing methods: delegate to the
            // drive's built-in CiA 402 homing mode. Starts at step 16, which
            // writes the home offset (0x607C) so the reference the drive finds
            // reads as home_position, before the normal sequence at step 0.
            m if m.is_integrated() => {
                self.homing_method = m.cia402_code();
                self.op = AxisOp::Homing(16);
                self.op_started = Some(Instant::now());
                let _ = view;
            }
            // Software search homing — the Axis monitors sensor/limit signals,
            // then sets the found position with the drive's configured
            // current-position method (soft_home_method).
            m => {
                self.homing_method = self.config.soft_home_method;
                self.configure_soft_homing(m);
                self.start_soft_homing(view);
            }
        }
    }

    // ═══════════════════════════════════════════
    // Position management
    // ═══════════════════════════════════════════

    /// Set the current position to the given user-unit value.
    ///
    /// Adjusts the internal home offset so that the current raw position
    /// maps to `user_units`. Does not move the motor.
    pub fn set_position(&mut self, view: &impl AxisView, user_units: f64) {
        self.home_offset =
            view.position_actual() - self.config.to_counts(user_units).round() as i32;
    }

    /// Set the home position in user units. This value is used by the next
    /// `home()` call to set the axis position at the reference point.
    /// Can be called at any time before homing.
    pub fn set_home_position(&mut self, user_units: f64) {
        self.config.home_position = user_units;
    }

    /// Set the maximum (positive) software position limit.
    pub fn set_software_max_limit(&mut self, user_units: f64) {
        self.config.max_position_limit = user_units;
        self.config.enable_max_position_limit = true;
    }

    /// Set the minimum (negative) software position limit.
    pub fn set_software_min_limit(&mut self, user_units: f64) {
        self.config.min_position_limit = user_units;
        self.config.enable_min_position_limit = true;
    }

    // ═══════════════════════════════════════════
    // SDO pass-through
    // ═══════════════════════════════════════════

    /// Write an SDO value to the drive.
    pub fn sdo_write(
        &mut self,
        client: &mut CommandClient,
        index: u16,
        sub_index: u8,
        value: serde_json::Value,
    ) {
        self.sdo.write(client, index, sub_index, value);
    }

    /// Start an SDO read from the drive. Returns a transaction ID.
    pub fn sdo_read(&mut self, client: &mut CommandClient, index: u16, sub_index: u8) -> u32 {
        self.sdo.read(client, index, sub_index)
    }

    /// Check the result of a previous SDO read.
    pub fn sdo_result(&mut self, client: &mut CommandClient, tid: u32) -> SdoResult {
        self.sdo.result(client, tid, Duration::from_secs(5))
    }

    // ═══════════════════════════════════════════
    // Tick — call every control cycle
    // ═══════════════════════════════════════════

    /// Update outputs and progress the current operation.
    ///
    /// Must be called every control cycle. Does three things:
    /// 1. Checks for drive faults
    /// 2. Progresses the current multi-tick operation
    /// 3. Updates output fields (position, velocity, status)
    ///
    /// Outputs are updated last so they reflect the final state after
    /// all processing for this tick.
    pub fn tick(&mut self, view: &mut impl AxisView, client: &mut CommandClient) {
        self.check_faults(view);
        self.progress_op(view, client);
        self.update_outputs(view);
        self.check_limits(view);
        self.record_trace(view);
    }

    // ═══════════════════════════════════════════
    // Internal: CiA-402 transition trace (debug aid)
    // ═══════════════════════════════════════════

    /// Append to the trace if the op-state or the control/status words changed
    /// since the last entry. Change-driven, so a multi-second stall (e.g. a halt
    /// waiting on set-point-acknowledge) costs a single line, not one per tick.
    fn record_trace(&mut self, view: &impl AxisView) {
        let cw = view.control_word();
        let sw = view.status_word();
        let changed = self
            .cw_sw_trace
            .back()
            .map_or(true, |e| e.cw != cw || e.sw != sw || e.op != self.op);
        if !changed {
            return;
        }
        if self.cw_sw_trace.len() >= CW_SW_TRACE_CAP {
            self.cw_sw_trace.pop_front();
        }
        self.cw_sw_trace.push_back(TraceEntry {
            seq: self.trace_seq,
            op: self.op.clone(),
            cw,
            sw,
        });
        self.trace_seq = self.trace_seq.wrapping_add(1);
    }

    /// The recent CiA-402 control/status-word transitions, decoded into a
    /// human-readable block. A debugging aid for handshake problems such as a
    /// halt-cancel timeout: each line shows the op-state, the control word (with
    /// `HALT`, `NewSP`, `ChgSet`, … flags) and the status word (CiA-402 state
    /// plus `SP_ACK`, `TgtReached`, …). Because entries are recorded only on
    /// change, this is a compact event log rather than a per-tick PDO dump.
    ///
    /// It is also dumped automatically to the log whenever an operation errors
    /// (see the `Axis error:` log line), so failures arrive with the sequence
    /// that produced them.
    pub fn trace(&self) -> String {
        let mut out = String::new();
        for e in &self.cw_sw_trace {
            out.push_str(&format!(
                "  [{:>4}] {:<20} CW={:#06x} [{}]  SW={:#06x} [{}]\n",
                e.seq,
                format!("{:?}", e.op),
                e.cw,
                decode_cw(e.cw),
                e.sw,
                decode_sw(e.sw),
            ));
        }
        out
    }

    // ═══════════════════════════════════════════
    // Internal: output update
    // ═══════════════════════════════════════════

    fn update_outputs(&mut self, view: &impl AxisView) {
        let raw = view.position_actual();
        self.raw_position = raw as i64;
        self.position = self.config.to_user((raw - self.home_offset) as f64);

        let vel = view.velocity_actual();
        let user_vel = self.config.to_user(vel as f64);
        self.speed = user_vel.abs();
        self.moving_positive = user_vel > 0.0;
        self.moving_negative = user_vel < 0.0;
        self.is_busy = self.op != AxisOp::Idle;
        self.in_motion = matches!(self.op, AxisOp::Moving(_, _, _, _) | AxisOp::SoftHoming(_));

        let sw = RawStatusWord(view.status_word());
        self.motor_on = sw.state() == Cia402State::OperationEnabled;

        self.last_raw_position = raw;
    }

    // ═══════════════════════════════════════════
    // Internal: fault check
    // ═══════════════════════════════════════════

    fn check_faults(&mut self, view: &impl AxisView) {
        let sw = RawStatusWord(view.status_word());
        let state = sw.state();

        if matches!(state, Cia402State::Fault | Cia402State::FaultReactionActive) {
            if !matches!(self.op, AxisOp::FaultRecovery(_)) {
                self.is_error = true;
                let ec = view.error_code();
                if ec != 0 {
                    self.error_code = ec as u32;
                }
                self.error_message = format!("Drive fault (state: {})", state);
                // Cancel the current operation so is_busy goes false
                self.op = AxisOp::Idle;
                self.op_started = None;
            }
        }
    }

    // ═══════════════════════════════════════════
    // Internal: operation timeout helper
    // ═══════════════════════════════════════════

    fn op_timed_out(&self) -> bool {
        self.op_started
            .map_or(false, |t| t.elapsed() > self.op_timeout)
    }

    fn homing_timed_out(&self) -> bool {
        self.op_started
            .map_or(false, |t| t.elapsed() > self.homing_timeout)
    }

    fn move_start_timed_out(&self) -> bool {
        self.op_started
            .map_or(false, |t| t.elapsed() > self.move_start_timeout)
    }

    /// Has the current operation exceeded the supplied stage timeout?
    /// Used by the halt state machine so each sub-stage gets its own
    /// budget rather than sharing the general `op_timeout`.
    fn op_stage_timed_out(&self, limit: Duration) -> bool {
        self.op_started.map_or(false, |t| t.elapsed() > limit)
    }

    fn set_op_error(&mut self, msg: &str) {
        self.is_error = true;
        self.error_message = msg.to_string();
        log::error!("Axis error: {}", msg);
        // Dump the CiA-402 handshake trace so failures (e.g. a halt-cancel
        // timeout) arrive with the control/status-word sequence that led to
        // them — far less data than logging every PDO every tick.
        if !self.cw_sw_trace.is_empty() {
            log::warn!(
                "Axis CiA-402 trace ({} recent transitions, oldest first):\n{}",
                self.cw_sw_trace.len(),
                self.trace(),
            );
        }
        self.op = AxisOp::Idle;
        self.op_started = None;
        self.is_busy = false;
        self.in_motion = false;
    }

    fn restore_pp_after_error(&mut self, msg: &str) {
        self.is_error = true;
        self.error_message = msg.to_string();
        self.op = AxisOp::SoftHoming(HomeState::WriteMotionModeOfOperation as u8);
        log::error!("Axis error: {}", msg);
    }

    fn finish_op_error(&mut self) {
        self.op = AxisOp::Idle;
        self.op_started = None;
        self.is_busy = false;
        self.in_motion = false;
    }

    fn complete_op(&mut self) {
        self.op = AxisOp::Idle;
        self.op_started = None;
        // Clear busy/motion flags directly so callers that observe state on
        // the same tick (e.g. check_limits, which runs after update_outputs)
        // see Idle immediately. For complete_op calls inside progress_op,
        // update_outputs would recompute these to the same values anyway.
        self.is_busy = false;
        self.in_motion = false;
    }

    // ═══════════════════════════════════════════
    // Internal: position limits and limit switches
    // ═══════════════════════════════════════════

    /// Resolve the effective maximum software limit for this tick, combining
    /// the static [`AxisConfig`] value (if enabled) with any dynamic limit
    /// supplied by the [`AxisView`] (e.g. a GM-linked variable). The most
    /// restrictive (smallest) value wins.
    fn effective_max_limit(&self, view: &impl AxisView) -> Option<f64> {
        let static_limit = if self.config.enable_max_position_limit {
            Some(self.config.max_position_limit)
        } else {
            None
        };
        match (static_limit, view.dynamic_max_position_limit()) {
            (Some(s), Some(d)) => Some(s.min(d)),
            (Some(v), None) | (None, Some(v)) => Some(v),
            (None, None) => None,
        }
    }

    /// Resolve the effective minimum software limit for this tick. See
    /// [`effective_max_limit`](Self::effective_max_limit) — the most
    /// restrictive (largest) value wins.
    fn effective_min_limit(&self, view: &impl AxisView) -> Option<f64> {
        let static_limit = if self.config.enable_min_position_limit {
            Some(self.config.min_position_limit)
        } else {
            None
        };
        match (static_limit, view.dynamic_min_position_limit()) {
            (Some(s), Some(d)) => Some(s.max(d)),
            (Some(v), None) | (None, Some(v)) => Some(v),
            (None, None) => None,
        }
    }

    /// Check whether a target position (in user units) exceeds a software limit.
    /// Returns `Some(error_message)` if the target is out of range, `None` if OK.
    /// Consults both the static [`AxisConfig`] limits and any dynamic limits
    /// exposed by the view, taking whichever is most restrictive.
    fn check_target_limit(&self, target: f64, view: &impl AxisView) -> Option<String> {
        if let Some(max) = self.effective_max_limit(view) {
            if target > max {
                return Some(format!(
                    "Target {:.3} exceeds max software limit {:.3}",
                    target, max
                ));
            }
        }
        if let Some(min) = self.effective_min_limit(view) {
            if target < min {
                return Some(format!(
                    "Target {:.3} exceeds min software limit {:.3}",
                    target, min
                ));
            }
        }
        None
    }

    /// Check software position limits, hardware limit switches, and home sensor.
    /// If a limit is violated and a move is in progress in that direction,
    /// halt the drive and set an error. Moving in the opposite direction is
    /// always allowed so the axis can be recovered.
    ///
    /// During software homing on a limit switch (`SoftHoming` + `SoftHomeSensor::PositiveLimit`
    /// or `NegativeLimit`), the homed-on switch is suppressed so it triggers a home
    /// event rather than an error halt. The opposite switch still protects.
    fn check_limits(&mut self, view: &mut impl AxisView) {
        // ── Software position limits (static config + dynamic GM-linked) ──
        let eff_max = self.effective_max_limit(view);
        let eff_min = self.effective_min_limit(view);
        let sw_max = eff_max.map_or(false, |m| self.position >= m);
        let sw_min = eff_min.map_or(false, |m| self.position <= m);

        self.at_max_limit = sw_max;
        self.at_min_limit = sw_min;

        // ── Hardware limit switches ──
        let hw_pos = view.positive_limit_active();
        let hw_neg = view.negative_limit_active();

        self.at_positive_limit_switch = hw_pos;
        self.at_negative_limit_switch = hw_neg;

        // ── Home sensor ──
        self.home_sensor = view.home_sensor_active();

        // ── Save previous sensor state for next tick's edge detection ──
        self.prev_positive_limit = hw_pos;
        self.prev_negative_limit = hw_neg;
        self.prev_home_sensor = view.home_sensor_active();

        // ── Halt logic (only while moving or soft-homing) ──
        let mut commanded_positive = false;
        let mut commanded_negative = false;

        let is_moving = matches!(self.op, AxisOp::Moving(_, _, _, _));
        let is_soft_homing = matches!(self.op, AxisOp::SoftHoming(_));

        if !is_moving && !is_soft_homing {
            return; // Only halt actively if we are currently driving into the limit
        }

        match &self.op {
            AxisOp::Moving(_, _, pos, neg) => {
                // Already user-frame (set by move_absolute / move_relative).
                commanded_positive = *pos;
                commanded_negative = *neg;
            }
            AxisOp::SoftHoming(_) => match self.soft_home_sensor {
                SoftHomeSensor::PositiveLimit => commanded_positive = true,
                SoftHomeSensor::NegativeLimit => commanded_negative = true,
                SoftHomeSensor::HomeSensor => {
                    commanded_positive = self.moving_positive;
                    commanded_negative = self.moving_negative;
                }
            },
            _ => {}
        }

        // During software homing, suppress the limit switch being homed on
        let suppress_pos = is_soft_homing && self.soft_home_sensor == SoftHomeSensor::PositiveLimit;
        let suppress_neg = is_soft_homing && self.soft_home_sensor == SoftHomeSensor::NegativeLimit;

        let effective_hw_pos = hw_pos && !suppress_pos;
        let effective_hw_neg = hw_neg && !suppress_neg;

        // During soft homing, suppress software limits too (we need to move freely)
        let effective_sw_max = sw_max && !is_soft_homing;
        let effective_sw_min = sw_min && !is_soft_homing;

        let positive_blocked = (effective_sw_max || effective_hw_pos) && commanded_positive;
        let negative_blocked = (effective_sw_min || effective_hw_neg) && commanded_negative;

        if positive_blocked || negative_blocked {
            let mut cw = RawControlWord(view.control_word());
            cw.set_bit(8, true); // halt
            view.set_control_word(cw.raw());

            let msg = if effective_hw_pos && commanded_positive {
                "Positive limit switch active".to_string()
            } else if effective_hw_neg && commanded_negative {
                "Negative limit switch active".to_string()
            } else if effective_sw_max && commanded_positive {
                format!(
                    "Software position limit: position {:.3} >= max {:.3}",
                    self.position,
                    eff_max.unwrap_or(self.position)
                )
            } else {
                format!(
                    "Software position limit: position {:.3} <= min {:.3}",
                    self.position,
                    eff_min.unwrap_or(self.position)
                )
            };

            if is_soft_homing {
                // Hitting the *opposite* limit during soft homing is a real
                // fault — the axis went the wrong way and must be reset.
                self.set_op_error(&msg);
            } else {
                // Regular move into a limit: enter the multi-stage Halting
                // close-out (wait for motor stop → cancel queued setpoint →
                // clear halt) so the drive ends in a clean state. Just
                // clearing halt isn't enough — the previous move's target is
                // still queued in the drive's PP buffer, and on the next
                // start_move some drives ignore the new setpoint until that
                // queued one is canceled.
                //
                // is_busy stays true through the close-out. Callers detect
                // why the move ended by inspecting
                // `at_positive_limit_switch` / `at_negative_limit_switch` /
                // `at_max_limit` / `at_min_limit` once `!is_busy()`.
                log::info!("Axis move halted by limit: {}", msg);
                self.command_halt(view);
                self.halt_stable_count = 0;
                self.last_raw_position = view.position_actual();
                self.op_started = Some(Instant::now());
                self.op = AxisOp::Halting(HaltState::WaitStopped as u8);
            }
        }
    }

    // ═══════════════════════════════════════════
    // Internal: operation progress
    // ═══════════════════════════════════════════

    fn progress_op(&mut self, view: &mut impl AxisView, client: &mut CommandClient) {
        match self.op.clone() {
            AxisOp::Idle => {}
            AxisOp::Enabling(step) => self.tick_enabling(view, step),
            AxisOp::Disabling(step) => self.tick_disabling(view, step),
            AxisOp::Moving(kind, step, pos, neg) => self.tick_moving(view, kind, step, pos, neg),
            AxisOp::Homing(step) => self.tick_homing(view, client, step),
            AxisOp::SoftHoming(step) => self.tick_soft_homing(view, client, step),
            AxisOp::Halting(step) => self.tick_halting(view, client, step),
            AxisOp::FaultRecovery(step) => self.tick_fault_recovery(view, step),
        }
    }

    // ── Enabling ──
    // Step 0: (done in enable()) ensure PP + cmd_shutdown
    // Step 1: wait ReadyToSwitchOn → cmd_enable_operation
    // Step 2: wait OperationEnabled → capture home → Idle
    fn tick_enabling(&mut self, view: &mut impl AxisView, step: u8) {
        match step {
            1 => {
                let sw = RawStatusWord(view.status_word());
                if sw.state() == Cia402State::ReadyToSwitchOn {
                    let mut cw = RawControlWord(view.control_word());
                    cw.cmd_enable_operation();
                    view.set_control_word(cw.raw());
                    self.op = AxisOp::Enabling(2);
                } else if self.op_timed_out() {
                    self.set_op_error("Enable timeout: waiting for ReadyToSwitchOn");
                }
            }
            2 => {
                let sw = RawStatusWord(view.status_word());
                if sw.state() == Cia402State::OperationEnabled {
                    // NO - We do not do software-based encoder. That would break absolute encoders.
                    // self.home_offset = view.position_actual();
                    // log::info!("Axis enabled — home captured at {}", self.home_offset);

                    // Possible TODO: Read the home_offset in the drive?

                    self.complete_op();
                } else if self.op_timed_out() {
                    self.set_op_error("Enable timeout: waiting for OperationEnabled");
                }
            }
            _ => self.complete_op(),
        }
    }

    // ── Disabling ──
    // Step 0: (done in disable()) cmd_shutdown
    // Step 1: wait not OperationEnabled → Idle
    fn tick_disabling(&mut self, view: &mut impl AxisView, step: u8) {
        match step {
            1 => {
                let sw = RawStatusWord(view.status_word());
                if sw.state() != Cia402State::OperationEnabled {
                    self.complete_op();
                } else if self.op_timed_out() {
                    self.set_op_error("Disable timeout: drive still in OperationEnabled");
                }
            }
            _ => self.complete_op(),
        }
    }

    // ── Moving ──
    // Step 0: (done in move_absolute/relative()) set params + trigger
    // Step 1: wait set_point_acknowledge → ack
    // Step 2: wait ack cleared (one tick)
    // Step 3: wait target_reached → Idle
    fn tick_moving(
        &mut self,
        view: &mut impl AxisView,
        kind: MoveKind,
        step: u8,
        pos: bool,
        neg: bool,
    ) {
        match step {
            1 => {
                // Wait for set-point acknowledge (bit 12)
                let sw = RawStatusWord(view.status_word());
                if sw.raw() & (1 << 12) != 0 {
                    // Ack: clear new set-point (bit 4)
                    let mut cw = RawControlWord(view.control_word());
                    cw.set_bit(4, false);
                    view.set_control_word(cw.raw());
                    self.op = AxisOp::Moving(kind, 2, pos, neg);
                } else if self.move_start_timed_out() {
                    self.set_op_error("Move timeout: set-point not acknowledged");
                }
            }
            2 => {
                // Wait for the drive to confirm it saw Bit 4 go low
                let sw = RawStatusWord(view.status_word());
                if sw.raw() & (1 << 12) == 0 {
                    // Handshake is officially reset. Now wait for physics.
                    self.op = AxisOp::Moving(kind, 3, pos, neg);
                }
            }
            3 => {
                // Wait for target reached (bit 10) — no timeout, moves can take arbitrarily long
                let sw = RawStatusWord(view.status_word());
                if sw.target_reached() {
                    self.complete_op();
                }
            }
            _ => self.complete_op(),
        }
    }

    // ── Homing (hardware-delegated) ──
    // Step 16: write home offset SDO (0x607C) — ENTRY POINT, so the found
    //          reference reads home_position (rarely zero)
    // Step 17: wait SDO ack, then → step 0
    // Step 0:  write homing method SDO (0x6098:0)
    // Step 1:  wait SDO ack
    // Step 2:  write homing speed SDO (0x6099:1 — search for switch)
    // Step 3:  wait SDO ack
    // Step 4:  write homing speed SDO (0x6099:2 — search for zero)
    // Step 5:  wait SDO ack
    // Step 6:  write homing accel SDO (0x609A:0)
    // Step 7:  wait SDO ack
    // Step 8:  switch to Homing mode (PDO field + SDO write 0x6060)
    // Step 9:  wait for Homing mode written + verified via SDO read-back (0x6061)
    // Step 10: trigger homing (rising edge on CW bit 4)
    // Step 11: wait for drive to acknowledge start (bit 12 clears)
    // Step 12: wait homing complete (bits 10+12 set, 13 clear)
    // Step 13: drive owns position (home_offset = 0), clear CW bit 4
    // Step 14: switch back to PP mode (PDO field + SDO write 0x6060)
    // Step 15: wait for PP mode written + verified, then → Idle
    //
    // If homing_speed and homing_accel are both 0, steps 2-7 are skipped
    // (preserves backward compatibility for users who pre-configure via SDO).
    //
    // Mode is switched AND verified over SDO (via FbSetModeOfOperation) rather
    // than trusting modes_of_operation_display(): on drives that don't PDO-map
    // 0x6060/0x6061 (e.g. Kollmorgen AKD) the cyclic display field is a codegen
    // stub mirrored from the commanded value, so it would falsely confirm.
    fn tick_homing(&mut self, view: &mut impl AxisView, client: &mut CommandClient, step: u8) {
        match step {
            0 => {
                // Write homing method via SDO (0x6098:0)
                self.homing_sdo_tid = self.sdo.write(client, 0x6098, 0, json!(self.homing_method));
                self.op = AxisOp::Homing(1);
            }
            1 => {
                // Wait for SDO write ack
                match self
                    .sdo
                    .result(client, self.homing_sdo_tid, Duration::from_secs(5))
                {
                    SdoResult::Ok(_) => {
                        // Skip speed/accel SDOs if both are zero
                        if self.config.homing_speed == 0.0 && self.config.homing_accel == 0.0 {
                            self.op = AxisOp::Homing(8);
                        } else {
                            self.op = AxisOp::Homing(2);
                        }
                    }
                    SdoResult::Pending => {
                        if self.homing_timed_out() {
                            self.set_op_error("Homing timeout: SDO write for homing method");
                        }
                    }
                    SdoResult::Err(e) => {
                        self.set_op_error(&format!("Homing SDO error: {}", e));
                    }
                    SdoResult::Timeout => {
                        self.set_op_error("Homing timeout: SDO write timed out");
                    }
                }
            }
            2 => {
                // Write homing speed (0x6099:1 — search for switch)
                let speed_counts = self.config.to_counts(self.config.homing_speed).round() as u32;
                self.homing_sdo_tid = self.sdo.write(client, 0x6099, 1, json!(speed_counts));
                self.op = AxisOp::Homing(3);
            }
            3 => {
                match self
                    .sdo
                    .result(client, self.homing_sdo_tid, Duration::from_secs(5))
                {
                    SdoResult::Ok(_) => {
                        self.op = AxisOp::Homing(4);
                    }
                    SdoResult::Pending => {
                        if self.homing_timed_out() {
                            self.set_op_error(
                                "Homing timeout: SDO write for homing speed (switch)",
                            );
                        }
                    }
                    SdoResult::Err(e) => {
                        self.set_op_error(&format!("Homing SDO error: {}", e));
                    }
                    SdoResult::Timeout => {
                        self.set_op_error("Homing timeout: SDO write timed out");
                    }
                }
            }
            4 => {
                // Write homing speed (0x6099:2 — search for zero, same value)
                let speed_counts = self.config.to_counts(self.config.homing_speed).round() as u32;
                self.homing_sdo_tid = self.sdo.write(client, 0x6099, 2, json!(speed_counts));
                self.op = AxisOp::Homing(5);
            }
            5 => {
                match self
                    .sdo
                    .result(client, self.homing_sdo_tid, Duration::from_secs(5))
                {
                    SdoResult::Ok(_) => {
                        self.op = AxisOp::Homing(6);
                    }
                    SdoResult::Pending => {
                        if self.homing_timed_out() {
                            self.set_op_error("Homing timeout: SDO write for homing speed (zero)");
                        }
                    }
                    SdoResult::Err(e) => {
                        self.set_op_error(&format!("Homing SDO error: {}", e));
                    }
                    SdoResult::Timeout => {
                        self.set_op_error("Homing timeout: SDO write timed out");
                    }
                }
            }
            6 => {
                // Write homing acceleration (0x609A:0)
                let accel_counts = self.config.to_counts(self.config.homing_accel).round() as u32;
                self.homing_sdo_tid = self.sdo.write(client, 0x609A, 0, json!(accel_counts));
                self.op = AxisOp::Homing(7);
            }
            7 => {
                match self
                    .sdo
                    .result(client, self.homing_sdo_tid, Duration::from_secs(5))
                {
                    SdoResult::Ok(_) => {
                        self.op = AxisOp::Homing(8);
                    }
                    SdoResult::Pending => {
                        if self.homing_timed_out() {
                            self.set_op_error("Homing timeout: SDO write for homing acceleration");
                        }
                    }
                    SdoResult::Err(e) => {
                        self.set_op_error(&format!("Homing SDO error: {}", e));
                    }
                    SdoResult::Timeout => {
                        self.set_op_error("Homing timeout: SDO write timed out");
                    }
                }
            }
            8 => {
                // Switch into Homing mode on BOTH channels:
                //  - the cyclic PDO field, so drives that PDO-map 0x6060 carry the
                //    correct mode on the wire, and
                //  - an SDO write + read-back of 0x6060/0x6061 (FbSetModeOfOperation),
                //    so drives that pin mode by SDO (e.g. Kollmorgen AKD, which does
                //    not PDO-map mode) actually transition AND are verified.
                // The SDO read-back replaces the old modes_of_operation_display()
                // check, which silently passed on PDO-unmapped drives because codegen
                // mirrors the commanded value into the display stub.
                view.set_modes_of_operation(ModesOfOperation::Homing.as_i8());
                // Ensure CW bit 4 starts LOW so the next step issues a clean rising edge.
                let mut cw = RawControlWord(view.control_word());
                cw.set_bit(4, false);
                view.set_control_word(cw.raw());
                self.fb_mode_of_operation.reset();
                self.fb_mode_of_operation
                    .start(ModesOfOperation::Homing as i8);
                self.fb_mode_of_operation.tick(client, &mut self.sdo);
                self.op = AxisOp::Homing(9);
            }
            9 => {
                // Wait for the mode switch to be written and verified over SDO.
                self.fb_mode_of_operation.tick(client, &mut self.sdo);
                if !self.fb_mode_of_operation.is_busy() {
                    if self.fb_mode_of_operation.is_error() {
                        self.set_op_error(&format!(
                            "Homing: failed to enter Homing mode: {} {}",
                            self.fb_mode_of_operation.error_code(),
                            self.fb_mode_of_operation.error_message()
                        ));
                    } else {
                        self.op = AxisOp::Homing(10);
                    }
                }
            }
            10 => {
                // Trigger homing: rising edge on bit 4
                // DIAGNOSTIC: position_actual just before triggering, to compare
                // against the post-home value (step 13) — tells us whether the
                // drive's method actually changes 0x6064 or only sets the bit.
                log::info!(
                    "Homing[trigger]: method={} position_actual(0x6064) BEFORE = {}",
                    self.homing_method,
                    view.position_actual(),
                );
                let mut cw = RawControlWord(view.control_word());
                cw.set_bit(4, true);
                view.set_control_word(cw.raw());
                self.op = AxisOp::Homing(11);
            }
            11 => {
                // One drive cycle after the trigger edge, then evaluate completion.
                //
                // We deliberately do NOT wait for bit 12 (homing attained) to clear
                // first. That old start-gate assumed the drive de-asserts attained at
                // the start of a new run and re-asserts on completion — true for
                // methods that take time to run, but an instantaneous method (35/37,
                // set-current-position) completes within one cycle, so bit 12 goes
                // high immediately and is never observed low. The gate's original
                // purpose (rejecting a stale PP set-point acknowledge in bit 12) is
                // now covered by verifying mode 6 over SDO in steps 8–9 before we
                // ever trigger: once in Homing mode, bit 12 carries homing semantics.
                let sw = view.status_word();
                if sw & (1 << 13) != 0 {
                    self.set_op_error("Homing error: drive reported homing failure");
                } else {
                    self.op = AxisOp::Homing(12);
                }
            }
            12 => {
                // Wait for homing complete.
                //
                // Per CiA-402, bit 12 (homing attained) with bit 13 (error) clear is
                // the authoritative "homed" indicator. We do NOT require bit 10
                // (target reached): a set-current-position home reports "attained,
                // target not reached" (bit12=1, bit10=0) and never sets bit 10.
                // Methods that move to a target set both, so bit 12 alone still holds.
                let sw = view.status_word();
                let error = sw & (1 << 13) != 0;
                let attained = sw & (1 << 12) != 0;

                if error {
                    self.set_op_error("Homing error: drive reported homing failure");
                } else if attained {
                    self.op = AxisOp::Homing(13);
                } else if self.homing_timed_out() {
                    self.set_op_error(&format!(
                        "Homing timeout: procedure did not complete (sw=0x{:04X})",
                        sw
                    ));
                }
            }
            13 => {
                // The DRIVE owns position after homing (CiA 402 applies its home
                // offset 0x607C to the feedback at the found reference), so the
                // software offset stays ZERO — we never want the software axis to
                // be the source of truth for a real drive. Reported position is
                // then to_user(raw) directly.
                self.home_offset = 0;
                log::info!(
                    "Homing[done]: position_actual(0x6064) AFTER = {} (drive owns the reference)",
                    view.position_actual(),
                );
                // Clear homing start bit in its own cycle before switching modes
                let mut cw = RawControlWord(view.control_word());
                cw.set_bit(4, false);
                view.set_control_word(cw.raw());
                self.op = AxisOp::Homing(14);
            }
            14 => {
                // One tick later (bit 4 already cleared in step 13, so the drive
                // sees the falling edge before the mode change), switch back to PP
                // mode. Same dual-channel approach as the switch into Homing: cyclic
                // PDO field plus an SDO write + read-back so it lands and is verified
                // on drives that don't PDO-map mode.
                view.set_modes_of_operation(ModesOfOperation::ProfilePosition.as_i8());
                self.fb_mode_of_operation.reset();
                self.fb_mode_of_operation
                    .start(ModesOfOperation::ProfilePosition as i8);
                self.fb_mode_of_operation.tick(client, &mut self.sdo);
                self.op = AxisOp::Homing(15);
            }
            15 => {
                // Wait for the switch back to PP mode to be written and verified.
                self.fb_mode_of_operation.tick(client, &mut self.sdo);
                if !self.fb_mode_of_operation.is_busy() {
                    if self.fb_mode_of_operation.is_error() {
                        self.set_op_error(&format!(
                            "Homing: failed to restore PP mode: {} {}",
                            self.fb_mode_of_operation.error_code(),
                            self.fb_mode_of_operation.error_message()
                        ));
                    } else {
                        log::info!("Homing complete — home offset: {}", self.home_offset);
                        self.complete_op();
                    }
                }
            }
            16 => {
                // Write the home offset (0x607C) so the reference the drive finds
                // reads as home_position — rarely zero. Runs first for every
                // integrated (drive-native) method, then falls through to the
                // normal method/speed/trigger sequence at step 0.
                let desired_counts =
                    self.config.to_counts(self.config.home_position).round() as i32;
                self.homing_sdo_tid = self.sdo.write(client, 0x607C, 0, json!(desired_counts));
                log::info!(
                    "Homing[offset]: writing 0x607C = {} counts ({} user units)",
                    desired_counts, self.config.home_position
                );
                self.op = AxisOp::Homing(17);
            }
            17 => {
                match self
                    .sdo
                    .result(client, self.homing_sdo_tid, Duration::from_secs(5))
                {
                    SdoResult::Ok(_) => {
                        self.op = AxisOp::Homing(0);
                    }
                    SdoResult::Pending => {
                        if self.homing_timed_out() {
                            self.set_op_error("Homing timeout: SDO write for home offset");
                        }
                    }
                    SdoResult::Err(e) => {
                        self.set_op_error(&format!("Homing SDO error (home offset): {}", e));
                    }
                    SdoResult::Timeout => {
                        self.set_op_error("Homing timeout: home offset SDO write timed out");
                    }
                }
            }
            _ => self.complete_op(),
        }
    }

    // ── Software homing helpers ──

    fn configure_soft_homing(&mut self, method: HomingMethod) {
        match method {
            HomingMethod::LimitSwitchPosPnp => {
                self.soft_home_sensor = SoftHomeSensor::PositiveLimit;
                self.soft_home_sensor_type = SoftHomeSensorType::Pnp;
                self.soft_home_direction = 1.0;
            }
            HomingMethod::LimitSwitchNegPnp => {
                self.soft_home_sensor = SoftHomeSensor::NegativeLimit;
                self.soft_home_sensor_type = SoftHomeSensorType::Pnp;
                self.soft_home_direction = -1.0;
            }
            HomingMethod::LimitSwitchPosNpn => {
                self.soft_home_sensor = SoftHomeSensor::PositiveLimit;
                self.soft_home_sensor_type = SoftHomeSensorType::Npn;
                self.soft_home_direction = 1.0;
            }
            HomingMethod::LimitSwitchNegNpn => {
                self.soft_home_sensor = SoftHomeSensor::NegativeLimit;
                self.soft_home_sensor_type = SoftHomeSensorType::Npn;
                self.soft_home_direction = -1.0;
            }
            HomingMethod::HomeSensorPosPnp => {
                self.soft_home_sensor = SoftHomeSensor::HomeSensor;
                self.soft_home_sensor_type = SoftHomeSensorType::Pnp;
                self.soft_home_direction = 1.0;
            }
            HomingMethod::HomeSensorNegPnp => {
                self.soft_home_sensor = SoftHomeSensor::HomeSensor;
                self.soft_home_sensor_type = SoftHomeSensorType::Pnp;
                self.soft_home_direction = -1.0;
            }
            HomingMethod::HomeSensorPosNpn => {
                self.soft_home_sensor = SoftHomeSensor::HomeSensor;
                self.soft_home_sensor_type = SoftHomeSensorType::Npn;
                self.soft_home_direction = 1.0;
            }
            HomingMethod::HomeSensorNegNpn => {
                self.soft_home_sensor = SoftHomeSensor::HomeSensor;
                self.soft_home_sensor_type = SoftHomeSensorType::Npn;
                self.soft_home_direction = -1.0;
            }
            _ => {} // integrated methods handled elsewhere
        }
    }

    fn start_soft_homing(&mut self, view: &mut impl AxisView) {
        self.op = AxisOp::SoftHoming(HomeState::EnsurePpMode as u8);
        self.op_started = Some(Instant::now());
    }

    fn check_soft_home_trigger(&self, view: &impl AxisView) -> bool {
        let raw = match self.soft_home_sensor {
            SoftHomeSensor::PositiveLimit => view.positive_limit_active(),
            SoftHomeSensor::NegativeLimit => view.negative_limit_active(),
            SoftHomeSensor::HomeSensor => view.home_sensor_active(),
        };
        match self.soft_home_sensor_type {
            SoftHomeSensorType::Pnp => raw,  // PNP: true = detected
            SoftHomeSensorType::Npn => !raw, // NPN: false = detected
        }
    }

    /// Calculate the maximum relative target for the specified direction.
    /// The result is adjusted for whether the motor direction has been inverted.
    fn calculate_max_relative_target(&self, direction: f64) -> i32 {
        let dir = if !self.config.invert_direction {
            direction
        } else {
            -direction
        };

        let target = if dir > 0.0 { i32::MAX } else { i32::MIN };

        return target;
    }

    /// Configure the command word for an immediate halt: set the halt bit and
    /// clear the new-setpoint bit. The set-point queue is flushed afterward by
    /// the shared mode toggle (`FbFlushQueue`), so no cancel set-point is needed.
    pub fn command_halt(&self, view: &mut impl AxisView) {
        let mut cw = RawControlWord(view.control_word());
        cw.set_bit(8, true); // halt
        cw.set_bit(4, false); // reset new setpoint bit
        cw.set_bit(5, false);
        cw.set_bit(6, false); // absolute move
        view.set_control_word(cw.raw());
    }

    /// Writes out the scaled homing speed into the bus.
    fn command_homing_speed(&self, view: &mut impl AxisView) {
        let cpu = self.config.counts_per_user();
        let vel = (self.config.homing_speed * cpu).round() as u32;
        let accel = (self.config.homing_accel * cpu).round() as u32;
        let decel = (self.config.homing_decel * cpu).round() as u32;
        view.set_profile_velocity(vel);
        view.set_profile_acceleration(accel);
        view.set_profile_deceleration(decel);
    }

    // ── Software homing state machine ──
    //
    // Phase 1: SEARCH (steps 0-3)
    //   Relative move in search direction until sensor triggers.
    //
    // Phase 2: HALT (steps 4-6)
    //   Stop the motor, cancel the old target.
    //
    // Phase 3: BACK-OFF (steps 7-11)
    //   Move opposite direction until sensor clears, then stop.
    //
    // Phase 4: SET HOME (steps 12-18)
    //   Write home offset to drive via SDO, trigger CurrentPosition homing,
    //   send hold set-point, complete.
    //
    fn tick_soft_homing(&mut self, view: &mut impl AxisView, client: &mut CommandClient, step: u8) {
        match HomeState::from_repr(step) {
            Some(HomeState::EnsurePpMode) => {
                //
                // If the drive crapped out in a previous mode, it might still be in homing mode.
                // Make sure we're in Profile Position mode.
                //
                log::info!("SoftHome: Ensuring PP mode..");
                self.fb_mode_of_operation
                    .start(ModesOfOperation::ProfilePosition as i8);
                self.fb_mode_of_operation.tick(client, &mut self.sdo);
                self.op = AxisOp::SoftHoming(HomeState::WaitPpMode as u8);
            }
            Some(HomeState::WaitPpMode) => {
                self.fb_mode_of_operation.tick(client, &mut self.sdo);
                if !self.fb_mode_of_operation.is_busy() {
                    if self.fb_mode_of_operation.is_error() {
                        self.set_op_error(&format!(
                            "Software homing SDO error writing homing mode of operation: {} {}",
                            self.fb_mode_of_operation.error_code(),
                            self.fb_mode_of_operation.error_message()
                        ));
                    } else {
                        log::info!("SoftHome: Drive is in PP mode!");

                        // If sensor is NOT triggered, search for it (issue a move).
                        // If sensor IS already triggered, skip search and go straight
                        // to the found-sensor halt/back-off sequence.
                        if !self.check_soft_home_trigger(view) {
                            log::info!("SoftHome: Not on home switch; seek out.");
                            self.op = AxisOp::SoftHoming(HomeState::Search as u8);
                        } else {
                            log::info!("SoftHome: Already on home switch, skipping ahead to back-off stage.");
                            self.op = AxisOp::SoftHoming(HomeState::WaitFoundSensor as u8);
                        }
                    }
                }
            }

            // ── Phase 1: SEARCH ──
            Some(HomeState::Search) => {
                view.set_modes_of_operation(ModesOfOperation::ProfilePosition.as_i8());

                // // Absolute move to a far-away position in the search direction.
                // // Use raw counts directly to avoid overflow with invert_direction.
                // let far_counts = (self.soft_home_direction * 999_999.0 * cpu).round() as i32;
                // let target = if self.config.invert_direction { -far_counts } else { far_counts };
                // let target = target + view.position_actual(); // offset from current

                // move in a relative direction as far as possible
                // we will stop when we reach the switch
                let target = self.calculate_max_relative_target(self.soft_home_direction);
                view.set_target_position(target);

                // let cpu = self.config.counts_per_user();
                // let vel = (self.config.homing_speed * cpu).round() as u32;
                // let accel = (self.config.homing_accel * cpu).round() as u32;
                // let decel = (self.config.homing_decel * cpu).round() as u32;
                // view.set_profile_velocity(vel);
                // view.set_profile_acceleration(accel);
                // view.set_profile_deceleration(decel);

                self.command_homing_speed(view);

                let mut cw = RawControlWord(view.control_word());
                cw.set_bit(4, true); // new set-point
                cw.set_bit(6, true); // sets true for relative move
                cw.set_bit(8, false); // clear halt
                cw.set_bit(13, true); // move relative to the actual current motor position
                view.set_control_word(cw.raw());

                log::info!(
                    "SoftHome[0]: SEARCH relative target={} vel={} dir={} pos={}",
                    target,
                    self.config.homing_speed,
                    self.soft_home_direction,
                    view.position_actual()
                );
                self.op = AxisOp::SoftHoming(HomeState::WaitSearching as u8);
            }
            Some(HomeState::WaitSearching) => {
                if self.check_soft_home_trigger(view) {
                    log::debug!("SoftHome[1]: sensor triggered during ack wait");
                    self.op = AxisOp::SoftHoming(HomeState::WaitFoundSensor as u8);
                    return;
                }
                let sw = RawStatusWord(view.status_word());
                if sw.raw() & (1 << 12) != 0 {
                    let mut cw = RawControlWord(view.control_word());
                    cw.set_bit(4, false);
                    view.set_control_word(cw.raw());
                    log::debug!("SoftHome[1]: set-point ack received, clearing bit 4");
                    self.op = AxisOp::SoftHoming(HomeState::WaitFoundSensor as u8);
                } else if self.homing_timed_out() {
                    self.set_op_error("Software homing timeout: set-point not acknowledged");
                }
            }
            // Some(HomeState::WaitSensor) => {
            //     if self.check_soft_home_trigger(view) {
            //         log::debug!("SoftHome[2]: sensor triggered during transition");
            //         self.op = AxisOp::SoftHoming(4);
            //         return;
            //     }
            //     log::debug!("SoftHome[2]: transition → monitoring");
            //     self.op = AxisOp::SoftHoming(3);
            // }
            Some(HomeState::WaitFoundSensor) => {
                if self.check_soft_home_trigger(view) {
                    log::info!(
                        "SoftHome[3]: sensor triggered at pos={}. HALTING",
                        view.position_actual()
                    );
                    log::info!("ControlWord is : {} ", view.control_word());

                    let mut cw = RawControlWord(view.control_word());
                    cw.set_bit(8, true); // halt
                    cw.set_bit(4, false); // reset new setpoint bit
                    view.set_control_word(cw.raw());

                    self.halt_stable_count = 0;
                    self.op = AxisOp::SoftHoming(HomeState::WaitStoppedFoundSensor as u8);
                } else if self.homing_timed_out() {
                    self.set_op_error("Software homing timeout: sensor not detected");
                }
            }

            Some(HomeState::WaitStoppedFoundSensor) => {
                const STABLE_WINDOW: i32 = 1;
                const STABLE_TICKS_REQUIRED: u8 = 10;

                // let mut cw = RawControlWord(view.control_word());
                // cw.set_bit(8, true);
                // view.set_control_word(cw.raw());

                let pos = view.position_actual();
                if (pos - self.last_raw_position).abs() <= STABLE_WINDOW {
                    self.halt_stable_count = self.halt_stable_count.saturating_add(1);
                } else {
                    self.halt_stable_count = 0;
                }

                if self.halt_stable_count >= STABLE_TICKS_REQUIRED {
                    log::info!(
                        "SoftHome[5] motor is stopped. Cancel move and wait for bit 12 go true."
                    );
                    self.flush.start(view, client, &mut self.sdo);
                    self.op = AxisOp::SoftHoming(HomeState::FlushingFound as u8);
                } else if self.homing_timed_out() {
                    self.set_op_error(
                        "Software homing timeout: motor did not stop after sensor trigger",
                    );
                }
            }
            Some(HomeState::FlushingFound) => {
                self.flush.tick(view, client, &mut self.sdo);
                if self.flush.is_busy() {
                    if self.homing_timed_out() {
                        self.set_op_error("Software homing timeout: queue flush did not complete");
                    }
                    return;
                }
                if self.flush.is_error() {
                    self.set_op_error(&format!(
                        "Software homing: queue flush failed: {} {}",
                        self.flush.error_code(),
                        self.flush.error_message()
                    ));
                    return;
                }
                // Queue flushed and back in PP. Release halt + set-point bits, drop
                // stale target, then debounce before backing off.
                let mut cw = RawControlWord(view.control_word());
                cw.set_bit(8, false);
                cw.set_bit(4, false);
                cw.set_bit(5, false);
                view.set_control_word(cw.raw());
                view.set_target_position(view.position_actual());
                log::info!("SoftHome[6]: queue flushed; proceeding to debounce.");
                self.op = AxisOp::SoftHoming(HomeState::DebounceFoundSensor as u8);
                self.ton.call(false, Duration::from_secs(3));
            }
            // Delay before back-off (60 = wait ~1 second for drive to settle)
            Some(HomeState::DebounceFoundSensor) => {
                self.ton.call(true, Duration::from_secs(3));

                let sw = RawStatusWord(view.status_word());
                if self.ton.q && sw.raw() & (1 << 12) == 0 {
                    self.ton.call(false, Duration::from_secs(3));
                    log::info!("SoftHome[6.a.]: delay complete, starting back-off from pos={} cw=0x{:04X} sw={:04x}",
                    view.position_actual(), view.control_word(), view.status_word());
                    self.op = AxisOp::SoftHoming(HomeState::BackOff as u8);
                }
            }

            // ── Phase 3: BACK-OFF until sensor clears ──
            Some(HomeState::BackOff) => {
                let target = (self.calculate_max_relative_target(-self.soft_home_direction)) / 2;
                view.set_target_position(target);

                self.command_homing_speed(view);

                let mut cw = RawControlWord(view.control_word());
                cw.set_bit(4, true); // new set-point
                cw.set_bit(6, true); // relative move
                cw.set_bit(13, true); // relative from current, actualy position
                view.set_control_word(cw.raw());
                log::info!(
                    "SoftHome[7]: BACK-OFF absolute target={} vel={} pos={} cw=0x{:04X}",
                    target,
                    self.config.homing_speed,
                    view.position_actual(),
                    cw.raw()
                );
                self.op = AxisOp::SoftHoming(HomeState::WaitBackingOff as u8);
            }
            Some(HomeState::WaitBackingOff) => {
                let sw = RawStatusWord(view.status_word());
                if sw.raw() & (1 << 12) != 0 {
                    let mut cw = RawControlWord(view.control_word());
                    cw.set_bit(4, false);
                    view.set_control_word(cw.raw());
                    log::info!(
                        "SoftHome[WaitBackingOff]: back-off ack received, pos={}",
                        view.position_actual()
                    );
                    self.op = AxisOp::SoftHoming(HomeState::WaitLostSensor as u8);
                } else if self.homing_timed_out() {
                    self.set_op_error("Software homing timeout: back-off not acknowledged");
                }
            }
            Some(HomeState::WaitLostSensor) => {
                if !self.check_soft_home_trigger(view) {
                    log::info!(
                        "SoftHome[WaitLostSensor]: sensor lost at pos={}. Halting...",
                        view.position_actual()
                    );

                    self.command_halt(view);
                    self.op = AxisOp::SoftHoming(HomeState::WaitStoppedLostSensor as u8);
                } else if self.homing_timed_out() {
                    self.set_op_error(
                        "Software homing timeout: sensor did not clear during back-off",
                    );
                }
            }
            Some(HomeState::WaitStoppedLostSensor) => {
                const STABLE_WINDOW: i32 = 1;
                const STABLE_TICKS_REQUIRED: u8 = 10;

                // let mut cw = RawControlWord(view.control_word());
                // cw.set_bit(8, true);
                // view.set_control_word(cw.raw());

                let pos = view.position_actual();
                if (pos - self.last_raw_position).abs() <= STABLE_WINDOW {
                    self.halt_stable_count = self.halt_stable_count.saturating_add(1);
                } else {
                    self.halt_stable_count = 0;
                }

                if self.halt_stable_count >= STABLE_TICKS_REQUIRED {
                    log::info!("SoftHome[WaitStoppedLostSensor] motor is stopped. Cancel move and wait for bit 12 go true.");
                    self.flush.start(view, client, &mut self.sdo);
                    self.op = AxisOp::SoftHoming(HomeState::FlushingLost as u8);
                } else if self.homing_timed_out() {
                    self.set_op_error("Software homing timeout: motor did not stop after back-off");
                }
            }
            Some(HomeState::FlushingLost) => {
                self.flush.tick(view, client, &mut self.sdo);
                if self.flush.is_busy() {
                    if self.homing_timed_out() {
                        self.set_op_error("Software homing timeout: queue flush did not complete");
                    }
                    return;
                }
                if self.flush.is_error() {
                    self.set_op_error(&format!(
                        "Software homing: queue flush failed: {} {}",
                        self.flush.error_code(),
                        self.flush.error_message()
                    ));
                    return;
                }
                // Queue flushed and back in PP. Release halt + set-point bits, then
                // write the home offset (0x607C) and verify.
                let mut cw = RawControlWord(view.control_word());
                cw.set_bit(8, false);
                cw.set_bit(4, false);
                cw.set_bit(5, false);
                view.set_control_word(cw.raw());

                let desired_counts =
                    self.config.to_counts(self.config.home_position).round() as i32;
                self.homing_sdo_tid = self.sdo.write(client, 0x607C, 0, json!(desired_counts));
                log::info!(
                    "SoftHome[FlushingLost]: queue flushed; writing home offset {} [{} counts].",
                    self.config.home_position, desired_counts
                );
                self.op = AxisOp::SoftHoming(HomeState::WaitHomeOffsetDone as u8);
            }

            Some(HomeState::WriteHomeOffset) => {
                // Drive-side "set reference at present position" entry point (used
                // by home(CurrentPosition)). Write the reference value to the
                // drive's home offset (0x607C); the current-position homing method
                // (soft_home_method) then sets position_actual to it, so the DRIVE
                // owns the position — no software offset.
                let desired_counts =
                    self.config.to_counts(self.config.home_position).round() as i32;
                self.homing_sdo_tid = self.sdo.write(client, 0x607C, 0, json!(desired_counts));
                log::info!(
                    "Home[CurrentPosition]: writing 0x607C = {} counts ({} user units)",
                    desired_counts, self.config.home_position
                );
                self.op = AxisOp::SoftHoming(HomeState::WaitHomeOffsetDone as u8);
            }
            Some(HomeState::WaitHomeOffsetDone) => {
                // Wait for home offset SDO ack
                match self
                    .sdo
                    .result(client, self.homing_sdo_tid, Duration::from_secs(5))
                {
                    SdoResult::Ok(_) => {
                        // DIAGNOSTIC: read 0x607C straight back so the log shows
                        // whether the drive actually stored the home offset we
                        // just wrote, vs. silently dropping it.
                        self.homing_sdo_tid = self.sdo.read(client, 0x607C, 0);
                        self.op = AxisOp::SoftHoming(HomeState::WaitHomeOffsetReadback as u8);
                    }
                    SdoResult::Pending => {
                        if self.homing_timed_out() {
                            self.set_op_error("Software homing timeout: home offset SDO write");
                        }
                    }
                    SdoResult::Err(e) => {
                        self.set_op_error(&format!("Software homing SDO error: {}", e));
                    }
                    SdoResult::Timeout => {
                        self.set_op_error("Software homing: home offset SDO timed out");
                    }
                }
            }
            Some(HomeState::WaitHomeOffsetReadback) => {
                // DIAGNOSTIC ONLY — never fails the op; logs the value the drive
                // reports for 0x607C after our write, then continues.
                let target = self.config.to_counts(self.config.home_position).round() as i32;
                match self
                    .sdo
                    .result(client, self.homing_sdo_tid, Duration::from_secs(5))
                {
                    SdoResult::Ok(val) => {
                        log::info!(
                            "SoftHome[diag]: 0x607C (home offset) read-back = {} (wrote {} counts)",
                            val,
                            target,
                        );
                        self.op = AxisOp::SoftHoming(HomeState::WriteHomingModeOp as u8);
                    }
                    SdoResult::Pending => {
                        if self.homing_timed_out() {
                            log::warn!("SoftHome[diag]: 0x607C read-back timed out; continuing");
                            self.op = AxisOp::SoftHoming(HomeState::WriteHomingModeOp as u8);
                        }
                    }
                    SdoResult::Err(e) => {
                        log::warn!("SoftHome[diag]: 0x607C read-back error: {}; continuing", e);
                        self.op = AxisOp::SoftHoming(HomeState::WriteHomingModeOp as u8);
                    }
                    SdoResult::Timeout => {
                        log::warn!("SoftHome[diag]: 0x607C read-back timed out; continuing");
                        self.op = AxisOp::SoftHoming(HomeState::WriteHomingModeOp as u8);
                    }
                }
            }
            Some(HomeState::WriteHomingModeOp) => {
                // Switch the mode of operation into Homing Mode so that we can execute
                // the homing command.

                self.fb_mode_of_operation.reset();
                self.fb_mode_of_operation
                    .start(ModesOfOperation::Homing as i8);
                self.fb_mode_of_operation.tick(client, &mut self.sdo);
                self.op = AxisOp::SoftHoming(HomeState::WaitWriteHomingModeOp as u8);
            }
            Some(HomeState::WaitWriteHomingModeOp) => {
                // Wait for method SDO ack
                self.fb_mode_of_operation.tick(client, &mut self.sdo);

                if !self.fb_mode_of_operation.is_busy() {
                    if self.fb_mode_of_operation.is_error() {
                        self.set_op_error(&format!(
                            "Software homing SDO error writing homing mode of operation: {} {}",
                            self.fb_mode_of_operation.error_code(),
                            self.fb_mode_of_operation.error_message()
                        ));
                    } else {
                        log::info!("SoftHome: Drive is now in Homing Mode.");
                        self.op = AxisOp::SoftHoming(HomeState::WriteHomingMethod as u8);
                    }
                }
            }
            Some(HomeState::WriteHomingMethod) => {
                // Write the CiA 402 homing method (0x6098). For current-position
                // homing this is the code carried by the HomingMethod variant
                // (35/37); for software search homing it is the drive's configured
                // current-position method (soft_home_method) — both are stashed in
                // self.homing_method by home().
                log::info!(
                    "SoftHome[diag]: writing 0x6098 (homing method) = {}",
                    self.homing_method
                );
                self.homing_sdo_tid =
                    self.sdo.write(client, 0x6098, 0, json!(self.homing_method));
                self.op = AxisOp::SoftHoming(HomeState::WaitWriteHomingMethodDone as u8);
            }
            Some(HomeState::WaitWriteHomingMethodDone) => {
                // Wait for method SDO ack
                match self
                    .sdo
                    .result(client, self.homing_sdo_tid, Duration::from_secs(5))
                {
                    SdoResult::Ok(_) => {
                        log::info!("SoftHome: Successfully wrote homing method.");
                        self.op = AxisOp::SoftHoming(HomeState::ClearHomingTrigger as u8);
                    }
                    SdoResult::Pending => {
                        if self.homing_timed_out() {
                            self.restore_pp_after_error(
                                "Software homing timeout: homing method SDO write",
                            );
                        }
                    }
                    SdoResult::Err(e) => {
                        self.restore_pp_after_error(&format!("Software homing SDO error: {}", e));
                    }
                    SdoResult::Timeout => {
                        self.restore_pp_after_error("Software homing: homing method SDO timed out");
                    }
                }
            }
            Some(HomeState::ClearHomingTrigger) => {
                // Switch to homing mode and ensure CW bit 4 starts LOW, so the
                // next state can issue a clean rising edge the drive will see.
                let mut cw = RawControlWord(view.control_word());
                cw.set_bit(4, false);
                view.set_control_word(cw.raw());
                self.op = AxisOp::SoftHoming(HomeState::TriggerHoming as u8);
            }
            Some(HomeState::TriggerHoming) => {
                // Rising edge on CW bit 4 to start homing.
                let mut cw = RawControlWord(view.control_word());
                cw.set_bit(4, true);
                view.set_control_word(cw.raw());
                log::info!("SoftHome[TriggerHoming]: start homing");
                self.op = AxisOp::SoftHoming(HomeState::WaitHomingStarted as u8);
            }
            Some(HomeState::WaitHomingStarted) => {
                // One drive cycle after the trigger edge, then evaluate completion.
                //
                // We deliberately do NOT wait for bit 12 (homing attained) to clear
                // first. That old start-gate assumed the drive de-asserts attained at
                // the start of a new run and re-asserts on completion — true for
                // methods that take time to run, but an instantaneous method (35/37,
                // set-current-position) completes within one cycle, so bit 12 goes
                // high immediately and may never be observed low, racing into a
                // spurious "did not acknowledge homing start" timeout. The gate's
                // original purpose (rejecting a stale bit 12 carried over from PP
                // set-point acknowledge) is already covered by the SDO mode-6
                // readback done earlier (FbSetModeOfOperation): once in Homing mode,
                // bit 12 carries homing semantics. This matches tick_homing step 11.
                let sw = view.status_word();
                if sw & (1 << 13) != 0 {
                    self.restore_pp_after_error("Software homing: drive reported homing error");
                } else {
                    self.op = AxisOp::SoftHoming(HomeState::WaitHomingDone as u8);
                }
            }
            Some(HomeState::WaitHomingDone) => {
                // Wait for homing complete. Per CiA-402, bit 12 (homing attained)
                // with bit 13 (error) clear is the authoritative "homed" indicator;
                // we do NOT require bit 10 (target reached). A set-current-position
                // home (method 35/37) reports "attained, target not reached"
                // (bit12=1, bit10=0) and never sets bit 10, so requiring it here
                // would hang until timeout (observed sw=0x1237). Methods that move
                // to a target set both, so bit 12 alone still holds. This matches
                // the integrated tick_homing completion check (step 12).
                let sw = view.status_word();
                let error = sw & (1 << 13) != 0;
                let attained = sw & (1 << 12) != 0;
                let reached = sw & (1 << 10) != 0;

                if error {
                    self.restore_pp_after_error("Software homing: drive reported homing error");
                } else if attained {
                    // DIAGNOSTIC: did the drive actually apply the set-position?
                    // position_actual (0x6064) should now read the value we wrote
                    // to 0x607C. If it instead reads a raw/unchanged number, the
                    // drive set the HOMED bit but did NOT move its reported
                    // position — meaning the persistence relies on software, not
                    // the drive.
                    log::info!(
                        "SoftHome[WaitHomingDone]: homing complete sw=0x{:04X} position_actual(0x6064)={} target(0x607C)={} counts",
                        sw,
                        view.position_actual(),
                        self.config.to_counts(self.config.home_position).round() as i32,
                    );
                    self.op = AxisOp::SoftHoming(HomeState::ResetHomingTrigger as u8);
                } else if self.homing_timed_out() {
                    self.restore_pp_after_error(&format!("Software homing timeout: drive homing did not complete (sw=0x{:04X} attained={} reached={})", sw, attained, reached));
                }
            }
            Some(HomeState::ResetHomingTrigger) => {
                // Clear CW bit 4 first, in its own RxPDO cycle, so the drive sees
                // the falling edge *before* we change modes_of_operation away from
                // Homing. Changing both at once can leave the drive committing
                // ambiguous state.
                let mut cw = RawControlWord(view.control_word());
                cw.set_bit(4, false);
                view.set_control_word(cw.raw());
                self.op = AxisOp::SoftHoming(HomeState::WaitHomingTriggerCleared as u8);
            }
            Some(HomeState::WaitHomingTriggerCleared) => {
                // One tick after clearing the homing trigger, and BEFORE switching
                // back to PP mode: align the PP target (0x607A) with the just-homed
                // actual position (0x6064). On PP re-entry the drive adopts 0x607A
                // as its position demand; if that demand differs from actual (which
                // the home just changed) the position loop slams the motor to close
                // the gap — that is the runaway. Copying actual -> target here (raw
                // counts, no scaling) removes the error before PP can act on it,
                // regardless of whether the home landed where intended.
                let pos = view.position_actual();
                view.set_target_position(pos);
                log::info!(
                    "SoftHome[diag]: post-home, pre-PP-switch position_actual(0x6064) = {}; \
                     set target_position(0x607A) = {} so PP re-entry has nothing to chase",
                    pos, pos
                );
                self.home_offset = 0; // drive handles it now
                self.op = AxisOp::SoftHoming(HomeState::AlignTargetBeforePP as u8);
            }
            Some(HomeState::AlignTargetBeforePP) => {
                // One tick later: the RxPDO carrying 0x607A = actual has now been
                // sent, so the drive sees target == actual. Re-assert each tick
                // (cheap) in case actual drifted, then switch to PP mode.
                view.set_target_position(view.position_actual());
                self.op = AxisOp::SoftHoming(HomeState::WriteMotionModeOfOperation as u8);
            }

            Some(HomeState::WriteMotionModeOfOperation) => {
                // Switch back to PP motion mode

                self.fb_mode_of_operation.reset();
                self.fb_mode_of_operation
                    .start(ModesOfOperation::ProfilePosition as i8);
                self.fb_mode_of_operation.tick(client, &mut self.sdo);
                self.op = AxisOp::SoftHoming(HomeState::WaitWriteMotionModeOfOperation as u8);
            }
            Some(HomeState::WaitWriteMotionModeOfOperation) => {
                // Wait for method SDO ack
                self.fb_mode_of_operation.tick(client, &mut self.sdo);

                if !self.fb_mode_of_operation.is_busy() {
                    if self.fb_mode_of_operation.is_error() {
                        self.set_op_error(&format!(
                            "Software homing SDO error writing homing mode of operation: {} {}",
                            self.fb_mode_of_operation.error_code(),
                            self.fb_mode_of_operation.error_message()
                        ));
                    } else {
                        if self.is_error {
                            log::error!("Drive back in PP mode after error. Homing sequence did not complete!");
                            self.finish_op_error();
                        } else {
                            log::info!(
                                "SoftHome[diag]: back in PP mode, position_actual(0x6064) = {}; \
                                 homing complete, holding (no new set-point latched)",
                                view.position_actual()
                            );
                            // DONE — do NOT latch a fresh PP set-point here.
                            //
                            // A CiA-402 PP drive only moves on a *rising edge* of
                            // controlword bit 4 (new set-point). After homing we are
                            // back in PP mode with bit 4 already low (cleared in
                            // ResetHomingTrigger) and 0x607A aligned to 0x6064
                            // (AlignTargetBeforePP), so the drive simply holds at the
                            // just-homed position — exactly like the proven SDO-only
                            // homing sequence (6060=6 … 6060=1), which never issues a
                            // post-home set-point and never moves.
                            //
                            // The old SendCurrentPositionTarget step DID drive a bit-4
                            // rising edge to latch an absolute set-point at
                            // view.position_actual(). Because homing has just changed
                            // the position frame (home_offset=0, 0x6064 := 0x607C) and
                            // the PDO snapshot lags that relabel by a cycle, the latched
                            // target raced the new 0x6064 and the position loop slammed
                            // the motor to close the gap — the ~10 mm post-home lurch on
                            // the AKD. Holding instead removes that move entirely.
                            self.complete_op();
                        }
                    }
                }
            }

            Some(HomeState::SendCurrentPositionTarget) => {
                // Hold position: send set-point to current position
                let current_pos = view.position_actual();
                log::info!(
                    "SoftHome[diag]: holding at position_actual(0x6064) = {}",
                    current_pos
                );
                view.set_target_position(current_pos);
                view.set_profile_velocity(0);
                let mut cw = RawControlWord(view.control_word());
                cw.set_bit(4, true);
                cw.set_bit(5, true);
                cw.set_bit(6, false); // absolute
                view.set_control_word(cw.raw());
                self.op = AxisOp::SoftHoming(HomeState::WaitCurrentPositionTargetSent as u8);
            }
            Some(HomeState::WaitCurrentPositionTargetSent) => {
                // Wait for hold ack
                let sw = RawStatusWord(view.status_word());
                if sw.raw() & (1 << 12) != 0 {
                    let mut cw = RawControlWord(view.control_word());
                    cw.set_bit(4, false);
                    view.set_control_word(cw.raw());
                    log::info!(
                        "Software homing complete — commanded {} user units; final position_actual(0x6064) = {} counts",
                        self.config.home_position,
                        view.position_actual()
                    );
                    self.complete_op();
                } else if self.homing_timed_out() {
                    self.set_op_error("Software homing timeout: hold position not acknowledged");
                }
            }
            _ => self.complete_op(),
        }
    }

    // ── Halting ──
    //
    // Three-stage close-out of the PP handshake, mirroring the soft-home
    // stop sequence (WaitStoppedFoundSensor → WaitFoundSensorAck →
    // WaitFoundSensorAckClear). Leaving any stage out results in a dirty
    // handshake that makes the next `move_absolute` time out at
    // "set-point not acknowledged."
    //
    // Step 0: (done in halt()) command_halt — bit 8 set, bit 4 cleared.
    // Step 1: wait for position to be stable → command_cancel_move.
    // Step 2: wait for SW bit 12 AND bit 10 → clear bit 4, set bit 5.
    // Step 3: wait for SW bit 12 to drop → Idle.
    fn tick_halting(
        &mut self,
        view: &mut impl AxisView,
        client: &mut CommandClient,
        step: u8,
    ) {
        match HaltState::from_repr(step) {
            Some(HaltState::WaitStopped) => {
                let pos = view.position_actual();
                let pos_stable = (pos - self.last_raw_position).abs() <= HALT_STABLE_WINDOW;

                let vel = view.velocity_actual().abs();
                let vel_stopped = vel <= HALT_STOPPED_VELOCITY;

                if pos_stable || vel_stopped {
                    self.halt_stable_count = self.halt_stable_count.saturating_add(1);
                } else {
                    self.halt_stable_count = 0;
                }

                if self.halt_stable_count >= HALT_STABLE_TICKS_REQUIRED {
                    // Motor stopped (halt still asserted). Flush the set-point
                    // queue via the shared mode toggle, then release halt.
                    self.flush.start(view, client, &mut self.sdo);
                    self.op_started = Some(Instant::now());
                    self.op = AxisOp::Halting(HaltState::Flushing as u8);
                } else if self.op_stage_timed_out(HALT_STAGE_TIMEOUT) {
                    self.set_op_error("Halt timeout: motor did not stop");
                }
            }
            Some(HaltState::Flushing) => {
                self.flush.tick(view, client, &mut self.sdo);
                if self.flush.is_busy() {
                    if self.op_stage_timed_out(HALT_STAGE_TIMEOUT) {
                        self.set_op_error("Halt timeout: set-point queue flush did not complete");
                    }
                    return;
                }
                if self.flush.is_error() {
                    self.set_op_error(&format!(
                        "Halt: set-point queue flush failed: {} {}",
                        self.flush.error_code(),
                        self.flush.error_message()
                    ));
                    return;
                }
                // Queue flushed and back in PP. Release halt + the set-point bits
                // and drop any stale target so the next move starts clean.
                let mut cw = RawControlWord(view.control_word());
                cw.set_bit(8, false); // clear halt
                cw.set_bit(4, false);
                cw.set_bit(5, false);
                view.set_control_word(cw.raw());
                view.set_target_position(view.position_actual());
                self.complete_op();
            }
            None => {
                log::warn!("Axis halt: unknown sub-step {}, forcing idle", step);
                self.complete_op();
            }
        }
    }

    // ── Fault Recovery ──
    // Step 0: (done in reset_faults()) clear bit 7
    // Step 1: assert bit 7 (fault reset rising edge)
    // Step 2: wait fault cleared → Idle
    fn tick_fault_recovery(&mut self, view: &mut impl AxisView, step: u8) {
        match step {
            1 => {
                // Assert fault reset (rising edge on bit 7)
                let mut cw = RawControlWord(view.control_word());
                cw.cmd_fault_reset();
                view.set_control_word(cw.raw());
                self.op = AxisOp::FaultRecovery(2);
            }
            2 => {
                // Wait for fault to clear
                let sw = RawStatusWord(view.status_word());
                let state = sw.state();
                if !matches!(state, Cia402State::Fault | Cia402State::FaultReactionActive) {
                    log::info!("Fault cleared (drive state: {})", state);
                    self.complete_op();
                } else if self.op_timed_out() {
                    self.set_op_error("Fault reset timeout: drive still faulted");
                }
            }
            _ => self.complete_op(),
        }
    }
}

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

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

    /// Mock AxisView for testing.
    struct MockView {
        control_word: u16,
        status_word: u16,
        target_position: i32,
        profile_velocity: u32,
        profile_acceleration: u32,
        profile_deceleration: u32,
        modes_of_operation: i8,
        modes_of_operation_display: i8,
        position_actual: i32,
        velocity_actual: i32,
        error_code: u16,
        positive_limit: bool,
        negative_limit: bool,
        home_sensor: bool,
    }

    impl MockView {
        fn new() -> Self {
            Self {
                control_word: 0,
                status_word: 0x0040, // SwitchOnDisabled
                target_position: 0,
                profile_velocity: 0,
                profile_acceleration: 0,
                profile_deceleration: 0,
                modes_of_operation: 0,
                modes_of_operation_display: 1, // PP
                position_actual: 0,
                velocity_actual: 0,
                error_code: 0,
                positive_limit: false,
                negative_limit: false,
                home_sensor: false,
            }
        }

        fn set_state(&mut self, state: u16) {
            self.status_word = state;
        }
    }

    impl AxisView for MockView {
        fn control_word(&self) -> u16 {
            self.control_word
        }
        fn set_control_word(&mut self, word: u16) {
            self.control_word = word;
        }
        fn set_target_position(&mut self, pos: i32) {
            self.target_position = pos;
        }
        fn set_profile_velocity(&mut self, vel: u32) {
            self.profile_velocity = vel;
        }
        fn set_profile_acceleration(&mut self, accel: u32) {
            self.profile_acceleration = accel;
        }
        fn set_profile_deceleration(&mut self, decel: u32) {
            self.profile_deceleration = decel;
        }
        fn set_modes_of_operation(&mut self, mode: i8) {
            self.modes_of_operation = mode;
        }
        fn modes_of_operation_display(&self) -> i8 {
            self.modes_of_operation_display
        }
        fn status_word(&self) -> u16 {
            self.status_word
        }
        fn position_actual(&self) -> i32 {
            self.position_actual
        }
        fn velocity_actual(&self) -> i32 {
            self.velocity_actual
        }
        fn error_code(&self) -> u16 {
            self.error_code
        }
        fn positive_limit_active(&self) -> bool {
            self.positive_limit
        }
        fn negative_limit_active(&self) -> bool {
            self.negative_limit
        }
        fn home_sensor_active(&self) -> bool {
            self.home_sensor
        }
    }

    fn test_config() -> AxisConfig {
        AxisConfig::new(12_800).with_user_scale(360.0)
    }

    /// Helper: create axis + mock client channels.
    fn test_axis() -> (
        Axis,
        CommandClient,
        tokio::sync::mpsc::UnboundedSender<mechutil::ipc::CommandMessage>,
        tokio::sync::mpsc::UnboundedReceiver<String>,
    ) {
        use tokio::sync::mpsc;
        let (write_tx, write_rx) = mpsc::unbounded_channel();
        let (response_tx, response_rx) = mpsc::unbounded_channel();
        let client = CommandClient::new(write_tx, response_rx);
        let axis = Axis::new(test_config(), "TestDrive");
        (axis, client, response_tx, write_rx)
    }

    #[test]
    fn axis_config_conversion() {
        let cfg = test_config();
        // 45 degrees = 1600 counts
        assert!((cfg.to_counts(45.0) - 1600.0).abs() < 0.01);
    }

    #[test]
    fn trace_records_on_change_not_every_tick() {
        let (mut axis, mut client, _r, _w) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0040); // Switch On Disabled

        // Many idle ticks with a constant control/status word → one entry, not
        // one per tick. This is what keeps a multi-second stall cheap.
        for _ in 0..10 {
            axis.tick(&mut view, &mut client);
        }
        let after_idle = axis.trace().lines().count();
        assert!(
            after_idle <= 1,
            "constant state must record ≤1 line, got {}",
            after_idle
        );

        // A status-word change records exactly one new transition.
        view.set_state(0x0027); // Operation Enabled
        axis.tick(&mut view, &mut client);
        assert!(
            axis.trace().lines().count() > after_idle,
            "a SW change adds a line"
        );
        assert!(
            axis.trace().contains("Operation Enabled"),
            "trace decodes the SW state"
        );
    }

    #[test]
    fn trace_decoders_render_handshake_bits() {
        // Cancel control word with HALT cleared (the intended fix) vs still set.
        assert_eq!(decode_cw(0x003F), "SwOn|EnVolt|QStop|EnOp|NewSP|ChgSet");
        assert!(
            decode_cw(0x013F).contains("HALT"),
            "0x13F still asserts HALT"
        );
        // Status word: Operation Enabled with set-point acknowledge (bit 12).
        let s = decode_sw(0x1027);
        assert!(
            s.contains("Operation Enabled") && s.contains("SP_ACK"),
            "got {s}"
        );
    }

    #[test]
    fn enable_sequence_sets_pp_mode_and_shutdown() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();

        axis.enable(&mut view);

        // Should have set PP mode
        assert_eq!(
            view.modes_of_operation,
            ModesOfOperation::ProfilePosition.as_i8()
        );
        // Should have issued shutdown command (bits 1,2 set; 0,3,7 clear)
        assert_eq!(view.control_word & 0x008F, 0x0006);
        // Should be in Enabling state
        assert_eq!(axis.op, AxisOp::Enabling(1));

        // Simulate drive reaching ReadyToSwitchOn
        view.set_state(0x0021); // ReadyToSwitchOn
        axis.tick(&mut view, &mut client);

        // Should have issued enable_operation (bits 0-3 set; 7 clear)
        assert_eq!(view.control_word & 0x008F, 0x000F);
        assert_eq!(axis.op, AxisOp::Enabling(2));

        // Simulate drive reaching OperationEnabled
        view.set_state(0x0027); // OperationEnabled
        axis.tick(&mut view, &mut client);

        // Should be idle now, motor_on = true
        assert_eq!(axis.op, AxisOp::Idle);
        assert!(axis.motor_on);
    }

    #[test]
    fn move_absolute_sets_target() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027); // OperationEnabled
        axis.tick(&mut view, &mut client); // update outputs

        // Move to 45 degrees at 90 deg/s, 180 deg/s² accel/decel
        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);

        // Target should be ~1600 counts (45° at 12800 cpr / 360°)
        assert_eq!(view.target_position, 1600);
        // Velocity: 90 deg/s * (12800/360) ≈ 3200 counts/s
        assert_eq!(view.profile_velocity, 3200);
        // Accel: 180 deg/s² * (12800/360) ≈ 6400 counts/s²
        assert_eq!(view.profile_acceleration, 6400);
        assert_eq!(view.profile_deceleration, 6400);
        // Bit 4 (new set-point) should be set
        assert!(view.control_word & (1 << 4) != 0);
        // Bit 6 (relative) should be clear for absolute move
        assert!(view.control_word & (1 << 6) == 0);
        // Should be in Moving state
        assert!(matches!(
            axis.op,
            AxisOp::Moving(MoveKind::Absolute, 1, _, _)
        ));
    }

    #[test]
    fn move_relative_sets_relative_bit() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);
        axis.tick(&mut view, &mut client);

        axis.move_relative(&mut view, 10.0, 90.0, 180.0, 180.0);

        // Bit 6 (relative) should be set
        assert!(view.control_word & (1 << 6) != 0);
        assert!(matches!(
            axis.op,
            AxisOp::Moving(MoveKind::Relative, 1, _, _)
        ));
    }

    #[test]
    fn move_completes_on_target_reached() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027); // OperationEnabled
        axis.tick(&mut view, &mut client);

        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);

        // Step 1: simulate set-point acknowledge (bit 12)
        view.status_word = 0x1027; // OperationEnabled + bit 12
        axis.tick(&mut view, &mut client);
        // Should have cleared bit 4
        assert!(view.control_word & (1 << 4) == 0);

        // Step 2: drive confirms it saw bit 4 go low (bit 12 clears). The move
        // FB waits for this handshake reset before watching for target_reached.
        view.status_word = 0x0027; // OperationEnabled, bit 12 cleared
        axis.tick(&mut view, &mut client);

        // Step 3: simulate target reached (bit 10)
        view.status_word = 0x0427; // OperationEnabled + bit 10
        axis.tick(&mut view, &mut client);
        // Should be idle now
        assert_eq!(axis.op, AxisOp::Idle);
        assert!(!axis.in_motion);
    }

    #[test]
    fn fault_detected_sets_error() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0008); // Fault
        view.error_code = 0x1234;

        axis.tick(&mut view, &mut client);

        assert!(axis.is_error);
        assert_eq!(axis.error_code, 0x1234);
        assert!(axis.error_message.contains("fault"));
    }

    #[test]
    fn fault_recovery_sequence() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0008); // Fault

        axis.reset_faults(&mut view);
        // Step 0: bit 7 should be cleared
        assert!(view.control_word & 0x0080 == 0);

        // Step 1: tick should assert bit 7
        axis.tick(&mut view, &mut client);
        assert!(view.control_word & 0x0080 != 0);

        // Step 2: simulate fault cleared → SwitchOnDisabled
        view.set_state(0x0040);
        axis.tick(&mut view, &mut client);
        assert_eq!(axis.op, AxisOp::Idle);
        assert!(!axis.is_error);
    }

    #[test]
    fn reset_faults_software_only_is_synchronous() {
        // When the axis hits a software error (e.g. target outside the
        // software limits) the drive stays in OperationEnabled — there is
        // no CiA 402 fault to clear. reset_faults() must return the axis
        // to Idle on the same call without engaging the drive's bit-7
        // fault-reset handshake.
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027); // OperationEnabled
        axis.tick(&mut view, &mut client);

        // Trigger a software-only error via target outside software limit.
        axis.set_software_min_limit(207.0);
        axis.move_absolute(&mut view, 200.0, 90.0, 180.0, 180.0);
        assert!(axis.is_error, "move past software limit must set is_error");
        assert!(!axis.is_busy);

        // Capture cw before reset. reset_faults must not modify it for
        // a software-only error (drive is healthy, no handshake needed).
        let cw_before = view.control_word;

        axis.reset_faults(&mut view);

        // Synchronous: error cleared, axis already Idle, not busy.
        assert!(!axis.is_error);
        assert_eq!(axis.error_code, 0);
        assert!(axis.error_message.is_empty());
        assert!(!axis.is_busy);
        assert_eq!(axis.op, AxisOp::Idle);
        // No drive handshake — control word untouched.
        assert_eq!(view.control_word, cw_before);
    }

    #[test]
    fn disable_sequence() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027); // OperationEnabled

        axis.disable(&mut view);
        // Should have sent shutdown command
        assert_eq!(view.control_word & 0x008F, 0x0006);

        // Simulate drive leaving OperationEnabled
        view.set_state(0x0021); // ReadyToSwitchOn
        axis.tick(&mut view, &mut client);
        assert_eq!(axis.op, AxisOp::Idle);
    }

    #[test]
    fn position_tracks_with_home_offset() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);

        // home_offset is now established by homing (the drive owns the
        // reference), not captured at enable(). Set it directly to verify the
        // reported-position formula: position = to_user(raw - home_offset).
        axis.home_offset = 5000;
        view.position_actual = 6600;
        axis.tick(&mut view, &mut client);

        // (6600 - 5000) = 1600 counts = 45° at 12800 counts / 360°.
        assert!((axis.position - 45.0).abs() < 0.1);
    }

    #[test]
    fn set_position_adjusts_home_offset() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.position_actual = 3200;

        axis.set_position(&view, 90.0);
        axis.tick(&mut view, &mut client);

        // home_offset = 3200 - to_counts(90.0) = 3200 - 3200 = 0
        assert_eq!(axis.home_offset, 0);
        assert!((axis.position - 90.0).abs() < 0.01);
    }

    #[test]
    fn halt_runs_multi_stage_close_out() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);

        axis.halt(&mut view);

        // halt() sets CW bit 8 (halt) and clears CW bit 4 (new setpoint).
        assert!(view.control_word & (1 << 8) != 0, "halt bit must be set");
        assert!(
            view.control_word & (1 << 4) == 0,
            "new_setpoint must be cleared"
        );

        // Halt is a multi-stage process. The first stage is WaitStopped.
        assert!(
            matches!(axis.op, AxisOp::Halting(_)),
            "halt should enter Halting state, not Idle"
        );
        let AxisOp::Halting(step) = axis.op.clone() else {
            unreachable!()
        };
        assert_eq!(step, HaltState::WaitStopped as u8);

        // Tick alone does NOT immediately return to Idle anymore —
        // WaitStopped polls position stability (5 consecutive ticks
        // with position stable or velocity near zero). With a static
        // MockView, position stays at 0 and velocity stays at 0, so
        // vel_stopped is true every tick → the counter accumulates
        // and the state progresses after HALT_STABLE_TICKS_REQUIRED.
        for _ in 0..HALT_STABLE_TICKS_REQUIRED {
            axis.tick(&mut view, &mut client);
        }
        // After enough stable ticks we advance past WaitStopped into the mode
        // toggle (Flushing), with the SDO mode switch under way.
        assert!(matches!(axis.op, AxisOp::Halting(_)));
        let AxisOp::Halting(step) = axis.op.clone() else {
            unreachable!()
        };
        assert_eq!(
            step,
            HaltState::Flushing as u8,
            "should advance past WaitStopped once position/velocity is stable"
        );
        // Halt stays asserted through the away-switch (the old target is still
        // live until the queue is flushed).
        assert!(view.control_word & (1 << 8) != 0, "halt held through the away mode switch");

        // axis.is_busy must remain true through the whole halt sequence so
        // callers like MoveToLoad don't see "stopped" until the PP state
        // is fully cleaned up.
        assert!(axis.is_busy, "is_busy must stay true across Halting stages");
    }

    #[test]
    fn is_busy_tracks_operations() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();

        // Idle — not busy
        axis.tick(&mut view, &mut client);
        assert!(!axis.is_busy);

        // Enable — busy
        axis.enable(&mut view);
        axis.tick(&mut view, &mut client);
        assert!(axis.is_busy);

        // Complete enable
        view.set_state(0x0021);
        axis.tick(&mut view, &mut client);
        view.set_state(0x0027);
        axis.tick(&mut view, &mut client);
        assert!(!axis.is_busy);

        // Move — busy
        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);
        axis.tick(&mut view, &mut client);
        assert!(axis.is_busy);
        assert!(axis.in_motion);
    }

    #[test]
    fn fault_during_move_cancels_op() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027); // OperationEnabled
        axis.tick(&mut view, &mut client);

        // Start a move
        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);
        axis.tick(&mut view, &mut client);
        assert!(axis.is_busy);
        assert!(!axis.is_error);

        // Fault occurs mid-move
        view.set_state(0x0008); // Fault
        axis.tick(&mut view, &mut client);

        // is_busy should be false, is_error should be true
        assert!(!axis.is_busy);
        assert!(axis.is_error);
        assert_eq!(axis.op, AxisOp::Idle);
    }

    #[test]
    fn move_absolute_rejected_by_max_limit() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);
        axis.tick(&mut view, &mut client);

        axis.set_software_max_limit(90.0);
        axis.move_absolute(&mut view, 100.0, 90.0, 180.0, 180.0);

        // Should not have started a move — error instead
        assert!(axis.is_error);
        assert_eq!(axis.op, AxisOp::Idle);
        assert!(axis.error_message.contains("max software limit"));
    }

    #[test]
    fn move_absolute_rejected_by_min_limit() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);
        axis.tick(&mut view, &mut client);

        axis.set_software_min_limit(-10.0);
        axis.move_absolute(&mut view, -20.0, 90.0, 180.0, 180.0);

        assert!(axis.is_error);
        assert_eq!(axis.op, AxisOp::Idle);
        assert!(axis.error_message.contains("min software limit"));
    }

    #[test]
    fn move_relative_rejected_by_max_limit() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);
        axis.tick(&mut view, &mut client);

        // Position is 0, max limit 50 — relative move of +60 should be rejected
        axis.set_software_max_limit(50.0);
        axis.move_relative(&mut view, 60.0, 90.0, 180.0, 180.0);

        assert!(axis.is_error);
        assert_eq!(axis.op, AxisOp::Idle);
        assert!(axis.error_message.contains("max software limit"));
    }

    #[test]
    fn move_within_limits_allowed() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);
        axis.tick(&mut view, &mut client);

        axis.set_software_max_limit(90.0);
        axis.set_software_min_limit(-90.0);
        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);

        // Should have started normally
        assert!(!axis.is_error);
        assert!(matches!(
            axis.op,
            AxisOp::Moving(MoveKind::Absolute, 1, _, _)
        ));
    }

    #[test]
    fn runtime_limit_halts_move_in_violated_direction() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);
        axis.tick(&mut view, &mut client);

        axis.set_software_max_limit(45.0);
        // Start a move to exactly the limit (allowed)
        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);

        // Simulate the drive overshooting past 45° (position_actual in counts)
        // home_offset is 0, so 1650 counts = 46.4°
        view.position_actual = 1650;
        view.velocity_actual = 100; // moving positive

        // Simulate set-point ack so we're in Moving step 2
        view.status_word = 0x1027;
        axis.tick(&mut view, &mut client);
        view.status_word = 0x0027;
        axis.tick(&mut view, &mut client);

        // Should have halted cleanly without error. The axis enters the
        // Halting close-out (caller waits for !is_busy then checks
        // at_max_limit).
        assert!(!axis.is_error);
        assert!(axis.at_max_limit);
        assert!(axis.is_busy);
        assert!(matches!(axis.op, AxisOp::Halting(_)));
        // Halt bit (bit 8) should be set
        assert!(view.control_word & (1 << 8) != 0);
    }

    #[test]
    fn runtime_limit_allows_move_in_opposite_direction() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);
        // Start at 50° (past max limit)
        view.position_actual = 1778; // ~50°
        axis.set_software_max_limit(45.0);
        axis.tick(&mut view, &mut client);
        assert!(axis.at_max_limit);

        // Move back toward 0 — should be allowed even though at max limit
        axis.move_absolute(&mut view, 0.0, 90.0, 180.0, 180.0);
        assert!(!axis.is_error);
        assert!(matches!(
            axis.op,
            AxisOp::Moving(MoveKind::Absolute, 1, _, _)
        ));

        // Simulate moving negative — limit check should not halt
        view.velocity_actual = -100;
        view.status_word = 0x1027; // ack
        axis.tick(&mut view, &mut client);
        // Still moving, no error from limit
        assert!(!axis.is_error);
    }

    #[test]
    fn positive_limit_switch_halts_positive_move() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);
        axis.tick(&mut view, &mut client);

        // Start a move in the positive direction
        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);
        view.velocity_actual = 100; // moving positive
                                    // Simulate set-point ack so we're in Moving step 2
        view.status_word = 0x1027;
        axis.tick(&mut view, &mut client);
        view.status_word = 0x0027;

        // Now the positive limit switch trips
        view.positive_limit = true;
        axis.tick(&mut view, &mut client);

        // Limit hit during a regular move enters the Halting close-out:
        // no error, halt bit asserted, drive's queued setpoint will be
        // canceled and halt cleared before the axis returns to Idle.
        // Caller waits for !is_busy then inspects at_positive_limit_switch.
        assert!(!axis.is_error);
        assert!(axis.at_positive_limit_switch);
        assert!(axis.is_busy);
        assert!(matches!(axis.op, AxisOp::Halting(_)));
        // Halt bit should be set
        assert!(view.control_word & (1 << 8) != 0);
    }

    #[test]
    fn negative_limit_switch_halts_negative_move() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);
        axis.tick(&mut view, &mut client);

        // Start a move in the negative direction
        axis.move_absolute(&mut view, -45.0, 90.0, 180.0, 180.0);
        view.velocity_actual = -100; // moving negative
        view.status_word = 0x1027;
        axis.tick(&mut view, &mut client);
        view.status_word = 0x0027;

        // Negative limit switch trips
        view.negative_limit = true;
        axis.tick(&mut view, &mut client);

        // Limit hit during a regular move enters the Halting close-out:
        // no error, halt bit asserted, drive's queued setpoint will be
        // canceled and halt cleared before the axis returns to Idle.
        // Caller waits for !is_busy then inspects at_negative_limit_switch.
        assert!(!axis.is_error);
        assert!(axis.at_negative_limit_switch);
        assert!(axis.is_busy);
        assert!(matches!(axis.op, AxisOp::Halting(_)));
        assert!(view.control_word & (1 << 8) != 0);
    }

    #[test]
    fn limit_halt_flushes_queue_via_mode_toggle() {
        // After a limit-switch halt, the axis runs the Halting close-out:
        // motor stop → toggle the mode of operation (PP → Homing → PP) to flush
        // the set-point queue → clear halt. This verifies it enters that toggle
        // with halt held; the SDO mode-switch completion is hardware-verified.
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027); // OperationEnabled
        axis.tick(&mut view, &mut client);

        // Drive an initial move into a positive limit.
        axis.move_absolute(&mut view, 45.0, 90.0, 180.0, 180.0);
        view.velocity_actual = 100;
        view.status_word = 0x1027;
        axis.tick(&mut view, &mut client);
        view.status_word = 0x0027;
        view.positive_limit = true;
        axis.tick(&mut view, &mut client);

        // Limit halt: in Halting close-out, halt asserted, busy, no error.
        assert!(!axis.is_error);
        assert!(axis.is_busy);
        assert!(matches!(axis.op, AxisOp::Halting(_)));
        assert!(view.control_word & (1 << 8) != 0);

        // Advance past WaitStopped into the mode toggle. With a static MockView
        // and no SDO responder, the mode switch stays in flight — so we verify
        // the structural transition here (the full SDO mode-switch completion is
        // exercised on hardware via the CiA-402 trace): halt is held while the
        // set-point queue is flushed by switching the mode of operation away
        // from Profile Position.
        view.velocity_actual = 0;
        view.positive_limit = false;
        for _ in 0..HALT_STABLE_TICKS_REQUIRED {
            axis.tick(&mut view, &mut client);
        }
        let AxisOp::Halting(step) = axis.op.clone() else {
            unreachable!()
        };
        assert_eq!(step, HaltState::Flushing as u8, "halt flushes the queue via a mode toggle");
        assert!(view.control_word & (1 << 8) != 0, "halt held through the queue flush");
        assert!(axis.is_busy, "axis stays busy through the close-out");
        assert_ne!(
            view.modes_of_operation,
            ModesOfOperation::ProfilePosition.as_i8(),
            "mode switched away from PP to flush the queue",
        );
    }

    #[test]
    fn limit_switch_allows_move_in_opposite_direction() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);
        // Positive limit is active, but we're moving negative (retreating)
        view.positive_limit = true;
        view.velocity_actual = -100;
        axis.tick(&mut view, &mut client);
        assert!(axis.at_positive_limit_switch);

        // Move in the negative direction should be allowed
        axis.move_absolute(&mut view, -10.0, 90.0, 180.0, 180.0);
        view.status_word = 0x1027;
        axis.tick(&mut view, &mut client);

        // Should still be moving, no error
        assert!(!axis.is_error);
        assert!(matches!(axis.op, AxisOp::Moving(_, _, _, _)));
    }

    #[test]
    fn limit_switch_ignored_when_not_moving() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);
        view.positive_limit = true;

        axis.tick(&mut view, &mut client);

        // Output flag is set, but no error since we're not moving
        assert!(axis.at_positive_limit_switch);
        assert!(!axis.is_error);
    }

    #[test]
    fn home_sensor_output_tracks_view() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);

        axis.tick(&mut view, &mut client);
        assert!(!axis.home_sensor);

        view.home_sensor = true;
        axis.tick(&mut view, &mut client);
        assert!(axis.home_sensor);

        view.home_sensor = false;
        axis.tick(&mut view, &mut client);
        assert!(!axis.home_sensor);
    }

    #[test]
    fn velocity_output_converted() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        view.set_state(0x0027);
        // 3200 counts/s = 90 deg/s
        view.velocity_actual = 3200;

        axis.tick(&mut view, &mut client);

        assert!((axis.speed - 90.0).abs() < 0.1);
        assert!(axis.moving_positive);
        assert!(!axis.moving_negative);
    }

    // ── Software homing tests ──

    fn soft_homing_config() -> AxisConfig {
        let mut cfg = AxisConfig::new(12_800).with_user_scale(360.0);
        cfg.homing_speed = 10.0;
        cfg.homing_accel = 20.0;
        cfg.homing_decel = 20.0;
        cfg
    }

    fn soft_homing_axis() -> (
        Axis,
        CommandClient,
        tokio::sync::mpsc::UnboundedSender<mechutil::ipc::CommandMessage>,
        tokio::sync::mpsc::UnboundedReceiver<String>,
    ) {
        use tokio::sync::mpsc;
        let (write_tx, write_rx) = mpsc::unbounded_channel();
        let (response_tx, response_rx) = mpsc::unbounded_channel();
        let client = CommandClient::new(write_tx, response_rx);
        let axis = Axis::new(soft_homing_config(), "TestDrive");
        (axis, client, response_tx, write_rx)
    }

    /// Helper: enable the axis and put it in OperationEnabled state.
    fn enable_axis(axis: &mut Axis, view: &mut MockView, client: &mut CommandClient) {
        view.set_state(0x0027); // OperationEnabled
        axis.tick(view, client);
    }

    /// Test helper: pull the next outgoing SDO request off `write_rx` and feed a
    /// success response back through the client. Returns the request so callers
    /// can inspect the object index / value. Works for ANY SDO — including the
    /// `FbSetModeOfOperation` mode write/read whose transaction id is private —
    /// because the outgoing message carries its own `transaction_id`.
    fn ack_next_sdo(
        write_rx: &mut tokio::sync::mpsc::UnboundedReceiver<String>,
        resp_tx: &tokio::sync::mpsc::UnboundedSender<mechutil::ipc::CommandMessage>,
        client: &mut CommandClient,
        value: serde_json::Value,
    ) -> mechutil::ipc::CommandMessage {
        let raw = write_rx
            .try_recv()
            .expect("expected an outgoing SDO request on write_rx");
        let req: mechutil::ipc::CommandMessage =
            serde_json::from_str(&raw).expect("outgoing SDO request is valid CommandMessage JSON");
        resp_tx
            .send(mechutil::ipc::CommandMessage::response(
                req.transaction_id,
                value,
            ))
            .unwrap();
        client.poll();
        req
    }

    /// Test helper: drive one `FbSetModeOfOperation` cycle (0x6060 write +
    /// 0x6061 read-back) to completion while the axis sits in whatever Wait*
    /// state owns it. The 100 ms read-back gate is real wall-clock time, so this
    /// sleeps just past it. `mode` is the value the drive reports for 0x6061.
    fn drive_one_mode_switch(
        axis: &mut Axis,
        view: &mut MockView,
        client: &mut CommandClient,
        write_rx: &mut tokio::sync::mpsc::UnboundedReceiver<String>,
        resp_tx: &tokio::sync::mpsc::UnboundedSender<mechutil::ipc::CommandMessage>,
        mode: i8,
    ) {
        // 0x6060 write ack → arms the 100 ms read-back timer.
        ack_next_sdo(write_rx, resp_tx, client, json!(null));
        axis.tick(view, client);
        std::thread::sleep(Duration::from_millis(110));
        // Timer elapsed → issues the 0x6061 read.
        axis.tick(view, client);
        ack_next_sdo(write_rx, resp_tx, client, json!({ "value": mode as i64 }));
        axis.tick(view, client);
    }

    #[test]
    fn soft_homing_pnp_sensor_detection_halts() {
        let (mut axis, mut client, _resp_tx, _write_rx) = soft_homing_axis();
        let mut view = MockView::new();
        enable_axis(&mut axis, &mut view, &mut client);

        axis.home(&mut view, HomingMethod::HomeSensorPosPnp);
        // Searching for the sensor.
        axis.op = AxisOp::SoftHoming(HomeState::WaitFoundSensor as u8);

        // PNP sensor trips (true = detected).
        view.home_sensor = true;
        view.position_actual = 5000;
        axis.tick(&mut view, &mut client);

        // Sensor found → halt asserted, advance to wait-stopped.
        assert_eq!(
            axis.op,
            AxisOp::SoftHoming(HomeState::WaitStoppedFoundSensor as u8)
        );
        assert!(
            view.control_word & (1 << 8) != 0,
            "halt bit set on sensor detection"
        );
        assert!(!axis.is_error);
    }

    #[test]
    fn soft_homing_npn_sensor_detection_halts() {
        let (mut axis, mut client, _resp_tx, _write_rx) = soft_homing_axis();
        let mut view = MockView::new();
        // NPN: sensor reads true normally, false when detected.
        view.home_sensor = true;
        enable_axis(&mut axis, &mut view, &mut client);

        axis.home(&mut view, HomingMethod::HomeSensorPosNpn);
        axis.op = AxisOp::SoftHoming(HomeState::WaitFoundSensor as u8);

        // NPN: sensor goes false = detected.
        view.home_sensor = false;
        view.position_actual = 3000;
        axis.tick(&mut view, &mut client);

        assert_eq!(
            axis.op,
            AxisOp::SoftHoming(HomeState::WaitStoppedFoundSensor as u8)
        );
        assert!(!axis.is_error);
    }

    #[test]
    fn soft_homing_limit_switch_suppresses_halt() {
        let (mut axis, mut client, _resp_tx, _write_rx) = soft_homing_axis();
        let mut view = MockView::new();
        enable_axis(&mut axis, &mut view, &mut client);

        // Software homing onto the positive limit switch.
        axis.home(&mut view, HomingMethod::LimitSwitchPosPnp);
        axis.op = AxisOp::SoftHoming(HomeState::WaitFoundSensor as u8);

        // The positive limit trips. Because we are homing *onto* it, the limit
        // protection in check_limits must suppress the error-halt and let the
        // homing FSM treat it as the home trigger instead.
        view.positive_limit = true;
        view.velocity_actual = 100; // moving positive
        view.position_actual = 8000;
        axis.tick(&mut view, &mut client);

        assert_eq!(
            axis.op,
            AxisOp::SoftHoming(HomeState::WaitStoppedFoundSensor as u8)
        );
        assert!(
            !axis.is_error,
            "homed-on limit switch must be suppressed, not faulted"
        );
    }

    #[test]
    fn soft_homing_opposite_limit_still_protects() {
        let (mut axis, mut client, _resp_tx, _write_rx) = soft_homing_axis();
        let mut view = MockView::new();
        enable_axis(&mut axis, &mut view, &mut client);

        // Software homing on home sensor (positive direction)
        axis.home(&mut view, HomingMethod::HomeSensorPosPnp);

        // Progress through initial steps
        axis.tick(&mut view, &mut client); // step 0 → 1
        view.status_word = 0x1027; // ack
        axis.tick(&mut view, &mut client); // step 1 → 2
        view.status_word = 0x0027;
        axis.tick(&mut view, &mut client); // step 2 → 3

        // Negative limit switch trips while searching positive (shouldn't happen
        // in practice, but tests protection)
        view.negative_limit = true;
        view.velocity_actual = -100; // moving negative
        axis.tick(&mut view, &mut client);

        // Should have halted with error (negative limit protects)
        assert!(axis.is_error);
        assert!(axis.error_message.contains("Negative limit switch"));
    }

    #[test]
    fn soft_homing_search_sets_directional_target() {
        let (mut axis, mut client, _resp_tx, _write_rx) = soft_homing_axis();
        let mut view = MockView::new();
        enable_axis(&mut axis, &mut view, &mut client);

        // Negative-direction home: the search move target must be negative.
        axis.home(&mut view, HomingMethod::HomeSensorNegPnp);
        axis.op = AxisOp::SoftHoming(HomeState::Search as u8); // skip the PP-mode SDO preamble
        axis.tick(&mut view, &mut client);
        assert!(view.target_position < 0, "negative home seeks a negative target");

        // Positive-direction home: the search move target must be positive.
        axis.home(&mut view, HomingMethod::HomeSensorPosPnp);
        axis.op = AxisOp::SoftHoming(HomeState::Search as u8);
        axis.tick(&mut view, &mut client);
        assert!(view.target_position > 0, "positive home seeks a positive target");
    }

    #[test]
    fn home_current_position_routes_to_drive_set() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        enable_axis(&mut axis, &mut view, &mut client);

        // CurrentPosition35 is the drive-side "set reference here" path: it enters
        // the SoftHoming FSM at WriteHomeOffset (writes 0x607C) rather than the
        // generic integrated homing path, and carries its own method code (35).
        axis.home(&mut view, HomingMethod::CurrentPosition35);
        assert!(matches!(
            axis.op,
            AxisOp::SoftHoming(s) if s == HomeState::WriteHomeOffset as u8
        ));
        assert_eq!(axis.homing_method, 35);
    }

    #[test]
    fn home_integrated_arbitrary_code() {
        let (mut axis, mut client, _resp_tx, _write_rx) = test_axis();
        let mut view = MockView::new();
        enable_axis(&mut axis, &mut view, &mut client);

        axis.home(&mut view, HomingMethod::Integrated(35));
        // Integrated homing now starts at step 16 (home-offset write).
        assert!(matches!(axis.op, AxisOp::Homing(16)));
        assert_eq!(axis.homing_method, 35);
    }

    #[test]
    fn hardware_homing_skips_speed_sdos_when_zero() {
        use mechutil::ipc::CommandMessage;

        let (mut axis, mut client, resp_tx, mut write_rx) = test_axis();
        let mut view = MockView::new();
        enable_axis(&mut axis, &mut view, &mut client);

        // Config has homing_speed = 0 and homing_accel = 0 (defaults)
        axis.home(&mut view, HomingMethod::Integrated(37));

        // Step 16: writes home-offset SDO (0x607C), then waits ack → step 0.
        axis.tick(&mut view, &mut client);
        assert!(matches!(axis.op, AxisOp::Homing(17)));
        let _ = write_rx.try_recv();
        let tid = axis.homing_sdo_tid;
        resp_tx
            .send(CommandMessage::response(tid, serde_json::json!(null)))
            .unwrap();
        client.poll();
        axis.tick(&mut view, &mut client);
        assert!(matches!(axis.op, AxisOp::Homing(0)));

        // Step 0: writes homing method SDO
        axis.tick(&mut view, &mut client);
        assert!(matches!(axis.op, AxisOp::Homing(1)));

        // Drain the SDO write message
        let _ = write_rx.try_recv();

        // Simulate SDO ack — need to use the correct tid from the sdo write
        let tid = axis.homing_sdo_tid;
        resp_tx
            .send(CommandMessage::response(tid, serde_json::json!(null)))
            .unwrap();
        client.poll();
        axis.tick(&mut view, &mut client);

        // Should have skipped to step 8 (set homing mode)
        assert!(matches!(axis.op, AxisOp::Homing(8)));
    }

    #[test]
    fn hardware_homing_writes_speed_sdos_when_nonzero() {
        use mechutil::ipc::CommandMessage;

        let (mut axis, mut client, resp_tx, mut write_rx) = soft_homing_axis();
        let mut view = MockView::new();
        enable_axis(&mut axis, &mut view, &mut client);

        // Config has homing_speed = 10.0, homing_accel = 20.0
        axis.home(&mut view, HomingMethod::Integrated(37));

        // Step 16: home-offset write (0x607C), ack → step 0.
        axis.tick(&mut view, &mut client);
        assert!(matches!(axis.op, AxisOp::Homing(17)));
        let _ = write_rx.try_recv();
        let tid = axis.homing_sdo_tid;
        resp_tx
            .send(CommandMessage::response(tid, serde_json::json!(null)))
            .unwrap();
        client.poll();
        axis.tick(&mut view, &mut client);

        // Step 0: writes homing method SDO
        axis.tick(&mut view, &mut client);
        assert!(matches!(axis.op, AxisOp::Homing(1)));
        let _ = write_rx.try_recv();

        // SDO ack for homing method
        let tid = axis.homing_sdo_tid;
        resp_tx
            .send(CommandMessage::response(tid, serde_json::json!(null)))
            .unwrap();
        client.poll();
        axis.tick(&mut view, &mut client);
        // Should go to step 2 (write speed SDO), not skip to 8
        assert!(matches!(axis.op, AxisOp::Homing(2)));
    }

    #[test]
    fn soft_homing_edge_during_search_ack() {
        let (mut axis, mut client, _resp_tx, _write_rx) = soft_homing_axis();
        let mut view = MockView::new();
        enable_axis(&mut axis, &mut view, &mut client);

        axis.home(&mut view, HomingMethod::HomeSensorPosPnp);
        // Waiting for the search move's set-point acknowledge.
        axis.op = AxisOp::SoftHoming(HomeState::WaitSearching as u8);

        // Sensor rises before the ack arrives — must still be caught.
        view.home_sensor = true;
        view.position_actual = 2000;
        axis.tick(&mut view, &mut client);

        assert_eq!(
            axis.op,
            AxisOp::SoftHoming(HomeState::WaitFoundSensor as u8)
        );
    }

    /// Regression: a set-current-position home (method 35/37) reports homing
    /// *attained* (SW bit 12) but never *target reached* (SW bit 10). The
    /// completion check must accept attained-alone, or it hangs to timeout
    /// (the field symptom was sw=0x1237 on the Kollmorgen AKD).
    #[test]
    fn soft_homing_completes_on_attained_without_reached() {
        let (mut axis, mut client, _resp_tx, _write_rx) = soft_homing_axis();
        let mut view = MockView::new();
        // OperationEnabled + homing attained (bit 12), target NOT reached (bit 10 clear).
        view.status_word = 0x1027;
        axis.op = AxisOp::SoftHoming(HomeState::WaitHomingDone as u8);
        axis.op_started = Some(Instant::now());

        axis.tick(&mut view, &mut client);

        assert_eq!(
            axis.op,
            AxisOp::SoftHoming(HomeState::ResetHomingTrigger as u8),
            "attained-only must complete homing, not wait for target_reached"
        );
        assert!(!axis.is_error);
    }

    /// Regression: the homing-start gate must not wait for SW bit 12 to *clear*.
    /// An instantaneous method sets attained within one cycle, so bit 12 may
    /// never be observed low — gating on it would race into a spurious
    /// "did not acknowledge homing start" timeout.
    #[test]
    fn soft_homing_start_gate_does_not_require_attained_clear() {
        let (mut axis, mut client, _resp_tx, _write_rx) = soft_homing_axis();
        let mut view = MockView::new();
        // Bit 12 already high (attained), no error bit.
        view.status_word = 0x1027;
        axis.op = AxisOp::SoftHoming(HomeState::WaitHomingStarted as u8);
        axis.op_started = Some(Instant::now());

        axis.tick(&mut view, &mut client);

        assert_eq!(
            axis.op,
            AxisOp::SoftHoming(HomeState::WaitHomingDone as u8),
            "start gate must advance even with attained already set"
        );
        assert!(!axis.is_error);
    }

    /// The shared set-point-queue flush toggles the mode of operation
    /// PP → Homing → PP via `FbSetModeOfOperation` (0x6060 write + 0x6061
    /// read-back). Drives the `FbFlushQueue` directly to completion.
    #[test]
    fn flush_queue_toggles_pp_homing_pp() {
        use tokio::sync::mpsc;
        let (write_tx, mut write_rx) = mpsc::unbounded_channel();
        let (resp_tx, response_rx) = mpsc::unbounded_channel();
        let mut client = CommandClient::new(write_tx, response_rx);
        let mut view = MockView::new();
        let mut sdo = SdoClient::new("TestDrive");
        let mut flush = FbFlushQueue::new();

        // start() switches AWAY from PP (to Homing) — issues the 0x6060 write.
        flush.start(&mut view, &mut client, &mut sdo);
        assert!(flush.is_busy());
        assert_eq!(view.modes_of_operation, ModesOfOperation::Homing.as_i8());

        // Away phase: complete the PP → Homing switch.
        ack_next_sdo(&mut write_rx, &resp_tx, &mut client, json!(null)); // 0x6060 write ack
        flush.tick(&mut view, &mut client, &mut sdo);
        std::thread::sleep(Duration::from_millis(110));
        flush.tick(&mut view, &mut client, &mut sdo); // issues 0x6061 read
        ack_next_sdo(
            &mut write_rx,
            &resp_tx,
            &mut client,
            json!({ "value": ModesOfOperation::Homing.as_i8() as i64 }),
        );
        flush.tick(&mut view, &mut client, &mut sdo); // mode_fb done → begin switch BACK to PP

        assert!(flush.is_busy(), "still flushing — now switching back to PP");
        assert_eq!(
            view.modes_of_operation,
            ModesOfOperation::ProfilePosition.as_i8()
        );

        // Back phase: complete the Homing → PP switch.
        ack_next_sdo(&mut write_rx, &resp_tx, &mut client, json!(null)); // 0x6060 write ack
        flush.tick(&mut view, &mut client, &mut sdo);
        std::thread::sleep(Duration::from_millis(110));
        flush.tick(&mut view, &mut client, &mut sdo); // issues 0x6061 read
        ack_next_sdo(
            &mut write_rx,
            &resp_tx,
            &mut client,
            json!({ "value": ModesOfOperation::ProfilePosition.as_i8() as i64 }),
        );
        flush.tick(&mut view, &mut client, &mut sdo);

        assert!(!flush.is_busy(), "flush complete");
        assert!(!flush.is_error());
    }

    /// End-to-end coverage of the production `home(CurrentPosition)` path (the
    /// one gen4_ac uses for "Home Press"): write 0x607C, switch to Homing mode,
    /// write the method, trigger the set-current-position home, switch back to
    /// PP, and hold. Drives every SDO ack and mode read-back. The drive reports
    /// attained-without-reached throughout (method completes instantly). The
    /// DRIVE owns the position afterward — the software offset is zero.
    #[test]
    fn home_current_position_sets_drive_and_zeros_offset() {
        let (mut axis, mut client, resp_tx, mut write_rx) = soft_homing_axis();
        let mut view = MockView::new();
        enable_axis(&mut axis, &mut view, &mut client);
        // OperationEnabled + homing attained (bit 12), target never reached.
        view.status_word = 0x1027;

        axis.set_home_position(90.0);
        axis.home(&mut view, HomingMethod::CurrentPosition35);
        assert_eq!(axis.config.home_position, 90.0);
        assert!(matches!(
            axis.op,
            AxisOp::SoftHoming(s) if s == HomeState::WriteHomeOffset as u8
        ));

        // WriteHomeOffset issues the 0x607C reference write.
        axis.tick(&mut view, &mut client); // → WaitHomeOffsetDone
        // WaitHomeOffsetDone: ack the 0x607C write.
        ack_next_sdo(&mut write_rx, &resp_tx, &mut client, json!(null));
        axis.tick(&mut view, &mut client); // → WaitHomeOffsetReadback (issues diagnostic 0x607C read)
        // Diagnostic read-back of 0x607C — value is logged only, not asserted on.
        ack_next_sdo(&mut write_rx, &resp_tx, &mut client, json!({ "value": -9701 }));
        axis.tick(&mut view, &mut client); // → WriteHomingModeOp

        // WriteHomingModeOp issues the Homing-mode switch.
        axis.tick(&mut view, &mut client); // → WaitWriteHomingModeOp
        drive_one_mode_switch(
            &mut axis,
            &mut view,
            &mut client,
            &mut write_rx,
            &resp_tx,
            ModesOfOperation::Homing.as_i8(),
        ); // → WriteHomingMethod

        // WriteHomingMethod issues the 0x6098 method write.
        axis.tick(&mut view, &mut client); // → WaitWriteHomingMethodDone
        ack_next_sdo(&mut write_rx, &resp_tx, &mut client, json!(null));
        axis.tick(&mut view, &mut client); // → ClearHomingTrigger

        axis.tick(&mut view, &mut client); // ClearHomingTrigger → TriggerHoming
        axis.tick(&mut view, &mut client); // TriggerHoming → WaitHomingStarted
        axis.tick(&mut view, &mut client); // WaitHomingStarted → WaitHomingDone
        axis.tick(&mut view, &mut client); // WaitHomingDone (bit 12) → ResetHomingTrigger
        axis.tick(&mut view, &mut client); // ResetHomingTrigger → WaitHomingTriggerCleared
        axis.tick(&mut view, &mut client); // WaitHomingTriggerCleared → AlignTargetBeforePP

        // Drive now owns the reference; the software offset is zeroed.
        assert_eq!(axis.home_offset, 0);

        // AlignTargetBeforePP re-asserts 0x607A = 0x6064, then advances to the
        // PP-mode switch (no SDO of its own).
        axis.tick(&mut view, &mut client); // AlignTargetBeforePP → WriteMotionModeOfOperation

        // Switch back to PP mode. Completing the PP switch finishes the home:
        // the drive holds at the just-homed position and NO fresh PP set-point is
        // latched (a latch would race the just-relabeled 0x6064 and lurch the
        // motor — the old SendCurrentPositionTarget bug). Mirrors the proven
        // SDO-only homing sequence, which never issues a post-home set-point.
        axis.tick(&mut view, &mut client); // WriteMotionModeOfOperation → WaitWriteMotionModeOfOperation
        drive_one_mode_switch(
            &mut axis,
            &mut view,
            &mut client,
            &mut write_rx,
            &resp_tx,
            ModesOfOperation::ProfilePosition.as_i8(),
        ); // → complete (Idle), no set-point latched

        assert_eq!(axis.op, AxisOp::Idle);
        assert!(!axis.is_error, "persistent home must finish clean");
        assert!(!axis.is_busy);
        assert_eq!(axis.home_offset, 0);
    }
}