1
0
Fork 0
hswro-alarm-bot/main.go

102 lines
2.6 KiB
Go

package main
import (
"html/template"
"log"
"net"
"os"
"path/filepath"
"sync"
"sync/atomic"
"time"
"git.sr.ht/~michalr/go-satel"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
const (
PersistenceFilename = "hs_wro_last_seen.bin"
retryDelaySec = 25
)
type RealSleeper struct {
duration time.Duration
}
func (self RealSleeper) Sleep(ch chan<- interface{}) {
go func() {
time.Sleep(self.duration)
ch <- nil
}()
}
func makeSatel(satelAddr string, poolInterval time.Duration) *satel.Satel {
satelConn, err := net.Dial("tcp", satelAddr)
if err != nil {
panic(err)
}
return satel.NewConfig(satelConn, satel.Config{EventsQueueSize: 10, PoolingInterval: poolInterval})
}
func getPersistenceFilePath() string {
var stateDir = os.Getenv("STATE_DIRECTORY")
if len(stateDir) != 0 {
return filepath.Join(stateDir, PersistenceFilename)
}
return PersistenceFilename
}
func main() {
var (
wg sync.WaitGroup
tgEvents = make(chan GenericMessage, 5)
logger = log.New(os.Stderr, "Main", log.Lmicroseconds)
sleeper = RealSleeper{time.Second * 60}
cleanShutdown = atomic.Bool{}
)
cleanShutdown.Store(false)
config := MakeConfig(logger)
s := makeSatel(config.SatelAddr, config.PoolInterval.GetDuration())
logger.Printf("Connected to Satel: %s", config.SatelAddr)
bot, err := tgbotapi.NewBotAPI(os.Getenv("TELEGRAM_APITOKEN"))
if err != nil {
panic(err)
}
logger.Print("Created Telegram Bot API client")
tgSender := TgSender{bot, s, log.New(os.Stderr, "TgFormatter", log.Lmicroseconds), config.ChatIds}
tpl := template.Must(template.New("TelegramMessage").Parse(TelegramMessageTemplate))
dataStore := MakeDataStore(log.New(os.Stderr, "DataStore", log.Lmicroseconds), getPersistenceFilePath())
Consume(
SendToTg(Throttle(NotifyViaHTTP(tgEvents, config, &wg, log.New(os.Stderr, "HTTPNotify", log.Lmicroseconds)),
&wg, sleeper, log.New(os.Stderr, "MessageThrottle", log.Lmicroseconds)),
tgSender, &wg, log.New(os.Stderr, "SendToTg", log.Lmicroseconds), tpl),
)
go CloseSatelOnCtrlC(s, &cleanShutdown)
for e := range FilterByTypeOrIndex(
FilterByLastSeen(s.Events, &wg, &dataStore, log.New(os.Stderr, "FilterByLastSeen", log.Lmicroseconds)),
&wg, config.AllowedTypes, config.AllowedIndexes) {
logger.Print("Received change from SATEL: ", e)
tgEvents <- GenericMessage{e.BasicEvents}
}
closeDebugTools := make(chan interface{})
WriteMemoryProfilePeriodically(&wg, log.New(os.Stderr, "DebugTools", log.Lmicroseconds), closeDebugTools)
logger.Print("Closing...")
close(closeDebugTools)
close(tgEvents)
wg.Wait()
if cleanShutdown.Load() {
os.Exit(0)
}
os.Exit(1)
}