about summary refs log tree commit diff
path: root/tools/mpd-stats/internal/mpd/mpd.go
blob: 859348e32f7ac5650e016ea1602e4e0cfc9d4064 (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
49
50
51
52
53
54
package mpd

import (
	"log"
	"time"

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

const (
	// List of subsystems: https://mpd.readthedocs.io/en/latest/protocol.html#querying-mpd-s-status
	SubSystemPlayer = "player"
)

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

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

	// We are only subscribing to the player subsystem
	p.Watcher, err = mpd.NewWatcher(net, addr, "", SubSystemPlayer)
	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
}