ad-plugins-rs 0.25.0

NDPlugin implementations for areaDetector-rs
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
//! IOC plugin registration and areaDetector IOC application framework.
//!
//! Provides:
//! - [`register_all_plugins`]: registers startup commands like
//!   `NDStatsConfigure`, `NDROIConfigure`, etc. on an `IocApplication`.
//! - [`AdIoc`]: pre-configured IOC application that handles all common
//!   areaDetector boilerplate (plugins, device support, asynRecord, etc.).

use std::sync::{Arc, Mutex};

use ad_core_rs::ioc::{
    PluginManager, attr_arg_defs, dtyp_from_port, extract_plugin_args, plugin_arg_defs,
    register_noop_commands,
};
use ad_core_rs::plugin::runtime::{create_plugin_runtime, create_plugin_runtime_multi_addr};
use ad_core_rs::plugin::wiring::WiringRegistry;
use asyn_rs::manager::PortManager;
use asyn_rs::trace::TraceManager;
use epics_base_rs::error::CaResult;
use epics_base_rs::server::autosave::AutosaveStartupConfig;
use epics_base_rs::server::iocsh::registry::*;
use epics_ca_rs::server::ioc_app::IocApplication;

/// Register all standard areaDetector plugin configure commands.
///
/// The `PluginManager` must have its driver context set (via `set_driver()`)
/// before any of these commands are invoked from st.cmd.
pub fn register_all_plugins(mut app: IocApplication, mgr: &Arc<PluginManager>) -> IocApplication {
    let ts_registry = Arc::new(crate::time_series::TsReceiverRegistry::new());

    // --- NDStdArraysConfigure ---
    {
        let m = mgr.clone();
        app = app.register_startup_command(CommandDef::new(
            "NDStdArraysConfigure",
            plugin_arg_defs(),
            "NDStdArraysConfigure portName [queueSize] ...",
            move |args: &[ArgValue], _ctx: &CommandContext| {
                let (port_name, _queue_size, ndarray_port) = extract_plugin_args(args)?;
                let dtyp = dtyp_from_port(&port_name);
                let drv = m.driver()?;
                let pool = drv.pool();
                let (handle, _data, _jh) = crate::std_arrays::create_std_arrays_runtime(
                    &port_name,
                    pool,
                    &ndarray_port,
                    m.wiring().clone(),
                );
                if let Err(e) = m.add_plugin(&dtyp, &handle) {
                    eprintln!("NDStdArraysConfigure: {e}");
                    return Ok(CommandOutcome::Continue);
                }
                if let Err(e) = m.wiring().rewire(handle.array_sender(), "", &ndarray_port) {
                    eprintln!("NDStdArraysConfigure: wiring failed: {e}");
                }
                println!("NDStdArraysConfigure: port={port_name}");
                Ok(CommandOutcome::Continue)
            },
        ));
    }

    // --- NDStatsConfigure ---
    {
        let m = mgr.clone();
        let tsr = ts_registry.clone();
        app = app.register_startup_command(CommandDef::new(
            "NDStatsConfigure",
            plugin_arg_defs(),
            "NDStatsConfigure portName [queueSize] ...",
            move |args: &[ArgValue], _ctx: &CommandContext| {
                let (port_name, queue_size, ndarray_port) = extract_plugin_args(args)?;
                let dtyp = dtyp_from_port(&port_name);
                let drv = m.driver()?;
                let pool = drv.pool();
                let (handle, _stats, _stats_params, _jh) = crate::stats::create_stats_runtime(
                    &port_name,
                    pool,
                    queue_size,
                    &ndarray_port,
                    m.wiring().clone(),
                    &tsr,
                );

                if let Err(e) = m.add_plugin(&dtyp, &handle) {
                    eprintln!("NDStatsConfigure: {e}");
                    return Ok(CommandOutcome::Continue);
                }
                if let Err(e) = m.wiring().rewire(handle.array_sender(), "", &ndarray_port) {
                    eprintln!("NDStatsConfigure: wiring failed: {e}");
                }
                println!("NDStatsConfigure: port={port_name}");

                Ok(CommandOutcome::Continue)
            },
        ));
    }

    // --- Generic plugins using create_plugin_runtime ---
    {
        let m = mgr.clone();
        app = app.register_startup_command(CommandDef::new(
            "NDROIConfigure",
            plugin_arg_defs(),
            "NDROIConfigure portName [queueSize] ...",
            move |args: &[ArgValue], _ctx: &CommandContext| {
                let (port_name, queue_size, ndarray_port) = extract_plugin_args(args)?;
                let dtyp = dtyp_from_port(&port_name);
                let drv = m.driver()?;
                let pool = drv.pool();
                let (handle, _roi_params, _jh) = crate::roi::create_roi_runtime(
                    &port_name,
                    pool,
                    queue_size,
                    &ndarray_port,
                    m.wiring().clone(),
                );
                if let Err(e) = m.add_plugin(&dtyp, &handle) {
                    eprintln!("NDROIConfigure: {e}");
                    return Ok(CommandOutcome::Continue);
                }
                if let Err(e) = m.wiring().rewire(handle.array_sender(), "", &ndarray_port) {
                    eprintln!("NDROIConfigure: wiring failed: {e}");
                }
                println!("NDROIConfigure: port={port_name}");
                Ok(CommandOutcome::Continue)
            },
        ));
    }
    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDProcessConfigure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::process::{ProcessConfig, ProcessProcessor};
            create_plugin_runtime(
                port_name,
                ProcessProcessor::new(ProcessConfig::default()),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );
    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDTransformConfigure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::transform::{TransformProcessor, TransformType};
            create_plugin_runtime(
                port_name,
                TransformProcessor::new(TransformType::None),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );
    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDColorConvertConfigure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::color_convert::{ColorConvertConfig, ColorConvertProcessor};
            use ad_core_rs::color::{NDBayerPattern, NDColorMode};
            let config = ColorConvertConfig {
                target_mode: NDColorMode::Mono,
                bayer_pattern: NDBayerPattern::RGGB,
                false_color: 0,
            };
            create_plugin_runtime(
                port_name,
                ColorConvertProcessor::new(config),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );
    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDOverlayConfigure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::overlay::OverlayProcessor;
            create_plugin_runtime(
                port_name,
                OverlayProcessor::new(vec![]),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );
    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDFFTConfigure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::fft::FFTProcessor;
            create_plugin_runtime(
                port_name,
                FFTProcessor::new(),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );
    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDCircularBuffConfigure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::circular_buff::{CircularBuffProcessor, TriggerCondition};
            create_plugin_runtime(
                port_name,
                // queue_size is C `maxBuffers_` (NDCircularBuffConfigure
                // queueSize); the processor bounds the accepted pre-count by it.
                CircularBuffProcessor::new(100, 100, TriggerCondition::External, queue_size),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );
    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDCodecConfigure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::codec::{CodecMode, CodecProcessor};
            use ad_core_rs::codec::CodecName;
            create_plugin_runtime(
                port_name,
                CodecProcessor::new(CodecMode::Compress {
                    codec: CodecName::LZ4,
                    quality: 90,
                }),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );
    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDScatterConfigure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::scatter::ScatterProcessor;
            create_plugin_runtime(
                port_name,
                ScatterProcessor::new(),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );
    // NDGatherConfigure: portName [queueSize] [blockingCallbacks] port1 [port2 ... portN]
    // Connects multiple upstream ports to a single Gather plugin.
    {
        let m = mgr.clone();
        let taken = std::mem::replace(&mut app, IocApplication::new());
        app = taken.register_startup_command(CommandDef::new(
            "NDGatherConfigure",
            plugin_arg_defs(),
            "NDGatherConfigure portName [queueSize] [blockingCallbacks] NDArrayPort [port2 ...]"
                .to_string(),
            move |args: &[ArgValue], _ctx: &CommandContext| {
                let (port_name, queue_size, first_port) = extract_plugin_args(args)?;
                let dtyp = dtyp_from_port(&port_name);
                if asyn_rs::asyn_record::get_port(&port_name).is_some() {
                    println!("NDGatherConfigure: port={port_name} already configured, skipping");
                    return Ok(CommandOutcome::Continue);
                }
                let drv = m.driver()?;
                let pool = drv.pool();
                let wiring = m.wiring().clone();

                let (handle, _jh) = create_plugin_runtime(
                    &port_name,
                    crate::gather::GatherProcessor::new(),
                    pool,
                    queue_size,
                    &first_port,
                    wiring.clone(),
                );

                // Wire first upstream port
                if !first_port.is_empty() {
                    if let Err(e) = wiring.rewire(handle.array_sender(), "", &first_port) {
                        eprintln!("NDGatherConfigure: wiring to {first_port} failed: {e}");
                    }
                }

                // Wire additional upstream ports (args index 4+)
                for i in 4..args.len() {
                    if let ArgValue::String(upstream) = &args[i] {
                        if !upstream.is_empty() {
                            if let Some(upstream_output) = wiring.lookup_output(upstream) {
                                upstream_output.lock().add(handle.array_sender().clone());
                            } else {
                                eprintln!(
                                    "NDGatherConfigure: upstream port '{upstream}' not found"
                                );
                            }
                        }
                    }
                }

                if let Err(e) = m.add_plugin(&dtyp, &handle) {
                    eprintln!("NDGatherConfigure: {e}");
                    return Ok(CommandOutcome::Continue);
                }
                println!("NDGatherConfigure: port={port_name}");
                Ok(CommandOutcome::Continue)
            },
        ));
    }
    // NDAttrPlotConfig: portName nAttributes cacheSize nDataBlocks NDArrayPort
    //                   [NDArrayAddr] [queueSize] [blockingCallbacks] [priority] [stackSize]
    // C arg order (NDPluginAttrPlot.cpp:308): port, n_attributes, cache_size,
    // n_selected_blocks, in_port, in_addr, queue_size, ... — distinct from the
    // generic portName/queueSize/blockingCallbacks/NDArrayPort layout, so this
    // command parses its own positional args. The plugin tracks up to
    // n_attributes numeric attributes and exposes n_data_blocks waveform blocks,
    // so the asyn port needs max(n_attributes, n_data_blocks) addresses (C uses
    // the same max, NDPluginAttrPlot.cpp:48).
    {
        let m = mgr.clone();
        let int = |name| ArgDesc {
            name,
            arg_type: ArgType::Int,
            optional: true,
        };
        let arg_defs = vec![
            ArgDesc {
                name: "portName",
                arg_type: ArgType::String,
                optional: false,
            },
            int("nAttributes"),
            int("cacheSize"),
            int("nDataBlocks"),
            ArgDesc {
                name: "NDArrayPort",
                arg_type: ArgType::String,
                optional: true,
            },
            int("NDArrayAddr"),
            int("queueSize"),
            int("blockingCallbacks"),
            int("priority"),
            int("stackSize"),
        ];
        let taken = std::mem::replace(&mut app, IocApplication::new());
        app = taken.register_startup_command(CommandDef::new(
            "NDAttrPlotConfig",
            arg_defs,
            "NDAttrPlotConfig portName nAttributes cacheSize nDataBlocks NDArrayPort \
             [NDArrayAddr] [queueSize] [blockingCallbacks] [priority] [stackSize]"
                .to_string(),
            move |args: &[ArgValue], _ctx: &CommandContext| {
                let AttrPlotArgs {
                    port_name,
                    n_attributes,
                    cache_size,
                    n_data_blocks,
                    in_port,
                    queue_size,
                } = parse_attr_plot_args(args)?;

                let dtyp = dtyp_from_port(&port_name);
                if asyn_rs::asyn_record::get_port(&port_name).is_some() {
                    println!("NDAttrPlotConfig: port={port_name} already configured, skipping");
                    return Ok(CommandOutcome::Continue);
                }
                let drv = m.driver()?;
                let pool = drv.pool();
                // Addr 0 always exists, so at least one address even for a
                // degenerate 0/0 request.
                let max_addr = n_attributes.max(n_data_blocks).max(1);
                let (handle, _jh) = create_plugin_runtime_multi_addr(
                    &port_name,
                    crate::attr_plot::AttrPlotProcessor::new(
                        n_attributes,
                        cache_size,
                        n_data_blocks,
                    ),
                    pool,
                    queue_size,
                    &in_port,
                    m.wiring().clone(),
                    max_addr,
                );
                if let Err(e) = m.add_plugin(&dtyp, &handle) {
                    eprintln!("NDAttrPlotConfig: {e}");
                    return Ok(CommandOutcome::Continue);
                }
                if let Err(e) = m.wiring().rewire(handle.array_sender(), "", &in_port) {
                    eprintln!("NDAttrPlotConfig: wiring failed: {e}");
                }
                println!("NDAttrPlotConfig: port={port_name}");
                Ok(CommandOutcome::Continue)
            },
        ));
    }
    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDFileTIFFConfigure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::file_tiff::TiffFileProcessor;
            create_plugin_runtime(
                port_name,
                TiffFileProcessor::new(),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );
    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDFileJPEGConfigure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::file_jpeg::JpegFileProcessor;
            create_plugin_runtime(
                port_name,
                JpegFileProcessor::new(50),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );
    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDFileHDF5Configure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::file_hdf5::Hdf5FileProcessor;
            create_plugin_runtime(
                port_name,
                Hdf5FileProcessor::new(),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );
    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDFileNetCDFConfigure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::file_netcdf::NetcdfFileProcessor;
            create_plugin_runtime(
                port_name,
                NetcdfFileProcessor::new(),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );
    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDFileMagickConfigure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::file_magick::MagickFileProcessor;
            create_plugin_runtime(
                port_name,
                MagickFileProcessor::new(),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );

    // --- NDAttrConfigure ---
    {
        let m = mgr.clone();
        let tsr = ts_registry.clone();
        app = app.register_startup_command(CommandDef::new(
            "NDAttrConfigure",
            attr_arg_defs(),
            "NDAttrConfigure portName [queueSize] ...",
            move |args: &[ArgValue], _ctx: &CommandContext| {
                let (port_name, queue_size, ndarray_port) = extract_plugin_args(args)?;
                // C arg index 5 is maxAttributes (NDPluginAttribute.cpp:245); a
                // missing iocsh int arg defaults to 0, which C floors to 1.
                let max_attributes = match args.get(5) {
                    Some(ArgValue::Int(n)) => *n as i32,
                    _ => 0,
                };
                let dtyp = dtyp_from_port(&port_name);
                let drv = m.driver()?;
                let pool = drv.pool();

                let (handle, _jh) = crate::attribute::create_attribute_runtime(
                    &port_name,
                    pool,
                    queue_size,
                    &ndarray_port,
                    m.wiring().clone(),
                    &tsr,
                    max_attributes,
                );
                if let Err(e) = m.add_plugin(&dtyp, &handle) {
                    eprintln!("NDAttrConfigure: {e}");
                    return Ok(CommandOutcome::Continue);
                }
                if let Err(e) = m.wiring().rewire(handle.array_sender(), "", &ndarray_port) {
                    eprintln!("NDAttrConfigure: wiring failed: {e}");
                }
                println!("NDAttrConfigure: port={port_name}");

                Ok(CommandOutcome::Continue)
            },
        ));
    }

    // --- NDROIStatConfigure ---
    {
        let m = mgr.clone();
        let tsr = ts_registry.clone();
        app = app.register_startup_command(CommandDef::new(
            "NDROIStatConfigure",
            plugin_arg_defs(),
            "NDROIStatConfigure portName [queueSize] ...",
            move |args: &[ArgValue], _ctx: &CommandContext| {
                let (port_name, queue_size, ndarray_port) = extract_plugin_args(args)?;
                let dtyp = dtyp_from_port(&port_name);
                let drv = m.driver()?;
                let pool = drv.pool();
                let (handle, _roi_stat_params, _jh) = crate::roi_stat::create_roi_stat_runtime(
                    &port_name,
                    pool,
                    queue_size,
                    &ndarray_port,
                    m.wiring().clone(),
                    32,
                    &tsr,
                );
                if let Err(e) = m.add_plugin(&dtyp, &handle) {
                    eprintln!("NDROIStatConfigure: {e}");
                    return Ok(CommandOutcome::Continue);
                }
                if let Err(e) = m.wiring().rewire(handle.array_sender(), "", &ndarray_port) {
                    eprintln!("NDROIStatConfigure: wiring failed: {e}");
                }
                println!("NDROIStatConfigure: port={port_name}");
                Ok(CommandOutcome::Continue)
            },
        ));
    }

    // --- Stub plugins (not yet fully implemented, use PassthroughProcessor) ---
    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDBadPixelConfigure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::bad_pixel::BadPixelProcessor;
            create_plugin_runtime(
                port_name,
                BadPixelProcessor::new(vec![]),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );

    app = register_generic_plugin(
        &mut app,
        mgr,
        "NDFileNexusConfigure",
        |port_name, queue_size, ndarray_port, pool, wiring| {
            use crate::file_nexus::NexusFileProcessor;
            create_plugin_runtime(
                port_name,
                NexusFileProcessor::new(),
                pool,
                queue_size,
                ndarray_port,
                wiring,
            )
        },
    );

    // --- NDTimeSeriesConfigure ---
    // Picks up a pending TS receiver from the registry (stored by Stats/ROIStat/Attr)
    // and creates the TS port.
    {
        let m = mgr.clone();
        let tsr = ts_registry.clone();
        app = app.register_startup_command(CommandDef::new(
            "NDTimeSeriesConfigure",
            plugin_arg_defs(),
            "NDTimeSeriesConfigure portName [queueSize] [blockingCallbacks] NDArrayPort",
            move |args: &[ArgValue], _ctx: &CommandContext| {
                let (port_name, queue_size, ndarray_port) = extract_plugin_args(args)?;
                let dtyp = dtyp_from_port(&port_name);
                if asyn_rs::asyn_record::get_port(&port_name).is_some() {
                    println!(
                        "NDTimeSeriesConfigure: port={port_name} already configured, skipping"
                    );
                    return Ok(CommandOutcome::Continue);
                }

                // Look up the pending receiver from the upstream plugin
                let (ts_rx, channel_names) = match tsr.take(&ndarray_port) {
                    Some(entry) => entry,
                    None => {
                        // No upstream TS receiver registered: the upstream is a raw
                        // NDArray source, so stand up the standalone
                        // NDPluginTimeSeries which ingests the arrays directly
                        // (C NDPluginTimeSeries.cpp). C's NDTimeSeriesConfigure
                        // takes maxSignals at arg index 5.
                        let max_signals = match args.get(5) {
                            Some(ArgValue::Int(n)) if *n >= 1 => *n as usize,
                            _ => 1,
                        };
                        let drv = m.driver()?;
                        let pool = drv.pool();
                        let (handle, _jh) = create_plugin_runtime_multi_addr(
                            &port_name,
                            crate::time_series_plugin::TimeSeriesProcessor::new(max_signals),
                            pool,
                            queue_size,
                            &ndarray_port,
                            m.wiring().clone(),
                            // C maxAddr = maxSignals + 1 (the 2-D array callback
                            // address is reserved at addr == maxSignals).
                            max_signals + 1,
                        );
                        if let Err(e) = m.add_plugin(&dtyp, &handle) {
                            eprintln!("NDTimeSeriesConfigure: {e}");
                            return Ok(CommandOutcome::Continue);
                        }
                        if let Err(e) = m.wiring().rewire(handle.array_sender(), "", &ndarray_port)
                        {
                            eprintln!("NDTimeSeriesConfigure: wiring failed: {e}");
                        }
                        println!(
                            "NDTimeSeriesConfigure: port={port_name} \
                             (standalone raw-array, maxSignals={max_signals}, \
                             upstream={ndarray_port})"
                        );
                        return Ok(CommandOutcome::Continue);
                    }
                };

                let channel_name_refs: Vec<&str> =
                    channel_names.iter().map(|s| s.as_str()).collect();
                let (ts_runtime, _ts_params, _ts_actor_jh, _ts_data_jh) =
                    crate::time_series::create_ts_port_runtime(
                        &port_name,
                        &channel_name_refs,
                        2048,
                        ts_rx,
                    );
                if let Err(e) = m.add_port(&dtyp, ts_runtime) {
                    eprintln!("NDTimeSeriesConfigure: {e}");
                    return Ok(CommandOutcome::Continue);
                }
                println!("NDTimeSeriesConfigure: port={port_name} (upstream={ndarray_port})");

                Ok(CommandOutcome::Continue)
            },
        ));
    }

    // --- NDPvaConfigure ---
    // C++ signature: NDPvaConfigure(portName, queueSize, blockingCallbacks,
    //   NDArrayPort, NDArrayAddr, pvName, maxBuffers, maxMemory, priority, stackSize)
    // args[5] = pvName is a STRING, unlike standard plugin_arg_defs which has Int there.
    {
        let m = mgr.clone();
        let pva_arg_defs = {
            let mut defs = plugin_arg_defs();
            // Replace args[5] (maxBuffers/Int) with pvName/String
            if defs.len() > 5 {
                defs[5] = ArgDesc {
                    name: "pvName",
                    arg_type: ArgType::String,
                    optional: true,
                };
            }
            defs
        };
        app = app.register_startup_command(CommandDef::new(
            "NDPvaConfigure",
            pva_arg_defs,
            "NDPvaConfigure portName queueSize blockingCallbacks NDArrayPort NDArrayAddr pvName"
                .to_string(),
            move |args: &[ArgValue], _ctx: &CommandContext| {
                let (port_name, queue_size, ndarray_port) = extract_plugin_args(args)?;
                let dtyp = dtyp_from_port(&port_name);
                if asyn_rs::asyn_record::get_port(&port_name).is_some() {
                    println!("NDPvaConfigure: port={port_name} already configured, skipping");
                    return Ok(CommandOutcome::Continue);
                }
                let drv = m.driver()?;
                let pool = drv.pool();

                // C++ NDPvaConfigure args[5] is pvName (6th argument).
                // If not provided, fall back to "{portName}:Image". Only the
                // `pva`-feature processor consumes it, so gate the binding to
                // avoid an unused-variable warning when `ioc` is built without `pva`.
                #[cfg(feature = "pva")]
                let pva_pv_name = match args.get(5) {
                    Some(ArgValue::String(s)) if !s.is_empty() => s.clone(),
                    _ => format!("{port_name}:Image"),
                };

                #[cfg(feature = "pva")]
                let processor = {
                    // The processor owns the validating `PvaPvHandle` (built
                    // with the canonical NTNDArray descriptor); registering a
                    // clone shares the same `latest`/`subscribers` state with
                    // the qsrv adapter. Producer posts and server reads flow
                    // through one validating owner — a frame that does not
                    // match the descriptor never becomes the served value.
                    let proc = crate::pva::PvaProcessor::new(pva_pv_name.clone());
                    epics_bridge_rs::qsrv::register_pva_pv_global(&pva_pv_name, proc.handle());
                    proc
                };
                #[cfg(not(feature = "pva"))]
                let processor = crate::passthrough::PassthroughProcessor::new("NDPvaConfigure");

                let (handle, _jh) = create_plugin_runtime(
                    &port_name,
                    processor,
                    pool,
                    queue_size,
                    &ndarray_port,
                    m.wiring().clone(),
                );
                if let Err(e) = m.add_plugin(&dtyp, &handle) {
                    eprintln!("NDPvaConfigure: {e}");
                    return Ok(CommandOutcome::Continue);
                }
                if let Err(e) = m.wiring().rewire(handle.array_sender(), "", &ndarray_port) {
                    eprintln!("NDPvaConfigure: wiring failed: {e}");
                }
                #[cfg(feature = "pva")]
                println!("NDPvaConfigure: port={port_name}, PV={pva_pv_name}");
                #[cfg(not(feature = "pva"))]
                println!("NDPvaConfigure: port={port_name} (stub — enable 'pva' feature)");
                Ok(CommandOutcome::Continue)
            },
        ));
    }

    app
}

