Files
home-automation-backend/src/components/homeassistant/homeassistant.go

55 lines
1.1 KiB
Go
Raw Normal View History

package homeassistant
import (
"encoding/json"
"fmt"
"log/slog"
"net/http"
"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)
}
}
func handlePooRecorderMsg(message haMessage) {
switch message.Action {
case "get_latest":
handleGetLatestPoo()
}
}
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))
}
}