Debian Codegraph @

autopaho/examples/docker/subscriber/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 // Connect to the server, subscribe, and write messages received to a file
19
20 import (
21 "context"
22 "fmt"
23 "net/url"
24 "os"
25 "os/signal"
26 "syscall"
27 "time"
28
29 "github.com/eclipse/paho.golang/autopaho"
30 "github.com/eclipse/paho.golang/paho"
31 "github.com/eclipse/paho.golang/paho/session/state"
32 storefile "github.com/eclipse/paho.golang/paho/store/file"
33 )
34
35 func main() {
36 cfg, err := getConfig()
37 if err != nil {
38 panic(err)
39 }
40
41 // Create a handler that will deal with incoming messages
42 h := NewHandler(cfg.writeToDisk, cfg.outputFileName, cfg.writeToStdOut)
43 defer h.Close()
44
45 var sessionState *state.State
46 if len(cfg.sessionFolder) == 0 {
47 sessionState = state.NewInMemory()
48 } else {
49 cliState, err := storefile.New(cfg.sessionFolder, "subdemo_cli_", ".pkt")
50 if err != nil {
51 panic(err)
52 }
53 srvState, err := storefile.New(cfg.sessionFolder, "subdemo_srv_", ".pkt")
54 if err != nil {
55 panic(err)
56 }
57 sessionState = state.New(cliState, srvState)
58 }
59
60 cliCfg := autopaho.ClientConfig{
61 ServerUrls: []*url.URL{cfg.serverURL},
62 KeepAlive: cfg.keepAlive,
63 CleanStartOnInitialConnection: false, // the default
64 SessionExpiryInterval: 60, // Session remains live 60 seconds after disconnect
65 ReconnectBackoff: autopaho.NewConstantBackoff(cfg.connectRetryDelay),
66 OnConnectionUp: func(cm *autopaho.ConnectionManager, connAck *paho.Connack) {
67 fmt.Println("mqtt connection up")
68 if _, err := cm.Subscribe(context.Background(), &paho.Subscribe{
69 Subscriptions: []paho.SubscribeOptions{
70 {Topic: cfg.topic, QoS: cfg.qos},
71 },
72 }); err != nil {
73 fmt.Printf("failed to subscribe (%s). This is likely to mean no messages will be received.", err)
74 return
75 }
76 fmt.Println("mqtt subscription made")
77 },
78 OnConnectError: func(err error) { fmt.Printf("error whilst attempting connection: %s\n", err) },
79 ClientConfig: paho.ClientConfig{
80 ClientID: cfg.clientID,
81 Session: sessionState,
82 OnPublishReceived: []func(paho.PublishReceived) (bool, error){
83 func(pr paho.PublishReceived) (bool, error) {
84 h.handle(pr.Packet)
85 return true, nil
86 }},
87 OnClientError: func(err error) { fmt.Printf("client error: %s\n", err) },
88 OnServerDisconnect: func(d *paho.Disconnect) {
89 if d.Properties != nil {
90 fmt.Printf("server requested disconnect: %s\n", d.Properties.ReasonString)
91 } else {
92 fmt.Printf("server requested disconnect; reason code: %d\n", d.ReasonCode)
93 }
94 },
95 },
96 }
97
98 if cfg.debug {
99 cliCfg.Debug = logger{prefix: "autoPaho"}
100 cliCfg.PahoDebug = logger{prefix: "paho"}
101 }
102
103 //
104 // Connect to the server
105 //
106 ctx, cancel := context.WithCancel(context.Background())
107 defer cancel()
108 cm, err := autopaho.NewConnection(ctx, cliCfg)
109 if err != nil {
110 panic(err)
111 }
112
113 // Messages will be handled through the callback so we really just need to wait until a shutdown
114 // is requested
115 sig := make(chan os.Signal, 1)
116 signal.Notify(sig, os.Interrupt)
117 signal.Notify(sig, syscall.SIGTERM)
118
119 <-sig
120 fmt.Println("signal caught - exiting")
121
122 // We could cancel the context at this point but will call Disconnect instead (this waits for autopaho to shutdown)
123 ctx, cancel = context.WithTimeout(context.Background(), time.Second)
124 defer cancel()
125 _ = cm.Disconnect(ctx)
126
127 fmt.Println("shutdown complete")
128 }
129
130 // logger implements the paho.Logger interface
131 type logger struct {
132 prefix string
133 }
134
135 // Println is the library provided NOOPLogger's
136 // implementation of the required interface function()
137 func (l logger) Println(v ...interface{}) {
138 fmt.Println(append([]interface{}{l.prefix + ":"}, v...)...)
139 }
140
141 // Printf is the library provided NOOPLogger's
142 // implementation of the required interface function(){}
143 func (l logger) Printf(format string, v ...interface{}) {
144 if len(format) > 0 && format[len(format)-1] != '\n' {
145 format = format + "\n" // some log calls in paho do not add \n
146 }
147 fmt.Printf(l.prefix+":"+format, v...)
148 }