forked from ClassicDIY/ModbusTool
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSlaveForm.cs
More file actions
375 lines (336 loc) · 13.1 KB
/
SlaveForm.cs
File metadata and controls
375 lines (336 loc) · 13.1 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
using System;
using System.IO.Ports;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows.Forms;
using Modbus.Common;
using ModbusLib;
using ModbusLib.Protocols;
namespace ModbusSlave
{
public partial class SlaveForm : BaseForm
{
private static UDPBroadcaster broadcasrter;
private Function _function = Function.HoldingRegister;
private ICommServer _listener;
private SerialPort _uart;
private Thread _thread;
#region Form
public SlaveForm()
{
InitializeComponent();
dataTab1.ShowDataLength = false;
dataTab2.ShowDataLength = false;
}
private void SlaveFormClosing(object sender, FormClosingEventArgs e)
{
SaveUserData();
DoDisconnect();
//broadcasrter.Stop();
}
private void SlaveFormLoading(object sender, EventArgs e)
{
LoadUserData();
}
private void LoadUserData()
{
FunctionCode = Modbus.Common.Properties.Settings.Default.Function;
}
private void SaveUserData()
{
Modbus.Common.Properties.Settings.Default.Function = FunctionCode;
Modbus.Common.Properties.Settings.Default.Save();
}
#endregion
#region Connect/disconnect
private void BtnConnectClick(object sender, EventArgs e)
{
try
{
switch (CommunicationMode)
{
case CommunicationMode.RTU:
_uart = new SerialPort(PortName, Baud, Parity, DataBits, StopBits);
_uart.Open();
var rtuServer = new ModbusServer(new ModbusRtuCodec()) { Address = SlaveId };
rtuServer.OutgoingData += DriverOutgoingData;
rtuServer.IncommingData += DriverIncommingData;
_listener = _uart.GetListener(rtuServer);
_listener.ServeCommand += listener_ServeCommand;
_listener.Start();
AppendLog(String.Format("Connected using RTU to {0}", PortName));
break;
case CommunicationMode.UDP:
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_socket.Bind(new IPEndPoint(IPAddress.Any, TCPPort));
//create a server driver
var udpServer = new ModbusServer(new ModbusTcpCodec()) { Address = SlaveId };
udpServer.OutgoingData += DriverOutgoingData;
udpServer.IncommingData += DriverIncommingData;
//listen for an incoming request
_listener = _socket.GetUdpListener(udpServer);
_listener.ServeCommand += listener_ServeCommand;
_listener.Start();
AppendLog(String.Format("Listening to UDP port {0}", TCPPort));
break;
case CommunicationMode.TCP:
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind(new IPEndPoint(IPAddress.Any, TCPPort));
_socket.Listen(10);
//create a server driver
_thread = new Thread(Worker);
_thread.Start();
AppendLog(String.Format("Listening to TCP port {0}", TCPPort));
// simulate classic
broadcasrter = new UDPBroadcaster();
broadcasrter.SendDatagrams(TCPPort);
break;
}
}
catch (Exception ex)
{
AppendLog(ex.Message);
return;
}
btnConnect.Enabled = false;
buttonDisconnect.Enabled = true;
grpExchange.Enabled = true;
groupBoxFunctions.Enabled = false;
groupBoxTCP.Enabled = false;
groupBoxRTU.Enabled = false;
groupBoxMode.Enabled = false;
}
/// <summary>
/// Running thread handler
/// </summary>
protected void Worker()
{
var server = new ModbusServer(new ModbusTcpCodec()) { Address = SlaveId };
server.IncommingData += DriverIncommingData;
server.OutgoingData += DriverOutgoingData;
try
{
while (_thread.ThreadState == ThreadState.Running)
{
//wait for an incoming connection
_listener = _socket.GetTcpListener(server);
_listener.ServeCommand += listener_ServeCommand;
_listener.Start();
AppendLog(String.Format("Accepted connection."));
Thread.Sleep(1);
}
}
catch (Exception ex)
{
String msg = ex.Message;
}
}
private void ButtonDisconnectClick(object sender, EventArgs e)
{
DoDisconnect();
btnConnect.Enabled = true;
buttonDisconnect.Enabled = false;
grpExchange.Enabled = true;
groupBoxMode.Enabled = true;
groupBoxFunctions.Enabled = true;
SetMode();
AppendLog("Disconnected");
}
private void DoDisconnect()
{
if (InvokeRequired)
{
BeginInvoke(new Action(DoDisconnect));
return;
}
if (_listener != null)
{
_listener.Abort();
_listener = null;
}
if (_uart != null)
{
_uart.Close();
_uart.Dispose();
_uart = null;
}
if (_thread != null && _thread.IsAlive)
{
if (_thread.Join(2000) == false)
{
_thread.Abort();
_thread = null;
}
}
if (_socket != null)
{
_socket.Dispose();
_socket = null;
}
}
#endregion
#region Listen functions
void listener_ServeCommand(object sender, ServeCommandEventArgs e)
{
var command = (ModbusCommand)e.Data.UserData;
Thread.Sleep(SlaveDelay);
//take the proper function command handler
switch (command.FunctionCode)
{
case ModbusCommand.FuncReadCoils:
if (_function == Function.CoilStatus)
DoRead(command);
else
IllegalFunction(command);
break;
case ModbusCommand.FuncReadInputDiscretes:
if (_function == Function.InputStatus)
DoRead(command);
else
IllegalFunction(command);
break;
case ModbusCommand.FuncReadInputRegisters:
if (_function == Function.InputRegister)
DoRead(command);
else
IllegalFunction(command);
break;
case ModbusCommand.FuncReadMultipleRegisters:
if (_function == Function.HoldingRegister)
DoRead(command);
else
IllegalFunction(command);
break;
case ModbusCommand.FuncWriteCoil:
if (_function == Function.CoilStatus)
DoWrite(command);
else
IllegalFunction(command);
break;
case ModbusCommand.FuncForceMultipleCoils:
if (_function == Function.CoilStatus)
DoWrite(command);
else
IllegalFunction(command);
break;
case ModbusCommand.FuncWriteMultipleRegisters:
if (_function == Function.HoldingRegister)
DoWrite(command);
else
IllegalFunction(command);
break;
case ModbusCommand.FuncWriteSingleRegister:
if (_function == Function.HoldingRegister)
DoWrite(command);
else
IllegalFunction(command);
break;
case ModbusCommand.FuncReadExceptionStatus:
//TODO
break;
case ModbusCommand.FuncReadCustom:
if (_function == Function.HoldingRegister)
{
for (int i = 0; i < command.Count; i++)
command.Data[i] = _registerData[command.Offset + i];
}
else
IllegalFunction(command);
break;
default:
//return an exception
command.ExceptionCode = ModbusCommand.ErrorIllegalFunction;
break;
}
}
private void IllegalFunction(ModbusCommand command)
{
AppendLog(String.Format("Illegal Function, expecting function code {0}.", FunctionCode));
command.ExceptionCode = ModbusCommand.ErrorIllegalFunction;
}
private byte FunctionCode
{
get
{
byte rVal = ModbusCommand.ErrorIllegalFunction;
switch (_function)
{
case Function.CoilStatus:
rVal = ModbusCommand.FuncReadCoils;
break;
case Function.HoldingRegister:
rVal = ModbusCommand.FuncReadMultipleRegisters;
break;
case Function.InputRegister:
rVal = ModbusCommand.FuncReadInputRegisters;
break;
case Function.InputStatus:
rVal = ModbusCommand.FuncReadInputDiscretes;
break;
}
return rVal;
}
set
{
switch (value)
{
case ModbusCommand.FuncReadCoils:
radioButtonCoilStatus.Checked = true;
_function = Function.CoilStatus;
break;
case ModbusCommand.FuncReadInputDiscretes:
radioButtonInputStatus.Checked = true;
_function = Function.InputStatus;
break;
case ModbusCommand.FuncReadInputRegisters:
radioButtonInputRegisters.Checked = true;
_function = Function.InputRegister;
break;
case ModbusCommand.FuncReadMultipleRegisters:
radioButtonHoldingRegister.Checked = true;
_function = Function.HoldingRegister;
break;
}
}
}
private void DoRead(ModbusCommand command)
{
for (int i = 0; i < command.Count; i++)
command.Data[i] = _registerData[command.Offset + i];
AppendLog(String.Format("Sent data: Function code:{0}.", command.FunctionCode));
}
private void DoWrite(ModbusCommand command)
{
var dataAddress = command.Offset;
if (dataAddress < StartAddress || dataAddress > StartAddress + _displayCtrlCount)
{
AppendLog(String.Format("Received address is not within viewable range, Received address:{0}.", dataAddress));
return;
}
if ((command.Count + dataAddress) > _registerData.Length)
{
AppendLog(String.Format("Received address is not within viewable range, Received address:{0}.", dataAddress));
return;
}
command.Data.CopyTo(_registerData, dataAddress);
UpdateDataTable();
AppendLog(String.Format("Received data: Function code:{0}.", command.FunctionCode));
}
#endregion
#region Radion button check handlers
private void RadioButtonFunctionCheckedChanged(object sender, EventArgs e)
{
if (sender is RadioButton)
{
var rb = (RadioButton)sender;
if (rb.Checked)
{
Function.TryParse(rb.Tag.ToString(), true, out _function);
ClearRegisterData();
}
}
}
#endregion
}
}