This commit is contained in:
nikzori
2025-01-14 11:31:23 +03:00
parent 41062d47e5
commit bb2a46d592
6 changed files with 301 additions and 1532 deletions

193
Datasheet.Designer.cs generated
View File

@@ -29,117 +29,134 @@
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Datasheet));
this.Label_DeviceNameLabel = new System.Windows.Forms.Label();
this.Label_DescriptionLabel = new System.Windows.Forms.Label();
this.Label_DeviceName = new System.Windows.Forms.Label();
this.Label_Description = new System.Windows.Forms.Label();
this.Button_StartStop = new System.Windows.Forms.Button();
this.Panel_Device = new System.Windows.Forms.Panel();
this.PD_Scrollbar = new System.Windows.Forms.VScrollBar();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.label1 = new System.Windows.Forms.Label();
this.Panel_Device.SuspendLayout();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.nudModbusID = new System.Windows.Forms.NumericUpDown();
this.labelModel = new System.Windows.Forms.Label();
this.labelFirmware = new System.Windows.Forms.Label();
this.buttonSetID = new System.Windows.Forms.Button();
this.buttonPoll = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.nudModbusID)).BeginInit();
this.SuspendLayout();
//
// Label_DeviceNameLabel
// groupBox1
//
this.Label_DeviceNameLabel.AutoSize = true;
this.Label_DeviceNameLabel.Location = new System.Drawing.Point(13, 13);
this.Label_DeviceNameLabel.Name = "Label_DeviceNameLabel";
this.Label_DeviceNameLabel.Size = new System.Drawing.Size(92, 13);
this.Label_DeviceNameLabel.TabIndex = 1;
this.Label_DeviceNameLabel.Text = "Имя устройства:";
//
// Label_DescriptionLabel
//
this.Label_DescriptionLabel.AutoSize = true;
this.Label_DescriptionLabel.Location = new System.Drawing.Point(13, 31);
this.Label_DescriptionLabel.Name = "Label_DescriptionLabel";
this.Label_DescriptionLabel.Size = new System.Drawing.Size(60, 13);
this.Label_DescriptionLabel.TabIndex = 2;
this.Label_DescriptionLabel.Text = "Описание:";
//
// Label_DeviceName
//
this.Label_DeviceName.AutoSize = true;
this.Label_DeviceName.Location = new System.Drawing.Point(104, 13);
this.Label_DeviceName.Name = "Label_DeviceName";
this.Label_DeviceName.Size = new System.Drawing.Size(35, 13);
this.Label_DeviceName.TabIndex = 3;
this.Label_DeviceName.Text = "label3";
//
// Label_Description
//
this.Label_Description.AutoSize = true;
this.Label_Description.Location = new System.Drawing.Point(72, 31);
this.Label_Description.Name = "Label_Description";
this.Label_Description.Size = new System.Drawing.Size(35, 13);
this.Label_Description.TabIndex = 4;
this.Label_Description.Text = "label4";
//
// Button_StartStop
//
this.Button_StartStop.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.Button_StartStop.Location = new System.Drawing.Point(505, 13);
this.Button_StartStop.Name = "Button_StartStop";
this.Button_StartStop.Size = new System.Drawing.Size(75, 23);
this.Button_StartStop.TabIndex = 5;
this.Button_StartStop.Text = "Старт";
this.Button_StartStop.UseVisualStyleBackColor = true;
this.Button_StartStop.Click += new System.EventHandler(this.Button_StartStop_Click);
//
// Panel_Device
//
this.Panel_Device.Controls.Add(this.PD_Scrollbar);
this.Panel_Device.Location = new System.Drawing.Point(13, 77);
this.Panel_Device.Name = "Panel_Device";
this.Panel_Device.Size = new System.Drawing.Size(567, 411);
this.Panel_Device.TabIndex = 6;
//
// PD_Scrollbar
//
this.PD_Scrollbar.Location = new System.Drawing.Point(549, 0);
this.PD_Scrollbar.Name = "PD_Scrollbar";
this.PD_Scrollbar.Size = new System.Drawing.Size(17, 440);
this.PD_Scrollbar.TabIndex = 0;
this.groupBox1.Controls.Add(this.buttonPoll);
this.groupBox1.Controls.Add(this.buttonSetID);
this.groupBox1.Controls.Add(this.labelFirmware);
this.groupBox1.Controls.Add(this.labelModel);
this.groupBox1.Controls.Add(this.nudModbusID);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Location = new System.Drawing.Point(369, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(211, 101);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Инфо";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(13, 64);
this.label1.Location = new System.Drawing.Point(6, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(14, 13);
this.label1.TabIndex = 7;
this.label1.Text = "#";
this.label1.Size = new System.Drawing.Size(49, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Модель:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(6, 31);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(62, 13);
this.label2.TabIndex = 1;
this.label2.Text = "Прошивка:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(6, 55);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(62, 13);
this.label3.TabIndex = 2;
this.label3.Text = "Modbus ID:";
//
// nudModbusID
//
this.nudModbusID.Location = new System.Drawing.Point(9, 71);
this.nudModbusID.Name = "nudModbusID";
this.nudModbusID.Size = new System.Drawing.Size(59, 20);
this.nudModbusID.TabIndex = 3;
//
// labelModel
//
this.labelModel.AutoSize = true;
this.labelModel.Location = new System.Drawing.Point(61, 16);
this.labelModel.Name = "labelModel";
this.labelModel.Size = new System.Drawing.Size(50, 13);
this.labelModel.TabIndex = 4;
this.labelModel.Text = "Standard";
//
// labelFirmware
//
this.labelFirmware.AutoSize = true;
this.labelFirmware.Location = new System.Drawing.Point(74, 31);
this.labelFirmware.Name = "labelFirmware";
this.labelFirmware.Size = new System.Drawing.Size(37, 13);
this.labelFirmware.TabIndex = 5;
this.labelFirmware.Text = "v1.0.4";
//
// buttonSetID
//
this.buttonSetID.Location = new System.Drawing.Point(74, 68);
this.buttonSetID.Name = "buttonSetID";
this.buttonSetID.Size = new System.Drawing.Size(75, 23);
this.buttonSetID.TabIndex = 6;
this.buttonSetID.Text = "Изменить";
this.buttonSetID.UseVisualStyleBackColor = true;
this.buttonSetID.Click += new System.EventHandler(this.buttonSetID_Click);
//
// buttonPoll
//
this.buttonPoll.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.buttonPoll.Location = new System.Drawing.Point(130, 19);
this.buttonPoll.Name = "buttonPoll";
this.buttonPoll.Size = new System.Drawing.Size(75, 23);
this.buttonPoll.TabIndex = 7;
this.buttonPoll.Text = "Опрос";
this.buttonPoll.UseVisualStyleBackColor = true;
//
// Datasheet
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(592, 500);
this.Controls.Add(this.label1);
this.Controls.Add(this.Panel_Device);
this.Controls.Add(this.Button_StartStop);
this.Controls.Add(this.Label_Description);
this.Controls.Add(this.Label_DeviceName);
this.Controls.Add(this.Label_DescriptionLabel);
this.Controls.Add(this.Label_DeviceNameLabel);
this.Controls.Add(this.groupBox1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "Datasheet";
this.Text = "Datasheet";
this.Panel_Device.ResumeLayout(false);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.nudModbusID)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label Label_DeviceNameLabel;
private System.Windows.Forms.Label Label_DescriptionLabel;
private System.Windows.Forms.Label Label_DeviceName;
private System.Windows.Forms.Label Label_Description;
private System.Windows.Forms.Button Button_StartStop;
private System.Windows.Forms.Panel Panel_Device;
private System.Windows.Forms.VScrollBar PD_Scrollbar;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button buttonSetID;
private System.Windows.Forms.Label labelFirmware;
private System.Windows.Forms.Label labelModel;
private System.Windows.Forms.NumericUpDown nudModbusID;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button buttonPoll;
}
}

View File

@@ -13,365 +13,37 @@ namespace Gidrolock_Modbus_Scanner
{
public partial class Datasheet : Form
{
byte modbusID;
Device device;
SerialPort port = Modbus.port;
bool isPolling = false;
bool isAwaitingResponse = false;
byte[] message = new byte[255];
int timeout = 3000;
int pollDelay = 250; // delay between each entry poll, ms
byte slaveID;
Device device = App.device;
List<Entry> entries;
List<EntryRow> entryRows;
int activeEntryIndex; // entry index for modbus responses
int activeDGVIndex; // index for DGV rows
SerialPort port = Modbus.port;
bool closed = false;
public Datasheet(byte slaveID)
public Datasheet(byte modbusID, Device device)
{
Modbus.ResponseReceived += PublishResponse;
this.slaveID = slaveID;
entries = device.entries;
InitializeComponent();
Label_DeviceName.Text = device.name;
Label_Description.Text = device.description;
int rowCount = 0;
entryRows = new List<EntryRow>();
foreach (Entry e in entries)
{
if (e.length > 1)
{
// multi-register entry check
if ((e.length == 2 && e.dataType == "uint32") || e.dataType == "string")
{
entryRows.Add(new EntryRow(rowCount, e.address, e.name));
rowCount++;
}
else
{
for (int i = 0; i < e.length; i++)
{
if (i < e.labels.Count)
{
entryRows.Add(new EntryRow(rowCount, e.address + i, e.labels[i]));
}
else
{
entryRows.Add(new EntryRow(rowCount, e.address + i, (e.address + i).ToString()));
}
rowCount++;
}
}
}
else
{
entryRows.Add(new EntryRow(rowCount, e.address, e.name));
rowCount++;
}
}
foreach (EntryRow row in entryRows)
Panel_Device.Controls.Add(row);
FormClosing += (s, e) => { closed = true; };
Task.Run(() => AutoPollAsync());
nudModbusID.Minimum = 1;
nudModbusID.Maximum = 246;
this.modbusID = modbusID;
this.device = device;
}
public async void AutoPollAsync()
private async void buttonSetID_Click(object sender, EventArgs e)
{
if (!port.IsOpen)
port.Open();
port.ReadTimeout = timeout;
try
Modbus.WriteSingleAsync(FunctionCode.WriteRegister, modbusID, 200, (byte)nudModbusID.Value);
byte[] data = null;
Modbus.ResponseReceived += (sndr, msg) =>
{
while (!closed)
{
if (isPolling)
{
if (entryRows[activeDGVIndex].chboxPanel.chbox.Checked)
{
//Console.WriteLine("Polling for " + device.entries[activeEntryIndex].name);
await PollForEntry(entries[activeEntryIndex]);
Thread.Sleep(150);
}
else //need to skip multiple dgv entries without accidentaly skipping entries
{
if (device.entries[activeEntryIndex].labels is null || device.entries[activeEntryIndex].labels.Count == 0)
activeDGVIndex++;
else
{
for (int i = 0; i < device.entries[activeEntryIndex].labels.Count; i++)
{
activeDGVIndex++;
}
}
}
activeEntryIndex++;
if (activeEntryIndex >= device.entries.Count)
activeEntryIndex = 0;
if (activeDGVIndex >= entryRows.Count)
activeDGVIndex = 0;
}
}
}
catch (Exception err)
data = msg.Data;
};
await Task.Run(() =>
{
MessageBox.Show(err.Message, "AutoPollAsync");
}
while (data is null) { continue; }
if (message[1] > 0x10) //exception code check
return;
}
public async Task PollForEntry(Entry entry)
{
byte[] message = new byte[8];
var send = Modbus.ReadRegAsync(port, slaveID, (FunctionCode)entry.registerType, entry.address, entry.length);
isAwaitingResponse = true;
Task delay = Task.WhenAny(Task.Delay(timeout), Task.Run(() => { while (isAwaitingResponse) { } return true; })).ContinueWith((t) =>
{
if (isAwaitingResponse)
{
Console.WriteLine("Response timed out.");
isAwaitingResponse = false;
}
return false;
});
await delay;
}
void PublishResponse(object sender, ModbusResponseEventArgs e)
{
if (isAwaitingResponse)
{
try
{
if (entries[activeEntryIndex].readOnce)
{
entryRows[activeDGVIndex].chboxPanel.chbox.Checked = false;
}
int dbc = e.Message[2]; // data byte count
switch (entries[activeEntryIndex].dataType)
{
case ("bool"):
if (entries[activeEntryIndex].labels is null || entries[activeEntryIndex].labels.Count == 0) // assume that no labels = 1 entry
{
//no valueParse keys
if (entries[activeEntryIndex].valueParse is null || entries[activeEntryIndex].valueParse.Keys.Count == 0)
{
// coil combobox
if (entries[activeEntryIndex].registerType == RegisterType.Coil)
{
entryRows[activeDGVIndex].SetValue(e.Data[0] > 0x00 ? "True" : "False");
}
// discrete inputs
else
{
entryRows[activeDGVIndex].SetValue(e.Data[0] > 0x00 ? "True" : "False");
}
}
else
{
try { entryRows[activeDGVIndex].valueLabel.Text = e.Data[0] > 0x00 ? entries[activeEntryIndex].valueParse["true"] : entries[activeEntryIndex].valueParse["false"]; }
catch (Exception err)
{
// coil combobox
if (entries[activeEntryIndex].registerType == RegisterType.Coil)
{
entryRows[activeDGVIndex].SetValue(e.Data[0] > 0x00 ? "True" : "False");
}
else // discrete inputs
{
entryRows[activeDGVIndex].SetValue(e.Data[0] > 0x00 ? "True" : "False");
}
}
}
activeDGVIndex++;
}
else
{
List<bool> values = new List<bool>();
for (int i = 0; i < dbc; i++)
{
for (int j = 0; j < 8; j++)
{
bool res = (((e.Data[i] >> j) & 0x01) >= 1) ? true : false;
values.Add(res);
}
}
for (int i = 0; i < entries[activeEntryIndex].labels.Count; i++)
{
if (entries[activeEntryIndex].registerType == RegisterType.Coil)
{
entryRows[activeDGVIndex].SetValue(e.Data[0] > 0x00 ? "True" : "False");
}
else
{
entryRows[activeDGVIndex].SetValue(e.Data[0] > 0x00 ? "True" : "False");
}
activeDGVIndex++;
}
}
break;
case ("uint16"):
ushort value = BitConverter.ToUInt16(e.Data, 0);
if (entries[activeEntryIndex].labels is null || entries[activeEntryIndex].labels.Count == 0) // single value
{
if (entries[activeEntryIndex].valueParse is null || entries[activeEntryIndex].valueParse.Keys.Count == 0)
{
//Array.Reverse(e.Data); // this was necessary, but something changed, idk
//Console.WriteLine("ushort parsed value: " + value);
entryRows[activeDGVIndex].SetValue(value.ToString());
}
else
{
try
{
entryRows[activeDGVIndex].SetValue(entries[activeEntryIndex].valueParse[value.ToString()]);
}
catch (Exception err)
{
entryRows[activeDGVIndex].SetValue(value.ToString());
MessageBox.Show("Error parsing uint value at address: " + entries[activeEntryIndex].address + "; " + err.Message, "uint16 parse");
}
}
activeDGVIndex++;
}
else // value group
{
try
{
List<ushort> values = new List<ushort>();
for (int i = 0; i < dbc; i += 2)
{
ushort s = BitConverter.ToUInt16(e.Data, i);
values.Add(s);
}
//Console.WriteLine("ushort values count: " + values.Count);
//Console.WriteLine("entity labels count: " + entries[activeEntryIndex].labels.Count);
for (int i = 0; i < entries[activeEntryIndex].labels.Count; i++)
{
if (device.entries[activeEntryIndex].valueParse != null)
{
entryRows[activeDGVIndex].SetValue(values[i].ToString());
}
else
{
entryRows[activeDGVIndex].SetValue(values[i].ToString());
}
activeDGVIndex++;
}
}
catch (Exception err)
{
entryRows[activeDGVIndex].SetValue(value.ToString());
MessageBox.Show("Error parsing uint value at address: " + entries[activeEntryIndex].address + "; " + err.Message, "uint16 group req parse");
}
}
break;
case ("uint32"):
Array.Reverse(e.Data);
entryRows[activeDGVIndex].SetValue(BitConverter.ToUInt32(e.Data, 0).ToString());
activeDGVIndex++;
break;
case ("string"):
List<byte> bytes = new List<byte>();
for (int i = 0; i < e.Data.Length; i++)
{
if (e.Data[i] != 0)
bytes.Add(e.Data[i]);
}
bytes.Reverse();
entryRows[activeDGVIndex].SetValue(System.Text.Encoding.UTF8.GetString(bytes.ToArray()));
activeDGVIndex++;
break;
default:
MessageBox.Show("Wrong data type set for entry " + entries[activeEntryIndex].name);
activeDGVIndex++;
break;
}
if (activeDGVIndex >= entryRows.Count)
activeDGVIndex = 0;
//MessageBox.Show("Получен ответ от устройства: " + dataCleaned, "Успех", MessageBoxButtons.OK);
port.DiscardInBuffer();
}
catch (Exception err) { MessageBox.Show(err.Message, "Publish response error"); }
}
if (activeDGVIndex >= entryRows.Count)
activeDGVIndex = 0;
isAwaitingResponse = false;
}
private void Button_StartStop_Click(object sender, EventArgs e)
{
isPolling = !isPolling;
Button_StartStop.Text = (isPolling ? "Стоп" : "Старт");
}
public class EntryRow : Panel
{
public CheckboxPanel chboxPanel = new CheckboxPanel() { Width = 20, Height = 20 };
public Label numberLabel = new Label() { Height = 20, Width = 30, TextAlign = ContentAlignment.MiddleLeft };
public Label addressLabel = new Label() { Height = 20, Width = 60, TextAlign = ContentAlignment.MiddleLeft };
public Label nameLabel = new Label() { Height = 20, Width = 220, TextAlign = ContentAlignment.MiddleLeft };
public Label valueLabel = new Label() { Height = 20, Width = 220, TextAlign = ContentAlignment.MiddleLeft };
public void SetValue(string value)
{
valueLabel.Text = value;
}
public EntryRow(int number, int address, string name)
{
chboxPanel.Parent = this;
numberLabel.Parent = this;
addressLabel.Parent = this;
nameLabel.Parent = this;
valueLabel.Parent = this;
chboxPanel.Location = new Point(Left, Top);
numberLabel.Location = new Point(20, Top);
addressLabel.Location = new Point(50, Top);
nameLabel.Location = new Point(110, Top);
valueLabel.Location = new Point(330, Top);
numberLabel.Text = number.ToString();
addressLabel.Text = address.ToString();
nameLabel.Text = name.ToString();
}
}
public class CheckboxPanel : Panel
{
public CheckBox chbox;
public CheckboxPanel() : base()
{
chbox = new CheckBox() { Parent = this, Location = new Point(Left, Top) };
}
public void SetVisibility(bool value)
{
chbox.Visible = value;
}
}
}
}

View File

@@ -12,6 +12,7 @@ namespace Gidrolock_Modbus_Scanner
{
public string name;
public string description;
public byte id;
public List<Entry> entries;
public CheckEntry checkEntry;

562
Main.Designer.cs generated
View File

@@ -29,443 +29,31 @@
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(App));
this.Button_Connect = new System.Windows.Forms.Button();
this.TextBox_Log = new System.Windows.Forms.TextBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.panel6 = new System.Windows.Forms.Panel();
this.TBox_RegValue = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.panel5 = new System.Windows.Forms.Panel();
this.UpDown_RegLength = new System.Windows.Forms.NumericUpDown();
this.label5 = new System.Windows.Forms.Label();
this.Button_SendCommand = new System.Windows.Forms.Button();
this.panel3 = new System.Windows.Forms.Panel();
this.TBox_RegAddress = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.panel4 = new System.Windows.Forms.Panel();
this.CBox_Function = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.Label_ConfigTip = new System.Windows.Forms.Label();
this.Button_LoadConfig = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.Label_ConfPath = new System.Windows.Forms.Label();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.button1 = new System.Windows.Forms.Button();
this.GBox_Serial = new System.Windows.Forms.GroupBox();
this.panel11 = new System.Windows.Forms.Panel();
this.CBox_Parity = new System.Windows.Forms.ComboBox();
this.label11 = new System.Windows.Forms.Label();
this.panel10 = new System.Windows.Forms.Panel();
this.CBox_StopBits = new System.Windows.Forms.ComboBox();
this.label10 = new System.Windows.Forms.Label();
this.panel8 = new System.Windows.Forms.Panel();
this.panel9 = new System.Windows.Forms.Panel();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.label9 = new System.Windows.Forms.Label();
this.CBox_DataBits = new System.Windows.Forms.ComboBox();
this.label8 = new System.Windows.Forms.Label();
this.panel7 = new System.Windows.Forms.Panel();
this.CBox_BaudRate = new System.Windows.Forms.ComboBox();
this.label7 = new System.Windows.Forms.Label();
this.panel2 = new System.Windows.Forms.Panel();
this.UpDown_ModbusID = new System.Windows.Forms.NumericUpDown();
this.label2 = new System.Windows.Forms.Label();
this.panel1 = new System.Windows.Forms.Panel();
this.CBox_Ports = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.groupBox2.SuspendLayout();
this.panel6.SuspendLayout();
this.panel5.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.UpDown_RegLength)).BeginInit();
this.panel3.SuspendLayout();
this.panel4.SuspendLayout();
this.groupBox1.SuspendLayout();
this.GBox_Serial.SuspendLayout();
this.panel11.SuspendLayout();
this.panel10.SuspendLayout();
this.panel8.SuspendLayout();
this.panel9.SuspendLayout();
this.panel7.SuspendLayout();
this.panel2.SuspendLayout();
this.button1 = new System.Windows.Forms.Button();
this.cBoxDevice = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.checkboxID = new System.Windows.Forms.CheckBox();
((System.ComponentModel.ISupportInitialize)(this.UpDown_ModbusID)).BeginInit();
this.panel1.SuspendLayout();
this.SuspendLayout();
//
// Button_Connect
//
this.Button_Connect.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.Button_Connect.Location = new System.Drawing.Point(388, 69);
this.Button_Connect.Name = "Button_Connect";
this.Button_Connect.Size = new System.Drawing.Size(104, 25);
this.Button_Connect.TabIndex = 4;
this.Button_Connect.Text = "Подключиться";
this.Button_Connect.UseVisualStyleBackColor = true;
this.Button_Connect.Click += new System.EventHandler(this.ButtonConnect_Click);
//
// TextBox_Log
//
this.TextBox_Log.Location = new System.Drawing.Point(12, 194);
this.TextBox_Log.Location = new System.Drawing.Point(12, 53);
this.TextBox_Log.Multiline = true;
this.TextBox_Log.Name = "TextBox_Log";
this.TextBox_Log.ReadOnly = true;
this.TextBox_Log.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.TextBox_Log.Size = new System.Drawing.Size(498, 133);
this.TextBox_Log.Size = new System.Drawing.Size(498, 160);
this.TextBox_Log.TabIndex = 1;
//
// groupBox2
//
this.groupBox2.Controls.Add(this.panel6);
this.groupBox2.Controls.Add(this.panel5);
this.groupBox2.Controls.Add(this.Button_SendCommand);
this.groupBox2.Controls.Add(this.panel3);
this.groupBox2.Controls.Add(this.panel4);
this.groupBox2.Location = new System.Drawing.Point(12, 333);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(498, 63);
this.groupBox2.TabIndex = 5;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Команды";
//
// panel6
//
this.panel6.Controls.Add(this.TBox_RegValue);
this.panel6.Controls.Add(this.label6);
this.panel6.Location = new System.Drawing.Point(303, 20);
this.panel6.Name = "panel6";
this.panel6.Size = new System.Drawing.Size(104, 43);
this.panel6.TabIndex = 4;
//
// TBox_RegValue
//
this.TBox_RegValue.Location = new System.Drawing.Point(3, 17);
this.TBox_RegValue.Name = "TBox_RegValue";
this.TBox_RegValue.Size = new System.Drawing.Size(98, 20);
this.TBox_RegValue.TabIndex = 1;
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(3, 0);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(55, 13);
this.label6.TabIndex = 0;
this.label6.Text = "Значение";
//
// panel5
//
this.panel5.Controls.Add(this.UpDown_RegLength);
this.panel5.Controls.Add(this.label5);
this.panel5.Location = new System.Drawing.Point(225, 20);
this.panel5.Name = "panel5";
this.panel5.Size = new System.Drawing.Size(75, 43);
this.panel5.TabIndex = 3;
//
// UpDown_RegLength
//
this.UpDown_RegLength.Location = new System.Drawing.Point(6, 17);
this.UpDown_RegLength.Name = "UpDown_RegLength";
this.UpDown_RegLength.Size = new System.Drawing.Size(66, 20);
this.UpDown_RegLength.TabIndex = 1;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(3, 0);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(40, 13);
this.label5.TabIndex = 0;
this.label5.Text = "Длина";
//
// Button_SendCommand
//
this.Button_SendCommand.Location = new System.Drawing.Point(415, 35);
this.Button_SendCommand.Name = "Button_SendCommand";
this.Button_SendCommand.Size = new System.Drawing.Size(77, 23);
this.Button_SendCommand.TabIndex = 4;
this.Button_SendCommand.Text = "Отправить";
this.Button_SendCommand.UseVisualStyleBackColor = true;
this.Button_SendCommand.Click += new System.EventHandler(this.Button_SendCommand_Click);
//
// panel3
//
this.panel3.Controls.Add(this.TBox_RegAddress);
this.panel3.Controls.Add(this.label3);
this.panel3.Location = new System.Drawing.Point(159, 20);
this.panel3.Name = "panel3";
this.panel3.Size = new System.Drawing.Size(63, 43);
this.panel3.TabIndex = 2;
//
// TBox_RegAddress
//
this.TBox_RegAddress.Location = new System.Drawing.Point(3, 18);
this.TBox_RegAddress.Name = "TBox_RegAddress";
this.TBox_RegAddress.Size = new System.Drawing.Size(56, 20);
this.TBox_RegAddress.TabIndex = 1;
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(3, 0);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(38, 13);
this.label3.TabIndex = 0;
this.label3.Text = "Адрес";
//
// panel4
//
this.panel4.Controls.Add(this.CBox_Function);
this.panel4.Controls.Add(this.label4);
this.panel4.Location = new System.Drawing.Point(0, 20);
this.panel4.Name = "panel4";
this.panel4.Size = new System.Drawing.Size(156, 43);
this.panel4.TabIndex = 0;
//
// CBox_Function
//
this.CBox_Function.FormattingEnabled = true;
this.CBox_Function.Location = new System.Drawing.Point(6, 17);
this.CBox_Function.Name = "CBox_Function";
this.CBox_Function.Size = new System.Drawing.Size(147, 21);
this.CBox_Function.TabIndex = 1;
this.CBox_Function.Text = "01 - Read Coil";
this.CBox_Function.SelectedIndexChanged += new System.EventHandler(this.OnSelectedFunctionChanged);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(3, 0);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(53, 13);
this.label4.TabIndex = 0;
this.label4.Text = "Функция";
//
// Label_ConfigTip
//
this.Label_ConfigTip.AutoSize = true;
this.Label_ConfigTip.Location = new System.Drawing.Point(5, 16);
this.Label_ConfigTip.Name = "Label_ConfigTip";
this.Label_ConfigTip.Size = new System.Drawing.Size(94, 13);
this.Label_ConfigTip.TabIndex = 10;
this.Label_ConfigTip.Text = "Выбранный путь:";
//
// Button_LoadConfig
//
this.Button_LoadConfig.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.Button_LoadConfig.Location = new System.Drawing.Point(89, 69);
this.Button_LoadConfig.Name = "Button_LoadConfig";
this.Button_LoadConfig.Size = new System.Drawing.Size(77, 25);
this.Button_LoadConfig.TabIndex = 11;
this.Button_LoadConfig.Text = "Файл";
this.Button_LoadConfig.UseVisualStyleBackColor = true;
this.Button_LoadConfig.Click += new System.EventHandler(this.LoadConfig);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.Label_ConfPath);
this.groupBox1.Controls.Add(this.progressBar1);
this.groupBox1.Controls.Add(this.button1);
this.groupBox1.Controls.Add(this.Button_LoadConfig);
this.groupBox1.Controls.Add(this.Label_ConfigTip);
this.groupBox1.Controls.Add(this.Button_Connect);
this.groupBox1.Location = new System.Drawing.Point(12, 85);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(498, 103);
this.groupBox1.TabIndex = 13;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Конфигурация";
//
// Label_ConfPath
//
this.Label_ConfPath.Location = new System.Drawing.Point(6, 29);
this.Label_ConfPath.Name = "Label_ConfPath";
this.Label_ConfPath.Size = new System.Drawing.Size(480, 37);
this.Label_ConfPath.TabIndex = 14;
this.Label_ConfPath.Text = "Файл не выбран.";
//
// progressBar1
//
this.progressBar1.Location = new System.Drawing.Point(172, 69);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(210, 25);
this.progressBar1.TabIndex = 14;
//
// button1
//
this.button1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.button1.Location = new System.Drawing.Point(6, 69);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(77, 25);
this.button1.TabIndex = 13;
this.button1.Text = "Папка";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.LoadFolder);
//
// GBox_Serial
//
this.GBox_Serial.Controls.Add(this.panel11);
this.GBox_Serial.Controls.Add(this.panel10);
this.GBox_Serial.Controls.Add(this.panel8);
this.GBox_Serial.Controls.Add(this.panel7);
this.GBox_Serial.Controls.Add(this.panel2);
this.GBox_Serial.Controls.Add(this.panel1);
this.GBox_Serial.Location = new System.Drawing.Point(12, 12);
this.GBox_Serial.Name = "GBox_Serial";
this.GBox_Serial.Size = new System.Drawing.Size(498, 67);
this.GBox_Serial.TabIndex = 15;
this.GBox_Serial.TabStop = false;
this.GBox_Serial.Text = "Серийный порт";
//
// panel11
//
this.panel11.Controls.Add(this.CBox_Parity);
this.panel11.Controls.Add(this.label11);
this.panel11.Location = new System.Drawing.Point(330, 19);
this.panel11.Name = "panel11";
this.panel11.Size = new System.Drawing.Size(79, 43);
this.panel11.TabIndex = 6;
//
// CBox_Parity
//
this.CBox_Parity.FormattingEnabled = true;
this.CBox_Parity.Location = new System.Drawing.Point(6, 17);
this.CBox_Parity.Name = "CBox_Parity";
this.CBox_Parity.Size = new System.Drawing.Size(70, 21);
this.CBox_Parity.TabIndex = 2;
this.CBox_Parity.Text = "8";
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(3, 0);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(103, 13);
this.label11.TabIndex = 0;
this.label11.Text = "Контроль четности";
//
// panel10
//
this.panel10.Controls.Add(this.CBox_StopBits);
this.panel10.Controls.Add(this.label10);
this.panel10.Location = new System.Drawing.Point(247, 19);
this.panel10.Name = "panel10";
this.panel10.Size = new System.Drawing.Size(79, 43);
this.panel10.TabIndex = 5;
//
// CBox_StopBits
//
this.CBox_StopBits.FormattingEnabled = true;
this.CBox_StopBits.Location = new System.Drawing.Point(6, 17);
this.CBox_StopBits.Name = "CBox_StopBits";
this.CBox_StopBits.Size = new System.Drawing.Size(70, 21);
this.CBox_StopBits.TabIndex = 2;
this.CBox_StopBits.Text = "8";
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(3, 0);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(59, 13);
this.label10.TabIndex = 0;
this.label10.Text = "Стоп-биты";
//
// panel8
//
this.panel8.Controls.Add(this.panel9);
this.panel8.Controls.Add(this.CBox_DataBits);
this.panel8.Controls.Add(this.label8);
this.panel8.Location = new System.Drawing.Point(162, 19);
this.panel8.Name = "panel8";
this.panel8.Size = new System.Drawing.Size(79, 43);
this.panel8.TabIndex = 4;
//
// panel9
//
this.panel9.Controls.Add(this.comboBox1);
this.panel9.Controls.Add(this.label9);
this.panel9.Location = new System.Drawing.Point(82, 0);
this.panel9.Name = "panel9";
this.panel9.Size = new System.Drawing.Size(79, 43);
this.panel9.TabIndex = 5;
//
// comboBox1
//
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(6, 17);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(70, 21);
this.comboBox1.TabIndex = 2;
this.comboBox1.Text = "8";
//
// label9
//
this.label9.AutoSize = true;
this.label9.Location = new System.Drawing.Point(3, 0);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(73, 13);
this.label9.TabIndex = 0;
this.label9.Text = "Биты данных";
//
// CBox_DataBits
//
this.CBox_DataBits.FormattingEnabled = true;
this.CBox_DataBits.Location = new System.Drawing.Point(6, 17);
this.CBox_DataBits.Name = "CBox_DataBits";
this.CBox_DataBits.Size = new System.Drawing.Size(70, 21);
this.CBox_DataBits.TabIndex = 2;
this.CBox_DataBits.Text = "8";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Location = new System.Drawing.Point(3, 0);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(73, 13);
this.label8.TabIndex = 0;
this.label8.Text = "Биты данных";
//
// panel7
//
this.panel7.Controls.Add(this.CBox_BaudRate);
this.panel7.Controls.Add(this.label7);
this.panel7.Location = new System.Drawing.Point(81, 19);
this.panel7.Name = "panel7";
this.panel7.Size = new System.Drawing.Size(75, 43);
this.panel7.TabIndex = 3;
//
// CBox_BaudRate
//
this.CBox_BaudRate.FormattingEnabled = true;
this.CBox_BaudRate.Location = new System.Drawing.Point(6, 17);
this.CBox_BaudRate.Name = "CBox_BaudRate";
this.CBox_BaudRate.Size = new System.Drawing.Size(65, 21);
this.CBox_BaudRate.TabIndex = 2;
this.CBox_BaudRate.Text = "9600";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Location = new System.Drawing.Point(3, 0);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(34, 13);
this.label7.TabIndex = 0;
this.label7.Text = "Боды";
//
// panel2
//
this.panel2.Controls.Add(this.UpDown_ModbusID);
this.panel2.Controls.Add(this.label2);
this.panel2.Location = new System.Drawing.Point(417, 19);
this.panel2.Name = "panel2";
this.panel2.Size = new System.Drawing.Size(75, 43);
this.panel2.TabIndex = 2;
//
// UpDown_ModbusID
//
this.UpDown_ModbusID.Location = new System.Drawing.Point(6, 17);
this.UpDown_ModbusID.Location = new System.Drawing.Point(334, 26);
this.UpDown_ModbusID.Name = "UpDown_ModbusID";
this.UpDown_ModbusID.Size = new System.Drawing.Size(66, 20);
this.UpDown_ModbusID.TabIndex = 1;
@@ -473,25 +61,16 @@
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(3, 0);
this.label2.Location = new System.Drawing.Point(331, 9);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(59, 13);
this.label2.TabIndex = 0;
this.label2.Text = "Modbus ID";
//
// panel1
//
this.panel1.Controls.Add(this.CBox_Ports);
this.panel1.Controls.Add(this.label1);
this.panel1.Location = new System.Drawing.Point(0, 19);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(75, 43);
this.panel1.TabIndex = 0;
//
// CBox_Ports
//
this.CBox_Ports.FormattingEnabled = true;
this.CBox_Ports.Location = new System.Drawing.Point(6, 17);
this.CBox_Ports.Location = new System.Drawing.Point(139, 24);
this.CBox_Ports.Name = "CBox_Ports";
this.CBox_Ports.Size = new System.Drawing.Size(65, 21);
this.CBox_Ports.TabIndex = 1;
@@ -500,21 +79,64 @@
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(3, 0);
this.label1.Location = new System.Drawing.Point(136, 7);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(32, 13);
this.label1.TabIndex = 0;
this.label1.Text = "Порт";
//
// button1
//
this.button1.Location = new System.Drawing.Point(414, 24);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(92, 23);
this.button1.TabIndex = 2;
this.button1.Text = "Подключиться";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.ButtonConnect_Click);
//
// cBoxDevice
//
this.cBoxDevice.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cBoxDevice.Location = new System.Drawing.Point(12, 24);
this.cBoxDevice.Name = "cBoxDevice";
this.cBoxDevice.Size = new System.Drawing.Size(121, 21);
this.cBoxDevice.TabIndex = 3;
this.cBoxDevice.SelectedIndexChanged += new System.EventHandler(this.cBoxDevice_SelectedIndexChanged);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(9, 8);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(67, 13);
this.label3.TabIndex = 4;
this.label3.Text = "Устройство";
//
// checkboxID
//
this.checkboxID.AutoSize = true;
this.checkboxID.Location = new System.Drawing.Point(313, 29);
this.checkboxID.Name = "checkboxID";
this.checkboxID.Size = new System.Drawing.Size(15, 14);
this.checkboxID.TabIndex = 5;
this.checkboxID.UseVisualStyleBackColor = true;
this.checkboxID.CheckedChanged += new System.EventHandler(this.checkboxID_CheckedChanged);
//
// App
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(518, 404);
this.Controls.Add(this.GBox_Serial);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.groupBox2);
this.ClientSize = new System.Drawing.Size(518, 226);
this.Controls.Add(this.checkboxID);
this.Controls.Add(this.label3);
this.Controls.Add(this.cBoxDevice);
this.Controls.Add(this.button1);
this.Controls.Add(this.CBox_Ports);
this.Controls.Add(this.label1);
this.Controls.Add(this.UpDown_ModbusID);
this.Controls.Add(this.TextBox_Log);
this.Controls.Add(this.label2);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
@@ -523,84 +145,22 @@
this.Text = "Gidrolock Modbus Scanner";
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.App_FormClosed);
this.Load += new System.EventHandler(this.Form1_Load);
this.groupBox2.ResumeLayout(false);
this.panel6.ResumeLayout(false);
this.panel6.PerformLayout();
this.panel5.ResumeLayout(false);
this.panel5.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.UpDown_RegLength)).EndInit();
this.panel3.ResumeLayout(false);
this.panel3.PerformLayout();
this.panel4.ResumeLayout(false);
this.panel4.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.GBox_Serial.ResumeLayout(false);
this.panel11.ResumeLayout(false);
this.panel11.PerformLayout();
this.panel10.ResumeLayout(false);
this.panel10.PerformLayout();
this.panel8.ResumeLayout(false);
this.panel8.PerformLayout();
this.panel9.ResumeLayout(false);
this.panel9.PerformLayout();
this.panel7.ResumeLayout(false);
this.panel7.PerformLayout();
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.UpDown_ModbusID)).EndInit();
this.panel1.ResumeLayout(false);
this.panel1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button Button_Connect;
private System.Windows.Forms.TextBox TextBox_Log;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Panel panel5;
private System.Windows.Forms.NumericUpDown UpDown_RegLength;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Button Button_SendCommand;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.ComboBox CBox_Function;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Panel panel6;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label Label_ConfigTip;
private System.Windows.Forms.Button Button_LoadConfig;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label Label_ConfPath;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.GroupBox GBox_Serial;
private System.Windows.Forms.Panel panel11;
private System.Windows.Forms.ComboBox CBox_Parity;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Panel panel10;
private System.Windows.Forms.ComboBox CBox_StopBits;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Panel panel8;
private System.Windows.Forms.Panel panel9;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.ComboBox CBox_DataBits;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Panel panel7;
private System.Windows.Forms.ComboBox CBox_BaudRate;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.NumericUpDown UpDown_ModbusID;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.ComboBox CBox_Ports;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox TBox_RegValue;
private System.Windows.Forms.TextBox TBox_RegAddress;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.CheckBox checkboxID;
private System.Windows.Forms.ComboBox cBoxDevice;
}
}

