go-mqtt-example/cmd/pub.go
Vincent Batts 8fd3f36252
initial commit
Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
2021-05-03 12:38:04 -04:00

117 lines
3.3 KiB
Go

/*
Copyright © 2021 Vincent Batts <vbatts@kinvolk.io>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"bufio"
"fmt"
"os"
"strings"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/spf13/cobra"
)
// pubCmd represents the pub command
var pubCmd = &cobra.Command{
Use: "pub",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("pub called")
opts := mqtt.NewClientOptions().AddBroker("tcp://infra1.batts.lan:1883")
// set the id to the client.
opts.SetClientID("dang-pub")
// create a new client.
c := mqtt.NewClient(opts)
//message := "hello this is the trial message"
//c.Publish("some_topic", 0, false, message)
//we are going to try connecting for max 10 times to the server if the connection fails.
for i := 0; i < 10; i++ {
if token := c.Connect(); token.Wait() && token.Error() == nil {
break
} else {
fmt.Println(token.Error())
time.Sleep(1 * time.Second)
}
}
//subscribe to the topic /go-mqtt/sample and request messages to be delivered
//at a maximum qos of zero, wait for the receipt to confirm the subscription
//same thing needs to go here as well.
if token := c.Subscribe("some_topic", 0, nil); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
// this is the shell where we will take input from the user and publish the message on the topic until user enters `bye`.
for {
var message string
fmt.Print(">> ")
// create a new bffer reader.
reader := bufio.NewReader(os.Stdin)
// read a string.
message, err := reader.ReadString('\n')
if err != nil {
fmt.Println(err)
}
if strings.Compare(message, "\n") > 0 {
// if there is a message, publish it.
token := c.Publish("some_topic", 0, false, message)
if strings.Compare(message, "bye\n") == 0 {
// if message == "bye" then exit the shell.
break
}
token.Wait()
}
}
//unsubscribe from /go-mqtt/sample
if token := c.Unsubscribe("some_topic"); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
c.Disconnect(250)
},
}
func init() {
rootCmd.AddCommand(pubCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// pubCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// pubCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}