Add HomeAssistant notification plugin (#27641)

This commit is contained in:
Frank 2026-03-01 19:30:31 +01:00 • committed by GitHub
parent ce1eb43191
commit 98763675ca
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 257 additions and 22 deletions

View file

@ -0,0 +1,88 @@
package messenger
import (
"errors"
"strings"
"github.com/evcc-io/evcc/api"
"github.com/evcc-io/evcc/util"
"github.com/evcc-io/evcc/util/homeassistant"
"github.com/evcc-io/evcc/util/request"
)
func init() {
registry.Add("homeassistant", NewHAMessengerFromConfig)
}
// HAMessenger implements the Home Assistant messenger
type HAMessenger struct {
log *util.Logger
conn *homeassistant.Connection
notify string
data map[string]any
}
// NewHAMessengerFromConfig creates a new Home Assistant messenger
func NewHAMessengerFromConfig(other map[string]any) (api.Messenger, error) {
var cc struct {
URI string
Notify string
Data map[string]any
}
if err := util.DecodeOther(other, &cc); err != nil {
return nil, err
}
if cc.URI == "" {
return nil, errors.New("missing uri")
}
log := util.NewLogger("homeassistant")
conn, err := homeassistant.NewConnection(log, cc.URI, "")
if err != nil {
return nil, err
}
return &HAMessenger{
log: log,
conn: conn,
notify: cc.Notify,
data: cc.Data,
}, nil
}
// Send sends a notification via Home Assistant
func (m *HAMessenger) Send(title, msg string) {
var err error
if m.notify != "" {
domain, service, _ := strings.Cut(m.notify, ".")
payload := map[string]any{
"title": title,
"message": msg,
}
if len(m.data) > 0 {
payload["data"] = m.data
}
err = m.conn.CallService(domain, service, payload)
// fall back to new-style notify.send_message for integrations
// that no longer support the legacy service call (e.g. Telegram in HA 2024+)
if se, ok := errors.AsType[*request.StatusError](err); ok && se.HasStatus(400) {
err = m.conn.CallService("notify", "send_message", map[string]any{
"entity_id": m.notify,
"title": title,
"message": msg,
})
}
} else {
err = m.conn.CallService("persistent_notification", "create", map[string]any{
"title": title,
"message": msg,
"notification_id": "evcc",
})
}
if err != nil {
m.log.ERROR.Println(err)
}
}

View file

@ -0,0 +1,74 @@
template: homeassistant
products:
- brand: Home Assistant
auth:
type: homeassistant
params: [uri]
params:
- name: uri
required: true
example: http://homeassistant.local:8123
description:
de: Home Assistant URI
en: Home Assistant URI
help:
en: " " # overwrite default
de: " " # overwrite default
service: homeassistant/instances
- name: notify
example: notify.mobile_app_android
description:
de: Benachrichtigungsdienst
en: Notify service
help:
de: >
Home Assistant Benachrichtigungsdienst in der Form `domain.service` (z. B. `notify.mobile_app_android`).
Leer lassen, um eine persistente Benachrichtigung in der HA-Oberfläche zu erstellen.
en: >
Home Assistant notify service in the form `domain.service` (e.g. `notify.mobile_app_android`).
Leave empty to create a persistent notification in the HA UI.
service: homeassistant/services?uri={uri}&domain=notify
- name: critical
type: bool
default: false
description:
de: Kritische Benachrichtigung
en: Critical notification
help:
de: Setzt ttl=0 und priority=high für sofortige Zustellung, auch im Energiesparmodus.
en: Sets ttl=0 and priority=high for immediate delivery even in battery saver mode.
- name: group
example: evcc
description:
de: Benachrichtigungsgruppe
en: Notification group
help:
de: Gruppiert Benachrichtigungen auf dem Gerät. Gleiche Gruppe fasst Meldungen zusammen.
en: Groups notifications on the device. Same group collapses multiple alerts together.
- name: notification_channel
example: alarm_stream
description:
de: Benachrichtigungskanal
en: Notification channel
help:
de: Android-Benachrichtigungskanal (bestimmt Ton und Priorität). Z. B. `alarm_stream` für Alarmton.
en: Android notification channel (controls sound and importance). E.g. `alarm_stream` for alarm sound.
render: |
type: homeassistant
uri: {{ .uri }}
{{- if .notify }}
notify: {{ .notify }}
{{- end }}
{{- if or .critical .group .notification_channel }}
data:
{{- if .critical }}
ttl: 0
priority: high
{{- end }}
{{- if .group }}
group: {{ .group }}
{{- end }}
{{- if .notification_channel }}
channel: {{ .notification_channel }}
{{- end }}
{{- end }}

View file

@ -49,13 +49,24 @@ func NewConnection(log *util.Logger, uri, home string) (*Connection, error) {
return c, nil
}
// URI returns the base URI of the Home Assistant instance
func (c *Connection) URI() string {
return c.instance.URI()
}
// GetStates retrieves the list of entities
func (c *Connection) GetStates() ([]StateResponse, error) {
var res []StateResponse
uri := fmt.Sprintf("%s/api/states", c.instance.URI())
err := c.GetJSON(uri, &res)
return res, err
}
// GetServices retrieves the list of callable services
func (c *Connection) GetServices() ([]ServiceDomainResponse, error) {
var res []ServiceDomainResponse
uri := fmt.Sprintf("%s/api/services", c.instance.URI())
err := c.GetJSON(uri, &res)
return res, err
}

View file

@ -10,7 +10,6 @@ import (
"github.com/evcc-io/evcc/server/service"
"github.com/evcc-io/evcc/util"
"github.com/samber/lo"
)
var log = util.NewLogger("homeassistant")
@ -19,6 +18,7 @@ func init() {
mux := http.NewServeMux()
mux.HandleFunc("GET /instances", getInstances)
mux.HandleFunc("GET /entities", getEntities)
mux.HandleFunc("GET /services", getServices)
service.Register("homeassistant", mux)
}
@ -30,43 +30,100 @@ func getInstances(w http.ResponseWriter, req *http.Request) {
jsonWrite(w, slices.Sorted(maps.Values(instances)))
}
func getEntities(w http.ResponseWriter, req *http.Request) {
func connectionFromRequest(req *http.Request) (*Connection, error) {
uri := util.DefaultScheme(strings.TrimSuffix(req.URL.Query().Get("uri"), "/"), "http")
if uri == "" {
jsonError(w, http.StatusBadRequest, errors.New("missing uri"))
return
return nil, errors.New("missing uri")
}
return NewConnection(log, uri, "")
}
conn, _ := NewConnection(log, uri, "")
res, err := conn.GetStates()
// domainsFromRequest parses the comma-separated "domain" query parameter.
func domainsFromRequest(req *http.Request) []string {
if domain := req.URL.Query().Get("domain"); domain != "" {
return strings.Split(domain, ",")
}
return nil
}
// matchesDomains reports whether entityID belongs to any of the given domains.
// If domains is empty, all entities match.
func matchesDomains(entityID string, domains []string) bool {
if len(domains) == 0 {
return true
}
for _, d := range domains {
if strings.HasPrefix(entityID, d+".") {
return true
}
}
return false
}
func getEntities(w http.ResponseWriter, req *http.Request) {
conn, err := connectionFromRequest(req)
if err != nil {
jsonError(w, http.StatusBadRequest, err)
return
}
var domains []string
if domain := req.URL.Query().Get("domain"); domain != "" {
domains = strings.Split(domain, ",")
states, err := conn.GetStates()
if err != nil {
jsonError(w, http.StatusBadRequest, err)
return
}
// cache list of entities
w.Header().Set("Cache-control", "max-age=300")
domains := domainsFromRequest(req)
jsonWrite(w, lo.Map(lo.Filter(res, func(e StateResponse, _ int) bool {
if len(domains) == 0 {
return true
var result []string
for _, e := range states {
if matchesDomains(e.EntityId, domains) {
result = append(result, e.EntityId)
}
}
for _, domain := range domains {
if strings.HasPrefix(e.EntityId, domain+".") {
return true
w.Header().Set("Cache-control", "max-age=300")
jsonWrite(w, result)
}
func getServices(w http.ResponseWriter, req *http.Request) {
conn, err := connectionFromRequest(req)
if err != nil {
jsonError(w, http.StatusBadRequest, err)
return
}
domains := domainsFromRequest(req)
seen := make(map[string]struct{})
// collect callable services from /api/services (e.g. notify.mobile_app_android)
svcRes, err := conn.GetServices()
if err != nil {
jsonError(w, http.StatusBadRequest, err)
return
}
for _, sd := range svcRes {
if len(domains) == 0 || slices.Contains(domains, sd.Domain) {
for svc := range sd.Services {
seen[sd.Domain+"."+svc] = struct{}{}
}
}
}
return false
}), func(e StateResponse, _ int) string {
return e.EntityId
}))
// collect entity-based notifiers from /api/states (e.g. Telegram in HA 2024+)
if len(domains) > 0 {
if states, err := conn.GetStates(); err == nil {
for _, e := range states {
if matchesDomains(e.EntityId, domains) {
seen[e.EntityId] = struct{}{}
}
}
}
}
w.Header().Set("Cache-control", "max-age=300")
jsonWrite(w, slices.Sorted(maps.Keys(seen)))
}
// jsonWrite writes a JSON response

View file

@ -5,6 +5,11 @@ import (
"strings"
)
type ServiceDomainResponse struct {
Domain string `json:"domain"`
Services map[string]any `json:"services"`
}
type StateResponse struct {
EntityId string `json:"entity_id"`
State string `json:"state"`