110 lines
3.0 KiB
C#
110 lines
3.0 KiB
C#
using Cowain.Bake.BLL;
|
||
using Cowain.Bake.Common;
|
||
using Cowain.Bake.Common.Core;
|
||
using HslCommunication;
|
||
using HslCommunication.Core;
|
||
using HslCommunication.ModBus;
|
||
using Newtonsoft.Json;
|
||
using Prism.Services.Dialogs;
|
||
using System;
|
||
using System.Collections.Generic;
|
||
using System.Collections.ObjectModel;
|
||
using System.Diagnostics;
|
||
using System.Linq;
|
||
using System.Net;
|
||
using System.Reflection;
|
||
using System.Text;
|
||
using System.Threading;
|
||
using System.Threading.Tasks;
|
||
using Unity;
|
||
using Hsl = HslCommunication.Profinet.Omron;
|
||
|
||
|
||
namespace Cowain.Bake.Communication.PLC
|
||
{
|
||
public class PLC_ModbusTcp : PLCBase
|
||
{
|
||
public override int Port { get; set; } = 502;
|
||
private ModbusTcpNet plc;
|
||
|
||
public PLC_ModbusTcp(IUnityContainer unityContainer, IDialogService dialogService) : base(unityContainer, dialogService)
|
||
{
|
||
|
||
}
|
||
|
||
public override void Close()
|
||
{
|
||
IsConnect = false;
|
||
try
|
||
{
|
||
plc?.ConnectClose();
|
||
plc?.Dispose();
|
||
plc = null;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
LogHelper.Instance.Error($"关闭PLC连接失败:{ex}");
|
||
}
|
||
|
||
|
||
}
|
||
|
||
public override void Connect()
|
||
{
|
||
Close();
|
||
if (plc == null)
|
||
{
|
||
plc = new ModbusTcpNet();
|
||
this.PLC = plc;
|
||
this.ByteTransform = plc.ByteTransform;
|
||
plc.ConnectTimeOut = 3000;
|
||
}
|
||
try
|
||
{
|
||
plc.IpAddress = this.IpAddress;
|
||
plc.Port = this.Port;
|
||
plc.ByteTransform.DataFormat = HslCommunication.Core.DataFormat.CDAB;
|
||
var result = plc.ConnectServer();
|
||
if (result.IsSuccess)
|
||
{
|
||
IsConnect = true;
|
||
}
|
||
else
|
||
{
|
||
IsConnect = false;
|
||
LogHelper.Instance.Error("连接PLC失败,请检查网络和参数");
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
IsConnect = false;
|
||
LogHelper.Instance.Error($"连接PLC失败{ex}");
|
||
}
|
||
}
|
||
|
||
public override void GetJsonParam(string param)
|
||
{
|
||
dynamic d = JsonConvert.DeserializeObject<dynamic>(param);
|
||
this.IpAddress = d.Ip;
|
||
this.Port = d.Port;
|
||
}
|
||
public override void GetReadAddress()
|
||
{
|
||
foreach (var storage in Storages)
|
||
{
|
||
storage.ReadAddress = storage.AddressType + ";" + storage.StartAddress;
|
||
}
|
||
}
|
||
|
||
public override OperateResult Write<T>(string address, T data, int maxCount = 5)
|
||
{
|
||
return Write<T>(plc, address, data, maxCount);
|
||
}
|
||
|
||
public override OperateResult Writes(string[] tags, object[] values, int maxCount = Global.MAX_READS)
|
||
{
|
||
return null;
|
||
}
|
||
}
|
||
}
|