vCloudTerminalV2.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  1. using JsonRpcLite.Network;
  2. using JsonRpcLite.Rpc;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using Vinno.IUS.Common.Log;
  8. using Vinno.vCloud.Common.FIS.AfterSales;
  9. using Vinno.vCloud.Common.FIS.FLYINSONOLogin;
  10. using Vinno.vCloud.Common.FIS.Helper;
  11. using Vinno.vCloud.Common.FIS.LiveVideos;
  12. using Vinno.vCloud.Common.FIS.Notification;
  13. using Vinno.vCloud.Common.FIS.Remedicals;
  14. using WingInterfaceLibrary.Enum;
  15. using WingInterfaceLibrary.Enum.NotificationEnum;
  16. using WingInterfaceLibrary.Interface;
  17. using WingInterfaceLibrary.Notifications;
  18. using WingInterfaceLibrary.Request;
  19. using WingInterfaceLibrary.Request.Device;
  20. using WingInterfaceLibrary.Result.Device;
  21. namespace Vinno.vCloud.Common.FIS
  22. {
  23. internal class vCloudTerminalV2 : IvCloudTerminalV2
  24. {
  25. private readonly Dictionary<TerminalFeatureType, object> _features = new Dictionary<TerminalFeatureType, object>();
  26. private readonly ConnectionInfo _connectionInfo;
  27. private readonly string _deviceName;
  28. private readonly string _password;
  29. private readonly bool _isUserDefined;
  30. private readonly LoginSource _loginSource;
  31. private readonly Platform _platform;
  32. private readonly string _deviceType;
  33. private readonly string _url;
  34. private readonly int _usScreenWidth;
  35. private readonly int _usScreenHeight;
  36. private readonly bool _isUseHttps;
  37. private string _token;
  38. private int _connectionCheckCycle;
  39. private string _prefix;
  40. private JsonRpcClient _client;
  41. private JsonRpcHttpClientEngine _clientEngine;
  42. private IConnectService _connectService;
  43. private IVinnoServerService _vinnoServerService;
  44. private IDeviceService _deviceService;
  45. private TerminalStatus _status;
  46. private ConnectionCheckerV2 _connectionChecker;
  47. private HeartRateKeeperV2 _heartRateKeeper;
  48. private bool _disposed;
  49. private int _reconnectCounter;
  50. private FISWebSocket _webSocket;
  51. /// <summary>
  52. /// Raised when the status is changed.
  53. /// </summary>
  54. public event EventHandler StatusChanged;
  55. /// <summary>
  56. /// Gets the unique id.
  57. /// </summary>
  58. public string UniqueId { get; private set; }
  59. /// <inheritdoc />
  60. /// <summary>
  61. /// Gets the status of the Terminal
  62. /// </summary>
  63. /// <remarks>
  64. /// </remarks>
  65. public TerminalStatus Status
  66. {
  67. get => _status;
  68. private set
  69. {
  70. if (_status != value)
  71. {
  72. _status = value;
  73. OnStatusChanged();
  74. }
  75. }
  76. }
  77. public string TerminalName => _deviceName;
  78. public string TerminalMode => _connectionInfo.DeviceMode;
  79. /// <summary>
  80. /// Gets the global remedical working folder.
  81. /// </summary>
  82. internal static string WorkingFolder { get; private set; }
  83. public vCloudTerminalV2(ConnectionInfo connectionInfo, bool isUseHttps = false)
  84. {
  85. _usScreenHeight = connectionInfo.USScreenHeight;
  86. _usScreenWidth = connectionInfo.USScreenWidth;
  87. _isUseHttps = isUseHttps;
  88. _prefix = "http://";
  89. if (_isUseHttps)
  90. {
  91. _prefix = "https://";
  92. }
  93. _connectionInfo = connectionInfo;
  94. _deviceName = connectionInfo.Account.Name;
  95. _password = connectionInfo.Account.Password;
  96. _isUserDefined = connectionInfo.Account.IsUserDefined;
  97. _url = connectionInfo.ServerUrl;
  98. _loginSource = connectionInfo.LoginSource;
  99. //Set the default value 10 seconds.
  100. _connectionCheckCycle = 10;
  101. _status = TerminalStatus.Offline;
  102. WorkingFolder = connectionInfo.FISFolder;
  103. if (!Directory.Exists(WorkingFolder))
  104. {
  105. Directory.CreateDirectory(WorkingFolder);
  106. }
  107. CreateJsonrpcClient();
  108. CreateConnectionKeeper();
  109. }
  110. /// <inheritdoc />
  111. /// <summary>
  112. /// Get the feature instance by feature enum.
  113. /// </summary>
  114. /// <typeparam name="T">The interface of the feature</typeparam>
  115. /// <param name="featureType">The feature type</param>
  116. /// <returns>The instance of the feature</returns>
  117. /// <remarks>
  118. /// If the feature doesn't exist, this method will return null.
  119. /// </remarks>
  120. public T GetFeature<T>(TerminalFeatureType featureType) where T : IFeatureV2
  121. {
  122. if (_features.ContainsKey(featureType))
  123. {
  124. var feature = _features[featureType];
  125. if (feature is T t)
  126. {
  127. return t;
  128. }
  129. }
  130. return default(T);
  131. }
  132. /// <summary>
  133. /// Connect to server.
  134. /// </summary>
  135. internal void Connect()
  136. {
  137. try
  138. {
  139. var connectRequest = new ConnectRequest
  140. {
  141. DeviceUniqueCode = _deviceName,
  142. Password = _password,
  143. DeviceModel = _connectionInfo.DeviceMode,
  144. DeviceType = _connectionInfo.DeviceType.ToString(),
  145. SoftwareVersion = _connectionInfo.SoftwareVersion,
  146. SystemVersion = _connectionInfo.USOS,
  147. CPUModel = _connectionInfo.USCPU,
  148. SystemLanguage = _connectionInfo.LanguageName,
  149. Description = "",
  150. Name = "",
  151. OrganizationCode = "",
  152. DepartmentCode = "",
  153. LoginSource = _connectionInfo.LoginSource,
  154. Platform = _connectionInfo.Platform,
  155. };
  156. ConnectResult result = JsonRpcHelper.Connect(_connectService, connectRequest);
  157. if (result == null)
  158. {
  159. throw new InvalidDataException("JsonRPCHelper Connect Result is null");
  160. }
  161. else
  162. {
  163. UniqueId = result.UniqueCode;
  164. _token = result.Token;
  165. HandleLoginResult();
  166. }
  167. }
  168. catch (Exception e)
  169. {
  170. Logger.WriteLineError($"Terminal {_deviceName} login url:{_url} failed {e}");
  171. Status = TerminalStatus.LoginFailed;
  172. }
  173. }
  174. public void Disconnect()
  175. {
  176. var status = TerminalStatus.Logoff;
  177. try
  178. {
  179. var tokenRequest = new TokenRequest
  180. {
  181. Token = _token,
  182. };
  183. bool result = JsonRpcHelper.Disconnect(_connectService, tokenRequest);
  184. if (!result)
  185. {
  186. throw new Exception($"JsonRPCHelper Disconnect Result is fail");
  187. }
  188. else if (result)
  189. {
  190. status = TerminalStatus.Logoff;
  191. }
  192. }
  193. catch (Exception e)
  194. {
  195. Logger.WriteLineError($"Disconnect terminal {_deviceName} error {e}");
  196. }
  197. finally
  198. {
  199. Release();
  200. FLYINSONOUserManager.Instance.Clear();
  201. Status = status;
  202. }
  203. }
  204. /// <summary>
  205. /// Update enabled feature types.
  206. /// </summary>
  207. /// <param name="enabledFeatureTypes">The enabled feature types.</param>
  208. public void UpdateFeatures(IEnumerable<TerminalFeatureType> enabledFeatureTypes)
  209. {
  210. var removedFeatures = _features.Keys.Where(f => !enabledFeatureTypes.Contains(f)).ToList();
  211. foreach (var feature in removedFeatures)
  212. {
  213. var disposable = _features[feature] as IDisposable;
  214. disposable?.Dispose();
  215. _features.Remove(feature);
  216. }
  217. foreach (var enabledFeature in enabledFeatureTypes)
  218. {
  219. if (!_features.ContainsKey(enabledFeature))
  220. {
  221. var feature = GetFeature(enabledFeature);
  222. _features.Add(enabledFeature, feature);
  223. }
  224. }
  225. }
  226. /// <summary>
  227. /// Get Device Is Encrypted Show
  228. /// </summary>
  229. /// <param name="isEncryptedShow"></param>
  230. /// <returns></returns>
  231. public bool IsEncryptedShow()
  232. {
  233. try
  234. {
  235. var tokenRequest = new TokenRequest
  236. {
  237. Token = _token,
  238. };
  239. var cacheDeviceDTO = JsonRpcHelper.GetDeviceByToken(_connectService, tokenRequest);
  240. if (cacheDeviceDTO == null)
  241. {
  242. throw new InvalidOperationException("JsonRPCHelper GetDeviceByToken Result is null");
  243. }
  244. else
  245. {
  246. return cacheDeviceDTO.IsEncryptedShow;
  247. }
  248. }
  249. catch (Exception ex)
  250. {
  251. Logger.WriteLineError($"IsEncryptedShow Error:{ex}");
  252. return false;
  253. }
  254. }
  255. /// <summary>
  256. /// Set Device Is Encrypted Show
  257. /// </summary>
  258. /// <param name="isEncryptedShow"></param>
  259. /// <returns></returns>
  260. public bool SetIsEncryptedShow(bool isEncryptedShow)
  261. {
  262. try
  263. {
  264. var setDeviceIsEncryptedShowRequest = new SetDeviceIsEncryptedShowRequest
  265. {
  266. IsEncryptedShow = isEncryptedShow,
  267. Token = _token
  268. };
  269. bool result = JsonRpcHelper.SetDeviceIsEncryptedShow(_connectService, setDeviceIsEncryptedShowRequest);
  270. if (!result)
  271. {
  272. throw new Exception($"JsonRPCHelper SetDeviceIsEncryptedShowAsync Result is false");
  273. }
  274. else
  275. {
  276. return true; ;
  277. }
  278. }
  279. catch (Exception ex)
  280. {
  281. Logger.WriteLineError($"SetDeviceIsEncryptedShow Error:{ex}");
  282. return false;
  283. }
  284. }
  285. public void Dispose()
  286. {
  287. if (!_disposed)
  288. {
  289. Release();
  290. _disposed = true;
  291. }
  292. GC.SuppressFinalize(this);
  293. }
  294. private void HandleLoginResult()
  295. {
  296. Status = TerminalStatus.Logoning;
  297. var tokenRequest = new TokenRequest
  298. {
  299. Token = _token
  300. };
  301. var result = JsonRpcHelper.QueryServerConfig(_deviceService, tokenRequest);
  302. if (result == null)
  303. {
  304. throw new InvalidDataException($"JsonRPCHelper QueryServerConfig Result is null");
  305. }
  306. else
  307. {
  308. vCloudServerConfig.Instance.IsUploadThumbnail = result.IsUploadThumbnail;
  309. vCloudServerConfig.Instance.PatientType = result.PatientType;
  310. vCloudServerConfig.Instance.HeartRateSeconds = result.HeartRateSeconds;
  311. vCloudServerConfig.Instance.NotificationUrl = result.NotificationUrl;
  312. vCloudServerConfig.Instance.MergedChannel = result.MergedChannel;
  313. Logger.WriteLineInfo($"vCloudServerConfig:{vCloudServerConfig.Instance}");
  314. if (result.ServerConfigList != null)
  315. {
  316. foreach (var kp in result.ServerConfigList)
  317. {
  318. Logger.WriteLineInfo($"ServerConfigList Key:{kp.Key},Value:{kp.Value} ");
  319. }
  320. }
  321. }
  322. if (IsEncryptedShow())
  323. {
  324. Logger.WriteLineInfo("Start SetIsEncryptedShow False");
  325. SetIsEncryptedShow(false);
  326. Logger.WriteLineInfo("SetIsEncryptedShow False Finish");
  327. }
  328. CreateHeartRateKeeper();
  329. CreateWebSocket();
  330. ReleaseFeatures();
  331. UpdateFeatures(_connectionInfo.EnabledFeatures);
  332. _reconnectCounter = 0;
  333. Status = TerminalStatus.Logon;
  334. Logger.WriteLineInfo($"{_deviceName} Login url:{_url} successed, Token:{_token}, UniqueId:{UniqueId}");
  335. }
  336. private void CreateWebSocket()
  337. {
  338. if (string.IsNullOrWhiteSpace(vCloudServerConfig.Instance.NotificationUrl))
  339. {
  340. Logger.WriteLineError($"CreateWebSocket Error Because The Notificaion Url is null");
  341. return;
  342. }
  343. if (_webSocket == null)
  344. {
  345. var uri = vCloudServerConfig.Instance.NotificationUrl.Replace("{0}", _token);
  346. uri = uri.Replace("{1}", "0");
  347. Logger.WriteLineInfo($"Websocket uri :{uri}");
  348. _webSocket = new FISWebSocket(uri);
  349. _webSocket.NotificationReceived += OnNoitificationReceived;
  350. _webSocket.Connect();
  351. }
  352. }
  353. private void DisposeWebSocket()
  354. {
  355. try
  356. {
  357. if (_webSocket != null)
  358. {
  359. _webSocket.NotificationReceived -= OnNoitificationReceived;
  360. _webSocket.Dispose();
  361. _webSocket = null;
  362. }
  363. }
  364. catch (Exception ex)
  365. {
  366. Logger.WriteLineError($"VCloudTerminalV2 Dispose WebSocket Error:{ex}");
  367. }
  368. }
  369. private void OnNoitificationReceived(object sender, NotificationArgs e)
  370. {
  371. switch (e.NotificationType)
  372. {
  373. case NotificationTypeEnum.ConnectionNotification:
  374. Logger.WriteLineInfo($"VCloudTerminalV2 ConnectionNotification Receive");
  375. break;
  376. case NotificationTypeEnum.DisconnectNotification:
  377. Logger.WriteLineInfo($"VCloudTerminalV2 DisconnectNotification Receive");
  378. break;
  379. case NotificationTypeEnum.DeviceControlledParametersNotification:
  380. try
  381. {
  382. if (e.Params is DeviceControlledParametersNotification deviceControlledParametersNotification)
  383. {
  384. HandleDeviceControlledParametersNotification(deviceControlledParametersNotification);
  385. }
  386. }
  387. catch (Exception ex)
  388. {
  389. Logger.WriteLineError($"vCloudTerminalV2 Handle DeviceControlledParametersNotification Error:{ex}");
  390. }
  391. break;
  392. }
  393. }
  394. private void HandleDeviceControlledParametersNotification(DeviceControlledParametersNotification deviceControlledParametersNotification)
  395. {
  396. if (deviceControlledParametersNotification.ControlType == ControlDeviceParameterEnum.Start)
  397. {
  398. Logger.WriteLineInfo($"VCloudTerminalV2 DeviceControlledParametersNotification StartControl Receive");
  399. var afterSales = GetFeature<IAfterSalesV2>(TerminalFeatureType.AfterSales);
  400. if (afterSales != null)
  401. {
  402. afterSales.UpdateAfterSalesInfo(deviceControlledParametersNotification.ControlUserCode, deviceControlledParametersNotification.ControlUserName);
  403. }
  404. else
  405. {
  406. var remoteControlRequest = new RemoteControlRequest
  407. {
  408. Token = _token,
  409. ControlUserCode = deviceControlledParametersNotification.ControlUserCode,
  410. };
  411. var result = JsonRpcHelper.RejectRemoteControl(_deviceService, remoteControlRequest);
  412. if (result)
  413. {
  414. Logger.WriteLineInfo($"VCloudTerminalV2 RejectRemoteControl Success");
  415. }
  416. else
  417. {
  418. Logger.WriteLineError($"VCloudTerminalV2 RejectRemoteControl Failed");
  419. }
  420. }
  421. }
  422. }
  423. private void CreateHeartRateKeeper()
  424. {
  425. if (_heartRateKeeper == null)
  426. {
  427. _heartRateKeeper = new HeartRateKeeperV2(_deviceService, _token, vCloudServerConfig.Instance.HeartRateSeconds);
  428. _heartRateKeeper.Start();
  429. }
  430. }
  431. private void DisposeHeartRateKeeper()
  432. {
  433. try
  434. {
  435. if (_heartRateKeeper != null)
  436. {
  437. _heartRateKeeper.Stop();
  438. _heartRateKeeper = null;
  439. }
  440. }
  441. catch (Exception ex)
  442. {
  443. Logger.WriteLineError($"vCloudTerminalV2 DisposeHeartRateKeeper Error:{ex}");
  444. }
  445. }
  446. private void OnStatusChanged()
  447. {
  448. Logger.WriteLineInfo($"VCloudTerminalV2 Status Changed:{_status}");
  449. StatusChanged?.Invoke(this, EventArgs.Empty);
  450. }
  451. private void CreateConnectionKeeper()
  452. {
  453. _connectionChecker = new ConnectionCheckerV2(_vinnoServerService, _connectionCheckCycle);
  454. var defaultStatus = false;
  455. if (!_connectionChecker.Check())
  456. {
  457. Status = TerminalStatus.Offline;
  458. }
  459. else
  460. {
  461. Status = TerminalStatus.Online;
  462. defaultStatus = true;
  463. }
  464. if (_connectionChecker != null)//当网络异常或者Server无法访问时,_connectionChecker.Check()一般会消耗十几秒,此时用户可能已经修改服务器地址,并重新登录,此时_connectionChecker已经被Dispose
  465. {
  466. _connectionChecker.Offlined += OnOfflined;
  467. _connectionChecker.Start(defaultStatus);
  468. }
  469. }
  470. private void DisposeConnectionKeeper()
  471. {
  472. try
  473. {
  474. if (_connectionChecker != null)
  475. {
  476. _connectionChecker.Offlined -= OnOfflined;
  477. _connectionChecker.Stop();
  478. _connectionChecker = null;
  479. }
  480. }
  481. catch (Exception ex)
  482. {
  483. Logger.WriteLineError($"VCloudTerminalV2 Dispose WebSocket Error:{ex}");
  484. }
  485. }
  486. private void OnOfflined(object sender, EventArgs e)
  487. {
  488. Release();
  489. Status = TerminalStatus.Offline;
  490. //No need to reconnect after instance release
  491. if (_disposed) return;
  492. //Reconnect
  493. if (_reconnectCounter < 5)
  494. {
  495. if (!string.IsNullOrEmpty(_deviceName) && !string.IsNullOrEmpty(_password))
  496. {
  497. CreateJsonrpcClient();
  498. CreateConnectionKeeper();
  499. if (Status == TerminalStatus.Online)
  500. {
  501. Status = TerminalStatus.Reconnecting;
  502. Connect();
  503. _reconnectCounter++;
  504. }
  505. }
  506. }
  507. else
  508. {
  509. Dispose();
  510. }
  511. }
  512. private void Release()
  513. {
  514. DisposeConnectionKeeper();
  515. DisposeHeartRateKeeper();
  516. DisposeWebSocket();
  517. ReleaseFeatures();
  518. ReleaseJsonrpcClient();
  519. }
  520. private void CreateJsonrpcClient()
  521. {
  522. try
  523. {
  524. _client = new JsonRpcClient();
  525. _clientEngine = new JsonRpcHttpClientEngine($"{_prefix}{_url}");
  526. _client.UseEngine(_clientEngine);
  527. _connectService = _client.CreateProxy<IConnectService>();
  528. _vinnoServerService = _client.CreateProxy<IVinnoServerService>();
  529. _deviceService = _client.CreateProxy<IDeviceService>();
  530. }
  531. catch (Exception ex)
  532. {
  533. Logger.WriteLineError($"VCloudTerminalV2 CreateJsonrpcClient Error:{ex}");
  534. }
  535. }
  536. private void ReleaseJsonrpcClient()
  537. {
  538. try
  539. {
  540. if (_client != null)
  541. {
  542. _client.Dispose();
  543. _client = null;
  544. _clientEngine = null;
  545. _connectService = null;
  546. _vinnoServerService = null;
  547. _deviceService = null;
  548. }
  549. }
  550. catch (Exception ex)
  551. {
  552. Logger.WriteLineError($"VCloudTerminal V2 ReleaseJsonrpcClient Error:{ex}");
  553. }
  554. }
  555. private void ReleaseFeatures()
  556. {
  557. foreach (var type in _features.Keys.ToList())
  558. {
  559. var feature = _features[type];
  560. var disposable = feature as IDisposable;
  561. disposable?.Dispose();
  562. _features.Remove(type);
  563. }
  564. }
  565. private IFeatureV2 GetFeature(TerminalFeatureType terminalFeatureType)
  566. {
  567. switch (terminalFeatureType)
  568. {
  569. case TerminalFeatureType.Remedical:
  570. return new RemedicalV2(_token, _client);
  571. case TerminalFeatureType.LiveVideo:
  572. if (_connectionInfo.DeviceType.ToUpper() == "SONOPOST")
  573. {
  574. return new LiveVideoV2(_token, UniqueId, _usScreenWidth, _usScreenHeight, _webSocket, true, _client, _connectionInfo.DeviceMode, _deviceType, _deviceName, _connectionInfo.SoftwareVersion);
  575. }
  576. else
  577. {
  578. return new LiveVideoV2(_token, UniqueId, _usScreenWidth, _usScreenHeight, _webSocket, false, _client, _connectionInfo.DeviceMode, _deviceType, _deviceName, _connectionInfo.SoftwareVersion);
  579. }
  580. case TerminalFeatureType.AfterSales:
  581. return new AfterSalesV2(_token, _client, _webSocket);
  582. default:
  583. return null;
  584. }
  585. }
  586. }
  587. }