generated from VLADIMIR/template
89 lines
1.9 KiB
Go
89 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"log"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"evening_detective_server/internal/modules/cudy"
|
|
"evening_detective_server/internal/services/wifi_service"
|
|
)
|
|
|
|
func collectCudy() {
|
|
path := os.Getenv("CUDY_SNAPSHOT_FILE")
|
|
if path == "" {
|
|
log.Fatal("CUDY_SNAPSHOT_FILE is required")
|
|
}
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
snapshot := cudy.Snapshot{}
|
|
var reader cudy.Reader
|
|
passwordFile := os.Getenv("CUDY_PASSWORD_FILE")
|
|
if passwordFile != "" {
|
|
password, err := os.ReadFile(passwordFile)
|
|
if err != nil {
|
|
log.Fatal("cannot read Cudy credential file")
|
|
}
|
|
base := os.Getenv("CUDY_URL")
|
|
if base == "" {
|
|
base = "http://192.168.10.1"
|
|
}
|
|
reader, err = cudy.NewReader(base, strings.TrimRight(string(password), "\r\n"))
|
|
if err != nil {
|
|
log.Fatal("invalid Cudy configuration")
|
|
}
|
|
snapshot, _ = wifi_service.New(path).Get(ctx)
|
|
snapshot.Enabled = true
|
|
}
|
|
timer := time.NewTicker(10 * time.Second)
|
|
defer timer.Stop()
|
|
for {
|
|
if reader != nil {
|
|
clients, err := reader.Read(ctx)
|
|
snapshot.HasError = err != nil
|
|
if err == nil {
|
|
snapshot.Clients = clients
|
|
snapshot.CollectedAt = time.Now().UTC()
|
|
}
|
|
}
|
|
if err := writeCudySnapshot(path, snapshot); err != nil {
|
|
log.Print("cannot publish Cudy snapshot")
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-timer.C:
|
|
}
|
|
}
|
|
}
|
|
|
|
func writeCudySnapshot(path string, snapshot cudy.Snapshot) error {
|
|
data, err := json.Marshal(snapshot)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
file, err := os.CreateTemp(filepath.Dir(path), ".cudy-")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
name := file.Name()
|
|
defer os.Remove(name)
|
|
if err = file.Chmod(0644); err == nil {
|
|
_, err = file.Write(data)
|
|
}
|
|
closeErr := file.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if closeErr != nil {
|
|
return closeErr
|
|
}
|
|
return os.Rename(name, path)
|
|
}
|