openpdu/src/ups.go
2021-01-04 12:28:20 +01:00

71 lines
1.3 KiB
Go

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("Ups.Host", "localhost")
viper.SetDefault("Ups.Name", "ups")
viper.SetDefault("Ups.Username", "")
viper.SetDefault("Ups.Password", "")
}
func UpsConnect() {
var username, password string
var connectErr, authenticationError error
var u nut.UPS
upsClient, connectErr = nut.Connect(viper.GetString("Ups.Host"))
if connectErr != nil {
logErr(connectErr.Error())
return
}
if username = viper.GetString("Ups.Username"); username == "" {
return
}
if password = viper.GetString("Ups.Password"); password == "" {
return
}
_, authenticationError = upsClient.Authenticate(username, password)
if authenticationError != nil {
logErr(authenticationError.Error())
return
}
upsList, listErr := upsClient.GetUPSList()
if listErr != nil {
logErr(listErr.Error())
return
}
for _, u = range upsList {
if u.Name == viper.GetString("Ups.Name") {
ups = u
logNotice("UPS connected")
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")
go UpsConnect()
}