-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoapp_client.go
84 lines (68 loc) · 2.42 KB
/
goapp_client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"fmt"
"log"
"net/http"
"os"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
func main() {
type initialSetup struct {
host string
clientID string
username string
password string
topic string
}
connectionDetails := initialSetup{host: "tcp://localhost:1883", clientID: "myDesktopClient", username: "3", password: "880b5c97-6a55-4dae-8f98-5b0cd74aac5a", topic: "channels/1/messages"}
client := connectToMQTTServer(connectionDetails.host, connectionDetails.clientID, connectionDetails.username, connectionDetails.password)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "UP")
})
http.HandleFunc("/send_message", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Sending Message")
publishToTopic(client, connectionDetails.topic, "hello from go")
})
http.HandleFunc("/command/on", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Sending Message")
publishToTopic(client, connectionDetails.topic, "1")
})
http.HandleFunc("/command/off", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Sending Message")
publishToTopic(client, connectionDetails.topic, "0")
})
subscribeToTopic(client, connectionDetails.topic)
log.Fatal(http.ListenAndServe(":8081", nil))
}
/******** Connect to MQTT Server on Mainflux *********/
func connectToMQTTServer(host string, clientID string, username string, password string) mqtt.Client {
opts := mqtt.NewClientOptions().AddBroker(host).SetClientID(clientID)
opts.SetUsername(username)
opts.SetPassword(password)
c := mqtt.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
return c
}
/**** Subscribe/Unsubscribe to Topic and Message handler ****/
var messageHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
fmt.Println("GO -----> :", string(msg.Payload()))
}
func subscribeToTopic(c mqtt.Client, topic string) {
if token := c.Subscribe(topic, 1, messageHandler); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
}
func unsubscribeFromTopic(c mqtt.Client, topic string) {
if token := c.Unsubscribe(topic); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
}
/******** Publish to Topic *********/
func publishToTopic(c mqtt.Client, topic string, message string) {
token := c.Publish("channels/1/messages", 1, false, message)
token.Wait()
}