OSDP.Net 5.3.0-beta.3
A .NET library for implementing the Open Supervised Device Protocol (OSDP)
Loading...
Searching...
No Matches
Bus.cs
1using System;
2using System.Collections.Generic;
3using System.Collections.Immutable;
4using System.Collections.ObjectModel;
5using System.Linq;
6using System.Threading;
7using System.Threading.Channels;
8using System.Threading.Tasks;
9
10using Microsoft.Extensions.Logging;
11
18
19// ReSharper disable TemplateIsNotCompileTimeConstantProblem
20
21namespace OSDP.Net
22{
26 internal class Bus : IDisposable
27 {
28 internal const byte DriverByte = 0xFF;
29
30 public static readonly TimeSpan DefaultPollInterval = TimeSpan.FromMilliseconds(200);
31
32 private readonly Dictionary<byte, bool> _lastOnlineConnectionStatus = new ();
33 private readonly Dictionary<byte, bool> _lastSecureConnectionStatus = new ();
34
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;
41
42 private CancellationTokenSource _cancellationTokenSource;
43 private Task _pollingTask;
44 private ImmutableSortedSet<DeviceProxy> _configuredDevices = ImmutableSortedSet<DeviceProxy>.Empty;
45
46 public Bus(IOsdpConnection connection, ChannelWriter<ReplyTracker> replies, TimeSpan pollInterval,
47 Action<TraceEntry> tracer, IDeviceProxyFactory deviceProxyFactory,
48 // ReSharper disable once ContextualLoggerProblem
49 ILogger<ControlPanel> logger = null)
50 {
51 Connection = connection ?? throw new ArgumentNullException(nameof(connection));
52 _replies = replies ?? throw new ArgumentNullException(nameof(replies));
53 _pollInterval = pollInterval;
54 _tracer = tracer;
55 Id = Guid.NewGuid();
56 _logger = logger;
57 _deviceProxyFactory = deviceProxyFactory;
58 }
59
60 private bool IsPolling => _pollInterval > TimeSpan.Zero;
61
65 public Guid Id { get; }
66
70 public IOsdpConnection Connection { get; private set; }
71
72 public IEnumerable<byte> ConfigureDeviceAddresses => _configuredDevices.Select(device => device.Address);
73
74 public void Dispose()
75 {
76 _commandAvailable?.Dispose();
77 _cancellationTokenSource?.Dispose();
78 }
79
80 private static TimeSpan IdleLineDelay(IOsdpConnection connection, int numberOfBytes) =>
81 LineTiming.ForCharacters(connection.BaudRate, numberOfBytes);
82
86 public async Task Close()
87 {
88 var cancellationTokenSource = _cancellationTokenSource;
89 var pollingTask = _pollingTask;
90
91 if (cancellationTokenSource != null)
92 {
93 cancellationTokenSource.Cancel();
94
95 if (pollingTask != null)
96 {
97 await pollingTask.ConfigureAwait(false);
98 }
99
100 _cancellationTokenSource = null;
101 _pollingTask = null;
102 }
103 }
104
110 public void SendCommand(byte address, CommandData command)
111 {
112 var foundDevice = _configuredDevices.First(device => device.Address == address);
113 foundDevice.SendCommand(command);
114 SignalCommandAvailable();
115 }
116
117 private void SignalCommandAvailable()
118 {
119 // Collapse repeated signals into one, like the AutoResetEvent this replaces
120 if (_commandAvailable.CurrentCount != 0) return;
121 try
122 {
123 _commandAvailable.Release();
124 }
125 catch (SemaphoreFullException)
126 {
127 // Another caller signaled first
128 }
129 catch (ObjectDisposedException)
130 {
131 // Bus is shutting down
132 }
133 }
134
142 public void AddDevice(byte address, bool useCrc, bool useSecureChannel, byte[] secureChannelKey = null)
143 {
144 var configuredDevices = _configuredDevices.ToImmutableSortedSet();
145
146 var foundDevice = configuredDevices.FirstOrDefault(device => device.Address == address);
147
148 if (foundDevice != null)
149 {
150 configuredDevices = configuredDevices.Remove(foundDevice);
151 }
152
153 var addedDevice = _deviceProxyFactory.Create(address, useCrc, useSecureChannel, secureChannelKey);
154
155 configuredDevices = configuredDevices.Add(addedDevice);
156
157 _configuredDevices = configuredDevices;
158 }
159
164 public void RemoveDevice(byte address)
165 {
166 var configuredDevices = _configuredDevices.ToImmutableSortedSet();
167
168 var foundDevice = configuredDevices.FirstOrDefault(device => device.Address == address);
169 if (foundDevice == null) return;
170
171 configuredDevices = configuredDevices.Remove(foundDevice);
172
173 _configuredDevices = configuredDevices;
174 }
175
181 public bool IsOnline(byte address)
182 {
183 var foundDevice = _configuredDevices.First(device => device.Address == address);
184
185 return foundDevice.IsConnected;
186 }
187
192 public void StartPolling()
193 {
194 var cancellationTokenSource = _cancellationTokenSource;
195 if (cancellationTokenSource != null) return;
196 _cancellationTokenSource = cancellationTokenSource = new CancellationTokenSource();
197
198 _pollingTask = Task.Run(async () =>
199 {
200 try
201 {
202 await PollingLoop(cancellationTokenSource.Token).ConfigureAwait(false);
203 }
204 catch (Exception exception)
205 {
206 _logger?.LogError(exception,
207 "[{OsdpConnection}] Unexpected exception in polling loop for connection {Guid}", Connection,
208 Id);
209 }
210 });
211 }
212
217 private async Task PollingLoop(CancellationToken cancellationToken)
218 {
219 DateTime lastMessageSentTime = DateTime.MinValue;
220 while (!cancellationToken.IsCancellationRequested)
221 {
222 if (!Connection.IsOpen)
223 {
224 try
225 {
226 await Connection.Open();
227 }
228 catch (Exception exception)
229 {
230 _logger?.LogError(exception, $"[{Connection}] Error while opening connection");
231 foreach (var device in _configuredDevices)
232 {
233 ResetDevice(device);
234 UpdateConnectionStatus(device);
235 }
236
237 await Delay(TimeSpan.FromSeconds(5), cancellationToken).ConfigureAwait(false);
238
239 continue;
240 }
241 }
242
243 if (IsPolling)
244 {
245 // Allow for immediate processing of commands in queue or incoming multipart messages
246 while (_pollInterval - (DateTime.UtcNow - lastMessageSentTime) > TimeSpan.Zero &&
247 !_configuredDevices.Any(device1 => device1.HasQueuedCommand) &&
248 !_configuredDevices.Any(device2 => device2.IsReceivingMultipartMessage) &&
249 !cancellationToken.IsCancellationRequested)
250 {
251 await Delay(TimeSpan.FromMilliseconds(10), cancellationToken).ConfigureAwait(false);
252 }
253
254 lastMessageSentTime = DateTime.UtcNow;
255
256 if (!_configuredDevices.Any())
257 {
258 continue;
259 }
260 }
261 else
262 {
263 // Keep CPU usage down while waiting for next command
264 await WaitForCommand(TimeSpan.FromMilliseconds(10), cancellationToken).ConfigureAwait(false);
265 }
266
267 // Don't put another round on the wire once the connection is being stopped
268 if (cancellationToken.IsCancellationRequested)
269 {
270 break;
271 }
272
273 foreach (var device in _configuredDevices)
274 {
275 // Right now it always sends sequence 0
276 if (!IsPolling)
277 {
278 device.MessageControl.ResetSequence();
279 }
280
281 // Requested delay for multi-messages and resets
282 if (device.RequestDelay > DateTime.UtcNow)
283 {
284 continue;
285 }
286
287 var commandMessage = device.GetNextCommandData(IsPolling);
288 if (commandMessage == null || WaitingForNextMultiMessage(commandMessage.Code, device.IsSendingMultipartMessage))
289 {
290 continue;
291 }
292
293 ReplyTracker reply;
294
295 try
296 {
297 // Reset the device if it loses connection
298 if (IsPolling && UpdateConnectionStatus(device) && !device.IsConnected)
299 {
300 ResetDevice(device);
301 }
302 else if(IsPolling && !device.IsConnected)
303 {
304 device.RequestDelay = DateTime.UtcNow + TimeSpan.FromSeconds(1);
305 }
306 }
307 catch (Exception exception)
308 {
309 _logger?.LogError(exception, $"[{Connection}] Error while notifying connection status for address {commandMessage.Address}");
310 }
311
312 try
313 {
314 reply = await SendCommandAndReceiveReply(commandMessage, device, cancellationToken).ConfigureAwait(false);
315
316 // Prevent plain text message replies when secure channel has been established
317 // The busy and Nak reply types are a special case which is allowed to be sent as insecure message on a secure channel
318 // Workaround for KeySet command sending back a clear text Ack
319 if (reply.ReplyMessage.Type != (byte)ReplyType.Busy && reply.ReplyMessage.Type != (byte)ReplyType.Nak && device.UseSecureChannel &&
320 device.IsSecurityEstablished && !reply.ReplyMessage.IsSecureMessage && commandMessage.Code != (byte)CommandType.KeySet)
321 {
322 _logger?.LogWarning(
323 "A plain text message was received when the secure channel had been established");
324 device.ResetSecureChannelSession();
325 ResetDevice(device);
326 continue;
327 }
328 }
329 catch (TimeoutException exception)
330 {
331 switch (IsPolling)
332 {
333 // Make sure the security is reset properly if reader goes offline
334 case true when device.IsSecurityEstablished && !IsOnline(commandMessage.Address):
335 ResetDevice(device);
336 break;
337 default:
338 _logger?.LogDebug($"[{Connection}] Retrying command {commandMessage} on connection {Id} because \"{exception.Message}\".");
339 device.RetryCommand(commandMessage.PayloadData as CommandData, isBusyRetry: false);
340 break;
341 }
342
343 continue;
344 }
345 catch (Exception exception)
346 {
347 if (!cancellationToken.IsCancellationRequested)
348 {
349 _logger?.LogError(exception,
350 $"[{Connection}] Error while sending command {commandMessage} to address {commandMessage.Address}. Connection {Id}");
351 }
352
353 continue;
354 }
355
356 try
357 {
358 if (reply.ReplyMessage.Type == (byte)ReplyType.Busy)
359 {
360 _logger?.LogDebug($"[{Connection}] Retrying command {commandMessage} on connection {Id} because the device is busy.");
361 device.RetryCommand(commandMessage.PayloadData as CommandData, isBusyRetry: true);
362 }
363 else
364 {
365 ProcessReply(reply, device);
366 }
367 }
368 catch (Exception exception)
369 {
370 _logger?.LogError(exception, $"[{Connection}] Error while processing reply {reply} from address {reply.ReplyMessage.Address}");
371 continue;
372 }
373
374 await Task.Delay(IdleLineDelay(Connection, 2)).ConfigureAwait(false);
375 }
376 }
377
378 // The polling task is complete. Time to close the connection.
379 try
380 {
381 await Connection.Close();
382 }
383 catch(Exception exception)
384 {
385 _logger?.LogError(exception, $"[{Connection}] Error while closing connection {Id}.");
386 }
387 }
388
389 private static async Task Delay(TimeSpan delay, CancellationToken cancellationToken)
390 {
391 try
392 {
393 await Task.Delay(delay, cancellationToken).ConfigureAwait(false);
394 }
395 catch (OperationCanceledException)
396 {
397 // The polling loop checks the token and exits normally, so the connection is still closed
398 }
399 }
400
401 private async Task WaitForCommand(TimeSpan timeout, CancellationToken cancellationToken)
402 {
403 try
404 {
405 await _commandAvailable.WaitAsync(timeout, cancellationToken).ConfigureAwait(false);
406 }
407 catch (OperationCanceledException)
408 {
409 // The polling loop checks the token and exits normally, so the connection is still closed
410 }
411 }
412
413 private static bool WaitingForNextMultiMessage(byte messageCode, bool sendingMultiMessage)
414 {
415 // File transfer override, it doesn't need to wait
416 return sendingMultiMessage && messageCode != (byte)CommandType.FileTransfer;
417 }
418
419 public event EventHandler<ConnectionStatusEventArgs> ConnectionStatusChanged;
420
425 public event EventHandler<SecureChannelHandshakeFailedEventArgs> SecureChannelHandshakeFailed;
426
432 private bool UpdateConnectionStatus(DeviceProxy device)
433 {
434 bool isConnected = device.IsConnected;
435 bool isSecureChannelEstablished = device.IsSecurityEstablished;
436
437 // Default to false when initializing status checks
438 _lastOnlineConnectionStatus.TryAdd(device.Address, false);
439 _lastSecureConnectionStatus.TryAdd(device.Address, false);
440
441 bool onlineConnectionChanged = _lastOnlineConnectionStatus[device.Address] != isConnected;
442 bool secureChannelStatusChanged = _lastSecureConnectionStatus[device.Address] != isSecureChannelEstablished;
443
444 if (!onlineConnectionChanged && !secureChannelStatusChanged) return false;
445
446 _lastOnlineConnectionStatus[device.Address] = isConnected;
447 _lastSecureConnectionStatus[device.Address] = isSecureChannelEstablished;
448
449 var handler = ConnectionStatusChanged;
450 handler?.Invoke(this,
451 new ConnectionStatusEventArgs(device.Address, isConnected, device.IsSecurityEstablished));
452
453 return true;
454 }
455
456 private void ProcessReply(ReplyTracker reply, DeviceProxy device)
457 {
458 // Request from PD to reset connection
459 if (device.IsConnected && reply.ReplyMessage.ControlBlock.Sequence == 0)
460 {
461 ResetDevice(device);
462 return;
463 }
464
465 if (!reply.IsValidReply)
466 {
467 return;
468 }
469
470 if (reply.ReplyMessage.IsSecureMessage)
471 {
472 if (!reply.ReplyMessage.IsValidMac)
473 {
474 ResetDevice(device);
475 return;
476 }
477 }
478
479 if (reply.ReplyMessage.Type != (byte)ReplyType.Busy)
480 {
481 device.ValidReplyHasBeenReceived(reply.ReplyMessage.Sequence);
482 }
483 else
484 {
485 return;
486 }
487
488 if (reply.ReplyMessage.Type == (byte)ReplyType.Nak)
489 {
490 var errorCode = (ErrorCode)reply.ReplyMessage.Payload.First();
491 if ((device.IsSecurityEstablished &&
492 errorCode is ErrorCode.DoesNotSupportSecurityBlock or ErrorCode.CommunicationSecurityNotMet
493 or ErrorCode.UnableToProcessCommand) ||
494 errorCode == ErrorCode.UnexpectedSequenceNumber)
495 {
496 ResetDevice(device);
497 }
498
499 if (reply.IsReplyToSecureChannelHandshake &&
500 errorCode is ErrorCode.UnknownCommandCode or ErrorCode.DoesNotSupportSecurityBlock
501 or ErrorCode.CommunicationSecurityNotMet)
502 {
503 OnSecureChannelHandshakeFailed(device.Address, SecureChannelHandshakeFailure.Nak);
504 }
505 }
506
507 switch ((ReplyType)reply.ReplyMessage.Type)
508 {
509 case ReplyType.CrypticData:
510 try
511 {
512 device.InitializeSecureChannel(reply.ReplyMessage.Payload, reply.ReplyMessage.SecureBlockData);
513 }
515 {
516 OnSecureChannelHandshakeFailed(device.Address, SecureChannelHandshakeFailure.KeyTypeMismatch);
517 throw;
518 }
519 catch (Exception)
520 {
521 OnSecureChannelHandshakeFailed(device.Address,
522 SecureChannelHandshakeFailure.ClientCryptogramRejected);
523 throw;
524 }
525 break;
526 case ReplyType.InitialRMac:
527 if (!reply.ValidateSecureChannelEstablishment())
528 {
529 _logger?.LogError($"[{Connection}] Cryptogram not accepted by address {reply.ReplyMessage.Address}");
530
531 // Restart the handshake with a new RND.A rather than resending the same osdp_SCRYPT
532 device.ResetSecureChannelSession();
533 OnSecureChannelHandshakeFailed(device.Address,
534 SecureChannelHandshakeFailure.ServerCryptogramRejected);
535 }
536 break;
537 }
538
539 _replies.TryWrite(reply);
540 }
541
542 private void OnSecureChannelHandshakeFailed(byte address, SecureChannelHandshakeFailure failure)
543 {
544 try
545 {
546 SecureChannelHandshakeFailed?.Invoke(this, new SecureChannelHandshakeFailedEventArgs(address, failure));
547 }
548 catch (Exception exception)
549 {
550 _logger?.LogError(exception, $"[{Connection}] Error while notifying secure channel handshake failure for address {address}");
551 }
552 }
553
554 public void ResetDevice(int address)
555 {
556 var foundDevice = _configuredDevices.First(device => device.Address == address);
557
558 ResetDevice(foundDevice);
559 }
560
561 public void SetSendingMultipartMessage(byte address, bool isSendingMultipartMessage)
562 {
563 var foundDevice = _configuredDevices.First(device => device.Address == address);
564
565 foundDevice.IsSendingMultipartMessage = isSendingMultipartMessage;
566 }
567
568 public void SetReceivingMultipartMessage(byte address, bool isReceivingMultipartMessage)
569 {
570 var foundDevice = _configuredDevices.First(device => device.Address == address);
571
572 foundDevice.IsReceivingMultipartMessage = isReceivingMultipartMessage;
573 }
574
575 public void SetSendingMultiMessageNoSecureChannel(byte address, bool isSendingMultiMessageNoSecureChannel)
576 {
577 var foundDevice = _configuredDevices.First(device => device.Address == address);
578
579 foundDevice.IsSendingMultiMessageNoSecureChannel = isSendingMultiMessageNoSecureChannel;
580 foundDevice.MessageControl.IsSendingMultiMessageNoSecureChannel = isSendingMultiMessageNoSecureChannel;
581 if (isSendingMultiMessageNoSecureChannel)
582 {
583 foundDevice.ResetSecureChannelSession();
584 }
585 }
586
587 public void SetRequestDelay(byte address, DateTime requestDelay)
588 {
589 var foundDevice = _configuredDevices.First(device => device.Address == address);
590
591 foundDevice.RequestDelay = requestDelay;
592 }
593
594 private void ResetDevice(DeviceProxy device)
595 {
596 device.RequestDelay = DateTime.UtcNow + TimeSpan.FromSeconds(1);
597 AddDevice(device.Address, device.MessageControl.UseCrc, device.UseSecureChannel, device.SecureChannelKey);
598 }
599
600 private async Task<ReplyTracker> SendCommandAndReceiveReply(OutgoingMessage command, DeviceProxy device, CancellationToken cancellationToken)
601 {
602 byte[] commandData;
603 try
604 {
605 commandData = command.BuildMessage(device.MessageSecureChannel);
606 }
607 catch (Exception exception)
608 {
609 _logger?.LogError(exception, $"[{Connection}] Error while building command {command}");
610 throw;
611 }
612
613 await Connection.WriteAsync(commandData).ConfigureAwait(false);
614
615 _tracer(new TraceEntry(TraceDirection.Output, Id, commandData.Skip(1).ToArray()));
616
617 await Task.Delay(IdleLineDelay(Connection, commandData.Length)).ConfigureAwait(false);
618
619 return await ReceiveReply(command, device, cancellationToken);
620 }
621
622 private async Task<ReplyTracker> ReceiveReply(OutgoingMessage command, DeviceProxy device, CancellationToken cancellationToken)
623 {
624 while (true)
625 {
626 var replyBuffer = new Collection<byte>();
627
628 if (!await WaitForStartOfMessage(Connection, replyBuffer, device.IsSendingMultipartMessage ? TimeSpan.FromSeconds(1) : TimeSpan.Zero, cancellationToken).ConfigureAwait(false))
629 {
630 throw new TimeoutException("Timeout waiting for reply message");
631 }
632
633 if (!await WaitForMessageLength(Connection, replyBuffer, cancellationToken).ConfigureAwait(false))
634 {
635 throw new TimeoutException("Timeout waiting for reply message length");
636 }
637
638 if (!await WaitForRestOfMessage(Connection, replyBuffer, ExtractMessageLength(replyBuffer), cancellationToken).ConfigureAwait(false))
639 {
640 throw new TimeoutException("Timeout waiting for rest of reply message");
641 }
642
643 _tracer(new TraceEntry(TraceDirection.Input, Id, replyBuffer.ToArray()));
644
645 // Checked on the raw bytes: parsing a secure reply runs it through the MAC chain, which a
646 // reply from an earlier session would corrupt
647 if (!IsReplyToCommand(replyBuffer, command.ControlBlock.Sequence))
648 {
649 _logger?.LogDebug(
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);
652 continue;
653 }
654
655 return new ReplyTracker(Id, new IncomingMessage(replyBuffer.ToArray(), device.MessageSecureChannel), command, device);
656 }
657 }
658
669 internal static bool IsReplyToCommand(IReadOnlyList<byte> replyBuffer, byte commandSequence)
670 {
671 var replySequence = ExtractSequence(replyBuffer);
672 return replySequence == commandSequence || replySequence == 0;
673 }
674
675 private static byte ExtractSequence(IReadOnlyList<byte> replyBuffer) => (byte)(replyBuffer[4] & 0x03);
676
677 internal static ushort ExtractMessageLength(IReadOnlyList<byte> replyBuffer)
678 {
679 return Message.ConvertBytesToUnsignedShort(new[] {replyBuffer[2], replyBuffer[3]});
680 }
681
682 internal static async Task<bool> WaitForRestOfMessage(IOsdpConnection connection, ICollection<byte> replyBuffer, ushort replyLength, CancellationToken cancellationToken)
683 {
684 while (replyBuffer.Count < replyLength)
685 {
686 int maxReadBufferLength = connection.BaudRate / 40;
687 int remainingLength = replyLength - replyBuffer.Count;
688 byte[] readBuffer = new byte[Math.Min(maxReadBufferLength, remainingLength)];
689 int bytesRead =
690 await TimeOutReadAsync(connection, readBuffer, connection.ReplyTimeout + IdleLineDelay(connection, readBuffer.Length),
691 cancellationToken)
692 .ConfigureAwait(false);
693 if (bytesRead > 0)
694 {
695 for (int index = 0; index < bytesRead; index++)
696 {
697 replyBuffer.Add(readBuffer[index]);
698 }
699 }
700 else
701 {
702 return false;
703 }
704 }
705
706 return true;
707 }
708
709 internal static async Task<bool> WaitForMessageLength(IOsdpConnection connection, ICollection<byte> replyBuffer, CancellationToken cancellationToken)
710 {
711 while (replyBuffer.Count < 4)
712 {
713 byte[] readBuffer = new byte[4];
714 int bytesRead =
715 await TimeOutReadAsync(connection, readBuffer, connection.ReplyTimeout, cancellationToken)
716 .ConfigureAwait(false);
717 if (bytesRead > 0)
718 {
719 for (int index = 0; index < bytesRead; index++)
720 {
721 replyBuffer.Add(readBuffer[index]);
722 }
723 }
724 else
725 {
726 return false;
727 }
728 }
729
730 return true;
731 }
732
733 internal static async Task<bool> WaitForStartOfMessage(IOsdpConnection connection, ICollection<byte> replyBuffer, TimeSpan extraWait, CancellationToken cancellationToken)
734 {
735 while (true)
736 {
737 byte[] readBuffer = new byte[1];
738 int bytesRead = await TimeOutReadAsync(connection, readBuffer,
739 connection.ReplyTimeout + extraWait,
740 cancellationToken)
741 .ConfigureAwait(false);
742 if (bytesRead == 0)
743 {
744 return false;
745 }
746
747 if (readBuffer[0] != Message.StartOfMessage)
748 {
749 continue;
750 }
751
752 replyBuffer.Add(readBuffer[0]);
753 break;
754 }
755
756 return true;
757 }
758
759 private static async Task<int> TimeOutReadAsync(IOsdpConnection connection, byte[] buffer, TimeSpan timeout, CancellationToken cancellationToken)
760 {
761 using var timedCancellationTokenSource = new CancellationTokenSource(timeout);
762 using var linkedCancellationTokenSource =
763 CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timedCancellationTokenSource.Token);
764 try
765 {
766 return await connection.ReadAsync(buffer, linkedCancellationTokenSource.Token).ConfigureAwait(false);
767 }
768 catch
769 {
770 // TODO: be more selective with exception types?
771 return 0;
772 }
773 }
774
775 public class ConnectionStatusEventArgs
776 {
777 public ConnectionStatusEventArgs(byte address, bool isConnected, bool isSecureSessionEstablished)
778 {
779 Address = address;
780 IsConnected = isConnected;
781 IsSecureSessionEstablished = isSecureSessionEstablished;
782 }
783
784 public byte Address { get; }
785
786 public bool IsConnected { get; }
787
788 public bool IsSecureSessionEstablished { get; }
789 }
790
794 public enum SecureChannelHandshakeFailure
795 {
799 Nak,
800
804 ClientCryptogramRejected,
805
809 KeyTypeMismatch,
810
814 ServerCryptogramRejected
815 }
816
817 public class SecureChannelHandshakeFailedEventArgs
818 {
819 public SecureChannelHandshakeFailedEventArgs(byte address, SecureChannelHandshakeFailure failure)
820 {
821 Address = address;
822 Failure = failure;
823 }
824
825 public byte Address { get; }
826
827 public SecureChannelHandshakeFailure Failure { get; }
828 }
829 }
830}
Represents a message that was received from the wire.
bool IsValidMac
Indicates if the message has a valid MAC signature which was validated via local message channel cont...
byte Type
Command/reply code of the message.
byte Sequence
Message sequence number.
byte[] SecureBlockData
Raw security block bytes.
bool IsSecureMessage
Indicates if the message was sent via an established secure channel.
byte[] Payload
Returns the raw message payload.
A base message class for sending or replying.
Definition Message.cs:12
const byte StartOfMessage
OSDP message SOM (start of the message) byte.
Definition Message.cs:21
A negative reply.
Definition Nak.cs:14
Exception thrown when the PD's Security Control Block (SCB) key type indicator does not match what th...
Definition Exceptions.cs:99
Defines a connection for communicating via OSDP protocol.
Task< int > ReadAsync(byte[] buffer, CancellationToken token)
Read from connection.
TimeSpan ReplyTimeout
Timeout value waiting for a reply.
Task WriteAsync(byte[] buffer)
Write to connection.
Task Close()
Close the connection for communications.
int BaudRate
Speed of the connection.
bool IsOpen
Is the connection open and ready to communicate.
Task Open()
Open the connection for communications.
ReplyType
Identifies the type of OSDP protocol reply (PD -> ACU) message.
Definition ReplyType.cs:7
CommandType
Identifies the type of OSDP protocol command (ACU -> PD) message.
Definition CommandType.cs:7
ErrorCode
Error code.
Definition Nak.cs:99
TraceDirection
Direction of trace.
Definition TraceEntry.cs:9
Represents low level data sent on the wire between the control panel and the devices.
Definition TraceEntry.cs:22