spacepanel_aggregator/setup.go

85 lines
1.7 KiB
Go
Raw Normal View History

2020-01-30 17:34:56 +00:00
package spacepanel_aggregator
import (
"fmt"
2020-01-30 23:24:19 +00:00
"github.com/gin-gonic/gin"
2020-01-30 17:34:56 +00:00
yaml "gopkg.in/yaml.v2"
io "io/ioutil"
2020-01-30 23:24:19 +00:00
"net/http"
"time"
2020-01-30 17:34:56 +00:00
)
var listen = ":8080"
var conffile = "conf.yml"
2020-01-30 23:24:19 +00:00
var sleeptime time.Duration = 60000000000 // nanoseconds
2020-01-30 17:34:56 +00:00
var leds [][]string
2020-01-30 23:24:19 +00:00
var spacestates map[string]State
2020-01-30 17:34:56 +00:00
func SetConf(s string) {
conffile = s
}
func SetIf(s string) {
listen = s
}
func Start() {
fmt.Println("Welcome to Spacepanel Aggregator!\n")
fmt.Println("Listen Interface: ", listen)
fmt.Println("Config-File: ", conffile)
bytes, err := io.ReadFile(conffile)
if err != nil {
ce(err)
}
err = yaml.Unmarshal(bytes, &leds)
if err != nil {
ce(err)
2020-01-30 23:24:19 +00:00
panic("An error occured while parsing the conffile, quitting...")
2020-01-30 17:34:56 +00:00
}
2020-01-30 23:24:19 +00:00
spacestates = make(map[string]State)
2020-01-30 17:34:56 +00:00
for i := 0; i < len(leds); i++ {
for j := 0; j < len(leds[i]); j++ {
2020-01-30 23:24:19 +00:00
spacestates[leds[i][j]] = Unknown
go Poll(leds[i][j])
2020-01-30 17:34:56 +00:00
}
}
2020-01-30 23:24:19 +00:00
fmt.Println("Loaded", len(leds), "LED-configs and", len(spacestates), "spaces.")
r := setupRouter()
_ = r.Run(listen)
}
func getBestState(states []string) State {
returner := Unknown
for i := 0; i < len(states); i++ {
if spacestates[states[i]] < returner {
returner = spacestates[states[i]]
}
}
return returner
}
func getLedStates(c *gin.Context) {
returner := make([]string, len(leds))
for i := 0; i < len(leds); i++ {
returner[i] = colors[getBestState(leds[i])]
}
c.JSON(http.StatusOK, returner)
}
func setupRouter() *gin.Engine {
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
// Ping test
//r.GET("/leds", getLedStates())
r.GET("/leds", getLedStates)
return r
2020-01-30 17:34:56 +00:00
}
func ce(err error) {
if err != nil {
fmt.Println("ERROR: ", err.Error())
}
}