You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

138 lines
2.8 KiB

using EasyModbus;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MasterClient.Client
{
class ModbusMaster : ICommClient
{
private ModbusClient client;
public byte identifier = 1;
public ModbusMaster(byte identifier = 1)
{
client = new ModbusClient();
this.identifier = identifier;
}
public void Connect()
{
try
{
if (client.Connected)
client.Disconnect();
client.Connect();
}
catch (Exception ex)
{
throw ex;
}
}
public void Disconnect()
{
try
{
client.Disconnect();
}
catch (Exception ex)
{
throw ex;
}
}
public bool GetStatus()
{
if (client == null)
return false;
return client.Connected;
}
public string ReadValue(string name)
{
if (!client.Connected)
throw new Exception("Disconnected status");
try
{
int address;
if (!int.TryParse(name, out address))
throw new Exception("cannot parse as int");
string value = "";
if (address >= 40001 && address < 50000)
value = client.ReadHoldingRegisters(address - 40001, 1)[0].ToString();
else if (address >= 30001 && address < 40000)
value = client.ReadInputRegisters(address - 30001, 1)[0].ToString();
else if (address >= 10001 && address < 20000)
value = client.ReadInputRegisters(address - 10001, 1)[0].ToString();
else if (address >= 1 && address < 10000)
value = client.ReadCoils(address - 1, 1)[0].ToString();
else
throw new Exception("Address is unavailable. (0x, 1x, 3x, 4x only)");
return value;
}
catch (Exception ex)
{
throw ex;
}
}
public void SetServer(string ip, int port)
{
client.IPAddress = ip;
client.Port = port;
client.UnitIdentifier = this.identifier;
}
public void WriteValue(string name, string value)
{
if (!client.Connected)
throw new Exception("Disconnected status");
try
{
// 0x, 4x 만 쓰기 가능
int address;
if (!int.TryParse(name, out address))
throw new Exception("Cannot parse as int");
if (address >= 40001 && address < 50000)
{
int parsed = 0;
if (!int.TryParse(value, out parsed))
throw new Exception("Value is not integer");
client.WriteSingleRegister(address - 40001, parsed);
}
else if (address >= 1 && address < 10000)
{
bool parsed = false;
if (value == "0")
parsed = false;
else if (value == "1")
parsed = true;
else if (!bool.TryParse(value, out parsed))
throw new Exception("Value is not boolean");
client.WriteSingleCoil(address - 1, parsed);
}
else
throw new Exception("Address is unavailable (0x, 4x only)");
}
catch (Exception ex)
{
throw ex;
}
}
}
}