model

package
v0.0.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 26, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ScanClassFast   = "fast"
	ScanClassNormal = "normal"
	ScanClassSlow   = "slow"
)

Variables

View Source
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 EnsureChannelID

func EnsureChannelID(ch *Channel) error

EnsureChannelID 确保通道具有非空 ID(优先使用 id,其次 name)。

func EnsureDeviceID

func EnsureDeviceID(dev *Device) error

EnsureDeviceID 确保设备具有非空 ID(优先使用 id,其次 name)。

func EnsureEdgeRuleID

func EnsureEdgeRuleID(rule *EdgeRule) error

EnsureEdgeRuleID 确保边缘规则具有非空 ID(优先使用 id,其次 name)。

func EnsurePointID

func EnsurePointID(p *Point) error

EnsurePointID 确保点位具有非空 ID(优先使用 id,其次 name)。

func GroupPointsByScanClass

func GroupPointsByScanClass(points []Point) map[string][]Point

GroupPointsByScanClass 按扫描类分组点位;未标注的点位归入 normal。

func MakePointRef

func MakePointRef(channelID, deviceID, pointID string) string

MakePointRef 构造公式/依赖引用:channel.device.point

func MatchSearchQuery

func MatchSearchQuery(haystack, query string) bool

MatchSearchQuery 多关键词模糊检索(空格分词,子串或字符顺序匹配)。

func MergeOpcUaDeviceConfig

func MergeOpcUaDeviceConfig(channelConfig, deviceConfig map[string]any) map[string]any

MergeOpcUaDeviceConfig 合并通道与设备 OPC UA 配置(设备字段覆盖通道同名字段),并规范化 endpoint。

func NormalizeOpcUaChannelConfig

func NormalizeOpcUaChannelConfig(config map[string]any)

NormalizeOpcUaChannelConfig 统一通道配置中的 url 与 endpoint 字段。

func NormalizeScanClass

func NormalizeScanClass(scanClass string) string

NormalizeScanClass 归一化扫描类名称;空值视为 normal。

func NormalizeVirtualShadowDevice

func NormalizeVirtualShadowDevice(cfg *VirtualShadowDeviceConfig) error

NormalizeVirtualShadowDevice 校验并规范化虚拟影子设备配置。

func ResolveOpcUaEndpoint

func ResolveOpcUaEndpoint(channelConfig, deviceConfig map[string]any) string

ResolveOpcUaEndpoint 解析 OPC UA 连接地址:设备 endpoint 优先,其次通道 url / endpoint。

func ScanClassInterval

func ScanClassInterval(scanClass string, deviceInterval Duration) time.Duration

ScanClassInterval 返回扫描类对应的采集周期;未知类回退到设备默认间隔。

func SetGlobalMetricsCollector

func SetGlobalMetricsCollector(mc *MetricsCollector)

SetGlobalMetricsCollector sets the shared collector instance

Types

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"` // 该通道下的设备列表
	StopChan chan struct{}  `json:"-" yaml:"-"`
	// 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)
	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"`

	// 时间戳
	Timestamp time.Time `json:"timestamp"`
}

ChannelMetrics 通道级监控指标

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

type CycleRecord struct {
	Timestamp time.Time
	Success   bool
}

CycleRecord 周期记录 (一轮采集的结果)

type DataCacheConfig

type DataCacheConfig struct {
	Enable        bool   `json:"enable" yaml:"enable"`
	MaxCount      int    `json:"max_count" yaml:"max_count"`           // Default 1000
	FlushInterval string `json:"flush_interval" yaml:"flush_interval"` // e.g. "1m"
}

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"`
	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"`                         // 该设备的点位列表
	State            int            `json:"state" yaml:"-"`                                                   // 运行时状态:0=Online, 1=Unstable, 2=Offline, 3=Quarantine
	QualityScore     int            `json:"quality_score" yaml:"-"`                                           // 质量评分 (0-100)
	StopChan         chan struct{}  `json:"-" yaml:"-"`
	// Runtime state fields
	NodeRuntime *NodeRuntime `json:"runtime,omitempty" yaml:"-"`
}

Device represents a device configuration (within a channel)

func NormalizeDevicesForSave

func NormalizeDevicesForSave(devices []Device) ([]Device, error)

NormalizeDevicesForSave 校验并去重设备列表,供配置持久化使用。

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")
}

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

