mirror of
https://github.com/kaspanet/kaspad.git
synced 2025-06-07 14:46:44 +00:00

* [NOD-381] Publish transaction messages to MQTT * [NOD-381] Remove redundant variable * [NOD-381] Send payload as string * [NOD-381] Add Error handling * [NOD-381] Respond with TransactionResponse * [NOD-381] Use transactionResponse for notifications * [NOD-381] Move code to appropriate places * [NOD-381] Pass raw block instead of txId * [NOD-381] Add comments to public functions * [NOD-381] Remove print statement * [NOD-381] Pass transaction instead of block; Use pointers so default will be nil; * [NOD-381] Use pointers so value could be nil * [NOD-381] Change variable name * [NOD-381] Set QoS to 2 * [NOD-381] Move isConnected to MQTT, so client won't have to worry about it; General code refactors;
55 lines
1.2 KiB
Go
55 lines
1.2 KiB
Go
package mqtt
|
|
|
|
import (
|
|
"errors"
|
|
"github.com/daglabs/btcd/apiserver/config"
|
|
mqtt "github.com/eclipse/paho.mqtt.golang"
|
|
)
|
|
|
|
// client is an instance of the MQTT client, in case we have an active connection
|
|
var client mqtt.Client
|
|
|
|
// GetClient returns an instance of the MQTT client, in case we have an active connection
|
|
func GetClient() (mqtt.Client, error) {
|
|
if client == nil {
|
|
return nil, errors.New("MQTT is not connected")
|
|
}
|
|
return client, nil
|
|
}
|
|
|
|
func isConnected() bool {
|
|
return client != nil
|
|
}
|
|
|
|
// Connect initiates a connection to the MQTT server, if defined
|
|
func Connect() error {
|
|
cfg := config.ActiveConfig()
|
|
if cfg.MQTTBrokerAddress == "" {
|
|
// MQTT broker not defined -- nothing to do
|
|
return nil
|
|
}
|
|
|
|
options := mqtt.NewClientOptions()
|
|
options.AddBroker(cfg.MQTTBrokerAddress)
|
|
options.SetUsername(cfg.MQTTUser)
|
|
options.SetPassword(cfg.MQTTPassword)
|
|
options.SetAutoReconnect(true)
|
|
|
|
newClient := mqtt.NewClient(options)
|
|
if token := newClient.Connect(); token.Wait() && token.Error() != nil {
|
|
return token.Error()
|
|
}
|
|
client = newClient
|
|
|
|
return nil
|
|
}
|
|
|
|
// Close closes the connection to the MQTT server, if previously connected
|
|
func Close() {
|
|
if client == nil {
|
|
return
|
|
}
|
|
client.Disconnect(250)
|
|
client = nil
|
|
}
|