/// Helper: register a generic plugin configure command that follows the standard pattern.
/// Parsed `NDAttrPlotConfig` arguments.
struct AttrPlotArgs {
    port_name: String,
    n_attributes: usize,
    cache_size: usize,
    n_data_blocks: usize,
    in_port: String,
    queue_size: usize,
}

/// Parse `NDAttrPlotConfig` positional args in C order
/// (`NDPluginAttrPlot.cpp:308`): `port, n_attributes, cache_size,
/// n_selected_blocks, in_port, in_addr, queue_size, ...`.
///
/// A present integer is honoured exactly — including an explicit `0`, which is
/// meaningful for `cache_size` (`0` = unlimited per-buffer cache). Fallbacks
/// apply only when an arg is absent; a real st.cmd always passes them, so the
/// fallbacks only affect malformed calls.
fn parse_attr_plot_args(args: &[ArgValue]) -> Result<AttrPlotArgs, String> {
    let port_name = match args.first() {
        Some(ArgValue::String(s)) if !s.is_empty() => s.clone(),
        _ => return Err("NDAttrPlotConfig: portName required".into()),
    };
    let usize_arg = |i: usize, default: usize| match args.get(i) {
        Some(ArgValue::Int(n)) => (*n).max(0) as usize,
        _ => default,
    };
    let in_port = match args.get(4) {
        Some(ArgValue::String(s)) => s.clone(),
        _ => String::new(),
    };
    Ok(AttrPlotArgs {
        port_name,
        n_attributes: usize_arg(1, 8),
        cache_size: usize_arg(2, 1000),
        n_data_blocks: usize_arg(3, 4),
        in_port,
        queue_size: usize_arg(6, 20),
    })
}

