Check-in Source P.3

Signed-off-by: mharb <mharb@noreply.localhost>
This commit is contained in:
2025-08-02 19:41:42 -04:00
parent 4c83529292
commit 53e8ee1d7a
4 changed files with 137 additions and 0 deletions

View File

@@ -0,0 +1,69 @@
using System;
using Modbus.Device;
using static System.Console;
namespace ProtosXdigitalDemo
{
internal class RegisterReader
{
private readonly ModbusIpMaster _master;
public RegisterReader(ModbusIpMaster master)
{
_master = master;
}
public void ReadAll()
{
WriteLine("Reading all input registers…");
try
{
// Read all input registers as ushorts
ushort[] registers = _master.ReadInputRegisters(0, ChannelCache.AnalogInputCount);
Display(registers);
// Convert to bool[] and display
bool[] bits = ConvertRegistersToBools(registers);
Display(bits);
}
catch (Exception ex)
{
WriteLine($"[Error] Reading input registers failed → {ex.Message}");
PromptKey("Press any key to continue…");
}
}
private void Display(ushort[] registers)
{
WriteLine("Input Registers (ushort):");
for (int i = 0; i < registers.Length; i++)
{
WriteLine($" Register #{i + 1}: {registers[i]}");
}
}
private void Display(bool[] bits)
{
WriteLine("Flattened Bits:");
for (int i = 0; i < bits.Length; i++)
{
WriteLine($" Bit #{i + 1}: {(bits[i] ? "On" : "Off")}");
}
}
// Map a ushort's bits to bools using AND operator
private bool[] ConvertRegistersToBools(ushort[] registers)
{
return registers.SelectMany(r => Enumerable.Range(0, 16)
.Select(bit => ((r >> bit) & 1) == 1))
.ToArray();
}
private void PromptKey(string prompt)
{
WriteLine(prompt);
ReadKey(intercept: true);
}
}
}