123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343 |
- using Aitex.Core.Util;
- using MECF.Framework.Common.Communications;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using HandlerBase = athosRT.tool.Comm.HandlerBase;
- //using TCPPortConnectionBase = athosRT.tool.Comm.TCPPortConnectionBase;
- namespace athosRT.tool.Comm
- {
- public abstract class TCPPortConnectionBase : IConnection
- {
- private AsynSocketClient _socket;
- protected HandlerBase _activeHandler;
- public HandlerBase HandlerInError;
- protected object _lockerActiveHandler = new object();
- private string _address;
- private bool _isAsciiMode;
- public int retryTime = 0;
- private PeriodicJob _thread;
- private object _locker = new object();
- private LinkedList<string> _lstAsciiMsgs = new LinkedList<string>();
- private LinkedList<byte[]> _lstBinsMsgs = new LinkedList<byte[]>();
- private string _newLine;
- public string Address => _address;
- public bool IsConnected => _socket.IsConnected;
- public bool IsBusy => _activeHandler != null;
- public bool IsCommunicationError { get; private set; }
- public string LastCommunicationError { get; private set; }
- public bool Connect()
- {
- _socket.Connect();
- int num = 0;
- while (!IsConnected && num < 25)
- {
- Thread.Sleep(200);//原本就有
- num++;
- }
- if (IsConnected)
- {
- return true;
- }
- Disconnect();
- return false;
- }
- public bool Disconnect()
- {
- _socket.Dispose();
- return true;
- }
- public TCPPortConnectionBase(string address, string newline = "\r", bool isAsciiMode = true)
- {
- _address = address;
- _newLine = newline;
- _isAsciiMode = isAsciiMode;
- _socket = new AsynSocketClient(address, isAsciiMode, newline);
- _socket.OnDataChanged += _port_OnAsciiDataReceived;
- _socket.OnBinaryDataChanged += _port_OnBinaryDataChanged;
- _socket.OnErrorHappened += _port_OnErrorHappened;
- _thread = new PeriodicJob(1, OnTimer, address + ".MonitorHandler", isStartNow: true);
- }
- private bool OnTimer()
- {
- lock (_locker)
- {
- if (_isAsciiMode)
- {
- while (_lstAsciiMsgs.Count > 0)
- {
- string value = _lstAsciiMsgs.First.Value;
- if (!string.IsNullOrEmpty(value))
- {
- if (_socket.NeedLog)
- {
- //LOG.Write("Start handler message:" + value, 2, "D:\\sorter\\trunk\\Framework\\Common\\Communications\\ConnectionBase.cs", "OnTimer", 412);
- }
- _port_HandleAsciiData(value);
- }
- _lstAsciiMsgs.RemoveFirst();
- }
- }
- else
- {
- while (_lstBinsMsgs.Count > 0)
- {
- byte[] value2 = _lstBinsMsgs.First.Value;
- _port_HandleBinarayData(value2);
- _lstBinsMsgs.RemoveFirst();
- }
- }
- }
- return true;
- }
- private void _port_OnErrorHappened(TCPErrorEventArgs obj)
- {
- //LOG.Error(obj.Reason, 2, "D:\\sorter\\trunk\\Framework\\Common\\Communications\\ConnectionBase.cs", "_port_OnErrorHappened", 439);
- }
- public virtual bool SendMessage(string message)
- {
- if (_socket != null && _socket.IsConnected)
- {
- return _socket.Write(message);
- }
- //LOG.Error("No connection writing message " + message, 2, "D:\\sorter\\trunk\\Framework\\Common\\Communications\\ConnectionBase.cs", "SendMessage", 447);
- return false;
- }
- public virtual bool SendMessage(byte[] message)
- {
- if (_socket != null && _socket.IsConnected)
- {
- return _socket.Write(message);
- }
- //LOG.Error("No connection writing message " + string.Join(" ", Array.ConvertAll(message, (byte x) => x.ToString("X2"))), 2, "D:\\sorter\\trunk\\Framework\\Common\\Communications\\ConnectionBase.cs", "SendMessage", 456);
- return false;
- }
- public void ForceClear()
- {
- lock (_lockerActiveHandler)
- {
- _activeHandler = null;
- IsCommunicationError = false;
- }
- }
- public void Execute(HandlerBase handler)
- {
- if (_activeHandler != null || handler == null || !_socket.IsConnected)
- {
- return;
- }
- lock (_lockerActiveHandler)
- {
- if (handler != null)
- {
- retryTime = 0;
- _activeHandler = handler;
- _activeHandler.SetState(EnumHandlerState.Sent);
- }
- }
- bool flag = _isAsciiMode ? SendMessage(handler.SendText) : SendMessage(handler.SendBinary);
- if (!flag)
- {
- //while (_lstAsciiMsgs.Count > 0)
- //{
- // string value = _lstAsciiMsgs.First!.Value;
- // if (!string.IsNullOrEmpty(value))
- // {
- // if (_socket.NeedLog)
- // {
- // //LOG.Write("Start handler message:" + value, 2, "D:\\sorter\\trunk\\Framework\\Common\\Communications\\ConnectionBase.cs", "OnTimer", 412);
- // }
- // _port_HandleAsciiData(value);
- // }
- // _lstAsciiMsgs.RemoveFirst();
- //}
- lock (_lockerActiveHandler)
- {
- //_activeHandler = null;
- }
- }
- }
- protected virtual MessageBase ParseResponse(string rawMessage)
- {
- return null;
- }
- protected virtual MessageBase ParseResponse(byte[] rawMessage)
- {
- return null;
- }
- protected virtual void OnEventArrived(MessageBase msg)
- {
- }
- protected virtual void ActiveHandlerProceedMessage(MessageBase msg)
- {
- //Trace.WriteLine("2222");
- //lock (_lockerActiveHandler)
- //{
- // //if (_activeHandler != null && (msg.IsFormatError || (_activeHandler.HandleMessage(msg, out var transactionComplete) && transactionComplete)))
- // if (_activeHandler != null)
- // {
- // bool flag = _activeHandler.HandleMessage(msg, out var transactionComplete);
- // Trace.WriteLine("333");
- // if (flag)
- // {
- // if (transactionComplete)
- // {
- // _activeHandler = null;
- // }
- // }
- // }
- //}
- }
- public void EnableLog(bool enable)
- {
- _socket.NeedLog = enable;
- }
- private void ProceedTransactionMessage(MessageBase msg)
- {
- if (msg?.IsFormatError ?? true)
- {
- SetCommunicationError(isError: true, "received invalid response message.");
- return;
- }
- if (msg.IsEvent)
- {
- OnEventArrived(msg);
- }
- //Trace.WriteLine("ProceedTransactionMessage");
- ActiveHandlerProceedMessage(msg);
- //Trace.WriteLine("ProceedTransactionMessage over");
- }
- private void _port_OnBinaryDataChanged(byte[] binaryData)
- {
- lock (_locker)
- {
- _lstBinsMsgs.AddLast(binaryData);
- }
- }
- private void _port_HandleBinarayData(byte[] binaryData)
- {
- MessageBase msg = ParseResponse(binaryData);
- ProceedTransactionMessage(msg);
- }
- private void _port_OnAsciiDataReceived(string oneLineMessage)
- {
- lock (_locker)
- {
- if (string.IsNullOrEmpty(_newLine))
- {
- _lstAsciiMsgs.AddLast(oneLineMessage);
- return;
- }
- string[] array = oneLineMessage.Split(_newLine.ToCharArray());
- foreach (string text in array)
- {
- if (!string.IsNullOrEmpty(text))
- {
- _lstAsciiMsgs.AddLast(text + _newLine);
- }
- }
- }
- }
- private void _port_HandleAsciiData(string oneLineMessage)
- {
- MessageBase msg = ParseResponse(oneLineMessage);
- //Trace.WriteLine("_port_HandleAsciiData1");
- ProceedTransactionMessage(msg);
- //Trace.WriteLine("_port_HandleAsciiData2");
- }
- public HandlerBase MonitorTimeout()
- {
- HandlerBase result = null;
- lock (_lockerActiveHandler)
- {
- if (_activeHandler != null && _activeHandler.CheckTimeout())
- {
- EV.PostWarningLog("System", Address + " receive " + _activeHandler.Name + " timeout");
- result = _activeHandler;
- HandlerInError = _activeHandler;
- _activeHandler = null;
- SetCommunicationError(isError: true, "receive response timeout");
- }
- }
- return result;
- }
- public void Retry()
- {
- //线程不安全且未被引用 暂时禁止使用
- //if (_activeHandler != null && _socket.IsConnected)
- //{
- // _activeHandler.SetState(EnumHandlerState.Sent);
- // if (!(_isAsciiMode ? SendMessage(_activeHandler.SendText) : SendMessage(_activeHandler.SendBinary)))
- // {
- // _activeHandler = null;
- // }
- //}
- }
- public void SetCommunicationError(bool isError, string reason)
- {
- IsCommunicationError = isError;
- LastCommunicationError = reason;
- }
- }
- }
|