Prepare for storing device data in database

- create device id from mqtt topic
- implement method for storing device in database

Still todo:
- extract other data (e.g. MAC, SN) from monitoring object
- find a way in mqtt to use global env
This commit is contained in:
2020-08-30 21:42:01 +02:00
parent 231c17d7c3
commit 985b4e8fde
3 changed files with 50 additions and 26 deletions

View File

@@ -8,6 +8,7 @@ import (
type Datastore interface {
AllDevices() ([]*Device, error)
InsertDevice(*Device) error
}
type DB struct {

View File

@@ -1,36 +1,41 @@
package models
type Device struct {
ID string
MAC string
SN string
ID string
MAC string
SN string
LastMsg string
}
func (db *DB) AllDevices() ([]*Device, error) {
rows, err := db.Query("SELECT * FROM devices")
if err != nil {
return nil, err
}
defer rows.Close()
rows, err := db.Query("SELECT * FROM devices")
if err != nil {
return nil, err
}
defer rows.Close()
devices := make([]*Device, 0)
for rows.Next() {
device := new(Device)
err := rows.Scan(&device.ID, &device.MAC, &device.SN, &device.LastMsg)
if err != nil {
return nil, err
}
devices = append(devices, device)
}
if err = rows.Err(); err != nil {
return nil, err
}
return devices, nil
devices := make([]*Device, 0)
for rows.Next() {
device := new(Device)
err := rows.Scan(&device.ID, &device.MAC, &device.SN, &device.LastMsg)
if err != nil {
return nil, err
}
devices = append(devices, device)
}
if err = rows.Err(); err != nil {
return nil, err
}
return devices, nil
}
func (db *DB) InsertDevice(device *Device) error {
sqlStmt := `INSERT OR REPLACE INTO table (id, mac, sn, lastMsg)
VALUES($1, $2, $3, $4);`
_, err := db.Exec(sqlStmt, device.ID, device.MAC, device.SN, device.LastMsg)
if err != nil {
return err
}
return err
}