diff --git a/util/homeassistant/oauth2.go b/util/homeassistant/oauth2.go index 1f9570284..52e196290 100644 --- a/util/homeassistant/oauth2.go +++ b/util/homeassistant/oauth2.go @@ -5,6 +5,7 @@ import ( "fmt" "net" "net/url" + "strings" "github.com/evcc-io/evcc/plugin/auth" "github.com/evcc-io/evcc/server/network" @@ -42,6 +43,8 @@ func NewHomeAssistantFromConfig(other map[string]any) (oauth2.TokenSource, error } func NewHomeAssistant(uri string) (oauth2.TokenSource, error) { + uri = strings.TrimRight(uri, "/") // normalize + extUrl := network.Config().ExternalURL() redirectUri := extUrl + network.CallbackPath @@ -68,5 +71,10 @@ func NewHomeAssistant(uri string) (oauth2.TokenSource, error) { host = h } + // use instance name instead of host if discovered on mDNS + if name := instanceNameByUri(uri); name != "" { + host = name + } + return auth.NewOAuth(ctx, "HomeAssistant", host, &oc) } diff --git a/util/homeassistant/zeroconf.go b/util/homeassistant/zeroconf.go index 8fd16d38c..b8a012ab3 100644 --- a/util/homeassistant/zeroconf.go +++ b/util/homeassistant/zeroconf.go @@ -25,10 +25,23 @@ func instanceUriByName(name string) string { return instances[name] } +func instanceNameByUri(uri string) string { + mu.Lock() + defer mu.Unlock() + + for n, u := range instances { + if uri == u { + return n + } + } + + return "" +} + func addInstance(name, uri string) { mu.Lock() defer mu.Unlock() - instances[name] = uri + instances[name] = strings.TrimRight(uri, "/") } func scan() {