compatible version to TBF

Refactor `NfcHanler` namespace to `NfcHandler` and enhance code consistency.
This commit is contained in:
Michal Buzik 2025-10-29 16:05:21 +01:00
parent 42002e3fa4
commit 320cddb177
23 changed files with 461 additions and 438 deletions

View File

@ -1,15 +1,16 @@
using System;
using JetBrains.Annotations;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NfcC7_DLL.NfcHanler;
using NfcC7_DLL.NfcHanler.Protocols;
using NfcC7_DLL.NfcHanler.Utils;
using NfcC7_DLL.NfcHandler;
using NfcC7_DLL.NfcHandler.Protocols;
using NfcC7_DLL.NfcHandler.Utils;
using NfcC7_DLL.NfcHandler;
namespace NfcC7_DLL.Tests.NfcHanler;
[TestClass]
[TestSubject(typeof(NFCHeadService))]
public class NFCHeadServiceTest
[TestSubject(typeof(NfcHeadService))]
public class NfcHeadServiceTest
{
[TestMethod]
@ -20,7 +21,7 @@ public class NFCHeadServiceTest
"HatCliDemo.exe",
74);
NFCHeadService service = new NFCHeadService(serialPortData);
NfcHeadService service = new NfcHeadService(serialPortData);
OptoHeadStatus status = service.SetTestingMode(OptoHeadStatus.OptoHeadC7);
Assert.AreEqual(OptoHeadStatus.OptoHeadC7, status);
}
@ -33,7 +34,7 @@ public class NFCHeadServiceTest
"HatCliDemo.exe",
74);
NFCHeadService service = new NFCHeadService(serialPortData);
NfcHeadService service = new NfcHeadService(serialPortData);
OptoHeadStatus status = service.SetTestingMode(OptoHeadStatus.OptoHeadDisabled);
Assert.AreEqual(OptoHeadStatus.OptoHeadDisabled, status);
}
@ -46,7 +47,7 @@ public class NFCHeadServiceTest
"HatCliDemo.exe",
74);
NFCHeadService service = new NFCHeadService(serialPortData);
NfcHeadService service = new NfcHeadService(serialPortData);
OptoHeadStatus status = service.SetTestingMode(OptoHeadStatus.OptoHeadC2);
Assert.AreEqual(OptoHeadStatus.OptoHeadC2, status);
@ -65,7 +66,7 @@ public class NFCHeadServiceTest
"HatCliDemo.exe",
74);
NFCHeadService service = new NFCHeadService(serialPortData);
NfcHeadService service = new NfcHeadService(serialPortData);
string? serialNr = service.GetSerialNr();
Assert.IsFalse(string.IsNullOrEmpty(serialNr));
Console.WriteLine("Found serial no: {0}",serialNr);
@ -79,7 +80,7 @@ public class NFCHeadServiceTest
"HatCliDemo.exe",
74);
NFCHeadService service = new NFCHeadService(serialPortData);
NfcHeadService service = new NfcHeadService(serialPortData);
OptoHeadStatus status = service.GetTestingMode();
Assert.IsFalse(OptoHeadStatus.Unknown == status);

View File

@ -1,9 +1,8 @@
using JetBrains.Annotations;
using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Helpers;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NfcC7_DLL.NfcHanler;
using NfcC7_DLL.NfcHanler.Protocols;
using NfcC7_DLL.NfcHanler.Utils;
using NfcC7_DLL.NfcHandler;
using NfcC7_DLL.NfcHandler.Protocols;
using NfcC7_DLL.NfcHandler.Utils;
namespace NfcC7_DLL.Tests.NfcHanler;
@ -21,7 +20,7 @@ public class OptoHeadServiceTest
"HatCliDemo.exe",
74);
NFCHeadService service = new NFCHeadService(serialPortData);
NfcHeadService service = new NfcHeadService(serialPortData);
OptoHeadStatus status = service.SetTestingMode(OptoHeadStatus.OptoHeadC7);
Assert.AreEqual(OptoHeadStatus.OptoHeadC7, status);
//Open serial connection to Optohead

View File

@ -2,7 +2,7 @@ using System;
using System.IO.Ports;
using JetBrains.Annotations;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NfcC7_DLL.NfcHanler.Utils;
using NfcC7_DLL.NfcHandler.Utils;
namespace NfcC7_DLL.Tests.NfcHanler.Utils;

