Update config.go, display.go, and 6 more files...

This commit is contained in:
Paolo Asperti 2020-12-30 14:47:36 +01:00
parent 97fed358c6
commit 1b542a3109
8 changed files with 157 additions and 68 deletions

View File

@ -6,7 +6,7 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
) )
func readConfig() { func init() {
viper.SetConfigName("openpdu") // name of config file (without extension) viper.SetConfigName("openpdu") // name of config file (without extension)
viper.SetConfigType("yaml") viper.SetConfigType("yaml")
viper.AddConfigPath(".") // optionally look for config in the working directory viper.AddConfigPath(".") // optionally look for config in the working directory

View File

@ -3,27 +3,69 @@ package main
import ( import (
"image" "image"
"image/color" "image/color"
"log"
"net" "net"
"time"
"github.com/spf13/viper" "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"
// "periph.io/x/periph/conn/i2c/i2creg"
"periph.io/x/periph/devices/ssd1306" "periph.io/x/periph/devices/ssd1306"
) )
func init() { func init() {
viper.SetDefault("DisplayType", "none") logInfo("display setup")
displayLoop() viper.SetDefault("Display.Type", "none")
viper.SetDefault("Display.W", 128)
viper.SetDefault("Display.H", 32)
viper.SetDefault("Display.Rotated", false)
viper.SetDefault("Display.SwapTopBottom", false)
go displayLoop()
logInfo("display setup completed")
} }
func displayLoop() { func displayLoop() {
if viper.GetString("DisplayType") == "ssd1306" { for {
initI2C() logInfo("ssd1306 display starting loop")
go disp()
if viper.GetString("Display.Type") != "ssd1306" {
logWarning("ssd1306 disabled")
time.Sleep(1 * time.Second)
continue
}
if i2cbus == nil {
logWarning("ssd1306 i2cbus not found")
time.Sleep(1 * time.Second)
continue
}
opts := ssd1306.Opts{
W: viper.GetInt("Display.W"),
H: viper.GetInt("Display.H"),
Rotated: viper.GetBool("Display.Rotated"),
Sequential: true,
SwapTopBottom: viper.GetBool("Display.SwapTopBottom"),
}
// Open a handle to a ssd1306 connected on the I²C bus:
dev, err := ssd1306.NewI2C(i2cbus, &opts)
if err != nil {
logErr(err.Error())
}
logInfo("ssd1306 display setup completed")
for {
err := disp(dev)
if err != nil {
logErr(err.Error())
time.Sleep(1 * time.Second)
logWarning("ssd1306 display disp error")
continue
}
}
} }
} }
@ -70,26 +112,11 @@ func getIPs() map[string]string {
return out return out
} }
func disp() { func disp(dev *ssd1306.Dev) error {
opts := ssd1306.Opts{
W: 128,
H: 32,
Rotated: false,
Sequential: true,
SwapTopBottom: false,
}
// Open a handle to a ssd1306 connected on the I²C bus:
dev, err := ssd1306.NewI2C(i2cbus, &opts)
if err != nil {
log.Fatal(err)
}
img := image.NewRGBA(image.Rect(0, 0, 128, 32)) img := image.NewRGBA(image.Rect(0, 0, 128, 32))
ips := getIPs() ips := getIPs()
lineHeight := 12 lineHeight := 12
// posX := 10
posX := 12 posX := 12
posY := lineHeight posY := lineHeight
// for name, ip := range ips { // for name, ip := range ips {
@ -99,6 +126,5 @@ func disp() {
addLabel(img, posX, posY, ip) addLabel(img, posX, posY, ip)
posY += lineHeight posY += lineHeight
} }
dev.Draw(img.Bounds(), img, image.Point{}) return dev.Draw(img.Bounds(), img, image.Point{})
} }

View File

