I have form which start do backgroundwork using tcp connection. How to give "Tuple<TcpClient, IModbusMaster> connection" as argument to background worker?
Assistant
To pass a Tuple<TcpClient, IModbusMaster> as an argument to a BackgroundWorker, you can make use of the DoWork event's DoWorkEventArgs parameter. Here's a step-by-step guide on how to achieve this:
Initialize the BackgroundWorker:
Set up your BackgroundWorker and handle its DoWork event.
Pass the Tuple as Argument:
When you start the BackgroundWorker using the RunWorkerAsync method, you can pass your Tuple as the argument.
Access the Tuple in DoWork Event:
Within the DoWork event handler, you can access the Argument property of DoWorkEventArgs to get the Tuple.
Below is an example demonstrating these steps:
csharp
using System;
using System.ComponentModel;
using System.Net.Sockets;
using NModbus; // Assuming you have a library like NModbus for Modbus communication.
class Program
{
static void Main()
{
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(Worker_DoWork);
// Create TcpClient and IModbusMaster (using a hypothetical library here)
TcpClient tcpClient = new TcpClient("127.0.0.1", 502); // Example IP and port
IModbusMaster modbusMaster = new ModbusFactory().CreateMaster(tcpClient); // Assuming a factory like this exists
// Create the tuple
Tuple<TcpClient, IModbusMaster> connection = new Tuple<TcpClient, IModbusMaster>(tcpClient, modbusMaster);
// Start the BackgroundWorker
worker.RunWorkerAsync(connection);
}
private static void Worker_DoWork(object sender, DoWorkEventArgs e)
{
// Retrieve the Tuple from the argument
var connection = e.Argument as Tuple<TcpClient, IModbusMaster>;
if (connection != null)
{
TcpClient tcpClient = connection.Item1;
IModbusMaster modbusMaster = connection.Item2;
// Perform background work here
// For example, read/write operations
// modbusMaster.Read...
}
}
}
Key Points:
Using the Argument: Use the RunWorkerAsync(object argument) method to pass the tuple to the BackgroundWorker. This method allows passing any object, and a Tuple is an object since it derives from System.Object.
Type Safety: Ensure appropriate type checks and casting within the DoWork event handler to avoid runtime errors.
Clean-up Resources: Remember to properly close the TCP connection and dispose of any resources once the work is done to avoid resource leaks.
This setup allows you to perform background operations using the provided connection without blocking the main thread.
User
Fix the same in my code:
Tuple<TcpClient, IModbusMaster> connection
Assistant
Certainly! To modify your code to work with a BackgroundWorker and pass a Tuple<TcpClient, IModbusMaster> as an argument, let's break it down step-by-step and incorporate it into your context.
Step-by-Step Code:
csharp
using System;
using System.ComponentModel;
using System.Net.Sockets;
using NModbus; // This assumes you are using a library like NModbus
public class ModbusBackgroundWorker
{
private BackgroundWorker worker;
public ModbusBackgroundWorker()
{
// Initialize the BackgroundWorker and set up the event handler
worker = new BackgroundWorker();
worker.DoWork += Worker_DoWork;
}
public void StartBackgroundWork(Tuple<TcpClient, IModbusMaster> connection)
{
if (connection == null)
{
throw new ArgumentNullException(nameof(connection));
}
// Start the BackgroundWorker with the connection tuple as argument
worker.RunWorkerAsync(connection);
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
// Retrieve the tuple from the DoWorkEventArgs
if (e.Argument is Tuple<TcpClient, IModbusMaster> connection)
{
TcpClient tcpClient = connection.Item1;
IModbusMaster modbusMaster = connection.Item2;
// Perform the desired background operations
try
{
// Example operation: Read coils, replace this with your actual operation
ushort startAddress = 0;
ushort numberOfPoints = 5;
bool[] coils = modbusMaster.ReadCoils(startAddress, numberOfPoints);
// Process read coils (or perform other actions)
foreach (var coil in coils)
{
Console.WriteLine($"Coil state: {coil}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error during Modbus operation: {ex.Message}");
}
finally
{
// Ensure resources are released properly
modbusMaster.Dispose();
tcpClient.Close();
}
}
}
}
User
Fix the same in my code:
using NModbus.Device;
using ModBusHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static ModBusHelper.ModBusExporterLinker;
using static ModBusHelper.ModBusProfile;
using NModbus;
using NModbus.Utility;
using System.Net;
namespace Configurator
{
public partial class ECTStatePageForm : Form
{
CommanderForm CommanderForm;
code
Assistant
To pass a Tuple<TcpClient, IModbusMaster> as an argument to a BackgroundWorker in your existing code, you need to modify the parts where you start the background worker and handle the DoWork event. Here's a step-by-step update to your code:
Pass the Tuple to RunWorkerAsync: Pass the connection tuple when you start the background worker.
Access the Tuple in the DoWork Event: Inside the DoWork event handler, retrieve the tuple from the DoWorkEventArgs.
Here's the modified code:
csharp
User
I have a textbox in form upload_settingsTextBox and I want to dynamically change color of the text. How to do it?
Assistant
To dynamically change the color of the text in a TextBox in a Windows Forms application, you can set the ForeColor property of the TextBox. The ForeColor property determines the color of the text displayed in the TextBox.
Here's a simple approach you can use to change the text color based on specific conditions or events:
Step-by-Step Guide:
Identify the Condition: First, determine the condition(s) under which the text color should change. This could be based on user input, a background process, a timer, etc.
Set the ForeColor Property: Once the condition is met, change the ForeColor property of the TextBox.
Here is a basic example with a condition and a button click event:
Example Code:
csharp
using System;
using System.Drawing;
using System.Windows.Forms;
namespace Configurator
{
public partial class ECTStatePageForm : Form
{
// Assuming upload_settingsTextBox is already defined within your form
TextBox upload_settingsTextBox = new TextBox();
public ECTStatePageForm()
{
InitializeComponent();
SetupForm();
}
private void SetupForm()
{
// Configure the TextBox (example setup, adjust as necessary)
upload_settingsTextBox.Location = new Point(10, 10);
upload_settingsTextBox.Size = new Size(200, 20);
this.Controls.Add(upload_settingsTextBox);
// Add a button to demonstrate dynamic color change
Button changeColorButton = new Button
{
Text = "Change Color",
Location = new Point(10, 40)
};
changeColorButton.Click += ChangeColorButton_Click;
this.Controls.Add(changeColorButton);
}
private void ChangeColorButton_Click(object sender, EventArgs e)
{
// Example condition: Change the text color based on some criteria
ChangeTextBoxColor(upload_settingsTextBox.Text.Length > 5);
}
private void ChangeTextBoxColor(bool condition)
{
if (condition)
{
// Change text color to red if condition is true
upload_settingsTextBox.ForeColor = Color.Red;
}
else
{
// Change text color to green if condition is false
upload_settingsTextBox.ForeColor = Color.Green;
}
}
}
}
User
Comeback to previous question. Fix this funt the same
Code:
private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
{
var connection = e.Argument as Tuple<TcpClient, IModbusMaster>;
if (connection == null)
{
MessageBox.Show("Ошибка соединения", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
code
TcpClient tcpClient = connection.Item1;
IModbusMaster modbusMaster = connection.Item2;
while (!e.Cancel)
{
if ((sender as BackgroundWorker).CancellationPending)
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
ModBusProfile.ssp sspValues = ModBusProfileHelper.swrct_state_page_Read(modbusMaster);
ste1TextBox.Invoke(new Action(() => ste1TextBox.Text = sspValues.ste[0].ToString()));
ste2TextBox.Invoke(new Action(() => ste2TextBox.Text = sspValues.ste[1].ToString()));
ste3TextBox.Invoke(new Action(() => ste3TextBox.Text = sspValues.ste[2].ToString()));
ste4TextBox.Invoke(new Action(() => ste4TextBox.Text = sspValues.ste[3].ToString()));
if (sspValues.cntv.Length > cntvDataTable.Rows.Count)
{
for (int i = 1; i < sspValues.cntv.Length; i++)
{
cntvDataGridView.Invoke(new MethodInvoker(() =>
{
cntvDataTable.Rows.Add(new object[] { i, 0 });
}));
}
}
else if (sspValues.cntv.Length < cntvDataTable.Rows.Count)
{
int current_row = cntvDataTable.Rows.Count - 1;
while (sspValues.cntv.Length < cntvDataTable.Rows.Count)
{
cntvDataGridView.Invoke(new MethodInvoker(() =>
{
cntvDataTable.Rows[current_row].Delete();
}));
current_row--;
}
}
for (int z = 0; z < sspValues.cntv.Length; z++)
{
cntvDataTable.Rows[z][1] = sspValues.cntv[z].Racc;
cntvDataTable.Rows[z][2] = sspValues.cntv[z].ofcnt;
cntvDataTable.Rows[z][3] = sspValues.cntv[z].oNacnt;
}
cntvDataGridView.Invoke(new Action(() =>
{
cntvDataGridView.DataSource = cntvDataTable;
}));
System.Threading.Thread.Sleep(1000);
}
}
}
Assistant
To correct the function BackgroundWork_DoWork and ensure it's robust, especially in context where you want an operation running on a background thread to update UI elements, you need to ensure the handling of resources and thread safety with UI elements. Here’s how you can modify the provided method:
Ensure Proper Resource Management: Always close and dispose of TcpClient and IModbusMaster when they are no longer needed, which usually happens either after a successful operation or upon catching an exception.
Safely Interact with UI Elements: Use Invoke or BeginInvoke to ensure that you access UI elements on the main UI thread.
Guard Against Cancellation Properly: Always check for a cancellation request and handle it gracefully.
Here's the revised version of your BackgroundWork_DoWork method:
csharp
User
I have a form which setups the tcp connection. Add to it constant checking that connection is active. If connection is active then CurrentConnectionStateTextBox is must show "Connected", if connection is not active or drops while working then CurrentConnectionStateTextBox must show "Disconnected".
Assistant
To continuously monitor the status of a TCP connection and update a TextBox to reflect whether the connection is active or not, you can use a Timer in conjunction with the established TCP connection. The Timer will periodically check the state of the connection. If the connection is active, it will display "Connected" in the CurrentConnectionStateTextBox; otherwise, it will display "Disconnected."
Here's a guide to implementing this:
Use a Timer: Set up a System.Windows.Forms.Timer to periodically check the status of the connection.
Check Connection State: Implement logic to check if the TCP connection is still active.
Update UI: Use Invoke or BeginInvoke to update the UI thread safely.
Here’s an example implementation:
csharp
User
Do the same but with my form.
Code:
using ModBusHelper;
using System;
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 CommonFunctions;
using static ModBusHelper.ModBusExporterLinker;
using static ModBusHelper.ModBusCommands;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Xml.Linq;
using NModbus.Device;
using System.Net.Sockets;
using SharpPcap.LibPcap;
using SharpPcap;
using Microsoft.Win32;
using NModbus;
using NModbus.Message;
using System.Net.Http;
using System.Net;
namespace Configurator
{
public partial class CommanderForm : Form
{
ModBusCommands CommandsHelper = new ModBusCommands();
ModBusFunctions ModbusFunctionsHelper = new ModBusFunctions();
ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
code
Assistant
To implement continuous connection status checking in your existing CommanderForm, we'll use a timer to periodically check the TCP connection status and update the CurrentConnectionStateTextBox accordingly. This will ensure that the UI reflects whether the connection is "Connected" or "Disconnected" in real time.
Here are the steps:
Add a Timer: Add a System.Windows.Forms.Timer to periodically check the state of the TCP connection.
Check Connection Effectively: Use a method to determine if the connection to the TCP server is still active.
Update UI Safely: Ensure you update the CurrentConnectionStateTextBox from the UI thread.
Here is the modified code adapted into your CommanderForm:
csharp
User
I have a form which starting background worker which receives dat by tcp connection. But if this form active and tcp connection is dropped I got constant errors of it. Fix this form as that background worker tried receive data only when tcp connection is up.
Code:
using NModbus.Device;
using ModBusHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static ModBusHelper.ModBusExporterLinker;
using static ModBusHelper.ModBusProfile;
using NModbus;
using NModbus.Utility;
using System.Net;
using System.Data.Common;
namespace Configurator
{
public partial class ECTStatePageForm : Form
{
CommanderForm CommanderForm;
code
Assistant
To ensure that your BackgroundWorker properly handles the loss of a TCP connection and stops trying to receive data when the connection is down, you should implement a more rigorous check before attempting Modbus operations. This involves periodically verifying the connection status before any operation and handling connection issues gracefully without flooding the user with error messages.
Here’s how you can update your code to address these needs:
Connection Check Before Operation: Ensure that the TCP connection is still active before attempting to read data.
Graceful Exception Handling: If the connection drops, handle the exception, update the UI to indicate the disconnection, and break the loop.
Here’s the modified version of your BackgroundWork_DoWork method:
csharp
User
Add check if connection is reenabled background worker starts work again.
Assistant
To implement functionality where the BackgroundWorker resumes its operations when the connection is reestablished, you can use a combination of a System.Windows.Forms.Timer to regularly check the connection status and control the operation of the BackgroundWorker.
Here’s how you can integrate this logic:
Manage Connection State with a Timer: Use a timer to periodically check if the TCP connection is active or has been re-established.
Control the BackgroundWorker: Use the connection status checks to start or stop the BackgroundWorker accordingly.
Updated Implementation:
csharp
User
This code not working. If I open a form and after that enable tcp connection then data is not updating.
Assistant
If your form is not updating data when the TCP connection is established after opening the form, it's likely due to the fact that the BackgroundWorker is not correctly restarting or the connection evaluation logic isn't triggering the restart. To resolve this, let's refine the approach by ensuring the form handles connection state changes more effectively.
Here's what we need to do:
Re-check the connection and worker state regularly.
Ensure the BackgroundWorker is correctly started when the connection is restored.
Adjust the logic so it attempts to re-establish or resume operations when a connection is detected.
I'll adjust the code along these lines:
Revised Implementation
csharp
User
Still the same. I opened ECTStatePageForm and after that in CommanderForm press the button which starts the TCP connection, but data in ECTStagePageForm is not updating.
Assistant
To resolve this issue, we need to ensure that the ECTStatePageForm is correctly notified when the TCP connection is established or reestablished in the CommanderForm. Here's an approach that should work:
Events for Connection Changes: Use events to notify the ECTStatePageForm of connection status changes initiated from the CommanderForm.
Form-Specific Connection Handling: Ensure that the ECTStatePageForm knows when to start or restart its operations based on these events.
Explicit Connection Management: Manage the lifecycle of the connection from the CommanderForm, and ensure that the ECTStatePageForm updates its _connection based on the CommanderForm.
Let's update the code to implement these ideas:
Step-by-Step Implementation
1. Modify CommanderForm to Trigger Connection Events
In CommanderForm, add events and methods to notify observers (like ECTStatePageForm) about connection state changes.
csharp
User
Do this approach in my code of CommanderForm:
using ModBusHelper;
using System;
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 CommonFunctions;
using static ModBusHelper.ModBusExporterLinker;
using static ModBusHelper.ModBusCommands;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Xml.Linq;
using NModbus.Device;
using System.Net.Sockets;
using SharpPcap.LibPcap;
using SharpPcap;
using Microsoft.Win32;
using NModbus;
using NModbus.Message;
using System.Net.Http;
using System.Net;
namespace Configurator
{
public partial class CommanderForm : Form
{
ModBusCommands CommandsHelper = new ModBusCommands();
ModBusFunctions ModbusFunctionsHelper = new ModBusFunctions();
ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
code
Assistant
To ensure that your CommanderForm properly communicates connection changes to other forms like ECTStatePageForm, we can use events to signal when the connection starts or stops. Here's how you would refactor your CommanderForm to implement this approach:
Define Events for Connection Notifications: We'll create events for ConnectionStarted and ConnectionStopped that other forms can subscribe to.
Trigger Events in the Connection Methods: These events will be invoked in the ConnectionStartButton_Click and ConnectionStopButton_Click methods.
Ensure that Other Forms Subscribe to These Events: Other forms, such as ECTStatePageForm, need to subscribe to these events to be notified of changes.
Implementing this will ensure your application can react appropriately to changes in connection states.
Updated CommanderForm Code:
csharp
User
Add subscription to this events in my code of ECTStatePageForm:
using NModbus.Device;
using ModBusHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static ModBusHelper.ModBusExporterLinker;
using static ModBusHelper.ModBusProfile;
using NModbus;
using NModbus.Utility;
using System.Net;
using System.Data.Common;
namespace Configurator
{
public partial class ECTStatePageForm : Form
{
CommanderForm CommanderForm;
code
Assistant
To ensure that your ECTStatePageForm properly reacts to changes in the connection state from the CommanderForm, you need to subscribe to the ConnectionStarted and ConnectionStopped events in the constructor of the ECTStatePageForm. This will allow your form to start data processing when a connection becomes active and stop processing when the connection is lost.
Here’s how you can update your ECTStatePageForm:
Updated Implementation for ECTStatePageForm:
csharp
User
Do the same stuff with another form which needs subscription to this events:
using NModbus.Device;
using ModBusHelper;
using NModbus;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Configurator
{
public partial class SWRCTStatePageForm : Form
{
CommanderForm CommanderForm;
code
Assistant
To subscribe to connection events from the CommanderForm in the SWRCTStatePageForm, you need to register event handlers for the ConnectionStarted and ConnectionStopped events in its constructor. This will enable SWRCTStatePageForm to respond appropriately when the connection state changes, allowing it to start or stop its background processes accordingly.
Here's how you can update your SWRCTStatePageForm:
Updated Implementation for SWRCTStatePageForm:
csharp
User
And another one the same stuff:
using ModBusHelper;
using NModbus;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static ModBusHelper.ModBusProfile;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
namespace Configurator
{
public partial class JournalRecordForm : Form
{
ModBusCommands CommandsHelper = new ModBusCommands();
ModBusFunctions ModbusFunctionsHelper = new ModBusFunctions();
ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
ModBusProfile ProfileHelper = new ModBusProfile();
code
Assistant
To subscribe the JournalRecordForm to connection events from the CommanderForm, you will need to ensure that the form registers for and handles the ConnectionStarted and ConnectionStopped events. This will allow JournalRecordForm to respond to changes in connection state, such as updating journal entries when a connection is available.
Here's how you can update your JournalRecordForm:
Updated Implementation for JournalRecordForm:
csharp
Not yet included in a published release.
Key Steps Explained:
Initialize BackgroundWorker: Create an instance of BackgroundWorker and subscribe to the DoWork event.
Start Background Work: Use StartBackgroundWork(Tuple<TcpClient, IModbusMaster> connection) to initiate background processes. This method validates the connection and starts the worker with the connection tuple.
Handle DoWork Event: Inside Worker_DoWork, check if the event argument is a tuple of your expected types. If so, extract the TcpClient and IModbusMaster objects.
Perform Operations: Execute your desired tasks using the Modbus master (e.g., reading coils) within the DoWork action, handling exceptions and cleaning up resources by disposing of them.
Cleaning Up: Always ensure that resources like TcpClient and IModbusMaster are properly disposed of, even in the case of exceptions, to prevent resource leaks.
This structure provides a robust way to manage background tasks with Modbus operations, leveraging the provided connection while maintaining clean resource management.
BackgroundWorker BackgroundWork = new BackgroundWorker();
DataTable rmsDataTable = new DataTable();
DataTable diapsDataTable = new DataTable();
ModBusProfile ModBusProfileHelper = new ModBusProfile();
ModBusFunctions ModbusFunctionsHelper = new ModBusFunctions();
ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
public ECTStatePageForm(CommanderForm CommanderFormInstance, Tuple<TcpClient, IModbusMaster> connection)
{
InitializeComponent();
this.CommanderForm = CommanderFormInstance;
ModBusProfile.esp esp = ExporterLinkerHelper.esp_Default;
ste1TextBox.Text = esp.ste[0].ToString();
ste2TextBox.Text = esp.ste[1].ToString();
ste3TextBox.Text = esp.ste[2].ToString();
ste4TextBox.Text = esp.ste[3].ToString();
rmsDataTable.Columns.Add("Канал", typeof(int));
rmsDataTable.Columns.Add("Действующее значение тока", typeof(float));
rmsDataTable.Rows.Add(new object[] { 0, esp.rms[0] });
rmsDataGridView.DataSource = rmsDataTable;
diapsDataTable.Columns.Add("Канал", typeof(int));
diapsDataTable.Columns.Add("Значения диапазонов", typeof(sbyte));
diapsDataTable.Rows.Add(new object[] { 0, esp.diaps[0] });
diapsDataGridView.DataSource = diapsDataTable;
BackgroundWork.WorkerSupportsCancellation = true;
BackgroundWork.DoWork += new DoWorkEventHandler(BackgroundWork_DoWork);
if (BackgroundWork.IsBusy != true)
{
// Start background work
try
{
BackgroundWork.RunWorkerAsync();
}
catch (InvalidOperationException ex)
{
MessageBox.Show($"Невозможно запустить процесс в фоновом режиме: {ex.Message}", "Ошибка запуска процесса", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
while (e.Cancel == false)
{
if ((worker.CancellationPending == true))
{
e.Cancel = true;
break;
}
else
{
// Perform a time consuming operation and report progress.
ModBusProfile.esp espValues = ModBusProfileHelper.ect_state_page_Read(_connection.Item2);
ste1TextBox.Invoke(new Action(() =>
{
ste1TextBox.Text = espValues.ste[0].ToString();
}));
ste2TextBox.Invoke(new Action(() =>
{
ste2TextBox.Text = espValues.ste[1].ToString();
}));
ste3TextBox.Invoke(new Action(() =>
{
ste3TextBox.Text = espValues.ste[2].ToString();
}));
ste4TextBox.Invoke(new Action(() =>
{
ste4TextBox.Text = espValues.ste[3].ToString();
}));
if (espValues.rms.Length > rmsDataTable.Rows.Count)
{
for (int i = 1; i < espValues.rms.Length; i++)
{
rmsDataGridView.Invoke(new MethodInvoker(() =>
{
rmsDataTable.Rows.Add(new object[] { i, 0 });
}));
}
}
else if (espValues.rms.Length < rmsDataTable.Rows.Count)
{
int current_row = rmsDataTable.Rows.Count - 1;
while (espValues.rms.Length < rmsDataTable.Rows.Count)
{
rmsDataGridView.Invoke(new MethodInvoker(() =>
{
rmsDataTable.Rows[current_row].Delete();
}));
current_row--;
}
}
if (espValues.diaps.Length > diapsDataTable.Rows.Count)
{
for (int i = 1; i < espValues.diaps.Length; i++)
{
diapsDataGridView.Invoke(new MethodInvoker(() =>
{
diapsDataTable.Rows.Add(new object[] { i, 0 });
}));
}
}
else if (espValues.diaps.Length < diapsDataTable.Rows.Count)
{
int current_row = diapsDataTable.Rows.Count - 1;
while (espValues.diaps.Length < diapsDataTable.Rows.Count)
{
diapsDataGridView.Invoke(new MethodInvoker(() =>
{
diapsDataTable.Rows[current_row].Delete();
}));
current_row--;
}
}
for (int k = 0; k < espValues.rms.Length; k++)
{
rmsDataTable.Rows[k][1] = espValues.rms[k];
}
rmsDataGridView.Invoke(new Action(() =>
{
rmsDataGridView.DataSource = rmsDataTable;
}));
for (int z = 0; z < espValues.diaps.Length; z++)
{
diapsDataTable.Rows[z][1] = espValues.diaps[z];
}
diapsDataGridView.Invoke(new Action(() =>
{
diapsDataGridView.DataSource = diapsDataTable;
}));
System.Threading.Thread.Sleep(1000);
}
}
}
private void ECTStatePageForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (BackgroundWork.WorkerSupportsCancellation == true)
{
BackgroundWork.CancelAsync();
}
}
}
}
using NModbus.Device;
using ModBusHelper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Text;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static ModBusHelper.ModBusExporterLinker;
using static ModBusHelper.ModBusProfile;
using NModbus;
using NModbus.Utility;
using System.Net;
namespace Configurator
{
public partial class ECTStatePageForm : Form
{
CommanderForm CommanderForm;
BackgroundWorker BackgroundWork = new BackgroundWorker();
DataTable rmsDataTable = new DataTable();
DataTable diapsDataTable = new DataTable();
ModBusProfile ModBusProfileHelper = new ModBusProfile();
ModBusFunctions ModbusFunctionsHelper = new ModBusFunctions();
ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
public ECTStatePageForm(CommanderForm CommanderFormInstance, Tuple<TcpClient, IModbusMaster> connection)
{
InitializeComponent();
this.CommanderForm = CommanderFormInstance;
ModBusProfile.esp esp = ExporterLinkerHelper.esp_Default;
ste1TextBox.Text = esp.ste[0].ToString();
ste2TextBox.Text = esp.ste[1].ToString();
ste3TextBox.Text = esp.ste[2].ToString();
ste4TextBox.Text = esp.ste[3].ToString();
rmsDataTable.Columns.Add("Канал", typeof(int));
rmsDataTable.Columns.Add("Действующее значение тока", typeof(float));
rmsDataTable.Rows.Add(new object[] { 0, esp.rms[0] });
rmsDataGridView.DataSource = rmsDataTable;
diapsDataTable.Columns.Add("Канал", typeof(int));
diapsDataTable.Columns.Add("Значения диапазонов", typeof(sbyte));
diapsDataTable.Rows.Add(new object[] { 0, esp.diaps[0] });
diapsDataGridView.DataSource = diapsDataTable;
BackgroundWork.WorkerSupportsCancellation = true;
BackgroundWork.DoWork += new DoWorkEventHandler(BackgroundWork_DoWork);
if (BackgroundWork.IsBusy != true)
{
// Start background work, passing the connection tuple
try
{
BackgroundWork.RunWorkerAsync(connection);
}
catch (InvalidOperationException ex)
{
MessageBox.Show($"Невозможно запустить процесс в фоновом режиме: {ex.Message}", "Ошибка запуска процесса", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
{
var connection = e.Argument as Tuple<TcpClient, IModbusMaster>;
if (connection == null)
{
MessageBox.Show("Invalid connection argument", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
TcpClient tcpClient = connection.Item1;
IModbusMaster modbusMaster = connection.Item2;
while (!e.Cancel)
{
if ((sender as BackgroundWorker).CancellationPending)
{
e.Cancel = true;
break;
}
try
{
ModBusProfile.esp espValues = ModBusProfileHelper.ect_state_page_Read(modbusMaster);
// Update the UI safely
ste1TextBox.Invoke(new Action(() => ste1TextBox.Text = espValues.ste[0].ToString()));
ste2TextBox.Invoke(new Action(() => ste2TextBox.Text = espValues.ste[1].ToString()));
ste3TextBox.Invoke(new Action(() => ste3TextBox.Text = espValues.ste[2].ToString()));
ste4TextBox.Invoke(new Action(() => ste4TextBox.Text = espValues.ste[3].ToString()));
// Update tables and grids
UpdateDataGrid(rmsDataGridView, rmsDataTable, espValues.rms);
UpdateDataGrid(diapsDataGridView, diapsDataTable, espValues.diaps);
System.Threading.Thread.Sleep(1000);
}
catch (Exception ex)
{
// Log or handle error
MessageBox.Show($"Error in Modbus operation: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// Dispose resources
modbusMaster.Dispose();
tcpClient.Close();
}
private void UpdateDataGrid<T>(DataGridView gridView, DataTable table, T[] values)
{
gridView.Invoke(new MethodInvoker(() =>
{
// Adjust row count
while (values.Length > table.Rows.Count)
{
table.Rows.Add(new object[] { table.Rows.Count, default(T) });
}
while (values.Length < table.Rows.Count)
{
table.Rows.RemoveAt(table.Rows.Count - 1);
}
// Update values
for (int i =0; i < values.Length; i++)
{
table.Rows[i][1] = values[i];
}
gridView.DataSource = table;
}));
}
private void ECTStatePageForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (BackgroundWork.WorkerSupportsCancellation)
{
BackgroundWork.CancelAsync();
}
}
}
}
Key Changes:
Connection Tuple Passed: The RunWorkerAsync(connection) method is now used to pass the Modbus connection to the BackgroundWorker.
Tuple Access: The DoWorkEventArgs e.Argument property is used to retrieve the tuple, and the TcpClient and IModbusMaster are extracted for use.
Safe Resource Management: The connection is disposed of properly within the finally block of your operations to prevent resource leaks.
UI Updates: The implementation ensures UI components are updated using Invoke to marshal calls back to the UI thread safely.
This implementation maintains the existing functionality while ensuring the necessary Modbus operations occur asynchronously and safely with proper resource management.
Explanation:
Event Handling: The example includes a button (ChangeColorButton_Click) that changes the text color based on a simple condition, such as the length of the text being greater than 5 characters.
Dynamic Color Update: The ChangeTextBoxColor method sets the ForeColor property conditionally, demonstrating how to dynamically alter text appearance in response to runtime conditions.
TextBox Setup: Make sure the upload_settingsTextBox is properly instantiated and added to the form's controls, so it is visible and interactive.
You can modify the condition and color values to align with your specific requirements. For example, you may want to change the text color based on input validation, program state, or other application-specific logic.
private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
{
var connection = e.Argument as Tuple<TcpClient, IModbusMaster>;
if (connection == null)
{
MessageBox.Show("Ошибка соединения", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
TcpClient tcpClient = connection.Item1;
IModbusMaster modbusMaster = connection.Item2;
try
{
while (!e.Cancel)
{
if ((sender as BackgroundWorker).CancellationPending)
{
e.Cancel = true;
break;
}
// Perform a time-consuming operation and report progress.
ModBusProfile.ssp sspValues = ModBusProfileHelper.swrct_state_page_Read(modbusMaster);
// Update TextBox controls with thread safety
ste1TextBox.Invoke(new Action(() => ste1TextBox.Text = sspValues.ste[0].ToString()));
ste2TextBox.Invoke(new Action(() => ste2TextBox.Text = sspValues.ste[1].ToString()));
ste3TextBox.Invoke(new Action(() => ste3TextBox.Text = sspValues.ste[2].ToString()));
ste4TextBox.Invoke(new Action(() => ste4TextBox.Text = sspValues.ste[3].ToString()));
// Ensure cntvDataTable has correct number of rows
cntvDataGridView.Invoke(new MethodInvoker(() => UpdateCntvDataTable(sspValues)));
System.Threading.Thread.Sleep(1000);
}
}
catch (Exception ex)
{
MessageBox.Show($"Error in Modbus operation: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
// Ensure resources are cleaned up
try { modbusMaster.Dispose(); } catch { }
try { tcpClient.Close(); } catch { }
}
}
private void UpdateCntvDataTable(ModBusProfile.ssp sspValues)
{
// Adjust rows count
while (sspValues.cntv.Length > cntvDataTable.Rows.Count)
{
cntvDataTable.Rows.Add(new object[] { cntvDataTable.Rows.Count, 0, 0, 0 });
}
while (sspValues.cntv.Length < cntvDataTable.Rows.Count)
{
cntvDataTable.Rows.RemoveAt(cntvDataTable.Rows.Count - 1);
}
// Update data
for (int z = 0; z < sspValues.cntv.Length; z++)
{
cntvDataTable.Rows[z][1] = sspValues.cntv[z].Racc;
cntvDataTable.Rows[z][2] = sspValues.cntv[z].ofcnt;
cntvDataTable.Rows[z][3] = sspValues.cntv[z].oNacnt;
}
// Set the updated table as the DataSource for the GridView
cntvDataGridView.DataSource = cntvDataTable;
}
Key Points in the Revised Code:
Exception Handling: A try-catch block is added to manage any exceptions that could occur during Modbus operations and to ensure that resources are properly disposed of in the finally block.
UI Updates: UI updates are performed with Invoke to ensure thread safety.
Helper Method: The UpdateCntvDataTable method encapsulates the logic for updating the DataTable and keeps the DoWork method clean and focused on the overarching control flow.
This revision makes sure that your operation safely interacts with UI components and manages resources properly, avoiding potential leaks or UI thread access violations.
using System;
using System.Net.Sockets;
using System.Windows.Forms;
public partial class TcpConnectionForm : Form
{
private TcpClient tcpClient;
private IModbusMaster modbusMaster; // Assuming you're using a library like NModbus
private Timer connectionCheckTimer;
public TcpConnectionForm()
{
InitializeComponent();
// Initialize TcpClient, IModbusMaster and other components
InitializeConnection();
// Set up the timer
connectionCheckTimer = new Timer();
connectionCheckTimer.Interval = 1000; // Check every second
connectionCheckTimer.Tick += ConnectionCheckTimer_Tick;
connectionCheckTimer.Start();
}
private void InitializeConnection()
{
// Example connection setup
try
{
tcpClient = new TcpClient("127.0.0.1", 502); // Example IP and port
modbusMaster = new ModbusFactory().CreateMaster(tcpClient); // Hypothetical factory method
CurrentConnectionStateTextBox.Text = "Connecting...";
// Assuming the connection is successful for the sake of illustration
CurrentConnectionStateTextBox.Text = "Connected";
}
catch (Exception ex)
{
MessageBox.Show($"Failed to establish connection: {ex.Message}", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
CurrentConnectionStateTextBox.Text = "Disconnected";
}
}
private void ConnectionCheckTimer_Tick(object sender, EventArgs e)
{
// Check if the tcpClient's connection is active
if (tcpClient != null && tcpClient.Connected)
{
UpdateConnectionState("Connected");
}
else
{
UpdateConnectionState("Disconnected");
}
}
private void UpdateConnectionState(string state)
{
if (CurrentConnectionStateTextBox.InvokeRequired)
{
CurrentConnectionStateTextBox.Invoke(new Action(() => CurrentConnectionStateTextBox.Text = state));
}
else
{
CurrentConnectionStateTextBox.Text = state;
}
}
// Dispose resources properly
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (tcpClient != null)
{
tcpClient.Close();
tcpClient = null;
}
if (modbusMaster != null)
{
modbusMaster.Dispose();
modbusMaster = null;
}
if (connectionCheckTimer != null)
{
connectionCheckTimer.Stop();
connectionCheckTimer.Dispose();
connectionCheckTimer = null;
}
}
base.Dispose(disposing);
}
}
Explanation:
Timer Configuration: A Timer is set up to fire every second (Interval = 1000). When the timer fires, it checks the status of the connection.
Connection Status Checking: The method ConnectionCheckTimer_Tick checks if tcpClient.Connected is true. This property can indicate whether the connection is still established, though note that TcpClient.Connected doesn't inherently track every little failure immediately (hence more robust logic might include sending small health check packets if needed).
UI Thread Safety: Use Invoke on the TextBox to update its text safely across threads.
Resource Cleanup: Override Dispose to ensure all resources such as TcpClient, IModbusMaster, and Timer are properly released.
This setup will help in maintaining an ongoing indication of the network connection's state in your application, reflecting this in the user interface.
private Tuple<TcpClient, IModbusMaster> _connection;
private static CommanderForm commanderFormInstance;
public static CommanderForm FormInstance;
private static ECTStatePageForm ectStatePageFormInstance;
private static SWRCTStatePageForm swrctStatePageFormInstance;
private static JournalRecordForm journalRecordFormInstance;
public CommanderForm()
{
InitializeComponent();
FormInstance = this;
}
public static CommanderForm GetInstance()
{
if (commanderFormInstance == null || commanderFormInstance.IsDisposed)
{
commanderFormInstance = new CommanderForm();
}
return commanderFormInstance;
}
private void ConnectionStartButton_Click(object sender, EventArgs e)
{
int modBusPort;
string boardIP;
if (BoardIPTextBox.Text != "")
{
boardIP = BoardIPTextBox.Text;
}
else
{
MessageBox.Show("Введите IP адрес устройства.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Attempt to retrieve and parse the ModBus port
try
{
modBusPort = int.Parse(ModBusPortTextBox.Text);
}
catch (FormatException)
{
MessageBox.Show("Неправильный формат номера порта. Пожалуйста введите целое число.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
catch (ArgumentNullException)
{
MessageBox.Show("Введите номер порта ModBus.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CurrentConnectionStateTextBox.ForeColor = Color.DarkGray;
CurrentConnectionStateTextBox.Text = "Подключение...";
try
{
_connection = ConnectionManager.OpenConnection(boardIP, modBusPort);
}
catch (ArgumentException ex)
{
CurrentConnectionStateTextBox.ForeColor = Color.Red;
CurrentConnectionStateTextBox.Text = "Ошибка";
MessageBox.Show("Ошибка ввода: " + ex.Message);
return;
}
catch (InvalidOperationException ex)
{
CurrentConnectionStateTextBox.ForeColor = Color.Red;
CurrentConnectionStateTextBox.Text = "Ошибка";
MessageBox.Show("Ошибка соединения: " + ex.Message);
return;
}
CurrentConnectionStateTextBox.Text = "Подключено";
CurrentConnectionStateTextBox.ForeColor = Color.Green;
}
private void ConnectionStopButton_Click(object sender, EventArgs e)
{
}
private void WriteValuesButton_Click(object sender, EventArgs e)
{
bool adminRights = false;
try
{
// Check for admin rights
try
{
if ((LoginComboBox.SelectedItem.ToString() == "Администратор") && (PasswordTextBox.Text == "admin"))
{
adminRights = true;
}
}
catch (NullReferenceException)
{
MessageBox.Show("Выберите тип пользователя.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Ensure settings are not empty
if ((Database.GeneralSettings_TextFormat.cmns.nAchans != "") && (Database.GeneralSettings_TextFormat.cmns.nDiap != ""))
{
try
{
ExporterLinkerHelper.WriteSettings(Database.GeneralSettings_TextFormat, adminRights, _connection);
write_SettingsTextBox.ForeColor = Color.Green;
write_SettingsTextBox.Text = "ОК";
}
catch (Exception ex)
{
write_SettingsTextBox.ForeColor = Color.Red;
write_SettingsTextBox.Text = "Ошибка";
MessageBox.Show($"При записи параметров возникла ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
write_SettingsTextBox.ForeColor = Color.Red;
write_SettingsTextBox.Text = "Ошибка";
MessageBox.Show("Не указаны параметры для записи. Пожалуйста, проверьте конфигурацию.", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
catch (Exception ex)
{
write_SettingsTextBox.ForeColor = Color.Red;
write_SettingsTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void ReadValuesButton_Click(object sender, EventArgs e)
{
try
{
// Attempt to read general settings
try
{
Database.GeneralSettings_TextFormat = ExporterLinkerHelper.get_GeneralSettings_Text(_connection);
read_SettingsTextBox.ForeColor = Color.Green;
read_SettingsTextBox.Text = "ОК";
}
catch (Exception ex)
{
read_SettingsTextBox.ForeColor = Color.Red;
read_SettingsTextBox.Text = "Ошибка";
MessageBox.Show($"При чтении параметров возникла ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
catch (Exception ex)
{
read_SettingsTextBox.ForeColor = Color.Red;
read_SettingsTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void upload_firmware_defaultButton_Click(object sender, EventArgs e)
{
try
{
int groupsIdentificatorsAccumulator = 0x00;
int cmnsIdentificator = 0x01;
int netsIdentificator = 0x02;
int timeIdentificator = 0x04;
int synsIdentificator = 0x08;
int swrcsIdentificator = 0x10;
int measIdentificator = 0x20;
if (upload_firmware_CheckBox1.Checked)
{
groupsIdentificatorsAccumulator |= cmnsIdentificator;
}
if (upload_firmware_CheckBox2.Checked)
{
groupsIdentificatorsAccumulator |= netsIdentificator;
}
if (upload_firmware_CheckBox3.Checked)
{
groupsIdentificatorsAccumulator |= timeIdentificator;
}
if (upload_firmware_CheckBox4.Checked)
{
groupsIdentificatorsAccumulator |= synsIdentificator;
}
if (upload_firmware_CheckBox5.Checked)
{
groupsIdentificatorsAccumulator |= swrcsIdentificator;
}
if (upload_firmware_CheckBox6.Checked)
{
groupsIdentificatorsAccumulator |= measIdentificator;
}
ushort bitMask = Convert.ToUInt16(groupsIdentificatorsAccumulator);
upload_firmware_defaultTextBox1.Text = $"0x{bitMask.ToString("X2")}";
try
{
WriteSingleRegisterRequestResponse response = CommandsHelper.upload_firmware_default(_connection.Item2, bitMask);
if ($"0x{response.Data[0].ToString("X2")}" == $"0x{bitMask.ToString("X2")}")
{
upload_firmware_defaultTextBox2.ForeColor = Color.Green;
upload_firmware_defaultTextBox2.Text = "ОК";
}
else
{
upload_firmware_defaultTextBox2.ForeColor = Color.Red;
upload_firmware_defaultTextBox2.Text = "Ошибка";
}
}
catch (Exception modbusException)
{
upload_firmware_defaultTextBox2.ForeColor = Color.Red;
upload_firmware_defaultTextBox2.Text = "Ошибка";
MessageBox.Show($"Ошибка при загрузке параметров: {modbusException.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
catch (Exception ex)
{
upload_firmware_defaultTextBox2.ForeColor = Color.Red;
upload_firmware_defaultTextBox2.Text = "Ошибка";
MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void upload_settingsButton_Click(object sender, EventArgs e)
{
try
{
WriteSingleRegisterRequestResponse response = CommandsHelper.upload_settings(_connection.Item2, 0x00);
if (response.Data[0] == 0)
{
try
{
if (upload_settingsCheckBox.Checked)
{
WriteSingleRegisterRequestResponse responseReset = CommandsHelper.reset_ect(_connection.Item2);
if ($"0x{responseReset.Data[0].ToString("X4")}" == "0x00FF")
{
upload_settingsTextBox.ForeColor = Color.Green;
upload_settingsTextBox.Text = "ОК";
}
}
else
{
upload_settingsTextBox.ForeColor = Color.Red;
upload_settingsTextBox.Text = "Ошибка";
}
}
catch (Exception modbusException)
{
upload_settingsTextBox.ForeColor = Color.Red;
upload_settingsTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка при загрузке параметров: {modbusException.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
catch (Exception ex)
{
upload_settingsTextBox.ForeColor = Color.Red;
upload_settingsTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка при загрузке параметров: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void get_last_settings_recordButton_Click(object sender, EventArgs e)
{
// Perform Modbus operation
bool[] lastSettingsRecordBoolArray;
byte lastSettingsRecord;
try
{
lastSettingsRecordBoolArray = CommandsHelper.get_last_settings_record(_connection.Item2);
lastSettingsRecord = ModbusFunctionsHelper.ConvertBoolArrayToByte(lastSettingsRecordBoolArray);
if ($"0x{lastSettingsRecord.ToString("X2")}" == "0x00")
{
get_last_settings_recordTextBox.ForeColor = Color.Green;
get_last_settings_recordTextBox.Text = "ОК";
}
else
{
get_last_settings_recordTextBox.ForeColor = Color.Red;
get_last_settings_recordTextBox.Text = "Ошибка";
}
}
catch (Exception ex)
{
get_last_settings_recordTextBox.ForeColor = Color.Red;
get_last_settings_recordTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка получения статуса последней записи настроек: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void reset_ectButton_Click(object sender, EventArgs e)
{
// Perform Modbus operation to reset ect
try
{
WriteSingleRegisterRequestResponse response = CommandsHelper.reset_ect(_connection.Item2);
if ($"0x{response.Data[0].ToString("X4")}" == "0x00FF")
{
reset_ectTextBox.ForeColor = Color.Green;
reset_ectTextBox.Text = "ОК";
}
else
{
reset_ectTextBox.ForeColor = Color.Red;
reset_ectTextBox.Text = "Ошибка";
}
}
catch (Exception ex)
{
reset_ectTextBox.ForeColor = Color.Red;
reset_ectTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка перезагрузки ЭТТ: {ex.Message}", "Ошибка ModBus соединения", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void nulify_swrcButton_Click(object sender, EventArgs e)
{
bool adminRights = false;
try
{
// Try to determine if the user has admin rights
try
{
if ((LoginComboBox.SelectedItem?.ToString() == "Администратор") && (PasswordTextBox.Text == "admin"))
{
adminRights = true;
}
}
catch (NullReferenceException)
{
nulify_swrcTextBox.ForeColor = Color.Red;
nulify_swrcTextBox.Text = "Ошибка";
MessageBox.Show("Выберите тип пользователя.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (adminRights)
{
try
{
// Perform Modbus operation
WriteSingleRegisterRequestResponse response = CommandsHelper.nulify_swrc(_connection.Item2);
if ($"0x{response.Data[0].ToString("X4")}" == "0x00FF")
{
nulify_swrcTextBox.ForeColor = Color.Green;
nulify_swrcTextBox.Text = "ОК";
}
else
{
nulify_swrcTextBox.ForeColor = Color.Red;
nulify_swrcTextBox.Text = "Ошибка";
}
}
catch (Exception modbusException)
{
nulify_swrcTextBox.ForeColor = Color.Red;
nulify_swrcTextBox.Text = "Ошибка";
MessageBox.Show($"При обнулении данных расхода ресурса произошла ошибка: {modbusException.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
nulify_swrcTextBox.ForeColor = Color.Red;
nulify_swrcTextBox.Text = "Ошибка";
MessageBox.Show("Для выполнения команды требуются права Администратора.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
catch (Exception ex)
{
nulify_swrcTextBox.ForeColor = Color.Red;
nulify_swrcTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void clear_swrc_journalButton_Click(object sender, EventArgs e)
{
bool adminRights = false;
try
{
// Determine if the user has admin rights
try
{
if ((LoginComboBox.SelectedItem?.ToString() == "Администратор") && (PasswordTextBox.Text == "admin"))
{
adminRights = true;
}
}
catch (NullReferenceException)
{
MessageBox.Show("Выберите тип пользователя.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (adminRights)
{
try
{
bool clearJournal = clear_swrc_journalCheckBox.Checked;
WriteSingleRegisterRequestResponse response = CommandsHelper.clear_swrc_journal(_connection.Item2, clearJournal);
string checkString = "0x00";
if (clearJournal)
{
checkString = "0x01";
}
if ($"0x{response.Data[0].ToString("X2")}" == checkString)
{
clear_swrc_journalTextBox.ForeColor = Color.Green;
clear_swrc_journalTextBox.Text = "ОК";
}
else
{
clear_swrc_journalTextBox.ForeColor = Color.Red;
clear_swrc_journalTextBox.Text = "Ошибка";
}
}
catch (Exception modbusEx)
{
clear_swrc_journalTextBox.ForeColor = Color.Red;
clear_swrc_journalTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка при очистке журнала СКРВ: {modbusEx.Message}", "Ошибка ModBus соединения", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
clear_swrc_journalTextBox.ForeColor = Color.Red;
clear_swrc_journalTextBox.Text = "Ошибка";
MessageBox.Show("Для выполнения команды требуются права Администратора.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
catch (Exception ex)
{
clear_swrc_journalTextBox.ForeColor = Color.Red;
clear_swrc_journalTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void ECTStatePageButton_Click(object sender, EventArgs e)
{
// Check if an instance is already open or disposed
if (ectStatePageFormInstance == null || ectStatePageFormInstance.IsDisposed)
{
// Create and show a new instance
ectStatePageFormInstance = new ECTStatePageForm(FormInstance, _connection);
ectStatePageFormInstance.Show();
}
else
{
// If instance exists, bring it to the front
ectStatePageFormInstance.BringToFront();
ectStatePageFormInstance.Focus();
}
}
private void SWRCTStatePageButton_Click(object sender, EventArgs e)
{
// Check if an instance is already open or disposed
if (swrctStatePageFormInstance == null || ectStatePageFormInstance.IsDisposed)
{
// Create and show a new instance
swrctStatePageFormInstance = new SWRCTStatePageForm(FormInstance, _connection);
swrctStatePageFormInstance.Show();
}
else
{
// If instance exists, bring it to the front
swrctStatePageFormInstance.BringToFront();
swrctStatePageFormInstance.Focus();
}
}
private void ReadJournalButton_Click(object sender, EventArgs e)
{
// Check if an instance is already open or disposed
if (journalRecordFormInstance == null || journalRecordFormInstance.IsDisposed)
{
// Create and show a new instance
journalRecordFormInstance = new JournalRecordForm(FormInstance, Database.Filtered_Journal_Records, _connection);
journalRecordFormInstance.Show();
}
else
{
// If instance exists, bring it to the front
journalRecordFormInstance.BringToFront();
journalRecordFormInstance.Focus();
}
}
}
}
using ModBusHelper;
using System;
using System.Drawing;
using System.Net.Sockets;
using System.Windows.Forms;
using NModbus;
namespace Configurator
{
public partial class CommanderForm : Form
{
ModBusCommands CommandsHelper = new ModBusCommands();
ModBusFunctions ModbusFunctionsHelper = new ModBusFunctions();
ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
private Tuple<TcpClient, IModbusMaster> _connection;
private Timer connectionCheckTimer;
private static CommanderForm commanderFormInstance;
public static CommanderForm FormInstance;
// Other form instances...
private static ECTStatePageForm ectStatePageFormInstance;
private static SWRCTStatePageForm swrctStatePageFormInstance;
private static JournalRecordForm journalRecordFormInstance;
public CommanderForm()
{
InitializeComponent();
FormInstance = this;
// Initialize connection check timer
connectionCheckTimer = new Timer();
connectionCheckTimer.Interval = 1000; // Check every second
connectionCheckTimer.Tick += ConnectionCheckTimer_Tick;
}
private void ConnectionStartButton_Click(object sender, EventArgs e)
{
int modBusPort;
string boardIP;
if (BoardIPTextBox.Text != "")
{
boardIP = BoardIPTextBox.Text;
}
else
{
MessageBox.Show("Введите IP адрес устройства.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
modBusPort = int.Parse(ModBusPortTextBox.Text);
}
catch (FormatException)
{
MessageBox.Show("Неправильный формат номера порта. Пожалуйста введите целое число.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CurrentConnectionStateTextBox.ForeColor = Color.DarkGray;
CurrentConnectionStateTextBox.Text = "Подключение...";
try
{
_connection = ConnectionManager.OpenConnection(boardIP, modBusPort);
CurrentConnectionStateTextBox.Text = "Подключено";
CurrentConnectionStateTextBox.ForeColor = Color.Green;
// Start the connection check timer
connectionCheckTimer.Start();
}
catch (Exception ex)
{
CurrentConnectionStateTextBox.ForeColor = Color.Red;
CurrentConnectionStateTextBox.Text = "Ошибка";
MessageBox.Show("Ошибка соединения: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ConnectionStopButton_Click(object sender, EventArgs e)
{
try
{
connectionCheckTimer.Stop();
_connection.Item2.Dispose();
_connection.Item1.Close();
_connection = null;
CurrentConnectionStateTextBox.Text = "Отключено";
CurrentConnectionStateTextBox.ForeColor = Color.Red;
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при отключении: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ConnectionCheckTimer_Tick(object sender, EventArgs e)
{
if (_connection != null && _connection.Item1.Connected)
{
UpdateConnectionStateTextBox("Подключено", Color.Green);
}
else
{
UpdateConnectionStateTextBox("Отключено", Color.Red);
}
}
private void UpdateConnectionStateTextBox(string state, Color color)
{
if (CurrentConnectionStateTextBox.InvokeRequired)
{
CurrentConnectionStateTextBox.Invoke(new Action(() =>
{
CurrentConnectionStateTextBox.Text = state;
CurrentConnectionStateTextBox.ForeColor = color;
}));
}
else
{
CurrentConnectionStateTextBox.Text = state;
CurrentConnectionStateTextBox.ForeColor = color;
}
}
public static CommanderForm GetInstance()
{
if (commanderFormInstance == null || commanderFormInstance.IsDisposed)
{
commanderFormInstance = new CommanderForm();
}
return commanderFormInstance;
}
// Add other necessary methods and event handlers here...
}
}
Key Points:
Timer Setup: A Timer is initialized in the form's constructor and set to check the connection status every 1000 milliseconds.
Check Connection: The ConnectionCheckTimer_Tick method checks whether the TCP client (_connection.Item1) is connected. It updates the UI based on this status.
UI Thread Safety: Updates to CurrentConnectionStateTextBox are done safely using Invoke, ensuring thread-safe modifications.
Start/Stop Connection Management: When starting the connection (ConnectionStartButton_Click), the timer is started. Conversely, when stopping the connection (ConnectionStopButton_Click), the connection resources are released, and the timer is stopped.
This implementation ensures your application continuously monitors the connection status and updates the UI in real-time to reflect whether the device remains connected.
private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
{
var connection = e.Argument as Tuple<TcpClient, IModbusMaster>;
if (connection == null)
{
Invoke(new Action(() =>
MessageBox.Show("Ошибка соединения", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error)
));
return;
}
TcpClient tcpClient = connection.Item1;
IModbusMaster modbusMaster = connection.Item2;
while (!e.Cancel)
{
if ((sender as BackgroundWorker).CancellationPending)
{
e.Cancel = true;
break;
}
// Check for connection before trying to read
if (!tcpClient.Connected)
{
// Update UI safely to show disconnection
Invoke(new Action(() =>
MessageBox.Show("Соединение потеряно", "Ошибка соединения", MessageBoxButtons.OK, MessageBoxIcon.Warning)
));
break;
}
try
{
// Perform a time-consuming operation and report progress
ModBusProfile.esp espValues = ModBusProfileHelper.ect_state_page_Read(modbusMaster);
// Update the UI safely
Invoke(new Action(() =>
{
ste1TextBox.Text = espValues.ste[0].ToString();
ste2TextBox.Text = espValues.ste[1].ToString();
ste3TextBox.Text = espValues.ste[2].ToString();
ste4TextBox.Text = espValues.ste[3].ToString();
// Update tables and grids
UpdateDataGrid(rmsDataGridView, rmsDataTable, espValues.rms);
UpdateDataGrid(diapsDataGridView, diapsDataTable, espValues.diaps);
}));
System.Threading.Thread.Sleep(1000);
}
catch (Exception ex)
{
// Handle errors such as connection problems
Invoke(new Action(() =>
MessageBox.Show($"Ошибка Modbus соединения: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error)
));
break;
}
}
// Ensure disposal of resources if necessary
if (tcpClient != null)
{
try { tcpClient.Close(); } catch { }
}
if (modbusMaster != null)
{
try { modbusMaster.Dispose(); } catch { }
}
}
Key Improvements:
Connection Check: Before performing any operations, the connection is checked with tcpClient.Connected. If not connected, it breaks out of the loop and shows a disconnection warning.
Graceful Exit on Disconnection: When the connection drops, the loop breaks, and a message is displayed only once to inform the user, avoiding multiple error message pop-ups.
Use Invoke for UI Updates: It ensures that UI updates occur on the UI thread, preventing cross-thread operation exceptions.
Resource Management: The code ensures that the TcpClient and IModbusMaster objects are properly disposed of or closed when no longer needed, especially before or after exiting the loop due to connection issues.
This setup helps manage the connection state robustly and avoids overwhelming the user with duplicate error messages in case of connection loss.
using NModbus.Device;
using ModBusHelper;
using System;
using System.Data;
using System.Net.Sockets;
using System.Windows.Forms;
using NModbus;
namespace Configurator
{
public partial class ECTStatePageForm : Form
{
CommanderForm CommanderForm;
BackgroundWorker BackgroundWork = new BackgroundWorker();
Timer connectionCheckTimer = new Timer();
DataTable rmsDataTable = new DataTable();
DataTable diapsDataTable = new DataTable();
ModBusProfile ModBusProfileHelper = new ModBusProfile();
ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
private Tuple<TcpClient, IModbusMaster> _connection;
public ECTStatePageForm(CommanderForm CommanderFormInstance, Tuple<TcpClient, IModbusMaster> connection)
{
InitializeComponent();
this.CommanderForm = CommanderFormInstance;
this._connection = connection;
ModBusProfile.esp esp = ExporterLinkerHelper.esp_Default;
ste1TextBox.Text = esp.ste[0].ToString();
ste2TextBox.Text = esp.ste[1].ToString();
ste3TextBox.Text = esp.ste[2].ToString();
ste4TextBox.Text = esp.ste[3].ToString();
rmsDataTable.Columns.Add("Канал", typeof(int));
rmsDataTable.Columns.Add("Действующее значение тока", typeof(float));
rmsDataTable.Rows.Add(new object[] { 0, esp.rms[0] });
rmsDataGridView.DataSource = rmsDataTable;
diapsDataTable.Columns.Add("Канал", typeof(int));
diapsDataTable.Columns.Add("Значения диапазонов", typeof(sbyte));
diapsDataTable.Rows.Add(new object[] { 0, esp.diaps[0] });
diapsDataGridView.DataSource = diapsDataTable;
BackgroundWork.WorkerSupportsCancellation = true;
BackgroundWork.DoWork += new DoWorkEventHandler(BackgroundWork_DoWork);
// Setup connection check timer
connectionCheckTimer.Interval = 1000; // check every second
connectionCheckTimer.Tick += ConnectionCheckTimer_Tick;
connectionCheckTimer.Start();
}
private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
{
var connection = e.Argument as Tuple<TcpClient, IModbusMaster>;
if (connection == null)
{
ShowMessage("Ошибка соединения", "Ошибка");
return;
}
TcpClient tcpClient = connection.Item1;
IModbusMaster modbusMaster = connection.Item2;
while (!e.Cancel)
{
if ((sender as BackgroundWorker).CancellationPending)
{
e.Cancel = true;
break;
}
// Check if still connected
if (!tcpClient.Connected)
{
ShowMessage("Соединение потеряно", "Ошибка соединения");
break;
}
try
{
// Perform a time-consuming operation and report progress
ModBusProfile.esp espValues = ModBusProfileHelper.ect_state_page_Read(modbusMaster);
// Update the UI safely
Invoke(new Action(() =>
{
ste1TextBox.Text = espValues.ste[0].ToString();
ste2TextBox.Text = espValues.ste[1].ToString();
ste3TextBox.Text = espValues.ste[2].ToString();
ste4TextBox.Text = espValues.ste[3].ToString();
// Update tables and grids
UpdateDataGrid(rmsDataGridView, rmsDataTable, espValues.rms);
UpdateDataGrid(diapsDataGridView, diapsDataTable, espValues.diaps);
}));
System.Threading.Thread.Sleep(1000);
}
catch (Exception ex)
{
ShowMessage($"Ошибка Modbus соединения: {ex.Message}", "Ошибка");
break;
}
}
// Dispose of resources safely
DisposeResources(tcpClient, modbusMaster);
}
private void ConnectionCheckTimer_Tick(object sender, EventArgs e)
{
if (_connection != null && _connection.Item1.Connected)
{
if (!BackgroundWork.IsBusy)
{
try
{
BackgroundWork.RunWorkerAsync(argument: _connection);
}
catch (InvalidOperationException ex)
{
ShowMessage($"Невозможно запустить процесс: {ex.Message}", "Ошибка запуска процесса");
}
}
}
else
{
// Connection is down, maybe try to reconnect logic here
if (BackgroundWork.IsBusy)
{
BackgroundWork.CancelAsync();
}
}
}
private void UpdateDataGrid<T>(DataGridView gridView, DataTable table, T[] values)
{
gridView.Invoke(new MethodInvoker(() =>
{
// Adjust row count
while (values.Length > table.Rows.Count)
{
table.Rows.Add(new object[] { table.Rows.Count, default(T) });
}
while (values.Length < table.Rows.Count)
{
table.Rows.RemoveAt(table.Rows.Count - 1);
}
// Update values
for (int i = 0; i < values.Length; i++)
{
table.Rows[i][1] = values[i];
}
gridView.DataSource = table;
}));
}
private void ECTStatePageForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (BackgroundWork.WorkerSupportsCancellation)
{
BackgroundWork.CancelAsync();
}
connectionCheckTimer.Stop();
}
private void ShowMessage(string message, string title)
{
Invoke(new Action(() =>
MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error)));
}
private void DisposeResources(TcpClient tcpClient, IModbusMaster modbusMaster)
{
try { tcpClient.Close(); } catch { }
try { modbusMaster.Dispose(); } catch { }
}
}
}
Key Changes:
Timer for Connection Management: A Timer checks the connection status every second (1000 ms). It also checks whether the background worker is running and controls its execution based on the connection status.
Restart Background Worker: If the connection is detected as reestablished and the worker is not busy, the worker is restarted to resume operations.
ShowMessage Method: A helper method to safely display messages using Invoke.
Connection Management on Timer Tick: The logic in ConnectionCheckTimer_Tick ensures the background worker restarts only when the connection is active, ensuring smooth operation without continuous error messages during disconnects.
This implementation provides robust, automatic management of network connectivity and background operations with improved user experience.
using NModbus.Device;
using ModBusHelper;
using System;
using System.Data;
using System.Net.Sockets;
using System.Windows.Forms;
using NModbus;
namespace Configurator
{
public partial class ECTStatePageForm : Form
{
CommanderForm CommanderForm;
BackgroundWorker BackgroundWork = new BackgroundWorker();
Timer connectionCheckTimer = new Timer();
DataTable rmsDataTable = new DataTable();
DataTable diapsDataTable = new DataTable();
ModBusProfile ModBusProfileHelper = new ModBusProfile();
ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
private Tuple<TcpClient, IModbusMaster> _connection;
public ECTStatePageForm(CommanderForm CommanderFormInstance, Tuple<TcpClient, IModbusMaster> connection)
{
InitializeComponent();
this.CommanderForm = CommanderFormInstance;
this._connection = connection;
ModBusProfile.esp esp = ExporterLinkerHelper.esp_Default;
ste1TextBox.Text = esp.ste[0].ToString();
ste2TextBox.Text = esp.ste[1].ToString();
ste3TextBox.Text = esp.ste[2].ToString();
ste4TextBox.Text = esp.ste[3].ToString();
rmsDataTable.Columns.Add("Канал", typeof(int));
rmsDataTable.Columns.Add("Действующее значение тока", typeof(float));
rmsDataTable.Rows.Add(new object[] { 0, esp.rms[0] });
rmsDataGridView.DataSource = rmsDataTable;
diapsDataTable.Columns.Add("Канал", typeof(int));
diapsDataTable.Columns.Add("Значения диапазонов", typeof(sbyte));
diapsDataTable.Rows.Add(new object[] { 0, esp.diaps[0] });
diapsDataGridView.DataSource = diapsDataTable;
BackgroundWork.WorkerSupportsCancellation = true;
BackgroundWork.DoWork += new DoWorkEventHandler(BackgroundWork_DoWork);
// Setup connection check timer
connectionCheckTimer.Interval = 1000; // check every second
connectionCheckTimer.Tick += ConnectionCheckTimer_Tick;
connectionCheckTimer.Start();
}
private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
{
var connection = e.Argument as Tuple<TcpClient, IModbusMaster>;
if (connection == null)
{
ShowMessage("Ошибка соединения", "Ошибка");
return;
}
TcpClient tcpClient = connection.Item1;
IModbusMaster modbusMaster = connection.Item2;
while (!e.Cancel)
{
if ((sender as BackgroundWorker).CancellationPending)
{
e.Cancel = true;
break;
}
// Check if still connected
if (!tcpClient.Connected)
{
ShowMessage("Соединение потеряно", "Ошибка соединения");
break;
}
try
{
// Perform a time-consuming operation and report progress
ModBusProfile.esp espValues = ModBusProfileHelper.ect_state_page_Read(modbusMaster);
// Update the UI safely
Invoke(new Action(() =>
{
ste1TextBox.Text = espValues.ste[0].ToString();
ste2TextBox.Text = espValues.ste[1].ToString();
ste3TextBox.Text = espValues.ste[2].ToString();
ste4TextBox.Text = espValues.ste[3].ToString();
// Update tables and grids
UpdateDataGrid(rmsDataGridView, rmsDataTable, espValues.rms);
UpdateDataGrid(diapsDataGridView, diapsDataTable, espValues.diaps);
}));
System.Threading.Thread.Sleep(1000);
}
catch (Exception ex)
{
ShowMessage($"Ошибка Modbus соединения: {ex.Message}", "Ошибка");
break;
}
}
DisposeResources(tcpClient, modbusMaster);
}
private void ConnectionCheckTimer_Tick(object sender, EventArgs e)
{
if (_connection != null && _connection.Item1.Connected)
{
if (!BackgroundWork.IsBusy)
{
try
{
BackgroundWork.RunWorkerAsync(argument: _connection);
}
catch (InvalidOperationException ex)
{
ShowMessage($"Невозможно запустить процесс: {ex.Message}", "Ошибка запуска процесса");
}
}
}
else if (!BackgroundWork.CancellationPending)
{
// Request cancellation if connection goes down
BackgroundWork.CancelAsync();
}
}
private void UpdateDataGrid<T>(DataGridView gridView, DataTable table, T[] values)
{
gridView.Invoke(new MethodInvoker(() =>
{
// Adjust row count
while (values.Length > table.Rows.Count)
{
table.Rows.Add(new object[] { table.Rows.Count, default(T) });
}
while (values.Length < table.Rows.Count)
{
table.Rows.RemoveAt(table.Rows.Count - 1);
}
// Update values
for (int i = 0; i < values.Length; i++)
{
table.Rows[i][1] = values[i];
}
gridView.DataSource = table;
}));
}
private void ECTStatePageForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (BackgroundWork.WorkerSupportsCancellation)
{
BackgroundWork.CancelAsync();
}
connectionCheckTimer.Stop();
}
private void ShowMessage(string message, string title)
{
Invoke(new Action(() =>
MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error)));
}
private void DisposeResources(TcpClient tcpClient, IModbusMaster modbusMaster)
{
try { tcpClient.Close(); } catch { }
try { modbusMaster.Dispose(); } catch { }
}
}
}
Key Updates:
Connection Check: The connection status is checked every second using the Timer.
Worker Restart Logic: If the connection is active and the worker is not running, the code attempts to start the worker.
Cancellation of Background Worker: When the connection is down, the worker is cancelled to ensure it stops execution gracefully without throwing errors.
Resource Disposal: DisposeResources will try to close and dispose of the TcpClient and IModbusMaster in a catch-less try block to mitigate any potential exceptions.
This approach should help the form recognize when the connection is reestablished and restart the BackgroundWorker to begin its operations once again. Make sure you have proper exception handling and resource management to deal with network fluctuations effectively.
public partial class CommanderForm : Form
{
public event Action<Tuple<TcpClient, IModbusMaster>> ConnectionStarted;
public event Action ConnectionStopped;
private Tuple<TcpClient, IModbusMaster> _connection;
private void ConnectionStartButton_Click(object sender, EventArgs e)
{
// Existing code to start the connection...
try
{
_connection = ConnectionManager.OpenConnection(boardIP, modBusPort);
// Notify observers that the connection has started
ConnectionStarted?.Invoke(_connection);
CurrentConnectionStateTextBox.Text = "Подключено";
CurrentConnectionStateTextBox.ForeColor = Color.Green;
}
catch (Exception ex)
{
CurrentConnectionStateTextBox.ForeColor = Color.Red;
CurrentConnectionStateTextBox.Text = "Ошибка";
MessageBox.Show("Ошибка соединения: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ConnectionStopButton_Click(object sender, EventArgs e)
{
try
{
if (_connection != null)
{
_connection.Item1.Close();
_connection.Item2.Dispose();
_connection = null;
// Notify observers that the connection has stopped
ConnectionStopped?.Invoke();
CurrentConnectionStateTextBox.Text = "Отключено";
CurrentConnectionStateTextBox.ForeColor = Color.Red;
}
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при отключении: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
2. Subscribe ECTStatePageForm to Connection Events
In the ECTStatePageForm constructor, subscribe to these events and handle them appropriately.
Events: CommanderForm raises ConnectionStarted and ConnectionStopped events to notify other components about the connection status.
Event Handlers: ECTStatePageForm subscribes to these events to manage its _connection object and control the BackgroundWorker.
Direct Triggering: When a connection is successfully established in the CommanderForm, it will notify the ECTStatePageForm, ensuring that the background worker starts processing with the new connection.
By using events and direct event handling, we ensure that each form can react immediately and appropriately to any changes in connection state managed elsewhere in the application. This approach provides a robust mechanism for shared connection management across forms and components.
private Tuple<TcpClient, IModbusMaster> _connection;
private Timer connectionCheckTimer;
private static CommanderForm commanderFormInstance;
public static CommanderForm FormInstance;
private static ECTStatePageForm ectStatePageFormInstance;
private static SWRCTStatePageForm swrctStatePageFormInstance;
private static JournalRecordForm journalRecordFormInstance;
public CommanderForm()
{
InitializeComponent();
FormInstance = this;
// Initialize connection check timer
connectionCheckTimer = new Timer();
connectionCheckTimer.Interval = 1000; // Check every second
connectionCheckTimer.Tick += ConnectionCheckTimer_Tick;
CurrentConnectionStateTextBox.Text = "Отключено";
CurrentConnectionStateTextBox.ForeColor = Color.Red;
}
public static CommanderForm GetInstance()
{
if (commanderFormInstance == null || commanderFormInstance.IsDisposed)
{
commanderFormInstance = new CommanderForm();
}
return commanderFormInstance;
}
private void ConnectionStartButton_Click(object sender, EventArgs e)
{
int modBusPort;
string boardIP;
if (BoardIPTextBox.Text != "")
{
boardIP = BoardIPTextBox.Text;
}
else
{
MessageBox.Show("Введите IP адрес устройства.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Attempt to retrieve and parse the ModBus port
try
{
modBusPort = int.Parse(ModBusPortTextBox.Text);
}
catch (FormatException)
{
MessageBox.Show("Неправильный формат номера порта. Пожалуйста введите целое число.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
catch (ArgumentNullException)
{
MessageBox.Show("Введите номер порта ModBus.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CurrentConnectionStateTextBox.ForeColor = Color.DarkGray;
CurrentConnectionStateTextBox.Text = "Подключение...";
try
{
_connection = ConnectionManager.OpenConnection(boardIP, modBusPort);
}
catch (ArgumentException ex)
{
CurrentConnectionStateTextBox.ForeColor = Color.Red;
CurrentConnectionStateTextBox.Text = "Ошибка";
MessageBox.Show("Ошибка ввода: " + ex.Message);
return;
}
catch (InvalidOperationException ex)
{
CurrentConnectionStateTextBox.ForeColor = Color.Red;
CurrentConnectionStateTextBox.Text = "Ошибка";
MessageBox.Show("Ошибка соединения: " + ex.Message);
return;
}
CurrentConnectionStateTextBox.Text = "Подключено";
CurrentConnectionStateTextBox.ForeColor = Color.Green;
// Start the connection check timer
connectionCheckTimer.Start();
}
private void ConnectionStopButton_Click(object sender, EventArgs e)
{
try
{
if (ConnectionManager.IsConnectionActive())
{
ConnectionManager.CloseConnection();
}
connectionCheckTimer.Stop();
CurrentConnectionStateTextBox.Text = "Отключено";
CurrentConnectionStateTextBox.ForeColor = Color.Red;
}
catch (Exception ex)
{
MessageBox.Show("Ошибка при отключении: " + ex.Message, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void ConnectionCheckTimer_Tick(object sender, EventArgs e)
{
if (_connection != null && _connection.Item1.Connected)
{
UpdateConnectionStateTextBox("Подключено", Color.Green);
}
else
{
UpdateConnectionStateTextBox("Отключено", Color.Red);
}
}
private void UpdateConnectionStateTextBox(string state, Color color)
{
if (CurrentConnectionStateTextBox.InvokeRequired)
{
CurrentConnectionStateTextBox.Invoke(new Action(() =>
{
CurrentConnectionStateTextBox.Text = state;
CurrentConnectionStateTextBox.ForeColor = color;
}));
}
else
{
CurrentConnectionStateTextBox.Text = state;
CurrentConnectionStateTextBox.ForeColor = color;
}
}
private void WriteValuesButton_Click(object sender, EventArgs e)
{
bool adminRights = false;
try
{
// Check for admin rights
try
{
if ((LoginComboBox.SelectedItem.ToString() == "Администратор") && (PasswordTextBox.Text == "admin"))
{
adminRights = true;
}
}
catch (NullReferenceException)
{
MessageBox.Show("Выберите тип пользователя.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// Ensure settings are not empty
if ((Database.GeneralSettings_TextFormat.cmns.nAchans != "") && (Database.GeneralSettings_TextFormat.cmns.nDiap != ""))
{
try
{
ExporterLinkerHelper.WriteSettings(Database.GeneralSettings_TextFormat, adminRights, _connection);
write_SettingsTextBox.ForeColor = Color.Green;
write_SettingsTextBox.Text = "ОК";
}
catch (Exception ex)
{
write_SettingsTextBox.ForeColor = Color.Red;
write_SettingsTextBox.Text = "Ошибка";
MessageBox.Show($"При записи параметров возникла ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
write_SettingsTextBox.ForeColor = Color.Red;
write_SettingsTextBox.Text = "Ошибка";
MessageBox.Show("Не указаны параметры для записи. Пожалуйста, проверьте конфигурацию.", "Предупреждение", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
catch (Exception ex)
{
write_SettingsTextBox.ForeColor = Color.Red;
write_SettingsTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void ReadValuesButton_Click(object sender, EventArgs e)
{
try
{
// Attempt to read general settings
try
{
Database.GeneralSettings_TextFormat = ExporterLinkerHelper.get_GeneralSettings_Text(_connection);
read_SettingsTextBox.ForeColor = Color.Green;
read_SettingsTextBox.Text = "ОК";
}
catch (Exception ex)
{
read_SettingsTextBox.ForeColor = Color.Red;
read_SettingsTextBox.Text = "Ошибка";
MessageBox.Show($"При чтении параметров возникла ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
catch (Exception ex)
{
read_SettingsTextBox.ForeColor = Color.Red;
read_SettingsTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void upload_firmware_defaultButton_Click(object sender, EventArgs e)
{
try
{
int groupsIdentificatorsAccumulator = 0x00;
int cmnsIdentificator = 0x01;
int netsIdentificator = 0x02;
int timeIdentificator = 0x04;
int synsIdentificator = 0x08;
int swrcsIdentificator = 0x10;
int measIdentificator = 0x20;
if (upload_firmware_CheckBox1.Checked)
{
groupsIdentificatorsAccumulator |= cmnsIdentificator;
}
if (upload_firmware_CheckBox2.Checked)
{
groupsIdentificatorsAccumulator |= netsIdentificator;
}
if (upload_firmware_CheckBox3.Checked)
{
groupsIdentificatorsAccumulator |= timeIdentificator;
}
if (upload_firmware_CheckBox4.Checked)
{
groupsIdentificatorsAccumulator |= synsIdentificator;
}
if (upload_firmware_CheckBox5.Checked)
{
groupsIdentificatorsAccumulator |= swrcsIdentificator;
}
if (upload_firmware_CheckBox6.Checked)
{
groupsIdentificatorsAccumulator |= measIdentificator;
}
ushort bitMask = Convert.ToUInt16(groupsIdentificatorsAccumulator);
upload_firmware_defaultTextBox1.Text = $"0x{bitMask.ToString("X2")}";
try
{
WriteSingleRegisterRequestResponse response = CommandsHelper.upload_firmware_default(_connection.Item2, bitMask);
if ($"0x{response.Data[0].ToString("X2")}" == $"0x{bitMask.ToString("X2")}")
{
upload_firmware_defaultTextBox2.ForeColor = Color.Green;
upload_firmware_defaultTextBox2.Text = "ОК";
}
else
{
upload_firmware_defaultTextBox2.ForeColor = Color.Red;
upload_firmware_defaultTextBox2.Text = "Ошибка";
}
}
catch (Exception modbusException)
{
upload_firmware_defaultTextBox2.ForeColor = Color.Red;
upload_firmware_defaultTextBox2.Text = "Ошибка";
MessageBox.Show($"Ошибка при загрузке параметров: {modbusException.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
catch (Exception ex)
{
upload_firmware_defaultTextBox2.ForeColor = Color.Red;
upload_firmware_defaultTextBox2.Text = "Ошибка";
MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void upload_settingsButton_Click(object sender, EventArgs e)
{
try
{
WriteSingleRegisterRequestResponse response = CommandsHelper.upload_settings(_connection.Item2, 0x00);
if (response.Data[0] == 0)
{
try
{
if (upload_settingsCheckBox.Checked)
{
WriteSingleRegisterRequestResponse responseReset = CommandsHelper.reset_ect(_connection.Item2);
if ($"0x{responseReset.Data[0].ToString("X4")}" == "0x00FF")
{
upload_settingsTextBox.ForeColor = Color.Green;
upload_settingsTextBox.Text = "ОК";
}
}
else
{
upload_settingsTextBox.ForeColor = Color.Red;
upload_settingsTextBox.Text = "Ошибка";
}
}
catch (Exception modbusException)
{
upload_settingsTextBox.ForeColor = Color.Red;
upload_settingsTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка при загрузке параметров: {modbusException.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
catch (Exception ex)
{
upload_settingsTextBox.ForeColor = Color.Red;
upload_settingsTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка при загрузке параметров: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void get_last_settings_recordButton_Click(object sender, EventArgs e)
{
// Perform Modbus operation
bool[] lastSettingsRecordBoolArray;
byte lastSettingsRecord;
try
{
lastSettingsRecordBoolArray = CommandsHelper.get_last_settings_record(_connection.Item2);
lastSettingsRecord = ModbusFunctionsHelper.ConvertBoolArrayToByte(lastSettingsRecordBoolArray);
if ($"0x{lastSettingsRecord.ToString("X2")}" == "0x00")
{
get_last_settings_recordTextBox.ForeColor = Color.Green;
get_last_settings_recordTextBox.Text = "ОК";
}
else
{
get_last_settings_recordTextBox.ForeColor = Color.Red;
get_last_settings_recordTextBox.Text = "Ошибка";
}
}
catch (Exception ex)
{
get_last_settings_recordTextBox.ForeColor = Color.Red;
get_last_settings_recordTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка получения статуса последней записи настроек: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void reset_ectButton_Click(object sender, EventArgs e)
{
// Perform Modbus operation to reset ect
try
{
WriteSingleRegisterRequestResponse response = CommandsHelper.reset_ect(_connection.Item2);
if ($"0x{response.Data[0].ToString("X4")}" == "0x00FF")
{
reset_ectTextBox.ForeColor = Color.Green;
reset_ectTextBox.Text = "ОК";
}
else
{
reset_ectTextBox.ForeColor = Color.Red;
reset_ectTextBox.Text = "Ошибка";
}
}
catch (Exception ex)
{
reset_ectTextBox.ForeColor = Color.Red;
reset_ectTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка перезагрузки ЭТТ: {ex.Message}", "Ошибка ModBus соединения", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void nulify_swrcButton_Click(object sender, EventArgs e)
{
bool adminRights = false;
try
{
// Try to determine if the user has admin rights
try
{
if ((LoginComboBox.SelectedItem?.ToString() == "Администратор") && (PasswordTextBox.Text == "admin"))
{
adminRights = true;
}
}
catch (NullReferenceException)
{
nulify_swrcTextBox.ForeColor = Color.Red;
nulify_swrcTextBox.Text = "Ошибка";
MessageBox.Show("Выберите тип пользователя.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (adminRights)
{
try
{
// Perform Modbus operation
WriteSingleRegisterRequestResponse response = CommandsHelper.nulify_swrc(_connection.Item2);
if ($"0x{response.Data[0].ToString("X4")}" == "0x00FF")
{
nulify_swrcTextBox.ForeColor = Color.Green;
nulify_swrcTextBox.Text = "ОК";
}
else
{
nulify_swrcTextBox.ForeColor = Color.Red;
nulify_swrcTextBox.Text = "Ошибка";
}
}
catch (Exception modbusException)
{
nulify_swrcTextBox.ForeColor = Color.Red;
nulify_swrcTextBox.Text = "Ошибка";
MessageBox.Show($"При обнулении данных расхода ресурса произошла ошибка: {modbusException.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
nulify_swrcTextBox.ForeColor = Color.Red;
nulify_swrcTextBox.Text = "Ошибка";
MessageBox.Show("Для выполнения команды требуются права Администратора.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
catch (Exception ex)
{
nulify_swrcTextBox.ForeColor = Color.Red;
nulify_swrcTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void clear_swrc_journalButton_Click(object sender, EventArgs e)
{
bool adminRights = false;
try
{
// Determine if the user has admin rights
try
{
if ((LoginComboBox.SelectedItem?.ToString() == "Администратор") && (PasswordTextBox.Text == "admin"))
{
adminRights = true;
}
}
catch (NullReferenceException)
{
MessageBox.Show("Выберите тип пользователя.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (adminRights)
{
try
{
bool clearJournal = clear_swrc_journalCheckBox.Checked;
WriteSingleRegisterRequestResponse response = CommandsHelper.clear_swrc_journal(_connection.Item2, clearJournal);
string checkString = "0x00";
if (clearJournal)
{
checkString = "0x01";
}
if ($"0x{response.Data[0].ToString("X2")}" == checkString)
{
clear_swrc_journalTextBox.ForeColor = Color.Green;
clear_swrc_journalTextBox.Text = "ОК";
}
else
{
clear_swrc_journalTextBox.ForeColor = Color.Red;
clear_swrc_journalTextBox.Text = "Ошибка";
}
}
catch (Exception modbusEx)
{
clear_swrc_journalTextBox.ForeColor = Color.Red;
clear_swrc_journalTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка при очистке журнала СКРВ: {modbusEx.Message}", "Ошибка ModBus соединения", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
else
{
clear_swrc_journalTextBox.ForeColor = Color.Red;
clear_swrc_journalTextBox.Text = "Ошибка";
MessageBox.Show("Для выполнения команды требуются права Администратора.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
}
catch (Exception ex)
{
clear_swrc_journalTextBox.ForeColor = Color.Red;
clear_swrc_journalTextBox.Text = "Ошибка";
MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void ECTStatePageButton_Click(object sender, EventArgs e)
{
// Check if an instance is already open or disposed
if (ectStatePageFormInstance == null || ectStatePageFormInstance.IsDisposed)
{
// Create and show a new instance
ectStatePageFormInstance = new ECTStatePageForm(FormInstance, _connection);
ectStatePageFormInstance.Show();
}
else
{
// If instance exists, bring it to the front
ectStatePageFormInstance.BringToFront();
ectStatePageFormInstance.Focus();
}
}
private void SWRCTStatePageButton_Click(object sender, EventArgs e)
{
// Check if an instance is already open or disposed
if (swrctStatePageFormInstance == null || ectStatePageFormInstance.IsDisposed)
{
// Create and show a new instance
swrctStatePageFormInstance = new SWRCTStatePageForm(FormInstance, _connection);
swrctStatePageFormInstance.Show();
}
else
{
// If instance exists, bring it to the front
swrctStatePageFormInstance.BringToFront();
swrctStatePageFormInstance.Focus();
}
}
private void ReadJournalButton_Click(object sender, EventArgs e)
{
// Check if an instance is already open or disposed
if (journalRecordFormInstance == null || journalRecordFormInstance.IsDisposed)
{
// Create and show a new instance
journalRecordFormInstance = new JournalRecordForm(FormInstance, Database.Filtered_Journal_Records, _connection);
journalRecordFormInstance.Show();
}
else
{
// If instance exists, bring it to the front
journalRecordFormInstance.BringToFront();
journalRecordFormInstance.Focus();
}
}
}
Events Defined: ConnectionStarted and ConnectionStopped events are declared to notify any interested subscribers about changes in connection state.
Event Invocation: These events are triggered in ConnectionStartButton_Click and ConnectionStopButton_Click methods, ensuring other forms know when the connection is established or closed.
Timer Check: Within ConnectionCheckTimer_Tick, we ensure that the ConnectionStopped event is called if the connection is lost.
Using the Events in Other Forms:
For the ECTStatePageForm, subscribe to these events to manage your forms’ operations accordingly. Here is an example:
csharp
public class ECTStatePageForm : Form
{
private Tuple<TcpClient, IModbusMaster> _connection;
private BackgroundWorker backgroundWorker = new BackgroundWorker();
public ECTStatePageForm(CommanderForm commanderForm)
{
InitializeComponent();
// Subscribe to connection events
commanderForm.ConnectionStarted += OnConnectionStarted;
commanderForm.ConnectionStopped += OnConnectionStopped;
// Setup background worker and other initializations...
}
private void OnConnectionStarted(Tuple<TcpClient, IModbusMaster> connection)
{
_connection = connection;
if (!backgroundWorker.IsBusy)
{
backgroundWorker.RunWorkerAsync(_connection);
}
}
private void OnConnectionStopped()
{
if (backgroundWorker.IsBusy)
{
backgroundWorker.CancelAsync();
}
}
// Additional method implementations for BackgroundWorker and data operations...
}
This ensures that the ECTStatePageForm and any other form subscribing to the connection events will automatically start and stop operations based on the connection state, providing a more synchronized and less error-prone application experience.
private BackgroundWorker BackgroundWork = new BackgroundWorker();
Timer connectionCheckTimer = new Timer();
DataTable rmsDataTable = new DataTable();
DataTable diapsDataTable = new DataTable();
ModBusProfile ModBusProfileHelper = new ModBusProfile();
ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
private Tuple<TcpClient, IModbusMaster> _connection;
public ECTStatePageForm(CommanderForm CommanderFormInstance, Tuple<TcpClient, IModbusMaster> connection)
{
InitializeComponent();
this.CommanderForm = CommanderFormInstance;
this._connection = connection;
ModBusProfile.esp esp = ExporterLinkerHelper.esp_Default;
ste1TextBox.Text = esp.ste[0].ToString();
ste2TextBox.Text = esp.ste[1].ToString();
ste3TextBox.Text = esp.ste[2].ToString();
ste4TextBox.Text = esp.ste[3].ToString();
rmsDataTable.Columns.Add("Канал", typeof(int));
rmsDataTable.Columns.Add("Действующее значение тока", typeof(float));
rmsDataTable.Rows.Add(new object[] { 0, esp.rms[0] });
rmsDataGridView.DataSource = rmsDataTable;
diapsDataTable.Columns.Add("Канал", typeof(int));
diapsDataTable.Columns.Add("Значения диапазонов", typeof(sbyte));
diapsDataTable.Rows.Add(new object[] { 0, esp.diaps[0] });
diapsDataGridView.DataSource = diapsDataTable;
BackgroundWork.WorkerSupportsCancellation = true;
BackgroundWork.DoWork += new DoWorkEventHandler(BackgroundWork_DoWork);
// Setup connection check timer
connectionCheckTimer.Interval = 1000; // check every second
connectionCheckTimer.Tick += ConnectionCheckTimer_Tick;
connectionCheckTimer.Start();
}
private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
{
var connection = e.Argument as Tuple<TcpClient, IModbusMaster>;
if (connection == null)
{
Invoke(new Action(() =>
MessageBox.Show("Ошибка соединения", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error)
));
return;
}
TcpClient tcpClient = connection.Item1;
IModbusMaster modbusMaster = connection.Item2;
while (!e.Cancel)
{
if ((sender as BackgroundWorker).CancellationPending)
{
e.Cancel = true;
break;
}
// Check for connection before trying to read
if (!tcpClient.Connected)
{
// Update UI safely to show disconnection
Invoke(new Action(() =>
MessageBox.Show("Соединение потеряно", "Ошибка соединения", MessageBoxButtons.OK, MessageBoxIcon.Warning)
));
break;
}
try
{
// Perform a time consuming operation and report progress.
ModBusProfile.esp espValues = ModBusProfileHelper.ect_state_page_Read(modbusMaster);
// Update the UI safely
Invoke(new Action(() =>
{
ste1TextBox.Text = espValues.ste[0].ToString();
ste2TextBox.Text = espValues.ste[1].ToString();
ste3TextBox.Text = espValues.ste[2].ToString();
ste4TextBox.Text = espValues.ste[3].ToString();
// Update tables and grids
UpdateDataGrid(rmsDataGridView, rmsDataTable, espValues.rms);
UpdateDataGrid(diapsDataGridView, diapsDataTable, espValues.diaps);
}));
System.Threading.Thread.Sleep(1000);
}
catch (Exception ex)
{
// Handle errors such as connection problems
Invoke(new Action(() =>
MessageBox.Show($"Ошибка Modbus соединения: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error)
));
break;
}
}
}
private void ConnectionCheckTimer_Tick(object sender, EventArgs e)
{
if (_connection != null && _connection.Item1.Connected)
{
if (!BackgroundWork.IsBusy)
{
try
{
BackgroundWork.RunWorkerAsync(argument: _connection);
}
catch (InvalidOperationException ex)
{
Invoke(new Action(() =>
MessageBox.Show($"Невозможно запустить процесс: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error)
));
}
}
}
else if (!BackgroundWork.CancellationPending)
{
// Request cancellation if connection goes down
BackgroundWork.CancelAsync();
}
}
private void UpdateDataGrid<T>(DataGridView gridView, DataTable table, T[] values)
{
gridView.Invoke(new MethodInvoker(() =>
{
// Adjust row count
while (values.Length > table.Rows.Count)
{
table.Rows.Add(new object[] { table.Rows.Count, default(T) });
}
while (values.Length < table.Rows.Count)
{
table.Rows.RemoveAt(table.Rows.Count - 1);
}
// Update values
for (int i = 0; i < values.Length; i++)
{
table.Rows[i][1] = values[i];
}
gridView.DataSource = table;
}));
}
private void ECTStatePageForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (BackgroundWork.WorkerSupportsCancellation)
{
BackgroundWork.CancelAsync();
}
}
}
}
using NModbus.Device;
using ModBusHelper;
using System;
using System.Data;
using System.Drawing;
using System.Net.Sockets;
using System.Windows.Forms;
using NModbus;
namespace Configurator
{
public partial class ECTStatePageForm : Form
{
CommanderForm CommanderForm;
private BackgroundWorker BackgroundWork = new BackgroundWorker();
private Timer connectionCheckTimer = new Timer();
DataTable rmsDataTable = new DataTable();
DataTable diapsDataTable = new DataTable();
ModBusProfile ModBusProfileHelper = new ModBusProfile();
ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
private Tuple<TcpClient, IModbusMaster> _connection;
public ECTStatePageForm(CommanderForm CommanderFormInstance)
{
InitializeComponent();
this.CommanderForm = CommanderFormInstance;
// Subscribe to events from the CommanderForm
CommanderForm.ConnectionStarted += OnConnectionStarted;
CommanderForm.ConnectionStopped += OnConnectionStopped;
ModBusProfile.esp esp = ExporterLinkerHelper.esp_Default;
ste1TextBox.Text = esp.ste[0].ToString();
ste2TextBox.Text = esp.ste[1].ToString();
ste3TextBox.Text = esp.ste[2].ToString();
ste4TextBox.Text = esp.ste[3].ToString();
rmsDataTable.Columns.Add("Канал", typeof(int));
rmsDataTable.Columns.Add("Действующее значение тока", typeof(float));
rmsDataTable.Rows.Add(new object[] { 0, esp.rms[0] });
rmsDataGridView.DataSource = rmsDataTable;
diapsDataTable.Columns.Add("Канал", typeof(int));
diapsDataTable.Columns.Add("Значения диапазонов", typeof(sbyte));
diapsDataTable.Rows.Add(new object[] { 0, esp.diaps[0] });
diapsDataGridView.DataSource = diapsDataTable;
BackgroundWork.WorkerSupportsCancellation = true;
BackgroundWork.DoWork += new DoWorkEventHandler(BackgroundWork_DoWork);
}
private void OnConnectionStarted(Tuple<TcpClient, IModbusMaster> connection)
{
_connection = connection;
if (!BackgroundWork.IsBusy)
{
BackgroundWork.RunWorkerAsync(argument: _connection);
}
}
private void OnConnectionStopped()
{
if (BackgroundWork.IsBusy)
{
BackgroundWork.CancelAsync();
}
}
private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
{
var connection = e.Argument as Tuple<TcpClient, IModbusMaster>;
if (connection == null)
{
Invoke(new Action(() =>
MessageBox.Show("Ошибка соединения", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error)
));
return;
}
TcpClient tcpClient = connection.Item1;
IModbusMaster modbusMaster = connection.Item2;
while (!e.Cancel)
{
if ((sender as BackgroundWorker).CancellationPending)
{
e.Cancel = true;
break;
}
if (!tcpClient.Connected)
{
Invoke(new Action(() =>
MessageBox.Show("Соединение потеряно", "Ошибка соединения", MessageBoxButtons.OK, MessageBoxIcon.Warning)
));
break;
}
try
{
ModBusProfile.esp espValues = ModBusProfileHelper.ect_state_page_Read(modbusMaster);
Invoke(new Action(() =>
{
ste1TextBox.Text = espValues.ste[0].ToString();
ste2TextBox.Text = espValues.ste[1].ToString();
ste3TextBox.Text = espValues.ste[2].ToString();
ste4TextBox.Text = espValues.ste[3].ToString();
UpdateDataGrid(rmsDataGridView, rmsDataTable, espValues.rms);
UpdateDataGrid(diapsDataGridView, diapsDataTable, espValues.diaps);
}));
System.Threading.Thread.Sleep(1000);
}
catch (Exception ex)
{
Invoke(new Action(() =>
MessageBox.Show($"Ошибка Modbus соединения: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error)
));
break;
}
}
}
private void UpdateDataGrid<T>(DataGridView gridView, DataTable table, T[] values)
{
gridView.Invoke(new MethodInvoker(() =>
{
while (values.Length > table.Rows.Count)
{
table.Rows.Add(new object[] { table.Rows.Count, default(T) });
}
while (values.Length < table.Rows.Count)
{
table.Rows.RemoveAt(table.Rows.Count - 1);
}
for (int i = 0; i < values.Length; i++)
{
table.Rows[i][1] = values[i];
}
gridView.DataSource = table;
}));
}
private void ECTStatePageForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (BackgroundWork.WorkerSupportsCancellation)
{
BackgroundWork.CancelAsync();
}
CommanderForm.ConnectionStarted -= OnConnectionStarted;
CommanderForm.ConnectionStopped -= OnConnectionStopped;
}
}
}
Explanation of the Changes:
Subscribe to Events: The form's constructor subscribes to ConnectionStarted and ConnectionStopped events from CommanderForm, allowing it to respond to changes in connection status.
Event Handlers: Handlers (OnConnectionStarted and OnConnectionStopped) update the form's _connection variable and control the BackgroundWorker's execution.
Safe UI Calls: Use Invoke for any UI updates or messages to ensure you're operating on the UI thread.
Unsubscribe in Cleanup: It's a good practice to unsubscribe from events in the FormClosing event to avoid potential memory leaks or attempts to handle events after the form is closed.
This setup ensures that your ECTStatePageForm will appropriately react to the connection's lifecycle and update its data processing logic to align with the current state of the TCP connection.
BackgroundWorker BackgroundWork = new BackgroundWorker();
DataTable cntvDataTable = new DataTable();
ModBusProfile ModBusProfileHelper = new ModBusProfile();
ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
public SWRCTStatePageForm(CommanderForm CommanderFormInstance, Tuple<TcpClient, IModbusMaster> connection)
{
InitializeComponent();
this.CommanderForm = CommanderFormInstance;
ModBusProfile.ssp ssp = ExporterLinkerHelper.ssp_Default;
ste1TextBox.Text = ssp.ste[0].ToString();
ste2TextBox.Text = ssp.ste[1].ToString();
ste3TextBox.Text = ssp.ste[2].ToString();
ste4TextBox.Text = ssp.ste[3].ToString();
cntvDataTable.Columns.Add("Канал", typeof(int));
cntvDataTable.Columns.Add("Накопленное значение расхода ресурса (%)", typeof(float));
cntvDataTable.Columns.Add("Количество отключений", typeof(ushort));
cntvDataTable.Columns.Add("Количество включений", typeof(ushort));
cntvDataTable.Rows.Add(new object[] { 0, ssp.cntv[0].Racc, ssp.cntv[0].ofcnt, ssp.cntv[0].oNacnt });
cntvDataGridView.DataSource = cntvDataTable;
BackgroundWork.WorkerSupportsCancellation = true;
BackgroundWork.DoWork += new DoWorkEventHandler(BackgroundWork_DoWork);
if (BackgroundWork.IsBusy != true)
{
try
{
// Start background work
try
{
BackgroundWork.RunWorkerAsync(argument: connection);
}
catch (InvalidOperationException ex)
{
MessageBox.Show($"Невозможно запустить процесс: {ex.Message}", "Ошибка запуска процесса", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
catch (Exception ex)
{
MessageBox.Show($"Ошибка: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
{
var connection = e.Argument as Tuple<TcpClient, IModbusMaster>;
if (connection == null)
{
MessageBox.Show("Ошибка соединения", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
TcpClient tcpClient = connection.Item1;
IModbusMaster modbusMaster = connection.Item2;
try
{
while (!e.Cancel)
{
if ((sender as BackgroundWorker).CancellationPending)
{
e.Cancel = true;
break;
}
// Perform a time-consuming operation and report progress.
ModBusProfile.ssp sspValues = ModBusProfileHelper.swrct_state_page_Read(modbusMaster);
// Update TextBox controls with thread safety
ste1TextBox.Invoke(new Action(() => ste1TextBox.Text = sspValues.ste[0].ToString()));
ste2TextBox.Invoke(new Action(() => ste2TextBox.Text = sspValues.ste[1].ToString()));
ste3TextBox.Invoke(new Action(() => ste3TextBox.Text = sspValues.ste[2].ToString()));
ste4TextBox.Invoke(new Action(() => ste4TextBox.Text = sspValues.ste[3].ToString()));
// Ensure cntvDataTable has correct number of rows
cntvDataGridView.Invoke(new MethodInvoker(() => UpdateCntvDataTable(sspValues)));
System.Threading.Thread.Sleep(1000);
}
}
catch (Exception ex)
{
// Log or handle error
MessageBox.Show($"Ошибка Modbus соединения: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void UpdateCntvDataTable(ModBusProfile.ssp sspValues)
{
// Adjust rows count
while (sspValues.cntv.Length > cntvDataTable.Rows.Count)
{
cntvDataTable.Rows.Add(new object[] { cntvDataTable.Rows.Count, 0, 0, 0 });
}
while (sspValues.cntv.Length < cntvDataTable.Rows.Count)
{
cntvDataTable.Rows.RemoveAt(cntvDataTable.Rows.Count - 1);
}
// Update data
for (int z = 0; z < sspValues.cntv.Length; z++)
{
cntvDataTable.Rows[z][1] = sspValues.cntv[z].Racc;
cntvDataTable.Rows[z][2] = sspValues.cntv[z].ofcnt;
cntvDataTable.Rows[z][3] = sspValues.cntv[z].oNacnt;
}
// Set the updated table as the DataSource for the GridView
cntvDataGridView.DataSource = cntvDataTable;
}
private void SWRCTStatePageForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (BackgroundWork.WorkerSupportsCancellation == true)
{
BackgroundWork.CancelAsync();
}
}
}
}
using NModbus.Device;
using ModBusHelper;
using NModbus;
using System;
using System.Data;
using System.Net.Sockets;
using System.Windows.Forms;
namespace Configurator
{
public partial class SWRCTStatePageForm : Form
{
CommanderForm CommanderForm;
private BackgroundWorker BackgroundWork = new BackgroundWorker();
private DataTable cntvDataTable = new DataTable();
private ModBusProfile ModBusProfileHelper = new ModBusProfile();
private ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
private Tuple<TcpClient, IModbusMaster> _connection;
public SWRCTStatePageForm(CommanderForm CommanderFormInstance)
{
InitializeComponent();
this.CommanderForm = CommanderFormInstance;
// Subscribe to events from the CommanderForm
CommanderForm.ConnectionStarted += OnConnectionStarted;
CommanderForm.ConnectionStopped += OnConnectionStopped;
ModBusProfile.ssp ssp = ExporterLinkerHelper.ssp_Default;
ste1TextBox.Text = ssp.ste[0].ToString();
ste2TextBox.Text = ssp.ste[1].ToString();
ste3TextBox.Text = ssp.ste[2].ToString();
ste4TextBox.Text = ssp.ste[3].ToString();
cntvDataTable.Columns.Add("Канал", typeof(int));
cntvDataTable.Columns.Add("Накопленное значение расхода ресурса (%)", typeof(float));
cntvDataTable.Columns.Add("Количество отключений", typeof(ushort));
cntvDataTable.Columns.Add("Количество включений", typeof(ushort));
cntvDataTable.Rows.Add(new object[] { 0, ssp.cntv[0].Racc, ssp.cntv[0].ofcnt, ssp.cntv[0].oNacnt });
cntvDataGridView.DataSource = cntvDataTable;
BackgroundWork.WorkerSupportsCancellation = true;
BackgroundWork.DoWork += new DoWorkEventHandler(BackgroundWork_DoWork);
}
private void OnConnectionStarted(Tuple<TcpClient, IModbusMaster> connection)
{
_connection = connection;
if (!BackgroundWork.IsBusy)
{
BackgroundWork.RunWorkerAsync(argument: _connection);
}
}
private void OnConnectionStopped()
{
if (BackgroundWork.IsBusy)
{
BackgroundWork.CancelAsync();
}
}
private void BackgroundWork_DoWork(object sender, DoWorkEventArgs e)
{
var connection = e.Argument as Tuple<TcpClient, IModbusMaster>;
if (connection == null)
{
Invoke(new Action(() =>
MessageBox.Show("Ошибка соединения", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error)
));
return;
}
TcpClient tcpClient = connection.Item1;
IModbusMaster modbusMaster = connection.Item2;
try
{
while (!e.Cancel)
{
if ((sender as BackgroundWorker).CancellationPending)
{
e.Cancel = true;
break;
}
ModBusProfile.ssp sspValues = ModBusProfileHelper.swrct_state_page_Read(modbusMaster);
Invoke(new Action(() =>
{
ste1TextBox.Text = sspValues.ste[0].ToString();
ste2TextBox.Text = sspValues.ste[1].ToString();
ste3TextBox.Text = sspValues.ste[2].ToString();
ste4TextBox.Text = sspValues.ste[3].ToString();
UpdateCntvDataTable(sspValues);
}));
System.Threading.Thread.Sleep(1000);
}
}
catch (Exception ex)
{
Invoke(new Action(() =>
MessageBox.Show($"Ошибка Modbus соединения: {ex.Message}", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error)
));
}
}
private void UpdateCntvDataTable(ModBusProfile.ssp sspValues)
{
while (sspValues.cntv.Length > cntvDataTable.Rows.Count)
{
cntvDataTable.Rows.Add(new object[] { cntvDataTable.Rows.Count, 0, 0, 0 });
}
while (sspValues.cntv.Length < cntvDataTable.Rows.Count)
{
cntvDataTable.Rows.RemoveAt(cntvDataTable.Rows.Count - 1);
}
for (int z = 0; z < sspValues.cntv.Length; z++)
{
cntvDataTable.Rows[z][1] = sspValues.cntv[z].Racc;
cntvDataTable.Rows[z][2] = sspValues.cntv[z].ofcnt;
cntvDataTable.Rows[z][3] = sspValues.cntv[z].oNacnt;
}
cntvDataGridView.DataSource = cntvDataTable;
}
private void SWRCTStatePageForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (BackgroundWork.WorkerSupportsCancellation)
{
BackgroundWork.CancelAsync();
}
CommanderForm.ConnectionStarted -= OnConnectionStarted;
CommanderForm.ConnectionStopped -= OnConnectionStopped;
}
}
}
Key Elements in the Updated Code:
Subscriptions to Events: The SWRCTStatePageForm subscribes to the ConnectionStarted and ConnectionStopped events from the CommanderForm in its constructor.
Event Handlers: The handlers OnConnectionStarted and OnConnectionStopped manage the starting and stopping of the BackgroundWorker responsible for data processing.
Completeness and Safety: Ensure all UI updates occur on the UI thread with Invoke, and unsubscribe from the events when the form is closing to prevent memory leaks.
This approach ensures that when the connection state changes, the SWRCTStatePageForm can react and manage its background operations accordingly.
CommanderForm CommanderForm;
DataTable JournalRecordsDataTable = new DataTable();
DataTable JournalRecordDataTable = new DataTable();
public JournalRecordForm(CommanderForm CommanderFormInstance, List<ModBusProfile.journal_record> Filtered_Journal_Records, Tuple<TcpClient, IModbusMaster> connection)
{
InitializeComponent();
this.CommanderForm = CommanderFormInstance;
JournalRecordDataTableInitialization();
JournalRecordsDataTableInitialization(Filtered_Journal_Records);
JournalRecordsDataGridView.SelectionChanged += JournalRecordsDataGridView_SelectionChanged;
try
{
Database.Journal_Record = ProfileHelper.journal_record_Read(connection.Item2);
int RecordCounter = 0;
foreach (ModBusProfile.journal_record record in Database.Journal_Record)
{
if (record.hdr.rtype == 0)
{
continue;
}
else if (record.hdr.rtype == 1)
{
if (record.hdr.subtype == 0)
{
JournalRecordsDataTable.Rows.Add(new object[] { RecordCounter, "Отключение выключателя", UnixTimeStampToDateTime((record.hdr.stamp.slo + (record.hdr.stamp.ns * 0.000000001))) });
Database.Filtered_Journal_Records.Add(record);
RecordCounter++;
continue;
}
else if (record.hdr.subtype == 1)
{
JournalRecordsDataTable.Rows.Add(new object[] { RecordCounter, "Включение выключателя", UnixTimeStampToDateTime((record.hdr.stamp.slo + (record.hdr.stamp.ns * 0.000000001))) });
Database.Filtered_Journal_Records.Add(record);
RecordCounter++;
continue;
}
}
else if (record.hdr.rtype == 2)
{
JournalRecordsDataTable.Rows.Add(new object[] { RecordCounter, "Обнуление счетчика ресурса", UnixTimeStampToDateTime((record.hdr.stamp.slo + (record.hdr.stamp.ns * 0.000000001))) });
Database.Filtered_Journal_Records.Add(record);
RecordCounter++;
continue;
}
}
}
catch (Exception modbusEx)
{
MessageBox.Show($"Ошибка получения записей журнала СКРВ: {modbusEx.Message}", "Ошибка ModBus соединения", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
// Unix timestamp is seconds past epoch
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddSeconds(unixTimeStamp).ToLocalTime();
return dateTime;
}
private void JournalRecordsDataTableInitialization(List<ModBusProfile.journal_record> Filtered_Journal_Records)
{
JournalRecordsDataTable.Columns.Add("Номер записи", typeof(int));
JournalRecordsDataTable.Columns.Add("Событие", typeof(string));
JournalRecordsDataTable.Columns.Add("Дата", typeof(DateTime));
foreach (DataColumn Column in JournalRecordsDataTable.Columns)
{
Column.ReadOnly = true;
}
int RecordCounter = 0;
foreach (ModBusProfile.journal_record record in Filtered_Journal_Records)
{
if (record.hdr.rtype == 0)
{
continue;
}
else if (record.hdr.rtype == 1)
{
if (record.hdr.subtype == 0)
{
JournalRecordsDataTable.Rows.Add(new object[] { RecordCounter, "Отключение выключателя", UnixTimeStampToDateTime(record.hdr.stamp.ns) });
RecordCounter++;
continue;
}
else if (record.hdr.subtype == 1)
{
JournalRecordsDataTable.Rows.Add(new object[] { RecordCounter, "Включение выключателя", UnixTimeStampToDateTime(record.hdr.stamp.ns) });
RecordCounter++;
continue;
}
}
else if (record.hdr.rtype == 2)
{
JournalRecordsDataTable.Rows.Add(new object[] { RecordCounter, "Обнуление счетчика ресурса", UnixTimeStampToDateTime(record.hdr.stamp.ns) });
RecordCounter++;
continue;
}
}
JournalRecordsDataGridView.DataSource = JournalRecordsDataTable;
}
private void JournalRecordDataTableInitialization()
{
List<ModBusProfile.journal_record> journal_record = ExporterLinkerHelper.journal_record_Default;
JournalRecordDataTable.Columns.Add("Канал", typeof(int));
JournalRecordDataTable.Columns.Add("Накопленное значение расхода ресурса (%)", typeof(float));
JournalRecordDataTable.Columns.Add("Количество отключений", typeof(ushort));
JournalRecordDataTable.Columns.Add("Количество включений", typeof(ushort));
JournalRecordDataTable.Rows.Add(new object[] { 0, journal_record[0].rcntv[0].Racc, journal_record[0].rcntv[0].ofcnt, journal_record[0].rcntv[0].oNacnt });
rcntvDataGridView.DataSource = JournalRecordDataTable;
}
private void JournalRecordsDataGridView_SelectionChanged(object sender, EventArgs e)
{
ShowJournalRecordInformation();
}
private void ShowJournalRecordInformation()
{
if (JournalRecordsDataGridView.CurrentRow == null) return;
if (Database.Filtered_Journal_Records.Count > 1)
{
int selectedRecordNumber = JournalRecordsDataGridView.CurrentRow.Index + 1;
ModBusProfile.journal_record SelectedRecord = Database.Filtered_Journal_Records[selectedRecordNumber];
// Тип события - rtype / substype
if (SelectedRecord.hdr.rtype == 1)
{
if (SelectedRecord.hdr.subtype == 0)
{
EventTypeTextBox.Text = "Отключение выключателя";
}
else if (SelectedRecord.hdr.subtype == 1)
{
EventTypeTextBox.Text = "Включение выключателя";
}
}
else if (SelectedRecord.hdr.rtype == 2)
{
EventTypeTextBox.Text = "Обнуление счетчика ресурса";
}
// Дата события - stamp.slo / stamp.ns
SloTextBox.Text = SelectedRecord.hdr.stamp.slo.ToString();
NsTextBox.Text = SelectedRecord.hdr.stamp.ns.ToString();
// Дополнительные данные - udt
UdtTextBox.Text = SelectedRecord.hdr.udt.ToString();
// Значение тока соответствующего аналогового канала на момент события - Ii
IiTextBox.Text = SelectedRecord.Ii.ToString();
// Значение износа выключателя в данном [от|в]ключении - Ri
RiTextBox.Text = SelectedRecord.Ri.ToString();
// Аккумулированные значения износа выключателя для каждого контакта - rcntv
if (SelectedRecord.rcntv.Length > JournalRecordDataTable.Rows.Count)
{
for (int i = 1; i < SelectedRecord.rcntv.Length; i++)
{
JournalRecordDataTable.Rows.Add(new object[] { i, 0 });
}
}
else if (SelectedRecord.rcntv.Length < JournalRecordDataTable.Rows.Count)
{
int current_row = JournalRecordDataTable.Rows.Count - 1;
while (SelectedRecord.rcntv.Length < JournalRecordDataTable.Rows.Count)
{
JournalRecordDataTable.Rows[current_row].Delete();
current_row--;
}
}
for (int z = 0; z < SelectedRecord.rcntv.Length; z++)
{
JournalRecordDataTable.Rows[z][1] = SelectedRecord.rcntv[z].Racc;
JournalRecordDataTable.Rows[z][2] = SelectedRecord.rcntv[z].ofcnt;
JournalRecordDataTable.Rows[z][3] = SelectedRecord.rcntv[z].oNacnt;
}
rcntvDataGridView.DataSource = JournalRecordDataTable;
}
}
}
}
using ModBusHelper;
using NModbus;
using System;
using System.Collections.Generic;
using System.Data;
using System.Net.Sockets;
using System.Windows.Forms;
namespace Configurator
{
public partial class JournalRecordForm : Form
{
ModBusCommands CommandsHelper = new ModBusCommands();
ModBusFunctions ModbusFunctionsHelper = new ModBusFunctions();
ModBusExporterLinker ExporterLinkerHelper = new ModBusExporterLinker();
ModBusProfile ProfileHelper = new ModBusProfile();
private CommanderForm CommanderForm;
private Tuple<TcpClient, IModbusMaster> _connection;
DataTable JournalRecordsDataTable = new DataTable();
DataTable JournalRecordDataTable = new DataTable();
public JournalRecordForm(CommanderForm CommanderFormInstance, List<ModBusProfile.journal_record> Filtered_Journal_Records)
{
InitializeComponent();
this.CommanderForm = CommanderFormInstance;
// Subscribe to connection events
CommanderForm.ConnectionStarted += OnConnectionStarted;
CommanderForm.ConnectionStopped += OnConnectionStopped;
JournalRecordDataTableInitialization();
JournalRecordsDataTableInitialization(Filtered_Journal_Records);
JournalRecordsDataGridView.SelectionChanged += JournalRecordsDataGridView_SelectionChanged;
}
private void OnConnectionStarted(Tuple<TcpClient, IModbusMaster> connection)
{
_connection = connection;
// Refresh journal entries when connection is available
UpdateJournalEntries();
}
private void OnConnectionStopped()
{
// Handle actions when connection stops, if needed
MessageBox.Show("Соединение разорвано, журналы могут быть неактуальны.", "Информация", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
private void UpdateJournalEntries()
{
try
{
Database.Journal_Record = ProfileHelper.journal_record_Read(_connection.Item2);
int RecordCounter = 0;
foreach (ModBusProfile.journal_record record in Database.Journal_Record)
{
if (record.hdr.rtype == 0)
{
continue;
}
if (record.hdr.rtype == 1)
{
if (record.hdr.subtype == 0)
{
JournalRecordsDataTable.Rows.Add(new object[] { RecordCounter, "Отключение выключателя", UnixTimeStampToDateTime((record.hdr.stamp.slo + (record.hdr.stamp.ns * 0.000000001))) });
}
else if (record.hdr.subtype == 1)
{
JournalRecordsDataTable.Rows.Add(new object[] { RecordCounter, "Включение выключателя", UnixTimeStampToDateTime((record.hdr.stamp.slo + (record.hdr.stamp.ns * 0.000000001))) });
}
Database.Filtered_Journal_Records.Add(record);
RecordCounter++;
}
else if (record.hdr.rtype == 2)
{
JournalRecordsDataTable.Rows.Add(new object[] { RecordCounter, "Обнуление счетчика ресурса", UnixTimeStampToDateTime((record.hdr.stamp.slo + (record.hdr.stamp.ns * 0.000000001))) });
Database.Filtered_Journal_Records.Add(record);
RecordCounter++;
}
}
JournalRecordsDataGridView.DataSource = JournalRecordsDataTable;
}
catch (Exception modbusEx)
{
MessageBox.Show($"Ошибка получения записей журнала СКРВ: {modbusEx.Message}", "Ошибка ModBus соединения", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
private void JournalRecordsDataTableInitialization(List<ModBusProfile.journal_record> Filtered_Journal_Records)
{
JournalRecordsDataTable.Columns.Add("Номер записи", typeof(int));
JournalRecordsDataTable.Columns.Add("Событие", typeof(string));
JournalRecordsDataTable.Columns.Add("Дата", typeof(DateTime));
foreach (DataColumn Column in JournalRecordsDataTable.Columns)
{
Column.ReadOnly = true;
}
int RecordCounter = 0;
foreach (ModBusProfile.journal_record record in Filtered_Journal_Records)
{
if (record.hdr.rtype == 0) continue;
string eventType = record.hdr.subtype switch {
0 => "Отключение выключателя",
1 => "Включение выключателя",
_ => "Неизвестный тип"
};
if (record.hdr.rtype == 1 || record.hdr.rtype == 2)
{
JournalRecordsDataTable.Rows.Add(new object[] { RecordCounter, eventType, UnixTimeStampToDateTime(record.hdr.stamp.ns) });
RecordCounter++;
}
}
JournalRecordsDataGridView.DataSource = JournalRecordsDataTable;
}
private void JournalRecordDataTableInitialization()
{
List<ModBusProfile.journal_record> journal_record = ExporterLinkerHelper.journal_record_Default;
JournalRecordDataTable.Columns.Add("Канал", typeof(int));
JournalRecordDataTable.Columns.Add("Накопленное значение расхода ресурса (%)", typeof(float));
JournalRecordDataTable.Columns.Add("Количество отключений", typeof(ushort));
JournalRecordDataTable.Columns.Add("Количество включений", typeof(ushort));
JournalRecordDataTable.Rows.Add(new object[] { 0, journal_record[0].rcntv[0].Racc, journal_record[0].rcntv[0].ofcnt, journal_record[0].rcntv[0].oNacnt });
rcntvDataGridView.DataSource = JournalRecordDataTable;
}
private void JournalRecordsDataGridView_SelectionChanged(object sender, EventArgs e)
{
ShowJournalRecordInformation();
}
private void ShowJournalRecordInformation()
{
if (JournalRecordsDataGridView.CurrentRow == null) return;
int selectedRecordNumber = JournalRecordsDataGridView.CurrentRow.Index;
if (selectedRecordNumber >= 0 && selectedRecordNumber < Database.Filtered_Journal_Records.Count)
{
ModBusProfile.journal_record SelectedRecord = Database.Filtered_Journal_Records[selectedRecordNumber];
EventTypeTextBox.Text = SelectedRecord.hdr.subtype switch
{
0 => "Отключение выключателя",
1 => "Включение выключателя",
_ => "Обнуление счетчика ресурса"
};
SloTextBox.Text = SelectedRecord.hdr.stamp.slo.ToString();
NsTextBox.Text = SelectedRecord.hdr.stamp.ns.ToString();
UdtTextBox.Text = SelectedRecord.hdr.udt.ToString();
IiTextBox.Text = SelectedRecord.Ii.ToString();
RiTextBox.Text = SelectedRecord.Ri.ToString();
for (int z = 0; z < SelectedRecord.rcntv.Length && z < JournalRecordDataTable.Rows.Count; z++)
{
JournalRecordDataTable.Rows[z][1] = SelectedRecord.rcntv[z].Racc;
JournalRecordDataTable.Rows[z][2] = SelectedRecord.rcntv[z].ofcnt;
JournalRecordDataTable.Rows[z][3] = SelectedRecord.rcntv[z].oNacnt;
}
rcntvDataGridView.DataSource = JournalRecordDataTable;
}
}
private void JournalRecordForm_FormClosing(object sender, FormClosingEventArgs e)
{
CommanderForm.ConnectionStarted -= OnConnectionStarted;
CommanderForm.ConnectionStopped -= OnConnectionStopped;
}
public static DateTime UnixTimeStampToDateTime(double unixTimeStamp)
{
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddSeconds(unixTimeStamp).ToLocalTime();
return dateTime;
}
}
}
Key Elements:
Subscription to Events: The JournalRecordForm subscribes to the ConnectionStarted and ConnectionStopped events from the CommanderForm within its constructor. This allows the form to react to connection changes dynamically, such as refreshing journal data when connected.
Event Handlers: OnConnectionStarted refreshes journal entries upon connecting, ensuring data is synced. OnConnectionStopped informs the user that the connection is lost, and data may become outdated.
Cleanup: The form properly unsubscribes from events upon closing to prevent unwanted behavior or memory leaks.
Improved Control Flow: Ensures that only valid records are processed during initialization, providing consistent and clear log records in the UI.
This approach ensures that your JournalRecordForm is synchronized with the connection status, updating or displaying relevant information as the connection state allows.