using HslCommunication;
|
using HslCommunication.Core.Pipe;
|
using HslCommunication.Profinet.Siemens;
|
|
namespace Plugin.CurrentSensorControl.Entity
|
{
|
public class S7Context
|
{
|
private static Dictionary<string, SiemensS7Net> cache = new Dictionary<string, SiemensS7Net>();
|
public static Dictionary<string, PLCTagData> dataCache = new Dictionary<string, PLCTagData>();
|
|
private static string Ip;
|
private static int Port;
|
|
public static void Init(string ip, int port)
|
{
|
Ip = ip;
|
Port = port;
|
}
|
|
|
public static SiemensS7Net Get(string name)
|
{
|
if (!cache.ContainsKey(name))
|
{
|
var client = new SiemensS7Net(SiemensPLCS.S1500);
|
cache[name] = client;
|
PipeTcpNet pipeTcpNet = new PipeTcpNet(Ip, Port);
|
pipeTcpNet.ConnectTimeOut = 5000;
|
pipeTcpNet.ReceiveTimeOut = 10000;
|
client.CommunicationPipe = pipeTcpNet;
|
client.ConnectServer();
|
}
|
return cache[name];
|
}
|
|
public static bool Connect(string name)
|
{
|
|
return false;
|
}
|
|
public static bool GetData(SiemensS7Net api, string name, out object val)
|
{
|
val = null;
|
if (dataCache.ContainsKey(name))
|
{
|
var data = dataCache[name];
|
string address = data.Address;
|
if (data.Type == PLCTagType.BOOL)
|
{
|
var res = api.ReadBool(address);
|
val = res.Content;
|
return res.IsSuccess;
|
}
|
else if (data.Type == PLCTagType.SHORT)
|
{
|
var res = api.ReadInt16(address);
|
val = res.Content;
|
return res.IsSuccess;
|
}
|
else if (data.Type == PLCTagType.INT)
|
{
|
var res = api.ReadInt32(address);
|
val = res.Content;
|
return res.IsSuccess;
|
}
|
else if (data.Type == PLCTagType.FLOAT)
|
{
|
var res = api.ReadFloat(address);
|
val = res.Content;
|
return res.IsSuccess;
|
}
|
return false;
|
}
|
else
|
{
|
return false;
|
}
|
}
|
|
public static bool WriteData(SiemensS7Net api, string name, object val)
|
{
|
if (dataCache.ContainsKey(name))
|
{
|
var data = dataCache[name];
|
string address = data.Address;
|
OperateResult res;
|
switch (data.Type)
|
{
|
case PLCTagType.BOOL:
|
res = api.Write(address, (bool)val);
|
break;
|
case PLCTagType.SHORT:
|
res = api.Write(address, (short)val);
|
break;
|
case PLCTagType.INT:
|
res = api.Write(address, (int)val);
|
break;
|
case PLCTagType.FLOAT:
|
res = api.Write(address, (float)val);
|
break;
|
default:
|
return true;
|
}
|
return res.IsSuccess;
|
}
|
else
|
{
|
return false;
|
}
|
}
|
}
|
}
|