ghettoptt/main.go

96 lines
1.9 KiB
Go
Raw Normal View History

2024-03-09 19:34:21 +00:00
package main
import (
2024-03-09 21:57:46 +00:00
"context"
"errors"
"log/slog"
2024-03-18 11:19:16 +00:00
"net/http"
2024-03-09 19:34:21 +00:00
"os"
2024-03-09 21:57:46 +00:00
"os/signal"
2024-03-09 19:34:21 +00:00
2024-03-18 11:19:16 +00:00
"git.t-juice.club/torjus/ghettoptt/bus"
"git.t-juice.club/torjus/ghettoptt/metrics"
2024-03-09 19:34:21 +00:00
"github.com/holoplot/go-evdev"
2024-03-18 11:19:16 +00:00
"github.com/prometheus/client_golang/prometheus/promhttp"
2024-03-09 19:34:21 +00:00
)
2024-03-18 11:19:16 +00:00
const Version = "v0.1.2"
2024-03-10 02:24:11 +00:00
2024-03-09 19:34:21 +00:00
func main() {
2024-03-09 21:57:46 +00:00
// 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()
2024-03-18 11:19:16 +00:00
// Setup metrics
m := metrics.NewMumbleMetricsCollector()
2024-03-09 19:34:21 +00:00
2024-03-18 11:19:16 +00:00
mbus := bus.NewMumbleBus(m)
defer mbus.Close()
2024-03-09 19:34:21 +00:00
// Start reading input events
input, err := evdev.OpenWithFlags("/dev/input/event1", os.O_RDONLY)
if err != nil {
panic(err)
}
2024-03-09 21:57:46 +00:00
defer input.Close()
input.NonBlock()
var done bool
2024-03-18 11:19:16 +00:00
// 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)
srv.ListenAndServe()
}()
2024-03-09 21:57:46 +00:00
// Listen for context cancellation
go func() {
<-ctx.Done()
done = true
input.Close()
}()
2024-03-09 19:34:21 +00:00
2024-03-09 21:57:46 +00:00
// Start listening for PTT key
2024-03-10 02:24:11 +00:00
slog.Info("Starting event listener", "version", Version)
2024-03-09 21:57:46 +00:00
for !done {
2024-03-09 19:34:21 +00:00
ev, err := input.ReadOne()
if err != nil {
2024-03-09 21:57:46 +00:00
if errors.Is(err, os.ErrClosed) {
continue
}
2024-03-18 11:19:16 +00:00
slog.Error("Error reading from input device", "error", err)
2024-03-09 21:57:46 +00:00
os.Exit(1)
2024-03-09 19:34:21 +00:00
}
if ev.Code == evdev.KEY_F24 && ev.Value == 1 {
2024-03-09 21:57:46 +00:00
slog.Info("PTT ON")
2024-03-18 11:19:16 +00:00
mbus.StartTalking()
2024-03-09 19:34:21 +00:00
}
if ev.Code == evdev.KEY_F24 && ev.Value == 0 {
2024-03-18 11:19:16 +00:00
slog.Info("PTT OFF")
mbus.StopTalking()
2024-03-09 19:34:21 +00:00
}
}
2024-03-18 11:19:16 +00:00
mbus.StopTalking()
<-srvCtx.Done()
2024-03-09 21:57:46 +00:00
slog.Info("Exiting")
2024-03-09 19:34:21 +00:00
}