完善子设备表设计以及业务系统设备添加接口和获取或分配计量点索引

This commit is contained in:
ChenYi 2026-01-19 17:29:57 +08:00
parent 6e98f5d4a9
commit 38cf8f6f1a
2 changed files with 128 additions and 65 deletions

View File

@ -31,6 +31,11 @@ namespace JiShe.IoT.BusinessSystemAggregation
ServerApplicationOptions serverOptions = options.Value; ServerApplicationOptions serverOptions = options.Value;
IoTDBOptions ioTDBOptions = _ioTDBOptions.Value; IoTDBOptions ioTDBOptions = _ioTDBOptions.Value;
private const string LUA_SCRIPT = @"
local hashKey = KEYS[1]
local fieldKeys = ARGV
return redis.call('HMGET', hashKey, unpack(fieldKeys))";
/// <summary> /// <summary>
/// 接收业务系统指令信息 /// 接收业务系统指令信息
/// </summary> /// </summary>
@ -118,9 +123,14 @@ namespace JiShe.IoT.BusinessSystemAggregation
return HttpDataResultExtensions.Success("指令下发成功"); return HttpDataResultExtensions.Success("指令下发成功");
} }
catch (UserFriendlyException)
{
throw; // 重新抛出用户友好异常
}
catch (Exception ex) catch (Exception ex)
{ {
return HttpDataResultExtensions.Failed($"指令处理失败,发送异常:{ex.Message}", -106); _logger.LogError(ex, "接收业务系统指令信息时发生异常");
return HttpDataResultExtensions.Failed("指令处理失败,发送异常", -106);
} }
} }
@ -147,16 +157,19 @@ namespace JiShe.IoT.BusinessSystemAggregation
return HttpDataResultExtensions.Failed<List<IoTDBDynamicObject>>(null, "设备地址不能为空", -103); return HttpDataResultExtensions.Failed<List<IoTDBDynamicObject>>(null, "设备地址不能为空", -103);
} }
// Lua脚本 // 验证设备地址格式,防止注入攻击
string luaScript = @" foreach (var deviceAddress in messageBody.DeviceAddresses)
local hashKey = KEYS[1] {
local fieldKeys = ARGV if (!IsValidDeviceAddress(deviceAddress))
return redis.call('HMGET', hashKey, unpack(fieldKeys))"; {
return HttpDataResultExtensions.Failed<List<IoTDBDynamicObject>>(null, $"设备地址格式不正确: {deviceAddress}", -107);
}
}
//执行脚本 //执行脚本
var result = await FreeRedisProvider.Instance.EvalAsync var result = await FreeRedisProvider.Instance.EvalAsync
( (
luaScript, LUA_SCRIPT,
new[] { RedisConst.CacheAllDeviceInfoHashKey }, new[] { RedisConst.CacheAllDeviceInfoHashKey },
messageBody.DeviceAddresses.ToArray() messageBody.DeviceAddresses.ToArray()
); );
@ -167,16 +180,24 @@ namespace JiShe.IoT.BusinessSystemAggregation
if (result is object[] values) if (result is object[] values)
{ {
foreach (var value in values) foreach (var value in values)
{
if (value != null)
{ {
var tempFocusInfo = ServiceProJsonSerializer.Deserialize<DeviceCacheInfos>(value as string); var tempFocusInfo = ServiceProJsonSerializer.Deserialize<DeviceCacheInfos>(value as string);
deviceCacheInfos.Add(tempFocusInfo); deviceCacheInfos.Add(tempFocusInfo);
} }
else
{
deviceCacheInfos.Add(null); // 添加空值以保持索引对应
}
}
} }
List<IoTDBDynamicObject> queryResult = new List<IoTDBDynamicObject>(); List<IoTDBDynamicObject> queryResult = new List<IoTDBDynamicObject>();
foreach (var deviceAddress in messageBody.DeviceAddresses) for (int i = 0; i < messageBody.DeviceAddresses.Count; i++)
{ {
var deviceCacheInfo = deviceCacheInfos.FirstOrDefault(x => x.DeviceAddress == deviceAddress); var deviceAddress = messageBody.DeviceAddresses[i];
var deviceCacheInfo = deviceCacheInfos.Count > i ? deviceCacheInfos[i] : null;
if (deviceCacheInfo == null) if (deviceCacheInfo == null)
{ {
@ -207,8 +228,8 @@ namespace JiShe.IoT.BusinessSystemAggregation
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "批量查询设备数据时发生异常");
return HttpDataResultExtensions.Failed<List<IoTDBDynamicObject>>(null, $"查询设备数据失败,发送异常:{ex.Message}", -106); return HttpDataResultExtensions.Failed<List<IoTDBDynamicObject>>(null, "查询设备数据失败", -106);
} }
} }
@ -235,16 +256,16 @@ namespace JiShe.IoT.BusinessSystemAggregation
return HttpDataResultExtensions.Failed<List<IoTDBDynamicObject>>(null, "设备地址不能为空", -103); return HttpDataResultExtensions.Failed<List<IoTDBDynamicObject>>(null, "设备地址不能为空", -103);
} }
// Lua脚本 // 验证设备地址格式,防止注入攻击
string luaScript = @" if (!IsValidDeviceAddress(messageBody.DeviceAddress))
local hashKey = KEYS[1] {
local fieldKeys = ARGV return HttpDataResultExtensions.Failed<List<IoTDBDynamicObject>>(null, $"设备地址格式不正确: {messageBody.DeviceAddress}", -107);
return redis.call('HMGET', hashKey, unpack(fieldKeys))"; }
//执行脚本 //执行脚本
var result = await FreeRedisProvider.Instance.EvalAsync var result = await FreeRedisProvider.Instance.EvalAsync
( (
luaScript, LUA_SCRIPT,
new[] { RedisConst.CacheAllDeviceInfoHashKey }, new[] { RedisConst.CacheAllDeviceInfoHashKey },
new List<string>() { messageBody.DeviceAddress }.ToArray() new List<string>() { messageBody.DeviceAddress }.ToArray()
); );
@ -255,18 +276,26 @@ namespace JiShe.IoT.BusinessSystemAggregation
if (result is object[] values) if (result is object[] values)
{ {
foreach (var value in values) foreach (var value in values)
{
if (value != null)
{ {
var tempFocusInfo = ServiceProJsonSerializer.Deserialize<DeviceCacheInfos>(value as string); var tempFocusInfo = ServiceProJsonSerializer.Deserialize<DeviceCacheInfos>(value as string);
deviceCacheInfos.Add(tempFocusInfo); deviceCacheInfos.Add(tempFocusInfo);
} }
else
{
deviceCacheInfos.Add(null);
}
}
} }
List<IoTDBDynamicObject> queryResult = new List<IoTDBDynamicObject>(); List<IoTDBDynamicObject> queryResult = new List<IoTDBDynamicObject>();
var deviceCacheInfo = deviceCacheInfos.FirstOrDefault(x => x.DeviceAddress == messageBody.DeviceAddress); var deviceCacheInfo = deviceCacheInfos.FirstOrDefault();
if (deviceCacheInfo == null) if (deviceCacheInfo == null)
{ {
_logger.LogError($"{nameof(BatchQueryDeviceDataInfoAsync)} 业务系统单个查询设备数据,设备地址:{messageBody.DeviceAddress}未找到设备地址缓存信息,消息体为:{input.Serialize()}"); _logger.LogError($"{nameof(QueryDeviceDataInfoAsync)} 业务系统单个查询设备数据,设备地址:{messageBody.DeviceAddress}未找到设备地址缓存信息,消息体为:{input.Serialize()}");
return HttpDataResultExtensions.Failed<List<IoTDBDynamicObject>>(null, "设备信息不存在", -108);
} }
var pageResult = await treeModelService.OpenRequestDeviceDataInfoPageAsync(new DeviceTreeModelDataInfoInput() var pageResult = await treeModelService.OpenRequestDeviceDataInfoPageAsync(new DeviceTreeModelDataInfoInput()
@ -292,8 +321,8 @@ namespace JiShe.IoT.BusinessSystemAggregation
} }
catch (Exception ex) catch (Exception ex)
{ {
_logger.LogError(ex, "查询单个设备数据时发生异常");
return HttpDataResultExtensions.Failed<List<IoTDBDynamicObject>>(null, $"查询设备数据失败,发送异常:{ex.Message}", -106); return HttpDataResultExtensions.Failed<List<IoTDBDynamicObject>>(null, "查询设备数据失败", -106);
} }
} }
@ -334,8 +363,26 @@ namespace JiShe.IoT.BusinessSystemAggregation
} }
catch (Exception ex) catch (Exception ex)
{ {
return HttpDataResultExtensions.Failed($"查询设备数据失败,发送异常:{ex.Message}", -106); _logger.LogError(ex, "批量新增设备数据时发生异常");
} return HttpDataResultExtensions.Failed("新增设备失败", -106);
}
}
/// <summary>
/// 验证设备地址格式是否合法
/// </summary>
/// <param name="deviceAddress">设备地址</param>
/// <returns>是否合法</returns>
private bool IsValidDeviceAddress(string deviceAddress)
{
if (string.IsNullOrWhiteSpace(deviceAddress))
return false;
// 可根据实际业务规则调整验证逻辑
// 这里简单检查是否包含非法字符
return !deviceAddress.Contains("..") &&
!deviceAddress.Contains("*") &&
!deviceAddress.Contains("~");
} }
} }
} }

