Skip to content

Commit

Permalink
sending booleans
Browse files Browse the repository at this point in the history
  • Loading branch information
leroxyl committed Oct 22, 2019
1 parent 1c652bc commit ffa2d75
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
22 changes: 15 additions & 7 deletions c8y/c8y_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"errors"
"fmt"
"log"
"strconv"
"strings"
"time"
)
Expand Down Expand Up @@ -91,13 +90,13 @@ func GetClient(uuid string, tenant string, user string, password string) (MQTT.C
c8yError := make(chan error)
c8yReady := make(chan bool)

// receive-callback
var receive MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
// callback for error messages
receive := func(client MQTT.Client, msg MQTT.Message) {
answer := string(msg.Payload())
log.Println("received error message:" + answer)
}

// configure OnConnect callback: subscribe
// configure OnConnect callback: subscribe to error messages when connected
opts.OnConnect = func(c MQTT.Client) {
log.Println("MQTT client connected.")

Expand All @@ -109,11 +108,13 @@ func GetClient(uuid string, tenant string, user string, password string) (MQTT.C
}
}

// create client and connect
client := MQTT.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
return nil, token.Error()
}

// wait for OnConnect callback
select {
case _ = <-c8yReady:
return client, nil
Expand All @@ -122,9 +123,16 @@ func GetClient(uuid string, tenant string, user string, password string) (MQTT.C
}
}

func Send(c MQTT.Client, valueToSend int) error {
message := "200,c8y_Value,V," + strconv.Itoa(valueToSend)
log.Println("publishing...")
func Send(c MQTT.Client, valueToSend bool) error {
var message string
if valueToSend {
// send true (1)
message = "200,c8y_Bool,B,1"
} else {
// send false (0)
message = "200,c8y_Bool,B,0"
}

if token := c.Publish("s/us", 0, false, message); token.Wait() && token.Error() != nil {
return token.Error()
}
Expand Down
15 changes: 10 additions & 5 deletions main/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"github.com/ubirch/ubirch-go-c8y-client/c8y"
"log"
"time"
)

const ConfigFile = "config.json"
Expand Down Expand Up @@ -34,11 +35,15 @@ func main() {
if err != nil {
log.Fatalf("error: %v", err)
}
defer client.Disconnect(0)

err = c8y.Send(client, 1)
if err != nil {
log.Fatalf("error: %v", err)
value := true
for {
err = c8y.Send(client, value)
if err != nil {
log.Fatalf("error: %v", err)
}
value = !value
time.Sleep(2 * time.Second)
}

defer client.Disconnect(0)
}

0 comments on commit ffa2d75

Please sign in to comment.