[cli] Add utility functions to init mqtt client
This commit is contained in:
parent
ad0f5e0d0f
commit
8d6df473d5
47
cli/cli.go
47
cli/cli.go
@ -1,6 +1,9 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
MQTT "github.com/eclipse/paho.mqtt.golang"
|
||||
"log"
|
||||
"os"
|
||||
"os/signal"
|
||||
@ -46,3 +49,47 @@ func HandleExit(p Part) {
|
||||
os.Exit(0)
|
||||
}()
|
||||
}
|
||||
|
||||
func InitMqttFlags(defaultClientId string, mqttBroker, username, password, clientId *string, mqttQos *int, mqttRetain *bool) {
|
||||
SetDefaultValueFromEnv(clientId, "MQTT_CLIENT_ID", defaultClientId)
|
||||
SetDefaultValueFromEnv(mqttBroker, "MQTT_BROKER", "tcp://127.0.0.1:1883")
|
||||
|
||||
flag.StringVar(mqttBroker, "mqtt-broker", *mqttBroker, "Broker Uri, use MQTT_BROKER env if arg not set")
|
||||
flag.StringVar(username, "mqtt-username", os.Getenv("MQTT_USERNAME"), "Broker Username, use MQTT_USERNAME env if arg not set")
|
||||
flag.StringVar(password, "mqtt-password", os.Getenv("MQTT_PASSWORD"), "Broker Password, MQTT_PASSWORD env if args not set")
|
||||
flag.StringVar(clientId, "mqtt-client-id", *clientId, "Mqtt client id, use MQTT_CLIENT_ID env if args not set")
|
||||
flag.IntVar(mqttQos, "mqtt-qos", *mqttQos, "Qos to pusblish message, use MQTT_QOS env if arg not set")
|
||||
flag.BoolVar(mqttRetain, "mqtt-retain", *mqttRetain, "Retain mqtt message, if not set, true if MQTT_RETAIN env variable is set")
|
||||
}
|
||||
|
||||
func InitIntFlag(key string, defValue int) int {
|
||||
var value int
|
||||
err := SetIntDefaultValueFromEnv(&value, key, defValue)
|
||||
if err != nil {
|
||||
log.Panicf("invalid int value: %v", err)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func Connect(uri, username, password, clientId string) (MQTT.Client, error) {
|
||||
//create a ClientOptions struct setting the broker address, clientid, turn
|
||||
//off trace output and set the default message handler
|
||||
opts := MQTT.NewClientOptions().AddBroker(uri)
|
||||
opts.SetUsername(username)
|
||||
opts.SetPassword(password)
|
||||
opts.SetClientID(clientId)
|
||||
opts.SetAutoReconnect(true)
|
||||
opts.SetDefaultPublishHandler(
|
||||
//define a function for the default message handler
|
||||
func(client MQTT.Client, msg MQTT.Message) {
|
||||
fmt.Printf("TOPIC: %s\n", msg.Topic())
|
||||
fmt.Printf("MSG: %s\n", msg.Payload())
|
||||
})
|
||||
|
||||
//create and start a client using the above ClientOptions
|
||||
client := MQTT.NewClient(opts)
|
||||
if token := client.Connect(); token.Wait() && token.Error() != nil {
|
||||
return nil, fmt.Errorf("unable to connect to mqtt bus: %v", token.Error())
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user