123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331 |
- using System;
- using System.Threading.Tasks;
- using JsonRpcLite.Services;
- using WingDeviceService.Common;
- using WingInterfaceLibrary.DTO.Authentication;
- using WingInterfaceLibrary.DTO.Device;
- using WingInterfaceLibrary.Enum;
- using WingInterfaceLibrary.Interface;
- using WingInterfaceLibrary.Request;
- using WingInterfaceLibrary.Request.Authentication;
- using WingInterfaceLibrary.Request.Device;
- using WingInterfaceLibrary.Request.Notification;
- using WingInterfaceLibrary.Result.Device;
- using WingServerCommon.Log;
- using WingServerCommon.Mapper;
- using WingServerCommon.Service;
- namespace WingDeviceService.Service
- {
- /// <summary>
- /// 鉴权服务
- /// </summary>
- public partial class DeviceService : JsonRpcService, IConnectService
- {
- private readonly string _sourceUrl = "cloud.xinglinghui.com";
- private readonly object _createShortCodeLocker = new object();
- /// <summary>设备连接云服务</summary>
- /// <param name="request">请求对象</param>
- /// <returns>授权响应</returns>
- /// <remarks>POST</remarks>
- public async Task<ConnectResult> Connect(ConnectRequest request)
- {
- try
- {
- #region Params Check
- if (string.IsNullOrWhiteSpace(request.DeviceUniqueCode))
- {
- throw new RpcException(1001, "DeviceUniqueCode empty error", "DeviceUniqueCode empty error");
- }
- if (string.IsNullOrWhiteSpace(request.DeviceModel))
- {
- throw new RpcException(1001, "DeviceModel empty error", "DeviceModel empty error");
- }
- if (string.IsNullOrWhiteSpace(request.DeviceType))
- {
- throw new RpcException(1001, "DeviceType empty error", "DeviceType empty error");
- }
- if (string.IsNullOrWhiteSpace(request.SoftwareVersion))
- {
- throw new RpcException(1001, "SoftwareVersion empty error", "SoftwareVersion empty error");
- }
- if (string.IsNullOrWhiteSpace(request.SystemVersion))
- {
- throw new RpcException(1001, "SystemVersion empty error", "SystemVersion empty error");
- }
- if (string.IsNullOrWhiteSpace(request.CPUModel))
- {
- throw new RpcException(1001, "CPUModel empty error", "CPUModel empty error");
- }
- if (string.IsNullOrWhiteSpace(request.SystemLanguage))
- {
- throw new RpcException(1001, "SystemLanguage empty error", "SystemLanguage empty error");
- }
- #endregion
- var deviceDto = await _deviceInfoDBServiceProxy.FindDeviceInfoBySerialNumberAsync(request.DeviceUniqueCode);
- var shortCode = deviceDto?.ShortCode;
- var deviceCode = deviceDto?.DeviceCode;
- if (string.IsNullOrWhiteSpace(shortCode))
- {
- shortCode = GenerateShortCode();
- }
- if (deviceDto == null)
- {
- var deviceInfoDB = new DeviceInfoDTO()
- {
- SerialNumber = request.DeviceUniqueCode,
- Name = request.Name,
- Description = request.Description,
- OrganizationCode = request.OrganizationCode,
- DeviceModel = request.DeviceModel,
- DeviceType = request.DeviceType,
- DeviceSoftwareVersion = request.SoftwareVersion,
- ShortCode = shortCode,
- SystemVersion = request.SystemVersion,
- CPUModel = request.CPUModel,
- SystemLanguage = request.SystemLanguage
- };
- deviceCode = await _deviceInfoDBServiceProxy.InsertDeviceInfoAsync(new WingInterfaceLibrary.DB.Request.CreateDeviceInfoDBRequest
- {
- Data = deviceInfoDB
- });
- }
- var now = DateTime.UtcNow;
- await _deviceInfoDBServiceProxy.UpdateLoginTimeAsync(new WingInterfaceLibrary.DB.Request.UpdateLoginTimeDBRequest
- {
- DeviceCode = deviceCode,
- LastLoginTime = now,
- ShortCode = shortCode,
- DeviceModel = request.DeviceModel,
- DeviceType = request.DeviceType,
- SoftwareVersion = request.SoftwareVersion,
- SystemVersion = request.SystemVersion,
- CPUModel = request.CPUModel,
- Description = request.Description,
- Name = request.Name,
- OrganizationCode = request.OrganizationCode,
- SystemLanguage = request.SystemLanguage,
- });
- var tokenId = await _authenticationServiceProxy.CreateAuthToken(new CreateAuthTokenRequest
- {
- Code = deviceCode,
- IssueTime = now,
- SourceUrl = _sourceUrl,
- });
- await SetDeviceOnlineAsync(deviceCode, true, true);
- //注册通知
- var subscribeNotifyRequest = new SubscribeNotifyRequest()
- {
- UserCode = deviceCode,
- Token = tokenId
- };
- var result = await _notificationService.SubscribeNotify(subscribeNotifyRequest);
- return new ConnectResult
- {
- Token = tokenId,
- UniqueCode = shortCode
- };
- }
- catch (RpcException)
- {
- throw;
- }
- catch (Exception ex)
- {
- throw new RpcException(1001, ex.Message, ex.InnerException?.Message);
- }
- }
- /// <summary>查询当前设备信息</summary>
- /// <param name="request">请求对象</param>
- /// <returns>设备信息</returns>
- /// <remarks>POST</remarks>
- public async Task<CacheDeviceDTO> GetDeviceByToken(TokenRequest request)
- {
- try
- {
- var deviceTokenDTO = await _authenticationServiceProxy.GetAuthToken(request);
- if (deviceTokenDTO == null || string.IsNullOrWhiteSpace(deviceTokenDTO.Code))
- {
- throw new RpcException(2004, "Permission validation error", "Permission validation error");
- }
- var cacheDeviceDTO = await GetDevice(deviceTokenDTO.Code);
- if (cacheDeviceDTO == null)
- {
- throw new RpcException(2004, "deviceInfo not find", "deviceInfo not find");
- }
- if (cacheDeviceDTO.LastLoginTime > deviceTokenDTO.IssueTime)
- {
- throw new RpcException(20041, "Permission validation error", "Permission validation error");
- }
- await SetDeviceOnlineAsync(deviceTokenDTO.Code, true);
- return cacheDeviceDTO;
- }
- catch (RpcException)
- {
- throw;
- }
- catch (Exception ex)
- {
- throw new RpcException(1001, ex.Message, ex.InnerException?.Message);
- }
- }
- /// <summary>设备与云服务断开连接</summary>
- /// <param name="request">请求对象</param>
- /// <returns>是否成功</returns>
- /// <value>true</value>
- public async Task<bool> DisConnect(TokenRequest request)
- {
- try
- {
- var deviceTokenDTO = await _authenticationServiceProxy.GetAuthToken(request);
- if (deviceTokenDTO == null || string.IsNullOrWhiteSpace(deviceTokenDTO.Code))
- {
- Logger.WriteLineWarn($"DisConnect: invalid token");
- }
- var cacheDeviceDTO = await GetDevice(deviceTokenDTO.Code);
- if (cacheDeviceDTO != null && cacheDeviceDTO.LastLoginTime <= deviceTokenDTO.IssueTime)
- {
- if (await UpdateLastLoginTime(cacheDeviceDTO))
- {
- _cacheDeviceManager.Remove(cacheDeviceDTO.DeviceCode);
- Logger.WriteLineInfo($"DisConnect: device disconnect success.");
- return true;
- }
- else
- {
- throw new RpcException(20041, "disconnect error", "disconnect error");
- }
- }
- return true;
- }
- catch (RpcException)
- {
- throw;
- }
- catch (Exception ex)
- {
- throw new RpcException(1001, ex.Message, ex.InnerException?.Message);
- }
- }
- /// <summary>生成唯一 shortCode</summary>
- /// <returns></returns>
- private string GenerateShortCode()
- {
- try
- {
- lock (_createShortCodeLocker)
- {
- var uniqueId = new byte[6];
- var rand = new Random((int)(DateTime.Now.Ticks % 1000000));
- for (int i = 0; i < 6; i++)
- {
- int randCode;
- do
- {
- randCode = rand.Next(50, 90);
- uniqueId[i] = Convert.ToByte(randCode);
- } while (randCode >= 58 && randCode <= 64 || randCode == 79 || randCode == 73);
- }
- return System.Text.Encoding.ASCII.GetString(uniqueId);
- }
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"GenerateShortCode error {ex}");
- }
- return string.Empty;
- }
- /// <summary>查询设备信息</summary>
- /// <param name="deviceCode"></param>
- /// <returns></returns>
- private async Task<CacheDeviceDTO> GetDevice(string deviceCode)
- {
- try
- {
- var cacheDTO = _cacheDeviceManager.Get(deviceCode);
- if (cacheDTO == null)
- {
- var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
- cacheDTO = deviceDTO.MappingTo<CacheDeviceDTO>();
- _cacheDeviceManager.AddOrUpdate(cacheDTO.DeviceCode, cacheDTO);
- }
- return cacheDTO;
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"GetDevice error {ex}");
- }
- return null;
- }
- /// <summary>更新设备在线状态</summary>
- /// <param name="deviceCode"></param>
- /// <param name="isOnline"></param>
- /// <param name="refresh"></param>
- /// <returns></returns>
- private async Task<CacheDeviceDTO> SetDeviceOnlineAsync(string deviceCode, bool isOnline, bool refresh = false)
- {
- try
- {
- var cacheDTO = _cacheDeviceManager.Get(deviceCode);
- if (cacheDTO == null || refresh)
- {
- var deviceDTO = await _deviceInfoDBServiceProxy.FindDeviceInfoByCodeAsync(deviceCode);
- cacheDTO = deviceDTO.MappingTo<CacheDeviceDTO>();
- cacheDTO.IsOnline = isOnline;
- cacheDTO.SourceUrl = _sourceUrl;
- _cacheDeviceManager.AddOrUpdate(cacheDTO.DeviceCode, cacheDTO);
- }
- else if (cacheDTO.IsOnline != isOnline)
- {
- cacheDTO.IsOnline = isOnline;
- _cacheDeviceManager.AddOrUpdate(cacheDTO.DeviceCode, cacheDTO);
- }
- return cacheDTO;
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"SetDeviceOnlineAsync error {ex}");
- }
- return null;
- }
- private async Task<bool> UpdateLastLoginTime(DeviceInfoDTO deviceInfo)
- {
- try
- {
- var result = await _deviceInfoDBServiceProxy.UpdateLoginTimeAsync(new WingInterfaceLibrary.DB.Request.UpdateLoginTimeDBRequest
- {
- DeviceCode = deviceInfo.DeviceCode,
- LastLoginTime = DateTime.UtcNow,
- ShortCode = deviceInfo.ShortCode,
- DeviceModel = deviceInfo.DeviceModel,
- DeviceType = deviceInfo.DeviceType,
- SoftwareVersion = deviceInfo.DeviceSoftwareVersion,
- SystemVersion = deviceInfo.SystemVersion,
- CPUModel = deviceInfo.CPUModel,
- Description = deviceInfo.Description,
- Name = deviceInfo.Name,
- OrganizationCode = deviceInfo.OrganizationCode,
- SystemLanguage = deviceInfo.SystemLanguage,
- });
- return result;
- }
- catch (Exception ex)
- {
- Logger.WriteLineError($"UpdateLastLoginTime err, {ex}");
- return false;
- }
- }
- }
- }
|