ConnectionManager.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Aitex.Core.RT.DataCenter;
  7. using Aitex.Core.RT.Log;
  8. using Aitex.Core.RT.OperationCenter;
  9. using Aitex.Core.Util;
  10. namespace MECF.Framework.Common.Communications
  11. {
  12. /// <summary>
  13. /// 管理所有连接,通常在PLC之前
  14. /// </summary>
  15. public class ConnectionManager : Singleton<ConnectionManager>
  16. {
  17. public List<NotifiableConnectionItem> ConnectionList
  18. {
  19. get
  20. {
  21. foreach (var conn in _connections)
  22. {
  23. conn.IsConnected = _dicConnections[conn.Name].IsConnected;
  24. }
  25. return _connections;
  26. }
  27. }
  28. private Dictionary<string, IConnection> _dicConnections = new Dictionary<string, IConnection>();
  29. private List<NotifiableConnectionItem> _connections = new List<NotifiableConnectionItem>();
  30. public void Initialize()
  31. {
  32. OP.Subscribe("Connection.Connect", (string cmd, object[] args) =>
  33. {
  34. Connect((string) args[0]);
  35. return true;
  36. });
  37. OP.Subscribe("Connection.Disconnect", (string cmd, object[] args) =>
  38. {
  39. Disconnect((string)args[0]);
  40. return true;
  41. });
  42. DATA.Subscribe("Connection.List", () => ConnectionList);
  43. }
  44. public void Terminate()
  45. {
  46. }
  47. public void Subscribe(string name, IConnection conn)
  48. {
  49. if (string.IsNullOrEmpty(name))
  50. {
  51. return;
  52. }
  53. if (conn == null)
  54. {
  55. return;
  56. }
  57. _connections.Add(new NotifiableConnectionItem(){Address = conn.Address, Name = name});
  58. _dicConnections[name] = conn;
  59. }
  60. public void Connect(string name)
  61. {
  62. if (_dicConnections.ContainsKey(name) && _dicConnections[name] != null)
  63. {
  64. _dicConnections[name].Connect();
  65. }
  66. }
  67. public void Disconnect(string name)
  68. {
  69. if (_dicConnections.ContainsKey(name) && _dicConnections[name] != null)
  70. {
  71. _dicConnections[name].Disconnect();
  72. }
  73. }
  74. }
  75. }