700
Main.cs
View File

@@ -2,30 +2,16 @@
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.IO;
using Newtonsoft.Json;
using System.Threading;
namespace Gidrolock_Modbus_Scanner
{
public partial class App : Form
{
public static int[] BaudRate = new int[]
{
110, 300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, 76800, 115200, 230300, 460800, 921600
};
public static int[] DataBits = new int[] { 7, 8 };
Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
byte[] message = new byte[255];
public bool isAwaitingResponse = false;
public short[] res = new short[12];
SerialPort port = Modbus.port;
@@ -34,16 +20,14 @@ namespace Gidrolock_Modbus_Scanner
public SelectedPath selectedPath = SelectedPath.Folder;
public static Device device; // Deserialized .json object
string path = String.Empty; // Path to selected file/folder
string defaultPath = Application.StartupPath + "\\Configs"; // Default folder path
OpenFileDialog ofd = new OpenFileDialog();
FolderBrowserDialog fbd = new FolderBrowserDialog();
Dictionary<CheckEntry, List<Device>> juju = new Dictionary<CheckEntry, List<Device>>(); // dictionary for device identification
string[] configs;
public byte[] latestMessage;
public Dictionary<string, string> models = new Dictionary<string, string>();
DateTime dateTime;
#region Initialization
public App()
@@ -51,78 +35,26 @@ namespace Gidrolock_Modbus_Scanner
InitializeComponent();
Modbus.Init();
Modbus.ResponseReceived += OnResponseReceived;
ofd.InitialDirectory = Application.StartupPath;
ofd.Filter = "JSON files (*.json)|*.json";
ofd.FilterIndex = 2;
ofd.RestoreDirectory = true;
this.UpDown_ModbusID.Value = 30;
this.UpDown_ModbusID.Value = 0;
TextBox_Log.Text = "Приложение готово к работе.";
CBox_Function.Items.Add("01 Read Coil");
CBox_Function.Items.Add("02 Read Discrete Input");
CBox_Function.Items.Add("03 Read Holding Register");
CBox_Function.Items.Add("04 Read Input Register");
CBox_Function.Items.Add("05 Write Single Coil");
CBox_Function.Items.Add("06 Write Single Register");
//CBox_Function.Items.Add("0F Write Multiple Coils");
//CBox_Function.Items.Add("10 Write Multiple Registers");
CBox_Function.SelectedItem = CBox_Function.Items[0];
cBoxDevice.Items.Add("Standard");
cBoxDevice.Items.Add("Premium Plus");
cBoxDevice.Items.Add("Inteli");
cBoxDevice.Items.Add("Premium");
cBoxDevice.SelectedIndex = 0;
CBox_BaudRate.Items.Add("110");
CBox_BaudRate.Items.Add("300");
CBox_BaudRate.Items.Add("1200");
CBox_BaudRate.Items.Add("2400");
CBox_BaudRate.Items.Add("4800");
CBox_BaudRate.Items.Add("9600");
CBox_BaudRate.Items.Add("14400");
CBox_BaudRate.Items.Add("19200");
CBox_BaudRate.Items.Add("28800");
CBox_BaudRate.Items.Add("38400");
CBox_BaudRate.Items.Add("57600");
CBox_BaudRate.Items.Add("76800");
CBox_BaudRate.Items.Add("115200");
CBox_BaudRate.Items.Add("230300");
CBox_BaudRate.Items.Add("460800");
CBox_BaudRate.Items.Add("921600");
CBox_BaudRate.SelectedIndex = 5;
checkboxID.Checked = false;
UpDown_ModbusID.Enabled = false;
UpDown_ModbusID.Value = 30;
UpDown_ModbusID.Minimum = 1;
UpDown_ModbusID.Maximum = 247;
CBox_DataBits.Items.Add("7");
CBox_DataBits.Items.Add("8");
CBox_DataBits.SelectedIndex = 1;
CBox_StopBits.Items.Add("Нет");
CBox_StopBits.Items.Add("1");
CBox_StopBits.Items.Add("1.5");
CBox_StopBits.Items.Add("2");
CBox_StopBits.SelectedIndex = 1;
CBox_Parity.Items.Add("Нет");
CBox_Parity.Items.Add("Четн.");
CBox_Parity.Items.Add("Нечетн.");
CBox_Parity.SelectedIndex = 0;
UpDown_RegLength.Value = 1;
/* TCP Setup */
/*
Radio_SerialPort.Checked = true;
GBox_Ethernet.Enabled = false;
TBox_IP.Text = "192.168.3.7";
TBox_Port.Text = "8887";
TBox_Timeout.Text = "3";
*/
if (Directory.GetDirectories(Application.StartupPath).Contains(Application.StartupPath + "\\Configs") == false)
{
Task.Delay(1500).ContinueWith(t =>
{
MessageBox.Show("Приложение не нашло стандартную папку для конфигураций. Была создана папка 'Configs' в папке с приложением.");
Directory.CreateDirectory(Application.StartupPath + "\\Configs");
Console.WriteLine("New initial directory for OpenFile: " + ofd.InitialDirectory);
});
}
ofd.InitialDirectory = Application.StartupPath + "\\Configs";
path = defaultPath;
UpdatePathLabel();
models.Add("Standard", "STW485");
models.Add("Premuim Plus", "BUP485");
models.Add("Inteli", "INTELI");
models.Add("Premium", "BUP485");
/* - Version Check - */
System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
@@ -131,15 +63,9 @@ namespace Gidrolock_Modbus_Scanner
Console.WriteLine("Version: " + version);
}
void UpdatePathLabel()
{
Label_ConfPath.Text = path;
}
void App_FormClosed(object sender, FormClosedEventArgs e)
{
port.Close();
if (!port.IsOpen)
Application.Exit();
}
void Form1_Load(object sender, EventArgs e)
@@ -147,76 +73,11 @@ namespace Gidrolock_Modbus_Scanner
CBox_Ports.Items.AddRange(SerialPort.GetPortNames());
if (CBox_Ports.Items.Count > 0)
CBox_Ports.SelectedIndex = 0;
Init();
}
void Init()
{
if (UpDown_ModbusID.Value == 0)
Button_Connect.Text = "Найти адрес";
else Button_Connect.Text = "Подключиться";
}
#endregion
// Send a custom message
async Task ReadRegisterAsync(FunctionCode functionCode, ushort address, ushort length)
{
if (CBox_Ports.Text == "")
MessageBox.Show("Необходимо выбрать COM порт.", "Ошибка", MessageBoxButtons.OK);
if (UpDown_ModbusID.Value == 0)
MessageBox.Show("Глобальное вещание пока не поддерживается");
/* - Port Setup - */
if (port.IsOpen)
port.Close();
port.Handshake = Handshake.None;
port.PortName = CBox_Ports.Text;
port.BaudRate = BaudRate[CBox_BaudRate.SelectedIndex];
port.Parity = Parity.None;
port.DataBits = DataBits[CBox_DataBits.SelectedIndex];
port.StopBits = (StopBits)CBox_StopBits.SelectedIndex;
port.ReadTimeout = 3000;
port.WriteTimeout = 3000;
port.ReadBufferSize = 8192;
message = new byte[255];
port.Open();
/* - Reading from Registers - */
if (CBox_Function.SelectedIndex < 4)
{
try
{
Modbus.ReadRegAsync(port, (byte)UpDown_ModbusID.Value, functionCode, address, length);
isAwaitingResponse = true;
await Task.Delay(port.ReadTimeout).ContinueWith(_ =>
{
if (isAwaitingResponse)
{
MessageBox.Show("Истекло время ожидания ответа.", "Ошибка");
port.Close();
}
});
}
catch (Exception err)
{
port.Close();
MessageBox.Show(err.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private async void ButtonConnect_Click(object sender, EventArgs e)
{
progressBar1.Value = 0;
if (path == String.Empty)
{
MessageBox.Show("Выберите конфигурацию для подключения и опроса устройства.");
return;
}
if (CBox_Ports.SelectedItem.ToString() == "COM1")
{
DialogResult res = MessageBox.Show("Выбран серийный порт COM1, который обычно является портом PS/2 или RS-232, не подключенным к Modbus устройству. Продолжить?", "Внимание", MessageBoxButtons.OKCancel);
@@ -225,236 +86,94 @@ namespace Gidrolock_Modbus_Scanner
}
if (UpDown_ModbusID.Value == 0)
{
DialogResult res = MessageBox.Show("Указан Modbus ID 0 — глобальное вещание. Если в линии находится больше одного ведомого устройства, возникнут проблемы с коллизией. Продолжить?", "Внимание", MessageBoxButtons.OKCancel);
DialogResult res = MessageBox.Show("Указан Modbus ID 0 — глобальное вещание. Устройства не смогут отвечать на сообщения. Продолжить?", "Внимание", MessageBoxButtons.OKCancel);
if (res == DialogResult.Cancel)
return;
}
/* - Port Setup - */
if (port.IsOpen)
port.Close();
port.Handshake = Handshake.None;
port.PortName = CBox_Ports.Text;
port.BaudRate = BaudRate[CBox_BaudRate.SelectedIndex];
port.Parity = Parity.None;
port.DataBits = DataBits[CBox_DataBits.SelectedIndex];
port.StopBits = (StopBits)CBox_StopBits.SelectedIndex;
port.ReadTimeout = 3000;
port.WriteTimeout = 3000;
port.ReadBufferSize = 8192;
message = new byte[255];
port.Open();
/* - Checking - */
if (selectedPath == SelectedPath.File)
try
{
var fileContent = string.Empty;
var filePath = string.Empty;
//Read the contents of the file into a stream
var fileStream = ofd.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
fileContent = reader.ReadToEnd();
}
progressBar1.Value = 100;
/* - Port Setup - */
if (port.IsOpen)
port.Close();
try
{
device = JsonConvert.DeserializeObject<Device>(fileContent);
Label_ConfigTip.Text = device.name;
}
catch (Exception err) { MessageBox.Show(err.Message); }
port.Handshake = Handshake.None;
port.PortName = CBox_Ports.Text;
port.BaudRate = 9600;
port.Parity = Parity.None;
port.DataBits = 8;
port.StopBits = StopBits.One;
try
{
AddLog("Попытка подключиться к устройству " + device.name);
datasheet = new Datasheet((byte)UpDown_ModbusID.Value);
datasheet.Show();
}
catch (Exception err) { MessageBox.Show(err.Message); }
}
else
{
string[] _configs = Directory.GetFiles(path, "*.json");
if (configs != _configs)
{
// something changed in the config folder, or we haven't gone through configs,
// remake the dictionary
configs = _configs;
juju = new Dictionary<CheckEntry, List<Device>>();
port.ReadTimeout = 3000;
port.WriteTimeout = 3000;
port.ReadBufferSize = 8192;
var fileContent = string.Empty;
FileStream fileStream;
Device _device;
port.Open();
foreach (string path in configs)
{
fileStream = File.OpenRead(path);
using (StreamReader reader = new StreamReader(fileStream))
fileContent = reader.ReadToEnd();
// get device object from .json
_device = JsonConvert.DeserializeObject<Device>(fileContent);
// send read request for 6 registers starting from 200
// if we've got error or a timeout, show appropriate errors
// else parse response to unicode and go through every .json
// if matching model is found, instantiate device window
// compare device object to key of each dictionary;
// add to that dictionary if device's check entry registers match the key
bool matched = false;
foreach (CheckEntry ce in juju.Keys)
{
if (_device.checkEntry.address == ce.address && _device.checkEntry.length == ce.length && _device.checkEntry.dataType == ce.dataType)
{
juju[ce].Add(_device);
matched = true;
break;
}
}
if (!matched)
{
juju.Add(_device.checkEntry, new List<Device>());
juju[_device.checkEntry].Add(_device);
}
} // all configs are sorted out, we can poll for each checkEntry
}
// setup event listener
byte[] message = null;
byte[] data = null;
Modbus.ResponseReceived += (sndr, msg) =>
{
message = msg.Message;
data = msg.Data;
};
foreach (CheckEntry ce in juju.Keys)
// send message
AddLog("Проверка модели устройства.");
byte id = (byte)UpDown_ModbusID.Value;
Modbus.ReadRegAsync(id, FunctionCode.ReadInput, 200, 6);
await Task.Run(() =>
{
await ReadRegisterAsync((FunctionCode)ce.registerType, ce.address, ce.length); // send read request to device,
while (message is null) { continue; }
while (message is null) // wait for response to arrive
Thread.Sleep(10);
if (message[1] > 0x10) //exception code check
return;
// confirm the model
string response = ByteArrayToUnicode(data);
if (response != models[cBoxDevice.SelectedItem.ToString()])
{
// response doesn't match expected model
// check whether it matches anything else, offer to open that model if it does
string match = "";
foreach (string key in models.Keys)
{
if (models[key] == response)
match = models[key];
}
if (message[1] > 0x10) // checking for exception code
continue;
// if no matches found,
if (match == "")
{
// report unknown device
}
else
{
// offer to switch to that model instead
// instantiate panel
}
}
else
{
// get pure data
byte[] data = new byte[message[2]];
for (int i = 0; i < data.Length; i++)
data[i] = message[i + 3];
if (ce.dataType == "string")
{
List<byte> bytes = new List<byte>();
for (int i = 0; i < data.Length; i++)
{
if (data[i] != 0) // clean empty bytes from 16-bit registers
bytes.Add(data[i]);
}
string value = Encoding.UTF8.GetString(bytes.ToArray());
foreach (Device dev in juju[ce])
{
if (dev.checkEntry.expectedValue == value)
{
Console.WriteLine("It's a match!");
device = dev;
break;
}
}
}
else if (ce.dataType == "bool")
{
// why would you even do that lmao
}
else if (ce.dataType == "uint16" || ce.dataType == "uint32")
{
byte[] _data = data;
Array.Reverse(_data);
if (ce.dataType == "uint16")
{
ushort value = BitConverter.ToUInt16(_data, 0);
foreach (Device dev in juju[ce])
{
short expValue;
if (Int16.TryParse(dev.checkEntry.expectedValue, out expValue) && expValue == value)
{
device = dev;
break;
}
}
}
else
{
int value = BitConverter.ToInt32(_data, 0);
foreach (Device dev in juju[ce])
{
int expValue;
if (Int32.TryParse(dev.checkEntry.expectedValue, out expValue) && expValue == value)
{
device = dev;
break;
}
}
}
}
// model is correct, instantiate config panel
}
if (!(device is null)) // found the correct device, abort loop
break;
message = null; // clear the array for the next item in case we haven't found the correct value
}
if (device is /* still */ null)
{
// none of the configs match the device responses
MessageBox.Show("Ни один из файлов конфигурации не подходит для устройства.");
return;
}
else
{
try
{
AddLog("Попытка подключиться к устройству " + device.name);
datasheet = new Datasheet((byte)UpDown_ModbusID.Value);
datasheet.Show();
}
catch (Exception err) { MessageBox.Show(err.Message); }
}
progressBar1.Value = 100;
});
}
/*
if (Radio_SerialPort.Checked)
await ReadRegisterAsync(FunctionCode.InputRegister, 200, 6);
//else EthernetParse();
*/
}
/*
async void EthernetParse()
{
string ipText = TBox_IP.Text;
string portText = TBox_Port.Text;
Regex ip = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
Regex port = new Regex(@"\d");
if (!ip.IsMatch(ipText))
MessageBox.Show("Неправильный формат IP-адреса.");
else if (!port.IsMatch(portText))
MessageBox.Show("Неправильный формат TCP-порта.");
else
catch (Exception ex)
{
int portParsed = Int32.Parse(portText);
await socket.ConnectAsync(ipText, portParsed);
byte[] data = new byte[8];
Modbus.BuildReadMessage(0x1E, 0x03, 128, 1, ref data);
AddLog("Sending to " + ipText + ":" + portText + ":" + Modbus.ByteArrayToString(data));
// set up an event listener to receive the response
await SocketDataTransfer(data);
MessageBox.Show(ex.Message);
}
}
*/
void CBox_Ports_Click(object sender, EventArgs e)
{
CBox_Ports.Items.Clear();
@@ -465,7 +184,7 @@ namespace Gidrolock_Modbus_Scanner
{
isAwaitingResponse = false;
AddLog("Получен ответ: " + Modbus.ByteArrayToString(e.Message));
switch(e.Status)
switch (e.Status)
{
case (ModbusStatus.ReadSuccess):
string values = "";
@@ -485,7 +204,7 @@ namespace Gidrolock_Modbus_Scanner
}
AddLog("Dec: " + values);
AddLog("Unicode: " + ByteArrayToUnicode(e.Data));
}
}
break;
case (ModbusStatus.WriteSuccess):
AddLog("Write success;");
@@ -540,239 +259,11 @@ namespace Gidrolock_Modbus_Scanner
TextBox_Log.Invoke((MethodInvoker)delegate { TextBox_Log.AppendText(Environment.NewLine + "[" + dateTime.Hour.ToString().PadLeft(2, '0') + ":" + dateTime.Minute.ToString().PadLeft(2, '0') + ":" + dateTime.Second.ToString().PadLeft(2, '0') + "] " + message); });
}
private async void Button_SendCommand_Click(object sender, EventArgs e)
{
/* - Port Setup - */
if (port.IsOpen)
port.Close();
port.Handshake = Handshake.None;
port.PortName = CBox_Ports.Text;
port.BaudRate = BaudRate[CBox_BaudRate.SelectedIndex];
port.Parity = Parity.None;
port.DataBits = DataBits[CBox_DataBits.SelectedIndex];
port.StopBits = (StopBits)CBox_StopBits.SelectedIndex;
port.ReadTimeout = 3000;
port.WriteTimeout = 3000;
port.ReadBufferSize = 8192;
message = new byte[255];
port.Open();
int functionCode = CBox_Function.SelectedIndex + 1;
Console.WriteLine("Set fCode: " + functionCode);
short address;
ushort length = (ushort)UpDown_RegLength.Value;
if (Int16.TryParse(TBox_RegAddress.Text, out address))
{
if (functionCode <= 4)
{
byte[] _msg = new byte[8];
Modbus.BuildReadMessage((byte)UpDown_ModbusID.Value, (byte)functionCode, (ushort)address, (ushort)length, ref _msg);
string msg = Modbus.ByteArrayToString(_msg);
AddLog("Отправка сообщения: " + msg);
await ReadRegisterAsync((FunctionCode)functionCode, (ushort)address, length);
}
else
{
string valueLower = TBox_RegValue.Text.ToLower();
switch ((FunctionCode)functionCode)
{
case (FunctionCode.WriteCoil):
Console.WriteLine("Trying to force single coil");
if (valueLower == "true" || valueLower == "1")
Modbus.WriteSingleAsync(port, (FunctionCode)functionCode, (byte)UpDown_ModbusID.Value, (ushort)address, 0xFF_00);
else if (valueLower == "false" || valueLower == "0")
Modbus.WriteSingleAsync(port, (FunctionCode)functionCode, (byte)UpDown_ModbusID.Value, (ushort)address, 0x00_00);
else MessageBox.Show("Неподходящие значения для регистра типа Coil");
break;
case (FunctionCode.WriteRegister):
short value = 0x00_00;
bool canWrite = false;
if (IsDec(valueLower))
{
try { value = Convert.ToInt16(valueLower); canWrite = true; }
catch (Exception err) { MessageBox.Show(err.Message); }
}
else if (IsHex(valueLower))
{
Console.WriteLine("Got hex value");
for (int i = 0; i < valueLower.Length; i++)
{
if (valueLower[i] == 'x')
{
valueLower = valueLower.Remove(i, 1);
break;
}
}
try { value = Convert.ToInt16(valueLower, 16); canWrite = true; }
catch (Exception err) { MessageBox.Show(err.Message); }
}
else if (IsBin(valueLower))
{
Console.WriteLine("Got bin value");
for (int i = 0; i < valueLower.Length; i++)
{
if (valueLower[i] == 'b')
{
valueLower = valueLower.Remove(i, 1);
break;
}
}
try { value = Convert.ToInt16(valueLower, 2); canWrite = true; }
catch (Exception err) { MessageBox.Show(err.Message); }
}
else if (valueLower == "true" || valueLower == "1")
{
value = 0x00_01;
canWrite = true;
}
else if (valueLower == "false" || valueLower == "0")
{
canWrite = true;
}
else
{
MessageBox.Show("Неподходящие значения для регистра типа Input Register");
break;
}
if (canWrite)
Modbus.WriteSingleAsync(port, (FunctionCode)functionCode, (byte)UpDown_ModbusID.Value, (ushort)address,
(ushort)value);
break;
default:
MessageBox.Show("WIP");
break;
}
}
}
}
private void OnSelectedFunctionChanged(object sender, EventArgs e)
{
if (CBox_Function.SelectedIndex < 4)
TBox_RegValue.Enabled = false;
else TBox_RegValue.Enabled = true;
if (CBox_Function.SelectedIndex == 4 || CBox_Function.SelectedIndex == 5)
UpDown_RegLength.Enabled = false;
else UpDown_RegLength.Enabled = true;
}
/* TCP/RTU switch behaviour */
/*
private void Radio_SerialPort_CheckedChanged(object sender, EventArgs e)
{
if (Radio_SerialPort.Checked)
GBox_Serial.Enabled = true;
else GBox_Serial.Enabled = false;
}
private void Radio_Ethernet_CheckedChanged(object sender, EventArgs e)
{
if (Radio_Ethernet.Checked)
GBox_Ethernet.Enabled = true;
else GBox_Ethernet.Enabled = false;
}
*/
private async Task<bool> SocketDataTransfer(byte[] data)
{
await Task.Run(() => { socket.Send(data); });
byte[] res = new byte[64];
await Task.Run(() =>
{
while (true)
{
int bytesReceived = socket.Receive(res);
if (bytesReceived == 0)
break;
string resParsed = "";
Modbus.ParseResponse(res, ref resParsed);
Console.Out.WriteLine("Received data on TCP socket: " + resParsed);
AddLog("Response from TCP Server: " + resParsed);
}
});
return true;
}
private void LoadConfig(object sender, EventArgs e)
{
if (ofd.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
path = ofd.FileName;
Label_ConfPath.Text = ofd.FileName;
selectedPath = SelectedPath.File;
}
UpdatePathLabel();
}
private void LoadFolder(object sender, EventArgs e)
{
fbd.RootFolder = Environment.SpecialFolder.MyComputer;
if (fbd.ShowDialog() == DialogResult.OK)
{
path = fbd.SelectedPath;
Label_ConfPath.Text = fbd.SelectedPath;
selectedPath = SelectedPath.Folder;
}
UpdatePathLabel();
}
private void CBox_Ports_Click(object sender, MouseEventArgs e)
{
}
public static bool IsHex(string str)
{
str = str.ToLower();
for (int i = 0; i < str.Length; i++)
{
if (str[i] < '0' || str[i] > 'F')
{
if ((i == 0 || i == 1) && str[i] == 'x')
continue;
else return false;
}
}
return true;
}
public static bool IsDec(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
public static bool IsBin(string str)
{
str = str.ToLower();
for (int i = 0; i < str.Length;i++)
{
if (str[i] != '0' && str[i] != '1')
{
if ((i == 0 || i == 1) && str[i] == 'b')
continue;
else return false;
}
}
return true;
}
public static string ByteArrayToUnicode(byte[] input)
public static string ByteArrayToUnicode(byte[] input)
{
// stupid fucking WinForm textbox breaks from null symbols
// stupid fucking Encoding class does byte-by-byte conversion
List<char> result = new List<char>(input.Length/2);
List<char> result = new List<char>(input.Length / 2);
byte[] flip = input;
Array.Reverse(flip); // stupid fucking BitConverter is little-endian and spits out chinese nonsense otherwise
for (int i = 0; i < flip.Length; i += 2)
@@ -782,6 +273,33 @@ namespace Gidrolock_Modbus_Scanner
result.Reverse();
return new string(result.ToArray());
}
private void checkboxID_CheckedChanged(object sender, EventArgs e)
{
UpDown_ModbusID.Enabled = checkboxID.Checked ? true : false;
}
private void cBoxDevice_SelectedIndexChanged(object sender, EventArgs e)
{
switch (cBoxDevice.SelectedItem)
{
case "Standard":
UpDown_ModbusID.Value = 30;
break;
case "Premium Plus":
UpDown_ModbusID.Value = 30;
break;
case "Inteli":
UpDown_ModbusID.Value = 26;
break;
case "Premium":
UpDown_ModbusID.Value = 26;
break;
default:
Console.WriteLine("Invalid change");
break;
}
}
}
}

