44 lines
940 B
Go
44 lines
940 B
Go
package main
|
|
|
|
import (
|
|
MQTT "github.com/eclipse/paho.mqtt.golang"
|
|
"math/rand"
|
|
"encoding/json"
|
|
"time"
|
|
)
|
|
|
|
type sensordata struct {
|
|
Temperature float32
|
|
Humidity float32
|
|
Battery float32
|
|
Light float32
|
|
}
|
|
|
|
func main() {
|
|
opts := MQTT.NewClientOptions().AddBroker("tcp://localhost:1883")
|
|
opts.SetClientID("go-sipmle-publish")
|
|
|
|
c := MQTT.NewClient(opts)
|
|
if token := c.Connect(); token.Wait() && token.Error() != nil {
|
|
panic(token.Error())
|
|
}
|
|
|
|
rand.Seed(time.Now().UTC().UnixNano())
|
|
|
|
for i := 0; i < 1000; i ++ {
|
|
d := sensordata{randfun(0, 20), randfun(10, 30), randfun(0, 100), randfun(0, 255)}
|
|
text, _ := json.Marshal(d)
|
|
token := c.Publish("abqGF3nbCeYIYzOckDrU1vOq6uuU16rb/test/counter2/", 2, false, text)
|
|
if token.Wait() && token.Error() != nil {
|
|
panic(token.Error())
|
|
}
|
|
time.Sleep(5 * time.Second)
|
|
}
|
|
}
|
|
|
|
|
|
func randfun(min int, max int) float32 {
|
|
t := rand.Float32() * float32(max-min)
|
|
|
|
return float32(min) + t
|
|
}
|