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}
stopRequested = atomic.Bool{}
)
stopRequested.Store(false)
config := MakeConfig(logger)
s := makeSatel(config.satelAddr, config.poolInterval)
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, &stopRequested)
for stopRequested.Load() == false {
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}
}
if stopRequested.Load() == false {
logger.Printf("Waiting %d seconds before trying again", retryDelaySec)
time.Sleep(retryDelaySec * time.Second)
}
}
close(tgEvents)
wg.Wait()
}