using System; using System.Collections.Generic; using Opc.Da; using BottleMgn.Interface; using YCS.Communications.OPC;
namespace BottleMgn.Implements { public class OPCReaderPLC : IOPCReader { private const string OpcServerName = "KEPware.KEPServerEx.V4"; private readonly OPCClient _opcClient;
public OPCReaderPLC() { _opcClient = Var.OpcClient ?? new OPCClient(OpcServerName); Var.OpcClient = _opcClient; }
/// <summary> /// Reads the current value from a PLC address /// </summary> /// <param name="plcAddress">The full OPC address of the PLC item</param> /// <returns>ResultModel containing the read value or error information</returns> public ResultModel ReadPLCValue(string plcAddress) { try { var item = CreateOpcItem(plcAddress);
_opcClient.Connect(); var result = _opcClient.GetItem(item); _opcClient.Disconnect();
if (result.Value == null) { return ResultMsg.OPCClientReaderError(); }
/// <summary> /// Writes a value to a PLC address /// </summary> /// <param name="plcAddress">The full OPC address of the PLC item</param> /// <param name="value">The value to write (will be converted to appropriate type)</param> /// <returns>ResultModel indicating success or failure</returns> public ResultModel WritePLCValue(string plcAddress, object value) { try { var item = new ItemValue { ClientHandle = Guid.NewGuid().ToString(), ItemPath = GetItemPath(plcAddress), ItemName = GetItemName(plcAddress), Value = value };
_opcClient.Connect(); var result = _opcClient.SetItem(item); _opcClient.Disconnect();
// Convert boolean values to "1"/"0" for consistency if (stringValue.Equals("true", StringComparison.OrdinalIgnoreCase)) return "1"; if (stringValue.Equals("false", StringComparison.OrdinalIgnoreCase)) return "0";
return stringValue; }
private string GetItemPath(string fullAddress) { // Implement logic to extract path from full address // Example: if fullAddress is "PLC1.Machine1.Tag1" return "PLC1.Machine1" var lastDot = fullAddress.LastIndexOf('.'); return lastDot > 0 ? fullAddress.Substring(0, lastDot) : string.Empty; }
private string GetItemName(string fullAddress) { // Implement logic to extract name from full address // Example: if fullAddress is "PLC1.Machine1.Tag1" return "Tag1" var lastDot = fullAddress.LastIndexOf('.'); return lastDot > 0 ? fullAddress.Substring(lastDot + 1) : fullAddress; } } }