summaryrefslogtreecommitdiff
path: root/audiotrond.go
blob: f59a4db247b74354d9b06e04b172c8762ff10d2f (plain)
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
// Copyright 2022 Benjamin Barenblat
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"time"

	"benjamin.barenblat.name/audiotrond/cfa635"
	"github.com/fhs/gompd/v2/mpd"
	"github.com/tarm/serial"
)

func putWrapped(lcd *cfa635.Module, col, row int, data []byte) error {
	for row < 4 && len(data) > 0 {
		if err := lcd.Put(col, row, data); err != nil {
			return err
		}
		if len(data) <= 20-col {
			data = nil
		} else {
			data = data[20-col:]
		}
		col = 0
		row++
	}
	return nil
}

func update[T comparable](dst *T, src T, mtime *time.Time, now time.Time) {
	if *dst == src {
		return
	}
	*dst = src
	*mtime = now
}

type playbackState byte

const (
	_ playbackState = 1 + iota
	stopped
	playing
	paused
)

type foreground byte

const (
	_ foreground = iota
	mpdForeground
	clockForeground
)

type model struct {
	State           playbackState
	LastStateChange time.Time

	Duration time.Duration
	Elapsed  time.Duration

	Track               string
	Artist              string
	Album               string
	LastTrackInfoUpdate time.Time

	Foreground foreground
}

func connectToCFA635() *cfa635.Module {
	s, err := serial.OpenPort(&serial.Config{Name: "/dev/lcd", Baud: 115200})
	if err != nil {
		panic(err)
	}
	m := cfa635.Connect(s)

	go func() {
		for r := m.ReadReport(); r != nil; r = m.ReadReport() {
			log.Println("report:", r)
		}
	}()

	return m
}

func reportPanicOrClear(lcd *cfa635.Module) {
	if v := recover(); v != nil {
		putWrapped(lcd, 0, 0, encode(fmt.Sprint("panic: ", v)))
		panic(v)
	}
	lcd.Clear()
}

func poll(mpd *mpd.Client, now time.Time, model *model) error {
	cmds := mpd.BeginCommandList()
	statusP := cmds.Status()
	currentP := cmds.CurrentSong()
	if err := cmds.End(); err != nil {
		return err
	}

	status, err := statusP.Value()
	if err != nil {
		return err
	}

	switch status["state"] {
	case "stop":
		update(&model.State, stopped, &model.LastStateChange, now)
	case "play":
		update(&model.State, playing, &model.LastStateChange, now)
	case "pause":
		update(&model.State, paused, &model.LastStateChange, now)
	}

	if status["duration"] == "" {
		model.Duration = 0
		model.Elapsed = 0
	} else {
		if model.Duration, err = time.ParseDuration(status["duration"] + "s"); err != nil {
			panic(err)
		}
		if model.Elapsed, err = time.ParseDuration(status["elapsed"] + "s"); err != nil {
			panic(err)
		}
	}

	current, err := currentP.Value()
	if err != nil {
		return err
	}

	update(&model.Track, current["Title"], &model.LastTrackInfoUpdate, now)
	update(&model.Artist, current["Artist"], &model.LastTrackInfoUpdate, now)
	update(&model.Album, current["Album"], &model.LastTrackInfoUpdate, now)
	return nil
}

func ellipsize(src []byte, ellipsis byte, dst []byte) {
	if len(src) <= len(dst) {
		copy(dst, src)
	} else {
		dots := len(dst) - 1
		copy(dst, src[:dots])
		dst[dots] = ellipsis
	}
}

func fmtTime(t, max time.Duration) string {
	f := func(neg string, h, m, s int) string {
		_ = h
		return fmt.Sprintf("%s%d:%02d", neg, m, s)
	}
	if max/time.Hour > 0 {
		f = func(neg string, h, m, s int) string {
			return fmt.Sprintf("%s%d:%02d:%02d", neg, h, m, s)
		}
	} else if int(max/time.Minute)%60 >= 10 {
		f = func(neg string, h, m, s int) string {
			_ = h
			return fmt.Sprintf("%s%02d:%02d", neg, m, s)
		}
	}

	var neg string
	if t < 0 {
		t *= -1
		neg = "-"
	}
	return f(neg, int(t/time.Hour), int(t/time.Minute)%60, int(t/time.Second)%60)
}

func main() {
	lcd := connectToCFA635()
	defer reportPanicOrClear(lcd)
	defer lcd.SetBacklight(0, 0)
	if err := lcd.SetLED(0, false, 0); err != nil {
		panic(err)
	}
	if err := lcd.SetLED(0, true, 0); err != nil {
		panic(err)
	}

	if err := lcd.Clear(); err != nil {
		panic(err)
	}

	mpd, err := mpd.Dial("unix", "/run/mpd/socket")
	if err != nil {
		panic(err)
	}

	var model model

	view1 := new(view)
	view1.LCD = cfa635.ClearedLCDState()
	view1.Mtime = time.Now()

	// Create an idle timer and put it in a drained state so the event loop
	// can set it.
	idle := time.NewTimer(0)
	<-idle.C

	sigterm := make(chan os.Signal, 1)
	signal.Notify(sigterm, os.Interrupt)

EventLoop:
	for {
		now := time.Now()

		if err := poll(mpd, now, &model); err != nil {
			panic(err)
		}

		var foreground2 foreground
		if model.State == playing || now.Sub(model.LastStateChange).Seconds() < 17 {
			foreground2 = mpdForeground
		} else {
			foreground2 = clockForeground
		}

		if foreground2 != model.Foreground {
			switch foreground2 {
			case mpdForeground:
				if err := initializeMPDDisplay(lcd); err != nil {
					panic(err)
				}
			case clockForeground:
				if err := initializeClockDisplay(lcd); err != nil {
					panic(err)
				}
			}
		}
		model.Foreground = foreground2

		var view2 *view
		switch model.Foreground {
		case mpdForeground:
			view2 = mpdView(&model, now, view1)
		case clockForeground:
			view2 = clockView(now)
		}
		if err := updateView(lcd, view1, view2); err != nil {
			panic(err)
		}
		view1 = view2

		idle.Reset(10 * time.Millisecond)
		select {
		case <-sigterm:
			break EventLoop
		case <-idle.C:
		}
	}
}