From 23004084b4d3379dee4db54a3a125189a710d1b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Rudowicz?= Date: Sun, 18 Feb 2024 19:15:56 +0100 Subject: [PATCH] Attempt to handle ctrl+c --- main.go | 2 +- satel_utils.go | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/main.go b/main.go index b53b34c..2b2c2db 100644 --- a/main.go +++ b/main.go @@ -146,7 +146,7 @@ func main() { tgSender, &wg, log.New(os.Stderr, "SendToTg", log.Lmicroseconds))) for e := range FilterByIndex(FilterByType( - FilterByLastSeen(s.Events, "hs_wro_last_seen.bin", log.New(os.Stderr, "FilterByLastSeen", log.Lmicroseconds)), + FilterByLastSeen(CloseChanOnCtrlC(s.Events), "hs_wro_last_seen.bin", log.New(os.Stderr, "FilterByLastSeen", log.Lmicroseconds)), allowedTypes), allowedIndexes) { logger.Print("Received change from SATEL: ", e) diff --git a/satel_utils.go b/satel_utils.go index 9736b95..4a17c4b 100644 --- a/satel_utils.go +++ b/satel_utils.go @@ -3,6 +3,8 @@ package main import ( "errors" "fmt" + "os" + "os/signal" "github.com/probakowski/go-satel" ) @@ -91,6 +93,28 @@ var SATEL_STRING_TO_CHANGE_TYPE = map[string]satel.ChangeType{ "zone-isolate": satel.ZoneIsolate, } +func CloseChanOnCtrlC(ev <-chan satel.Event) <-chan satel.Event { + returnChan := make(chan satel.Event) + exitSignal := make(chan os.Signal, 1) + signal.Notify(exitSignal, os.Interrupt) + go func() { + defer close(returnChan) + loop: + for { + select { + case <-exitSignal: + return + case e, ok := <-ev: + if !ok { + break loop + } + returnChan <- e + } + } + }() + return returnChan +} + func StringToSatelChangeType(s string) (satel.ChangeType, error) { ct, ok := SATEL_STRING_TO_CHANGE_TYPE[s] if !ok {