701 lines
28 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
{
/// <summary>
/// 设备聚合服务
/// </summary>
/// <param name="logger"></param>
/// <param name="deviceAppService">设备服务</param>
/// <param name="oneNETDeviceService">OneNET设备服务</param>
/// <param name="redisPubSubService">Redis发布订阅服务</param>
/// <param name="ioTDBDataChannelManageService">数据通道</param>
/// <param name="_ioTDBOptions">IoTDBOptions</param>
public class DeviceAggregationService(ILogger<DeviceAggregationService> logger, IDeviceAppService deviceAppService, IOneNETDeviceService oneNETDeviceService, IReliableRedisPubSubService redisPubSubService, IIoTDBDataChannelManageService ioTDBDataChannelManageService,IOptions<IoTDBOptions> _ioTDBOptions) : IoTAppService, IDeviceAggregationService
{
IoTDBOptions ioTDBOptions = _ioTDBOptions.Value;
/// <summary>
/// 管理后台创建设备信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[Authorize(DeviceManagementPermissions.DeviceInfoManagement.Create)]
public async Task<bool> 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;
}
}
/// <summary>
/// 管理后台批量创建设备信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<bool> 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;
}
}
/// <summary>
/// 车间创建设备信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<bool> 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;
}
}
/// <summary>
/// 车间批量创建设备信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<bool> 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;
}
}
/// <summary>
/// 删除设备信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
/// <exception cref="UserFriendlyException"></exception>
[Authorize(DeviceManagementPermissions.DeviceInfoManagement.Delete)]
public async Task<bool> 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($"不支持的物联网平台");
}
/// <summary>
/// 根据设备ID查询设备信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
/// <exception cref="UserFriendlyException"></exception>
public async Task<DeviceManagementInfoDto> FindByIdAsync(IdInput input)
{
return await deviceAppService.FindByIdAsync(input);
}
/// <summary>
/// 重新推送设备信息到物联网平台
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
/// <exception cref="UserFriendlyException"></exception>
public async Task<DeviceManagementInfoDto> RepushDeviceInfoToIoTPlatform(IdInput input)
{
try
{
var entityDevice = await FreeSqlDbContext.Instance.Select<DeviceManagementInfo>().Where(f => f.Id == input.Id).FirstAsync<DeviceManagementInfoDto>();
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;
}
}
/// <summary>
/// 更新设备信息并处理缓存
/// </summary>
/// <param name="input"></param>
/// <param name="pushResult"></param>
/// <returns></returns>
/// <exception cref="UserFriendlyException"></exception>
private async Task<DeviceManagementInfoDto> DeviceUpdateHandler(DeviceManagementInfoDto input, HttpDataResult pushResult)
{
UpdateDeviceInput updateDeviceInput = input.Adapt<UpdateDeviceInput>();
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>();
deviceCacheInfos.IoTPlatformResponse = null;
deviceCacheInfos.PlatformPassword = null;
FreeRedisProvider.Instance.HSet<DeviceCacheInfos>(RedisConst.CacheAllDeviceInfoHashKey, input.DeviceAddress, deviceCacheInfos);
return input.Adapt<DeviceManagementInfoDto>();
}
/// <summary>
/// 发送设备指令信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<bool> DeviceCommandForApiAsync(DeviceCommandForApiInput input)
{
try
{
var deviceInfo = await deviceAppService.FindByIdAsync(input);
if (deviceInfo == null)
{
throw new UserFriendlyException($"设备不存在");
}
//将指令存储Kafka的OneNET主题中
var commandRequest = new OpenApiRequest()
{
Message = new ReceiveCommandInfoDto()
{
DeviceAddress = deviceInfo.DeviceAddress,
Commands = input.CommandContent.Deserialize<Dictionary<string,object>>(),
DeviceType = input.DeviceType ?? DeviceTypeEnum.Focus,//todo 设备类型 需要跟设备统一什么情况下知道具体设备类型
SourceType = DeviceTelemetrySourceTypeEnum.AdminSystem,
TelemetryType = input.TelemetryType ?? DeviceTelemetryCommandTypeEnum.,
IoTPlatform = deviceInfo.IoTPlatform,
}.Serialize(),
};
var packetTaskInfo = GetDeviceTelemetryPacketTaskInfo(ioTDBOptions, commandRequest, deviceInfo.Adapt<DeviceCacheInfos>(), 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;
}
}
#region OneNET
/// <summary>
/// OneNET设备创建
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
protected async Task<bool> OneNETDeviceCreateAsync(CreateDeviceAggregationInput input)
{
try
{
CreateDeviceInput createDeviceInput = input.Adapt<CreateDeviceInput>();
var productInfo = await FreeSqlDbContext.Instance.Select<OneNETProductInfos>()
.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;
}
}
/// <summary>
/// OneNET设备批量创建
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
protected async Task<bool> OneNETDeviceBatchCreateAsync(BatchCreateDeviceAggregationInput input)
{
try
{
var productInfo = await FreeSqlDbContext.Instance.Select<OneNETProductInfos>()
.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<CreateDeviceInput>()
};
foreach (var item in input.AddressList)
{
CreateDeviceInput createDeviceInput = input.Adapt<CreateDeviceInput>();
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<string>()
};
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;
}
}
/// <summary>
/// 重新推送设备信息到OneNET物联网平台
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
/// <exception cref="UserFriendlyException"></exception>
public async Task<DeviceManagementInfoDto> RepushDeviceInfoToOneNET(DeviceManagementInfoDto input)
{
try
{
var productInfo = await FreeSqlDbContext.Instance.Select<OneNETProductInfos>()
.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;
}
}
/// <summary>
/// 删除OneNET平台设备
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
/// <exception cref="UserFriendlyException"></exception>
public async Task<bool> DeleteDeviceInfoToOneNET(DeviceManagementInfoDto input)
{
try
{
var productInfo = await FreeSqlDbContext.Instance.Select<OneNETProductInfos>()
.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;
}
}
/// <summary>
/// 发送OneNET平台设备指令
/// </summary>
/// <param name="deviceInfo"></param>
/// <param name="packetTaskInfo"></param>
/// <returns></returns>
/// <exception cref="UserFriendlyException"></exception>
public async Task<bool> 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
/// <summary>
/// CTWing 设备创建
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
protected async Task<bool> CTWingDeviceCreateAsync(CreateDeviceAggregationInput input)
{
throw new UserFriendlyException($"CTWing 设备创建失败,功能未实现。");
}
/// <summary>
/// CTWing 批量设备创建
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
protected async Task<bool> CTWingDeviceBatchCreateAsync(BatchCreateDeviceAggregationInput input)
{
try
{
throw new UserFriendlyException($"CTWing 批量设备创建失败CTWing暂未实现。");
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 重新推送设备信息到CTWing物联网平台
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
/// <exception cref="UserFriendlyException"></exception>
public async Task<DeviceManagementInfoDto> RepushDeviceInfoToCTWing(DeviceManagementInfoDto input)
{
try
{
throw new UserFriendlyException($"推送失败CTWing暂未实现。");
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 删除CTWing平台设备
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
/// <exception cref="UserFriendlyException"></exception>
public async Task<bool> DeleteDeviceInfoToCTWing(DeviceManagementInfoDto input)
{
try
{
throw new UserFriendlyException($"删除失败CTWing暂未实现。");
}
catch (Exception)
{
throw;
}
}
#endregion
}
}