package pht import ( "context" "encoding/json" "fmt" "log" "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 IF NOT EXISTS pht ( id uuid primary key default gen_random_uuid(), 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 } 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 { 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", "timestamp", "temp", "press", "humid", ).Values(packet.Publisher, r.Timestamp, r.Temperature, r.Pressure, r.Humidity) query, args, err := stmt.ToSql() if err != nil { return err } _, err = db.Exec(ctx, query, args...) return err } func init() { topic.Register("pht", &topic.Topic{ CreateTable: createTable, Store: store, }) }