autocore-std 3.3.40

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
//! Function block for the Beckhoff EL3356 strain-gauge EtherCAT terminal.
//!
//! # Responsibilities
//!
//! - **Peak tracking**: maintains `peak_load` as the largest-magnitude `load`
//!   value seen since construction or the last [`reset_peak`](El3356::reset_peak) /
//!   [`tare`](El3356::tare) call.
//! - **Tare pulse**: [`tare`](El3356::tare) sets the device's tare bit and
//!   automatically clears it after 100 ms. Also resets the peak.
//! - **Load cell configuration via SDO**: [`configure`](El3356::configure)
//!   sequences three SDO writes to `0x8000`:
//!     - sub `0x23` — sensitivity (mV/V)
//!     - sub `0x24` — full-scale load
//!     - sub `0x27` — scale factor
//!
//! # Wiring in project.json
//!
//! The FB is device-agnostic at construction; the EtherCAT device name is
//! passed to [`new`](El3356::new) and used for SDO topic routing. The five
//! PDO-linked GM variables (`{prefix}_load`, `_load_steady`, `_load_error`,
//! `_load_overrange`, `_tare`) must exist and be linked to the terminal's
//! corresponding FQDNs in `project.json`.
//!
//! # Example
//!
//! ```ignore
//! use autocore_std::fb::beckhoff::El3356;
//! use autocore_std::el3356_view;
//!
//! pub struct MyProgram {
//!     load_cell: El3356,
//!     manual_tare_edge: autocore_std::fb::RTrig,
//! }
//!
//! impl MyProgram {
//!     pub fn new() -> Self {
//!         Self {
//!             load_cell: El3356::new("EL3356_0"),
//!             manual_tare_edge: Default::default(),
//!         }
//!     }
//! }
//!
//! impl ControlProgram for MyProgram {
//!     type Memory = GlobalMemory;
//!
//!     fn process_tick(&mut self, ctx: &mut TickContext<Self::Memory>) {
//!         // Edge-detect a manual tare button from an HMI
//!         if self.manual_tare_edge.call(ctx.gm.manual_tare) {
//!             self.load_cell.tare();
//!         }
//!
//!         let mut view = el3356_view!(ctx.gm, impact);
//!         self.load_cell.tick(&mut view, ctx.client);
//!
//!         // Peak load is exposed for display / logging
//!         ctx.gm.impact_peak_load = self.load_cell.peak_load;
//!     }
//! }
//! ```
//! # Regarding Filtering on the EL3356
//! 
//! To start, Beckhoff implements an averager as a hardware quadruple averager (a 4-sample moving average filter). 
//! Because this averager operates directly on the internal, high-speed conversion clock of the ADC rather than 
//! the slower EtherCAT cycle time, its effect on latency is incredibly small.
//! 
//! A moving average delays a signal by roughly (N−1)/2 sample periods. Based on the terminal's 
//! internal hardware sampling rates:
//!     Mode 0 (10.5 kSps internal rate): The 4-sample averager adds roughly 0.14 ms of latency.
//!     Mode 1 (105.5 kSps internal rate): The 4-sample averager adds roughly 0.014 ms of latency.
//! When you compare this to the latencies of the software IIR filters (which range from 0.3 ms up to 3600 ms), 
//! turning the averager on is practically "free" in terms of time penalty.
//! Why Use Both a Filter and an Averager?
//! It comes down to the order of operations in signal processing and the different types of noise each tool is 
//! designed to eliminate. The signal chain in the EL3356 runs like this:
//! Raw ADC → Hardware Averager → Software Filter (FIR/IIR) → Process Data Object (PDO)
//! You use them together because they tackle entirely different problems:
//! 1. Targeting Different Noise Profiles
//!     The Averager: A moving average is the optimal tool for eliminating high-frequency, random Gaussian 
//! "white noise" caused by electrical interference in your sensor wires or the internal electronics. 
//! It smooths out the "fuzz."
//!     The Software Filter: FIR and IIR filters are designed to eliminate specific, lower-frequency phenomena. 
//! An FIR notch filter kills 50/60 Hz AC mains hum. An IIR low-pass filter damps mechanical vibrations 
//! (like the swinging of a hopper or the physical ringing of a force plate after a sudden impact).
//! 2. Protecting the IIR Filter
//! IIR (Infinite Impulse Response) filters are highly sensitive to sudden, sharp spikes in data. 
//! If a random spike of electrical noise hits an IIR filter, the filter's math causes that spike to "ring" 
//! and decay slowly (an exponential tail), which subtly skews your weight value. By running the hardware averager 
//! first, you clip off those random electrical spikes before they ever reach the sensitive math of the IIR filter.
//! 3. Achieving Lower Overall Latency
//! Because the averager cleans up the baseline signal without distorting the shape of your step response (it maintains a linear phase), 
//! it feeds a much cleaner baseline into the software filter stage. 
//! This often allows you to get away with using a weaker, faster IIR filter (e.g., using IIR3 instead of IIR5) to handle 
//! your mechanical vibrations, ultimately saving you tens or hundreds of milliseconds of total system latency.
//! 


use crate::ethercat::{SdoClient, SdoResult};
use crate::CommandClient;
use serde_json::json;
use strum_macros::FromRepr;
use std::time::{Duration, Instant};

use super::El3356View;

/// Duration of the tare pulse. Matches the `T#100MS` preset in the original
/// TwinCAT implementation.
const TARE_PULSE: Duration = Duration::from_millis(100);

/// Per-SDO timeout. SDO transfers against a functioning EL3356 complete in
/// tens of milliseconds; a multi-second ceiling is generous.
const SDO_TIMEOUT: Duration = Duration::from_secs(3);

// SDO sub-indices on object 0x8000.
const SDO_IDX: u16 = 0x8000;
const SUB_MV_V: u8 = 0x23;
const SUB_FULL_SCALE: u8 = 0x24;
const SUB_SCALE_FACTOR: u8 = 0x27;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
    Idle,
    WritingMvV,
    WritingFullScale,
    WritingScaleFactor,
    WaitWriteGeneralSdo,
    ReadingMvV,
    ReadingFullScale,
    ReadingScaleFactor,
    WaitReadGeneralSdo
}


