Documentation
¶
Index ¶
- Constants
- Variables
- func BuildVirtualShadowFormulas(points []VirtualShadowPointDef) (map[string]string, error)
- func CalculateQualityScore(m *ChannelMetrics) int
- func EnsureChannelID(ch *Channel) error
- func EnsureDeviceID(dev *Device) error
- func EnsureEdgeRuleID(rule *EdgeRule) error
- func EnsurePointID(p *Point) error
- func FormatBuildTime() string
- func GenerateShortID(length int) string
- func GroupPointsByScanClass(points []Point) map[string][]Point
- func InferVirtualShadowChannel(points []VirtualShadowPointDef) string
- func IsEndpointLikeDeviceID(id string) bool
- func IsNorthboundVirtualDevice(deviceID string, virtualDevices OpcUaDeviceMap) bool
- func MakePointRef(channelID, deviceID, pointID string) string
- func MatchSearchQuery(haystack, query string) bool
- func MergeOpcUaDeviceConfig(channelConfig, deviceConfig map[string]any) map[string]any
- func NormalizeOpcUaChannelConfig(config map[string]any)
- func NormalizeOpcUaDeviceID(dev *Device)
- func NormalizeScanClass(scanClass string) string
- func NormalizeVirtualShadowDevice(cfg *VirtualShadowDeviceConfig) error
- func RawDataType(point Point) string
- func ResolveOpcUaEndpoint(channelConfig, deviceConfig map[string]any) string
- func ScanClassInterval(scanClass string, deviceInterval Duration) time.Duration
- func SetGlobalMetricsCollector(mc *MetricsCollector)
- type AICopilotSettings
- type AICopilotSettingsPublic
- type BACnetServerConfig
- type BackupInfo
- type BatchReadSnapshot
- type Channel
- type ChannelMetrics
- type ChannelScanSLA
- type ConnectivityReport
- type ConnectivityResult
- type ConnectivityTarget
- type ConsistencyCheckResult
- type CycleRecord
- type DataCacheConfig
- type Device
- type DeviceCommunicationProfile
- type DeviceMetrics
- type DevicePublishConfig
- type DeviceStorage
- type DriverConfig
- type Duration
- type EdgeFailureRecord
- type EdgeOSMQTTConfig
- type EdgeOSNATSConfig
- type EdgeRule
- type EdgeRuleEvent
- type EdgeRuleEventAction
- type EdgeRuleEventPhase
- type ErrorRecord
- type FailedAction
- type GatewayConfig
- type HAConfig
- type HTTPConfig
- type HostnameConfig
- type IPConfig
- type InstallConfig
- type InstallResult
- type InstallStatus
- type LDAPConfig
- type MQTTConfig
- type MTUNegotiationRecord
- type ManualTime
- type MetricsCollector
- func (mc *MetricsCollector) GetChannelMetrics(channelID string) *ChannelMetrics
- func (mc *MetricsCollector) GetDeviceMetrics(deviceID string) *DeviceMetrics
- func (mc *MetricsCollector) GetPointMetrics(pointID string) *PointMetrics
- func (mc *MetricsCollector) RecordConnectionStart(channelID string)
- func (mc *MetricsCollector) RecordCycle(channelID string, success bool)
- func (mc *MetricsCollector) RecordError(channelID string, errType, code, message string)
- func (mc *MetricsCollector) RecordPointDebug(channelID, pointID string, raw []byte, parsed any, quality string)
- func (mc *MetricsCollector) RecordReconnect(channelID string)
- func (mc *MetricsCollector) RecordRequest(channelID string, success bool, duration time.Duration, errorType string)
- func (mc *MetricsCollector) UpdateDeviceMetrics(deviceID string, update func(*DeviceMetrics))
- type NTPConfig
- type NetworkInterface
- type NodeRuntime
- type NorthboundConfig
- type OPCUAConfig
- type OpcUaDeviceMap
- type PathCheckResult
- type Point
- type PointData
- type PointMetrics
- type PointSourceRef
- type PortCheckResult
- type ProtocolConfig
- type RTTNode
- type RegisterType
- func (r RegisterType) Code() byte
- func (r RegisterType) FunctionCode() byte
- func (r RegisterType) MarshalJSON() ([]byte, error)
- func (r RegisterType) MarshalYAML() (interface{}, error)
- func (r RegisterType) ShortString() string
- func (r RegisterType) String() string
- func (r *RegisterType) UnmarshalJSON(data []byte) error
- func (r *RegisterType) UnmarshalYAML(unmarshal func(interface{}) error) error
- type RequestRecord
- type RuleAction
- type RuleMinuteSnapshot
- type RuleRuntimeState
- type RuleSource
- type ServerConfig
- type ShadowDevice
- type ShadowDiffPoint
- type ShadowIngressMessage
- type ShadowIngressMeta
- type ShadowIngressPoint
- type ShadowPoint
- type ShadowWriteRequest
- type ShadowWriteResponse
- type SourceDeviceSummary
- type SouthboundManager
- type SparkplugBConfig
- type StateConfig
- type StaticRoute
- type SyncConfig
- type SystemConfig
- type ThresholdConfig
- type TimeConfig
- type TrendPoint
- type UserConfig
- type Value
- type VirtualDevice
- type VirtualShadowDeviceConfig
- type VirtualShadowPointDef
- type WindowConfig
Constants ¶
const ( EdgeErrorTypeFormula = "formula_error" EdgeErrorTypeExecution = "execution_error" EdgeErrorTypeTimeout = "timeout" EdgeErrorTypeDispatch = "dispatch_error" EdgeErrorTypeOther = "other" )
Edge error log categories exposed to API and UI.
const ( LogCategorySouthbound = "southbound" LogCategoryEdgeCompute = "edge_compute" LogCategorySystem = "system" LogCategoryNorthbound = "northbound" )
Log categories exposed to WebSocket log stream and REST APIs.
const ( ScanClassFast = "fast" ScanClassNormal = "normal" ScanClassSlow = "slow" )
Variables ¶
var ( Version = "dev" BuildTime = "unknown" CommitID = "unknown" )
Build-time metadata injected by goreleaser.
Functions ¶
func BuildVirtualShadowFormulas ¶
func BuildVirtualShadowFormulas(points []VirtualShadowPointDef) (map[string]string, error)
BuildVirtualShadowFormulas 将 UI 点位定义转换为引擎公式表。
func CalculateQualityScore ¶
func CalculateQualityScore(m *ChannelMetrics) int
CalculateQualityScore computes channel quality score including SLA penalties.
func EnsureChannelID ¶
EnsureChannelID 确保通道具有非空 ID(优先使用 id,其次 name)。
func EnsureDeviceID ¶
EnsureDeviceID 确保设备具有非空 ID(优先使用 id,其次 name)。
func EnsureEdgeRuleID ¶
EnsureEdgeRuleID 确保边缘规则具有非空 ID(优先使用 id,其次 name)。
func FormatBuildTime ¶
func FormatBuildTime() string
func GenerateShortID ¶
GenerateShortID 生成随机小写字母数字 ID(与前端 channel/device ID 风格一致)。
func GroupPointsByScanClass ¶
GroupPointsByScanClass 按扫描类分组点位;未标注的点位归入 normal。
func InferVirtualShadowChannel ¶
func InferVirtualShadowChannel(points []VirtualShadowPointDef) string
InferVirtualShadowChannel 从点位引用推断虚拟设备主要归属通道(兼容 OPC UA 等按通道分组场景)。
func IsEndpointLikeDeviceID ¶
IsEndpointLikeDeviceID reports whether id looks like a connection URL rather than a stable device key.
func IsNorthboundVirtualDevice ¶
func IsNorthboundVirtualDevice(deviceID string, virtualDevices OpcUaDeviceMap) bool
IsNorthboundVirtualDevice reports whether deviceID is configured as a virtual device.
func MakePointRef ¶
MakePointRef 构造公式/依赖引用:channel.device.point
func MatchSearchQuery ¶
MatchSearchQuery 多关键词模糊检索(空格分词,子串或字符顺序匹配)。
func MergeOpcUaDeviceConfig ¶
MergeOpcUaDeviceConfig 合并通道与设备 OPC UA 配置(设备字段覆盖通道同名字段),并规范化 endpoint。
func NormalizeOpcUaChannelConfig ¶
NormalizeOpcUaChannelConfig 统一通道配置中的 url 与 endpoint 字段。
func NormalizeOpcUaDeviceID ¶
func NormalizeOpcUaDeviceID(dev *Device)
NormalizeOpcUaDeviceID replaces empty or endpoint-like device IDs with a generated short ID. Endpoint URLs belong in device config, not as routing identifiers.
func NormalizeScanClass ¶
NormalizeScanClass 归一化扫描类名称;空值视为 normal。
func NormalizeVirtualShadowDevice ¶
func NormalizeVirtualShadowDevice(cfg *VirtualShadowDeviceConfig) error
NormalizeVirtualShadowDevice 校验并规范化虚拟影子设备配置。
func RawDataType ¶
RawDataType returns the protocol payload type. ParseType is authoritative for byte-oriented protocols; DataType remains the converted output type.
func ResolveOpcUaEndpoint ¶
ResolveOpcUaEndpoint 解析 OPC UA 连接地址:设备 endpoint 优先,其次通道 url / endpoint。
func ScanClassInterval ¶
ScanClassInterval 返回扫描类对应的采集周期;未知类回退到设备默认间隔。
func SetGlobalMetricsCollector ¶
func SetGlobalMetricsCollector(mc *MetricsCollector)
SetGlobalMetricsCollector sets the shared collector instance
Types ¶
type AICopilotSettings ¶
type AICopilotSettings struct {
DeploymentMode string `json:"deployment_mode"` // local | remote | cloud
Provider string `json:"provider"` // edgeCore-local | edgeCore-center | openai | anthropic | azure-openai | deepseek | qwen | ernie | zhipu | moonshot | custom
// AI Model Center (Mode A/B — remote)
GrpcEndpoint string `json:"grpc_endpoint"`
// Direct LLM API (Mode C — cloud or custom provider)
BaseURL string `json:"base_url"`
AuthType string `json:"auth_type"` // none | bearer | api_key | basic | azure_key | custom_header
APIKey string `json:"api_key,omitempty"`
APIKeyHeader string `json:"api_key_header"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
AzureAPIVersion string `json:"azure_api_version"`
CustomHeaders map[string]string `json:"custom_headers,omitempty"`
Model string `json:"model"`
EnableCloud bool `json:"enable_cloud"`
TokensLimit int `json:"tokens_limit"`
TasksLimit int `json:"tasks_limit"`
// MCP (Model Context Protocol) 配置
McpEnabled bool `json:"mcp_enabled"` // MCP 服务开关
McpApiKey string `json:"mcp_api_key,omitempty"` // MCP API Key(简化认证,替代 JWT)
McpFullAccess bool `json:"mcp_full_access"` // 用户确认后开启全功能读写(创建/删除/写入)
}
AICopilotSettings is persisted in config.db → ai_copilot bucket (key: settings).
func DefaultAICopilotSettings ¶
func DefaultAICopilotSettings() AICopilotSettings
func (AICopilotSettings) ProviderLabel ¶
func (s AICopilotSettings) ProviderLabel() string
ProviderLabel returns a human-readable provider name for status UI.
func (AICopilotSettings) RuntimeMode ¶
func (s AICopilotSettings) RuntimeMode() string
RuntimeMode maps deployment_mode to the runtime mode used by Agent / Quota UI.
func (AICopilotSettings) ToPublic ¶
func (s AICopilotSettings) ToPublic() AICopilotSettingsPublic
type AICopilotSettingsPublic ¶
type AICopilotSettingsPublic struct {
AICopilotSettings
APIKeySet bool `json:"api_key_set"`
PasswordSet bool `json:"password_set"`
McpApiKeySet bool `json:"mcp_api_key_set"`
APIKey string `json:"api_key,omitempty"`
Password string `json:"password,omitempty"`
McpApiKey string `json:"mcp_api_key,omitempty"`
}
AICopilotSettingsPublic masks secrets for GET /api/ai/settings.
type BACnetServerConfig ¶
type BACnetServerConfig struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Enable bool `json:"enable" yaml:"enable"`
Interface string `json:"interface" yaml:"interface"` // 网络接口名 (如 eth0),空则自动选择
IP string `json:"ip" yaml:"ip"` // 绑定的 IP 地址,空则自动选择
Port int `json:"port" yaml:"port"` // BACnet 端口,默认 47808 (0xBAC0)
SubnetCIDR int `json:"subnet_cidr" yaml:"subnet_cidr"` // 子网 CIDR,默认 24
DeviceID int `json:"device_id" yaml:"device_id"` // BACnet 设备实例 ID,默认自动生成
DeviceName string `json:"device_name" yaml:"device_name"` // BACnet 设备名称
VendorID uint32 `json:"vendor_id" yaml:"vendor_id"` // 厂商 ID,默认 999
VendorName string `json:"vendor_name" yaml:"vendor_name"` // 厂商名称
MaxPDU uint16 `json:"max_pdu" yaml:"max_pdu"` // 最大 PDU 大小,默认 1476
Devices OpcUaDeviceMap `json:"devices" yaml:"devices"` // 暴露的设备列表,空则全部暴露
VirtualDevices OpcUaDeviceMap `json:"virtual_devices" yaml:"virtual_devices"` // 虚拟设备
}
BACnetServerConfig 北向 BACnet Server 配置,以从机模式运行,对外暴露点位数据
type BackupInfo ¶
type BackupInfo struct {
BackupPath string `json:"backupPath"`
BackupTime time.Time `json:"backupTime"`
OriginalPath string `json:"originalPath"`
FileSizeBytes int64 `json:"fileSizeBytes"`
Version string `json:"version"`
Checksum string `json:"checksum,omitempty"`
}
BackupInfo 描述数据库备份文件的元信息。
type BatchReadSnapshot ¶
type BatchReadSnapshot struct {
CurrentGap int `json:"current_gap"`
MaxGap int `json:"max_gap"`
MergedRequests uint64 `json:"merged_requests"`
SavedRequests uint64 `json:"saved_requests"`
FillEfficiency float64 `json:"fill_efficiency"`
}
BatchReadSnapshot Batch Read快照
type Channel ¶
type Channel struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Protocol string `json:"protocol" yaml:"protocol"` // modbus-tcp, modbus-rtu, s7, opc-ua, etc.
Enable bool `json:"enable" yaml:"enable"`
Config map[string]any `json:"config" yaml:"config"` // 协议特定配置 (IP, Port, etc.)
Devices []Device `json:"devices" yaml:"devices"` // 该通道下的设备列表
// Runtime fields
NodeRuntime *NodeRuntime `json:"runtime,omitempty" yaml:"-"`
}
Channel represents a collection channel (采集通道) 一个通道对应一个采集驱动 (如 Modbus TCP, S7, Modbus RTU 等)
type ChannelMetrics ¶
type ChannelMetrics struct {
// 质量评分 (0-100)
QualityScore int `json:"qualityScore"`
// 协议信息
Protocol string `json:"protocol"` // 协议类型
// 通信质量指标
SuccessRate float64 `json:"successRate"` // 成功率 (0-1)
TimeoutCount int64 `json:"timeoutCount"` // 超时次数
CrcError int64 `json:"crcError"` // CRC错误次数
CrcErrorRate float64 `json:"crcErrorRate"` // CRC错误率
RetryRate float64 `json:"retryRate"` // 重试率
ExceptionCode int64 `json:"exceptionCode"` // 异常响应次数
// 响应时间指标 (毫秒)
AvgRtt float64 `json:"avgRtt"` // 平均响应时间
MaxRtt float64 `json:"maxRtt"` // 最大响应时间
MinRtt float64 `json:"minRtt"` // 最小响应时间
// 连接指标
LocalAddr string `json:"localAddr"` // 本地地址 (IP:Port)
RemoteAddr string `json:"remoteAddr"` // 远程地址 (IP:Port)
LinkUp bool `json:"linkUp"` // 通道链路是否已建立
ReconnectCount int64 `json:"reconnectCount"` // 重连次数
ConnectionSeconds int64 `json:"connectionSeconds"` // 当前连接时长(秒)
LastDisconnectTime time.Time `json:"lastDisconnectTime"` // 最后断开时间
// 请求统计
TotalRequests int64 `json:"totalRequests"` // 总请求数
SuccessCount int64 `json:"successCount"` // 成功次数
FailureCount int64 `json:"failureCount"` // 失败次数
// 丢包率
PacketLoss float64 `json:"packetLoss"` // (超时+CRC)/总数
// 趋势数据 (最近1小时,每5分钟一个点)
Trend []TrendPoint `json:"trend,omitempty"`
// 最近异常 (最近10条)
RecentErrors []ErrorRecord `json:"recentErrors,omitempty"`
// ScanEngine SLA 联动(Phase C)
ScanLagP95Ms float64 `json:"scanLagP95Ms,omitempty"`
ScanDriftAvgMs float64 `json:"scanDriftAvgMs,omitempty"`
ScanDriftAvgMsWindow float64 `json:"scanDriftAvgMsWindow,omitempty"`
ScanMissDeadlineTotal uint64 `json:"scanMissDeadlineTotal,omitempty"`
ScanMissDeadlineWindow uint64 `json:"scanMissDeadlineWindow,omitempty"`
CircuitBreakerOpen int `json:"circuitBreakerOpen,omitempty"`
SLAWarnings []map[string]any `json:"slaWarnings,omitempty"`
// ScanSLA 调度 SLA 明细(通道级,与通信质量分离)
ScanSLA *ChannelScanSLA `json:"scanSla,omitempty"`
// 时间戳
Timestamp time.Time `json:"timestamp"`
}
ChannelMetrics 通道级监控指标
type ChannelScanSLA ¶
type ChannelScanSLA struct {
ScanLagP95Ms float64 `json:"scanLagP95Ms,omitempty"`
ScanDriftAvgMs float64 `json:"scanDriftAvgMs,omitempty"`
ScanDriftAvgMsWindow float64 `json:"scanDriftAvgMsWindow,omitempty"`
ScanMissDeadlineTotal uint64 `json:"scanMissDeadlineTotal,omitempty"`
ScanMissDeadlineWindow uint64 `json:"scanMissDeadlineWindow,omitempty"`
CircuitBreakerOpen int `json:"circuitBreakerOpen,omitempty"`
SLAWarnings []map[string]any `json:"slaWarnings,omitempty"`
}
ChannelScanSLA 通道级调度 SLA(与通信质量指标分离)。
type ConnectivityReport ¶
type ConnectivityReport struct {
Success bool `json:"success"`
Details []ConnectivityResult `json:"details"`
}
ConnectivityReport aggregates results of connectivity checks
type ConnectivityResult ¶
type ConnectivityResult struct {
Target string `json:"target"`
Success bool `json:"success"`
Message string `json:"message"`
}
ConnectivityResult represents the result of a connectivity check
type ConnectivityTarget ¶
type ConnectivityTarget struct {
Type string `json:"type"` // gateway, ip, domain, http
Target string `json:"target"`
Timeout int `json:"timeout"` // Seconds
}
ConnectivityTarget represents a target to verify network connectivity
type ConsistencyCheckResult ¶
type ConsistencyCheckResult struct {
Pass bool `json:"pass"`
DiffPoints []ShadowDiffPoint `json:"diff_points"`
DiffSource string `json:"diff_source"`
RepairSuggest string `json:"repair_suggest"`
}
ConsistencyCheckResult represents the result of a consistency check
type CycleRecord ¶
CycleRecord 周期记录 (一轮采集的结果)
type DataCacheConfig ¶
type Device ¶
type Device struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Enable bool `json:"enable" yaml:"enable"`
Interval Duration `json:"interval" yaml:"interval"`
// Spatial attributes / 空间属性 - 物理位置信息,用于资产管理和设备定位
StationName string `json:"station_name,omitempty" yaml:"station_name,omitempty"` // 局站名称 / Station name
StationCode string `json:"station_code,omitempty" yaml:"station_code,omitempty"` // 局站编码 / Station code
RoomName string `json:"room_name,omitempty" yaml:"room_name,omitempty"` // 机房名称 / Equipment room name
RoomCode string `json:"room_code,omitempty" yaml:"room_code,omitempty"` // 机房编码 / Equipment room code
DegradeOnFailure *bool `json:"degrade_on_failure,omitempty" yaml:"degrade_on_failure,omitempty"` // 默认 true;设为 false 关闭失败退避
DeviceFile string `json:"device_file,omitempty" yaml:"device_file,omitempty"` // 设备配置文件路径
Config map[string]any `json:"config" yaml:"config"` // 设备特定配置(如 slave_id)
Storage DeviceStorage `json:"storage,omitempty" yaml:"storage,omitempty"` // Data storage strategy
Points []Point `json:"points,omitempty" yaml:"points,omitempty"` // 该设备的点位列表
PointsCount int `json:"points_count,omitempty" yaml:"-"` // 列表 API 省略 points 时返回点位数量
State int `json:"state" yaml:"-"` // 运行时状态:0=Online, 1=Unstable, 2=Offline, 3=Quarantine
QualityScore int `json:"quality_score" yaml:"-"` // 质量评分 (0-100)
// Runtime state fields
NodeRuntime *NodeRuntime `json:"runtime,omitempty" yaml:"-"`
}
Device represents a device configuration (within a channel)
func NormalizeDevicesForSave ¶
NormalizeDevicesForSave 校验并去重设备列表,供配置持久化使用。
func (Device) DeepCopy ¶
DeepCopy returns a deep copy of a Device so callers may mutate the result (Points, Config, DegradeOnFailure, NodeRuntime) without corrupting the channel manager's internal state. Without this, the Points slice and Config map share backing storage with the stored device, so MCP/API update handlers mutate the live configuration before the change-diff / restart decision runs.
func (Device) WithPointsSummary ¶
WithPointsSummary returns a copy with Points stripped and PointsCount populated. Used by list APIs to avoid shipping large point payloads to the UI.
type DeviceCommunicationProfile ¶
type DeviceCommunicationProfile struct {
DeviceID string `json:"device_id"`
ChannelID string `json:"channel_id"`
ProtocolType string `json:"protocol_type"`
SlaveID interface{} `json:"slave_id"`
AvgResponseTime time.Duration `json:"avg_response_time"`
MaxResponseTime time.Duration `json:"max_response_time"`
ErrorRate float64 `json:"error_rate"`
StabilityScore float64 `json:"stability_score"`
OptimalTimeout time.Duration `json:"optimal_timeout"`
OptimalInterval time.Duration `json:"optimal_interval"`
RetryCount int `json:"retry_count"`
BatchSize int `json:"batch_size"`
ProtocolParams map[string]interface{} `json:"protocol_params"`
LastUpdated time.Time `json:"last_updated"`
CollectionSuccessRate float64 `json:"collection_success_rate"`
AbnormalPointCount int `json:"abnormal_point_count"`
ConsecutiveFailures int `json:"consecutive_failures"`
// RTT相关字段
RTTSamples []int64 `json:"rtt_samples"`
RTTSampleWindow int `json:"rtt_sample_window"`
EWMARTT int64 `json:"ewma_rtt"`
// MTU相关字段
CurrentMTU int `json:"current_mtu"`
MaxMTU int `json:"max_mtu"`
MinMTU int `json:"min_mtu"`
// Gap合并相关字段
CurrentGap int `json:"current_gap"`
MaxGap int `json:"max_gap"`
GapFillStrategy int `json:"gap_fill_strategy"`
// 心跳相关字段
HeartbeatInterval int `json:"heartbeat_interval"`
LastActivity time.Time `json:"last_activity"`
}
DeviceCommunicationProfile 设备通信画像结构
type DeviceMetrics ¶
type DeviceMetrics struct {
// 健康评分 (0-100)
HealthScore int `json:"healthScore"`
// 基础信息
State int `json:"state"` // 0:在线, 1:不稳定, 2:离线, 3:隔离
LastCollectTime time.Time `json:"lastCollectTime"` // 上次采集时间
ConsecutiveFailures int `json:"consecutiveFailures"` // 连续失败次数
Degraded bool `json:"degraded"` // 是否降级
Recovering bool `json:"recovering"` // 是否恢复中
// 采集质量
PointSuccessRate float64 `json:"pointSuccessRate"` // 点位成功率
AvgCollectTime float64 `json:"avgCollectTime"` // 平均采集耗时(ms)
AbnormalPoints int `json:"abnormalPoints"` // 异常点位数量
InvalidValues int `json:"invalidValues"` // 无效值数量
NullValueRate float64 `json:"nullValueRate"` // Null值比例
// 时间戳
Timestamp time.Time `json:"timestamp"`
// 通信画像(RTT/MTU/Gap,来自 Shadow 优化器)
CommunicationProfile map[string]interface{} `json:"communicationProfile,omitempty"`
}
DeviceMetrics 设备级监控指标
type DevicePublishConfig ¶
type DevicePublishConfig struct {
Enable bool `json:"enable" yaml:"enable"`
Strategy string `json:"strategy" yaml:"strategy"` // "realtime" or "periodic"
Interval Duration `json:"interval" yaml:"interval"` // Push interval for periodic mode (e.g., "5s", "1m")
}
func LookupNorthboundPublishConfig ¶
func LookupNorthboundPublishConfig(deviceID string, devices, virtualDevices OpcUaDeviceMap) (DevicePublishConfig, bool)
LookupNorthboundPublishConfig resolves publish settings for a device ID across real-device and virtual-device northbound maps. A device is published only when it is explicitly enabled in the mapping; empty maps do NOT imply allow-all, so new devices are not auto-mapped until they are enabled in the tree.
type DeviceStorage ¶
type DeviceStorage struct {
Enable bool `json:"enable" yaml:"enable"`
Strategy string `json:"strategy" yaml:"strategy"` // "realtime" (every record), "interval" (fixed time)
Interval int `json:"interval" yaml:"interval"` // Storage interval in minutes (1, 10, 60)
MaxRecords int `json:"max_records" yaml:"max_records"` // Max history records (default 1000)
}
DeviceStorage defines data storage strategy for a device
type DriverConfig ¶
type DriverConfig struct {
ChannelID string `json:"channel_id"`
Protocol string `json:"protocol"` // Protocol name (e.g. modbus-tcp, modbus-rtu)
Config map[string]any `json:"config"`
}
DriverConfig is the configuration passed to a driver
type Duration ¶
func (Duration) MarshalJSON ¶
func (Duration) MarshalText ¶
func (*Duration) UnmarshalJSON ¶
func (*Duration) UnmarshalText ¶
type EdgeFailureRecord ¶
type EdgeFailureRecord struct {
ID string `json:"id"`
RuleID string `json:"rule_id"`
RuleName string `json:"rule_name,omitempty"`
Category string `json:"category,omitempty"`
ChannelID string `json:"channel_id,omitempty"`
DeviceID string `json:"device_id,omitempty"`
ErrorType string `json:"error_type,omitempty"`
Phase string `json:"phase"`
Error string `json:"error"`
Timestamp time.Time `json:"timestamp"`
TriggerValue any `json:"trigger_value,omitempty"`
Condition string `json:"condition,omitempty"`
ActionType string `json:"action_type,omitempty"`
ActionIndex int `json:"action_index,omitempty"`
Context map[string]any `json:"context,omitempty"`
}
EdgeFailureRecord is a structured failure log entry accessible via API.
type EdgeOSMQTTConfig ¶
type EdgeOSMQTTConfig struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Enable bool `json:"enable" yaml:"enable"`
Broker string `json:"broker" yaml:"broker"`
ClientID string `json:"client_id" yaml:"client_id"`
NodeID string `json:"node_id" yaml:"node_id"`
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
QoS byte `json:"qos" yaml:"qos"`
Retain bool `json:"retain" yaml:"retain"`
CleanSession bool `json:"clean_session" yaml:"clean_session"`
KeepAlive int `json:"keep_alive" yaml:"keep_alive"`
ConnectTimeout int `json:"connect_timeout" yaml:"connect_timeout"`
AutoReconnect bool `json:"auto_reconnect" yaml:"auto_reconnect"`
MaxReconnectInterval int `json:"max_reconnect_interval" yaml:"max_reconnect_interval"`
HeartbeatInterval string `json:"heartbeat_interval" yaml:"heartbeat_interval"` // e.g. "30s" V1 心跳
Devices map[string]DevicePublishConfig `json:"devices" yaml:"devices"` // Key: DeviceID, Value: DevicePublishConfig
VirtualDevices OpcUaDeviceMap `json:"virtual_devices" yaml:"virtual_devices"`
// EAN 2.0 能力层配置 | EAN 2.0 capability layer config
// EANEnabled 控制北向 EAN Runtime 启停;MCP Runtime 不受此字段影响
EANEnabled bool `json:"ean_enabled" yaml:"ean_enabled"`
// EANHeartbeatSec EAN 心跳周期(秒),0 时使用默认值 60
EANHeartbeatSec int `json:"ean_heartbeat_sec" yaml:"ean_heartbeat_sec"`
// EANEventAutoPublish 设备数据变化时是否自动发布 EAN Event
EANEventAutoPublish bool `json:"ean_event_auto_publish" yaml:"ean_event_auto_publish"`
// Phase 4 (EX-P4): V1 命令面开关——已全面下线,默认 false(不订阅 edgeCore/cmd/*);
// 命令统一 EAN Invoke($edgeos/invoke/*)。V1 数据面/告警不受影响。
// V1 command plane switch (Phase 4): default false - V1 command plane fully retired; commands use EAN Invoke.
V1CommandEnabled bool `json:"v1_command_enabled" yaml:"v1_command_enabled"`
}
EdgeOSMQTTConfig defines configuration for edgeOS(MQTT) northbound channel
type EdgeOSNATSConfig ¶
type EdgeOSNATSConfig struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Enable bool `json:"enable" yaml:"enable"`
URL string `json:"url" yaml:"url"`
ClientID string `json:"client_id" yaml:"client_id"`
NodeID string `json:"node_id" yaml:"node_id"`
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
Token string `json:"token" yaml:"token"`
ConnectTimeout int `json:"connect_timeout" yaml:"connect_timeout"`
ReconnectWait int `json:"reconnect_wait" yaml:"reconnect_wait"`
MaxReconnects int `json:"max_reconnects" yaml:"max_reconnects"`
PingInterval int `json:"ping_interval" yaml:"ping_interval"`
MaxPingsOutstanding int `json:"max_pings_outstanding" yaml:"max_pings_outstanding"`
JetStreamEnabled bool `json:"jetstream_enabled" yaml:"jetstream_enabled"`
HeartbeatInterval string `json:"heartbeat_interval" yaml:"heartbeat_interval"` // e.g. "30s" V1 心跳
Devices map[string]DevicePublishConfig `json:"devices" yaml:"devices"` // Key: DeviceID, Value: DevicePublishConfig
VirtualDevices OpcUaDeviceMap `json:"virtual_devices" yaml:"virtual_devices"`
// EAN 2.0 能力层配置 | EAN 2.0 capability layer config
// EANEnabled 控制北向 EAN Runtime 启停;MCP Runtime 不受此字段影响
EANEnabled bool `json:"ean_enabled" yaml:"ean_enabled"`
// EANHeartbeatSec EAN 心跳周期(秒),0 时使用默认值 60
EANHeartbeatSec int `json:"ean_heartbeat_sec" yaml:"ean_heartbeat_sec"`
// EANEventAutoPublish 设备数据变化时是否自动发布 EAN Event
EANEventAutoPublish bool `json:"ean_event_auto_publish" yaml:"ean_event_auto_publish"`
// Phase 4 (EX-P4): V1 命令面开关——已全面下线,默认 false(不订阅 edgeCore.cmd.*);
// 命令统一 EAN Invoke($edgeos/invoke/*)。V1 数据面/告警不受影响。
// V1 command plane switch (Phase 4): default false - V1 command plane fully retired; commands use EAN Invoke.
V1CommandEnabled bool `json:"v1_command_enabled" yaml:"v1_command_enabled"`
}
EdgeOSNATSConfig defines configuration for edgeOS(NATS) northbound channel
type EdgeRule ¶
type EdgeRule struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Type string `json:"type" yaml:"type"` // threshold, calculation, state, window
Enable bool `json:"enable" yaml:"enable"`
Priority int `json:"priority" yaml:"priority"`
CheckInterval string `json:"check_interval" yaml:"check_interval"` // e.g. "5s", "1m"
TriggerMode string `json:"trigger_mode" yaml:"trigger_mode"` // always, on_change
Source RuleSource `json:"source" yaml:"source"` // Deprecated: use Sources
Sources []RuleSource `json:"sources" yaml:"sources"` // New: Multiple sources
TriggerLogic string `json:"trigger_logic" yaml:"trigger_logic"` // "AND", "OR", "EXPR"
Condition string `json:"condition" yaml:"condition"` // Boolean Expression
Expression string `json:"expression" yaml:"expression"` // Calculation Expression
Actions []RuleAction `json:"actions" yaml:"actions"`
Window *WindowConfig `json:"window,omitempty" yaml:"window,omitempty"`
State *StateConfig `json:"state,omitempty" yaml:"state,omitempty"`
}
EdgeRule represents an edge computing rule
func NormalizeEdgeRulesForSave ¶
NormalizeEdgeRulesForSave 校验并去重边缘规则列表,供 edge.db 持久化使用。
type EdgeRuleEvent ¶
type EdgeRuleEvent struct {
ID string `json:"id"`
RuleID string `json:"rule_id"`
RuleName string `json:"rule_name"`
StartedAt time.Time `json:"started_at"`
EndedAt time.Time `json:"ended_at,omitempty"`
DurationMs int64 `json:"duration_ms,omitempty"`
Status string `json:"status"` // running, completed, error, dropped
Triggered bool `json:"triggered"`
TriggerSource Value `json:"trigger_source,omitempty"`
TriggerValue any `json:"trigger_value,omitempty"`
Condition string `json:"condition,omitempty"`
OutputValue any `json:"output_value,omitempty"`
Phases []EdgeRuleEventPhase `json:"phases,omitempty"`
Actions []EdgeRuleEventAction `json:"actions,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
}
EdgeRuleEvent is a complete rule execution record from trigger to completion.
type EdgeRuleEventAction ¶
type EdgeRuleEventAction struct {
Index int `json:"index"`
Type string `json:"type"`
Status string `json:"status"` // success, failed, skipped
Error string `json:"error,omitempty"`
StartedAt time.Time `json:"started_at"`
EndedAt time.Time `json:"ended_at,omitempty"`
DurationMs int64 `json:"duration_ms,omitempty"`
}
EdgeRuleEventAction captures a single action outcome within an event.
type EdgeRuleEventPhase ¶
type EdgeRuleEventPhase struct {
Phase string `json:"phase"`
StartedAt time.Time `json:"started_at"`
EndedAt time.Time `json:"ended_at,omitempty"`
DurationMs int64 `json:"duration_ms,omitempty"`
Error string `json:"error,omitempty"`
Detail map[string]any `json:"detail,omitempty"`
}
EdgeRuleEventPhase captures one stage in a rule execution lifecycle.
type ErrorRecord ¶
type ErrorRecord struct {
Time time.Time `json:"time"` // 发生时间
Type string `json:"type"` // 错误类型: timeout, crc, exception, network
Code string `json:"code"` // 错误码
Message string `json:"message"` // 错误描述
}
ErrorRecord 错误记录
type FailedAction ¶
type GatewayConfig ¶
type GatewayConfig struct {
Gateway string `json:"gateway"`
Metric int `json:"metric"`
Interface string `json:"interface"`
Scope string `json:"scope"` // Default, Specific
Enabled bool `json:"enabled"`
}
GatewayConfig represents a gateway configuration
type HAConfig ¶
type HAConfig struct {
Role string `json:"role"` // master, backup
HeartbeatType string `json:"heartbeat_type"` // TCP, UDP, HTTP
Interval int `json:"interval"` // Seconds
Timeout int `json:"timeout"` // Seconds
Retries int `json:"retries"`
}
HAConfig represents High Availability settings
type HTTPConfig ¶
type HTTPConfig struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Enable bool `json:"enable" yaml:"enable"`
URL string `json:"url" yaml:"url"` // Base URL
Method string `json:"method" yaml:"method"` // POST/PUT
Headers map[string]string `json:"headers" yaml:"headers"`
AuthType string `json:"auth_type" yaml:"auth_type"` // None, Basic, Bearer, APIKey
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
Token string `json:"token" yaml:"token"`
APIKeyName string `json:"api_key_name" yaml:"api_key_name"`
APIKeyValue string `json:"api_key_value" yaml:"api_key_value"`
DataEndpoint string `json:"data_endpoint" yaml:"data_endpoint"` // Relative path for data
DeviceEventEndpoint string `json:"device_event_endpoint" yaml:"device_event_endpoint"` // Relative path for events
Cache DataCacheConfig `json:"cache" yaml:"cache"`
Devices OpcUaDeviceMap `json:"devices" yaml:"devices"` // Key: DeviceID; legacy bool or DevicePublishConfig
VirtualDevices OpcUaDeviceMap `json:"virtual_devices" yaml:"virtual_devices"`
}
type HostnameConfig ¶
type HostnameConfig struct {
Name string `json:"name"`
EnableMDNS bool `json:"enable_mdns"`
EnableBare bool `json:"enable_bare"` // Bare hostname access
HTTPPort int `json:"http_port"`
HTTPSPort int `json:"https_port"`
Interfaces []string `json:"interfaces"` // e.g. ["eth0", "wlan0"]
}
HostnameConfig represents system hostname and access settings
type IPConfig ¶
type IPConfig struct {
Address string `json:"address"` // IP address
Prefix int `json:"prefix"` // Prefix length (e.g., 24 for IPv4, 64 for IPv6)
Version string `json:"version"` // IPv4, IPv6
Source string `json:"source"` // DHCP, Static
Enabled bool `json:"enabled"`
}
IPConfig represents an IP address configuration
type InstallConfig ¶
type InstallConfig struct {
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
StoragePath string `json:"storagePath"`
GatewayName string `json:"gatewayName"`
GatewayLocation string `json:"gatewayLocation"`
DeviceSerial string `json:"deviceSerial"`
MigrateFromDB string `json:"migrateFromDB,omitempty"`
MigrateConfig bool `json:"migrateConfig,omitempty"`
MigrateRuntime bool `json:"migrateRuntime,omitempty"`
}
type InstallResult ¶
type InstallStatus ¶
type LDAPConfig ¶
type LDAPConfig struct {
Enabled bool `json:"enabled"`
Server string `json:"server"` // e.g., ldap.example.com
Port int `json:"port"` // e.g., 389 or 636
BaseDN string `json:"base_dn"` // e.g., dc=example,dc=com
BindDN string `json:"bind_dn"` // e.g., cn=admin,dc=example,dc=com (optional for anonymous bind)
BindPassword string `json:"bind_password"` // (optional)
UserFilter string `json:"user_filter"` // e.g., (uid=%s) or (sAMAccountName=%s)
Attributes string `json:"attributes"` // e.g., "uid,cn,mail"
UseSSL bool `json:"use_ssl"` // LDAPS
SkipVerify bool `json:"skip_verify"` // Skip SSL verification
}
LDAPConfig represents LDAP authentication settings
type MQTTConfig ¶
type MQTTConfig struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Enable bool `json:"enable" yaml:"enable"`
Broker string `json:"broker" yaml:"broker"`
ClientID string `json:"client_id" yaml:"client_id"`
Topic string `json:"topic" yaml:"topic"`
SubscribeTopic string `json:"subscribe_topic" yaml:"subscribe_topic"` // New: Subscribe topic for write requests
StatusTopic string `json:"status_topic" yaml:"status_topic"` // Online/Offline status topic
LwtTopic string `json:"lwt_topic" yaml:"lwt_topic"` // LWT topic (if different from StatusTopic)
DeviceStatusTopic string `json:"device_status_topic" yaml:"device_status_topic"` // Sub-device Online/Offline topic
DeviceLifecycleTopic string `json:"device_lifecycle_topic" yaml:"device_lifecycle_topic"` // Sub-device Add/Remove topic
OnlinePayload string `json:"online_payload" yaml:"online_payload"` // Payload for online status
OfflinePayload string `json:"offline_payload" yaml:"offline_payload"` // Payload for offline status (graceful disconnect)
LwtPayload string `json:"lwt_payload" yaml:"lwt_payload"` // Payload for LWT (ungraceful disconnect)
IgnoreOfflineData bool `json:"ignore_offline_data" yaml:"ignore_offline_data"` // If true, do not report data when device is offline
WriteResponseTopic string `json:"write_response_topic" yaml:"write_response_topic"` // Topic for write responses
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
Cache DataCacheConfig `json:"cache" yaml:"cache"`
Devices map[string]DevicePublishConfig `json:"devices" yaml:"devices"`
VirtualDevices OpcUaDeviceMap `json:"virtual_devices" yaml:"virtual_devices"`
}
type MTUNegotiationRecord ¶
type MTUNegotiationRecord struct {
AttemptValue int `json:"attempt_value"`
ResponseTime int64 `json:"response_time"`
RetryCount int `json:"retry_count"`
Success bool `json:"success"`
Timestamp time.Time `json:"timestamp"`
}
MTUNegotiationRecord MTU协商记录
type ManualTime ¶
type MetricsCollector ¶
type MetricsCollector struct {
// contains filtered or unexported fields
}
MetricsCollector 监控指标收集器
func GetGlobalMetricsCollector ¶
func GetGlobalMetricsCollector() *MetricsCollector
GetGlobalMetricsCollector returns the shared collector instance
func NewMetricsCollector ¶
func NewMetricsCollector() *MetricsCollector
NewMetricsCollector 创建新的监控指标收集器
func (*MetricsCollector) GetChannelMetrics ¶
func (mc *MetricsCollector) GetChannelMetrics(channelID string) *ChannelMetrics
GetChannelMetrics 获取通道监控指标
func (*MetricsCollector) GetDeviceMetrics ¶
func (mc *MetricsCollector) GetDeviceMetrics(deviceID string) *DeviceMetrics
GetDeviceMetrics 获取设备监控指标
func (*MetricsCollector) GetPointMetrics ¶
func (mc *MetricsCollector) GetPointMetrics(pointID string) *PointMetrics
GetPointMetrics 返回点位调试信息副本
func (*MetricsCollector) RecordConnectionStart ¶
func (mc *MetricsCollector) RecordConnectionStart(channelID string)
RecordConnectionStart 记录连接开始
func (*MetricsCollector) RecordCycle ¶
func (mc *MetricsCollector) RecordCycle(channelID string, success bool)
RecordCycle 记录一轮完整采集的结果
func (*MetricsCollector) RecordError ¶
func (mc *MetricsCollector) RecordError(channelID string, errType, code, message string)
RecordError 记录错误
func (*MetricsCollector) RecordPointDebug ¶
func (mc *MetricsCollector) RecordPointDebug(channelID, pointID string, raw []byte, parsed any, quality string)
RecordPointDebug 保存点位调试信息(原始字节 + 解析后值)。 原始字节(RawValue)与最新解析值每次读取都保存,保证按需调试(如点击点位值查看原始报文) 能反映真实设备报文;聚合计数按 pointDebugSampleRate 采样写入以降低热路径锁竞争。 RawValue 截断至 pointDebugMaxRawBytes,map 有上限(evictPointMetricsIfNeeded)。
func (*MetricsCollector) RecordReconnect ¶
func (mc *MetricsCollector) RecordReconnect(channelID string)
RecordReconnect 记录重连事件
func (*MetricsCollector) RecordRequest ¶
func (mc *MetricsCollector) RecordRequest(channelID string, success bool, duration time.Duration, errorType string)
RecordRequest 记录一次请求
func (*MetricsCollector) UpdateDeviceMetrics ¶
func (mc *MetricsCollector) UpdateDeviceMetrics(deviceID string, update func(*DeviceMetrics))
UpdateDeviceMetrics 更新设备监控指标
type NetworkInterface ¶
type NetworkInterface struct {
Name string `json:"name"`
MAC string `json:"mac"`
Status string `json:"status"` // UP, DOWN
InterfaceMetric int `json:"interface_metric"`
IPConfigs []IPConfig `json:"ip_configs"`
Gateways []GatewayConfig `json:"gateways"`
Enabled bool `json:"enabled"`
}
NetworkInterface represents a physical or virtual network interface
type NodeRuntime ¶
type NodeRuntime struct {
FailCount int `json:"fail_count"`
SuccessCount int `json:"success_count"`
LastFailTime time.Time `json:"last_fail_time"`
NextRetryTime time.Time `json:"next_retry_time"`
State int `json:"state"` // NodeState enum
}
NodeRuntime defines runtime statistics for a node (device or channel)
type NorthboundConfig ¶
type NorthboundConfig struct {
MQTT []MQTTConfig `json:"mqtt" yaml:"mqtt"`
HTTP []HTTPConfig `json:"http" yaml:"http"`
OPCUA []OPCUAConfig `json:"opcua" yaml:"opcua"`
SparkplugB []SparkplugBConfig `json:"sparkplug_b" yaml:"sparkplug_b"`
EdgeOSMQTT []EdgeOSMQTTConfig `json:"edgeos_mqtt" yaml:"edgeos_mqtt"`
EdgeOSNATS []EdgeOSNATSConfig `json:"edgeos_nats" yaml:"edgeos_nats"`
BACnetServer []BACnetServerConfig `json:"bacnet_server" yaml:"bacnet_server"`
Status map[string]int `json:"status,omitempty" yaml:"-"`
}
NorthboundConfig defines configuration for northbound data reporting
func NormalizeNorthboundForSave ¶
func NormalizeNorthboundForSave(cfg NorthboundConfig) (NorthboundConfig, error)
NormalizeNorthboundForSave 校验北向通道 ID 并剔除运行时 Status 字段,供 edge.db 持久化使用。
func SanitizeNorthboundForClient ¶
func SanitizeNorthboundForClient(cfg NorthboundConfig) NorthboundConfig
SanitizeNorthboundForClient redacts secrets from northbound config API responses.
type OPCUAConfig ¶
type OPCUAConfig struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Enable bool `json:"enable" yaml:"enable"`
Port int `json:"port" yaml:"port"`
Endpoint string `json:"endpoint" yaml:"endpoint"`
SecurityPolicy string `json:"security_policy" yaml:"security_policy"` // Auto, None, Basic256Sha256, Basic256, Basic128Rsa15, Aes128_Sha256_RsaOaep, Aes256Sha256RsaPss
SecurityMode string `json:"security_mode" yaml:"security_mode"` // Auto, None, Sign, SignAndEncrypt
TrustedCertPath string `json:"trusted_cert_path" yaml:"trusted_cert_path"`
AuthMethods []string `json:"auth_methods" yaml:"auth_methods"` // "Anonymous", "UserName", "Certificate"
Users map[string]string `json:"users" yaml:"users"` // Username -> Password
CertFile string `json:"cert_file" yaml:"cert_file"` // legacy path fallback
KeyFile string `json:"key_file" yaml:"key_file"` // legacy path fallback
// ServerCertPEM / ServerKeyPEM 持久化在北向配置(edge.db),启动时物化到 data/certs/opcua/{id}/
ServerCertPEM string `json:"server_cert_pem,omitempty" yaml:"server_cert_pem,omitempty"`
ServerKeyPEM string `json:"server_key_pem,omitempty" yaml:"server_key_pem,omitempty"`
TrustedCertsPEM []string `json:"trusted_certs_pem,omitempty" yaml:"trusted_certs_pem,omitempty"`
HasServerCert bool `json:"has_server_cert,omitempty" yaml:"-"`
HasServerKey bool `json:"has_server_key,omitempty" yaml:"-"`
Devices OpcUaDeviceMap `json:"devices" yaml:"devices"` // Key: DeviceID, Value: enable/strategy/interval
VirtualDevices OpcUaDeviceMap `json:"virtual_devices" yaml:"virtual_devices"` // Key: VirtualShadowDeviceID, Value: enable
}
func MergeOPCUAConfig ¶
func MergeOPCUAConfig(existing, incoming OPCUAConfig) OPCUAConfig
MergeOPCUAConfig merges incoming OPC UA config with existing stored secrets/certs.
func SanitizeOPCUAForClient ¶
func SanitizeOPCUAForClient(cfg OPCUAConfig) OPCUAConfig
SanitizeOPCUAForClient strips sensitive PEM material before API responses.
type OpcUaDeviceMap ¶
type OpcUaDeviceMap map[string]DevicePublishConfig
OpcUaDeviceMap 北向 OPC UA 服务端的设备映射,兼容历史 bool 与 DevicePublishConfig 两种格式。
func (OpcUaDeviceMap) AllowsDevice ¶
func (m OpcUaDeviceMap) AllowsDevice(deviceID string) bool
AllowsDevice 仅允许显式启用(Enable=true)的设备暴露到北向地址空间; 未在映射中列出或显式禁用的设备默认不暴露,需在树形映射中启用后才可见。
func (*OpcUaDeviceMap) UnmarshalJSON ¶
func (m *OpcUaDeviceMap) UnmarshalJSON(data []byte) error
func (*OpcUaDeviceMap) UnmarshalYAML ¶
func (m *OpcUaDeviceMap) UnmarshalYAML(unmarshal func(any) error) error
type PathCheckResult ¶
type Point ¶
type Point struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
RegisterType RegisterType `json:"register_type" yaml:"register_type"`
FunctionCode byte `json:"function_code" yaml:"function_code"` // 允许非标准功能码 (当前会将配置初始化值设置为0)
Address string `json:"address" yaml:"address"` // 地址字符串,支持不同协议格式
DataType string `json:"datatype" yaml:"datatype"` // int16, float32, bool, bit.0
ParseType string `json:"parse_type,omitempty" yaml:"parse_type,omitempty"` // 原始字节解析类型,如 INT16、FLOAT32
Scale float64 `json:"scale" yaml:"scale"`
Offset float64 `json:"offset" yaml:"offset"`
Format string `json:"format,omitempty" yaml:"format,omitempty"`
WordOrder string `json:"word_order,omitempty" yaml:"word_order,omitempty"`
ReadFormula string `json:"read_formula,omitempty" yaml:"read_formula,omitempty"`
WriteFormula string `json:"write_formula,omitempty" yaml:"write_formula,omitempty"`
Unit string `json:"unit" yaml:"unit"`
ReadWrite string `json:"readwrite" yaml:"readwrite"` // R / RW
Group string `json:"group" yaml:"group"`
ScanClass string `json:"scan_class,omitempty" yaml:"scan_class,omitempty"` // fast / normal / slow
ReportMode string `json:"report_mode" yaml:"report_mode"` // cycle / cov / event
Threshold *ThresholdConfig `json:"threshold" yaml:"threshold"`
DeviceID string `json:"-" yaml:"-"` // Runtime field, not persisted
}
Point represents a data point configuration (Tag/Variable)
type PointData ¶
type PointData struct {
ID string `json:"id"`
Name string `json:"name"`
SlaveID uint8 `json:"slave_id"`
RegisterType string `json:"register_type"`
FunctionCode byte `json:"function_code"`
Address string `json:"address"`
DataType string `json:"datatype"`
ParseType string `json:"parse_type,omitempty"`
Value any `json:"value"`
Quality string `json:"quality"`
Timestamp time.Time `json:"timestamp"` // 采集时间(兼容旧字段)
CollectedAt time.Time `json:"collected_at"` // 采集时间
UpdatedAt time.Time `json:"updated_at"` // 影子更新时间
Unit string `json:"unit,omitempty"`
ReadWrite string `json:"readwrite"` // R / RW
// 点位配置字段(与 Point 对齐),供点位列表接口透传给前端,
// 避免"设备协议类型(format)"、编辑回显等依赖配置的展示丢失
Format string `json:"format,omitempty"`
WordOrder string `json:"word_order,omitempty"`
Scale float64 `json:"scale,omitempty"`
Offset float64 `json:"offset,omitempty"`
ReadFormula string `json:"read_formula,omitempty"`
WriteFormula string `json:"write_formula,omitempty"`
Group string `json:"group,omitempty"`
ScanClass string `json:"scan_class,omitempty"`
ReportMode string `json:"report_mode,omitempty"`
}
PointData represents point configuration and current value for frontend display
type PointMetrics ¶
type PointMetrics struct {
PointID string `json:"pointId"` // 点位ID
LastUpdateTime time.Time `json:"lastUpdateTime"` // 最近更新时间
Quality string `json:"quality"` // 质量码: Good, Bad, Uncertain
RawValue []byte `json:"rawValue"` // 原始寄存器数据
ParsedValue any `json:"parsedValue"` // 解析后的值
DataType string `json:"dataType"` // 数据类型
ByteOrder string `json:"byteOrder"` // 字节序
UpdateCount int64 `json:"updateCount"` // 更新次数
ErrorCount int64 `json:"errorCount"` // 错误次数
LastError string `json:"lastError"` // 最后错误信息
LastErrorTime time.Time `json:"lastErrorTime"` // 最后错误时间
}
PointMetrics 点位级监控指标
type PointSourceRef ¶
type PointSourceRef struct {
ChannelID string `json:"channel_id"`
ChannelName string `json:"channel_name"`
DeviceID string `json:"device_id"`
DeviceName string `json:"device_name"`
PointID string `json:"point_id"`
PointName string `json:"point_name"`
Ref string `json:"ref"`
}
PointSourceRef 可选点位引用(供 UI 拼积木选择)
type PortCheckResult ¶
type ProtocolConfig ¶
type ProtocolConfig struct {
HeartbeatInterval int `json:"heartbeat_interval"`
}
ProtocolConfig 协议配置
type RTTNode ¶
type RTTNode struct {
SeqNo uint16 `json:"seq_no"`
SendTS time.Time `json:"send_ts"`
RecvTS time.Time `json:"recv_ts"`
AckStatus bool `json:"ack_status"`
RTT int64 `json:"rtt"`
}
RTTNode RTT统计节点
type RegisterType ¶
type RegisterType int
RegisterType 定义寄存器类型
const ( RegHolding RegisterType = iota // 0: 默认Holding寄存器 (03) RegCoil // 1: Coil (01) RegDiscreteInput // 2: Discrete Input (02) RegInput // 3: Input Register (04) RegCustom // 4: 非标准 )
func ParseRegisterType ¶
func ParseRegisterType(s string) RegisterType
func (RegisterType) FunctionCode ¶
func (r RegisterType) FunctionCode() byte
func (RegisterType) MarshalJSON ¶
func (r RegisterType) MarshalJSON() ([]byte, error)
func (RegisterType) MarshalYAML ¶
func (r RegisterType) MarshalYAML() (interface{}, error)
func (RegisterType) String ¶
func (r RegisterType) String() string
func (*RegisterType) UnmarshalJSON ¶
func (r *RegisterType) UnmarshalJSON(data []byte) error
func (*RegisterType) UnmarshalYAML ¶
func (r *RegisterType) UnmarshalYAML(unmarshal func(interface{}) error) error
type RequestRecord ¶
type RequestRecord struct {
Timestamp time.Time
Success bool
Duration time.Duration // RTT
ErrorType string // timeout, crc, exception, network
}
RequestRecord 请求记录 (用于滑动窗口统计)
type RuleAction ¶
type RuleMinuteSnapshot ¶
type RuleMinuteSnapshot struct {
RuleID string `json:"rule_id"`
RuleName string `json:"rule_name"`
Minute string `json:"minute"` // e.g. "2026-01-29 10:51"
Category string `json:"category,omitempty"`
ChannelID string `json:"channel_id,omitempty"`
DeviceID string `json:"device_id,omitempty"`
ErrorType string `json:"error_type,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
UpdatedAt time.Time `json:"updated_at"`
// Deprecated: kept for backward-compatible reads of historical bblot rows.
Status string `json:"status,omitempty"`
TriggerCount int64 `json:"trigger_count,omitempty"`
LastValue any `json:"last_value,omitempty"`
LastTrigger time.Time `json:"last_trigger,omitempty"`
}
RuleMinuteSnapshot represents a minute-level error log entry for a rule.
type RuleRuntimeState ¶
type RuleRuntimeState struct {
RuleID string `json:"rule_id"`
RuleName string `json:"rule_name"`
Enable bool `json:"enable"`
LastCheckTime time.Time `json:"last_check_time,omitempty"` // For CheckInterval
LastWindowEval time.Time `json:"last_window_eval,omitempty"` // Window aggregation step tick
LastTrigger time.Time `json:"last_trigger"`
LastValue any `json:"last_value"`
TriggerCount int64 `json:"trigger_count"`
SuccessCount int64 `json:"success_count"` // completed trigger cycles without error
FailureCount int64 `json:"failure_count"` // evaluate/dispatch/action failures
ActionSuccessCount int64 `json:"action_success_count"` // individual action successes
ActionFailureCount int64 `json:"action_failure_count"` // individual action failures
CurrentStatus string `json:"current_status"` // NORMAL, WARNING, ALARM
ConditionStart time.Time `json:"condition_start,omitempty"`
ConditionCount int `json:"condition_count,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
ActionLastRuns map[int]time.Time `json:"action_last_runs,omitempty"`
ExecutionPhase string `json:"execution_phase,omitempty"` // idle, window, evaluate, state_hold, trigger, action, completed, error
ExecutionActionIndex int `json:"execution_action_index,omitempty"` // 0-based when execution_phase=action
}
RuleRuntimeState represents the runtime status of a rule
type RuleSource ¶
type RuleSource struct {
Alias string `json:"alias" yaml:"alias"` // Variable name in expression (e.g. "t1")
ChannelID string `json:"channel_id" yaml:"channel_id"`
DeviceID string `json:"device_id" yaml:"device_id"`
PointID string `json:"point_id" yaml:"point_id"`
PointName string `json:"point_name" yaml:"point_name"`
}
type ServerConfig ¶
type ServerConfig struct {
Port int `json:"port" yaml:"port"`
LogLevel string `json:"logLevel" yaml:"logLevel"`
}
ServerConfig represents server configuration
type ShadowDevice ¶
type ShadowDevice struct {
ShadowDeviceID string `json:"shadow_device_id"`
PhysicalDeviceID string `json:"physical_device_id"`
ChannelID string `json:"channel_id"`
Version uint64 `json:"version"`
UpdatedAt time.Time `json:"updated_at"`
Points map[string]ShadowPoint `json:"points"`
// 通信画像相关字段
CommunicationProfile *DeviceCommunicationProfile `json:"communication_profile,omitempty"`
}
ShadowDevice represents a real shadow device (physical device shadow)
type ShadowDiffPoint ¶
type ShadowDiffPoint struct {
PointID string `json:"point_id"`
Field string `json:"field"` // "value", "version", "timestamp", "quality"
Expected any `json:"expected"`
Actual any `json:"actual"`
}
ShadowDiffPoint represents a difference found during consistency check
type ShadowIngressMessage ¶
type ShadowIngressMessage struct {
MessageID string `json:"message_id"`
QoS int `json:"qos"` // 0, 1, 2
DeviceID string `json:"device_id"`
ChannelID string `json:"channel_id"`
Timestamp time.Time `json:"timestamp"`
Points []ShadowIngressPoint `json:"points"`
Meta ShadowIngressMeta `json:"meta"`
}
ShadowIngressMessage represents the standard message format from Points layer to ShadowIngress
type ShadowIngressMeta ¶
ShadowIngressMeta represents metadata in the ingress message
type ShadowIngressPoint ¶
type ShadowIngressPoint struct {
PointID string `json:"point_id"`
Value any `json:"value"`
Unit string `json:"unit"`
Quality string `json:"quality"`
SamplePeriodMs int `json:"sample_period_ms"`
CollectedAt time.Time `json:"collected_at"` // 设备侧采集时间
Degraded bool `json:"degraded,omitempty"`
}
ShadowIngressPoint represents a single point in the ingress message
type ShadowPoint ¶
type ShadowPoint struct {
Value any `json:"value"`
PreviousValue any `json:"previous_value,omitempty"` // notify-only: prior value before this delta
Unit string `json:"unit"`
RW string `json:"rw"` // "r" or "rw"
SamplePeriodMs int `json:"sample_period_ms"`
Quality string `json:"quality"`
Degraded bool `json:"degraded,omitempty"` // 点位降级标记
Timestamp time.Time `json:"timestamp"` // 采集时间(兼容旧字段)
CollectedAt time.Time `json:"collected_at"` // 采集时间
UpdatedAt time.Time `json:"updated_at"` // 影子更新时间
Version uint64 `json:"version"`
}
ShadowPoint represents a single point in a shadow device
type ShadowWriteRequest ¶
type ShadowWriteRequest struct {
ShadowDeviceID string `json:"shadow_device_id"`
PointID string `json:"point_id"`
Value any `json:"value"`
QoS int `json:"qos"`
Timestamp time.Time `json:"timestamp"`
}
ShadowWriteRequest represents a write request to shadow device
type ShadowWriteResponse ¶
type ShadowWriteResponse struct {
Success bool `json:"success"`
Version uint64 `json:"version"`
Timestamp time.Time `json:"timestamp"`
Error string `json:"error,omitempty"`
}
ShadowWriteResponse represents a write response from shadow device
type SourceDeviceSummary ¶
type SourceDeviceSummary struct {
Key string `json:"key"`
ChannelID string `json:"channel_id"`
ChannelName string `json:"channel_name"`
DeviceID string `json:"device_id"`
DeviceName string `json:"device_name"`
PointCount int `json:"point_count"`
State int `json:"state,omitempty"` // 0=Online, 1=Unstable, 2=Offline, 3=Quarantine
Online bool `json:"online"`
}
SourceDeviceSummary 源设备摘要(供 UI 检索列表,不含全量点位)
type SouthboundManager ¶
type SouthboundManager interface {
GetChannels() []Channel
GetChannelDevices(channelID string) []Device
GetDevice(channelID, deviceID string) *Device
WritePoint(channelID, deviceID, pointID string, value any) error
GetDevicePoints(channelID, deviceID string) ([]PointData, error)
// GetShadowPoint 从影子设备实时快照中读取单个点位数据。
// 供 OPC UA Server 的 ReadHandler 调用,使第三方客户端能按需获取实时值。
GetShadowPoint(channelID, deviceID, pointID string) (*ShadowPoint, error)
}
SouthboundManager interface defines methods required by Northbound components to interact with southbound devices (e.g. for building address space or writing values)
type SparkplugBConfig ¶
type SparkplugBConfig struct {
ID string `json:"id" yaml:"id"`
Name string `json:"name" yaml:"name"`
Enable bool `json:"enable" yaml:"enable"`
ClientID string `json:"client_id" yaml:"client_id"`
GroupID string `json:"group_id" yaml:"group_id"`
NodeID string `json:"node_id" yaml:"node_id"`
EnableAlias bool `json:"enable_alias" yaml:"enable_alias"`
GroupPath bool `json:"group_path" yaml:"group_path"`
OfflineCache bool `json:"offline_cache" yaml:"offline_cache"`
CacheMemSize int `json:"cache_mem_size" yaml:"cache_mem_size"`
CacheDiskSize int `json:"cache_disk_size" yaml:"cache_disk_size"`
CacheResendInt int `json:"cache_resend_int" yaml:"cache_resend_int"`
Broker string `json:"broker" yaml:"broker"`
Port int `json:"port" yaml:"port"`
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"`
SSL bool `json:"ssl" yaml:"ssl"`
CACert string `json:"ca_cert" yaml:"ca_cert"`
ClientCert string `json:"client_cert" yaml:"client_cert"`
ClientKey string `json:"client_key" yaml:"client_key"`
KeyPassword string `json:"key_password" yaml:"key_password"`
Devices OpcUaDeviceMap `json:"devices" yaml:"devices"` // Key: DeviceID; legacy bool or DevicePublishConfig
VirtualDevices OpcUaDeviceMap `json:"virtual_devices" yaml:"virtual_devices"`
}
type StateConfig ¶
type StaticRoute ¶
type StaticRoute struct {
Destination string `json:"destination"`
Prefix int `json:"prefix"`
Gateway string `json:"gateway"`
Interface string `json:"interface"`
Metric int `json:"metric"`
Enabled bool `json:"enabled"`
}
StaticRoute represents a static routing rule
type SyncConfig ¶
type SyncConfig struct {
Enabled bool `json:"enabled" yaml:"enabled"`
Port int `json:"port,omitempty" yaml:"port,omitempty"`
}
SyncConfig controls multi-node configuration sync (libp2p gossip).
type SystemConfig ¶
type SystemConfig struct {
Sync SyncConfig `json:"sync,omitempty" yaml:"sync,omitempty"`
Time TimeConfig `json:"time"`
Network []NetworkInterface `json:"network"`
Routes []StaticRoute `json:"routes"`
HA HAConfig `json:"ha"`
Hostname HostnameConfig `json:"hostname"`
Location string `json:"location"`
LDAP LDAPConfig `json:"ldap"`
ConnectivityTargets []ConnectivityTarget `json:"connectivity_targets,omitempty"`
}
SystemConfig aggregates all system settings
type ThresholdConfig ¶
type ThresholdConfig struct {
High float64 `json:"high" yaml:"high"`
Low float64 `json:"low" yaml:"low"`
}
ThresholdConfig defines alarm thresholds for a point
type TimeConfig ¶
type TimeConfig struct {
Mode string `json:"mode"` // manual, ntp
Manual ManualTime `json:"manual"`
NTP NTPConfig `json:"ntp"`
}
TimeConfig represents system time settings
type TrendPoint ¶
TrendPoint 趋势数据点
type UserConfig ¶
type UserConfig struct {
Username string `json:"username" yaml:"username"`
Password string `json:"password" yaml:"password"` // Plain text (or hashed, but simple for now)
Role string `json:"role" yaml:"role"`
}
UserConfig represents a user configuration
type Value ¶
type Value struct {
ChannelID string `json:"channel_id"`
DeviceID string `json:"device_id"`
PointID string `json:"point_id"`
Value any `json:"value"`
Quality string `json:"quality"`
TS time.Time `json:"timestamp"`
CachedAt time.Time `json:"cachedAt,omitempty"`
Meta map[string]any `json:"meta,omitempty"`
}
Value represents the standardized output of a collected point
type VirtualDevice ¶
type VirtualDevice struct {
VirtualDeviceID string `json:"virtual_device_id"`
ChannelID string `json:"channel_id,omitempty"`
Version uint64 `json:"version"`
UpdatedAt time.Time `json:"updated_at"`
FormulaPoints map[string]string `json:"formula_points"` // pointID -> formula
Dependencies []string `json:"dependencies"` // list of dependent point keys
Points map[string]ShadowPoint `json:"points"` // computed values
}
VirtualDevice represents a virtual shadow device with formula-based points
type VirtualShadowDeviceConfig ¶
type VirtualShadowDeviceConfig struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
Enable bool `json:"enable"`
Points []VirtualShadowPointDef `json:"points"`
}
VirtualShadowDeviceConfig 虚拟影子设备配置(持久化)
type VirtualShadowPointDef ¶
type VirtualShadowPointDef struct {
PointID string `json:"point_id"`
Name string `json:"name,omitempty"`
Unit string `json:"unit,omitempty"`
Mode string `json:"mode"` // "map" 直接映射 | "formula" 公式计算
SourceRef string `json:"source_ref,omitempty"` // map 模式:ch1.dev1.temp
Formula string `json:"formula,omitempty"` // formula 模式
}
VirtualShadowPointDef 虚拟影子点位定义(UI 配置)
type WindowConfig ¶
type WindowConfig struct {
Type string `json:"type" yaml:"type"` // sliding, tumbling
Size string `json:"size" yaml:"size"` // e.g. "10s", "100" (count)
Interval string `json:"interval" yaml:"interval"` // Step size for sliding
AggrFunc string `json:"aggr_func" yaml:"aggr_func"` // avg, min, max, sum, count
}