config in its own package

This commit is contained in:
Paolo Asperti 2022-06-03 12:43:31 +02:00
parent 1098116513
commit 9a7eef618f
Signed by: paspo
GPG Key ID: 06D46905D19D5182
15 changed files with 170 additions and 138 deletions

View File

@ -6,6 +6,7 @@ import (
"strings" "strings"
"time" "time"
"git.openpdu.org/OpenPDU/openpdu/config"
"git.openpdu.org/OpenPDU/openpdu/i2c" "git.openpdu.org/OpenPDU/openpdu/i2c"
"git.openpdu.org/OpenPDU/openpdu/syslog" "git.openpdu.org/OpenPDU/openpdu/syslog"
PahoMQTT "github.com/eclipse/paho.mqtt.golang" PahoMQTT "github.com/eclipse/paho.mqtt.golang"
@ -179,8 +180,8 @@ func (c *I2CChannel) ToString() string {
func (c *I2CChannel) SaveLastState() { func (c *I2CChannel) SaveLastState() {
if c.onboot == "last" { if c.onboot == "last" {
s := fmt.Sprintf("boards.%s.channels.%s.lastvalue", c.parent.ID, c.ID) s := fmt.Sprintf("boards.%s.channels.%s.lastvalue", c.parent.ID, c.ID)
viper.Set(s, c.Status()) config.Set(s, c.Status())
viper.WriteConfig() config.WriteConfig()
} }
} }
@ -314,7 +315,7 @@ func (b *I2CBoard) Initialize() {
case "last": case "last":
s := fmt.Sprintf("boards.%s.channels.%s.lastvalue", c.parent.ID, c.ID) s := fmt.Sprintf("boards.%s.channels.%s.lastvalue", c.parent.ID, c.ID)
switch viper.GetBool(s) { switch config.GetBool(s) {
case true: case true:
c.SetOn() c.SetOn()
case false: case false:
@ -342,19 +343,19 @@ func (c *I2CChannel) OnBoot() string {
func (c *I2CChannel) SetOnBoot(str string) { func (c *I2CChannel) SetOnBoot(str string) {
c.onboot = str c.onboot = str
s := fmt.Sprintf("boards.%s.channels.%s.onboot", c.parent.ID, c.ID) s := fmt.Sprintf("boards.%s.channels.%s.onboot", c.parent.ID, c.ID)
viper.Set(s, str) config.Set(s, str)
} }
func (c *I2CChannel) SetMQTTStateTopic(str string) { func (c *I2CChannel) SetMQTTStateTopic(str string) {
c.mqttStateTopic = str c.mqttStateTopic = str
s := fmt.Sprintf("boards.%s.channels.%s.mqtt.statetopic", c.parent.ID, c.ID) s := fmt.Sprintf("boards.%s.channels.%s.mqtt.statetopic", c.parent.ID, c.ID)
viper.Set(s, str) config.Set(s, str)
} }
func (c *I2CChannel) SetMQTTCommandTopic(str string) { func (c *I2CChannel) SetMQTTCommandTopic(str string) {
c.mqttCommandTopic = str c.mqttCommandTopic = str
s := fmt.Sprintf("boards.%s.channels.%s.mqtt.commandtopic", c.parent.ID, c.ID) s := fmt.Sprintf("boards.%s.channels.%s.mqtt.commandtopic", c.parent.ID, c.ID)
viper.Set(s, str) config.Set(s, str)
} }
func (c *I2CChannel) MQTTHandler(client PahoMQTT.Client, msg PahoMQTT.Message) { func (c *I2CChannel) MQTTHandler(client PahoMQTT.Client, msg PahoMQTT.Message) {

View File

@ -6,6 +6,7 @@ import (
"strings" "strings"
"time" "time"
"git.openpdu.org/OpenPDU/openpdu/config"
"git.openpdu.org/OpenPDU/openpdu/syslog" "git.openpdu.org/OpenPDU/openpdu/syslog"
PahoMQTT "github.com/eclipse/paho.mqtt.golang" PahoMQTT "github.com/eclipse/paho.mqtt.golang"
"github.com/spf13/viper" "github.com/spf13/viper"
@ -174,8 +175,8 @@ func (c *MQTTChannel) ToString() string {
func (c *MQTTChannel) SaveLastState() { func (c *MQTTChannel) SaveLastState() {
if c.onboot == "last" { if c.onboot == "last" {
s := fmt.Sprintf("boards.%s.channels.%s.lastvalue", c.parent.ID, c.ID) s := fmt.Sprintf("boards.%s.channels.%s.lastvalue", c.parent.ID, c.ID)
viper.Set(s, c.value) config.Set(s, c.value)
viper.WriteConfig() config.WriteConfig()
} }
} }
@ -315,19 +316,19 @@ func (c *MQTTChannel) OnBoot() string {
func (c *MQTTChannel) SetOnBoot(str string) { func (c *MQTTChannel) SetOnBoot(str string) {
c.onboot = str c.onboot = str
s := fmt.Sprintf("boards.%s.channels.%s.onboot", c.parent.ID, c.ID) s := fmt.Sprintf("boards.%s.channels.%s.onboot", c.parent.ID, c.ID)
viper.Set(s, str) config.Set(s, str)
} }
func (c *MQTTChannel) SetMQTTStateTopic(str string) { func (c *MQTTChannel) SetMQTTStateTopic(str string) {
c.mqttStateTopic = str c.mqttStateTopic = str
s := fmt.Sprintf("boards.%s.channels.%s.mqtt.statetopic", c.parent.ID, c.ID) s := fmt.Sprintf("boards.%s.channels.%s.mqtt.statetopic", c.parent.ID, c.ID)
viper.Set(s, str) config.Set(s, str)
} }
func (c *MQTTChannel) SetMQTTCommandTopic(str string) { func (c *MQTTChannel) SetMQTTCommandTopic(str string) {
c.mqttCommandTopic = str c.mqttCommandTopic = str
s := fmt.Sprintf("boards.%s.channels.%s.mqtt.commandtopic", c.parent.ID, c.ID) s := fmt.Sprintf("boards.%s.channels.%s.mqtt.commandtopic", c.parent.ID, c.ID)
viper.Set(s, str) config.Set(s, str)
} }
func (c *MQTTChannel) MQTTStateTopic() string { func (c *MQTTChannel) MQTTStateTopic() string {

View File

@ -1,9 +1,8 @@
package main package config
import ( import (
"fmt" "log"
"git.openpdu.org/OpenPDU/openpdu/syslog"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -14,7 +13,7 @@ func init() {
viper.AddConfigPath("/etc/openpdu/") // path to look for the config file in viper.AddConfigPath("/etc/openpdu/") // path to look for the config file in
err := viper.ReadInConfig() // Find and read the config file err := viper.ReadInConfig() // Find and read the config file
if err != nil { // Handle errors reading the config file if err != nil { // Handle errors reading the config file
syslog.Err(fmt.Sprintf("Can't read config file: %s \n", err.Error())) log.Printf("Can't read config file: %s \n", err.Error())
} }
// temporary disabled because it screwsup the config on save // temporary disabled because it screwsup the config on save
@ -25,3 +24,31 @@ func init() {
// }) // })
// viper.WatchConfig() // viper.WatchConfig()
} }
func SetDefault(k string, v interface{}) {
viper.SetDefault(k, v)
}
func GetString(k string) string {
return viper.GetString(k)
}
func GetInt(k string) int {
return viper.GetInt(k)
}
func GetBool(k string) bool {
return viper.GetBool(k)
}
func Set(k string, v interface{}) {
viper.Set(k, v)
}
func WriteConfig() {
viper.WriteConfig()
}
func ConfigFileUsed() string {
return viper.ConfigFileUsed()
}

View File

@ -7,10 +7,11 @@ import (
"net" "net"
"time" "time"
"git.openpdu.org/OpenPDU/openpdu/config"
"git.openpdu.org/OpenPDU/openpdu/i2c" "git.openpdu.org/OpenPDU/openpdu/i2c"
"git.openpdu.org/OpenPDU/openpdu/outlet" "git.openpdu.org/OpenPDU/openpdu/outlet"
"git.openpdu.org/OpenPDU/openpdu/syslog" "git.openpdu.org/OpenPDU/openpdu/syslog"
"github.com/spf13/viper"
"golang.org/x/image/font" "golang.org/x/image/font"
"golang.org/x/image/font/basicfont" "golang.org/x/image/font/basicfont"
"golang.org/x/image/math/fixed" "golang.org/x/image/math/fixed"
@ -19,24 +20,23 @@ import (
func init() { func init() {
syslog.Info("display setup") syslog.Info("display setup")
viper.SetDefault("Display.Type", "none") config.SetDefault("Display.Type", "none")
viper.SetDefault("Display.W", 128) config.SetDefault("Display.W", 128)
viper.SetDefault("Display.H", 32) config.SetDefault("Display.H", 32)
viper.SetDefault("Display.Rotated", false) config.SetDefault("Display.Rotated", false)
viper.SetDefault("Display.SwapTopBottom", false) config.SetDefault("Display.SwapTopBottom", false)
viper.SetDefault("Display.networkinterface", "eth0") config.SetDefault("Display.networkinterface", "eth0")
} }
func displayLoop() { func displayLoop() {
for { for {
syslog.Info("ssd1306 display starting loop") if config.GetString("Display.Type") != "ssd1306" {
if viper.GetString("Display.Type") != "ssd1306" {
syslog.Warning("ssd1306 disabled")
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
continue continue
} }
syslog.Info("ssd1306 display starting loop")
if i2c.I2Cbus == nil { if i2c.I2Cbus == nil {
syslog.Warning("ssd1306 i2cbus not found") syslog.Warning("ssd1306 i2cbus not found")
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
@ -44,11 +44,11 @@ func displayLoop() {
} }
opts := ssd1306.Opts{ opts := ssd1306.Opts{
W: viper.GetInt("Display.W"), W: config.GetInt("Display.W"),
H: viper.GetInt("Display.H"), H: config.GetInt("Display.H"),
Rotated: viper.GetBool("Display.Rotated"), Rotated: config.GetBool("Display.Rotated"),
Sequential: true, Sequential: true,
SwapTopBottom: viper.GetBool("Display.SwapTopBottom"), SwapTopBottom: config.GetBool("Display.SwapTopBottom"),
} }
// Open a handle to a ssd1306 connected on the I²C bus: // Open a handle to a ssd1306 connected on the I²C bus:
@ -128,7 +128,7 @@ func dispOutletStatusString() string {
func disp(dev *ssd1306.Dev) error { func disp(dev *ssd1306.Dev) error {
img := image.NewRGBA(image.Rect(0, 0, 128, 32)) img := image.NewRGBA(image.Rect(0, 0, 128, 32))
iface := viper.GetString("Display.NetworkInterface") iface := config.GetString("Display.NetworkInterface")
ips := getIPs() ips := getIPs()
ip, found := ips[iface] ip, found := ips[iface]
if !found { if !found {

View File

@ -1,16 +1,16 @@
package main package main
import ( import (
"git.openpdu.org/OpenPDU/openpdu/config"
"git.openpdu.org/OpenPDU/openpdu/syslog" "git.openpdu.org/OpenPDU/openpdu/syslog"
"git.openpdu.org/OpenPDU/openpdu/ups" "git.openpdu.org/OpenPDU/openpdu/ups"
"git.openpdu.org/OpenPDU/openpdu/webui" "git.openpdu.org/OpenPDU/openpdu/webui"
"github.com/spf13/viper"
) )
const version = "0.1" const version = "0.1"
func init() { func init() {
viper.SetDefault("system.hostname", "openpdu") config.SetDefault("system.hostname", "openpdu")
} }
func main() { func main() {
@ -21,7 +21,7 @@ func main() {
go MQTTRefreshLoop() go MQTTRefreshLoop()
go ups.UpsConnect() go ups.UpsConnect()
go displayLoop() go displayLoop()
syslog.Info("hostname: " + viper.GetString("system.hostname")) syslog.Info("hostname: " + config.GetString("system.hostname"))
webui.StartServer() webui.StartServer()
} }

View File

@ -4,25 +4,25 @@ import (
"fmt" "fmt"
"time" "time"
"git.openpdu.org/OpenPDU/openpdu/config"
"git.openpdu.org/OpenPDU/openpdu/syslog" "git.openpdu.org/OpenPDU/openpdu/syslog"
MQTT "github.com/eclipse/paho.mqtt.golang" MQTT "github.com/eclipse/paho.mqtt.golang"
"github.com/spf13/viper"
) )
var MQTTclient MQTT.Client var MQTTclient MQTT.Client
func init() { func init() {
viper.SetDefault("Mqtt.CliendID", "OpenPDU") // max 23 chars config.SetDefault("Mqtt.CliendID", "OpenPDU") // max 23 chars
viper.SetDefault("Mqtt.Prefix", "openpdu") // max 23 chars config.SetDefault("Mqtt.Prefix", "openpdu") // max 23 chars
viper.SetDefault("Mqtt.Schema", "tcp") config.SetDefault("Mqtt.Schema", "tcp")
viper.SetDefault("Mqtt.Host", "localhost") config.SetDefault("Mqtt.Host", "localhost")
viper.SetDefault("Mqtt.Port", "1883") config.SetDefault("Mqtt.Port", "1883")
viper.SetDefault("Mqtt.Username", "") config.SetDefault("Mqtt.Username", "")
viper.SetDefault("Mqtt.Password", "") config.SetDefault("Mqtt.Password", "")
viper.SetDefault("Mqtt.LWTTopic", "LWT") config.SetDefault("Mqtt.LWTTopic", "LWT")
viper.SetDefault("Mqtt.LWTMessageOnline", "Online") config.SetDefault("Mqtt.LWTMessageOnline", "Online")
viper.SetDefault("Mqtt.LWTMessageOffline", "Offline") config.SetDefault("Mqtt.LWTMessageOffline", "Offline")
viper.SetDefault("Mqtt.HomeAssistant", false) config.SetDefault("Mqtt.HomeAssistant", false)
// MQTT.ERROR = log.New(os.Stdout, "[ERROR] ", 0) // MQTT.ERROR = log.New(os.Stdout, "[ERROR] ", 0)
// MQTT.CRITICAL = log.New(os.Stdout, "[CRIT] ", 0) // MQTT.CRITICAL = log.New(os.Stdout, "[CRIT] ", 0)
@ -34,17 +34,17 @@ func init() {
// https://girishjoshi.io/post/golang-paho-mqtt/ // https://girishjoshi.io/post/golang-paho-mqtt/
func Setup() { func Setup() {
uri := viper.GetString("Mqtt.Schema") + "://" + viper.GetString("Mqtt.Host") + ":" + viper.GetString("Mqtt.Port") uri := config.GetString("Mqtt.Schema") + "://" + config.GetString("Mqtt.Host") + ":" + config.GetString("Mqtt.Port")
opts := MQTT.NewClientOptions().AddBroker(uri) opts := MQTT.NewClientOptions().AddBroker(uri)
opts.SetClientID(viper.GetString("Mqtt.CliendID")) opts.SetClientID(config.GetString("Mqtt.CliendID"))
opts.SetWill(viper.GetString("Mqtt.Prefix")+"/"+viper.GetString("Mqtt.LWTTopic"), viper.GetString("Mqtt.LWTMessageOffline"), 0, false) opts.SetWill(config.GetString("Mqtt.Prefix")+"/"+config.GetString("Mqtt.LWTTopic"), config.GetString("Mqtt.LWTMessageOffline"), 0, false)
if username := viper.GetString("Mqtt.Username"); username != "" { if username := config.GetString("Mqtt.Username"); username != "" {
opts.SetUsername(username) opts.SetUsername(username)
} }
if password := viper.GetString("Mqtt.Password"); password != "" { if password := config.GetString("Mqtt.Password"); password != "" {
opts.SetPassword(password) opts.SetPassword(password)
} }
@ -61,7 +61,7 @@ func Setup() {
}) })
opts.SetOnConnectHandler(func(c MQTT.Client) { opts.SetOnConnectHandler(func(c MQTT.Client) {
syslog.Notice("mqtt connected") syslog.Notice("mqtt connected")
PublishRoot(viper.GetString("Mqtt.Prefix")+"/"+viper.GetString("Mqtt.LWTTopic"), viper.GetString("Mqtt.LWTMessageOnline")) PublishRoot(config.GetString("Mqtt.Prefix")+"/"+config.GetString("Mqtt.LWTTopic"), config.GetString("Mqtt.LWTMessageOnline"))
}) })
MQTTclient = MQTT.NewClient(opts) MQTTclient = MQTT.NewClient(opts)
@ -79,7 +79,7 @@ func Setup() {
func Subscribe(topic string, handler func(MQTT.Client, MQTT.Message)) { func Subscribe(topic string, handler func(MQTT.Client, MQTT.Message)) {
// MQTTHandler(MQTT.Client, MQTT.Message) // MQTTHandler(MQTT.Client, MQTT.Message)
MQTTclient.Subscribe(viper.GetString("Mqtt.Prefix")+"/switch/"+topic, 1, handler) MQTTclient.Subscribe(config.GetString("Mqtt.Prefix")+"/switch/"+topic, 1, handler)
syslog.Debug(fmt.Sprintf("MQTT subscribed to topic: %s", topic)) syslog.Debug(fmt.Sprintf("MQTT subscribed to topic: %s", topic))
} }
@ -99,7 +99,7 @@ func Publish(topic string, value string) {
return return
} }
if MQTTclient.IsConnected() { if MQTTclient.IsConnected() {
MQTTclient.Publish(viper.GetString("Mqtt.Prefix")+"/switch/"+topic, 0, false, value) MQTTclient.Publish(config.GetString("Mqtt.Prefix")+"/switch/"+topic, 0, false, value)
} }
} }

View File

@ -7,6 +7,7 @@ import (
"time" "time"
"git.openpdu.org/OpenPDU/openpdu/board" "git.openpdu.org/OpenPDU/openpdu/board"
"git.openpdu.org/OpenPDU/openpdu/config"
"git.openpdu.org/OpenPDU/openpdu/events" "git.openpdu.org/OpenPDU/openpdu/events"
"git.openpdu.org/OpenPDU/openpdu/mqtt" "git.openpdu.org/OpenPDU/openpdu/mqtt"
"git.openpdu.org/OpenPDU/openpdu/outlet" "git.openpdu.org/OpenPDU/openpdu/outlet"
@ -59,21 +60,21 @@ func MQTTSetup() {
continue continue
} }
mqtt.Subscribe(topic, c.MQTTHandler) mqtt.Subscribe(topic, c.MQTTHandler)
hAssTopic := "homeassistant/switch/" + viper.GetString("Mqtt.Prefix") + "/" + fmt.Sprint(o) + "/config" hAssTopic := "homeassistant/switch/" + config.GetString("Mqtt.Prefix") + "/" + fmt.Sprint(o) + "/config"
v := "" v := ""
if viper.GetBool("Mqtt.HomeAssistant") { if config.GetBool("Mqtt.HomeAssistant") {
cfg := map[string]interface{}{ cfg := map[string]interface{}{
"name": outlet.Outlets[o].Description, "name": outlet.Outlets[o].Description,
"state_topic": viper.GetString("Mqtt.Prefix") + "/switch/" + c.MQTTStateTopic(), "state_topic": config.GetString("Mqtt.Prefix") + "/switch/" + c.MQTTStateTopic(),
"command_topic": viper.GetString("Mqtt.Prefix") + "/switch/" + c.MQTTCommandTopic(), "command_topic": config.GetString("Mqtt.Prefix") + "/switch/" + c.MQTTCommandTopic(),
"payload_off": "off", "payload_off": "off",
"payload_on": "on", "payload_on": "on",
"avty_t": viper.GetString("Mqtt.Prefix") + "/" + viper.GetString("Mqtt.LWTTopic"), "avty_t": config.GetString("Mqtt.Prefix") + "/" + config.GetString("Mqtt.LWTTopic"),
"pl_avail": viper.GetString("Mqtt.LWTMessageOnline"), "pl_avail": config.GetString("Mqtt.LWTMessageOnline"),
"pl_not_avail": viper.GetString("Mqtt.LWTMessageOffline"), "pl_not_avail": config.GetString("Mqtt.LWTMessageOffline"),
"unique_id": viper.GetString("Mqtt.Prefix") + "_" + fmt.Sprint(o), "unique_id": config.GetString("Mqtt.Prefix") + "_" + fmt.Sprint(o),
"device": map[string]interface{}{ "device": map[string]interface{}{
"identifiers": []string{viper.GetString("Mqtt.Prefix")}, "identifiers": []string{config.GetString("Mqtt.Prefix")},
}, },
} }
@ -87,18 +88,18 @@ func MQTTSetup() {
mqtt.PublishRoot(hAssTopic, v) mqtt.PublishRoot(hAssTopic, v)
} }
hAssTopic := "homeassistant/switch/" + viper.GetString("Mqtt.Prefix") + "/config" hAssTopic := "homeassistant/switch/" + config.GetString("Mqtt.Prefix") + "/config"
v := "" v := ""
if viper.GetBool("Mqtt.HomeAssistant") { if config.GetBool("Mqtt.HomeAssistant") {
cfg := map[string]interface{}{ cfg := map[string]interface{}{
"name": viper.GetString("system.hostname"), "name": config.GetString("system.hostname"),
"avty_t": viper.GetString("Mqtt.Prefix") + "/" + viper.GetString("Mqtt.LWTTopic"), "avty_t": config.GetString("Mqtt.Prefix") + "/" + config.GetString("Mqtt.LWTTopic"),
"pl_avail": viper.GetString("Mqtt.LWTMessageOnline"), "pl_avail": config.GetString("Mqtt.LWTMessageOnline"),
"pl_not_avail": viper.GetString("Mqtt.LWTMessageOffline"), "pl_not_avail": config.GetString("Mqtt.LWTMessageOffline"),
"unique_id": viper.GetString("Mqtt.Prefix"), "unique_id": config.GetString("Mqtt.Prefix"),
"device": map[string]interface{}{ "device": map[string]interface{}{
"identifiers": []string{viper.GetString("Mqtt.Prefix")}, "identifiers": []string{config.GetString("Mqtt.Prefix")},
"name": viper.GetString("system.hostname"), "name": config.GetString("system.hostname"),
"model": "OpenPDU", "model": "OpenPDU",
"sw_version": version, "sw_version": version,
"manufacturer": "OpenPDU", "manufacturer": "OpenPDU",

View File

@ -5,9 +5,9 @@ import (
"log" "log"
"time" "time"
"git.openpdu.org/OpenPDU/openpdu/config"
"git.openpdu.org/OpenPDU/openpdu/events" "git.openpdu.org/OpenPDU/openpdu/events"
"github.com/RackSec/srslog" "github.com/RackSec/srslog"
"github.com/spf13/viper"
) )
var logger *srslog.Writer var logger *srslog.Writer
@ -22,7 +22,7 @@ var defaults = map[string]interface{}{
func init() { func init() {
for k, v := range defaults { for k, v := range defaults {
viper.SetDefault(k, v) config.SetDefault(k, v)
} }
Connected = false Connected = false
events.AddListener("config_changed", Reconfigure) events.AddListener("config_changed", Reconfigure)
@ -44,14 +44,15 @@ func Reconfigure() {
func Connect() { func Connect() {
var err error var err error
hostname := viper.GetString("Syslog.Host") hostname := config.GetString("Syslog.Host")
port := viper.GetInt("Syslog.Port") port := config.GetInt("Syslog.Port")
protocol := viper.GetString("Syslog.Protocol") protocol := config.GetString("Syslog.Protocol")
format := viper.GetString("Syslog.Format") format := config.GetString("Syslog.Format")
conn := fmt.Sprintf("%s:%d", hostname, port) conn := fmt.Sprintf("%s:%d", hostname, port)
logger, err = srslog.Dial(protocol, conn, srslog.LOG_WARNING|srslog.LOG_DAEMON, "openpdu") logger, err = srslog.Dial(protocol, conn, srslog.LOG_WARNING|srslog.LOG_DAEMON, "openpdu")
if err != nil { if err != nil {
Connected = false
Err(fmt.Sprintf("failed to connect to syslog: %s", err.Error())) Err(fmt.Sprintf("failed to connect to syslog: %s", err.Error()))
time.Sleep(1 * time.Second) time.Sleep(1 * time.Second)
go Connect() go Connect()
@ -65,6 +66,7 @@ func Connect() {
} }
Connected = true Connected = true
logger.Info("OpenPDU connected to syslog")
} }
func Alert(msg string) { func Alert(msg string) {

View File

@ -1,10 +1,10 @@
package ups package ups
import ( import (
"git.openpdu.org/OpenPDU/openpdu/config"
"git.openpdu.org/OpenPDU/openpdu/events" "git.openpdu.org/OpenPDU/openpdu/events"
"git.openpdu.org/OpenPDU/openpdu/syslog" "git.openpdu.org/OpenPDU/openpdu/syslog"
nut "github.com/robbiet480/go.nut" nut "github.com/robbiet480/go.nut"
"github.com/spf13/viper"
) )
var upsClient nut.Client var upsClient nut.Client
@ -22,7 +22,7 @@ var defaults = map[string]interface{}{
func init() { func init() {
for k, v := range defaults { for k, v := range defaults {
viper.SetDefault(k, v) config.SetDefault(k, v)
} }
Connected = false Connected = false
events.AddListener("config_changed", Reconfigure) events.AddListener("config_changed", Reconfigure)
@ -33,16 +33,16 @@ func UpsConnect() {
var connectErr, authenticationError error var connectErr, authenticationError error
var u nut.UPS var u nut.UPS
upsClient, connectErr = nut.Connect(viper.GetString("Ups.Host"), viper.GetInt("Ups.Port")) upsClient, connectErr = nut.Connect(config.GetString("Ups.Host"), config.GetInt("Ups.Port"))
if connectErr != nil { if connectErr != nil {
syslog.Err(connectErr.Error()) syslog.Err(connectErr.Error())
return return
} }
if username = viper.GetString("Ups.Username"); username == "" { if username = config.GetString("Ups.Username"); username == "" {
return return
} }
if password = viper.GetString("Ups.Password"); password == "" { if password = config.GetString("Ups.Password"); password == "" {
return return
} }
@ -59,7 +59,7 @@ func UpsConnect() {
} }
for _, u = range upsList { for _, u = range upsList {
if u.Name == viper.GetString("Ups.Name") { if u.Name == config.GetString("Ups.Name") {
ups = u ups = u
Connected = true Connected = true
UpsReadVars() UpsReadVars()

View File

@ -3,7 +3,7 @@ package webui
import ( import (
"path" "path"
"github.com/spf13/viper" "git.openpdu.org/OpenPDU/openpdu/config"
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
) )
@ -12,7 +12,7 @@ func backupPage(ctx *macaron.Context) {
} }
func backupDownload(ctx *macaron.Context) { func backupDownload(ctx *macaron.Context) {
cfgFile := viper.ConfigFileUsed() cfgFile := config.ConfigFileUsed()
_, fileName := path.Split(cfgFile) _, fileName := path.Split(cfgFile)
ctx.ServeFile(cfgFile, fileName) ctx.ServeFile(cfgFile, fileName)
} }

View File

@ -3,8 +3,8 @@ package webui
import ( import (
"strings" "strings"
"git.openpdu.org/OpenPDU/openpdu/config"
"git.openpdu.org/OpenPDU/openpdu/mqtt" "git.openpdu.org/OpenPDU/openpdu/mqtt"
"github.com/spf13/viper"
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
) )
@ -17,17 +17,17 @@ func SetMQTTReconfigFunction(f MQTTReconfigFunction) {
} }
func mqttPage(ctx *macaron.Context) { func mqttPage(ctx *macaron.Context) {
ctx.Data["schema"] = viper.GetString("Mqtt.Schema") ctx.Data["schema"] = config.GetString("Mqtt.Schema")
ctx.Data["host"] = viper.GetString("Mqtt.Host") ctx.Data["host"] = config.GetString("Mqtt.Host")
ctx.Data["port"] = viper.GetString("Mqtt.Port") ctx.Data["port"] = config.GetString("Mqtt.Port")
ctx.Data["clientid"] = viper.GetString("Mqtt.CliendID") ctx.Data["clientid"] = config.GetString("Mqtt.CliendID")
ctx.Data["prefix"] = viper.GetString("Mqtt.Prefix") ctx.Data["prefix"] = config.GetString("Mqtt.Prefix")
ctx.Data["username"] = viper.GetString("Mqtt.Username") ctx.Data["username"] = config.GetString("Mqtt.Username")
ctx.Data["password"] = viper.GetString("Mqtt.Password") ctx.Data["password"] = config.GetString("Mqtt.Password")
ctx.Data["lwttopic"] = viper.GetString("Mqtt.LWTTopic") ctx.Data["lwttopic"] = config.GetString("Mqtt.LWTTopic")
ctx.Data["lwtonline"] = viper.GetString("Mqtt.LWTMessageOnline") ctx.Data["lwtonline"] = config.GetString("Mqtt.LWTMessageOnline")
ctx.Data["lwtoffline"] = viper.GetString("Mqtt.LWTMessageOffline") ctx.Data["lwtoffline"] = config.GetString("Mqtt.LWTMessageOffline")
ctx.Data["homeassistant"] = viper.GetString("Mqtt.homeassistant") ctx.Data["homeassistant"] = config.GetString("Mqtt.homeassistant")
if mqtt.Connected() { if mqtt.Connected() {
ctx.Data["mqttstatus"] = "Connected" ctx.Data["mqttstatus"] = "Connected"
@ -60,24 +60,24 @@ func mqttPost(ctx *macaron.Context, f MQTTPostForm) {
"tcp", "tcp",
"ssl", "ssl",
"ws": "ws":
viper.Set("Mqtt.Schema", schema) config.Set("Mqtt.Schema", schema)
default: default:
mqttPage(ctx) mqttPage(ctx)
return return
} }
viper.Set("Mqtt.Host", strings.ToLower(strings.TrimSpace(f.Host))) config.Set("Mqtt.Host", strings.ToLower(strings.TrimSpace(f.Host)))
viper.Set("Mqtt.Port", strings.ToLower(strings.TrimSpace(f.Port))) config.Set("Mqtt.Port", strings.ToLower(strings.TrimSpace(f.Port)))
viper.Set("Mqtt.CliendID", strings.TrimSpace(f.ClientID)) config.Set("Mqtt.CliendID", strings.TrimSpace(f.ClientID))
viper.Set("Mqtt.Prefix", strings.TrimSpace(f.Prefix)) config.Set("Mqtt.Prefix", strings.TrimSpace(f.Prefix))
viper.Set("Mqtt.Username", strings.TrimSpace(f.Username)) config.Set("Mqtt.Username", strings.TrimSpace(f.Username))
viper.Set("Mqtt.Password", f.Password) config.Set("Mqtt.Password", f.Password)
viper.Set("Mqtt.LWTTopic", strings.TrimSpace(f.LWTTopic)) config.Set("Mqtt.LWTTopic", strings.TrimSpace(f.LWTTopic))
viper.Set("Mqtt.LWTMessageOnline", strings.TrimSpace(f.LWTMessageOnline)) config.Set("Mqtt.LWTMessageOnline", strings.TrimSpace(f.LWTMessageOnline))
viper.Set("Mqtt.LWTMessageOffline", strings.TrimSpace(f.LWTMessageOffline)) config.Set("Mqtt.LWTMessageOffline", strings.TrimSpace(f.LWTMessageOffline))
viper.Set("Mqtt.HomeAssistant", f.HomeAssistant) config.Set("Mqtt.HomeAssistant", f.HomeAssistant)
viper.WriteConfig() config.WriteConfig()
if mqttReconfigFunction != nil { if mqttReconfigFunction != nil {
go mqttReconfigFunction() go mqttReconfigFunction()

View File

@ -6,9 +6,9 @@ import (
"strconv" "strconv"
"strings" "strings"
"git.openpdu.org/OpenPDU/openpdu/config"
"git.openpdu.org/OpenPDU/openpdu/events" "git.openpdu.org/OpenPDU/openpdu/events"
"git.openpdu.org/OpenPDU/openpdu/outlet" "git.openpdu.org/OpenPDU/openpdu/outlet"
"github.com/spf13/viper"
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
) )
@ -75,7 +75,7 @@ func outletEditPost(ctx *macaron.Context, f OutletPostForm) {
outlet.Outlets[num].Description = strings.TrimSpace(f.Description) outlet.Outlets[num].Description = strings.TrimSpace(f.Description)
s2 := fmt.Sprintf("outlets.%s.description", outlet.Outlets[num].ID) s2 := fmt.Sprintf("outlets.%s.description", outlet.Outlets[num].ID)
viper.Set(s2, outlet.Outlets[num].Description) config.Set(s2, outlet.Outlets[num].Description)
mqttstate := strings.TrimSpace(f.MQTTStateTopic) mqttstate := strings.TrimSpace(f.MQTTStateTopic)
if mqttstate == "" { if mqttstate == "" {
@ -89,7 +89,7 @@ func outletEditPost(ctx *macaron.Context, f OutletPostForm) {
} }
outlet.Outlets[num].Channel.SetMQTTCommandTopic(mqttcommand) outlet.Outlets[num].Channel.SetMQTTCommandTopic(mqttcommand)
viper.WriteConfig() config.WriteConfig()
events.FireEvent("outlet_config_changed") events.FireEvent("outlet_config_changed")

View File

@ -3,16 +3,16 @@ package webui
import ( import (
"strings" "strings"
"git.openpdu.org/OpenPDU/openpdu/config"
"git.openpdu.org/OpenPDU/openpdu/syslog" "git.openpdu.org/OpenPDU/openpdu/syslog"
"github.com/spf13/viper"
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
) )
func syslogPage(ctx *macaron.Context) { func syslogPage(ctx *macaron.Context) {
ctx.Data["host"] = viper.GetString("Syslog.Host") ctx.Data["host"] = config.GetString("Syslog.Host")
ctx.Data["port"] = viper.GetInt("Syslog.Port") ctx.Data["port"] = config.GetInt("Syslog.Port")
ctx.Data["protocol"] = viper.GetString("Syslog.Protocol") ctx.Data["protocol"] = config.GetString("Syslog.Protocol")
ctx.Data["format"] = viper.GetString("Syslog.Format") ctx.Data["format"] = config.GetString("Syslog.Format")
if syslog.Connected { if syslog.Connected {
ctx.Data["status"] = "Connected" ctx.Data["status"] = "Connected"
@ -32,12 +32,12 @@ type SyslogPostForm struct {
func syslogPost(ctx *macaron.Context, f SyslogPostForm) { func syslogPost(ctx *macaron.Context, f SyslogPostForm) {
// TODO: check protocol, it should be 'udp' or 'tcp' // TODO: check protocol, it should be 'udp' or 'tcp'
viper.Set("Syslog.Host", strings.ToLower(strings.TrimSpace(f.Host))) config.Set("Syslog.Host", strings.ToLower(strings.TrimSpace(f.Host)))
viper.Set("Syslog.Port", f.Port) config.Set("Syslog.Port", f.Port)
viper.Set("Syslog.Protocol", strings.TrimSpace(f.Protocol)) config.Set("Syslog.Protocol", strings.TrimSpace(f.Protocol))
// TODO: check format, it should be 'RFC5424' or 'RFC3164' // TODO: check format, it should be 'RFC5424' or 'RFC3164'
viper.Set("Syslog.Format", strings.TrimSpace(f.Format)) config.Set("Syslog.Format", strings.TrimSpace(f.Format))
viper.WriteConfig() config.WriteConfig()
syslogPage(ctx) syslogPage(ctx)
} }

View File

@ -3,17 +3,17 @@ package webui
import ( import (
"strings" "strings"
"git.openpdu.org/OpenPDU/openpdu/config"
"git.openpdu.org/OpenPDU/openpdu/ups" "git.openpdu.org/OpenPDU/openpdu/ups"
"github.com/spf13/viper"
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
) )
func upsPage(ctx *macaron.Context) { func upsPage(ctx *macaron.Context) {
ctx.Data["host"] = viper.GetString("Ups.Host") ctx.Data["host"] = config.GetString("Ups.Host")
ctx.Data["port"] = viper.GetInt("Ups.Port") ctx.Data["port"] = config.GetInt("Ups.Port")
ctx.Data["upsname"] = viper.GetString("Ups.Name") ctx.Data["upsname"] = config.GetString("Ups.Name")
ctx.Data["username"] = viper.GetString("Ups.Username") ctx.Data["username"] = config.GetString("Ups.Username")
ctx.Data["password"] = viper.GetString("Ups.Password") ctx.Data["password"] = config.GetString("Ups.Password")
if ups.Connected { if ups.Connected {
ctx.Data["serverstatus"] = "Connected" ctx.Data["serverstatus"] = "Connected"
@ -40,12 +40,12 @@ type UPSPostForm struct {
} }
func upsPost(ctx *macaron.Context, f UPSPostForm) { func upsPost(ctx *macaron.Context, f UPSPostForm) {
viper.Set("Ups.Host", strings.ToLower(strings.TrimSpace(f.Host))) config.Set("Ups.Host", strings.ToLower(strings.TrimSpace(f.Host)))
viper.Set("Ups.Port", f.Port) config.Set("Ups.Port", f.Port)
viper.Set("Ups.Name", strings.TrimSpace(f.UpsName)) config.Set("Ups.Name", strings.TrimSpace(f.UpsName))
viper.Set("Ups.Username", strings.TrimSpace(f.Username)) config.Set("Ups.Username", strings.TrimSpace(f.Username))
viper.Set("Ups.Password", f.Password) config.Set("Ups.Password", f.Password)
viper.WriteConfig() config.WriteConfig()
upsPage(ctx) upsPage(ctx)
} }

View File

@ -3,10 +3,10 @@ package webui
import ( import (
"net/http" "net/http"
"git.openpdu.org/OpenPDU/openpdu/config"
"git.openpdu.org/OpenPDU/openpdu/syslog" "git.openpdu.org/OpenPDU/openpdu/syslog"
"github.com/go-macaron/binding" "github.com/go-macaron/binding"
"github.com/go-macaron/pongo2" "github.com/go-macaron/pongo2"
"github.com/spf13/viper"
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
) )
@ -14,7 +14,7 @@ import (
type Dictionary map[string]interface{} type Dictionary map[string]interface{}
func init() { func init() {
viper.SetDefault("system.listeningport", 4000) config.SetDefault("system.listeningport", 4000)
} }
func StartServer() { func StartServer() {
@ -39,5 +39,5 @@ func StartServer() {
m.Post("/json/outlet/:id/toggle", jsonOutletToggle) m.Post("/json/outlet/:id/toggle", jsonOutletToggle)
syslog.Info("Web interface ready") syslog.Info("Web interface ready")
http.ListenAndServe("0.0.0.0:"+viper.GetString("system.listeningport"), m) http.ListenAndServe("0.0.0.0:"+config.GetString("system.listeningport"), m)
} }