common/Ui/MagFluxToolBox/FrmTest.cs
2026-04-23 17:50:07 +02:00

1004 lines
38 KiB
C#

using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Xylem.Common.Hardware.WaterMeter.MagFlux.DataPackages.DataTypes;
using Xylem.Common.Hardware.WaterMeter.MagFlux.DataPackages.EventArguments;
using Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore;
using Xylem.Common.Hardware.WaterMeter.MagFlux.MagFluxCore.Consts;
using Xylem.Common.Hardware.WaterMeter.WaterMeterCore;
using Xylem.Common.Utils.ProcessExec.EventArguments;
namespace Xylem.Common.Ui.MagFluxToolBox
{
/// <summary>
/// Test form for MagFlux operation
/// </summary>
public partial class FrmTest : Form
{
#region Variables
private const String HeaderRefFlow = @"Ref Flow [m³/h]";
private const String HeaderDutFlow = @"DUT Flow [m³/h]";
private const String StrBtnChange = "Change";
private const String StrBtnSet = "Set";
/// <summary>
/// Reference to list of calibration points in cubic meters per hour.
/// </summary>
private List<Calibration> _calibPointsCmPerH;
private DataTable _dataTableCalibPoints;
private readonly MeterBatch _meterBatch = new MeterBatch();
private MagFluxMeter _magFluxMeter;
private const String StrConnecting = "Connecting to PCB";
private const String StrNotConnected = "NOT CONNECTED";
private const String StrOverallProcess = "Overall Process";
private const String StrEpbControlBit0 = @"Empty Pipe Detection OFF";
private const String StrEpbControlBit1 = @"Empty Pipe Detection flags only";
private const String StrEpbControlBit2 = @"Empty Pipe Detection active";
private UInt32 _lastState;
private DateTimeOffset _startTime;
private readonly Boolean _updateGui = true;
//private Boolean _tryConnectPcb;
private PcbAccess _pcbAccess = PcbAccess.None;
private Boolean _pcbIsInitialized;
private Boolean _cyclicUpdateEnabled;
private Int32 _timerCtr200ms;
// external update remarks form
// private readonly FrmHistory _frmHistory = new FrmHistory();
//private readonly Version _version;
// status information
private static readonly Color ColorDefault = Color.Black;
private static readonly Color ColorSuccess = Color.Green;
private static readonly Color ColorProcessFailed = Color.Red;
//private static readonly Color ColorOngoingProcess = Color.Blue;
//private static readonly Color ColorUnknownStatus = Color.Gray;
//private const String SuccessSign = @"✔";
//private const String FailedSign = @"✘";
private const String StrSeparator = "-----------------------------------------------------" +
"-----------------------------------------------------";
#endregion
#region FormControls
/// <summary>
/// Ctor FW update
/// </summary>
public FrmTest()
{
InitializeComponent();
var cultureInfo = new CultureInfo("en-GB");
Thread.CurrentThread.CurrentUICulture = cultureInfo;
Thread.CurrentThread.CurrentCulture = cultureInfo;
}
/// <summary>
/// Clear data table and set genesis to not connected
/// </summary>
private void Init()
{
ProcessViewControl(false);
_magFluxMeter?.StopStreamingCatcher();
lblPcbId.Text = StrNotConnected;
lblPcbId.ForeColor = Color.Red;
btnInitPcb.Visible = false;
btnInitPcb.Enabled = false;
lblWaitingForMeterResponse.Visible = false;
btnConnect.Enabled = true;
SetControlDownloadsLocked();
tbxUniqueId.Text = "";
tbxSensorNo.Text = "";
tbxFwVersion.Text = "";
tbxFwBuildDate.Text = "";
tbxFwGitHash.Text = "";
tbxMeterSize.Text = "";
tbxFlowRate.Text = "";
tbxStatus.Text = "";
tbxVolume.Text = "";
tbxFwdVolume.Text = "";
tbxRevVolume.Text = "";
tbxMeterSize.ReadOnly = true;
tbxSensorNo.ReadOnly = true;
btnChangeSensorNo.Text = StrBtnChange;
btnChangeMeterSize.Text = StrBtnChange;
gridViewCalib.Visible = false;
var errorStateInfos = StateDef.GetInfoOfAllErrorStates();
if (errorStateInfos.Count >= 10)
{
cbxStatus0.Text = errorStateInfos[0];
cbxStatus1.Text = errorStateInfos[1];
cbxStatus2.Text = errorStateInfos[2];
cbxStatus3.Text = errorStateInfos[3];
cbxStatus4.Text = errorStateInfos[4];
cbxStatus5.Text = errorStateInfos[5];
cbxStatus6.Text = errorStateInfos[6];
cbxStatus7.Text = errorStateInfos[7];
cbxStatus8.Text = errorStateInfos[8];
cbxStatus9.Text = errorStateInfos[9];
}
cbxStatus10.Text = StrEpbControlBit0;
cbxStatus11.Text = StrEpbControlBit1;
cbxStatus12.Text = StrEpbControlBit2;
CheckUpdateEnabled();
}
private void FrmTest_Load(Object sender, EventArgs e)
{
var version = Assembly.GetExecutingAssembly().GetName().Version;
Init();
var strVersion = $@"ToolBox {version}";
lblSoftwareVersion.Text = strVersion;
LogText(strVersion);
LogText(StrSeparator);
try
{
var fileVersion = FileVersionInfo.GetVersionInfo("magflux_api.dll");
strVersion = $@"MagFlux API {fileVersion.FileVersion}";
lblMagFluxApi.Text = strVersion;
LogText(strVersion);
LogText(StrSeparator);
fileVersion = FileVersionInfo.GetVersionInfo("shared_code.dll");
strVersion = $"Shared Code {fileVersion.FileVersion}";
lblSharedCode.Text = strVersion;
LogText(strVersion);
LogText(StrSeparator);
}
catch (Exception ex)
{
LogText(ex.Message);
}
}
private void FrmTest_FormClosing(Object sender, FormClosingEventArgs e)
{
if (_magFluxMeter != null)
{
_magFluxMeter.OnStreamingRecordDecoded -= StreamingCatcher_OnStreamingRecordDecoded;
_magFluxMeter.Logout();
_magFluxMeter.StopStreamingCatcher();
}
_meterBatch?.RemoveAllMeters();
_meterBatch?.Dispose();
Dispose();
}
private void cbComSlot_SelectedIndexChanged(Object sender, EventArgs e)
{
Init();
}
#endregion
#region Data Grid Calibration
/// <summary>
/// Edit calibrations and fill the data back to calibration data field
/// </summary>
/// <remarks date="2023-Mai-31" author="Thomas Wiedebusch">
/// - Initial.
/// </remarks>
/// <remarks date="2025-Mar-05" author="Thomas Wiedebusch">
/// - Cell content changed to string being able to replace "," by "." and so to use the German keyboard layout.
/// </remarks>
private void gridViewCalib_CellEndEdit(Object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex < 0 || e.RowIndex < 0 || _dataTableCalibPoints == null
|| _calibPointsCmPerH == null || _calibPointsCmPerH.Count < e.RowIndex)
{
return;
}
var array = _calibPointsCmPerH.ToArray();
var index = e.RowIndex;
_calibPointsCmPerH.Clear();
// Ignore the decimal comma on German keyboard layout and replace it by a point
var cellContent = gridViewCalib.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString().Replace(",",".");
if (float.TryParse(cellContent, out var floatResult))
{
if (gridViewCalib.Columns[e.ColumnIndex].Name == HeaderRefFlow)
array[index].refFlowRate = floatResult;
if (gridViewCalib.Columns[e.ColumnIndex].Name == HeaderDutFlow)
array[index].dutFlowRate = floatResult;
foreach (var a in array)
{
_calibPointsCmPerH.Add(a);
}
}
FillDataGridWithCalibInfos();
}
catch (Exception)
{
// ignored
}
}
/// <summary>
/// Build data grid for calibrations
/// </summary>
/// <remarks date="2023-Mai-31" author="Thomas Wiedebusch">
/// - Initial.
/// </remarks>
/// <remarks date="2025-Mar-05" author="Thomas Wiedebusch">
/// - Cell content changed to string being able to replace "," by "." and so to use the German keyboard layout.
/// </remarks>
private void FillDataGridWithCalibInfos()
{
if (_calibPointsCmPerH == null)
return;
_dataTableCalibPoints?.Dispose();
_dataTableCalibPoints = new DataTable();
_dataTableCalibPoints.Columns.Add(HeaderRefFlow);
_dataTableCalibPoints.Columns.Add(HeaderDutFlow);
//_dataTableCalibPoints.Columns.Add(HeaderRefFlow, typeof(Single));
//_dataTableCalibPoints.Columns.Add(HeaderDutFlow, typeof(Single));
try
{
foreach (var cb in _calibPointsCmPerH)
{
var row = _dataTableCalibPoints.NewRow();
//row[HeaderRefFlow] = (Single)Math.Round(cb.refFlowRate, 6);
//row[HeaderDutFlow] = (Single)Math.Round(cb.dutFlowRate, 6);
row[HeaderRefFlow] = Math.Round(cb.refFlowRate, 6);
row[HeaderDutFlow] = Math.Round(cb.dutFlowRate, 6);
_dataTableCalibPoints.Rows.Add(row);
}
gridViewCalib.DataSource = _dataTableCalibPoints;
foreach (DataGridViewColumn column in gridViewCalib.Columns)
{
column.SortMode = DataGridViewColumnSortMode.NotSortable;
}
gridViewCalib.Visible = true;
}
catch (Exception)
{
//not implemented
}
}
#endregion --------------------------------------- Data Grid Calibration --------------------------------------
#region ActivationControls
private void SetControlDownloadsLocked()
{
btnConnect.Enabled = true;
btnAbortCalibration.Enabled = false;
btnPrepareCalibration.Enabled = false;
btnReadCalibration.Enabled = false;
btnWriteCalibration.Enabled = false;
btnChangeSensorNo.Enabled = false;
btnChangeMeterSize.Enabled = false;
btnInitPcb.Enabled = false;
tmrRequestUpdate.Enabled = false;
cbxEmptyPipeCtrl.Enabled = false;
cbxSimulatedFlow.Enabled = false;
cbxEnableDeviceStatusUpdate.Enabled = false;
_cyclicUpdateEnabled = false;
}
private void SetControlsDownloadIsOngoing()
{
btnConnect.Enabled = false;
btnAbortCalibration.Enabled = false;
btnPrepareCalibration.Enabled = false;
btnReadCalibration.Enabled = false;
btnWriteCalibration.Enabled = false;
btnChangeSensorNo.Enabled = false;
btnChangeMeterSize.Enabled = false;
btnInitPcb.Enabled = false;
tmrRequestUpdate.Enabled = false;
cbxEmptyPipeCtrl.Enabled = false;
cbxSimulatedFlow.Enabled = false;
cbxEnableDeviceStatusUpdate.Enabled = false;
_cyclicUpdateEnabled = false;
}
//private void SetControlsDownloadIsFinished()
//{
// btnConnect.Enabled = true;
// btnAbortCalibration.Enabled = false;
// btnReadCalibration.Enabled = true;
// cbxEmptyPipeCtrl.Enabled = true;
// cbxSimulatedFlow.Enabled = true;
// // Lock buttons if not allowed due to release FW
// if (!cbxCalibrationValuesAreReadOnly.Checked)
// {
// btnPrepareCalibration.Enabled = true;
// btnWriteCalibration.Enabled = true;
// btnChangeSensorNo.Enabled = true;
// btnChangeMeterSize.Enabled = true;
// }
// btnInitPcb.Enabled = !_pcbIsInitialized;
// tmrRequestUpdate.Enabled = true;
// _cyclicUpdateEnabled = true;
//}
private void SetControlsDownloadEnabled()
{
btnConnect.Enabled = true;
btnAbortCalibration.Enabled = false;
btnReadCalibration.Enabled = true;
cbxEmptyPipeCtrl.Enabled = true;
cbxSimulatedFlow.Enabled = true;
cbxEnableDeviceStatusUpdate.Enabled = true;
// Lock buttons if not allowed due to release FW
if (!cbxCalibrationValuesAreReadOnly.Checked)
{
btnPrepareCalibration.Enabled = true;
btnWriteCalibration.Enabled = true;
btnChangeSensorNo.Enabled = true;
btnChangeMeterSize.Enabled = true;
}
btnInitPcb.Enabled = !_pcbIsInitialized;
tmrRequestUpdate.Enabled = true;
_cyclicUpdateEnabled = true;
}
#endregion
#region BoardControls
/// <summary>
/// Cyclic execution of catcher on incoming events.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StreamingCatcher_OnStreamingRecordDecoded(Object sender, MagFluxFlowDataEventArgs e)
{
try
{
Invoke(new Action(() =>
{
tbxVolume.Text = $@"{e.NewData.VolumeCm:F3}";
tbxFwdVolume.Text = $@"{e.NewData.ForwardVolumeCm:F3}";
tbxRevVolume.Text = $@"{e.NewData.NegativeReverseVolumeCm:F3}";
tbxFlowRate.Text = $@"{e.NewData.FlowRateCmPh:F3}";
tbxStatus.Text = $@"0x{e.NewData.StatusBits:X8}";
tbxTime.Text = $@"{e.NewData.TimeS:F3}";
tbxAverElectrode.Text = $@"{_magFluxMeter.AverageElectrode_mV:F6}";
tbxStdDevElectrode.Text = $@"{_magFluxMeter.StandardDeviationElectrode_mV:F6}";
if (_lastState != e.NewData.StatusBits)
{
// remind states for next run
_lastState = e.NewData.StatusBits;
UpdateStateDisplay();
}
}));
}
catch (Exception)
{
// ignored
}
}
/// <summary>
/// Update state display on GUI
/// </summary>
private void UpdateStateDisplay()
{
cbxStatus0.Checked = StateDef.CheckStateMask(_lastState, 0);
cbxStatus1.Checked = StateDef.CheckStateMask(_lastState, 1);
cbxStatus2.Checked = StateDef.CheckStateMask(_lastState, 2);
cbxStatus3.Checked = StateDef.CheckStateMask(_lastState, 3);
cbxStatus4.Checked = StateDef.CheckStateMask(_lastState, 4);
cbxStatus5.Checked = StateDef.CheckStateMask(_lastState, 5);
cbxStatus6.Checked = StateDef.CheckStateMask(_lastState, 6);
cbxStatus7.Checked = StateDef.CheckStateMask(_lastState, 7);
cbxStatus8.Checked = StateDef.CheckStateMask(_lastState, 8);
cbxStatus9.Checked = StateDef.CheckStateMask(_lastState, 9);
}
/// <summary>
/// Connect to MagFlux and read out all needed information.
/// </summary>
/// <remarks date="2024-Aug-20" author="T.Wiedebusch">
/// - PcbId taken to decide board initialization.
/// </remarks>
/// <remarks date="2025-Feb-04" author="T.Wiedebusch">
/// - Calibration cleared at connect as a new MagFlux may be connected.
/// </remarks>
private void Connect()
{
try
{
Init();
if (string.IsNullOrEmpty(cbComSlot.SelectedItem.ToString()) ||
!int.TryParse(cbComSlot.SelectedItem.ToString(), out var slotNr))
{
return;
}
//lblOverall.Text = @"Establish data base connection..";
SetControlsDownloadIsOngoing();
Task.Factory.StartNew(() =>
{
_pcbAccess = PcbAccess.Connect;
tmrProgressUpdate.Interval = 200;
ViewProgressPcb(true);
//dispose old meter
_meterBatch.RemoveAllMeters();
_magFluxMeter = null;
Thread.Sleep(200);
//assign new meter and assign meter to FW update file if this exists
_magFluxMeter = new MagFluxMeter();
_magFluxMeter.SetupFromConfigFile(slotNr);
_meterBatch.AddMeter(_magFluxMeter);
_magFluxMeter.Configuration.UseRegisterWatchService = false;
_magFluxMeter.Configuration.UseMinMaxCheck = false;
_magFluxMeter.OnStreamingRecordDecoded += StreamingCatcher_OnStreamingRecordDecoded;
_meterBatch.MetersLogin();
Invoke(new Action(() =>
{
if (_magFluxMeter != null && _magFluxMeter.IsLoggedOn)
{
if (!string.IsNullOrEmpty(_magFluxMeter.PcbId))
{
lblPcbId.Text = $@"PcbId: {_magFluxMeter.PcbId}";
lblPcbId.ForeColor = Color.Green;
btnInitPcb.Visible = false;
_pcbIsInitialized = true;
tbxBoardCalibration.Text = $@"{_magFluxMeter.BoardCalib:F4}";
}
else
{
lblPcbId.Text = @"PCB NOT INITIALIZED";
lblPcbId.ForeColor = Color.DarkOrange;
_pcbIsInitialized = false;
btnInitPcb.Visible = true;
tbxBoardCalibration.Text = @"?";
}
tbxUniqueId.Text = _magFluxMeter.UniqueId;
tbxSensorNo.Text = _magFluxMeter.SensorSerialNo;
tbxFwVersion.Text = _magFluxMeter.FwVersion;
tbxFwBuildDate.Text = _magFluxMeter.FwBuildDate;
tbxFwGitHash.Text = _magFluxMeter.FwGitHash;
tbxMeterSize.Text = _magFluxMeter.MeterSizeMm.ToString();
SetEmptyPipeStatusBits();
cbxEmptyPipeCtrl.SelectedIndex = _magFluxMeter.EpdControlBits;
cbxIgnoreEmptyPipeStatus.Checked = _magFluxMeter.IgnoreEmptyPipeDetection;
cbxSimulatedFlow.Checked = _magFluxMeter.SimulatedFlowIsActive;
cbxSimulatedFlow.ForeColor = _magFluxMeter.SimulatedFlowIsActive ? Color.Red :
SystemColors.ControlText;
cbxCalibrationValuesAreReadOnly.Checked = _magFluxMeter.IsCalibrationValuesReadOnly;
cbxCalibrationValuesAreReadOnly.ForeColor = _magFluxMeter.IsCalibrationValuesReadOnly ?
Color.Red : SystemColors.ControlText;
// Update calibration values
btnReadCalibration_Click(this, null);
CheckUpdateEnabled();
}
}));
}).ContinueWith(delegate
{
_magFluxMeter.StartStreamingCatcher();
_magFluxMeter.Logout();
_pcbAccess = PcbAccess.Done;
ViewProgressPcb(false);
});
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
LogErrorText(ex.Message);
}
}
private void GetDeviceStatus()
{
if (_magFluxMeter != null && cbxEnableDeviceStatusUpdate.Checked)
{
if (_magFluxMeter.GetDeviceStatus(out var deviceStatusMsg))
{
rtbDeviceStatus.SuspendLayout();
rtbDeviceStatus.SelectionStart = rtbDeviceStatus.Text.Length;
rtbDeviceStatus.SelectionLength = 0;
//rtbDeviceStatus.SelectionColor = color;
rtbDeviceStatus.AppendText($"{deviceStatusMsg}{Environment.NewLine}");
//rtbDeviceStatus.SelectionColor = deviceStatusMsg.ForeColor;
rtbDeviceStatus.ScrollToCaret();
rtbDeviceStatus.ResumeLayout();
}
}
}
private void SetEmptyPipeStatusBits()
{
if (_magFluxMeter != null && _magFluxMeter.GetEmptyPipeControl())
{
cbxStatus10.Checked = _magFluxMeter.EpdControlBits == 0x00;
cbxStatus11.Checked = _magFluxMeter.EpdControlBits == 0x01;
cbxStatus12.Checked = _magFluxMeter.EpdControlBits == 0x02;
}
}
#endregion
#region ProcessControls
private void ViewProgressPcb(Boolean isActive, String msg = StrConnecting)
{
if (_updateGui)
{
if (isActive)
{
Invoke(new Action(() =>
{
ProcessViewControl(true);
lblActualProcess.Text = msg;
lblOverall.Text = StrOverallProcess;
}));
}
else
{
Invoke(new Action(() =>
{
ProcessViewControl(false);
}));
}
}
}
/// <summary>
/// View all process bars and labels
/// </summary>
private void ProcessViewControl(Boolean view)
{
if (view)
{
lblActualProcess.Visible = true;
lblOverall.Visible = true;
barOverallProgressUpdate.Visible = true;
barSingleProgressUpdate.Visible = true;
_lastState = (UInt32)State.Okay;
tmrProgressUpdate.Enabled = true;
}
else
{
lblActualProcess.Visible = false;
lblOverall.Visible = false;
barOverallProgressUpdate.Visible = false;
barSingleProgressUpdate.Visible = false;
tmrProgressUpdate.Enabled = false;
_lastState = (UInt32)State.Okay;
lblWaitingForMeterResponse.Visible = false;
lblActualProcess.Text = "";
lblOverall.Text = "";
}
//common actions and settings
lblActualProcess.Update();
lblOverall.Update();
barOverallProgressUpdate.Value = 0;
barOverallProgressUpdate.Update();
barSingleProgressUpdate.Value = 0;
barSingleProgressUpdate.Update();
Update();
}
/// <summary>
/// Output exclusively to user update remarks text window.
/// </summary>
/// <remarks date="2021-Apr-26" author="Thomas Wiedebusch">
/// - Color added.
/// </remarks>
private void LogText(String txtHistory)
{
InfoWindowColoredText(txtHistory, ColorDefault);
}
/// <summary>
/// Output exclusively to user update remarks text window.
/// </summary>
private void LogErrorText(String txtHistory)
{
InfoWindowColoredText(txtHistory, ColorProcessFailed);
}
/// <summary>
/// Output exclusively to user update remarks text window.
/// </summary>
private void LogSuccessText(String txtHistory)
{
InfoWindowColoredText(txtHistory, ColorSuccess);
}
/// <summary>
/// Output exclusively to user update remarks text window.
/// </summary>
private void InfoWindowColoredText(String txtHistory, Color color)
{
//if (_frmHistory?.rtbHistory == null)
// return;
//Invoke(new Action(() =>
//{
// _frmHistory.rtbHistory.SuspendLayout();
// _frmHistory.rtbHistory.SelectionStart = _frmHistory.rtbHistory.Text.Length;
// _frmHistory.rtbHistory.SelectionLength = 0;
// _frmHistory.rtbHistory.SelectionColor = color;
// _frmHistory.rtbHistory.AppendText($"{txtHistory}{Environment.NewLine}");
// _frmHistory.rtbHistory.SelectionColor = _frmHistory.rtbHistory.ForeColor;
// _frmHistory.rtbHistory.ScrollToCaret();
// _frmHistory.rtbHistory.ResumeLayout();
//}));
}
#endregion
#region Checks
private void CheckUpdateEnabled()
{
//this check has been placed here to force display update
if (_magFluxMeter != null)
{
SetControlsDownloadEnabled();
return;
}
SetControlDownloadsLocked();
}
#endregion
#region Events
/// <summary>
/// Process update event for displaying messages in history window
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
/// <remarks date="2020-Dec-10" author="Thomas Wiedebusch">
/// - Initial
/// </remarks>
public virtual void ProcessUpdate_Event(Object sender, ProcessExecEventArgs e)
{
LogText(e.OverallProcessMessage);
}
#endregion
#region TimerControls
private void tmrRequestUpdate_Tick(Object sender, EventArgs e)
{
if (_magFluxMeter != null && _cyclicUpdateEnabled)
{
_timerCtr200ms++;
switch (_timerCtr200ms)
{
case 1:
_magFluxMeter.GetStdDev_Electrode_mV(out _);
break;
case 2:
_magFluxMeter.GetAverage_Electrode_mV(out _);
break;
case 3:
_magFluxMeter.GetForwardVolume_cm(out _);
_magFluxMeter.GetBackwardVolume_cm(out _);
_magFluxMeter.GetVolume_cm(out _);
break;
case 4:
break;
case 5:
_timerCtr200ms = 0;
GetDeviceStatus();
break;
default:
_timerCtr200ms = 0;
break;
}
}
}
private void tmrProgressUpdate_Tick(Object sender, EventArgs e)
{
switch (_pcbAccess)
{
case PcbAccess.Connect:
barOverallProgressUpdate.Value = barOverallProgressUpdate.Value + 1 > 100 ? 0 :
barOverallProgressUpdate.Value + 1;
barSingleProgressUpdate.Value = barSingleProgressUpdate.Value + 4 > 100 ? 0 :
barSingleProgressUpdate.Value + 4;
lblOverall.Text = StrOverallProcess;
break;
case PcbAccess.InitPcb:
barOverallProgressUpdate.Value = barOverallProgressUpdate.Value + 1 > 100 ? 0 :
barOverallProgressUpdate.Value + 1;
barSingleProgressUpdate.Value = barSingleProgressUpdate.Value + 4 > 100 ? 0 :
barSingleProgressUpdate.Value + 4;
lblOverall.Text = StrOverallProcess;
break;
}
SetTimeDisplay();
Update();
}
private void SetTimeDisplay()
{
var time = DateTimeOffset.UtcNow;
var timeSpan = time - _startTime;
lblUpdateTime.Text = $@"{(UInt32)timeSpan.TotalMinutes}:{timeSpan.Seconds:00}";
}
#endregion
#region User Inputs
private void cbxIgnoreEmptyPipeStatus_CheckedChanged(Object sender, EventArgs e)
{
var retVal = _magFluxMeter?.SetIgnoreFailOnEmptyPipeOnHealthy(cbxIgnoreEmptyPipeStatus.Checked);
if (retVal != null && (Boolean)retVal)
{
cbxIgnoreEmptyPipeStatus.ForeColor = SystemColors.ControlText;
SetEmptyPipeStatusBits();
}
else
{
cbxIgnoreEmptyPipeStatus.ForeColor = Color.Red;
}
}
private void cbxSimulatedFlow_CheckedChanged(Object sender, EventArgs e)
{
if (_magFluxMeter != null)
{
_magFluxMeter.SetSimulatedFlowActive(cbxSimulatedFlow.Checked);
cbxSimulatedFlow.Checked = _magFluxMeter.SimulatedFlowIsActive;
cbxSimulatedFlow.ForeColor = _magFluxMeter.SimulatedFlowIsActive ? Color.Red :
SystemColors.ControlText;
}
}
private void btnInitPcb_Click(Object sender, EventArgs e)
{
SetControlsDownloadIsOngoing();
_startTime = DateTimeOffset.UtcNow;
_magFluxMeter?.StopStreamingCatcher();
Task.Factory.StartNew(() =>
{
tmrProgressUpdate.Interval = 200;
ViewProgressPcb(true, "Initialize PCB");
_pcbAccess = PcbAccess.InitPcb;
_magFluxMeter.SetPCBToDemoDefaults();
Invoke(new Action(CheckUpdateEnabled));
}).ContinueWith(delegate
{
ViewProgressPcb(false);
_pcbAccess = PcbAccess.Done;
Invoke(new Action(Connect));
});
}
private void btnChangeSensorNo_Click(Object sender, EventArgs e)
{
// enable edit and change text to button text to "Set"
if (string.Equals(StrBtnChange, btnChangeSensorNo.Text))
{
btnChangeSensorNo.Text = StrBtnSet;
tbxSensorNo.ReadOnly = false;
}
else
{
btnChangeSensorNo.Text = StrBtnChange;
tbxSensorNo.ReadOnly = true;
if (UInt32.TryParse(tbxSensorNo.Text, out var sensorSerialNo))
{
if (_magFluxMeter != null && _magFluxMeter.SetSensorSerialNo(sensorSerialNo))
{
// reconnect to publish the new serial number to the streaming protocol
Connect();
}
}
}
}
private void btnChangeMeterSize_Click(Object sender, EventArgs e)
{
// enable edit and change text to button text to "Set"
if (string.Equals(StrBtnChange, btnChangeMeterSize.Text))
{
btnChangeMeterSize.Text = StrBtnSet;
tbxMeterSize.ReadOnly = false;
}
else
{
btnChangeMeterSize.Text = StrBtnChange;
tbxMeterSize.ReadOnly = true;
if (UInt16.TryParse(tbxMeterSize.Text, out var meterSize_mm))
{
_magFluxMeter?.SetMeterSizeMm(meterSize_mm);
}
}
}
private void btnPrepareCalibration_Click(Object sender, EventArgs e)
{
SetControlsDownloadIsOngoing();
_magFluxMeter?.InitCalibration();
btnAbortCalibration.Enabled = true;
btnReadCalibration_Click(this, null);
SetControlsDownloadEnabled();
}
private void btnReadCalibration_Click(Object sender, EventArgs e)
{
SetControlsDownloadIsOngoing();
_magFluxMeter?.ReadCalibration(out _calibPointsCmPerH);
if (_calibPointsCmPerH == null)
return;
_dataTableCalibPoints?.Clear();
FillDataGridWithCalibInfos();
SetControlsDownloadEnabled();
}
private void btnWriteCalibration_Click(Object sender, EventArgs e)
{
SetControlsDownloadIsOngoing();
if (_calibPointsCmPerH == null)
return;
//TOD O THW test start to increase calibrations above 6
//var calib = new Calibration();
//calib.dutFlowRate = 2;
//calib.refFlowRate = 2;
//_calibPointsCmPerH.Add(calib);
//calib.dutFlowRate = 15;
//calib.refFlowRate = 15;
//_calibPointsCmPerH.Add(calib);
//TOD O THW test stop
_magFluxMeter?.WriteCalibration(_calibPointsCmPerH);
btnReadCalibration_Click(this, null);
}
private void btnAbortCalibration_Click(Object sender, EventArgs e)
{
_magFluxMeter?.StopCalibration();
}
private void btnConnect_Click(Object sender, EventArgs e)
{
////TOD O THW test start
//_magFluxMeter = new MagFluxMeter();
//_magFluxMeter.SetupFromConfigFile(1);
//_meterBatch.AddMeter(_magFluxMeter);
//_meterBatch.MetersLogin();
//var calibPointsCmPerH = new List<Calibration>();
//var calibPoint = new Calibration[6];
//calibPoint[0].dutFlowRate = 0.01f;
//calibPoint[0].refFlowRate = 0;
//calibPoint[1].dutFlowRate = 100;
//calibPoint[1].refFlowRate = 99.9f;
//calibPoint[2].dutFlowRate = 0;
//calibPoint[2].refFlowRate = 0;
//calibPoint[3].dutFlowRate = 10.0f;
//calibPoint[3].refFlowRate = 9.9f;
//calibPoint[4].dutFlowRate = 0;
//calibPoint[4].refFlowRate = 0;
//calibPoint[5].dutFlowRate = 69.3f;
//calibPoint[5].refFlowRate = 70.2f;
//calibPointsCmPerH.AddRange(calibPoint);
//_magFluxMeter?.WriteCalibration(calibPointsCmPerH);
////TOD O THW test end
_startTime = DateTimeOffset.UtcNow;
Connect();
}
private void cbxEmptyPipeCtrl_SelectedIndexChanged(Object sender, EventArgs e)
{
if (_magFluxMeter != null)
{
// The selected item index has to be sorted as 0 = EPD off, 1 = EPD flags only, 2 = EPD active
_magFluxMeter.SetEmptyPipeControl(cbxEmptyPipeCtrl.SelectedIndex);
_magFluxMeter.GetEmptyPipeControl();
cbxStatus10.Checked = _magFluxMeter.EpdControlBits == 0;
cbxStatus11.Checked = _magFluxMeter.EpdControlBits == 1;
cbxStatus12.Checked = _magFluxMeter.EpdControlBits == 2;
cbxIgnoreEmptyPipeStatus.Checked = _magFluxMeter.IgnoreEmptyPipeDetection;
}
}
#endregion
#region ExternalCalls
/// <summary>
/// Access to PCB
/// </summary>
public enum PcbAccess
{
/// <summary>
/// No access required
/// </summary>
None,
/// <summary>
/// Connect to the device
/// </summary>
Connect,
/// <summary>
/// Initialize the board
/// </summary>
InitPcb,
/// <summary>
/// Access has been executed and finished
/// </summary>
Done
}
/// <summary>
///
/// </summary>
public MsgEventArgs LastMsgEvent;
/// <inheritdoc />
public class MsgEventArgs : EventArgs
{
/// <summary>
/// Text to display
/// </summary>
public String Text;
/// <summary>
/// Headline
/// </summary>
public String Caption;
/// <summary>
/// Buttons
/// </summary>
public MessageBoxButtons Buttons;
/// <summary>
/// Icon
/// </summary>
public MessageBoxIcon Icon;
}
/// <summary>
/// Message pop up event handler
/// </summary>
public event EventHandler<MsgEventArgs> OnMsgPopUp;
private void MessageBoxShow(String text, String caption, MessageBoxButtons buttons, MessageBoxIcon icon)
{
if (_updateGui)
{
MessageBox.Show(text, caption, buttons, icon);
}
else
{
LastMsgEvent = new MsgEventArgs { Text = text, Caption = caption, Buttons = buttons, Icon = icon };
OnMsgPopUp?.Invoke(this, LastMsgEvent);
}
}
#endregion
}
}