-
Notifications
You must be signed in to change notification settings - Fork 1
Get data from Home Assistant
Roman edited this page Oct 2, 2024
·
2 revisions
If you want to get some data from Home Assistant, you can easily fetch them via the Home Assistant API:
Here is some go code that does this:
var haToken = "<yourHomeAssistantToken>"
var haUrl = "<yourHomeAssistantUrl>" // eg. https://my-homeassistant.com
type HomeAssistantStateEntity struct {
EntityId string `json:"entity_id"`
State string `json:"state"`
Attributes map[string]interface{} `json:"attributes"`
LastChanged time.Time `json:"last_changed"`
LastUpdated time.Time `json:"last_updated"`
Context struct {
Id string `json:"id"`
ParentId string `json:"parent_id"`
UserId string `json:"user_id"`
} `json:"context"`
}
func getHomeAssistantValue(entityId string) (string, error) {
url := fmt.Sprintf("%s/api/states/%s", haUrl, entityId)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, url, nil)
if err != nil {
return "", err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", haToken))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
var data HomeAssistantStateEntity
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return "", err
}
return data.State, nil
}