You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
1.1 KiB
47 lines
1.1 KiB
package mqtt
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
|
|
"github.com/dustinpianalto/errors"
|
|
"github.com/dustinpianalto/weather"
|
|
mqtt "github.com/eclipse/paho.mqtt.golang"
|
|
)
|
|
|
|
var (
|
|
AmbientService weather.AmbientService
|
|
)
|
|
|
|
func CreateMQTTClient(host, username, password string, port int) {
|
|
opts := mqtt.NewClientOptions()
|
|
opts.AddBroker(fmt.Sprintf("tcp://%s:%d", host, port))
|
|
opts.SetClientID("weather_bridge")
|
|
opts.SetUsername(username)
|
|
opts.SetPassword(password)
|
|
opts.OnConnect = connectHandler
|
|
opts.OnConnectionLost = connectionLostHandler
|
|
client := mqtt.NewClient(opts)
|
|
log.Println("mqtt client created")
|
|
token := client.Connect()
|
|
if token.Wait() && token.Error() != nil {
|
|
log.Println(token.Error())
|
|
return
|
|
}
|
|
initServices(&client)
|
|
log.Println("mqtt client initalized")
|
|
}
|
|
|
|
func connectHandler(client mqtt.Client) {
|
|
log.Println("MQTT Connected")
|
|
}
|
|
|
|
func connectionLostHandler(client mqtt.Client, err error) {
|
|
const method string = "mqtt/connectionLostHandler"
|
|
log.Println(errors.E(method, errors.Internal, "MQTT Connection Lost", err))
|
|
}
|
|
|
|
func initServices(client *mqtt.Client) {
|
|
AmbientService = eventService{client: client}
|
|
}
|