diff --git a/README.md b/README.md index bc221b80a..bfb08cd8d 100644 --- a/README.md +++ b/README.md @@ -538,6 +538,7 @@ Note: to modify writable settings perform a `POST` request appending the value a The MQTT API follows the REST API's structure, with loadpoint ids starting at `0`: - `evcc`: root topic +- `evcc/status`: status (`online`/`offline`) - `evcc/updated`: timestamp of last update - `evcc/site`: site dynamic state - `evcc/site/prioritySoC`: battery priority SoC (writable) diff --git a/cmd/config.go b/cmd/config.go index de8c9cd64..360fc597e 100644 --- a/cmd/config.go +++ b/cmd/config.go @@ -39,6 +39,13 @@ type mqttConfig struct { Topic string } +func (conf *mqttConfig) RootTopic() string { + if conf.Topic != "" { + return conf.Topic + } + return "evcc" +} + type qualifiedConfig struct { Name, Type string Other map[string]interface{} `mapstructure:",remain"` diff --git a/cmd/root.go b/cmd/root.go index f4b1bf787..aebe3b621 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -178,7 +178,7 @@ func run(cmd *cobra.Command, args []string) { // setup mqtt publisher if conf.Mqtt.Broker != "" { - publisher := server.NewMQTT(conf.Mqtt.Topic) + publisher := server.NewMQTT(conf.Mqtt.RootTopic()) go publisher.Run(site, pipe.NewDropper(ignoreMqtt...).Pipe(tee.Attach())) } diff --git a/cmd/setup.go b/cmd/setup.go index deacc9109..71e3a8811 100644 --- a/cmd/setup.go +++ b/cmd/setup.go @@ -19,6 +19,7 @@ import ( "github.com/andig/evcc/util/cloud" "github.com/andig/evcc/util/pipe" "github.com/andig/evcc/util/sponsor" + paho "github.com/eclipse/paho.mqtt.golang" "github.com/spf13/viper" ) @@ -117,7 +118,10 @@ func configureMQTT(conf mqttConfig) error { } var err error - mqtt.Instance, err = mqtt.RegisteredClient(log, conf.Broker, conf.User, conf.Password, clientID, 1) + mqtt.Instance, err = mqtt.RegisteredClient(log, conf.Broker, conf.User, conf.Password, clientID, 1, func(options *paho.ClientOptions) { + topic := fmt.Sprintf("%s/status", conf.RootTopic()) + options.SetWill(topic, "offline", 1, true) + }) if err != nil { return fmt.Errorf("failed configuring mqtt: %w", err) } diff --git a/provider/mqtt/client.go b/provider/mqtt/client.go index 63f884f74..c6bd84ac0 100644 --- a/provider/mqtt/client.go +++ b/provider/mqtt/client.go @@ -8,7 +8,7 @@ import ( "github.com/andig/evcc/api" "github.com/andig/evcc/util" - mqtt "github.com/eclipse/paho.mqtt.golang" + paho "github.com/eclipse/paho.mqtt.golang" ) const ( @@ -37,14 +37,16 @@ type Config struct { type Client struct { log *util.Logger mux sync.Mutex - Client mqtt.Client + Client paho.Client broker string Qos byte listener map[string][]func(string) } +type Option func(*paho.ClientOptions) + // NewClient creates new Mqtt publisher -func NewClient(log *util.Logger, broker, user, password, clientID string, qos byte) (*Client, error) { +func NewClient(log *util.Logger, broker, user, password, clientID string, qos byte, opts ...Option) (*Client, error) { broker = util.DefaultPort(broker, 1883) log.INFO.Printf("connecting %s at %s", clientID, broker) @@ -55,7 +57,7 @@ func NewClient(log *util.Logger, broker, user, password, clientID string, qos by listener: make(map[string][]func(string)), } - options := mqtt.NewClientOptions() + options := paho.NewClientOptions() options.AddBroker(broker) options.SetUsername(user) options.SetPassword(password) @@ -66,7 +68,12 @@ func NewClient(log *util.Logger, broker, user, password, clientID string, qos by options.SetConnectionLostHandler(mc.ConnectionLostHandler) options.SetConnectTimeout(connectTimeout) - client := mqtt.NewClient(options) + // additional options + for _, o := range opts { + o(options) + } + + client := paho.NewClient(options) if token := client.Connect(); token.Wait() && token.Error() != nil { return nil, fmt.Errorf("error connecting: %w", token.Error()) } @@ -77,12 +84,12 @@ func NewClient(log *util.Logger, broker, user, password, clientID string, qos by } // ConnectionLostHandler logs cause of connection loss as warning -func (m *Client) ConnectionLostHandler(client mqtt.Client, reason error) { +func (m *Client) ConnectionLostHandler(client paho.Client, reason error) { m.log.ERROR.Printf("%s connection lost: %v", m.broker, reason.Error()) } // ConnectionHandler restores listeners -func (m *Client) ConnectionHandler(client mqtt.Client) { +func (m *Client) ConnectionHandler(client paho.Client) { m.log.DEBUG.Printf("%s connected", m.broker) m.mux.Lock() @@ -115,7 +122,7 @@ func (m *Client) Listen(topic string, callback func(string)) { // listen attaches listener to topic func (m *Client) listen(topic string) { - token := m.Client.Subscribe(topic, m.Qos, func(c mqtt.Client, msg mqtt.Message) { + token := m.Client.Subscribe(topic, m.Qos, func(c paho.Client, msg paho.Message) { payload := string(msg.Payload()) m.log.TRACE.Printf("recv %s: '%v'", topic, payload) if len(payload) > 0 { @@ -132,7 +139,7 @@ func (m *Client) listen(topic string) { } // WaitForToken synchronously waits until token operation completed -func (m *Client) WaitForToken(token mqtt.Token) { +func (m *Client) WaitForToken(token paho.Token) { if token.WaitTimeout(publishTimeout) { if token.Error() != nil { m.log.ERROR.Printf("error: %s", token.Error()) diff --git a/provider/mqtt/registry.go b/provider/mqtt/registry.go index 727d873cb..5a80fd1ab 100644 --- a/provider/mqtt/registry.go +++ b/provider/mqtt/registry.go @@ -28,12 +28,12 @@ func (r clientRegistry) Get(broker string) (*Client, error) { var registry clientRegistry = make(map[string]*Client) // RegisteredClient reuses an registered Mqtt publisher or creates a new one -func RegisteredClient(log *util.Logger, broker, user, password, clientID string, qos byte) (*Client, error) { +func RegisteredClient(log *util.Logger, broker, user, password, clientID string, qos byte, opts ...Option) (*Client, error) { key := fmt.Sprintf("%s.%s", broker, log.Name()) client, err := registry.Get(key) if err != nil { - if client, err = NewClient(log, broker, user, password, clientID, qos); err == nil { + if client, err = NewClient(log, broker, user, password, clientID, qos, opts...); err == nil { registry.Add(key, client) } } diff --git a/server/mqtt.go b/server/mqtt.go index ea3ff7184..16d3d7178 100644 --- a/server/mqtt.go +++ b/server/mqtt.go @@ -19,10 +19,6 @@ type MQTT struct { // NewMQTT creates MQTT server func NewMQTT(root string) *MQTT { - if root == "" { - root = "evcc" - } - return &MQTT{ Handler: mqtt.Instance, root: root, @@ -88,6 +84,10 @@ func (m *MQTT) listenSetters(topic string, apiHandler core.LoadPointAPI) { // Run starts the MQTT publisher for the MQTT API func (m *MQTT) Run(site core.SiteAPI, in <-chan util.Param) { + // alive + topic := fmt.Sprintf("%s/status", m.root) + m.publish(topic, true, "online") + // site setters m.Handler.Listen(fmt.Sprintf("%s/site/prioritySoC/set", m.root), func(payload string) { soc, err := strconv.Atoi(payload) @@ -97,7 +97,7 @@ func (m *MQTT) Run(site core.SiteAPI, in <-chan util.Param) { }) // number of loadpoints - topic := fmt.Sprintf("%s/loadpoints", m.root) + topic = fmt.Sprintf("%s/loadpoints", m.root) m.publish(topic, true, len(site.LoadPoints())) // loadpoint setters