package main import ( "bytes" "context" "database/sql" "embed" "encoding/json" "errors" "fmt" "html/template" "log" "math" "net/http" "os" "os/signal" "path/filepath" "strconv" "strings" "sync" "syscall" "time" _ "github.com/mattn/go-sqlite3" "github.com/robinson/gos7" "gopkg.in/yaml.v3" ) //go:embed static var staticFiles embed.FS const version = "0.7.1" // --------------------------------------------------------------------------- // Config structs // --------------------------------------------------------------------------- type Config struct { Server ServerConfig `yaml:"server"` PLC PLCConfig `yaml:"plc"` Thresholds ThresholdsConfig `yaml:"thresholds"` Trend TrendConfig `yaml:"trend"` Press PressConfig `yaml:"press"` UI UIConfig `yaml:"ui"` DB DBConfig `yaml:"db"` } type ServerConfig struct { ListenAddr string `yaml:"listen_addr"` } type PLCConfig struct { IP string `yaml:"ip"` DBNum int `yaml:"db_num"` Rack int `yaml:"rack"` Slot int `yaml:"slot"` PollMs int `yaml:"poll_ms"` ConnectTimeoutSec int `yaml:"connect_timeout_sec"` IdleTimeoutSec int `yaml:"idle_timeout_sec"` ReconnectDelaySec int `yaml:"reconnect_delay_sec"` } type ThresholdsConfig struct { WarningPercent float64 `yaml:"warning_percent"` CriticalPercent float64 `yaml:"critical_percent"` GaugeMaxPercent float64 `yaml:"gauge_max_percent"` ImbalanceWarningPercent float64 `yaml:"imbalance_warning_percent"` ImbalanceCriticalPercent float64 `yaml:"imbalance_critical_percent"` LegacyWarningKn float64 `yaml:"warning_kn,omitempty"` LegacyCriticalKn float64 `yaml:"critical_kn,omitempty"` LegacyMaxKn float64 `yaml:"max_kn,omitempty"` } type TrendConfig struct { Minutes int `yaml:"minutes"` } // PressConfig: Go field is MaxTonnage (idiomatic). YAML tag kept as MAX_TONNAGE // so existing config files need no changes. LegacyMaxTonnage handles old // configs that used the lowercase "max_tonnage" key. type PressConfig struct { MaxTonnage float64 `yaml:"MAX_TONNAGE"` LegacyMaxTonnage float64 `yaml:"max_tonnage,omitempty"` } type UIConfig struct { Title string `yaml:"title"` Subtitle string `yaml:"subtitle"` LeftLabel string `yaml:"left_label"` RightLabel string `yaml:"right_label"` UnitForce string `yaml:"unit_force"` UnitPct string `yaml:"unit_percent"` } type DBConfig struct { Path string `yaml:"path"` BusyTimeoutMs int `yaml:"busy_timeout_ms"` BatchSize int `yaml:"batch_size"` FlushIntervalMs int `yaml:"flush_interval_ms"` RetentionDays int `yaml:"retention_days"` MaxChartPoints int `yaml:"max_chart_points"` WriterQueueSize int `yaml:"writer_queue_size"` AlarmQueueSize int `yaml:"alarm_queue_size"` CheckpointPages int `yaml:"checkpoint_pages"` CleanupIntervalHr int `yaml:"cleanup_interval_hours"` } func defaultConfig() Config { return Config{ Server: ServerConfig{ ListenAddr: ":8080", }, PLC: PLCConfig{ IP: "192.168.0.1", DBNum: 1001, Rack: 0, Slot: 1, PollMs: 500, ConnectTimeoutSec: 5, IdleTimeoutSec: 5, ReconnectDelaySec: 5, }, Thresholds: ThresholdsConfig{ WarningPercent: 80, CriticalPercent: 95, GaugeMaxPercent: 130, ImbalanceWarningPercent: 10, ImbalanceCriticalPercent: 20, }, Trend: TrendConfig{ Minutes: 5, }, Press: PressConfig{ MaxTonnage: 64, }, UI: UIConfig{ Title: "Force Monitor", Subtitle: "Siemens S7-1215C • Piezo peak/stroke input • PLC values in % • kN calculated from MAX_TONNAGE", LeftLabel: "LEVI STEBER", RightLabel: "DESNI STEBER", UnitForce: "kN", UnitPct: "%", }, DB: DBConfig{ Path: "force_monitor.db", BusyTimeoutMs: 5000, BatchSize: 32, FlushIntervalMs: 1000, RetentionDays: 30, MaxChartPoints: 2000, WriterQueueSize: 4096, AlarmQueueSize: 512, CheckpointPages: 1000, CleanupIntervalHr: 6, }, } } // --------------------------------------------------------------------------- // Config normalisation helpers — eliminate repetitive if-chains // --------------------------------------------------------------------------- func setIfZeroF(dst *float64, def float64) { if *dst <= 0 { *dst = def } } func setIfZeroI(dst *int, def int) { if *dst <= 0 { *dst = def } } func setIfEmpty(dst *string, def string) { if strings.TrimSpace(*dst) == "" { *dst = def } } func normalizeConfig(cfg *Config) { def := defaultConfig() setIfEmpty(&cfg.Server.ListenAddr, def.Server.ListenAddr) setIfEmpty(&cfg.PLC.IP, def.PLC.IP) setIfZeroI(&cfg.PLC.DBNum, def.PLC.DBNum) setIfZeroI(&cfg.PLC.PollMs, def.PLC.PollMs) setIfZeroI(&cfg.PLC.ConnectTimeoutSec, def.PLC.ConnectTimeoutSec) setIfZeroI(&cfg.PLC.IdleTimeoutSec, def.PLC.IdleTimeoutSec) setIfZeroI(&cfg.PLC.ReconnectDelaySec, def.PLC.ReconnectDelaySec) // Legacy threshold key migration (warning_kn / critical_kn / max_kn) if cfg.Thresholds.WarningPercent <= 0 && cfg.Thresholds.LegacyWarningKn > 0 { cfg.Thresholds.WarningPercent = cfg.Thresholds.LegacyWarningKn } if cfg.Thresholds.CriticalPercent <= 0 && cfg.Thresholds.LegacyCriticalKn > 0 { cfg.Thresholds.CriticalPercent = cfg.Thresholds.LegacyCriticalKn } if cfg.Thresholds.GaugeMaxPercent <= 0 && cfg.Thresholds.LegacyMaxKn > 0 { cfg.Thresholds.GaugeMaxPercent = cfg.Thresholds.LegacyMaxKn } setIfZeroF(&cfg.Thresholds.WarningPercent, def.Thresholds.WarningPercent) setIfZeroF(&cfg.Thresholds.CriticalPercent, def.Thresholds.CriticalPercent) setIfZeroF(&cfg.Thresholds.GaugeMaxPercent, def.Thresholds.GaugeMaxPercent) setIfZeroF(&cfg.Thresholds.ImbalanceWarningPercent, def.Thresholds.ImbalanceWarningPercent) setIfZeroF(&cfg.Thresholds.ImbalanceCriticalPercent, def.Thresholds.ImbalanceCriticalPercent) if cfg.Thresholds.ImbalanceCriticalPercent < cfg.Thresholds.ImbalanceWarningPercent { cfg.Thresholds.ImbalanceCriticalPercent = cfg.Thresholds.ImbalanceWarningPercent } setIfZeroI(&cfg.Trend.Minutes, def.Trend.Minutes) // Legacy press tonnage key migration (max_tonnage lowercase) if cfg.Press.MaxTonnage <= 0 && cfg.Press.LegacyMaxTonnage > 0 { cfg.Press.MaxTonnage = cfg.Press.LegacyMaxTonnage } setIfZeroF(&cfg.Press.MaxTonnage, def.Press.MaxTonnage) setIfEmpty(&cfg.UI.Title, def.UI.Title) setIfEmpty(&cfg.UI.Subtitle, def.UI.Subtitle) setIfEmpty(&cfg.UI.LeftLabel, def.UI.LeftLabel) setIfEmpty(&cfg.UI.RightLabel, def.UI.RightLabel) setIfEmpty(&cfg.UI.UnitForce, def.UI.UnitForce) setIfEmpty(&cfg.UI.UnitPct, def.UI.UnitPct) setIfEmpty(&cfg.DB.Path, def.DB.Path) setIfZeroI(&cfg.DB.BusyTimeoutMs, def.DB.BusyTimeoutMs) setIfZeroI(&cfg.DB.BatchSize, def.DB.BatchSize) setIfZeroI(&cfg.DB.FlushIntervalMs, def.DB.FlushIntervalMs) setIfZeroI(&cfg.DB.RetentionDays, def.DB.RetentionDays) setIfZeroI(&cfg.DB.MaxChartPoints, def.DB.MaxChartPoints) setIfZeroI(&cfg.DB.WriterQueueSize, def.DB.WriterQueueSize) setIfZeroI(&cfg.DB.AlarmQueueSize, def.DB.AlarmQueueSize) setIfZeroI(&cfg.DB.CheckpointPages, def.DB.CheckpointPages) setIfZeroI(&cfg.DB.CleanupIntervalHr, def.DB.CleanupIntervalHr) } func loadOrCreateConfig(configPath string) (Config, error) { cfg := defaultConfig() _, err := os.Stat(configPath) if errors.Is(err, os.ErrNotExist) { data, marshalErr := yaml.Marshal(&cfg) if marshalErr != nil { return cfg, fmt.Errorf("failed to marshal default config: %w", marshalErr) } if writeErr := os.WriteFile(configPath, data, 0644); writeErr != nil { return cfg, fmt.Errorf("failed to create config file: %w", writeErr) } log.Printf("config file not found, created default config: %s", configPath) return cfg, nil } if err != nil { return cfg, fmt.Errorf("failed to stat config file: %w", err) } data, err := os.ReadFile(configPath) if err != nil { return cfg, fmt.Errorf("failed to read config file: %w", err) } if err := yaml.Unmarshal(data, &cfg); err != nil { return cfg, fmt.Errorf("failed to parse config file: %w", err) } normalizeConfig(&cfg) return cfg, nil } // --------------------------------------------------------------------------- // Domain types // --------------------------------------------------------------------------- type Sample struct { TS time.Time SilaLPct float32 SilaRPct float32 SilaLKN float32 SilaRKN float32 SumPercent float32 SumKN float32 ImbalancePercent float32 BiasPercent float32 } type AlarmEvent struct { TS time.Time Severity string Source string Code string State string Message string Value float64 Limit float64 } type AppState struct { sync.RWMutex Connected bool SilaL float32 SilaR float32 SilaLkN float32 SilaRkN float32 SumPercent float32 SumkN float32 ImbalancePercent float32 BiasPercent float32 LastUpdate time.Time DroppedSamples uint64 DroppedEvents uint64 } type APIState struct { Connected bool `json:"connected"` SilaL float32 `json:"sila_l"` SilaR float32 `json:"sila_r"` SilaLkN float32 `json:"sila_l_kn"` SilaRkN float32 `json:"sila_r_kn"` SumPercent float32 `json:"sum_percent"` SumkN float32 `json:"sum_kn"` ImbalancePercent float32 `json:"imbalance_percent"` BiasPercent float32 `json:"bias_percent"` LastUpdate string `json:"last_update"` DroppedSamples uint64 `json:"dropped_samples"` DroppedEvents uint64 `json:"dropped_events"` } type HistoryPoint struct { Time string `json:"time"` SilaL float32 `json:"sila_l"` SilaR float32 `json:"sila_r"` } type HistoryResponse struct { Window string `json:"window"` Points []HistoryPoint `json:"points"` } type TrendResponse struct { Window string `json:"window"` AvgPeak5m float32 `json:"avg_peak_5m"` AvgPeak1h float32 `json:"avg_peak_1h"` AvgImbalance5m float32 `json:"avg_imbalance_5m"` AvgImbalance1h float32 `json:"avg_imbalance_1h"` ForceDeltaPct float32 `json:"force_delta_pct"` ImbalanceDeltaPct float32 `json:"imbalance_delta_pct"` ForceDirection string `json:"force_direction"` ImbalanceDirection string `json:"imbalance_direction"` ProcessStability string `json:"process_stability"` StabilityReason string `json:"stability_reason"` ForceStdDev float32 `json:"force_stddev"` ImbalanceStdDev float32 `json:"imbalance_stddev"` SampleCount int `json:"sample_count"` OldHalfCount int `json:"old_half_count"` NewHalfCount int `json:"new_half_count"` } type AlarmEventAPI struct { Time string `json:"time"` Severity string `json:"severity"` Source string `json:"source"` State string `json:"state"` Message string `json:"message"` Value float64 `json:"value"` Limit float64 `json:"limit"` } type AlarmResponse struct { Events []AlarmEventAPI `json:"events"` } type PageData struct { Title string Subtitle string LeftLabel string RightLabel string UnitForce string UnitPct string MaxTonnage float64 WarningPercent float64 CriticalPercent float64 GaugeMaxPercent float64 ImbalanceWarningPercent float64 ImbalanceCriticalPercent float64 PollMs int DefaultWindow string DefaultTrendWindow string } type NumericStats struct { Avg float64 AvgSq float64 Min float64 Max float64 Count int } func (s NumericStats) StdDev() float64 { if s.Count <= 1 { return 0 } v := s.AvgSq - (s.Avg * s.Avg) if v < 0 { v = 0 } return math.Sqrt(v) } type AlarmTracker struct { sync.Mutex PLCKnown bool PLCConnected bool LeftZone string RightZone string ImbZone string } // --------------------------------------------------------------------------- // Package-level singletons // --------------------------------------------------------------------------- var ( cfg Config state AppState db *sql.DB sampleCh chan Sample alarmCh chan AlarmEvent alarmTracker AlarmTracker uiTemplate = template.Must(template.New("ui").Parse(uiHTML)) cachedUI []byte // pre-rendered template (PageData is immutable after startup) ) // --------------------------------------------------------------------------- // Force calculation — accepts maxTonnage explicitly (testable, no global dep) // --------------------------------------------------------------------------- func calculateForces(leftPercent, rightPercent float32, maxTonnage float64) (leftKN, rightKN, sumPercent, sumKN float32) { lp := float64(leftPercent) rp := float64(rightPercent) sumPct := (lp + rp) / 2.0 left := (lp / 100.0) * (maxTonnage / 2.0) right := (rp / 100.0) * (maxTonnage / 2.0) total := (sumPct / 100.0) * maxTonnage return float32(left), float32(right), float32(sumPct), float32(total) } // --------------------------------------------------------------------------- // State helpers // --------------------------------------------------------------------------- func snapshotState() APIState { state.RLock() defer state.RUnlock() lastUpdate := "" if !state.LastUpdate.IsZero() { lastUpdate = state.LastUpdate.Format(time.RFC3339Nano) } return APIState{ Connected: state.Connected, SilaL: state.SilaL, SilaR: state.SilaR, SilaLkN: state.SilaLkN, SilaRkN: state.SilaRkN, SumPercent: state.SumPercent, SumkN: state.SumkN, ImbalancePercent: state.ImbalancePercent, BiasPercent: state.BiasPercent, LastUpdate: lastUpdate, DroppedSamples: state.DroppedSamples, DroppedEvents: state.DroppedEvents, } } func markDisconnected(reason string) { state.Lock() state.Connected = false state.Unlock() maybeLogPLCDisconnected(reason) } func enqueueSample(s Sample) { select { case sampleCh <- s: default: state.Lock() state.DroppedSamples++ state.Unlock() } } func enqueueAlarm(a AlarmEvent) { select { case alarmCh <- a: default: state.Lock() state.DroppedEvents++ state.Unlock() } } // --------------------------------------------------------------------------- // Database initialisation // --------------------------------------------------------------------------- // ensureColumn adds a column to tableName if it does not already exist. // NOTE: tableName and columnName are always hardcoded call-site constants — // never derived from user input — so fmt.Sprintf is safe here. func ensureColumn(database *sql.DB, tableName, columnName, definition string) error { rows, err := database.Query(fmt.Sprintf("PRAGMA table_info(%s)", tableName)) if err != nil { return err } defer rows.Close() found := false for rows.Next() { var cid int var name, ctype string var notNull int var dfltValue sql.NullString var pk int if err := rows.Scan(&cid, &name, &ctype, ¬Null, &dfltValue, &pk); err != nil { return err } if name == columnName { found = true break } } if err := rows.Err(); err != nil { return err } if found { return nil } _, err = database.Exec(fmt.Sprintf("ALTER TABLE %s ADD COLUMN %s %s", tableName, columnName, definition)) return err } func initDatabase(dbPath string) (*sql.DB, error) { dsn := fmt.Sprintf("file:%s?_busy_timeout=%d&_foreign_keys=on", filepath.ToSlash(dbPath), cfg.DB.BusyTimeoutMs) database, err := sql.Open("sqlite3", dsn) if err != nil { return nil, fmt.Errorf("open sqlite: %w", err) } database.SetMaxOpenConns(1) database.SetMaxIdleConns(1) database.SetConnMaxLifetime(0) pragmas := []string{ "PRAGMA journal_mode=WAL;", "PRAGMA synchronous=NORMAL;", fmt.Sprintf("PRAGMA wal_autocheckpoint=%d;", cfg.DB.CheckpointPages), fmt.Sprintf("PRAGMA busy_timeout=%d;", cfg.DB.BusyTimeoutMs), "PRAGMA temp_store=MEMORY;", } for _, q := range pragmas { if _, err := database.Exec(q); err != nil { _ = database.Close() return nil, fmt.Errorf("sqlite pragma failed (%s): %w", q, err) } } schema := ` CREATE TABLE IF NOT EXISTS samples ( id INTEGER PRIMARY KEY AUTOINCREMENT, ts DATETIME NOT NULL, ts_unix_ns INTEGER NOT NULL DEFAULT 0, sila_l_pct REAL NOT NULL, sila_r_pct REAL NOT NULL, sila_l_kn REAL NOT NULL, sila_r_kn REAL NOT NULL, sum_pct REAL NOT NULL, sum_kn REAL NOT NULL, imbalance_pct REAL NOT NULL DEFAULT 0, bias_pct REAL NOT NULL DEFAULT 0 ); CREATE INDEX IF NOT EXISTS idx_samples_ts ON samples(ts); CREATE INDEX IF NOT EXISTS idx_samples_ts_unix_ns ON samples(ts_unix_ns); CREATE TABLE IF NOT EXISTS alarm_events ( id INTEGER PRIMARY KEY AUTOINCREMENT, ts DATETIME NOT NULL, ts_unix_ns INTEGER NOT NULL DEFAULT 0, severity TEXT NOT NULL, source TEXT NOT NULL, code TEXT NOT NULL, state TEXT NOT NULL, message TEXT NOT NULL, value REAL NOT NULL DEFAULT 0, limit_value REAL NOT NULL DEFAULT 0 ); CREATE INDEX IF NOT EXISTS idx_alarm_events_ts_unix_ns ON alarm_events(ts_unix_ns DESC); ` if _, err := database.Exec(schema); err != nil { _ = database.Close() return nil, fmt.Errorf("create schema: %w", err) } if err := ensureColumn(database, "samples", "ts_unix_ns", "INTEGER NOT NULL DEFAULT 0"); err != nil { _ = database.Close() return nil, fmt.Errorf("ensure ts_unix_ns column: %w", err) } if err := ensureColumn(database, "samples", "imbalance_pct", "REAL NOT NULL DEFAULT 0"); err != nil { _ = database.Close() return nil, fmt.Errorf("ensure imbalance_pct column: %w", err) } if err := ensureColumn(database, "samples", "bias_pct", "REAL NOT NULL DEFAULT 0"); err != nil { _ = database.Close() return nil, fmt.Errorf("ensure bias_pct column: %w", err) } if _, err := database.Exec(`CREATE INDEX IF NOT EXISTS idx_samples_ts_unix_ns ON samples(ts_unix_ns)`); err != nil { _ = database.Close() return nil, fmt.Errorf("create ts_unix_ns index: %w", err) } if _, err := database.Exec(` UPDATE samples SET ts_unix_ns = CAST(strftime('%s', ts) AS INTEGER) * 1000000000 WHERE ts_unix_ns = 0 AND ts IS NOT NULL `); err != nil { log.Printf("warning: ts_unix_ns backfill failed: %v", err) } if _, err := database.Exec(` UPDATE alarm_events SET ts_unix_ns = CAST(strftime('%s', ts) AS INTEGER) * 1000000000 WHERE ts_unix_ns = 0 AND ts IS NOT NULL `); err != nil { log.Printf("warning: alarm ts_unix_ns backfill failed: %v", err) } return database, nil } // --------------------------------------------------------------------------- // DB writer goroutines — both now respect config values and context shutdown // --------------------------------------------------------------------------- func startDBWriter(ctx context.Context, database *sql.DB) { ticker := time.NewTicker(time.Duration(cfg.DB.FlushIntervalMs) * time.Millisecond) defer ticker.Stop() batch := make([]Sample, 0, cfg.DB.BatchSize) flush := func() { if len(batch) == 0 { return } tx, err := database.Begin() if err != nil { log.Printf("db begin failed: %v", err) return } stmt, err := tx.Prepare(` INSERT INTO samples ( ts, ts_unix_ns, sila_l_pct, sila_r_pct, sila_l_kn, sila_r_kn, sum_pct, sum_kn, imbalance_pct, bias_pct ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) `) if err != nil { _ = tx.Rollback() log.Printf("db prepare failed: %v", err) return } ok := true for _, s := range batch { _, err := stmt.Exec( s.TS.UTC().Format(time.RFC3339Nano), s.TS.UTC().UnixNano(), s.SilaLPct, s.SilaRPct, s.SilaLKN, s.SilaRKN, s.SumPercent, s.SumKN, s.ImbalancePercent, s.BiasPercent, ) if err != nil { ok = false log.Printf("db insert failed: %v", err) break } } _ = stmt.Close() if !ok { _ = tx.Rollback() return } if err := tx.Commit(); err != nil { log.Printf("db commit failed: %v", err) return } batch = batch[:0] } for { select { case <-ctx.Done(): // Drain any remaining queued samples before exit for { select { case s := <-sampleCh: batch = append(batch, s) default: flush() return } } case s := <-sampleCh: batch = append(batch, s) if len(batch) >= cfg.DB.BatchSize { flush() } case <-ticker.C: flush() } } } func startAlarmWriter(ctx context.Context, database *sql.DB) { // BUG FIX: was hardcoded 1000ms / 32 — now uses the same config values as startDBWriter ticker := time.NewTicker(time.Duration(cfg.DB.FlushIntervalMs) * time.Millisecond) defer ticker.Stop() batch := make([]AlarmEvent, 0, cfg.DB.BatchSize) flush := func() { if len(batch) == 0 { return } tx, err := database.Begin() if err != nil { log.Printf("alarm db begin failed: %v", err) return } stmt, err := tx.Prepare(` INSERT INTO alarm_events ( ts, ts_unix_ns, severity, source, code, state, message, value, limit_value ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) `) if err != nil { _ = tx.Rollback() log.Printf("alarm db prepare failed: %v", err) return } ok := true for _, a := range batch { _, err := stmt.Exec( a.TS.UTC().Format(time.RFC3339Nano), a.TS.UTC().UnixNano(), a.Severity, a.Source, a.Code, a.State, a.Message, a.Value, a.Limit, ) if err != nil { ok = false log.Printf("alarm db insert failed: %v", err) break } } _ = stmt.Close() if !ok { _ = tx.Rollback() return } if err := tx.Commit(); err != nil { log.Printf("alarm db commit failed: %v", err) return } batch = batch[:0] } for { select { case <-ctx.Done(): // Drain remaining alarm events before exit for { select { case a := <-alarmCh: batch = append(batch, a) default: flush() return } } case a := <-alarmCh: batch = append(batch, a) if len(batch) >= cfg.DB.BatchSize { flush() } case <-ticker.C: flush() } } } func startDBCleanup(ctx context.Context, database *sql.DB) { if cfg.DB.RetentionDays <= 0 { return } ticker := time.NewTicker(time.Duration(cfg.DB.CleanupIntervalHr) * time.Hour) defer ticker.Stop() cleanup := func() { cutoffNs := time.Now().AddDate(0, 0, -cfg.DB.RetentionDays).UTC().UnixNano() if _, err := database.Exec(`DELETE FROM samples WHERE ts_unix_ns > 0 AND ts_unix_ns < ?`, cutoffNs); err != nil { log.Printf("db cleanup samples failed: %v", err) } if _, err := database.Exec(`DELETE FROM alarm_events WHERE ts_unix_ns > 0 AND ts_unix_ns < ?`, cutoffNs); err != nil { log.Printf("db cleanup alarms failed: %v", err) } } cleanup() for { select { case <-ctx.Done(): return case <-ticker.C: cleanup() } } } // --------------------------------------------------------------------------- // Alarm zone helpers // --------------------------------------------------------------------------- func zoneFromValue(value float64, warn, crit float64) string { if value >= crit { return "critical" } if value >= warn { return "warning" } return "ok" } func sourceName(source string) string { switch source { case "force_left": return "Left force" case "force_right": return "Right force" case "imbalance": return "Imbalance" case "plc": return "PLC" default: return source } } func sourceLimit(source, zone string) float64 { switch source { case "imbalance": if zone == "critical" { return cfg.Thresholds.ImbalanceCriticalPercent } if zone == "warning" { return cfg.Thresholds.ImbalanceWarningPercent } default: if zone == "critical" { return cfg.Thresholds.CriticalPercent } if zone == "warning" { return cfg.Thresholds.WarningPercent } } return 0 } func maybeLogZoneChange(source, prev, curr string, value float64) { if prev == curr { return } name := sourceName(source) now := time.Now() if prev == "" && curr == "ok" { return } switch curr { case "ok": enqueueAlarm(AlarmEvent{ TS: now, Severity: "info", Source: source, Code: source + "_clear", State: "clear", Message: fmt.Sprintf("%s returned to OK", name), Value: value, Limit: 0, }) case "warning": msg := fmt.Sprintf("%s entered WARNING zone", name) if prev == "critical" { msg = fmt.Sprintf("%s downgraded from CRITICAL to WARNING", name) } enqueueAlarm(AlarmEvent{ TS: now, Severity: "warning", Source: source, Code: source + "_warning", State: "active", Message: msg, Value: value, Limit: sourceLimit(source, "warning"), }) case "critical": msg := fmt.Sprintf("%s entered CRITICAL zone", name) if prev == "warning" { msg = fmt.Sprintf("%s escalated from WARNING to CRITICAL", name) } enqueueAlarm(AlarmEvent{ TS: now, Severity: "critical", Source: source, Code: source + "_critical", State: "active", Message: msg, Value: value, Limit: sourceLimit(source, "critical"), }) } } func evaluateProcessAlarms(s Sample) { leftZone := zoneFromValue(float64(s.SilaLPct), cfg.Thresholds.WarningPercent, cfg.Thresholds.CriticalPercent) rightZone := zoneFromValue(float64(s.SilaRPct), cfg.Thresholds.WarningPercent, cfg.Thresholds.CriticalPercent) imbZone := zoneFromValue(float64(s.ImbalancePercent), cfg.Thresholds.ImbalanceWarningPercent, cfg.Thresholds.ImbalanceCriticalPercent) alarmTracker.Lock() defer alarmTracker.Unlock() maybeLogZoneChange("force_left", alarmTracker.LeftZone, leftZone, float64(s.SilaLPct)) maybeLogZoneChange("force_right", alarmTracker.RightZone, rightZone, float64(s.SilaRPct)) maybeLogZoneChange("imbalance", alarmTracker.ImbZone, imbZone, float64(s.ImbalancePercent)) alarmTracker.LeftZone = leftZone alarmTracker.RightZone = rightZone alarmTracker.ImbZone = imbZone } func maybeLogPLCConnected() { alarmTracker.Lock() defer alarmTracker.Unlock() if !alarmTracker.PLCKnown { alarmTracker.PLCKnown = true alarmTracker.PLCConnected = true enqueueAlarm(AlarmEvent{ TS: time.Now(), Severity: "info", Source: "plc", Code: "plc_connected", State: "info", Message: "PLC connection established", Value: 1, Limit: 0, }) return } if !alarmTracker.PLCConnected { alarmTracker.PLCConnected = true enqueueAlarm(AlarmEvent{ TS: time.Now(), Severity: "info", Source: "plc", Code: "plc_restored", State: "info", Message: "PLC connection restored", Value: 1, Limit: 0, }) } } func maybeLogPLCDisconnected(reason string) { alarmTracker.Lock() defer alarmTracker.Unlock() if !alarmTracker.PLCKnown || !alarmTracker.PLCConnected { return } alarmTracker.PLCConnected = false alarmTracker.LeftZone = "" alarmTracker.RightZone = "" alarmTracker.ImbZone = "" enqueueAlarm(AlarmEvent{ TS: time.Now(), Severity: "critical", Source: "plc", Code: "plc_disconnected", State: "active", Message: "PLC connection lost: " + reason, Value: 0, Limit: 0, }) } // --------------------------------------------------------------------------- // PLC poller // --------------------------------------------------------------------------- func startPLCPoller(ctx context.Context) { pollInterval := time.Duration(cfg.PLC.PollMs) * time.Millisecond reconnectDelay := time.Duration(cfg.PLC.ReconnectDelaySec) * time.Second for { // Check for shutdown before attempting a new connection select { case <-ctx.Done(): return default: } handler := gos7.NewTCPClientHandler(cfg.PLC.IP, cfg.PLC.Rack, cfg.PLC.Slot) handler.Timeout = time.Duration(cfg.PLC.ConnectTimeoutSec) * time.Second handler.IdleTimeout = time.Duration(cfg.PLC.IdleTimeoutSec) * time.Second if err := handler.Connect(); err != nil { markDisconnected(err.Error()) log.Printf("PLC connect failed: %v - retrying in %ds...", err, cfg.PLC.ReconnectDelaySec) select { case <-ctx.Done(): return case <-time.After(reconnectDelay): } continue } maybeLogPLCConnected() client := gos7.NewClient(handler) log.Println("PLC connected successfully") // BUG FIX: buf was allocated inside the inner loop, causing a heap // allocation every poll cycle. Moved outside — reused each iteration. buf := make([]byte, 8) for { select { case <-ctx.Done(): _ = handler.Close() return default: } if err := client.AGReadDB(cfg.PLC.DBNum, 0, 8, buf); err != nil { log.Printf("PLC read error: %v - reconnecting...", err) markDisconnected(err.Error()) _ = handler.Close() break } var helper gos7.Helper silaL := helper.GetRealAt(buf, 0) silaR := helper.GetRealAt(buf, 4) leftKN, rightKN, sumPercent, sumKN := calculateForces(silaL, silaR, cfg.Press.MaxTonnage) imbalance := float32(math.Abs(float64(silaL - silaR))) bias := silaL - silaR now := time.Now() state.Lock() state.Connected = true state.SilaL = silaL state.SilaR = silaR state.SilaLkN = leftKN state.SilaRkN = rightKN state.SumPercent = sumPercent state.SumkN = sumKN state.ImbalancePercent = imbalance state.BiasPercent = bias state.LastUpdate = now state.Unlock() sample := Sample{ TS: now, SilaLPct: silaL, SilaRPct: silaR, SilaLKN: leftKN, SilaRKN: rightKN, SumPercent: sumPercent, SumKN: sumKN, ImbalancePercent: imbalance, BiasPercent: bias, } evaluateProcessAlarms(sample) enqueueSample(sample) select { case <-ctx.Done(): _ = handler.Close() return case <-time.After(pollInterval): } } } } // --------------------------------------------------------------------------- // Query helpers // --------------------------------------------------------------------------- func parseWindow(raw string) (time.Duration, string, error) { s := strings.TrimSpace(strings.ToLower(raw)) if s == "" { s = fmt.Sprintf("%dm", cfg.Trend.Minutes) } if strings.HasSuffix(s, "d") { n, err := strconv.Atoi(strings.TrimSuffix(s, "d")) if err != nil || n <= 0 { return 0, "", fmt.Errorf("invalid day window") } d := time.Duration(n) * 24 * time.Hour return d, s, nil } d, err := time.ParseDuration(s) if err != nil || d <= 0 { return 0, "", fmt.Errorf("invalid window") } return d, s, nil } func formatHistoryLabel(t time.Time, window time.Duration) string { local := t.Local() if window >= 12*time.Hour { return local.Format("02.01 15:04") } return local.Format("15:04:05.000") } func queryHistory(window time.Duration) ([]HistoryPoint, error) { cutoffNs := time.Now().Add(-window).UTC().UnixNano() rows, err := db.Query(`SELECT ts, sila_l_pct, sila_r_pct FROM samples WHERE ts_unix_ns >= ? ORDER BY ts_unix_ns ASC`, cutoffNs) if err != nil { return nil, err } defer rows.Close() points := make([]HistoryPoint, 0, 1024) for rows.Next() { var ts string var l, r float64 if err := rows.Scan(&ts, &l, &r); err != nil { return nil, err } t, err := time.Parse(time.RFC3339Nano, ts) if err != nil { continue } points = append(points, HistoryPoint{ Time: formatHistoryLabel(t, window), SilaL: float32(l), SilaR: float32(r), }) } if err := rows.Err(); err != nil { return nil, err } if len(points) <= cfg.DB.MaxChartPoints { return points, nil } return downsamplePoints(points, cfg.DB.MaxChartPoints), nil } func downsamplePoints(points []HistoryPoint, max int) []HistoryPoint { if len(points) <= max || max < 3 { return points } out := make([]HistoryPoint, 0, max) step := float64(len(points)-1) / float64(max-1) used := make(map[int]struct{}, max) for i := 0; i < max; i++ { idx := int(float64(i) * step) if idx >= len(points) { idx = len(points) - 1 } if _, ok := used[idx]; ok { continue } used[idx] = struct{}{} out = append(out, points[idx]) } if len(out) == 0 { return points } out[len(out)-1] = points[len(points)-1] return out } func validField(field string) (string, error) { switch field { case "sum_pct": return "sum_pct", nil case "imbalance_pct": return "imbalance_pct", nil default: return "", fmt.Errorf("invalid field") } } func queryNumericStats(field string, fromNs, toNs int64) (NumericStats, error) { safeField, err := validField(field) if err != nil { return NumericStats{}, err } query := fmt.Sprintf(` SELECT COALESCE(AVG(%[1]s), 0), COALESCE(AVG(%[1]s * %[1]s), 0), COALESCE(MIN(%[1]s), 0), COALESCE(MAX(%[1]s), 0), COUNT(*) FROM samples WHERE ts_unix_ns >= ? AND ts_unix_ns < ? `, safeField) var stats NumericStats err = db.QueryRow(query, fromNs, toNs).Scan(&stats.Avg, &stats.AvgSq, &stats.Min, &stats.Max, &stats.Count) if err != nil { return NumericStats{}, err } return stats, nil } // --------------------------------------------------------------------------- // Trend / stability classification // --------------------------------------------------------------------------- // classifyDirection is a single generic direction classifier that replaces // the two near-identical classifyForceDirection / classifyImbalanceDirection // functions that existed previously. // // stableThreshold — abs(delta) below this value → "stable" // posLabel — label when delta > threshold (e.g. "rising", "worsening") // negLabel — label when delta < -threshold (e.g. "falling", "improving") func classifyDirection(delta float64, oldCount, newCount int, stableThreshold float64, posLabel, negLabel string) string { if oldCount < 3 || newCount < 3 { return "insufficient_data" } if math.Abs(delta) < stableThreshold { return "stable" } if delta > 0 { return posLabel } return negLabel } func classifyProcessStability(forceStd, imbStd, forceDelta, avgImb5m float64, sampleCount int) (string, string) { if sampleCount < 8 { return "insufficient_data", "Too few samples in selected trend window" } if forceStd >= 6.0 || math.Abs(forceDelta) >= 8.0 || avgImb5m >= cfg.Thresholds.ImbalanceCriticalPercent || imbStd >= 4.0 { if avgImb5m >= cfg.Thresholds.ImbalanceCriticalPercent { return "unstable", "High average imbalance in last 5 minutes" } if math.Abs(forceDelta) >= 8.0 { return "unstable", "Average peak force is drifting fast" } if forceStd >= 6.0 { return "unstable", "Force variation is too high" } return "unstable", "Imbalance variation is too high" } if forceStd >= 3.0 || math.Abs(forceDelta) >= 3.0 || avgImb5m >= cfg.Thresholds.ImbalanceWarningPercent || imbStd >= 2.0 { if avgImb5m >= cfg.Thresholds.ImbalanceWarningPercent { return "caution", "Imbalance is trending above warning region" } if math.Abs(forceDelta) >= 3.0 { return "caution", "Average force is drifting" } if forceStd >= 3.0 { return "caution", "Force is less repeatable than normal" } return "caution", "Imbalance repeatability is degrading" } return "stable", "Process variation is low" } func buildTrendResponse(window time.Duration, label string) (TrendResponse, error) { nowNs := time.Now().UTC().UnixNano() windowNs := window.Nanoseconds() startNs := nowNs - windowNs midNs := startNs + (windowNs / 2) force5m, err := queryNumericStats("sum_pct", nowNs-(5*time.Minute).Nanoseconds(), nowNs) if err != nil { return TrendResponse{}, err } force1h, err := queryNumericStats("sum_pct", nowNs-(1*time.Hour).Nanoseconds(), nowNs) if err != nil { return TrendResponse{}, err } imb5m, err := queryNumericStats("imbalance_pct", nowNs-(5*time.Minute).Nanoseconds(), nowNs) if err != nil { return TrendResponse{}, err } imb1h, err := queryNumericStats("imbalance_pct", nowNs-(1*time.Hour).Nanoseconds(), nowNs) if err != nil { return TrendResponse{}, err } forceOld, err := queryNumericStats("sum_pct", startNs, midNs) if err != nil { return TrendResponse{}, err } forceNew, err := queryNumericStats("sum_pct", midNs, nowNs) if err != nil { return TrendResponse{}, err } imbOld, err := queryNumericStats("imbalance_pct", startNs, midNs) if err != nil { return TrendResponse{}, err } imbNew, err := queryNumericStats("imbalance_pct", midNs, nowNs) if err != nil { return TrendResponse{}, err } forceDelta := forceNew.Avg - forceOld.Avg imbDelta := imbNew.Avg - imbOld.Avg forceDirection := classifyDirection(forceDelta, forceOld.Count, forceNew.Count, 1.0, "rising", "falling") imbDirection := classifyDirection(imbDelta, imbOld.Count, imbNew.Count, 0.5, "worsening", "improving") fullWindowForce, err := queryNumericStats("sum_pct", startNs, nowNs) if err != nil { return TrendResponse{}, err } fullWindowImb, err := queryNumericStats("imbalance_pct", startNs, nowNs) if err != nil { return TrendResponse{}, err } stability, reason := classifyProcessStability( fullWindowForce.StdDev(), fullWindowImb.StdDev(), forceDelta, imb5m.Avg, fullWindowForce.Count, ) return TrendResponse{ Window: label, AvgPeak5m: float32(force5m.Avg), AvgPeak1h: float32(force1h.Avg), AvgImbalance5m: float32(imb5m.Avg), AvgImbalance1h: float32(imb1h.Avg), ForceDeltaPct: float32(forceDelta), ImbalanceDeltaPct: float32(imbDelta), ForceDirection: forceDirection, ImbalanceDirection: imbDirection, ProcessStability: stability, StabilityReason: reason, ForceStdDev: float32(fullWindowForce.StdDev()), ImbalanceStdDev: float32(fullWindowImb.StdDev()), SampleCount: fullWindowForce.Count, OldHalfCount: forceOld.Count, NewHalfCount: forceNew.Count, }, nil } func queryAlarmEvents(limit int) ([]AlarmEventAPI, error) { if limit <= 0 { limit = 20 } if limit > 100 { limit = 100 } rows, err := db.Query(` SELECT ts, severity, source, state, message, value, limit_value FROM alarm_events ORDER BY ts_unix_ns DESC LIMIT ? `, limit) if err != nil { return nil, err } defer rows.Close() events := make([]AlarmEventAPI, 0, limit) for rows.Next() { var ts, severity, source, state, message string var value, limitValue float64 if err := rows.Scan(&ts, &severity, &source, &state, &message, &value, &limitValue); err != nil { return nil, err } t, err := time.Parse(time.RFC3339Nano, ts) displayTime := ts if err == nil { displayTime = t.Local().Format("02.01.2006 15:04:05") } events = append(events, AlarmEventAPI{ Time: displayTime, Severity: severity, Source: source, State: state, Message: message, Value: value, Limit: limitValue, }) } if err := rows.Err(); err != nil { return nil, err } return events, nil } // --------------------------------------------------------------------------- // HTTP handlers // --------------------------------------------------------------------------- func apiData(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-store") _ = json.NewEncoder(w).Encode(snapshotState()) } func apiHistory(w http.ResponseWriter, r *http.Request) { window, label, err := parseWindow(r.URL.Query().Get("window")) if err != nil { http.Error(w, "invalid window", http.StatusBadRequest) return } points, err := queryHistory(window) if err != nil { http.Error(w, "history query failed", http.StatusInternalServerError) log.Printf("history query failed: %v", err) return } w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-store") _ = json.NewEncoder(w).Encode(HistoryResponse{ Window: label, Points: points, }) } func apiTrend(w http.ResponseWriter, r *http.Request) { window, label, err := parseWindow(r.URL.Query().Get("window")) if err != nil { http.Error(w, "invalid trend window", http.StatusBadRequest) return } resp, err := buildTrendResponse(window, label) if err != nil { http.Error(w, "trend query failed", http.StatusInternalServerError) log.Printf("trend query failed: %v", err) return } w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-store") _ = json.NewEncoder(w).Encode(resp) } func apiAlarms(w http.ResponseWriter, r *http.Request) { limit := 20 if raw := strings.TrimSpace(r.URL.Query().Get("limit")); raw != "" { if n, err := strconv.Atoi(raw); err == nil && n > 0 { limit = n } } events, err := queryAlarmEvents(limit) if err != nil { http.Error(w, "alarm query failed", http.StatusInternalServerError) log.Printf("alarm query failed: %v", err) return } w.Header().Set("Content-Type", "application/json") w.Header().Set("Cache-Control", "no-store") _ = json.NewEncoder(w).Encode(AlarmResponse{ Events: events, }) } // serveUI serves the pre-rendered UI page. PageData is derived solely from // the immutable config, so we render the template once at startup and reuse. func serveUI(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") _, _ = w.Write(cachedUI) } // initCachedUI renders the HTML template once at startup. func initCachedUI() { data := PageData{ Title: cfg.UI.Title, Subtitle: cfg.UI.Subtitle, LeftLabel: cfg.UI.LeftLabel, RightLabel: cfg.UI.RightLabel, UnitForce: cfg.UI.UnitForce, UnitPct: cfg.UI.UnitPct, MaxTonnage: cfg.Press.MaxTonnage, WarningPercent: cfg.Thresholds.WarningPercent, CriticalPercent: cfg.Thresholds.CriticalPercent, GaugeMaxPercent: cfg.Thresholds.GaugeMaxPercent, ImbalanceWarningPercent: cfg.Thresholds.ImbalanceWarningPercent, ImbalanceCriticalPercent: cfg.Thresholds.ImbalanceCriticalPercent, PollMs: cfg.PLC.PollMs, DefaultWindow: fmt.Sprintf("%dm", cfg.Trend.Minutes), DefaultTrendWindow: "15m", } var buf bytes.Buffer if err := uiTemplate.Execute(&buf, data); err != nil { log.Fatalf("failed to pre-render UI template: %v", err) } cachedUI = buf.Bytes() } // --------------------------------------------------------------------------- // main // --------------------------------------------------------------------------- func main() { wd, err := os.Getwd() if err != nil { log.Fatalf("failed to get working directory: %v", err) } configPath := filepath.Join(wd, "config.yaml") cfg, err = loadOrCreateConfig(configPath) if err != nil { log.Fatalf("failed to load config: %v", err) } dbPath := cfg.DB.Path if !filepath.IsAbs(dbPath) { dbPath = filepath.Join(wd, dbPath) } db, err = initDatabase(dbPath) if err != nil { log.Fatalf("failed to init database: %v", err) } defer db.Close() sampleCh = make(chan Sample, cfg.DB.WriterQueueSize) alarmCh = make(chan AlarmEvent, cfg.DB.AlarmQueueSize) // BUG FIX: was hardcoded 512 initCachedUI() log.Printf("S7-1200 Force Monitor v%s", version) log.Printf("Config: %s", configPath) log.Printf("DB: %s", dbPath) log.Printf("PLC: ip=%s db=%d rack=%d slot=%d poll=%dms", cfg.PLC.IP, cfg.PLC.DBNum, cfg.PLC.Rack, cfg.PLC.Slot, cfg.PLC.PollMs) log.Printf("Press: MAX_TONNAGE=%.2f %s", cfg.Press.MaxTonnage, cfg.UI.UnitForce) // Graceful shutdown via SIGINT / SIGTERM ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() var wg sync.WaitGroup wg.Add(4) go func() { defer wg.Done(); startDBWriter(ctx, db) }() go func() { defer wg.Done(); startAlarmWriter(ctx, db) }() go func() { defer wg.Done(); startDBCleanup(ctx, db) }() go func() { defer wg.Done(); startPLCPoller(ctx) }() mux := http.NewServeMux() mux.Handle("/static/", http.FileServer(http.FS(staticFiles))) mux.HandleFunc("/", serveUI) mux.HandleFunc("/api/data", apiData) mux.HandleFunc("/api/history", apiHistory) mux.HandleFunc("/api/trend", apiTrend) mux.HandleFunc("/api/alarms", apiAlarms) srv := &http.Server{ Addr: cfg.Server.ListenAddr, Handler: mux, } log.Printf("Listening on http://localhost%s", cfg.Server.ListenAddr) go func() { if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { log.Fatalf("HTTP server error: %v", err) } }() <-ctx.Done() log.Println("Shutting down — flushing DB writers...") shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := srv.Shutdown(shutdownCtx); err != nil { log.Printf("HTTP server shutdown error: %v", err) } wg.Wait() log.Println("Shutdown complete") } const uiHTML = ` {{.Title}}

