| 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 | |
| 27 | const serverURL = "mqtt://127.0.0.1:1883" |
| 28 | const testTopic = "testTopic" // We publish all messages to the same topic because the server should maintain message order |
| 29 | const msgCount = 10000 |
| 30 | const NotifyEvery = 100 |
| 31 | const timeoutSecs = 60 |
| 32 | const QOS = 1 |
| 33 | const useMemoryQueue = false |
| 34 | |
| 35 | var disconnectAtCount = []uint64{5} // IThe connection will be dropped before publishing the message # in this slice |
| 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 | // Use a local server (a simple way to provide this is to use the docker example i.e. `docker compose up mosquitto`) |
| 43 | u, err := url.Parse(serverURL) |
| 44 | if err != nil { |
| 45 | panic(err) |
| 46 | } |
| 47 | |
| 48 | subReady := make(chan struct{}) |
| 49 | subComplete := make(chan struct{}) |
| 50 | go func() { |
| 51 | defer close(subComplete) |
| 52 | subscribe(ctx, u, msgCount, subReady) |
| 53 | stop() // All done so close things down |
| 54 | }() |
| 55 | select { |
| 56 | case <-subReady: // Wait for subscribe to connect/subscribe |
| 57 | case <-ctx.Done(): |
| 58 | fmt.Println("signal caught - exiting") |
| 59 | return |
| 60 | } |
| 61 | |
| 62 | publish(ctx, u, msgCount) |
| 63 | |
| 64 | fmt.Println("messages published") // Note that messages may not have been transmitted to server at this point |
| 65 | |
| 66 | <-ctx.Done() // Wait for user to trigger exit |
| 67 | fmt.Println("signal caught - exiting") |
| 68 | } |