26 internal class Bus : IDisposable
28 internal const byte DriverByte = 0xFF;
30 public static readonly TimeSpan DefaultPollInterval = TimeSpan.FromMilliseconds(200);
32 private readonly Dictionary<byte, bool> _lastOnlineConnectionStatus =
new ();
33 private readonly Dictionary<byte, bool> _lastSecureConnectionStatus =
new ();
35 private readonly ILogger<ControlPanel> _logger;
36 private readonly TimeSpan _pollInterval;
37 private readonly ChannelWriter<ReplyTracker> _replies;
38 private readonly Action<TraceEntry> _tracer;
39 private readonly SemaphoreSlim _commandAvailable =
new (0, 1);
40 private readonly IDeviceProxyFactory _deviceProxyFactory;
42 private CancellationTokenSource _cancellationTokenSource;
43 private Task _pollingTask;
44 private ImmutableSortedSet<DeviceProxy> _configuredDevices = ImmutableSortedSet<DeviceProxy>.Empty;
46 public Bus(
IOsdpConnection connection, ChannelWriter<ReplyTracker> replies, TimeSpan pollInterval,
47 Action<TraceEntry> tracer, IDeviceProxyFactory deviceProxyFactory,
49 ILogger<ControlPanel> logger =
null)
51 Connection = connection ??
throw new ArgumentNullException(nameof(connection));
52 _replies = replies ??
throw new ArgumentNullException(nameof(replies));
53 _pollInterval = pollInterval;
57 _deviceProxyFactory = deviceProxyFactory;
60 private bool IsPolling => _pollInterval > TimeSpan.Zero;
65 public Guid Id {
get; }
72 public IEnumerable<byte> ConfigureDeviceAddresses => _configuredDevices.Select(device => device.Address);
76 _commandAvailable?.Dispose();
77 _cancellationTokenSource?.Dispose();
80 private static TimeSpan IdleLineDelay(
IOsdpConnection connection,
int numberOfBytes) =>
81 LineTiming.ForCharacters(connection.
BaudRate, numberOfBytes);
86 public async Task Close()
88 var cancellationTokenSource = _cancellationTokenSource;
89 var pollingTask = _pollingTask;
91 if (cancellationTokenSource !=
null)
93 cancellationTokenSource.Cancel();
95 if (pollingTask !=
null)
97 await pollingTask.ConfigureAwait(
false);
100 _cancellationTokenSource =
null;
110 public void SendCommand(
byte address,
CommandData command)
112 var foundDevice = _configuredDevices.First(device => device.Address == address);
113 foundDevice.SendCommand(command);
114 SignalCommandAvailable();
117 private void SignalCommandAvailable()
120 if (_commandAvailable.CurrentCount != 0)
return;
123 _commandAvailable.Release();
125 catch (SemaphoreFullException)
129 catch (ObjectDisposedException)
142 public void AddDevice(
byte address,
bool useCrc,
bool useSecureChannel,
byte[] secureChannelKey =
null)
144 var configuredDevices = _configuredDevices.ToImmutableSortedSet();
146 var foundDevice = configuredDevices.FirstOrDefault(device => device.Address == address);
148 if (foundDevice !=
null)
150 configuredDevices = configuredDevices.Remove(foundDevice);
153 var addedDevice = _deviceProxyFactory.Create(address, useCrc, useSecureChannel, secureChannelKey);
155 configuredDevices = configuredDevices.Add(addedDevice);
157 _configuredDevices = configuredDevices;
164 public void RemoveDevice(
byte address)
166 var configuredDevices = _configuredDevices.ToImmutableSortedSet();
168 var foundDevice = configuredDevices.FirstOrDefault(device => device.Address == address);
169 if (foundDevice ==
null)
return;
171 configuredDevices = configuredDevices.Remove(foundDevice);
173 _configuredDevices = configuredDevices;
181 public bool IsOnline(
byte address)
183 var foundDevice = _configuredDevices.First(device => device.Address == address);
185 return foundDevice.IsConnected;
192 public void StartPolling()
194 var cancellationTokenSource = _cancellationTokenSource;
195 if (cancellationTokenSource !=
null)
return;
196 _cancellationTokenSource = cancellationTokenSource =
new CancellationTokenSource();
198 _pollingTask = Task.Run(async () =>
202 await PollingLoop(cancellationTokenSource.Token).ConfigureAwait(
false);
204 catch (Exception exception)
206 _logger?.LogError(exception,
207 "[{OsdpConnection}] Unexpected exception in polling loop for connection {Guid}", Connection,
217 private async Task PollingLoop(CancellationToken cancellationToken)
219 DateTime lastMessageSentTime = DateTime.MinValue;
220 while (!cancellationToken.IsCancellationRequested)
226 await Connection.
Open();
228 catch (Exception exception)
230 _logger?.LogError(exception, $
"[{Connection}] Error while opening connection");
231 foreach (var device
in _configuredDevices)
234 UpdateConnectionStatus(device);
237 await Delay(TimeSpan.FromSeconds(5), cancellationToken).ConfigureAwait(
false);
246 while (_pollInterval - (DateTime.UtcNow - lastMessageSentTime) > TimeSpan.Zero &&
247 !_configuredDevices.Any(device1 => device1.HasQueuedCommand) &&
248 !_configuredDevices.Any(device2 => device2.IsReceivingMultipartMessage) &&
249 !cancellationToken.IsCancellationRequested)
251 await Delay(TimeSpan.FromMilliseconds(10), cancellationToken).ConfigureAwait(
false);
254 lastMessageSentTime = DateTime.UtcNow;
256 if (!_configuredDevices.Any())
264 await WaitForCommand(TimeSpan.FromMilliseconds(10), cancellationToken).ConfigureAwait(
false);
268 if (cancellationToken.IsCancellationRequested)
273 foreach (var device
in _configuredDevices)
278 device.MessageControl.ResetSequence();
282 if (device.RequestDelay > DateTime.UtcNow)
287 var commandMessage = device.GetNextCommandData(IsPolling);
288 if (commandMessage ==
null || WaitingForNextMultiMessage(commandMessage.Code, device.IsSendingMultipartMessage))
298 if (IsPolling && UpdateConnectionStatus(device) && !device.IsConnected)
302 else if(IsPolling && !device.IsConnected)
304 device.RequestDelay = DateTime.UtcNow + TimeSpan.FromSeconds(1);
307 catch (Exception exception)
309 _logger?.LogError(exception, $
"[{Connection}] Error while notifying connection status for address {commandMessage.Address}");
314 reply = await SendCommandAndReceiveReply(commandMessage, device, cancellationToken).ConfigureAwait(
false);
319 if (reply.ReplyMessage.
Type != (
byte)
ReplyType.Busy && reply.ReplyMessage.
Type != (
byte)
ReplyType.Nak && device.UseSecureChannel &&
323 "A plain text message was received when the secure channel had been established");
324 device.ResetSecureChannelSession();
329 catch (TimeoutException exception)
334 case true when device.IsSecurityEstablished && !IsOnline(commandMessage.Address):
338 _logger?.LogDebug($
"[{Connection}] Retrying command {commandMessage} on connection {Id} because \"{exception.Message}\".");
339 device.RetryCommand(commandMessage.PayloadData as
CommandData, isBusyRetry:
false);
345 catch (Exception exception)
347 if (!cancellationToken.IsCancellationRequested)
349 _logger?.LogError(exception,
350 $
"[{Connection}] Error while sending command {commandMessage} to address {commandMessage.Address}. Connection {Id}");
360 _logger?.LogDebug($
"[{Connection}] Retrying command {commandMessage} on connection {Id} because the device is busy.");
361 device.RetryCommand(commandMessage.PayloadData as
CommandData, isBusyRetry:
true);
365 ProcessReply(reply, device);
368 catch (Exception exception)
370 _logger?.LogError(exception, $
"[{Connection}] Error while processing reply {reply} from address {reply.ReplyMessage.Address}");
374 await Task.Delay(IdleLineDelay(Connection, 2)).ConfigureAwait(
false);
381 await Connection.
Close();
383 catch(Exception exception)
385 _logger?.LogError(exception, $
"[{Connection}] Error while closing connection {Id}.");
389 private static async Task Delay(TimeSpan delay, CancellationToken cancellationToken)
393 await Task.Delay(delay, cancellationToken).ConfigureAwait(
false);
395 catch (OperationCanceledException)
401 private async Task WaitForCommand(TimeSpan timeout, CancellationToken cancellationToken)
405 await _commandAvailable.WaitAsync(timeout, cancellationToken).ConfigureAwait(
false);
407 catch (OperationCanceledException)
413 private static bool WaitingForNextMultiMessage(
byte messageCode,
bool sendingMultiMessage)
416 return sendingMultiMessage && messageCode != (byte)
CommandType.FileTransfer;
419 public event EventHandler<ConnectionStatusEventArgs> ConnectionStatusChanged;
425 public event EventHandler<SecureChannelHandshakeFailedEventArgs> SecureChannelHandshakeFailed;
432 private bool UpdateConnectionStatus(DeviceProxy device)
434 bool isConnected = device.IsConnected;
435 bool isSecureChannelEstablished = device.IsSecurityEstablished;
438 _lastOnlineConnectionStatus.TryAdd(device.Address,
false);
439 _lastSecureConnectionStatus.TryAdd(device.Address,
false);
441 bool onlineConnectionChanged = _lastOnlineConnectionStatus[device.Address] != isConnected;
442 bool secureChannelStatusChanged = _lastSecureConnectionStatus[device.Address] != isSecureChannelEstablished;
444 if (!onlineConnectionChanged && !secureChannelStatusChanged)
return false;
446 _lastOnlineConnectionStatus[device.Address] = isConnected;
447 _lastSecureConnectionStatus[device.Address] = isSecureChannelEstablished;
449 var handler = ConnectionStatusChanged;
450 handler?.Invoke(
this,
451 new ConnectionStatusEventArgs(device.Address, isConnected, device.IsSecurityEstablished));
456 private void ProcessReply(ReplyTracker reply, DeviceProxy device)
459 if (device.IsConnected && reply.ReplyMessage.ControlBlock.Sequence == 0)
465 if (!reply.IsValidReply)
481 device.ValidReplyHasBeenReceived(reply.ReplyMessage.
Sequence);
491 if ((device.IsSecurityEstablished &&
492 errorCode is
ErrorCode.DoesNotSupportSecurityBlock or
ErrorCode.CommunicationSecurityNotMet
494 errorCode ==
ErrorCode.UnexpectedSequenceNumber)
499 if (reply.IsReplyToSecureChannelHandshake &&
501 or
ErrorCode.CommunicationSecurityNotMet)
503 OnSecureChannelHandshakeFailed(device.Address, SecureChannelHandshakeFailure.Nak);
516 OnSecureChannelHandshakeFailed(device.Address, SecureChannelHandshakeFailure.KeyTypeMismatch);
521 OnSecureChannelHandshakeFailed(device.Address,
522 SecureChannelHandshakeFailure.ClientCryptogramRejected);
527 if (!reply.ValidateSecureChannelEstablishment())
529 _logger?.LogError($
"[{Connection}] Cryptogram not accepted by address {reply.ReplyMessage.Address}");
532 device.ResetSecureChannelSession();
533 OnSecureChannelHandshakeFailed(device.Address,
534 SecureChannelHandshakeFailure.ServerCryptogramRejected);
539 _replies.TryWrite(reply);
542 private void OnSecureChannelHandshakeFailed(
byte address, SecureChannelHandshakeFailure failure)
546 SecureChannelHandshakeFailed?.Invoke(
this,
new SecureChannelHandshakeFailedEventArgs(address, failure));
548 catch (Exception exception)
550 _logger?.LogError(exception, $
"[{Connection}] Error while notifying secure channel handshake failure for address {address}");
554 public void ResetDevice(
int address)
556 var foundDevice = _configuredDevices.First(device => device.Address == address);
558 ResetDevice(foundDevice);
561 public void SetSendingMultipartMessage(
byte address,
bool isSendingMultipartMessage)
563 var foundDevice = _configuredDevices.First(device => device.Address == address);
565 foundDevice.IsSendingMultipartMessage = isSendingMultipartMessage;
568 public void SetReceivingMultipartMessage(
byte address,
bool isReceivingMultipartMessage)
570 var foundDevice = _configuredDevices.First(device => device.Address == address);
572 foundDevice.IsReceivingMultipartMessage = isReceivingMultipartMessage;
575 public void SetSendingMultiMessageNoSecureChannel(
byte address,
bool isSendingMultiMessageNoSecureChannel)
577 var foundDevice = _configuredDevices.First(device => device.Address == address);
579 foundDevice.IsSendingMultiMessageNoSecureChannel = isSendingMultiMessageNoSecureChannel;
580 foundDevice.MessageControl.IsSendingMultiMessageNoSecureChannel = isSendingMultiMessageNoSecureChannel;
581 if (isSendingMultiMessageNoSecureChannel)
583 foundDevice.ResetSecureChannelSession();
587 public void SetRequestDelay(
byte address, DateTime requestDelay)
589 var foundDevice = _configuredDevices.First(device => device.Address == address);
591 foundDevice.RequestDelay = requestDelay;
594 private void ResetDevice(DeviceProxy device)
596 device.RequestDelay = DateTime.UtcNow + TimeSpan.FromSeconds(1);
597 AddDevice(device.Address, device.MessageControl.UseCrc, device.UseSecureChannel, device.SecureChannelKey);
600 private async Task<ReplyTracker> SendCommandAndReceiveReply(OutgoingMessage command, DeviceProxy device, CancellationToken cancellationToken)
605 commandData = command.BuildMessage(device.MessageSecureChannel);
607 catch (Exception exception)
609 _logger?.LogError(exception, $
"[{Connection}] Error while building command {command}");
613 await Connection.
WriteAsync(commandData).ConfigureAwait(
false);
617 await Task.Delay(IdleLineDelay(Connection, commandData.Length)).ConfigureAwait(
false);
619 return await ReceiveReply(command, device, cancellationToken);
622 private async Task<ReplyTracker> ReceiveReply(OutgoingMessage command, DeviceProxy device, CancellationToken cancellationToken)
626 var replyBuffer =
new Collection<byte>();
628 if (!await WaitForStartOfMessage(Connection, replyBuffer, device.IsSendingMultipartMessage ? TimeSpan.FromSeconds(1) : TimeSpan.Zero, cancellationToken).ConfigureAwait(
false))
630 throw new TimeoutException(
"Timeout waiting for reply message");
633 if (!await WaitForMessageLength(Connection, replyBuffer, cancellationToken).ConfigureAwait(
false))
635 throw new TimeoutException(
"Timeout waiting for reply message length");
638 if (!await WaitForRestOfMessage(Connection, replyBuffer, ExtractMessageLength(replyBuffer), cancellationToken).ConfigureAwait(
false))
640 throw new TimeoutException(
"Timeout waiting for rest of reply message");
647 if (!IsReplyToCommand(replyBuffer, command.ControlBlock.Sequence))
650 "[{Connection}] Discarding a reply with sequence number {ReplySequence} while waiting for the reply to sequence number {CommandSequence}",
651 Connection, ExtractSequence(replyBuffer), command.ControlBlock.Sequence);
655 return new ReplyTracker(Id,
new IncomingMessage(replyBuffer.ToArray(), device.MessageSecureChannel), command, device);
669 internal static bool IsReplyToCommand(IReadOnlyList<byte> replyBuffer,
byte commandSequence)
671 var replySequence = ExtractSequence(replyBuffer);
672 return replySequence == commandSequence || replySequence == 0;
675 private static byte ExtractSequence(IReadOnlyList<byte> replyBuffer) => (byte)(replyBuffer[4] & 0x03);
677 internal static ushort ExtractMessageLength(IReadOnlyList<byte> replyBuffer)
679 return Message.ConvertBytesToUnsignedShort(
new[] {replyBuffer[2], replyBuffer[3]});
682 internal static async Task<bool> WaitForRestOfMessage(
IOsdpConnection connection, ICollection<byte> replyBuffer, ushort replyLength, CancellationToken cancellationToken)
684 while (replyBuffer.Count < replyLength)
686 int maxReadBufferLength = connection.BaudRate / 40;
687 int remainingLength = replyLength - replyBuffer.Count;
688 byte[] readBuffer =
new byte[Math.Min(maxReadBufferLength, remainingLength)];
690 await TimeOutReadAsync(connection, readBuffer, connection.
ReplyTimeout + IdleLineDelay(connection, readBuffer.Length),
692 .ConfigureAwait(
false);
695 for (
int index = 0; index < bytesRead; index++)
697 replyBuffer.Add(readBuffer[index]);
709 internal static async Task<bool> WaitForMessageLength(
IOsdpConnection connection, ICollection<byte> replyBuffer, CancellationToken cancellationToken)
711 while (replyBuffer.Count < 4)
713 byte[] readBuffer =
new byte[4];
715 await TimeOutReadAsync(connection, readBuffer, connection.
ReplyTimeout, cancellationToken)
716 .ConfigureAwait(
false);
719 for (
int index = 0; index < bytesRead; index++)
721 replyBuffer.Add(readBuffer[index]);
733 internal static async Task<bool> WaitForStartOfMessage(
IOsdpConnection connection, ICollection<byte> replyBuffer, TimeSpan extraWait, CancellationToken cancellationToken)
737 byte[] readBuffer =
new byte[1];
738 int bytesRead = await TimeOutReadAsync(connection, readBuffer,
741 .ConfigureAwait(
false);
752 replyBuffer.Add(readBuffer[0]);
759 private static async Task<int> TimeOutReadAsync(
IOsdpConnection connection,
byte[] buffer, TimeSpan timeout, CancellationToken cancellationToken)
761 using var timedCancellationTokenSource =
new CancellationTokenSource(timeout);
762 using var linkedCancellationTokenSource =
763 CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timedCancellationTokenSource.Token);
766 return await connection.
ReadAsync(buffer, linkedCancellationTokenSource.Token).ConfigureAwait(
false);
775 public class ConnectionStatusEventArgs
777 public ConnectionStatusEventArgs(
byte address,
bool isConnected,
bool isSecureSessionEstablished)
780 IsConnected = isConnected;
781 IsSecureSessionEstablished = isSecureSessionEstablished;
784 public byte Address {
get; }
786 public bool IsConnected {
get; }
788 public bool IsSecureSessionEstablished {
get; }
794 public enum SecureChannelHandshakeFailure
804 ClientCryptogramRejected,
814 ServerCryptogramRejected
817 public class SecureChannelHandshakeFailedEventArgs
819 public SecureChannelHandshakeFailedEventArgs(
byte address, SecureChannelHandshakeFailure failure)
825 public byte Address {
get; }
827 public SecureChannelHandshakeFailure Failure {
get; }