From 6230869120c0823822a18b5ccd068b432331659b Mon Sep 17 00:00:00 2001 From: Pieter Hollander Date: Thu, 25 Jul 2024 19:15:11 +0200 Subject: [PATCH] Add capability to read from options.json to provide Home Assistant support. --- main.go | 57 +++++++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 49 insertions(+), 8 deletions(-) diff --git a/main.go b/main.go index abce7c6..5a58c20 100644 --- a/main.go +++ b/main.go @@ -143,14 +143,59 @@ type InverterSettingsData struct { Inverters []InverterSettings `json:"inverter"` } +// Config settings struct +type Config struct { + DB string `json:"db"` + OpenDTU string `json:"opendtu"` + TimescaleDBEnabled string `json:"timescaledb"` + TZ string `json:"tz"` +} + var logger = slog.New(slog.NewJSONHandler(os.Stdout, nil)) +var config Config + +// LoadConfig attempts to read the configuration from options.json +// If it fails, it falls back to using environment variables +func LoadConfig() Config { + configFilePath := os.Getenv("CONFIG_FILE") + if configFilePath == "" { + configFilePath = "/data/options.json" + } + + data, err := os.ReadFile(configFilePath) + if err == nil { + // Successfully read the file, parse the JSON + err = json.Unmarshal(data, &config) + if err != nil { + log.Fatalf("Error parsing config file: %v", err) + } + } else { + // Fallback to environment variables + config.DB = os.Getenv("DB_URL") + if config.DB == "" { + log.Fatal("DB_URL environment variable is not set.") + } + config.OpenDTU = os.Getenv("REMOTE_URL") + if config.OpenDTU == "" { + log.Fatal("REMOTE_URL environment variable is not set.") + } + + config.TimescaleDBEnabled = os.Getenv("TIMESCALEDB_ENABLED") + config.TZ = os.Getenv("TZ") + } + + return config +} // Main program func main() { // Initial logger setup slog.SetDefault(logger) - dbConnStr := (os.Getenv("DB_URL")) + // Load the configuration + config := LoadConfig() + + dbConnStr := config.DB // Connect to PostgreSQL db, err := sql.Open("postgres", dbConnStr) if err != nil { @@ -161,12 +206,8 @@ func main() { // Create tables if they don't exist createTables(db) - // Get WebSocket URL from environment variable - RemoteURL := os.Getenv("REMOTE_URL") - wsURL := "ws://" + RemoteURL + "/livedata" - if wsURL == "" { - log.Fatal("WEBSOCKET_URL environment variable is not set.") - } + // Create WebSocket URL from config variable + wsURL := "ws://" + config.OpenDTU + "/livedata" // Establish WebSocket connection c, _, err := websocket.DefaultDialer.Dial(wsURL, nil) @@ -353,7 +394,7 @@ func createTables(db *sql.DB) { if err != nil { log.Fatal("Error creating tables: ", err) } - timescaleEnabled := os.Getenv("TIMESCALEDB_ENABLED") + timescaleEnabled := config.TimescaleDBEnabled enableTimescaleDB := ` -- CREATE EXTENSION IF NOT EXISTS timescaledb;