-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmodbus.cs
334 lines (303 loc) · 10.5 KB
/
modbus.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
/**
* Original code from https://github.com/DRKPI/Modbus-Poll.git
* - Removed Regions
* - Added SendFc6
*
*
*
*
*
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
namespace HanmatekPSLib
{
class modbus
{
private SerialPort sp = new SerialPort();
public string modbusStatus;
//private int v;
public modbus()
{
}
public modbus(int v)
{
//this.v = v;
}
~modbus()
{
}
public bool Open(string portName, int baudRate, int databits, Parity parity, StopBits stopBits)
{
//Ensure port isn't already opened:
if (!sp.IsOpen)
{
//Assign desired settings to the serial port:
sp.PortName = portName;
sp.BaudRate = baudRate;
sp.DataBits = databits;
sp.Parity = parity;
sp.StopBits = stopBits;
//These timeouts are default and cannot be editted through the class at this point:
sp.ReadTimeout = 500;
sp.WriteTimeout = 500;
try
{
sp.Open();
}
catch (Exception err)
{
modbusStatus = "Error opening " + portName + ": " + err.Message;
return false;
}
modbusStatus = portName + " opened successfully";
return true;
}
else
{
modbusStatus = portName + " already opened";
return false;
}
}
public bool Close()
{
//Ensure port is opened before attempting to close:
if (sp.IsOpen)
{
try
{
sp.Close();
}
catch (Exception err)
{
modbusStatus = "Error closing " + sp.PortName + ": " + err.Message;
return false;
}
modbusStatus = sp.PortName + " closed successfully";
return true;
}
else
{
modbusStatus = sp.PortName + " is not open";
return false;
}
}
private void GetCRC(byte[] message, ref byte[] CRC)
{
//Function expects a modbus message of any length as well as a 2 byte CRC array in which to
//return the CRC values:
ushort CRCFull = 0xFFFF;
byte CRCHigh = 0xFF, CRCLow = 0xFF;
char CRCLSB;
for (int i = 0; i < (message.Length) - 2; i++)
{
CRCFull = (ushort)(CRCFull ^ message[i]);
for (int j = 0; j < 8; j++)
{
CRCLSB = (char)(CRCFull & 0x0001);
CRCFull = (ushort)((CRCFull >> 1) & 0x7FFF);
if (CRCLSB == 1)
CRCFull = (ushort)(CRCFull ^ 0xA001);
}
}
CRC[1] = CRCHigh = (byte)((CRCFull >> 8) & 0xFF);
CRC[0] = CRCLow = (byte)(CRCFull & 0xFF);
}
private void BuildMessage(byte address, byte type, ushort start, ushort registers, ref byte[] message)
{
//Array to receive CRC bytes:
byte[] CRC = new byte[2];
message[0] = address;
message[1] = type;
message[2] = (byte)(start >> 8);
message[3] = (byte)start;
message[4] = (byte)(registers >> 8);
message[5] = (byte)registers;
GetCRC(message, ref CRC);
message[message.Length - 2] = CRC[0];
message[message.Length - 1] = CRC[1];
}
private void BuildMessage(byte address, byte type, ushort start, ref byte[] message)
{
//Array to receive CRC bytes:
byte[] CRC = new byte[2];
message[0] = address;
message[1] = type;
message[2] = (byte)(start >> 8);
message[3] = (byte)start;
GetCRC(message, ref CRC);
message[message.Length - 2] = CRC[0];
message[message.Length - 1] = CRC[1];
}
private bool CheckResponse(byte[] response)
{
//Perform a basic CRC check:
byte[] CRC = new byte[2];
GetCRC(response, ref CRC);
if (CRC[0] == response[response.Length - 2] && CRC[1] == response[response.Length - 1])
return true;
else
return false;
}
private void GetResponse(ref byte[] response)
{
//There is a bug in .Net 2.0 DataReceived Event that prevents people from using this
//event as an interrupt to handle data (it doesn't fire all of the time). Therefore
//we have to use the ReadByte command for a fixed length as it's been shown to be reliable.
for (int i = 0; i < response.Length; i++)
{
response[i] = (byte)(sp.ReadByte());
}
}
public bool SendFc6(byte address, ushort start, short value)
{
//Ensure port is open:
if (sp.IsOpen)
{
//Clear in/out buffers:
sp.DiscardOutBuffer();
sp.DiscardInBuffer();
//Message is 1 addr + 1 fcn + 2 start + 2 reg val + 2 CRC
byte[] message = new byte[8];
//Function 16 response is fixed at 8 bytes
byte[] response = new byte[8];
//Add bytecount to message:
message[4] = (byte)(value >> 8);
message[5] = (byte)(value & 0xff);
//Build outgoing message:
BuildMessage(address, (byte)6, start, ref message);
//Send Modbus message to Serial Port:
try
{
sp.Write(message, 0, message.Length);
GetResponse(ref response);
}
catch (Exception err)
{
modbusStatus = "Error in write event: " + err.Message;
throw err;
//return false;
}
//Evaluate message:
if (CheckResponse(response))
{
modbusStatus = "Write successful";
return true;
}
else
{
modbusStatus = "CRC error";
return false;
}
}
else
{
modbusStatus = "Serial port not open";
return false;
}
}
public bool SendFc16(byte address, ushort start, ushort registers, short[] values)
{
//Ensure port is open:
if (sp.IsOpen)
{
//Clear in/out buffers:
sp.DiscardOutBuffer();
sp.DiscardInBuffer();
//Message is 1 addr + 1 fcn + 2 start + 2 reg + 1 count + 2 * reg vals + 2 CRC
byte[] message = new byte[9 + 2 * registers];
//Function 16 response is fixed at 8 bytes
byte[] response = new byte[8];
//Add bytecount to message:
message[6] = (byte)(registers * 2);
//Put write values into message prior to sending:
for (int i = 0; i < registers; i++)
{
message[7 + 2 * i] = (byte)(values[i] >> 8);
message[8 + 2 * i] = (byte)(values[i]);
}
//Build outgoing message:
BuildMessage(address, (byte)16, start, registers, ref message);
//Send Modbus message to Serial Port:
try
{
sp.Write(message, 0, message.Length);
GetResponse(ref response);
}
catch (Exception err)
{
modbusStatus = "Error in write event: " + err.Message;
return false;
}
//Evaluate message:
if (CheckResponse(response))
{
modbusStatus = "Write successful";
return true;
}
else
{
modbusStatus = "CRC error";
return false;
}
}
else
{
modbusStatus = "Serial port not open";
return false;
}
}
public bool SendFc3(byte address, ushort start, ushort registers, ref short[] values)
{
//Ensure port is open:
if (sp.IsOpen)
{
//Clear in/out buffers:
sp.DiscardOutBuffer();
sp.DiscardInBuffer();
//Function 3 request is always 8 bytes:
byte[] message = new byte[8];
//Function 3 response buffer:
byte[] response = new byte[5 + 2 * registers];
//Build outgoing modbus message:
BuildMessage(address, (byte)3, start, registers, ref message);
//Send modbus message to Serial Port:
try
{
sp.Write(message, 0, message.Length);
GetResponse(ref response);
}
catch (Exception err)
{
modbusStatus = "Error in read event: " + err.Message;
return false;
}
//Evaluate message:
if (CheckResponse(response))
{
//Return requested register values:
for (int i = 0; i < (response.Length - 5) / 2; i++)
{
values[i] = response[2 * i + 3];
values[i] <<= 8;
values[i] += response[2 * i + 4];
}
modbusStatus = "Read successful";
return true;
}
else
{
modbusStatus = "CRC error";
return false;
}
}
else
{
modbusStatus = "Serial port not open";
return false;
}
}
}
}