saunaservice/main.go

117 lines
2.4 KiB
Go
Raw Permalink Normal View History

package main
import (
"encoding/json"
"log"
"time"
2023-02-21 08:20:44 +00:00
// "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"
2023-02-21 08:20:44 +00:00
// "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)
2023-02-21 08:20:44 +00:00
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"
2023-02-21 08:20:44 +00:00
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()
}
2023-02-21 08:20:44 +00:00
next_update = time.Now().Add(update_interval)
}
last_value = measure.Value
2023-02-21 08:20:44 +00:00
// 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)
}
}