Debian Codegraph @

autopaho/examples/docker/publisher/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 "context"
20 "encoding/json"
21 "fmt"
22 "net/url"
23 "os"
24 "os/signal"
25 "sync"
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/log"
32 "github.com/eclipse/paho.golang/paho/session/state"
33 storefile "github.com/eclipse/paho.golang/paho/store/file"
34 )
35
36 // Connect to the server and publish a message periodically
37 func main() {
38 cfg, err := getConfig()
39 if err != nil {
40 panic(err)
41 }
42
43 var sessionState *state.State
44 if len(cfg.sessionFolder) == 0 {
45 sessionState = state.NewInMemory()
46 } else {
47 cliState, err := storefile.New(cfg.sessionFolder, "pubdemo_cli_", ".pkt")
48 if err != nil {
49 panic(err)
50 }
51 srvState, err := storefile.New(cfg.sessionFolder, "pubdemo_srv_", ".pkt")
52 if err != nil {
53 panic(err)
54 }
55 sessionState = state.New(cliState, srvState)
56 }
57
58 cliCfg := autopaho.ClientConfig{
59 ServerUrls: []*url.URL{cfg.serverURL},
60 KeepAlive: cfg.keepAlive,
61 CleanStartOnInitialConnection: false, // the default
62 SessionExpiryInterval: 60, // Session remains live 60 seconds after disconnect
63 ReconnectBackoff: autopaho.NewConstantBackoff(cfg.connectRetryDelay),
64 OnConnectionUp: func(*autopaho.ConnectionManager, *paho.Connack) { fmt.Println("mqtt connection up") },
65 OnConnectError: func(err error) { fmt.Printf("error whilst attempting connection: %s\n", err) },
66 Debug: log.NOOPLogger{},
67 ClientConfig: paho.ClientConfig{
68 ClientID: cfg.clientID,
69 Session: sessionState,
70 OnClientError: func(err error) { fmt.Printf("client error: %s\n", err) },
71 OnServerDisconnect: func(d *paho.Disconnect) {
72 if d.Properties != nil {
73 fmt.Printf("server requested disconnect: %s\n", d.Properties.ReasonString)
74 } else {
75 fmt.Printf("server requested disconnect; reason code: %d\n", d.ReasonCode)
76 }
77 },
78 },
79 }
80
81 if cfg.debug {
82 cliCfg.Debug = logger{prefix: "autoPaho"}
83 cliCfg.PahoDebug = logger{prefix: "paho"}
84 }
85
86 ctx, cancel := context.WithCancel(context.Background())
87 defer cancel()
88
89 // Connect to the server - this will return immediately after initiating the connection process
90 cm, err := autopaho.NewConnection(ctx, cliCfg)
91 if err != nil {
92 panic(err)
93 }
94
95 var wg sync.WaitGroup
96
97 // Start off a goRoutine that publishes messages
98 wg.Add(1)
99 go func() {
100 defer wg.Done()
101 var count uint64
102 for {
103 // AwaitConnection will return immediately if connection is up; adding this call stops publication whilst
104 // connection is unavailable.
105 err = cm.AwaitConnection(ctx)
106 if err != nil { // Should only happen when context is cancelled
107 fmt.Printf("publisher done (AwaitConnection: %s)\n", err)
108 return
109 }
110
111 count += 1
112 // The message could be anything; lets make it JSON containing a simple count (makes it simpler to track the messages)
113 msg, err := json.Marshal(struct {
114 Count uint64
115 }{Count: count})
116 if err != nil {
117 panic(err)
118 }
119
120 // Publish will block, so we run it in a goRoutine
121 // Note that we could use PublishViaQueue if we wanted to trust that the library will deliver (and, ideally,
122 // use a file-based queue and state).
123 go func(msg []byte) {
124 pr, err := cm.Publish(ctx, &paho.Publish{
125 QoS: cfg.qos,
126 Topic: cfg.topic,
127 Payload: msg,
128 })
129 if err != nil {
130 fmt.Printf("error publishing message %s: %s\n", msg, err)
131 } else if pr.ReasonCode != 0 && pr.ReasonCode != 16 { // 16 = Server received message but there are no subscribers
132 fmt.Printf("reason code %d received for message %s\n", pr.ReasonCode, msg)
133 } else if cfg.printMessages {
134 fmt.Printf("sent message: %s\n", msg)
135 }
136 }(msg)
137
138 select {
139 case <-time.After(cfg.delayBetweenMessages):
140 case <-ctx.Done():
141 fmt.Println("publisher done")
142 return
143 }
144 }
145 }()
146
147 // Wait for a signal before exiting
148 sig := make(chan os.Signal, 1)
149 signal.Notify(sig, os.Interrupt)
150 signal.Notify(sig, syscall.SIGTERM)
151
152 <-sig
153 fmt.Println("signal caught - exiting")
154 cancel()
155
156 wg.Wait()
157 fmt.Println("shutdown complete")
158 }
159
160 // logger implements the paho.Logger interface
161 type logger struct {
162 prefix string
163 }
164
165 // Println is the library provided NOOPLogger's
166 // implementation of the required interface function()
167 func (l logger) Println(v ...interface{}) {
168 fmt.Println(append([]interface{}{l.prefix + ":"}, v...)...)
169 }
170
171 // Printf is the library provided NOOPLogger's
172 // implementation of the required interface function(){}
173 func (l logger) Printf(format string, v ...interface{}) {
174 if len(format) > 0 && format[len(format)-1] != '\n' {
175 format = format + "\n" // some log calls in paho do not add \n
176 }
177 fmt.Printf(l.prefix+":"+format, v...)
178 }