2020-02-04 20:25:10 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
io "io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
flag "github.com/spf13/pflag"
|
|
|
|
"gopkg.in/yaml.v2"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
configFile string
|
|
|
|
addr string
|
|
|
|
)
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
flag.StringVar(&configFile, "config", "conf.yml", "")
|
|
|
|
flag.StringVar(&addr, "addr", ":8080", "")
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
flag.Parse()
|
|
|
|
|
|
|
|
if _, err := os.Stat(configFile); err == os.ErrNotExist {
|
|
|
|
logrus.Fatal("Config file not found")
|
|
|
|
flag.PrintDefaults()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
logrus.Println("Welcome to Spacepanel Aggregator!")
|
|
|
|
logrus.Println()
|
|
|
|
logrus.Printf("Listen Address: %s", addr)
|
|
|
|
logrus.Printf("Config-File: %s", configFile)
|
|
|
|
|
|
|
|
bytes, err := io.ReadFile(configFile)
|
|
|
|
if err != nil {
|
|
|
|
logrus.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2020-02-04 21:58:26 +00:00
|
|
|
var ledSpaceMap map[int][]string
|
2020-02-04 20:25:10 +00:00
|
|
|
err = yaml.Unmarshal(bytes, &ledSpaceMap)
|
|
|
|
if err != nil {
|
|
|
|
logrus.Fatalf("Error loading config file: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
spaceCount := 0
|
|
|
|
for _, spaces := range ledSpaceMap {
|
|
|
|
spaceCount += len(spaces)
|
|
|
|
}
|
|
|
|
|
|
|
|
fmt.Println("Loaded", len(ledSpaceMap), "LED-configs and", spaceCount, "spaces.")
|
|
|
|
|
|
|
|
aggregator := NewStateAggregator(ledSpaceMap)
|
|
|
|
|
|
|
|
server := http.Server{
|
|
|
|
Addr: addr,
|
|
|
|
}
|
|
|
|
|
|
|
|
http.HandleFunc("/leds", func(writer http.ResponseWriter, request *http.Request) {
|
|
|
|
data, err := json.Marshal(aggregator.GetLedStates())
|
|
|
|
if err != nil {
|
|
|
|
logrus.Error(err)
|
2020-02-04 21:45:06 +00:00
|
|
|
writer.WriteHeader(501)
|
2020-02-04 20:25:10 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-02-04 21:45:06 +00:00
|
|
|
writer.Header().Add("Content-Type", "application/json")
|
2020-02-04 20:25:10 +00:00
|
|
|
writer.Write(data)
|
|
|
|
})
|
|
|
|
|
|
|
|
server.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
logrus.Infof("Request: %s %s %s", r.RemoteAddr, r.Method, r.URL)
|
|
|
|
http.DefaultServeMux.ServeHTTP(w, r)
|
|
|
|
})
|
|
|
|
|
|
|
|
logrus.Fatal(server.ListenAndServe())
|
|
|
|
}
|