Skip to content

Commit

Permalink
json format added
Browse files Browse the repository at this point in the history
  • Loading branch information
klumw committed Nov 20, 2022
1 parent 12ea6fc commit 67cbded
Showing 1 changed file with 42 additions and 10 deletions.
52 changes: 42 additions & 10 deletions gqmqtt.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package main

import (
"encoding/binary"
"encoding/json"
"errors"
"flag"
"fmt"
Expand Down Expand Up @@ -45,6 +46,7 @@ func main() {
interval := flag.Uint("i", 60, "update interval for mqtt topic in seconds")
user := flag.String("u", "", "mqtt user")
pwd := flag.String("p", "", "mqtt password")
jfmt := flag.Bool("j", false, "output data in json format")

flag.Parse()

Expand All @@ -56,6 +58,10 @@ func main() {
exitWithMsg("invalid Geiger Counter model")
}

if *verbose {
fmt.Printf("host:%s\nsleep time:%ds\n", *host, *interval)
}

ports, err := serial.GetPortsList()
if err != nil {
exitWithError(err)
Expand Down Expand Up @@ -122,28 +128,34 @@ func main() {
break
}
cpm, _ := bytesToCpmValue(&buff)
cpmi := int(cpm)
if *verbose {
fmt.Printf("%d,", cpm)
}
sendCPM(client, cpm, topic)
var data string
if !*jfmt {
data = fmt.Sprint(cpmi)
} else {
data, err = toJson(interval, &cpmi)
if err != nil {
log.Fatal(err)
}
}
publish(&client, &data, topic)
time.Sleep(time.Duration(*interval) * time.Second)
}
}

func createMqttClient(host *string, user *string, pwd *string) MQTT.Client {

opts := MQTT.NewClientOptions().AddBroker(*host)

if *pwd != "" {
opts.SetPassword(*pwd)
}
if *user != "" {
opts.SetUsername(*user)
}
opts.SetClientID("Geiger Counter")

c := MQTT.NewClient(opts)

if token := c.Connect(); token.Wait() && token.Error() != nil {
exitWithError(token.Error())
}
Expand All @@ -163,11 +175,13 @@ func bytesToCpmValue(buff *[]byte) (uint32, error) {
}
}

func sendCPM(client MQTT.Client, value uint32, topic *string) {
if !client.IsConnected() {
log.Fatal("mqtt not connected!")
} else {
token := client.Publish(*topic, byte(0), false, strconv.FormatUint(uint64(value), 10))
func publish(client *MQTT.Client, value *string, topic *string) {
if !(*client).IsConnected() {
token := (*client).Connect()
token.Wait()
}
{
token := (*client).Publish(*topic, byte(0), false, *value)
token.Wait()
}
}
Expand All @@ -190,3 +204,21 @@ func isElementInArray[T comparable](element T, elements *[]T) bool {
}
return false
}

func toJson(interval *uint, cpm *int) (string, error) {
var res string
now := time.Now()
time := now.Format(time.RFC3339)
sleep := fmt.Sprint(*interval)
cpmStr := fmt.Sprint(*cpm)
c := struct {
Time string `json:"Time"`
Cpm string `json:"Cpm"`
Sleep string `json:"Sleep"`
}{Time: time, Cpm: cpmStr, Sleep: sleep}
b, err := json.MarshalIndent(&c, "", "\t")
if err == nil {
res = string(b[:])
}
return res, err
}

0 comments on commit 67cbded

Please sign in to comment.