This commit is contained in:
Mats Tornberg
2025-11-22 21:19:38 +01:00
parent 57ba34b929
commit b6343149c8
4 changed files with 213 additions and 91 deletions

View File

@@ -35,9 +35,29 @@ func (ds *DataStore) Close() error {
return ds.db.Close() return ds.db.Close()
} }
// initTables creates the necessary database tables // initTables creates the necessary database tables and applies migrations
func (ds *DataStore) initTables() error { func (ds *DataStore) initTables() error {
tables := []string{ // Create schema version table
if _, err := ds.db.Exec(`
CREATE TABLE IF NOT EXISTS schema_version (
version INTEGER PRIMARY KEY,
applied_at INTEGER NOT NULL
)
`); err != nil {
return err
}
// Get current schema version
currentVersion := ds.getCurrentSchemaVersion()
// Apply migrations
migrations := []struct {
version int
sql []string
}{
{
version: 1,
sql: []string{
`CREATE TABLE IF NOT EXISTS devices ( `CREATE TABLE IF NOT EXISTS devices (
id INTEGER PRIMARY KEY, id INTEGER PRIMARY KEY,
name TEXT, name TEXT,
@@ -66,21 +86,73 @@ func (ds *DataStore) initTables() error {
last_data TEXT, last_data TEXT,
last_seen INTEGER last_seen INTEGER
)`, )`,
},
},
{
version: 2,
sql: []string{
`ALTER TABLE devices ADD COLUMN protocol TEXT`,
`ALTER TABLE devices ADD COLUMN model TEXT`,
},
},
} }
for _, table := range tables { // Apply pending migrations
if _, err := ds.db.Exec(table); err != nil { for _, migration := range migrations {
if migration.version > currentVersion {
for _, sql := range migration.sql {
if _, err := ds.db.Exec(sql); err != nil {
// Ignore errors for ALTER TABLE ADD COLUMN if column already exists
if !ds.isColumnExistsError(err) {
return fmt.Errorf("migration v%d failed: %w", migration.version, err)
}
}
}
// Record migration
if err := ds.recordMigration(migration.version); err != nil {
return err return err
} }
} }
}
return nil return nil
} }
// getCurrentSchemaVersion returns the current schema version
func (ds *DataStore) getCurrentSchemaVersion() int {
var version int
err := ds.db.QueryRow("SELECT MAX(version) FROM schema_version").Scan(&version)
if err != nil {
return 0
}
return version
}
// recordMigration records that a migration has been applied
func (ds *DataStore) recordMigration(version int) error {
_, err := ds.db.Exec(
"INSERT INTO schema_version (version, applied_at) VALUES (?, ?)",
version, time.Now().Unix(),
)
return err
}
// isColumnExistsError checks if the error is due to a column already existing
func (ds *DataStore) isColumnExistsError(err error) bool {
if err == nil {
return false
}
return sql.ErrNoRows != err &&
(err.Error() == "duplicate column name: protocol" ||
err.Error() == "duplicate column name: model")
}
// UpsertDevice inserts or updates a device // UpsertDevice inserts or updates a device
func (ds *DataStore) UpsertDevice(device *Device) error { func (ds *DataStore) UpsertDevice(device *Device) error {
_, err := ds.db.Exec( _, err := ds.db.Exec(
"INSERT OR REPLACE INTO devices (id, name, unique_id) VALUES (?, ?, ?)", "INSERT OR REPLACE INTO devices (id, name, unique_id, protocol, model) VALUES (?, ?, ?, ?, ?)",
device.ID, device.Name, device.UniqueID, device.ID, device.Name, device.UniqueID, device.Protocol, device.Model,
) )
return err return err
} }
@@ -89,9 +161,9 @@ func (ds *DataStore) UpsertDevice(device *Device) error {
func (ds *DataStore) GetDevice(id int) (*Device, error) { func (ds *DataStore) GetDevice(id int) (*Device, error) {
device := &Device{} device := &Device{}
err := ds.db.QueryRow( err := ds.db.QueryRow(
"SELECT id, name, unique_id FROM devices WHERE id = ?", "SELECT id, name, unique_id, protocol, model FROM devices WHERE id = ?",
id, id,
).Scan(&device.ID, &device.Name, &device.UniqueID) ).Scan(&device.ID, &device.Name, &device.UniqueID, &device.Protocol, &device.Model)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@@ -101,7 +173,7 @@ func (ds *DataStore) GetDevice(id int) (*Device, error) {
// ListDevices returns an iterator over all devices // ListDevices returns an iterator over all devices
func (ds *DataStore) ListDevices() iter.Seq[*Device] { func (ds *DataStore) ListDevices() iter.Seq[*Device] {
return func(yield func(*Device) bool) { return func(yield func(*Device) bool) {
rows, err := ds.db.Query("SELECT id, name, unique_id FROM devices ORDER BY id") rows, err := ds.db.Query("SELECT id, name, unique_id, protocol, model FROM devices ORDER BY id")
if err != nil { if err != nil {
return return
} }
@@ -109,7 +181,7 @@ func (ds *DataStore) ListDevices() iter.Seq[*Device] {
for rows.Next() { for rows.Next() {
device := &Device{} device := &Device{}
if err := rows.Scan(&device.ID, &device.Name, &device.UniqueID); err != nil { if err := rows.Scan(&device.ID, &device.Name, &device.UniqueID, &device.Protocol, &device.Model); err != nil {
continue continue
} }
if !yield(device) { if !yield(device) {

View File

@@ -7,6 +7,8 @@ type Device struct {
ID int `json:"id"` ID int `json:"id"`
Name string `json:"name"` Name string `json:"name"`
UniqueID string `json:"unique_id"` UniqueID string `json:"unique_id"`
Protocol string `json:"protocol"`
Model string `json:"model"`
} }
// Sensor represents a Telldus sensor // Sensor represents a Telldus sensor

View File

@@ -24,10 +24,14 @@ func (s *Syncer) SyncDevices() error {
for i := 0; i < numDevices; i++ { for i := 0; i < numDevices; i++ {
deviceID := telldus.GetDeviceId(i) deviceID := telldus.GetDeviceId(i)
name := telldus.GetName(deviceID) name := telldus.GetName(deviceID)
protocol := telldus.GetProtocol(deviceID)
model := telldus.GetModel(deviceID)
device := &datastore.Device{ device := &datastore.Device{
ID: deviceID, ID: deviceID,
Name: name, Name: name,
UniqueID: fmt.Sprintf("telldus_device_%d", deviceID), UniqueID: fmt.Sprintf("telldus_device_%d", deviceID),
Protocol: protocol,
Model: model,
} }
if err := s.store.UpsertDevice(device); err != nil { if err := s.store.UpsertDevice(device); err != nil {
log.Printf("Error upserting device %d: %v", deviceID, err) log.Printf("Error upserting device %d: %v", deviceID, err)

View File

@@ -1,6 +1,7 @@
package mqtt package mqtt
import ( import (
"encoding/json"
"fmt" "fmt"
"log" "log"
@@ -8,23 +9,45 @@ import (
"git.k7n.net/mats/go-telldus/pkg/telldus" "git.k7n.net/mats/go-telldus/pkg/telldus"
) )
// DeviceDiscovery represents Home Assistant device discovery payload // HADevice represents a device in Home Assistant MQTT discovery
type DeviceDiscovery struct { type HADevice struct {
Identifiers []string `json:"identifiers"`
Name string `json:"name"`
Manufacturer string `json:"manufacturer"`
Model string `json:"model,omitempty"`
}
// SwitchDiscovery represents Home Assistant MQTT switch discovery config
// Reference: https://www.home-assistant.io/integrations/switch.mqtt/
type SwitchDiscovery struct {
Name string `json:"name"` Name string `json:"name"`
CommandTopic string `json:"command_topic"` CommandTopic string `json:"command_topic"`
StateTopic string `json:"state_topic"` StateTopic string `json:"state_topic"`
UniqueID string `json:"unique_id"` UniqueID string `json:"unique_id"`
Device map[string]interface{} `json:"device"` Device HADevice `json:"device"`
PayloadOn string `json:"payload_on,omitempty"`
PayloadOff string `json:"payload_off,omitempty"`
StateOn string `json:"state_on,omitempty"`
StateOff string `json:"state_off,omitempty"`
OptimisticMode bool `json:"optimistic,omitempty"`
Qos int `json:"qos,omitempty"`
Retain bool `json:"retain,omitempty"`
AvailabilityTopic string `json:"availability_topic,omitempty"`
} }
// SensorDiscovery represents Home Assistant sensor discovery payload // SensorDiscovery represents Home Assistant MQTT sensor discovery config
// Reference: https://www.home-assistant.io/integrations/sensor.mqtt/
type SensorDiscovery struct { type SensorDiscovery struct {
Name string `json:"name"` Name string `json:"name"`
StateTopic string `json:"state_topic"` StateTopic string `json:"state_topic"`
UniqueID string `json:"unique_id"`
Device HADevice `json:"device"`
UnitOfMeasurement string `json:"unit_of_measurement,omitempty"` UnitOfMeasurement string `json:"unit_of_measurement,omitempty"`
DeviceClass string `json:"device_class,omitempty"` DeviceClass string `json:"device_class,omitempty"`
UniqueID string `json:"unique_id"` StateClass string `json:"state_class,omitempty"`
Device map[string]interface{} `json:"device"` ValueTemplate string `json:"value_template,omitempty"`
Qos int `json:"qos,omitempty"`
AvailabilityTopic string `json:"availability_topic,omitempty"`
} }
// PublishAllDiscovery publishes Home Assistant discovery messages for all devices and sensors // PublishAllDiscovery publishes Home Assistant discovery messages for all devices and sensors
@@ -55,19 +78,29 @@ func (c *Client) PublishDeviceDiscovery(deviceID int) error {
return fmt.Errorf("device %d not found: %w", deviceID, err) return fmt.Errorf("device %d not found: %w", deviceID, err)
} }
topic := fmt.Sprintf("homeassistant/switch/%s/config", device.UniqueID) discovery := SwitchDiscovery{
payload := fmt.Sprintf(`{ Name: device.Name,
"name": "%s", CommandTopic: fmt.Sprintf("telldus/device/%d/set", deviceID),
"command_topic": "telldus/device/%d/set", StateTopic: fmt.Sprintf("telldus/device/%d/state", deviceID),
"state_topic": "telldus/device/%d/state", UniqueID: device.UniqueID,
"unique_id": "%s", PayloadOn: "ON",
"device": { PayloadOff: "OFF",
"identifiers": ["telldus_%d"], StateOn: "ON",
"name": "%s", StateOff: "OFF",
"manufacturer": "Telldus" Device: HADevice{
Identifiers: []string{fmt.Sprintf("telldus_%d", deviceID)},
Name: device.Name,
Manufacturer: "Telldus",
Model: fmt.Sprintf("%s %s", device.Protocol, device.Model),
},
} }
}`, device.Name, deviceID, deviceID, device.UniqueID, deviceID, device.Name)
payload, err := json.Marshal(discovery)
if err != nil {
return fmt.Errorf("failed to marshal discovery: %w", err)
}
topic := fmt.Sprintf("homeassistant/switch/%s/config", device.UniqueID)
c.client.Publish(topic, 0, true, payload) c.client.Publish(topic, 0, true, payload)
return nil return nil
} }
@@ -120,39 +153,50 @@ func (c *Client) PublishSensorDiscovery(protocol, model string, id int) error {
// publishSensorDiscoveryForSensor publishes discovery messages for a sensor's data types // publishSensorDiscoveryForSensor publishes discovery messages for a sensor's data types
func (c *Client) publishSensorDiscoveryForSensor(sensor *datastore.Sensor, dataTypes int) error { func (c *Client) publishSensorDiscoveryForSensor(sensor *datastore.Sensor, dataTypes int) error {
if dataTypes&telldus.DataTypeTemperature != 0 && sensor.TemperatureUniqueID != "" { sensorDevice := HADevice{
topic := fmt.Sprintf("homeassistant/sensor/%s/config", sensor.TemperatureUniqueID) Identifiers: []string{fmt.Sprintf("telldus_sensor_%s_%s_%d", sensor.Protocol, sensor.Model, sensor.ID)},
payload := fmt.Sprintf(`{ Name: sensor.Name,
"name": "%s Temperature", Manufacturer: "Telldus",
"state_topic": "telldus/sensor/%s/%s/%d/temperature", Model: fmt.Sprintf("%s %s", sensor.Protocol, sensor.Model),
"unit_of_measurement": "°C",
"device_class": "temperature",
"unique_id": "%s",
"device": {
"identifiers": ["telldus_sensor_%s_%s_%d"],
"name": "%s",
"manufacturer": "Telldus"
} }
}`, sensor.Name, sensor.Protocol, sensor.Model, sensor.ID, sensor.TemperatureUniqueID,
sensor.Protocol, sensor.Model, sensor.ID, sensor.Name) if dataTypes&telldus.DataTypeTemperature != 0 && sensor.TemperatureUniqueID != "" {
discovery := SensorDiscovery{
Name: fmt.Sprintf("%s Temperature", sensor.Name),
StateTopic: fmt.Sprintf("telldus/sensor/%s/%s/%d/temperature", sensor.Protocol, sensor.Model, sensor.ID),
UniqueID: sensor.TemperatureUniqueID,
UnitOfMeasurement: "°C",
DeviceClass: "temperature",
StateClass: "measurement",
Device: sensorDevice,
}
payload, err := json.Marshal(discovery)
if err != nil {
return fmt.Errorf("failed to marshal temperature discovery: %w", err)
}
topic := fmt.Sprintf("homeassistant/sensor/%s/config", sensor.TemperatureUniqueID)
c.client.Publish(topic, 0, true, payload) c.client.Publish(topic, 0, true, payload)
} }
if dataTypes&telldus.DataTypeHumidity != 0 && sensor.HumidityUniqueID != "" { if dataTypes&telldus.DataTypeHumidity != 0 && sensor.HumidityUniqueID != "" {
topic := fmt.Sprintf("homeassistant/sensor/%s/config", sensor.HumidityUniqueID) discovery := SensorDiscovery{
payload := fmt.Sprintf(`{ Name: fmt.Sprintf("%s Humidity", sensor.Name),
"name": "%s Humidity", StateTopic: fmt.Sprintf("telldus/sensor/%s/%s/%d/humidity", sensor.Protocol, sensor.Model, sensor.ID),
"state_topic": "telldus/sensor/%s/%s/%d/humidity", UniqueID: sensor.HumidityUniqueID,
"unit_of_measurement": "%%", UnitOfMeasurement: "%",
"device_class": "humidity", DeviceClass: "humidity",
"unique_id": "%s", StateClass: "measurement",
"device": { Device: sensorDevice,
"identifiers": ["telldus_sensor_%s_%s_%d"],
"name": "%s",
"manufacturer": "Telldus"
} }
}`, sensor.Name, sensor.Protocol, sensor.Model, sensor.ID, sensor.HumidityUniqueID,
sensor.Protocol, sensor.Model, sensor.ID, sensor.Name) payload, err := json.Marshal(discovery)
if err != nil {
return fmt.Errorf("failed to marshal humidity discovery: %w", err)
}
topic := fmt.Sprintf("homeassistant/sensor/%s/config", sensor.HumidityUniqueID)
c.client.Publish(topic, 0, true, payload) c.client.Publish(topic, 0, true, payload)
} }