using JiShe.IoT.DeviceAggregation.Dto; using JiShe.ServicePro; using JiShe.ServicePro.ApacheIoTDB.Provider.Options; using JiShe.ServicePro.Core; using JiShe.ServicePro.DataChannelManages; using JiShe.ServicePro.DeviceManagement.DeviceInfos; using JiShe.ServicePro.DeviceManagement.DeviceInfos.Dto; using JiShe.ServicePro.DeviceManagement.Permissions; using JiShe.ServicePro.Dto; using JiShe.ServicePro.Enums; using JiShe.ServicePro.FreeRedisProvider; using JiShe.ServicePro.IoTDBManagement.DataChannels; using JiShe.ServicePro.IoTDBManagement.TableModels; using JiShe.ServicePro.OneNETManagement.OneNETDevices; using JiShe.ServicePro.OneNETManagement.OneNETProducts; using Mapster; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Volo.Abp; namespace JiShe.IoT.DeviceAggregation { /// /// 设备聚合服务 /// /// /// 设备服务 /// OneNET设备服务 /// Redis发布订阅服务 /// 数据通道 /// IoTDBOptions public class DeviceAggregationService(ILogger logger, IDeviceAppService deviceAppService, IOneNETDeviceService oneNETDeviceService, IReliableRedisPubSubService redisPubSubService, IIoTDBDataChannelManageService ioTDBDataChannelManageService,IOptions _ioTDBOptions) : IoTAppService, IDeviceAggregationService { IoTDBOptions ioTDBOptions = _ioTDBOptions.Value; /// /// 管理后台创建设备信息 /// /// /// [Authorize(DeviceManagementPermissions.DeviceInfoManagement.Create)] public async Task CreateDeviceForApiAsync(CreateDeviceAggregationInput input) { try { input.DeviceSourceTypeEnum = ServicePro.Enums.DeviceSourceTypeEnum.AdminSystem; if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.CTWing) { return await CTWingDeviceCreateAsync(input); } else if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.OneNET) { return await OneNETDeviceCreateAsync(input); } throw new UserFriendlyException($"不支持的物联网平台"); } catch (Exception) { throw; } } /// /// 管理后台批量创建设备信息 /// /// /// [Authorize(DeviceManagementPermissions.DeviceInfoManagement.Create)] public async Task BatchCreateDeviceForApiAsync(BatchCreateDeviceAggregationInput input) { try { if (input.AddressList == null || input.AddressList.Count <= 0) { throw new UserFriendlyException($"批量创建设备失败,设备信息不能为空。"); } if (input.AddressList.Count > 100) { throw new UserFriendlyException($"批量创建设备失败,设备信息不能超过100个。"); } input.DeviceSourceTypeEnum = ServicePro.Enums.DeviceSourceTypeEnum.AdminSystem; if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.CTWing) { return await CTWingDeviceBatchCreateAsync(input); } else if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.OneNET) { return await OneNETDeviceBatchCreateAsync(input); } throw new UserFriendlyException($"不支持的物联网平台"); } catch (Exception) { throw; } } /// /// 车间创建设备信息 /// /// /// public async Task CreateDeviceWorkshopAsync(CreateDeviceAggregationInput input) { try { input.DeviceSourceTypeEnum = DeviceSourceTypeEnum.Workshop; if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.CTWing) { return await CTWingDeviceCreateAsync(input); } else if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.OneNET) { return await OneNETDeviceCreateAsync(input); } throw new UserFriendlyException($"不支持的物联网平台"); } catch (Exception) { throw; } } /// /// 车间批量创建设备信息 /// /// /// public async Task BatchCreateDeviceWorkshopAsync(BatchCreateDeviceAggregationInput input) { try { if (input.AddressList == null || input.AddressList.Count <= 0) { throw new UserFriendlyException($"批量创建设备失败,设备信息不能为空。"); } if (input.AddressList.Count > 100) { throw new UserFriendlyException($"批量创建设备失败,设备信息不能超过100个。"); } input.DeviceSourceTypeEnum = DeviceSourceTypeEnum.Workshop; if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.CTWing) { return await CTWingDeviceBatchCreateAsync(input); } else if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.OneNET) { return await OneNETDeviceBatchCreateAsync(input); } throw new UserFriendlyException($"不支持的物联网平台"); } catch (Exception) { throw; } } /// /// 删除设备信息 /// /// /// /// [Authorize(DeviceManagementPermissions.DeviceInfoManagement.Delete)] public async Task DeleteAsync(IdInput input) { //检查设备信息是不是已经存在 var existsDeviceInfo = await deviceAppService.FindByIdAsync(input); if (existsDeviceInfo == null) { throw new UserFriendlyException($"删除设备失败,未找到对应设备信息。"); } //根据设备平台调用删除接口 if (existsDeviceInfo.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.OneNET) { return await DeleteDeviceInfoToOneNET(existsDeviceInfo); } else if (existsDeviceInfo.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.CTWing) { return await DeleteDeviceInfoToCTWing(existsDeviceInfo); } throw new UserFriendlyException($"不支持的物联网平台"); } /// /// 根据设备ID查询设备信息 /// /// /// /// public async Task FindByIdAsync(IdInput input) { return await deviceAppService.FindByIdAsync(input); } /// /// 重新推送设备信息到物联网平台 /// /// /// /// public async Task RepushDeviceInfoToIoTPlatform(IdInput input) { try { var entityDevice = await FreeSqlDbContext.Instance.Select().Where(f => f.Id == input.Id).FirstAsync(); if (entityDevice == null) { throw new UserFriendlyException($"推送失败,未找到设备数据"); } if (entityDevice.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.CTWing) { return await RepushDeviceInfoToCTWing(entityDevice); } else if (entityDevice.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.OneNET) { return await RepushDeviceInfoToOneNET(entityDevice); } throw new UserFriendlyException($"推送失败,异常的物联网平台"); } catch (Exception) { throw; } } /// /// 更新设备信息并处理缓存 /// /// /// /// /// private async Task DeviceUpdateHandler(DeviceManagementInfoDto input, HttpDataResult pushResult) { UpdateDeviceInput updateDeviceInput = input.Adapt(); updateDeviceInput.IoTPlatformResponse = pushResult.Serialize(); updateDeviceInput.IsPlatformPushSuccess = true; var updateResult = await deviceAppService.UpdateAsync(updateDeviceInput); if (updateResult == null) { logger.LogError($"{nameof(CreateDeviceForApiAsync)} 更新设备信息失败:{input.Serialize()}"); throw new UserFriendlyException($"推送结果更新失败。"); } //设备数据缓存到Redis DeviceCacheInfos deviceCacheInfos = input.Adapt(); deviceCacheInfos.IoTPlatformResponse = null; deviceCacheInfos.PlatformPassword = null; FreeRedisProvider.Instance.HSet(RedisConst.CacheAllDeviceInfoHashKey, input.DeviceAddress, deviceCacheInfos); return input.Adapt(); } /// /// 发送设备指令信息 /// /// /// public async Task DeviceCommandForApiAsync(DeviceCommandForApiInput input) { try { var deviceInfo = await deviceAppService.FindByIdAsync(input); if (deviceInfo == null) { throw new UserFriendlyException($"设备不存在"); } //将指令存储 var commandRequest = new OpenApiRequest() { Message = new ReceiveCommandInfoDto() { DeviceAddress = deviceInfo.DeviceAddress, Commands = input.CommandContent.Deserialize>(), DeviceType = input.DeviceType ?? DeviceTypeEnum.GATEWAY,//todo 设备类型 需要跟设备统一什么情况下知道具体设备类型 SourceType = DeviceTelemetrySourceTypeEnum.AdminSystem, TelemetryType = input.TelemetryType ?? DeviceTelemetryCommandTypeEnum.抄读, IoTPlatform = deviceInfo.IoTPlatform, }.Serialize(), }; var packetTaskInfo = GetDeviceTelemetryPacketTaskInfo(ioTDBOptions, commandRequest, deviceInfo.Adapt(), commandRequest.Message); //数据写入遥测任务数据存储通道 await ioTDBDataChannelManageService.DeviceTelemetryTaskWriterAsync(DataChannelManage.DeviceTelemetryTaskDataChannel.Writer, (DistributedMessageCenterConst.OneNETCommandIssuedEventName, packetTaskInfo)); if (deviceInfo.IoTPlatform == IoTPlatformTypeEnum.OneNET) { return await DeviceCommandInfoToOneNET(deviceInfo, packetTaskInfo); } else if (deviceInfo.IoTPlatform == IoTPlatformTypeEnum.CTWing) { await redisPubSubService.PublishReliableAsync(DistributedMessageCenterConst.CTWingAepCommandIssuedEventName,commandRequest); return true; } else { throw new UserFriendlyException($"创建设备失败,未找到对应的产品配置信息。"); } } catch (Exception) { throw; } } /// /// 业务系统批量创建设备信息 /// /// /// public async Task BatchCreateDeviceBusinessSystemAsync(BatchCreateDeviceAggregationInput input) { try { if (input.AddressList == null || input.AddressList.Count <= 0) { throw new UserFriendlyException($"业务系统批量创建设备信息,设备信息不能为空。"); } if (input.AddressList.Count > 100) { throw new UserFriendlyException($"业务系统批量创建设备信息,设备信息不能超过100个。"); } if (input.DeviceSourceTypeEnum != DeviceSourceTypeEnum.Prepay && input.DeviceSourceTypeEnum != DeviceSourceTypeEnum.Energy) { throw new UserFriendlyException($"业务系统批量创建设备信息,设备来源异常。"); } if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.CTWing) { return await CTWingDeviceBatchCreateAsync(input); } else if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.OneNET) { return await OneNETDeviceBatchCreateAsync(input); } throw new UserFriendlyException($"不支持的物联网平台"); } catch (Exception) { throw; } } #region OneNET 设备操作 /// /// OneNET设备创建 /// /// /// protected async Task OneNETDeviceCreateAsync(CreateDeviceAggregationInput input) { try { CreateDeviceInput createDeviceInput = input.Adapt(); var productInfo = await FreeSqlDbContext.Instance.Select() .Where(e => e.IoTPlatformProductId == input.IoTPlatformProductId)//此处不需要过滤产品状态,方便测试产品配置信息是否准确,避免跟车间生产搞混 .WhereIf(input.DeviceSourceTypeEnum == DeviceSourceTypeEnum.Workshop, e => e.IsEnabled == true) .FirstAsync(); if (productInfo == null) { throw new UserFriendlyException($"创建设备失败,未找到对应的产品配置信息。"); } createDeviceInput.DeviceName = input.DeviceAddress; createDeviceInput.IoTPlatformAccountId = productInfo.OneNETAccountId; createDeviceInput.IoTPlatformDeviceOpenInfo = $"{input.IoTPlatformProductId}{input.DeviceAddress}"; createDeviceInput.PlatformPassword = productInfo.ProductAccesskey; createDeviceInput.IoTPlatformProductName = productInfo.ProductName; createDeviceInput.AccountPhoneNumber = productInfo.AccountPhoneNumber; var insertResult = await deviceAppService.CreateAsync(createDeviceInput); if (insertResult == null) { logger.LogError($"{nameof(CreateDeviceForApiAsync)} 添加设备信息失败:{input.Serialize()}"); return false; } //推送至OneNET平台 var pushResult = await oneNETDeviceService.CreateDeviceInfoAsync(new CreateDeviceInfoInput() { DeviceName = createDeviceInput.IoTPlatformDeviceOpenInfo, ProductId = productInfo.IoTPlatformProductId, OneNETAccountId = productInfo.OneNETAccountId, Description = input.DeviceAddress, }); if (pushResult == null || pushResult.Code != ServicePro.Enums.ResponeResultEnum.Success) { logger.LogError($"{nameof(CreateDeviceForApiAsync)} 推送设备信息失败:{pushResult.Serialize()}"); return false; } await DeviceUpdateHandler(insertResult, pushResult); return true; } catch (Exception) { throw; } } /// /// OneNET设备批量创建 /// /// /// protected async Task OneNETDeviceBatchCreateAsync(BatchCreateDeviceAggregationInput input) { try { var productInfo = await FreeSqlDbContext.Instance.Select() .Where(e => e.IoTPlatformProductId == input.IoTPlatformProductId)//此处不需要过滤产品状态,方便测试产品配置信息是否准确,避免跟车间生产搞混 .WhereIf(input.DeviceSourceTypeEnum == DeviceSourceTypeEnum.Workshop, e => e.IsEnabled == true) .FirstAsync(); if (productInfo == null) { throw new UserFriendlyException($"批量创建设备失败,未找到对应的产品配置信息。"); } BatchCreateDeviceInput batchCreateDeviceInput = new BatchCreateDeviceInput() { IoTPlatform = input.IoTPlatform, AddressList = input.AddressList, DeviceInputs = new List() }; foreach (var item in input.AddressList) { CreateDeviceInput createDeviceInput = input.Adapt(); createDeviceInput.DeviceName = item; createDeviceInput.DeviceAddress = item; createDeviceInput.IoTPlatformAccountId = productInfo.OneNETAccountId; createDeviceInput.IoTPlatformDeviceOpenInfo = $"{input.IoTPlatformProductId}{item}"; createDeviceInput.PlatformPassword = productInfo.ProductAccesskey; createDeviceInput.IoTPlatformProductName = productInfo.ProductName; createDeviceInput.AccountPhoneNumber = productInfo.AccountPhoneNumber; createDeviceInput.DeviceSourceTypeEnum = input.DeviceSourceTypeEnum.Value; batchCreateDeviceInput.DeviceInputs.Add(createDeviceInput); } var insertResult = await deviceAppService.BatchCreateAsync(batchCreateDeviceInput); if (insertResult == null) { logger.LogError($"{nameof(OneNETDeviceBatchCreateAsync)} OneNET设备批量创建添加设备信息失败:{input.Serialize()}"); return false; } //推送至OneNET平台 var oneNETBatchCreateDeviceInfoInput = new BatchCreateDeviceInfoInput() { ProductId = productInfo.IoTPlatformProductId, OneNETAccountId = productInfo.OneNETAccountId, DeviceList = new List() }; oneNETBatchCreateDeviceInfoInput.DeviceList = batchCreateDeviceInput.DeviceInputs.Select(d => d.IoTPlatformDeviceOpenInfo).ToList(); var pushResult = await oneNETDeviceService.BatchCreateDeviceInfoAsync(oneNETBatchCreateDeviceInfoInput); if (pushResult == null || pushResult.Code != ServicePro.Enums.ResponeResultEnum.Success) { logger.LogError($"{nameof(CreateDeviceForApiAsync)} 推送设备信息失败:{pushResult.Serialize()}"); return false; } foreach (var item in insertResult) { var successEntity = pushResult.Data.Successlist.Where(d => d.DeviceName == item.IoTPlatformDeviceOpenInfo).FirstOrDefault(); if (successEntity != null) { await DeviceUpdateHandler(item, HttpDataResultExtensions.Success(successEntity)); } } return true; } catch (Exception) { throw; } } /// /// 重新推送设备信息到OneNET物联网平台 /// /// /// /// public async Task RepushDeviceInfoToOneNET(DeviceManagementInfoDto input) { try { var productInfo = await FreeSqlDbContext.Instance.Select() .Where(e => e.IoTPlatformProductId == input.IoTPlatformProductId) .FirstAsync(); if (productInfo == null) { throw new UserFriendlyException($"推送失败,未找到对应的产品配置信息。"); } //检查OneNET平台设备是否已经存在 var oneNETDeviceInfoResult = await oneNETDeviceService.DeviceInfoDetailAsync(new DeviceInfoDetailInput() { DeviceName = input.IoTPlatformDeviceOpenInfo, ProductId = productInfo.IoTPlatformProductId, OneNETAccountId = productInfo.OneNETAccountId, }); if (oneNETDeviceInfoResult != null && oneNETDeviceInfoResult.Code == ServicePro.Enums.ResponeResultEnum.Success) { throw new UserFriendlyException($"推送失败,OneNET账号{productInfo.AccountPhoneNumber}的产品下{productInfo.ProductName}已经存在该设备{input.DeviceAddress}。"); } //推送至OneNET平台 var pushResult = await oneNETDeviceService.CreateDeviceInfoAsync(new CreateDeviceInfoInput() { DeviceName = input.IoTPlatformDeviceOpenInfo, ProductId = productInfo.IoTPlatformProductId, OneNETAccountId = productInfo.OneNETAccountId, Description = input.DeviceAddress, }); if (pushResult == null || pushResult.Code != ServicePro.Enums.ResponeResultEnum.Success) { logger.LogError($"{nameof(CreateDeviceForApiAsync)} 推送设备信息失败:{pushResult.Serialize()}"); throw new UserFriendlyException($"平台请求失败。"); } return await DeviceUpdateHandler(input, pushResult); } catch (Exception) { throw; } } /// /// 删除OneNET平台设备 /// /// /// /// public async Task DeleteDeviceInfoToOneNET(DeviceManagementInfoDto input) { try { var productInfo = await FreeSqlDbContext.Instance.Select() .Where(e => e.IoTPlatformProductId == input.IoTPlatformProductId) .FirstAsync(); if (productInfo == null) { throw new UserFriendlyException($"删除失败,未找到对应的产品配置信息。"); } //删除OneNET平台设备信息 var deleteResult = await oneNETDeviceService.DeleteDeviceInfoAsync(new DeleteDeviceInfoInput() { DeviceName = input.IoTPlatformDeviceOpenInfo, ProductId = productInfo.IoTPlatformProductId, OneNETAccountId = productInfo.OneNETAccountId, }); if (deleteResult == null || deleteResult.Code != ServicePro.Enums.ResponeResultEnum.Success) { logger.LogError($"{nameof(CreateDeviceForApiAsync)} 删除设备信息失败:{deleteResult.Serialize()}"); throw new UserFriendlyException($"删除设备平台请求失败。"); } var localDeleteReult = await deviceAppService.DeleteAsync(new IdInput() { Id = input.Id }); if (localDeleteReult == false) { throw new UserFriendlyException($"平台设备信息删除成功,系统删除设备失败。"); } return localDeleteReult; } catch (Exception) { throw; } } /// /// 发送OneNET平台设备指令 /// /// /// /// /// public async Task DeviceCommandInfoToOneNET(DeviceManagementInfoDto deviceInfo, DeviceTelemetryPacketTaskInfo packetTaskInfo) { try { //检查下设备是否在线 var deviceOnlineStatus = await oneNETDeviceService.DeviceInfoDetailAsync(new DeviceInfoDetailInput() { DeviceName = deviceInfo.IoTPlatformDeviceOpenInfo, OneNETAccountId = deviceInfo.IoTPlatformAccountId, ProductId = deviceInfo.IoTPlatformProductId, }); if (deviceOnlineStatus == null || deviceOnlineStatus.Code != ResponeResultEnum.Success) { throw new UserFriendlyException("获取平台设备信息失败"); } if (deviceOnlineStatus.Data.Status != 1) { throw new UserFriendlyException("设备不在线"); } await redisPubSubService.PublishReliableAsync(DistributedMessageCenterConst.OneNETCommandIssuedEventName, packetTaskInfo); return true; } catch (Exception) { throw; } } #endregion #region CTWing 设备操作 /// /// CTWing 设备创建 /// /// /// protected async Task CTWingDeviceCreateAsync(CreateDeviceAggregationInput input) { throw new UserFriendlyException($"CTWing 设备创建失败,功能未实现。"); } /// /// CTWing 批量设备创建 /// /// /// protected async Task CTWingDeviceBatchCreateAsync(BatchCreateDeviceAggregationInput input) { try { throw new UserFriendlyException($"CTWing 批量设备创建失败,CTWing暂未实现。"); } catch (Exception) { throw; } } /// /// 重新推送设备信息到CTWing物联网平台 /// /// /// /// public async Task RepushDeviceInfoToCTWing(DeviceManagementInfoDto input) { try { throw new UserFriendlyException($"推送失败,CTWing暂未实现。"); } catch (Exception) { throw; } } /// /// 删除CTWing平台设备 /// /// /// /// public async Task DeleteDeviceInfoToCTWing(DeviceManagementInfoDto input) { try { throw new UserFriendlyException($"删除失败,CTWing暂未实现。"); } catch (Exception) { throw; } } #endregion } }