/// Digital software filter settings for the Beckhoff EL3356/EP3356 load cell terminal.
/// The selected filter processes the ADC data before it is output as a process value.
/// Factory default for an EL3356 is FIR 50Hz
#[repr(u16)]
#[derive(Copy, Clone, Debug, FromRepr)]
pub enum El3356Filters {
    /// 50 Hz FIR (Finite Impulse Response) notch filter.
    /// Acts as a non-recursive filter that suppresses 50 Hz mains frequency interference 
    /// and its multiples. Select this in environments with 50 Hz AC power to eliminate electrical noise.
    /// 
    /// **Estimated Latency (10-90% step response):** ~13 ms.
    FIR50Hz = 0,

    /// 60 Hz FIR (Finite Impulse Response) notch filter.
    /// Acts as a non-recursive filter that suppresses 60 Hz mains frequency interference 
    /// and its multiples. Select this in environments with 60 Hz AC power to eliminate electrical noise.
    /// 
    /// **Estimated Latency (10-90% step response):** ~16 ms.
    FIR60Hz = 1,

    /// Weakest IIR (Infinite Impulse Response) low-pass filter (Level 1).
    /// Cutoff frequency of roughly 2000 Hz. IIR filters run cycle-synchronously.
    /// Select this when you need a very fast step response (highly dynamic measurement) 
    /// and only minimal signal smoothing is required.
    /// 
    /// **Estimated Latency (10-90% step response):** ~0.3 ms.
    IIR1 = 2,

    /// IIR low-pass filter (Level 2).
    /// Cutoff frequency of roughly 500 Hz. Provides very light smoothing.
    /// 
    /// **Estimated Latency (10-90% step response):** ~0.8 ms.
    IIR2 = 3,

    /// IIR low-pass filter (Level 3).
    /// Cutoff frequency of roughly 125 Hz. Suitable for fast machinery tracking.
    /// 
    /// **Estimated Latency (10-90% step response):** ~3.5 ms.
    IIR3 = 4,

    /// IIR low-pass filter (Level 4).
    /// Cutoff frequency of roughly 30 Hz. A good baseline for moderate mechanical vibrations.
    /// 
    /// **Estimated Latency (10-90% step response):** ~14 ms.
    IIR4 = 5,

    /// IIR low-pass filter (Level 5).
    /// Cutoff frequency of roughly 8 Hz. Stronger smoothing for slower processes.
    /// 
    /// **Estimated Latency (10-90% step response):** ~56 ms.
    IIR5 = 6,

    /// IIR low-pass filter (Level 6).
    /// Cutoff frequency of roughly 2 Hz. Heavy smoothing for mostly static loads.
    /// 
    /// **Estimated Latency (10-90% step response):** ~225 ms.
    IIR6 = 7,

    /// IIR low-pass filter (Level 7).
    /// Cutoff frequency of roughly 0.5 Hz. Very heavy smoothing.
    /// 
    /// **Estimated Latency (10-90% step response):** ~900 ms.
    IIR7 = 8,

    /// Strongest IIR low-pass filter (Level 8).
    /// Cutoff frequency of roughly 0.1 Hz. Select this for highly static measurements 
    /// where maximum damping is needed to obtain a completely calm, stable weight/signal value.
    /// 
    /// **Estimated Latency (10-90% step response):** ~3600 ms.
    IIR8 = 9,

    /// Dynamically adjusts between IIR1 and IIR8 based on the rate of signal change.
    /// When the input variable changes rapidly, the filter automatically "opens" (e.g., switches 
    /// toward IIR1) to track the load quickly. When the signal stabilizes, it "closes" (towards IIR8) 
    /// to provide maximum damping and high accuracy for static states. Select this for applications 
    /// like dosing or filling where you need both fast tracking and high precision.
    /// 
    /// **Estimated Latency:** Variable, sweeping dynamically from ~0.3 ms up to ~3600 ms.
    DynamicIIR = 10,

    /// Variable FIR notch filter adjusted dynamically via Process Data Objects (PDO).
    /// Allows the notch filter frequency to be set in 0.1 Hz increments during operation 
    /// (from 0.1 Hz to 200 Hz) via an output data object. Select this to suppress mechanical 
    /// vibrations or interference of a known, potentially variable frequency (e.g., compensating 
    /// for oscillations from a driven screw conveyor where the rotational speed is known).
    /// 
    /// **Estimated Latency:** Variable, inherently dependent on the specific frequency dialed into the PDO.
    PDOFilterFrequency = 11
}

/// Function block for the Beckhoff EL3356 strain-gauge terminal.
pub struct El3356 {
    // Configuration
    sdo: SdoClient,

    // Outputs — read by the control program each tick
    /// Largest absolute load seen since construction, last reset, or last tare.
    pub peak_load: f32,
    /// True while a configuration read or write sequence is in progress.
    pub busy: bool,
    /// True after an SDO operation failed. Clear with [`clear_error`](El3356::clear_error).
    pub error: bool,
    /// Last error message, if any.
    pub error_message: String,
    /// Current sensitivity (mV/V) value on the device. Populated by the last
    /// successful [`configure`](Self::configure) or
    /// [`read_configuration`](Self::read_configuration). `None` until one of
    /// those completes. Reset to `None` at the start of each call.
    pub configured_mv_v: Option<f32>,
    /// Current full-scale load value on the device. Populated by the last
    /// successful [`configure`](Self::configure) or
    /// [`read_configuration`](Self::read_configuration). `None` until one
    /// completes. Reset to `None` at the start of each call.
    pub configured_full_scale_load: Option<f32>,
    /// Current scale factor on the device. Populated by the last successful
    /// [`configure`](Self::configure) or
    /// [`read_configuration`](Self::read_configuration). `None` until one
    /// completes. Reset to `None` at the start of each call.
    pub configured_scale_factor: Option<f32>,

    // Internal state
    state: State,
    pending_tid: Option<u32>,
    /// Values buffered for the current configure() sequence.
    pending_full_scale: f32,
    pending_mv_v: f32,
    pending_scale_factor: f32,
    /// When set, `tick()` will hold `view.tare = true` until this moment is
    /// reached, at which point it clears the tare bit.
    tare_release_at: Option<Instant>,


    /// Resulting value of a general SDO read.
    sdo_res_value : serde_json::Value
}

