From 98763675ca47047b17ba446c2f8ff15b2f068c9b Mon Sep 17 00:00:00 2001 From: Frank <639906+syphernl@users.noreply.github.com> Date: Sun, 1 Mar 2026 19:30:31 +0100 Subject: [PATCH] Add HomeAssistant notification plugin (#27641) --- messenger/homeassistant.go | 88 +++++++++++++++++ .../definition/messenger/homeassistant.yaml | 74 ++++++++++++++ util/homeassistant/connection.go | 13 ++- util/homeassistant/service.go | 99 +++++++++++++++---- util/homeassistant/types.go | 5 + 5 files changed, 257 insertions(+), 22 deletions(-) create mode 100644 messenger/homeassistant.go create mode 100644 templates/definition/messenger/homeassistant.yaml diff --git a/messenger/homeassistant.go b/messenger/homeassistant.go new file mode 100644 index 000000000..d96b3950c --- /dev/null +++ b/messenger/homeassistant.go @@ -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) + } +} diff --git a/templates/definition/messenger/homeassistant.yaml b/templates/definition/messenger/homeassistant.yaml new file mode 100644 index 000000000..2394a32be --- /dev/null +++ b/templates/definition/messenger/homeassistant.yaml @@ -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 }} diff --git a/util/homeassistant/connection.go b/util/homeassistant/connection.go index a17889c23..58a823317 100644 --- a/util/homeassistant/connection.go +++ b/util/homeassistant/connection.go @@ -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 } diff --git a/util/homeassistant/service.go b/util/homeassistant/service.go index 04bd8a704..13f8853ff 100644 --- a/util/homeassistant/service.go +++ b/util/homeassistant/service.go @@ -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 diff --git a/util/homeassistant/types.go b/util/homeassistant/types.go index 5a16d3c2e..9ec56eafe 100644 --- a/util/homeassistant/types.go +++ b/util/homeassistant/types.go @@ -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"`