-
-
Notifications
You must be signed in to change notification settings - Fork 108
/
Port.cs
274 lines (249 loc) · 8.71 KB
/
Port.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO.Ports;
using System.Threading;
namespace Iot.Device.Modbus
{
/// <summary>
/// Represents a serial port used for Modbus communication.
/// </summary>
public abstract class Port : IDisposable
{
private SerialPort _serialPort;
/// <summary>
/// Formats an array of bytes as a string.
/// </summary>
/// <param name="buffer">The buffer to format.</param>
/// <returns>A string representation of the buffer in hexadecimal format.</returns>
protected static string Format(byte[] buffer)
{
if (buffer.Length > 0)
{
var sb = new System.Text.StringBuilder();
foreach (var b in buffer)
{
sb.Append(b.ToString("X2"));
sb.Append(' ');
}
return sb.ToString();
}
else
{
return string.Empty;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="Port"/> class with the specified port settings.
/// </summary>
/// <param name="portName">The name of the serial port.</param>
/// <param name="baudRate">The baud rate.</param>
/// <param name="parity">The parity.</param>
/// <param name="dataBits">The number of data bits.</param>
/// <param name="stopBits">The number of stop bits.</param>
/// <param name="receivedBytesThreshold">The number of bytes required before the DataReceived event is fired. Default is 1.</param>
/// <param name="mode">The mode of serial port, default is RS485.</param>
public Port(
string portName,
int baudRate,
Parity parity,
int dataBits,
StopBits stopBits,
int receivedBytesThreshold = 1,
SerialMode mode = SerialMode.RS485)
{
_serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
_serialPort.Mode = mode;
_serialPort.Handshake = Handshake.RequestToSend;
_serialPort.ReceivedBytesThreshold = receivedBytesThreshold;
}
/// <summary>
/// Initializes a new instance of the <see cref="Port"/> class with the specified serial port.
/// </summary>
/// <param name="port">The serial port.</param>
/// <param name="receivedBytesThreshold">The number of bytes required before the DataReceived event is fired. Default is 1.</param>
/// <param name="mode">The mode of serial port, default is RS485.</param>
public Port(SerialPort port, int receivedBytesThreshold = 1, SerialMode mode = SerialMode.RS485)
{
_serialPort = port;
_serialPort.Mode = mode;
if (receivedBytesThreshold != 1)
{
_serialPort.ReceivedBytesThreshold = receivedBytesThreshold;
}
}
/// <summary>
/// Gets the name of the serial port.
/// </summary>
public string PortName => _serialPort != null ? _serialPort.PortName : string.Empty;
/// <summary>
/// Gets a value indicating whether the serial port is open.
/// </summary>
public bool IsOpen => _serialPort != null ? _serialPort.IsOpen : false;
/// <summary>
/// Gets or sets the read timeout in milliseconds.
/// </summary>
public int ReadTimeout
{
get => _serialPort != null ? _serialPort.ReadTimeout : Timeout.Infinite;
set
{
if (_serialPort != null)
{
_serialPort.ReadTimeout = value;
}
}
}
/// <summary>
/// Gets or sets the write timeout in milliseconds.
/// </summary>
public int WriteTimeout
{
get => _serialPort != null ? _serialPort.WriteTimeout : Timeout.Infinite;
set
{
if (_serialPort != null)
{
_serialPort.WriteTimeout = value;
}
}
}
/// <summary>
/// Gets or sets the size of the input buffer.
/// </summary>
public int ReadBufferSize
{
get => _serialPort != null ? _serialPort.ReadBufferSize : 0;
set
{
if (_serialPort != null)
{
_serialPort.ReadBufferSize = value;
}
}
}
/// <summary>
/// Gets or sets the size of the output buffer.
/// </summary>
public int WriteBufferSize
{
get => _serialPort != null ? _serialPort.WriteBufferSize : 0;
set
{
if (_serialPort != null)
{
_serialPort.WriteBufferSize = value;
}
}
}
/// <summary>
/// Checks if the serial port is open and opens it if necessary.
/// </summary>
/// <returns>True if the serial port is open, false otherwise.</returns>
protected bool CheckOpen()
{
if (_serialPort != null)
{
if (!_serialPort.IsOpen)
{
_serialPort.DataReceived += (sender, args) =>
{
if (_serialPort.BytesToRead > 0)
{
DataReceived(_serialPort.BytesToRead);
}
};
_serialPort.Open();
}
return _serialPort.IsOpen;
}
return false;
}
/// <summary>
/// Event handler for the DataReceived event.
/// </summary>
/// <param name="bytesToRead">The number of bytes available to read.</param>
protected virtual void DataReceived(int bytesToRead)
{
}
/// <summary>
/// Reads a single byte of data from the serial port.
/// </summary>
/// <returns>The byte read from the serial port.</returns>
protected byte DataRead()
{
if (CheckOpen())
{
return (byte)_serialPort.ReadByte();
}
else
{
return 0;
}
}
/// <summary>
/// Reads a specified number of bytes from the serial port.
/// </summary>
/// <param name="length">The number of bytes to read.</param>
/// <returns>An array of bytes read from the serial port.</returns>
protected byte[] DataRead(int length)
{
var buffer = new byte[length];
if (CheckOpen())
{
for (int offset = 0; offset < buffer.Length;)
{
int count = _serialPort.Read(buffer, offset, buffer.Length - offset);
if (count < 1)
{
break;
}
offset += count;
}
}
return buffer;
}
/// <summary>
/// Writes a single byte of data to the serial port.
/// </summary>
/// <param name="value">The byte to write to the serial port.</param>
protected void DataWrite(byte value)
{
if (CheckOpen())
{
_serialPort.WriteByte(value);
}
}
/// <summary>
/// Writes a specified number of bytes to the serial port.
/// </summary>
/// <param name="buffer">The buffer that contains the data to write.</param>
/// <param name="offset">The zero-based byte offset in the buffer at which to begin writing.</param>
/// <param name="count">The number of bytes to write.</param>
protected void DataWrite(byte[] buffer, int offset, int count)
{
if (CheckOpen())
{
_serialPort.Write(buffer, offset, count);
#if DEBUG
System.Diagnostics.Debug.WriteLine($"{PortName} TX ({buffer.Length}): {Format(buffer)}");
#endif
}
}
/// <summary>
/// Releases the resources used by the serial port.
/// </summary>
public void Dispose()
{
if (_serialPort != null)
{
if (_serialPort.IsOpen)
{
_serialPort.Close();
}
_serialPort.Dispose();
_serialPort = null;
}
}
}
}