Compare commits

..

3 Commits

Author SHA1 Message Date
ChenYi
fd30054a8b 更新 2025-08-04 17:29:56 +08:00
ChenYi
f30074d7d9 优化设备指令下发处理逻辑 2025-08-04 17:29:47 +08:00
ChenYi
e99e853db3 OneNET设备批量添加 2025-08-04 11:59:07 +08:00
12 changed files with 547 additions and 93 deletions

@ -1 +1 @@
Subproject commit f038a3c4239c680b512523d7b777c7e73cbc1ebf Subproject commit 8df0a54f551a1f894014c9b0e8eca5d7c5c4f51b

View File

@ -0,0 +1,35 @@
using JiShe.ServicePro.Enums;
using System.ComponentModel.DataAnnotations;
namespace JiShe.IoT.DeviceAggregation
{
/// <summary>
/// 批量创建设备信息
/// </summary>
public class BatchCreateDeviceAggregationInput
{
/// <summary>
/// 表通信地址集合
/// </summary>
[Required(ErrorMessage = "设备地址不能为空")]
public List<string> AddressList { get; set; }
/// <summary>
/// 物联网平台类型
/// </summary>
[Required(ErrorMessage = "物联网平台类型不能为空")]
public IoTPlatformTypeEnum IoTPlatform { get; set; }
/// <summary>
/// 集中器在物联网平台中对应的产品Id
/// </summary>
[Required(ErrorMessage = "产品Id不能为空")]
public string IoTPlatformProductId { get; set; }
/// <summary>
/// 设备来源类型
/// </summary>
public DeviceSourceTypeEnum? DeviceSourceTypeEnum { get; set; }
}
}

View File

@ -21,10 +21,16 @@ namespace JiShe.IoT.DeviceAggregation.Dto
public IoTPlatformTypeEnum IoTPlatform { get; set; } public IoTPlatformTypeEnum IoTPlatform { get; set; }
/// <summary> /// <summary>
/// 集中器在物联网平台中对应的产品Id /// 设备在物联网平台中对应的产品Id
/// </summary> /// </summary>
[Required(ErrorMessage = "产品Id不能为空")] [Required(ErrorMessage = "产品Id不能为空")]
public string IoTPlatformProductId { get; set; } public string IoTPlatformProductId { get; set; }
/// <summary>
/// 设备来源类型
/// </summary>
public DeviceSourceTypeEnum? DeviceSourceTypeEnum { get; set; }
} }
} }

View File

@ -0,0 +1,36 @@
using JiShe.ServicePro.Enums;
using System.ComponentModel.DataAnnotations;
namespace JiShe.IoT.DeviceAggregation
{
/// <summary>
/// 设备命令
/// </summary>
public class DeviceCommandForApiInput
{
/// <summary>
/// 表通信地址
/// </summary>
[Required(ErrorMessage = "设备地址不能为空")]
public string DeviceAddress { get; set; }
/// <summary>
/// 物联网平台类型
/// </summary>
[Required(ErrorMessage = "物联网平台类型不能为空")]
public IoTPlatformTypeEnum IoTPlatform { get; set; }
/// <summary>
/// 设备在物联网平台中对应的产品Id
/// </summary>
[Required(ErrorMessage = "产品Id不能为空")]
public string IoTPlatformProductId { get; set; }
/// <summary>
/// 设备在物联网平台中发送的命令内容JSON格式
/// </summary>
[Required(ErrorMessage = "命令内容不能为空")]
public string CommandContent { get; set; }
}
}

View File

@ -17,6 +17,13 @@ namespace JiShe.IoT.DeviceAggregation
/// <returns></returns> /// <returns></returns>
Task<bool> CreateDeviceForApiAsync(CreateDeviceAggregationInput input); Task<bool> CreateDeviceForApiAsync(CreateDeviceAggregationInput input);
/// <summary>
/// 管理后台批量创建设备信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
Task<bool> BatchCreateDeviceForApiAsync(BatchCreateDeviceAggregationInput input);
/// <summary> /// <summary>
/// 车间创建设备信息 /// 车间创建设备信息
/// </summary> /// </summary>
@ -24,6 +31,20 @@ namespace JiShe.IoT.DeviceAggregation
/// <returns></returns> /// <returns></returns>
Task<bool> CreateDeviceWorkshopAsync(CreateDeviceAggregationInput input); Task<bool> CreateDeviceWorkshopAsync(CreateDeviceAggregationInput input);
/// <summary>
/// 车间批量创建设备信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
Task<bool> BatchCreateDeviceWorkshopAsync(BatchCreateDeviceAggregationInput input);
/// <summary>
/// 发送设备指令信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
Task<bool> DeviceCommandForApiAsync(DeviceCommandForApiInput input);
/// <summary> /// <summary>
/// 删除设备信息 /// 删除设备信息
/// </summary> /// </summary>

View File

@ -43,4 +43,8 @@
<PackageReference Include="JiShe.ServicePro.OneNETManagement.Application.Contracts" /> <PackageReference Include="JiShe.ServicePro.OneNETManagement.Application.Contracts" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="BusinessSystemAggregation\Dto\" />
</ItemGroup>
</Project> </Project>

View File

@ -1,5 +1,8 @@
using JiShe.IoT.OneNETAggregation.Dto; using JiShe.IoT.OneNETAggregation.Dto;
using JiShe.ServicePro; using JiShe.ServicePro;
using JiShe.ServicePro.Core;
using JiShe.ServicePro.DeviceManagement.DeviceInfos;
using JiShe.ServicePro.Dto;
using JiShe.ServicePro.Encrypt; using JiShe.ServicePro.Encrypt;
using JiShe.ServicePro.Enums; using JiShe.ServicePro.Enums;
using JiShe.ServicePro.Kafka.Consts; using JiShe.ServicePro.Kafka.Consts;
@ -18,7 +21,7 @@ namespace JiShe.IoT.BusinessSystemAggregation
/// <summary> /// <summary>
/// 业务系统聚合服务 /// 业务系统聚合服务
/// </summary> /// </summary>
public class BusinessSystemAggregationService(IOptions<ServerApplicationOptions> options, IKafkaProducerService _producerService) :IoTAppService, IBusinessSystemAggregationService public class BusinessSystemAggregationService(IOptions<ServerApplicationOptions> options, IKafkaProducerService _producerService, IDeviceAppService deviceAppService) : IoTAppService, IBusinessSystemAggregationService
{ {
ServerApplicationOptions srverOptions = options.Value; ServerApplicationOptions srverOptions = options.Value;
@ -34,16 +37,38 @@ namespace JiShe.IoT.BusinessSystemAggregation
bool verifySignatureReult = EncryptUtil.OpenApiVerifySignature(input.Message, input.Nonce, input.Timestamp, input.Signature, srverOptions.VerifySignatureToken); bool verifySignatureReult = EncryptUtil.OpenApiVerifySignature(input.Message, input.Nonce, input.Timestamp, input.Signature, srverOptions.VerifySignatureToken);
if (verifySignatureReult == false)//签名校验失败 if (verifySignatureReult == false)//签名校验失败
{ {
return HttpDataResultExtensions.Failed<List<OneNetWorkshopProductListOutput>>("签名校验失败", -101, ResponeResultEnum.NotAllowed); return HttpDataResultExtensions.Failed("签名校验失败", -101, ResponeResultEnum.NotAllowed);
} }
if (string.IsNullOrWhiteSpace(input.Message)) if (string.IsNullOrWhiteSpace(input.Message))
{ {
return HttpDataResultExtensions.Failed<List<OneNetWorkshopProductListOutput>>("指令下发内容不能为空", -102, ResponeResultEnum.Fail); return HttpDataResultExtensions.Failed("指令下发内容不能为空", -102, ResponeResultEnum.Fail);
} }
//将指令存储Kafka中 //查询设备信息,判断设备在哪个平台
var messageBody = input.Message.Deserialize<ReceiveCommandInfoDto>();
//限定来源类型必须为业务系统
if (messageBody.SourceType != DeviceTelemetrySourceTypeEnum.BusinessSystem)
{
return HttpDataResultExtensions.Failed("设备指令来源类型错误业务系统传固定值2", -103, ResponeResultEnum.Fail);
}
var deviceInfo = await deviceAppService.FindByDeviceAddressAsync(messageBody.DeviceAddress);
//将指令存储Kafka的OneNET主题中
if (deviceInfo.IoTPlatform == IoTPlatformTypeEnum.OneNET)
{
await _producerService.ProduceAsync(KafkaTopicConsts.OneNETCommandIssuedEventName, $"{GuidGenerator.Create()}", input); await _producerService.ProduceAsync(KafkaTopicConsts.OneNETCommandIssuedEventName, $"{GuidGenerator.Create()}", input);
}
else if (deviceInfo.IoTPlatform == IoTPlatformTypeEnum.CTWing)
{
await _producerService.ProduceAsync(KafkaTopicConsts.CTWingAepCommandIssuedEventName, $"{GuidGenerator.Create()}", input);
}
else
{
return HttpDataResultExtensions.Failed("指令处理失败,当前设备平台类型异常",-104);
}
return HttpDataResultExtensions.Success("指令下发Kafka成功"); return HttpDataResultExtensions.Success("指令下发Kafka成功");
} }

