427bc44a3e
Signed-off-by: tkl <tkl@barsch.fritz.box>
117 lines
2.4 KiB
Go
117 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"time"
|
|
|
|
// "periph.io/x/conn/v3/gpio"
|
|
"periph.io/x/conn/v3/onewire"
|
|
"periph.io/x/conn/v3/physic"
|
|
"periph.io/x/devices/v3/ds18b20"
|
|
"periph.io/x/host/v3"
|
|
"periph.io/x/host/v3/netlink"
|
|
|
|
// "periph.io/x/host/v3/rpi"
|
|
|
|
mqtt "github.com/eclipse/paho.mqtt.golang"
|
|
)
|
|
|
|
type sample struct {
|
|
Value float64 `json:"value"`
|
|
Unit string `json:"unit"`
|
|
}
|
|
|
|
var (
|
|
logger log.Logger = *log.Default()
|
|
)
|
|
|
|
func init() {
|
|
logger.SetPrefix("Temperature: ")
|
|
}
|
|
|
|
var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
|
|
logger.Printf("Received message: %s from topic: %s\n", msg.Payload(), msg.Topic())
|
|
}
|
|
|
|
var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
|
|
logger.Println("Connected")
|
|
}
|
|
|
|
var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
|
|
logger.Printf("Connect lost: %v", err)
|
|
}
|
|
|
|
func main() {
|
|
logger.Println("Starting")
|
|
|
|
// MQTT connection
|
|
opts := mqtt.NewClientOptions()
|
|
opts.AddBroker("tcp://p5:1883")
|
|
opts.SetClientID("saunaservice")
|
|
opts.SetDefaultPublishHandler(messagePubHandler)
|
|
opts.OnConnect = connectHandler
|
|
opts.OnConnectionLost = connectLostHandler
|
|
client := mqtt.NewClient(opts)
|
|
if token := client.Connect(); token.Wait() && token.Error() != nil {
|
|
panic(token.Error())
|
|
}
|
|
|
|
var addr onewire.Address = 0x8f01193726f5fd28
|
|
if _, err := host.Init(); err != nil {
|
|
logger.Fatal(err)
|
|
}
|
|
|
|
// get 1wire bus
|
|
bus, err := netlink.New(1)
|
|
if err != nil {
|
|
logger.Fatal(err)
|
|
}
|
|
defer bus.Close()
|
|
|
|
// res, err := bus.Search(false)
|
|
// log.Print(res)
|
|
|
|
sensor, err := ds18b20.New(bus, addr, 9)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
var res physic.Env
|
|
var measure = sample{
|
|
Value: 0.0,
|
|
Unit: "°C",
|
|
}
|
|
var last_value = float64(0.0)
|
|
update_interval := time.Minute
|
|
next_update := time.Now().Add(update_interval)
|
|
for {
|
|
sensor.Sense(&res)
|
|
log.Print(res.Temperature.String())
|
|
|
|
measure.Value = float64(res.Temperature.Celsius())
|
|
|
|
topic := "sauna/temperature"
|
|
if measure.Value != last_value || next_update.Before(time.Now()) {
|
|
res, err := json.Marshal(measure)
|
|
if err != nil {
|
|
logger.Print(err)
|
|
} else {
|
|
token := client.Publish(topic, 0, false, res)
|
|
token.Wait()
|
|
}
|
|
next_update = time.Now().Add(update_interval)
|
|
}
|
|
last_value = measure.Value
|
|
|
|
// if measure.Value > 72.0 {
|
|
// rpi.P1_40.Out(gpio.Low)
|
|
// } else if measure.Value < 68.0 {
|
|
// rpi.P1_40.Out(gpio.High)
|
|
// }
|
|
|
|
time.Sleep(time.Second)
|
|
}
|
|
|
|
}
|