Skip to content

Commit

Permalink
bridge base structures
Browse files Browse the repository at this point in the history
  • Loading branch information
balazsgrill committed Jun 29, 2024
1 parent 1db512f commit 9edf4ee
Show file tree
Hide file tree
Showing 2 changed files with 92 additions and 2 deletions.
10 changes: 8 additions & 2 deletions bridge/fields.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package bridge

import (
"fmt"
"log"

"github.com/home2mqtt/hass"
)
Expand All @@ -14,9 +15,14 @@ func AttachSensor[T any](runtime hass.IPubSubRuntime, stateTopic string, valueTe
}()
}

func AttachField[T any](runtime hass.IPubSubRuntime, stateTopic string, commandTopic string, field hass.IField[T]) {
func AttachField[T any](runtime hass.IPubSubRuntime, stateTopic string, commandTopic string, field hass.IField[T], parseValue func(str string) (T, error)) {
runtime.Receive(commandTopic, func(topic string, payload []byte) {
field.SetValue(field.ParseValue(payload))
value, err := parseValue(string(payload))
if err != nil {
log.Println(err)
return
}
field.SetValue(value)
})
AttachSensor[T](runtime, stateTopic, "", field)
}
84 changes: 84 additions & 0 deletions bridge/properties.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package bridge

import (
"log"
"strings"

"github.com/home2mqtt/hass"
)

type PropertyContext struct {
hass.IPubSubRuntime
Base string
Id string
}

type IProperty[T any] interface {
StateTopic() string
CommandTopic() string
NotifyState(value T)
OnCommand(callback func(value T))
}

func (pc *PropertyContext) DefineString(name string) IProperty[string] {
return &stringProperty{
property: property{
PropertyContext: pc,
name: name,
},
}
}

func (pc *PropertyContext) DefineFloat(name string) IProperty[float64] {
return &floatProperty{
property: property{
PropertyContext: pc,
name: name,
},
}
}

type property struct {
*PropertyContext
name string
}

func (p *property) StateTopic() string {
return strings.Join([]string{p.Base, p.Id, p.name}, "/")
}

func (p *property) CommandTopic() string {
return strings.Join([]string{p.Base, p.Id, p.name, "set"}, "/")
}

type stringProperty struct {
property
}

func (p *stringProperty) NotifyState(value string) {
hass.SendString(p, p.StateTopic(), value)
}

func (p *stringProperty) OnCommand(callback func(value string)) {
hass.ReceiveString(p, p.CommandTopic(), func(topic, payload string) {
callback(payload)
})
}

type floatProperty struct {
property
}

func (p *floatProperty) NotifyState(value float64) {
hass.SendFloat(p, p.StateTopic(), value)
}

func (p *floatProperty) OnCommand(callback func(value float64)) {
hass.ReceiveFloat(p, p.CommandTopic(), func(topic string, payload float64, err error) {
if err == nil {
callback(payload)
} else {
log.Printf("Float value error received on %s: %v\n", topic, err)
}
})
}

0 comments on commit 9edf4ee

Please sign in to comment.