Created
June 11, 2020 07:41
-
-
Save velotiotech/5bb7428bf0e8f298b1ecc9a30d0fc774 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package publisher | |
import ( | |
"config" | |
"encoding/json" | |
"fmt" | |
"log" | |
"math/rand" | |
"os" | |
"time" | |
"github.com/eclipse/paho.mqtt.golang" | |
) | |
type SensorData struct { | |
Id string `json:"id"` | |
Temperature float64 `json:"temperature"` | |
Humidity float64 `json:"humidity"` | |
Timestamp int64 `json:"timestamp"` | |
City string `json:"city"` | |
} | |
func StartMQTTPublisher() { | |
fmt.Println("MQTT publisher Started") | |
mqtt.DEBUG = log.New(os.Stdout, "", 0) | |
mqtt.ERROR = log.New(os.Stdout, "", 0) | |
opts := mqtt.NewClientOptions().AddBroker(config.GetMqttServerurl()).SetClientID("MqttPublisherClient") | |
opts.SetKeepAlive(2 * time.Second) | |
opts.SetPingTimeout(1 * time.Second) | |
c := mqtt.NewClient(opts) | |
if token := c.Connect(); token.Wait() && token.Error() != nil { | |
panic(token.Error()) | |
} | |
go func() { | |
t := 20.04 | |
h := 32.06 | |
for i := 0; i < 100; i++ { | |
sensordata := SensorData{ | |
Id: "CITIMUM", | |
Temperature: t, | |
Humidity: h, | |
Timestamp: time.Now().Unix(), | |
City: "Mumbai", | |
} | |
requestBody, err := json.Marshal(sensordata) | |
if err != nil { | |
fmt.Println(err) | |
} | |
token := c.Publish(config.GetMQTTTopicName(), 0, false, requestBody) | |
token.Wait() | |
if i < 50 { | |
t = t + 1*rand.Float64() | |
h = h + 1*rand.Float64() | |
} else { | |
t = t - 1*rand.Float64() | |
h = h - 1*rand.Float64() | |
} | |
time.Sleep(5 * time.Second) | |
} | |
}() | |
go func() { | |
t := 16.02 | |
h := 24.04 | |
for i := 0; i < 100; i++ { | |
sensordata := SensorData{ | |
Id: "CITIPUN", | |
Temperature: t, | |
Humidity: h, | |
Timestamp: time.Now().Unix(), | |
City: "Pune", | |
} | |
requestBody, err := json.Marshal(sensordata) | |
if err != nil { | |
fmt.Println(err) | |
} | |
token := c.Publish(config.GetMQTTTopicName(), 0, false, requestBody) | |
token.Wait() | |
if i < 50 { | |
t = t + 1*rand.Float64() | |
h = h + 1*rand.Float64() | |
} else { | |
t = t - 1*rand.Float64() | |
h = h - 1*rand.Float64() | |
} | |
time.Sleep(5 * time.Second) | |
} | |
}() | |
time.Sleep(1000 * time.Second) | |
c.Disconnect(250) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment