This repository has been archived on 2025-02-01. You can view files and clone it, but cannot push or open issues or pull requests.
esp8266-temperature/weather-generator-mqtt/csvdata-pub.go

59 lines
1.1 KiB
Go

package main
import (
MQTT "github.com/eclipse/paho.mqtt.golang"
"encoding/csv"
"encoding/json"
"fmt"
"os"
"time"
"strconv"
)
type sensordata struct {
Temperature float32
Humidity float32
Battery float32
Light float32
}
func main() {
file, err := os.Open("06720099999.csv")
if err != nil {
panic(err.Error())
}
defer file.Close()
reader := csv.NewReader(file)
rows, err := reader.ReadAll()
if err != nil {
panic(err.Error())
}
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())
}
for n, col := range rows {
if n == 0 {
continue
}
ts := col[13] // temp*10,qualitycheck
tempStr := ts[0:5]
tempInt, _ := strconv.Atoi(tempStr)
temp := float32(tempInt) / 10
fmt.Printf("Got temperature %f\n", temp)
d := sensordata{temp, 0, 0, 0}
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)
}
}