View File

@ -276,8 +276,10 @@ namespace JiShe.IoT.DeviceAggregation
UpdateDeviceInput updateDeviceInput = input.Adapt<UpdateDeviceInput>(); UpdateDeviceInput updateDeviceInput = input.Adapt<UpdateDeviceInput>();
updateDeviceInput.IoTPlatformResponse = pushResult.Serialize(); updateDeviceInput.IoTPlatformResponse = pushResult.Serialize();
updateDeviceInput.IsPlatformPushSuccess = true; updateDeviceInput.IsPlatformPushSuccess = true;
if (!string.IsNullOrWhiteSpace(updateDeviceInput.PlatformPassword))
{
updateDeviceInput.PlatformPassword = platformPassword; updateDeviceInput.PlatformPassword = platformPassword;
}
var updateResult = await deviceAppService.UpdateAsync(updateDeviceInput); var updateResult = await deviceAppService.UpdateAsync(updateDeviceInput);
if (updateResult == null) if (updateResult == null)
@ -799,28 +801,29 @@ namespace JiShe.IoT.DeviceAggregation
IoTPlatformProductId = input.IoTPlatformProductId, IoTPlatformProductId = input.IoTPlatformProductId,
}); });
foreach (var item in input.AddressList) foreach (var item in input.DeviceInfos)
{ {
if (checkDevicesInfos != null) if (checkDevicesInfos != null)
{ {
if (checkDevicesInfos.Any(e => e.DeviceAddress == item))
var checkDevices = checkDevicesInfos.Where(e => e.DeviceAddress == item.DeviceAddress).FirstOrDefault();
if (checkDevices != null && checkDevices.IsPlatformPushSuccess)
{ {
logger.LogError($"{nameof(OneNETDeviceBatchCreateAsync)} 平台{input.IoTPlatform} 产品 {input.IoTPlatformProductId} 下设备信息已存在:{item}"); logger.LogError($"{nameof(OneNETDeviceBatchCreateAsync)} 平台{input.IoTPlatform} 产品 {input.IoTPlatformProductId} 下设备信息已存在:{item.DeviceAddress}");
continue; continue;
} }
} }
CreateDeviceInput createDeviceInput = input.Adapt<CreateDeviceInput>(); CreateDeviceInput createDeviceInput = input.Adapt<CreateDeviceInput>();
createDeviceInput.DeviceName = item; createDeviceInput.DeviceName = item.DeviceAddress;
createDeviceInput.DeviceAddress = item; createDeviceInput.DeviceAddress = item.DeviceAddress;
createDeviceInput.IoTPlatformAccountId = productInfo.OneNETAccountId; createDeviceInput.IoTPlatformAccountId = productInfo.OneNETAccountId;
createDeviceInput.IoTPlatformDeviceOpenInfo = $"{input.IoTPlatformProductId}{item}"; createDeviceInput.IoTPlatformDeviceOpenInfo = $"{input.IoTPlatformProductId}{item.DeviceAddress}";
createDeviceInput.PlatformPassword = productInfo.ProductAccesskey; createDeviceInput.PlatformPassword = productInfo.ProductAccesskey;
createDeviceInput.IoTPlatformProductName = productInfo.ProductName; createDeviceInput.IoTPlatformProductName = productInfo.ProductName;
createDeviceInput.AccountPhoneNumber = productInfo.AccountPhoneNumber; createDeviceInput.AccountPhoneNumber = productInfo.AccountPhoneNumber;
createDeviceInput.DeviceSourceType = input.DeviceSourceType.Value;
createDeviceInput.DeviceType = input.DeviceType.Value;
if (input.DeviceSourceType.HasValue) if (input.DeviceSourceType.HasValue)
{ {
@ -832,18 +835,26 @@ namespace JiShe.IoT.DeviceAggregation
createDeviceInput.DeviceType = input.DeviceType.Value; createDeviceInput.DeviceType = input.DeviceType.Value;
} }
if(item.BusinessSystemDeviceDataId.HasValue)
{
createDeviceInput.BusinessSystemDeviceDataId = item.BusinessSystemDeviceDataId.Value;
}
batchCreateDeviceInput.DeviceInputs.Add(createDeviceInput); batchCreateDeviceInput.DeviceInputs.Add(createDeviceInput);
} }
if(batchCreateDeviceInput.DeviceInputs != null || batchCreateDeviceInput.DeviceInputs.Count > 0)
{
var insertResult = await deviceAppService.BatchCreateAsync(batchCreateDeviceInput); var insertResult = await deviceAppService.BatchCreateAsync(batchCreateDeviceInput);
if (insertResult == null) if (insertResult == null)
{ {
logger.LogError($"{nameof(OneNETDeviceBatchCreateAsync)} OneNET设备批量创建添加设备信息失败{input.Serialize()}"); logger.LogError($"{nameof(OneNETDeviceBatchCreateAsync)} OneNET设备批量创建添加设备信息失败{input.Serialize()}");
return false; return false;
} }
//网关或者直连设备 推送至OneNET平台
//推送至OneNET平台
var oneNETBatchCreateDeviceInfoInput = new BatchCreateDeviceInfoInput() var oneNETBatchCreateDeviceInfoInput = new BatchCreateDeviceInfoInput()
{ {
ProductId = productInfo.IoTPlatformProductId, ProductId = productInfo.IoTPlatformProductId,
@ -870,6 +881,11 @@ namespace JiShe.IoT.DeviceAggregation
await DeviceUpdateHandler(item, HttpDataResultExtensions.Success(successEntity), successEntity.SecurityKey); await DeviceUpdateHandler(item, HttpDataResultExtensions.Success(successEntity), successEntity.SecurityKey);
} }
} }
}
//处理子设备
return true; return true;
} }