2025-07-31 18:51:24 +08:00

3350 lines
97 KiB
Markdown
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.

# YunDa.SOMS.Application 应用层文档
## 目录
1. [模块概述](#模块概述)
2. [架构设计](#架构设计)
3. [核心基础设施](#核心基础设施)
4. [业务模块](#业务模块)
5. [技术栈](#技术栈)
6. [开发指南](#开发指南)
7. [API文档](#api文档)
8. [最佳实践](#最佳实践)
## 模块概述
YunDa.SOMS.Application 是云达智能变电站运维管理系统(SOMS)的应用服务层负责实现系统的核心业务逻辑和对外API接口。该模块基于ABP框架构建采用领域驱动设计(DDD)和分层架构模式,为变电站运维管理提供全面的应用服务。
### 主要职责
- **业务逻辑实现**: 封装复杂的业务规则和流程
- **API接口提供**: 为前端和外部系统提供RESTful API
- **数据传输对象**: 定义输入输出的数据传输对象(DTO)
- **权限控制**: 实现基于角色的访问控制(RBAC)
- **审计日志**: 记录系统操作和数据变更
- **缓存管理**: 提供Redis缓存支持
- **实时通信**: 支持WebSocket和SignalR实时数据推送
### 设计理念
1. **分离关注点**: 将业务逻辑与数据访问、表示层分离
2. **依赖倒置**: 依赖抽象而非具体实现
3. **单一职责**: 每个服务类专注于特定的业务领域
4. **开闭原则**: 对扩展开放,对修改封闭
5. **可测试性**: 支持单元测试和集成测试
## 架构设计
### 整体架构
```
YunDa.SOMS.Application/
├── YunDa.SOMS.Application.Core/ # 核心基础设施
├── YunDa.SOMS.Application/ # 主应用服务
├── YunDa.SOMS.MongoDB.Application/ # MongoDB应用服务
└── YunDa.SOMS.ExternalInteraction.Application/ # 外部交互服务
```
### 模块依赖关系
```mermaid
graph TD
A[YunDa.SOMS.Application] --> B[YunDa.SOMS.Application.Core]
C[YunDa.SOMS.MongoDB.Application] --> B
D[YunDa.SOMS.ExternalInteraction.Application] --> B
B --> E[YunDa.SOMS.Core]
B --> F[YunDa.SOMS.EntityFrameworkCore]
B --> G[YunDa.SOMS.MongoDB]
B --> H[YunDa.SOMS.Redis]
B --> I[YunDa.SOMS.DataTransferObject]
```
### 分层架构
1. **应用服务层 (Application Services)**
- 协调领域对象执行业务用例
- 处理数据传输对象(DTO)转换
- 实现事务管理和权限控制
2. **领域服务层 (Domain Services)**
- 实现复杂的业务逻辑
- 处理跨聚合根的业务操作
3. **基础设施层 (Infrastructure)**
- 数据持久化(Entity Framework Core)
- 缓存服务(Redis)
- 文档存储(MongoDB)
- 外部系统集成
## 核心基础设施
### SOMSAppServiceBase
所有应用服务的基类,提供通用功能:
```csharp
[AbpAuthorize]
[DisableAuditing]
public abstract class SOMSAppServiceBase : ApplicationService
{
protected readonly ISessionAppService _sessionAppService;
protected readonly IAppServiceConfiguration _appServiceConfiguration;
// 获取当前登录用户
protected virtual LoginUserOutput GetCurrentUser()
// 图片处理功能
protected virtual byte[] ResizeImage(byte[] imageBytes, int width, int height)
}
```
**主要功能:**
- 用户会话管理
- 权限验证
- 本地化支持
- 图片处理工具
- 配置访问
### IAppServiceBase<T>
标准CRUD操作的通用接口
```csharp
public interface IAppServiceBase<TSearchConditionInput, TResultOutput, TEditInput, TDelPrimaryKey>
{
RequestPageResult<TResultOutput> FindDatas(PageSearchCondition<TSearchConditionInput> searchCondition);
Task<RequestResult<TResultOutput>> CreateOrUpdateAsync(TEditInput input);
Task<RequestEasyResult> DeleteByIdsAsync(List<TDelPrimaryKey> ids);
Task<RequestEasyResult> DeleteByIdAsync(TDelPrimaryKey id);
}
```
**设计优势:**
- 统一的CRUD接口规范
- 泛型支持提高代码复用
- 标准化的返回结果格式
- 支持分页查询
### 配置管理
#### IAppServiceConfiguration
系统配置接口,管理应用级配置参数:
```csharp
public interface IAppServiceConfiguration
{
string SysAttachmentFolder { get; set; } // 系统附件文件夹
int MasterStationType { get; set; } // 主站类型
long MaxDataCount { get; set; } // 遥测分析最大查询项
string MasterStationBaseUrl { get; set; } // 主站通信基础URL
string IsmsGateWayIp { get; set; } // ISMS网关IP
string FtpIp { get; set; } // FTP服务器IP
int UploadWaitSeconds { get; set; } // 上传等待时间
bool IsCpmpressImageForMasterStation { get; set; } // 是否压缩图片
}
```
### 会话管理
#### SessionAppService
管理用户会话和认证信息:
```csharp
[DisableAuditing]
public class SessionAppService : ISessionAppService
{
private readonly IHttpContextAccessor _contextAccessor;
public CurrentLoginInformationsOutput GetCurrentLoginInformations()
{
// 从HTTP上下文获取用户信息
// 解析JWT Token中的用户数据
// 返回当前登录用户信息和应用信息
if (_contextAccessor.HttpContext?.User?.Identity?.IsAuthenticated == true)
{
string userDataJsonStr = _contextAccessor.HttpContext.User.Claims
.Where(claim => claim.Type == ClaimTypes.UserData)
.FirstOrDefault().Value;
output.User = JsonConvert.DeserializeObject<LoginUserOutput>(userDataJsonStr);
}
}
}
```
### 审计日志
#### SOMSAuditingStore
自定义审计日志存储实现:
```csharp
public class SOMSAuditingStore : IAuditingStore
{
private readonly IMongoDbRepository<SysAuditLog, Guid> _sysAuditLogRepository;
private List<string> _serviceNames = new List<string> { "综自信息查询", "变电所扩展服务" };
public async Task SaveAsync(AuditInfo auditInfo)
{
if (auditInfo == null) return;
if (_serviceNames.Contains(auditInfo.ServiceName))
{
SysAuditLog sysAuditLog = CreateFromAuditInfo(auditInfo);
_sysAuditLogRepository.CollectionName = "SysAuditLog_" + DateTime.Now.ToString("yyyyMM");
_sysAuditLogRepository.InsertOne(sysAuditLog);
}
}
}
```
**审计功能:**
- 自动记录API调用
- 按服务名称过滤
- MongoDB分表存储按月份
- 异常处理和日志记录
#### SOMSAuditingHelper
自定义审计日志助手:
```csharp
public class SOMSAuditingHelper : IAuditingHelper
{
public AuditInfo CreateAuditInfo(Type type, MethodInfo method, object[] arguments)
{
// 获取类型和方法的Description特性
var typeDescription = type.GetCustomAttribute<DescriptionAttribute>();
var methodDescription = method.GetCustomAttribute<DescriptionAttribute>();
return new AuditInfo
{
TenantId = AbpSession.TenantId,
UserId = AbpSession.UserId,
ServiceName = typeDescription?.Description ?? type.Name,
MethodName = methodDescription?.Description ?? method.Name,
Parameters = ConvertArgumentsToJson(arguments),
ExecutionTime = Clock.Now
};
}
}
```
### 实时通信服务
#### IRealTimeCommunicationService
统一的WebSocket和SignalR通信接口
```csharp
public interface IRealTimeCommunicationService
{
// 通知相关
Task SendNotificationToUserAsync(string userId, string message, string type = "info", string title = null, Guid? transformerSubstationId = null);
Task BroadcastNotificationAsync(string message, string type = "info", string title = null, Guid? transformerSubstationId = null);
// 数据更新
Task SendDataUpdateAsync(string dataType, object data, string[] targetUsers = null, Guid? transformerSubstationId = null);
Task SendAlarmAsync(object alarmData, string[] targetUsers = null, Guid? transformerSubstationId = null);
Task SendDeviceUpdateAsync(string deviceId, string status, object data = null, string[] targetUsers = null, Guid? transformerSubstationId = null);
// 系统事件
Task SendSystemEventAsync(string eventType, object eventData, string[] targetUsers = null, Guid? transformerSubstationId = null);
// 用户管理
Task<bool> IsUserOnlineAsync(string userId);
Task<int> GetOnlineUserCountAsync();
Task<string[]> GetOnlineUsersAsync();
// 自定义消息
Task SendCustomMessageAsync(string messageType, object data, string[] targetUsers = null, bool useSignalR = true);
}
```
#### RealTimeCommunicationService
实时通信服务实现:
```csharp
public class RealTimeCommunicationService : IRealTimeCommunicationService, ITransientDependency
{
private readonly ISignalRService _signalRService;
private readonly IWebSocketService _webSocketService;
private readonly ICommunicationConfigurationCacheService _configurationCacheService;
public virtual async Task SendDataUpdateAsync(string dataType, object data, string[] targetUsers = null, Guid? transformerSubstationId = null)
{
// 从配置缓存服务获取WebSocket优先级设置
var useWebSocketPriority = await _configurationCacheService.GetWebSocketPriorityAsync(transformerSubstationId);
var enableAutoFailover = await _configurationCacheService.GetEnableAutoFailoverAsync(transformerSubstationId);
var retryCount = await _configurationCacheService.GetFailoverRetryCountAsync(transformerSubstationId);
// 根据配置选择通信方式并实现故障转移
if (useWebSocketPriority)
{
// 优先使用WebSocket失败时转移到SignalR
}
else
{
// 优先使用SignalR失败时转移到WebSocket
}
}
}
```
**特性:**
- 支持WebSocket和SignalR双通道
- 配置驱动的通信策略
- 自动故障转移机制
- 消息压缩和持久化
- 变电站级别的配置隔离
### 通信配置缓存服务
#### ICommunicationConfigurationCacheService
通信配置缓存服务接口:
```csharp
public interface ICommunicationConfigurationCacheService
{
// WebSocket配置
Task<bool> GetWebSocketPriorityAsync(Guid? transformerSubstationId = null);
Task<int> GetWebSocketTimeoutSecondsAsync(Guid? transformerSubstationId = null);
// SignalR配置
Task<int> GetSignalRTimeoutSecondsAsync(Guid? transformerSubstationId = null);
// 故障转移配置
Task<bool> GetEnableAutoFailoverAsync(Guid? transformerSubstationId = null);
Task<int> GetFailoverRetryCountAsync(Guid? transformerSubstationId = null);
// 消息配置
Task<bool> GetEnableMessageCompressionAsync(Guid? transformerSubstationId = null);
Task<bool> GetEnableMessagePersistenceAsync(Guid? transformerSubstationId = null);
Task<int> GetMaxMessageQueueLengthAsync(Guid? transformerSubstationId = null);
// 缓存管理
Task ClearCacheAsync(Guid? transformerSubstationId = null);
Task ClearAllCacheAsync();
Task WarmupCacheAsync();
}
```
#### CommunicationConfigurationCacheService
通信配置缓存服务实现:
```csharp
public class CommunicationConfigurationCacheService : ICommunicationConfigurationCacheService, ITransientDependency
{
private readonly IRepository<CommunicationConfiguration, Guid> _communicationConfigurationRepository;
private readonly IMemoryCache _memoryCache;
private const string CACHE_KEY_PREFIX = "CommConfig_";
private const int CACHE_EXPIRATION_MINUTES = 30;
// 默认配置值
private const bool DEFAULT_WEBSOCKET_PRIORITY = false;
private const int DEFAULT_WEBSOCKET_TIMEOUT = 30;
private const int DEFAULT_SIGNALR_TIMEOUT = 30;
private const bool DEFAULT_ENABLE_AUTO_FAILOVER = true;
private const int DEFAULT_FAILOVER_RETRY_COUNT = 3;
public async Task<bool> GetWebSocketPriorityAsync(Guid? transformerSubstationId = null)
{
var config = await GetEffectiveConfigurationAsync(transformerSubstationId);
return config?.WebSocketPriority ?? DEFAULT_WEBSOCKET_PRIORITY;
}
private async Task<CommunicationConfiguration> GetEffectiveConfigurationAsync(Guid? transformerSubstationId)
{
var cacheKey = GetCacheKey(transformerSubstationId);
if (_memoryCache.TryGetValue(cacheKey, out CommunicationConfiguration cachedConfig))
{
return cachedConfig;
}
// 首先查找指定变电站的配置
var config = _communicationConfigurationRepository.GetAll()
.Where(x => x.IsActive && x.TransformerSubstationId == transformerSubstationId)
.OrderBy(x => x.Priority)
.FirstOrDefault();
// 如果没有找到且不是全局查询,则查找全局配置
if (config == null && transformerSubstationId.HasValue)
{
config = _communicationConfigurationRepository.GetAll()
.Where(x => x.IsActive && x.TransformerSubstationId == null)
.OrderBy(x => x.Priority)
.FirstOrDefault();
}
// 缓存配置
var cacheOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(CACHE_EXPIRATION_MINUTES),
SlidingExpiration = TimeSpan.FromMinutes(CACHE_EXPIRATION_MINUTES / 2)
};
_memoryCache.Set(cacheKey, config, cacheOptions);
return config;
}
}
```
**特性:**
- 内存缓存提高性能
- 支持变电站级别配置
- 配置继承机制(变电站配置 -> 全局配置 -> 默认值)
- 缓存预热和清理功能
- 滑动过期策略
### 扩展应用服务
#### InspectionTaskExtensionAppService
巡检任务扩展服务,提供对外通信接口:
```csharp
[AbpAllowAnonymous, Description("对外通信-巡检扩展管理服务")]
public class InspectionTaskExtensionAppService : AbpServiceBase, IInspectionTaskExtensionAppService
{
private readonly IRepository<InspectionCard, Guid> _inspectionCardRepository;
private readonly IMongoDbRepository<InspectionResult, Guid> _inspectionResultRepository;
private readonly IMongoDbRepository<InspectionItemResult, Guid> _inspectionItemResultRepository;
private readonly IMongoDbRepository<RobotTaskResult, Guid> _robotTaskResultRepository;
// 文件上传处理
private ByteArrayContent GetFileByteArrayContent(byte[] fileBytes, out int fileByteCount)
{
if (fileBytes == null)
{
fileByteCount = 0;
return null;
}
if (_appServiceConfiguration.IsCpmpressImageForMasterStation)
{
var imageBytes = ImageChangeSize.CutImageSize(fileBytes);
fileByteCount = imageBytes.Length;
return new ByteArrayContent(imageBytes);
}
else
{
fileByteCount = fileBytes.Length;
return new ByteArrayContent(fileBytes);
}
}
// HTTP请求处理
public async Task<RequestEasyResult> SendHttpRequestAsync(string url, object input)
{
return await Task.Run(() =>
{
try
{
HttpHelper.HttpPostRequest(url, input);
var inputjson = JsonConvert.SerializeObject(input);
Log4Helper.Info(this.GetType(), $"请求地址:{url},请求内容:{inputjson}");
return new RequestEasyResult { Flag = true };
}
catch (Exception ex)
{
Log4Helper.Error(this.GetType(), "巡检任务扩展服务", ex);
return new RequestEasyResult { Flag = false, Message = ex.Message };
}
});
}
}
```
**功能:**
- 巡检结果数据处理
- 文件上传和压缩
- HTTP请求封装
- 机器人任务结果管理
- 对外接口通信
## 业务模块
### 数据监控 (DataMonitoring)
负责变电站数据监控相关的业务逻辑是SOMS系统的核心功能模块
#### 遥测配置管理 (TelemeteringConfiguration)
**服务类**: `TelemeteringConfigurationAppService`
**接口**: `ITelemeteringConfigurationAppService`
**核心功能:**
- 遥测点配置管理(模拟量数据点)
- 数据采集参数设置(采样频率、系数、单位)
- 环境温度监控和缓存
- 通信数据结构管理
**主要方法:**
```csharp
[HttpPost, Audited, Description("遥测数据增加或修改")]
public async Task<RequestResult<TelemeteringConfigurationOutput>> CreateOrUpdateAsync(EditTelemeteringConfigurationInput input)
[HttpPost, Description("查询遥测数据")]
public RequestPageResult<TelemeteringConfigurationOutput> FindDatas(PageSearchCondition<TelemeteringConfigurationSearchConditionInput> searchCondition)
[HttpPost, AbpAllowAnonymous]
public RequestResult<dynamic> FindTelesignalisationConfigurationDataStruct(TelemeteringConfigurationSearchConditionInput input)
[HttpGet, AbpAllowAnonymous]
public async Task<RequestResult<float>> GetEnvironmentTempValue(Guid? transubstationId)
```
**数据模型特点:**
- 支持虚拟装置点位配置
- 多级地址映射(信息地址、装置地址、调度地址)
- 系数和小数位数配置
- 数据来源分类(综自、保护装置等)
- 主副设备关联支持
#### 遥信配置管理 (TelesignalisationConfiguration)
**服务类**: `TelesignalisationConfigurationAppService`
**接口**: `ITelesignalisationConfigurationAppService`
**核心功能:**
- 遥信点配置管理(开关量数据点)
- 开关状态监控和变位检测
- 通信数据结构管理
- 自检配置关联
**主要方法:**
```csharp
[HttpPost, Audited, Description("遥信数据增加或修改")]
public async Task<RequestResult<TelesignalisationConfigurationOutput>> CreateOrUpdateAsync(EditTelesignalisationConfigurationInput input)
[HttpPost, Description("查询遥信数据")]
public RequestPageResult<TelesignalisationConfigurationOutput> FindDatas(PageSearchCondition<TelesignalisationConfigurationSearchConditionInput> searchCondition)
[HttpPost, AbpAllowAnonymous]
public RequestResult<dynamic> FindTelesignalisationConfigurationDataStruct(TelesignalisationConfigurationSearchConditionInput input)
[HttpGet, AbpAllowAnonymous]
public RequestResult<List<SelectModelOutput>> FindTelesignalisationConfigurationForSelect(SelectTelesignalisationSearchConditionInput searchCondition)
```
**特殊功能:**
- 支持单双点类型配置
- 正常状态和异常状态定义
- 与自检配置的关联
- 通信数据结构自动计算
#### 遥控配置管理 (TelecommandConfiguration)
**服务类**: `TelecommandConfigurationAppService`
**接口**: `ITelecommandConfigurationAppService`
**核心功能:**
- 遥控指令配置管理
- 操作权限和安全控制
- 执行计划和模板管理
- 相关遥信关联
**数据模型:**
```csharp
public class TelecommandConfiguration : SOMSAuditedEntity, ISOMSPassivable
{
public string Name { get; set; } // 遥控名称
public bool IsVirtualDevice { get; set; } // 是否虚拟装置
public int InfoAddress { get; set; } // 信息地址
public int DeviceAddress { get; set; } // 装置地址
public int DispatcherAddress { get; set; } // 调度地址
public RemoteTypeEnum RemoteType { get; set; } // 单双点类型
public Guid? RelatedTelesignalisationId { get; set; } // 相关遥信
public Guid? PrimaryEquipmentInfoId { get; set; } // 主设备
public Guid? SecondaryEquipmentInfoId { get; set; } // 副设备
public DataSourceCategoryEnum? DataSourceCategory { get; set; } // 数据来源
}
```
**安全特性:**
- 双设备关联支持(主副设备)
- 相关遥信状态验证
- 操作权限控制
- 执行结果反馈
#### 报警策略管理
##### 遥测报警策略 (TelemeteringAlarmStrategy)
**核心功能:**
- 基于阈值的模拟量报警
- 多级报警等级设置
- 报警抑制和恢复逻辑
**数据模型:**
```csharp
public class TelemeteringAlarmStrategy : SOMSAuditedEntity, ISOMSPassivable
{
public int SeqNo { get; set; } // 顺序
public float MinValue { get; set; } // 最小值
public float MaxValue { get; set; } // 最大值
public Guid? DMAlarmCategoryId { get; set; } // 报警分类
public Guid? TelemeteringConfigurationId { get; set; } // 关联遥测
public Guid? EquipmentInfoId { get; set; } // 关联设备
public Guid? TransformerSubstationId { get; set; } // 所属变电站
}
```
##### 遥测报警模板 (TelemeteringAlarmTemplate)
**核心功能:**
- 报警策略模板化管理
- 批量应用报警配置
- 标准化报警参数
**应用场景:**
- 同类型设备批量配置
- 报警参数标准化
- 快速部署新设备
#### 联动策略管理
##### 联动策略 (LinkageStrategy)
**核心功能:**
- 基于JavaScript规则引擎的联动逻辑
- 多条件组合判断
- 时间间隔和重复控制
**数据模型:**
```csharp
public class LinkageStrategy : SOMSAuditedEntity, ISOMSPassivable
{
public string Name { get; set; } // 联动名称
public string Rule { get; set; } // JavaScript规则
public string ConditionIds { get; set; } // 条件ID列表
public int TimeOfWithRelationship { get; set; } // 条件关系时间间隔
public int RepeatLinkageInterval { get; set; } // 重复联动间隔
public int ForceLinkageTimes { get; set; } // 强制联动次数
public int ForceLinkageSeconds { get; set; } // 强制联动时间
public Guid TransformerSubstationId { get; set; } // 关联变电站
}
```
**规则示例:**
```javascript
// 简单逻辑运算
"((30 + 4) * 2+2)||true"
// 条件判断
"if(0==1){return 1+1;}else{return 2+1;}"
// 复杂条件组合
"(condition1 && condition2) || (condition3 && !condition4)"
```
##### 联动条件 (LinkageCondition)
**核心功能:**
- 多类型条件定义(遥测、遥信、设备状态)
- 条件参数配置
- 条件组合逻辑
**数据模型:**
```csharp
public class LinkageCondition : SOMSAuditedEntity, ISOMSPassivable
{
public ConditionTypeEnum ConditionType { get; set; } // 条件类型
public Guid? EquipmentTypeId { get; set; } // 设备类型
public Guid? EquipmentInfoId { get; set; } // 关联设备
public Guid? TelemeteringConfigurationId { get; set; } // 遥测关联
public Guid? TelesignalisationConfigurationId { get; set; } // 遥信关联
public float? MinValue { get; set; } // 最小值
public float? MaxValue { get; set; } // 最大值
public bool? BoolValue { get; set; } // 布尔值
public Guid? TransformerSubstationId { get; set; } // 所属变电站
}
```
**条件类型:**
- **遥测条件**: 基于模拟量阈值判断
- **遥信条件**: 基于开关量状态判断
- **设备条件**: 基于设备运行状态判断
- **时间条件**: 基于时间窗口判断
##### 联动执行活动 (LinkageExecuteActivity)
**核心功能:**
- 联动动作定义和执行
- 多种执行类型支持
- 执行结果反馈
**执行类型:**
- **遥控执行**: 发送遥控指令
- **摄像头控制**: 调整摄像头预置位
- **报警发送**: 发送报警通知
- **数据记录**: 记录事件日志
**执行流程:**
```csharp
public async Task ExecuteLinkageDataAsync(LinkageStrategyModel linkageStrategy, string resultStr, string code)
{
// 1. 解析联动策略
// 2. 获取执行活动列表
// 3. 按类型分组执行
// 4. 记录执行结果
// 5. 发送执行反馈
}
```
#### 自检配置管理 (SelfCheckingConfiguration)
**核心功能:**
- 设备自检策略配置
- 通信状态监控
- 超时判断和处理
**数据模型:**
```csharp
public class SelfCheckingConfiguration : SOMSAuditedEntity, ISOMSPassivable
{
public string Name { get; set; } // 配置名称
public DataTypeEnum DataType { get; set; } // 数据类型(遥测/遥信/遥控)
public int TimeOfJudgment { get; set; } // 判定时间(秒)
public JudgmentModeEnum JudgmentMode { get; set; } // 判定模式
public Guid? EquipmentInfoId { get; set; } // 关联设备
public Guid? TransformerSubstationId { get; set; } // 所属变电站
}
```
**判定模式:**
- **超时判定**: 数据超时未更新
- **变化判定**: 数据值异常变化
- **范围判定**: 数据值超出正常范围
- **通信判定**: 通信链路状态检查
#### 模板管理系统
##### 遥测模板 (TelemeteringTemplate)
- 遥测点标准化配置
- 批量创建遥测点
- 参数模板化管理
##### 遥信模板 (TelesignalisationTemplate)
- 遥信点标准化配置
- 批量创建遥信点
- 状态定义模板化
##### 遥控模板 (TelecommandTemplate)
- 遥控指令标准化配置
- 批量创建遥控点
- 安全参数模板化
#### 实时数据处理
**数据流程:**
```
设备数据 → IEC104协议解析 → ActionBlock队列处理 → 数据验证 → Redis缓存 → MongoDB存储
```
**缓存策略:**
- **TelemeteringModelListRedis**: 遥测数据实时库
- **TelesignalisationModelListRedis**: 遥信数据实时库
- **AlarmListRedis**: 告警数据缓存
- **EnvironmentTempValueRedis**: 环境温度数据缓存
**存储策略:**
- **周期保存**: 按固定时间间隔保存数据
- **变化保存**: 数据变化时触发保存
- **混合保存**: 结合周期和变化保存策略
- **分表存储**: 按时间分表提高查询性能
#### 报警分析引擎
**报警类型:**
- **遥测报警**: 基于阈值的模拟量报警
- **遥信报警**: 开关量状态变化报警
- **设备报警**: 设备自检和状态报警
- **二次回路报警**: 二次回路逻辑分析报警
**报警处理流程:**
1. 数据采集和预处理
2. 报警策略匹配
3. 报警条件判断
4. 报警生成和分级
5. 报警通知和记录
6. 联动策略触发
#### 能源管理 (EnergyManagement)
**核心功能:**
- 电能数据采集和分析
- 能耗统计和报表
- 能效分析和优化建议
#### 环境数据监控 (EnvironmentLiveData)
**核心功能:**
- 环境参数实时监控
- 温湿度数据采集
- 环境报警和控制
#### 智能设备巡检 (IntelligentDeviceInspector)
**核心功能:**
- 设备状态智能分析
- 异常模式识别
- 预测性维护建议
### 综合信息管理 (GeneralInformation)
管理变电站基础信息和设备档案是SOMS系统的基础数据管理模块
#### 设备信息管理 (EquipmentInfo)
**服务类**: `EquipmentInfoAppService`, `EquipmentInfoExAppService`
**接口**: `IEquipmentInfoAppService`, `IEquipmentInfoExAppService`
**核心功能:**
- 设备档案全生命周期管理
- 设备状态实时监控
- 安全状态自动更新
- 模板同步和批量操作
- 设备资产信息管理
**数据模型:**
```csharp
public class EquipmentInfo : SOMSAuditedEntity, ISOMSPassivable
{
public string Name { get; set; } // 设备名称
public string Code { get; set; } // 设备编码
public Guid? EquipmentTypeId { get; set; } // 设备类型
public Guid? BelongEquipmentInfoId { get; set; } // 所属设备
public Guid? ManufacturerInfoId { get; set; } // 生产厂商
public Guid? TransformerSubstationId { get; set; } // 所属变电站
public bool IsRemoteControl { get; set; } // 是否可远程控制
public SafetyStateTypeEnum? SafetyStateType { get; set; } // 安防状态
public SafetyStateTypeEnum? SafetyPlanStateType { get; set; } // 计划安防状态
public DateTime? SafetyPlanTime { get; set; } // 安防计划时间
public string Remark { get; set; } // 备注
}
public enum SafetyStateTypeEnum
{
[Description("不具备此功能")]
None = 0,
[Description("布防")]
Arming = 1,
[Description("撤防")]
Disarming = 2,
}
```
**主要方法:**
```csharp
[HttpPost, Audited, Description("设备信息增加或修改")]
public async Task<RequestResult<EquipmentInfoOutput>> CreateOrUpdateAsync(EditEquipmentInfoInput input)
[HttpGet, AbpAllowAnonymous, ShowApi]
public RequestEasyResult FreshSafetyState()
[HttpPost, Audited, Description("根据设备类型同步更新遥信、遥测、模板")]
public RequestEasyResult SyncTeleTemplate()
// 扩展服务方法
public RequestResult<EquipementInfoAssetOutput> GetEquipmentInfoAsset(Guid equipementId)
```
**安全状态管理:**
- **自动状态更新**: 根据计划时间自动切换安防状态
- **状态类型**: 布防、撤防、不具备功能
- **计划调度**: 支持预设安防状态切换时间
- **状态监控**: 实时监控设备安防状态变化
**模板同步功能:**
- 根据设备类型自动创建遥测、遥信、遥控配置
- 批量应用设备模板参数
- 模板参数继承和覆盖机制
- 同步状态跟踪和异常处理
**设备资产管理:**
- 设备基础信息档案
- 保护装置关联信息
- ISMS系统设备映射
- 设备核心参数管理
#### 变电站管理 (TransformerSubstation)
**服务类**: `TransformerSubstationAppService`, `TransformerSubstationExAppService`
**接口**: `ITransformerSubstationAppService`
**核心功能:**
- 变电站基础信息管理
- 地理位置和坐标管理
- 通信参数配置
- 主站服务地址管理
- 供电线路关联
**数据模型:**
```csharp
public class TransformerSubstation : SOMSAuditedEntity, ISOMSPassivable
{
public int SeqNo { get; set; } // 序号
public string SubstationName { get; set; } // 变电站名称
public string CommMgrIP { get; set; } // 通信管理机IP
public string MasterStationAddress { get; set; } // 主站服务地址
public double? Longitude { get; set; } // 经度
public double? Latitude { get; set; } // 纬度
public Guid? PowerSupplyLineId { get; set; } // 供电线路
public string Remark { get; set; } // 备注
// 导航属性
public virtual PowerSupplyLine PowerSupplyLine { get; set; }
public virtual IEnumerable<VideoDev> VideoDevs { get; set; }
public virtual IEnumerable<EquipmentInfo> EquipmentInfos { get; set; }
}
```
**地理信息管理:**
- GPS坐标定位
- 地理位置可视化
- 区域范围管理
- 地图集成支持
**通信配置:**
- 通信管理机IP配置
- 主站服务地址管理
- 通信协议参数设置
- 网络连接状态监控
**数据同步功能:**
- 与ISMS系统数据同步
- 变电站信息自动导入
- 数据一致性检查
- 同步状态跟踪
#### 设备类型管理 (EquipmentType)
**服务类**: `EquipmentTypeAppService`
**接口**: `IEquipmentTypeAppService`
**核心功能:**
- 设备分类体系管理
- 层级结构维护
- 模板关联管理
- 类型参数配置
**数据模型:**
```csharp
public class EquipmentType : SOMSAuditedEntity, ISOMSPassivable
{
public string Name { get; set; } // 类型名称
public string Code { get; set; } // 类型编码
public Guid? EquipmentTypeId { get; set; } // 父节点ID
// 导航属性
public virtual IEnumerable<EquipmentInfo> EquipmentInfos { get; set; }
public virtual IEnumerable<TelemeteringTemplate> TelemeteringTemplates { get; set; }
public virtual IEnumerable<TelesignalisationTemplate> TelesignalisationTemplates { get; set; }
public virtual IEnumerable<TelecommandTemplate> TelecommandTemplates { get; set; }
}
```
**层级管理:**
- 树形结构组织
- 父子关系维护
- 层级权限控制
- 递归查询支持
**模板关联:**
- 遥测模板关联
- 遥信模板关联
- 遥控模板关联
- 模板继承机制
#### 制造商信息管理 (ManufacturerInfo)
**服务类**: `ManufacturerInfoAppService`
**接口**: `IManufacturerInfoAppService`
**核心功能:**
- 厂商档案管理
- 联系方式维护
- 产品信息管理
- 厂商编码规范
**数据模型:**
```csharp
public class ManufacturerInfo : SOMSFullAuditedEntity, ISOMSPassivable
{
public string ManufacturerName { get; set; } // 厂商名称
public string ManufacturerCode { get; set; } // 厂商编码
public string PhoneNumber { get; set; } // 厂商电话
public string EmailAddress { get; set; } // 邮件地址
public string ManufacturerAddress { get; set; } // 厂商地址
public string Remark { get; set; } // 备注
}
```
**厂商管理:**
- 厂商基础信息维护
- 联系方式管理
- 产品线管理
- 服务支持信息
#### 保护装置管理 (ProtectionDevice)
**服务类**: `ProtectionDeviceAppService`
**接口**: `IProtectionDeviceAppService`
**核心功能:**
- 保护装置档案管理
- 装置参数配置
- ISMS系统集成
- 保护定值管理
**数据模型:**
```csharp
public class ProtectionDeviceInfo : SOMSAuditedEntity, ISOMSPassivable
{
public int SeqNo { get; set; } // 顺序号
public string Name { get; set; } // 设备名称
public Guid EquipmentInfoId { get; set; } // 关联设备
public string ISMS_DeviceId { get; set; } // ISMS设备ID
public Guid? ProtectionDeviceTypeId { get; set; } // 保护装置类型
public string InstallationArea { get; set; } // 安装区域
public string PostionDescription { get; set; } // 位置描述
public string RunNumber { get; set; } // 运行编号
// 导航属性
public virtual EquipmentInfo EquipmentInfo { get; set; }
public virtual ProtectionDeviceType ProtectionDeviceType { get; set; }
}
```
**ISMS集成:**
- 与ISMS保护装置数据同步
- 装置状态实时监控
- 保护动作记录
- 定值管理集成
#### 保护定值管理 (ProtectionSetting)
**核心功能:**
- 保护定值配置管理
- 定值版本控制
- 定值下发和校验
- 定值变更记录
**数据模型:**
```csharp
public class ProtectionSetting : SOMSAuditedEntity
{
public Guid EquipmentInfoId { get; set; } // 对应设备
public Guid ProtectionDeviceInfoId { get; set; } // 对应保护装置
public string ISMS_DeviceId { get; set; } // ISMS设备ID
public string ISMS_DeviceDZId { get; set; } // 定值ID
// 导航属性
public virtual EquipmentInfo EquipmentInfo { get; set; }
public virtual ProtectionDeviceInfo ProtectionDeviceInfo { get; set; }
}
```
#### 供电线路管理 (PowerSupplyLine)
**核心功能:**
- 供电线路档案管理
- 线路参数配置
- 线路拓扑关系
- 线路状态监控
#### 二次回路信息 (SecondaryCircuitInfo)
**核心功能:**
- 二次回路图纸管理
- 回路连接关系
- 回路状态分析
- 回路故障诊断
#### 设备位置管理 (EquipmentLocation)
**核心功能:**
- 设备物理位置管理
- 位置坐标定位
- 位置可视化展示
- 位置变更记录
#### 设备视点管理 (EquipmentViewPoint)
**核心功能:**
- 设备监控视点配置
- 摄像头关联管理
- 视点切换控制
- 视点状态监控
#### 主站信息管理 (MasterStation)
**核心功能:**
- 主站系统信息管理
- 主站通信配置
- 主站状态监控
- 主站服务管理
#### 数据集成特性
**ISMS系统集成:**
- 保护装置数据同步
- 设备状态实时更新
- 保护动作记录同步
- 定值管理集成
**数据一致性:**
- 跨模块数据关联
- 数据完整性约束
- 数据变更追踪
- 数据同步机制
**批量操作支持:**
- 批量导入设备信息
- 批量更新设备参数
- 批量应用模板配置
- 批量状态变更
### 视频监控 (VideoSurveillance)
提供视频监控和智能巡检功能是SOMS系统的重要组成部分
#### 视频设备管理 (VideoDev)
**服务类**: `VideoDevAppService`, `VideoElectronicFenceAppService`
**接口**: `IVideoDevAppService`
**核心功能:**
- 摄像头设备配置管理
- 电子围栏监控和报警
- 设备权限控制
- 设备状态监控
- 配置信息同步
**数据模型:**
```csharp
public class VideoDev : SOMSAuditedEntity, ISOMSPassivable
{
public int? SeqNo { get; set; } // 序号
public string Name { get; set; } // 设备名称
public string Ip { get; set; } // 设备IP地址
public int? Port { get; set; } // 端口号
public string DevUserName { get; set; } // 设备用户名
public string DevPassword { get; set; } // 设备密码
public int? ChannelNo { get; set; } // 通道号
public VideoDevTypeEnum VideoDevType { get; set; } // 设备类型
public string InstallationArea { get; set; } // 安装区域
public string PostionDescription { get; set; } // 位置描述
public Guid? VideoDevId { get; set; } // 父设备IDNVR
public Guid? LinkVideoDevId { get; set; } // 关联设备ID
public Guid? MasterStationId { get; set; } // 主站ID
public CtrAuPosEnum? CtrAuPos { get; set; } // 控制权位置
public Guid? TransformerSubstationId { get; set; } // 所属变电站
// 导航属性
public virtual VideoDev Parent { get; set; } // NVR信息
public virtual VideoDev LinkVideoDev { get; set; } // 关联相机
public virtual TransformerSubstation TransformerSubstation { get; set; }
public virtual IEnumerable<PresetPoint> PresetPoints { get; set; }
}
```
**设备类型:**
- **NVR**: 网络视频录像机
- **DVR**: 数字视频录像机
- **Camera**: 网络摄像机
- **PTZ**: 云台摄像机
**电子围栏功能:**
```csharp
[HttpPost, ShowApi, AllowAnonymous]
public RequestEasyResult UploadCfg([FromBody] Dictionary<string,List<int>> request)
[HttpGet, ShowApi, AllowAnonymous]
public async Task<RequestEasyResult> UploadAlarmMsg([FromQuery] string id, [FromQuery]string? content)
```
**特殊功能:**
- 配置信息批量上传
- 报警信息实时上传
- Redis缓存报警数据
- 自动关联预置点
#### 预置点管理 (PresetPoint)
**服务类**: `PresetPointAppService`
**接口**: `IPresetPointAppService`
**核心功能:**
- 摄像头预置位配置
- 巡检路径规划
- 设备视点关联
- 自动巡航控制
**数据模型:**
```csharp
public class PresetPoint : SOMSAuditedEntity, ISOMSPassivable
{
public int Number { get; set; } // 预置点号
public string Name { get; set; } // 预置点名称
public string Remark { get; set; } // 备注
public Guid? VideoDevId { get; set; } // 所属摄像头
public Guid? EquipmentViewPointId { get; set; } // 设备视口
public Guid? EquipmentTypeId { get; set; } // 设备类型
public Guid? EquipmentInfoId { get; set; } // 关联设备
// 导航属性
public virtual VideoDev VideoDev { get; set; }
public virtual EquipmentViewPoint EquipmentViewPoint { get; set; }
public virtual EquipmentType EquipmentType { get; set; }
public virtual EquipmentInfo EquipmentInfo { get; set; }
public virtual IEnumerable<InspectionItem> InspectionItems { get; set; }
public virtual IEnumerable<MeasureTemperaturePoint> MeasureTemperaturePoints { get; set; }
}
```
**预置点功能:**
- 预置位精确定位
- 设备关联映射
- 巡检路径优化
- 视点状态监控
#### 巡检管理系统
##### 巡检卡片管理 (InspectionCard)
**服务类**: `InspectionCardAppService`
**接口**: `IInspectionCardAppService`
**核心功能:**
- 巡检任务单管理
- 巡检流程配置
- 主站任务下发
- 临时巡检支持
**数据模型:**
```csharp
public class InspectionCard : SOMSAuditedEntity, ISOMSPassivable
{
public string Code { get; set; } // 巡检记录单编号
public string CardName { get; set; } // 任务单名称
public string Remark { get; set; } // 备注
public bool IsIssue { get; set; } // 是否主站下发
public bool IsTemporary { get; set; } // 是否临时任务
public bool OpenWiper { get; set; } // 是否打开雨刷
public int ResidenceTime { get; set; } // 停留时间
public StationLevelEnum? CenterType { get; set; } // 发送者站级别
public Guid? MasterStationId { get; set; } // 主站ID
public Guid? TransformerSubstationId { get; set; } // 所属变电站
// 导航属性
public virtual MasterStation MasterStation { get; set; }
public virtual TransformerSubstation TransformerSubstation { get; set; }
public virtual IEnumerable<InspectionItem> InspectionItems { get; set; }
public virtual IEnumerable<InspectionPlanTask> InspectionPlanTasks { get; set; }
}
```
**巡检任务特性:**
- 支持主站下发任务
- 临时巡检任务支持
- 雨刷控制功能
- 停留时间配置
##### 巡检项目管理 (InspectionItem)
**服务类**: `InspectionItemAppService`
**接口**: `IInspectionItemAppService`
**核心功能:**
- 巡检点位配置
- 巡检动作定义
- 设备关联管理
- 执行流程控制
**数据模型:**
```csharp
public class InspectionItem : SOMSAuditedEntity, ISOMSPassivable
{
public int SeqNo { get; set; } // 序号
public string Name { get; set; } // 巡检项名称
public ProcessActionEnum ProcessAction { get; set; } // 处理动作
public int ResidenceTime { get; set; } // 停留时间
public int PictureNum { get; set; } // 拍照数量
public Guid? InspectionCardId { get; set; } // 所属任务单
public Guid? VideoDevId { get; set; } // 所属摄像头
public Guid? PresetPointId { get; set; } // 所属预置点
// 导航属性
public virtual InspectionCard InspectionCard { get; set; }
public virtual VideoDev VideoDev { get; set; }
public virtual PresetPoint PresetPoint { get; set; }
}
public enum ProcessActionEnum
{
[Description("无活动")]
None = 0,
[Description("仅拍照")]
Photograph = 1,
[Description("测温及拍照")]
MeasureTemperature = 2,
}
```
**巡检动作类型:**
- **无活动**: 仅移动到预置点
- **仅拍照**: 拍照记录
- **测温及拍照**: 红外测温和拍照
##### 巡检计划任务 (InspectionPlanTask)
**服务类**: `InspectionPlanTaskAppService`
**接口**: `IInspectionPlanTaskAppService`
**核心功能:**
- 巡检计划调度
- 定时任务管理
- 周期性巡检
- 执行时间控制
**数据模型:**
```csharp
public class InspectionPlanTask : SOMSAuditedEntity, ISOMSPassivable
{
public int SeqNo { get; set; } // 序号
public string PlanTaskName { get; set; } // 任务项名称
public WeekEnum? ExecutionWeek { get; set; } // 执行周
public string ExecutionDate { get; set; } // 执行日期
public string ExecutionTime { get; set; } // 执行时间
public string Remark { get; set; } // 备注
public Guid? InspectionCardId { get; set; } // 所属任务单
// 导航属性
public virtual InspectionCard InspectionCard { get; set; }
}
```
**调度功能:**
- 按周期执行(每日、每周、每月)
- 精确时间控制
- 任务状态跟踪
- 执行结果记录
#### 红外测温管理 (MeasureTemperaturePoint)
**服务类**: `MeasureTemperaturePointAppService`
**接口**: `IMeasureTemperaturePointAppService`
**核心功能:**
- 红外测温点配置
- 温度监控和报警
- 测温区域定义
- 遥测数据关联
**数据模型:**
```csharp
public class MeasureTemperaturePoint : SOMSAuditedEntity, ISOMSPassivable
{
public int Number { get; set; } // 测温点号
public string Name { get; set; } // 测温点名称
public MeasureTemperatureTypeEnum MeasureTemperatureType { get; set; } // 测温类型
public string CoordinateJsonStr { get; set; } // 测温区域坐标
public Guid? TelemeteringConfigurationId { get; set; } // 关联遥测点
public float? Emissivity { get; set; } // 发射率
public float? Distance { get; set; } // 距离
public float? ReflectedTemperature { get; set; } // 反射温度
public Guid? PresetPointId { get; set; } // 关联预置点
public Guid? EquipmentTypeId { get; set; } // 设备类型
public Guid? EquipmentInfoId { get; set; } // 关联设备
// 导航属性
public virtual PresetPoint PresetPoint { get; set; }
public virtual EquipmentType EquipmentType { get; set; }
public virtual EquipmentInfo EquipmentInfo { get; set; }
public virtual TelemeteringConfiguration TelemeteringConfiguration { get; set; }
}
public enum MeasureTemperatureTypeEnum
{
[Description("点")]
Point = 1,
[Description("线")]
Line = 2,
[Description("区域")]
Area = 3
}
```
**测温功能:**
- **点测温**: 单点温度测量
- **线测温**: 线性区域温度测量
- **区域测温**: 面积区域温度测量
**测温参数:**
- **发射率**: 材料发射率设置
- **距离**: 测温距离补偿
- **反射温度**: 环境反射温度
- **坐标定义**: JSON格式区域坐标
#### 摄像机权限管理 (CameraAuthentication)
**服务类**: `CameraAuthenticationAppService`
**接口**: `ICameraAuthenticationAppService`
**核心功能:**
- 摄像机访问权限控制
- 用户权限分配
- 权限时效管理
- 权限状态监控
#### 照明控制 (LightingControl)
**服务类**: `LightingControlAppService`
**接口**: `ILightingControlAppService`
**核心功能:**
- 照明设备控制
- 亮度调节
- 定时开关控制
- 照明状态监控
#### 多维检测 (MultidimensionalCheck)
**服务类**: `MultidimensionalCheckAppService`
**接口**: `IMultidimensionalCheckAppService`
**核心功能:**
- 多维度数据检测
- 综合状态分析
- 异常模式识别
- 检测结果评估
#### 多维检测调度 (MultidimensionalCheckSchedule)
**服务类**: `MultidimensionalCheckScheduleAppService`
**接口**: `IMultidimensionalCheckScheduleAppService`
**核心功能:**
- 检测任务调度
- 定时检测计划
- 检测流程管理
- 调度状态监控
#### 模式识别 (PatternRecognition)
**服务类**: `PatternRecognitionAppService`
**接口**: `IPatternRecognitionAppService`
**核心功能:**
- 图像模式识别
- 异常检测算法
- 智能分析引擎
- 识别结果处理
**识别类型:**
- 设备状态识别
- 异常情况检测
- 人员行为分析
- 环境变化监测
#### 视频设备与设备信息关联 (VideoDevEquipmentInfo)
**服务类**: `VideoDevEquipmentInfoAppService`
**接口**: `IVideoDevEquipmentInfoAppService`
**核心功能:**
- 视频设备与监控设备关联
- 关联关系管理
- 数据同步维护
- 关联状态监控
#### 巡检实时数据 (InspectionLiveData)
**服务类**: `InspectionLiveDataAppService`
**接口**: `IInspectionLiveDataAppService`
**核心功能:**
- 巡检过程实时数据
- 巡检状态监控
- 实时结果反馈
- 异常情况处理
#### 视频监控集成特性
**实时通信支持:**
- WebSocket实时视频流
- SignalR状态推送
- 实时报警通知
- 设备状态更新
**数据存储策略:**
- 配置数据SQL存储
- 巡检结果MongoDB存储
- 实时状态Redis缓存
- 图片文件系统存储
**外部系统集成:**
- 主站系统任务下发
- 第三方视频平台集成
- 报警系统联动
- 移动端应用支持
**智能化功能:**
- 自动巡检路径优化
- 智能异常检测
- 预测性维护建议
- 自适应参数调整
### 系统管理 (System)
提供系统级管理功能是SOMS系统的基础管理模块
#### 用户管理 (User)
**服务类**: `UserAppService`
**接口**: `IUserAppService`
**核心功能:**
- 用户账户全生命周期管理
- 用户权限分配和控制
- 密码策略和安全管理
- 用户状态监控
- 登录错误控制
**数据模型:**
```csharp
public class SysUser : SOMSAuditedEntity, ISOMSPassivable
{
public string UserName { get; set; } // 用户名
public string Name { get; set; } // 姓名
public string Surname { get; set; } // 姓氏
public string Password { get; set; } // 密码
public string EmailAddress { get; set; } // 邮箱地址
public int ErrorTimes { get; set; } // 连续错误登录次数
public DateTime? LastLoginErrorDate { get; set; } // 最后错误登录时间
public bool IsOnline { get; set; } // 是否在线
public int UserPriority { get; set; } // 用户优先级
public string OrganizationalUnit { get; set; } // 组织单位
public bool IsActive { get; set; } // 是否活动
}
```
**主要方法:**
```csharp
[HttpPost, Audited, Description("系统用户添加或修改")]
public async Task<RequestResult<UserOutput>> CreateOrUpdateAsync(EditUserInput input)
[HttpPost, Description("查询系统用户信息")]
public RequestPageResult<UserOutput> FindDatas(PageSearchCondition<UserSearchConditionInput> searchCondition)
[HttpGet, Audited, Description("删除系统用户单个信息")]
public async Task<RequestEasyResult> DeleteByIdAsync(Guid id)
```
**安全特性:**
- 密码复杂度验证
- 登录错误次数限制
- 账户锁定机制
- 在线状态跟踪
- 用户优先级控制
#### 角色管理 (Role)
**服务类**: `RoleAppService`
**接口**: `IRoleAppService`
**核心功能:**
- 角色定义和管理
- 权限配置和分配
- 角色继承关系
- 角色状态控制
**数据模型:**
```csharp
public class SysRole : SOMSAuditedEntity, ISOMSPassivable
{
public string RoleName { get; set; } // 角色名称
public string Remark { get; set; } // 备注
public bool IsActive { get; set; } // 是否活动
public const string AdminRole = "超级管理员"; // 管理员角色常量
}
```
**主要方法:**
```csharp
[HttpPost, Audited, Description("角色添加或修改")]
public async Task<RequestResult<RoleOutput>> CreateOrUpdateAsync(EditRoleInput input)
[HttpPost, Description("查询角色信息")]
public RequestPageResult<RoleOutput> FindDatas(PageSearchCondition<RoleSearchConditionInput> searchCondition)
[HttpGet, Audited, Description("删除角色单个信息")]
public async Task<RequestEasyResult> DeleteByIdAsync(Guid id)
```
**角色特性:**
- 超级管理员角色
- 角色权限继承
- 角色状态管理
- 角色关联用户管理
#### 功能管理 (Function)
**服务类**: `FunctionAppService`
**接口**: `IFunctionAppService`
**核心功能:**
- 系统功能模块管理
- 菜单结构维护
- 功能权限控制
- 访问控制配置
**数据模型:**
```csharp
public class SysFunction : SOMSAuditedEntity, ISOMSPassivable
{
public int SeqNo { get; set; } // 序号
public string Name { get; set; } // 功能名称
public string Code { get; set; } // 功能编码
public FunctionType Type { get; set; } // 功能类别
public string LoadUrl { get; set; } // 功能加载链接
public bool IsOperatorPage { get; set; } // 是否操作页面
public string Icon { get; set; } // 功能显示图标
public string Remark { get; set; } // 备注
public Guid? SysFunctionId { get; set; } // 父功能ID自关联
}
public enum FunctionType
{
[Description("浏览器端")]
Web = 0,
[Description("客户端")]
Client = 1,
[Description("运维客户端")]
MaintenanceSystemClient = 2,
}
```
**主要方法:**
```csharp
[HttpPost, Audited, Description("系统功能信息添加或删除")]
public async Task<RequestResult<FunctionOutput>> CreateOrUpdateAsync(EditFunctionInput input)
[HttpPost, Description("查询系统功能信息")]
public RequestPageResult<FunctionOutput> FindDatas(PageSearchCondition<FunctionSearchConditionInput> searchCondition)
[HttpGet, Audited, Description("删除系统功能单个信息")]
public async Task<RequestEasyResult> DeleteByIdAsync(Guid id)
```
**功能特性:**
- 层级结构管理
- 多端支持Web、客户端、运维客户端
- 图标和URL配置
- 操作页面标识
#### 角色用户关联 (RoleUser)
**服务类**: `RoleUserAppService`
**接口**: `IRoleUserAppService`
**核心功能:**
- 用户角色分配
- 角色用户关联管理
- 权限继承控制
**数据模型:**
```csharp
public class SysRoleUser : SOMSAuditedEntity, ISOMSPassivable
{
public Guid? SysUserId { get; set; } // 关联用户ID
public Guid? SysRoleId { get; set; } // 关联角色ID
public bool IsActive { get; set; } // 是否活动
// 导航属性
public SysUser SysUser { get; set; } // 关联用户
public SysRole SysRole { get; set; } // 关联角色
}
```
#### 角色功能关联 (RoleFunction)
**服务类**: `RoleFunctionAppService`
**接口**: `IRoleFunctionAppService`
**核心功能:**
- 角色功能权限分配
- 功能访问控制
- 编辑权限管理
**数据模型:**
```csharp
public class SysRoleFunction : SOMSAuditedEntity, ISOMSPassivable
{
public Guid? SysFunctionId { get; set; } // 关联功能ID
public Guid? SysRoleId { get; set; } // 关联角色ID
public bool IsEdit { get; set; } // 是否可编辑
public bool IsActive { get; set; } // 是否活动
// 导航属性
public SysFunction SysFunction { get; set; } // 关联功能
public SysRole SysRole { get; set; } // 关联角色
}
```
#### 配置管理
##### 系统配置 (Configuration)
**服务类**: `ConfigurationAppService`
**接口**: `IConfigurationAppService`
**核心功能:**
- 系统参数配置管理
- 变电站级别配置
- 配置类型分类管理
- 配置值动态获取
**主要方法:**
```csharp
[HttpGet, ShowApi, Description("获取系统配置")]
public RequestResult<SysConfigurationOutput> GetSysConfongiguration([FromQuery] string name, Guid stationId)
[HttpGet, ShowApi, Description("获取系统配置")]
public RequestResult<List<SysConfigurationOutput>> GetSysConfongigurations([FromQuery] string? name, Guid stationId, SysConfigurationTypeEnum? type, string? code)
[HttpPost, Audited, Description("系统配置添加或修改")]
public async Task<RequestResult<SysConfigurationOutput>> CreateOrUpdateAsync(EditSysConfigurationInput input)
```
**配置特性:**
- 变电站级别配置隔离
- 配置类型分类管理
- 配置代码标识
- 动态配置获取
##### 通信配置 (CommunicationConfiguration)
**服务类**: `CommunicationConfigurationService`
**接口**: `ICommunicationConfigurationService`
**核心功能:**
- 实时通信参数配置
- WebSocket和SignalR配置
- 故障转移策略配置
- 消息压缩和持久化配置
**配置继承机制:**
```
变电站特定配置 → 全局配置 → 系统默认值
```
**缓存策略:**
- MemoryCache本地缓存
- 配置更新自动清除缓存
- 缓存预热支持
- 滑动过期策略
**故障转移:**
- 基于配置的智能故障转移
- WebSocket和SignalR自动切换
- 可配置重试次数和策略
##### 全景配置 (PanoramaConfiguration)
**服务类**: `PanoramaConfigurationAppService`
**接口**: `IPanoramaConfigurationAppService`
**核心功能:**
- 全景图配置管理
- 全景场景管理
- 全景热点管理
- 数据库存储替代JSON文件
**数据模型:**
```csharp
public class PanoramaConfiguration : SOMSAuditedEntity, ISOMSPassivable
{
public string Name { get; set; } // 配置名称
public string Description { get; set; } // 配置描述
public Guid? TransformerSubstationId { get; set; } // 所属变电站
// 导航属性
public virtual IEnumerable<PanoramaScene> PanoramaScenes { get; set; }
}
public class PanoramaScene : SOMSAuditedEntity, ISOMSPassivable
{
public string SceneName { get; set; } // 场景名称
public string ImageUrl { get; set; } // 图片URL
public Guid PanoramaConfigurationId { get; set; } // 所属配置
// 导航属性
public virtual IEnumerable<PanoramaHotSpot> PanoramaHotSpots { get; set; }
}
public class PanoramaHotSpot : SOMSAuditedEntity, ISOMSPassivable
{
public string HotSpotName { get; set; } // 热点名称
public string HotSpotType { get; set; } // 热点类型
public string Position { get; set; } // 位置坐标
public string TargetScene { get; set; } // 目标场景
public Guid PanoramaSceneId { get; set; } // 所属场景
}
```
**重构特性:**
- 从JSON文件迁移到数据库
- 更好的数据管理和并发控制
- 支持数据关联和查询
- 提供标准CRUD操作
##### URL配置 (AppUrlConfiguration)
**服务类**: `AppUrlConfigurationService`
**接口**: `IAppUrlConfigurationService`
**核心功能:**
- 应用URL地址配置
- 服务端点管理
- URL自动发现
- 配置动态更新
#### 权限控制体系
**RBAC模型:**
```
用户 (User) → 角色 (Role) → 功能 (Function)
↓ ↓ ↓
SysUser → SysRoleUser → SysRoleFunction
```
**权限验证流程:**
1. 用户登录验证
2. 获取用户角色列表
3. 获取角色功能权限
4. 验证功能访问权限
5. 检查编辑权限
**权限特性:**
- 基于角色的访问控制
- 功能级权限控制
- 编辑权限细分
- 权限继承机制
- 动态权限验证
#### 系统管理集成特性
**审计日志:**
- 所有管理操作自动记录
- 用户操作轨迹跟踪
- 权限变更记录
- 配置修改历史
**数据一致性:**
- 外键约束保证数据完整性
- 级联删除控制
- 数据变更事务管理
- 并发控制机制
**扩展性设计:**
- 接口驱动架构
- 模块化服务设计
- 配置项动态扩展
- 多租户支持预留
### 移动监控 (MobileSurveillance)
机器人巡检和移动监控系统,提供智能化巡检解决方案:
#### 机器人管理 (RobotInfo)
**服务类**: `RobotInfoAppService`
**接口**: `IRobotInfoAppService`
**核心功能:**
- 机器人档案全生命周期管理
- 机器人状态实时监控
- 通信参数配置
- 摄像头设备关联
- 机器人类型管理
**数据模型:**
```csharp
public class RobotInfo : SOMSAuditedEntity, ISOMSPassivable
{
public int? SeqNo { get; set; } // 序号
public string Name { get; set; } // 机器人名称
public string Code { get; set; } // 机器人编码(通讯用)
public RobotTypeEnum? RobotType { get; set; } // 机器人类型
public string IP { get; set; } // IP地址
public int? Port { get; set; } // 端口号
public string Url { get; set; } // 通信URL
public Guid? GeneralCameraId { get; set; } // 普通摄像头
public Guid? InfraredCameraId { get; set; } // 红外摄像头
public Guid? ManufacturerInfoId { get; set; } // 生产商
public Guid? TransformerSubstationId { get; set; } // 所属变电站
public string Remark { get; set; } // 备注
// 导航属性
public virtual VideoDev GeneralCamera { get; set; } // 普通摄像头
public virtual VideoDev InfraredCamera { get; set; } // 红外摄像头
public virtual ManufacturerInfo ManufacturerInfo { get; set; }
public virtual TransformerSubstation TransformerSubstation { get; set; }
}
public enum RobotTypeEnum
{
[Description("轮式机器人")]
轮式机器人 = 10,
[Description("轨道式机器人")]
轨道式机器人 = 20,
[Description("其他")]
其他 = 999
}
public enum RobotManufacturerCodeEnum
{
DaLi = 1, // 大立
GuoZi = 2 // 国自
}
```
**主要方法:**
```csharp
[HttpPost, Audited, Description("机器人信息增加或修改")]
public async Task<RequestResult<RobotInfoOutput>> CreateOrUpdateAsync(EditRobotInfoInput input)
[HttpPost, Description("查询机器人信息")]
public RequestPageResult<RobotInfoOutput> FindDatas(PageSearchCondition<RobotInfoSearchConditionInput> searchCondition)
[HttpGet, Description("获取机器人类型下拉框数据")]
public RequestResult<List<SelectModelOutput>> FindRobotTypeForSelect()
[HttpGet, Description("获取机器人结构树")]
public RequestResult<List<TreeModelOutput>> GetRobotTreeNode(RobotInfoSearchConditionInput searchCondition)
[HttpGet, Description("根据机器人Id获取摄像头信息")]
public RequestResult<List<VideoCameraOuput>> GetCameraByRobotInfoId(Guid Id)
```
**特殊功能:**
- 机器人编码唯一性验证
- 双摄像头配置(普通+红外)
- HTTP通信方式支持
- 机器人树形结构展示
- 巡检报表目录管理
#### 机器人设备信息 (RobotDeviceInfo)
**服务类**: `RobotDeviceInfoAppService`
**接口**: `IRobotDeviceInfoAppService`
**核心功能:**
- 机器人设备点位管理
- 空轨设备关联
- 巡检主机服务配置
- 设备传感器管理
**数据模型:**
```csharp
public class RobotDeviceInfo : SOMSAuditedEntity, ISOMSPassivable
{
public int? SeqNo { get; set; } // 序号
public string DeviceId { get; set; } // 设备ID
public string DeviceName { get; set; } // 设备名称
public string DeviceType { get; set; } // 设备类型
public string DeviceStatus { get; set; } // 设备状态
public string CommunicationProtocol { get; set; } // 通信协议
public string ConfigurationParameters { get; set; } // 配置参数
public Guid? RobotInfoId { get; set; } // 关联机器人
public Guid? TransformerSubstationId { get; set; } // 所属变电站
// 导航属性
public virtual RobotInfo RobotInfo { get; set; }
public virtual TransformerSubstation TransformerSubstation { get; set; }
}
```
**设备管理特性:**
- 设备点位精确定位
- 多种通信协议支持
- 设备状态实时监控
- 配置参数动态管理
#### 机器人任务 (RobotTask)
**服务类**: `RobotTaskAppService`
**接口**: `IRobotTaskAppService`
**核心功能:**
- 机器人任务调度管理
- 巡检路径规划
- 任务执行监控
- 任务优先级控制
- 定期任务配置
**数据模型:**
```csharp
public class RobotTask : SOMSAuditedEntity, ISOMSPassivable
{
public string TaskName { get; set; } // 任务名称
public string TaskCode { get; set; } // 任务编码
public RobotActionEnum RobotAction { get; set; } // 机器人动作
public RobotTaskPriorityEnum Priority { get; set; } // 优先级
public DeviceLevelEnum DeviceLevel { get; set; } // 设备层级
public string DeviceList { get; set; } // 设备列表(逗号分隔)
public DateTime? FixedStartTime { get; set; } // 定期开始时间
public string WeekCycle { get; set; } // 周期(周)
public string DayCycle { get; set; } // 周期(日)
public string TimeCycle { get; set; } // 周期(时间)
public Guid? RobotInfoId { get; set; } // 关联机器人
public Guid? TransformerSubstationId { get; set; } // 所属变电站
// 导航属性
public virtual RobotInfo RobotInfo { get; set; }
public virtual TransformerSubstation TransformerSubstation { get; set; }
}
public enum RobotActionEnum
{
[Description("自主充电")]
自主充电 = 0,
[Description("定点巡检")]
定点巡检 = 1,
[Description("路径巡检")]
路径巡检 = 2,
[Description("返回充电桩")]
返回充电桩 = 3
}
public enum RobotTaskPriorityEnum
{
[Description("优先级1")]
优先级1 = 1,
[Description("优先级2")]
优先级2 = 2,
[Description("优先级3")]
优先级3 = 3,
[Description("优先级4")]
优先级4 = 4
}
public enum DeviceLevelEnum
{
[Description("间隔")]
间隔 = 1,
[Description("主设备")]
主设备 = 2,
[Description("设备点位")]
设备点位 = 3
}
```
**任务调度特性:**
- 多优先级任务队列
- 定时任务和周期任务
- 设备层级巡检
- 任务执行状态跟踪
- 自动充电管理
#### 机器人任务结果 (RobotTaskResult)
**服务类**: `RobotTaskResultAppService`
**接口**: `IRobotTaskResultAppService`
**核心功能:**
- 机器人巡检结果管理
- 任务执行状态记录
- 巡检数据分析
- 异常情况处理
#### 机器人任务项结果 (RobotTaskItemResult)
**服务类**: `RobotTaskItemResultAppService`
**接口**: `IRobotTaskItemResultAppService`
**核心功能:**
- 任务项级别结果记录
- 详细巡检数据管理
- 图片和视频文件管理
- 测温数据记录
**集成特性:**
- 与主站系统数据同步
- 自动上传巡检结果
- 延时处理机制
- 异常重试机制
### 运维管理 (MaintenanceAndOperations)
设备维护和运行操作管理系统:
#### 维护系统 (MaintenanceSystem)
**服务类**: `MaintenanceSystemInfoAppService`
**接口**: `IMaintenanceSystemInfoAppService`
**核心功能:**
- 维护系统信息管理
- 维护模块版本控制
- 维护计划制定
- 工单管理系统
- 备件库存管理
**数据模型:**
```csharp
public class MaintenanceSystemInfoOutput : Entity<Guid>
{
public string Name { get; set; } // 功能名称
public string Version { get; set; } // 版本号
public DateTime UpdateTime { get; set; } // 更新时间
public string Remark { get; set; } // 备注
}
```
**维护模块:**
- 定值管理模块
- 板卡诊断模块
- 智能报告模块
- 极性校验模块
- 后台服务
- 客户端
- 数据服务
**维护功能:**
- 设备维护计划制定
- 维护工单生成和跟踪
- 维护历史记录管理
- 备件需求分析
- 维护成本统计
#### 继电保护设置管理 (RelaySettingsManagement)
**服务类**: `RelaySettingAppService`
**接口**: `IRelaySettingAppService`
**核心功能:**
- 继电保护参数管理
- 保护定值配置
- 定值版本控制
- 定值下发和校验
- 保护动作分析
**保护定值管理:**
- 定值参数配置
- 定值文件管理
- 定值变更记录
- 定值校验功能
- 定值备份恢复
**版本控制:**
- 定值版本管理
- 变更历史追踪
- 版本比较功能
- 回滚操作支持
#### 二次设备管理 (SecondaryEquipment)
**服务类**: `SecondaryEquipmentAppService`
**接口**: `ISecondaryEquipmentAppService`
**核心功能:**
- 二次设备档案管理
- 设备接线图管理
- 设备试验记录
- 设备状态监控
- 设备维护记录
**二次回路管理:**
```csharp
public class SecondaryCircuitProtectionDevice : Entity<Guid>
{
public Guid SecondaryCircuitId { get; set; } // 二次回路ID
public Guid ProtectionDeviceId { get; set; } // 保护装置ID
public string Remark { get; set; } // 备注
public bool IsActive { get; set; } // 是否在用
// 导航属性
public virtual SecondaryCircuit SecondaryCircuit { get; set; }
public virtual ProtectionDeviceInfo ProtectionDevice { get; set; }
}
```
**设备管理特性:**
- 二次设备分类管理
- 设备技术参数记录
- 设备运行状态监控
- 设备维护计划
- 设备故障诊断
#### 运维集成特性
**ISMS系统集成:**
- 与ISMS保护装置数据同步
- 保护动作记录同步
- 定值管理集成
- 设备状态实时更新
**数据管理:**
- 运维数据统一管理
- 历史数据归档
- 数据分析和报表
- 数据备份和恢复
**移动端支持:**
- 移动运维应用
- 现场数据采集
- 实时状态查询
- 移动工单处理
**智能化功能:**
- 预测性维护
- 智能故障诊断
- 维护计划优化
- 成本效益分析
## 技术栈
### 核心框架
- **ABP Framework**: 应用框架基础
- **ASP.NET Core**: Web API框架
- **Entity Framework Core**: ORM数据访问
- **AutoMapper**: 对象映射
### 数据存储
- **SQL Server**: 关系型数据库
- **MongoDB**: 文档数据库
- **Redis**: 内存缓存
### 通信技术
- **SignalR**: 实时通信
- **WebSocket**: 双向通信
- **RESTful API**: HTTP接口
### 开发工具
- **Dependency Injection**: 依赖注入
- **Serilog**: 结构化日志
- **Swagger**: API文档
- **JWT**: 身份认证
## 开发指南
### 创建新的应用服务
1. **定义接口**
```csharp
public interface IMyAppService : IAppServiceBase<MySearchInput, MyOutput, MyEditInput, Guid>
{
// 自定义方法
Task<RequestResult<MyCustomOutput>> CustomMethodAsync(MyCustomInput input);
}
```
2. **实现服务类**
```csharp
[Description("我的应用服务")]
public class MyAppService : SOMSAppServiceBase, IMyAppService
{
private readonly IRepository<MyEntity, Guid> _repository;
public MyAppService(
ISessionAppService sessionAppService,
IRepository<MyEntity, Guid> repository)
: base(sessionAppService)
{
_repository = repository;
}
[HttpPost, Audited, Description("创建或更新")]
public async Task<RequestResult<MyOutput>> CreateOrUpdateAsync(MyEditInput input)
{
// 实现业务逻辑
}
}
```
3. **注册服务**
```csharp
// 在模块的Initialize方法中自动注册
IocManager.RegisterAssemblyByConvention(assembly);
```
### 数据传输对象(DTO)设计
```csharp
// 搜索条件
public class MySearchInput
{
public string Name { get; set; }
public Guid? CategoryId { get; set; }
public DateTime? StartDate { get; set; }
}
// 输出对象
public class MyOutput : EntityDto<Guid>
{
public string Name { get; set; }
public string Description { get; set; }
public DateTime CreationTime { get; set; }
}
// 编辑输入
public class MyEditInput : EntityDto<Guid?>
{
[Required]
public string Name { get; set; }
public string Description { get; set; }
}
```
### 权限控制
```csharp
[AbpAuthorize("MyPermission")]
public async Task<RequestResult<MyOutput>> SecureMethodAsync(MyInput input)
{
// 需要特定权限才能访问
}
[AbpAllowAnonymous]
public RequestResult<List<MyOutput>> PublicMethodAsync()
{
// 允许匿名访问
}
```
### 审计日志
```csharp
[Audited]
[Description("重要操作")]
public async Task<RequestEasyResult> ImportantOperationAsync(MyInput input)
{
// 操作会被自动记录到审计日志
}
```
### 缓存使用
```csharp
public class MyAppService : SOMSAppServiceBase
{
private readonly IRedisRepository<MyData, string> _redisRepository;
public async Task<MyData> GetCachedDataAsync(string key)
{
return await _redisRepository.GetAsync(key);
}
public async Task SetCachedDataAsync(string key, MyData data)
{
await _redisRepository.SetAsync(key, data, TimeSpan.FromMinutes(30));
}
}
```
## API文档
### 标准API响应格式
YunDa.SOMS.Application 采用统一的API响应格式确保前端和客户端的一致性处理。
#### 成功响应 (RequestResult<T>)
```json
{
"flag": true,
"message": "操作成功",
"resultData": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "示例设备",
"code": "DEV001",
"creationTime": "2024-01-15T10:30:00Z"
}
}
```
#### 分页响应 (RequestPageResult<T>)
```json
{
"flag": true,
"message": "查询成功",
"resultData": [
{
"id": "550e8400-e29b-41d4-a716-446655440000",
"name": "设备1",
"code": "DEV001"
},
{
"id": "550e8400-e29b-41d4-a716-446655440001",
"name": "设备2",
"code": "DEV002"
}
],
"totalCount": 150,
"pageIndex": 1,
"pageSize": 20
}
```
#### 简单响应 (RequestEasyResult)
```json
{
"flag": true,
"message": "删除成功"
}
```
#### 错误响应
```json
{
"flag": false,
"message": "设备编码已存在,请使用其他编码",
"resultData": null
}
```
### API端点规范
#### URL命名规范
```
/api/SOMS/{ModuleName}/{Action}
```
**示例:**
- `/api/SOMS/EquipmentInfo/FindDatas` - 查询设备信息
- `/api/SOMS/TelemeteringConfiguration/CreateOrUpdate` - 创建或更新遥测配置
- `/api/SOMS/VideoDev/DeleteById` - 删除视频设备
#### HTTP方法使用
- **GET**: 查询单个资源、获取下拉框数据、获取配置信息
- **POST**: 查询列表数据、创建或更新资源、复杂查询操作
- **DELETE**: 删除资源较少使用多数使用POST方式
### 核心API端点
#### 数据监控模块
##### 遥测配置管理
```http
# 查询遥测配置
POST /api/SOMS/TelemeteringConfiguration/FindDatas
Content-Type: application/json
{
"pageIndex": 1,
"pageSize": 20,
"searchCondition": {
"name": "电压",
"equipmentInfoId": "550e8400-e29b-41d4-a716-446655440000",
"transformerSubstationId": "550e8400-e29b-41d4-a716-446655440001"
}
}
# 创建或更新遥测配置
POST /api/SOMS/TelemeteringConfiguration/CreateOrUpdate
Content-Type: application/json
{
"id": null,
"name": "A相电压",
"unit": "kV",
"coefficient": 1.0,
"decimalDigits": 2,
"infoAddress": 1001,
"deviceAddress": 1,
"dispatcherAddress": 1001,
"equipmentInfoId": "550e8400-e29b-41d4-a716-446655440000",
"transformerSubstationId": "550e8400-e29b-41d4-a716-446655440001"
}
# 获取环境温度
GET /api/SOMS/TelemeteringConfiguration/GetEnvironmentTempValue?transubstationId=550e8400-e29b-41d4-a716-446655440001
```
##### 遥信配置管理
```http
# 查询遥信配置
POST /api/SOMS/TelesignalisationConfiguration/FindDatas
Content-Type: application/json
{
"pageIndex": 1,
"pageSize": 20,
"searchCondition": {
"name": "开关",
"equipmentTypeId": "550e8400-e29b-41d4-a716-446655440002"
}
}
# 获取遥信下拉框数据
GET /api/SOMS/TelesignalisationConfiguration/FindTelesignalisationConfigurationForSelect?transformerSubstationId=550e8400-e29b-41d4-a716-446655440001
```
##### 遥控配置管理
```http
# 创建或更新遥控配置
POST /api/SOMS/TelecommandConfiguration/CreateOrUpdate
Content-Type: application/json
{
"id": null,
"name": "断路器分闸",
"remoteType": 1,
"infoAddress": 2001,
"deviceAddress": 1,
"dispatcherAddress": 2001,
"relatedTelesignalisationId": "550e8400-e29b-41d4-a716-446655440003",
"equipmentInfoId": "550e8400-e29b-41d4-a716-446655440000"
}
```
#### 综合信息管理模块
##### 设备信息管理
```http
# 查询设备信息
POST /api/SOMS/EquipmentInfo/FindDatas
Content-Type: application/json
{
"pageIndex": 1,
"pageSize": 20,
"searchCondition": {
"name": "变压器",
"equipmentTypeId": "550e8400-e29b-41d4-a716-446655440004",
"transformerSubstationId": "550e8400-e29b-41d4-a716-446655440001"
}
}
# 创建或更新设备信息
POST /api/SOMS/EquipmentInfo/CreateOrUpdate
Content-Type: application/json
{
"id": null,
"name": "主变压器T1",
"code": "T1",
"equipmentTypeId": "550e8400-e29b-41d4-a716-446655440004",
"manufacturerInfoId": "550e8400-e29b-41d4-a716-446655440005",
"transformerSubstationId": "550e8400-e29b-41d4-a716-446655440001",
"isRemoteControl": true,
"safetyStateType": 1
}
# 刷新安全状态
GET /api/SOMS/EquipmentInfo/FreshSafetyState
# 同步模板配置
POST /api/SOMS/EquipmentInfo/SyncTeleTemplate
```
##### 变电站管理
```http
# 查询变电站信息
POST /api/SOMS/TransformerSubstation/FindDatas
Content-Type: application/json
{
"pageIndex": 1,
"pageSize": 20,
"searchCondition": {
"substationName": "220kV"
}
}
# 创建或更新变电站
POST /api/SOMS/TransformerSubstation/CreateOrUpdate
Content-Type: application/json
{
"id": null,
"substationName": "220kV东郊变电站",
"commMgrIP": "192.168.1.100",
"longitude": 116.407526,
"latitude": 39.904030,
"masterStationAddress": "http://192.168.1.200:8080"
}
```
#### 视频监控模块
##### 视频设备管理
```http
# 查询视频设备
POST /api/SOMS/VideoDev/FindDatas
Content-Type: application/json
{
"pageIndex": 1,
"pageSize": 20,
"searchCondition": {
"name": "球机",
"videoDevType": 3,
"transformerSubstationId": "550e8400-e29b-41d4-a716-446655440001"
}
}
# 创建或更新视频设备
POST /api/SOMS/VideoDev/CreateOrUpdate
Content-Type: application/json
{
"id": null,
"name": "主控室球机",
"ip": "192.168.1.101",
"port": 8000,
"devUserName": "admin",
"devPassword": "admin123",
"channelNo": 1,
"videoDevType": 3,
"installationArea": "主控室",
"transformerSubstationId": "550e8400-e29b-41d4-a716-446655440001"
}
```
##### 预置点管理
```http
# 查询预置点
POST /api/SOMS/PresetPoint/FindDatas
Content-Type: application/json
{
"pageIndex": 1,
"pageSize": 20,
"searchCondition": {
"videoDevId": "550e8400-e29b-41d4-a716-446655440006"
}
}
# 创建或更新预置点
POST /api/SOMS/PresetPoint/CreateOrUpdate
Content-Type: application/json
{
"id": null,
"number": 1,
"name": "主变压器监控点",
"videoDevId": "550e8400-e29b-41d4-a716-446655440006",
"equipmentInfoId": "550e8400-e29b-41d4-a716-446655440000"
}
```
##### 巡检管理
```http
# 查询巡检任务单
POST /api/SOMS/InspectionCard/FindDatas
Content-Type: application/json
{
"pageIndex": 1,
"pageSize": 20,
"searchCondition": {
"cardName": "日常巡检",
"transformerSubstationId": "550e8400-e29b-41d4-a716-446655440001"
}
}
# 查询巡检计划任务
POST /api/SOMS/InspectionPlanTask/FindDatas
Content-Type: application/json
{
"pageIndex": 1,
"pageSize": 20,
"searchCondition": {
"inspectionCardId": "550e8400-e29b-41d4-a716-446655440007"
}
}
```
#### 系统管理模块
##### 用户管理
```http
# 查询用户信息
POST /api/SOMS/User/FindDatas
Content-Type: application/json
{
"pageIndex": 1,
"pageSize": 20,
"searchCondition": {
"userName": "admin",
"name": "管理员"
}
}
# 创建或更新用户
POST /api/SOMS/User/CreateOrUpdate
Content-Type: application/json
{
"id": null,
"userName": "operator01",
"name": "操作员1",
"surname": "张",
"password": "Password123!",
"emailAddress": "operator01@company.com",
"userPriority": 2,
"organizationalUnit": "运维部"
}
```
##### 角色管理
```http
# 查询角色信息
POST /api/SOMS/Role/FindDatas
Content-Type: application/json
{
"pageIndex": 1,
"pageSize": 20,
"searchCondition": {
"roleName": "操作员"
}
}
# 创建或更新角色
POST /api/SOMS/Role/CreateOrUpdate
Content-Type: application/json
{
"id": null,
"roleName": "高级操作员",
"remark": "具有高级操作权限的操作员角色"
}
```
#### 移动监控模块
##### 机器人管理
```http
# 查询机器人信息
POST /api/SOMS/RobotInfo/FindDatas
Content-Type: application/json
{
"pageIndex": 1,
"pageSize": 20,
"searchCondition": {
"name": "巡检机器人",
"robotType": 10,
"transformerSubstationId": "550e8400-e29b-41d4-a716-446655440001"
}
}
# 创建或更新机器人
POST /api/SOMS/RobotInfo/CreateOrUpdate
Content-Type: application/json
{
"id": null,
"name": "轮式巡检机器人R1",
"code": "ROBOT001",
"robotType": 10,
"ip": "192.168.1.150",
"port": 8080,
"url": "http://192.168.1.150:8080/api",
"transformerSubstationId": "550e8400-e29b-41d4-a716-446655440001"
}
# 获取机器人类型下拉框
GET /api/SOMS/RobotInfo/FindRobotTypeForSelect
# 获取机器人结构树
GET /api/SOMS/RobotInfo/GetRobotTreeNode?transformerSubstationId=550e8400-e29b-41d4-a716-446655440001
```
### API认证和授权
#### JWT Token认证
```http
# 用户登录
POST /api/TokenAuth/Authenticate
Content-Type: application/json
{
"userName": "admin",
"password": "admin123"
}
# 响应
{
"flag": true,
"message": "登录成功!",
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"encryptedAccessToken": "encrypted_token_string",
"expireInSeconds": 2147483647,
"userId": "550e8400-e29b-41d4-a716-446655440000"
}
```
#### API调用示例
```http
# 使用Token调用API
POST /api/SOMS/EquipmentInfo/FindDatas
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Content-Type: application/json
{
"pageIndex": 1,
"pageSize": 20,
"searchCondition": {}
}
```
### 错误处理
#### 常见错误码
- **400 Bad Request**: 请求参数错误
- **401 Unauthorized**: 未授权访问
- **403 Forbidden**: 权限不足
- **404 Not Found**: 资源不存在
- **500 Internal Server Error**: 服务器内部错误
#### 错误响应示例
```json
{
"flag": false,
"message": "设备编码不能为空",
"resultData": null,
"errorCode": "VALIDATION_ERROR",
"details": [
{
"field": "code",
"message": "设备编码是必填字段"
}
]
}
```
## 最佳实践
### 1. 服务设计原则
#### SOLID原则应用
**单一职责原则 (SRP)**
```csharp
// ✅ 好的做法:专注于设备信息管理
public class EquipmentInfoAppService : SOMSAppServiceBase, IEquipmentInfoAppService
{
// 只处理设备信息相关的业务逻辑
public async Task<RequestResult<EquipmentInfoOutput>> CreateOrUpdateAsync(EditEquipmentInfoInput input)
public RequestPageResult<EquipmentInfoOutput> FindDatas(PageSearchCondition<EquipmentInfoSearchConditionInput> searchCondition)
}
// ❌ 避免:在一个服务中处理多种不相关的业务
public class MixedAppService : SOMSAppServiceBase
{
// 不要在同一个服务中混合设备管理、用户管理、报警管理等
}
```
**接口隔离原则 (ISP)**
```csharp
// ✅ 好的做法:细分接口
public interface IEquipmentInfoQueryService
{
RequestPageResult<EquipmentInfoOutput> FindDatas(PageSearchCondition<EquipmentInfoSearchConditionInput> searchCondition);
RequestResult<EquipmentInfoOutput> GetById(Guid id);
}
public interface IEquipmentInfoCommandService
{
Task<RequestResult<EquipmentInfoOutput>> CreateOrUpdateAsync(EditEquipmentInfoInput input);
Task<RequestEasyResult> DeleteByIdAsync(Guid id);
}
```
**依赖倒置原则 (DIP)**
```csharp
// ✅ 好的做法:依赖抽象
public class TelemeteringConfigurationAppService : SOMSAppServiceBase
{
private readonly IRepository<TelemeteringConfiguration, Guid> _repository;
private readonly IRedisRepository<EnvironmentTempValue, string> _redisRepository;
public TelemeteringConfigurationAppService(
IRepository<TelemeteringConfiguration, Guid> repository,
IRedisRepository<EnvironmentTempValue, string> redisRepository)
{
_repository = repository;
_redisRepository = redisRepository;
}
}
```
### 2. 异常处理最佳实践
#### 统一异常处理模式
```csharp
public async Task<RequestResult<MyOutput>> MyMethodAsync(MyInput input)
{
var result = new RequestResult<MyOutput>();
try
{
// 1. 输入验证
if (input == null)
{
result.Flag = false;
result.Message = "输入参数不能为空";
return result;
}
// 2. 业务逻辑处理
var data = await ProcessBusinessLogicAsync(input);
// 3. 成功响应
result.Flag = true;
result.ResultData = data;
result.Message = "操作成功";
}
catch (BusinessException ex)
{
// 业务异常:返回友好错误信息
result.Flag = false;
result.Message = ex.Message;
Log4Helper.Warning(this.GetType(), "业务异常", ex);
}
catch (ValidationException ex)
{
// 验证异常:返回验证错误信息
result.Flag = false;
result.Message = "数据验证失败:" + ex.Message;
Log4Helper.Info(this.GetType(), "验证异常", ex);
}
catch (Exception ex)
{
// 系统异常:记录详细日志,返回通用错误信息
result.Flag = false;
result.Message = "系统异常,请联系管理员";
Log4Helper.Error(this.GetType(), "系统异常", ex);
}
return result;
}
```
#### 自定义业务异常
```csharp
public class EquipmentCodeDuplicateException : BusinessException
{
public EquipmentCodeDuplicateException(string code)
: base($"设备编码 '{code}' 已存在,请使用其他编码")
{
}
}
// 使用示例
if (await IsEquipmentCodeExistsAsync(input.Code))
{
throw new EquipmentCodeDuplicateException(input.Code);
}
```
### 3. 性能优化策略
#### 异步编程
```csharp
// ✅ 好的做法:使用异步方法
public async Task<RequestResult<List<EquipmentInfoOutput>>> GetEquipmentListAsync()
{
var equipments = await _equipmentRepository.GetAllListAsync();
var manufacturers = await _manufacturerRepository.GetAllListAsync();
// 并行处理
var tasks = equipments.Select(async equipment =>
{
var output = ObjectMapper.Map<EquipmentInfoOutput>(equipment);
output.ManufacturerName = manufacturers.FirstOrDefault(m => m.Id == equipment.ManufacturerInfoId)?.ManufacturerName;
return output;
});
var results = await Task.WhenAll(tasks);
return new RequestResult<List<EquipmentInfoOutput>> { Flag = true, ResultData = results.ToList() };
}
```
#### 缓存策略
```csharp
public class TelemeteringConfigurationAppService : SOMSAppServiceBase
{
private readonly IMemoryCache _memoryCache;
private readonly IRedisRepository<EnvironmentTempValue, string> _redisRepository;
public async Task<RequestResult<float>> GetEnvironmentTempValue(Guid? transubstationId)
{
// 1. 内存缓存
var cacheKey = $"env_temp_{transubstationId}";
if (_memoryCache.TryGetValue(cacheKey, out float cachedValue))
{
return new RequestResult<float> { Flag = true, ResultData = cachedValue };
}
// 2. Redis缓存
var redisKey = $"EnvironmentTempValue_{transubstationId}";
var redisValue = await _redisRepository.GetAsync(redisKey);
if (redisValue != null)
{
_memoryCache.Set(cacheKey, redisValue.Value, TimeSpan.FromMinutes(5));
return new RequestResult<float> { Flag = true, ResultData = redisValue.Value };
}
// 3. 数据库查询
var dbValue = await GetEnvironmentTempFromDatabaseAsync(transubstationId);
// 4. 更新缓存
await _redisRepository.SetAsync(redisKey, new EnvironmentTempValue { Value = dbValue }, TimeSpan.FromMinutes(30));
_memoryCache.Set(cacheKey, dbValue, TimeSpan.FromMinutes(5));
return new RequestResult<float> { Flag = true, ResultData = dbValue };
}
}
```
#### 分页查询优化
```csharp
public RequestPageResult<EquipmentInfoOutput> FindDatas(PageSearchCondition<EquipmentInfoSearchConditionInput> searchCondition)
{
var query = _equipmentRepository.GetAllIncluding(
e => e.EquipmentType,
e => e.ManufacturerInfo,
e => e.TransformerSubstation)
.WhereIf(!string.IsNullOrWhiteSpace(searchCondition.SearchCondition.Name),
e => e.Name.Contains(searchCondition.SearchCondition.Name))
.WhereIf(searchCondition.SearchCondition.EquipmentTypeId.HasValue,
e => e.EquipmentTypeId == searchCondition.SearchCondition.EquipmentTypeId)
.WhereIf(searchCondition.SearchCondition.TransformerSubstationId.HasValue,
e => e.TransformerSubstationId == searchCondition.SearchCondition.TransformerSubstationId);
// 先获取总数(避免加载所有数据)
var totalCount = query.Count();
// 分页查询
var pagedData = query
.OrderBy(e => e.SeqNo)
.ThenBy(e => e.Name)
.Skip((searchCondition.PageIndex - 1) * searchCondition.PageSize)
.Take(searchCondition.PageSize)
.ToList();
var result = ObjectMapper.Map<List<EquipmentInfoOutput>>(pagedData);
return new RequestPageResult<EquipmentInfoOutput>
{
Flag = true,
ResultData = result,
TotalCount = totalCount,
PageIndex = searchCondition.PageIndex,
PageSize = searchCondition.PageSize
};
}
```
### 4. 安全最佳实践
#### 输入验证
```csharp
[HttpPost, Audited, Description("设备信息增加或修改")]
public async Task<RequestResult<EquipmentInfoOutput>> CreateOrUpdateAsync(EditEquipmentInfoInput input)
{
// 1. 基础验证
if (input == null)
return new RequestResult<EquipmentInfoOutput> { Flag = false, Message = "输入参数不能为空" };
// 2. 业务规则验证
if (string.IsNullOrWhiteSpace(input.Name))
return new RequestResult<EquipmentInfoOutput> { Flag = false, Message = "设备名称不能为空" };
if (string.IsNullOrWhiteSpace(input.Code))
return new RequestResult<EquipmentInfoOutput> { Flag = false, Message = "设备编码不能为空" };
// 3. 数据格式验证
if (input.Code.Length > 50)
return new RequestResult<EquipmentInfoOutput> { Flag = false, Message = "设备编码长度不能超过50个字符" };
// 4. 业务唯一性验证
if (await IsEquipmentCodeDuplicateAsync(input.Code, input.Id))
return new RequestResult<EquipmentInfoOutput> { Flag = false, Message = "设备编码已存在" };
// 5. 权限验证(通过特性自动处理)
// [AbpAuthorize("Equipment.Create")] 或 [AbpAuthorize("Equipment.Update")]
return input.Id.HasValue ? await UpdateAsync(input) : await CreateAsync(input);
}
```
#### 权限控制
```csharp
// 方法级权限控制
[AbpAuthorize("Equipment.Create")]
public async Task<RequestResult<EquipmentInfoOutput>> CreateAsync(EditEquipmentInfoInput input)
[AbpAuthorize("Equipment.Update")]
public async Task<RequestResult<EquipmentInfoOutput>> UpdateAsync(EditEquipmentInfoInput input)
[AbpAuthorize("Equipment.Delete")]
public async Task<RequestEasyResult> DeleteByIdAsync(Guid id)
// 匿名访问(谨慎使用)
[AbpAllowAnonymous]
public RequestResult<List<SelectModelOutput>> GetEquipmentTypesForSelect()
```
#### SQL注入防护
```csharp
// ✅ 好的做法使用LINQ和参数化查询
var equipments = _equipmentRepository.GetAll()
.Where(e => e.Name.Contains(searchName))
.Where(e => e.TransformerSubstationId == stationId)
.ToList();
// ✅ 好的做法使用参数化原生SQL
var sql = "SELECT * FROM gi_equipment_info WHERE Name LIKE @name AND TransformerSubstationId = @stationId";
var parameters = new { name = $"%{searchName}%", stationId = stationId };
var result = await _repository.QueryAsync<EquipmentInfo>(sql, parameters);
// ❌ 避免字符串拼接SQL
var badSql = $"SELECT * FROM gi_equipment_info WHERE Name LIKE '%{searchName}%'"; // 存在SQL注入风险
```
### 5. 测试策略
#### 单元测试示例
```csharp
[Test]
public async Task CreateEquipmentInfo_WithValidInput_ShouldReturnSuccess()
{
// Arrange
var input = new EditEquipmentInfoInput
{
Name = "测试设备",
Code = "TEST001",
EquipmentTypeId = Guid.NewGuid(),
TransformerSubstationId = Guid.NewGuid()
};
var mockRepository = new Mock<IRepository<EquipmentInfo, Guid>>();
var mockSessionService = new Mock<ISessionAppService>();
var service = new EquipmentInfoAppService(mockRepository.Object, mockSessionService.Object);
// Act
var result = await service.CreateOrUpdateAsync(input);
// Assert
Assert.IsTrue(result.Flag);
Assert.IsNotNull(result.ResultData);
Assert.AreEqual("测试设备", result.ResultData.Name);
}
[Test]
public async Task CreateEquipmentInfo_WithDuplicateCode_ShouldReturnError()
{
// Arrange
var input = new EditEquipmentInfoInput
{
Name = "测试设备",
Code = "DUPLICATE001"
};
// 模拟编码重复
var mockRepository = new Mock<IRepository<EquipmentInfo, Guid>>();
mockRepository.Setup(r => r.FirstOrDefaultAsync(It.IsAny<Expression<Func<EquipmentInfo, bool>>>()))
.ReturnsAsync(new EquipmentInfo { Code = "DUPLICATE001" });
var service = new EquipmentInfoAppService(mockRepository.Object, Mock.Of<ISessionAppService>());
// Act
var result = await service.CreateOrUpdateAsync(input);
// Assert
Assert.IsFalse(result.Flag);
Assert.IsTrue(result.Message.Contains("编码已存在"));
}
```
#### 集成测试示例
```csharp
[Test]
public async Task EquipmentInfo_CRUD_Integration_Test()
{
// 使用真实数据库连接进行集成测试
using var scope = _serviceProvider.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<IEquipmentInfoAppService>();
// 1. 创建设备
var createInput = new EditEquipmentInfoInput
{
Name = "集成测试设备",
Code = "INTEGRATION001"
};
var createResult = await service.CreateOrUpdateAsync(createInput);
Assert.IsTrue(createResult.Flag);
var equipmentId = createResult.ResultData.Id;
// 2. 查询设备
var queryResult = service.FindDatas(new PageSearchCondition<EquipmentInfoSearchConditionInput>
{
SearchCondition = new EquipmentInfoSearchConditionInput { Name = "集成测试设备" },
PageIndex = 1,
PageSize = 10
});
Assert.IsTrue(queryResult.Flag);
Assert.AreEqual(1, queryResult.ResultData.Count);
// 3. 更新设备
var updateInput = new EditEquipmentInfoInput
{
Id = equipmentId,
Name = "更新后的设备名称",
Code = "INTEGRATION001"
};
var updateResult = await service.CreateOrUpdateAsync(updateInput);
Assert.IsTrue(updateResult.Flag);
Assert.AreEqual("更新后的设备名称", updateResult.ResultData.Name);
// 4. 删除设备
var deleteResult = await service.DeleteByIdAsync(equipmentId);
Assert.IsTrue(deleteResult.Flag);
}
```
### 6. 代码质量保证
#### 代码审查清单
- [ ] 是否遵循命名规范
- [ ] 是否有适当的异常处理
- [ ] 是否有输入验证
- [ ] 是否有权限控制
- [ ] 是否有日志记录
- [ ] 是否有单元测试
- [ ] 是否有性能考虑
- [ ] 是否有安全考虑
#### 性能监控
```csharp
public async Task<RequestResult<T>> MonitoredMethodAsync<T>(Func<Task<RequestResult<T>>> operation, string operationName)
{
var stopwatch = Stopwatch.StartNew();
try
{
var result = await operation();
stopwatch.Stop();
Log4Helper.Info(this.GetType(), $"{operationName} 执行完成,耗时: {stopwatch.ElapsedMilliseconds}ms");
if (stopwatch.ElapsedMilliseconds > 5000) // 超过5秒记录警告
{
Log4Helper.Warning(this.GetType(), $"{operationName} 执行时间过长: {stopwatch.ElapsedMilliseconds}ms");
}
return result;
}
catch (Exception ex)
{
stopwatch.Stop();
Log4Helper.Error(this.GetType(), $"{operationName} 执行失败,耗时: {stopwatch.ElapsedMilliseconds}ms", ex);
throw;
}
}
```
### 7. 部署和运维
#### 配置管理
```json
{
"ConnectionStrings": {
"Default": "Server=localhost;Database=SOMS;Trusted_Connection=true;",
"Redis": "localhost:6379",
"MongoDB": "mongodb://localhost:27017/SOMS"
},
"SysBaseConfig": {
"SysAttachmentFolder": "/app/data/attachments",
"MaxDataCount": 10000,
"MasterStationType": 1
},
"Logging": {
"LogLevel": {
"Default": "Information",
"YunDa.SOMS": "Debug"
}
}
}
```
#### 健康检查
```csharp
public class SOMSHealthCheck : IHealthCheck
{
private readonly IRepository<EquipmentInfo, Guid> _equipmentRepository;
private readonly IRedisRepository<string, string> _redisRepository;
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
// 检查数据库连接
await _equipmentRepository.CountAsync();
// 检查Redis连接
await _redisRepository.SetAsync("health_check", "ok", TimeSpan.FromMinutes(1));
return HealthCheckResult.Healthy("SOMS应用服务正常");
}
catch (Exception ex)
{
return HealthCheckResult.Unhealthy("SOMS应用服务异常", ex);
}
}
}
```
---
## 总结
YunDa.SOMS.Application 应用层是整个SOMS系统的核心业务逻辑层提供了完整的变电站运维管理功能。通过本文档开发人员可以
1. **理解系统架构**: 掌握应用层的整体设计和模块划分
2. **快速上手开发**: 了解开发规范和最佳实践
3. **正确使用API**: 掌握各模块的API接口和调用方法
4. **保证代码质量**: 遵循安全、性能和可维护性要求
### 技术特色
- **模块化设计**: 清晰的业务模块划分,便于维护和扩展
- **统一的基础设施**: 通用的基类和接口,提高开发效率
- **完善的权限控制**: 基于角色的访问控制,确保系统安全
- **实时通信支持**: WebSocket和SignalR双通道实时数据推送
- **多数据源支持**: SQL Server、MongoDB、Redis多数据源集成
- **智能化功能**: 联动策略、模式识别、预测性维护等智能特性
### 持续改进
本文档将随着系统的发展持续更新,如有问题或建议,请联系开发团队。
**联系方式:**
- 技术支持: tech-support@yunda.com
- 文档反馈: docs-feedback@yunda.com
- 项目地址: [内部GitLab地址]
---
*最后更新时间: 2024年1月15日*
*文档版本: v1.0*
*适用系统版本: SOMS v2.0+*