Publish packets.

This commit is contained in:
2022-02-27 02:10:21 -08:00
parent a3966fc28b
commit 579c17bb6a
11 changed files with 624 additions and 36 deletions

View File

@@ -3,6 +3,8 @@ package pht
import (
"context"
"encoding/json"
"fmt"
"log"
"git.wntrmute.dev/kyle/sensenet/topic"
"github.com/Masterminds/squirrel"
@@ -11,13 +13,13 @@ import (
var psql = squirrel.StatementBuilder.PlaceholderFormat(squirrel.Dollar)
func createTable(ctx context.Context, db topic.Database) error {
stmt := `CREATE TABLE pht IF NOT EXISTS (
stmt := `CREATE TABLE IF NOT EXISTS pht (
id uuid primary key default gen_random_uuid(),
source text,
timestamp int,
temp real,
press real,
humid real
source text not null,
timestamp int not null,
temp real not null,
press real not null,
humid real not null
);`
_, err := db.Exec(ctx, stmt)
return err
@@ -34,7 +36,9 @@ 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
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)
}
stmt := psql.Insert("pht").Columns(
"source",
@@ -42,7 +46,7 @@ func store(ctx context.Context, db topic.Database, packet *topic.Packet) error {
"temp",
"press",
"humid",
).Values(packet.Publisher, r.Timestamp, r.Pressure, r.Humidity)
).Values(packet.Publisher, r.Timestamp, r.Temperature, r.Pressure, r.Humidity)
query, args, err := stmt.ToSql()
if err != nil {
return err
@@ -52,11 +56,9 @@ func store(ctx context.Context, db topic.Database, packet *topic.Packet) error {
return err
}
var PHT = &topic.Topic{
CreateTable: createTable,
Store: store,
}
func init() {
topic.Register("pht", PHT)
topic.Register("pht", &topic.Topic{
CreateTable: createTable,
Store: store,
})
}