Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
1529 lines (1358 loc) · 69.9 KB
/
Copy pathProgram.cs
File metadata and controls
1529 lines (1358 loc) · 69.9 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
// =============================================================================
// OSDP SC2 ACU Benchmark
//
// A command-line Access Control Unit (ACU) that measures the response rate and
// latency of a Peripheral Device (PD) implementation of OSDP Secure Channel v2
// across two phases:
//
// 1. Asymmetric pairing - the post-quantum osdp_PAIR/osdp_PAIRR exchange
// that derives the 32-byte SCBK out of band.
// 2. SC2 messaging init - the symmetric SC2 handshake (CHLNG / CCRYPT /
// SCRYPT) that brings the secure channel up,
// repeated with the derived key.
//
// Results are printed to the console and written to a Markdown report.
//
// Usage:
// OsdpSc2Benchmark --port COM5 [options]
//
// Options:
// --port <name> Serial port of the RS-485 bus (required, e.g. COM5)
// --baud <rate> Baud rate (default 38400)
// --address <0-127> PD address (default 0)
// --mode <both|pairing|sc2> Which phase(s) to run (default both)
// --pair-iterations <n> Pairing trials (default 1; needs a
// manual PD reset between trials if raised)
// --sc2-iterations <n> SC2 handshake trials (default 5). Each session
// also issues osdp_ID, osdp_CAP and osdp_KEYSET and times the
// reply interval for each.
// --pair-timeout <sec> Per-pairing timeout (default 30)
// --sc2-timeout <sec> Per-SC2-handshake timeout (default 15)
// --scbk <hex> Pre-shared 32-byte SCBK (64 hex chars). If given, the
// SC2 phase uses it instead of deriving one by pairing.
// --output <path> Markdown report path (default benchmark-report.md)
// --help Show this help.
//
// The PD under test is expected to trust the OSDP.Net demo CA for pairing
// (CertificateAuthority.Demo()), matching the OSDP.Net console demonstration.
// =============================================================================
using System.Diagnostics;
using System.Text;
using OSDP.Net;
using OSDP.Net.Connections;
using OSDP.Net.Messages;
using OSDP.Net.Messages.SecureChannel;
using OSDP.Net.Model.CommandData;
using OSDP.Net.Model.ReplyData;
using OSDP.Net.Pairing;
if (args.Contains("--self-test"))
{
// Validates the timing arithmetic without a PD. Exits before touching a serial port.
Console.WriteLine(PairingProfiler.SelfTest());
// Fragment sizing is the other piece of arithmetic that a bad answer would only reveal on
// hardware, where retrying costs a manual PD reset.
Console.WriteLine("Fragment size derivation (packet size -> fragment payload):");
var fragmentCases = new (ushort Packet, int Expected)[]
{
(BenchmarkConfig.MaxPacketSize, BenchmarkConfig.MaxPacketSize - 8 - BenchmarkConfig.PairingFragmentHeaderSize),
(256, 256 - 8 - BenchmarkConfig.PairingFragmentHeaderSize),
(128, 128 - 8 - BenchmarkConfig.PairingFragmentHeaderSize),
};
var fragmentFailures = new List<string>();
foreach (var (packet, expected) in fragmentCases)
{
ushort actual = BenchmarkConfig.MaxFragmentForPacket(packet);
Console.WriteLine($" {packet,5} B packet -> {actual,5} B fragment");
if (actual != expected) fragmentFailures.Add($"{packet} B: expected {expected}, got {actual}");
}
Console.WriteLine(fragmentFailures.Count == 0
? "SELF-TEST PASSED: fragment sizing matches header + code + CRC + fragment header."
: "SELF-TEST FAILED:\n - " + string.Join("\n - ", fragmentFailures));
return 0;
}
var config = BenchmarkConfig.Parse(args);
if (config is null)
{
return 1; // Parse already printed usage / the error.
}
var runner = new BenchmarkRunner(config);
try
{
return await runner.RunAsync();
}
catch (Exception ex)
{
Console.Error.WriteLine();
Console.Error.WriteLine($"FATAL: {ex.GetType().Name}: {ex.Message}");
Console.Error.WriteLine(ex.StackTrace);
return 2;
}
// =============================================================================
// Configuration
// =============================================================================
/// <summary>Parsed command-line options driving the benchmark run.</summary>
internal sealed class BenchmarkConfig
{
public string Port { get; private set; }
public int Baud { get; private set; } = 38400;
public byte Address { get; private set; } = 0;
public RunMode Mode { get; private set; } = RunMode.Both;
// Pairing is a one-shot operation in practice: a PD that has paired holds an established
// secure channel and NAKs the cleartext osdp_PAIR that a second trial would need
// (CommunicationSecurityNotMet). Repeating it requires a manual PD reset between trials, so
// the default is a single trial. Raise this only if you are resetting the PD by hand.
public int PairIterations { get; private set; } = 1;
// Maximum pairing fragment size, in payload bytes. Null means "derive it from the PD's reported
// receive buffer capability", which is the default: the ACU queries osdp_ID and osdp_CAP before
// pairing and sizes fragments to what the device says it can take.
public ushort? FragmentSizeOverride { get; private set; }
/// <summary>Fragment size used when the PD does not report a usable receive buffer size.</summary>
public const ushort DefaultFragmentSize = 1024;
/// <summary>
/// Bytes the multipart fragment header adds inside the message payload: TotalSize, Offset and
/// FragmentSize, two bytes each under <see cref="MessageDataFragmentFieldSize.TwoBytes"/>, which
/// is what the pairing exchange uses. <see cref="Message.CalculateMaximumMessageSize"/> accounts
/// for the OSDP framing around the payload but not for this header inside it.
/// </summary>
public const int PairingFragmentHeaderSize = 6;
/// <summary>Largest total OSDP packet the protocol allows.</summary>
public const ushort MaxPacketSize = 1440;
/// <summary>
/// Converts a total packet size into the largest pairing fragment payload that fits inside it.
/// The PD's receive buffer capability describes the whole packet, so the framing has to come off
/// before the number means anything. Pairing rides cleartext, hence <c>isEncrypted: false</c>.
/// </summary>
public static ushort MaxFragmentForPacket(ushort totalPacketSize)
{
ushort payload = Message.CalculateMaximumMessageSize(totalPacketSize, isEncrypted: false);
return (ushort)Math.Max(payload - PairingFragmentHeaderSize, 0);
}
// Size advertised to the PD via osdp_ACURXSIZE so it knows how large a reply packet the ACU can
// accept. This is the only lever over PD -> ACU fragment size: --fragment-size governs only the
// ACU's outbound fragments, which is why message 2 did not shrink when it was raised. 0 skips
// the command entirely.
public ushort AcuReceiveSize { get; private set; } = MaxPacketSize;
/// <summary>
/// Upper bound on a derived fragment size. Derived from <see cref="MaxPacketSize"/> rather than
/// chosen: the ceiling is on the whole packet, so the payload ceiling is that minus framing.
/// </summary>
public static ushort MaxFragmentSize => MaxFragmentForPacket(MaxPacketSize);
public int Sc2Iterations { get; private set; } = 5;
public TimeSpan PairTimeout { get; private set; } = TimeSpan.FromSeconds(30);
public TimeSpan Sc2Timeout { get; private set; } = TimeSpan.FromSeconds(15);
public byte[] PresharedScbk { get; private set; } // null unless --scbk supplied
public string OutputPath { get; private set; } = "benchmark-report.md";
/// <summary>How long to wait for the PD to answer cleartext polls before a pairing attempt.</summary>
public TimeSpan OnlineWait { get; } = TimeSpan.FromSeconds(5);
/// <summary>Settle time between trials so the bus returns to a known state.</summary>
public TimeSpan InterTrialDelay { get; } = TimeSpan.FromMilliseconds(750);
public enum RunMode { Both, Pairing, Sc2 }
public bool RunPairing => Mode is RunMode.Both or RunMode.Pairing;
public bool RunSc2 => Mode is RunMode.Both or RunMode.Sc2;
public static BenchmarkConfig Parse(string[] args)
{
var c = new BenchmarkConfig();
try
{
for (int i = 0; i < args.Length; i++)
{
string a = args[i];
string Next(string name)
{
if (i + 1 >= args.Length)
throw new ArgumentException($"Option {name} requires a value.");
return args[++i];
}
switch (a)
{
case "--help" or "-h" or "/?":
PrintUsage();
return null;
case "--port": c.Port = Next(a); break;
case "--baud": c.Baud = int.Parse(Next(a)); break;
case "--address": c.Address = ParseAddress(Next(a)); break;
case "--mode": c.Mode = ParseMode(Next(a)); break;
case "--pair-iterations": c.PairIterations = int.Parse(Next(a)); break;
case "--fragment-size": c.FragmentSizeOverride = ushort.Parse(Next(a)); break;
case "--acu-receive-size": c.AcuReceiveSize = ushort.Parse(Next(a)); break;
case "--sc2-iterations": c.Sc2Iterations = int.Parse(Next(a)); break;
case "--pair-timeout": c.PairTimeout = TimeSpan.FromSeconds(double.Parse(Next(a))); break;
case "--sc2-timeout": c.Sc2Timeout = TimeSpan.FromSeconds(double.Parse(Next(a))); break;
case "--scbk": c.PresharedScbk = ParseHexKey(Next(a)); break;
case "--output": c.OutputPath = Next(a); break;
default:
throw new ArgumentException($"Unknown option: {a}");
}
}
if (string.IsNullOrWhiteSpace(c.Port))
throw new ArgumentException("--port is required (e.g. --port COM5).");
if (c.Mode == RunMode.Sc2 && c.PresharedScbk is null)
{
// sc2-only has nothing to derive a key from; it needs one supplied.
throw new ArgumentException(
"--mode sc2 requires --scbk <hex> (no pairing phase runs to derive a key).");
}
}
catch (Exception ex)
{
Console.Error.WriteLine($"Argument error: {ex.Message}");
Console.Error.WriteLine("Run with --help for usage.");
return null;
}
return c;
}
private static byte ParseAddress(string s)
{
byte addr = byte.Parse(s);
if (addr > 127) throw new ArgumentException("--address must be between 0 and 127.");
return addr;
}
private static RunMode ParseMode(string s) => s.ToLowerInvariant() switch
{
"both" => RunMode.Both,
"pairing" or "pair" => RunMode.Pairing,
"sc2" => RunMode.Sc2,
_ => throw new ArgumentException($"--mode must be both|pairing|sc2 (got '{s}').")
};
private static byte[] ParseHexKey(string hex)
{
hex = hex.Replace("-", "").Replace(" ", "").Trim();
if (hex.Length != 64)
throw new ArgumentException("--scbk must be 32 bytes (64 hex characters).");
var key = new byte[32];
for (int i = 0; i < 32; i++)
key[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
return key;
}
public static void PrintUsage()
{
Console.WriteLine(
"""
OSDP SC2 ACU Benchmark - measures PD response rate for pairing and SC2 init.
Usage:
OsdpSc2Benchmark --port COM5 [options]
Options:
--port <name> Serial port (required, e.g. COM5, /dev/ttyUSB0)
--baud <rate> Baud rate (default 38400)
--address <0-127> PD address (default 0)
--mode <both|pairing|sc2> Which phase(s) to run (default both)
--pair-iterations <n> Pairing trials (default 1; >1 needs
a manual PD reset per trial)
--fragment-size <n> Pairing fragment payload bytes. Default is derived
from the PD's reported receive buffer (whole-packet)
minus framing, capped at OSDP's 1440-byte packet.
Governs ACU -> PD fragments only.
--acu-receive-size <n> Packet size advertised to the PD via osdp_ACURXSIZE
(default 1440, 0 to skip). The only lever over
PD -> ACU fragment size.
--sc2-iterations <n> SC2 handshake trials (default 5)
--pair-timeout <sec> Per-pairing timeout (default 30)
--sc2-timeout <sec> Per-SC2-handshake timeout (default 15)
--scbk <hex> Pre-shared 32-byte SCBK (64 hex). If set, the
SC2 phase uses it instead of pairing to derive one.
--output <path> Markdown report path (default benchmark-report.md)
--self-test Verify the timing profiler's arithmetic against a
synthetic exchange and exit. No PD or serial port
needed.
--help Show this help.
""");
}
}
// =============================================================================
// Trial results and statistics
// =============================================================================
/// <summary>Outcome of a single benchmark trial.</summary>
internal sealed record TrialResult(
int Index,
bool Success,
double ElapsedMs,
string Detail,
string FailureCategory,
PairingProfile Profile = null,
IReadOnlyList<CommandTiming> Commands = null);
/// <summary>Round-trip time for one OSDP command issued after the channel was up.</summary>
internal sealed record CommandTiming(string Name, double Ms, bool Success, string Detail);
/// <summary>
/// What the PD reported about itself, plus the fragment size derived from it.
/// </summary>
internal sealed class DeviceQuery
{
public string Identity { get; init; }
public IReadOnlyList<string> Capabilities { get; init; }
public IReadOnlyList<CommandTiming> Timings { get; init; }
/// <summary>Total OSDP packet the PD can receive, per capability 10. Null if not reported.</summary>
public int? ReceiveBufferSize { get; init; }
/// <summary>Largest reassembled multipart message, per capability 11. Null if not reported.</summary>
public int? LargestCombinedMessageSize { get; init; }
public bool Succeeded { get; init; }
}
/// <summary>One measured span within a pairing exchange.</summary>
internal sealed record PairingSegment(string Name, double Ms, string Attribution, int Fragments);
/// <summary>
/// A stage-by-stage timing breakdown of a single pairing exchange, derived from the
/// <see cref="PairingProgress"/> reports emitted by <c>ControlPanel.PairDevice</c>.
/// </summary>
internal sealed class PairingProfile
{
public IReadOnlyList<PairingSegment> Segments { get; init; }
public double TotalMs { get; init; }
/// <summary>True when a message produced a single progress callback, so its wire time
/// could not be separated from the adjacent turnaround.</summary>
public bool HasCollapsedSpans { get; init; }
}
/// <summary>
/// Captures pairing progress reports with timestamps so the exchange can be profiled.
/// </summary>
/// <remarks>
/// This deliberately implements <see cref="IProgress{T}"/> by hand instead of using
/// <see cref="Progress{T}"/>. <see cref="Progress{T}"/> marshals its callback through the captured
/// synchronization context (or the thread pool, in a console app), so the timestamp would include
/// scheduling delay — precisely the sub-millisecond-to-millisecond quantity being measured here.
/// Reporting inline on the calling thread keeps the samples faithful to the protocol events.
/// </remarks>
internal sealed class PairingProfiler : IProgress<PairingProgress>
{
private readonly record struct Sample(double AtMs, PairingStage Stage);
private readonly List<Sample> _samples = new();
private readonly object _gate = new();
private readonly Stopwatch _sw = Stopwatch.StartNew();
/// <summary>The most recently reported stage, used to attribute failures.</summary>
public PairingStage LastStage { get; private set; } = PairingStage.SendingRequest;
public void Report(PairingProgress value)
{
double at = _sw.Elapsed.TotalMilliseconds;
lock (_gate)
{
_samples.Add(new Sample(at, value.Stage));
LastStage = value.Stage;
}
}
/// <summary>
/// Derives the per-operation breakdown. Returns null if the exchange did not run to completion.
/// </summary>
public PairingProfile BuildProfile()
{
Sample[] samples;
lock (_gate) samples = _samples.ToArray();
return DeriveProfile(samples);
}
/// <summary>
/// Exercises <see cref="DeriveProfile"/> against a synthetic exchange so the segment arithmetic
/// can be checked without hardware. Pairing needs a manual PD reset to retry, so the math is
/// worth validating before spending a real attempt on it.
/// </summary>
public static string SelfTest()
{
var sb = new StringBuilder();
// A synthetic exchange chosen so every span is checkable by hand, including the
// first-fragment correction each group receives.
//
// scope : marker at 5 -> 5
// msg1 : 3 callbacks at 145/195/245, perFragment 50
// build = (145-5) - 50 -> 90
// wire = (245-145) + 50 -> 150
// msg2 : 2 callbacks at 445/505, perFragment 60
// turnaround = (445-245) - 60 -> 140
// wire = (505-445) + 60 -> 120
// msg3 : 2 callbacks at 605/645, perFragment 40
// verify = (605-505) - 40 -> 60
// wire = (645-605) + 40 -> 80
// result : 1 callback at 745, no gap to measure, correction 0
// turnaround = (745-645) - 0 -> 100
// wire = 0 -> 0
// finalize : 755 - 745 -> 10
// total : 755
var samples = new[]
{
new Sample(5, PairingStage.SendingRequest), // marker, after scope acquisition
new Sample(145, PairingStage.SendingRequest), // msg1 fragment 1
new Sample(195, PairingStage.SendingRequest),
new Sample(245, PairingStage.SendingRequest), // msg1 fragment 3
new Sample(445, PairingStage.AwaitingResponse),
new Sample(505, PairingStage.AwaitingResponse),
new Sample(605, PairingStage.SendingConfirmation),
new Sample(645, PairingStage.SendingConfirmation),
new Sample(745, PairingStage.AwaitingResult),
new Sample(755, PairingStage.Completed),
};
var p = DeriveProfile(samples);
if (p is null)
{
return "SELF-TEST FAILED: DeriveProfile returned null for a completed exchange.";
}
sb.AppendLine("Profiler self-test (synthetic exchange, no hardware):");
foreach (var seg in p.Segments)
{
sb.AppendLine($" {seg.Ms,8:0.0} ms {seg.Name} [{seg.Attribution}]");
}
sb.AppendLine($" {p.TotalMs,8:0.0} ms total exchange");
sb.AppendLine();
// Expected values follow directly from the synthetic timestamps above.
var expected = new (string Name, double Ms)[]
{
("Acquire bus command scope", 5),
("Build message 1 (ML-KEM keygen + ML-DSA sign)", 90),
("Message 1 on the wire (ACU -> PD)", 150),
("PD turnaround before message 2", 140),
("Message 2 on the wire (PD -> ACU)", 120),
("Verify PD credential + derive key (ProcessMessage2)", 60),
("Message 3 on the wire (ACU -> PD)", 80),
("PD turnaround before result", 100),
("Result message on the wire (PD -> ACU)", 0),
("Confirm key (ProcessResult)", 10),
};
var failures = new List<string>();
foreach (var (name, ms) in expected)
{
var seg = p.Segments.FirstOrDefault(s => s.Name == name);
if (seg is null) { failures.Add($"missing segment '{name}'"); continue; }
if (Math.Abs(seg.Ms - ms) > 0.001) failures.Add($"'{name}': expected {ms} ms, got {seg.Ms}");
}
if (Math.Abs(p.TotalMs - 755) > 0.001) failures.Add($"total: expected 755 ms, got {p.TotalMs}");
if (!p.HasCollapsedSpans) failures.Add("expected HasCollapsedSpans for the single-fragment messages");
// Segments must account for the whole exchange with no gap or double-count.
double sum = p.Segments.Sum(s => s.Ms);
if (Math.Abs(sum - p.TotalMs) > 0.001) failures.Add($"segments sum to {sum} ms but total is {p.TotalMs} ms");
sb.AppendLine(failures.Count == 0
? "SELF-TEST PASSED: all segments and the total reconcile."
: "SELF-TEST FAILED:\n - " + string.Join("\n - ", failures));
return sb.ToString();
}
private static PairingProfile DeriveProfile(Sample[] samples)
{
if (samples.Length < 2 || samples[^1].Stage != PairingStage.Completed)
{
return null; // Incomplete exchange - a partial profile would be misleading.
}
// Group by stage and take the extremes by timestamp rather than by list position, so the
// result holds even if a fragment callback arrives from another thread out of order.
//
// The origin is the stopwatch zero (PairDevice entry), NOT the first sample: the gap before
// the first report is real work (acquiring the bus command scope) and must not be discarded.
const double t0 = 0.0;
double tEnd = samples.Max(s => s.AtMs);
// The earliest SendingRequest sample is the SendingRequest(0.0) marker emitted before
// CreateMessage1; the remaining SendingRequest samples are per-fragment send callbacks.
double tMarker = samples.Where(s => s.Stage == PairingStage.SendingRequest).Min(s => s.AtMs);
Sample[] Group(PairingStage stage, bool skipMarker = false) => samples
.Where(s => s.Stage == stage && !(skipMarker && s.AtMs == tMarker))
.ToArray();
var sendReq = Group(PairingStage.SendingRequest, skipMarker: true);
var awaitResp = Group(PairingStage.AwaitingResponse);
var sendConf = Group(PairingStage.SendingConfirmation);
var awaitRes = Group(PairingStage.AwaitingResult);
double? First(Sample[] g) => g.Length == 0 ? null : g.Min(s => s.AtMs);
double? Last(Sample[] g) => g.Length == 0 ? null : g.Max(s => s.AtMs);
// Per-fragment cost, from the gaps between consecutive fragment callbacks.
double? PerFragment(Sample[] g) =>
g.Length >= 2 ? (g.Max(s => s.AtMs) - g.Min(s => s.AtMs)) / (g.Length - 1) : null;
var segments = new List<PairingSegment>();
void Add(string name, double ms, string attribution, int fragments = 0) =>
segments.Add(new PairingSegment(name, ms, attribution, fragments));
/// Splits the span [boundary, last-of-group] into the compute that preceded the message and
/// the message's own time on the wire.
///
/// Both the send and receive progress callbacks fire *after* a fragment's round trip
/// completes (ControlPanel.ExchangePairingMessage invokes onSendProgress after awaiting
/// SendCommand). So the first callback of a group arrives one whole fragment late, and a
/// naive boundary would bill that fragment to the preceding compute step. At 128-byte
/// fragments that error is small; at 1024 it is ~270 ms and badly distorts the split.
/// The measured per-fragment mean is moved back to the wire to correct it.
void AddSplit(string computeName, string computeAttribution, string wireName,
double? boundary, Sample[] group)
{
if (boundary is null || group.Length == 0) return;
double first = First(group).Value;
double last = Last(group).Value;
double available = Math.Max(first - boundary.Value, 0);
double correction = Math.Min(PerFragment(group) ?? 0, available);
Add(computeName, available - correction, computeAttribution);
Add(wireName, (last - first) + correction, "Serial link", group.Length);
}
Add("Acquire bus command scope", tMarker - t0, "ACU / bus");
AddSplit("Build message 1 (ML-KEM keygen + ML-DSA sign)", "ACU crypto",
"Message 1 on the wire (ACU -> PD)", tMarker, sendReq);
AddSplit("PD turnaround before message 2", "PD crypto + poll wait",
"Message 2 on the wire (PD -> ACU)", Last(sendReq), awaitResp);
AddSplit("Verify PD credential + derive key (ProcessMessage2)", "ACU crypto",
"Message 3 on the wire (ACU -> PD)", Last(awaitResp), sendConf);
AddSplit("PD turnaround before result", "PD crypto + poll wait",
"Result message on the wire (PD -> ACU)", Last(sendConf), awaitRes);
double? lastResultSample = Last(awaitRes) ?? Last(sendConf);
if (lastResultSample is not null)
{
Add("Confirm key (ProcessResult)", tEnd - lastResultSample.Value, "ACU crypto");
}
// A single-fragment group gives no gap to measure, so its wire time cannot be separated
// from the preceding step and stays folded into it.
bool collapsed = new[] { sendReq, awaitResp, sendConf, awaitRes }.Any(g => g.Length == 1);
return new PairingProfile
{
Segments = segments,
TotalMs = tEnd - t0,
HasCollapsedSpans = collapsed,
};
}
}
/// <summary>Aggregate latency statistics over the successful trials of a phase.</summary>
internal sealed class TrialStats
{
public int Total { get; init; }
public int Successes { get; init; }
public int Failures => Total - Successes;
public double SuccessRate => Total == 0 ? 0 : 100.0 * Successes / Total;
public double MinMs { get; init; }
public double MaxMs { get; init; }
public double MeanMs { get; init; }
public double MedianMs { get; init; }
public double P95Ms { get; init; }
public static TrialStats From(IReadOnlyList<TrialResult> trials)
{
var latencies = trials.Where(t => t.Success).Select(t => t.ElapsedMs).OrderBy(x => x).ToArray();
if (latencies.Length == 0)
{
return new TrialStats { Total = trials.Count, Successes = 0 };
}
double Percentile(double p)
{
// Nearest-rank percentile on the ascending-sorted latencies.
int rank = (int)Math.Ceiling(p / 100.0 * latencies.Length);
rank = Math.Clamp(rank, 1, latencies.Length);
return latencies[rank - 1];
}
double median = latencies.Length % 2 == 1
? latencies[latencies.Length / 2]
: (latencies[latencies.Length / 2 - 1] + latencies[latencies.Length / 2]) / 2.0;
return new TrialStats
{
Total = trials.Count,
Successes = latencies.Length,
MinMs = latencies[0],
MaxMs = latencies[^1],
MeanMs = latencies.Average(),
MedianMs = median,
P95Ms = Percentile(95),
};
}
}
// =============================================================================
// Benchmark runner
// =============================================================================
internal sealed class BenchmarkRunner
{
private readonly BenchmarkConfig _config;
private readonly ControlPanel _panel = new();
private Guid _connectionId;
// Demo trust: the PD under test is expected to trust the same demo CA.
private readonly CertificateAuthority _ca = CertificateAuthority.Demo();
private PairingConfiguration _acuPairingConfig;
// Live connection-status snapshot maintained from ConnectionStatusChanged.
private volatile bool _isConnected;
private volatile bool _isSecure;
private TaskCompletionSource<bool> _secureEstablished;
// Every pairing attempt made, phase-1 trials and SCBK-derivation fallbacks alike. Drives the
// timing profile; the response-rate statistics use only the numbered phase-1 trials.
private readonly List<TrialResult> _allPairingAttempts = new();
// Result of the pre-pairing osdp_ID / osdp_CAP interrogation, and the fragment size it implied.
private DeviceQuery _discovery;
private ushort _fragmentSize = BenchmarkConfig.DefaultFragmentSize;
private string _fragmentRationale = "not yet resolved";
public BenchmarkRunner(BenchmarkConfig config) => _config = config;
public async Task<int> RunAsync()
{
_acuPairingConfig = new PairingConfiguration(
PairingCredentials.Generate(new DeviceIdentity("Z-bit Systems", "ACU-Benchmark", "BENCH-0001"), _ca),
PairingTrustAnchor.FromCa(_ca));
PrintHeader();
_panel.ConnectionStatusChanged += OnConnectionStatusChanged;
_connectionId = _panel.StartConnection(new SerialPortOsdpConnection(_config.Port, _config.Baud));
var pairingTrials = new List<TrialResult>();
var sc2Trials = new List<TrialResult>();
byte[] scbk = _config.PresharedScbk;
try
{
// ---- Phase 0: interrogate the PD before sizing anything -------------
// osdp_ID and osdp_CAP go out in cleartext on an unpaired PD. The reported receive
// buffer size is what sets the pairing fragment size, so this has to happen before
// pairing, not after.
Console.WriteLine("\n== Phase 0: PD interrogation (cleartext) ==");
ResetToCleartext();
bool online = await WaitForOnlineAsync(_config.OnlineWait);
if (!online)
{
Console.WriteLine(" PD not answering cleartext polls yet; querying anyway.");
}
_discovery = await QueryDeviceAsync(advertiseReceiveSize: true);
PrintCommandTimings(_discovery.Timings, " ");
if (_discovery.Identity is not null)
{
Console.WriteLine($" identity: {_discovery.Identity}");
}
foreach (var line in _discovery.Capabilities)
{
Console.WriteLine($" cap: {line}");
}
(_fragmentSize, _fragmentRationale) = ResolveFragmentSize(_discovery);
Console.WriteLine($" fragment size: {_fragmentSize} bytes ({_fragmentRationale})");
// ---- Phase 1: pairing response rate --------------------------------
if (_config.RunPairing)
{
Console.WriteLine($"\n== Phase 1: Asymmetric pairing ({_config.PairIterations} trials) ==");
for (int i = 1; i <= _config.PairIterations; i++)
{
var (trial, derivedScbk) = await RunPairingTrialAsync(i);
pairingTrials.Add(trial);
scbk ??= derivedScbk; // keep the first key we manage to derive
ReportTrial(trial);
PrintProfile(trial.Profile);
await Task.Delay(_config.InterTrialDelay);
}
}
// ---- Phase 2: SC2 messaging initialization -------------------------
if (_config.RunSc2)
{
if (scbk is null)
{
// Pairing produced no key (or wasn't run) and none was supplied; derive one now.
Console.WriteLine("\nNo SCBK yet; running a one-off pairing to derive a key for the SC2 phase...");
scbk = await DeriveScbkForSc2Async();
}
if (scbk is null)
{
Console.WriteLine("Could not obtain an SCBK; skipping the SC2 initialization phase.");
}
else
{
Console.WriteLine($"\n== Phase 2: SC2 messaging initialization ({_config.Sc2Iterations} trials) ==");
for (int i = 1; i <= _config.Sc2Iterations; i++)
{
var trial = await RunSc2InitTrialAsync(i, scbk);
sc2Trials.Add(trial);
ReportTrial(trial);
PrintCommandTimings(trial.Commands);
await Task.Delay(_config.InterTrialDelay);
}
}
}
}
finally
{
_panel.ConnectionStatusChanged -= OnConnectionStatusChanged;
try { _panel.RemoveDevice(_connectionId, _config.Address); } catch { /* ignore */ }
try { await _panel.StopConnection(_connectionId); } catch { /* ignore */ }
try { await _panel.Shutdown(); } catch { /* ignore */ }
}
// ---- Report ------------------------------------------------------------
var pairingStats = TrialStats.From(pairingTrials);
var sc2Stats = TrialStats.From(sc2Trials);
PrintSummary("Pairing", pairingStats, pairingTrials, _config.RunPairing);
PrintSummary("SC2 init", sc2Stats, sc2Trials, _config.RunSc2 && sc2Trials.Count > 0);
var report = ReportWriter.Build(_config, scbk, pairingTrials, pairingStats, sc2Trials, sc2Stats,
_allPairingAttempts, _discovery, _fragmentSize, _fragmentRationale);
await File.WriteAllTextAsync(_config.OutputPath, report);
Console.WriteLine($"\nMarkdown report written to: {Path.GetFullPath(_config.OutputPath)}");
return 0;
}
// ---- Pairing trial -----------------------------------------------------
/// <summary>
/// Runs one pairing attempt and records it in <see cref="_allPairingAttempts"/>.
/// </summary>
/// <remarks>
/// Every attempt is recorded, including the fallback attempts made by
/// <see cref="DeriveScbkForSc2Async"/>. Those are not numbered phase-1 trials and must stay out
/// of the response-rate statistics, but a pairing that completed there is still a real exchange
/// and its timing profile is exactly what the report is for. Dropping it produced a report that
/// claimed no pairing completed while the PD had in fact paired.
/// </remarks>
private async Task<(TrialResult trial, byte[] scbk)> RunPairingTrialAsync(int index)
{
var outcome = await RunPairingTrialCoreAsync(index);
_allPairingAttempts.Add(outcome.trial);
return outcome;
}
private async Task<(TrialResult trial, byte[] scbk)> RunPairingTrialCoreAsync(int index)
{
// Fresh cleartext session for each pairing attempt.
ResetToCleartext();
bool onlineAtStart = await WaitForOnlineAsync(_config.OnlineWait);
var profiler = new PairingProfiler();
var sw = Stopwatch.StartNew();
try
{
using var cts = new CancellationTokenSource(_config.PairTimeout + TimeSpan.FromSeconds(5));
PairingResult result = await _panel.PairDevice(
_connectionId, _config.Address, _acuPairingConfig,
maximumFragmentSize: _fragmentSize,
timeout: _config.PairTimeout, progress: profiler, cancellationToken: cts.Token);
sw.Stop();
string detail = $"paired with {result.PeerIdentity}";
return (new TrialResult(index, true, sw.Elapsed.TotalMilliseconds, detail, null,
profiler.BuildProfile()), result.Scbk);
}
catch (PairingException ex)
{
sw.Stop();
string detail = $"stage={profiler.LastStage}, status={ex.Status}: {ex.Message}";
return (new TrialResult(index, false, sw.Elapsed.TotalMilliseconds, detail, ex.Status.ToString()), null);
}
catch (TimeoutException)
{
sw.Stop();
string cat = onlineAtStart ? "Timeout" : "Timeout (PD offline in cleartext)";
// Report the actual elapsed time, not the configured budget — the underlying call can
// give up earlier than --pair-timeout.
string detail = $"stage={profiler.LastStage}: timed out after {sw.Elapsed.TotalSeconds:0.0}s " +
$"(budget {_config.PairTimeout.TotalSeconds:0}s)" +
(onlineAtStart ? "" : " (PD did not answer cleartext polls before the attempt)");
return (new TrialResult(index, false, sw.Elapsed.TotalMilliseconds, detail, cat), null);
}
catch (Exception ex)
{
sw.Stop();
return (new TrialResult(index, false, sw.Elapsed.TotalMilliseconds,
$"stage={profiler.LastStage}: {ex.GetType().Name}: {ex.Message}", ex.GetType().Name), null);
}
}
/// <summary>
/// Issues osdp_ID and osdp_CAP and times each reply. Used twice: once in cleartext before
/// pairing (to size the pairing fragments from what the PD says it can receive), and again on
/// each established SC2 session.
/// </summary>
private async Task<DeviceQuery> QueryDeviceAsync(byte[] keysetKey = null,
bool advertiseReceiveSize = false)
{
var timings = new List<CommandTiming>();
string identity = null;
var capabilityLines = new List<string>();
int? receiveBuffer = null;
int? largestCombined = null;
bool allOk = true;
// --- osdp_ID -------------------------------------------------------------
var sw = Stopwatch.StartNew();
try
{
var id = await _panel.IdReport(_connectionId, _config.Address);
sw.Stop();
identity = $"vendor {BitConverter.ToString(id.VendorCode.Take(3).ToArray())}, " +
$"model {id.ModelNumber}, version {id.Version}, S/N {id.SerialNumber}, " +
$"firmware {id.FirmwareMajor}.{id.FirmwareMinor}.{id.FirmwareBuild}";
timings.Add(new CommandTiming("osdp_ID (ID Report)", sw.Elapsed.TotalMilliseconds, true, identity));
}
catch (Exception ex)
{
sw.Stop();
allOk = false;
timings.Add(new CommandTiming("osdp_ID (ID Report)", sw.Elapsed.TotalMilliseconds, false,
$"{ex.GetType().Name}: {ex.Message}"));
}
// --- osdp_CAP ------------------------------------------------------------
sw = Stopwatch.StartNew();
try
{
var caps = await _panel.DeviceCapabilities(_connectionId, _config.Address);
sw.Stop();
foreach (var cap in caps.Capabilities)
{
// Capabilities 10 and 11 encode a 16-bit size across the two capability bytes,
// little-endian, rather than a compliance/count pair.
int size = cap.Compliance | (cap.NumberOf << 8);
switch (cap.Function)
{
case CapabilityFunction.ReceiveBufferSize:
receiveBuffer = size;
capabilityLines.Add($"ReceiveBufferSize = {size} bytes (whole packet)");
break;
case CapabilityFunction.LargestCombinedMessageSize:
largestCombined = size;
capabilityLines.Add($"LargestCombinedMessageSize = {size} bytes");
break;
default:
capabilityLines.Add($"{cap.Function} = compliance {cap.Compliance}, numberOf {cap.NumberOf}");
break;
}
}
timings.Add(new CommandTiming("osdp_CAP (PD Capabilities)", sw.Elapsed.TotalMilliseconds, true,
$"{capabilityLines.Count} capabilities"));
}
catch (Exception ex)
{
sw.Stop();
allOk = false;
timings.Add(new CommandTiming("osdp_CAP (PD Capabilities)", sw.Elapsed.TotalMilliseconds, false,
$"{ex.GetType().Name}: {ex.Message}"));
}
// --- osdp_ACURXSIZE ------------------------------------------------------
// Tells the PD how large a reply packet the ACU can accept, which is the only control the
// ACU has over PD -> ACU fragmentation. Sent during the cleartext interrogation so it is in
// effect for the pairing exchange, where message 2 is the dominant cost.
if (advertiseReceiveSize && _config.AcuReceiveSize > 0)
{
sw = Stopwatch.StartNew();
try
{
bool ok = await _panel.ACUReceiveSize(_connectionId, _config.Address, _config.AcuReceiveSize);
sw.Stop();
if (!ok) allOk = false;
timings.Add(new CommandTiming("osdp_ACURXSIZE (advertise ACU receive size)",
sw.Elapsed.TotalMilliseconds, ok,
ok ? $"{_config.AcuReceiveSize} bytes" : "PD did not ACK"));
}
catch (Exception ex)
{
sw.Stop();
allOk = false;
timings.Add(new CommandTiming("osdp_ACURXSIZE (advertise ACU receive size)",
sw.Elapsed.TotalMilliseconds, false, $"{ex.GetType().Name}: {ex.Message}"));
}
}
// --- osdp_KEYSET ---------------------------------------------------------
// Only meaningful on a secured session. The SAME key is re-installed deliberately: writing a
// fresh random key would leave the PD holding a key this run has not recorded, and recovering
// from that needs a manual PD reset. This still exercises the real KEYSET path and its reply.
if (keysetKey is not null)
{
sw = Stopwatch.StartNew();
try
{
var keyType = keysetKey.Length == 32
? KeyType.SecureChannelBaseKeyAes256
: KeyType.SecureChannelBaseKey;
bool ok = await _panel.EncryptionKeySet(_connectionId, _config.Address,
new EncryptionKeyConfiguration(keyType, keysetKey));
sw.Stop();
if (!ok) allOk = false;
timings.Add(new CommandTiming("osdp_KEYSET (re-install same SCBK)",
sw.Elapsed.TotalMilliseconds, ok, ok ? $"{keyType}, {keysetKey.Length} bytes" : "PD returned false"));
}
catch (Exception ex)
{
sw.Stop();
allOk = false;
timings.Add(new CommandTiming("osdp_KEYSET (re-install same SCBK)",
sw.Elapsed.TotalMilliseconds, false, $"{ex.GetType().Name}: {ex.Message}"));
}
}
return new DeviceQuery
{
Identity = identity,
Capabilities = capabilityLines,
Timings = timings,
ReceiveBufferSize = receiveBuffer,
LargestCombinedMessageSize = largestCombined,
Succeeded = allOk,
};
}
/// <summary>
/// Chooses the pairing fragment size from what the PD reported, honouring an explicit override.
/// </summary>
private (ushort Size, string Rationale) ResolveFragmentSize(DeviceQuery query)
{
if (_config.FragmentSizeOverride is { } forced)
{
return (forced, $"forced by --fragment-size {forced}");
}
if (query?.ReceiveBufferSize is { } buffer && buffer > 64)
{
ushort usable = BenchmarkConfig.MaxFragmentForPacket((ushort)Math.Min(buffer, ushort.MaxValue));
if (usable >= 64)
{
ushort size = Math.Min(usable, BenchmarkConfig.MaxFragmentSize);
string rationale = size < usable
? $"PD receive buffer {buffer} B packet -> {usable} B payload " +
$"(Message.CalculateMaximumMessageSize less the {BenchmarkConfig.PairingFragmentHeaderSize} B " +
$"fragment header), capped at {BenchmarkConfig.MaxFragmentSize} B"
: $"PD receive buffer {buffer} B packet -> {usable} B payload " +
$"(Message.CalculateMaximumMessageSize less the {BenchmarkConfig.PairingFragmentHeaderSize} B " +
$"fragment header)";
return (size, rationale);
}
}
return (BenchmarkConfig.DefaultFragmentSize,
query?.ReceiveBufferSize is null
? "PD did not report a receive buffer size; using the default"
: $"PD reported an unusably small receive buffer ({query.ReceiveBufferSize} B); using the default");
}
private static void PrintCommandTimings(IReadOnlyList<CommandTiming> timings, string indent = " ")
{
if (timings is null) return;
foreach (var t in timings)
{
Console.WriteLine($"{indent}{(t.Success ? " " : "! ")}{t.Ms,8:0.0} ms {t.Name}" +
(t.Success ? "" : $" <- {t.Detail}"));
}
}
private static void PrintProfile(PairingProfile profile)
{
if (profile is null) return;
Console.WriteLine(" timing profile:");