80 lines
1.8 KiB
Go
80 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"strings"
|
|
"syscall"
|
|
|
|
"gitlab.hamburg.ccc.de/ccchh/spaceapid/config"
|
|
"gitlab.hamburg.ccc.de/ccchh/spaceapid/handlers"
|
|
"gitlab.hamburg.ccc.de/ccchh/spaceapid/types"
|
|
"gitlab.hamburg.ccc.de/ccchh/spaceapid/util"
|
|
)
|
|
|
|
var (
|
|
flagHelp bool
|
|
version string
|
|
)
|
|
|
|
func init() {
|
|
flag.BoolVar(&flagHelp, "h", false, "Print help output")
|
|
}
|
|
|
|
func main() {
|
|
log.Println("SpaceAPId version", version)
|
|
|
|
flag.Parse()
|
|
|
|
if flagHelp {
|
|
flag.PrintDefaults()
|
|
os.Exit(0)
|
|
}
|
|
|
|
// Get spaceapid configuration
|
|
conf := config.ParseConfiguration()
|
|
|
|
// Merge old state if present
|
|
util.MergeOldState(&conf.Response)
|
|
|
|
// Register signal handler
|
|
sc := make(chan os.Signal, 1)
|
|
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM)
|
|
go func(resp *types.SpaceAPIResponseV14) {
|
|
<-sc
|
|
log.Println("Saving state and shutting down...")
|
|
util.SaveCurrentState(*resp)
|
|
os.Exit(0)
|
|
}(&conf.Response)
|
|
|
|
// Register HTTP handlers
|
|
http.HandleFunc("/",
|
|
handlers.Root(&conf.Response),
|
|
)
|
|
http.HandleFunc("/state/open",
|
|
handlers.StateOpen(conf.Credentials, conf.Dynamic.State.Open.AllowedCredentials, &conf.Response.State),
|
|
)
|
|
// Register handlers for Environmental Sensors
|
|
for key, envSensorConfigs := range conf.Dynamic.Sensors {
|
|
for i, envSensorConfig := range envSensorConfigs {
|
|
pattern := fmt.Sprintf("/sensors/%s/%s", key, envSensorConfig.SensorData.Location)
|
|
if envSensorConfig.SensorData.Name != "" {
|
|
pattern += "/" + envSensorConfig.SensorData.Name
|
|
}
|
|
http.HandleFunc(strings.ToLower(pattern),
|
|
handlers.EnvironmentSensor(
|
|
conf.Credentials, envSensorConfig.AllowedCredentials, &conf.Response.Sensors[key][i],
|
|
),
|
|
)
|
|
}
|
|
}
|
|
|
|
// Start webserver
|
|
log.Println("Starting HTTP server...")
|
|
log.Fatalln(http.ListenAndServe(":8080", nil))
|
|
}
|