1
0
Fork 0

Call multiple services and collect any errors

main v0.14.0-beta.1
Jordan Hotmann 2023-11-28 09:47:11 -07:00
parent b0859ed4f0
commit 6a4c1fb88f
No known key found for this signature in database
GPG Key ID: 01B504170C2A2EA3
2 changed files with 60 additions and 0 deletions

View File

@ -1,8 +1,10 @@
package homeassistant package homeassistant
import ( import (
"errors"
"fmt" "fmt"
"strings" "strings"
"sync"
"github.com/go-resty/resty/v2" "github.com/go-resty/resty/v2"
) )
@ -51,3 +53,35 @@ func (c *RestClient) CallServiceManual(domain string, entityId string, service s
} }
return err return err
} }
type CallServiceInput struct {
EntityID string
Service string
Extras map[string]any
}
func (c *RestClient) CallServices(inputs ...*CallServiceInput) error {
errorChannel := make(chan error)
var wg sync.WaitGroup
wg.Add(len(inputs))
go func() {
wg.Wait()
close(errorChannel)
}()
for _, input := range inputs {
go func(input *CallServiceInput) {
defer wg.Done()
err := c.CallService(input.EntityID, input.Service, input.Extras)
errorChannel <- err
}(input)
}
var returnErrors []error
for err := range errorChannel {
returnErrors = append(returnErrors, err)
}
return errors.Join(returnErrors...)
}

View File

@ -41,6 +41,32 @@ func (n *NatsConnection) GenericStateSubscriber(logger *slog.Logger, entityId st
} }
} }
func (n *NatsConnection) GenericTimerListener(logger *slog.Logger, timerName string, handler func() error) {
if timerName == "" {
panic(errors.New("timer name cannot be empty"))
}
topic := fmt.Sprintf("homeassistant.%s.finished", timerName)
l := logger.With("topic", topic, "timer", timerName)
l.Debug("Subscribing to topic")
sub, ch, err := n.Subscribe(topic)
if err != nil {
l.Error("Error subscribing to topic", "error", err)
return
}
defer sub.Unsubscribe()
for msg := range ch {
go msg.Ack()
l.Debug("Timer ended", "name", timerName)
err = handler()
if err != nil {
l.Error("Error handling timer event", "error", err)
continue
}
}
}
func (n *NatsConnection) GenericScheduleSubscriber(logger *slog.Logger, scheduleName string, handler func() error) { func (n *NatsConnection) GenericScheduleSubscriber(logger *slog.Logger, scheduleName string, handler func() error) {
if scheduleName == "" { if scheduleName == "" {
panic(errors.New("schedule name cannot be empty")) panic(errors.New("schedule name cannot be empty"))