type Duration time.Duration

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

func (Duration) MarshalText

func (d Duration) MarshalText() ([]byte, error)

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(b []byte) error

func (*Duration) UnmarshalText

func (d *Duration) UnmarshalText(text []byte) error

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"
	Devices              map[string]DevicePublishConfig `json:"devices" yaml:"devices"`                       // Key: DeviceID, Value: DevicePublishConfig
}

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"
	Devices             map[string]DevicePublishConfig `json:"devices" yaml:"devices"`                       // Key: DeviceID, Value: DevicePublishConfig
}

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

func NormalizeEdgeRulesForSave(rules []EdgeRule) ([]EdgeRule, error)

NormalizeEdgeRulesForSave 校验并去重边缘规则列表,供 edge.db 持久化使用。

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 FailedAction struct {
	ID         string         `json:"id"`
	RuleID     string         `json:"rule_id"`
	Action     RuleAction     `json:"action"`
	Value      Value          `json:"value"`
	Timestamp  time.Time      `json:"timestamp"`
	RetryCount int            `json:"retry_count"`
	LastError  string         `json:"last_error"`
	Env        map[string]any `json:"env"`
}

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             map[string]bool   `json:"devices" yaml:"devices"` // Key: DeviceID, Value: Enable
}

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 InstallResult struct {
	Success bool   `json:"success"`
	Message string `json:"message"`
	Error   string `json:"error,omitempty"`
}

type InstallStatus

type InstallStatus struct {
	IsInstalled bool     `json:"isInstalled"`
	CurrentStep int      `json:"currentStep"`
	TotalSteps  int      `json:"totalSteps"`
	Progress    int      `json:"progress"`
	Status      string   `json:"status"`
	LogMessages []string `json:"logMessages"`
}

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"`
}

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 ManualTime struct {
	Datetime string `json:"datetime"` // YYYY-MM-DD HH:MM:SS
	Timezone string `json:"timezone"`
	SyncRTC  bool   `json:"sync_rtc"`
}

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 保存点位调试信息(原始字节 + 解析后值)

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 NTPConfig

type NTPConfig struct {
	Servers  []string `json:"servers"`
	Interval int      `json:"interval"` // Hours
	Enabled  bool     `json:"enabled"`
}

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"`
	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
}

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=false 的条目会被排除。

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 PathCheckResult struct {
	Accessible bool   `json:"accessible"`
	Path       string `json:"path"`
	Error      string `json:"error,omitempty"`
}

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
	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"`
	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
}

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 PortCheckResult struct {
	Available bool   `json:"available"`
	Port      int    `json:"port"`
	Error     string `json:"error,omitempty"`
}

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) Code

func (r RegisterType) Code() byte

Code 返回Modbus功能码

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) ShortString

func (r RegisterType) ShortString() string

ShortString 返回短名称

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 RuleAction struct {
	Type   string         `json:"type" yaml:"type"` // mqtt, http, log, command
	Config map[string]any `json:"config" yaml:"config"`
}

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"
	Status       string    `json:"status"`
	TriggerCount int64     `json:"trigger_count"`
	LastValue    any       `json:"last_value"`
	LastTrigger  time.Time `json:"last_trigger"`
	ErrorMessage string    `json:"error_message,omitempty"`
	UpdatedAt    time.Time `json:"updated_at"`
}

RuleMinuteSnapshot represents a minute-level summary of rule execution

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
	LastTrigger    time.Time         `json:"last_trigger"`
	LastValue      any               `json:"last_value"`
	TriggerCount   int64             `json:"trigger_count"`
	CurrentStatus  string            `json:"current_status"` // NORMAL, 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"`
}

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

type ShadowIngressMeta struct {
	Source   string `json:"source"`
	Sequence uint64 `json:"sequence"`
}

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"`
	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"`
}

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        map[string]bool `json:"devices" yaml:"devices"` // Key: DeviceID, Value: Enable
}

type StateConfig

type StateConfig struct {
	Duration string `json:"duration" yaml:"duration"` // e.g. "10s" (Hold time)
	Count    int    `json:"count" yaml:"count"`       // Consecutive count
}

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

type TrendPoint struct {
	Time time.Time `json:"time"` // 时间点
	Rate float64   `json:"rate"` // 成功率
}

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"`
	ChannelID   string                  `json:"channel_id"`
	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
}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL