Add tiny webserver for JSON data
This commit is contained in:
37
main.go
37
main.go
@ -4,6 +4,7 @@ import (
|
|||||||
"bufio"
|
"bufio"
|
||||||
"bytes"
|
"bytes"
|
||||||
"database/sql"
|
"database/sql"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"image"
|
"image"
|
||||||
"image/jpeg"
|
"image/jpeg"
|
||||||
@ -75,6 +76,7 @@ func main() {
|
|||||||
webcamURL := getEnv("WEBCAM_URL", "http://furnace.service:8082/stream")
|
webcamURL := getEnv("WEBCAM_URL", "http://furnace.service:8082/stream")
|
||||||
minBrightness := getEnvInt("MIN_BRIGHTNESS", 150)
|
minBrightness := getEnvInt("MIN_BRIGHTNESS", 150)
|
||||||
checkInterval := getEnvDuration("CHECK_INTERVAL", 2*time.Second)
|
checkInterval := getEnvDuration("CHECK_INTERVAL", 2*time.Second)
|
||||||
|
webPort := getEnv("FURNACE_WEB_PORT", "8090")
|
||||||
|
|
||||||
fmt.Println("Using DB:", dbPath)
|
fmt.Println("Using DB:", dbPath)
|
||||||
fmt.Println("Using webcam:", webcamURL)
|
fmt.Println("Using webcam:", webcamURL)
|
||||||
@ -83,6 +85,9 @@ func main() {
|
|||||||
|
|
||||||
db, err := sql.Open("sqlite", dbPath)
|
db, err := sql.Open("sqlite", dbPath)
|
||||||
|
|
||||||
|
go startWebServer(db, getEnv("HTTP_PORT", webPort))
|
||||||
|
fmt.Println("Starting json data server on port ", webPort)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@ -254,3 +259,35 @@ func sendNtfyNotification(light Light, on bool) {
|
|||||||
}
|
}
|
||||||
resp.Body.Close()
|
resp.Body.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func startWebServer(db *sql.DB, port string) {
|
||||||
|
http.HandleFunc("/lights", func(w http.ResponseWriter, r *http.Request) {
|
||||||
|
rows, err := db.Query(`
|
||||||
|
SELECT name, state, MAX(timestamp)
|
||||||
|
FROM light_checks
|
||||||
|
GROUP BY name
|
||||||
|
`)
|
||||||
|
if err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
resp := make(map[string]string)
|
||||||
|
for rows.Next() {
|
||||||
|
var key, state string
|
||||||
|
var ts string
|
||||||
|
if err := rows.Scan(&key, &state, &ts); err != nil {
|
||||||
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
resp[lights[key].Name] = state
|
||||||
|
}
|
||||||
|
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
json.NewEncoder(w).Encode(resp)
|
||||||
|
})
|
||||||
|
|
||||||
|
log.Println("HTTP server listening on", port)
|
||||||
|
log.Fatal(http.ListenAndServe(":"+port, nil))
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user