OSDP.Net 5.3.0-beta.3
A .NET library for implementing the Open Supervised Device Protocol (OSDP)
Loading...
Searching...
No Matches
ControlPanel.cs
1using System;
2using System.Collections;
3using System.Collections.Concurrent;
4using System.Collections.Generic;
5using System.Linq;
6using System.Threading;
7using System.Threading.Channels;
8using System.Threading.Tasks;
9using Microsoft.Extensions.Logging;
10using Microsoft.Extensions.Logging.Abstractions;
21
22namespace OSDP.Net
23{
28 public class ControlPanel
29 {
30 internal const byte ConfigurationAddress = 0x7f;
31
32 private readonly object _lockBusCreation = new ();
33 private readonly ConcurrentDictionary<Guid, Bus> _buses = new();
34 private readonly ILogger<ControlPanel> _logger;
35 private readonly Channel<ReplyTracker> _replies =
36 Channel.CreateUnbounded<ReplyTracker>(new UnboundedChannelOptions { SingleReader = true });
37 private TimeSpan _replyResponseTimeout = TimeSpan.FromSeconds(8);
38 private readonly ConcurrentDictionary<int, SemaphoreSlim> _requestLocks = new();
39 private readonly TimeSpan _timeToWaitToCheckOnData = TimeSpan.FromMilliseconds(10);
40 private readonly IDeviceProxyFactory _deviceProxyFactory;
41 private CancellationTokenSource _shutdownCts = new();
42 private int _inFlightCommands;
43
46 [Obsolete("Sending a ILogger is deprecated, please send ILoggerFactory instead.")]
47 public ControlPanel(ILogger<ControlPanel> logger) : this(null, null, logger) { }
48
51 public ControlPanel(ILoggerFactory loggerFactory = null) : this(null, loggerFactory, null) { }
52
53 internal ControlPanel(IDeviceProxyFactory deviceProxyFactory, ILoggerFactory loggerFactory = null)
54 : this(deviceProxyFactory, loggerFactory, null) { }
55
56 private ControlPanel(IDeviceProxyFactory deviceProxyFactory, ILoggerFactory loggerFactory,
57 ILogger<ControlPanel> logger)
58 {
59 _logger = logger
60 ?? loggerFactory?.CreateLogger<ControlPanel>()
61 ?? NullLoggerFactory.Instance.CreateLogger<ControlPanel>();
62 _deviceProxyFactory = deviceProxyFactory ?? new DeviceProxyFactory();
63
64 Task.Run(ProcessReplies);
65 }
66
67 private async Task ProcessReplies()
68 {
69 var reader = _replies.Reader;
70 while (await reader.WaitToReadAsync().ConfigureAwait(false))
71 {
72 while (reader.TryRead(out var reply))
73 {
74 try
75 {
76 OnReplyReceived(reply);
77 }
78 catch (Exception exception)
79 {
80 _logger.LogError(exception, "Error while dispatching reply {Reply}", reply);
81 }
82 }
83 }
84 }
85
91 public Guid StartConnection(IOsdpConnection connection) => StartConnection(connection, Bus.DefaultPollInterval);
92
100 public Guid StartConnection(IOsdpConnection connection, TimeSpan pollInterval, bool isTracing) =>
101 StartConnection(connection, pollInterval, isTracing ? OSDPFileCaptureTracer.Trace : _ => { });
102
109 public Guid StartConnection(IOsdpConnection connection, TimeSpan pollInterval) =>
110 StartConnection(connection, pollInterval, _ => { });
111
123 public Guid StartConnection(IOsdpConnection connection, TimeSpan pollInterval, Action<TraceEntry> tracer)
124 {
125 var newBus = CreateBus(connection, pollInterval, tracer);
126 newBus.ConnectionStatusChanged += BusOnConnectionStatusChanged;
127 newBus.StartPolling();
128 return newBus.Id;
129 }
130
137 private Bus CreateBus(IOsdpConnection connection, TimeSpan pollInterval, Action<TraceEntry> tracer)
138 {
139 // Lock while we check/create the bus. This is a very quick operation, so the lock is not a performance problem.
140 lock (_lockBusCreation)
141 {
142 var existingBusWithThisConnection = _buses.Values
143 .FirstOrDefault(bus => bus.Connection == connection);
144 if (existingBusWithThisConnection != null)
145 throw new InvalidOperationException(
146 $"The IOsdpConnection is already active in connection {existingBusWithThisConnection.Id}. " +
147 "That connection must be stopped before starting a new one.");
148
149 var newBus = new Bus(
150 connection,
151 _replies.Writer,
152 pollInterval,
153 tracer,
154 _deviceProxyFactory,
155 _logger);
156
157 _buses[newBus.Id] = newBus;
158 return newBus;
159 }
160 }
161
166 public async Task StopConnection(Guid connectionId)
167 {
168 if (!_buses.TryGetValue(connectionId, out Bus bus))
169 {
170 return;
171 }
172
173 // At this point, there might be multiple threads running concurrently trying to stop the connection.
174 // No worries, the method is reentrant. All threads will complete safely.
175
176 bus.ConnectionStatusChanged -= BusOnConnectionStatusChanged;
177 await bus.Close().ConfigureAwait(false);
178
179 foreach (byte address in bus.ConfigureDeviceAddresses)
180 {
181 // This will fire twice if two threads call StopConnection for the same connection simultaneously.
182 OnConnectionStatusChanged(bus.Id, address, false, false);
183 _requestLocks.TryRemove(new { connectionId, address }.GetHashCode(), out _);
184 }
185 bus.Dispose();
186 _buses.TryRemove(connectionId, out bus);
187 }
188
189 private void BusOnConnectionStatusChanged(object sender, Bus.ConnectionStatusEventArgs eventArgs)
190 {
191 if (sender is Bus bus)
192 OnConnectionStatusChanged(bus.Id, eventArgs.Address, eventArgs.IsConnected,
193 eventArgs.IsSecureSessionEstablished);
194 }
195
202 public async Task SendCustomCommand(Guid connectionId, byte address, CommandData command)
203 {
204 await SendCommand(connectionId, address, command).ConfigureAwait(false);
205 }
206
213 public void EnqueueCustomCommand(Guid connectionId, byte address, CommandData command)
214 {
215 if (!_buses.TryGetValue(connectionId, out var bus))
216 {
217 throw new ArgumentException("Connection could not be found", nameof(connectionId));
218 }
219
220 bus.SendCommand(address, command);
221 }
222
227 public async Task<DeviceIdentification> IdReport(Guid connectionId, byte address) =>
228 await IdReport(connectionId, address, CancellationToken.None).ConfigureAwait(false);
229
235 public async Task<DeviceIdentification> IdReport(Guid connectionId, byte address, CancellationToken cancellationToken)
236 {
237 var message = await SendCommand(
238 connectionId,
239 address,
240 new IdReport(),
241 cancellationToken).ConfigureAwait(false);
242
243 return DeviceIdentification.ParseData(message.Payload);
244 }
245
253 public async Task<ExtendedDeviceIdentification> ExtendedIdReport(Guid connectionId, byte address,
254 TimeSpan timeout, CancellationToken cancellationToken = default)
255 {
256 using var scope = await BeginCommandAsync(connectionId, address, timeout, cancellationToken);
257 return await WaitForExtendedIdData(connectionId, address, timeout, scope.Token);
258 }
259
260 private async Task<T> WaitForMultiPartData<T>(
261 Guid connectionId,
262 byte address,
263 TimeSpan timeout,
264 CommandData command,
265 Func<byte[], T> parser,
266 Action<EventHandler<MultiPartMessageDataReplyEventArgs>> subscribe,
267 Action<EventHandler<MultiPartMessageDataReplyEventArgs>> unsubscribe,
268 CancellationToken cancellationToken)
269 {
270 bool complete = false;
271 byte[] data = null;
272
273 void Handler(object sender, MultiPartMessageDataReplyEventArgs args)
274 {
275 // Only process matching replies
276 if (args.ConnectionId != connectionId || args.Address != address) return;
277
278 var fragment = args.DataFragmentResponse;
279 data ??= new byte[fragment.WholeMessageLength];
280
281 complete = Message.BuildMultiPartMessageData(fragment.WholeMessageLength, fragment.Offset,
282 fragment.LengthOfFragment, fragment.Data, data);
283 }
284
285 subscribe(Handler);
286 SetReceivingMultipartMessaging(connectionId, address, true);
287
288 try
289 {
290 await SendCommand(connectionId, address, command, cancellationToken, throwOnNak: false)
291 .ConfigureAwait(false);
292
293 DateTime endTime = DateTime.UtcNow + timeout;
294
295 while (DateTime.UtcNow <= endTime)
296 {
297 if (complete)
298 {
299 return parser(data);
300 }
301
302 await Task.Delay(_timeToWaitToCheckOnData, cancellationToken);
303 }
304
305 throw new TimeoutException("Timeout waiting to receive multi-part data.");
306 }
307 finally
308 {
309 unsubscribe(Handler);
310 SetReceivingMultipartMessaging(connectionId, address, false);
311 }
312 }
313
314 private async Task<ExtendedDeviceIdentification> WaitForExtendedIdData(Guid connectionId, byte address,
315 TimeSpan timeout, CancellationToken cancellationToken)
316 {
317 return await WaitForMultiPartData(
318 connectionId,
319 address,
320 timeout,
321 new IdReport(requestExtended: true),
322 data => ExtendedDeviceIdentification.ParseData(data),
323 handler => ExtendedIdReplyReceived += handler,
324 handler => ExtendedIdReplyReceived -= handler,
325 cancellationToken).ConfigureAwait(false);
326 }
327
332 public async Task<DeviceCapabilities> DeviceCapabilities(Guid connectionId, byte address)
333 {
334 return Model.ReplyData.DeviceCapabilities.ParseData((await SendCommand(
335 connectionId,
336 address,
337 new Model.CommandData.DeviceCapabilities()).ConfigureAwait(false)).Payload);
338 }
339
346 public async Task<LocalStatus> LocalStatus(Guid connectionId, byte address)
347 {
348 return Model.ReplyData.LocalStatus.ParseData((await SendCommand(
349 connectionId,
350 address,
351 new NoPayloadCommandData(CommandType.LocalStatus)).ConfigureAwait(false)).Payload);
352 }
353
360 public async Task<InputStatus> InputStatus(Guid connectionId, byte address)
361 {
362 return Model.ReplyData.InputStatus.ParseData((await SendCommand(
363 connectionId,
364 address,
365 new NoPayloadCommandData(CommandType.InputStatus)).ConfigureAwait(false)).Payload);
366 }
367
374 public async Task<OutputStatus> OutputStatus(Guid connectionId, byte address)
375 {
376 return Model.ReplyData.OutputStatus.ParseData((await SendCommand(
377 connectionId,
378 address,
379 new NoPayloadCommandData(CommandType.OutputStatus)).ConfigureAwait(false)).Payload);
380 }
381
391 public async Task<byte[]> GetPIVData(Guid connectionId, byte address, GetPIVData getPIVData, TimeSpan timeout,
392 CancellationToken cancellationToken = default)
393 {
394 using var scope = await BeginCommandAsync(connectionId, address, timeout, cancellationToken);
395 return await WaitForPIVData(connectionId, address, getPIVData, timeout, scope.Token);
396 }
397
398 private SemaphoreSlim GetRequestLock(Guid connectionId, byte address)
399 {
400 int hash = new { connectionId, address }.GetHashCode();
401
402 if (_requestLocks.TryGetValue(hash, out var requestLock))
403 {
404 return requestLock;
405 }
406
407 var newRequestLock = new SemaphoreSlim(1, 1);
408 _requestLocks[hash] = newRequestLock;
409 return newRequestLock;
410 }
411
412 private async Task<CommandScope> BeginCommandAsync(Guid connectionId, byte address, TimeSpan timeout,
413 CancellationToken cancellationToken)
414 {
415 var linkedCts =
416 CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _shutdownCts.Token);
417 Interlocked.Increment(ref _inFlightCommands);
418 try
419 {
420 var requestLock = GetRequestLock(connectionId, address);
421 if (!await requestLock.WaitAsync(timeout, linkedCts.Token).ConfigureAwait(false))
422 {
423 throw new TimeoutException("Timeout waiting for another request to complete.");
424 }
425 return new CommandScope(this, requestLock, linkedCts);
426 }
427 catch
428 {
429 linkedCts.Dispose();
430 Interlocked.Decrement(ref _inFlightCommands);
431 throw;
432 }
433 }
434
435 private sealed class CommandScope : IDisposable
436 {
437 private readonly ControlPanel _owner;
438 private readonly SemaphoreSlim _requestLock;
439 private readonly CancellationTokenSource _linkedCts;
440
441 public CommandScope(ControlPanel owner, SemaphoreSlim requestLock, CancellationTokenSource linkedCts)
442 {
443 _owner = owner;
444 _requestLock = requestLock;
445 _linkedCts = linkedCts;
446 }
447
448 public CancellationToken Token => _linkedCts.Token;
449
450 public void Dispose()
451 {
452 _requestLock.Release();
453 _linkedCts.Dispose();
454 Interlocked.Decrement(ref _owner._inFlightCommands);
455 }
456 }
457
458 private async Task<byte[]> WaitForPIVData(Guid connectionId, byte address, GetPIVData getPIVData, TimeSpan timeout,
459 CancellationToken cancellationToken)
460 {
461 return await WaitForMultiPartData(
462 connectionId,
463 address,
464 timeout,
465 getPIVData,
466 data => data,
467 handler => PIVDataReplyReceived += handler,
468 handler => PIVDataReplyReceived -= handler,
469 cancellationToken).ConfigureAwait(false);
470 }
471
478 public async Task<ReaderStatus> ReaderStatus(Guid connectionId, byte address)
479 {
480 return Model.ReplyData.ReaderStatus.ParseData((await SendCommand(connectionId, address,
481 new NoPayloadCommandData(CommandType.ReaderStatus)).ConfigureAwait(false)).Payload);
482 }
483
491 public async Task<ReturnReplyData<ManufacturerSpecific>> ManufacturerSpecificCommand(Guid connectionId,
492 byte address,
493 Model.CommandData.ManufacturerSpecific manufacturerSpecific)
494 {
495 var reply = await SendCommand(connectionId, address, manufacturerSpecific).ConfigureAwait(false);
496
497 return new ReturnReplyData<ManufacturerSpecific>
498 {
499 Ack = reply.Type == (byte)ReplyType.Ack,
500 ReplyData = reply.Type == (byte)ReplyType.ManufactureSpecific
501 ? ManufacturerSpecific.ParseData(reply.Payload)
502 : null
503 };
504 }
505
514 public async Task<ReturnReplyData<ExtendedRead>> ExtendedWriteData(Guid connectionId, byte address,
515 ExtendedWrite extendedWrite)
516 {
517 var reply = await SendCommand(connectionId, address, extendedWrite).ConfigureAwait(false);
518
519 return new ReturnReplyData<ExtendedRead>
520 {
521 Ack = reply.Type == (byte)ReplyType.Ack,
522 ReplyData = reply.Type == (byte)ReplyType.ExtendedRead
523 ? ExtendedRead.ParseData(reply.Payload)
524 : null
525 };
526 }
527
538 public async Task<ReturnReplyData<ManufacturerSpecific>> ManufacturerSpecificCommand(Guid connectionId, byte address,
539 Model.CommandData.ManufacturerSpecific manufacturerSpecific, ushort maximumFragmentSize, TimeSpan timeout,
540 CancellationToken cancellationToken = default)
541 {
542 using var scope = await BeginCommandAsync(connectionId, address, timeout, cancellationToken);
543 return await WaitForManufactureResponse(connectionId, address, manufacturerSpecific, maximumFragmentSize,
544 scope.Token);
545 }
546
547 private async Task<ReturnReplyData<ManufacturerSpecific>> WaitForManufactureResponse(Guid connectionId, byte address,
548 Model.CommandData.ManufacturerSpecific manufacturerSpecific, ushort maximumFragmentSize, CancellationToken cancellationToken)
549 {
550 SetReceivingMultipartMessaging(connectionId, address, true);
551
552 var manufactureCommandCode = manufacturerSpecific.Data.Skip(0).Take(1).ToArray();
553 var manufactureCommandData = manufacturerSpecific.Data.Skip(1).ToArray();
554 ushort totalSize = (ushort)manufactureCommandData.Length;
555 ushort offset = 0;
556 bool continueTransfer = true;
557 IncomingMessage reply = null;
558
559 try
560 {
561 while (!cancellationToken.IsCancellationRequested && continueTransfer)
562 {
563 ushort fragmentSize = (ushort)Math.Min(maximumFragmentSize, totalSize - offset);
564 reply = await SendCommand(connectionId, address, new Model.CommandData.ManufacturerSpecific(
565 manufacturerSpecific.VendorCode, manufactureCommandCode.Concat(
566 new MessageDataFragment(totalSize, offset, fragmentSize,
567 manufactureCommandData.Skip(offset).Take(fragmentSize).ToArray(),
568 MessageDataFragmentFieldSize.FourBytes).BuildData()
569 .ToArray()).ToArray()), cancellationToken)
570 .ConfigureAwait(false);
571
572 if (reply.Type != (byte)ReplyType.Ack) break;
573
574 offset += maximumFragmentSize;
575
576 // Determine if we should continue on successful status
577 continueTransfer = offset < totalSize;
578 }
579
580 if (reply == null)
581 {
582 throw new Exception("Command didn't return a valid reply");
583 }
584
585 return new ReturnReplyData<ManufacturerSpecific>
586 {
587 Ack = reply.Type == (byte)ReplyType.Ack,
589 };
590 }
591 finally
592 {
593 SetReceivingMultipartMessaging(connectionId, address, false);
594 }
595 }
596
604 public async Task<ReturnReplyData<OutputStatus>> OutputControl(Guid connectionId, byte address,
605 OutputControls outputControls)
606 {
607 var reply = await SendCommand(connectionId, address, outputControls).ConfigureAwait(false);
608
609 return new ReturnReplyData<OutputStatus>
610 {
611 Ack = reply.Type == (byte)ReplyType.Ack,
612 ReplyData = reply.Type == (byte)ReplyType.OutputStatusReport
613 ? Model.ReplyData.OutputStatus.ParseData(reply.Payload)
614 : null
615 };
616 }
617
625 public async Task<bool> ReaderLedControl(Guid connectionId, byte address, ReaderLedControls readerLedControls)
626 {
627 var reply = await SendCommand(connectionId, address, readerLedControls).ConfigureAwait(false);
628
629 return reply.Type == (byte)ReplyType.Ack;
630 }
631
639 public async Task<bool> ReaderBuzzerControl(Guid connectionId, byte address,
640 ReaderBuzzerControl readerBuzzerControl)
641 {
642 var reply = await SendCommand(connectionId, address, readerBuzzerControl).ConfigureAwait(false);
643
644 return reply.Type == (byte)ReplyType.Ack;
645 }
646
654 public async Task<bool> ReaderTextOutput(Guid connectionId, byte address, ReaderTextOutput readerTextOutput)
655 {
656 var reply = await SendCommand(connectionId, address, readerTextOutput).ConfigureAwait(false);
657
658 return reply.Type == (byte)ReplyType.Ack;
659 }
660
669 byte address, CommunicationConfiguration communicationConfiguration)
670 {
671 if (_buses.Any(bus =>
672 bus.Key == connectionId &&
673 address != communicationConfiguration.Address &&
674 bus.Value.ConfigureDeviceAddresses.Any(configuredAddress =>
675 configuredAddress == communicationConfiguration.Address)))
676 {
677 throw new Exception("Address is already configured on the bus.");
678 }
679
681 (await SendCommand(connectionId, address, communicationConfiguration).ConfigureAwait(false))
682 .Payload);
683 }
684
692 public async Task<bool> EncryptionKeySet(Guid connectionId, byte address,
693 EncryptionKeyConfiguration encryptionKeyConfiguration)
694 {
695 var reply = await SendCommand(connectionId, address, encryptionKeyConfiguration).ConfigureAwait(false);
696
697 return reply.Type == (byte)ReplyType.Ack;
698 }
699
712 public Task<Model.ReplyData.FileTransferStatus.StatusDetail> FileTransfer(Guid connectionId, byte address, byte fileType, byte[] fileData, ushort fragmentSize,
713 Action<FileTransferStatus> callback, CancellationToken cancellationToken = default)
714 {
715 var bus = _buses[connectionId];
716 return Task.Run(async () =>
717 {
718 bus.SetSendingMultipartMessage(address, true);
719 try
720 {
721 return await SendFileTransferCommands(connectionId, address, fileType, fileData, fragmentSize, callback,
722 cancellationToken);
723 }
724 finally
725 {
726 bus.SetSendingMultipartMessage(address, false);
727 bus.SetSendingMultiMessageNoSecureChannel(address, false);
728 }
729 }, cancellationToken);
730 }
731
732 private async Task<Model.ReplyData.FileTransferStatus.StatusDetail> SendFileTransferCommands(Guid connectionId,
733 byte address, byte fileType, byte[] fileData,
734 ushort fragmentSize, Action<FileTransferStatus> callback, CancellationToken cancellationToken)
735 {
736 int totalSize = fileData.Length;
737 int offset = 0;
738 bool isFirstMessage = true;
739
740 // Keep going until
741 // * operation's cancelled
742 // * an error occurs
743 // * transfer's completed
744 while (true)
745 {
746 cancellationToken.ThrowIfCancellationRequested();
747
748 // Get the fragment size if it doesn't exceed the total size
749 var nextFragmentSize = (ushort)Math.Min(fragmentSize, totalSize - offset);
750
751 var reply = await SendCommand(connectionId, address,
752 new FileTransferFragment(fileType,
753 new MessageDataFragment(totalSize, offset, nextFragmentSize,
754 fileData.Skip(offset).Take(nextFragmentSize).ToArray(),
756 cancellationToken, throwOnNak: false)
757 .ConfigureAwait(false);
758
759 // On the first message, calculate the proper fragment size based on whether encryption is being used
760 if (isFirstMessage)
761 {
762 isFirstMessage = false;
763 fragmentSize = Message.CalculateMaximumMessageSize(fragmentSize, reply.IsSecureMessage);
764 }
765
766 // Update offset
767 offset += nextFragmentSize;
768
769 // Parse the fileTransfer status
770 var fileTransferStatusReply = reply.Type == (byte)ReplyType.FileTransferStatus
771 ? Model.ReplyData.FileTransferStatus.ParseData(reply.Payload)
772 : null;
773
774 // Check reply to see if PD has requested some change in com procedures.
775 if (fileTransferStatusReply != null)
776 {
777 // Leave the secure channel if needed
778 if ((fileTransferStatusReply.Action &
779 Model.ReplyData.FileTransferStatus.ControlFlags.LeaveSecureChannel) ==
781 {
782 _buses[connectionId].SetSendingMultiMessageNoSecureChannel(address, true);
783 }
784
785 // Set request delay if specified
786 if (fileTransferStatusReply is { RequestedDelay: > 0 })
787 {
788 _buses[connectionId].SetRequestDelay(address,
789 DateTime.UtcNow.AddMilliseconds(fileTransferStatusReply.RequestedDelay));
790 }
791
792 // Set fragment size if requested
793 if (fileTransferStatusReply is { UpdateMessageMaximum: > 0 })
794 {
795 fragmentSize = Message.CalculateMaximumMessageSize(fileTransferStatusReply.UpdateMessageMaximum,
796 reply.IsSecureMessage);
797 }
798 }
799
800 var status = new FileTransferStatus(
801 fileTransferStatusReply?.Detail ?? Model.ReplyData.FileTransferStatus.StatusDetail.UnknownError,
802 offset,
803 reply.Type == (byte)ReplyType.Nak ? Nak.ParseData(reply.Payload) : null);
804
805 // Report status to progress listeners
806 callback(status);
807
808 switch (status.Status)
809 {
810 // Abort transfer on error.
811 case < 0:
812 throw new FileTransferException("File transfer failed", status);
813 // File transfer is completed, but PD wants us to keep sending "idling" file transfer message (FtFragmentSize = 0) until we receive another status.
814 case Model.ReplyData.FileTransferStatus.StatusDetail.FinishingFileTransfer:
815 fragmentSize = 0;
816 break;
817 default:
818 {
819 if (offset >= totalSize)
820 {
821 // We're done. Return the last successful (=positive) status code.
822 return status.Status;
823 }
824
825 break;
826 }
827 }
828 }
829 }
830
840 public async Task<BiometricReadResult> ScanAndSendBiometricData(Guid connectionId, byte address,
841 BiometricReadData biometricReadData, TimeSpan timeout,
842 CancellationToken cancellationToken = default)
843 {
844 using var scope = await BeginCommandAsync(connectionId, address, timeout, cancellationToken);
845 return await WaitForBiometricRead(connectionId, address, biometricReadData, timeout, scope.Token);
846 }
847
848 private async Task<BiometricReadResult> WaitForBiometricRead(Guid connectionId, byte address,
849 BiometricReadData biometricReadData, TimeSpan timeout,
850 CancellationToken cancellationToken)
851 {
852 bool complete = false;
853 BiometricReadResult result = null;
854
855 void Handler(object sender, BiometricReadResultsReplyEventArgs args)
856 {
857 // Only process matching replies
858 if (args.ConnectionId != connectionId || args.Address != address) return;
859
860 complete = true;
861
862 result = args.BiometricReadResult;
863 }
864
865 BiometricReadResultsReplyReceived += Handler;
866 SetReceivingMultipartMessaging(connectionId, address, true);
867
868 try
869 {
870 await SendCommand(connectionId, address, biometricReadData, cancellationToken, throwOnNak: false)
871 .ConfigureAwait(false);
872
873 DateTime endTime = DateTime.UtcNow + timeout;
874
875 while (DateTime.UtcNow <= endTime)
876 {
877 if (complete)
878 {
879 return result;
880 }
881
882 await Task.Delay(_timeToWaitToCheckOnData, cancellationToken);
883 }
884
885 throw new TimeoutException("Timeout waiting to for biometric read data.");
886 }
887 finally
888 {
889 BiometricReadResultsReplyReceived -= Handler;
890 SetReceivingMultipartMessaging(connectionId, address, false);
891 }
892 }
893
894
904 public async Task<BiometricMatchResult> ScanAndMatchBiometricTemplate(Guid connectionId, byte address,
905 BiometricTemplateData biometricTemplateData, TimeSpan timeout,
906 CancellationToken cancellationToken = default)
907 {
908 using var scope = await BeginCommandAsync(connectionId, address, timeout, cancellationToken);
909 return await WaitForBiometricMatch(connectionId, address, biometricTemplateData, timeout, scope.Token);
910 }
911
912 private async Task<BiometricMatchResult> WaitForBiometricMatch(Guid connectionId, byte address,
913 BiometricTemplateData biometricTemplateData, TimeSpan timeout,
914 CancellationToken cancellationToken)
915 {
916 bool complete = false;
917 BiometricMatchResult result = null;
918
919 void Handler(object sender, BiometricMatchReplyEventArgs args)
920 {
921 // Only process matching replies
922 if (args.ConnectionId != connectionId || args.Address != address) return;
923
924 complete = true;
925
926 result = args.BiometricMatchResult;
927 }
928
929 BiometricMatchReplyReceived += Handler;
930 SetReceivingMultipartMessaging(connectionId, address, true);
931
932 try
933 {
934 await SendCommand(connectionId, address, biometricTemplateData, cancellationToken, throwOnNak: false)
935 .ConfigureAwait(false);
936
937 DateTime endTime = DateTime.UtcNow + timeout;
938
939 while (DateTime.UtcNow <= endTime)
940 {
941 if (complete)
942 {
943 return result;
944 }
945
946 await Task.Delay(_timeToWaitToCheckOnData, cancellationToken);
947 }
948
949 throw new TimeoutException("Timeout waiting to for biometric match.");
950 }
951 finally
952 {
953 BiometricMatchReplyReceived -= Handler;
954 SetReceivingMultipartMessaging(connectionId, address, false);
955 }
956 }
957
970 public async Task<byte[]> AuthenticationChallenge(Guid connectionId, byte address,
971 byte algorithm, byte key, byte[] challenge, ushort maximumFragmentSize, TimeSpan timeout,
972 CancellationToken cancellationToken = default)
973 {
974 using var scope = await BeginCommandAsync(connectionId, address, timeout, cancellationToken);
975 return await WaitForChallengeResponse(connectionId, address, algorithm, key, challenge, maximumFragmentSize,
976 timeout, scope.Token);
977 }
978
979 private async Task<byte[]> WaitForChallengeResponse(Guid connectionId, byte address, byte algorithm, byte key,
980 byte[] challenge, ushort maximumFragmentSize, TimeSpan timeout,
981 CancellationToken cancellationToken)
982 {
983 bool complete = false;
984 var requestData = new List<byte> { algorithm, key };
985 requestData.AddRange(challenge);
986 byte[] responseData = null;
987
988 void Handler(object sender, MultiPartMessageDataReplyEventArgs args)
989 {
990 // Only process matching replies
991 if (args.ConnectionId != connectionId || args.Address != address) return;
992
993 var dataFragmentResponse = args.DataFragmentResponse;
994 responseData ??= new byte[dataFragmentResponse.WholeMessageLength];
995
996 complete = Message.BuildMultiPartMessageData(dataFragmentResponse.WholeMessageLength, dataFragmentResponse.Offset,
997 dataFragmentResponse.LengthOfFragment, dataFragmentResponse.Data, responseData);
998 }
999
1000 AuthenticationChallengeResponseReceived += Handler;
1001 SetReceivingMultipartMessaging(connectionId, address, true);
1002
1003 ushort totalSize = (ushort)requestData.Count;
1004 ushort offset = 0;
1005 bool continueTransfer = true;
1006
1007 try
1008 {
1009 while (!cancellationToken.IsCancellationRequested && continueTransfer)
1010 {
1011 ushort fragmentSize = (ushort)Math.Min(maximumFragmentSize, totalSize - offset);
1012 await SendCommand(connectionId, address, new AuthenticationChallengeFragment(
1013 new MessageDataFragment(totalSize, offset, fragmentSize,
1014 requestData.Skip(offset).Take((ushort)Math.Min(fragmentSize, totalSize - offset))
1015 .ToArray(),
1016 MessageDataFragmentFieldSize.TwoBytes)), cancellationToken)
1017 .ConfigureAwait(false);
1018
1019 offset += fragmentSize;
1020
1021 // Determine if we should continue on successful status
1022 continueTransfer = offset < totalSize;
1023 }
1024
1025 DateTime endTime = DateTime.UtcNow + timeout;
1026
1027 while (DateTime.UtcNow <= endTime)
1028 {
1029 if (complete)
1030 {
1031 return responseData;
1032 }
1033
1034 await Task.Delay(_timeToWaitToCheckOnData, cancellationToken);
1035 }
1036
1037 throw new TimeoutException("Timeout waiting to receive challenge response.");
1038 }
1039 finally
1040 {
1041 AuthenticationChallengeResponseReceived -= Handler;
1042 SetReceivingMultipartMessaging(connectionId, address, false);
1043 }
1044 }
1045
1053 public async Task<bool> ACUReceiveSize(Guid connectionId, byte address, ushort maximumReceiveSize)
1054 {
1055 var reply = await SendCommand(connectionId, address, new ACUReceiveSize(maximumReceiveSize))
1056 .ConfigureAwait(false);
1057
1058 return reply.Type == (byte)ReplyType.Ack;
1059 }
1060
1068 public async Task<bool> KeepReaderActive(Guid connectionId, byte address, ushort keepAliveTimeInMilliseconds)
1069 {
1070 var reply = await SendCommand(connectionId, address, new KeepReaderActive(keepAliveTimeInMilliseconds))
1071 .ConfigureAwait(false);
1072
1073 return reply.Type == (byte)ReplyType.Ack;
1074 }
1075
1082 public async Task<bool> AbortCurrentOperation(Guid connectionId, byte address)
1083 {
1084 var reply = await SendCommand(connectionId, address, new NoPayloadCommandData(CommandType.Abort))
1085 .ConfigureAwait(false);
1086
1087 return reply.Type == (byte)ReplyType.Ack;
1088 }
1089
1096 public bool IsOnline(Guid connectionId, byte address)
1097 {
1098 return _buses[connectionId].IsOnline(address);
1099 }
1100
1101 private void SetReceivingMultipartMessaging(Guid connectionId, byte address, bool isReceivingMultipartMessaging)
1102 {
1103 if (!_buses.TryGetValue(connectionId, out var bus))
1104 {
1105 throw new ArgumentException("Connection could not be found", nameof(connectionId));
1106 }
1107
1108 bus.SetReceivingMultipartMessage(address, isReceivingMultipartMessaging);
1109 }
1110
1111 private async Task<IncomingMessage> SendCommand(Guid connectionId, byte address, CommandData command,
1112 CancellationToken cancellationToken = default, bool throwOnNak = true)
1113 {
1114 var source = new TaskCompletionSource<IncomingMessage>();
1115
1116 void EventHandler(object sender, ReplyEventArgs replyEventArgs)
1117 {
1118 var reply = replyEventArgs.Reply;
1119 if (!reply.MatchIssuingCommand(address, command.Code)) return;
1120
1121 if (throwOnNak && replyEventArgs.Reply.ReplyMessage.Type == (byte)ReplyType.Nak)
1122 {
1123 source.SetException(new NackReplyException(Nak.ParseData(reply.ReplyMessage.Payload)));
1124 }
1125 else
1126 {
1127 source.SetResult(reply.ReplyMessage);
1128 }
1129 }
1130
1131 if (!_buses.TryGetValue(connectionId, out var bus))
1132 {
1133 throw new ArgumentException("Connection could not be found", nameof(connectionId));
1134 }
1135
1136 ReplyReceived += EventHandler;
1137
1138 try
1139 {
1140 bus.SendCommand(address, command);
1141
1142 var task = await Task.WhenAny(
1143 source.Task, Task.Delay(_replyResponseTimeout, cancellationToken)).ConfigureAwait(false);
1144
1145 if (source.Task != task)
1146 {
1147 throw task.IsCanceled
1148 ? new OperationCanceledException(cancellationToken)
1149 : new TimeoutException();
1150 }
1151
1152 return await source.Task;
1153 }
1154 finally
1155 {
1156 ReplyReceived -= EventHandler;
1157 }
1158 }
1159
1163 public async Task Shutdown()
1164 {
1165 var shutdownCts = _shutdownCts;
1166 shutdownCts.Cancel();
1167
1168 foreach (var bus in _buses.Values)
1169 {
1170 bus.ConnectionStatusChanged -= BusOnConnectionStatusChanged;
1171 await bus.Close().ConfigureAwait(false);
1172
1173 foreach (byte address in bus.ConfigureDeviceAddresses)
1174 {
1175 OnConnectionStatusChanged(bus.Id, address, false, false);
1176 }
1177 bus.Dispose();
1178 }
1179 _buses.Clear();
1180
1181 while (Volatile.Read(ref _inFlightCommands) > 0)
1182 {
1183 await Task.Delay(_timeToWaitToCheckOnData).ConfigureAwait(false);
1184 }
1185
1186 foreach (var requestLock in _requestLocks.Values)
1187 {
1188 requestLock.Dispose();
1189 }
1190 _requestLocks.Clear();
1191
1192 _shutdownCts = new CancellationTokenSource();
1193 shutdownCts.Dispose();
1194
1195 OSDPFileCaptureTracer.CloseAllWriters();
1196 }
1197
1203 public void ResetDevice(Guid connectionId, int address)
1204 {
1205 if (_buses.TryGetValue(connectionId, out Bus bus))
1206 {
1207 bus.ResetDevice(address);
1208 }
1209 }
1210
1219 public void AddDevice(Guid connectionId, byte address, bool useCrc, bool useSecureChannel, byte[] secureChannelKey = null)
1220 {
1221 if (!_buses.TryGetValue(connectionId, out Bus foundBus))
1222 {
1223 throw new ArgumentException("Connection could not be found", nameof(connectionId));
1224 }
1225
1226 if (address > 127)
1227 {
1228 throw new ArgumentOutOfRangeException(nameof(address), "Address is out of range, it must between 0 and 127.");
1229 }
1230
1231 foundBus.AddDevice(address, useCrc, useSecureChannel, useSecureChannel ? secureChannelKey : null);
1232 }
1233
1239 public void RemoveDevice(Guid connectionId, byte address)
1240 {
1241 if (_buses.TryGetValue(connectionId, out Bus bus))
1242 {
1243 bus.RemoveDevice(address);
1244 }
1245 }
1246
1261 public async Task<DiscoveryResult> DiscoverDevice(IEnumerable<IOsdpConnection> connections, DiscoveryOptions options = null)
1262 {
1263 options ??= new DiscoveryOptions();
1264 DiscoveryResult result = new();
1265 Guid connectionId = Guid.Empty;
1266
1267 // ReSharper disable AccessToModifiedClosure
1268 // Disable the warning which doesn't apply to us as we are accumulating/modifying results of the discovery
1269 // in the above variables which are closed over. We are good with with
1270
1271 void UpdateStatus(DiscoveryStatus status)
1272 {
1273 result.Status = status;
1274 options.ProgressCallback?.Invoke(result);
1275 }
1276
1277 async Task<DeviceIdentification> TryIdReport(byte address)
1278 {
1279 try
1280 {
1281 return await IdReport(connectionId, address, options.CancellationToken).ConfigureAwait(false);
1282 }
1283 catch (TimeoutException)
1284 {
1285 return null;
1286 }
1287 }
1288
1289 async Task<bool> FindConnectionWithActiveDevice()
1290 {
1291 bool isFirst = true;
1292
1293 foreach (IOsdpConnection connection in connections)
1294 {
1295 if (!isFirst)
1296 {
1297 await Task.Delay(options.ReconnectDelay, options.CancellationToken);
1298 }
1299 isFirst = false;
1300
1301 // WARNING: We are specifying zero timespan here so that Polling is
1302 // DISABLED on this entire connection. If we don't do this, it seems
1303 // non-existent devices will attempt to start polling and those commands
1304 // ends up getting "stuck" so that even when we get to the valid device
1305 // we'll end up timing out and not finding it :(
1306 // Polling on "other" devices should be doing this, but there's something
1307 // funky in there. If the device we are looking for happens to be at addr
1308 // 0, everything will work, but anything else doesn't unless we disable
1309 // polling
1310 connectionId = StartConnection(connection, TimeSpan.Zero, options.Tracer ?? (_ => {}));
1311
1312 AddDevice(connectionId, ConfigurationAddress, true, false);
1313
1314 result.Connection = connection;
1315 UpdateStatus(DiscoveryStatus.LookingForDeviceOnConnection);
1316
1317 var deviceIdentification = await TryIdReport(ConfigurationAddress).ConfigureAwait(false);
1318 if (deviceIdentification != null)
1319 {
1320 result.Id = deviceIdentification;
1321 RemoveDevice(connectionId, ConfigurationAddress);
1322 await StopConnection(connectionId).ConfigureAwait(false);
1323 UpdateStatus(DiscoveryStatus.ConnectionWithDeviceFound);
1324 return true;
1325 }
1326
1327 await StopConnection(connectionId).ConfigureAwait(false);
1328 }
1329
1330 result.Connection = null;
1331 return false;
1332 }
1333
1334 async Task<bool> FindDeviceAddress()
1335 {
1336 connectionId = StartConnection(result.Connection, TimeSpan.Zero, options.Tracer ?? (_ => {}));
1337 for (byte address = 0; address < ConfigurationAddress; address++)
1338 {
1339 AddDevice(connectionId, address, true, false);
1340
1341 result.Address = address;
1342 UpdateStatus(DiscoveryStatus.LookingForDeviceAtAddress);
1343 var deviceIdentification = await TryIdReport(address).ConfigureAwait(false);
1344
1345 if (deviceIdentification != null)
1346 {
1347 result.Id = deviceIdentification;
1348 UpdateStatus(DiscoveryStatus.DeviceIdentified);
1349 return true;
1350 }
1351
1352 RemoveDevice(connectionId, address);
1353 }
1354 await StopConnection(connectionId).ConfigureAwait(false);
1355
1356 // Since we didn't find a valid device, for an unexpected reason
1357 // let's just leave the at the configuration address
1358 result.Address = ConfigurationAddress;
1359 return false;
1360 }
1361
1362 async Task CheckForDefaultSecurityKey()
1363 {
1364 // A PD that reports no AES128 support can't accept the default key, so don't bother asking.
1365 // A PD that leaves the capability out is still asked.
1366 var communicationSecurity = result.Capabilities?.Get(CapabilityFunction.CommunicationSecurity);
1367 if (communicationSecurity != null && (communicationSecurity.Compliance & 0x01) == 0)
1368 {
1369 result.UsesDefaultSecurityKey = false;
1370 return;
1371 }
1372
1373 // Both handlers run on the bus polling thread, and the PD keeps getting asked until the
1374 // connection is stopped, so the first answer wins and the rest are ignored
1375 var defaultKeyCheck =
1376 new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
1377
1378 void HandleStatusChange(object sender, ConnectionStatusEventArgs args)
1379 {
1380 if (args.ConnectionId == connectionId && args.Address == result.Address &&
1382 {
1383 defaultKeyCheck.TrySetResult(true);
1384 }
1385 }
1386
1387 void HandleHandshakeFailed(object sender, Bus.SecureChannelHandshakeFailedEventArgs args)
1388 {
1389 if (args.Address == result.Address)
1390 {
1391 defaultKeyCheck.TrySetResult(false);
1392 }
1393 }
1394
1395 Bus bus = null;
1396 ConnectionStatusChanged += HandleStatusChange;
1397
1398 try
1399 {
1400 connectionId = StartConnection(result.Connection, Bus.DefaultPollInterval,
1401 options.Tracer ?? (_ => { }));
1402
1403 // Subscribe before the device is added so the first handshake reply can't be missed
1404 bus = _buses[connectionId];
1405 bus.SecureChannelHandshakeFailed += HandleHandshakeFailed;
1406 AddDevice(connectionId, result.Address, true, true);
1407
1408 // A PD that never answers the handshake still needs the timeout
1409 using var timeoutCancellation =
1410 CancellationTokenSource.CreateLinkedTokenSource(options.CancellationToken);
1411 var completedTask = await Task.WhenAny(defaultKeyCheck.Task,
1412 Task.Delay(TimeSpan.FromSeconds(8), timeoutCancellation.Token)).ConfigureAwait(false);
1413 timeoutCancellation.Cancel();
1414
1415 if (completedTask != defaultKeyCheck.Task)
1416 {
1417 options.CancellationToken.ThrowIfCancellationRequested();
1418 }
1419
1420 result.UsesDefaultSecurityKey = completedTask == defaultKeyCheck.Task &&
1421 await defaultKeyCheck.Task.ConfigureAwait(false);
1422 }
1423 finally
1424 {
1425 ConnectionStatusChanged -= HandleStatusChange;
1426 if (bus != null) bus.SecureChannelHandshakeFailed -= HandleHandshakeFailed;
1427 }
1428 }
1429
1430 UpdateStatus(DiscoveryStatus.Started);
1431
1432 // While we are doing discovery, we want to override default behavior which allows
1433 // underlying wire protocols to retry things if something goes wrong. In the
1434 // interests for time while cycling through every possible address, we are going to
1435 // not be as gracious
1436 var origResponseTimeout = _replyResponseTimeout;
1437 _replyResponseTimeout = options.ResponseTimeout;
1438
1439 try
1440 {
1441 if (!_buses.IsEmpty)
1442 {
1443 throw new ControlPanelInUseException();
1444 }
1445
1446 if (!await FindConnectionWithActiveDevice().ConfigureAwait(false))
1447 {
1448 UpdateStatus(DiscoveryStatus.DeviceNotFound);
1449 return null;
1450 }
1451
1452 if (!await FindDeviceAddress().ConfigureAwait(false))
1453 {
1454 throw new DeviceDiscoveryException(
1455 $"Unable to determine address of device that responded to a configuration address on baud rate {result.Connection.BaudRate}");
1456 }
1457
1458 result.Capabilities = await DeviceCapabilities(connectionId, result.Address).ConfigureAwait(false);
1459 UpdateStatus(DiscoveryStatus.CapabilitiesDiscovered);
1460
1461 // Connection above was opened intentionally with no polling (see above comments). Now we
1462 // need to open a new connection with polling before doing the next step
1463 await StopConnection(connectionId).ConfigureAwait(false);
1464 connectionId = Guid.Empty;
1465
1466 await CheckForDefaultSecurityKey().ConfigureAwait(false);
1467
1468 UpdateStatus(DiscoveryStatus.Succeeded);
1469 return result;
1470 }
1471 catch (Exception exception)
1472 {
1473 result.Error = exception;
1474 UpdateStatus(exception is OperationCanceledException
1475 ? DiscoveryStatus.Cancelled : DiscoveryStatus.Error);
1476 throw;
1477 }
1478 finally
1479 {
1480 if (connectionId != Guid.Empty) await StopConnection(connectionId).ConfigureAwait(false);
1481 _replyResponseTimeout = origResponseTimeout;
1482 }
1483
1484 // ReSharper enable AccessToModifiedClosure
1485 }
1486
1487 private void OnConnectionStatusChanged(Guid connectionId, byte address, bool isConnected,
1488 bool isSecureChannelEstablished)
1489 {
1490 ConnectionStatusChanged?.Invoke(this,
1491 new ConnectionStatusEventArgs(connectionId, address, isConnected, isSecureChannelEstablished));
1492 }
1493
1494 private void OnReplyReceived(ReplyTracker reply)
1495 {
1496 // Not wrapped in try/catch: ReplyReceived is a private event whose subscribers are
1497 // internal SendCommand handlers. Exceptions must propagate back to callers via the
1498 // TaskCompletionSource so they receive the actual error instead of a timeout.
1499 ReplyReceived?.Invoke(this, new ReplyEventArgs { Reply = reply });
1500
1501 try
1502 {
1503 switch ((ReplyType)reply.ReplyMessage.Type)
1504 {
1505 case ReplyType.Nak:
1506 NakReplyReceived?.Invoke(this,
1507 new NakReplyEventArgs(reply.ConnectionId, reply.ReplyMessage.Address,
1508 Nak.ParseData(reply.ReplyMessage.Payload)));
1509 break;
1510 case ReplyType.LocalStatusReport:
1511 LocalStatusReportReplyReceived?.Invoke(this,
1512 new LocalStatusReportReplyEventArgs(reply.ConnectionId,
1513 reply.ReplyMessage.Address,
1514 Model.ReplyData.LocalStatus.ParseData(reply.ReplyMessage.Payload)));
1515 break;
1516 case ReplyType.InputStatusReport:
1517 InputStatusReportReplyReceived?.Invoke(this,
1518 new InputStatusReportReplyEventArgs(reply.ConnectionId,
1519 reply.ReplyMessage.Address,
1520 Model.ReplyData.InputStatus.ParseData(reply.ReplyMessage.Payload)));
1521 break;
1522 case ReplyType.OutputStatusReport:
1524 new OutputStatusReportReplyEventArgs(reply.ConnectionId,
1525 reply.ReplyMessage.Address,
1526 Model.ReplyData.OutputStatus.ParseData(reply.ReplyMessage.Payload)));
1527 break;
1528 case ReplyType.ReaderStatusReport:
1530 new ReaderStatusReportReplyEventArgs(reply.ConnectionId,
1531 reply.ReplyMessage.Address,
1532 Model.ReplyData.ReaderStatus.ParseData(reply.ReplyMessage.Payload)));
1533 break;
1534 case ReplyType.RawReaderData:
1535 RawCardDataReplyReceived?.Invoke(this,
1536 new RawCardDataReplyEventArgs(reply.ConnectionId,
1537 reply.ReplyMessage.Address,
1538 RawCardData.ParseData(reply.ReplyMessage.Payload)));
1539 break;
1540 case ReplyType.FormattedReaderData:
1541 FormattedCardDataReplyReceived?.Invoke(this,
1542 new FormattedCardDataReplyEventArgs(reply.ConnectionId,
1543 reply.ReplyMessage.Address,
1544 FormattedCardData.ParseData(reply.ReplyMessage.Payload)));
1545 break;
1546 case ReplyType.ManufactureSpecific:
1548 new ManufacturerSpecificReplyEventArgs(reply.ConnectionId,
1549 reply.ReplyMessage.Address,
1550 ManufacturerSpecific.ParseData(reply.ReplyMessage.Payload)));
1551 break;
1552 case ReplyType.ExtendedRead:
1553 ExtendedReadReplyReceived?.Invoke(this,
1554 new ExtendedReadReplyEventArgs(reply.ConnectionId,
1555 reply.ReplyMessage.Address,
1556 ExtendedRead.ParseData(reply.ReplyMessage.Payload)));
1557 break;
1558 case ReplyType.PIVData:
1559 PIVDataReplyReceived?.Invoke(this,
1560 new MultiPartMessageDataReplyEventArgs(reply.ConnectionId,
1561 reply.ReplyMessage.Address,
1562 DataFragmentResponse.ParseData(reply.ReplyMessage.Payload)));
1563 break;
1564 case ReplyType.ExtendedPdIdReport:
1565 ExtendedIdReplyReceived?.Invoke(this,
1566 new MultiPartMessageDataReplyEventArgs(reply.ConnectionId,
1567 reply.ReplyMessage.Address,
1568 DataFragmentResponse.ParseData(reply.ReplyMessage.Payload)));
1569 break;
1570 case ReplyType.ResponseToChallenge:
1571 AuthenticationChallengeResponseReceived?.Invoke(this,
1572 new MultiPartMessageDataReplyEventArgs(reply.ConnectionId,
1573 reply.ReplyMessage.Address,
1574 DataFragmentResponse.ParseData(reply.ReplyMessage.Payload)));
1575 break;
1576 case ReplyType.KeypadData:
1577 KeypadReplyReceived?.Invoke(this,
1578 new KeypadReplyEventArgs(reply.ConnectionId, reply.ReplyMessage.Address,
1579 KeypadData.ParseData(reply.ReplyMessage.Payload)));
1580 break;
1581 case ReplyType.BiometricData:
1582 BiometricReadResultsReplyReceived?.Invoke(this,
1583 new BiometricReadResultsReplyEventArgs(reply.ConnectionId,
1584 reply.ReplyMessage.Address,
1585 BiometricReadResult.ParseData(reply.ReplyMessage.Payload)));
1586 break;
1587 case ReplyType.BiometricMatchResult:
1588 BiometricMatchReplyReceived?.Invoke(this,
1589 new BiometricMatchReplyEventArgs(reply.ConnectionId,
1590 reply.ReplyMessage.Address,
1591 BiometricMatchResult.ParseData(reply.ReplyMessage.Payload)));
1592 break;
1593 }
1594 }
1595 catch (Exception ex)
1596 {
1597 _logger.LogError(ex,
1598 "Error in typed reply event handler for reply {ReplyType} from address {Address}",
1599 (ReplyType)reply.ReplyMessage.Type, reply.ReplyMessage.Address);
1600 }
1601
1602 try
1603 {
1604 RawReplyReceived?.Invoke(this,
1605 new RawReplyEventArgs(reply.ConnectionId, reply.ReplyMessage.Address,
1606 reply.ReplyMessage.Type, reply.ReplyMessage.Payload));
1607 }
1608 catch (Exception ex)
1609 {
1610 _logger.LogError(ex,
1611 "Error in raw reply event handler for reply {ReplyType} from address {Address}",
1612 (ReplyType)reply.ReplyMessage.Type, reply.ReplyMessage.Address);
1613 }
1614 }
1615
1616 private event EventHandler<ReplyEventArgs> ReplyReceived;
1617
1621 public event EventHandler<RawReplyEventArgs> RawReplyReceived;
1622
1626 public event EventHandler<ConnectionStatusEventArgs> ConnectionStatusChanged;
1627
1631 public event EventHandler<NakReplyEventArgs> NakReplyReceived;
1632
1636 public event EventHandler<LocalStatusReportReplyEventArgs> LocalStatusReportReplyReceived;
1637
1641 public event EventHandler<InputStatusReportReplyEventArgs> InputStatusReportReplyReceived;
1642
1646 public event EventHandler<OutputStatusReportReplyEventArgs> OutputStatusReportReplyReceived;
1647
1651 public event EventHandler<ReaderStatusReportReplyEventArgs> ReaderStatusReportReplyReceived;
1652
1656 public event EventHandler<RawCardDataReplyEventArgs> RawCardDataReplyReceived;
1657
1661 [Obsolete("Use Raw Card Data for incoming card reads.")]
1662 public event EventHandler<FormattedCardDataReplyEventArgs> FormattedCardDataReplyReceived;
1663
1667 public event EventHandler<ManufacturerSpecificReplyEventArgs> ManufacturerSpecificReplyReceived;
1668
1672 public event EventHandler<ExtendedReadReplyEventArgs> ExtendedReadReplyReceived;
1673
1677 public event EventHandler<KeypadReplyEventArgs> KeypadReplyReceived;
1678
1682 private event EventHandler<BiometricReadResultsReplyEventArgs> BiometricReadResultsReplyReceived;
1683
1687 private event EventHandler<BiometricMatchReplyEventArgs> BiometricMatchReplyReceived;
1688
1692 private event EventHandler<MultiPartMessageDataReplyEventArgs> PIVDataReplyReceived;
1693
1697 private event EventHandler<MultiPartMessageDataReplyEventArgs> ExtendedIdReplyReceived;
1698
1702 private event EventHandler<MultiPartMessageDataReplyEventArgs> AuthenticationChallengeResponseReceived;
1703
1707 public class NakReplyEventArgs : EventArgs
1708 {
1715 public NakReplyEventArgs(Guid connectionId, byte address, Nak nak)
1716 {
1717 ConnectionId = connectionId;
1718 Address = address;
1719 Nak = nak;
1720 }
1721
1725 public Guid ConnectionId { get; }
1726
1730 public byte Address { get; }
1731
1735 public Nak Nak { get; }
1736 }
1737
1741 public class ConnectionStatusEventArgs : EventArgs
1742 {
1750 public ConnectionStatusEventArgs(Guid connectionId, byte address, bool isConnected,
1751 bool isSecureChannelEstablished)
1752 {
1753 ConnectionId = connectionId;
1754 Address = address;
1755 IsConnected = isConnected;
1756 IsSecureChannelEstablished = isSecureChannelEstablished;
1757 }
1758
1762 public Guid ConnectionId { get; }
1763
1767 public byte Address { get; }
1768
1772 public bool IsConnected { get; }
1773
1777 public bool IsSecureChannelEstablished { get; }
1778
1780 public override string ToString() =>
1781 $"{ConnectionId}:{Address} - Conn: {IsConnected}; Sec: {IsSecureChannelEstablished}";
1782 }
1783
1787 public class LocalStatusReportReplyEventArgs : EventArgs
1788 {
1795 public LocalStatusReportReplyEventArgs(Guid connectionId, byte address, LocalStatus localStatus)
1796 {
1797 ConnectionId = connectionId;
1798 Address = address;
1799 LocalStatus = localStatus;
1800 }
1801
1805 public Guid ConnectionId { get; }
1806
1810 public byte Address { get; }
1811
1815 public LocalStatus LocalStatus { get; }
1816 }
1817
1821 public class InputStatusReportReplyEventArgs : EventArgs
1822 {
1829 public InputStatusReportReplyEventArgs(Guid connectionId, byte address, InputStatus inputStatus)
1830 {
1831 ConnectionId = connectionId;
1832 Address = address;
1833 InputStatus = inputStatus;
1834 }
1835
1839 public Guid ConnectionId { get; }
1840
1844 public byte Address { get; }
1845
1849 public InputStatus InputStatus { get; }
1850 }
1851
1855 public class OutputStatusReportReplyEventArgs : EventArgs
1856 {
1863 public OutputStatusReportReplyEventArgs(Guid connectionId, byte address, OutputStatus outputStatus)
1864 {
1865 ConnectionId = connectionId;
1866 Address = address;
1867 OutputStatus = outputStatus;
1868 }
1869
1873 public Guid ConnectionId { get; }
1874
1878 public byte Address { get; }
1879
1884 }
1885
1889 public class ReaderStatusReportReplyEventArgs : EventArgs
1890 {
1897 public ReaderStatusReportReplyEventArgs(Guid connectionId, byte address, ReaderStatus readerStatus)
1898 {
1899 ConnectionId = connectionId;
1900 Address = address;
1901 ReaderStatus = readerStatus;
1902 }
1903
1907 public Guid ConnectionId { get; }
1908
1912 public byte Address { get; }
1913
1918 }
1919
1923 public class RawCardDataReplyEventArgs : EventArgs
1924 {
1931 public RawCardDataReplyEventArgs(Guid connectionId, byte address, RawCardData rawCardData)
1932 {
1933 ConnectionId = connectionId;
1934 Address = address;
1935 RawCardData = rawCardData;
1936 }
1937
1941 public Guid ConnectionId { get; }
1942
1946 public byte Address { get; }
1947
1951 public RawCardData RawCardData { get; }
1952 }
1953
1957 public class FormattedCardDataReplyEventArgs : EventArgs
1958 {
1965 public FormattedCardDataReplyEventArgs(Guid connectionId, byte address, FormattedCardData formattedCardData)
1966 {
1967 ConnectionId = connectionId;
1968 Address = address;
1969 FormattedCardData = formattedCardData;
1970 }
1971
1975 public Guid ConnectionId { get; }
1976
1980 public byte Address { get; }
1981
1986 }
1987
1991 public class ManufacturerSpecificReplyEventArgs : EventArgs
1992 {
1999 public ManufacturerSpecificReplyEventArgs(Guid connectionId, byte address, ManufacturerSpecific manufacturerSpecific)
2000 {
2001 ConnectionId = connectionId;
2002 Address = address;
2003 ManufacturerSpecific = manufacturerSpecific;
2004 }
2005
2009 public Guid ConnectionId { get; }
2010
2014 public byte Address { get; }
2015
2020 }
2021
2025 public class ExtendedReadReplyEventArgs : EventArgs
2026 {
2033 public ExtendedReadReplyEventArgs(Guid connectionId, byte address, ExtendedRead extendedRead)
2034 {
2035 ConnectionId = connectionId;
2036 Address = address;
2037 ExtendedRead = extendedRead;
2038 }
2039
2043 public Guid ConnectionId { get; }
2044
2048 public byte Address { get; }
2049
2054 }
2055
2059 private class MultiPartMessageDataReplyEventArgs : EventArgs
2060 {
2067 public MultiPartMessageDataReplyEventArgs(Guid connectionId, byte address, DataFragmentResponse dataFragmentResponse)
2068 {
2069 ConnectionId = connectionId;
2070 Address = address;
2071 DataFragmentResponse = dataFragmentResponse;
2072 }
2073
2077 public Guid ConnectionId { get; }
2078
2082 public byte Address { get; }
2083
2087 public DataFragmentResponse DataFragmentResponse { get; }
2088 }
2089
2093 public class KeypadReplyEventArgs : EventArgs
2094 {
2101 public KeypadReplyEventArgs(Guid connectionId, byte address, KeypadData keypadData)
2102 {
2103 ConnectionId = connectionId;
2104 Address = address;
2105 KeypadData = keypadData;
2106 }
2107
2111 public Guid ConnectionId { get; }
2112
2116 public byte Address { get; }
2117
2121 public KeypadData KeypadData { get; }
2122 }
2123
2127 private class BiometricReadResultsReplyEventArgs : EventArgs
2128 {
2135 public BiometricReadResultsReplyEventArgs(Guid connectionId, byte address,
2136 BiometricReadResult biometricReadResult)
2137 {
2138 ConnectionId = connectionId;
2139 Address = address;
2140 BiometricReadResult = biometricReadResult;
2141 }
2142
2146 public Guid ConnectionId { get; }
2147
2151 public byte Address { get; }
2152
2156 public BiometricReadResult BiometricReadResult { get; }
2157 }
2158
2162 private class BiometricMatchReplyEventArgs : EventArgs
2163 {
2170 public BiometricMatchReplyEventArgs(Guid connectionId, byte address,
2171 BiometricMatchResult biometricMatchResult)
2172 {
2173 ConnectionId = connectionId;
2174 Address = address;
2175 BiometricMatchResult = biometricMatchResult;
2176 }
2177
2181 public Guid ConnectionId { get; }
2182
2186 public byte Address { get; }
2187
2191 public BiometricMatchResult BiometricMatchResult { get; }
2192 }
2193
2198 {
2206 Nak nak)
2207 {
2208 Status = status;
2209 CurrentOffset = currentOffset;
2210 Nak = nak;
2211 }
2212
2217
2221 public int CurrentOffset { get; }
2222
2226 public Nak Nak { get; }
2227 }
2228
2232 public class FileTransferException : Exception
2233 {
2234 internal FileTransferException(string msg, FileTransferStatus status) : base(msg)
2235 {
2236 Status = status;
2237 }
2238
2243 }
2244
2248 public class RawReplyEventArgs : EventArgs
2249 {
2257 public RawReplyEventArgs(Guid connectionId, byte address, byte replyType, ReadOnlyMemory<byte> payload)
2258 {
2259 ConnectionId = connectionId;
2260 Address = address;
2261 ReplyType = replyType;
2262 Payload = payload;
2263 }
2264
2268 public Guid ConnectionId { get; }
2269
2273 public byte Address { get; }
2274
2278 public byte ReplyType { get; }
2279
2283 public ReadOnlyMemory<byte> Payload { get; }
2284 }
2285
2286 private class ReplyEventArgs : EventArgs
2287 {
2288 public ReplyTracker Reply { get; set; }
2289 }
2290 }
2291}
A connection status has been changed.
byte Address
Address assigned to the device.
Guid ConnectionId
Identify the connection for communicating to the device.
ConnectionStatusEventArgs(Guid connectionId, byte address, bool isConnected, bool isSecureChannelEstablished)
Initializes a new instance of the ConnectionStatusEventArgs class.
bool IsSecureChannelEstablished
Is the secure channel currently established.
bool IsConnected
Is the device currently connected?
byte Address
Address assigned to the device.
ExtendedReadReplyEventArgs(Guid connectionId, byte address, ExtendedRead extendedRead)
Initializes a new instance of the ExtendedReadReplyEventArgs class.
ExtendedRead ExtendedRead
An extended read reply.
Guid ConnectionId
Identify the connection for communicating to the device.
An error has occurred during a file transfer operation.
FileTransferStatus Status
The last received status from the PD that indicates what error has occurred.
Track the status of a file transfer to a PD.
Model.ReplyData.FileTransferStatus.StatusDetail Status
The last status returned from the PD.
Nak Nak
Contains Nak reply if returned.
FileTransferStatus(Model.ReplyData.FileTransferStatus.StatusDetail status, int currentOffset, Nak nak)
Initializes a new instance of the FileTransferStatus class.
int CurrentOffset
The current offset in the data of the file transfer.
FormattedCardData FormattedCardData
A formatted card data reply.
byte Address
Address assigned to the device.
FormattedCardDataReplyEventArgs(Guid connectionId, byte address, FormattedCardData formattedCardData)
Initializes a new instance of the FormattedCardDataReplyEventArgs class.
Guid ConnectionId
Identify the connection for communicating to the device.
InputStatusReportReplyEventArgs(Guid connectionId, byte address, InputStatus inputStatus)
Initializes a new instance of the LocalStatusReportReplyEventArgs class.
InputStatus InputStatus
An input status report reply.
byte Address
Address assigned to the device.
Guid ConnectionId
Identify the connection for communicating to the device.
KeypadReplyEventArgs(Guid connectionId, byte address, KeypadData keypadData)
Initializes a new instance of the KeypadReplyEventArgs class.
Guid ConnectionId
Identify the connection for communicating to the device.
byte Address
Address assigned to the device.
LocalStatus LocalStatus
A local status report reply.
Guid ConnectionId
Identify the connection for communicating to the device.
byte Address
Address assigned to the device.
LocalStatusReportReplyEventArgs(Guid connectionId, byte address, LocalStatus localStatus)
Initializes a new instance of the LocalStatusReportReplyEventArgs class.
Guid ConnectionId
Identify the connection for communicating to the device.
ManufacturerSpecificReplyEventArgs(Guid connectionId, byte address, ManufacturerSpecific manufacturerSpecific)
Initializes a new instance of the ManufacturerSpecificReplyEventArgs class.
ManufacturerSpecific ManufacturerSpecific
A manufacturer specific reply.
NakReplyEventArgs(Guid connectionId, byte address, Nak nak)
Initializes a new instance of the NakReplyEventArgs class.
Nak Nak
A negative reply that has been received.
Guid ConnectionId
Identify the connection for communicating to the device.
byte Address
Address assigned to the device.
OutputStatusReportReplyEventArgs(Guid connectionId, byte address, OutputStatus outputStatus)
Initializes a new instance of the OutputStatusReportReplyEventArgs class.
Guid ConnectionId
Identify the connection for communicating to the device.
OutputStatus OutputStatus
An output status report reply.
byte Address
Address assigned to the device.
RawCardDataReplyEventArgs(Guid connectionId, byte address, RawCardData rawCardData)
Initializes a new instance of the RawCardDataReplyEventArgs class.
Guid ConnectionId
Identify the connection for communicating to the device.
RawCardData RawCardData
A raw card data reply.
Guid ConnectionId
Identify the connection for communicating to the device.
byte ReplyType
The reply type code of the message.
byte Address
Address assigned to the device.
RawReplyEventArgs(Guid connectionId, byte address, byte replyType, ReadOnlyMemory< byte > payload)
Initializes a new instance of the RawReplyEventArgs class.
ReadOnlyMemory< byte > Payload
The raw reply payload.
Guid ConnectionId
Identify the connection for communicating to the device.
ReaderStatusReportReplyEventArgs(Guid connectionId, byte address, ReaderStatus readerStatus)
Initializes a new instance of the ReaderStatusReportReplyEventArgs class.
ReaderStatus ReaderStatus
A reader status report reply.
The OSDP control panel used to communicate to Peripheral Devices (PDs) as an Access Control Unit (ACU...
Guid StartConnection(IOsdpConnection connection, TimeSpan pollInterval, Action< TraceEntry > tracer)
Start polling on the defined connection.
async Task< ReaderStatus > ReaderStatus(Guid connectionId, byte address)
Request to get the status of all the readers of a PD.
async Task Shutdown()
Shutdown the control panel and stop all communication to PDs.
async Task< ReturnReplyData< ManufacturerSpecific > > ManufacturerSpecificCommand(Guid connectionId, byte address, Model.CommandData.ManufacturerSpecific manufacturerSpecific)
Sends a manufacture specific command to a PD.
Task< Model.ReplyData.FileTransferStatus.StatusDetail > FileTransfer(Guid connectionId, byte address, byte fileType, byte[] fileData, ushort fragmentSize, Action< FileTransferStatus > callback, CancellationToken cancellationToken=default)
Send a file to a PD.
async Task< bool > ACUReceiveSize(Guid connectionId, byte address, ushort maximumReceiveSize)
Inform the PD the maximum size that the ACU can receive.
async Task StopConnection(Guid connectionId)
Stop the bus for a specific connection.
async Task< ExtendedDeviceIdentification > ExtendedIdReport(Guid connectionId, byte address, TimeSpan timeout, CancellationToken cancellationToken=default)
Request to get an Extended ID Report from the PD.
async Task< DiscoveryResult > DiscoverDevice(IEnumerable< IOsdpConnection > connections, DiscoveryOptions options=null)
Attempts a device discovery on a given connection.
async Task< ReturnReplyData< ManufacturerSpecific > > ManufacturerSpecificCommand(Guid connectionId, byte address, Model.CommandData.ManufacturerSpecific manufacturerSpecific, ushort maximumFragmentSize, TimeSpan timeout, CancellationToken cancellationToken=default)
Sends a manufacturer specific multi-part command to a PD.
void ResetDevice(Guid connectionId, int address)
Reset communication sequence with the PD specified.
async Task< DeviceCapabilities > DeviceCapabilities(Guid connectionId, byte address)
Request to get the capabilities of the PD.
async Task< ReturnReplyData< ExtendedRead > > ExtendedWriteData(Guid connectionId, byte address, ExtendedWrite extendedWrite)
Sends an extended write (transparent mode) command to a PD to facilitate communications with an ISO 7...
ControlPanel(ILoggerFactory loggerFactory=null)
Initializes a new instance of the T:OSDP.Net.ControlPanel class.
async Task< InputStatus > InputStatus(Guid connectionId, byte address)
Request to get the status of all the inputs of a PD.
async Task< byte[]> AuthenticationChallenge(Guid connectionId, byte address, byte algorithm, byte key, byte[] challenge, ushort maximumFragmentSize, TimeSpan timeout, CancellationToken cancellationToken=default)
Instruct the PD to perform a challenge/response sequence.
async Task< byte[]> GetPIVData(Guid connectionId, byte address, GetPIVData getPIVData, TimeSpan timeout, CancellationToken cancellationToken=default)
Request to get PIV data from PD.
async Task< Model.ReplyData.CommunicationConfiguration > CommunicationConfiguration(Guid connectionId, byte address, CommunicationConfiguration communicationConfiguration)
Send a command that sets the communication configuration on a PD.
EventHandler< ManufacturerSpecificReplyEventArgs > ManufacturerSpecificReplyReceived
Occurs when manufacturer specific reply is received.
async Task< LocalStatus > LocalStatus(Guid connectionId, byte address)
Request to get the local status of a PD.
async Task< bool > ReaderTextOutput(Guid connectionId, byte address, ReaderTextOutput readerTextOutput)
Send a command that sends text to be shown on a PD.
EventHandler< OutputStatusReportReplyEventArgs > OutputStatusReportReplyReceived
Occurs when output status report reply is received.
EventHandler< ExtendedReadReplyEventArgs > ExtendedReadReplyReceived
Occurs when an extended read reply (transparent mode) is received.
Guid StartConnection(IOsdpConnection connection, TimeSpan pollInterval)
Start polling on the defined connection.
async Task< DeviceIdentification > IdReport(Guid connectionId, byte address)
Request to get an ID Report from the PD.
async Task< ReturnReplyData< OutputStatus > > OutputControl(Guid connectionId, byte address, OutputControls outputControls)
Send a command to alter the state of one or more outputs on a PD.
EventHandler< FormattedCardDataReplyEventArgs > FormattedCardDataReplyReceived
Occurs when formatted card data reply is received.
EventHandler< ConnectionStatusEventArgs > ConnectionStatusChanged
Occurs when connection status changed.
async Task SendCustomCommand(Guid connectionId, byte address, CommandData command)
Send a custom command for testing.
EventHandler< NakReplyEventArgs > NakReplyReceived
Occurs when a negative reply is received.
EventHandler< LocalStatusReportReplyEventArgs > LocalStatusReportReplyReceived
Occurs when local status report reply is received.
void EnqueueCustomCommand(Guid connectionId, byte address, CommandData command)
Enqueue a custom command to be sent without waiting for a response.
void AddDevice(Guid connectionId, byte address, bool useCrc, bool useSecureChannel, byte[] secureChannelKey=null)
Add a PD to the control panel.
async Task< bool > ReaderLedControl(Guid connectionId, byte address, ReaderLedControls readerLedControls)
Send a command to alter the LED color on a PD.
ControlPanel(ILogger< ControlPanel > logger)
Initializes a new instance of the T:OSDP.Net.ControlPanel class.
EventHandler< RawReplyEventArgs > RawReplyReceived
Occurs when any reply is received.
async Task< BiometricReadResult > ScanAndSendBiometricData(Guid connectionId, byte address, BiometricReadData biometricReadData, TimeSpan timeout, CancellationToken cancellationToken=default)
Send a request to the PD to read from a biometric scan and send back the data template.
async Task< OutputStatus > OutputStatus(Guid connectionId, byte address)
Request to get the status of all the outputs of a PD.
async Task< bool > EncryptionKeySet(Guid connectionId, byte address, EncryptionKeyConfiguration encryptionKeyConfiguration)
Send a command that sets the encryption key configuration on a PD.
async Task< bool > KeepReaderActive(Guid connectionId, byte address, ushort keepAliveTimeInMilliseconds)
Instructs the PD to maintain communication with the credential for a specified time.
Guid StartConnection(IOsdpConnection connection)
Start polling on the defined connection.
async Task< bool > ReaderBuzzerControl(Guid connectionId, byte address, ReaderBuzzerControl readerBuzzerControl)
Send a command to control the buzzer on a PD.
Guid StartConnection(IOsdpConnection connection, TimeSpan pollInterval, bool isTracing)
Start polling on the defined connection.
EventHandler< ReaderStatusReportReplyEventArgs > ReaderStatusReportReplyReceived
Occurs when reader status report reply is received.
async Task< BiometricMatchResult > ScanAndMatchBiometricTemplate(Guid connectionId, byte address, BiometricTemplateData biometricTemplateData, TimeSpan timeout, CancellationToken cancellationToken=default)
Send a request to the PD to perform a biometric scan and match it to the provided template.
void RemoveDevice(Guid connectionId, byte address)
Remove a PD from the control panel.
EventHandler< RawCardDataReplyEventArgs > RawCardDataReplyReceived
Occurs when raw card data reply is received.
bool IsOnline(Guid connectionId, byte address)
Is the PD online.
async Task< bool > AbortCurrentOperation(Guid connectionId, byte address)
Instructs the PD to abort the current operation.
EventHandler< InputStatusReportReplyEventArgs > InputStatusReportReplyReceived
Occurs when input status report reply is received.
EventHandler< KeypadReplyEventArgs > KeypadReplyReceived
Occurs when key pad data reply is received.
async Task< DeviceIdentification > IdReport(Guid connectionId, byte address, CancellationToken cancellationToken)
Request to get an ID Report from the PD.
Represents a message that was received from the wire.
byte Type
Command/reply code of the message.
byte[] Payload
Returns the raw message payload.
A base message class for sending or replying.
Definition Message.cs:12
byte Address
Address assigned to the device.
Definition Message.cs:68
static ushort CalculateMaximumMessageSize(ushort dataSize, bool isEncrypted=false, ushort cryptoLength=16)
Calculates the largest payload that fits in a message of the given total size, accounting for the mes...
Definition Message.cs:202
Command data to send a request to the PD to perform a biometric scan and match.
Command data to send a request to the PD to perform a biometric scan and return data.
Command data to set the communication configuration on a PD.
Represents the capabilities of a device within the context of OSDP (Open Supervised Device Protocol).
Command data to set the encryption key configuration on a PD.
Extended write (transparent mode) command data sent to a PD.
Command data to send a data fragment of a file to a PD.
Manufacture specific command data sent to a PD.
static ManufacturerSpecific ParseData(ReadOnlySpan< byte > data)
Parses the message payload bytes.
Represents a fragment of data for a multipart message.
Command data to control the outputs of a PD.
Command data to control the color of LEDs.
byte Code
Gets the command or reply code byte value that represent the type of data.
Generic ACK reply.
Definition Ack.cs:11
A biometric match reply after a scan.
The actual communication configuration of the PD sent as a reply.
A multi-part message data fragment reply.
static DataFragmentResponse ParseData(ReadOnlySpan< byte > data)
Parses the message payload bytes.
The PD device capabilities data sent as a reply.
The PD identification data sent as a reply.
static DeviceIdentification ParseData(ReadOnlySpan< byte > data)
Parses the message payload bytes.
An extended read (transparent mode) reply.
static ExtendedRead ParseData(ReadOnlySpan< byte > data)
Parses the message payload bytes.
The PD file transfer status sent as a reply.
static FormattedCardData ParseData(ReadOnlySpan< byte > data)
Parses the data.
A input status report reply as defined in OSDP v2.2.2 specification.
static KeypadData ParseData(ReadOnlySpan< byte > data)
Parses the message payload bytes.
A local status report reply.
A negative reply.
Definition Nak.cs:14
A output status report reply.
static OutputStatus ParseData(ReadOnlySpan< byte > data)
Parses the message payload bytes.
static RawCardData ParseData(ReadOnlySpan< byte > data)
Parses the data.
A reader status report reply.
Represent a failure condition where PD indicates that it didn't accept the command by replying with o...
Definition Exceptions.cs:34
This exception will be thrown if a caller attempts to perform device discovery on a control panel tha...
Represents an error condition encountered during device discovery.
Defines a set of optional parameters the caller can pass in to the ControlPanel.DiscoverDevice(System...
Contains the results of the device discovery.
IOsdpConnection Connection
When Status is DiscoveryStatus.LookingForDeviceOnConnection this property identifies connection being...
byte Address
When Status is DiscoveryStatus.LookingForDeviceAtAddress, this property identifies the address being ...
DeviceCapabilities Capabilities
After status DiscoveryStatus.CapabilitiesDiscovered, this property will contain the capabilities repo...
Defines a connection for communicating via OSDP protocol.
ReplyType
Identifies the type of OSDP protocol reply (PD -> ACU) message.
Definition ReplyType.cs:7
@ ManufactureSpecific
osdp_MFGREP - manufacturer specific reply
Definition ReplyType.cs:120
@ Nak
osdp_NAK - acknowledge; error response
Definition ReplyType.cs:16
@ FileTransferStatus
osdp_FTSTAT - file transfer status
Definition ReplyType.cs:101
@ ExtendedRead
osdp_XRD - extended read reply
Definition ReplyType.cs:125
@ OutputStatusReport
osdp_OSTATR - output status report
Definition ReplyType.cs:41
CommandType
Identifies the type of OSDP protocol command (ACU -> PD) message.
Definition CommandType.cs:7
MessageDataFragmentFieldSize
Defines the field size used for the MessageDataFragment.TotalSize and MessageDataFragment....
CapabilityFunction
Definitions of the capability function codes.
DiscoveryStatus
Represents current state of the device discovery process.
Definition Bus.cs:22