FsmConnection.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Aitex.Core.RT.Fsm;
  8. using Aitex.Core.RT.Log;
  9. using Aitex.Core.Utilities;
  10. using MECF.Framework.Common.Fsm;
  11. namespace MECF.Framework.Common.Communications
  12. {
  13. public class FsmConnection : ActiveFsm
  14. {
  15. private enum ConnectionState
  16. {
  17. Init = 1000,
  18. NotConnect,
  19. Connecting,
  20. Connected,
  21. Error,
  22. }
  23. private enum MSG
  24. {
  25. Connect = 1000,
  26. Disconnect,
  27. ConnectFailed,
  28. Connected,
  29. Reset,
  30. CommunicationError,
  31. ReceiveBinaryData,
  32. SendBinaryData,
  33. ReceiveAsciiData,
  34. SendAsciiData,
  35. ConfirmConnection,
  36. }
  37. public bool IsConnected
  38. {
  39. get
  40. {
  41. return FsmState == (int)ConnectionState.Connected;
  42. }
  43. }
  44. public bool IsError
  45. {
  46. get
  47. {
  48. return FsmState == (int)ConnectionState.Error;
  49. }
  50. }
  51. public event Action<string> OnError;
  52. public event Action OnConnected;
  53. public event Action OnDisconnected;
  54. private IConnectable _connectable;
  55. private IConnectionContext _config;
  56. public string Name { get; set; }
  57. private string _lastError;
  58. public FsmConnection()
  59. {
  60. }
  61. public virtual void Initialize(int fsmInterval, IConnectable connectable, IConnectionContext config)
  62. {
  63. _connectable = connectable;
  64. _config = config;
  65. _connectable.OnBinaryDataReceived += _connectable_OnBinaryDataChanged;
  66. _connectable.OnAsciiDataReceived += _connectable_OnAsciiDataChanged;
  67. _connectable.OnCommunicationError += ConnectableOnCommunicationError;
  68. EnumLoop<ConnectionState>.ForEach((item) =>
  69. {
  70. MapState((int)item, item.ToString());
  71. });
  72. EnumLoop<MSG>.ForEach((item) =>
  73. {
  74. MapMessage((int)item, item.ToString());
  75. });
  76. //init
  77. EnterExitTransition<ConnectionState, FSM_MSG>(ConnectionState.Init, FsmEnterInit, FSM_MSG.NONE, null);
  78. Transition(ConnectionState.Init, MSG.Disconnect, null, ConnectionState.NotConnect);
  79. Transition(ConnectionState.Init, MSG.Connect, null, ConnectionState.Connecting);
  80. //Connecting
  81. EnterExitTransition<ConnectionState, FSM_MSG>(ConnectionState.Connecting, FsmEnterConnecting, FSM_MSG.NONE, null);
  82. Transition(ConnectionState.Connecting, MSG.ConnectFailed, null, ConnectionState.Error);
  83. Transition(ConnectionState.Connecting, MSG.Connected, null, ConnectionState.Connected);
  84. Transition(ConnectionState.Connecting, MSG.Disconnect, FsmDisconnect, ConnectionState.NotConnect);
  85. Transition(ConnectionState.Connecting, FSM_MSG.TIMER, FsmMonitorConnecting, ConnectionState.Connecting);
  86. //Connected
  87. EnterExitTransition<ConnectionState, FSM_MSG>(ConnectionState.Connected, FsmEnterConnected, FSM_MSG.NONE, FsmExitConnected);
  88. Transition(ConnectionState.Connected, MSG.Disconnect, FsmDisconnect, ConnectionState.NotConnect);
  89. Transition(ConnectionState.Connected, MSG.CommunicationError, null, ConnectionState.Error);
  90. Transition(ConnectionState.Connected, MSG.ConnectFailed, null, ConnectionState.Error);
  91. Transition(ConnectionState.Connected, FSM_MSG.TIMER, FsmMonitorConnected, ConnectionState.Connected);
  92. Transition(ConnectionState.Connected, MSG.ConfirmConnection, FsmMonitorConnected, ConnectionState.Connected);
  93. Transition(ConnectionState.Connected, MSG.ReceiveBinaryData, FsmReceiveBinaryData, ConnectionState.Connected);
  94. Transition(ConnectionState.Connected, MSG.SendBinaryData, FsmSendBinaryData, ConnectionState.Connected);
  95. Transition(ConnectionState.Connected, MSG.ReceiveAsciiData, FsmReceiveAsciiData, ConnectionState.Connected);
  96. Transition(ConnectionState.Connected, MSG.SendAsciiData, FsmSendAsciiData, ConnectionState.Connected);
  97. //NotConnect
  98. Transition(ConnectionState.NotConnect, MSG.Connect, null, ConnectionState.Connecting);
  99. //Error
  100. EnterExitTransition<ConnectionState, FSM_MSG>(ConnectionState.Error, FsmEnterError, FSM_MSG.NONE, null);
  101. Transition(ConnectionState.Error, MSG.Disconnect, null, ConnectionState.NotConnect);
  102. Transition(ConnectionState.Error, MSG.Reset, null, ConnectionState.Connecting);
  103. StartFsm(Name, fsmInterval, (int)ConnectionState.Init);
  104. }
  105. public virtual void Terminate()
  106. {
  107. StopFsm();
  108. try
  109. {
  110. _connectable.Disconnect(out _);
  111. }
  112. catch (Exception ex)
  113. {
  114. LOG.Write(ex);
  115. }
  116. }
  117. protected virtual void OnReceiveData(string message)
  118. {
  119. }
  120. protected virtual void OnReceiveData(byte[] message)
  121. {
  122. }
  123. protected virtual void OnConnect()
  124. {
  125. }
  126. protected virtual void OnDisconnect()
  127. {
  128. }
  129. protected virtual void OnConnectMonitor()
  130. {
  131. }
  132. private bool FsmSendAsciiData(object[] param)
  133. {
  134. if (!_connectable.SendAsciiData((string)param[0]))
  135. {
  136. PostMsg(MSG.ConfirmConnection);
  137. }
  138. return true;
  139. }
  140. private bool FsmReceiveAsciiData(object[] param)
  141. {
  142. try
  143. {
  144. OnReceiveData((string)param[0]);
  145. }
  146. catch (Exception ex)
  147. {
  148. LOG.Write(ex);
  149. }
  150. return true;
  151. }
  152. private bool FsmSendBinaryData(object[] param)
  153. {
  154. if (!_connectable.SendBinaryData((byte[])param[0]))
  155. {
  156. PostMsg(MSG.ConfirmConnection);
  157. }
  158. return true;
  159. }
  160. private bool FsmReceiveBinaryData(object[] param)
  161. {
  162. try
  163. {
  164. OnReceiveData((byte[])param[0]);
  165. }
  166. catch (Exception ex)
  167. {
  168. LOG.Write(ex);
  169. }
  170. return true;
  171. }
  172. private void ConnectableOnCommunicationError(string obj)
  173. {
  174. if (!CheckToPostMessage((int)MSG.CommunicationError, out string reason, obj))
  175. {
  176. LOG.Write(reason);
  177. }
  178. }
  179. private void _connectable_OnAsciiDataChanged(string obj)
  180. {
  181. if (!CheckToPostMessage((int)MSG.ReceiveAsciiData, out string reason, obj))
  182. {
  183. LOG.Write(reason);
  184. }
  185. }
  186. private void _connectable_OnBinaryDataChanged(byte[] obj)
  187. {
  188. if (!CheckToPostMessage((int)MSG.ReceiveBinaryData, out string reason, obj))
  189. {
  190. LOG.Write(reason);
  191. }
  192. }
  193. private bool FsmDisconnect(object[] param)
  194. {
  195. if (!_connectable.Disconnect(out string reason))
  196. {
  197. LOG.Write(reason);
  198. return false;
  199. }
  200. return true;
  201. }
  202. private bool FsmExitConnected(object[] param)
  203. {
  204. if (OnDisconnected != null)
  205. {
  206. OnDisconnected();
  207. }
  208. OnDisconnect();
  209. return true;
  210. }
  211. private bool FsmEnterError(object[] param)
  212. {
  213. if (OnError != null)
  214. {
  215. OnError(_lastError);
  216. }
  217. return true;
  218. }
  219. private bool FsmEnterConnecting(object[] param)
  220. {
  221. if (!_connectable.Connect(out string reason))
  222. {
  223. _lastError = reason;
  224. PostMsg(MSG.ConnectFailed);
  225. }
  226. return true;
  227. }
  228. private bool FsmMonitorConnecting(object[] param)
  229. {
  230. if (_connectable.CheckIsConnected())
  231. {
  232. PostMsg(MSG.Connected);
  233. return true;
  234. }
  235. if (!PeformConnect())
  236. {
  237. _lastError = $"Can not connect with {Name}";
  238. PostMsg(MSG.ConnectFailed);
  239. return true;
  240. }
  241. return true;
  242. }
  243. private bool FsmMonitorConnected(object[] param)
  244. {
  245. if (_config.EnableCheckConnection)
  246. {
  247. if (!_connectable.CheckIsConnected())
  248. {
  249. if (!PeformConnect())
  250. {
  251. _lastError = $"Can not connect with {Name}";
  252. PostMsg(MSG.ConnectFailed);
  253. return false;
  254. }
  255. }
  256. }
  257. OnConnectMonitor();
  258. return true;
  259. }
  260. private bool PeformConnect()
  261. {
  262. int retryTime = 0;
  263. do
  264. {
  265. if (!_connectable.Connect(out string reason))
  266. {
  267. _lastError = reason;
  268. return false;
  269. }
  270. Thread.Sleep(10);
  271. if (_connectable.CheckIsConnected())
  272. {
  273. return true;
  274. }
  275. if (retryTime < _config.MaxRetryConnectCount)
  276. {
  277. retryTime++;
  278. LOG.Write($"{Name} retry connect {retryTime} /{_config.MaxRetryConnectCount} time");
  279. Thread.Sleep(_config.RetryConnectIntervalMs);
  280. }
  281. } while (retryTime < _config.MaxRetryConnectCount);
  282. if (!_connectable.CheckIsConnected())
  283. {
  284. LOG.Error($"Can not connect with {Name}");
  285. return false;
  286. }
  287. return true;
  288. }
  289. private bool FsmEnterConnected(object[] param)
  290. {
  291. if (OnConnected != null)
  292. OnConnected();
  293. OnConnect();
  294. return true;
  295. }
  296. private bool FsmEnterInit(object[] param)
  297. {
  298. if (_config.IsEnabled)
  299. {
  300. PostMsg(MSG.Connect);
  301. }
  302. else
  303. {
  304. PostMsg(MSG.Disconnect);
  305. }
  306. return true;
  307. }
  308. public void InvokeSendData<T>(T data)
  309. {
  310. if (!CheckToPostMessage((int)MSG.SendAsciiData, out string reason, data))
  311. {
  312. LOG.Write(reason);
  313. }
  314. }
  315. public void InvokeConnect()
  316. {
  317. if (!CheckToPostMessage((int)MSG.Connect, out string reason))
  318. {
  319. LOG.Write(reason);
  320. }
  321. }
  322. public void InvokeDisconnect()
  323. {
  324. if (!CheckToPostMessage((int)MSG.Disconnect, out string reason))
  325. {
  326. LOG.Write(reason);
  327. }
  328. }
  329. public void InvokeError()
  330. {
  331. if (!CheckToPostMessage((int)MSG.CommunicationError, out string reason))
  332. {
  333. LOG.Write(reason);
  334. }
  335. }
  336. public void InvokeReset()
  337. {
  338. if (!CheckToPostMessage((int)MSG.Reset, out string reason))
  339. {
  340. LOG.Write(reason);
  341. }
  342. }
  343. }
  344. }