Siegfried Siegert
985b4e8fde
- 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
35 lines
593 B
Go
35 lines
593 B
Go
package models
|
|
|
|
import (
|
|
"database/sql"
|
|
|
|
_ "github.com/mattn/go-sqlite3"
|
|
)
|
|
|
|
type Datastore interface {
|
|
AllDevices() ([]*Device, error)
|
|
InsertDevice(*Device) error
|
|
}
|
|
|
|
type DB struct {
|
|
*sql.DB
|
|
}
|
|
|
|
func NewDB(dataSourceName string) (*DB, error) {
|
|
db, err := sql.Open("sqlite3", dataSourceName)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err = db.Ping(); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
sqlStmt := "CREATE TABLE IF NOT EXISTS devices (id TEXT not null primary key, mac TEXT, sn TEXT, lastMsg TEXT);"
|
|
_, err = db.Exec(sqlStmt)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &DB{db}, nil
|
|
}
|