OSDP.Net 5.2.1
A .NET library for implementing the Open Supervised Device Protocol (OSDP)
Loading...
Searching...
No Matches
ReadOnlySerialPortOsdpConnection.cs
1using System;
2using System.IO.Ports;
3using System.Threading;
4using System.Threading.Tasks;
5
7{
13 {
14 private readonly string _portName;
15 private SerialPort _serialPort;
16
23 public ReadOnlySerialPortOsdpConnection(string portName, int baudRate) : base(baudRate)
24 {
25 _portName = portName ?? throw new ArgumentNullException(nameof(portName));
26 }
27
29 public override Task Open()
30 {
31 if (_serialPort == null)
32 {
33 _serialPort = new SerialPort(_portName, BaudRate)
34 {
35 DataBits = 8,
36 Parity = Parity.None,
37 StopBits = StopBits.One,
38 ReadTimeout = 1000,
39 Handshake = Handshake.None
40 };
41
42 _serialPort.Open();
43 IsOpen = true;
44 }
45
46 return Task.CompletedTask;
47 }
48
50 public override Task Close()
51 {
52 if (_serialPort != null)
53 {
54 _serialPort.Close();
55 _serialPort.Dispose();
56 _serialPort = null;
57 }
58
59 IsOpen = false;
60 return Task.CompletedTask;
61 }
62
67 public override Task WriteAsync(byte[] buffer)
68 {
69 throw new NotSupportedException(
70 "This is a read-only connection for passive monitoring. Write operations are not supported.");
71 }
72
74 public override async Task<int> ReadAsync(byte[] buffer, CancellationToken token)
75 {
76 if (_serialPort == null || !IsOpen)
77 {
78 throw new InvalidOperationException("Connection is not open.");
79 }
80
81 var task = _serialPort.BaseStream.ReadAsync(buffer, 0, buffer.Length, token);
82
83 if (await Task.WhenAny(task, Task.Delay(-1, token)) == task)
84 {
85 return await task.ConfigureAwait(false);
86 }
87
88 throw new TimeoutException();
89 }
90
92 public override string ToString()
93 {
94 return $"{_portName} (Read-Only)";
95 }
96 }
97}
int BaudRate
Speed of the connection.
OsdpConnection(int baudRate)
Creates an instance of OsdpConnection.
virtual bool IsOpen
Is the connection open and ready to communicate.
ReadOnlySerialPortOsdpConnection(string portName, int baudRate)
Initializes a new instance of the ReadOnlySerialPortOsdpConnection class.
override Task Open()
Open the connection for communications.
override Task Close()
Close the connection for communications.
override Task WriteAsync(byte[] buffer)
Write to connection.
override async Task< int > ReadAsync(byte[] buffer, CancellationToken token)
Read from connection.Number of actual bytes read