ConnectService.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  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. ThrowCustomerException(CustomerRpcCode.DeviceUniqueCodeEmpty, "DeviceUniqueCode empty error");
  39. }
  40. if (string.IsNullOrWhiteSpace(request.DeviceModel))
  41. {
  42. ThrowCustomerException(CustomerRpcCode.DeviceModelEmpty, "DeviceModel empty error");
  43. }
  44. if (string.IsNullOrWhiteSpace(request.DeviceType))
  45. {
  46. ThrowCustomerException(CustomerRpcCode.DeviceTypeEmpty, "DeviceType empty error");
  47. }
  48. if (string.IsNullOrWhiteSpace(request.SoftwareVersion))
  49. {
  50. ThrowCustomerException(CustomerRpcCode.SoftwareVersionEmpty, "SoftwareVersion empty error");
  51. }
  52. if (string.IsNullOrWhiteSpace(request.SystemVersion))
  53. {
  54. ThrowCustomerException(CustomerRpcCode.SystemVersionEmpty, "SystemVersion empty error");
  55. }
  56. if (string.IsNullOrWhiteSpace(request.CPUModel))
  57. {
  58. ThrowCustomerException(CustomerRpcCode.CPUModelEmpty, "CPUModel empty error");
  59. }
  60. if (string.IsNullOrWhiteSpace(request.SystemLanguage))
  61. {
  62. ThrowCustomerException(CustomerRpcCode.SystemVersionEmpty, "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. Password = request.Password,
  91. Description = request.Description,
  92. OrganizationCode = request.OrganizationCode,
  93. DeviceModel = request.DeviceModel,
  94. DeviceType = request.DeviceType,
  95. DeviceSoftwareVersion = request.SoftwareVersion,
  96. ShortCode = shortCode,
  97. SystemVersion = request.SystemVersion,
  98. CPUModel = request.CPUModel,
  99. SystemLanguage = request.SystemLanguage
  100. };
  101. deviceCode = await _deviceInfoDBServiceProxy.InsertDeviceInfoAsync(new WingInterfaceLibrary.DB.Request.CreateDeviceInfoDBRequest
  102. {
  103. Data = deviceInfoDB
  104. });
  105. //创建虚拟机构
  106. var inventedOrgCode = "invented_" + shortCode;
  107. var orgData = new TableDataItem<OrganizationDTO>
  108. {
  109. Data = new OrganizationDTO
  110. {
  111. OrganizationCode = inventedOrgCode,
  112. RootCode = inventedOrgCode,
  113. OrganizationName = shortCode,
  114. OrganizationType = OrganizationTypeEnum.Corporation,
  115. State = OrganizationStateEnum.Audited,
  116. RegionCode = "1000000",
  117. Isinvented = true
  118. },
  119. PlatformDatas = new Dictionary<string, string>(),
  120. ExtensionData = string.Empty,
  121. };
  122. await _organizationDBService.CreateOrganizationsAsync(new CreateOrganizationsDBRequest { Infos = new List<TableDataItem<OrganizationDTO>> { orgData } });
  123. }
  124. else
  125. {
  126. deviceDto.DeviceModel = request.DeviceModel;
  127. deviceDto.DeviceType = request.DeviceType;
  128. deviceDto.DeviceSoftwareVersion = request.SoftwareVersion;
  129. deviceDto.SystemVersion = request.SystemVersion;
  130. deviceDto.CPUModel = request.CPUModel;
  131. // deviceDto.Description = request.Description;
  132. // deviceDto.Name = request.Name;
  133. // deviceDto.OrganizationCode = request.OrganizationCode;
  134. deviceDto.SystemLanguage = request.SystemLanguage;
  135. await _deviceInfoDBServiceProxy.UpdateDeviceInfoByCodeAsync(deviceDto.DeviceCode, deviceDto, string.Empty, true);
  136. }
  137. var applyRequest = new ApplyTokenRequest(AccountType.US, deviceName, request.Platform, request.LoginSource, deviceCode, _sourceUrl, 0);
  138. var tokenInfo = await _authenticationService.ApplyTokenAsync(applyRequest);
  139. if (!string.IsNullOrWhiteSpace(tokenInfo.Code))
  140. {
  141. _deviceHeartRateManager.AddOrUpdate(tokenInfo.Code);
  142. }
  143. return new ConnectResult
  144. {
  145. Token = tokenInfo.Code,
  146. UniqueCode = shortCode
  147. };
  148. }
  149. catch (Exception ex)
  150. {
  151. Logger.WriteLineWarn($"device connect server failed, err:{ex}");
  152. throw;
  153. }
  154. }
  155. /// <summary>查询当前设备信息</summary>
  156. /// <param name="request">请求对象</param>
  157. /// <returns>设备信息</returns>
  158. /// <remarks>POST</remarks>
  159. public async Task<CacheDeviceDTO> GetDeviceByTokenAsync(TokenRequest request)
  160. {
  161. var deviceCode = await GetClientIdByTokenAsync(request.Token);
  162. var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
  163. var cacheDeviceInfo = deviceDTO.MappingTo<CacheDeviceDTO>();
  164. cacheDeviceInfo.IsOnline = await GetDeviceOnlineState(deviceCode);
  165. return cacheDeviceInfo;
  166. }
  167. /// <summary>设备与云服务断开连接</summary>
  168. /// <param name="request">请求对象</param>
  169. /// <returns>是否成功</returns>
  170. /// <value>true</value>
  171. public async Task<bool> DisConnectAsync(TokenRequest request)
  172. {
  173. try
  174. {
  175. await _authenticationService.LogOffAsync(request);
  176. return true;
  177. }
  178. catch (Exception ex)
  179. {
  180. Logger.WriteLineWarn($"device disconnect failed, ex:{ex}");
  181. throw;
  182. }
  183. }
  184. /// <summary>获取设备在线状态</summary>
  185. /// <param name="deviceCode"></param>
  186. /// <returns></returns>
  187. private async Task<bool> GetDeviceOnlineState(string deviceCode)
  188. {
  189. var tokenList = await _authenticationService.GetTokensWithClientIdAsync(new GetTokensWithClientIdRequest { ClientId = deviceCode });
  190. return tokenList.FirstOrDefault()?.IsOnline ?? false;
  191. }
  192. /// <summary>生成唯一 shortCode</summary>
  193. /// <returns></returns>
  194. private string GenerateShortCode()
  195. {
  196. try
  197. {
  198. lock (_createShortCodeLocker)
  199. {
  200. var uniqueId = new byte[6];
  201. var rand = new Random((int)(DateTime.Now.Ticks % 1000000));
  202. for (int i = 0; i < 6; i++)
  203. {
  204. int randCode;
  205. do
  206. {
  207. randCode = rand.Next(50, 90);
  208. uniqueId[i] = Convert.ToByte(randCode);
  209. } while (randCode >= 58 && randCode <= 64 || randCode == 79 || randCode == 73);
  210. }
  211. return System.Text.Encoding.ASCII.GetString(uniqueId);
  212. }
  213. }
  214. catch (Exception ex)
  215. {
  216. Logger.WriteLineError($"GenerateShortCode error {ex}");
  217. }
  218. return string.Empty;
  219. }
  220. }
  221. }