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

125 lines
3.6 KiB
C#

using System;
using HighWayIot.Log4net;
using HslCommunication;
using HslCommunication.Profinet.Melsec;
namespace HighWayIot.Plc
{ public class PlcConnect
{
private static LogHelper logNet = LogHelper.Instance;
/// <summary>
/// 静态懒加载
/// </summary>
private static readonly MelsecMcNet Instance = new PlcConnect().CreateAb();
private PlcConnect()
{
}
/// <summary>
/// 初始化三菱的服务器
/// </summary>
/// <returns></returns>
private MelsecMcNet CreateAb()
{
string Ip = "";
MelsecMcNet plc = new MelsecMcNet();
plc.CommunicationPipe = new HslCommunication.Core.Pipe.PipeTcpNet(Ip, 0)
{
ConnectTimeOut = 1000, // 连接超时时间,单位毫秒
SleepTime = 0,
SocketKeepAliveTime = -1,
IsPersistentConnection = true,
};
return plc;
}
/// <summary>
/// 读取bool 页面
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
public static bool ReadBool(string address)
{
var result = Instance.ReadBool(address);
return result.IsSuccess && result.Content;
}
/// <summary>
/// plc 是不是保持链接
/// </summary>
public static bool IsConnect
{
get
{
var result = Instance.ReadPlcType();
return result.IsSuccess;
}
}
/// <summary>
/// 写入数据
/// </summary>
/// <param name="address">地址</param>
/// <param name="value">值</param>
/// <param name="type">数据类型</param>
/// <returns></returns>
public static OperateResult Write(string address, object value, DataTypeEnum type)
{
var result = new OperateResult() { IsSuccess = false };
switch (type)
{
case DataTypeEnum.Bool:
result= Instance.Write(address, Convert.ToBoolean(value));
break;
case DataTypeEnum.Byte:
result = Instance.Write(address, Convert.ToByte(value));
break;
case DataTypeEnum.Int16:
result = Instance.Write(address, Convert.ToInt16(value));
break;
case DataTypeEnum.UInt16:
result = Instance.Write(address, Convert.ToUInt16(value));
break;
case DataTypeEnum.Int32:
result = Instance.Write(address, Convert.ToInt32(value));
break;
case DataTypeEnum.UInt32:
result = Instance.Write(address, Convert.ToUInt32(value));
break;
case DataTypeEnum.Int64:
result = Instance.Write(address, Convert.ToInt64(value));
break;
case DataTypeEnum.UInt64:
result = Instance.Write(address, Convert.ToUInt64(value));
break;
case DataTypeEnum.Float:
result = Instance.Write(address, Convert.ToSingle(value));
break;
case DataTypeEnum.Double:
result = Instance.Write(address, Convert.ToDouble(value));
break;
}
logNet.Info($"write 地址[{address}] value:[{value}] type:[{type.ToString()}] result:[{result.IsSuccess}]");
return result;
}
}
}