C#之Modbus通讯
CZerocheng 2/5/2024 CSharp
# 效果演示

# 什么是 Modbus
Modbus 是一种主从式(Master-Slave)的通信协议,主站(Master)主动发起通信,例如 PLC、上位机;从站(Slave):被动响应通信请求,例如传感器、驱动器。数据传输采用二进制数据帧格式:RTU 模式(Remote Terminal Unit):二进制帧,数据紧凑,效率高。ASCII 模式:每个字节以 ASCII 表示,易于调试,但效率较低。Modbus TCP:基于以太网的通信协议,无需校验。
# 常用功能码
01:读取线圈状态。
02:读取输入状态。
03:读取保持寄存器。
04:读取输入寄存器。
05:写单个线圈。
06:写单个寄存器。
16:写多个寄存器。
# 使用IOTClient编写ModBusTcp
查看
using CommunicationDemo.Model;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Threading;
using System.Windows;
using WebSocketLib;
using IoTClient.Clients.Modbus;
using IoTClient;
using System.Collections.ObjectModel;
using CommunicationDemo.Enum;
using System.Net;
using IoTClient.Models;
using IoTClient.Enums;
namespace CommunicationDemo.ViewModel
{
public class ModbusTcpViewModel : ObservableObject
{
ModbusTcpClient client = null;
public RichTextBox ReceiveTextBox = new RichTextBox();
public TextBox SendTextBox = new TextBox();
private const int MaxLines = 100;
private string IPHost = string.Empty;
private Thread UIThread = null;
private ConcurrentQueue<Action> UIQueue = new ConcurrentQueue<Action>();
public Dispatcher MyDispatcher { get; set; }
public ModbusTcpConfigModel ClientConfig { get; set; } = new ModbusTcpConfigModel();
public ObservableCollection<ModbusInput> BatchDataList { get; set; } = new ObservableCollection<ModbusInput>();
public ObservableCollection<DataTypeEnum> DataTypeList { get; set; } = new ObservableCollection<DataTypeEnum>(System.Enum.GetValues(typeof(DataTypeEnum)).Cast<DataTypeEnum>());
public ObservableCollection<EncodingEnum> EncodingTypeList { get; set; } = new ObservableCollection<EncodingEnum>(System.Enum.GetValues(typeof(EncodingEnum)).Cast<EncodingEnum>());
private int encodingTypeSelectedIndex = 0;
public int EncodingTypeSelectedIndex
{
get { return encodingTypeSelectedIndex; }
set { SetProperty(ref encodingTypeSelectedIndex, value); }
}
private EncodingEnum encodingTypeSelectedItem = EncodingEnum.UTF8;
public EncodingEnum EncodingTypeSelectedItem
{
get { return encodingTypeSelectedItem; }
set
{
SetProperty(ref encodingTypeSelectedItem, value);
switch (value)
{
case EncodingEnum.ASCII:
SelectedEnconding = Encoding.ASCII;
break;
case EncodingEnum.Unicode:
SelectedEnconding = Encoding.Unicode;
break;
//case EncodingEnum.UnicodeBig:
// SelectedEnconding = Encoding.BigEndianUnicode;
// break;
case EncodingEnum.UTF8:
SelectedEnconding = Encoding.UTF8;
break;
case EncodingEnum.UTF32:
SelectedEnconding = Encoding.UTF32;
break;
//case EncodingEnum.ANSI:
// SelectedEnconding = En
// break;
//case EncodingEnum.GB2312:
// break;
//default:
// break;
}
}
}
private Encoding SelectedEnconding = Encoding.UTF8;
private int dataTypeSelectedIndex = 0;
public int DataTypeSelectedIndex
{
get { return dataTypeSelectedIndex; }
set { SetProperty(ref dataTypeSelectedIndex, value); }
}
private DataTypeEnum dataTypeSelectedItem;
public DataTypeEnum DataTypeSelectedItem
{
get { return dataTypeSelectedItem; }
set { SetProperty(ref dataTypeSelectedItem, value); }
}
private string address;
public string Address
{
get { return address; }
set { SetProperty(ref address, value); }
}
private byte stationNumber = 1;
public byte StationNumber
{
get { return stationNumber; }
set { SetProperty(ref stationNumber, value); }
}
private ushort numberOfByte = 10;
public ushort NumberOfByte
{
get { return numberOfByte; }
set { SetProperty(ref numberOfByte, value); }
}
private string message;
public string Message
{
get { return message; }
set { SetProperty(ref message, value); }
}
private bool isRecycle;
public bool IsRecycle
{
get { return isRecycle; }
set { SetProperty(ref isRecycle, value); }
}
private bool isConnected = false;
public bool IsConnected
{
get { return isConnected; }
set { SetProperty(ref isConnected, value); }
}
private bool isCanRead = false;
public bool IsCanRead
{
get { return isCanRead; }
set { SetProperty(ref isCanRead, value); }
}
private bool isCanWrite = false;
public bool IsCanWrite
{
get { return isCanWrite; }
set { SetProperty(ref isCanWrite, value); }
}
private bool IsRunning => IsRecycle;
private int interval = 10;
public int Interval
{
get { return interval; }
set { SetProperty(ref interval, value); }
}
public IRelayCommand<string> command { get; set; }
public IRelayCommand<string> Command => command = new RelayCommand<string>(MyCommand);
private void MyCommand(string commandName)
{
Task.Run(() =>
{
switch (commandName)
{
case "连接":
Connection();
break;
case "读取":
SingleRead();
break;
case "写入":
SingleWrite();
break;
case "断开":
DisConnection();
break;
case "复制":
Copy();
break;
case "添加":
Add();
break;
case "删除":
break;
case "批量读取":
break;
case "批量写入":
break;
default:
break;
}
});
}
private void Add()
{
BatchDataList.Add(new ModbusInput() { Address = "100", DataType = DataTypeEnum.Bool, FunctionCode = 4 });
}
private void SingleWrite()
{
if (null == client)
{
HandyControl.Controls.MessageBox.Show("服务端未连接,请连接!", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
if (string.IsNullOrWhiteSpace(Address))
{
HandyControl.Controls.MessageBox.Show("写入地址不能为空!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (!string.IsNullOrWhiteSpace(Message))
{
if (IsRecycle)
{
IsCanWrite = false;
while (IsRunning)
{
try
{
Result res = WriteData();
if (res.IsSucceed)
{
UIQueue.Enqueue(new Action(() =>
{
AppendToTextBox($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")} | 向{ClientConfig.IP}:{ClientConfig.Port}的地址{Address}写入类型为{dataTypeSelectedItem} | {Message}", "lime");
}));
}
else
{
HandyControl.Controls.MessageBox.Show($"写入失败,{res.Err}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
IsRecycle = false;
}
Thread.Sleep(Interval);
}
catch (Exception ex)
{
HandyControl.Controls.MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
IsCanWrite = true;
}
else
{
try
{
Result res = WriteData();
if (res.IsSucceed)
{
UIQueue.Enqueue(new Action(() =>
{
AppendToTextBox($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")} | 向{ClientConfig.IP}:{ClientConfig.Port}的地址{Address}写入类型为{dataTypeSelectedItem} | {Message}", "lime");
}));
}
else
{
HandyControl.Controls.MessageBox.Show($"写入失败,{res.Err}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
catch (Exception ex)
{
HandyControl.Controls.MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
else
{
HandyControl.Controls.MessageBox.Show("待发送的消息不能为空!", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
private void SingleRead()
{
if (null == client)
{
HandyControl.Controls.MessageBox.Show("服务端未连接,请连接!", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
if (string.IsNullOrWhiteSpace(Address))
{
HandyControl.Controls.MessageBox.Show("读取地址不能为空!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (IsRecycle)
{
IsCanRead = false;
while (IsRunning)
{
try
{
DataResult res = ReadData();
if (res.Result.IsSucceed)
{
UIQueue.Enqueue(new Action(() =>
{
AppendToTextBox($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")} | 向{ClientConfig.IP}:{ClientConfig.Port}的地址{Address}读取类型为{dataTypeSelectedItem} | {res.Data.ToString().TrimEnd('\0')}", "orange");
}));
}
else
{
UIQueue.Enqueue(new Action(() =>
{
AppendToTextBox($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")} | 向{ClientConfig.IP}:{ClientConfig.Port}的地址{Address}读取类型为{dataTypeSelectedItem} | {res.Result.Err}", "red");
}));
IsRecycle = false;
}
Thread.Sleep(Interval);
}
catch (Exception ex)
{
HandyControl.Controls.MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
IsCanRead = true;
}
else
{
try
{
DataResult res = ReadData();
if (res.Result.IsSucceed)
{
UIQueue.Enqueue(new Action(() =>
{
AppendToTextBox($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")} | 向{ClientConfig.IP}:{ClientConfig.Port}的地址{Address}读取类型为{dataTypeSelectedItem} | {res.Data.ToString().TrimEnd('\0')}", "orange");
}));
}
else
{
UIQueue.Enqueue(new Action(() =>
{
AppendToTextBox($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff")} | 向{ClientConfig.IP}:{ClientConfig.Port}的地址{Address}读取类型为{dataTypeSelectedItem} | {res.Result.Err}", "red");
}));
}
}
catch (Exception ex)
{
HandyControl.Controls.MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
private void Copy()
{
if (IsRecycle)
{
Task.Run(() =>
{
HandyControl.Controls.MessageBox.Show("复制文本时请停止循环发送!", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
});
return;
}
UIQueue.Enqueue(new Action(() =>
{
try
{
MyDispatcher.BeginInvoke(new Action(() =>
{
ReceiveTextBox.Focus();
ReceiveTextBox.SelectAll();
ReceiveTextBox.Copy();
}));
}
catch (Exception)
{
Task.Run(() =>
{
HandyControl.Controls.MessageBox.Show("请停止通讯!", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
});
}
}));
}
private void DisConnection()
{
client.Close();
IsConnected = false;
}
private void Connection()
{
try
{
if (string.IsNullOrWhiteSpace(ClientConfig.IP))
{
ShowMessageBox("IP地址不能为空!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
if (ClientConfig.Port <= 0)
{
ShowMessageBox("端口必须大于0!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
client = new ModbusTcpClient(ClientConfig.IP, ClientConfig.Port, ClientConfig.Timeout, ClientConfig.EndianFormat);
Result res = client.Open();
if (res.IsSucceed)
{
IsConnected = true;
IsCanRead = true;
IsCanWrite = true;
ShowMessageBox("连接成功!", "信息", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
ShowMessageBox("连接失败!", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
catch (Exception ex)
{
HandyControl.Controls.MessageBox.Show(ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private Result WriteData()
{
Result result = new Result();
result.IsSucceed = false;
try
{
switch (DataTypeSelectedItem)
{
case DataTypeEnum.Bool:
bool res = Message.ToUpper() == "TRUE" ? true : false;
result = client.Write(Address, res, StationNumber, 5);
break;
//case DataTypeEnum.Byte:
// result = client.Write(Address, new byte(), StationNumber, 5);
// result.Err = "类型是只读模式";
// break;
case DataTypeEnum.Int16:
result = client.Write(Address, Convert.ToInt16(Message), StationNumber, 16);
break;
case DataTypeEnum.UInt16:
result = client.Write(Address, Convert.ToUInt16(Message), StationNumber, 16);
break;
case DataTypeEnum.Int32:
result = client.Write(Address, Convert.ToInt32(Message), StationNumber, 16);
break;
case DataTypeEnum.UInt32:
result = client.Write(Address, Convert.ToUInt32(Message), StationNumber, 16);
break;
case DataTypeEnum.Int64:
result = client.Write(Address, Convert.ToInt64(Message), StationNumber, 16);
break;
case DataTypeEnum.UInt64:
result = client.Write(Address, Convert.ToUInt64(Message), StationNumber, 16);
break;
case DataTypeEnum.Float:
float.TryParse(Message, out float floatvalue);
result = client.Write(Address, floatvalue, StationNumber, 16);
break;
case DataTypeEnum.Double:
double.TryParse(Message, out double doublevalue);
result = client.Write(Address, doublevalue, StationNumber, 16);
break;
case DataTypeEnum.String:
result = client.Write(Address, Message, StationNumber, 16, SelectedEnconding);
break;
default:
result.Err = "没有该类型,请选择正确的数据类型";
result.IsSucceed = false;
break;
}
return result;
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString());
result.Err = ex.Message;
return result;
}
}
private DataResult ReadData()
{
DataResult dataresult = new DataResult();
switch (DataTypeSelectedItem)
{
case DataTypeEnum.Bool:
Result<bool> resultBool = client.ReadCoil(Address, StationNumber, 1);
SetResultData(resultBool, dataresult);
break;
case DataTypeEnum.Int16:
Result<short> resultShort = client.ReadInt16(Address, StationNumber, 3,4);
SetResultData(resultShort, dataresult);
break;
case DataTypeEnum.UInt16:
Result<ushort> resultUint16 = client.ReadUInt16(Address, StationNumber, 3);
SetResultData(resultUint16, dataresult);
break;
case DataTypeEnum.Int32:
Result<int> resultInt32 = client.ReadInt32(Address, StationNumber, 3);
SetResultData(resultInt32, dataresult);
break;
case DataTypeEnum.UInt32:
Result<uint> resultUInt32 = client.ReadUInt32(Address, StationNumber, 3);
SetResultData(resultUInt32, dataresult);
break;
case DataTypeEnum.Int64:
Result<long> resultInt64 = client.ReadInt64(Address, StationNumber, 3);
SetResultData(resultInt64, dataresult);
break;
case DataTypeEnum.UInt64:
Result<ulong> resultUInt64 = client.ReadUInt64(Address, StationNumber, 3);
SetResultData(resultUInt64, dataresult);
break;
case DataTypeEnum.Float:
Result<float> resultFloat = client.ReadFloat(Address, StationNumber, 3);
SetResultData(resultFloat, dataresult);
break;
case DataTypeEnum.Double:
Result<double> resultDouble = client.ReadDouble(Address, StationNumber, 3);
SetResultData(resultDouble, dataresult);
break;
case DataTypeEnum.String:
Result<string> resultString = client.ReadString(Address, StationNumber, 3, SelectedEnconding, NumberOfByte);
SetResultData(resultString, dataresult);
break;
default:
dataresult.Result = new Result();
dataresult.Result.IsSucceed = false;
dataresult.Result.Err = "没有该类型,请选择正确的数据类型";
break;
}
return dataresult;
}
private DataResult SetResultData<T>(Result<T> result, DataResult dataResult)
{
dataResult.Result = result;
if (result.IsSucceed)
dataResult.Data = result.Value;
return dataResult;
}
private void ShowMessageBox(string message, string caption, MessageBoxButton button, MessageBoxImage icon)
{
Task.Run(() =>
{
HandyControl.Controls.MessageBox.Show(message, caption, button, icon);
});
}
private void Client_OnLoseLineEvent(object sender, EventArgs e)
{
Task.Run(() =>
{
HandyControl.Controls.MessageBox.Show(sender.ToString(), "错误", MessageBoxButton.OK, MessageBoxImage.Error);
});
}
public ModbusTcpViewModel()
{
UIThread = new Thread(RecycleRefreshThread);
UIThread.Name = "循环时滚动UI线程";
UIThread.Start();
}
private void RecycleRefreshThread()
{
while (true)
{
var flag = UIQueue.TryDequeue(out var action);
if (flag)
action();
else
Thread.Sleep(1);
}
}
private void AppendToTextBox(string text, string color)
{
MyDispatcher.BeginInvoke(new Action(() =>
{
var document = ReceiveTextBox.Document;
var paragraphs = document.Blocks.OfType<Paragraph>().ToList();
if (paragraphs.Count >= 100)
document.Blocks.Remove(paragraphs.First());
var paragraph = new Paragraph();
paragraph.Inlines.Add(new Run(text) { Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString(color)) });
ReceiveTextBox.Document.Blocks.Add(paragraph);
ReceiveTextBox.ScrollToEnd();
}));
}
}
}
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
<UserControl x:Class="CommunicationDemo.View.ModbusTcpView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:CommunicationDemo.View"
xmlns:hc="https://handyorg.github.io/handycontrol"
xmlns:viewmodel="clr-namespace:CommunicationDemo.ViewModel"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800" Loaded="UserControl_Loaded">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<DockPanel LastChildFill="True">
<TextBlock Text="消息:" Margin="5"/>
<Border DockPanel.Dock="Bottom" Margin="5" CornerRadius="2" Height="380" BorderThickness="1" BorderBrush="#326cf3">
<StackPanel Orientation="Vertical">
<WrapPanel Orientation="Horizontal">
<TextBox Text="{Binding Address}" Margin="10" Width="200" Height="30" FontSize="12" hc:InfoElement.TitleWidth="60" hc:InfoElement.Placeholder="起始地址" hc:InfoElement.TitlePlacement="Left" hc:InfoElement.Title="起始地址:" Style="{StaticResource TextBoxExtend}" />
<TextBox Text="{Binding StationNumber}" Margin="20,0" Width="200" Height="30" FontSize="12" hc:InfoElement.TitleWidth="40" hc:InfoElement.Placeholder="站号" hc:InfoElement.TitlePlacement="Left" hc:InfoElement.Title="站号:" Style="{StaticResource TextBoxExtend}"/>
<ComboBox ItemsSource="{Binding DataTypeList,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" SelectedIndex="{Binding DataTypeSelectedIndex}" SelectedItem="{Binding DataTypeSelectedItem}" Margin="20,0" Width="200" Height="30" hc:InfoElement.TitleWidth="60" hc:InfoElement.TitlePlacement="Left" hc:InfoElement.Title="数据类型:" Style="{StaticResource ComboBoxExtend}"/>
<ComboBox ItemsSource="{Binding EncodingTypeList,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" SelectedIndex="{Binding EncodingTypeSelectedIndex}" SelectedItem="{Binding EncodingTypeSelectedItem}" Margin="20,0" Width="200" Height="30" hc:InfoElement.TitleWidth="40" hc:InfoElement.TitlePlacement="Left" hc:InfoElement.Title="编码:" Style="{StaticResource ComboBoxExtend}"/>
<TextBox Text="{Binding NumberOfByte}" Margin="10,0" Width="200" Height="30" FontSize="12" hc:InfoElement.TitleWidth="60" hc:InfoElement.Placeholder="一个寄存器两个字节" hc:InfoElement.TitlePlacement="Left" hc:InfoElement.Title="字节数:" Style="{StaticResource TextBoxExtend}"/>
</WrapPanel>
<GroupBox Header="单个读写" Style="{x:Null}" BorderBrush="CornflowerBlue" Margin="0,10,0,0" BorderThickness="0,1,0,0">
<StackPanel Margin="0,10">
<StackPanel Orientation="Horizontal">
<Button Content="读取" IsEnabled="{Binding IsCanRead}" Command="{Binding Command}" CommandParameter="读取" Style="{StaticResource ButtonWarning}" Height="30" Width="60" Margin="10,0"/>
<Button Content="写入" IsEnabled="{Binding IsCanWrite}" Command="{Binding Command}" CommandParameter="写入" Style="{StaticResource ButtonSuccess}" Height="30" Width="60" Margin="10,0"/>
<!--<Button Content="暂停" Command="{Binding Command}" CommandParameter="暂停" Style="{StaticResource ButtonSuccess}" Height="30" Width="60" Margin="10,0" />-->
<CheckBox Content="循环" Margin="5" IsChecked="{Binding IsRecycle}"/>
<TextBox Text="{Binding Interval, UpdateSourceTrigger=LostFocus,Mode=TwoWay}" Width="200" Margin="5" Height="30" hc:InfoElement.TitleWidth="90" hc:InfoElement.Placeholder="循环间隔" hc:InfoElement.TitlePlacement="Left" hc:InfoElement.Title="循环间隔(ms):" Style="{StaticResource TextBoxExtend}"/>
<Button Content="复制文本" HorizontalAlignment="Right" Command="{Binding Command}" CommandParameter="复制" Style="{StaticResource ButtonWarning}" Height="30" Width="120" Margin="640,0,10,0" />
</StackPanel>
<TextBox Text="{Binding Message}" Margin="10" Height="30" FontSize="12" hc:InfoElement.TitleWidth="60" hc:InfoElement.Placeholder="写入内容" hc:InfoElement.TitlePlacement="Left" hc:InfoElement.Title="写入内容:" Style="{StaticResource TextBoxExtend}"/>
</StackPanel>
</GroupBox>
<GroupBox Style="{x:Null}" Header="批量读写" Height="400" BorderBrush="CornflowerBlue" Margin="0,0,0,10" BorderThickness="0,1,0,0" IsEnabled="False">
<StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="10,10,0,0">
<Button Content="批量读取" HorizontalAlignment="Left" Command="{Binding Command}" CommandParameter="批量读取" Style="{StaticResource ButtonInfo}" Height="30" Width="120" Margin="0,0,0,0" />
<Button Content="批量写入" HorizontalAlignment="Right" Command="{Binding Command}" CommandParameter="批量写入" Style="{StaticResource ButtonWarning}" Height="30" Width="120" Margin="10,0,650,0"/>
<Button Content="添加" HorizontalAlignment="Right" Command="{Binding Command}" CommandParameter="添加" Style="{StaticResource ButtonSuccess}" Height="30" Width="120" Margin="20,0" />
<Button Content="删除" HorizontalAlignment="Right" Command="{Binding Command}" CommandParameter="删除" Style="{StaticResource ButtonDanger}" Height="30" Width="120" Margin="5,0"/>
</StackPanel>
<DataGrid HeadersVisibility="All" Margin="5" RowHeaderWidth="60" Background="AliceBlue" AutoGenerateColumns="False" ItemsSource="{Binding BatchDataList}" hc:DataGridAttach.ShowRowNumber="True">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Address}" Header="地址"/>
<!--<DataGridComboBoxColumn Width="100" CanUserResize="False" SelectedValueBinding="{Binding Type}" Header="类型"/>
<DataGridTextColumn Binding="{Binding Remark}" Header="内容"/>-->
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</GroupBox>
</StackPanel>
</Border>
<RichTextBox x:Name="ReceiveTextBox" Margin="5" FontSize="16" VerticalScrollBarVisibility="Auto"
IsReadOnly="True" Background="Black" />
</DockPanel>
<Border Grid.Column="1" BorderBrush="#326cf3" BorderThickness="1" Margin="5">
<hc:TransitioningContentControl >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<hc:PropertyGrid x:Name="propertyGrid" SelectedObject="{Binding ClientConfig}"/>
<StackPanel Orientation="Vertical" Grid.Row="1" Margin="0,10">
<Button Content="连接" IsEnabled="{Binding IsConnected,Converter={StaticResource Boolean2BooleanReConverter}}" Command="{Binding Command}" CommandParameter="连接" Style="{StaticResource ButtonPrimary}" Height="40" Width="{Binding ElementName=propertyGrid,Path=ActualWidth}" Margin="10,0"/>
<Button Content="断开" Command="{Binding Command}" IsEnabled="{Binding IsConnected}" CommandParameter="断开" Style="{StaticResource ButtonDanger}" Height="40" Width="{Binding ElementName=propertyGrid,Path=ActualWidth}" Margin="10,20"/>
</StackPanel>
</Grid>
</hc:TransitioningContentControl>
</Border>
</Grid>
</UserControl>
public partial class ModbusTcpView : UserControl
{
private ModbusTcpViewModel viewmodel = new ModbusTcpViewModel();
public ModbusTcpView()
{
InitializeComponent();
this.DataContext = viewmodel;
}
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
viewmodel.ReceiveTextBox = ReceiveTextBox;
viewmodel.MyDispatcher = this.Dispatcher;
}
}
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
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
public class ModbusTcpConfigModel
{
[Category("基础")]
[DisplayName("IP")]
public string IP { get; set; } = "127.0.0.1";
[Category("基础")]
[DisplayName("端口")]
public int Port { get; set; } = 502;
[Category("基础")]
[DisplayName("超时时间")]
public int Timeout { get; set; } = 1500;
[Category("大小端")]
public EndianFormat EndianFormat { get; set; } = EndianFormat.CDAB;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17