2022-02-27 06:57:13 +00:00
|
|
|
package pht
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
2022-02-27 10:10:21 +00:00
|
|
|
"fmt"
|
|
|
|
"log"
|
2022-02-27 06:57:13 +00:00
|
|
|
|
|
|
|
"git.wntrmute.dev/kyle/sensenet/topic"
|
|
|
|
"github.com/Masterminds/squirrel"
|
|
|
|
)
|
|
|
|
|
|
|
|
var psql = squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar)
|
|
|
|
|
|
|
|
func createTable(ctx context.Context, db topic.Database) error {
|
2022-02-27 10:10:21 +00:00
|
|
|
stmt := `CREATE TABLE IF NOT EXISTS pht (
|
2022-02-27 06:57:13 +00:00
|
|
|
id uuid primary key default gen_random_uuid(),
|
2022-02-27 10:10:21 +00:00
|
|
|
source text not null,
|
|
|
|
timestamp int not null,
|
|
|
|
temp real not null,
|
|
|
|
press real not null,
|
|
|
|
humid real not null
|
2022-02-27 06:57:13 +00:00
|
|
|
);`
|
|
|
|
_, err := db.Exec(ctx, stmt)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
type reading struct {
|
|
|
|
Timestamp int64 `json:"timestamp"`
|
|
|
|
Temperature float64 `json:"temperature"`
|
|
|
|
Pressure float64 `json:"pressure"`
|
|
|
|
Humidity float64 `json:"relative_humidity"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func store(ctx context.Context, db topic.Database, packet *topic.Packet) error {
|
|
|
|
r := &reading{}
|
|
|
|
err := json.Unmarshal(packet.Payload, r)
|
|
|
|
if err != nil {
|
2022-02-27 10:10:21 +00:00
|
|
|
log.Printf("packet topic: %s [%x]", packet.Topic, packet.Topic)
|
|
|
|
log.Printf("packet payload: %s [%x]", packet.Payload, packet.Payload)
|
|
|
|
return fmt.Errorf("pht: failed to unmarshal JSON: %w", err)
|
2022-02-27 06:57:13 +00:00
|
|
|
}
|
|
|
|
stmt := psql.Insert("pht").Columns(
|
|
|
|
"source",
|
|
|
|
"timestamp",
|
|
|
|
"temp",
|
|
|
|
"press",
|
|
|
|
"humid",
|
2022-02-27 10:10:21 +00:00
|
|
|
).Values(packet.Publisher, r.Timestamp, r.Temperature, r.Pressure, r.Humidity)
|
2022-02-27 06:57:13 +00:00
|
|
|
query, args, err := stmt.ToSql()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = db.Exec(ctx, query, args...)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
2022-02-27 10:10:21 +00:00
|
|
|
topic.Register("pht", &topic.Topic{
|
|
|
|
CreateTable: createTable,
|
|
|
|
Store: store,
|
|
|
|
})
|
2022-02-27 06:57:13 +00:00
|
|
|
}
|