fn register_generic_plugin<F>(
    app: &mut IocApplication,
    mgr: &Arc<PluginManager>,
    cmd_name: &'static str,
    factory: F,
) -> IocApplication
where
    F: Fn(
            &str,
            usize,
            &str,
            Arc<ad_core_rs::ndarray_pool::NDArrayPool>,
            Arc<WiringRegistry>,
        ) -> (
            ad_core_rs::plugin::runtime::PluginRuntimeHandle,
            std::thread::JoinHandle<()>,
        ) + Send
        + Sync
        + 'static,
{
    let m = mgr.clone();
    // Take ownership of app temporarily via a dummy
    let taken = std::mem::replace(app, IocApplication::new());
    taken.register_startup_command(CommandDef::new(
        cmd_name,
        plugin_arg_defs(),
        format!("{cmd_name} portName [queueSize] ..."),
        move |args: &[ArgValue], _ctx: &CommandContext| {
            let (port_name, queue_size, ndarray_port) = extract_plugin_args(args)?;
            let dtyp = dtyp_from_port(&port_name);
            // Skip if port already exists (allows commonPlugins.cmd to be
            // loaded multiple times with different PREFIX for alias records).
            if asyn_rs::asyn_record::get_port(&port_name).is_some() {
                println!("{cmd_name}: port={port_name} already configured, skipping");
                return Ok(CommandOutcome::Continue);
            }
            let drv = m.driver()?;
            let pool = drv.pool();
            let (handle, _jh) = factory(
                &port_name,
                queue_size,
                &ndarray_port,
                pool,
                m.wiring().clone(),
            );
            if let Err(e) = m.add_plugin(&dtyp, &handle) {
                eprintln!("{cmd_name}: {e}");
                return Ok(CommandOutcome::Continue);
            }
            if let Err(e) = m.wiring().rewire(handle.array_sender(), "", &ndarray_port) {
                eprintln!("{cmd_name}: wiring failed: {e}");
            }
            println!("{cmd_name}: port={port_name}");
            Ok(CommandOutcome::Continue)
        },
    ))
}

