86 lines
1.4 KiB
Go
86 lines
1.4 KiB
Go
package ha
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
|
|
"gitnet.fr/deblan/ha-rgb-screen/internal/color"
|
|
"gitnet.fr/deblan/ha-rgb-screen/internal/config"
|
|
)
|
|
|
|
type Client struct {
|
|
params *config.Config
|
|
client *http.Client
|
|
}
|
|
|
|
func NewClient(params *config.Config) *Client {
|
|
return &Client{
|
|
params: params,
|
|
client: new(http.Client),
|
|
}
|
|
}
|
|
|
|
func (c *Client) IsAmbianceEnabled() (bool, error) {
|
|
req, err := http.NewRequest(
|
|
"GET",
|
|
c.params.Url+"/api/states/"+c.params.StateId,
|
|
nil,
|
|
)
|
|
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", "Bearer "+c.params.Token)
|
|
|
|
resp, err := c.client.Do(req)
|
|
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
body, err := io.ReadAll(resp.Body)
|
|
|
|
type value struct {
|
|
State string `json:"state"`
|
|
}
|
|
|
|
v := new(value)
|
|
err = json.Unmarshal(body, v)
|
|
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
|
|
return v.State == "on", err
|
|
}
|
|
|
|
func (c *Client) UpdateLight(rgb color.RGB) error {
|
|
data := fmt.Sprintf(`{"rgb": [%.0f, %.0f, %.0f]}`, rgb.R, rgb.G, rgb.B)
|
|
|
|
if c.params.Verbose {
|
|
log.Printf("[debug] Request Body=%s", data)
|
|
}
|
|
|
|
req, err := http.NewRequest(
|
|
"POST",
|
|
c.params.Url+"/api/webhook/"+c.params.WebhookName,
|
|
bytes.NewBuffer([]byte(data)),
|
|
)
|
|
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
|
|
|
_, err = c.client.Do(req)
|
|
|
|
return err
|
|
}
|