using System;
using System.Text;
using System.Windows.Forms;
using ZJ_BYD.Untils;
namespace ZJ_BYD.Common
{
public class PlcHelper
{
///
/// 获取PLC值
///
///
///
///
///
public static (bool ok, string val) GetPlcVal(string dataType, string address, string length = "1")
{
var strVal = string.Empty;
try
{
switch (dataType)
{
case "bool":
if (Program.omronCipNet == null)
{
Program.communicationstatus = "异常";
return (false, strVal);
}
else
{
var operateBoolResult = Program.omronCipNet.ReadBool(address);
if (!operateBoolResult.IsSuccess)
{
return (false, strVal);
}
else
{
var boolVal = operateBoolResult.Content;
strVal = boolVal.ToString();
return (true, strVal);
}
}
case "short":
if (Program.omronCipNet == null)
{
Program.communicationstatus = "异常";
return (false, strVal);
}
else
{
var operateShortResult = Program.omronCipNet.ReadInt16(address);
if (!operateShortResult.IsSuccess)
{
return (false, strVal);
}
else
{
var shortVal = operateShortResult.Content;
strVal = shortVal.ToString();
return (true, strVal);
}
}
case "ushort":
if (Program.omronCipNet == null)
{
Program.communicationstatus = "异常";
return (false, strVal);
}
else
{
var operateShortResult = Program.omronCipNet.ReadUInt16(address);
if (!operateShortResult.IsSuccess)
{
return (false, strVal);
}
else
{
var shortVal = operateShortResult.Content;
strVal = shortVal.ToString();
return (true, strVal);
}
}
case "float":
if (Program.omronCipNet == null)
{
Program.communicationstatus = "异常";
return (false, strVal);
}
else
{
var operateFloatResult = Program.omronCipNet.ReadFloat(address);
if (!operateFloatResult.IsSuccess)
{
return (false, strVal);
}
else
{
var floatVal = operateFloatResult.Content;
strVal = floatVal.ToString("f3");
return (true, strVal);
}
}
case "string":
if (Program.omronCipNet == null)
{
Program.communicationstatus = "异常";
return (false, strVal);
}
else
{
var operateFloatResult = Program.omronCipNet.ReadString(address, ushort.Parse(length), Encoding.UTF8);
if (!operateFloatResult.IsSuccess)
{
return (false, strVal);
}
else
{
strVal = operateFloatResult.Content;
return (true, strVal);
}
}
default:
LogHelper.WriteLog("未知数据类型!");
return (false, strVal);
}
}
catch (Exception ex)
{
var errMsg = ex == null ? "未知异常" : ex.Message;
MessageBox.Show($"GetPlcVal方法出发异常:{errMsg},请联系管理员!");
return (false, strVal);
}
}
}
}