/// Parse a REAL32 value from an `ethercat.read_sdo` response.
///
/// The autocore-ethercat module reports the 4 raw bytes as a `u32` under the
/// `value` field (little-endian assembly). The EL3356 stores its calibration
/// parameters as IEEE-754 REAL32, so we reinterpret those bits as `f32` via
/// `f32::from_bits`. As a fallback (e.g. future module revisions that return
/// a numeric `value`), we also accept a direct `f64` and coerce.
fn parse_sdo_real32(data: &serde_json::Value) -> Option<f32> {
    let v = data.get("value")?;
    if let Some(bits) = v.as_u64() {
        // Canonical path: raw 4-byte u32 reinterpret as f32.
        return Some(f32::from_bits(bits as u32));
    }
    if let Some(f) = v.as_f64() {
        return Some(f as f32);
    }
    None
}

impl El3356 {
    /// Create a new EL3356 function block for the given EtherCAT device name.
    ///
    /// `device` must match the name used in `project.json`'s ethercat device
    /// list (it's the `device` field sent with every SDO request).
    pub fn new(device: &str) -> Self {
        Self {
            sdo: SdoClient::new(device),
            peak_load: 0.0,
            busy: false,
            error: false,
            error_message: String::new(),
            configured_mv_v: None,
            configured_full_scale_load: None,
            configured_scale_factor: None,
            state: State::Idle,
            pending_tid: None,
            pending_full_scale: 0.0,
            pending_mv_v: 0.0,
            pending_scale_factor: 0.0,
            tare_release_at: None,
            sdo_res_value : serde_json::Value::Null
        }
    }

    /// Call every control cycle.
    ///
    /// Performs three things, in order:
    /// 1. Updates `peak_load` from `*view.load`.
    /// 2. Releases the tare pulse after 100 ms.
    /// 3. Progresses any in-flight SDO operation from [`configure`](Self::configure).
    pub fn tick(&mut self, view: &mut El3356View, client: &mut CommandClient) {
        // 1. Peak tracking
        let abs_load = view.load.abs();
        if abs_load > self.peak_load.abs() {
            self.peak_load = *view.load;
        }

        // 2. Tare pulse release
        if let Some(release_at) = self.tare_release_at {
            if Instant::now() >= release_at {
                *view.tare = false;
                self.tare_release_at = None;
            } else {
                *view.tare = true;
            }
        }

        // 3. SDO sequence
        self.progress_sdo(client);
    }

    /// Begin an SDO configuration sequence: sensitivity (mV/V), full-scale
    /// load, and scale factor written to object `0x8000` subs `0x23`, `0x24`,
    /// and `0x27` respectively. Non-blocking — sets `busy = true` and returns
    /// immediately. Poll `busy` / `error` on subsequent ticks.
    ///
    /// No-op (logs a warning) if the FB is already `busy`. Any existing error
    /// flag is cleared at the start of a new sequence.
    pub fn configure(
        &mut self,
        client: &mut CommandClient,
        full_scale_load: f32,
        sensitivity_mv_v: f32,
        scale_factor: f32,
    ) {
        if self.busy {
            log::warn!("El3356::configure called while busy; request ignored");
            return;
        }
        self.error = false;
        self.error_message.clear();
        self.pending_full_scale = full_scale_load;
        self.pending_mv_v = sensitivity_mv_v;
        self.pending_scale_factor = scale_factor;

        // Start with mV/V (sub 0x23)
        let tid = self.sdo.write(client, SDO_IDX, SUB_MV_V, json!(sensitivity_mv_v));
        self.pending_tid = Some(tid);
        self.state = State::WritingMvV;
        self.busy = true;
    }

    /// Begin an SDO read sequence that fetches the three calibration
    /// parameters from the terminal's non-volatile memory.
    ///
    /// The EL3356 stores sensitivity, full-scale load, and scale factor
    /// persistently, so the card may power up with values from a previous
    /// configuration — not necessarily what the current control program
    /// expects. Call `read_configuration` at startup (or whenever you need
    /// to verify the sensor parameters) to populate the `configured_*`
    /// fields with the device's current values.
    ///
    /// Non-blocking: sets `busy = true` and returns immediately. Poll `busy`
    /// / `error` on subsequent ticks. No-op (logs a warning) if already busy.
    /// Clears `error` and resets all three `configured_*` fields to `None`
    /// at the start so intermediate values aren't mistaken for final ones.
    pub fn read_configuration(&mut self, client: &mut CommandClient) {
        if self.busy {
            log::warn!("El3356::read_configuration called while busy; request ignored");
            return;
        }
        self.error = false;
        self.error_message.clear();
        self.configured_mv_v = None;
        self.configured_full_scale_load = None;
        self.configured_scale_factor = None;

        let tid = self.sdo.read(client, SDO_IDX, SUB_MV_V);
        self.pending_tid = Some(tid);
        self.state = State::ReadingMvV;
        self.busy = true;
    }

    /// Reset `peak_load` to `0.0`. Immediate; no IPC.
    pub fn reset_peak(&mut self) {
        self.peak_load = 0.0;
    }

    /// Pulse the tare bit high for 100 ms, and reset the peak.
    ///
    /// The device-side bit (`view.tare`) is actually written by [`tick`](Self::tick),
    /// so `tick` must be called every cycle. If `tare` is called while a
    /// previous pulse is still in progress, the 100 ms window restarts.
    pub fn tare(&mut self) {
        self.peak_load = 0.0;
        self.tare_release_at = Some(Instant::now() + TARE_PULSE);
    }

    /// Clear the error flag and message.
    pub fn clear_error(&mut self) {
        self.error = false;
        self.error_message.clear();
    }

    /// Write an arbitrary SDO. Non-blocking; sets `busy = true` and tracks
    /// the response through the FB's state machine like the other operations.
    ///
    /// Does **not** touch the `configured_*` calibration fields — generic
    /// writes are orthogonal to the calibration cycle managed by
    /// [`configure`](Self::configure) and [`read_configuration`](Self::read_configuration).
    pub fn sdo_write(
        &mut self,
        client: &mut CommandClient,
        index: u16,
        sub_index: u8,
        value: serde_json::Value,
    ) {
        if self.busy {
            log::warn!("El3356::sdo_write called while busy; request ignored");
            return;
        }

        self.error = false;
        self.error_message.clear();

        let tid = self.sdo.write(client, index, sub_index, value);
        self.pending_tid = Some(tid);
        self.state = State::WaitWriteGeneralSdo;
        self.busy = true;
    }

