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