about summary refs log tree commit diff
path: root/tools/mpd-stats/internal/mpd/mpd.go
blob: 5b57ee480387b21449d9c603bc9c2e63f84fc30c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package mpd

import (
	"log"
	"time"

	"github.com/fhs/gompd/v2/mpd"
)

type Player struct {
	Watcher *mpd.Watcher
	Client  *mpd.Client
}

func NewPlayer(net string, addr string) (*Player, error) {
	var (
		p   Player
		err error
	)

	p.Watcher, err = mpd.NewWatcher(net, addr, "", "player")
	if err != nil {
		log.Fatalf("failed to create a watcher: %v", err)
	}

	p.Client, err = mpd.Dial(net, addr)
	if err != nil {
		log.Fatalf("failed to start mpd client: %v", err)
	}

	go func() {
		for range time.Tick(30 * time.Second) {
			p.Client.Ping()
		}
	}()

	return &p, nil
}

func (p *Player) Close() error {
	if err := p.Watcher.Close(); err != nil {
		return err
	}
	if err := p.Client.Close(); err != nil {
		return err
	}
	return nil
}