-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathModBusParser.cs
More file actions
465 lines (366 loc) · 10.8 KB
/
ModBusParser.cs
File metadata and controls
465 lines (366 loc) · 10.8 KB
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
using System;
using System.Collections;
using System.IO;
using System.Threading.Tasks;
namespace Waher.Networking.Modbus
{
/// <summary>
/// Processes incoming ModBus data from a client.
/// </summary>
public class ModBusParser
{
private readonly ModBusTcpServer server;
private byte[] data;
private byte state;
private ushort transactionId;
private ushort protocolId;
private ushort length;
private ushort bytesLeft;
private ushort dataPos;
private byte unitAddress;
private byte functionCode;
/// <summary>
/// Processes incoming ModBus data from a client.
/// </summary>
/// <param name="Server">Server reference.</param>
public ModBusParser(ModBusTcpServer Server)
{
this.server = Server;
this.state = 0;
}
/// <summary>
/// Called when binary data has been received.
/// </summary>
/// <param name="e">Event arguments.</param>
/// <returns>If data was received successfully.</returns>
public async Task<bool> DataReceived(ServerConnectionDataEventArgs e)
{
byte[] Buffer = e.Buffer;
int Count = e.Count;
int Offset = e.Offset;
byte b;
while (Count-- > 0)
{
b = Buffer[Offset++];
switch (this.state)
{
case 0: // Transaction ID (MSB)
this.transactionId = b;
this.state++;
break;
case 1: // Transaction ID (LSB)
this.transactionId <<= 8;
this.transactionId |= b;
this.state++;
break;
case 2: // Protocol ID (MSB)
this.protocolId = b;
this.state++;
break;
case 3: // Protocol ID (LSB)
this.protocolId <<= 8;
this.protocolId |= b;
this.state++;
break;
case 4: // Length (MSB)
this.length = b;
this.state++;
break;
case 5: // Length (LSB)
this.length <<= 8;
this.length |= b;
this.bytesLeft = (ushort)(this.length - 2);
this.dataPos = 0;
this.data = new byte[this.bytesLeft];
this.state++;
break;
case 6: // Unit Address
this.unitAddress = b;
this.state++;
break;
case 7: // Function Code
this.functionCode = b;
this.state++;
if (this.bytesLeft == 0)
{
this.state = 0;
if (!await this.FrameReceived(e))
return false;
}
break;
case 8: // Data
this.data[this.dataPos++] = b;
this.bytesLeft--;
if (this.bytesLeft == 0)
{
this.state = 0;
if (!await this.FrameReceived(e))
return false;
}
break;
}
}
return true;
}
private async Task<bool> FrameReceived(ServerConnectionDataEventArgs e)
{
try
{
if (this.protocolId != 0)
{
e.Server.Error("Invalid protocol ID received.");
return false;
}
switch (this.functionCode)
{
case 0x01: // Read Coils
if (this.data.Length != 4)
{
e.Server.Error("Expected four bytes of data.");
return false;
}
ushort ReferenceNr = this.data[0];
ReferenceNr <<= 8;
ReferenceNr |= this.data[1];
ushort NrRegisters = this.data[2];
NrRegisters <<= 8;
NrRegisters |= this.data[3];
BitArray Bits = new BitArray(NrRegisters);
ReadBitsEventArgs BitsEventArgs = new ReadBitsEventArgs(
this.unitAddress, ReferenceNr, NrRegisters, Bits);
await this.server.RaiseReadCoils(BitsEventArgs);
byte[] Bytes = ToBytes(Bits);
int c = Bytes.Length;
if (c > 255)
throw new Exception("Too many bits requested.");
byte[] Data = new byte[c + 1];
Data[0] = (byte)c;
Buffer.BlockCopy(Bytes, 0, Data, 1, c);
return await this.SendResponse(e, false, Data);
case 0x02: // Read Input Discretes
if (this.data.Length != 4)
{
e.Server.Error("Expected four bytes of data.");
return false;
}
ReferenceNr = this.data[0];
ReferenceNr <<= 8;
ReferenceNr |= this.data[1];
NrRegisters = this.data[2];
NrRegisters <<= 8;
NrRegisters |= this.data[3];
Bits = new BitArray(NrRegisters);
BitsEventArgs = new ReadBitsEventArgs(this.unitAddress,
ReferenceNr, NrRegisters, Bits);
await this.server.RaiseReadInputDiscretes(BitsEventArgs);
Bytes = ToBytes(Bits);
c = Bytes.Length;
if (c > 255)
throw new Exception("Too many bits requested.");
Data = new byte[c + 1];
Data[0] = (byte)c;
Buffer.BlockCopy(Bytes, 0, Data, 1, c);
return await this.SendResponse(e, false, Data);
case 0x03: // Read Multiple Registers
if (this.data.Length != 4)
{
e.Server.Error("Expected four bytes of data.");
return false;
}
ReferenceNr = this.data[0];
ReferenceNr <<= 8;
ReferenceNr |= this.data[1];
NrRegisters = this.data[2];
NrRegisters <<= 8;
NrRegisters |= this.data[3];
ushort[] Words = new ushort[NrRegisters];
ReadWordsEventArgs WordsEventArgs = new ReadWordsEventArgs(
this.unitAddress, ReferenceNr, NrRegisters, Words);
await this.server.RaiseReadMultipleRegisters(WordsEventArgs);
Bytes = ToBytes(Words);
c = Bytes.Length;
if (c > 255)
throw new Exception("Too many words requested.");
Data = new byte[c + 1];
Data[0] = (byte)c;
Buffer.BlockCopy(Bytes, 0, Data, 1, c);
return await this.SendResponse(e, false, Data);
case 0x04: // Read Input Registers
if (this.data.Length != 4)
{
e.Server.Error("Expected four bytes of data.");
return false;
}
ReferenceNr = this.data[0];
ReferenceNr <<= 8;
ReferenceNr |= this.data[1];
NrRegisters = this.data[2];
NrRegisters <<= 8;
NrRegisters |= this.data[3];
Words = new ushort[NrRegisters];
WordsEventArgs = new ReadWordsEventArgs(this.unitAddress,
ReferenceNr, NrRegisters, Words);
await this.server.RaiseReadInputRegisters(WordsEventArgs);
Bytes = ToBytes(Words);
c = Bytes.Length;
if (c > 255)
throw new Exception("Too many words requested.");
Data = new byte[c + 1];
Data[0] = (byte)c;
Buffer.BlockCopy(Bytes, 0, Data, 1, c);
return await this.SendResponse(e, false, Data);
case 0x05: // Write Coil
if (this.data.Length != 4)
{
e.Server.Error("Expected four bytes of data.");
return false;
}
ReferenceNr = this.data[0];
ReferenceNr <<= 8;
ReferenceNr |= this.data[1];
bool BooleanValue = this.data[2] != 0;
WriteBitEventArgs BitEventArgs = new WriteBitEventArgs(
this.unitAddress, ReferenceNr, BooleanValue);
await this.server.RaiseWriteCoil(BitEventArgs);
Data = new byte[3];
Data[0] = 1;
Data[2] = BitEventArgs.Value ? (byte)0xff : (byte)0;
return await this.SendResponse(e, false, Data);
case 0x06: // Write Register
if (this.data.Length != 4)
{
e.Server.Error("Expected four bytes of data.");
return false;
}
ReferenceNr = this.data[0];
ReferenceNr <<= 8;
ReferenceNr |= this.data[1];
ushort WordValue = this.data[2];
WordValue <<= 8;
WordValue |= this.data[3];
WriteWordEventArgs WordEventArgs = new WriteWordEventArgs(
this.unitAddress, ReferenceNr, WordValue);
await this.server.RaiseWriteRegister(WordEventArgs);
WordValue = WordEventArgs.Value;
Data = new byte[4];
Data[0] = 2;
Data[2] = (byte)(WordValue >> 8);
Data[3] = (byte)WordValue;
return await this.SendResponse(e, false, Data);
case 0x10: // Write Multiple Registers
if (this.data.Length < 5)
{
e.Server.Error("Expected at least five bytes of data.");
return false;
}
ReferenceNr = this.data[0];
ReferenceNr <<= 8;
ReferenceNr |= this.data[1];
NrRegisters = this.data[2];
NrRegisters <<= 8;
NrRegisters |= this.data[3];
byte ByteCount = this.data[4];
if (this.data.Length != 5 + ByteCount)
{
e.Server.Error("Unexpected length.");
return false;
}
if (ByteCount != NrRegisters << 1)
{
e.Server.Error("Inconsistency between number of registers and byte count.");
return false;
}
int i, j = 5;
for (i = 0; i < NrRegisters; i++)
{
WordValue = this.data[j++];
WordValue <<= 8;
WordValue |= this.data[j++];
WordEventArgs = new WriteWordEventArgs(
this.unitAddress, (ushort)(ReferenceNr + i), WordValue);
await this.server.RaiseWriteRegister(WordEventArgs);
}
Data = new byte[4];
Buffer.BlockCopy(this.data, 0, Data, 0, 4);
return await this.SendResponse(e, false, Data);
default:
e.Server.Error("Unsupported function code received.");
return await this.SendResponse(e, true, 0x01);
}
}
catch (Exception ex)
{
// TODO: Return error message.
e.Server.Error(ex.Message);
return false;
}
}
/// <summary>
/// Converts a bit-array to a byte array.
/// </summary>
/// <param name="Bits">Array of bits</param>
/// <returns>Byte array</returns>
public static byte[] ToBytes(BitArray Bits)
{
int c = Bits.Length;
int d = (c + 7) / 8;
byte[] Result = new byte[d];
int i, j;
byte b, o;
for (i = j = b = 0, o = 1; i < c; i++)
{
if (Bits[i])
b |= o;
o <<= 1;
if (o == 0)
{
Result[j++] = b;
o = 1;
b = 0;
}
}
if (j < d)
Result[j] = b;
return Result;
}
/// <summary>
/// Converts a word-array to a byte array.
/// </summary>
/// <param name="Words">Array of words</param>
/// <returns>Byte array</returns>
public static byte[] ToBytes(ushort[] Words)
{
int c = Words.Length;
int d = c << 1;
byte[] Result = new byte[d];
int i, j;
ushort w;
for (i = j = 0; i < c; i++)
{
w = Words[i];
Result[j + 1] = (byte)w;
w >>= 8;
Result[j] = (byte)w;
j += 2;
}
return Result;
}
private Task<bool> SendResponse(ServerConnectionDataEventArgs e, bool Error, params byte[] Data)
{
MemoryStream Frame = new MemoryStream();
Frame.WriteByte((byte)(this.transactionId >> 8));
Frame.WriteByte((byte)this.transactionId);
Frame.WriteByte(0); // Protocol Identitfier (Hi)
Frame.WriteByte(0); // Protocol Identitfier (Lo)
int Len = Data?.Length ?? 0;
ushort Length = (ushort)(Len + 2);
Frame.WriteByte((byte)(Length >> 8));
Frame.WriteByte((byte)Length);
Frame.WriteByte(this.unitAddress);
Frame.WriteByte(Error ? (byte)(this.functionCode | 0x80) : this.functionCode);
if (Len > 0)
Frame.Write(Data, 0, Len);
return e.SendAsync(true, Frame.ToArray());
}
}
}