Skip to content

Instantly share code, notes, and snippets.

@chazcheadle
Created August 17, 2016 16:18
Show Gist options
  • Select an option

  • Save chazcheadle/673e1c259c11bccb40031f556de36c45 to your computer and use it in GitHub Desktop.

Select an option

Save chazcheadle/673e1c259c11bccb40031f556de36c45 to your computer and use it in GitHub Desktop.
Golang/MQTT JSON server timestamp
package main
import (
"fmt"
"encoding/json"
"os"
"time"
MQTT "github.com/eclipse/paho.mqtt.golang"
)
type serverInfo struct {
Timestamp string `json:"timestamp"`
}
func main() {
opts := MQTT.NewClientOptions().AddBroker("tcp://BROKER_ADDRESS:PORT")
opts.SetClientID("CLIENT_ID")
c := MQTT.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
ticker := time.NewTicker(time.Millisecond * 1000)
go func() {
for timestamp := range ticker.C {
message := serverInfo{Timestamp:timestamp.Format("2006-01-02T15:04:05")}
messageJSON, err := json.Marshal(message)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
token := c.Publish("TOPIC", 0, false, messageJSON)
token.Wait()
}
}()
select {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment