Debian Codegraph @

autopaho/examples/router/router.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 "context"
20 "fmt"
21 "net/url"
22 "os"
23 "os/signal"
24 "syscall"
25
26 "github.com/eclipse/paho.golang/autopaho"
27 "github.com/eclipse/paho.golang/paho"
28 )
29
30 const clientID = "PahoGoClient" // Change this to something random if using a public test server
31
32 // This example demonstrates the use of a StandardRouter; please note that the router API is likely to change
33 // prior to the release of v1.0.
34
35 func main() {
36 // App will run until cancelled by user (e.g. ctrl-c)
37 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
38 defer stop()
39
40 // We will connect to the Eclipse test server (note that you may see messages that other users publish)
41 u, err := url.Parse("mqtt://mqtt.eclipseprojects.io:1883")
42 if err != nil {
43 panic(err)
44 }
45
46 router := paho.NewStandardRouter()
47 router.DefaultHandler(func(p *paho.Publish) { fmt.Printf("defaulthandler received message with topic: %s\n", p.Topic) })
48
49 cliCfg := autopaho.ClientConfig{
50 ServerUrls: []*url.URL{u},
51 KeepAlive: 20, // Keepalive message should be sent every 20 seconds
52 // We don't want the broker to delete any session info when we disconnect
53 CleanStartOnInitialConnection: true,
54 SessionExpiryInterval: 0,
55 OnConnectError: func(err error) { fmt.Printf("error whilst attempting connection: %s\n", err) },
56 // eclipse/paho.golang/paho provides base mqtt functionality, the below config will be passed in for each connection
57 ClientConfig: paho.ClientConfig{
58 // If you are using QOS 1/2, then it's important to specify a client id (which must be unique)
59 ClientID: clientID,
60 // OnPublishReceived is a slice of functions that will be called when a message is received.
61 // You can write the function(s) yourself or use the supplied Router
62 OnPublishReceived: []func(paho.PublishReceived) (bool, error){
63 func(pr paho.PublishReceived) (bool, error) {
64 router.Route(pr.Packet.Packet())
65 return true, nil // we assume that the router handles all messages (todo: amend router API)
66 }},
67 OnClientError: func(err error) { fmt.Printf("client error: %s\n", err) },
68 OnServerDisconnect: func(d *paho.Disconnect) {
69 if d.Properties != nil {
70 fmt.Printf("server requested disconnect: %s\n", d.Properties.ReasonString)
71 } else {
72 fmt.Printf("server requested disconnect; reason code: %d\n", d.ReasonCode)
73 }
74 },
75 },
76 }
77
78 c, err := autopaho.NewConnection(ctx, cliCfg) // starts process; will reconnect until context cancelled
79 if err != nil {
80 panic(err)
81 }
82
83 if err = c.AwaitConnection(ctx); err != nil {
84 panic(err)
85 }
86
87 // In most cases subscribing in OnConnectionUp is recommended (so subscription will be re-established after
88 // a reconnection. However, for the purposes of this demo subscribing here is simpler.
89 if _, err := c.Subscribe(context.Background(), &paho.Subscribe{
90 Subscriptions: []paho.SubscribeOptions{
91 {Topic: "test/#", QoS: 1}, // For this example, we get all messages under test
92 },
93 }); err != nil {
94 panic(fmt.Sprintf("failed to subscribe (%s). This is likely to mean no messages will be received.", err))
95 }
96
97 // Handlers can be registered/deregistered at any time. It's important to note that you need to subscribe AND create
98 // a handler
99 router.RegisterHandler("test/test/#", func(p *paho.Publish) { fmt.Printf("test/test/# received message with topic: %s\n", p.Topic) })
100 router.RegisterHandler("test/test/foo", func(p *paho.Publish) { fmt.Printf("test/test/foo received message with topic: %s\n", p.Topic) })
101 router.RegisterHandler("test/nomatch", func(p *paho.Publish) { fmt.Printf("test/nomatch received message with topic: %s\n", p.Topic) })
102 router.RegisterHandler("test/quit", func(p *paho.Publish) { stop() }) // Context will be cancelled if we receive a matching message
103
104 // We publish three messages to test out the various route handlers
105 topics := []string{"test/test", "test/test/foo", "test/xxNoMatch", "test/quit"}
106 for _, t := range topics {
107 if _, err := c.Publish(ctx, &paho.Publish{
108 QoS: 1,
109 Topic: t,
110 Payload: []byte("TestMessage on topic: " + t),
111 }); err != nil {
112 if ctx.Err() == nil {
113 panic(err) // Publish will exit when context cancelled or if something went wrong
114 }
115 }
116 }
117
118 <-c.Done() // Wait for clean shutdown (cancelling the context triggered the shutdown)
119 }