| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
package main |
| 17 |
|
| 18 |
import ( |
| 19 |
"bytes" |
| 20 |
"context" |
| 21 |
"encoding/json" |
| 22 |
"flag" |
| 23 |
"fmt" |
| 24 |
"log" |
| 25 |
"net/url" |
| 26 |
"os" |
| 27 |
"os/signal" |
| 28 |
"sync" |
| 29 |
"syscall" |
| 30 |
"time" |
| 31 |
|
| 32 |
"github.com/eclipse/paho.golang/autopaho" |
| 33 |
"github.com/eclipse/paho.golang/autopaho/extensions/rpc" |
| 34 |
"github.com/eclipse/paho.golang/paho" |
| 35 |
) |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
type Request struct { |
| 44 |
Function string `json:"function"` |
| 45 |
Param1 int `json:"param1"` |
| 46 |
Param2 int `json:"param2"` |
| 47 |
} |
| 48 |
|
| 49 |
type Response struct { |
| 50 |
Value int `json:"value"` |
| 51 |
} |
| 52 |
|
| 53 |
const qos = 0 |
| 54 |
|
| 55 |
func listener(ctx context.Context, cliCfg autopaho.ClientConfig, topic string, qos byte) { |
| 56 |
initialSubscriptionMade := make(chan struct{}) |
| 57 |
var initialSubscriptionOnce sync.Once |
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
cliCfg.OnConnectionUp = func(cm *autopaho.ConnectionManager, connAck *paho.Connack) { |
| 63 |
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5*time.Second)) |
| 64 |
defer cancel() |
| 65 |
if _, err := cm.Subscribe(ctx, &paho.Subscribe{ |
| 66 |
Subscriptions: []paho.SubscribeOptions{ |
| 67 |
{Topic: topic, QoS: qos}, |
| 68 |
}, |
| 69 |
}); err != nil { |
| 70 |
fmt.Printf("listener failed to subscribe (%s). This is likely to mean no messages will be received.", err) |
| 71 |
return |
| 72 |
} |
| 73 |
initialSubscriptionOnce.Do(func() { close(initialSubscriptionMade) }) |
| 74 |
} |
| 75 |
cliCfg.OnPublishReceived = []func(paho.PublishReceived) (bool, error){ |
| 76 |
func(received paho.PublishReceived) (bool, error) { |
| 77 |
if received.Packet.Properties != nil && received.Packet.Properties.CorrelationData != nil && received.Packet.Properties.ResponseTopic != "" { |
| 78 |
log.Printf("Received message with response topic %s and correl id %s\n%s", received.Packet.Properties.ResponseTopic, string(received.Packet.Properties.CorrelationData), string(received.Packet.Payload)) |
| 79 |
|
| 80 |
var r Request |
| 81 |
var resp Response |
| 82 |
|
| 83 |
if err := json.NewDecoder(bytes.NewReader(received.Packet.Payload)).Decode(&r); err != nil { |
| 84 |
log.Printf("Failed to decode Request: %v", err) |
| 85 |
} |
| 86 |
|
| 87 |
switch r.Function { |
| 88 |
case "add": |
| 89 |
resp.Value = r.Param1 + r.Param2 |
| 90 |
case "mul": |
| 91 |
resp.Value = r.Param1 * r.Param2 |
| 92 |
case "div": |
| 93 |
resp.Value = r.Param1 / r.Param2 |
| 94 |
case "sub": |
| 95 |
resp.Value = r.Param1 - r.Param2 |
| 96 |
} |
| 97 |
|
| 98 |
body, _ := json.Marshal(resp) |
| 99 |
_, err := received.Client.Publish(ctx, &paho.Publish{ |
| 100 |
Properties: &paho.PublishProperties{ |
| 101 |
CorrelationData: received.Packet.Properties.CorrelationData, |
| 102 |
}, |
| 103 |
Topic: received.Packet.Properties.ResponseTopic, |
| 104 |
Payload: body, |
| 105 |
}) |
| 106 |
if err != nil { |
| 107 |
log.Fatalf("failed to publish message: %s", err) |
| 108 |
} |
| 109 |
} |
| 110 |
return true, nil |
| 111 |
}} |
| 112 |
|
| 113 |
_, err := autopaho.NewConnection(ctx, cliCfg) |
| 114 |
if err != nil { |
| 115 |
panic(err) |
| 116 |
} |
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
connCtx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| 122 |
defer cancel() |
| 123 |
select { |
| 124 |
case <-connCtx.Done(): |
| 125 |
log.Fatalf("listener failed to connect & subscribe: %s", err) |
| 126 |
case <-initialSubscriptionMade: |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
func main() { |
| 131 |
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) |
| 132 |
defer cancel() |
| 133 |
|
| 134 |
server := flag.String("server", "mqtt://mqtt.eclipseprojects.io:1883", "The full URL of the MQTT server to connect to") |
| 135 |
rTopic := flag.String("rtopic", "rpc/request", "Topic for requests to go to") |
| 136 |
flag.Parse() |
| 137 |
|
| 138 |
serverUrl, err := url.Parse(*server) |
| 139 |
if err != nil { |
| 140 |
panic(err) |
| 141 |
} |
| 142 |
|
| 143 |
genericCfg := autopaho.ClientConfig{ |
| 144 |
ServerUrls: []*url.URL{serverUrl}, |
| 145 |
KeepAlive: 30, |
| 146 |
ReconnectBackoff: autopaho.NewConstantBackoff(2 * time.Second), |
| 147 |
ConnectTimeout: 5 * time.Second, |
| 148 |
OnConnectError: func(err error) { fmt.Printf("error whilst attempting connection: %s\n", err) }, |
| 149 |
ClientConfig: paho.ClientConfig{ |
| 150 |
OnClientError: func(err error) { fmt.Printf("requested disconnect: %s\n", err) }, |
| 151 |
OnServerDisconnect: func(d *paho.Disconnect) { |
| 152 |
if d.Properties != nil { |
| 153 |
fmt.Printf("requested disconnect: %s\n", d.Properties.ReasonString) |
| 154 |
} else { |
| 155 |
fmt.Printf("requested disconnect; reason code: %d\n", d.ReasonCode) |
| 156 |
} |
| 157 |
}, |
| 158 |
}, |
| 159 |
} |
| 160 |
|
| 161 |
lCfg := genericCfg |
| 162 |
lCfg.ClientConfig.ClientID = "rpc-listener" |
| 163 |
listener(ctx, lCfg, *rTopic, qos) |
| 164 |
|
| 165 |
cliCfg := genericCfg |
| 166 |
cliCfg.ClientID = "rpc-requestor" |
| 167 |
|
| 168 |
initialSubscriptionMade := make(chan struct{}) |
| 169 |
var initialSubscriptionOnce sync.Once |
| 170 |
|
| 171 |
cliCfg.OnConnectionUp = func(cm *autopaho.ConnectionManager, connAck *paho.Connack) { |
| 172 |
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(5*time.Second)) |
| 173 |
defer cancel() |
| 174 |
if _, err := cm.Subscribe(ctx, &paho.Subscribe{ |
| 175 |
Subscriptions: []paho.SubscribeOptions{ |
| 176 |
{Topic: fmt.Sprintf("%s/responses", cliCfg.ClientID), QoS: qos}, |
| 177 |
}, |
| 178 |
}); err != nil { |
| 179 |
fmt.Printf("requestor failed to subscribe (%s). This is likely to mean no messages will be received.", err) |
| 180 |
return |
| 181 |
} |
| 182 |
initialSubscriptionOnce.Do(func() { close(initialSubscriptionMade) }) |
| 183 |
} |
| 184 |
|
| 185 |
router := paho.NewStandardRouter() |
| 186 |
cliCfg.OnPublishReceived = []func(paho.PublishReceived) (bool, error){ |
| 187 |
func(p paho.PublishReceived) (bool, error) { |
| 188 |
router.Route(p.Packet.Packet()) |
| 189 |
return false, nil |
| 190 |
}} |
| 191 |
|
| 192 |
cm, err := autopaho.NewConnection(ctx, cliCfg) |
| 193 |
if err != nil { |
| 194 |
panic(err) |
| 195 |
} |
| 196 |
|
| 197 |
|
| 198 |
connCtx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| 199 |
defer cancel() |
| 200 |
select { |
| 201 |
case <-connCtx.Done(): |
| 202 |
log.Fatalf("requestor failed to connect & subscribe: %s", err) |
| 203 |
case <-initialSubscriptionMade: |
| 204 |
} |
| 205 |
|
| 206 |
h, err := rpc.NewHandler(ctx, rpc.HandlerOpts{ |
| 207 |
Conn: cm, |
| 208 |
Router: router, |
| 209 |
ResponseTopicFmt: "%s/responses", |
| 210 |
ClientID: cliCfg.ClientID, |
| 211 |
}) |
| 212 |
|
| 213 |
if err != nil { |
| 214 |
log.Fatal(err) |
| 215 |
} |
| 216 |
|
| 217 |
resp, err := h.Request(ctx, &paho.Publish{ |
| 218 |
Topic: *rTopic, |
| 219 |
Payload: []byte(`{"function":"mul", "param1": 10, "param2": 5}`), |
| 220 |
}) |
| 221 |
if err != nil { |
| 222 |
log.Fatal(err) |
| 223 |
} |
| 224 |
|
| 225 |
log.Printf("Received response: %s", string(resp.Payload)) |
| 226 |
|
| 227 |
resp, err = h.Request(ctx, &paho.Publish{ |
| 228 |
Topic: *rTopic, |
| 229 |
Payload: []byte(`{"function":"mul", "param1": 10, "param2": 5}`), |
| 230 |
}) |
| 231 |
if err != nil { |
| 232 |
log.Fatal(err) |
| 233 |
} |
| 234 |
|
| 235 |
log.Printf("Received response: %s", string(resp.Payload)) |
| 236 |
|
| 237 |
resp, err = h.Request(ctx, &paho.Publish{ |
| 238 |
Topic: *rTopic, |
| 239 |
Payload: []byte(`{"function":"add", "param1": 5, "param2": 7}`), |
| 240 |
}) |
| 241 |
if err != nil { |
| 242 |
log.Fatal(err) |
| 243 |
} |
| 244 |
|
| 245 |
log.Printf("Received response: %s", string(resp.Payload)) |
| 246 |
} |