View File

@ -1,21 +1,19 @@
using JiShe.IoT.DeviceAggregation.Dto; using JiShe.IoT.DeviceAggregation.Dto;
using JiShe.IoT.OneNETAggregation.Dto;
using JiShe.ServicePro; using JiShe.ServicePro;
using JiShe.ServicePro.Core; using JiShe.ServicePro.Core;
using JiShe.ServicePro.DeviceManagement.DeviceInfos; using JiShe.ServicePro.DeviceManagement.DeviceInfos;
using JiShe.ServicePro.DeviceManagement.DeviceInfos.Dto; using JiShe.ServicePro.DeviceManagement.DeviceInfos.Dto;
using JiShe.ServicePro.DeviceManagement.Permissions; using JiShe.ServicePro.DeviceManagement.Permissions;
using JiShe.ServicePro.Dto;
using JiShe.ServicePro.Enums;
using JiShe.ServicePro.FreeRedisProvider; using JiShe.ServicePro.FreeRedisProvider;
using JiShe.ServicePro.Kafka.Consts;
using JiShe.ServicePro.Kafka.Producer;
using JiShe.ServicePro.OneNET.Provider.OpenApiModels.Devices;
using JiShe.ServicePro.OneNETManagement.OneNETDevices; using JiShe.ServicePro.OneNETManagement.OneNETDevices;
using JiShe.ServicePro.OneNETManagement.OneNETProducts; using JiShe.ServicePro.OneNETManagement.OneNETProducts;
using Mapster; using Mapster;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO.Pipelines;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp; using Volo.Abp;
namespace JiShe.IoT.DeviceAggregation namespace JiShe.IoT.DeviceAggregation
@ -26,7 +24,8 @@ namespace JiShe.IoT.DeviceAggregation
/// <param name="logger"></param> /// <param name="logger"></param>
/// <param name="deviceAppService">设备服务</param> /// <param name="deviceAppService">设备服务</param>
/// <param name="oneNETDeviceService">OneNET设备服务</param> /// <param name="oneNETDeviceService">OneNET设备服务</param>
public class DeviceAggregationService(ILogger<DeviceAggregationService> logger, IDeviceAppService deviceAppService, IOneNETDeviceService oneNETDeviceService) : IoTAppService, IDeviceAggregationService /// <param name="producerService">KafKa生产服务</param>
public class DeviceAggregationService(ILogger<DeviceAggregationService> logger, IDeviceAppService deviceAppService, IOneNETDeviceService oneNETDeviceService, IKafkaProducerService producerService) : IoTAppService, IDeviceAggregationService
{ {
/// <summary> /// <summary>
/// 管理后台创建设备信息 /// 管理后台创建设备信息
@ -38,7 +37,7 @@ namespace JiShe.IoT.DeviceAggregation
{ {
try try
{ {
input.DeviceSourceTypeEnum = ServicePro.Enums.DeviceSourceTypeEnum.AdminSystem;
if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.CTWing) if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.CTWing)
{ {
return await CTWingDeviceCreateAsync(input); return await CTWingDeviceCreateAsync(input);
@ -58,6 +57,46 @@ namespace JiShe.IoT.DeviceAggregation
} }
/// <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>
/// 车间创建设备信息 /// 车间创建设备信息
/// </summary> /// </summary>
@ -67,6 +106,7 @@ namespace JiShe.IoT.DeviceAggregation
{ {
try try
{ {
input.DeviceSourceTypeEnum = DeviceSourceTypeEnum.Workshop;
if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.CTWing) if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.CTWing)
{ {
@ -88,64 +128,36 @@ namespace JiShe.IoT.DeviceAggregation
} }
/// <summary> /// <summary>
/// OneNET设备创建 /// 车间批量创建设备信息
/// </summary> /// </summary>
/// <param name="input"></param> /// <param name="input"></param>
/// <returns></returns> /// <returns></returns>
public async Task<bool> OneNETDeviceCreateAsync(CreateDeviceAggregationInput input) public async Task<bool> BatchCreateDeviceWorkshopAsync(BatchCreateDeviceAggregationInput input)
{ {
try try
{ {
CreateDeviceInput createDeviceInput = input.Adapt<CreateDeviceInput>(); if (input.AddressList == null || input.AddressList.Count <= 0)
var productInfo = await FreeSqlDbContext.Instance.Select<OneNETProductInfos>()
.Where(e => e.IoTPlatformProductId == input.IoTPlatformProductId)//此处不需要过滤产品状态,方便测试产品配置信息是否准确,避免跟车间生产搞混
.FirstAsync();
if (productInfo == null)
{ {
throw new UserFriendlyException($"创建设备失败,未找到对应的产品配置信息。"); throw new UserFriendlyException($"批量创建设备失败,设备信息不能为空。");
} }
//检查设备信息是不是已经存在 if (input.AddressList.Count > 100)
var existsDeviceInfo = await deviceAppService.FindDeviceInfosAsync(input.DeviceAddress, createDeviceInput.IoTPlatform);
if (existsDeviceInfo != null)
{ {
throw new UserFriendlyException($"创建设备失败,当前平台设备信息已经存在。"); throw new UserFriendlyException($"批量创建设备失败设备信息不能超过100个。");
} }
createDeviceInput.DeviceName = input.DeviceAddress; input.DeviceSourceTypeEnum = DeviceSourceTypeEnum.Workshop;
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 (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.CTWing)
if (insertResult == null)
{ {
logger.LogError($"{nameof(CreateDeviceForApiAsync)} 添加设备信息失败:{input.Serialize()}"); return await CTWingDeviceBatchCreateAsync(input);
return false; }
else if (input.IoTPlatform == ServicePro.Enums.IoTPlatformTypeEnum.OneNET)
{
return await OneNETDeviceBatchCreateAsync(input);
} }
//推送至OneNET平台 throw new UserFriendlyException($"不支持的物联网平台");
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) catch (Exception)
{ {
@ -154,16 +166,6 @@ namespace JiShe.IoT.DeviceAggregation
} }
} }
/// <summary>
/// CTWing 设备创建
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public async Task<bool> CTWingDeviceCreateAsync(CreateDeviceAggregationInput input)
{
throw new UserFriendlyException($"CTWing 设备创建失败,功能未实现。");
}
/// <summary> /// <summary>
/// 删除设备信息 /// 删除设备信息
/// </summary> /// </summary>
@ -173,8 +175,24 @@ namespace JiShe.IoT.DeviceAggregation
[Authorize(DeviceManagementPermissions.DeviceInfoManagement.Delete)] [Authorize(DeviceManagementPermissions.DeviceInfoManagement.Delete)]
public async Task<bool> DeleteAsync(IdInput input) public async Task<bool> DeleteAsync(IdInput input)
{ {
return await deviceAppService.DeleteAsync(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> /// <summary>
@ -223,16 +241,71 @@ namespace JiShe.IoT.DeviceAggregation
} }
/// <summary> /// <summary>
/// 重新推送设备信息到CTWing物联网平台 /// 更新设备信息并处理缓存
/// </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;
RedisProvider.Instance.HSet<DeviceCacheInfos>(RedisConst.CacheAllDeviceInfoHashKey, input.DeviceAddress, deviceCacheInfos);
return input.Adapt<DeviceManagementInfoDto>();
}
/// <summary>
/// 发送设备指令信息
/// </summary> /// </summary>
/// <param name="input"></param> /// <param name="input"></param>
/// <returns></returns> /// <returns></returns>
/// <exception cref="UserFriendlyException"></exception> public async Task<bool> DeviceCommandForApiAsync(DeviceCommandForApiInput input)
public async Task<DeviceManagementInfoDto> RepushDeviceInfoToCTWing(DeviceManagementInfoDto input)
{ {
try try
{ {
throw new UserFriendlyException($"推送失败CTWing暂未实现。"); var deviceInfo = await deviceAppService.FindByDeviceAddressAsync(input.DeviceAddress);
//将指令存储Kafka的OneNET主题中
var commandRequest = new OpenApiRequest()
{
Message = new ReceiveCommandInfoDto()
{
DeviceAddress = input.DeviceAddress,
Commands = input.CommandContent.Deserialize<Dictionary<string,object>>(),
DeviceType = DeviceTypeEnum.Focus,//todo 设备类型 需要跟设备统一什么情况下知道具体设备类型
SourceType = DeviceTelemetrySourceTypeEnum.AdminSystem,
}.Serialize(),
};
if (deviceInfo.IoTPlatform == IoTPlatformTypeEnum.OneNET)
{
await producerService.ProduceAsync(KafkaTopicConsts.OneNETCommandIssuedEventName, $"{GuidGenerator.Create()}", commandRequest);
return true;
}
else if (deviceInfo.IoTPlatform == IoTPlatformTypeEnum.CTWing)
{
await producerService.ProduceAsync(KafkaTopicConsts.CTWingAepCommandIssuedEventName, $"{GuidGenerator.Create()}", commandRequest);
return true;
}
else
{
throw new UserFriendlyException($"创建设备失败,未找到对应的产品配置信息。");
}
} }
catch (Exception) catch (Exception)
{ {
@ -241,6 +314,148 @@ namespace JiShe.IoT.DeviceAggregation
} }
} }
#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.IoTPlatformAccountId = productInfo.OneNETAccountId;
createDeviceInput.IoTPlatformDeviceOpenInfo = $"{input.IoTPlatformProductId}{item}";
createDeviceInput.PlatformPassword = productInfo.ProductAccesskey;
createDeviceInput.IoTPlatformProductName = productInfo.ProductName;
createDeviceInput.AccountPhoneNumber = productInfo.AccountPhoneNumber;
}
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 = 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> /// <summary>
/// 重新推送设备信息到OneNET物联网平台 /// 重新推送设备信息到OneNET物联网平台
/// </summary> /// </summary>
@ -288,33 +503,124 @@ namespace JiShe.IoT.DeviceAggregation
} }
/// <summary> /// <summary>
/// 更新设备信息并处理缓存 /// 删除OneNET平台设备
/// </summary> /// </summary>
/// <param name="input"></param> /// <param name="input"></param>
/// <param name="pushResult"></param>
/// <returns></returns> /// <returns></returns>
/// <exception cref="UserFriendlyException"></exception> /// <exception cref="UserFriendlyException"></exception>
private async Task<DeviceManagementInfoDto> DeviceUpdateHandler(DeviceManagementInfoDto input, HttpDataResult pushResult) public async Task<bool> DeleteDeviceInfoToOneNET(DeviceManagementInfoDto input)
{ {
UpdateDeviceInput updateDeviceInput = input.Adapt<UpdateDeviceInput>(); try
updateDeviceInput.IoTPlatformResponse = pushResult.Serialize();
updateDeviceInput.IsPlatformPushSuccess = true;
var updateResult = await deviceAppService.UpdateAsync(updateDeviceInput);
if (updateResult == null)
{ {
logger.LogError($"{nameof(CreateDeviceForApiAsync)} 更新设备信息失败:{input.Serialize()}"); var productInfo = await FreeSqlDbContext.Instance.Select<OneNETProductInfos>()
throw new UserFriendlyException($"推送结果更新失败。"); .Where(e => e.IoTPlatformProductId == input.IoTPlatformProductId)
.FirstAsync();
if (productInfo == null)
{
throw new UserFriendlyException($"删除失败,未找到对应的产品配置信息。");
} }
//设备数据缓存到Redis
DeviceCacheInfos deviceCacheInfos = input.Adapt<DeviceCacheInfos>();
deviceCacheInfos.IoTPlatformResponse = null;
deviceCacheInfos.PlatformPassword = null;
RedisProvider.Instance.HSet<DeviceCacheInfos>(RedisConst.CacheAllDeviceInfoHashKey, input.DeviceAddress, deviceCacheInfos); //删除OneNET平台设备信息
var deleteResult = await oneNETDeviceService.DeleteDeviceInfoAsync(new DeleteDeviceInfoInput()
{
DeviceName = input.IoTPlatformDeviceOpenInfo,
ProductId = productInfo.IoTPlatformProductId,
OneNETAccountId = productInfo.OneNETAccountId,
Description = input.DeviceAddress,
});
return input.Adapt<DeviceManagementInfoDto>(); 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;
} }
} }
#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
}
} }

