Created
August 18, 2016 03:31
-
-
Save chazcheadle/748a4856dc2b8900f961ee0427191ec6 to your computer and use it in GitHub Desktop.
Golang: Send image over MQTT
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" | |
| "io/ioutil" | |
| "os" | |
| log "github.com/Sirupsen/logrus" | |
| MQTT "github.com/eclipse/paho.mqtt.golang" | |
| ) | |
| var ( | |
| mqttBroker = "tcp://HOST:1883" | |
| mqttClientId = "Send_image_mqtt" | |
| mqttTopic = "test/topic" | |
| imageFile = "test.png" | |
| ) | |
| func main() { | |
| opts := MQTT.NewClientOptions() | |
| opts.AddBroker(mqttBroker) | |
| opts.SetClientID(mqttClientId) | |
| c := MQTT.NewClient(opts) | |
| if token := c.Connect(); token.Wait() && token.Error() != nil { | |
| log.Warn("Error connecting to broker: ", mqttBroker) | |
| panic(token.Error()) | |
| } | |
| fileHandle, err := os.Open(imageFile) | |
| if err != nil { | |
| log.Fatal("Error opening file.") | |
| } | |
| defer func () { | |
| if err := fileHandle.Close(); err != nil { | |
| panic(err) | |
| } | |
| }() | |
| contents, err := ioutil.ReadAll(fileHandle) | |
| if err != nil { | |
| log.Fatal("Error reading file.") | |
| } | |
| fmt.Println(len(contents)) | |
| token := c.Publish(mqttTopic, 0, false, string(contents)) | |
| token.Wait() | |
| log.Info(token.Error()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment