2024-09-17 16:28:12 +02:00
|
|
|
package homeassistant
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"encoding/json"
|
|
|
|
|
"fmt"
|
|
|
|
|
"log/slog"
|
|
|
|
|
"net/http"
|
2024-09-18 16:41:26 +02:00
|
|
|
"strings"
|
2024-09-17 16:28:12 +02:00
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
"github.com/spf13/viper"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type haMessage struct {
|
|
|
|
|
Target string `json:"target"`
|
|
|
|
|
Action string `json:"action"`
|
|
|
|
|
Content string `json:"content"`
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func HandleHaMessage(w http.ResponseWriter, r *http.Request) {
|
|
|
|
|
var message haMessage
|
|
|
|
|
decoder := json.NewDecoder(r.Body)
|
|
|
|
|
decoder.DisallowUnknownFields()
|
|
|
|
|
err := decoder.Decode(&message)
|
|
|
|
|
if err != nil {
|
|
|
|
|
slog.Warn(fmt.Sprintln("HandleHaMessage Error decoding request body", err))
|
|
|
|
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
switch message.Target {
|
|
|
|
|
case "poo_recorder":
|
|
|
|
|
handlePooRecorderMsg(message)
|
2024-09-18 16:41:26 +02:00
|
|
|
case "location_recorder":
|
|
|
|
|
handleLocationRecorderMsg(message)
|
2024-09-17 16:28:12 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func handlePooRecorderMsg(message haMessage) {
|
|
|
|
|
switch message.Action {
|
|
|
|
|
case "get_latest":
|
|
|
|
|
handleGetLatestPoo()
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-18 16:41:26 +02:00
|
|
|
func handleLocationRecorderMsg(message haMessage) {
|
|
|
|
|
if message.Action == "record" {
|
|
|
|
|
port := viper.GetString("port")
|
|
|
|
|
req, err := http.NewRequest("POST", "http://localhost:"+port+"/location/record", strings.NewReader(strings.ReplaceAll(message.Content, "'", "\"")))
|
|
|
|
|
if err != nil {
|
|
|
|
|
slog.Warn(fmt.Sprintln("handleLocationRecorderMsg Error creating request to location recorder", err))
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
|
client := &http.Client{
|
|
|
|
|
Timeout: time.Second * 1,
|
|
|
|
|
}
|
|
|
|
|
_, err = client.Do(req)
|
|
|
|
|
if err != nil {
|
|
|
|
|
slog.Warn(fmt.Sprintln("handleLocationRecorderMsg Error sending request to location recorder", err))
|
|
|
|
|
}
|
|
|
|
|
} else {
|
|
|
|
|
slog.Warn(fmt.Sprintln("handleLocationRecorderMsg Unknown action", message.Action))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-17 16:28:12 +02:00
|
|
|
func handleGetLatestPoo() {
|
|
|
|
|
client := &http.Client{
|
|
|
|
|
Timeout: time.Second * 1,
|
|
|
|
|
}
|
|
|
|
|
port := viper.GetString("port")
|
|
|
|
|
_, err := client.Get("http://localhost:" + port + "/poo/latest")
|
|
|
|
|
if err != nil {
|
|
|
|
|
slog.Warn(fmt.Sprintln("handleGetLatestPoo Error sending request to poo recorder", err))
|
|
|
|
|
}
|
|
|
|
|
}
|