Innovenergy_trunk/csharp/Lib/Devices/IEM3kGridMeter/IEM3kGridMeterDevice.cs

132 lines
3.6 KiB
C#

/*using InnovEnergy.Lib.Protocols.Modbus.Channels;
using InnovEnergy.Lib.Protocols.Modbus.Clients;
using InnovEnergy.Lib.Protocols.Modbus.Slaves;
using InnovEnergy.Lib.Utils;
namespace InnovEnergy.Lib.Devices.IEM3kGridMeter;
public class Iem3KGridMeterDevice: ModbusDevice<Iem3KGridMeterRegisters>
{
public Iem3KGridMeterDevice(String hostname, UInt16 port = 502, Byte slaveId = 1) : this(new TcpChannel(hostname, port), slaveId)
{
}
private Iem3KGridMeterDevice(Channel channel, Byte slaveId = 1) : base(new ModbusTcpClient(channel, slaveId))
{
}
public Iem3KGridMeterDevice(ModbusClient client) : base(client)
{
}
public new Iem3KGridMeterRegisters? Read()
{
try
{
return base.Read();
}
catch
{
// TODO: Log
$"Failed to read data from {nameof(Iem3KGridMeterDevice)}".WriteLine();
return null;
}
}
public new void Write(Iem3KGridMeterRegisters registers)
{
try
{
base.Write(registers);
}
catch
{
// TODO: Log
$"Failed to write data to {nameof(Iem3KGridMeterDevice)}".WriteLine();
}
}
}*/
using InnovEnergy.Lib.Protocols.Modbus.Channels;
using InnovEnergy.Lib.Protocols.Modbus.Clients;
using InnovEnergy.Lib.Protocols.Modbus.Slaves;
using InnovEnergy.Lib.Utils;
using System;
namespace InnovEnergy.Lib.Devices.IEM3kGridMeter
{
public class Iem3KGridMeterDevice : ModbusDevice<Iem3KGridMeterRegisters>
{
private readonly string _hostname;
private readonly ushort _port;
private readonly byte _slaveId;
public Iem3KGridMeterDevice(string hostname, ushort port = 502, byte slaveId = 1)
: this(new TcpChannel(hostname, port), slaveId)
{
_hostname = hostname ?? throw new ArgumentNullException(nameof(hostname));
_port = port;
_slaveId = slaveId;
}
private Iem3KGridMeterDevice(TcpChannel channel, byte slaveId = 1)
: base(new ModbusTcpClient(channel, slaveId))
{
_hostname = channel.Host;
_port = channel.Port;
_slaveId = slaveId;
Console.WriteLine($"Initializing Iem3KGridMeterDevice with channel: {channel.Host}:{channel.Port}");
}
public Iem3KGridMeterDevice(ModbusClient client)
: base(client)
{
if (client is ModbusTcpClient tcpClient)
{
_hostname = tcpClient.Channel.Host;
_port = tcpClient.Channel.Port;
_slaveId = tcpClient.SlaveId;
}
else
{
throw new ArgumentException("Invalid client type", nameof(client));
}
Console.WriteLine("Initializing Iem3KGridMeterDevice with ModbusClient");
}
public new Iem3KGridMeterRegisters? Read()
{
try
{
Console.WriteLine($"Attempting to read data from {_hostname}:{_port} with slaveId {_slaveId}");
return base.Read();
}
catch (Exception ex)
{
Console.WriteLine($"Failed to read data from {nameof(Iem3KGridMeterDevice)}: {ex.Message}");
return null;
}
}
public new void Write(Iem3KGridMeterRegisters registers)
{
try
{
base.Write(registers);
}
catch (Exception ex)
{
Console.WriteLine($"Failed to write data to {nameof(Iem3KGridMeterDevice)}: {ex.Message}");
}
}
}
}