Files
gidrolock-configurator/Datasheet.cs

564 lines
21 KiB
C#
Raw Normal View History

2025-01-24 11:50:32 +03:00
using System;
2025-01-24 11:46:36 +03:00
using System.Collections;
2024-12-05 15:57:07 +03:00
using System.Collections.Generic;
using System.Drawing;
2025-02-28 18:00:17 +03:00
using System.IO;
using System.IO.Ports;
2024-12-05 15:57:07 +03:00
using System.Linq;
2025-02-28 18:00:17 +03:00
using System.Threading;
2024-12-05 15:57:07 +03:00
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Gidrolock_Modbus_Scanner
{
public partial class Datasheet : Form
{
2025-01-14 11:31:23 +03:00
byte modbusID;
Device device;
2025-01-24 11:46:36 +03:00
ModbusResponseEventArgs latestMessage;
2025-01-21 14:38:59 +03:00
2025-01-14 11:31:23 +03:00
SerialPort port = Modbus.port;
2024-12-16 11:35:20 +03:00
bool isPolling = false;
2024-12-09 16:24:02 +03:00
bool isAwaitingResponse = false;
2025-01-21 14:38:59 +03:00
bool isValveClosed = false;
bool alarmStatus = false;
bool cleaningStatus = false;
2024-12-09 16:24:02 +03:00
2025-01-24 11:46:36 +03:00
List<WiredSensor> wiredSensors = new List<WiredSensor>();
List<WirelessSensor> wirelessSensors;
2025-02-28 18:00:17 +03:00
public static string firmwarePath;
2025-01-24 11:46:36 +03:00
2025-02-28 18:00:17 +03:00
Thread fileThread = new Thread((ThreadStart)delegate
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.InitialDirectory = Application.StartupPath;
ofd.RestoreDirectory = true;
if (ofd.ShowDialog() == DialogResult.OK)
{
firmwarePath = ofd.FileName;
//firmwarePathLabel.Text = ofd.FileName;
}
});
public Datasheet(byte modbusID, Device device) : base()
2024-12-05 15:57:07 +03:00
{
2025-01-24 11:46:36 +03:00
InitializeComponent();
2025-01-14 11:31:23 +03:00
nudModbusID.Minimum = 1;
nudModbusID.Maximum = 246;
2025-01-24 11:46:36 +03:00
nudModbusID.Value = modbusID;
2025-01-14 11:31:23 +03:00
this.modbusID = modbusID;
this.device = device;
2025-01-21 14:38:59 +03:00
2025-01-24 17:54:04 +03:00
cBoxSpeed.Items.Add("1200");
cBoxSpeed.Items.Add("2400");
cBoxSpeed.Items.Add("4800");
cBoxSpeed.Items.Add("9600");
cBoxSpeed.Items.Add("14400");
cBoxSpeed.Items.Add("19200");
cBoxSpeed.Items.Add("38400");
cBoxSpeed.Items.Add("57600");
cBoxSpeed.Items.Add("115200");
cBoxSpeed.Text = port.BaudRate.ToString();
2025-01-24 11:46:36 +03:00
labelModel.Text = device.name;
labelFirmware.Text = "v???";
2025-01-21 14:38:59 +03:00
if (!device.hasCleaningMode)
{
labelCleaning.Text = "Недоступна.";
buttonCleaning.Enabled = false;
}
2025-01-24 11:46:36 +03:00
if (!device.hasBattery)
labelBattery.Text = "Нет";
else labelBattery.Text = "???%";
Modbus.ResponseReceived += (sndr, msg) => { isAwaitingResponse = false; latestMessage = msg; };
2025-01-21 14:38:59 +03:00
2025-01-24 11:46:36 +03:00
for (int i = 0; i < device.wiredSensors; i++)
{
WiredSensor ws = new WiredSensor(i) { Width = 495, Height = 24 };
sensorPanel.Controls.Add(ws);
ws.Visible = true;
2025-02-28 18:00:17 +03:00
2025-01-24 11:46:36 +03:00
}
if (device.hasScenarioSensor)
{
ScenarioSensor scenSen = new ScenarioSensor() { Width = 495, Height = 24 };
sensorPanel.Controls.Add(scenSen);
scenSen.Visible = true;
}
2025-01-24 17:54:04 +03:00
if (device.wiredSensors < device.sensorAlarm.length)
2025-01-21 14:38:59 +03:00
{
2025-01-24 11:46:36 +03:00
wirelessSensors = new List<WirelessSensor>();
2025-01-24 17:54:04 +03:00
int wsrIndex = device.sensorAlarm.length - device.wiredSensors - (device.hasScenarioSensor ? 1 : 0);
2025-01-24 11:46:36 +03:00
for (int i = 0; i < wsrIndex; i++)
{
WirelessSensor wsr = new WirelessSensor(i) { Width = 495, Height = 24 };
sensorPanel.Controls.Add(wsr);
wsr.Visible = true;
}
}
for (int i = 0; i < sensorPanel.Controls.Count; i++)
sensorPanel.Controls[i].BackColor = i % 2 == 0 ? Color.White : Color.LightGray;
2025-01-21 14:38:59 +03:00
2025-01-24 11:46:36 +03:00
2025-02-28 18:00:17 +03:00
sensorPanel.Update();
2025-01-21 14:38:59 +03:00
}
private async void buttonPoll_Click(object sender, EventArgs e)
{
// hardcoded for now, probably easier to keep it like this in the future
2025-01-24 11:46:36 +03:00
try
2025-01-21 14:38:59 +03:00
{
bool res = await PollEntry(device.firmware);
Console.WriteLine("Polling for alarm status, poll success: " + res);
if (res)
{
labelFirmware.Text = App.ByteArrayToUnicode(latestMessage.Data);
}
if (device.hasBattery)
{
res = await PollEntry(device.batteryCharge);
if (res)
{
labelBattery.Text = latestMessage.Data.Last().ToString();
}
}
2025-02-28 18:00:17 +03:00
res = await PollEntry(device.valveStatus);
2025-01-24 11:46:36 +03:00
Console.WriteLine("Polling for valve status, poll success: " + res);
if (res)
{
if (latestMessage.Data.Last() > 0)
{
isValveClosed = true;
labelValve.Text = "Закрыт";
buttonValve.Text = "Открыть";
}
else
{
isValveClosed = false;
labelValve.Text = "Открыт";
buttonValve.Text = "Закрыть";
}
}
2025-01-24 11:46:36 +03:00
res = await PollEntry(device.alarmStatus);
Console.WriteLine("Polling for alarm status, poll success: " + res);
if (res)
{
Console.WriteLine("Alarm data: " + Modbus.ByteArrayToString(latestMessage.Data));
Console.WriteLine("Alarm data.last: " + latestMessage.Data.Last().ToString());
2025-01-24 11:46:36 +03:00
if (latestMessage.Data.Last() > 0)
{
alarmStatus = true;
buttonAlarm.Text = "Выключить";
labelAlarm.Text = "Протечка!";
}
else
{
alarmStatus = false;
buttonAlarm.Text = "Авария";
labelAlarm.Text = "нет";
}
}
if (device.hasCleaningMode)
{
res = await PollEntry(device.cleaningMode);
if (res)
{
if (latestMessage.Data.Last() > 0)
{
cleaningStatus = true;
buttonCleaning.Text = "Выключить";
labelCleaning.Text = "вкл";
2025-01-24 11:46:36 +03:00
}
else
{
cleaningStatus = false;
buttonCleaning.Text = "Включить";
labelCleaning.Text = "выкл";
2025-01-24 11:46:36 +03:00
}
}
}
2025-01-24 17:54:04 +03:00
res = await PollEntry(device.sensorAlarm);
2025-01-24 11:46:36 +03:00
if (res)
{
BitArray bArray = new BitArray(latestMessage.Data);
bool[] bools = new bool[bArray.Length];
bArray.CopyTo(bools, 0);
2025-01-24 17:54:04 +03:00
for (int i = 0; i < sensorPanel.Controls.Count; i++)
2025-01-24 11:46:36 +03:00
{
Sensor snsr = sensorPanel.Controls[i] as Sensor;
snsr.labelLeak.Text = bools[i] ? "Протечка!" : "нет";
}
}
2025-01-24 17:54:04 +03:00
res = await PollEntry(device.radioStatus);
if (res)
{
List<byte> values = new List<byte>(latestMessage.Data.Length / 2);
for (int i = 1; i < latestMessage.Data.Length; i += 2)
values.Add(latestMessage.Data[i]);
int add = device.wiredSensors + (device.hasScenarioSensor ? 1 : 0);
2025-01-28 09:35:16 +03:00
for (int i = 0; i < sensorPanel.Controls.Count - add; i++)
2025-01-24 17:54:04 +03:00
{
WirelessSensor snsr = sensorPanel.Controls[i + add] as WirelessSensor;
string txt = "нет";
switch (values[i])
{
case 1:
txt = "норма";
break;
case 2:
txt = "протечка";
break;
case 3:
txt = "разряжен";
break;
case 4:
txt = "потеря";
break;
}
snsr.labelStatus.Text = txt;
}
}
2025-01-21 14:38:59 +03:00
}
2025-01-24 11:46:36 +03:00
catch (Exception err) { MessageBox.Show(err.Message); }
}
2024-12-05 17:52:25 +03:00
2025-01-21 14:38:59 +03:00
async Task<bool> PollEntry(Entry entry)
{
2025-01-24 11:46:36 +03:00
bool res = false;
Modbus.ReadRegAsync(modbusID, (FunctionCode)entry.registerType, entry.address, entry.length);
2025-01-21 14:38:59 +03:00
isAwaitingResponse = true;
2025-02-14 10:37:32 +03:00
Task.Delay(2000).ContinueWith(_ =>
2025-01-24 11:46:36 +03:00
{
if (isAwaitingResponse)
{
MessageBox.Show("Превышено время ожидания ответа от устройства.");
isAwaitingResponse = false;
}
});
while (isAwaitingResponse) { continue; }
if (latestMessage != null && latestMessage.Status != ModbusStatus.Error)
res = true;
Console.WriteLine("Poll attempt finished");
return res;
}
2025-01-21 14:38:59 +03:00
2025-01-24 11:46:36 +03:00
private async void buttonSetID_Click(object sender, EventArgs e)
{
byte newID = (byte)nudModbusID.Value; // should prevent assigning wrong ID if UpDown is fiddled with in the middle of request
Modbus.WriteSingleAsync(FunctionCode.WriteRegister, modbusID, 128, newID);
await Task.Delay(2000).ContinueWith(_ =>
2025-01-21 14:38:59 +03:00
{
if (isAwaitingResponse)
{
2025-01-24 11:46:36 +03:00
MessageBox.Show("Превышено время ожидания ответа от устройства.");
2025-01-21 14:38:59 +03:00
isAwaitingResponse = false;
}
return false;
});
2025-01-24 11:46:36 +03:00
while (isAwaitingResponse) { continue; }
2025-01-21 14:38:59 +03:00
2025-01-24 11:46:36 +03:00
if (latestMessage != null && latestMessage.Status != ModbusStatus.Error)
modbusID = newID;
2025-01-21 14:38:59 +03:00
}
2025-01-24 11:46:36 +03:00
private async void buttonValve_Click(object sender, EventArgs e)
{
2025-02-28 18:00:17 +03:00
ushort value = isValveClosed ? (ushort)0 : (ushort)0xFF00;
2025-01-24 11:46:36 +03:00
Modbus.WriteSingleAsync(FunctionCode.WriteCoil, modbusID, device.valveStatus.address, value);
2025-01-21 14:38:59 +03:00
Task.Delay(2000).ContinueWith(_ =>
2024-12-09 16:24:02 +03:00
{
2025-01-24 11:46:36 +03:00
if (isAwaitingResponse)
{
MessageBox.Show("Превышено время ожидания ответа от устройства.");
isAwaitingResponse = false;
}
return false;
2024-12-09 16:24:02 +03:00
});
2025-01-24 11:46:36 +03:00
while (isAwaitingResponse) { continue; }
if (latestMessage != null && latestMessage.Status != ModbusStatus.Error)
{
isValveClosed = !isValveClosed;
labelValve.Text = isValveClosed ? "Закрыт" : "Открыт";
buttonValve.Text = isValveClosed ? "Открыть" : "Закрыть";
}
}
2025-01-17 10:40:18 +03:00
2025-01-24 11:46:36 +03:00
private async void buttonAlarm_Click(object sender, EventArgs e)
2025-01-17 10:40:18 +03:00
{
2025-01-24 11:46:36 +03:00
ushort value = alarmStatus ? (ushort)0 : (ushort)0xFF00;
Modbus.WriteSingleAsync(FunctionCode.WriteCoil, modbusID, device.alarmStatus.address, value);
Task.Delay(2000).ContinueWith(_ =>
2025-01-24 11:46:36 +03:00
{
if (isAwaitingResponse)
{
MessageBox.Show("Превышено время ожидания ответа от устройства.");
isAwaitingResponse = false;
}
return false;
});
while (isAwaitingResponse) { continue; }
if (latestMessage != null && latestMessage.Status != ModbusStatus.Error)
{
alarmStatus = !alarmStatus;
labelAlarm.Text = alarmStatus ? "Протечка!" : "Нет";
buttonAlarm.Text = alarmStatus ? "Выключить" : "Авария";
}
}
private async void buttonCleaning_Click(object sender, EventArgs e)
{
ushort value = cleaningStatus ? (ushort)0 : (ushort)0xFF00;
Modbus.WriteSingleAsync(FunctionCode.WriteCoil, modbusID, device.cleaningMode.address, value);
Task.Delay(2000).ContinueWith(_ =>
2025-01-24 11:46:36 +03:00
{
if (isAwaitingResponse)
{
MessageBox.Show("Превышено время ожидания ответа от устройства.");
isAwaitingResponse = false;
}
return false;
});
while (isAwaitingResponse) { continue; }
if (latestMessage != null && latestMessage.Status != ModbusStatus.Error)
{
cleaningStatus = !cleaningStatus;
labelCleaning.Text = cleaningStatus ? "вкл" : "выкл";
buttonCleaning.Text = cleaningStatus ? "Выключить" : "Включить";
}
}
private async void buttonSetSpeed_Click(object sender, EventArgs e)
{
try
{
string str = cBoxSpeed.Items[cBoxSpeed.SelectedIndex].ToString();
str = str.Substring(0, str.Length - 2); //clip off two zeroes at the end
ushort newSpeed = (ushort)Int16.Parse(str);
//Console.WriteLine("Baudrate: " + newSpeed);
// send speed value to device
// await for response
Modbus.WriteSingleAsync(FunctionCode.WriteRegister, modbusID, device.baudRate.address, newSpeed);
Task.Delay(2000).ContinueWith(_ =>
{
if (isAwaitingResponse)
{
MessageBox.Show("Превышено время ожидания ответа от устройства.");
isAwaitingResponse = false;
}
return false;
});
while (isAwaitingResponse) { continue; }
if (latestMessage.Status != ModbusStatus.Error)
{
port.Close();
port.BaudRate = newSpeed;
port.Open();
}
}
catch (Exception ex) { MessageBox.Show(ex.Message); }
}
2025-02-28 18:00:17 +03:00
private void BrowseFirmware_Click(object sender, EventArgs e)
{
try
{
fileThread.TrySetApartmentState(ApartmentState.STA);
fileThread.Start();
while (!fileThread.IsAlive) { Thread.Sleep(1); }
Thread.Sleep(1);
fileThread.Join();
}
catch (Exception err) { MessageBox.Show(err.Message); }
}
private void WriteFirmware_Click(object sender, EventArgs e)
{
FileStream fileStream = File.OpenRead(firmwarePath);
long bytesLeft = fileStream.Length;
int offset = 0;
int count;
byte[] buffer;
byte[] bdma;
List<byte> message;
int dma = 0;
Task.Run(() =>
{
while (bytesLeft > 0)
{
count = bytesLeft > 64 ? 64 : (int)bytesLeft;
buffer = new byte[count];
fileStream.Read(buffer, offset, count);
bdma = new byte[2];
bdma[0] = (byte)((dma & 0xFF_00) >> 16);
bdma[1] = (byte)(dma & 0x00_FF);
message = new List<byte>();
message.Add(modbusID); // device ID
message.Add(0x10); // function code
message.Add(0xFF); // register address
message.Add(0xFF); // register address
message.Add(0x00); // regCnt (?)
message.Add(0x21); // regCnt (?)
message.Add(0x42); // data bytecount
message.Add(bdma[0]);
message.Add(bdma[1]);
for (int i = 0; i < buffer.Length; i++)
{
message.Add(buffer[i]);
}
byte[] CRC = new byte[2];
Modbus.GetCRC(message.ToArray(), ref CRC);
message.Add(CRC[0]);
message.Add(CRC[1]);
Console.WriteLine("Outgoing firmware message: " + Modbus.ByteArrayToString(message.ToArray()));
isAwaitingResponse = true;
port.Write(message.ToArray(), 0, message.Count);
Task.Delay(2000).ContinueWith(_ =>
{
if (isAwaitingResponse)
{
MessageBox.Show("Превышено время ожидания ответа от устройства.");
isAwaitingResponse = false;
return;
}
});
while (isAwaitingResponse) { continue; }
bytesLeft -= count;
offset += count;
dma += 32;
}
});
}
2025-01-24 11:46:36 +03:00
}
public class Sensor : FlowLayoutPanel
{
public Label labelName = new Label() { Width = 60, Height = 24 };
public Label labelLeakFluff = new Label() { Width = 60, Height = 24 };
public Label labelLeak = new Label() { Width = 50, Height = 24 };
}
public class WiredSensor : Sensor
{
public Label labelBreakFluff = new Label() { Width = 45, Height = 24 };
public Label labelBreak = new Label() { Width = 55, Height = 24 }; // обрыв линии для WSP+
2025-01-24 17:54:04 +03:00
//public Label labelWSPPlusFluff = new Label() { Width = 45, Height = 24 };
//public CheckBox wspPlusCheckbox = new CheckBox() { Width = 20, Height = 14 };
2025-01-24 11:46:36 +03:00
public WiredSensor(int count)
{
this.Margin = Padding.Empty;
this.Padding = new Padding(0, 5, 0, 0);
this.WrapContents = false;
this.BackColor = Color.White;
this.Height = 15;
this.FlowDirection = FlowDirection.LeftToRight;
this.Controls.Add(labelName);
this.Controls.Add(labelBreakFluff);
this.Controls.Add(labelBreak);
this.Controls.Add(labelLeakFluff);
this.Controls.Add(labelLeak);
2025-01-24 17:54:04 +03:00
//this.Controls.Add(labelWSPPlusFluff);
//this.Controls.Add(wspPlusCheckbox);
2025-01-24 11:46:36 +03:00
labelName.Text = "WSP " + (count + 1);
labelLeakFluff.Text = "Протечка:";
labelLeak.Text = "неизвестно";
labelBreakFluff.Text = "Обрыв:";
labelBreak.Text = "неизвестно";
2025-01-24 17:54:04 +03:00
//labelWSPPlusFluff.Text = "WSP+:";
//wspPlusCheckbox.Margin = Padding.Empty;
2025-01-17 10:40:18 +03:00
}
2025-01-24 11:46:36 +03:00
}
public class WirelessSensor : Sensor
{
2025-01-24 17:54:04 +03:00
public Label labelStatusFluff = new Label() { Width = 45, Height = 24 };
public Label labelStatus = new Label() { Width = 55, Height = 24 };
2025-01-17 10:40:18 +03:00
2025-01-24 11:46:36 +03:00
public WirelessSensor(int count)
2025-01-17 10:40:18 +03:00
{
2025-01-24 11:46:36 +03:00
this.Margin = Padding.Empty;
this.Padding = new Padding(0, 5, 0, 0);
this.BackColor = Color.White;
this.FlowDirection = FlowDirection.LeftToRight;
this.WrapContents = false;
this.Controls.Add(labelName);
2025-01-24 17:54:04 +03:00
this.Controls.Add(labelStatusFluff);
this.Controls.Add(labelStatus);
2025-01-24 11:46:36 +03:00
this.Controls.Add(labelLeakFluff);
this.Controls.Add(labelLeak);
labelName.Text = "WSR " + (count + 1);
labelLeakFluff.Text = "Протечка:";
labelLeak.Text = "неизвестно";
2025-01-24 17:54:04 +03:00
labelStatusFluff.Text = "Статус:";
labelStatus.Text = "неизвестно";
2025-01-17 10:40:18 +03:00
}
2025-01-24 11:46:36 +03:00
}
2025-01-21 14:38:59 +03:00
2025-01-24 11:46:36 +03:00
public class ScenarioSensor : Sensor
{
public ScenarioSensor()
2025-01-21 14:38:59 +03:00
{
2025-01-24 11:46:36 +03:00
labelName.Width = 172;
this.Margin = Padding.Empty;
this.Padding = new Padding(0, 5, 0, 0);
this.FlowDirection = FlowDirection.LeftToRight;
this.WrapContents = false;
2025-01-21 14:38:59 +03:00
2025-01-24 11:46:36 +03:00
this.Controls.Add(labelName);
this.Controls.Add(labelLeakFluff);
this.Controls.Add(labelLeak);
labelName.Text = "Сценарный датчик";
labelLeakFluff.Text = "Протечка:";
labelLeak.Text = "неизвестно";
}
}
}