{{.Title}}

{{.Subtitle}}

MAX_TONNAGE = {{printf "%.1f" .MaxTonnage}} {{.UnitForce}}

Disconnected
Last update: --:--:--.---
Dropped S: 0 | E: 0
Machine verdict
NO DATA
Waiting for PLC data
FORCE
NO DATA
--
IMBALANCE
NO DATA
--
PLC
OFFLINE
Disconnected
TOTAL PEAK FORCE
0.0
{{.UnitForce}}
TOTAL %
0.0 {{.UnitPct}}
IMBALANCE
0.0 {{.UnitPct}}
abs(L - R)
BIAS
0.0 {{.UnitPct}}
L - R
LIMITS
Force W {{printf "%.0f" .WarningPercent}} / C {{printf "%.0f" .CriticalPercent}}
Imb W {{printf "%.0f" .ImbalanceWarningPercent}} / C {{printf "%.0f" .ImbalanceCriticalPercent}}

Drift / Deterioration Intelligence

Averages, drift direction, imbalance deterioration and process stability
AVG PEAK 5 MIN
--
No data
AVG PEAK 1 HOUR
--
No data
FORCE TREND
--
No data
IMBALANCE TREND
--
No data
PROCESS STABILITY
--
No data

Event / Alarm Timeline

Recent transitions show exactly when the process began drifting, overloading, losing balance, or losing PLC communication
Newest events first • clear events included
Time Severity Source Event Value Limit
No events yet

{{.LeftLabel}}

NORMAL
0.0
{{.UnitPct}}
0.0 {{.UnitForce}}

{{.RightLabel}}

NORMAL
0.0
{{.UnitPct}}
0.0 {{.UnitForce}}

Peak Trend

Piezo peak/stroke history from SQLite with visible warning and critical limits
`