81 lines
1.8 KiB
Go
81 lines
1.8 KiB
Go
|
package homeassistant
|
||
|
|
||
|
import (
|
||
|
"bytes"
|
||
|
"context"
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"io"
|
||
|
"net/http"
|
||
|
"time"
|
||
|
|
||
|
"git.faercol.me/faercol/http-boot-server/bootserver/config"
|
||
|
"git.faercol.me/faercol/http-boot-server/bootserver/logger"
|
||
|
)
|
||
|
|
||
|
type Entity struct {
|
||
|
State string `json:"state"`
|
||
|
ID string `json:"-"`
|
||
|
Attributes map[string]string `json:"attributes,omitempty"`
|
||
|
}
|
||
|
|
||
|
func newBootOptionEntity(device, option string) Entity {
|
||
|
return Entity{
|
||
|
State: option,
|
||
|
ID: "httpboot." + device,
|
||
|
Attributes: nil,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
type HomeAssistantExporter struct {
|
||
|
clt *http.Client
|
||
|
baseURL string
|
||
|
token string
|
||
|
}
|
||
|
|
||
|
func New(conf *config.AppConfig) *HomeAssistantExporter {
|
||
|
clt := http.Client{}
|
||
|
return &HomeAssistantExporter{
|
||
|
clt: &clt,
|
||
|
baseURL: conf.HomeAssistantHost,
|
||
|
token: conf.HomeAssistantToken,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (e *HomeAssistantExporter) SendBootOption(ctx context.Context, device string, option string) error {
|
||
|
subCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
||
|
defer cancel()
|
||
|
|
||
|
entity := newBootOptionEntity(device, option)
|
||
|
|
||
|
dat, err := json.Marshal(entity)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
req, err := http.NewRequestWithContext(subCtx, http.MethodPost, e.baseURL+"/api/states/"+entity.ID, bytes.NewBuffer(dat))
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
req.Header.Add("Authorization", "Bearer "+e.token)
|
||
|
|
||
|
resp, err := e.clt.Do(req)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
switch resp.StatusCode {
|
||
|
case http.StatusOK:
|
||
|
logger.L.Debugf("Updated boot info for device %s to %s", device, option)
|
||
|
case http.StatusCreated:
|
||
|
logger.L.Debugf("Created boot info for device %s with value %s", device, option)
|
||
|
default:
|
||
|
respBod, err := io.ReadAll(resp.Body)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return fmt.Errorf("unexpected returncode %d (%s)", resp.StatusCode, string(respBod))
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|