-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1678 lines (1473 loc) · 63 KB
/
Program.cs
File metadata and controls
1678 lines (1473 loc) · 63 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 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)
{
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;
}
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)
{
return await RunSdCardOperationAsync(options);
}
if (options.LanChipInfo)
{
return await RunLanChipInfoAsync(options);
}
return await RunStreamingSessionAsync(options);
}
private static async Task<int> RunStreamingSessionAsync(CliOptions options)
{
// Build connection options from CLI parameters
var connectionOptions = new DeviceConnectionOptions
{
ConnectionRetry = new ConnectionRetryOptions
{
Enabled = options.ConnectAttempts > 1,
MaxAttempts = Math.Max(1, options.ConnectAttempts),
ConnectionTimeout = TimeSpan.FromSeconds(options.ConnectTimeoutSeconds)
}
};
// Connect via TCP or Serial based on provided options
DaqifiDevice device;
string connectionDescription;
if (!string.IsNullOrWhiteSpace(options.SerialPort))
{
device = await DaqifiDeviceFactory.ConnectSerialAsync(
options.SerialPort,
options.BaudRate,
connectionOptions);
connectionDescription = $"{options.SerialPort} @ {options.BaudRate} baud";
}
else
{
device = await DaqifiDeviceFactory.ConnectTcpAsync(
options.IpAddress!,
options.Port,
connectionOptions);
connectionDescription = $"{options.IpAddress}:{options.Port}";
}
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(outputWriter, 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 (!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 connectionOptions = new DeviceConnectionOptions
{
ConnectionRetry = new ConnectionRetryOptions
{
Enabled = options.ConnectAttempts > 1,
MaxAttempts = Math.Max(1, options.ConnectAttempts),
ConnectionTimeout = TimeSpan.FromSeconds(options.ConnectTimeoutSeconds)
}
};
DaqifiDevice device;
string connectionDescription;
if (!string.IsNullOrWhiteSpace(options.SerialPort))
{
device = await DaqifiDeviceFactory.ConnectSerialAsync(
options.SerialPort,
options.BaudRate,
connectionOptions);
connectionDescription = $"{options.SerialPort} @ {options.BaudRate} baud";
}
else
{
device = await DaqifiDeviceFactory.ConnectTcpAsync(
options.IpAddress!,
options.Port,
connectionOptions);
connectionDescription = $"{options.IpAddress}:{options.Port}";
}
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> RunSdCardOperationAsync(CliOptions options)
{
var connectionOptions = new DeviceConnectionOptions
{
ConnectionRetry = new ConnectionRetryOptions
{
Enabled = options.ConnectAttempts > 1,
MaxAttempts = Math.Max(1, options.ConnectAttempts),
ConnectionTimeout = TimeSpan.FromSeconds(options.ConnectTimeoutSeconds)
}
};
DaqifiDevice device;
string connectionDescription;
if (!string.IsNullOrWhiteSpace(options.SerialPort))
{
device = await DaqifiDeviceFactory.ConnectSerialAsync(
options.SerialPort,
options.BaudRate,
connectionOptions);
connectionDescription = $"{options.SerialPort} @ {options.BaudRate} baud";
}
else
{
device = await DaqifiDeviceFactory.ConnectTcpAsync(
options.IpAddress!,
options.Port,
connectionOptions);
connectionDescription = $"{options.IpAddress}:{options.Port}";
}
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.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 =>
{
Console.Write($"\r Received {p.BytesReceived:N0} bytes...");
});
var result = await streamingDevice.DownloadSdCardFileAsync(
options.SdDownloadFileName, progress);
Console.WriteLine();
Console.WriteLine($"Download complete: {result.FileSize:N0} bytes in {result.Duration.TotalSeconds:F1}s");
if (result.FilePath != null)
{
Console.WriteLine($"Saved to: {result.FilePath}");
// Parse the downloaded file (any supported format)
var downloadExt = Path.GetExtension(result.FilePath).ToLowerInvariant();
if (downloadExt is ".bin" or ".csv" or ".json")
{
Console.WriteLine();
Console.WriteLine("--- Parsing downloaded file ---");
options.SdParsePath = result.FilePath;
// Pass the connected device's config so the parser can
// scale raw ADC values using the device's calibration.
var deviceConfig = SdCardDeviceConfiguration.FromDevice((DaqifiDevice)device);
return await RunSdCardParseAsync(options, deviceConfig);
}
}
}
else if (options.SdFormat)
{
Console.Write("Are you sure you want to format the SD card? This erases ALL data. (y/N): ");
var confirm = Console.ReadLine()?.Trim().ToLowerInvariant();
if (confirm == "y")
{
await streamingDevice.FormatSdCardAsync();
Console.WriteLine("Format command sent.");
}
else
{
Console.WriteLine("Format canceled.");
}
}
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error: {FormatException(ex)}");
return 1;
}
finally
{
try
{
device.Disconnect();
}
catch (Exception ex)
{
Console.Error.WriteLine($"Disconnect error: {FormatException(ex)}");
}
}
}
private static async Task<int> RunSdCardParseAsync(
CliOptions options,
SdCardDeviceConfiguration? deviceConfig = null)
{
var filePath = options.SdParsePath!;
if (!File.Exists(filePath))
{
Console.Error.WriteLine($"File not found: {filePath}");
return 1;
}
SdCardLogFormat format;
try
{
format = SdCardFileParserFactory.DetectFormat(filePath);
}
catch (ArgumentException ex)
{
Console.Error.WriteLine(ex.Message);
return 1;
}
var formatLabel = GetLogFormatLabel(filePath);
Console.WriteLine($"Parsing {formatLabel} SD card log file: {filePath}");
var parseOptions = new SdCardParseOptions
{
Progress = new Progress<SdCardParseProgress>(p =>
{
var pct = p.TotalBytes > 0
? (p.BytesRead * 100 / p.TotalBytes).ToString(CultureInfo.InvariantCulture)
: "?";
var unit = format == SdCardLogFormat.Protobuf ? "messages" : "lines";
Console.Write($"\r {pct}% — {p.MessagesRead} {unit} read ({p.BytesRead} bytes)");
}),
ConfigurationOverride = deviceConfig
};
try
{
var session = await SdCardFileParserFactory.ParseFileAsync(filePath, parseOptions);
Console.WriteLine();
Console.WriteLine($"File: {session.FileName}");
if (session.FileCreatedDate.HasValue)
{
Console.WriteLine($"Created: {session.FileCreatedDate.Value:yyyy-MM-dd HH:mm:ss}");
}
if (session.DeviceConfig != null)
{
var cfg = session.DeviceConfig;
Console.WriteLine($"Device Config:");
Console.WriteLine($" Analog ports: {cfg.AnalogPortCount}");
Console.WriteLine($" Digital ports: {cfg.DigitalPortCount}");
Console.WriteLine($" Timestamp freq: {cfg.TimestampFrequency} Hz");
if (cfg.FirmwareRevision != null) Console.WriteLine($" Firmware: {cfg.FirmwareRevision}");
if (cfg.DevicePartNumber != null) Console.WriteLine($" Part number: {cfg.DevicePartNumber}");
if (cfg.DeviceSerialNumber != null) Console.WriteLine($" Serial number: {cfg.DeviceSerialNumber}");
}
var sampleCount = 0;
using var outputWriter = CreateOutputWriter(options);
await foreach (var sample in session.Samples)
{
sampleCount++;
if (options.MessageLimit > 0 && sampleCount > options.MessageLimit)
{
break;
}
var analogStr = string.Join(", ",
sample.AnalogValues.Select(v => v.ToString("F3", CultureInfo.InvariantCulture)));
outputWriter.WriteLine(
$"[{sample.Timestamp:HH:mm:ss.fff}] analog=[{analogStr}] digital=0x{sample.DigitalData:X}");
}
Console.WriteLine($"Total samples: {sampleCount}");
return 0;
}
catch (Exception ex)
{
Console.Error.WriteLine($"Error parsing file: {FormatException(ex)}");
return 1;
}
}
/// <summary>
/// Captures raw protobuf stream data from device to a local .bin file,
/// then parses it with the SD card file parser.
/// </summary>
private static async Task<int> RunCaptureAndParseAsync(CliOptions options)
{
var connectionOptions = new DeviceConnectionOptions
{
ConnectionRetry = new ConnectionRetryOptions
{
Enabled = options.ConnectAttempts > 1,
MaxAttempts = Math.Max(1, options.ConnectAttempts),
ConnectionTimeout = TimeSpan.FromSeconds(options.ConnectTimeoutSeconds)
}
};
DaqifiDevice device;
string connectionDescription;
if (!string.IsNullOrWhiteSpace(options.SerialPort))
{
device = await DaqifiDeviceFactory.ConnectSerialAsync(
options.SerialPort,
options.BaudRate,
connectionOptions);
connectionDescription = $"{options.SerialPort} @ {options.BaudRate} baud";
}
else
{
device = await DaqifiDeviceFactory.ConnectTcpAsync(
options.IpAddress!,
options.Port,
connectionOptions);
connectionDescription = $"{options.IpAddress}:{options.Port}";
}
using var _ = device;
var capturePath = options.CaptureAndParsePath!;
try
{
Console.WriteLine($"Connected to {connectionDescription}");
Console.WriteLine($"Capturing raw stream to: {capturePath}");
await using var captureStream = new FileStream(capturePath, FileMode.Create, FileAccess.Write, FileShare.Read);
var messageCount = 0;
var statusCaptured = false;