diff --git a/src/config.go b/src/config.go index c18be03..9c049a1 100644 --- a/src/config.go +++ b/src/config.go @@ -3,7 +3,9 @@ package main import ( "fmt" + "git.openpdu.org/OpenPDU/openpdu/events" "git.openpdu.org/OpenPDU/openpdu/syslog" + "github.com/fsnotify/fsnotify" "github.com/spf13/viper" ) @@ -16,4 +18,10 @@ func init() { if err != nil { // Handle errors reading the config file syslog.Err(fmt.Sprintf("Can't read config file: %s \n", err.Error())) } + viper.WatchConfig() + viper.OnConfigChange(func(e fsnotify.Event) { + //The Viper configuration has changed to perform the responding operation + fmt.Println("Config file changed:", e.Name) + events.FireEvent("config_changed") + }) } diff --git a/src/events/events.go b/src/events/events.go new file mode 100644 index 0000000..5478b31 --- /dev/null +++ b/src/events/events.go @@ -0,0 +1,28 @@ +package events + +var handlers map[string][]func() + +func init() { + handlers = make(map[string][]func()) +} + +func AddListener(event string, f func()) { + l, isPresent := handlers[event] + if !isPresent { + handlers[event] = []func(){ + f, + } + } else { + handlers[event] = append(l, f) + } +} + +func FireEvent(event string) { + l, isPresent := handlers[event] + if !isPresent { + return + } + for _, v := range l { + v() + } +} diff --git a/src/go.mod b/src/go.mod index 5decd63..ce66c83 100644 --- a/src/go.mod +++ b/src/go.mod @@ -12,6 +12,7 @@ require ( golang.org/x/image v0.0.0-20201208152932-35266b937fa6 gopkg.in/macaron.v1 v1.4.0 periph.io/x/periph v3.6.7+incompatible + github.com/fsnotify/fsnotify v1.4.7 ) replace git.openpdu.org/OpenPDU/openpdu => ./src diff --git a/src/ups/ups.go b/src/ups/ups.go index 978431d..ef793c0 100644 --- a/src/ups/ups.go +++ b/src/ups/ups.go @@ -1,6 +1,7 @@ package ups import ( + "git.openpdu.org/OpenPDU/openpdu/events" "git.openpdu.org/OpenPDU/openpdu/syslog" nut "github.com/robbiet480/go.nut" "github.com/spf13/viper" @@ -10,11 +11,18 @@ var upsClient nut.Client var ups nut.UPS var Vars map[string]nut.Variable +var defaults = map[string]interface{}{ + "Ups.Host": "localhost", + "Ups.Name": "ups", + "Ups.Username": "", + "Ups.Password": "", +} + func init() { - viper.SetDefault("Ups.Host", "localhost") - viper.SetDefault("Ups.Name", "ups") - viper.SetDefault("Ups.Username", "") - viper.SetDefault("Ups.Password", "") + for k, v := range defaults { + viper.SetDefault(k, v) + } + events.AddListener("config_changed", Reconfigure) } func UpsConnect() { @@ -51,6 +59,7 @@ func UpsConnect() { if u.Name == viper.GetString("Ups.Name") { ups = u syslog.Notice("UPS connected") + events.FireEvent("ups_connected") UpsReadVars() } } @@ -67,5 +76,6 @@ func Reconfigure() { ups = nut.UPS{} upsClient = nut.Client{} syslog.Notice("UPS disconnected") + events.FireEvent("ups_disconnected") go UpsConnect() }