Debian Codegraph @

paho/cmd/stdinpub/main.go

raw
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 "bufio"
20 "context"
21 "flag"
22 "fmt"
23 "io"
24 "log"
25 "net"
26 "os"
27 "os/signal"
28 "syscall"
29
30 "github.com/eclipse/paho.golang/paho"
31 )
32
33 func main() {
34 stdin := bufio.NewReader(os.Stdin)
35 hostname, _ := os.Hostname()
36
37 server := flag.String("server", "127.0.0.1:1883", "The full URL of the MQTT server to connect to")
38 topic := flag.String("topic", hostname, "Topic to publish the messages on")
39 qos := flag.Int("qos", 0, "The QoS to send the messages at")
40 retained := flag.Bool("retained", false, "Are the messages sent with the retained flag")
41 clientid := flag.String("clientid", "", "A clientid for the connection")
42 username := flag.String("username", "", "A username to authenticate to the MQTT server")
43 password := flag.String("password", "", "Password to match username")
44 flag.Parse()
45
46 conn, err := net.Dial("tcp", *server)
47 if err != nil {
48 log.Fatalf("Failed to connect to %s: %s", *server, err)
49 }
50
51 c := paho.NewClient(paho.ClientConfig{
52 Conn: conn,
53 })
54
55 cp := &paho.Connect{
56 KeepAlive: 30,
57 ClientID: *clientid,
58 CleanStart: true,
59 Username: *username,
60 Password: []byte(*password),
61 }
62
63 if *username != "" {
64 cp.UsernameFlag = true
65 }
66 if *password != "" {
67 cp.PasswordFlag = true
68 }
69
70 log.Println(cp.UsernameFlag, cp.PasswordFlag)
71
72 ca, err := c.Connect(context.Background(), cp)
73 if err != nil {
74 log.Fatalln(err)
75 }
76 if ca.ReasonCode != 0 {
77 log.Fatalf("Failed to connect to %s : %d - %s", *server, ca.ReasonCode, ca.Properties.ReasonString)
78 }
79
80 fmt.Printf("Connected to %s\n", *server)
81
82 ic := make(chan os.Signal, 1)
83 signal.Notify(ic, os.Interrupt, syscall.SIGTERM)
84 go func() {
85 <-ic
86 fmt.Println("signal received, exiting")
87 if c != nil {
88 d := &paho.Disconnect{ReasonCode: 0}
89 c.Disconnect(d)
90 }
91 os.Exit(0)
92 }()
93
94 for {
95 message, err := stdin.ReadString('\n')
96 if err == io.EOF {
97 os.Exit(0)
98 }
99
100 if _, err = c.Publish(context.Background(), &paho.Publish{
101 Topic: *topic,
102 QoS: byte(*qos),
103 Retain: *retained,
104 Payload: []byte(message),
105 }); err != nil {
106 log.Println("error sending message:", err)
107 continue
108 }
109 log.Println("sent")
110 }
111 }