diff --git a/src/device/input/raw/raw.go b/src/device/input/raw/raw.go index e7145b4..712bb5f 100644 --- a/src/device/input/raw/raw.go +++ b/src/device/input/raw/raw.go @@ -16,7 +16,7 @@ func New(ctx context.Context) Raw { return NewKeyboard() } if port, _ := strconv.Atoi(os.Getenv("RAW_UDP")); port != 0 { - return NewUDP(port) + return NewUDP(ctx, port) } generator := randomCharFromRange('a', 'g') if p, ok := os.LookupEnv("RAW_RANDOM_WEIGHT_FILE"); ok && len(p) > 0 { diff --git a/src/device/input/raw/udp.go b/src/device/input/raw/udp.go index 1d2b221..96f24fa 100644 --- a/src/device/input/raw/udp.go +++ b/src/device/input/raw/udp.go @@ -1,6 +1,7 @@ package raw import ( + "context" "log" "net" "os" @@ -9,29 +10,41 @@ import ( type UDP struct { conn net.PacketConn + c chan []byte + ctx context.Context } -func NewUDP(port int) UDP { +func NewUDP(ctx context.Context, port int) UDP { conn, err := net.ListenPacket("udp", ":"+strconv.Itoa(port)) if err != nil { panic(err) } - return UDP{ + result := UDP{ conn: conn, + c: make(chan []byte, 8), + ctx: ctx, + } + go result.listen() + return result +} + +func (udp UDP) listen() { + debugging := os.Getenv("DEBUG") == "true" + for udp.ctx.Err() == nil { + buff := make([]byte, 256) + n, _, err := udp.conn.ReadFrom(buff) + if err != nil { + panic(err) + } + if debugging { + log.Printf("raw.UDP.Read() => %s", buff[:n]) + } + udp.c <- buff[:n] } } func (udp UDP) Read() []byte { - 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) - } - if os.Getenv("DEBUG") == "true" { - log.Printf("raw.UDP.Read() => %s", buff[:n]) - } - return buff[:n] + return <-udp.c } func (udp UDP) Close() {