105 lines
2.1 KiB
Go
105 lines
2.1 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"log"
|
||
|
"time"
|
||
|
|
||
|
"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"
|
||
|
|
||
|
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://nuc: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)
|
||
|
for {
|
||
|
sensor.Sense(&res)
|
||
|
log.Print(res.Temperature.String())
|
||
|
|
||
|
measure.Value = float64(res.Temperature.Celsius())
|
||
|
|
||
|
topic := "sauna/temperature"
|
||
|
if measure.Value != last_value {
|
||
|
res, err := json.Marshal(measure)
|
||
|
if err != nil {
|
||
|
logger.Print(err)
|
||
|
} else {
|
||
|
token := client.Publish(topic, 0, false, res)
|
||
|
token.Wait()
|
||
|
}
|
||
|
}
|
||
|
|
||
|
last_value = measure.Value
|
||
|
time.Sleep(time.Second)
|
||
|
}
|
||
|
|
||
|
}
|