OSDP.Net 5.2.1
A .NET library for implementing the Open Supervised Device Protocol (OSDP)
Loading...
Searching...
No Matches
TcpOsdpConnection.cs
1using System;
2using System.IO;
3using System.Net.Sockets;
4using System.Threading;
5using System.Threading.Tasks;
6using Microsoft.Extensions.Logging;
7
9
19internal sealed class TcpOsdpConnection : OsdpConnection
20{
21 private readonly ILogger _logger;
22 private TcpClient _tcpClient;
23 private NetworkStream _stream;
24
31 public TcpOsdpConnection(
32 TcpClient tcpClient, int baudRate, ILoggerFactory loggerFactory) : base(baudRate)
33 {
34 IsOpen = true;
35 _tcpClient = tcpClient;
36 _stream = tcpClient.GetStream();
37 _logger = loggerFactory?.CreateLogger<TcpOsdpConnection>();
38 }
39
41 public override async Task<int> ReadAsync(byte[] buffer, CancellationToken token)
42 {
43 try
44 {
45 var bytes = await _stream.ReadAsync(buffer, 0, buffer.Length, token).ConfigureAwait(false);
46 if (bytes == 0) { IsOpen = false; }
47 return bytes;
48 }
49 catch (Exception exception)
50 {
51 if (exception is not OperationCanceledException && IsOpen)
52 {
53 if (exception is IOException && exception.InnerException is SocketException)
54 {
55 _logger?.LogInformation("Error reading TCP stream: {ExceptionMessage}", exception.Message);
56 }
57 else
58 {
59 _logger?.LogWarning(exception, "Error reading TCP stream");
60 }
61
62 IsOpen = false;
63 }
64 return 0;
65 }
66 }
67
69 public override async Task WriteAsync(byte[] buffer)
70 {
71 try
72 {
73 await _stream.WriteAsync(buffer, 0, buffer.Length).ConfigureAwait(false);
74 }
75 catch (Exception ex)
76 {
77 if (IsOpen)
78 {
79 _logger?.LogWarning(ex, "Error writing TCP stream");
80 IsOpen = false;
81 }
82 }
83 }
84
89 public override Task Open() => throw new NotSupportedException("Connection is already established");
90
92 public override Task Close()
93 {
94 IsOpen = false;
95 _stream?.Dispose();
96 _tcpClient?.Dispose();
97 _stream = null;
98 _tcpClient = null;
99 return Task.CompletedTask;
100 }
101}
Base OSDP connection class.
Task Open()
Open the connection for communications.
Task Close()
Close the connection for communications.
bool IsOpen
Is the connection open and ready to communicate.