-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
2220 lines (1952 loc) · 85.2 KB
/
Copy pathProgram.cs
File metadata and controls
2220 lines (1952 loc) · 85.2 KB
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
using System.Globalization;
using System.Net;
using System.Text;
using Daqifi.Core.Communication.Messages;
using Daqifi.Core.Communication.Producers;
using Daqifi.Core.Communication.Transport;
using Daqifi.Core.Device;
using Daqifi.Core.Device.Discovery;
using Daqifi.Core.Device.Protocol;
using Daqifi.Core.Device.SdCard;
using Daqifi.Core.Firmware;
using Daqifi.Core.Logging.Export;
using Google.Protobuf;
using Microsoft.Extensions.Logging.Abstractions;
namespace Daqifi.Core.Cli;
internal class Program
{
private const int DefaultPort = 9760;
private const int DefaultBaudRate = 9600;
private const int DefaultRate = 100;
private const int DefaultDurationSeconds = 10;
private const int DefaultConnectTimeoutSeconds = 5;
private static async Task<int> Main(string[] args)
{
try
{
return await RunAsync(args);
}
catch (Exception ex)
{
// Last-resort guard. An exception that escapes Main aborts the process with SIGABRT
// (exit code 134) and dumps a stack trace, which reads as a tool defect rather than an
// expected operational failure. Report it the way every other failure path does.
Console.Error.WriteLine($"Error: {FormatException(ex)}");
return 1;
}
}
private static async Task<int> RunAsync(string[] args)
{
var options = CliOptions.Parse(args);
if (options.ShowHelp)
{
PrintHelp();
return 0;
}
if (options.Errors.Count > 0)
{
foreach (var error in options.Errors)
{
Console.Error.WriteLine(error);
}
Console.Error.WriteLine("Use --help to see available options.");
return 1;
}
// Continuous "watch" mode owns its own exit code and is a dedicated dispatch
// path: handle it before one-shot discovery so the two never run together.
if (options.Watch && options.WatchSerial)
{
Console.Error.WriteLine("Cannot specify both --watch and --watch-serial. Use one or the other.");
return 1;
}
if (options.Watch)
{
return await RunWatchAsync(new WiFiDeviceFinder(), options);
}
if (options.WatchSerial)
{
return await RunWatchAsync(new SerialDeviceFinder(), options);
}
if (options.Discover)
{
await DiscoverAsync(options.DiscoveryTimeoutSeconds);
}
if (options.DiscoverSerial)
{
await DiscoverSerialDevicesAsync(options.DiscoveryTimeoutSeconds);
}
// SD card file parse is a local-only operation (no device needed)
if (!string.IsNullOrWhiteSpace(options.SdParsePath))
{
return await RunSdCardParseAsync(options);
}
if (!string.IsNullOrWhiteSpace(options.FirmwareDownloadLatestDirectory))
{
return await RunFirmwareDownloadLatestAsync(options);
}
if (!string.IsNullOrWhiteSpace(options.FirmwareDownloadTag))
{
return await RunFirmwareDownloadByTagAsync(options);
}
// Check if we have a connection target (IP or serial)
var hasIpTarget = !string.IsNullOrWhiteSpace(options.IpAddress);
var hasSerialTarget = !string.IsNullOrWhiteSpace(options.SerialPort);
if (!hasIpTarget && !hasSerialTarget)
{
if (options.Discover || options.DiscoverSerial)
{
return 0;
}
Console.Error.WriteLine("Missing required option: --ip or --serial");
Console.Error.WriteLine("Use --help to see available options.");
return 1;
}
if (hasIpTarget && hasSerialTarget)
{
Console.Error.WriteLine("Cannot specify both --ip and --serial. Use one or the other.");
return 1;
}
if (hasIpTarget)
{
var ipAddress = options.IpAddress!.Trim();
if (!IPAddress.TryParse(ipAddress, out _))
{
Console.Error.WriteLine($"Invalid IP address: {ipAddress}");
return 1;
}
}
if (!string.IsNullOrWhiteSpace(options.FirmwareUpdateLatestDirectory))
{
return await RunFirmwareUpdateLatestAsync(options);
}
if (!string.IsNullOrWhiteSpace(options.FirmwareHexPath))
{
return await RunFirmwareUpdateAsync(options);
}
// Route to capture-and-parse (captures live stream, then parses as SD card file)
if (!string.IsNullOrWhiteSpace(options.CaptureAndParsePath))
{
return await RunCaptureAndParseAsync(options);
}
// Route to SD card operations if any SD card flags are set
if (options.SdList || options.SdLogStart || options.SdLogStop ||
options.SdDeleteFileName != null || options.SdDownloadFileName != null ||
options.SdFormat || options.SdStorage)
{
return await RunSdCardOperationAsync(options);
}
if (options.LanChipInfo)
{
return await RunLanChipInfoAsync(options);
}
return await RunStreamingSessionAsync(options);
}
/// <summary>
/// A connected device together with the human-readable description of how it was reached.
/// </summary>
private sealed record Connection(DaqifiDevice Device, string Description);
/// <summary>
/// Connects to the device described by <paramref name="options"/> over serial or TCP.
/// </summary>
/// <returns>
/// The connection, or <c>null</c> when connecting failed — in which case a single-line error has
/// already been written to stderr and the caller should return exit code 1.
/// </returns>
private static async Task<Connection?> ConnectAsync(CliOptions options)
{
var connectionOptions = new DeviceConnectionOptions
{
ConnectionRetry = new ConnectionRetryOptions
{
Enabled = options.ConnectAttempts > 1,
MaxAttempts = Math.Max(1, options.ConnectAttempts),
ConnectionTimeout = TimeSpan.FromSeconds(options.ConnectTimeoutSeconds)
}
};
var useSerial = !string.IsNullOrWhiteSpace(options.SerialPort);
var description = useSerial
? $"{options.SerialPort} @ {options.BaudRate} baud"
: $"{options.IpAddress}:{options.Port}";
try
{
var device = useSerial
? await DaqifiDeviceFactory.ConnectSerialAsync(
options.SerialPort!,
options.BaudRate,
connectionOptions)
: await DaqifiDeviceFactory.ConnectTcpAsync(
options.IpAddress!,
options.Port,
connectionOptions);
return new Connection(device, description);
}
catch (Exception ex)
{
// Caught broadly on purpose. A failed connect is an ordinary outcome for a CLI (device
// unplugged, wrong port, wrong IP), and the transport layer surfaces it as any of a
// long and evolving list of exception types — IO, UnauthorizedAccess, Timeout, socket
// and argument errors among them. Catching the specific types would leave the crash in
// place for whichever one we did not list.
Console.Error.WriteLine($"Error: Could not connect to {description}: {FormatException(ex)}");
return null;
}
}
private static async Task<int> RunStreamingSessionAsync(CliOptions options)
{
var connection = await ConnectAsync(options);
if (connection is null)
{
return 1;
}
var device = connection.Device;
var connectionDescription = connection.Description;
using var _ = device;
using var outputWriter = CreateOutputWriter(options);
device.StatusChanged += (_, eventArgs) =>
{
Console.WriteLine($"Status: {eventArgs.Status}");
};
using var stopCts = new CancellationTokenSource();
if (options.DurationSeconds > 0)
{
stopCts.CancelAfter(TimeSpan.FromSeconds(options.DurationSeconds));
}
var messageCount = 0;
// The device sends analog and digital data in separate protobuf
// messages that share the same timestamp. We buffer the pending
// analog message and merge it with the subsequent digital message
// before writing a single combined output row.
DaqifiOutMessage? pendingAnalog = null;
var pendingLock = new object();
device.MessageReceived += (_, eventArgs) =>
{
if (stopCts.IsCancellationRequested)
{
return;
}
if (eventArgs.Message.Data is not DaqifiOutMessage message)
{
return;
}
if (options.ShowStatusMessages && ProtobufProtocolHandler.DetectMessageType(message) == ProtobufMessageType.Status)
{
WriteStatusSummary(message);
return;
}
if (!IsStreamLikeMessage(message))
{
return;
}
lock (pendingLock)
{
var hasAnalog = message.AnalogInData.Count > 0 || message.AnalogInDataFloat.Count > 0;
var hasDigital = message.DigitalData.Length > 0;
if (hasAnalog && !hasDigital)
{
// Flush any stale pending message before buffering the new one
if (pendingAnalog != null)
{
WriteMergedSample(outputWriter, pendingAnalog, null, options.OutputFormat, ref messageCount, options.MessageLimit, stopCts);
}
pendingAnalog = message;
return;
}
if (hasDigital && pendingAnalog != null && pendingAnalog.MsgTimeStamp == message.MsgTimeStamp)
{
// Matching pair — merge and write
WriteMergedSample(outputWriter, pendingAnalog, message, options.OutputFormat, ref messageCount, options.MessageLimit, stopCts);
pendingAnalog = null;
return;
}
// Digital-only with no matching analog, or timestamp mismatch
if (pendingAnalog != null)
{
WriteMergedSample(outputWriter, pendingAnalog, null, options.OutputFormat, ref messageCount, options.MessageLimit, stopCts);
pendingAnalog = null;
}
WriteMergedSample(outputWriter, message, null, options.OutputFormat, ref messageCount, options.MessageLimit, stopCts);
}
};
Console.CancelKeyPress += (_, eventArgs) =>
{
eventArgs.Cancel = true;
stopCts.Cancel();
};
try
{
Console.WriteLine($"Connected to {connectionDescription}");
if (options.ShowStatusMessages)
{
// The device's status message is requested and consumed during connect, before this
// method gets a chance to subscribe, and the device does not re-send one while
// streaming. Print the summary from the metadata that connect already parsed
// instead of waiting for a message that will never arrive.
WriteStatusSummary(device.Metadata);
}
if (!string.IsNullOrWhiteSpace(options.ChannelMask))
{
if (!IsValidChannelMask(options.ChannelMask))
{
Console.Error.WriteLine($"Invalid channel mask: {options.ChannelMask}");
return 1;
}
device.Send(ScpiMessageProducer.EnableAdcChannels(options.ChannelMask));
}
device.Send(ScpiMessageProducer.StartStreaming(options.SampleRate));
Console.WriteLine($"Streaming at {options.SampleRate} Hz...");
try
{
await Task.Delay(Timeout.InfiniteTimeSpan, stopCts.Token);
}
catch (OperationCanceledException)
{
// Expected when cancellation is requested.
}
device.Send(ScpiMessageProducer.StopStreaming);
Console.WriteLine("Streaming stopped.");
// Flush any buffered analog-only message that never got a matching digital
lock (pendingLock)
{
if (pendingAnalog != null)
{
WriteMergedSample(outputWriter, pendingAnalog, null, options.OutputFormat, ref messageCount, options.MessageLimit, stopCts);
pendingAnalog = null;
}
}
if (options.MinSamples > 0 && messageCount < options.MinSamples)
{
Console.Error.WriteLine(
$"Validation failed: received {messageCount} sample(s), expected at least {options.MinSamples}.");
return 2;
}
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error: {FormatException(ex)}");
return 1;
}
finally
{
try
{
if (!options.KeepConnected)
{
device.Disconnect();
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Disconnect error: {FormatException(ex)}");
}
}
}
private static async Task<int> RunFirmwareUpdateAsync(
CliOptions options,
string? firmwareHexPathOverride = null)
{
var firmwareHexPath = firmwareHexPathOverride ?? options.FirmwareHexPath;
if (string.IsNullOrWhiteSpace(firmwareHexPath))
{
Console.Error.WriteLine("Firmware update requires a HEX path.");
return 1;
}
var connection = await ConnectAsync(options);
if (connection is null)
{
return 1;
}
var device = connection.Device;
var connectionDescription = connection.Description;
using var _ = device;
using var hidTransport = new HidLibraryTransport();
using var httpClient = new HttpClient();
using var firmwareUpdateService = new FirmwareUpdateService(
hidTransport,
new GitHubFirmwareDownloadService(httpClient),
new ProcessExternalProcessRunner(),
NullLogger<FirmwareUpdateService>.Instance);
firmwareUpdateService.StateChanged += (_, stateArgs) =>
{
Console.WriteLine(
$"[State] {stateArgs.PreviousState} -> {stateArgs.CurrentState} | " +
$"{stateArgs.Operation} | {stateArgs.ChangedAtUtc:O}");
};
var progress = new Progress<FirmwareUpdateProgress>(report =>
{
var byteSummary = report.TotalBytes > 0
? $" [{report.BytesWritten}/{report.TotalBytes} bytes]"
: string.Empty;
Console.WriteLine(
$"[Progress] {report.PercentComplete,6:F1}% | " +
$"{report.State} | {report.CurrentOperation}{byteSummary}");
});
try
{
Console.WriteLine($"Connected to {connectionDescription}");
if (device is not DaqifiStreamingDevice streamingDevice)
{
Console.Error.WriteLine("Firmware update requires a streaming device connection.");
return 1;
}
Console.WriteLine($"Starting PIC32 firmware update with HEX file: {firmwareHexPath}");
await firmwareUpdateService.UpdateFirmwareAsync(
streamingDevice,
firmwareHexPath,
progress);
Console.WriteLine("Firmware update completed successfully.");
return 0;
}
catch (FirmwareUpdateException ex)
{
Console.Error.WriteLine("Firmware update failed.");
Console.Error.WriteLine($" State: {ex.FailedState}");
Console.Error.WriteLine($" Operation: {ex.Operation}");
Console.Error.WriteLine($" Message: {ex.Message}");
if (!string.IsNullOrWhiteSpace(ex.RecoveryGuidance))
{
Console.Error.WriteLine($" Recovery: {ex.RecoveryGuidance}");
}
if (ex.InnerException != null)
{
Console.Error.WriteLine($" Inner: {FormatException(ex.InnerException)}");
}
return 1;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Firmware update invocation error: {FormatException(ex)}");
Console.Error.WriteLine($" State: {firmwareUpdateService.CurrentState}");
return 1;
}
finally
{
try
{
device.Disconnect();
}
catch (Exception ex)
{
Console.Error.WriteLine($"Disconnect error: {FormatException(ex)}");
}
}
}
private static async Task<int> RunFirmwareDownloadLatestAsync(CliOptions options)
{
if (string.IsNullOrWhiteSpace(options.FirmwareDownloadLatestDirectory))
{
Console.Error.WriteLine("Missing destination directory for --fw-download-latest.");
return 1;
}
using var httpClient = new HttpClient();
var downloadService = new GitHubFirmwareDownloadService(httpClient);
var progress = new Progress<int>(percent =>
{
Console.WriteLine($"[Download] {percent,3}%");
});
try
{
Console.WriteLine("Downloading latest PIC32 firmware...");
var downloadedPath = await downloadService.DownloadLatestFirmwareAsync(
options.FirmwareDownloadLatestDirectory,
progress: progress);
if (string.IsNullOrWhiteSpace(downloadedPath))
{
Console.Error.WriteLine("No latest firmware HEX asset found.");
return 1;
}
Console.WriteLine($"Downloaded latest firmware HEX: {downloadedPath}");
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Firmware download failed: {FormatException(ex)}");
return 1;
}
}
private static async Task<int> RunFirmwareDownloadByTagAsync(CliOptions options)
{
if (string.IsNullOrWhiteSpace(options.FirmwareDownloadTag))
{
Console.Error.WriteLine("Missing tag for --fw-download-tag.");
return 1;
}
if (string.IsNullOrWhiteSpace(options.FirmwareDownloadTagDirectory))
{
Console.Error.WriteLine("Missing destination directory for --fw-download-tag.");
return 1;
}
using var httpClient = new HttpClient();
var downloadService = new GitHubFirmwareDownloadService(httpClient);
var progress = new Progress<int>(percent =>
{
Console.WriteLine($"[Download] {percent,3}%");
});
try
{
Console.WriteLine($"Downloading PIC32 firmware for tag {options.FirmwareDownloadTag}...");
var downloadedPath = await downloadService.DownloadFirmwareByTagAsync(
options.FirmwareDownloadTag,
options.FirmwareDownloadTagDirectory,
progress: progress);
if (string.IsNullOrWhiteSpace(downloadedPath))
{
Console.Error.WriteLine(
$"No HEX firmware asset found for tag {options.FirmwareDownloadTag}.");
return 1;
}
Console.WriteLine($"Downloaded firmware HEX: {downloadedPath}");
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Firmware download failed: {FormatException(ex)}");
return 1;
}
}
private static async Task<int> RunFirmwareUpdateLatestAsync(CliOptions options)
{
if (string.IsNullOrWhiteSpace(options.FirmwareUpdateLatestDirectory))
{
Console.Error.WriteLine("Missing destination directory for --fw-update-latest.");
return 1;
}
using var httpClient = new HttpClient();
var downloadService = new GitHubFirmwareDownloadService(httpClient);
var progress = new Progress<int>(percent =>
{
Console.WriteLine($"[Download] {percent,3}%");
});
try
{
Console.WriteLine("Downloading latest PIC32 firmware before update...");
var downloadedPath = await downloadService.DownloadLatestFirmwareAsync(
options.FirmwareUpdateLatestDirectory,
progress: progress);
if (string.IsNullOrWhiteSpace(downloadedPath))
{
Console.Error.WriteLine("No latest firmware HEX asset found.");
return 1;
}
Console.WriteLine($"Downloaded latest firmware HEX: {downloadedPath}");
return await RunFirmwareUpdateAsync(options, downloadedPath);
}
catch (Exception ex)
{
Console.Error.WriteLine($"Firmware download/update failed: {FormatException(ex)}");
return 1;
}
}
private static async Task DiscoverAsync(int timeoutSeconds)
{
using var finder = new WiFiDeviceFinder();
var timeout = TimeSpan.FromSeconds(timeoutSeconds <= 0 ? 5 : timeoutSeconds);
var devices = await finder.DiscoverAsync(timeout);
Console.WriteLine("Discovered WiFi devices:");
foreach (var device in devices)
{
Console.WriteLine($" - {device.Name} ({device.IPAddress}:{device.Port}) SN:{device.SerialNumber}");
}
}
private static async Task DiscoverSerialDevicesAsync(int timeoutSeconds)
{
Console.WriteLine("Discovering serial devices (this may take a moment)...");
using var finder = new SerialDeviceFinder();
var timeout = TimeSpan.FromSeconds(timeoutSeconds <= 0 ? 30 : timeoutSeconds);
finder.DeviceDiscovered += (_, args) =>
{
Console.WriteLine($" Found: {args.DeviceInfo.Name} ({args.DeviceInfo.PortName}) " +
$"SN:{args.DeviceInfo.SerialNumber} FW:{args.DeviceInfo.FirmwareVersion}");
};
List<IDeviceInfo> devices;
try
{
devices = (await finder.DiscoverAsync(timeout)).ToList();
}
catch (Exception ex)
{
Console.WriteLine($"Error during serial discovery: {ex.Message}");
devices = new List<IDeviceInfo>();
}
Console.WriteLine();
Console.WriteLine($"Discovered {devices.Count} DAQiFi device(s):");
if (devices.Count == 0)
{
Console.WriteLine(" (no DAQiFi devices found)");
Console.WriteLine();
Console.WriteLine("Available serial ports (not verified as DAQiFi devices):");
var ports = SerialStreamTransport.GetAvailablePortNames();
if (ports.Length == 0)
{
Console.WriteLine(" (none)");
}
else
{
foreach (var port in ports)
{
Console.WriteLine($" - {port}");
}
}
}
else
{
foreach (var device in devices)
{
Console.WriteLine($" - {device.Name} ({device.PortName}) SN:{device.SerialNumber} FW:{device.FirmwareVersion}");
}
}
}
private static async Task<int> RunWatchAsync(IDeviceFinder finder, CliOptions options)
{
// A positive --duration auto-stops the watch; <= 0 means run until Ctrl+C,
// matching how streaming and SD logging treat DurationSeconds in this CLI.
var bounded = options.DurationSeconds > 0;
if (bounded)
{
Console.WriteLine($"Watching for devices for {options.DurationSeconds}s (Ctrl+C to stop early)...");
}
else
{
Console.WriteLine("Watching for devices (Ctrl+C to stop)...");
}
Console.WriteLine("Legend: [+] discovered, [-] lost");
Console.WriteLine();
// Surface operational errors (scan failures, a failed stop) via the exit code so
// scripts/CI don't read a clean exit as success, consistent with the other handlers.
var hadError = false;
// ContinuousDeviceFinder owns and disposes the inner finder (LeaveInnerFinderOpen = false),
// so a single using covers both.
using var watcher = new ContinuousDeviceFinder(finder, new ContinuousDiscoveryOptions
{
Interval = TimeSpan.FromSeconds(1),
PassTimeout = TimeSpan.FromSeconds(3),
MissThreshold = 2,
});
watcher.DeviceDiscovered += (_, args) =>
{
var d = args.DeviceInfo;
Console.WriteLine($" [+] discovered {d.Name} SN:{d.SerialNumber} ({DescribeEndpoint(d)})");
};
watcher.DeviceLost += (_, args) =>
{
var d = args.DeviceInfo;
Console.WriteLine($" [-] lost {d.Name} SN:{d.SerialNumber} ({DescribeEndpoint(d)})");
};
watcher.ScanError += (_, args) =>
{
hadError = true;
Console.Error.WriteLine($"Scan error: {args.Exception.Message}");
};
using var stopCts = new CancellationTokenSource();
if (bounded)
{
stopCts.CancelAfter(TimeSpan.FromSeconds(options.DurationSeconds));
}
// Register Ctrl+C BEFORE starting the scan so an early Ctrl+C triggers graceful
// shutdown instead of killing the process. CancelKeyPress is a process-global event,
// so we remove the handler again in the outer finally (it would otherwise leak and
// could fire against a disposed token if watch mode runs more than once in-process).
ConsoleCancelEventHandler cancelHandler = (_, e) =>
{
e.Cancel = true;
// Ctrl+C fires on its own thread and can race shutdown disposing stopCts.
try { stopCts.Cancel(); }
catch (ObjectDisposedException) { /* already shutting down */ }
};
Console.CancelKeyPress += cancelHandler;
try
{
try
{
watcher.Start();
}
catch (Exception ex)
{
// Never started, so there is nothing to stop; the outer finally unsubscribes.
Console.Error.WriteLine($"Error: {FormatException(ex)}");
return 1;
}
try
{
await Task.Delay(Timeout.InfiniteTimeSpan, stopCts.Token);
}
catch (OperationCanceledException)
{
// Expected: duration elapsed or Ctrl+C pressed.
}
finally
{
// Always stop the scan loop, even if the wait above threw unexpectedly.
try
{
await watcher.StopAsync();
}
catch (Exception ex)
{
hadError = true;
Console.Error.WriteLine($"Error stopping watcher: {FormatException(ex)}");
}
}
}
finally
{
Console.CancelKeyPress -= cancelHandler;
}
var live = watcher.Devices;
Console.WriteLine();
Console.WriteLine($"Final live set: {live.Count} device(s)");
foreach (var d in live)
{
Console.WriteLine($" - {d.Name} SN:{d.SerialNumber} ({DescribeEndpoint(d)})");
}
return hadError ? 1 : 0;
}
// Renders whichever endpoint the transport populated (IP for WiFi, port for serial).
private static string DescribeEndpoint(IDeviceInfo device)
{
if (!string.IsNullOrWhiteSpace(device.PortName))
{
return device.PortName!;
}
if (device.IPAddress != null)
{
return $"{device.IPAddress}:{device.Port}";
}
return device.ConnectionType.ToString();
}
private static async Task<int> RunSdCardOperationAsync(CliOptions options)
{
// Resolve (and reject) the download destination before connecting, so a bad path costs
// nothing and can never be discovered after a long transfer.
string? sdDownloadDestination = null;
if (!string.IsNullOrWhiteSpace(options.SdDownloadFileName))
{
sdDownloadDestination = ResolveSdDownloadDestination(
options.SdDownloadFileName,
options.SdDownloadDestination,
options.Overwrite,
out var destinationError);
if (sdDownloadDestination is null)
{
Console.Error.WriteLine(destinationError);
return 1;
}
}
var connection = await ConnectAsync(options);
if (connection is null)
{
return 1;
}
var device = connection.Device;
var connectionDescription = connection.Description;
using var _ = device;
try
{
Console.WriteLine($"Connected to {connectionDescription}");
if (device is not DaqifiStreamingDevice streamingDevice)
{
Console.Error.WriteLine("SD card operations require a streaming device.");
return 1;
}
await streamingDevice.InitializeAsync();
if (options.SdStorage)
{
Console.WriteLine("Querying SD card storage...");
var storage = await streamingDevice.GetSdCardStorageAsync();
Console.WriteLine($" Free: {storage.FreeBytes,15:N0} bytes ({storage.FreeBytes / 1024.0 / 1024.0:F2} MiB)");
Console.WriteLine($" Used: {storage.UsedBytes,15:N0} bytes ({storage.UsedBytes / 1024.0 / 1024.0:F2} MiB)");
Console.WriteLine($" Total: {storage.TotalBytes,15:N0} bytes ({storage.TotalBytes / 1024.0 / 1024.0:F2} MiB)");
if (storage.TotalBytes > 0)
{
Console.WriteLine($" Used%: {storage.UsedBytes * 100.0 / storage.TotalBytes:F1}%");
}
}
else if (options.SdList)
{
Console.WriteLine("Listing SD card files...");
var files = await streamingDevice.GetSdCardFilesAsync();
if (files.Count == 0)
{
Console.WriteLine(" (no files found)");
}
else
{
foreach (var file in files)
{
var dateStr = file.CreatedDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "unknown date";
var formatStr = GetLogFormatLabel(file.FileName);
Console.WriteLine($" {file.FileName,-35} {dateStr} [{formatStr}]");
}
}
Console.WriteLine($"Total: {files.Count} file(s)");
}
else if (options.SdLogStart)
{
streamingDevice.StreamingFrequency = options.SampleRate;
// Enable channels before starting SD card logging. Core's
// StartSdCardLoggingAsync only forwards the channel mask — it does
// not enable channels itself. Without an explicit mask we enable all
// ADC channels (the device reports AnalogInputChannels in its
// capabilities after InitializeAsync) and DIO ports so the log
// file is not empty.
var channelMask = options.ChannelMask;
if (!string.IsNullOrWhiteSpace(channelMask) && !IsValidChannelMask(channelMask))
{
Console.Error.WriteLine($"Invalid channel mask: {channelMask}");
return 1;
}
if (string.IsNullOrWhiteSpace(channelMask))
{
var adcCount = streamingDevice.Metadata.Capabilities.AnalogInputChannels;
if (adcCount > 0)
{
channelMask = ((1u << adcCount) - 1).ToString();
}
}
if (!string.IsNullOrWhiteSpace(channelMask))
{
streamingDevice.Send(ScpiMessageProducer.EnableAdcChannels(channelMask));
await Task.Delay(100);
}
streamingDevice.Send(ScpiMessageProducer.EnableDioPorts());
await Task.Delay(100);
await streamingDevice.StartSdCardLoggingAsync(
channelMask: channelMask,
format: options.SdLogFormat);
Console.WriteLine("SD card logging started.");
if (options.DurationSeconds > 0)
{
using var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(options.DurationSeconds));
Console.CancelKeyPress += (_, eventArgs) =>
{
eventArgs.Cancel = true;
cts.Cancel();
};
try
{
Console.WriteLine($"Logging for {options.DurationSeconds} seconds (Ctrl+C to stop early)...");
await Task.Delay(Timeout.InfiniteTimeSpan, cts.Token);
}
catch (OperationCanceledException)
{
// Expected
}
await streamingDevice.StopSdCardLoggingAsync();
Console.WriteLine("SD card logging stopped.");
}
else
{
Console.WriteLine("Use --sd-log-stop to stop logging.");
}
}
else if (options.SdLogStop)
{
await streamingDevice.StopSdCardLoggingAsync();
Console.WriteLine("SD card logging stopped.");
}
else if (!string.IsNullOrWhiteSpace(options.SdDeleteFileName))
{
Console.WriteLine($"Deleting SD card file: {options.SdDeleteFileName}");
await streamingDevice.DeleteSdCardFileAsync(options.SdDeleteFileName);
Console.WriteLine("Delete command sent.");
Console.WriteLine("Refreshing file list...");
var files = streamingDevice.SdCardFiles;
foreach (var file in files)
{
var dateStr = file.CreatedDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? "unknown date";
var formatStr = GetLogFormatLabel(file.FileName);
Console.WriteLine($" {file.FileName,-35} {dateStr} [{formatStr}]");
}
Console.WriteLine($"Total: {files.Count} file(s)");
}
else if (!string.IsNullOrWhiteSpace(options.SdDownloadFileName))
{
Console.WriteLine($"Downloading SD card file: {options.SdDownloadFileName}");
var progress = new Progress<SdCardTransferProgress>(p =>