1
0
Fork 0

Get full HA state

main v0.3.0
Jordan Hotmann 2023-10-16 10:54:09 -06:00
parent 877e1b1b28
commit e86eee3984
No known key found for this signature in database
GPG Key ID: 01B504170C2A2EA3
3 changed files with 29 additions and 7 deletions

View File

@ -71,11 +71,14 @@ func logRequest(w http.ResponseWriter, r *http.Request) {
func getEntityStateHandler(w http.ResponseWriter, r *http.Request) {
logRequest(w, r)
entityId := chi.URLParam(r, "entityId")
full := r.URL.Query().Get("full") == "true"
kvVal, err := nats.GetKeyValue(fmt.Sprintf("%s.%s", HA_STATE_PREFIX, entityId))
if err == nil && len(kvVal) > 0 {
w.Write(kvVal)
return
if !full {
kvVal, err := nats.GetKeyValue(fmt.Sprintf("%s.%s", HA_STATE_PREFIX, entityId))
if err == nil && len(kvVal) > 0 {
w.Write(kvVal)
return
}
}
data, err := haClient.GetState(entityId)
@ -85,7 +88,11 @@ func getEntityStateHandler(w http.ResponseWriter, r *http.Request) {
}
nats.SetKeyValueString(fmt.Sprintf("%s.%s", HA_STATE_PREFIX, entityId), data.State)
render.PlainText(w, r, data.State)
if full {
render.JSON(w, r, data)
} else {
render.PlainText(w, r, data.State)
}
}
func setEntityStateHandler(w http.ResponseWriter, r *http.Request) {

View File

@ -120,6 +120,7 @@ func WatchTimers() {
timer, err := GetTimer(timerName)
if err != nil {
logger.Error("Error retrieving timer", "timer", timerName, "error", err)
timer.Cancel()
continue
}

View File

@ -4,7 +4,7 @@ import (
"fmt"
"code.jhot.me/jhot/hats/internal/api"
"code.jhot.me/jhot/hats/pkg/homeassistant"
ha "code.jhot.me/jhot/hats/pkg/homeassistant"
"github.com/go-resty/resty/v2"
)
@ -19,6 +19,20 @@ func NewHatsClient(baseUrl string) *HatsClient {
}
}
func (c *HatsClient) GetStateFull(entityId string) (ha.StateData, error) {
var data ha.StateData
resp, err := c.client.R().SetResult(&data).SetQueryParam("full", "true").Get(fmt.Sprintf("api/state/%s", entityId))
if err == nil && !resp.IsSuccess() {
err = fmt.Errorf("%d status code received: %s", resp.StatusCode(), resp.String())
}
if err != nil {
return data, err
}
return data, nil
}
func (c *HatsClient) GetState(entityId string) (string, error) {
resp, err := c.client.R().Get(fmt.Sprintf("api/state/%s", entityId))
if err == nil && !resp.IsSuccess() {
@ -39,7 +53,7 @@ func (c *HatsClient) GetStateBool(entityId string) (bool, error) {
return false, err
}
return homeassistant.StateToBool(stateString), nil
return ha.StateToBool(stateString), nil
}
func (c *HatsClient) CallService(entityId string, service string, extras ...map[string]string) error {