Debian Codegraph @

autopaho/examples/basics/basics.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 "strconv"
25 "syscall"
26 "time"
27
28 "github.com/eclipse/paho.golang/autopaho"
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 const topic = "PahoGoTestTopic"
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 cliCfg := autopaho.ClientConfig{
47 ServerUrls: []*url.URL{u},
48 KeepAlive: 20, // Keepalive message should be sent every 20 seconds
49 // CleanStartOnInitialConnection defaults to false. Setting this to true will clear the session on the first connection.
50 CleanStartOnInitialConnection: false,
51 // SessionExpiryInterval - Seconds that a session will survive after disconnection.
52 // It is important to set this because otherwise, any queued messages will be lost if the connection drops and
53 // the server will not queue messages while it is down. The specific setting will depend upon your needs
54 // (60 = 1 minute, 3600 = 1 hour, 86400 = one day, 0xFFFFFFFE = 136 years, 0xFFFFFFFF = don't expire)
55 SessionExpiryInterval: 60,
56 OnConnectionUp: func(cm *autopaho.ConnectionManager, connAck *paho.Connack) {
57 fmt.Println("mqtt connection up")
58 // Subscribing in the OnConnectionUp callback is recommended (ensures the subscription is reestablished if
59 // the connection drops)
60 if _, err := cm.Subscribe(context.Background(), &paho.Subscribe{
61 Subscriptions: []paho.SubscribeOptions{
62 {Topic: topic, QoS: 1},
63 },
64 }); err != nil {
65 fmt.Printf("failed to subscribe (%s). This is likely to mean no messages will be received.", err)
66 }
67 fmt.Println("mqtt subscription made")
68 },
69 OnConnectError: func(err error) { fmt.Printf("error whilst attempting connection: %s\n", err) },
70 // eclipse/paho.golang/paho provides base mqtt functionality, the below config will be passed in for each connection
71 ClientConfig: paho.ClientConfig{
72 // If you are using QOS 1/2, then it's important to specify a client id (which must be unique)
73 ClientID: clientID,
74 // OnPublishReceived is a slice of functions that will be called when a message is received.
75 // You can write the function(s) yourself or use the supplied Router
76 OnPublishReceived: []func(paho.PublishReceived) (bool, error){
77 func(pr paho.PublishReceived) (bool, error) {
78 fmt.Printf("received message on topic %s; body: %s (retain: %t)\n", pr.Packet.Topic, pr.Packet.Payload, pr.Packet.Retain)
79 return true, nil
80 }},
81 OnClientError: func(err error) { fmt.Printf("client error: %s\n", err) },
82 OnServerDisconnect: func(d *paho.Disconnect) {
83 if d.Properties != nil {
84 fmt.Printf("server requested disconnect: %s\n", d.Properties.ReasonString)
85 } else {
86 fmt.Printf("server requested disconnect; reason code: %d\n", d.ReasonCode)
87 }
88 },
89 },
90 }
91
92 c, err := autopaho.NewConnection(ctx, cliCfg) // starts process; will reconnect until context cancelled
93 if err != nil {
94 panic(err)
95 }
96 // Wait for the connection to come up
97 if err = c.AwaitConnection(ctx); err != nil {
98 panic(err)
99 }
100
101 ticker := time.NewTicker(time.Second)
102 msgCount := 0
103 defer ticker.Stop()
104 for {
105 select {
106 case <-ticker.C:
107 msgCount++
108 // Publish a test message (use PublishViaQueue if you don't want to wait for a response)
109 if _, err = c.Publish(ctx, &paho.Publish{
110 QoS: 1,
111 Topic: topic,
112 Payload: []byte("TestMessage: " + strconv.Itoa(msgCount)),
113 }); err != nil {
114 if ctx.Err() == nil {
115 panic(err) // Publish will exit when context cancelled or if something went wrong
116 }
117 }
118 continue
119 case <-ctx.Done():
120 }
121 break
122 }
123
124 fmt.Println("signal caught - exiting")
125 <-c.Done() // Wait for clean shutdown (cancelling the context triggered the shutdown)
126 }