Debian Codegraph @

autopaho/examples/rpc/main.go

raw symbols SCIP
1 /*
2 * Copyright (c) 2024 Contributors to the Eclipse Foundation
3 *
4 * All rights reserved. This program and the accompanying materials
5 * are made available under the terms of the Eclipse Public License v2.0
6 * and Eclipse Distribution License v1.0 which accompany this distribution.
7 *
8 * The Eclipse Public License is available at
9 * https://www.eclipse.org/legal/epl-2.0/
10 * and the Eclipse Distribution License is available at
11 * http://www.eclipse.org/org/documents/edl-v10.php.
12 *
13 * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
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 // rpc - demonstrates the use of autopaho/extensions/rpc
38 // Sets up a listener that responds to messages on a topic (defaults to `rpc/request`). The request body should be a
39 // simple math equation in JSON format (e.g. `{"function":"mul", "param1": 10, "param2": 5}`).
40 //
41 // A second connection to the broker is then established and a few sample equations sent.
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{}) // Closed when subscription made (otherwise we might send request before subscription in place)
57 var initialSubscriptionOnce sync.Once // We only want to close the above once!
58
59 // Subscribing in OnConnectionUp is the recommended approach because this ensures the subscription is reestablished
60 // following reconnection (the subscription should survive `cliCfg.SessionExpiryInterval` after disconnection,
61 // but in this case that is 0, and it's safer if we don't assume the session survived anyway).
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 // Connection must be up, and subscription made, within a reasonable time period.
119 // In a real app you would probably not wait for the subscription, but it's important here because otherwise the
120 // request colud be sent before the subscription is in place.
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) // Start the listener (this will respond to requests)
164
165 cliCfg := genericCfg
166 cliCfg.ClientID = "rpc-requestor"
167
168 initialSubscriptionMade := make(chan struct{}) // Closed when subscription made (otherwise we might send request before subscription in place)
169 var initialSubscriptionOnce sync.Once // We only want to close the above 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 // Wait for the subscription to be made (otherwise we may miss the response!)
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 }