// ============================================================================
// AdIoc — Pre-configured IOC application for areaDetector-based systems
// ============================================================================

/// A pre-configured IOC application for areaDetector-based systems.
///
/// Handles all common boilerplate:
/// - `IocApplication` creation with CA server port
/// - `TraceManager` and `PluginManager`
/// - `asynRecord` registration
/// - All NDPlugin configure commands (`NDStdArraysConfigure`, `NDStatsConfigure`, etc.)
/// - No-op commands from commonPlugins.cmd
/// - Universal asyn device support (handles all @asyn() linked records)
/// - Report shell command
///
/// Detector libraries register their configure commands via
/// `register_startup_command`, then call `run_from_args` to start the IOC.
///
/// # Example
///
/// ```rust,ignore
/// #[tokio::main]
/// async fn main() -> CaResult<()> {
///     epics_base_rs::runtime::env::set_default("MYDET", env!("CARGO_MANIFEST_DIR"));
///
///     let mut ioc = AdIoc::new();
///     my_detector::ioc_support::register(&mut ioc);
///     ioc.run_from_args().await
/// }
/// ```
pub struct AdIoc {
    app: Option<IocApplication>,
    mgr: Arc<PluginManager>,
    ports: Arc<PortManager>,
    trace: Arc<TraceManager>,
    /// Resources kept alive for the IOC's lifetime (e.g. driver runtimes).
    _resources: Vec<Box<dyn std::any::Any + Send>>,
}

