44 lines
1.2 KiB
Go
44 lines
1.2 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
func postToHomeAssistant(config *Config, entityID string, value int, unit string, friendlyName string) error {
|
|
url := fmt.Sprintf("%s/api/states/%s", config.HomeAssistant.URL, entityID)
|
|
payload := map[string]interface{}{
|
|
"state": fmt.Sprintf("%d", value),
|
|
"attributes": map[string]interface{}{
|
|
"unit_of_measurement": unit,
|
|
"friendly_name": friendlyName,
|
|
"device_class": "measurement",
|
|
},
|
|
}
|
|
jsonData, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return fmt.Errorf("marshal error: %w", err)
|
|
}
|
|
req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
|
|
if err != nil {
|
|
return fmt.Errorf("request error: %w", err)
|
|
}
|
|
req.Header.Set("Authorization", "Bearer "+config.HomeAssistant.Token)
|
|
req.Header.Set("Content-Type", "application/json")
|
|
client := &http.Client{Timeout: 5 * time.Second}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return fmt.Errorf("HTTP error: %w", err)
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != 200 && resp.StatusCode != 201 {
|
|
body, _ := io.ReadAll(resp.Body)
|
|
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body))
|
|
}
|
|
return nil
|
|
}
|