-
Notifications
You must be signed in to change notification settings - Fork 201
/
BaseForm.cs
763 lines (705 loc) · 24.7 KB
/
BaseForm.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
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
using System;
using System.Configuration;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.IO.Ports;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Windows.Forms.LinkLabel;
namespace Modbus.Common
{
public partial class BaseForm : Form
{
private DisplayFormat _displayFormat = DisplayFormat.Integer;
private CommunicationMode _communicationMode = CommunicationMode.TCP;
protected Socket _socket;
protected readonly ushort[] _registerData;
private bool _logPaused = false;
#region Form
public BaseForm()
{
InitializeComponent();
_registerData = new ushort[65600];
}
private void BaseFormLoading(object sender, EventArgs e)
{
comboBoxBaudRate.SelectedIndex = 4;
FillRTUDropDownLists();
CurrentTab.RegisterData = _registerData;
if (_registerData == null)
{
throw new ApplicationException("Failed to allocate 128k block");
}
LoadUserData();
CurrentTab.DisplayFormat = DisplayFormat;
RefreshData();
}
private void BaseFormClosing(object sender, FormClosingEventArgs e)
{
SaveUserData();
}
private void FillRTUDropDownLists()
{
comboBoxSerialPorts.Items.Clear();
foreach (var port in SerialPort.GetPortNames())
{
comboBoxSerialPorts.Items.Add(port);
}
if (comboBoxSerialPorts.Items.Count > 0)
comboBoxSerialPorts.SelectedIndex = 0;
comboBoxParity.Items.Clear();
comboBoxParity.Items.Add(Parity.None.ToString());
comboBoxParity.Items.Add(Parity.Odd.ToString());
comboBoxParity.Items.Add(Parity.Even.ToString());
comboBoxParity.Items.Add(Parity.Mark.ToString());
comboBoxParity.Items.Add(Parity.Space.ToString());
}
private void LoadUserData()
{
CommunicationMode mode;
if (Enum.TryParse(Properties.Settings.Default.CommunicationMode, out mode))
CommunicationMode = mode;
DisplayFormat format;
if (Enum.TryParse(Properties.Settings.Default.DisplayFormat, out format))
DisplayFormat = format;
IPAddress ipAddress;
if (IPAddress.TryParse(Properties.Settings.Default.IPAddress, out ipAddress))
IPAddress = ipAddress;
TCPPort = Properties.Settings.Default.TCPPort;
PortName = Properties.Settings.Default.PortName;
Baud = Properties.Settings.Default.Baud;
Parity = Properties.Settings.Default.Parity;
StartAddress = Properties.Settings.Default.StartAddress;
DataLength = Properties.Settings.Default.DataLength;
SlaveId = Properties.Settings.Default.SlaveId;
SlaveDelay = Properties.Settings.Default.SlaveDelay;
DataBits = Properties.Settings.Default.DataBits;
StopBits = Properties.Settings.Default.StopBits;
}
private void SaveUserData()
{
Properties.Settings.Default.CommunicationMode = CommunicationMode.ToString();
Properties.Settings.Default.IPAddress = IPAddress.ToString();
Properties.Settings.Default.DisplayFormat = DisplayFormat.ToString();
Properties.Settings.Default.TCPPort = TCPPort;
Properties.Settings.Default.PortName = PortName;
Properties.Settings.Default.Baud = Baud;
Properties.Settings.Default.Parity = Parity;
Properties.Settings.Default.StartAddress = StartAddress;
Properties.Settings.Default.DataLength = DataLength;
Properties.Settings.Default.SlaveId = SlaveId;
Properties.Settings.Default.SlaveDelay = SlaveDelay;
Properties.Settings.Default.DataBits = DataBits;
Properties.Settings.Default.StopBits = StopBits;
Properties.Settings.Default.Save();
}
#endregion
#region Import - Export
private void ButtonImportClick(object sender, EventArgs e)
{
openFileDialog.AddExtension = true;
openFileDialog.DefaultExt = ".csv";
openFileDialog.Multiselect = false;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
using (var s = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read))
{
using (var r = new StreamReader(s))
{
var rec = r.ReadToEnd();
var sets = rec.Split(',');
var first = true;
foreach (var s1 in sets)
{
DisplayFormat fmt;
var v = s1.Split(':');
var address = int.Parse(v[0]);
ushort data;
if (v[1].StartsWith("0x", StringComparison.CurrentCultureIgnoreCase))
{
fmt = DisplayFormat.Hex;
var sub = v[1].Substring(2);
ushort.TryParse(sub, NumberStyles.HexNumber, CultureInfo.CurrentCulture, out data);
}
else if (v[1].Length > 6) //must be binary
{
fmt = DisplayFormat.Binary;
data = Convert.ToUInt16(v[1], 2);
}
else
{
fmt = DisplayFormat.Integer;
data = Convert.ToUInt16(v[1], 10);
}
if (address < _registerData.Length)
{
_registerData[address] = data;
}
if (first)
{
SetFunction(fmt);
first = false;
StartAddress = UInt16.Parse(v[0]);
}
}
r.Close();
DataLength = Convert.ToUInt16(sets.Length);
// display data
}
s.Close();
}
RefreshData();
}
}
public delegate void SetFunctionDelegate(DisplayFormat log);
protected void SetFunction(DisplayFormat fmt)
{
if (InvokeRequired)
{
BeginInvoke(new SetFunctionDelegate(SetFunction), new object[] { fmt });
return;
}
DisplayFormat = fmt;
switch (fmt)
{
case DisplayFormat.Integer:
radioButtonInteger.Checked = true;
break;
case DisplayFormat.Binary:
radioButtonBinary.Checked = true;
break;
case DisplayFormat.Hex:
radioButtonHex.Checked = true;
break;
case DisplayFormat.LED:
radioButtonLED.Checked = true;
break;
case DisplayFormat.FloatReverse:
radioButtonReverseFloat.Checked = true;
break;
}
}
private void ButtonExportClick(object sender, EventArgs e)
{
var startAddress = StartAddress;
var length = DataLength;
string suffix = "-";
switch (DisplayFormat)
{
case DisplayFormat.Integer:
suffix = "_Decimal_";
break;
case DisplayFormat.Hex:
suffix = "_HEX_";
break;
case DisplayFormat.Binary:
suffix = "_Binary_";
break;
case DisplayFormat.LED:
suffix = "_LED_";
break;
}
var filename = "ModbusExport_" + startAddress + suffix + DateTime.Now.ToString("yyyyMMddHHmm") + ".csv";
saveFileDialog.AddExtension = true;
saveFileDialog.DefaultExt = ".csv";
saveFileDialog.FileName = filename;
saveFileDialog.OverwritePrompt = true;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
using (var s = saveFileDialog.OpenFile())
{
using (var w = new StreamWriter(s))
{
for (var x = 0; x < length; x++)
{
w.Write(startAddress++);
w.Write(':');
var data = _registerData[StartAddress + x];
switch (DisplayFormat)
{
case DisplayFormat.Integer:
w.Write(string.Format("{0}", data));
break;
case DisplayFormat.Hex:
w.Write(string.Format("0x{0:x4}", data));
break;
case DisplayFormat.Binary:
case DisplayFormat.LED:
w.Write(Convert.ToString(data, 2).PadLeft(16, '0'));
break;
}
if (x < length - 1)
w.Write(',');
}
w.Flush();
w.Close();
}
s.Close();
}
}
}
#endregion
#region Radion button check handlers
private void RadioButtonModeChanged(object sender, EventArgs e)
{
SetMode();
}
protected void SetMode()
{
if (radioButtonTCP.Checked)
{
_communicationMode = CommunicationMode.TCP;
groupBoxTCP.Enabled = true;
groupBoxRTU.Enabled = false;
}
if (radioButtonRTU.Checked)
{
_communicationMode = CommunicationMode.RTU;
groupBoxTCP.Enabled = false;
groupBoxRTU.Enabled = true;
}
if (radioButtonUDP.Checked)
{
_communicationMode = CommunicationMode.UDP;
groupBoxTCP.Enabled = true;
groupBoxRTU.Enabled = false;
}
}
private void RadioButtonDisplayFormatCheckedChanged(object sender, EventArgs e)
{
if (sender is RadioButton)
{
var rb = (RadioButton)sender;
if (rb.Checked)
{
DisplayFormat.TryParse(rb.Tag.ToString(), true, out _displayFormat);
CurrentTab.DisplayFormat = DisplayFormat;
RefreshData();
}
}
}
#endregion
#region properties
private ushort _startAddress;
protected ushort StartAddress
{
get
{
return _startAddress;
}
set
{
CurrentTab.StartAddress = value;
var tab = tabControl1.SelectedTab;
tab.Text = value.ToString();
_startAddress = value;
}
}
private ushort _dataLength;
private bool showDataLength;
protected ushort DataLength
{
get
{
return _dataLength;
}
set
{
_dataLength = value;
CurrentTab.DataLength = value;
}
}
public bool ShowDataLength
{
get => showDataLength;
set
{
showDataLength = value;
foreach (DataTab tab in tabPage1.Controls)
{
tab.ShowDataLength = value;
}
foreach (DataTab tab in tabPage2.Controls)
{
tab.ShowDataLength = value;
}
}
}
protected IPAddress IPAddress
{
get
{
return IPAddress.Parse(txtIP.Text);
}
set
{
txtIP.Text = value.ToString();
}
}
protected int TCPPort
{
get
{
return Int32.Parse(textBoxPort.Text);
}
set
{
textBoxPort.Text = Convert.ToString(value);
}
}
protected byte SlaveId
{
get
{
return Byte.Parse(textBoxSlaveID.Text);
}
set
{
textBoxSlaveID.Text = Convert.ToString(value);
}
}
protected int SlaveDelay
{
get
{
return int.Parse(textBoxSlaveDelay.Text);
}
set
{
textBoxSlaveDelay.Text = Convert.ToString(value);
}
}
protected string PortName
{
get
{
return comboBoxSerialPorts.Text;
}
set
{
comboBoxSerialPorts.Text = value;
}
}
protected int Baud
{
get
{
return Int32.Parse(comboBoxBaudRate.Text);
}
set
{
comboBoxBaudRate.SelectedItem = Convert.ToString(value);
}
}
protected Parity Parity
{
get
{
var parity = Parity.None;
if (comboBoxParity.SelectedItem.Equals(Parity.None.ToString()))
{
parity = Parity.None;
}
else if (comboBoxParity.SelectedItem.Equals(Parity.Odd.ToString()))
{
parity = Parity.Odd;
}
else if (comboBoxParity.SelectedItem.Equals(Parity.Even.ToString()))
{
parity = Parity.Even;
}
else if (comboBoxParity.SelectedItem.Equals(Parity.Mark.ToString()))
{
parity = Parity.Mark;
}
else if (comboBoxParity.SelectedItem.Equals(Parity.Space.ToString()))
{
parity = Parity.Space;
}
return parity;
}
set
{
comboBoxParity.SelectedItem = Convert.ToString(value);
}
}
protected int DataBits
{
get
{
int bits = 0;
switch (comboBoxDataBits.SelectedIndex)
{
case 0:
bits = 7;
break;
case 1:
bits = 8;
break;
}
return bits;
}
set
{
switch (value)
{
case 7:
comboBoxDataBits.SelectedIndex = 0;
break;
case 8:
comboBoxDataBits.SelectedIndex = 1;
break;
}
}
}
protected StopBits StopBits
{
get
{
StopBits bits = StopBits.None;
switch (comboBoxStopBits.SelectedIndex)
{
case 0:
bits = StopBits.None;
break;
case 1:
bits = StopBits.One;
break;
case 2:
bits = StopBits.OnePointFive;
break;
case 3:
bits = StopBits.Two;
break;
}
return bits;
}
set
{
switch (value)
{
case StopBits.None:
comboBoxStopBits.SelectedIndex = 0;
break;
case StopBits.One:
comboBoxStopBits.SelectedIndex = 1;
break;
case StopBits.OnePointFive:
comboBoxStopBits.SelectedIndex = 2;
break;
case StopBits.Two:
comboBoxStopBits.SelectedIndex = 3;
break;
}
}
}
protected DisplayFormat DisplayFormat
{
get { return _displayFormat; }
set
{
switch (value)
{
case DisplayFormat.LED:
radioButtonLED.Checked = true;
break;
case DisplayFormat.Binary:
radioButtonBinary.Checked = true;
break;
case DisplayFormat.Hex:
radioButtonHex.Checked = true;
break;
case DisplayFormat.Integer:
radioButtonInteger.Checked = true;
break;
case DisplayFormat.FloatReverse:
radioButtonReverseFloat.Checked = true;
break;
}
_displayFormat = value;
CurrentTab.DisplayFormat = DisplayFormat;
RefreshData();
}
}
protected CommunicationMode CommunicationMode
{
get { return _communicationMode; }
set
{
switch (value)
{
case CommunicationMode.TCP:
radioButtonTCP.Checked = true;
break;
case CommunicationMode.UDP:
radioButtonUDP.Checked = true;
break;
case CommunicationMode.RTU:
radioButtonRTU.Checked = true;
break;
}
_communicationMode = value;
}
}
#endregion
#region Logging
public delegate void AppendLogDelegate(String log);
protected void ButtonClearLogClick(object sender, EventArgs e)
{
listBoxCommLog.Items.Clear();
}
private void buttonPauseLog_Click(object sender, EventArgs e)
{
_logPaused = !_logPaused;
buttonPauseLog.Text = _logPaused ? "Resume" : "Pause";
}
private async void buttonSaveLog_ClickAsync(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.FileName = "ModbusLog";
saveFileDialog.OverwritePrompt = true;
saveFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog.DefaultExt = "txt";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
using (StreamWriter writer = new StreamWriter(saveFileDialog.FileName, append: true))
{
foreach (string line in listBoxCommLog.Items)
{
await writer.WriteLineAsync(line);
}
}
}
}
protected void DriverIncommingData(byte[] data, int len)
{
if (_logPaused)
return;
var hex = new StringBuilder(len);
for(int i = 0; i < len; i++)
{
hex.AppendFormat("{0:x2} ", data[i]);
}
AppendLog(String.Format("RX: {0}", hex));
}
protected void DriverOutgoingData(byte[] data)
{
if (_logPaused)
return;
var hex = new StringBuilder(data.Length * 2);
foreach (byte b in data)
hex.AppendFormat("{0:x2} ", b);
AppendLog(String.Format("TX: {0}", hex));
}
protected void AppendLog(String log)
{
if (_logPaused)
return;
if (InvokeRequired)
{
BeginInvoke(new AppendLogDelegate(AppendLog), new object[] { log });
return;
}
var now = DateTime.Now;
var tmpStr = ">" + now.ToLongTimeString() + ": " + log;
listBoxCommLog.Items.Add(tmpStr);
listBoxCommLog.SelectedIndex = listBoxCommLog.Items.Count - 1;
//listBoxCommLog.SelectedIndex = -1;
}
#endregion
#region Data Table
protected void ButtonDataClearClick(object sender, EventArgs e)
{
ClearRegisterData();
}
protected void ClearRegisterData()
{
for (int i = 0; i < _registerData.Length; i++)
{
_registerData[i] = 0;
}
RefreshData();
}
protected DataTab CurrentTab
{
get
{
var tab = tabControl1.SelectedTab;
return (DataTab)tab.Controls[0];
}
}
public void RefreshData()
{
if (InvokeRequired)
{
BeginInvoke(new Action(RefreshData));
return;
}
CurrentTab.RefreshData();
// Reset event handler
CurrentTab.OnApply -= dataTab_OnApply;
CurrentTab.OnApply += dataTab_OnApply;
}
public void UpdateDataTable()
{
if (InvokeRequired)
{
BeginInvoke(new Action(UpdateDataTable));
return;
}
CurrentTab.UpdateDataTable();
}
#endregion
private void tabControl1_Selected(object sender, TabControlEventArgs e)
{
CurrentTab.RegisterData = _registerData;
CurrentTab.DisplayFormat = DisplayFormat;
var tab = tabControl1.SelectedTab;
if (tab.Text.Equals("...") && tabControl1.TabPages.Count < 20)
{
DataTab dataTab = new DataTab();
dataTab.DataLength = 256;
dataTab.DisplayFormat = DisplayFormat.Integer;
dataTab.Location = new Point(3, 3);
dataTab.Name = "dataTab" + (tabControl1.TabPages.Count + 1);
dataTab.RegisterData = _registerData;
dataTab.ShowDataLength = ShowDataLength;
dataTab.Size = new Size(839, 406);
dataTab.StartAddress = 0;
dataTab.TabIndex = 0;
dataTab.OnApply += dataTab_OnApply;
TabPage tabPage = new TabPage();
tabPage.Controls.Add(dataTab);
tabPage.Location = new Point(4, 22);
tabPage.Name = "tabPage" + (tabControl1.TabPages.Count + 1);
tabPage.Padding = new Padding(3);
tabPage.Size = new Size(851, 411);
tabPage.TabIndex = tabControl1.TabPages.Count;
tabPage.Text = "...";
tabPage.UseVisualStyleBackColor = true;
tabControl1.Controls.Add(tabPage);
}
var address = CurrentTab.StartAddress;
tab.Text = address.ToString();
_startAddress = address;
_dataLength = CurrentTab.DataLength;
}
void dataTab_OnApply(object sender, EventArgs e)
{
var tab = tabControl1.SelectedTab;
var address = CurrentTab.StartAddress;
tab.Text = address.ToString();
_startAddress = address;
_dataLength = CurrentTab.DataLength;
}
private void donate_Click(object sender, EventArgs e)
{
string url = "https://www.buymeacoffee.com/r4K2HIB";
System.Diagnostics.Process.Start(url);
}
}
}