spaceapid/main.go

77 lines
1.7 KiB
Go
Raw Normal View History

2023-11-04 20:10:08 +01:00
package main
import (
"flag"
"fmt"
2023-11-04 20:10:08 +01:00
"log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
2023-11-04 20:10:08 +01:00
"gitlab.hamburg.ccc.de/ccchh/spaceapid/config"
"gitlab.hamburg.ccc.de/ccchh/spaceapid/handlers"
2023-11-10 03:49:05 +01:00
"gitlab.hamburg.ccc.de/ccchh/spaceapid/types"
"gitlab.hamburg.ccc.de/ccchh/spaceapid/util"
2023-11-04 20:10:08 +01:00
)
var (
flagHelp bool
)
func init() {
flag.BoolVar(&flagHelp, "h", false, "Print help output")
}
2023-11-04 20:10:08 +01:00
func main() {
flag.Parse()
if flagHelp {
flag.PrintDefaults()
os.Exit(0)
}
// Get spaceapid configuration
conf := config.ParseConfiguration()
2023-11-04 20:10:08 +01:00
// Merge old state if present
util.MergeOldState(&conf.Response)
2023-11-10 03:49:05 +01:00
// Register signal handler
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM)
2024-01-06 19:43:51 +01:00
go func(resp *types.SpaceAPIResponseV14) {
<-sc
2023-11-10 03:49:05 +01:00
log.Println("Saving state and shutting down...")
util.SaveCurrentState(*resp)
os.Exit(0)
}(&conf.Response)
2023-11-10 03:49:05 +01:00
// 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],
),
)
}
}
2023-11-04 20:10:08 +01:00
// Start webserver
2023-11-04 20:10:08 +01:00
log.Println("Starting HTTP server...")
2023-11-10 03:49:05 +01:00
log.Fatalln(http.ListenAndServe(":8080", nil))
2023-11-04 20:10:08 +01:00
}