30 internal const byte ConfigurationAddress = 0x7f;
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;
46 [Obsolete(
"Sending a ILogger is deprecated, please send ILoggerFactory instead.")]
47 public ControlPanel(ILogger<ControlPanel> logger) : this(null, null, logger) { }
51 public ControlPanel(ILoggerFactory loggerFactory =
null) : this(null, loggerFactory, null) { }
53 internal ControlPanel(IDeviceProxyFactory deviceProxyFactory, ILoggerFactory loggerFactory =
null)
54 : this(deviceProxyFactory, loggerFactory, null) { }
56 private ControlPanel(IDeviceProxyFactory deviceProxyFactory, ILoggerFactory loggerFactory,
57 ILogger<ControlPanel> logger)
61 ?? NullLoggerFactory.Instance.CreateLogger<
ControlPanel>();
62 _deviceProxyFactory = deviceProxyFactory ??
new DeviceProxyFactory();
64 Task.Run(ProcessReplies);
67 private async Task ProcessReplies()
69 var reader = _replies.Reader;
70 while (await reader.WaitToReadAsync().ConfigureAwait(
false))
72 while (reader.TryRead(out var reply))
76 OnReplyReceived(reply);
78 catch (Exception exception)
80 _logger.LogError(exception,
"Error while dispatching reply {Reply}", reply);
101 StartConnection(connection, pollInterval, isTracing ? OSDPFileCaptureTracer.Trace : _ => { });
125 var newBus = CreateBus(connection, pollInterval, tracer);
126 newBus.ConnectionStatusChanged += BusOnConnectionStatusChanged;
127 newBus.StartPolling();
137 private Bus CreateBus(
IOsdpConnection connection, TimeSpan pollInterval, Action<TraceEntry> tracer)
140 lock (_lockBusCreation)
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.");
149 var newBus =
new Bus(
157 _buses[newBus.Id] = newBus;
168 if (!_buses.TryGetValue(connectionId, out Bus bus))
176 bus.ConnectionStatusChanged -= BusOnConnectionStatusChanged;
177 await bus.Close().ConfigureAwait(
false);
179 foreach (
byte address
in bus.ConfigureDeviceAddresses)
182 OnConnectionStatusChanged(bus.Id, address,
false,
false);
183 _requestLocks.TryRemove(
new { connectionId, address }.GetHashCode(), out _);
186 _buses.TryRemove(connectionId, out bus);
189 private void BusOnConnectionStatusChanged(
object sender, Bus.ConnectionStatusEventArgs eventArgs)
191 if (sender is Bus bus)
192 OnConnectionStatusChanged(bus.Id, eventArgs.Address, eventArgs.IsConnected,
193 eventArgs.IsSecureSessionEstablished);
204 await SendCommand(connectionId, address, command).ConfigureAwait(
false);
215 if (!_buses.TryGetValue(connectionId, out var bus))
217 throw new ArgumentException(
"Connection could not be found", nameof(connectionId));
220 bus.SendCommand(address, command);
227 public async Task<DeviceIdentification>
IdReport(Guid connectionId,
byte address) =>
228 await
IdReport(connectionId, address, CancellationToken.None).ConfigureAwait(
false);
235 public async Task<DeviceIdentification>
IdReport(Guid connectionId,
byte address, CancellationToken cancellationToken)
237 var message = await SendCommand(
241 cancellationToken).ConfigureAwait(
false);
253 public async Task<ExtendedDeviceIdentification>
ExtendedIdReport(Guid connectionId,
byte address,
254 TimeSpan timeout, CancellationToken cancellationToken =
default)
256 using var scope = await BeginCommandAsync(connectionId, address, timeout, cancellationToken);
257 return await WaitForExtendedIdData(connectionId, address, timeout, scope.Token);
260 private async Task<T> WaitForMultiPartData<T>(
265 Func<
byte[], T> parser,
266 Action<EventHandler<MultiPartMessageDataReplyEventArgs>> subscribe,
267 Action<EventHandler<MultiPartMessageDataReplyEventArgs>> unsubscribe,
268 CancellationToken cancellationToken)
270 bool complete =
false;
273 void Handler(
object sender, MultiPartMessageDataReplyEventArgs args)
276 if (args.ConnectionId != connectionId || args.Address != address)
return;
278 var fragment = args.DataFragmentResponse;
279 data ??=
new byte[fragment.WholeMessageLength];
281 complete =
Message.BuildMultiPartMessageData(fragment.WholeMessageLength, fragment.Offset,
282 fragment.LengthOfFragment, fragment.Data, data);
286 SetReceivingMultipartMessaging(connectionId, address,
true);
290 await SendCommand(connectionId, address, command, cancellationToken, throwOnNak:
false)
291 .ConfigureAwait(
false);
293 DateTime endTime = DateTime.UtcNow + timeout;
295 while (DateTime.UtcNow <= endTime)
302 await Task.Delay(_timeToWaitToCheckOnData, cancellationToken);
305 throw new TimeoutException(
"Timeout waiting to receive multi-part data.");
309 unsubscribe(Handler);
310 SetReceivingMultipartMessaging(connectionId, address,
false);
314 private async Task<ExtendedDeviceIdentification> WaitForExtendedIdData(Guid connectionId,
byte address,
315 TimeSpan timeout, CancellationToken cancellationToken)
317 return await WaitForMultiPartData(
321 new IdReport(requestExtended:
true),
322 data => ExtendedDeviceIdentification.ParseData(data),
323 handler => ExtendedIdReplyReceived += handler,
324 handler => ExtendedIdReplyReceived -= handler,
325 cancellationToken).ConfigureAwait(
false);
346 public async Task<LocalStatus>
LocalStatus(Guid connectionId,
byte address)
351 new NoPayloadCommandData(
CommandType.LocalStatus)).ConfigureAwait(
false)).Payload);
360 public async Task<InputStatus>
InputStatus(Guid connectionId,
byte address)
365 new NoPayloadCommandData(
CommandType.InputStatus)).ConfigureAwait(
false)).Payload);
374 public async Task<OutputStatus>
OutputStatus(Guid connectionId,
byte address)
379 new NoPayloadCommandData(
CommandType.OutputStatus)).ConfigureAwait(
false)).Payload);
392 CancellationToken cancellationToken =
default)
394 using var scope = await BeginCommandAsync(connectionId, address, timeout, cancellationToken);
395 return await WaitForPIVData(connectionId, address, getPIVData, timeout, scope.Token);
398 private SemaphoreSlim GetRequestLock(Guid connectionId,
byte address)
400 int hash =
new { connectionId, address }.GetHashCode();
402 if (_requestLocks.TryGetValue(hash, out var requestLock))
407 var newRequestLock =
new SemaphoreSlim(1, 1);
408 _requestLocks[hash] = newRequestLock;
409 return newRequestLock;
412 private async Task<CommandScope> BeginCommandAsync(Guid connectionId,
byte address, TimeSpan timeout,
413 CancellationToken cancellationToken)
416 CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, _shutdownCts.Token);
417 Interlocked.Increment(ref _inFlightCommands);
420 var requestLock = GetRequestLock(connectionId, address);
421 if (!await requestLock.WaitAsync(timeout, linkedCts.Token).ConfigureAwait(
false))
423 throw new TimeoutException(
"Timeout waiting for another request to complete.");
425 return new CommandScope(
this, requestLock, linkedCts);
430 Interlocked.Decrement(ref _inFlightCommands);
435 private sealed class CommandScope : IDisposable
438 private readonly SemaphoreSlim _requestLock;
439 private readonly CancellationTokenSource _linkedCts;
441 public CommandScope(
ControlPanel owner, SemaphoreSlim requestLock, CancellationTokenSource linkedCts)
444 _requestLock = requestLock;
445 _linkedCts = linkedCts;
448 public CancellationToken Token => _linkedCts.Token;
450 public void Dispose()
452 _requestLock.Release();
453 _linkedCts.Dispose();
454 Interlocked.Decrement(ref _owner._inFlightCommands);
458 private async Task<byte[]> WaitForPIVData(Guid connectionId,
byte address,
GetPIVData getPIVData, TimeSpan timeout,
459 CancellationToken cancellationToken)
461 return await WaitForMultiPartData(
467 handler => PIVDataReplyReceived += handler,
468 handler => PIVDataReplyReceived -= handler,
469 cancellationToken).ConfigureAwait(
false);
478 public async Task<ReaderStatus>
ReaderStatus(Guid connectionId,
byte address)
481 new NoPayloadCommandData(
CommandType.ReaderStatus)).ConfigureAwait(
false)).Payload);
495 var reply = await SendCommand(connectionId, address, manufacturerSpecific).ConfigureAwait(
false);
497 return new ReturnReplyData<ManufacturerSpecific>
514 public async Task<ReturnReplyData<ExtendedRead>>
ExtendedWriteData(Guid connectionId,
byte address,
517 var reply = await SendCommand(connectionId, address, extendedWrite).ConfigureAwait(
false);
519 return new ReturnReplyData<ExtendedRead>
540 CancellationToken cancellationToken =
default)
542 using var scope = await BeginCommandAsync(connectionId, address, timeout, cancellationToken);
543 return await WaitForManufactureResponse(connectionId, address, manufacturerSpecific, maximumFragmentSize,
547 private async Task<ReturnReplyData<ManufacturerSpecific>> WaitForManufactureResponse(Guid connectionId,
byte address,
550 SetReceivingMultipartMessaging(connectionId, address,
true);
552 var manufactureCommandCode = manufacturerSpecific.Data.Skip(0).Take(1).ToArray();
553 var manufactureCommandData = manufacturerSpecific.Data.Skip(1).ToArray();
554 ushort totalSize = (ushort)manufactureCommandData.Length;
556 bool continueTransfer =
true;
561 while (!cancellationToken.IsCancellationRequested && continueTransfer)
563 ushort fragmentSize = (ushort)Math.Min(maximumFragmentSize, totalSize - offset);
565 manufacturerSpecific.VendorCode, manufactureCommandCode.Concat(
567 manufactureCommandData.Skip(offset).Take(fragmentSize).ToArray(),
569 .ToArray()).ToArray()), cancellationToken)
570 .ConfigureAwait(
false);
574 offset += maximumFragmentSize;
577 continueTransfer = offset < totalSize;
582 throw new Exception(
"Command didn't return a valid reply");
585 return new ReturnReplyData<ManufacturerSpecific>
593 SetReceivingMultipartMessaging(connectionId, address,
false);
604 public async Task<ReturnReplyData<OutputStatus>>
OutputControl(Guid connectionId,
byte address,
607 var reply = await SendCommand(connectionId, address, outputControls).ConfigureAwait(
false);
609 return new ReturnReplyData<OutputStatus>
627 var reply = await SendCommand(connectionId, address, readerLedControls).ConfigureAwait(
false);
629 return reply.Type == (byte)
ReplyType.Ack;
642 var reply = await SendCommand(connectionId, address, readerBuzzerControl).ConfigureAwait(
false);
644 return reply.Type == (byte)
ReplyType.Ack;
656 var reply = await SendCommand(connectionId, address, readerTextOutput).ConfigureAwait(
false);
658 return reply.Type == (byte)
ReplyType.Ack;
671 if (_buses.Any(bus =>
672 bus.Key == connectionId &&
673 address != communicationConfiguration.
Address &&
674 bus.Value.ConfigureDeviceAddresses.Any(configuredAddress =>
675 configuredAddress == communicationConfiguration.
Address)))
677 throw new Exception(
"Address is already configured on the bus.");
681 (await SendCommand(connectionId, address, communicationConfiguration).ConfigureAwait(
false))
695 var reply = await SendCommand(connectionId, address, encryptionKeyConfiguration).ConfigureAwait(
false);
697 return reply.Type == (byte)
ReplyType.Ack;
713 Action<FileTransferStatus> callback, CancellationToken cancellationToken =
default)
715 var bus = _buses[connectionId];
716 return Task.Run(async () =>
718 bus.SetSendingMultipartMessage(address,
true);
721 return await SendFileTransferCommands(connectionId, address, fileType, fileData, fragmentSize, callback,
726 bus.SetSendingMultipartMessage(address,
false);
727 bus.SetSendingMultiMessageNoSecureChannel(address,
false);
729 }, cancellationToken);
733 byte address,
byte fileType,
byte[] fileData,
734 ushort fragmentSize, Action<FileTransferStatus> callback, CancellationToken cancellationToken)
736 int totalSize = fileData.Length;
738 bool isFirstMessage =
true;
746 cancellationToken.ThrowIfCancellationRequested();
749 var nextFragmentSize = (ushort)Math.Min(fragmentSize, totalSize - offset);
751 var reply = await SendCommand(connectionId, address,
754 fileData.Skip(offset).Take(nextFragmentSize).ToArray(),
756 cancellationToken, throwOnNak:
false)
757 .ConfigureAwait(
false);
762 isFirstMessage =
false;
767 offset += nextFragmentSize;
770 var fileTransferStatusReply = reply.Type == (byte)
ReplyType.FileTransferStatus
775 if (fileTransferStatusReply !=
null)
778 if ((fileTransferStatusReply.Action &
782 _buses[connectionId].SetSendingMultiMessageNoSecureChannel(address,
true);
786 if (fileTransferStatusReply is { RequestedDelay: > 0 })
788 _buses[connectionId].SetRequestDelay(address,
789 DateTime.UtcNow.AddMilliseconds(fileTransferStatusReply.RequestedDelay));
793 if (fileTransferStatusReply is { UpdateMessageMaximum: > 0 })
795 fragmentSize = Message.CalculateMaximumMessageSize(fileTransferStatusReply.UpdateMessageMaximum,
796 reply.IsSecureMessage);
801 fileTransferStatusReply?.Detail ?? Model.ReplyData.FileTransferStatus.StatusDetail.UnknownError,
803 reply.Type == (
byte)
ReplyType.Nak ?
Nak.ParseData(reply.Payload) :
null);
808 switch (status.Status)
814 case Model.ReplyData.FileTransferStatus.StatusDetail.FinishingFileTransfer:
819 if (offset >= totalSize)
822 return status.Status;
842 CancellationToken cancellationToken =
default)
844 using var scope = await BeginCommandAsync(connectionId, address, timeout, cancellationToken);
845 return await WaitForBiometricRead(connectionId, address, biometricReadData, timeout, scope.Token);
848 private async Task<BiometricReadResult> WaitForBiometricRead(Guid connectionId,
byte address,
850 CancellationToken cancellationToken)
852 bool complete =
false;
855 void Handler(
object sender, BiometricReadResultsReplyEventArgs args)
858 if (args.ConnectionId != connectionId || args.Address != address)
return;
862 result = args.BiometricReadResult;
865 BiometricReadResultsReplyReceived += Handler;
866 SetReceivingMultipartMessaging(connectionId, address,
true);
870 await SendCommand(connectionId, address, biometricReadData, cancellationToken, throwOnNak:
false)
871 .ConfigureAwait(
false);
873 DateTime endTime = DateTime.UtcNow + timeout;
875 while (DateTime.UtcNow <= endTime)
882 await Task.Delay(_timeToWaitToCheckOnData, cancellationToken);
885 throw new TimeoutException(
"Timeout waiting to for biometric read data.");
889 BiometricReadResultsReplyReceived -= Handler;
890 SetReceivingMultipartMessaging(connectionId, address,
false);
906 CancellationToken cancellationToken =
default)
908 using var scope = await BeginCommandAsync(connectionId, address, timeout, cancellationToken);
909 return await WaitForBiometricMatch(connectionId, address, biometricTemplateData, timeout, scope.Token);
912 private async Task<BiometricMatchResult> WaitForBiometricMatch(Guid connectionId,
byte address,
914 CancellationToken cancellationToken)
916 bool complete =
false;
919 void Handler(
object sender, BiometricMatchReplyEventArgs args)
922 if (args.ConnectionId != connectionId || args.Address != address)
return;
926 result = args.BiometricMatchResult;
929 BiometricMatchReplyReceived += Handler;
930 SetReceivingMultipartMessaging(connectionId, address,
true);
934 await SendCommand(connectionId, address, biometricTemplateData, cancellationToken, throwOnNak:
false)
935 .ConfigureAwait(
false);
937 DateTime endTime = DateTime.UtcNow + timeout;
939 while (DateTime.UtcNow <= endTime)
946 await Task.Delay(_timeToWaitToCheckOnData, cancellationToken);
949 throw new TimeoutException(
"Timeout waiting to for biometric match.");
953 BiometricMatchReplyReceived -= Handler;
954 SetReceivingMultipartMessaging(connectionId, address,
false);
971 byte algorithm,
byte key,
byte[] challenge, ushort maximumFragmentSize, TimeSpan timeout,
972 CancellationToken cancellationToken =
default)
974 using var scope = await BeginCommandAsync(connectionId, address, timeout, cancellationToken);
975 return await WaitForChallengeResponse(connectionId, address, algorithm, key, challenge, maximumFragmentSize,
976 timeout, scope.Token);
979 private async Task<byte[]> WaitForChallengeResponse(Guid connectionId,
byte address,
byte algorithm,
byte key,
980 byte[] challenge, ushort maximumFragmentSize, TimeSpan timeout,
981 CancellationToken cancellationToken)
983 bool complete =
false;
984 var requestData =
new List<byte> { algorithm, key };
985 requestData.AddRange(challenge);
986 byte[] responseData =
null;
988 void Handler(
object sender, MultiPartMessageDataReplyEventArgs args)
991 if (args.ConnectionId != connectionId || args.Address != address)
return;
993 var dataFragmentResponse = args.DataFragmentResponse;
994 responseData ??=
new byte[dataFragmentResponse.WholeMessageLength];
996 complete =
Message.BuildMultiPartMessageData(dataFragmentResponse.WholeMessageLength, dataFragmentResponse.Offset,
997 dataFragmentResponse.LengthOfFragment, dataFragmentResponse.Data, responseData);
1000 AuthenticationChallengeResponseReceived += Handler;
1001 SetReceivingMultipartMessaging(connectionId, address,
true);
1003 ushort totalSize = (ushort)requestData.Count;
1005 bool continueTransfer =
true;
1009 while (!cancellationToken.IsCancellationRequested && continueTransfer)
1011 ushort fragmentSize = (ushort)Math.Min(maximumFragmentSize, totalSize - offset);
1012 await SendCommand(connectionId, address,
new AuthenticationChallengeFragment(
1014 requestData.Skip(offset).Take((ushort)Math.Min(fragmentSize, totalSize - offset))
1017 .ConfigureAwait(
false);
1019 offset += fragmentSize;
1022 continueTransfer = offset < totalSize;
1025 DateTime endTime = DateTime.UtcNow + timeout;
1027 while (DateTime.UtcNow <= endTime)
1031 return responseData;
1034 await Task.Delay(_timeToWaitToCheckOnData, cancellationToken);
1037 throw new TimeoutException(
"Timeout waiting to receive challenge response.");
1041 AuthenticationChallengeResponseReceived -= Handler;
1042 SetReceivingMultipartMessaging(connectionId, address,
false);
1053 public async Task<bool>
ACUReceiveSize(Guid connectionId,
byte address, ushort maximumReceiveSize)
1055 var reply = await SendCommand(connectionId, address,
new ACUReceiveSize(maximumReceiveSize))
1056 .ConfigureAwait(
false);
1058 return reply.Type == (byte)
ReplyType.Ack;
1068 public async Task<bool>
KeepReaderActive(Guid connectionId,
byte address, ushort keepAliveTimeInMilliseconds)
1070 var reply = await SendCommand(connectionId, address,
new KeepReaderActive(keepAliveTimeInMilliseconds))
1071 .ConfigureAwait(
false);
1073 return reply.Type == (byte)
ReplyType.Ack;
1084 var reply = await SendCommand(connectionId, address,
new NoPayloadCommandData(
CommandType.Abort))
1085 .ConfigureAwait(
false);
1087 return reply.Type == (byte)
ReplyType.Ack;
1098 return _buses[connectionId].IsOnline(address);
1101 private void SetReceivingMultipartMessaging(Guid connectionId,
byte address,
bool isReceivingMultipartMessaging)
1103 if (!_buses.TryGetValue(connectionId, out var bus))
1105 throw new ArgumentException(
"Connection could not be found", nameof(connectionId));
1108 bus.SetReceivingMultipartMessage(address, isReceivingMultipartMessaging);
1111 private async Task<IncomingMessage> SendCommand(Guid connectionId,
byte address,
CommandData command,
1112 CancellationToken cancellationToken =
default,
bool throwOnNak =
true)
1114 var source =
new TaskCompletionSource<IncomingMessage>();
1116 void EventHandler(
object sender, ReplyEventArgs replyEventArgs)
1118 var reply = replyEventArgs.Reply;
1119 if (!reply.MatchIssuingCommand(address, command.
Code))
return;
1121 if (throwOnNak && replyEventArgs.Reply.ReplyMessage.Type == (
byte)
ReplyType.Nak)
1127 source.SetResult(reply.ReplyMessage);
1131 if (!_buses.TryGetValue(connectionId, out var bus))
1133 throw new ArgumentException(
"Connection could not be found", nameof(connectionId));
1136 ReplyReceived += EventHandler;
1140 bus.SendCommand(address, command);
1142 var task = await Task.WhenAny(
1143 source.Task, Task.Delay(_replyResponseTimeout, cancellationToken)).ConfigureAwait(
false);
1145 if (source.Task != task)
1147 throw task.IsCanceled
1148 ?
new OperationCanceledException(cancellationToken)
1149 : new TimeoutException();
1152 return await source.Task;
1156 ReplyReceived -= EventHandler;
1165 var shutdownCts = _shutdownCts;
1166 shutdownCts.Cancel();
1168 foreach (var bus
in _buses.Values)
1170 bus.ConnectionStatusChanged -= BusOnConnectionStatusChanged;
1171 await bus.Close().ConfigureAwait(
false);
1173 foreach (
byte address
in bus.ConfigureDeviceAddresses)
1175 OnConnectionStatusChanged(bus.Id, address,
false,
false);
1181 while (Volatile.Read(ref _inFlightCommands) > 0)
1183 await Task.Delay(_timeToWaitToCheckOnData).ConfigureAwait(
false);
1186 foreach (var requestLock
in _requestLocks.Values)
1188 requestLock.Dispose();
1190 _requestLocks.Clear();
1192 _shutdownCts =
new CancellationTokenSource();
1193 shutdownCts.Dispose();
1195 OSDPFileCaptureTracer.CloseAllWriters();
1205 if (_buses.TryGetValue(connectionId, out Bus bus))
1207 bus.ResetDevice(address);
1219 public void AddDevice(Guid connectionId,
byte address,
bool useCrc,
bool useSecureChannel,
byte[] secureChannelKey =
null)
1221 if (!_buses.TryGetValue(connectionId, out Bus foundBus))
1223 throw new ArgumentException(
"Connection could not be found", nameof(connectionId));
1228 throw new ArgumentOutOfRangeException(nameof(address),
"Address is out of range, it must between 0 and 127.");
1231 foundBus.AddDevice(address, useCrc, useSecureChannel, useSecureChannel ? secureChannelKey :
null);
1241 if (_buses.TryGetValue(connectionId, out Bus bus))
1243 bus.RemoveDevice(address);
1265 Guid connectionId = Guid.Empty;
1273 result.Status = status;
1274 options.ProgressCallback?.Invoke(result);
1277 async Task<DeviceIdentification> TryIdReport(
byte address)
1281 return await
IdReport(connectionId, address, options.CancellationToken).ConfigureAwait(
false);
1283 catch (TimeoutException)
1289 async Task<bool> FindConnectionWithActiveDevice()
1291 bool isFirst =
true;
1297 await Task.Delay(options.ReconnectDelay, options.CancellationToken);
1310 connectionId =
StartConnection(connection, TimeSpan.Zero, options.Tracer ?? (_ => {}));
1312 AddDevice(connectionId, ConfigurationAddress,
true,
false);
1314 result.Connection = connection;
1317 var deviceIdentification = await TryIdReport(ConfigurationAddress).ConfigureAwait(
false);
1318 if (deviceIdentification !=
null)
1320 result.Id = deviceIdentification;
1330 result.Connection =
null;
1334 async Task<bool> FindDeviceAddress()
1337 for (
byte address = 0; address < ConfigurationAddress; address++)
1339 AddDevice(connectionId, address,
true,
false);
1341 result.Address = address;
1343 var deviceIdentification = await TryIdReport(address).ConfigureAwait(
false);
1345 if (deviceIdentification !=
null)
1347 result.Id = deviceIdentification;
1358 result.Address = ConfigurationAddress;
1362 async Task CheckForDefaultSecurityKey()
1367 if (communicationSecurity !=
null && (communicationSecurity.Compliance & 0x01) == 0)
1369 result.UsesDefaultSecurityKey =
false;
1375 var defaultKeyCheck =
1376 new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
1383 defaultKeyCheck.TrySetResult(
true);
1387 void HandleHandshakeFailed(
object sender, Bus.SecureChannelHandshakeFailedEventArgs args)
1391 defaultKeyCheck.TrySetResult(
false);
1401 options.Tracer ?? (_ => { }));
1404 bus = _buses[connectionId];
1405 bus.SecureChannelHandshakeFailed += HandleHandshakeFailed;
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();
1415 if (completedTask != defaultKeyCheck.Task)
1417 options.CancellationToken.ThrowIfCancellationRequested();
1420 result.UsesDefaultSecurityKey = completedTask == defaultKeyCheck.Task &&
1421 await defaultKeyCheck.Task.ConfigureAwait(
false);
1426 if (bus !=
null) bus.SecureChannelHandshakeFailed -= HandleHandshakeFailed;
1436 var origResponseTimeout = _replyResponseTimeout;
1437 _replyResponseTimeout = options.ResponseTimeout;
1441 if (!_buses.IsEmpty)
1446 if (!await FindConnectionWithActiveDevice().ConfigureAwait(
false))
1452 if (!await FindDeviceAddress().ConfigureAwait(
false))
1455 $
"Unable to determine address of device that responded to a configuration address on baud rate {result.Connection.BaudRate}");
1464 connectionId = Guid.Empty;
1466 await CheckForDefaultSecurityKey().ConfigureAwait(
false);
1471 catch (Exception exception)
1473 result.Error = exception;
1474 UpdateStatus(exception is OperationCanceledException
1480 if (connectionId != Guid.Empty) await
StopConnection(connectionId).ConfigureAwait(
false);
1481 _replyResponseTimeout = origResponseTimeout;
1487 private void OnConnectionStatusChanged(Guid connectionId,
byte address,
bool isConnected,
1488 bool isSecureChannelEstablished)
1491 new ConnectionStatusEventArgs(connectionId, address, isConnected, isSecureChannelEstablished));
1494 private void OnReplyReceived(ReplyTracker reply)
1499 ReplyReceived?.Invoke(
this,
new ReplyEventArgs {
Reply = reply });
1507 new NakReplyEventArgs(reply.ConnectionId, reply.ReplyMessage.
Address,
1512 new LocalStatusReportReplyEventArgs(reply.ConnectionId,
1518 new InputStatusReportReplyEventArgs(reply.ConnectionId,
1524 new OutputStatusReportReplyEventArgs(reply.ConnectionId,
1530 new ReaderStatusReportReplyEventArgs(reply.ConnectionId,
1536 new RawCardDataReplyEventArgs(reply.ConnectionId,
1542 new FormattedCardDataReplyEventArgs(reply.ConnectionId,
1548 new ManufacturerSpecificReplyEventArgs(reply.ConnectionId,
1554 new ExtendedReadReplyEventArgs(reply.ConnectionId,
1559 PIVDataReplyReceived?.Invoke(
this,
1560 new MultiPartMessageDataReplyEventArgs(reply.ConnectionId,
1565 ExtendedIdReplyReceived?.Invoke(
this,
1566 new MultiPartMessageDataReplyEventArgs(reply.ConnectionId,
1571 AuthenticationChallengeResponseReceived?.Invoke(
this,
1572 new MultiPartMessageDataReplyEventArgs(reply.ConnectionId,
1578 new KeypadReplyEventArgs(reply.ConnectionId, reply.ReplyMessage.
Address,
1582 BiometricReadResultsReplyReceived?.Invoke(
this,
1583 new BiometricReadResultsReplyEventArgs(reply.ConnectionId,
1588 BiometricMatchReplyReceived?.Invoke(
this,
1589 new BiometricMatchReplyEventArgs(reply.ConnectionId,
1595 catch (Exception ex)
1597 _logger.LogError(ex,
1598 "Error in typed reply event handler for reply {ReplyType} from address {Address}",
1606 reply.ReplyMessage.
Type, reply.ReplyMessage.
Payload));
1608 catch (Exception ex)
1610 _logger.LogError(ex,
1611 "Error in raw reply event handler for reply {ReplyType} from address {Address}",
1616 private event EventHandler<ReplyEventArgs> ReplyReceived;
1661 [Obsolete(
"Use Raw Card Data for incoming card reads.")]
1682 private event EventHandler<BiometricReadResultsReplyEventArgs> BiometricReadResultsReplyReceived;
1687 private event EventHandler<BiometricMatchReplyEventArgs> BiometricMatchReplyReceived;
1692 private event EventHandler<MultiPartMessageDataReplyEventArgs> PIVDataReplyReceived;
1697 private event EventHandler<MultiPartMessageDataReplyEventArgs> ExtendedIdReplyReceived;
1702 private event EventHandler<MultiPartMessageDataReplyEventArgs> AuthenticationChallengeResponseReceived;
1751 bool isSecureChannelEstablished)
1781 $
"{ConnectionId}:{Address} - Conn: {IsConnected}; Sec: {IsSecureChannelEstablished}";
2059 private class MultiPartMessageDataReplyEventArgs : EventArgs
2067 public MultiPartMessageDataReplyEventArgs(Guid connectionId,
byte address,
DataFragmentResponse dataFragmentResponse)
2069 ConnectionId = connectionId;
2077 public Guid ConnectionId {
get; }
2082 public byte Address {
get; }
2087 public DataFragmentResponse DataFragmentResponse {
get; }
2127 private class BiometricReadResultsReplyEventArgs : EventArgs
2135 public BiometricReadResultsReplyEventArgs(Guid connectionId,
byte address,
2138 ConnectionId = connectionId;
2146 public Guid ConnectionId {
get; }
2151 public byte Address {
get; }
2156 public BiometricReadResult BiometricReadResult {
get; }
2162 private class BiometricMatchReplyEventArgs : EventArgs
2170 public BiometricMatchReplyEventArgs(Guid connectionId,
byte address,
2171 BiometricMatchResult biometricMatchResult)
2173 ConnectionId = connectionId;
2175 BiometricMatchResult = biometricMatchResult;
2181 public Guid ConnectionId {
get; }
2186 public byte Address {
get; }
2191 public BiometricMatchResult BiometricMatchResult {
get; }
2232 public class FileTransferException : Exception
2257 public RawReplyEventArgs(Guid connectionId,
byte address,
byte replyType, ReadOnlyMemory<byte> payload)
2286 private class ReplyEventArgs : EventArgs
2288 public ReplyTracker Reply {
get;
set; }