    /// Read an arbitrary SDO. Non-blocking; the response lands in the
    /// internal result buffer, retrievable via [`result`](Self::result),
    /// [`result_as_f64`](Self::result_as_f64),
    /// [`result_as_i64`](Self::result_as_i64), or
    /// [`result_as_f32`](Self::result_as_f32) once `busy` clears.
    ///
    /// Does **not** touch the `configured_*` calibration fields — generic
    /// reads are orthogonal to the calibration cycle managed by
    /// [`configure`](Self::configure) and [`read_configuration`](Self::read_configuration).
    pub fn sdo_read(
        &mut self,
        client: &mut CommandClient,
        index: u16,
        sub_index: u8,
    ) {
        if self.busy {
            log::warn!("El3356::sdo_read called while busy; request ignored");
            return;
        }

        self.error = false;
        self.error_message.clear();

        let tid = self.sdo.read(client, index, sub_index);
        self.pending_tid = Some(tid);
        self.state = State::WaitReadGeneralSdo;
        self.busy = true;
    }

    /// Enable or disable the filter on Mode 0, which is the default, slower mode of the bridge input ADC.
    /// Factory default is TRUE.
    /// Mode 0 is active when the Sample Mode bit of the Control Word is FALSE.
    pub fn set_mode0_filter_enabled(&mut self, client: &mut CommandClient, enable : bool) {
        if self.busy {
            log::warn!("El3356::set_mode0_filter_enabled called while busy; request ignored");
            return;
        }

        self.sdo_write(client, 0x8000, 0x01, json!(enable));
    }

    /// Enable or disable the averager on Mode 0, which is the default, slower mode of the bridge input ADC.
    /// The averager is low-latency and should usually be left on.
    /// Mode 0 (10.5 kSps internal rate): The 4-sample averager adds roughly 0.14 ms of latency.
    /// Factory default is TRUE.
    /// Mode 0 is active when the Sample Mode bit of the Control Word is FALSE.
    pub fn set_mode0_averager_enabled(&mut self, client: &mut CommandClient, enable : bool) {
        if self.busy {
            log::warn!("El3356::set_mode0_averager_enabled called while busy; request ignored");
            return;
        }

        self.sdo_write(client, 0x8000, 0x03, json!(enable));
    }    

    /// Set the Mode 1 filter (CoE 0x8000:11). 
    /// Mode 0, the default mode, is High Precision. 
    /// Mode 0 is active when the Sample Mode bit of the Control Word is FALSE.
    /// The ADC runs slower (yielding a hardware latency of around 7.2 ms) but delivers very high accuracy and low noise.     
    /// Mode 0 is typically used paired with a stronger IIR filter—for highly accurate, static weighing where a completely calm value is required.
    pub fn set_mode0_filter(&mut self, client: &mut CommandClient, filter : El3356Filters) {
        if self.busy {
            log::warn!("El3356::set_mode0_filter called while busy; request ignored");
            return;
        }

        self.sdo_write(client, 0x8000, 0x11, json!(filter as u16));
    }


    /// Enable or disable the filter on Mode 1, the faster mode of the bridge input ADC.
    /// Factory default is TRUE.
    /// Mode 1 is active when the Sample Mode bit of the Control Word is TRUE.
    pub fn set_mode1_filter_enabled(&mut self, client: &mut CommandClient, enable : bool) {
        if self.busy {
            log::warn!("El3356::set_mode1_filter_enabled called while busy; request ignored");
            return;
        }

        self.sdo_write(client, 0x8000, 0x02, json!(enable));
    }

    /// Enable or disable the averager on Mode 1, the faster mode of the bridge input ADC.
    /// The averager is low-latency and should usually be left on.
    /// Mode 1 (105.5 kSps internal rate): The 4-sample averager adds roughly 0.014 ms of latency.
    /// Factory default is TRUE.
    /// Mode 1 is active when the Sample Mode bit of the Control Word is TRUE.
    pub fn set_mode1_averager_enabled(&mut self, client: &mut CommandClient, enable : bool) {
        if self.busy {
            log::warn!("El3356::set_mode1_averager_enabled called while busy; request ignored");
            return;
        }

        self.sdo_write(client, 0x8000, 0x05, json!(enable));
    }

    /// Set the Mode 1 filter (CoE 0x8000:12).
    /// Mode 1 sacrifices a bit of accuracy for speed: the ADC runs much faster
    /// (yielding a hardware latency around 0.72 ms).
    /// Mode 1 is typically paired with a very weak filter (like IIR1 or disabled entirely)
    /// to track fast transients — for example, capturing a rapid impact or
    /// tracking a high-speed dosing cycle.
    /// Mode 1 is active when the Sample Mode bit of the Control Word is TRUE.
    pub fn set_mode1_filter(&mut self, client: &mut CommandClient, filter : El3356Filters) {
        if self.busy {
            log::warn!("El3356::set_mode1_filter called while busy; request ignored");
            return;
        }

        self.sdo_write(client, 0x8000, 0x12, json!(filter as u16));
    }



    /// The FB encountered an error processing the last command.
    pub fn is_error(&self) -> bool {
        return self.error;
    }

    /// The FB is busy processing a command.
    pub fn is_busy(&self) -> bool {
        return self.busy;
    }

    /// Full reset: drop all transient state so the FB behaves as if
    /// freshly constructed (except for the cached SDO device name).
    ///
    /// Clears the error flag, cancels any in-flight SDO operation, releases
    /// the tare bit on the next [`tick`](Self::tick), and discards the last
    /// `sdo_read` result. Does **not** zero `peak_load` — call
    /// [`reset_peak`](Self::reset_peak) or [`tare`](Self::tare) if you need
    /// that — and does **not** clear `configured_*`; those stay populated
    /// from the last [`configure`](Self::configure) or
    /// [`read_configuration`](Self::read_configuration) so the program's
    /// view of the device's calibration survives a mid-op abort.
    pub fn reset(&mut self) {
        self.error = false;
        self.error_message.clear();
        self.pending_tid = None;
        self.state = State::Idle;
        self.busy = false;
        self.tare_release_at = None;
        self.sdo_res_value = serde_json::Value::Null;
    }


