修复: Owl取流JSON反序列化(JsonOpts+PascalCase属性)+前端字段兼容+规则引擎SqlSugar语法

This commit is contained in:
2026-06-08 10:50:14 +08:00
parent 8a6776eac9
commit 1fb746c548
17 changed files with 701 additions and 266 deletions
@@ -87,6 +87,41 @@ namespace VolPro.Entity.DomainModels
[Editable(true)]
public int? RuleID { get; set; }
/// <summary>
///数值型恢复阈值(如>28℃触发,≤26℃恢复)
/// </summary>
[Display(Name ="数值型恢复阈值(如>28℃触发,≤26℃恢复)")]
[DisplayFormat(DataFormatString="18,2")]
[Column(TypeName="decimal")]
[Editable(true)]
public decimal? RecoveryThreshold_Numeric { get; set; }
/// <summary>
///开关型恢复阈值(如开触发,关恢复)
/// </summary>
[Display(Name ="开关型恢复阈值(如开触发,关恢复)")]
[MaxLength(50)]
[Column(TypeName="nvarchar(50)")]
[Editable(true)]
public string RecoveryThreshold_Switch { get; set; }
/// <summary>
///该条件上次触发的时间
/// </summary>
[Display(Name ="该条件上次触发的时间")]
[Column(TypeName="datetime")]
[Editable(true)]
public DateTime? LastTriggered { get; set; }
/// <summary>
///该条件上次触发时的实际值
/// </summary>
[Display(Name ="该条件上次触发时的实际值")]
[DisplayFormat(DataFormatString="18,2")]
[Column(TypeName="decimal")]
[Editable(true)]
public decimal? LastTriggerValue { get; set; }
}
}
@@ -0,0 +1,47 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace VolPro.WebApi.Controllers.Warehouse;
/// <summary>
/// 文件服务。对外暴露 VolPro 文件系统中的静态文件(截图、导出等)。
/// 不走 VolPro JWT 认证体系——网关 B 组接口直接调用。
/// </summary>
[ApiController]
[AllowAnonymous]
public class FileServiceController : Controller
{
/// <summary>
/// 获取截图文件。
/// 文件存放于 VolPro.WebApi/Download/Screenshots/ 目录。
/// </summary>
/// <param name="filename">文件名(含扩展名,如 abc.png</param>
[HttpGet("api/gateway/screenshots/{filename}")]
public IActionResult GetScreenshot(string filename)
{
// 安全检查:禁止路径穿越(.., /, \)
if (string.IsNullOrWhiteSpace(filename) ||
filename.Contains("..") ||
filename.Contains('/') ||
filename.Contains('\\'))
return BadRequest(new { error = "非法文件名" });
var folder = Path.Combine(AppContext.BaseDirectory, "Download", "Screenshots");
var filePath = Path.Combine(folder, filename);
if (!System.IO.File.Exists(filePath))
return NotFound(new { error = "文件不存在" });
var ext = Path.GetExtension(filename).ToLowerInvariant();
var contentType = ext switch
{
".png" => "image/png",
".jpg" or ".jpeg" => "image/jpeg",
".gif" => "image/gif",
_ => "application/octet-stream"
};
return PhysicalFile(filePath, contentType);
}
}
@@ -0,0 +1,7 @@
中文提示 : 检测到你没有开启文件,AllowLoadLocalInfile=true加到自符串上,已自动执行 SET GLOBAL local_infile=1 在试一次
English Message : Loading local data is disabled; this must be enabled on both the client and server sides at SqlSugar.Check.ExceptionEasy(String enMessage, String cnMessage)
at SqlSugar.MySqlFastBuilder.ExecuteBulkCopyAsync(DataTable dt)
at SqlSugar.FastestProvider`1._BulkCopy(List`1 datas)
at SqlSugar.FastestProvider`1.BulkCopyAsync(List`1 datas)
at SqlSugar.FastestProvider`1.BulkCopy(List`1 datas)
at VolPro.Core.Services.Logger.Start() in D:\Code\SecMPS\api_sqlsugar\VolPro.Core\Services\Logger.cs:line 194SqlSugar
@@ -21,6 +21,7 @@ using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text.Json;
using Microsoft.Extensions.Logging;
namespace Warehouse.Services
{
@@ -31,16 +32,19 @@ namespace Warehouse.Services
{
private readonly IHttpContextAccessor _httpContextAccessor;
private readonly Igateway_nodesRepository _repository;
private readonly ILogger<gateway_nodesService> _logger;
[ActivatorUtilitiesConstructor]
public gateway_nodesService(
Igateway_nodesRepository dbRepository,
IHttpContextAccessor httpContextAccessor
IHttpContextAccessor httpContextAccessor,
ILogger<gateway_nodesService> logger
)
: base(dbRepository)
{
_httpContextAccessor = httpContextAccessor;
_repository = dbRepository;
_logger = logger;
}
/// <summary>
@@ -51,39 +55,53 @@ namespace Warehouse.Services
[Obsolete("由 A1 API Controller 自动调用,不建议手动调用")]
public async Task<gateway_nodes> RegisterNodeAsync(string nodeCode, string token, string adapterTypes, string baseUrl)
{
var existingList = await _repository.FindAsIQueryable(x => x.NodeCode == nodeCode).ToListAsync();
var existing = existingList.FirstOrDefault();
gateway_nodes entity;
if (existing != null)
_logger.LogInformation("[A1] 网关注册: NodeCode={Node}, Adapters={Adapters}", nodeCode, adapterTypes);
try
{
if (existing.NodeToken != token)
throw new UnauthorizedAccessException("NodeToken 不匹配");
var existingList = await _repository.FindAsIQueryable(x => x.NodeCode == nodeCode).ToListAsync();
var existing = existingList.FirstOrDefault();
existing.AdapterTypes = adapterTypes;
existing.BaseUrl = baseUrl;
existing.IsOnline = "在线";
existing.LastHeartbeat = DateTime.Now;
_repository.DbContext.Updateable(existing).ExecuteCommand();
entity = existing;
}
else
{
entity = new gateway_nodes
gateway_nodes entity;
if (existing != null)
{
NodeCode = nodeCode,
NodeName = nodeCode,
NodeToken = token,
AdapterTypes = adapterTypes,
BaseUrl = baseUrl,
IsOnline = "在线",
Enable = "启用",
LastHeartbeat = DateTime.Now,
CreateDate = DateTime.Now
};
_repository.DbContext.Insertable(entity).ExecuteCommand();
if (existing.NodeToken != token)
{
_logger.LogWarning("[A1] 注册失败: NodeCode={Node} Token不匹配", nodeCode);
throw new UnauthorizedAccessException("NodeToken 不匹配");
}
existing.AdapterTypes = adapterTypes;
existing.BaseUrl = baseUrl;
existing.IsOnline = "在线";
existing.LastHeartbeat = DateTime.Now;
_repository.DbContext.Updateable(existing).ExecuteCommand();
entity = existing;
_logger.LogInformation("[A1] 网关注册(更新): NodeId={Id}, NodeCode={Node}", entity.NodeId, nodeCode);
}
else
{
entity = new gateway_nodes
{
NodeCode = nodeCode,
NodeName = nodeCode,
NodeToken = token,
AdapterTypes = adapterTypes,
BaseUrl = baseUrl,
IsOnline = "在线",
Enable = "启用",
LastHeartbeat = DateTime.Now,
CreateDate = DateTime.Now
};
_repository.DbContext.Insertable(entity).ExecuteCommand();
_logger.LogInformation("[A1] 网关注册(新增): NodeId={Id}, NodeCode={Node}", entity.NodeId, nodeCode);
}
return entity;
}
catch (Exception ex)
{
_logger.LogError(ex, "[A1] 注册异常: NodeCode={Node}", nodeCode);
throw;
}
return entity;
}
/// <summary>
@@ -92,14 +110,27 @@ namespace Warehouse.Services
[Obsolete("由 A2 API Controller 自动调用,不建议手动调用")]
public async Task UpdateHeartbeatAsync(string nodeCode, string token)
{
var entityList = await _repository.FindAsIQueryable(x => x.NodeCode == nodeCode && x.NodeToken == token).ToListAsync();
var entity = entityList.FirstOrDefault();
if (entity == null)
throw new UnauthorizedAccessException("认证失败:NodeCode 或 Token 无效");
try
{
var entityList = await _repository.FindAsIQueryable(x => x.NodeCode == nodeCode && x.NodeToken == token).ToListAsync();
var entity = entityList.FirstOrDefault();
if (entity == null)
{
_logger.LogWarning("[A2] 心跳认证失败: NodeCode={Node}", nodeCode);
throw new UnauthorizedAccessException("认证失败:NodeCode 或 Token 无效");
}
entity.IsOnline = "在线";
entity.LastHeartbeat = DateTime.Now;
_repository.DbContext.Updateable(entity).ExecuteCommand();
entity.IsOnline = "在线";
entity.LastHeartbeat = DateTime.Now;
_repository.DbContext.Updateable(entity).ExecuteCommand();
_logger.LogDebug("[A2] 心跳更新: NodeCode={Node}", nodeCode);
}
catch (UnauthorizedAccessException) { throw; }
catch (Exception ex)
{
_logger.LogError(ex, "[A2] 心跳异常: NodeCode={Node}", nodeCode);
throw;
}
}
/// <summary>
@@ -110,69 +141,83 @@ namespace Warehouse.Services
[Obsolete("由 A3 API Controller 自动调用,不建议手动调用")]
public async Task<(int added, int updated)> SyncDevicesAsync(int gatewayNodeId, List<SyncDeviceItem> devices)
{
var db = _repository.DbContext;
var adapterCodes = devices.Select(d => d.AdapterCode).Distinct().ToList();
var existingIds = db.Queryable<base_device>()
.Where(x => x.NodeId == gatewayNodeId && adapterCodes.Contains(x.AdapterCode))
.ToList()
.ToDictionary(x => (x.AdapterCode, x.SourceId), x => x.DeviceId);
int added = 0, updated = 0;
foreach (var d in devices)
_logger.LogInformation("[A3] 设备同步开始: NodeId={Id}, 设备数={Count}", gatewayNodeId, devices.Count);
try
{
var key = (d.AdapterCode, d.SourceId);
existingIds.TryGetValue(key, out var existingId);
bool isNew = existingId == 0;
var db = _repository.DbContext;
int? parentDeviceId = null;
if (!string.IsNullOrEmpty(d.ParentSourceId))
{
existingIds.TryGetValue((d.AdapterCode, d.ParentSourceId), out var pid);
if (pid > 0) parentDeviceId = pid;
}
var adapterCodes = devices.Select(d => d.AdapterCode).Distinct().ToList();
// 全局去重——不限定 NodeId,防止网关重启后 NodeId 变化导致重复插入
var existingIds = db.Queryable<base_device>()
.Where(x => adapterCodes.Contains(x.AdapterCode))
.ToList()
.ToDictionary(x => (x.AdapterCode, x.SourceId), x => x.DeviceId);
if (isNew)
int added = 0, updated = 0;
foreach (var d in devices)
{
var entity = new base_device
var key = (d.AdapterCode, d.SourceId);
existingIds.TryGetValue(key, out var existingId);
bool isNew = existingId == 0;
int? parentDeviceId = null;
if (!string.IsNullOrEmpty(d.ParentSourceId))
{
DeviceName = d.Name ?? $"DEV_{d.SourceId}",
AdapterCode = d.AdapterCode,
SourceId = d.SourceId,
DeviceCategory = d.Category,
DeviceGroup = d.Group,
NodeId = gatewayNodeId,
IsParent = d.IsParent ? "是" : "否",
ParentDeviceId = parentDeviceId,
IsOnline = d.IsOnline ? "在线" : "离线",
IpAddress = d.IpAddress,
Port = d.Port,
ExtraData = d.ExtraDataJson,
Enable = "启用",
LastSyncTime = DateTime.Now,
CreateDate = DateTime.Now
};
db.Insertable(entity).ExecuteCommand();
added++;
}
else
{
var entity = db.Queryable<base_device>().InSingle(existingId);
if (entity != null)
existingIds.TryGetValue((d.AdapterCode, d.ParentSourceId), out var pid);
if (pid > 0) parentDeviceId = pid;
}
if (isNew)
{
entity.IsOnline = d.IsOnline ? "在线" : "离线";
entity.IsParent = d.IsParent ? "是" : "否";
entity.ParentDeviceId = parentDeviceId ?? entity.ParentDeviceId;
entity.IpAddress = d.IpAddress;
entity.Port = d.Port;
entity.ExtraData = d.ExtraDataJson ?? entity.ExtraData;
entity.LastSyncTime = DateTime.Now;
db.Updateable(entity).ExecuteCommand();
updated++;
var entity = new base_device
{
DeviceName = d.Name ?? $"DEV_{d.SourceId}",
AdapterCode = d.AdapterCode,
SourceId = d.SourceId,
DeviceCategory = d.Category,
DeviceGroup = d.Group,
NodeId = gatewayNodeId,
IsParent = d.IsParent ? "是" : "否",
ParentDeviceId = parentDeviceId,
IsOnline = d.IsOnline ? "在线" : "离线",
IpAddress = d.IpAddress,
Port = d.Port,
ExtraData = d.ExtraDataJson,
Enable = "启用",
LastSyncTime = DateTime.Now,
CreateDate = DateTime.Now
};
var newId = db.Insertable(entity).ExecuteReturnIdentity();
// 补入去重字典,同批次子设备可查到父设备
existingIds[(d.AdapterCode, d.SourceId)] = Convert.ToInt32(newId);
added++;
}
else
{
var entity = db.Queryable<base_device>().InSingle(existingId);
if (entity != null)
{
entity.NodeId = gatewayNodeId; // 重新归属到当前网关
entity.IsOnline = d.IsOnline ? "在线" : "离线";
entity.IsParent = d.IsParent ? "是" : "否";
entity.ParentDeviceId = parentDeviceId ?? entity.ParentDeviceId;
entity.IpAddress = d.IpAddress;
entity.Port = d.Port;
entity.ExtraData = d.ExtraDataJson ?? entity.ExtraData;
entity.LastSyncTime = DateTime.Now;
db.Updateable(entity).ExecuteCommand();
updated++;
}
}
}
_logger.LogInformation("[A3] 设备同步完成: 新增{Added}台, 更新{Updated}台", added, updated);
return (added, updated);
}
catch (Exception ex)
{
_logger.LogError(ex, "[A3] 设备同步异常: NodeId={Id}, 设备数={Count}", gatewayNodeId, devices.Count);
throw;
}
return (added, updated);
}
}