summaryrefslogtreecommitdiff
path: root/pkg/controller/controller.go
diff options
context:
space:
mode:
Diffstat (limited to 'pkg/controller/controller.go')
-rw-r--r--pkg/controller/controller.go62
1 files changed, 57 insertions, 5 deletions
diff --git a/pkg/controller/controller.go b/pkg/controller/controller.go
index ab04fcc..01e36cd 100644
--- a/pkg/controller/controller.go
+++ b/pkg/controller/controller.go
@@ -23,9 +23,10 @@
package controller
import (
+ "container/list"
"errors"
"fmt"
- "log"
+ // "log"
"strings"
"github.com/scgolang/midi"
@@ -47,8 +48,32 @@ const (
LED_BLINK_MAX = byte(0x7f)
)
+type EventType int
+
+const (
+ ButtonPressed EventType = iota
+ ButtonReleased
+)
+
+func (e EventType) String() string {
+ switch e {
+ case ButtonPressed:
+ return "button pressed"
+ case ButtonReleased:
+ return "button released"
+ default:
+ return "unknown"
+ }
+}
+
+type Event struct {
+ Button byte
+ Type EventType
+}
+
type Controller struct {
- Dev *midi.Device
+ Dev *midi.Device
+ subscribers list.List
}
func openDevice(devices []*midi.Device, prefix string) (d *midi.Device, err error) {
@@ -78,17 +103,39 @@ func NewController(c Config) (*Controller, error) {
return ctrl, nil
}
+func (c *Controller) sendEvent(ev Event) {
+ var next *list.Element
+ for sub := c.subscribers.Front(); sub != nil; sub = next {
+ next = sub.Next()
+
+ ch, ok := (sub.Value).(chan<- Event)
+ if !ok {
+ panic(fmt.Sprintf("controller: subscriber list element value has wrong type: %T", sub.Value))
+ }
+
+ select {
+ case ch <- ev:
+ default:
+ // subscriber is not respoding...
+ // log.Printf("controller: removing subscriber '%v', because it is not responding", ch)
+ close(ch)
+ c.subscribers.Remove(sub)
+ }
+ }
+}
+
func (c *Controller) handleMidiPacket(p midi.Packet) {
- num := p.Data[1]
+ ev := Event{Button: p.Data[1]}
switch p.Data[0] {
case BUTTON_ON:
- log.Printf("controller: button %d pressed", num)
+ ev.Type = ButtonPressed
case BUTTON_OFF:
- log.Printf("controller: button %d released", num)
+ ev.Type = ButtonReleased
default:
// ignore all other events
return
}
+ c.sendEvent(ev)
}
func (c *Controller) Init() error {
@@ -149,3 +196,8 @@ func (c *Controller) LedBlink(num, wait byte) error {
}
return c.setLed(num, wait+LED_BLINK_MIN)
}
+
+func (c *Controller) Subscribe(out chan<- Event) {
+ // log.Printf("controller: subscribing '%v' to events", out)
+ c.subscribers.PushBack(out)
+}