ghettoptt/main.go
Torjus Håkestad 84fcfdde62
All checks were successful
go-test-build / go-test-build (1.21) (push) Successful in 58s
go-test-build / go-test-build (1.22) (push) Successful in 1m0s
golangci-lint / goglangci-lint (push) Successful in 1m21s
nix-check-build / nix-check-build (push) Successful in 1m26s
Add workflows and fix linter errors
2024-10-11 01:18:53 +02:00

124 lines
2.7 KiB
Go

package main
import (
"context"
"errors"
"log/slog"
"net/http"
"os"
"os/signal"
"time"
"git.t-juice.club/torjus/ghettoptt/bus"
"git.t-juice.club/torjus/ghettoptt/debouncer"
"git.t-juice.club/torjus/ghettoptt/metrics"
"github.com/holoplot/go-evdev"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const Version = "v0.1.4"
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()
// Setup metrics
m := metrics.NewMumbleMetricsCollector()
mbus := bus.NewMumbleBus(m)
defer mbus.Close()
// Start reading input events
input, err := evdev.OpenWithFlags("/dev/input/by-id/usb-SteelSeries_SteelSeries_Rival_710_Gaming_Mouse-if02-event-kbd", os.O_RDONLY)
if err != nil {
panic(err)
}
defer input.Close()
if err := input.NonBlock(); err != nil {
slog.Error("Failed to set non-blocking mode", "error", err)
os.Exit(1)
}
// Start metrics server
srvCtx, srvCancel := context.WithCancel(context.Background())
defer srvCancel()
go func() {
mux := http.NewServeMux()
mux.Handle("/metrics", promhttp.Handler())
srv := http.Server{
Handler: mux,
Addr: ":8989",
}
go func() {
<-ctx.Done()
_ = srv.Shutdown(context.Background())
srvCancel()
}()
slog.Info("Starting metrics server", "addr", srv.Addr)
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
slog.Warn("Failed to start metrics server", "error", err)
}
}()
// Listen for context cancellation
go func() {
<-ctx.Done()
input.Close()
}()
// Start listening for PTT key
slog.Info("Starting event listener", "version", Version)
eventCh := make(chan bool)
doneCtx, doneCancel := context.WithCancel(srvCtx)
defer doneCancel()
debouncer := debouncer.New(eventCh, 400*time.Millisecond)
go func() {
var done bool
for !done {
ev, err := input.ReadOne()
if err != nil {
if errors.Is(err, os.ErrClosed) {
continue
}
slog.Error("Error reading from input device", "error", err)
_ = mbus.StopTalking()
os.Exit(1)
}
if ev.Code == evdev.KEY_F24 && ev.Value == 1 {
slog.Debug("PTT ON")
eventCh <- true
}
if ev.Code == evdev.KEY_F24 && ev.Value == 0 {
slog.Debug("PTT OFF")
eventCh <- false
}
if doneCtx.Err() != nil {
close(eventCh)
done = true
}
}
}()
for v := range debouncer.C {
if v {
_ = mbus.StartTalking()
slog.Info("Started talking")
} else {
_ = mbus.StopTalking()
slog.Info("Stopped talking")
}
}
_ = mbus.StopTalking()
<-srvCtx.Done()
slog.Info("Exiting")
}