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

@@ -26,6 +26,13 @@ type DailySchedule struct {
exceptionDates []time.Time
allowlistDates []time.Time
enabledEntity string
enabledEntityState string
enabledEntityRunOnError bool
disabledEntity string
disabledEntityState string
disabledEntityRunOnError bool
}
func (s DailySchedule) Hash() string {
@@ -110,6 +117,40 @@ func (sb scheduleBuilderEnd) OnlyOnDates(t time.Time, tl ...time.Time) scheduleB
return sb
}
/*
Enable this schedule only when the current state of {entityId} matches {state}.
If there is a network error while retrieving state, the schedule runs if {runOnNetworkError} is true.
*/
func (sb scheduleBuilderEnd) EnabledEntity(entityId, state string, runOnNetworkError bool) scheduleBuilderEnd {
if entityId == "" || state == "" {
panic(fmt.Sprintf("Either entityId or state is empty in EnabledEntity entityId='%s' state='%s'", entityId, state))
}
if sb.schedule.enabledEntity != "" {
panic(fmt.Sprintf("You can't use EnabledEntity and DisabledEntity together. Error occurred while setting EnabledEntity on a schedule with params entityId=%s state=%s runOnNetworkError=%t", entityId, state, runOnNetworkError))
}
sb.schedule.enabledEntity = entityId
sb.schedule.enabledEntityState = state
sb.schedule.enabledEntityRunOnError = runOnNetworkError
return sb
}
/*
Disable this schedule when the current state of {entityId} matches {state}.
If there is a network error while retrieving state, the schedule runs if {runOnNetworkError} is true.
*/
func (sb scheduleBuilderEnd) DisabledEntity(entityId, state string, runOnNetworkError bool) scheduleBuilderEnd {
if entityId == "" || state == "" {
panic(fmt.Sprintf("Either entityId or state is empty in EnabledEntity entityId='%s' state='%s'", entityId, state))
}
if sb.schedule.enabledEntity != "" {
panic(fmt.Sprintf("You can't use EnabledEntity and DisabledEntity together. Error occurred while setting DisabledEntity on a schedule with params entityId=%s state=%s runOnNetworkError=%t", entityId, state, runOnNetworkError))
}
sb.schedule.disabledEntity = entityId
sb.schedule.disabledEntityState = state
sb.schedule.disabledEntityRunOnError = runOnNetworkError
return sb
}
func (sb scheduleBuilderEnd) Build() DailySchedule {
return sb.schedule
}
@@ -145,6 +186,12 @@ func (s DailySchedule) maybeRunCallback(a *App) {
if c := checkAllowlistDates(s.allowlistDates); c.fail {
return
}
if c := checkEnabledEntity(a.state, s.enabledEntity, s.enabledEntityState, s.enabledEntityRunOnError); c.fail {
return
}
if c := checkDisabledEntity(a.state, s.disabledEntity, s.disabledEntityState, s.disabledEntityRunOnError); c.fail {
return
}
go s.callback(a.service, a.state)
}