63 lines
1.2 KiB
Go
63 lines
1.2 KiB
Go
package pht
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
|
|
"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 {
|
|
stmt := `CREATE TABLE pht IF NOT EXISTS (
|
|
id uuid primary key default gen_random_uuid(),
|
|
source text,
|
|
timestamp int,
|
|
temp real,
|
|
press real,
|
|
humid real
|
|
);`
|
|
_, 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 {
|
|
return err
|
|
}
|
|
stmt := psql.Insert("pht").Columns(
|
|
"source",
|
|
"timestamp",
|
|
"temp",
|
|
"press",
|
|
"humid",
|
|
).Values(packet.Publisher, r.Timestamp, r.Pressure, r.Humidity)
|
|
query, args, err := stmt.ToSql()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
_, err = db.Exec(ctx, query, args...)
|
|
return err
|
|
}
|
|
|
|
var PHT = &topic.Topic{
|
|
CreateTable: createTable,
|
|
Store: store,
|
|
}
|
|
|
|
func init() {
|
|
topic.Register("pht", PHT)
|
|
}
|