View File

@@ -37,7 +37,7 @@ namespace Gidrolock_Modbus_Scanner
GetCRC(message, ref CRC);
message[message.Length - 2] = CRC[0];
message[message.Length - 1] = CRC[1];
string msg = ByteArrayToString(message);
//string msg = ByteArrayToString(message);
//Console.WriteLine("Message: " + msg);
return message;
}
@@ -64,7 +64,7 @@ namespace Gidrolock_Modbus_Scanner
#endregion
#region Read Functions
public static bool ReadRegAsync(SerialPort port, byte slaveID, FunctionCode functionCode, ushort address, ushort length)
public static bool ReadRegAsync(byte slaveID, FunctionCode functionCode, ushort address, ushort length)
{
//Ensure port is open:
if (port.IsOpen)
@@ -78,13 +78,14 @@ namespace Gidrolock_Modbus_Scanner
//Build outgoing modbus message:
BuildReadMessage(slaveID, (byte)functionCode, address, length, ref message);
if (message.Length > 1)
{
//Send modbus message to Serial Port:
try
{
port.Write(message, 0, message.Length);
Console.WriteLine("Message sent");
return true;
}
catch (Exception err)
@@ -106,7 +107,7 @@ namespace Gidrolock_Modbus_Scanner
#endregion
#region Write Single Coil/Register
public static bool WriteSingleAsync(SerialPort port, FunctionCode functionCode, byte slaveID, ushort address, ushort value)
public static bool WriteSingleAsync(FunctionCode functionCode, byte slaveID, ushort address, ushort value)
{
//Ensure port is open:
if (!port.IsOpen)
@@ -244,7 +245,7 @@ namespace Gidrolock_Modbus_Scanner
byte[] message = new byte[port.BytesToRead];
//Console.WriteLine("Bytes to read:" + port.BytesToRead);
port.Read(message, 0, port.BytesToRead);
//Console.WriteLine("Incoming message: " + ByteArrayToString(message, false));
Console.WriteLine("Incoming message: " + ByteArrayToString(message, false));
if (message[1] <= 0x04) // read functions
{
//Console.WriteLine("It's a read message");