2024-09-18 02:09:25 +02:00
|
|
|
package home_assistant
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"github.com/carlmjohnson/requests"
|
|
|
|
"net/http"
|
2024-12-16 19:40:10 +01:00
|
|
|
"time"
|
2024-09-18 02:09:25 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
type Config struct {
|
|
|
|
Token string
|
|
|
|
BaseURL string
|
|
|
|
}
|
|
|
|
|
|
|
|
type Client struct {
|
|
|
|
config Config
|
|
|
|
client *http.Client
|
|
|
|
}
|
|
|
|
|
|
|
|
func New(client *http.Client, config Config) *Client {
|
|
|
|
return &Client{config: config, client: client}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) GetState(ctx context.Context, entityID string) (string, error) {
|
2024-12-16 19:40:10 +01:00
|
|
|
var resp struct {
|
2024-09-18 02:09:25 +02:00
|
|
|
State string `json:"state"`
|
|
|
|
}
|
|
|
|
|
2024-12-16 19:40:10 +01:00
|
|
|
err := c.getState(ctx, entityID, &resp)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
return resp.State, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) GetTimeState(ctx context.Context, entityID string) (time.Time, error) {
|
|
|
|
var resp struct {
|
|
|
|
State time.Time `json:"state"`
|
|
|
|
}
|
2024-09-18 02:09:25 +02:00
|
|
|
|
2024-12-16 19:40:10 +01:00
|
|
|
err := c.getState(ctx, entityID, &resp)
|
|
|
|
if err != nil {
|
|
|
|
return time.Time{}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return resp.State, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Client) getState(ctx context.Context, entityID string, resp any) error {
|
2024-09-18 02:09:25 +02:00
|
|
|
err := requests.URL(c.config.BaseURL).
|
|
|
|
Header("Authorization", "Bearer "+c.config.Token).
|
|
|
|
Pathf("/api/states/%s", entityID).
|
|
|
|
ToJSON(&resp).
|
|
|
|
Fetch(ctx)
|
|
|
|
if err != nil {
|
2024-12-16 19:40:10 +01:00
|
|
|
return err
|
2024-09-18 02:09:25 +02:00
|
|
|
}
|
|
|
|
|
2024-12-16 19:40:10 +01:00
|
|
|
return nil
|
2024-09-18 02:09:25 +02:00
|
|
|
}
|