Add configurable device aliases
This commit is contained in:
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -12,10 +13,13 @@ import (
|
||||
|
||||
const envPrefix = "MQTT_SCRUBBER_"
|
||||
|
||||
var invalidDeviceCharacters = regexp.MustCompile(`[^a-z0-9_]+`)
|
||||
|
||||
type Config struct {
|
||||
MQTT MQTTConfig `json:"mqtt"`
|
||||
Influx InfluxConfig `json:"influx"`
|
||||
App AppConfig `json:"app"`
|
||||
MQTT MQTTConfig `json:"mqtt"`
|
||||
Influx InfluxConfig `json:"influx"`
|
||||
App AppConfig `json:"app"`
|
||||
DeviceAliases map[string]string `json:"device_aliases"`
|
||||
}
|
||||
|
||||
type MQTTConfig struct {
|
||||
@@ -80,6 +84,8 @@ func Load(path string) (Config, error) {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
cfg.DeviceAliases = normalizeDeviceAliases(cfg.DeviceAliases)
|
||||
|
||||
if err := cfg.Validate(); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
@@ -161,6 +167,18 @@ func applyEnvOverrides(cfg *Config) error {
|
||||
setString(&cfg.App.LogLevel, envPrefix+"APP_LOG_LEVEL")
|
||||
setString(&cfg.App.HealthAddress, envPrefix+"APP_HEALTH_ADDRESS")
|
||||
|
||||
if raw, ok := os.LookupEnv(envPrefix + "DEVICE_ALIASES"); ok {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
cfg.DeviceAliases = nil
|
||||
} else {
|
||||
aliases := make(map[string]string)
|
||||
if err := json.Unmarshal([]byte(raw), &aliases); err != nil {
|
||||
return fmt.Errorf("parse %sDEVICE_ALIASES: %w", envPrefix, err)
|
||||
}
|
||||
cfg.DeviceAliases = aliases
|
||||
}
|
||||
}
|
||||
|
||||
if raw, ok := os.LookupEnv(envPrefix + "MQTT_TOPICS"); ok {
|
||||
cfg.MQTT.Topics = splitAndTrim(raw)
|
||||
}
|
||||
@@ -227,3 +245,34 @@ func splitAndTrim(value string) []string {
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func normalizeDeviceAliases(aliases map[string]string) map[string]string {
|
||||
if len(aliases) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
normalized := make(map[string]string, len(aliases))
|
||||
for device, alias := range aliases {
|
||||
cleanDevice := normalizeDeviceKey(device)
|
||||
cleanAlias := strings.TrimSpace(alias)
|
||||
if cleanDevice == "" || cleanAlias == "" {
|
||||
continue
|
||||
}
|
||||
normalized[cleanDevice] = cleanAlias
|
||||
}
|
||||
|
||||
if len(normalized) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return normalized
|
||||
}
|
||||
|
||||
func normalizeDeviceKey(value string) string {
|
||||
normalized := strings.ToLower(strings.TrimSpace(value))
|
||||
normalized = strings.ReplaceAll(normalized, "-", "_")
|
||||
normalized = strings.ReplaceAll(normalized, " ", "_")
|
||||
normalized = invalidDeviceCharacters.ReplaceAllString(normalized, "_")
|
||||
normalized = strings.Trim(normalized, "_")
|
||||
return normalized
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user