View File

@ -1,12 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<Nullable>disable</Nullable>
<Copyright>Copyright © 2025</Copyright>
<AssemblyVersion>1.1.0.0</AssemblyVersion>
<FileVersion>1.1.0.0</FileVersion>
<TargetFramework>net472</TargetFramework>
<LangVersion>10</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">

View File

@ -0,0 +1,11 @@
using NfcC7_DLL.NfcHandler.Protocols;
namespace NfcC7_DLL.NfcHandler
{
public class HeadInfo
{
string SerialNr { get; set; }
OptoHeadStatus OptoHeadStatus { get; set; }
}
}

View File

@ -1,6 +1,6 @@
namespace NfcC7_DLL.NfcHanler
namespace NfcC7_DLL.NfcHandler
{
public class JsonDataFromPoseidon
{

View File

@ -0,0 +1,219 @@
using System.Text.RegularExpressions;
using NfcC7_DLL.NfcHandler.Protocols;
using NfcC7_DLL.NfcHandler.Utils;
namespace NfcC7_DLL.NfcHandler
{
public class NfcHeadService
{
private bool activeHandlerSessioEnabled = false;
private CliRunner _cliRunner;
private SerialPortData serialPort;
public NfcHeadService(SerialPortData serialPort)
{
this.serialPort = serialPort;
this._cliRunner = null;
ValidateCliFileExistence(true);
}
private CliRunner CliRunner
{
get { return (_cliRunner != null ? _cliRunner : (_cliRunner = new CliRunner(CliLogging))); }
}
private bool CliLogging
{
get { return false; }
}
private static readonly Regex OpticalDataModeRegex = new Regex(
@"(?im)(?:" +
@"^\s*OpticalDataMode\s*Id\s*:\s*([^\r\n]+)\s*$" + // old format
@"|" +
@"""OpticalDataMode""\s*:\s*""?(0x[0-9A-Fa-f]+|\d+)""?" + // JSON format (handles hex and decimal)
@")",
RegexOptions.Compiled);
public bool TryGetOpticalDataMode(string result, out string s)
{
s = null;
if (string.IsNullOrEmpty(result))
return false;
var m = OpticalDataModeRegex.Match(result);
if (!m.Success)
return false;
// one of the groups will be filled
s = !string.IsNullOrEmpty(m.Groups[1].Value)
? m.Groups[1].Value.Trim()
: m.Groups[2].Value.Trim();
return true;
}
private static readonly Regex DeviceIdRegex = new Regex(
@"(?im)(?:" +
@"^\s*Device\s*Id\s*:\s*([^\r\n]+)\s*$" + // old format
@"|" +
@"""DeviceId""\s*:\s*""?([0-9]+)""?" + // JSON format
@")",
RegexOptions.Compiled);
public bool TryGetDeviceId(string result, out string s)
{
s = null;
if (string.IsNullOrEmpty(result))
return false;
var m = DeviceIdRegex.Match(result);
if (!m.Success)
return false;
// one of the groups will be filled
s = !string.IsNullOrEmpty(m.Groups[1].Value)
? m.Groups[1].Value.Trim()
: m.Groups[2].Value.Trim();
return true;
}
private void ValidateCliFileExistence(bool showErrorIfMissing)
{
if (serialPort != null)
{
if (!serialPort.CliExists)
{
throw new Exception("CLI file " + serialPort.SerialPortCmdClientPath +
" does not exist! Current path: " + Environment.CurrentDirectory);
}
}
}
/// <summary>
/// ////////////
/// </summary>
public string GetSerialNr()
{
if (serialPort == null)
throw new Exception("Serial port not initialized");
Task optoheadDeviceIdTask = CliRunner.AddSendAsync(serialPort, SerialPortData.EMeterArg.DeviceId);
var timeOut = CliRunner.AddTimeOut(5000);
var doneTask = CliRunner.WhenAny();
if (timeOut == doneTask)
{
throw new Exception("Timeout");
}
else
{
if (optoheadDeviceIdTask is Task<string>)
{
string serialNr;
if (optoheadDeviceIdTask.Status == TaskStatus.Faulted)
throw new Exception("Error TaskStatus.Faulted");
string result = (optoheadDeviceIdTask as Task<string>).Result;
if (TryGetDeviceId(result, out serialNr))
{
return serialNr;
}
}
}
return null;
}
public OptoHeadStatus SetTestingMode(OptoHeadStatus status)
{
if (serialPort == null)
throw new Exception("Serial port not initialized");
Task optoheadMode =
CliRunner.AddSendAsync(serialPort, SerialPortData.EMeterArg.Optohead, $"0x{((byte)status):X2}");
var timeOut = CliRunner.AddTimeOut(5000);
var doneTask = CliRunner.WhenAny();
if (timeOut == doneTask)
{
throw new Exception("Timeout");
}
else
{
if (optoheadMode is Task<string>)
{
string strOpticalDataMode;
if (optoheadMode.Status == TaskStatus.Faulted)
throw new Exception("Error TaskStatus.Faulted");
string result = (optoheadMode as Task<string>).Result;
if (TryGetOpticalDataMode(result, out strOpticalDataMode))
{
byte value;
if (strOpticalDataMode.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
value = Convert.ToByte(strOpticalDataMode, 16); // interpret as hex
else
value = Convert.ToByte(strOpticalDataMode); // interpret as decimal
OptoHeadStatus optoheadStatus = (OptoHeadStatus)value;
return optoheadStatus;
}
}
}
return OptoHeadStatus.Unknown;
}
public OptoHeadStatus GetTestingMode()
{
if (serialPort == null)
throw new Exception("Serial port not initialized");
Task optoheadMode = CliRunner.AddSendAsync(serialPort, SerialPortData.EMeterArg.Optohead);
var timeOut = CliRunner.AddTimeOut(5000);
var doneTask = CliRunner.WhenAny();
if (timeOut == doneTask)
{
throw new Exception("Timeout");
}
else
{
if (optoheadMode is Task<string>)
{
string strOpticalDataMode;
if (optoheadMode.Status == TaskStatus.Faulted)
throw new Exception("Error TaskStatus.Faulted");
string result = (optoheadMode as Task<string>).Result;
if (TryGetOpticalDataMode(result, out strOpticalDataMode))
{
byte value;
if (strOpticalDataMode.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
value = Convert.ToByte(strOpticalDataMode, 16); // interpret as hex
else
value = Convert.ToByte(strOpticalDataMode); // interpret as decimal
OptoHeadStatus optoheadStatus = (OptoHeadStatus)value;
return optoheadStatus;
}
}
}
return OptoHeadStatus.Unknown;
}
private void SendCommand()
{
}
private string RawDataAnswer()
{
return "";
}
}
}

View File

@ -0,0 +1,109 @@
using System.IO.Ports;
using NfcC7_DLL.NfcHandler.Protocols;
using NfcC7_DLL.NfcHandler.Utils;
namespace NfcC7_DLL.NfcHandler
{
public class OptoHeadService
{
public class Con
{
public string com = "COM5";
public int baudrate = 38400;
public int dataBits = 8;
public Parity parity = Parity.None;
public StopBits stopbits = StopBits.Two;
public int readTimeout = 5000;
public int writeTimeout = 1000;
}
private Con Connection { get; set; }
private SERIAL_Driver driver;
/// <summary>
/// Filed After Run() is called.
/// </summary>
public WaterMetrologyData WaterMetrologyData { get; private set; }
public OptoHeadService(Con con)
{
Connection = con;
driver = new SERIAL_Driver();
}
public bool CreateSerialConnection()
{
bool isopen = false;
Con con = Connection;
byte[] message = {0x00};
byte[] bytesReceived;
if (!driver.isOpen())
{
isopen = driver.OpenConnection(
con.com,
con.baudrate,
con.dataBits,
con.parity,
con.stopbits,
con.readTimeout,
con.writeTimeout);
}
return isopen;
}
public void CloseSerialConnection()
{
dissableRunLoop = true;
driver.Close();
}
public void RunLoop()
{
Task.Run(() => Run());
}
private bool dissableRunLoop = false;
/// <summary>
/// Run the service. Catch one communication to WaterMetrologyData field.
/// </summary>
public void Run()
{
while (!dissableRunLoop)
{
WaterMetrologyData = ParseData(RunReading());
}
}
byte[] RunReading()
{
if (driver.isOpen())
{
driver.SendMessage(new byte[] {0x00}, 1);
return driver.GetRawData();
}
else
{
dissableRunLoop = true;
}
return new byte[] {0xFF};
}
public WaterMetrologyData ParseData(byte[] data)
{
try
{
return WaterMetrologyData.Parse(data, DateTime.Now, "");
}catch(Exception e)
{
return null;
}
}
}
}

View File

@ -0,0 +1,10 @@
namespace NfcC7_DLL.NfcHandler.Protocols
{
public enum OptoHeadStatus : byte
{
Unknown = 0xFF,
OptoHeadDisabled = 0x00,
OptoHeadC2 = 0xC2,
OptoHeadC7 = 0xC7,
}
}

View File

@ -0,0 +1,44 @@
using System;
namespace NfcC7_DLL.NfcHandler.Protocols
{
public class WaterMetrologyData
{
private OptoHeadStatus _optoHeadStatus;
private WaterMetrologyDataC7 c7Data;
private WaterMetrologyDataC2 c2Data;
public WaterMetrologyDataC7 C7Data { get => c7Data; }
public WaterMetrologyDataC2 C2Data { get => c2Data; }
public OptoHeadStatus OptoHeadStatus { get => _optoHeadStatus; }
public static WaterMetrologyData Parse(byte[] data, DateTime dt, string dutinfo)
{
if (data.Length < 24)
{
throw new ArgumentException("Invalid data length for WaterMetrologyData C2.");
}
WaterMetrologyData waterMetrologyData = new WaterMetrologyData();
waterMetrologyData._optoHeadStatus = OptoHeadStatus.Unknown;
// Probably C2
if(data.Length > 24 && data.Length < 48)
{
waterMetrologyData.c2Data = WaterMetrologyDataC2.Parse(data, dt, dutinfo);
waterMetrologyData._optoHeadStatus = OptoHeadStatus.OptoHeadC2;
}
// Probably C7
else if(data.Length >= 48)
{
waterMetrologyData.c7Data = WaterMetrologyDataC7.Parse(data, dt, dutinfo);
waterMetrologyData._optoHeadStatus = OptoHeadStatus.OptoHeadC7;
}
return waterMetrologyData;
}
public override string ToString()
{
return $"Status: {_optoHeadStatus}, C7Data: {c7Data}, C2Data: {c2Data}";
}
}
}

View File

@ -1,4 +1,4 @@
namespace NfcC7_DLL.NfcHanler.Protocols
namespace NfcC7_DLL.NfcHandler.Protocols
{
public class WaterMetrologyDataC2
{

View File

@ -1,4 +1,4 @@
namespace NfcC7_DLL.NfcHanler.Protocols
namespace NfcC7_DLL.NfcHandler.Protocols
{
public class WaterMetrologyDataC7 : WaterMetrologyDataC2
{

View File

@ -1,10 +1,9 @@
using System.Diagnostics;
using System.Reflection;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace NfcC7_DLL.NfcHanler.Utils
namespace NfcC7_DLL.NfcHandler.Utils
{
public class CliRunner
{
@ -123,29 +122,36 @@ namespace NfcC7_DLL.NfcHanler.Utils
CreateNoWindow = true
};
using var process = new Process { StartInfo = psi, EnableRaisingEvents = true };
process.Start();
Task<string> stdOutTask = process.StandardOutput.ReadToEndAsync();
Task<string> stdErrTask = process.StandardError.ReadToEndAsync();
var process = new Process { StartInfo = psi, EnableRaisingEvents = true };
try
{
await Task.WhenAll(stdOutTask, stdErrTask, process.WaitForExitAsync(ct));
}
catch (OperationCanceledException)
{
if (!process.HasExited)
process.Start();
Task<string> stdOutTask = process.StandardOutput.ReadToEndAsync();
Task<string> stdErrTask = process.StandardError.ReadToEndAsync();
try
{
process.Kill();
await Task.WhenAll(stdOutTask, stdErrTask, process.WaitForExitAsync(ct));
}
catch (OperationCanceledException)
{
if (!process.HasExited)
{
process.Kill();
}
throw;
}
throw;
string allOutput = (stdOutTask.Result ?? "") + (stdErrTask.Result ?? "");
//log?.Debug(allOutput);
return allOutput;
}
finally
{
process?.Dispose();
}
string allOutput = (stdOutTask.Result ?? "") + (stdErrTask.Result ?? "");
//log?.Debug(allOutput);
return allOutput;
}
public Task<T> AddRunAndCaptureJsonAsync<T>(SerialPortData data, SerialPortData.EMeterArg eMeterArg) where T : new()
@ -167,20 +173,27 @@ namespace NfcC7_DLL.NfcHanler.Utils
CreateNoWindow = true
};
using var process = new Process { StartInfo = psi, EnableRaisingEvents = true };
process.Start();
var process = new Process { StartInfo = psi, EnableRaisingEvents = true };
try
{
process.Start();
var stdoutTask = process.StandardOutput.ReadToEndAsync();
var stderrTask = process.StandardError.ReadToEndAsync();
var stdoutTask = process.StandardOutput.ReadToEndAsync();
var stderrTask = process.StandardError.ReadToEndAsync();
await Task.WhenAll(stdoutTask, stderrTask, process.WaitForExitAsync(ct));
await Task.WhenAll(stdoutTask, stderrTask, process.WaitForExitAsync(ct));
string allOutput = (stdoutTask.Result ?? "") + (stderrTask.Result ?? "");
//log?.Debug(allOutput);
string allOutput = (stdoutTask.Result ?? "") + (stderrTask.Result ?? "");
//log?.Debug(allOutput);
string json = ExtractJson(allOutput);
if (TryJsonStringDeserialize(json, out T result)) return result;
return default;
string json = ExtractJson(allOutput);
if (TryJsonStringDeserialize(json, out T result)) return result;
return default;
}
finally
{
process?.Dispose();
}
}
public bool TryJsonStringDeserialize<T>(string json, out T runAndCaptureJsonAsync) where T : new()

View File

@ -1,6 +1,6 @@
using System.Diagnostics;
namespace NfcC7_DLL.NfcHanler.Utils
namespace NfcC7_DLL.NfcHandler.Utils
{
public static class ProcessExtensions
{

View File

@ -7,7 +7,7 @@ using System.IO.Ports;
// Author: Venkat, Rajeshwar
//*****************************************************************************
namespace NfcC7_DLL.NfcHanler.Utils
namespace NfcC7_DLL.NfcHandler.Utils
{
public class SERIAL_Driver
{

View File

@ -1,4 +1,4 @@
namespace NfcC7_DLL.NfcHanler.Utils
namespace NfcC7_DLL.NfcHandler.Utils
{
public class SerialPortData
{

View File

@ -5,7 +5,7 @@
// Author: Venkat, Rajeshwar
//*****************************************************************************
namespace NfcC7_DLL.NfcHanler.Utils
namespace NfcC7_DLL.NfcHandler.Utils
{
public static class Tools
{

View File

@ -1,9 +0,0 @@
using NfcC7_DLL.NfcHanler.Protocols;
namespace NfcC7_DLL.NfcHanler;
public class HeadInfo
{
string SerialNr { get; set; }
OptoHeadStatus OptoHeadStatus { get; set; }
}

View File

@ -1,216 +0,0 @@
using System.Text.RegularExpressions;
using System.Windows;
using NfcC7_DLL.NfcHanler.Protocols;
using NfcC7_DLL.NfcHanler.Utils;
namespace NfcC7_DLL.NfcHanler;
public class NFCHeadService
{
private bool activeHandlerSessioEnabled = false;
private CliRunner _cliRunner;
private SerialPortData serialPort;
public NFCHeadService(SerialPortData serialPort)
{
this.serialPort = serialPort;
ValidateCliFileExistence(true);
}
private CliRunner CliRunner
{
get
{
return (_cliRunner != null ?
_cliRunner :
(_cliRunner = new CliRunner(CliLogging)));
}
}
private bool CliLogging{get {return false; }}
private static readonly Regex OpticalDataModeRegex = new Regex(
@"(?im)(?:" +
@"^\s*OpticalDataMode\s*Id\s*:\s*([^\r\n]+)\s*$" + // old format
@"|" +
@"""OpticalDataMode""\s*:\s*""?(0x[0-9A-Fa-f]+|\d+)""?" + // JSON format (handles hex and decimal)
@")",
RegexOptions.Compiled);
public bool TryGetOpticalDataMode(string result, out string s)
{
s = null;
if (string.IsNullOrEmpty(result))
return false;
var m = OpticalDataModeRegex.Match(result);
if (!m.Success)
return false;
// one of the groups will be filled
s = !string.IsNullOrEmpty(m.Groups[1].Value)
? m.Groups[1].Value.Trim()
: m.Groups[2].Value.Trim();
return true;
}
private static readonly Regex DeviceIdRegex = new Regex(
@"(?im)(?:" +
@"^\s*Device\s*Id\s*:\s*([^\r\n]+)\s*$" + // old format
@"|" +
@"""DeviceId""\s*:\s*""?([0-9]+)""?" + // JSON format
@")",
RegexOptions.Compiled);
public bool TryGetDeviceId(string result, out string s)
{
s = null;
if (string.IsNullOrEmpty(result))
return false;
var m = DeviceIdRegex.Match(result);
if (!m.Success)
return false;
// one of the groups will be filled
s = !string.IsNullOrEmpty(m.Groups[1].Value)
? m.Groups[1].Value.Trim()
: m.Groups[2].Value.Trim();
return true;
}
private void ValidateCliFileExistence(bool showErrorIfMissing)
{
if (serialPort != null)
{
if (!serialPort.CliExists)
{
throw new Exception("CLI file " + serialPort.SerialPortCmdClientPath + " does not exist! Current path: " + Environment.CurrentDirectory);
}
}
}
/// <summary>
/// ////////////
/// </summary>
public string? GetSerialNr()
{
if (serialPort == null)
throw new Exception("Serial port not initialized");
Task optoheadDeviceIdTask = CliRunner.AddSendAsync(serialPort, SerialPortData.EMeterArg.DeviceId);
var timeOut = CliRunner.AddTimeOut(5000);
var doneTask = CliRunner.WhenAny();
if (timeOut == doneTask)
{
throw new Exception("Timeout");
}
else
{
if (optoheadDeviceIdTask is Task<string>)
{
string serialNr;
if (optoheadDeviceIdTask.Status == TaskStatus.Faulted)
throw new Exception("Error TaskStatus.Faulted");
string result = (optoheadDeviceIdTask as Task<string>).Result;
if (TryGetDeviceId(result, out serialNr))
{
return serialNr;
}
}
}
return null;
}
public OptoHeadStatus SetTestingMode(OptoHeadStatus status)
{
if (serialPort == null)
throw new Exception("Serial port not initialized");
Task optoheadMode = CliRunner.AddSendAsync(serialPort, SerialPortData.EMeterArg.Optohead, $"0x{((byte)status):X2}");
var timeOut = CliRunner.AddTimeOut(5000);
var doneTask = CliRunner.WhenAny();
if (timeOut == doneTask)
{
throw new Exception("Timeout");
}
else
{
if (optoheadMode is Task<string>)
{
string strOpticalDataMode;
if (optoheadMode.Status == TaskStatus.Faulted)
throw new Exception("Error TaskStatus.Faulted");
string result = (optoheadMode as Task<string>).Result;
if (TryGetOpticalDataMode(result, out strOpticalDataMode))
{
byte value;
if (strOpticalDataMode.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
value = Convert.ToByte(strOpticalDataMode, 16); // interpret as hex
else
value = Convert.ToByte(strOpticalDataMode); // interpret as decimal
OptoHeadStatus optoheadStatus = (OptoHeadStatus)value;
return optoheadStatus;
}
}
}
return OptoHeadStatus.Unknown;
}
public OptoHeadStatus GetTestingMode()
{
if (serialPort == null)
throw new Exception("Serial port not initialized");
Task optoheadMode = CliRunner.AddSendAsync(serialPort, SerialPortData.EMeterArg.Optohead);
var timeOut = CliRunner.AddTimeOut(5000);
var doneTask = CliRunner.WhenAny();
if (timeOut == doneTask)
{
throw new Exception("Timeout");
}
else
{
if (optoheadMode is Task<string>)
{
string strOpticalDataMode;
if (optoheadMode.Status == TaskStatus.Faulted)
throw new Exception("Error TaskStatus.Faulted");
string result = (optoheadMode as Task<string>).Result;
if (TryGetOpticalDataMode(result, out strOpticalDataMode))
{
byte value;
if (strOpticalDataMode.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
value = Convert.ToByte(strOpticalDataMode, 16); // interpret as hex
else
value = Convert.ToByte(strOpticalDataMode); // interpret as decimal
OptoHeadStatus optoheadStatus = (OptoHeadStatus)value;
return optoheadStatus;
}
}
}
return OptoHeadStatus.Unknown;
}
private void SendCommand()
{
}
private string RawDataAnswer()
{
return "";
}
}

View File

@ -1,109 +0,0 @@
using System.IO.Ports;
using System.Windows.Documents;
using NfcC7_DLL.NfcHanler.Protocols;
using NfcC7_DLL.NfcHanler.Utils;
namespace NfcC7_DLL.NfcHanler;
public class OptoHeadService
{
public class Con
{
public string com = "COM5";
public int baudrate = 38400;
public int dataBits = 8;
public Parity parity = Parity.None;
public StopBits stopbits = StopBits.Two;
public int readTimeout = 5000;
public int writeTimeout = 1000;
}
private Con Connection { get; set; }
private SERIAL_Driver driver;
/// <summary>
/// Filed After Run() is called.
/// </summary>
public WaterMetrologyData? WaterMetrologyData { get; private set; }
public OptoHeadService(Con con)
{
Connection = con;
driver = new SERIAL_Driver();
}
public bool CreateSerialConnection()
{
bool isopen = false;
Con con = Connection;
byte[] message = {0x00};
byte[] bytesReceived;
if (!driver.isOpen())
{
isopen = driver.OpenConnection(
con.com,
con.baudrate,
con.dataBits,
con.parity,
con.stopbits,
con.readTimeout,
con.writeTimeout);
}
return isopen;
}
public void CloseSerialConnection()
{
dissableRunLoop = true;
driver.Close();
}
public void RunLoop()
{
Task.Run(() => Run());
}
private bool dissableRunLoop = false;
/// <summary>
/// Run the service. Catch one communication to WaterMetrologyData field.
/// </summary>
public void Run()
{
while (!dissableRunLoop)
{
WaterMetrologyData = ParseData(RunReading());
}
}
byte[] RunReading()
{
if (driver.isOpen())
{
driver.SendMessage(new byte[] {0x00}, 1);
return driver.GetRawData();
}
else
{
dissableRunLoop = true;
}
return [0xFF];
}
public WaterMetrologyData? ParseData(byte[] data)
{
try
{
return WaterMetrologyData.Parse(data, DateTime.Now, "");
}catch(Exception e)
{
return null;
}
}
}

View File

@ -1,9 +0,0 @@
namespace NfcC7_DLL.NfcHanler.Protocols;
public enum OptoHeadStatus : byte
{
Unknown = 0xFF,
OptoHeadDisabled = 0x00,
OptoHeadC2 = 0xC2,
OptoHeadC7 = 0xC7,
}

View File

@ -1,41 +0,0 @@
namespace NfcC7_DLL.NfcHanler.Protocols;
public class WaterMetrologyData
{
private OptoHeadStatus _optoHeadStatus;
private WaterMetrologyDataC7 c7Data;
private WaterMetrologyDataC2 c2Data;
public WaterMetrologyDataC7 C7Data { get => c7Data; }
public WaterMetrologyDataC2 C2Data { get => c2Data; }
public OptoHeadStatus OptoHeadStatus { get => _optoHeadStatus; }
public static WaterMetrologyData? Parse(byte[] data, DateTime dt, string dutinfo)
{
if (data.Length < 24)
{
throw new ArgumentException("Invalid data length for WaterMetrologyData C2.");
}
WaterMetrologyData waterMetrologyData = new WaterMetrologyData();
waterMetrologyData._optoHeadStatus = OptoHeadStatus.Unknown;
// Probably C2
if(data.Length > 24 && data.Length < 48)
{
waterMetrologyData.c2Data = WaterMetrologyDataC2.Parse(data, dt, dutinfo);
waterMetrologyData._optoHeadStatus = OptoHeadStatus.OptoHeadC2;
}
// Probably C7
else if(data.Length >= 48)
{
waterMetrologyData.c7Data = WaterMetrologyDataC7.Parse(data, dt, dutinfo);
waterMetrologyData._optoHeadStatus = OptoHeadStatus.OptoHeadC7;
}
return waterMetrologyData;
}
public override string ToString()
{
return $"Status: {_optoHeadStatus}, C7Data: {c7Data}, C2Data: {c2Data}";
}
}