@ -2,7 +2,7 @@ package main
import ( import (
"errors" "errors"
"log" "fmt"
"periph.io/x/periph/conn/i2c" "periph.io/x/periph/conn/i2c"
"periph.io/x/periph/conn/i2c/i2creg" "periph.io/x/periph/conn/i2c/i2creg"
@ -74,23 +74,28 @@ func (b I2CBoard) channelToggle(ch uint) error {
return nil return nil
} }
func initI2C() { func init() {
var err error var err error
logInfo("i2c setup")
// Make sure periph is initialized. // Make sure periph is initialized.
if _, err = host.Init(); err != nil { if _, err = host.Init(); err != nil {
log.Fatal(err) logErr(err.Error())
} }
// Use i2creg I²C bus registry to find the first available I²C bus. // Use i2creg I²C bus registry to find the first available I²C bus.
// i2cbus, err = i2creg.Open("/dev/i2c-1") // i2cbus, err = i2creg.Open("/dev/i2c-1")
i2cbus, err = i2creg.Open("") i2cbus, err = i2creg.Open("")
if err != nil { if err != nil {
log.Fatal(err) logErr(err.Error())
} }
// defer i2cbus.Close()
// bus 0 logInfo("i2c setup completed")
// Dev is a valid conn.Conn. }
func initI2C() {
mydevice := &i2c.Dev{Addr: 0x27, Bus: i2cbus} mydevice := &i2c.Dev{Addr: 0x27, Bus: i2cbus}
// Send a command 0x10 and expect a 5 bytes reply. // Send a command 0x10 and expect a 5 bytes reply.
@ -99,7 +104,7 @@ func initI2C() {
// read := make([]byte, 5) // read := make([]byte, 5)
// if err := d.Tx(write, read); err != nil { // if err := d.Tx(write, read); err != nil {
if _, err := mydevice.Write(write); err != nil { if _, err := mydevice.Write(write); err != nil {
log.Fatal(err) logErr(err.Error())
} }
MyBoard.i2cdev = *mydevice MyBoard.i2cdev = *mydevice
@ -110,9 +115,9 @@ func initI2C() {
for i = 0; i < 8; i++ { for i = 0; i < 8; i++ {
v, err := MyBoard.channelStatus(i) v, err := MyBoard.channelStatus(i)
if err != nil { if err != nil {
log.Fatal(err) logErr(err.Error())
} }
log.Printf("Channel %d status: %v", i, v) logInfo(fmt.Sprintf("Channel %d status: %v", i, v))
} }
}() }()
} }

View File

@ -1,11 +1,6 @@
package main package main
import ( import (
// "encoding/json"
"log"
// "periph.io/x/periph"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -17,10 +12,9 @@ func init() {
} }
func main() { func main() {
readConfig()
go mqttLoop() go mqttLoop()
go UpsConnect() go UpsConnect()
log.Printf("hostname: %v\n", viper.Get("hostname")) logInfo("hostname: " + viper.GetString("hostname"))
startServer() startServer()
} }
@ -34,7 +28,5 @@ func main() {
- fai funzionare toggle - fai funzionare toggle
- scan i2c - scan i2c
- impostazioni log - impostazioni log
- impostazioni mqtt
*/ */

View File

@ -1,7 +1,6 @@
package main package main
import ( import (
"fmt"
"time" "time"
MQTT "github.com/eclipse/paho.mqtt.golang" MQTT "github.com/eclipse/paho.mqtt.golang"
@ -49,13 +48,13 @@ func mqttLoop() {
opts.SetConnectTimeout(5 * time.Second) opts.SetConnectTimeout(5 * time.Second)
opts.SetConnectionLostHandler(func(c MQTT.Client, err error) { opts.SetConnectionLostHandler(func(c MQTT.Client, err error) {
fmt.Printf("!!!!!! mqtt connection lost error: %s\n" + err.Error()) logErr("mqtt connection lost error: " + err.Error())
}) })
opts.SetReconnectingHandler(func(c MQTT.Client, options *MQTT.ClientOptions) { opts.SetReconnectingHandler(func(c MQTT.Client, options *MQTT.ClientOptions) {
fmt.Println("...... mqtt reconnecting ......") logNotice("mqtt reconnecting")
}) })
opts.SetOnConnectHandler(func(c MQTT.Client) { opts.SetOnConnectHandler(func(c MQTT.Client) {
fmt.Println("...... mqtt connected ......") logNotice("mqtt connected")
// MQTTclient.Publish("openpdu/status", 0, false, "connected") // MQTTclient.Publish("openpdu/status", 0, false, "connected")
}) })

View File

@ -6,19 +6,81 @@ import (
syslog "github.com/RackSec/srslog" syslog "github.com/RackSec/srslog"
) )
var logger *syslog.Writer
func init() { func init() {
w, err := syslog.Dial("", "", syslog.LOG_ERR, "testtag") var err error
logger, err = syslog.Dial("", "", syslog.LOG_ERR, "openpdu")
// w, err := syslog.Dial("udp", "192.168.0.50:514", syslog.LOG_ERR, "openpdu")
if err != nil { if err != nil {
log.Fatal("failed to connect to syslog:", err) log.Fatal("failed to connect to syslog:", err)
} }
defer w.Close()
w.Alert("this is an alert") // logger.Alert("this is an alert")
w.Crit("this is critical") // logger.Crit("this is critical")
w.Err("this is an error") // logger.Err("this is an error")
w.Warning("this is a warning") // logger.Warning("this is a warning")
w.Notice("this is a notice") // logger.Notice("this is a notice")
w.Info("this is info") // logger.Info("this is info")
w.Debug("this is debug") // logger.Debug("this is debug")
w.Write([]byte("these are some bytes")) // logger.Write([]byte("these are some bytes"))
}
func logAlert(msg string) {
if logger == nil {
log.Printf(msg)
} else {
logger.Alert(msg)
}
}
func logCrit(msg string) {
if logger == nil {
log.Printf(msg)
} else {
logger.Crit(msg)
}
}
func logErr(msg string) {
if logger == nil {
log.Printf(msg)
} else {
logger.Err(msg)
}
}
func logWarning(msg string) {
if logger == nil {
log.Printf(msg)
} else {
logger.Warning(msg)
}
}
func logNotice(msg string) {
if logger == nil {
log.Printf(msg)
} else {
logger.Notice(msg)
}
}
func logInfo(msg string) {
if logger == nil {
log.Printf(msg)
} else {
logger.Info(msg)
}
}
func logDebug(msg string) {
if logger == nil {
log.Printf(msg)
} else {
logger.Debug(msg)
}
} }

View File

@ -1,8 +1,6 @@
package main package main
import ( import (
"fmt"
nut "github.com/robbiet480/go.nut" nut "github.com/robbiet480/go.nut"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
@ -25,7 +23,7 @@ func UpsConnect() {
upsClient, connectErr = nut.Connect(viper.GetString("UpsHost")) upsClient, connectErr = nut.Connect(viper.GetString("UpsHost"))
if connectErr != nil { if connectErr != nil {
fmt.Print(connectErr) logErr(connectErr.Error())
return return
} }
@ -38,20 +36,20 @@ func UpsConnect() {
_, authenticationError = upsClient.Authenticate(username, password) _, authenticationError = upsClient.Authenticate(username, password)
if authenticationError != nil { if authenticationError != nil {
fmt.Print(authenticationError) logErr(authenticationError.Error())
return return
} }
upsList, listErr := upsClient.GetUPSList() upsList, listErr := upsClient.GetUPSList()
if listErr != nil { if listErr != nil {
fmt.Print(listErr) logErr(listErr.Error())
return return
} }
for _, u = range upsList { for _, u = range upsList {
if u.Name == viper.GetString("UpsName") { if u.Name == viper.GetString("UpsName") {
ups = u ups = u
fmt.Print("UPS connected") logNotice("UPS connected")
UpsReadVars() UpsReadVars()
} }
} }
@ -67,6 +65,6 @@ func UpsReadVars() {
func UpsReconfigure() { func UpsReconfigure() {
ups = nut.UPS{} ups = nut.UPS{}
upsClient = nut.Client{} upsClient = nut.Client{}
fmt.Print("UPS disconnected") logNotice("UPS disconnected")
go UpsConnect() go UpsConnect()
} }

View File

@ -8,6 +8,7 @@ import (
"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"
) )
@ -98,6 +99,10 @@ func jsonOutletToggle(ctx *macaron.Context) {
}) })
} }
func init() {
viper.SetDefault("listeningport", 4000)
}
func startServer() { func startServer() {
m := macaron.Classic() m := macaron.Classic()
m.Use(pongo2.Pongoer()) m.Use(pongo2.Pongoer())
@ -119,6 +124,8 @@ func startServer() {
ctx.HTML(200, "boards") // 200 is the response code. ctx.HTML(200, "boards") // 200 is the response code.
}) })
log.Println("Server is running...") logInfo("hostname: " + viper.GetString("hostname"))
log.Println(http.ListenAndServe("0.0.0.0:4000", m))
logInfo("Web interface ready")
http.ListenAndServe("0.0.0.0:"+viper.GetString("listeningport"), m)
} }