MQTTListener/models/devices.go
Siegfried Siegert 985b4e8fde 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
2020-08-30 21:42:01 +02:00

42 lines
849 B
Go

package models
type Device struct {
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()
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
}