ConnectService.cs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using JsonRpcLite.Services;
  6. using WingInterfaceLibrary.DB.Request;
  7. using WingInterfaceLibrary.DTO.Device;
  8. using WingInterfaceLibrary.DTO.Organization;
  9. using WingInterfaceLibrary.Enum;
  10. using WingInterfaceLibrary.Interface;
  11. using WingInterfaceLibrary.Request;
  12. using WingInterfaceLibrary.Request.Authentication;
  13. using WingInterfaceLibrary.Request.Device;
  14. using WingInterfaceLibrary.Result.Device;
  15. using WingServerCommon.Log;
  16. using WingServerCommon.Mapper;
  17. using WingServerCommon.Service;
  18. namespace WingDeviceService.Service
  19. {
  20. /// <summary>
  21. /// 鉴权服务
  22. /// </summary>
  23. public partial class DeviceService : JsonRpcService, IConnectService
  24. {
  25. private readonly string _sourceUrl = "cloud.xinglinghui.com";
  26. private readonly object _createShortCodeLocker = new object();
  27. /// <summary>设备连接云服务</summary>
  28. /// <param name="request">请求对象</param>
  29. /// <returns>授权响应</returns>
  30. /// <remarks>POST</remarks>
  31. public async Task<ConnectResult> ConnectAsync(ConnectRequest request)
  32. {
  33. try
  34. {
  35. #region Params Check
  36. if (string.IsNullOrWhiteSpace(request.DeviceUniqueCode))
  37. {
  38. throw new RpcException(1001, "DeviceUniqueCode empty error", "DeviceUniqueCode empty error");
  39. }
  40. if (string.IsNullOrWhiteSpace(request.DeviceModel))
  41. {
  42. throw new RpcException(1001, "DeviceModel empty error", "DeviceModel empty error");
  43. }
  44. if (string.IsNullOrWhiteSpace(request.DeviceType))
  45. {
  46. throw new RpcException(1001, "DeviceType empty error", "DeviceType empty error");
  47. }
  48. if (string.IsNullOrWhiteSpace(request.SoftwareVersion))
  49. {
  50. throw new RpcException(1001, "SoftwareVersion empty error", "SoftwareVersion empty error");
  51. }
  52. if (string.IsNullOrWhiteSpace(request.SystemVersion))
  53. {
  54. throw new RpcException(1001, "SystemVersion empty error", "SystemVersion empty error");
  55. }
  56. if (string.IsNullOrWhiteSpace(request.CPUModel))
  57. {
  58. throw new RpcException(1001, "CPUModel empty error", "CPUModel empty error");
  59. }
  60. if (string.IsNullOrWhiteSpace(request.SystemLanguage))
  61. {
  62. throw new RpcException(1001, "SystemLanguage empty error", "SystemLanguage empty error");
  63. }
  64. #endregion
  65. var deviceDto = await _deviceInfoDBServiceProxy.FindDeviceInfoBySerialNumberAsync(request.DeviceUniqueCode);
  66. var shortCode = deviceDto?.ShortCode;
  67. var deviceCode = deviceDto?.DeviceCode;
  68. var deviceName = deviceDto?.Name;
  69. if (string.IsNullOrWhiteSpace(shortCode))
  70. {
  71. shortCode = GenerateShortCode();
  72. }
  73. if (string.IsNullOrWhiteSpace(deviceName))
  74. {
  75. if (deviceDto == null && !string.IsNullOrWhiteSpace(request.Name))
  76. {
  77. deviceName = request.Name;
  78. }
  79. else
  80. {
  81. deviceName = shortCode;
  82. }
  83. }
  84. if (deviceDto == null)
  85. {
  86. var deviceInfoDB = new DeviceInfoDTO()
  87. {
  88. SerialNumber = request.DeviceUniqueCode,
  89. Name = request.Name,
  90. Description = request.Description,
  91. OrganizationCode = request.OrganizationCode,
  92. DeviceModel = request.DeviceModel,
  93. DeviceType = request.DeviceType,
  94. DeviceSoftwareVersion = request.SoftwareVersion,
  95. ShortCode = shortCode,
  96. SystemVersion = request.SystemVersion,
  97. CPUModel = request.CPUModel,
  98. SystemLanguage = request.SystemLanguage
  99. };
  100. deviceCode = await _deviceInfoDBServiceProxy.InsertDeviceInfoAsync(new WingInterfaceLibrary.DB.Request.CreateDeviceInfoDBRequest
  101. {
  102. Data = deviceInfoDB
  103. });
  104. //创建虚拟机构
  105. var inventedOrgCode = "invented_" + shortCode;
  106. var orgData = new TableDataItem<OrganizationDTO>
  107. {
  108. Data = new OrganizationDTO
  109. {
  110. OrganizationCode = inventedOrgCode,
  111. RootCode = inventedOrgCode,
  112. OrganizationName = shortCode,
  113. OrganizationType = OrganizationTypeEnum.Corporation,
  114. State = OrganizationStateEnum.Audited,
  115. RegionCode = "1000000",
  116. Isinvented = true
  117. },
  118. PlatformDatas = new Dictionary<string, string>(),
  119. ExtensionData = string.Empty,
  120. };
  121. await _organizationDBService.CreateOrganizationsAsync(new CreateOrganizationsDBRequest { Infos = new List<TableDataItem<OrganizationDTO>> { orgData } });
  122. }
  123. var applyRequest = new ApplyTokenRequest(AccountType.US, deviceName, request.Platform, request.LoginSource, deviceCode, _sourceUrl, 0);
  124. var tokenInfo = await _authenticationService.ApplyTokenAsync(applyRequest);
  125. if (!string.IsNullOrWhiteSpace(tokenInfo.Code))
  126. {
  127. _deviceHeartRateManager.AddOrUpdate(tokenInfo.Code);
  128. }
  129. return new ConnectResult
  130. {
  131. Token = tokenInfo.Code,
  132. UniqueCode = shortCode
  133. };
  134. }
  135. catch (RpcException)
  136. {
  137. throw;
  138. }
  139. catch (Exception ex)
  140. {
  141. throw new RpcException(1001, ex.Message, ex.InnerException?.Message);
  142. }
  143. }
  144. /// <summary>查询当前设备信息</summary>
  145. /// <param name="request">请求对象</param>
  146. /// <returns>设备信息</returns>
  147. /// <remarks>POST</remarks>
  148. public async Task<CacheDeviceDTO> GetDeviceByTokenAsync(TokenRequest request)
  149. {
  150. var deviceCode = await ValidateTokenAsync(request.Token);
  151. var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  152. var cacheDeviceInfo = deviceDTO.MappingTo<CacheDeviceDTO>();
  153. cacheDeviceInfo.IsOnline = await GetDeviceOnlineState(deviceCode);
  154. return cacheDeviceInfo;
  155. }
  156. /// <summary>设备与云服务断开连接</summary>
  157. /// <param name="request">请求对象</param>
  158. /// <returns>是否成功</returns>
  159. /// <value>true</value>
  160. public async Task<bool> DisConnectAsync(TokenRequest request)
  161. {
  162. try
  163. {
  164. await ValidateTokenAsync(request.Token);
  165. await _authenticationService.LogOffAsync(request);
  166. return true;
  167. }
  168. catch (RpcException)
  169. {
  170. throw;
  171. }
  172. catch (Exception ex)
  173. {
  174. throw new RpcException(1001, ex.Message, ex.InnerException?.Message);
  175. }
  176. }
  177. /// <summary>获取设备在线状态</summary>
  178. /// <param name="deviceCode"></param>
  179. /// <returns></returns>
  180. private async Task<bool> GetDeviceOnlineState(string deviceCode)
  181. {
  182. var tokenList = await _authenticationService.GetTokensWithClientIdAsync(new GetTokensWithClientIdRequest { ClientId = deviceCode });
  183. return tokenList.FirstOrDefault()?.IsOnline ?? false;
  184. }
  185. /// <summary>生成唯一 shortCode</summary>
  186. /// <returns></returns>
  187. private string GenerateShortCode()
  188. {
  189. try
  190. {
  191. lock (_createShortCodeLocker)
  192. {
  193. var uniqueId = new byte[6];
  194. var rand = new Random((int)(DateTime.Now.Ticks % 1000000));
  195. for (int i = 0; i < 6; i++)
  196. {
  197. int randCode;
  198. do
  199. {
  200. randCode = rand.Next(50, 90);
  201. uniqueId[i] = Convert.ToByte(randCode);
  202. } while (randCode >= 58 && randCode <= 64 || randCode == 79 || randCode == 73);
  203. }
  204. return System.Text.Encoding.ASCII.GetString(uniqueId);
  205. }
  206. }
  207. catch (Exception ex)
  208. {
  209. Logger.WriteLineError($"GenerateShortCode error {ex}");
  210. }
  211. return string.Empty;
  212. }
  213. }
  214. }