-
Notifications
You must be signed in to change notification settings - Fork 10
/
gochat-mqtt.go
58 lines (48 loc) · 1.52 KB
/
gochat-mqtt.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
package main
import (
"bufio"
"flag"
"fmt"
MQTT "git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git"
"io"
"math/rand"
"os"
"strconv"
"strings"
"time"
)
func messageReceived(client *MQTT.Client, msg MQTT.Message) {
topics := strings.Split(msg.Topic(), "/")
msgFrom := topics[len(topics)-1]
fmt.Print(msgFrom + ": " + string(msg.Payload()))
}
func main() {
stdin := bufio.NewReader(os.Stdin)
rand.Seed(time.Now().Unix())
server := flag.String("server", "tcp://iot.eclipse.org:1883", "The MQTT server to connect to")
room := flag.String("room", "gochat", "The chat room to enter. default 'gochat'")
name := flag.String("name", "user"+strconv.Itoa(rand.Intn(1000)), "Username to be displayed")
flag.Parse()
subTopic := strings.Join([]string{"/gochat/", *room, "/+"}, "")
pubTopic := strings.Join([]string{"/gochat/", *room, "/", *name}, "")
opts := MQTT.NewClientOptions().AddBroker(*server).SetClientID(*name).SetCleanSession(true)
opts.OnConnect = func(c *MQTT.Client) {
if token := c.Subscribe(subTopic, 1, messageReceived); token.Wait() && token.Error() != nil {
panic(token.Error())
}
}
client := MQTT.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
fmt.Printf("Connected as %s to %s\n", *name, *server)
for {
message, err := stdin.ReadString('\n')
if err == io.EOF {
os.Exit(0)
}
if token := client.Publish(pubTopic, 1, false, message); token.Wait() && token.Error() != nil {
fmt.Println("Failed to send message")
}
}
}