initial commit

Signed-off-by: Vincent Batts <vbatts@hashbangbash.com>
This commit is contained in:
Vincent Batts 2021-05-03 12:38:04 -04:00
commit 8fd3f36252
No known key found for this signature in database
GPG key ID: 524F155275DF0C3E
8 changed files with 871 additions and 0 deletions

117
cmd/pub.go Normal file
View file

@ -0,0 +1,117 @@
/*
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")
}

91
cmd/root.go Normal file
View file

@ -0,0 +1,91 @@
/*
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 (
"fmt"
"github.com/spf13/cobra"
"os"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
)
var cfgFile string
// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "dang",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. 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.`,
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func init() {
cobra.OnInitialize(initConfig)
// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.dang.yaml)")
// Cobra also supports local flags, which will only run
// when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// Search config in home directory with name ".dang" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".dang")
}
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}

106
cmd/sub.go Normal file
View file

@ -0,0 +1,106 @@
/*
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 (
"fmt"
"os"
"strings"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
"github.com/spf13/cobra"
)
var flag bool = false
// subCmd represents the sub command
var subCmd = &cobra.Command{
Use: "sub",
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("sub called")
opts := mqtt.NewClientOptions().AddBroker("tcp://infra1.batts.lan:1883")
// set the id to the client.
opts.SetClientID("dang-sub")
opts.SetDefaultPublishHandler(f)
// create a new client.
c := mqtt.NewClient(opts)
if token := c.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
//c.Subscribe("some_topic", 0, nil)
if token := c.Subscribe("some_topic", 0, nil); token.Wait() && token.Error() != nil {
fmt.Println(token.Error())
os.Exit(1)
}
for flag == false {
time.Sleep(1 * time.Second)
//fmt.Println("waiting: ", wcount)
//wcount += 1
}
//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(subCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// subCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// subCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
//define a function for the default message handler
var f mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
topic := msg.Topic()
payload := msg.Payload()
if strings.Compare(string(payload), "\n") > 0 {
fmt.Printf("TOPIC: %s\n", topic)
fmt.Printf("MSG: %s\n", payload)
}
if strings.Compare("bye\n", string(payload)) == 0 {
fmt.Println("exitting")
flag = true
}
}