impl AdIoc {
    /// Create a new AdIoc with default configuration.
    pub fn new() -> Self {
        let trace = Arc::new(TraceManager::new());
        let mgr = PluginManager::new(trace.clone());
        // The asyn iocsh commands resolve ports and mutate trace state through
        // this manager, so it shares the IOC's `TraceManager` — a manager with
        // a `TraceManager` of its own would make `asynSetTrace*` mutate state
        // that no driver or plugin ever reads.
        let ports = Arc::new(PortManager::with_trace_manager(trace.clone()));

        asyn_rs::asyn_record::register_asyn_record_type();

        // `IocApplication::new()` already resolves the server port through
        // C `envGetInetPortConfigParam` (`runtime::net::cas_server_port`);
        // re-reading EPICS_CA_SERVER_PORT here with a strict parse dropped
        // that parity (no 5000 floor, no sscanf leniency, no diagnostics).
        let mut app = IocApplication::new();

        // `$(ADCORE)` resolves `$(ADCORE)/ioc/commonPlugins.cmd` and the
        // `$(ADCORE)/db` templates. Take the path from ad-core-rs itself rather
        // than guessing a sibling of this crate: only the owning crate can name
        // its own directory under a version-suffixed registry checkout.
        epics_base_rs::runtime::env::set_default("ADCORE", ad_core_rs::AD_CORE_DIR);

        // Everything the IOC always needs is wired here, once. The protocol
        // runner is the only thing `run` and `run_with_pva` disagree about;
        // configuring the application separately per runner is how a command
        // set ends up present on one path and missing from the other.
        app = register_all_plugins(app, &mgr);
        app = register_noop_commands(app);
        app = app.autosave_startup(Arc::new(Mutex::new(AutosaveStartupConfig::new())));

        // Universal asyn device support — handles all standard asyn DTYPs
        // (asynInt32, asynFloat64, asynOctet, array types) via @asyn() links.
        app = asyn_rs::adapter::register_asyn_device_support(app);

        // The asyn iocsh command set: port creation (`drvAsynIPPortConfigure`
        // and friends), `asynOctetSetInputEos` / `asynOctetSetOutputEos`,
        // `asynSetOption`, `asynReport` and the trace mutators — on the startup
        // shell as well as the interactive one. A socket detector's st.cmd
        // creates its port and sets the EOS before `iocInit`.
        app = asyn_rs::iocsh::register_asyn_commands(app, ports.clone());

        Self {
            app: Some(app),
            mgr,
            ports,
            trace,
            _resources: Vec::new(),
        }
    }

