Add capability to read from options.json to provide Home Assistant support.
All checks were successful
Build Docker image / build (push) Successful in 1m23s
Build Golang packages / release (push) Has been skipped

This commit is contained in:
Pieter Hollander 2024-07-25 19:15:11 +02:00
parent 2f3e8ad1d6
commit 6230869120
Signed by: pieter
SSH key fingerprint: SHA256:HbX+9cBXsop9SuvL+mELd29sK+7DehFfdVweFVDtMSg

57
main.go
View file

@ -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;