    /// Get the full response from the most recent [`sdo_read`](Self::sdo_read).
    ///
    /// The returned value is the complete `ethercat.read_sdo` payload — an
    /// object with `value`, `value_hex`, `size`, `raw_bytes`, etc. Prefer the
    /// typed accessors ([`result_as_f64`](Self::result_as_f64),
    /// [`result_as_i64`](Self::result_as_i64),
    /// [`result_as_f32`](Self::result_as_f32)) for scalar register reads.
    pub fn result(&self) -> serde_json::Value {
        self.sdo_res_value.clone()
    }

    /// Get the `value` field of the most recent [`sdo_read`](Self::sdo_read)
    /// as an `f64`, if the SDO returned a number. Returns `None` if no read
    /// has completed, the response had no `value` field, or the field is not
    /// coercible to `f64`.
    pub fn result_as_f64(&self) -> Option<f64> {
        self.sdo_res_value.get("value").and_then(|v| v.as_f64())
    }

    /// Get the `value` field of the most recent [`sdo_read`](Self::sdo_read)
    /// as an `i64`. See [`result_as_f64`](Self::result_as_f64) for `None`
    /// semantics.
    pub fn result_as_i64(&self) -> Option<i64> {
        self.sdo_res_value.get("value").and_then(|v| v.as_i64())
    }

    /// Get the `value` field of the most recent [`sdo_read`](Self::sdo_read)
    /// as an `f32`, interpreting the returned `u32` bit pattern as an
    /// IEEE-754 single-precision float. This is the correct accessor for
    /// REAL32 SDOs (e.g. the EL3356's calibration parameters).
    pub fn result_as_f32(&self) -> Option<f32> {
        parse_sdo_real32(&self.sdo_res_value)
    }


    // ──────────────────────────────────────────────────────────────
    // Internal helpers
    // ──────────────────────────────────────────────────────────────

    fn progress_sdo(&mut self, client: &mut CommandClient) {
        let tid = match self.pending_tid {
            Some(t) => t,
            None => return,
        };

        let result = self.sdo.result(client, tid, SDO_TIMEOUT);
        match result {
            SdoResult::Pending => {} // keep waiting
            SdoResult::Ok(data) => match self.state {
                State::WritingMvV => {
                    self.configured_mv_v = Some(self.pending_mv_v);
                    let next_tid = self.sdo.write(
                        client, SDO_IDX, SUB_FULL_SCALE, json!(self.pending_full_scale),
                    );
                    self.pending_tid = Some(next_tid);
                    self.state = State::WritingFullScale;
                }
                State::WritingFullScale => {
                    self.configured_full_scale_load = Some(self.pending_full_scale);
                    let next_tid = self.sdo.write(
                        client, SDO_IDX, SUB_SCALE_FACTOR, json!(self.pending_scale_factor),
                    );
                    self.pending_tid = Some(next_tid);
                    self.state = State::WritingScaleFactor;
                }
                State::WritingScaleFactor => {
                    self.configured_scale_factor = Some(self.pending_scale_factor);
                    self.pending_tid = None;
                    self.state = State::Idle;
                    self.busy = false;
                },
                State::WaitWriteGeneralSdo => {
                    self.pending_tid = None;
                    self.state = State::Idle;
                    self.busy = false;
                },
                State::ReadingMvV => match parse_sdo_real32(&data) {
                    Some(v) => {
                        self.configured_mv_v = Some(v);
                        let next_tid = self.sdo.read(client, SDO_IDX, SUB_FULL_SCALE);
                        self.pending_tid = Some(next_tid);
                        self.state = State::ReadingFullScale;
                    }
                    None => self.set_error(&format!(
                        "SDO read 0x8000:0x{:02X} (mV/V) returned unparseable value: {}",
                        SUB_MV_V, data,
                    )),
                },
                State::ReadingFullScale => match parse_sdo_real32(&data) {
                    Some(v) => {
                        self.configured_full_scale_load = Some(v);
                        let next_tid = self.sdo.read(client, SDO_IDX, SUB_SCALE_FACTOR);
                        self.pending_tid = Some(next_tid);
                        self.state = State::ReadingScaleFactor;
                    }
                    None => self.set_error(&format!(
                        "SDO read 0x8000:0x{:02X} (full-scale) returned unparseable value: {}",
                        SUB_FULL_SCALE, data,
                    )),
                },
                State::ReadingScaleFactor => match parse_sdo_real32(&data) {
                    Some(v) => {
                        self.configured_scale_factor = Some(v);
                        self.pending_tid = None;
                        self.state = State::Idle;
                        self.busy = false;
                    }
                    None => self.set_error(&format!(
                        "SDO read 0x8000:0x{:02X} (scale factor) returned unparseable value: {}",
                        SUB_SCALE_FACTOR, data,
                    )),
                },
                State::WaitReadGeneralSdo => {
                    self.sdo_res_value = data;
                    self.pending_tid = None;
                    self.state = State::Idle;
                    self.busy = false;
                },
                State::Idle => {
                    // Response arrived but we're not in a sequence; discard.
                    self.pending_tid = None;
                }
            },
            SdoResult::Err(e) => {
                self.set_error(&format!("SDO {:?} failed: {}", self.state, e));
            }
            SdoResult::Timeout => {
                self.set_error(&format!("SDO {:?} timed out after {:?}", self.state, SDO_TIMEOUT));
            }
        }
    }

    fn set_error(&mut self, message: &str) {
        log::error!("El3356: {}", message);
        self.error = true;
        self.error_message = message.to_string();
        self.pending_tid = None;
        self.state = State::Idle;
        self.busy = false;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use mechutil::ipc::CommandMessage;
    use tokio::sync::mpsc;

    /// Local storage for PDO fields used in tests. Avoids depending on
    /// auto-generated GlobalMemory field names.
    #[derive(Default)]
    struct TestPdo {
        tare: bool,
        load: f32,
        load_steady: bool,
        load_error: bool,
        load_overrange: bool,
    }

    impl TestPdo {
        fn view(&mut self) -> El3356View<'_> {
            El3356View {
                tare:           &mut self.tare,
                load:           &self.load,
                load_steady:    &self.load_steady,
                load_error:     &self.load_error,
                load_overrange: &self.load_overrange,
            }
        }
    }

