Treat config from environment variables

This commit is contained in:
nemunaire 2023-08-02 20:06:15 +02:00
parent ce161c2fae
commit 9165b9ad82
2 changed files with 40 additions and 0 deletions

38
config.go Normal file
View File

@ -0,0 +1,38 @@
package main
import (
"flag"
"fmt"
"os"
"strings"
)
func parseEnvironmentVariables() (err error) {
for _, line := range os.Environ() {
if strings.HasPrefix(line, "LINKY2INFLUX_") {
err := parseConfigLine(line)
if err != nil {
return fmt.Errorf("error in environment (%q): %w", line, err)
}
}
}
return
}
func parseConfigLine(line string) (err error) {
fields := strings.SplitN(line, "=", 2)
orig_key := strings.TrimSpace(fields[0])
value := strings.TrimSpace(fields[1])
if len(value) == 0 {
return
}
key := strings.TrimPrefix(orig_key, "LINKY2INFLUX_")
key = strings.Replace(key, "_", "-", -1)
key = strings.ToLower(key)
err = flag.Set(key, value)
return
}

View File

@ -184,6 +184,8 @@ func main() {
var pushFrequency = flag.Bool("push-frequency", false, "Also fetch data about the grid frequency")
flag.Parse()
parseEnvironmentVariables()
if len(flag.Args()) < 1 {
log.Println("missing required argument: serial device (eg. /dev/ttyUSB0)")
return