    /// Access the shared `PluginManager`.
    pub fn mgr(&self) -> &Arc<PluginManager> {
        &self.mgr
    }

    /// Access the shared [`PortManager`] — the manager the asyn iocsh commands
    /// resolve against.
    ///
    /// A detector crate registers its driver port here (or through the
    /// `drvAsyn*PortConfigure` iocsh commands, which publish to the same
    /// registry) so that `asynReport`, `asynSetOption` and the EOS commands can
    /// act on it from st.cmd.
    pub fn ports(&self) -> &Arc<PortManager> {
        &self.ports
    }

    /// Access the shared `TraceManager`.
    pub fn trace(&self) -> &Arc<TraceManager> {
        &self.trace
    }

    /// The configured [`IocApplication`] this IOC will run.
    ///
    /// `AdIoc` wires the application at construction, so
    /// [`IocApplication::startup_commands`] here is exactly the surface the
    /// startup script will be executed against.
    pub fn app(&self) -> &IocApplication {
        self.app
            .as_ref()
            .expect("AdIoc application is taken only by run()")
    }

    /// Register a record type (equivalent to C EPICS dbd record type registration).
    pub fn register_record_type(
        &mut self,
        name: &str,
        factory: epics_base_rs::server::RecordFactory,
    ) {
        let app = self.app.take().unwrap();
        self.app = Some(app.register_record_type(name, move || factory()));
    }