    fn test_client() -> (
        CommandClient,
        mpsc::UnboundedSender<CommandMessage>,
        mpsc::UnboundedReceiver<String>,
    ) {
        let (write_tx, write_rx) = mpsc::unbounded_channel();
        let (response_tx, response_rx) = mpsc::unbounded_channel();
        let client = CommandClient::new(write_tx, response_rx);
        (client, response_tx, write_rx)
    }

    /// Read the transaction_id from the most recently sent IPC message.
    fn last_sent_tid(rx: &mut mpsc::UnboundedReceiver<String>) -> u32 {
        let msg_json = rx.try_recv().expect("expected a message on the wire");
        let msg: CommandMessage = serde_json::from_str(&msg_json).unwrap();
        msg.transaction_id
    }

    fn assert_last_sent(
        rx: &mut mpsc::UnboundedReceiver<String>,
        expected_topic: &str,
        expected_sub: u8,
    ) -> u32 {
        let msg_json = rx.try_recv().expect("expected a message on the wire");
        let msg: CommandMessage = serde_json::from_str(&msg_json).unwrap();
        assert_eq!(msg.topic, expected_topic);
        assert_eq!(msg.data["index"], format!("0x{:04X}", SDO_IDX));
        assert_eq!(msg.data["sub"], expected_sub);
        msg.transaction_id
    }

    // ── peak tracking ──

    #[test]
    fn peak_follows_largest_magnitude() {
        let (mut client, _resp_tx, _write_rx) = test_client();
        let mut fb = El3356::new("EL3356_0");
        let mut pdo = TestPdo::default();

        // Positive then larger negative: peak should track absolute magnitude,
        // but store the signed value at the peak (matches TwinCAT code exactly).
        pdo.load = 10.0;
        fb.tick(&mut pdo.view(), &mut client);
        assert_eq!(fb.peak_load, 10.0);

        pdo.load = -25.0;
        fb.tick(&mut pdo.view(), &mut client);
        assert_eq!(fb.peak_load, -25.0);

        pdo.load = 20.0; // smaller than |-25|, shouldn't overwrite
        fb.tick(&mut pdo.view(), &mut client);
        assert_eq!(fb.peak_load, -25.0);
    }

    #[test]
    fn reset_peak_zeroes_it() {
        let (mut client, _resp_tx, _write_rx) = test_client();
        let mut fb = El3356::new("EL3356_0");
        let mut pdo = TestPdo { load: 42.0, ..Default::default() };
        fb.tick(&mut pdo.view(), &mut client);
        assert_eq!(fb.peak_load, 42.0);
        fb.reset_peak();
        assert_eq!(fb.peak_load, 0.0);
    }

    // ── tare pulse ──

    #[test]
    fn tare_resets_peak_and_pulses_bit() {
        let (mut client, _resp_tx, _write_rx) = test_client();
        let mut fb = El3356::new("EL3356_0");
        let mut pdo = TestPdo { load: 50.0, ..Default::default() };

        fb.tick(&mut pdo.view(), &mut client);
        assert_eq!(fb.peak_load, 50.0);

        fb.tare();
        // Tare itself sets peak=0 immediately
        assert_eq!(fb.peak_load, 0.0);

        // tick() writes the tare bit high while within the pulse window
        fb.tick(&mut pdo.view(), &mut client);
        assert!(pdo.tare, "tare bit should be high within pulse window");

        // Wait past the 100 ms window (small margin)
        std::thread::sleep(TARE_PULSE + Duration::from_millis(20));
        fb.tick(&mut pdo.view(), &mut client);
        assert!(!pdo.tare, "tare bit should be cleared after pulse window");
    }

    // ── configure state machine ──

    #[test]
    fn configure_sequences_three_sdo_writes() {
        let (mut client, resp_tx, mut write_rx) = test_client();
        let mut fb = El3356::new("EL3356_0");
        let mut pdo = TestPdo::default();

        fb.configure(&mut client, 1000.0, 2.0, 100000.0);
        assert!(fb.busy);
        assert_eq!(fb.state, State::WritingMvV);

        // 1st write: mV/V
        let tid1 = assert_last_sent(&mut write_rx, "ethercat.write_sdo", SUB_MV_V);
        resp_tx.send(CommandMessage::response(tid1, json!(null))).unwrap();
        client.poll();
        fb.tick(&mut pdo.view(), &mut client);
        assert_eq!(fb.configured_mv_v, Some(2.0));
        assert_eq!(fb.state, State::WritingFullScale);
        assert!(fb.busy);

        // 2nd write: full-scale
        let tid2 = assert_last_sent(&mut write_rx, "ethercat.write_sdo", SUB_FULL_SCALE);
        resp_tx.send(CommandMessage::response(tid2, json!(null))).unwrap();
        client.poll();
        fb.tick(&mut pdo.view(), &mut client);
        assert_eq!(fb.configured_full_scale_load, Some(1000.0));
        assert_eq!(fb.state, State::WritingScaleFactor);
        assert!(fb.busy);

        // 3rd write: scale factor
        let tid3 = assert_last_sent(&mut write_rx, "ethercat.write_sdo", SUB_SCALE_FACTOR);
        resp_tx.send(CommandMessage::response(tid3, json!(null))).unwrap();
        client.poll();
        fb.tick(&mut pdo.view(), &mut client);
        assert_eq!(fb.configured_scale_factor, Some(100000.0));
        assert_eq!(fb.state, State::Idle);
        assert!(!fb.busy);
        assert!(!fb.error);
    }

    #[test]
    fn configure_while_busy_is_noop() {
        let (mut client, _resp_tx, mut write_rx) = test_client();
        let mut fb = El3356::new("EL3356_0");

        fb.configure(&mut client, 1000.0, 2.0, 100000.0);
        let _tid1 = last_sent_tid(&mut write_rx);
        assert!(fb.busy);

        // Second call while busy: nothing on the wire, state unchanged.
        fb.configure(&mut client, 9999.0, 9.0, 99.0);
        assert!(write_rx.try_recv().is_err(), "no new message should have been sent");
        assert_eq!(fb.pending_mv_v, 2.0);
    }

