123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880 |
- using Aitex.Core.RT.DataCenter;
- using Aitex.Core.RT.Device;
- using Aitex.Core.RT.Event;
- using Aitex.Core.RT.Log;
- using Aitex.Core.RT.OperationCenter;
- using Aitex.Core.Util;
- using MECF.Framework.Common.Communications;
- using MECF.Framework.RT.Core.IoProviders;
- using MECF.Framework.RT.Core.IoProviders.Mitsubishis;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Net;
- using System.Net.Sockets;
- using System.Runtime.InteropServices;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Xml;
- namespace EFEMRT.Devices
- {
- public class SuperMCProtocolPLC : IoProvider
- {
- private string _ip = "127.0.0.1";
- private string _localIp = "127.0.0.1";
- private int _port = 6731;
- private int _socketId = 101;
- private int _stationId = 102;
- private byte[] _bufferIn;
- private byte[] _bufferOut;
- private MCProtocol.MC_COMMAND_HEADER _header;
- //private MCProtocol.MC_RESPONSE_HEADER _response;
- private MCProtocol.MC_BATCH_COMMAND _batchCommand;
- private MCSocket _socket;
- private int demandAiFrom; //should be the same the offset in lstBuffers
- private int demandAiSize;
- private int demandAoFrom; //should be the same the offset in lstBuffers
- private int demandAoSize;
- private bool inDemanding = false;
- private string aiStoragename = "R";
- private string aoStoragename = "R";
- private string diStoragename = "M";
- private string doStoragename = "M";
- private int perIoLength = 960;
- private int diStartOffset=0;
- private int doStartOffset=0;
- private int aiStartOffset=0;
- private int aoStartOffset=0;
- 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 List<IoBlockItem> _blockSectionsDemand;
-
- public override void Initialize(string module, string name, List<IoBlockItem> lstBuffers, IIoBuffer buffer, XmlElement nodeParameter, Dictionary<int, string> ioMappingPathFile)
- {
- Module = module;
- Name = name;
- _source = module + "." + name;
- _buffer = buffer;
- _nodeParameter = nodeParameter;
- _blockSections = lstBuffers;
- buffer.SetBufferBlock(_source, lstBuffers);
- buffer.SetIoMap(_source, ioMappingPathFile);
- SetParameter(nodeParameter);
- State = IoProviderStateEnum.Uninitialized;
- _thread = new PeriodicJob(50, OnTimer, name);
- //Module = module;
- //Name = name;
- //_source = module + "." + name;
- //_buffer = buffer;
- //_nodeParameter = nodeParameter;
- //SetParameter(nodeParameter);
- //if (demandAiSize != 0 || demandAoSize != 0)
- //{
- // var lstBuffersnew = new List<IoBlockItem>();
- // foreach (var bf in lstBuffers)
- // {
- // if (demandAiSize > 0 && bf.Type == IoType.AI)
- // {
- // var bfNew = new IoBlockItem()
- // {
- // Offset = demandAiFrom + demandAiSize,
- // Size = bf.Size - demandAiSize,
- // Type = bf.Type,
- // };
- // lstBuffersnew.Add(bfNew);
- // }
- // else if (demandAoSize > 0 && bf.Type == IoType.AO)
- // {
- // var bfNew = new IoBlockItem()
- // {
- // Offset = demandAoFrom + demandAoSize,
- // Size = bf.Size - demandAoSize,
- // Type = bf.Type,
- // };
- // lstBuffersnew.Add(bfNew);
- // }
- // else
- // lstBuffersnew.Add(bf);
- // }
- // _blockSectionsDemand = lstBuffersnew;
- //}
- //_blockSections = lstBuffers;
- //buffer.SetBufferBlock(_source, lstBuffers);
- //buffer.SetIoMap(_source, ioMappingPathFile);
- //State = IoProviderStateEnum.Uninitialized;
- //_thread = new PeriodicJob(50, OnTimer, name);
- //DATA.Subscribe($"{Name}.ComunicationSpanTotal", () => comunicationSpanTotal);
- //DATA.Subscribe($"{Name}.ComunicationSpanDi", () => comunicationSpanDi);
- //DATA.Subscribe($"{Name}.ComunicationSpanDo", () => comunicationSpanDo);
- //DATA.Subscribe($"{Name}.ComunicationSpanAi", () => comunicationSpanAi);
- //DATA.Subscribe($"{Name}.ComunicationSpanAo", () => comunicationSpanAo);
- }
- protected override bool OnTimer()
- {
- if (State == IoProviderStateEnum.Uninitialized)
- {
- SetState(IoProviderStateEnum.Opening);
- Open();
- }
- if (State == IoProviderStateEnum.Opened)
- {
- 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 (inDemanding)
- {
- short[] aiBuffer = ReadAi(bufferSection.Offset, bufferSection.Size);
- if (aiBuffer != null)
- {
- _buffer.SetAiBuffer(_source, bufferSection.Offset, aiBuffer);
- }
- }
- else
- {
- if (_blockSectionsDemand != null)
- {
- var section = _blockSectionsDemand.Find(x => x.Type == IoType.AI);
- if (section != null && demandAiSize > 0)
- {
- short[] aiBuffer = ReadAi(section.Offset, section.Size);
- if (aiBuffer != null)
- {
- _buffer.SetAiBuffer(_source, demandAiFrom, aiBuffer, demandAiSize);
- }
- }
- }
- else
- {
- short[] aiBuffer = ReadAi(bufferSection.Offset, bufferSection.Size);
- if (aiBuffer != null)
- {
- _buffer.SetAiBuffer(_source, bufferSection.Offset, aiBuffer);
- }
- }
- }
- stopwatchAi.Stop();
- }
- }
- comunicationSpanDi = (int)stopwatchDi.ElapsedMilliseconds;
- stopwatchDi.Reset();
- comunicationSpanAi = (int)stopwatchAi.ElapsedMilliseconds;
- stopwatchAi.Reset();
- stopwatchAo.Start();
- Dictionary<int, short[]> aos = _buffer.GetAoBuffer(_source);
- if (aos != null)
- {
- if (inDemanding)
- {
- if (demandAoSize > 0)
- {
- foreach (var ao in aos)
- {
- WriteAo(ao.Key, ao.Value);
- }
- }
- }
- else
- {
- foreach (var ao in aos)
- {
- if (ao.Key == demandAoFrom)
- {
- short[] data = new short[ao.Value.Length - demandAoSize];
- Array.Copy(ao.Value, demandAoSize, data, 0, data.Length);
- WriteAo(demandAoFrom + demandAoSize, data);
- }
- else
- WriteAo(ao.Key, 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(doo.Key, doo.Value);
- }
- }
- stopwatchDo.Stop();
- comunicationSpanDo = (int)stopwatchDo.ElapsedMilliseconds;
- stopwatchDo.Reset();
- stopwatchTotal.Stop();
- comunicationSpanTotal = (int)stopwatchTotal.ElapsedMilliseconds;
- stopwatchTotal.Reset();
- }
- catch (Exception ex)
- {
- LOG.Write($"{Name} {ex}");
- //SetState(IoProviderStateEnum.Error);
- Thread.Sleep(1000);
- Close();
- Open();
- }
- }
- _trigError.CLK = State == IoProviderStateEnum.Error;
- if (_trigError.Q)
- {
- EV.PostMessage(Module, EventEnum.DefaultAlarm, string.Format("{0} error", _source));
- }
- return true;
- }
- protected override void SetParameter(XmlElement nodeParameter)
- {
- string strIp = nodeParameter.GetAttribute("ip");
- _localIp = nodeParameter.GetAttribute("localIp");
- string strPort = nodeParameter.GetAttribute("port");
- string networkId = nodeParameter.GetAttribute("network_id");
- string stationId = nodeParameter.GetAttribute("station_id");
- aiStoragename = nodeParameter.GetAttribute("aiStoragename");
- aoStoragename = nodeParameter.GetAttribute("aoStoragename");
- diStoragename = nodeParameter.GetAttribute("diStoragename");
- doStoragename = nodeParameter.GetAttribute("doStoragename");
- int.TryParse(nodeParameter.GetAttribute("perIoLength"), out perIoLength);
- perIoLength = perIoLength == 0 ? 960 : perIoLength;
- int.TryParse(nodeParameter.GetAttribute("demandAiFrom"), out demandAiFrom);
- int.TryParse(nodeParameter.GetAttribute("demandAiSize"), out demandAiSize);
- int.TryParse(nodeParameter.GetAttribute("demandAoFrom"), out demandAoFrom);
- int.TryParse(nodeParameter.GetAttribute("demandAoSize"), out demandAoSize);
- if (nodeParameter.HasAttribute("diStartOffset"))
- int.TryParse(nodeParameter.GetAttribute("diStartOffset"), out diStartOffset);
- if (nodeParameter.HasAttribute("doStartOffset"))
- int.TryParse(nodeParameter.GetAttribute("doStartOffset"), out doStartOffset);
- _port = int.Parse(strPort);
- _ip = strIp;
- _socketId = int.Parse(networkId);
- _stationId = int.Parse(stationId);
- DATA.Subscribe($"{Name}.CommunicationStatus", () => _socket == null ? false : _socket.Connected);
- OP.Subscribe($"{Name}.Reconnect", (string cmd, object[] args) =>
- {
- Close();
- Open();
- return true;
- });
- }
- protected override void Open()
- {
- _socket = new MCSocket();
- _header = new MCProtocol.MC_COMMAND_HEADER()
- {
- ProtocolID = MCProtocol.MC_SUBHEADER_COMMAND_MESSAGE,
- NetworkID = (byte)_socketId,
- StationID = (byte)_stationId,
- RequestIONumber = MCProtocol.MC_REQUEST_MODULE_IO_NUMBER,
- RequestStationNumber = MCProtocol.MC_REQUEST_MODULE_STATION_NUMBER,
- RequestDataLen = 0,
- CPUMonitorTimer = (ushort)(MCProtocol.MC_CPU_MONITOR_TIMER * 2),
- };
- _batchCommand = new MCProtocol.MC_BATCH_COMMAND()
- {
- Command = MCProtocol.MC_COMMAND_BATCH_READ,
- DeviceCode = MCProtocol.MC_DEVICE_CODE_DATA_REGISTER_WORD,
- DevicePoints = 0,
- HeadAddr = 0,
- Reserved = 0,
- SubCommand = MCProtocol.MC_SUBCOMMAND_WORD_UNITS,
- };
- _bufferOut = new byte[2048];
- _bufferIn = new byte[2048];
- _socket.Open(_ip, _port, _localIp);
- SetState(IoProviderStateEnum.Opened);
- }
- protected override void Close()
- {
- _socket.Close();
- SetState(IoProviderStateEnum.Closed);
- }
- protected override bool[] ReadDi(int _offset, int size)
- {
- int offset = _offset + diStartOffset;
- bool[] buff = new bool[size];
- int count = size / perIoLength;
- if (count < 1)
- {
- bool[] dibuffer = DoReadDi(offset, size);
- if (dibuffer != null)
- Array.Copy(dibuffer, 0, buff, 0, dibuffer.Length);
- }
- else
- {
- bool[] dibuffer;
- for (int i = 0; i < count; i++)
- {
- dibuffer = DoReadDi(i * perIoLength + offset, perIoLength);
- if (dibuffer != null)
- Array.Copy(dibuffer, 0, buff, i * perIoLength, dibuffer.Length);
- }
- if (size % perIoLength != 0)
- {
- dibuffer = DoReadDi(offset + perIoLength * count, size % perIoLength);
- if (dibuffer != null)
- Array.Copy(dibuffer, 0, buff, size - size % perIoLength, dibuffer.Length);
- }
- }
- return buff;
- }
- public bool SetDemandReadWrite()
- {
- inDemanding = true;
- Thread.Sleep(500);
- inDemanding = false;
- return true;
- }
- protected override short[] ReadAi(int offset, int size)
- {
- short[] buff = new short[size];
- int count = size / perIoLength;
- if (count < 1)
- {
- short[] aibuffer = DoReadAi(offset, size);
- if (aibuffer != null)
- Array.Copy(aibuffer, 0, buff, 0, aibuffer.Length);
- }
- else
- {
- short[] aibuffer;
- for (int i = 0; i < count; i++)
- {
- aibuffer = DoReadAi(i * perIoLength + offset, perIoLength);
- if (aibuffer != null)
- Array.Copy(aibuffer, 0, buff, i * perIoLength, aibuffer.Length);
- }
- if (size % perIoLength != 0)
- {
- aibuffer = DoReadAi(offset + perIoLength * count, size % perIoLength);
- if (aibuffer != null)
- Array.Copy(aibuffer, 0, buff, size - size % perIoLength, aibuffer.Length);
- }
- }
- return buff;
- }
- protected override void WriteDo(int _offset, bool[] data)
- {
- int offset = _offset + doStartOffset;
- bool[] databuffer = new bool[perIoLength];
- int count = data.Length / perIoLength;
- if (count < 1)
- {
- Array.Copy(data, 0, databuffer, 0, data.Length);
- Array.Resize(ref databuffer, data.Length);
- DoWriteDo(offset, databuffer);
- }
- else
- {
- for (int i = 0; i < count; i++)
- {
- Array.Copy(data, i * perIoLength, databuffer, 0, databuffer.Length);
- DoWriteDo(offset + perIoLength * i, databuffer);
- }
- if (data.Length % perIoLength != 0)
- {
- Array.Copy(data, perIoLength * count, databuffer, 0, data.Length % perIoLength);
- Array.Resize(ref databuffer, data.Length % perIoLength);
- DoWriteDo(offset + perIoLength * count, databuffer);
- }
- }
- }
- protected override void WriteAo(int offset, short[] data)
- {
- short[] databuffer = new short[perIoLength];
- int count = data.Length / perIoLength;
- if (count < 1)
- {
- Array.Copy(data, 0, databuffer, 0, data.Length);
- Array.Resize(ref databuffer, data.Length);
- DoWriteAo(offset, databuffer);
- }
- else
- {
- for (int i = 0; i < count; i++)
- {
- Array.Copy(data, i * perIoLength, databuffer, 0, databuffer.Length);
- DoWriteAo(offset + perIoLength * i, databuffer, data.Length, i);
- }
- if (data.Length % perIoLength != 0)
- {
- Array.Copy(data, perIoLength * count, databuffer, 0, data.Length % perIoLength);
- Array.Resize(ref databuffer, data.Length % perIoLength);
- DoWriteAo(offset + perIoLength * count, databuffer, data.Length);
- }
- }
- }
- private bool WriteData(byte[] data, int length)
- {
- return _socket.Write(data, length);
- }
- private int ReceiveData(byte[] data)
- {
- return _socket.Read(data);
- }
- private short[] DoReadAi(int offset, int size)
- {
- _batchCommand.DeviceCode = (byte)MelsecElement.ChooseMelsecElement(aiStoragename).m_nBinCode;
- _batchCommand.Command = MCProtocol.MC_COMMAND_BATCH_READ;
- _batchCommand.SubCommand = MCProtocol.MC_SUBCOMMAND_WORD_UNITS;
- _batchCommand.HeadAddr = (ushort)(offset & 0xFFFF);
- _batchCommand.Reserved = (byte)(offset >> 16);
- _batchCommand.DevicePoints = (ushort)size;
- _header.RequestDataLen = (ushort)(MCProtocol.MC_BATCH_COMMAND_SIZE + MCProtocol.JUNK_SIZE);
- byte[] buffer = MCProtocol.Struct2Bytes(_header);
- byte[] command = MCProtocol.Struct2Bytes(_batchCommand);
- Array.Copy(buffer, 0, _bufferOut, 0, buffer.Length);
- Array.Copy(command, 0, _bufferOut, MCProtocol.MC_QHEADER_COMMAND_SIZE, command.Length);
- if (!WriteData(_bufferOut, MCProtocol.MC_QHEADER_COMMAND_SIZE + MCProtocol.MC_BATCH_COMMAND_SIZE))
- {
- return null;
- }
- //receiveLen < MCProtocol.MC_QHEADER_RESPONSE_SIZE means no data in bufferIn
- int receiveLen = ReceiveData(_bufferIn);
- int dataLength = receiveLen - MCProtocol.MC_QHEADER_RESPONSE_SIZE;
- if (dataLength < 0)
- {
- return null;
- }
- MCProtocol.MC_RESPONSE_HEADER responseHeader =
- MCProtocol.ToStruct<MCProtocol.MC_RESPONSE_HEADER>(_bufferIn);
- if (responseHeader.ProtocolId != 0x00d0 && responseHeader.CompleteCode != MCProtocol.MC_COMPLETE_CODE_SUCCESS)
- {
- return null;
- }
- short[] datas = new short[size];
- byte[] dataBuff = new byte[dataLength];
- Array.Copy(_bufferIn, MCProtocol.MC_QHEADER_RESPONSE_SIZE, dataBuff, 0, dataBuff.Length);
- for (int i = 0, dataBuffIndex = 0; i < datas.Length & dataBuffIndex < dataBuff.Length; i++, dataBuffIndex += 2)
- {
- datas[i] = (short)BitConverter.ToUInt16(dataBuff, 0 + i * 2);
- }
- return datas;
- }
- private void DoWriteAo(int offset, short[] data, int total = 0, int count = 100)
- {
- ushort[] uData = new ushort[data.Length];
- uData = data.Select(x => (ushort)x).ToArray();
- _batchCommand.DeviceCode = (byte)MelsecElement.ChooseMelsecElement(aoStoragename).m_nBinCode;
- _batchCommand.Command = MCProtocol.MC_COMMAND_BATCH_WRITE;
- _batchCommand.SubCommand = MCProtocol.MC_SUBCOMMAND_WORD_UNITS;
- _batchCommand.HeadAddr = (ushort)(offset & 0xFFFF);
- _batchCommand.Reserved = (byte)(offset >> 16);
- _batchCommand.DevicePoints = (ushort)data.Length;
- _header.RequestDataLen = (ushort)(MCProtocol.MC_BATCH_COMMAND_SIZE + MCProtocol.JUNK_SIZE + MCProtocol.ShortSize * data.Length);
- byte[] header = MCProtocol.Struct2Bytes(_header);
- byte[] command = MCProtocol.Struct2Bytes(_batchCommand);
- byte[] byteData = MCProtocol.Ushort2Byte(uData);
- Array.Copy(header, 0, _bufferOut, 0, header.Length);
- Array.Copy(command, 0, _bufferOut, MCProtocol.MC_QHEADER_COMMAND_SIZE, command.Length);
- Array.Copy(byteData, 0, _bufferOut, MCProtocol.MC_QHEADER_COMMAND_SIZE + MCProtocol.MC_BATCH_COMMAND_SIZE, byteData.Length);
- if (!WriteData(_bufferOut, MCProtocol.MC_QHEADER_COMMAND_SIZE + MCProtocol.MC_BATCH_COMMAND_SIZE + MCProtocol.ShortSize * data.Length))
- {
- return;
- }
- if (ReceiveData(_bufferIn) <= 0)
- {
- return;
- }
- MCProtocol.MC_RESPONSE_HEADER responseHeader =
- MCProtocol.ToStruct<MCProtocol.MC_RESPONSE_HEADER>(_bufferIn);
- if (responseHeader.ProtocolId != 0x00d0 && responseHeader.CompleteCode != MCProtocol.MC_COMPLETE_CODE_SUCCESS)
- {
- LOG.Write(" failed with code," + responseHeader.CompleteCode);
- return;
- }
- }
- private bool[] DoReadDi(int offset, int size)
- {
- _batchCommand.DeviceCode = (byte)MelsecElement.ChooseMelsecElement(diStoragename).m_nBinCode;
- _batchCommand.Command = MCProtocol.MC_COMMAND_BATCH_READ;
- _batchCommand.SubCommand = MCProtocol.MC_SUBCOMMAND_WORD_UNITS;
- _batchCommand.HeadAddr = (ushort)(offset & 0xFFFF);
- _batchCommand.Reserved = (byte)(offset >> 16);
- _batchCommand.DevicePoints = (ushort)(size % 16 > 0 ? size / 16 + 1 : size / 16);
- _header.RequestDataLen = (ushort)(MCProtocol.MC_BATCH_COMMAND_SIZE + MCProtocol.JUNK_SIZE);
- byte[] buffer = MCProtocol.Struct2Bytes(_header);
- byte[] command = MCProtocol.Struct2Bytes(_batchCommand);
- Array.Copy(buffer, 0, _bufferOut, 0, buffer.Length);
- Array.Copy(command, 0, _bufferOut, MCProtocol.MC_QHEADER_COMMAND_SIZE, command.Length);
- if (!WriteData(_bufferOut, MCProtocol.MC_QHEADER_COMMAND_SIZE + MCProtocol.MC_BATCH_COMMAND_SIZE))
- {
- return null;
- }
- //receiveLen < MCProtocol.MC_QHEADER_RESPONSE_SIZE means no data in bufferIn
- int receiveLen = ReceiveData(_bufferIn);
- int dataLength = receiveLen - MCProtocol.MC_QHEADER_RESPONSE_SIZE;
- if (dataLength < 0)
- {
- return null;
- }
- MCProtocol.MC_RESPONSE_HEADER responseHeader =
- MCProtocol.ToStruct<MCProtocol.MC_RESPONSE_HEADER>(_bufferIn);
- if (responseHeader.ProtocolId != 0x00d0 && responseHeader.CompleteCode != MCProtocol.MC_COMPLETE_CODE_SUCCESS)
- {
- return null;
- }
- bool[] datas = new bool[dataLength * 8];
- byte[] dataBuff = new byte[dataLength];
- Array.Copy(_bufferIn, MCProtocol.MC_QHEADER_RESPONSE_SIZE, dataBuff, 0, dataBuff.Length);
- var bitArray = new BitArray(dataBuff);
- for (int i = 0; i < datas.Length; i++)
- {
- datas[i] = bitArray.Get(i);
- }
- return datas.Select(x => x).Take(size).ToArray();
- }
- private void DoWriteDo(int offset, bool[] data)
- {
- _batchCommand.DeviceCode = (byte)MelsecElement.ChooseMelsecElement(doStoragename).m_nBinCode;
- _batchCommand.Command = MCProtocol.MC_COMMAND_BATCH_WRITE;
- _batchCommand.SubCommand = MCProtocol.MC_SUBCOMMAND_WORD_UNITS;
- _batchCommand.HeadAddr = (ushort)(offset & 0xFFFF);
- _batchCommand.Reserved = (byte)(offset >> 16);
- _batchCommand.DevicePoints = (ushort)(data.Length % 16 > 0 ? data.Length / 16 + 1 : data.Length / 16);
- _header.RequestDataLen = (ushort)(MCProtocol.MC_BATCH_COMMAND_SIZE + MCProtocol.JUNK_SIZE + _batchCommand.DevicePoints * 2);
- //one word = two bytes , so _batchCommand.DevicePoints * 2
- byte[] byteData = new byte[_batchCommand.DevicePoints * 2];
- for (int i = 0, byteDataIndex = 0; i < data.Length & byteDataIndex < byteData.Length; i += 8, byteDataIndex++)
- {
- byteData[byteDataIndex] += (byte)(data[i] ? 1 : 0);
- byteData[byteDataIndex] += (byte)(i + 1 < data.Length && data[i + 1] ? 1 << 1 : 0);
- byteData[byteDataIndex] += (byte)(i + 2 < data.Length && data[i + 2] ? 1 << 2 : 0);
- byteData[byteDataIndex] += (byte)(i + 3 < data.Length && data[i + 3] ? 1 << 3 : 0);
- byteData[byteDataIndex] += (byte)(i + 4 < data.Length && data[i + 4] ? 1 << 4 : 0);
- byteData[byteDataIndex] += (byte)(i + 5 < data.Length && data[i + 5] ? 1 << 5 : 0);
- byteData[byteDataIndex] += (byte)(i + 6 < data.Length && data[i + 6] ? 1 << 6 : 0);
- byteData[byteDataIndex] += (byte)(i + 7 < data.Length && data[i + 7] ? 1 << 7 : 0);
- }
- byte[] header = MCProtocol.Struct2Bytes(_header);
- byte[] command = MCProtocol.Struct2Bytes(_batchCommand);
- Array.Copy(header, 0, _bufferOut, 0, header.Length);
- Array.Copy(command, 0, _bufferOut, MCProtocol.MC_QHEADER_COMMAND_SIZE, command.Length);
- Array.Copy(byteData, 0, _bufferOut, MCProtocol.MC_QHEADER_COMMAND_SIZE + MCProtocol.MC_BATCH_COMMAND_SIZE, byteData.Length);
- if (!WriteData(_bufferOut, MCProtocol.MC_QHEADER_COMMAND_SIZE + MCProtocol.MC_BATCH_COMMAND_SIZE + byteData.Length))
- {
- return;
- }
- if (ReceiveData(_bufferIn) <= 0)
- {
- return;
- }
- MCProtocol.MC_RESPONSE_HEADER responseHeader =
- MCProtocol.ToStruct<MCProtocol.MC_RESPONSE_HEADER>(_bufferIn);
- if (responseHeader.CompleteCode != MCProtocol.MC_COMPLETE_CODE_SUCCESS)
- {
- LOG.Write("Write PLC failed with code," + responseHeader.CompleteCode);
- return;
- }
- }
- }
- class MCSocket
- {
- private int m_nPort;
- private string m_strAddress;
- private Socket m_socket;
- private int m_nTimeOut;
- public MCSocket()
- {
- m_nTimeOut = 30000;
- }
- ~MCSocket()
- {
- }
- public bool Connected
- {
- get { return (m_socket != null && m_socket.Connected); }
- }
- public bool Open(string strAddress, int nPort, string strLocalAddress)
- {
- if (Connected)
- return true;
- Close();
- m_strAddress = strAddress;
- m_nPort = nPort;
- m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- try
- {
- // Bind to specific local endpoint
- IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 0);
- m_socket.Bind(localEndPoint);
- IPAddress ipAddress = IPAddress.Parse(m_strAddress);
- IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, m_nPort);
- //m_socket = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- m_socket.SendTimeout = m_nTimeOut;
- m_socket.ReceiveTimeout = m_nTimeOut;
- m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
- m_socket.Connect(ipEndPoint);
- }
- catch (Exception ex)
- {
- LOG.Write(ex);
- return false;
- }
- return true;
- }
- public bool Close()
- {
- if (m_socket == null) return true;
- try
- {
- m_socket.Shutdown(SocketShutdown.Both);
- m_socket.Close();
- m_socket = null;
- }
- catch (Exception ex)
- {
- LOG.Write(ex);
- return false;
- }
- return true;
- }
- public int Read(byte[] buffer)
- {
- int ret = -1;
- if (!Connected) return ret;
- return m_socket.Receive(buffer);
- //try
- //{
- // ret = m_socket.Receive(buffer);
- //}
- //catch (Exception ex)
- //{
- // LOG.Write(ex);
- //}
- //return ret;
- }
- public bool Read(byte[] buffer, int length)
- {
- if (!Connected) return false;
- try
- {
- m_socket.Receive(buffer, SocketFlags.None);
- }
- catch (Exception ex)
- {
- LOG.Write(ex);
- return false;
- }
- return true;
- }
- public bool Write(byte[] buffer)
- {
- if (!Connected) return false;
- try
- {
- m_socket.Send(buffer, SocketFlags.None);
- }
- catch (Exception ex)
- {
- LOG.Write(ex);
- return false;
- }
- return true;
- }
- public bool Write(byte[] buffer, int length)
- {
- if (!Connected) return false;
- return m_socket.Send(buffer, length, SocketFlags.None) >= 0;
- //try
- //{
- // m_socket.Send(buffer, length, SocketFlags.None);
- //}
- //catch (Exception ex)
- //{
- // LOG.Write(ex);
- // return false;
- //}
- //return true;
- }
- }
- }
|