Files
rpi-sensors/climate-server.go

111 lines
3.1 KiB
Go

package main
import (
"errors"
"fmt"
"github.com/gorilla/mux"
"log"
"net/http"
"strconv"
)
const DEBUG = true
const ROOT_URL = "climate/"
func main() {
err := setup()
defer teardown()
if err == nil {
startServer()
} else {
fmt.Println(err)
}
}
func setup() error {
err := InitDb()
if err != nil {
return err
}
return nil
}
func teardown() {
CloseDb()
}
func startServer() {
port := "8001"
r := mux.NewRouter()
r.HandleFunc("/", showCharts).Methods("GET")
r.HandleFunc("/since/{mins}", showCharts).Methods("GET")
r.HandleFunc("/data/", sendData).Methods("GET")
r.HandleFunc("/data/since/{mins}", sendData).Methods("GET")
r.HandleFunc("/data/last/", sendLastSnapshot).Methods("GET")
r.HandleFunc("/", saveSnapshot).Methods("POST")
r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
http.Handle("/", r)
fmt.Printf("Listening on port %s...\n", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}
func showCharts(w http.ResponseWriter, r *http.Request) {
if countStr := mux.Vars(r)["mins"]; countStr != "" {
if _, err := strconv.ParseInt(countStr, 10, 0); err != nil {
http.Redirect(w, r, "/" + ROOT_URL + "/", 303)
}
}
http.ServeFile(w, r, "charts.html")
}
func sendData(w http.ResponseWriter, r *http.Request) {
var count int64 = 60
if vars := mux.Vars(r); vars["mins"] != "" {
newCount, err := strconv.ParseInt(vars["mins"], 10, 0)
if err != nil {
http.Redirect(w, r, "/" + ROOT_URL + "/", 303)
}
count = newCount
}
records, err := getSnapshotRecordsFromDb(int(count))
if internalErrorOnErr(fmt.Errorf("couldn't get snapshots from db: %w", err), w, r) { return }
json, err := createJsonFromSnapshotRecords(records)
if internalErrorOnErr(fmt.Errorf("couldn't create json from snapshots: %w", err), w, r) { return }
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, string(json))
}
func sendLastSnapshot(w http.ResponseWriter, r *http.Request) {
record, err := getLastSnapshotRecordFromDb()
if internalErrorOnErr(fmt.Errorf("couldn't get last snapshot from db: %w", err), w, r) { return }
json, err := createJsonFromSnapshotRecords([]*SnapshotRecord{record})
if internalErrorOnErr(fmt.Errorf("couldn't create json from last snapshots: %w", err), w, r) { return }
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, string(json))
}
func saveSnapshot(w http.ResponseWriter, r *http.Request) {
snapshotSub, err := createSnapshotSubFromJsonBodyStream(r.Body)
if internalErrorOnErr(fmt.Errorf("couldn't create snapshot from JSON: %w", err), w, r) { return }
newId, err := writeSnapshotToDb(snapshotSub)
if internalErrorOnErr(fmt.Errorf("couldn't submit snapshot into the database: %w", err), w, r) { return }
fmt.Fprintf(w, "{id: %v}", newId)
}
func internalErrorOnErr(err error, w http.ResponseWriter, r *http.Request) bool {
if errors.Unwrap(err) != nil {
errorMessage := "Internal Server Error!"
if DEBUG {
errorMessage += fmt.Sprintf(" Happened during %s request for pattern '%s': %s",
r.Method,
r.URL,
err.Error())
}
fmt.Println(errorMessage)
http.Error(w, errorMessage, 500)
return true
}
return false
}