Skip to content

Instantly share code, notes, and snippets.

@Abathargh
Created April 29, 2020 18:31
Show Gist options
  • Save Abathargh/999ee1c5b521496adeb92c41b18400ee to your computer and use it in GitHub Desktop.
Save Abathargh/999ee1c5b521496adeb92c41b18400ee to your computer and use it in GitHub Desktop.
Esempio di Client MQTT implementato in go tramite paho.mqtt.golang
package main
import (
"fmt"
"github.com/eclipse/paho.mqtt.golang"
"log"
"os"
"os/signal"
"syscall"
)
const (
brokAddr = "localhost"
port = 1883
hostId = "Main"
topic = "test"
)
func receiveCallback(client mqtt.Client, message mqtt.Message) {
fmt.Printf("Topic: %v\tPayload: %s\n", message.Topic(), message.Payload())
}
func main() {
quit := make(chan os.Signal)
signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
opts := mqtt.NewClientOptions().AddBroker(fmt.Sprintf("tcp://%v:%v", brokAddr, port))
opts.SetClientID(hostId)
client := mqtt.NewClient(opts)
connectionToken := client.Connect()
if connectionToken.Wait() && connectionToken.Error() != nil {
log.Fatal(connectionToken.Error())
}
subscriptionToken := client.Subscribe(topic, 0, receiveCallback)
if subscriptionToken.Wait() && subscriptionToken.Error() != nil {
log.Fatal(subscriptionToken.Error())
}
<-quit
client.Disconnect(200)
fmt.Println("Bye!")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment