openpdu/src/ups.go

71 lines
1.3 KiB
Go
Raw Normal View History

2020-12-27 21:29:16 +00:00
package main
import (
nut "github.com/robbiet480/go.nut"
"github.com/spf13/viper"
)
var upsClient nut.Client
var ups nut.UPS
var upsVars map[string]nut.Variable
func init() {
viper.SetDefault("UpsHost", "localhost")
viper.SetDefault("UpsName", "ups")
viper.SetDefault("UpsUsername", "")
viper.SetDefault("UpsPassword", "")
}
func UpsConnect() {
var username, password string
var connectErr, authenticationError error
var u nut.UPS
upsClient, connectErr = nut.Connect(viper.GetString("UpsHost"))
if connectErr != nil {
logErr(connectErr.Error())
2020-12-27 21:29:16 +00:00
return
}
if username = viper.GetString("UpsUsername"); username == "" {
return
}
if password = viper.GetString("UpsPassword"); password == "" {
return
}
_, authenticationError = upsClient.Authenticate(username, password)
if authenticationError != nil {
logErr(authenticationError.Error())
2020-12-27 21:29:16 +00:00
return
}
upsList, listErr := upsClient.GetUPSList()
if listErr != nil {
logErr(listErr.Error())
2020-12-27 21:29:16 +00:00
return
}
for _, u = range upsList {
if u.Name == viper.GetString("UpsName") {
ups = u
logNotice("UPS connected")
2020-12-27 21:29:16 +00:00
UpsReadVars()
}
}
}
func UpsReadVars() {
upsVars = map[string]nut.Variable{}
for _, v := range ups.Variables {
upsVars[v.Name] = v
}
}
func UpsReconfigure() {
ups = nut.UPS{}
upsClient = nut.Client{}
logNotice("UPS disconnected")
2020-12-27 21:29:16 +00:00
go UpsConnect()
}