    #[test]
    fn sdo_error_sets_error_and_clears_busy() {
        let (mut client, resp_tx, mut write_rx) = test_client();
        let mut fb = El3356::new("EL3356_0");
        let mut pdo = TestPdo::default();

        fb.configure(&mut client, 1000.0, 2.0, 100000.0);
        let tid1 = last_sent_tid(&mut write_rx);

        // Simulate error response
        let mut err_msg = CommandMessage::response(tid1, json!(null));
        err_msg.success = false;
        err_msg.error_message = "device offline".to_string();
        resp_tx.send(err_msg).unwrap();
        client.poll();

        fb.tick(&mut pdo.view(), &mut client);
        assert!(fb.error);
        assert!(fb.error_message.contains("device offline"));
        assert!(!fb.busy);
        assert_eq!(fb.state, State::Idle);
    }

    #[test]
    fn clear_error_resets_flag() {
        let mut fb = El3356::new("EL3356_0");
        fb.error = true;
        fb.error_message = "boom".to_string();
        fb.clear_error();
        assert!(!fb.error);
        assert!(fb.error_message.is_empty());
    }

    // ── read_configuration ──

    /// Helper: build the response payload that `ethercat.read_sdo` sends for
    /// a REAL32 read — the `value` field is the u32 bit-pattern of the f32.
    fn sdo_read_response_f32(v: f32) -> serde_json::Value {
        json!({
            "device": "EL3356_0",
            "index": "0x8000",
            "sub": 0,
            "size": 4,
            "value_hex": format!("0x{:08X}", v.to_bits()),
            "value": v.to_bits() as u64,
        })
    }

    fn assert_last_sent_read(
        rx: &mut mpsc::UnboundedReceiver<String>,
        expected_sub: u8,
    ) -> u32 {
        let msg_json = rx.try_recv().expect("expected a message on the wire");
        let msg: CommandMessage = serde_json::from_str(&msg_json).unwrap();
        assert_eq!(msg.topic, "ethercat.read_sdo");
        assert_eq!(msg.data["index"], format!("0x{:04X}", SDO_IDX));
        assert_eq!(msg.data["sub"], expected_sub);
        assert!(msg.data.get("value").is_none(), "reads must not include a value field");
        msg.transaction_id
    }

    #[test]
    fn read_configuration_fetches_three_sdos() {
        let (mut client, resp_tx, mut write_rx) = test_client();
        let mut fb = El3356::new("EL3356_0");
        let mut pdo = TestPdo::default();

        fb.read_configuration(&mut client);
        assert!(fb.busy);
        assert_eq!(fb.state, State::ReadingMvV);
        // Starts cleared so transient reads aren't mistaken for final values.
        assert_eq!(fb.configured_mv_v, None);
        assert_eq!(fb.configured_full_scale_load, None);
        assert_eq!(fb.configured_scale_factor, None);

        // 1st read: mV/V — device reports 2.5
        let tid1 = assert_last_sent_read(&mut write_rx, SUB_MV_V);
        resp_tx.send(CommandMessage::response(tid1, sdo_read_response_f32(2.5))).unwrap();
        client.poll();
        fb.tick(&mut pdo.view(), &mut client);
        assert_eq!(fb.configured_mv_v, Some(2.5));
        assert_eq!(fb.state, State::ReadingFullScale);
        assert!(fb.busy);

        // 2nd read: full-scale — device reports 500.0
        let tid2 = assert_last_sent_read(&mut write_rx, SUB_FULL_SCALE);
        resp_tx.send(CommandMessage::response(tid2, sdo_read_response_f32(500.0))).unwrap();
        client.poll();
        fb.tick(&mut pdo.view(), &mut client);
        assert_eq!(fb.configured_full_scale_load, Some(500.0));
        assert_eq!(fb.state, State::ReadingScaleFactor);

        // 3rd read: scale factor — device reports 100000.0
        let tid3 = assert_last_sent_read(&mut write_rx, SUB_SCALE_FACTOR);
        resp_tx.send(CommandMessage::response(tid3, sdo_read_response_f32(100_000.0))).unwrap();
        client.poll();
        fb.tick(&mut pdo.view(), &mut client);
        assert_eq!(fb.configured_scale_factor, Some(100_000.0));
        assert_eq!(fb.state, State::Idle);
        assert!(!fb.busy);
        assert!(!fb.error);
    }

    #[test]
    fn read_configuration_while_busy_is_noop() {
        let (mut client, _resp_tx, mut write_rx) = test_client();
        let mut fb = El3356::new("EL3356_0");

        fb.configure(&mut client, 1000.0, 2.0, 100_000.0);
        let _tid = last_sent_tid(&mut write_rx);
        assert!(fb.busy);

        fb.read_configuration(&mut client);
        assert!(write_rx.try_recv().is_err(), "no new message should have been sent");
        // State should still be the configure-write state, not a read state.
        assert_eq!(fb.state, State::WritingMvV);
    }

    #[test]
    fn read_configuration_error_clears_busy_and_leaves_partial_none() {
        let (mut client, resp_tx, mut write_rx) = test_client();
        let mut fb = El3356::new("EL3356_0");
        let mut pdo = TestPdo::default();

        // Pre-seed with stale values so we can confirm they're cleared on read start.
        fb.configured_mv_v = Some(9.9);
        fb.configured_full_scale_load = Some(9999.0);
        fb.configured_scale_factor = Some(99.0);

        fb.read_configuration(&mut client);
        assert_eq!(fb.configured_mv_v, None);
        assert_eq!(fb.configured_full_scale_load, None);
        assert_eq!(fb.configured_scale_factor, None);

        let tid1 = last_sent_tid(&mut write_rx);
        let mut err_msg = CommandMessage::response(tid1, json!(null));
        err_msg.success = false;
        err_msg.error_message = "SDO abort: 0x06020000".to_string();
        resp_tx.send(err_msg).unwrap();
        client.poll();

        fb.tick(&mut pdo.view(), &mut client);
        assert!(fb.error);
        assert!(fb.error_message.contains("SDO abort"));
        assert!(!fb.busy);
        assert_eq!(fb.state, State::Idle);
        // All three stay None after a failed read — user should not trust partial data.
        assert_eq!(fb.configured_mv_v, None);
        assert_eq!(fb.configured_full_scale_load, None);
        assert_eq!(fb.configured_scale_factor, None);
    }

