mirror of
https://github.com/jwetzell/showbridge-go.git
synced 2026-04-26 12:55:29 +00:00
94 lines
1.9 KiB
Go
94 lines
1.9 KiB
Go
package module
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"log/slog"
|
|
"time"
|
|
|
|
"github.com/jwetzell/showbridge-go/internal/common"
|
|
"github.com/jwetzell/showbridge-go/internal/config"
|
|
)
|
|
|
|
type TimeInterval struct {
|
|
config config.ModuleConfig
|
|
Duration uint32
|
|
ctx context.Context
|
|
router common.RouteIO
|
|
ticker *time.Ticker
|
|
logger *slog.Logger
|
|
cancel context.CancelFunc
|
|
}
|
|
|
|
func init() {
|
|
RegisterModule(ModuleRegistration{
|
|
Type: "time.interval",
|
|
New: func(config config.ModuleConfig) (common.Module, error) {
|
|
params := config.Params
|
|
|
|
durationInt, err := params.GetInt("duration")
|
|
if err != nil {
|
|
return nil, fmt.Errorf("time.interval duration error: %w", err)
|
|
}
|
|
return &TimeInterval{Duration: uint32(durationInt), config: config, logger: CreateLogger(config)}, nil
|
|
},
|
|
})
|
|
}
|
|
|
|
func (i *TimeInterval) Id() string {
|
|
return i.config.Id
|
|
}
|
|
|
|
func (i *TimeInterval) Type() string {
|
|
return i.config.Type
|
|
}
|
|
|
|
func (i *TimeInterval) Start(ctx context.Context) error {
|
|
i.logger.Debug("running")
|
|
router, ok := ctx.Value(common.RouterContextKey).(common.RouteIO)
|
|
|
|
if !ok {
|
|
return errors.New("time.interval unable to get router from context")
|
|
}
|
|
i.router = router
|
|
moduleContext, cancel := context.WithCancel(ctx)
|
|
i.ctx = moduleContext
|
|
i.cancel = cancel
|
|
|
|
ticker := time.NewTicker(time.Millisecond * time.Duration(i.Duration))
|
|
i.ticker = ticker
|
|
defer ticker.Stop()
|
|
|
|
for {
|
|
select {
|
|
case <-i.ctx.Done():
|
|
i.logger.Debug("done")
|
|
return nil
|
|
case <-ticker.C:
|
|
if i.router != nil {
|
|
i.router.HandleInput(i.ctx, i.Id(), time.Now())
|
|
}
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
func (i *TimeInterval) Output(ctx context.Context, payload any) error {
|
|
i.ticker.Reset(time.Millisecond * time.Duration(i.Duration))
|
|
return nil
|
|
}
|
|
|
|
func (i *TimeInterval) Stop() {
|
|
i.cancel()
|
|
}
|
|
|
|
func (i *TimeInterval) Get(key string) (any, error) {
|
|
switch key {
|
|
case "duration":
|
|
return i.Duration, nil
|
|
default:
|
|
return nil, errors.New("time.interval key not found")
|
|
}
|
|
}
|