    /// Register a startup command (e.g., detector configure command).
    pub fn register_startup_command(&mut self, cmd: CommandDef) {
        let app = self.app.take().unwrap();
        self.app = Some(app.register_startup_command(cmd));
    }

    /// Register a static device support factory for a fixed DTYP name.
    pub fn register_device_support<F>(&mut self, dtyp: &str, factory: F)
    where
        F: Fn() -> Box<dyn epics_base_rs::server::device_support::DeviceSupport>
            + Send
            + Sync
            + 'static,
    {
        let app = self.app.take().unwrap();
        self.app = Some(app.register_device_support(dtyp, factory));
    }

    /// Register a dynamic device support factory (dispatches by context).
    pub fn register_dynamic_device_support<F>(&mut self, factory: F)
    where
        F: Fn(
                &epics_ca_rs::server::ioc_app::DeviceSupportContext,
            ) -> Option<Box<dyn epics_base_rs::server::device_support::DeviceSupport>>
            + Send
            + Sync
            + 'static,
    {
        let app = self.app.take().unwrap();
        self.app = Some(app.register_dynamic_device_support(factory));
    }

    /// Keep a resource alive for the IOC's lifetime.
    ///
    /// Use this for driver runtimes that must not be dropped while the IOC is
    /// running. The resource is stored until `run()` returns.
    pub fn keep_alive<T: Send + 'static>(&mut self, resource: T) {
        self._resources.push(Box::new(resource));
    }

    /// Register a shell command.
    pub fn register_shell_command(&mut self, cmd: CommandDef) {
        let app = self.app.take().unwrap();
        self.app = Some(app.register_shell_command(cmd));
    }

    /// Register an inline EPICS record.
    pub fn record(&mut self, name: &str, record: impl epics_base_rs::server::record::Record) {
        let app = self.app.take().unwrap();
        self.app = Some(app.record(name, record));
    }

    /// Parse command-line args for the startup script path and run.
    pub async fn run_from_args(self) -> CaResult<()> {
        let args: Vec<String> = std::env::args().collect();
        let script = if args.len() > 1 && !args[1].starts_with('-') {
            args[1].clone()
        } else {
            let bin = args.first().map(|s| s.as_str()).unwrap_or("ioc");
            eprintln!("Usage: {bin} <st.cmd>");
            std::process::exit(1);
        };
        self.run(&script).await
    }

    /// Run the IOC with a given startup script path.
    pub async fn run(self, script: &str) -> CaResult<()> {
        let app = self.app.unwrap();

        app.startup_script(script)
            // CA links resolve with zero further setup: the `ca` link set
            // installs at the base `AfterCaLinkInit` hook, before
            // `setup_cp_links` warms Passive CP holders.
            .register_link_set_installer(epics_ca_rs::calink::calink_link_set_install)
            .run(epics_ca_rs::server::run_ca_ioc)
            .await
    }

    /// Run the IOC with both CA and PVA protocols (QSRV bridge).
    ///
    /// Same as [`Self::run`] but uses [`epics_bridge_rs::qsrv::run_ca_pva_qsrv_ioc`]
    /// as the protocol runner, serving records over CA (default port 5064) and
    /// pvAccess (default port 5075) simultaneously. PVA plugin PVs (NTNDArray)
    /// registered during st.cmd are wired into the PVA server automatically.
    #[cfg(feature = "pva")]
    pub async fn run_with_pva(self, script: &str) -> CaResult<()> {
        let app = self.app.unwrap();

        app.startup_script(script)
            // External links resolve with zero further setup: both link
            // sets install at the base `AfterCaLinkInit` hook — before
            // `setup_cp_links` warms Passive CP holders and before the
            // iocInit external-link wait, both `ca` and `pva`.
            .register_link_set_installer(epics_ca_rs::calink::calink_link_set_install)
            .register_link_set_installer(epics_bridge_rs::qsrv::pvalink_link_set_install)
            .run(epics_bridge_rs::qsrv::run_ca_pva_qsrv_ioc)
            .await
    }

    /// Run the IOC with PVA from command-line args.
    #[cfg(feature = "pva")]
    pub async fn run_from_args_with_pva(self) -> CaResult<()> {
        let args: Vec<String> = std::env::args().collect();
        let script = if args.len() > 1 && !args[1].starts_with('-') {
            args[1].clone()
        } else {
            let bin = args.first().map(|s| s.as_str()).unwrap_or("ioc");
            eprintln!("Usage: {bin} <st.cmd>");
            std::process::exit(1);
        };
        self.run_with_pva(&script).await
    }
}

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

    #[test]
    fn parse_attr_plot_args_maps_c_positional_order() {
        // C NDAttrPlotConfig(port, n_attributes, cache_size, n_selected_blocks,
        // in_port, in_addr, queue_size, ...) — NDPluginAttrPlot.cpp:308. The
        // distinct order (n_attributes/cache/blocks before in_port, queue at
        // index 6) is the parity-critical mapping this guards.
        let args = vec![
            ArgValue::String("AP1".to_string()),
            ArgValue::Int(10),                    // n_attributes
            ArgValue::Int(500),                   // cache_size
            ArgValue::Int(3),                     // n_selected_blocks
            ArgValue::String("DET1".to_string()), // in_port
            ArgValue::Int(0),                     // in_addr
            ArgValue::Int(50),                    // queue_size
            ArgValue::Int(0),                     // blocking_callbacks
        ];
        let p = parse_attr_plot_args(&args).unwrap();
        assert_eq!(p.port_name, "AP1");
        assert_eq!(p.n_attributes, 10);
        assert_eq!(p.cache_size, 500);
        assert_eq!(p.n_data_blocks, 3);
        assert_eq!(p.in_port, "DET1");
        assert_eq!(p.queue_size, 50);
    }

    #[test]
    fn parse_attr_plot_args_requires_port_name() {
        assert!(parse_attr_plot_args(&[]).is_err());
        assert!(parse_attr_plot_args(&[ArgValue::String(String::new())]).is_err());
        assert!(parse_attr_plot_args(&[ArgValue::Int(1)]).is_err());
    }

    #[test]
    fn parse_attr_plot_args_honours_explicit_zero_and_defaults_absent() {
        // Boundary: an explicit cache_size=0 is meaningful (unlimited) and must be
        // honoured; absent n_attributes/n_data_blocks/queue_size fall back.
        let args = vec![
            ArgValue::String("AP2".to_string()),
            ArgValue::Missing, // n_attributes absent
            ArgValue::Int(0),  // cache_size = unlimited (explicit 0, not a fallback)
        ];
        let p = parse_attr_plot_args(&args).unwrap();
        assert_eq!(p.n_attributes, 8, "absent n_attributes -> fallback");
        assert_eq!(
            p.cache_size, 0,
            "explicit 0 cache_size honoured (unlimited)"
        );
        assert_eq!(p.n_data_blocks, 4, "absent n_data_blocks -> fallback");
        assert_eq!(p.in_port, "", "absent in_port -> empty");
        assert_eq!(p.queue_size, 20, "absent queue_size -> fallback");
    }
}