add enable/disable function to every builder

This commit is contained in:
Sam Lewis
2023-10-07 14:02:24 -04:00
parent eb26a44459
commit a06f62d1ba
6 changed files with 241 additions and 19 deletions

View File

@@ -2,6 +2,7 @@ package gomeassistant
import (
"encoding/json"
"fmt"
"time"
"github.com/golang-module/carbon"
@@ -27,6 +28,13 @@ type EntityListener struct {
runOnStartup bool
runOnStartupCompleted bool
enabledEntity string
enabledEntityState string
enabledEntityRunOnError bool
disabledEntity string
disabledEntityState string
disabledEntityRunOnError bool
}
type EntityListenerCallback func(*Service, *State, EntityData)
@@ -148,6 +156,40 @@ func (b elBuilder3) RunOnStartup() elBuilder3 {
return b
}
/*
Enable this listener only when the current state of {entityId} matches {state}.
If there is a network error while retrieving state, the listener runs if {runOnNetworkError} is true.
*/
func (b elBuilder3) EnabledEntity(entityId, state string, runOnNetworkError bool) elBuilder3 {
if entityId == "" || state == "" {
panic(fmt.Sprintf("Either entityId or state is empty in EnabledEntity entityId='%s' state='%s'", entityId, state))
}
if b.entityListener.enabledEntity != "" {
panic(fmt.Sprintf("You can't use EnabledEntity and DisabledEntity together. Error occurred while setting EnabledEntity on an entity listener with params entityId=%s state=%s runOnNetworkError=%t", entityId, state, runOnNetworkError))
}
b.entityListener.enabledEntity = entityId
b.entityListener.enabledEntityState = state
b.entityListener.enabledEntityRunOnError = runOnNetworkError
return b
}
/*
Disable this listener when the current state of {entityId} matches {state}.
If there is a network error while retrieving state, the listener runs if {runOnNetworkError} is true.
*/
func (b elBuilder3) DisabledEntity(entityId, state string, runOnNetworkError bool) elBuilder3 {
if entityId == "" || state == "" {
panic(fmt.Sprintf("Either entityId or state is empty in EnabledEntity entityId='%s' state='%s'", entityId, state))
}
if b.entityListener.enabledEntity != "" {
panic(fmt.Sprintf("You can't use EnabledEntity and DisabledEntity together. Error occurred while setting DisabledEntity on an entity listener with params entityId=%s state=%s runOnNetworkError=%t", entityId, state, runOnNetworkError))
}
b.entityListener.disabledEntity = entityId
b.entityListener.disabledEntityState = state
b.entityListener.disabledEntityRunOnError = runOnNetworkError
return b
}
func (b elBuilder3) Build() EntityListener {
return b.entityListener
}
@@ -195,6 +237,12 @@ func callEntityListeners(app *App, msgBytes []byte) {
if c := checkExceptionRanges(l.exceptionRanges); c.fail {
continue
}
if c := checkEnabledEntity(app.state, l.enabledEntity, l.enabledEntityState, l.enabledEntityRunOnError); c.fail {
continue
}
if c := checkDisabledEntity(app.state, l.disabledEntity, l.disabledEntityState, l.disabledEntityRunOnError); c.fail {
continue
}
entityData := EntityData{
TriggerEntityId: eid,