-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
1db512f
commit 9edf4ee
Showing
2 changed files
with
92 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
}) | ||
} |