using System; using HighWayIot.Log4net; using HslCommunication; using HslCommunication.Profinet.Melsec; namespace HighWayIot.Plc { public class PlcConnect { private static LogHelper logNet = LogHelper.Instance; /// /// 静态懒加载 /// private static readonly MelsecMcNet Instance = new PlcConnect().CreateAb(); private PlcConnect() { } /// /// 初始化三菱的服务器 /// /// 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; } /// /// 读取bool 页面 /// /// /// public static bool ReadBool(string address) { var result = Instance.ReadBool(address); return result.IsSuccess && result.Content; } /// /// plc 是不是保持链接 /// public static bool IsConnect { get { var result = Instance.ReadPlcType(); return result.IsSuccess; } } /// /// 写入数据 /// /// 地址 /// 值 /// 数据类型 /// 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; } } }