123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614 |
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Threading;
- using System.Xml;
- using Aitex.Core.RT.DataCenter;
- using Aitex.Core.RT.Event;
- using Aitex.Core.RT.IOCore;
- using Aitex.Core.RT.Log;
- using Aitex.Core.RT.OperationCenter;
- using Aitex.Core.RT.SCCore;
- using Aitex.Core.Util;
- using MECF.Framework.Common.Communications;
- using MECF.Framework.Common.PLC;
- using MECF.Framework.RT.Core.IoProviders;
- using MECF.Framework.RT.Core.IoProviders.Common;
- namespace JetVirgoPM.Devices
- {
- public class PlcAdapter : IoProvider, IConnection
- {
- public string Address
- {
- get { return $"{_ip}:{_port}"; }
- }
- public bool IsConnected
- {
- get { return IsOpened; }
- }
- public bool Connect()
- {
- return true;
- }
- public bool Disconnect()
- {
- return true;
- }
- private string _localIp = "127.0.0.1";
- private int _socketId = 101;
- private int _stationId = 102;
- private byte[] _bufferIn;
- private byte[] _bufferOut;
- private IPlc _plc = null;
- private bool _isOpened = false;
- private string _ip = "192.168.10.10";
- private int _port = 9600;
- private int _aoBlockStartPosition = 1000;
- private int _aiBlockStartPosition = 2000;
- private int _doBlockStartPosition = 0;
- private int _diBlockStartPosition = 20;
- private string _diBlockType = "W";
- private string _doBlockType = "W";
- private string _aiBlockType = "D";
- private string _aoBlockType = "D";
- R_TRIG _failedTrigger = new R_TRIG();
- private Stopwatch stopwatchDi = new Stopwatch();
- private Stopwatch stopwatchDo = new Stopwatch();
- private Stopwatch stopwatchAi = new Stopwatch();
- private Stopwatch stopwatchAo = new Stopwatch();
- private int comunicationSpanDi;
- private int comunicationSpanDo;
- private int comunicationSpanAi;
- private int comunicationSpanAo;
- protected int comunicationSpanTotal;
- private Stopwatch stopwatchTotal = new Stopwatch();
- //private int diStartAddress;
- //private int doStartAddress;
- //private int aiStartAddress;
- //private int aoStartAddress;
- //private List<IoBlockItem> _blockSectionsDemand;
- private int plcCollectionInterval;
- private R_TRIG _trigConnected = new R_TRIG();
- public override void Initialize(string module, string name, List<IoBlockItem> lstBuffers, IIoBuffer buffer, XmlElement nodeParameter, string ioMappingPathFile, string ioModule)
- {
- Module = module;
- Name = name;
- _source = module + "." + name;
- _buffer = buffer;
- _nodeParameter = nodeParameter;
- _blockSections = lstBuffers;
- buffer.SetBufferBlock(_source, lstBuffers);
- buffer.SetIoMapByModule(_source, 0, ioMappingPathFile, ioModule);
- SetParameter(nodeParameter);
- State = IoProviderStateEnum.Uninitialized;
- plcCollectionInterval = SC.ContainsItem("System.PlcCollectionInterval") ? SC.GetValue<int>("System.PlcCollectionInterval") : 50;
- _thread = new PeriodicJob(plcCollectionInterval, OnTimer, name);
- ConnectionManager.Instance.Subscribe(Name, this);
- DATA.Subscribe($"{Module}.{Name}.IsConnected", () => _plc == null ? false : _plc.CheckIsConnected());
- OP.Subscribe($"{Module}.{Name}.Reconnect", (string cmd, object[] args) =>
- {
- Close();
- Open();
- return true;
- });
- //if (SC.GetValue<bool>("System.IsSimulatorMode"))
- //{
- // Open();
- //}
- }
- protected override bool OnTimer()
- {
- if (_plc == null)
- {
- Open();
- }
- if (State != IoProviderStateEnum.Opened || _plc == null || !_plc.CheckIsConnected())
- return true;
- _trigConnected.CLK = _plc.CheckIsConnected();
- try
- {
- stopwatchTotal.Start();
- foreach (var bufferSection in _blockSections)
- {
- if (bufferSection.Type == IoType.DI)
- {
- stopwatchDi.Start();
- bool[] diBuffer = ReadDi(bufferSection.Offset, bufferSection.Size);
- if (diBuffer != null)
- {
- _buffer.SetDiBuffer(_source, bufferSection.Offset, diBuffer);
- //TraceArray(diBuffer);
- }
- stopwatchDi.Stop();
- }
- else if (bufferSection.Type == IoType.AI)
- {
- stopwatchAi.Start();
- if (bufferSection.AIOType == typeof(float))
- {
- float[] aiBuffer = ReadAiFloat(bufferSection.Offset, bufferSection.Size);
- if (aiBuffer != null)
- {
- _buffer.SetAiBufferFloat(_source, bufferSection.Offset, aiBuffer);
- }
- }
- else
- {
- short[] aiBuffer = ReadAi(bufferSection.Offset, bufferSection.Size);
- if (aiBuffer != null)
- {
- _buffer.SetAiBuffer(_source, bufferSection.Offset, aiBuffer);
- }
- }
- stopwatchAi.Stop();
- }
- else if (bufferSection.Type == IoType.DO)
- {
- if (SC.GetValue<bool>("System.IsSimulatorMode"))
- {
- Dictionary<int, bool[]> dos = _buffer.GetDoBuffer(_source);
- if (dos != null)
- {
- foreach (var doo in dos)
- {
- WriteDo(_doBlockStartPosition, doo.Value);
- }
- }
- continue;
- }
- if (_trigConnected.Q)
- {
- bool[] doBuffer = ReadDo(bufferSection.Offset, bufferSection.Size);
- if (doBuffer != null)
- {
- _buffer.SetDoBuffer(_source, bufferSection.Offset, doBuffer);
- }
- }
- }
- else if (bufferSection.Type == IoType.AO)
- {
- if (bufferSection.AIOType == typeof(float))
- {
- if (SC.GetValue<bool>("System.IsSimulatorMode"))
- {
- Dictionary<int, float[]> aos = _buffer.GetAoBufferFloat(_source);
- if (aos != null)
- {
- foreach (var ao in aos)
- {
- WriteAoFloat(_aoBlockStartPosition, ao.Value);
- }
- }
- continue;
- }
- if (_trigConnected.Q)
- {
- float[] aoBuffer = ReadAoFloat(bufferSection.Offset, bufferSection.Size);
- if (aoBuffer != null)
- {
- _buffer.SetAoBufferFloat(_source, bufferSection.Offset, aoBuffer);
- }
- }
- }
- else
- {
- if (_trigConnected.Q)
- {
- short[] aoBuffer = ReadAo(bufferSection.Offset, bufferSection.Size);
- if (aoBuffer != null)
- {
- _buffer.SetAoBuffer(_source, bufferSection.Offset, aoBuffer);
- }
- }
- }
- }
- }
- comunicationSpanDi = (int)stopwatchDi.ElapsedMilliseconds;
- stopwatchDi.Reset();
- comunicationSpanAi = (int)stopwatchAi.ElapsedMilliseconds;
- stopwatchAi.Reset();
- //stopwatchAo.Start();
- //Dictionary<int, short[]> aos = _buffer.GetAoBuffer(_source);
- //if (aos != null)
- //{
- // foreach (var ao in aos)
- // {
- // WriteAo(aoStartAddress, ao.Value);
- // }
- //}
- //stopwatchAo.Stop();
- //comunicationSpanAo = (int)stopwatchAo.ElapsedMilliseconds;
- //stopwatchAo.Reset();
- //stopwatchDo.Start();
- //Dictionary<int, bool[]> dos = _buffer.GetDoBuffer(_source);
- //if (dos != null)
- //{
- // foreach (var doo in dos)
- // {
- // WriteDo(doStartAddress, doo.Value);
- // }
- //}
- //stopwatchDo.Stop();
- //comunicationSpanDo = (int)stopwatchDo.ElapsedMilliseconds;
- //stopwatchDo.Reset();
- stopwatchTotal.Stop();
- comunicationSpanTotal = (int)stopwatchTotal.ElapsedMilliseconds;
- stopwatchTotal.Reset();
- }
- catch (Exception ex)
- {
- LOG.Error($"{Name} {ex}");
- //SetState(IoProviderStateEnum.Error);
- Thread.Sleep(1000);
- Close();
- Open();
- }
- _trigError.CLK = State == IoProviderStateEnum.Error;
- if (_trigError.Q)
- {
- EV.PostAlarmLog(Module, $"{_source} PLC {_ip}:{_port} error");
- }
- _trigNotConnected.CLK = State != IoProviderStateEnum.Opened;
- if (_trigNotConnected.T)
- {
- EV.PostInfoLog(Module, $"{_source} connected");
- }
- if (_trigNotConnected.R)
- {
- EV.PostAlarmLog(Module, $"{_source} PLC {_ip}:{_port} not connected");
- }
- return true;
- }
- protected override void SetParameter(XmlElement nodeParameter)
- {
- string strIp = nodeParameter.GetAttribute("ip");
- string strPort = nodeParameter.GetAttribute("port");
- string localIp = nodeParameter.GetAttribute("localIp");
- string diBlockType = nodeParameter.GetAttribute("diBlockType");
- string doBlockType = nodeParameter.GetAttribute("doBlockType");
- string aiBlockType = nodeParameter.GetAttribute("aiBlockType");
- string aoBlockType = nodeParameter.GetAttribute("aoBlockType");
- string diStartPosition = nodeParameter.GetAttribute("diStartPosition");
- string doStartPosition = nodeParameter.GetAttribute("doStartPosition");
- string aiStartPosition = nodeParameter.GetAttribute("aiStartPosition");
- string aoStartPosition = nodeParameter.GetAttribute("aoStartPosition");
- _port = int.Parse(strPort);
- _ip = strIp;
- _localIp = localIp;
- //if (!Enum.TryParse(diBlockType, out _diBlockType))
- //{
- // LOG.Error($"plc config error, block type {diBlockType} not valid");
- //}
- //if (!Enum.TryParse(doBlockType, out _doBlockType))
- //{
- // LOG.Error($"plc config error, block type {doBlockType} not valid");
- //}
- //if (!Enum.TryParse(aiBlockType, out _aiBlockType))
- //{
- // LOG.Error($"plc config error, block type {aiBlockType} not valid");
- //}
- //if (!Enum.TryParse(aoBlockType, out _aoBlockType))
- //{
- // LOG.Error($"plc config error, block type {aoBlockType} not valid");
- //}
- _diBlockType = nodeParameter.GetAttribute("diBlockType").Substring(0, 1);
- _doBlockType = nodeParameter.GetAttribute("doBlockType").Substring(0, 1);
- _aiBlockType = nodeParameter.GetAttribute("aiBlockType").Substring(0, 1);
- _aoBlockType = nodeParameter.GetAttribute("aoBlockType").Substring(0, 1);
- if (!int.TryParse(diStartPosition, out _diBlockStartPosition))
- {
- LOG.Error($"plc config error, start position {diStartPosition} not valid");
- }
- if (!int.TryParse(doStartPosition, out _doBlockStartPosition))
- {
- LOG.Error($"plc config error, start position {doStartPosition} not valid");
- }
- if (!int.TryParse(aiStartPosition, out _aiBlockStartPosition))
- {
- LOG.Error($"plc config error, start position {aiStartPosition} not valid");
- }
- if (!int.TryParse(aoStartPosition, out _aoBlockStartPosition))
- {
- LOG.Error($"plc config error, start position {aoStartPosition} not valid");
- }
- }
- protected override void Open()
- {
- if (SC.GetValue<bool>("System.IsSimulatorMode"))
- {
- _plc = new WcfPlc(Module, Name, $"WcfPlc_{Module}");
- _plc.Initialize();
- }
- else
- {
- _plc = new FinsTcpPlc(_ip, _port, _localIp);
- }
- _bufferOut = new byte[2048];
- _bufferIn = new byte[2048];
- try
- {
- OperateResult connect = _plc.Connect() ? OperateResult.CreateSuccessResult() : new OperateResult();
- if (connect.IsSuccess)
- {
- SetState(IoProviderStateEnum.Opened);
- }
- }
- catch (Exception ex)
- {
- LOG.Error(ex.Message);
- }
- }
- protected override void Close()
- {
- _plc.Disconnect();
- SetState(IoProviderStateEnum.Closed);
- }
- protected override bool[] ReadDi(int offset, int size)
- {
- bool[] buff = DoReadDi(offset, (ushort)size);
- return buff;
- }
- protected bool[] ReadDo(int offset, int size)
- {
- bool[] buff = DoReadDo(offset, (ushort)size);
- return buff;
- }
- protected override short[] ReadAi(int offset, int size)
- {
- short[] buff = DoReadAi(offset, (ushort)size);
- return buff;
- }
- protected override float[] ReadAiFloat(int offset, int size)
- {
- float[] buff = DoReadAiFloat(offset, (ushort)size);
- return buff;
- }
- protected float[] ReadAoFloat(int offset, int size)
- {
- float[] buff = DoReadAoFloat(offset, (ushort)size);
- return buff;
- }
- protected short[] ReadAo(int offset, int size)
- {
- short[] buff = DoReadAo(offset, (ushort)size);
- return buff;
- }
- protected override void WriteDo(int offset, bool[] data)
- {
- DoWriteDo(offset, data);
- }
- protected override void WriteAo(int offset, short[] data)
- {
- DoWriteAo(offset, data);
- }
- protected override void WriteAoFloat(int offset, float[] data)
- {
- DoWriteAoFloat(offset, data);
- }
- #region PLC read write
- private short[] DoReadAi(int offset, ushort size)
- {
- if (_plc.ReadInt16($"{_aiBlockType}{_aiBlockStartPosition + offset}", out short[] result, size, out string reason))
- {
- return result;
- }
- LOG.Write(reason);
- return null;
- }
- private float[] DoReadAiFloat(int offset, ushort size)
- {
- if (_plc.ReadFloat($"{_aiBlockType}{_aiBlockStartPosition + offset}", out float[] result, size, out string reason))
- {
- return result;
- }
- LOG.Write(reason);
- return null;
- }
- private short[] DoReadAo(int offset, ushort size)
- {
- if (_plc.ReadInt16($"{_aoBlockType}{_aoBlockStartPosition + offset}", out short[] result, size, out string reason))
- {
- return result;
- }
- LOG.Write(reason);
- return null;
- }
- private float[] DoReadAoFloat(int offset, ushort size)
- {
- if (_plc.ReadFloat($"{_aoBlockType}{_aoBlockStartPosition + offset}", out float[] result, size, out string reason))
- {
- return result;
- }
- LOG.Write(reason);
- return null;
- }
- private bool DoWriteAoFloat(int offset, float[] data, int total = 0, int count = 100)
- {
- if (_plc.WriteFloat($"{_aoBlockType}{_aoBlockStartPosition + offset}", data, out string reason))
- {
- return true;
- }
- LOG.Write(reason);
- return false;
- }
- private bool DoWriteAo(int offset, short[] data, int total = 0, int count = 100)
- {
- if (_plc.WriteInt16($"{_aoBlockType}{_aoBlockStartPosition + offset}", data, out string reason))
- {
- return true;
- }
- LOG.Write(reason);
- return false;
- }
- private bool[] DoReadDi(int offset, ushort size)
- {
- if (_plc.ReadBool($"{_diBlockType}{_diBlockStartPosition + (offset >> 4)}.{offset & 0x0f}", out bool[] result, size, out string reason))
- {
- return result;
- }
- LOG.Write(reason);
- return null;
- }
- private bool[] DoReadDo(int offset, ushort size)
- {
- if (_plc.ReadBool($"{_doBlockType}{_doBlockStartPosition + (offset >> 4)}.{offset & 0x0f}", out bool[] result, size, out string reason))
- {
- return result;
- }
- LOG.Write(reason);
- return null;
- }
- private bool DoWriteDo(int offset, bool[] data)
- {
- if (_plc.WriteBool($"{_doBlockType}{_doBlockStartPosition + (offset >> 4)}.{offset & 0x0f}", data, out string reason))
- {
- return true;
- }
- LOG.Write(reason);
- return false;
- }
- #endregion
- public override bool SetValue(AOAccessor aoItem, short value)
- {
- if (State != IoProviderStateEnum.Opened)
- return false;
- return true;
- }
- public override bool SetValueFloat(AOAccessor aoItem, float value)
- {
- if (State != IoProviderStateEnum.Opened)
- return false;
- return DoWriteAoFloat(aoItem.Index << 1, new[] { value });
- }
- public override bool SetValue(DOAccessor doItem, bool value)
- {
- if (State != IoProviderStateEnum.Opened)
- return false;
- return DoWriteDo(doItem.Index, new[] { value });
- }
- }
- }
|