schnutibox/pkg/watcher/watcher.go

76 lines
1.4 KiB
Go
Raw Normal View History

2021-08-05 09:43:35 +02:00
package watcher
import (
2021-08-26 14:09:02 +02:00
"fmt"
2021-08-05 09:43:35 +02:00
"time"
"github.com/rs/zerolog/log"
"go.xsfx.dev/schnutibox/internal/metrics"
2021-08-26 14:09:02 +02:00
"go.xsfx.dev/schnutibox/pkg/currentsong"
2021-08-05 09:43:35 +02:00
"go.xsfx.dev/schnutibox/pkg/mpc"
"go.xsfx.dev/schnutibox/pkg/timer"
)
const tickerTime = time.Second
// Run runs actions after tickerTime is over, over again and again.
// Right now its mostly used for setting metrics.
func Run() {
log.Debug().Msg("starting watch")
ticker := time.NewTicker(tickerTime)
go func() {
for {
<-ticker.C
// Timer.
go timer.T.Handle()
2021-08-05 09:43:35 +02:00
// Metrics.
go func() {
m, err := mpc.Conn()
if err != nil {
log.Error().Err(err).Msg("could not connect")
2021-08-05 09:43:35 +02:00
return
}
uris, err := mpc.PlaylistURIS(m)
2021-08-05 09:43:35 +02:00
if err != nil {
log.Error().Err(err).Msg("could not get playlist uris")
2021-08-05 09:43:35 +02:00
metrics.BoxErrors.Inc()
return
}
// Gettings MPD state.
s, err := m.Status()
if err != nil {
log.Error().Err(err).Msg("could not get status")
2021-08-05 09:43:35 +02:00
metrics.BoxErrors.Inc()
return
}
2021-08-26 14:09:02 +02:00
currentSong, err := m.CurrentSong()
if err != nil {
log.Error().Err(err).Msg("could not get current song")
metrics.BoxErrors.Inc()
return
}
if len(currentSong) != 0 {
currentsong.Write(fmt.Sprintf("%s - %s", currentSong["Artist"], currentSong["Track"]))
} else {
currentsong.Write("")
}
2021-08-05 09:43:35 +02:00
// Sets the metrics.
metrics.Set(uris, s["state"])
}()
}
}()
}