View File

@ -13,7 +13,7 @@ using Volo.Abp.EntityFrameworkCore;
namespace JiShe.IoT.Migrations namespace JiShe.IoT.Migrations
{ {
[DbContext(typeof(IoTDbContext))] [DbContext(typeof(IoTDbContext))]
[Migration("20250731021938_InitialCreate")] [Migration("20250804031635_InitialCreate")]
partial class InitialCreate partial class InitialCreate
{ {
/// <inheritdoc /> /// <inheritdoc />
@ -599,6 +599,10 @@ namespace JiShe.IoT.Migrations
.HasColumnType("int") .HasColumnType("int")
.HasComment("设备在线状态"); .HasComment("设备在线状态");
b.Property<int?>("DeviceSourceTypeEnum")
.HasColumnType("int")
.HasComment("设备来源类型");
b.Property<string>("ExtraProperties") b.Property<string>("ExtraProperties")
.HasColumnType("longtext") .HasColumnType("longtext")
.HasColumnName("ExtraProperties") .HasColumnName("ExtraProperties")

View File

@ -886,6 +886,7 @@ namespace JiShe.IoT.Migrations
DeviceOnlineStatus = table.Column<int>(type: "int", nullable: true, comment: "设备在线状态"), DeviceOnlineStatus = table.Column<int>(type: "int", nullable: true, comment: "设备在线状态"),
LastOnlineTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: "最后在线时间"), LastOnlineTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: "最后在线时间"),
LastOfflineTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: "最后离线时间"), LastOfflineTime = table.Column<DateTime>(type: "datetime(6)", nullable: true, comment: "最后离线时间"),
DeviceSourceTypeEnum = table.Column<int>(type: "int", nullable: true, comment: "设备来源类型"),
ConcurrencyStamp = table.Column<string>(type: "varchar(40)", maxLength: 40, nullable: false) ConcurrencyStamp = table.Column<string>(type: "varchar(40)", maxLength: 40, nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"), .Annotation("MySql:CharSet", "utf8mb4"),
CreationTime = table.Column<DateTime>(type: "datetime(6)", nullable: false), CreationTime = table.Column<DateTime>(type: "datetime(6)", nullable: false),

View File

@ -596,6 +596,10 @@ namespace JiShe.IoT.Migrations
.HasColumnType("int") .HasColumnType("int")
.HasComment("设备在线状态"); .HasComment("设备在线状态");
b.Property<int?>("DeviceSourceTypeEnum")
.HasColumnType("int")
.HasComment("设备来源类型");
b.Property<string>("ExtraProperties") b.Property<string>("ExtraProperties")
.HasColumnType("longtext") .HasColumnType("longtext")
.HasColumnName("ExtraProperties") .HasColumnName("ExtraProperties")

View File

@ -29,6 +29,18 @@ namespace JiShe.IoT.Controllers
return await _deviceAggregationService.CreateDeviceForApiAsync(input); return await _deviceAggregationService.CreateDeviceForApiAsync(input);
} }
/// <summary>
/// 批量创建设备信息
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
[HttpPost(nameof(BatchCreateAsync))]
[SwaggerOperation(summary: "批量创建设备信息", Tags = new[] { "AggregationDevice" })]
public async Task<bool> BatchCreateAsync(BatchCreateDeviceAggregationInput input)
{
return await _deviceAggregationService.BatchCreateDeviceForApiAsync(input);
}
/// <summary> /// <summary>
/// 删除设备信息 /// 删除设备信息
/// </summary> /// </summary>