MessageBridge.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. using NEIntelligentControl2.Models;
  2. using NEIntelligentControl2.Models.Messages;
  3. using NEIntelligentControl2.Models.Windturbine;
  4. using NEIntelligentControl2.Service.Windturbine;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Configuration;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Text.Json;
  11. using System.Text.Json.Serialization;
  12. using System.Threading.Tasks;
  13. namespace NEIntelligentControl2.Service.WebSocket
  14. {
  15. /// <summary>
  16. /// 用于消息收发,WebSocket
  17. /// </summary>
  18. public class MessageBridge
  19. {
  20. private static readonly object _RegisterLocker = new object();
  21. private Dictionary<string, HashSet<IMessage>> _Observers; // 订阅者
  22. private WebSocketStomp _WebSocket; // WebSocket
  23. private WebSocketStomp _Adapter; // 适配器
  24. public WebSocketStomp WebSocket { get => _WebSocket; }// 用于消息发送
  25. private static JsonSerializerOptions SerializerOptions = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
  26. private CacheManager _CacheManager;
  27. private WEBHelper _WEBHelper;
  28. private string _Url;
  29. public MessageBridge(CacheManager cm, UrlManager um, WEBHelper web)
  30. {
  31. _Observers = new Dictionary<string, HashSet<IMessage>>();
  32. _CacheManager = cm;
  33. _WEBHelper = web;
  34. _Url = um.ServicePath;
  35. string calcurl = null;
  36. string adapterurl = null;
  37. try
  38. {
  39. #if (DEBUG)
  40. calcurl = ConfigurationManager.AppSettings["ServiceSocketPathDebug"];
  41. adapterurl = ConfigurationManager.AppSettings["AdapterSocketPathDebug"];
  42. #else
  43. calcurl = ConfigurationManager.AppSettings["ServiceSocketPath"];
  44. calcurl = ConfigurationManager.AppSettings["AdapterSocketPath"];
  45. #endif
  46. }
  47. catch (Exception e)
  48. {
  49. Console.WriteLine($"配置文件读取出现错误:{e.Message}");
  50. }
  51. // WebSocket
  52. _WebSocket = new WebSocketStomp(WebSocket_OnMessage, calcurl,
  53. "SubscribeSuggestion".GetConfiguration(), "SubscribeRuntimeFault".GetConfiguration(),
  54. "SubscribeRuntimeAlarm".GetConfiguration(), "SubscribePopupAlarm".GetConfiguration());
  55. _WebSocket.IsCheckTime = true;
  56. // DataAdapter
  57. _Adapter = new WebSocketStomp(WebSocket_OnMessage_Adapter, adapterurl, "WindturbineInformation".GetConfiguration(), "PVInformation".GetConfiguration());
  58. SerializerOptions.Converters.Add(new DateTimeConverter());
  59. Task.Run(RefreshCustomLockInfo);
  60. }
  61. /// <summary>
  62. /// 定时刷新自定义挂牌信息
  63. /// </summary>
  64. private async void RefreshCustomLockInfo()
  65. {
  66. while (true)
  67. {
  68. try
  69. {
  70. List<CustomLockInfo> ls = _WEBHelper.HttpGetJSON<List<CustomLockInfo>>($"{_Url}/api/windturbine/customer-lock");
  71. if (ls == null) continue;
  72. _CacheManager.CustomLockInfos = ls.ToDictionary(c => c.WindturbineID, c => c);
  73. }
  74. catch { }
  75. await Task.Delay(5000);
  76. }
  77. }
  78. private void WebSocket_OnMessage(object sender, WebSocketSharp.MessageEventArgs e)
  79. {
  80. var v = StompMessage.Deserialize(e.Data);
  81. _WebSocket.Time = DateTime.Now;
  82. if (v.Command.ToUpper() != "MESSAGE" || !v.Headers.ContainsKey("destination") || !_Observers.ContainsKey(v.Headers["destination"])) return;
  83. var value = GetValue(v);
  84. var vs = _Observers[v.Headers["destination"]].ToArray();
  85. foreach (var iv in vs)
  86. {
  87. try
  88. {
  89. iv.OnMessage(value);
  90. }
  91. catch (Exception ee)
  92. {
  93. Console.WriteLine(ee.ToString());
  94. }
  95. }
  96. }
  97. private void WebSocket_OnMessage_Adapter(object sender, WebSocketSharp.MessageEventArgs e)
  98. {
  99. var v = StompMessage.Deserialize(e.Data);
  100. if (v.Command.ToUpper() != "MESSAGE" || !v.Headers.ContainsKey("destination") || !_Observers.ContainsKey(v.Headers["destination"])) return;
  101. _Adapter.Time = DateTime.Now;
  102. var value = GetValue(v);
  103. var vs = _Observers[v.Headers["destination"]].ToArray();
  104. foreach (var iv in vs)
  105. {
  106. try
  107. {
  108. iv.OnMessage(value);
  109. }
  110. catch (Exception ee)
  111. {
  112. Console.WriteLine(ee.ToString());
  113. }
  114. }
  115. }
  116. /// <summary>
  117. /// 注册,在不需要使用消息的时候请取消注册,避免造成内存泄露
  118. /// </summary>
  119. public void Register(IMessage message)
  120. {
  121. if (message == null || message.MessageTypes == null) return;
  122. lock (_RegisterLocker)
  123. {
  124. foreach (var v in message.MessageTypes)
  125. {
  126. if (v == null)
  127. {
  128. Console.WriteLine("注册消息不能为空");
  129. continue;
  130. }
  131. if (!_Observers.ContainsKey(v))
  132. {
  133. _Observers.Add(v, new HashSet<IMessage>());
  134. }
  135. _Observers[v].Add(message);
  136. }
  137. }
  138. }
  139. /// <summary>
  140. /// 取消注册
  141. /// </summary>
  142. public void Unregister(IMessage message)
  143. {
  144. if (message == null || message.MessageTypes == null) return;
  145. lock (_RegisterLocker)
  146. {
  147. foreach (var v in message.MessageTypes)
  148. {
  149. if (_Observers.ContainsKey(v))
  150. {
  151. _Observers[v].Remove(message);
  152. }
  153. }
  154. }
  155. }
  156. /// <summary>
  157. /// 关闭WebSocket连接
  158. /// </summary>
  159. public void Close()
  160. {
  161. _WebSocket.Close();
  162. _Adapter.Close();
  163. }
  164. /// <summary>
  165. /// 获取不同类型的数据
  166. /// </summary>
  167. /// <returns></returns>
  168. private object GetValue(StompMessage v)
  169. {
  170. if (!v.Headers.ContainsKey("destination")) return v;
  171. var type = v.Headers["destination"];
  172. switch (type)
  173. {
  174. case "/topic/suggestion":// 启停推荐
  175. return GetSuggestion(v);
  176. case "/topic/windturbine":// 风机信息
  177. return GetWindturbineInfo(v);
  178. case "/topic/pv":// 光伏信息
  179. return GetPVInfo(v);
  180. case "/topic/fault-popup":// 报警弹窗
  181. return FalutPopupInfo(v);
  182. case "/topic/fault-count":// 故障数量
  183. return GetFaultCount(v);
  184. case "/topic/alarm-count":// 报警数量
  185. return GetAlarmCount(v);
  186. default: return v;
  187. }
  188. }
  189. private object GetAlarmCount(StompMessage v)
  190. {
  191. try
  192. {
  193. var val = JsonSerializer.Deserialize<List<Models.Alarm.AlarmInfo>>(v.Body, SerializerOptions);
  194. return val;
  195. }
  196. catch (Exception e)
  197. {
  198. Console.WriteLine($"解析报警弹窗数据出现错误:{e.Message}");
  199. }
  200. return null;
  201. }
  202. /// <summary>
  203. /// 故障数量信息解析
  204. /// </summary>
  205. private object GetFaultCount(StompMessage v)
  206. {
  207. try
  208. {
  209. var val = JsonSerializer.Deserialize<List<Models.Alarm.FaultInfoModel>>(v.Body, SerializerOptions);
  210. return val;
  211. }
  212. catch (Exception e)
  213. {
  214. Console.WriteLine($"解析报警弹窗数据出现错误:{e.Message}");
  215. }
  216. return null;
  217. }
  218. /// <summary>
  219. /// 报警弹窗信息解析
  220. /// </summary>
  221. private object FalutPopupInfo(StompMessage v)
  222. {
  223. try
  224. {
  225. var val = JsonSerializer.Deserialize<List<Models.Alarm.FaultInfo>>(v.Body, SerializerOptions);
  226. return val;
  227. }
  228. catch (Exception e)
  229. {
  230. Console.WriteLine($"解析报警弹窗数据出现错误:{e.Message}");
  231. }
  232. return null;
  233. }
  234. /// <summary>
  235. /// 光伏信息解析
  236. /// </summary>
  237. private object GetPVInfo(StompMessage v)
  238. {
  239. try
  240. {
  241. var val = JsonSerializer.Deserialize<Dictionary<string, Models.PV.PVInfo>>(v.Body, SerializerOptions);
  242. _CacheManager.PVInfos = val;
  243. return val;
  244. }
  245. catch (Exception e)
  246. {
  247. Console.WriteLine($"解析光伏数据出现错误:{e.Message}");
  248. }
  249. return null;
  250. }
  251. /// <summary>
  252. /// 风机信息解析
  253. /// </summary>
  254. private object GetWindturbineInfo(StompMessage sm)
  255. {
  256. try
  257. {
  258. var val = JsonSerializer.Deserialize<Dictionary<string, Models.Windturbine.WindturbineInfo>>(sm.Body, SerializerOptions);
  259. _CacheManager.Windturbineinfos = val;
  260. return val;
  261. }
  262. catch (Exception e)
  263. {
  264. Console.WriteLine($"解析风机数据出现错误:{e.Message}");
  265. }
  266. return null;
  267. }
  268. /// <summary>
  269. /// 启停推荐数据解析
  270. /// </summary>
  271. private List<Models.Windturbine.WindturbineSuggestion> GetSuggestion(StompMessage sm)
  272. {
  273. try
  274. {
  275. var val = JsonSerializer.Deserialize<List<Models.Windturbine.WindturbineSuggestion>>(sm.Body, SerializerOptions);
  276. return val;
  277. }
  278. catch (Exception e)
  279. {
  280. Console.WriteLine($"解析启停推荐数据出现错误:{e.Message}");
  281. }
  282. return null;
  283. }
  284. }
  285. public class WebSocketStomp
  286. {
  287. private WebSocketSharp.WebSocket _WebSocket; // 当前WebSocket
  288. private int _Index; // 发送序列
  289. private bool _IsInitConnecting = false; // WebSocket是否正在重新连接
  290. private string[] _Settings; // 要注册的数据类型
  291. private string _Url; // 连接地址
  292. private EventHandler<WebSocketSharp.MessageEventArgs> _Message; // 消息发送
  293. /// <summary>
  294. /// 是否检测时间,用于确定websocket是否断开连接
  295. /// </summary>
  296. public bool IsCheckTime { get; set; } = false;
  297. /// <summary>
  298. /// 当前心跳时间
  299. /// </summary>
  300. public DateTime Time { get; set; }
  301. public WebSocketStomp(EventHandler<WebSocketSharp.MessageEventArgs> onMessage, string url, params string[] settings)
  302. {
  303. try
  304. {
  305. _Settings = settings;
  306. _Url = url;
  307. _Message = onMessage;
  308. Task.Run(Connect);
  309. // 用于定时检测WebSocket是否连接,如果断开则重新连接
  310. Task.Factory.StartNew(Protector, TaskCreationOptions.LongRunning);
  311. }
  312. catch (Exception e)
  313. {
  314. Console.WriteLine($"连接WebSocket[{_Url}]出现错误:{e.Message}");
  315. }
  316. }
  317. /// <summary>
  318. /// 连接WebSocket
  319. /// </summary>
  320. private void Connect()
  321. {
  322. _WebSocket?.Close();
  323. _WebSocket = new WebSocketSharp.WebSocket(_Url);
  324. _WebSocket.OnMessage += _Message;
  325. _WebSocket.Connect();
  326. if (!_WebSocket.IsAlive)
  327. {
  328. Console.WriteLine($"WebSocket连接失败,{DateTime.Now}");
  329. return;
  330. }
  331. var connect = new StompMessage("CONNECT");
  332. connect["accept-version"] = "1.2";
  333. connect["host"] = "";
  334. _WebSocket.Send(connect.ToString());
  335. foreach (var v in _Settings)
  336. {
  337. Subscribe(v);
  338. }
  339. Time = DateTime.Now;
  340. Console.WriteLine($"WebSocket连接成功,{DateTime.Now}");
  341. }
  342. /// <summary>
  343. /// 用于检测WebSocket连接是否被断开,如果断开则重新连接
  344. /// </summary>
  345. private async void Protector()
  346. {
  347. while (true)
  348. {
  349. await Task.Delay(10000);
  350. if (IsCheckTime)
  351. {
  352. if ((DateTime.Now - Time).TotalSeconds < 90) continue;
  353. }
  354. else if ((_WebSocket != null && _WebSocket.IsAlive) || _IsInitConnecting)
  355. {
  356. continue;
  357. }
  358. Reconnect();
  359. }
  360. }
  361. /// <summary>
  362. /// 重新连接WebSocket
  363. /// </summary>
  364. private void Reconnect()
  365. {
  366. Console.WriteLine($"WebSocket开始重新连接,{DateTime.Now}");
  367. try
  368. {
  369. _IsInitConnecting = true;
  370. Connect();
  371. }
  372. finally
  373. {
  374. _IsInitConnecting = false;
  375. }
  376. }
  377. /// <summary>
  378. /// 向服务器请求注册
  379. /// </summary>
  380. public void Subscribe(string destination)
  381. {
  382. try
  383. {
  384. var sub = new StompMessage("SUBSCRIBE");
  385. sub["id"] = "sub-" + _Index++;
  386. sub["destination"] = destination;
  387. _WebSocket.Send(sub.ToString());
  388. }
  389. catch { }
  390. }
  391. /// <summary>
  392. /// 向服务器请求注册
  393. /// </summary>
  394. public async void Subscribe(string subid, string destination)
  395. {
  396. _Index++;
  397. var sub = new StompMessage("SUBSCRIBE");
  398. sub["id"] = subid;
  399. sub["destination"] = destination;
  400. _WebSocket.Send(sub.ToString());
  401. await Task.Delay(500);
  402. }
  403. /// <summary>
  404. /// 向服务器请求注册
  405. /// </summary>
  406. public async void Subscribe(string destination, Dictionary<string, string> headers)
  407. {
  408. try
  409. {
  410. _Index++;
  411. var sub = new StompMessage("SUBSCRIBE");
  412. foreach (var kv in headers)
  413. {
  414. sub[kv.Key] = kv.Value;
  415. }
  416. if (!headers.ContainsKey("id"))
  417. {
  418. sub["id"] = "sub-" + _Index++;
  419. }
  420. sub["destination"] = destination;
  421. _WebSocket.Send(sub.ToString());
  422. await Task.Delay(500);
  423. }
  424. catch { }
  425. }
  426. /// <summary>
  427. /// 发送消息
  428. /// </summary>
  429. public async void Send(StompMessage stomp)
  430. {
  431. if (stomp == null) return;
  432. stomp["id"] = "cs-" + _Index++;
  433. stomp["content-type"] = "application/json;charset=utf-8";
  434. stomp["accept-version"] = "1.2";
  435. stomp["clientId"] = RandomString(20);
  436. _WebSocket.Send(stomp.ToString());
  437. await Task.Delay(500);
  438. }
  439. /// <summary>
  440. /// 发送消息
  441. /// </summary>
  442. public async void Send(string destination, object content)
  443. {
  444. var stomp = new StompMessage("SEND", System.Text.Json.JsonSerializer.Serialize(content));
  445. stomp["id"] = "cs-" + _Index++;
  446. stomp["destination"] = destination;
  447. stomp["content-type"] = "application/json;charset=utf-8";
  448. stomp["accept-version"] = "1.2";
  449. stomp["clientId"] = RandomString(20);
  450. _WebSocket.Send(stomp.ToString());
  451. await Task.Delay(500);
  452. }
  453. /// <summary>
  454. /// 发送消息
  455. /// </summary>
  456. public async void Send(string destination, string command, string body, Dictionary<string, string> headers)
  457. {
  458. var stomp = new StompMessage(command, body + "\r\n", headers);
  459. stomp["id"] = "cs-" + _Index++;
  460. stomp["destination"] = destination;
  461. stomp["content-type"] = "application/json;charset=utf-8";
  462. stomp["accept-version"] = "1.2";
  463. stomp["clientId"] = RandomString(20);
  464. string stompText = stomp.ToString();
  465. _WebSocket.Send(stompText);
  466. await Task.Delay(500);
  467. }
  468. /// <summary>
  469. /// 获取随机字符串
  470. /// </summary>
  471. /// <param name="length">字符串长度</param>
  472. /// <returns>随机字符串</returns>
  473. private string RandomString(int length)
  474. {
  475. const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  476. var random = new Random();
  477. return new string(Enumerable.Repeat(chars, length)
  478. .Select(s => s[random.Next(s.Length)]).ToArray());
  479. }
  480. /// <summary>
  481. /// 关闭WebSocket连接
  482. /// </summary>
  483. internal void Close()
  484. {
  485. _WebSocket.Close();
  486. }
  487. }
  488. public class DateTimeConverter : JsonConverter<DateTime>
  489. {
  490. public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  491. {
  492. DateTime.TryParse(reader.GetString(), out DateTime dt);
  493. return dt;
  494. }
  495. public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
  496. {
  497. writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
  498. }
  499. }
  500. }