From 287b9c7b4efb6aff9899c148c48b934e9c59db43 Mon Sep 17 00:00:00 2001 From: Bel LaPointe Date: Fri, 24 Mar 2023 18:48:54 -0600 Subject: [PATCH] udp input except no clean shutdown --- src/device/input/input.go | 7 ++++++ src/device/input/input_test.go | 1 + src/device/input/udp.go | 46 ++++++++++++++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 src/device/input/udp.go diff --git a/src/device/input/input.go b/src/device/input/input.go index c11f56c..e088922 100644 --- a/src/device/input/input.go +++ b/src/device/input/input.go @@ -3,6 +3,7 @@ package input import ( "context" "os" + "strconv" "syscall" ) @@ -47,6 +48,12 @@ func newSourceFunc() func() Input { return singletonKeyboard } } + if port, _ := strconv.Atoi(os.Getenv("INPUT_UDP")); port != 0 { + singletonUDP := NewUDP(port) + return func() Input { + return singletonUDP + } + } return func() Input { generator := randomCharFromRange('a', 'g') if p, ok := os.LookupEnv("INPUT_RANDOM_WEIGHT_FILE"); ok && len(p) > 0 { diff --git a/src/device/input/input_test.go b/src/device/input/input_test.go index 60d589a..4eff7a6 100644 --- a/src/device/input/input_test.go +++ b/src/device/input/input_test.go @@ -12,6 +12,7 @@ func TestInput(t *testing.T) { var _ Input = &Buffered{} var _ Input = Remap{} var _ Input = &Refresh{} + var _ Input = UDP{} } func TestNewNew(t *testing.T) { diff --git a/src/device/input/udp.go b/src/device/input/udp.go new file mode 100644 index 0000000..1d21e43 --- /dev/null +++ b/src/device/input/udp.go @@ -0,0 +1,46 @@ +package input + +import ( + "net" + "strconv" +) + +type UDP struct { + conn net.PacketConn +} + +func NewUDP(port int) UDP { + conn, err := net.ListenPacket("udp", ":"+strconv.Itoa(port)) + if err != nil { + panic(err) + } + return UDP{ + conn: conn, + } +} + +func (udp UDP) Read() []Button { + panic("NEEDS TO BE IN BG THREAD SO WE CAN SHUT DOWN WITHOUT BLOCKING ON READ OR AT LEAST BE RESPONSIVE") + buff := make([]byte, 1024) + n, _, err := udp.conn.ReadFrom(buff) + if err != nil { + panic(err) + } + buttons := make([]Button, 0, n) + down := true + for i := range buff[:n] { + if buff[i] == '!' { + down = false + } else { + if buff[i] != '\n' { + buttons = append(buttons, Button{Char: buff[i], Down: down}) + } + down = true + } + } + return buttons +} + +func (udp UDP) Close() { + udp.conn.Close() +}