From ef93665838bd8fee51606ebcd95c84a82a3a1520 Mon Sep 17 00:00:00 2001 From: Christian Pointner Date: Mon, 11 Feb 2019 20:41:12 +0100 Subject: subscribing to controller events works now --- pkg/controller/controller.go | 62 ++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 57 insertions(+), 5 deletions(-) (limited to 'pkg/controller') 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) +} -- cgit v1.2.3