From 7fda11391313db4e219f19793fcaf6611d209536 Mon Sep 17 00:00:00 2001 From: Sam Lewis Date: Wed, 9 Nov 2022 20:16:35 -0500 Subject: [PATCH] add etl.RunOnStartup --- app.go | 23 +++++++++++++++++++++-- entitylistener.go | 10 ++++++++-- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/app.go b/app.go index b8a9905..e6f1ee6 100644 --- a/app.go +++ b/app.go @@ -189,10 +189,29 @@ func (a *App) Start() { ws.SubscribeToStateChangedEvents(id, a.conn, a.ctx) a.entityListenersId = id - // entity listeners + // entity listeners runOnStartup + for eid, etls := range a.entityListeners { + for _, etl := range etls { + if etl.runOnStartup && !etl.runOnStartupCompleted { + entityState, err := a.state.Get(eid) + if err != nil { + log.Default().Println("Failed to get entity state \"", eid, "\" during startup, skipping RunOnStartup") + } + etl.callback(a.service, a.state, EntityData{ + TriggerEntityId: eid, + FromState: entityState.State, + FromAttributes: entityState.Attributes, + ToState: entityState.State, + ToAttributes: entityState.Attributes, + LastChanged: entityState.LastChanged, + }) + } + } + } + + // entity listeners and event listeners elChan := make(chan ws.ChanMsg) go ws.ListenWebsocket(a.conn, a.ctx, elChan) - var msg ws.ChanMsg for { msg = <-elChan diff --git a/entitylistener.go b/entitylistener.go index 59b1ef4..f4f70b5 100644 --- a/entitylistener.go +++ b/entitylistener.go @@ -24,9 +24,10 @@ type EntityListener struct { exceptionDays []time.Time exceptionRanges []timeRange -} -// TODO: add RunOnStartup() to etl, evl, schedule + runOnStartup bool + runOnStartupCompleted bool +} type EntityListenerCallback func(*Service, *State, EntityData) @@ -142,6 +143,11 @@ func (b elBuilder3) ExceptionRange(start, end time.Time) elBuilder3 { return b } +func (b elBuilder3) RunOnStartup() elBuilder3 { + b.entityListener.runOnStartup = true + return b +} + func (b elBuilder3) Build() EntityListener { return b.entityListener }