Created
August 17, 2016 16:18
-
-
Save chazcheadle/673e1c259c11bccb40031f556de36c45 to your computer and use it in GitHub Desktop.
Golang/MQTT JSON server timestamp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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