2020-08-30 07:16:50 +02:00
|
|
|
package models
|
|
|
|
|
2020-09-02 09:02:30 +02:00
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
2020-08-30 07:16:50 +02:00
|
|
|
type Device struct {
|
2020-08-30 21:42:01 +02:00
|
|
|
ID string
|
|
|
|
MAC string
|
|
|
|
SN string
|
2020-08-30 07:16:50 +02:00
|
|
|
LastMsg string
|
|
|
|
}
|
|
|
|
|
|
|
|
func (db *DB) AllDevices() ([]*Device, error) {
|
2020-08-30 21:42:01 +02:00
|
|
|
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
|
2020-08-30 07:16:50 +02:00
|
|
|
}
|
|
|
|
|
2020-08-30 21:42:01 +02:00
|
|
|
func (db *DB) InsertDevice(device *Device) error {
|
2020-09-02 09:02:30 +02:00
|
|
|
sqlStmt := `INSERT OR REPLACE INTO devices (id, mac, sn, lastMsg)
|
2020-08-30 21:42:01 +02:00
|
|
|
VALUES($1, $2, $3, $4);`
|
|
|
|
_, err := db.Exec(sqlStmt, device.ID, device.MAC, device.SN, device.LastMsg)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2020-08-30 07:16:50 +02:00
|
|
|
|
2020-09-02 09:02:30 +02:00
|
|
|
// DEBUG
|
|
|
|
fmt.Printf("Sucessfully inserted device with ID %s to database\n", device.ID)
|
|
|
|
|
2020-08-30 21:42:01 +02:00
|
|
|
return err
|
|
|
|
}
|