From a1fa070078e505f443c31667f9005458cc87023d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torjus=20H=C3=A5kestad?= Date: Sat, 9 Mar 2024 22:57:46 +0100 Subject: [PATCH] Improve logging --- main.go | 41 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/main.go b/main.go index 7e07790..7fce446 100644 --- a/main.go +++ b/main.go @@ -1,14 +1,27 @@ package main import ( - "fmt" + "context" + "errors" + "log/slog" "os" + "os/signal" "github.com/godbus/dbus/v5" "github.com/holoplot/go-evdev" ) func main() { + // Setup logger + h := slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}) + logger := slog.New(h) + slog.SetDefault(logger) + + // Setup signal handler + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + + // Connect to dbus conn, err := dbus.ConnectSessionBus() if err != nil { panic(err) @@ -22,19 +35,37 @@ func main() { if err != nil { panic(err) } + defer input.Close() + input.NonBlock() - for { + var done bool + + // Listen for context cancellation + go func() { + <-ctx.Done() + done = true + input.Close() + }() + + // Start listening for PTT key + for !done { ev, err := input.ReadOne() if err != nil { - panic(err) + if errors.Is(err, os.ErrClosed) { + continue + } + slog.Error("Error reading fron input device", "error", err) + os.Exit(1) } if ev.Code == evdev.KEY_F24 && ev.Value == 1 { - fmt.Printf("PTT ON!\n") + slog.Info("PTT ON") obj.Go("net.sourceforge.mumble.Mumble.startTalking", 0, nil) } if ev.Code == evdev.KEY_F24 && ev.Value == 0 { - fmt.Printf("PTT OFF!\n") + slog.Info("PTT OFF") obj.Go("net.sourceforge.mumble.Mumble.stopTalking", 0, nil) } } + obj.Go("net.sourceforge.mumble.Mumble.stopTalking", 0, nil) + slog.Info("Exiting") }