add Exceptions to eventListener

This commit is contained in:
Sam Lewis
2022-10-31 02:01:24 -04:00
parent d077c3feec
commit d158524783
4 changed files with 52 additions and 3 deletions

View File

@@ -36,4 +36,4 @@ _Note: I may provide a Docker image in the future with file watching to restart
Gome-Assistant is a new library, and I'm opening it up early to get some user feedback on the API and help shape the direction. I plan for it to grow to cover all Home Assistant use cases, services, and event types. So it's possible — maybe likely — that breaking changes will happen before v1.0.0!
## API Reference (WIP)
## API Reference (TODO)

5
app.go
View File

@@ -35,6 +35,11 @@ See https://pkg.go.dev/time#ParseDuration for all valid time units.
*/
type DurationString string
type timeRange struct {
start time.Time
end time.Time
}
/*
NewApp establishes the websocket connection and returns an object
you can use to register schedules and listeners.

View File

@@ -16,6 +16,9 @@ type EventListener struct {
betweenEnd string
throttle time.Duration
lastRan carbon.Carbon
exceptionDays []time.Time
exceptionRanges []timeRange
}
type EventListenerCallback func(*Service, EventData)
@@ -77,6 +80,16 @@ func (b eventListenerBuilder3) Throttle(s DurationString) eventListenerBuilder3
return b
}
func (b eventListenerBuilder3) ExceptionDay(t time.Time) eventListenerBuilder3 {
b.eventListener.exceptionDays = append(b.eventListener.exceptionDays, t)
return b
}
func (b eventListenerBuilder3) ExceptionRange(start, end time.Time) eventListenerBuilder3 {
b.eventListener.exceptionRanges = append(b.eventListener.exceptionRanges, timeRange{start, end})
return b
}
func (b eventListenerBuilder3) Build() EventListener {
return b.eventListener
}
@@ -100,10 +113,16 @@ func callEventListeners(app *app, msg ws.ChanMsg) {
for _, l := range listeners {
// Check conditions
if c := checkWithinTimeRange(l.betweenStart, l.betweenEnd); c.fail {
return
continue
}
if c := checkThrottle(l.throttle, l.lastRan); c.fail {
return
continue
}
if c := checkExceptionDays(l.exceptionDays); c.fail {
continue
}
if c := checkExceptionRanges(l.exceptionRanges); c.fail {
continue
}
eventData := EventData{

View File

@@ -60,3 +60,28 @@ func checkThrottle(throttle time.Duration, lastRan carbon.Carbon) conditionCheck
}
return cc
}
func checkExceptionDays(eList []time.Time) conditionCheck {
cc := conditionCheck{fail: false}
for _, e := range eList {
y1, m1, d1 := e.Date()
y2, m2, d2 := time.Now().Date()
if y1 == y2 && m1 == m2 && d1 == d2 {
cc.fail = true
break
}
}
return cc
}
func checkExceptionRanges(eList []timeRange) conditionCheck {
cc := conditionCheck{fail: false}
now := time.Now()
for _, eRange := range eList {
if now.After(eRange.start) && now.Before(eRange.end) {
cc.fail = true
break
}
}
return cc
}