/
custom_store.go
100 lines (79 loc) · 2.12 KB
/
custom_store.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
* Copyright (c) 2013 IBM Corp.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Seth Hoenig
* Allan Stockdill-Mander
* Mike Robertson
*/
// This demonstrates how to implement your own Store interface and provide
// it to the go-mqtt client.
package main
import (
"fmt"
"time"
MQTT "git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git"
)
// This NoOpStore type implements the go-mqtt/Store interface, which
// allows it to be used by the go-mqtt client library. However, it is
// highly recommended that you do not use this NoOpStore in production,
// because it will NOT provide any sort of guaruntee of message delivery.
type NoOpStore struct {
// Contain nothing
}
func (store *NoOpStore) Open() {
// Do nothing
}
func (store *NoOpStore) Put(string, *MQTT.Message) {
// Do nothing
}
func (store *NoOpStore) Get(string) *MQTT.Message {
// Do nothing
return nil
}
func (store *NoOpStore) Del(string) {
// Do nothing
}
func (store *NoOpStore) All() []string {
return nil
}
func (store *NoOpStore) Close() {
// Do Nothing
}
func (store *NoOpStore) Reset() {
// Do Nothing
}
func (store *NoOpStore) SetTracer(tracer *MQTT.Tracer) {
// Do Nothing
}
func main() {
myNoOpStore := &NoOpStore{}
opts := MQTT.NewClientOptions()
opts.SetBroker("tcp://test.mosquitto.org:1883")
opts.SetClientId("custom-store")
opts.SetStore(myNoOpStore)
var callback MQTT.MessageHandler = func(client *MQTT.MqttClient, msg MQTT.Message) {
fmt.Printf("TOPIC: %s\n", msg.Topic())
fmt.Printf("MSG: %s\n", msg.Payload())
}
c := MQTT.NewClient(opts)
_, err := c.Start()
if err != nil {
panic(err)
}
filter, _ := MQTT.NewTopicFilter("/go-mqtt/sample", 0)
c.StartSubscription(callback, filter)
for i := 0; i < 5; i++ {
text := fmt.Sprintf("this is msg #%d!", i)
c.Publish(MQTT.QOS_ONE, "/go-mqtt/sample", []byte(text))
}
for i := 1; i < 5; i++ {
time.Sleep(1 * time.Second)
}
c.Disconnect(250)
}