    #[test]
    fn parse_sdo_real32_from_u32_bits() {
        // 2.5 as IEEE-754: 0x40200000
        let v = json!({"value": 0x40200000u64});
        assert_eq!(parse_sdo_real32(&v), Some(2.5));
    }

    #[test]
    fn parse_sdo_real32_from_f64_fallback() {
        let v = json!({"value": 3.25});
        assert_eq!(parse_sdo_real32(&v), Some(3.25));
    }

    #[test]
    fn parse_sdo_real32_missing_field() {
        let v = json!({"size": 4});
        assert_eq!(parse_sdo_real32(&v), None);
    }

    // ── generic sdo_write / sdo_read ──

    #[test]
    fn sdo_write_does_not_wipe_calibration_fields() {
        let (mut client, _resp_tx, mut write_rx) = test_client();
        let mut fb = El3356::new("EL3356_0");

        // Seed calibration state as if configure() had already completed.
        fb.configured_mv_v = Some(2.0);
        fb.configured_full_scale_load = Some(1000.0);
        fb.configured_scale_factor = Some(100_000.0);

        // An unrelated SDO write (e.g. a filter setter) must not touch them.
        fb.sdo_write(&mut client, 0x8000, 0x11, json!(0u16));
        let _tid = last_sent_tid(&mut write_rx);

        assert_eq!(fb.configured_mv_v, Some(2.0));
        assert_eq!(fb.configured_full_scale_load, Some(1000.0));
        assert_eq!(fb.configured_scale_factor, Some(100_000.0));
        assert!(fb.busy);
        assert_eq!(fb.state, State::WaitWriteGeneralSdo);
    }

    #[test]
    fn sdo_read_does_not_wipe_calibration_fields() {
        let (mut client, _resp_tx, mut write_rx) = test_client();
        let mut fb = El3356::new("EL3356_0");

        fb.configured_mv_v = Some(2.0);
        fb.configured_full_scale_load = Some(1000.0);
        fb.configured_scale_factor = Some(100_000.0);

        fb.sdo_read(&mut client, 0x8000, 0x11);
        let _tid = last_sent_tid(&mut write_rx);

        assert_eq!(fb.configured_mv_v, Some(2.0));
        assert_eq!(fb.configured_full_scale_load, Some(1000.0));
        assert_eq!(fb.configured_scale_factor, Some(100_000.0));
    }

    #[test]
    fn sdo_read_populates_result_accessors() {
        let (mut client, resp_tx, mut write_rx) = test_client();
        let mut fb = El3356::new("EL3356_0");
        let mut pdo = TestPdo::default();

        fb.sdo_read(&mut client, 0x8000, 0x11);
        let tid = last_sent_tid(&mut write_rx);

        // Respond with a u16 filter value (integer path) — represents a read
        // of the Mode 0 filter select register.
        let payload = json!({
            "device": "EL3356_0", "index": "0x8000", "sub": 0x11,
            "size": 2, "value_hex": "0x0001", "value": 1u64,
        });
        resp_tx.send(CommandMessage::response(tid, payload)).unwrap();
        client.poll();
        fb.tick(&mut pdo.view(), &mut client);

        assert!(!fb.busy);
        assert_eq!(fb.result_as_i64(), Some(1));
        assert_eq!(fb.result_as_f64(), Some(1.0));
        // result() returns the full object
        assert_eq!(fb.result()["sub"], 0x11);
    }

    #[test]
    fn result_as_f32_reinterprets_real32_bits() {
        let (mut client, resp_tx, mut write_rx) = test_client();
        let mut fb = El3356::new("EL3356_0");
        let mut pdo = TestPdo::default();

        fb.sdo_read(&mut client, 0x8000, 0x23);
        let tid = last_sent_tid(&mut write_rx);

        // Simulate a REAL32 read returning the bit pattern of 2.5
        let payload = json!({
            "device": "EL3356_0", "index": "0x8000", "sub": 0x23,
            "size": 4, "value_hex": format!("0x{:08X}", 2.5f32.to_bits()),
            "value": 2.5f32.to_bits() as u64,
        });
        resp_tx.send(CommandMessage::response(tid, payload)).unwrap();
        client.poll();
        fb.tick(&mut pdo.view(), &mut client);

        assert_eq!(fb.result_as_f32(), Some(2.5));
        // result_as_i64 returns the raw u32 bit pattern — not useful for REAL32
        // but also not wrong; this asserts the accessor at least returns something.
        assert_eq!(fb.result_as_i64(), Some(2.5f32.to_bits() as i64));
    }

    #[test]
    fn result_accessors_none_before_any_read() {
        let fb = El3356::new("EL3356_0");
        assert_eq!(fb.result_as_f64(), None);
        assert_eq!(fb.result_as_i64(), None);
        assert_eq!(fb.result_as_f32(), None);
        assert_eq!(fb.result(), serde_json::Value::Null);
    }

    #[test]
    fn reset_clears_latent_state() {
        let (mut client, _resp_tx, mut write_rx) = test_client();
        let mut fb = El3356::new("EL3356_0");
        let mut pdo = TestPdo::default();

        // Accumulate state: tare pulse, pending SDO, stale read buffer.
        fb.tare();
        assert!(fb.tare_release_at.is_some());

        fb.sdo_read(&mut client, 0x8000, 0x11);
        let _ = last_sent_tid(&mut write_rx);
        fb.sdo_res_value = json!({"value": 99});

        fb.reset();

        // reset() drops op state, pulse timer, and prior read buffer...
        assert!(!fb.busy);
        assert!(!fb.error);
        assert_eq!(fb.state, State::Idle);
        assert!(fb.tare_release_at.is_none());
        assert_eq!(fb.sdo_res_value, serde_json::Value::Null);

        // ...but does not touch peak_load or the configured_* fields.
        // (The peak was zeroed by tare() above; seed a new value post-reset.)
        pdo.load = 42.0;
        fb.tick(&mut pdo.view(), &mut client);
        assert_eq!(fb.peak_load, 42.0);
    }

    #[test]
    fn is_error_and_is_busy_accessors() {
        let mut fb = El3356::new("EL3356_0");
        assert!(!fb.is_error());
        assert!(!fb.is_busy());
        fb.error = true;
        fb.busy = true;
        assert!(fb.is_error());
        assert!(fb.is_busy());
    }
}