generated from VLADIMIR/template
44 lines
1.1 KiB
Go
44 lines
1.1 KiB
Go
// Package wifi_service reads the collector's latest snapshot without LAN access.
|
|
package wifi_service
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"io"
|
|
"os"
|
|
"time"
|
|
|
|
"evening_detective_server/internal/modules/cudy"
|
|
)
|
|
|
|
type Service struct {
|
|
path string
|
|
now func() time.Time
|
|
}
|
|
|
|
func New(path string) *Service { return &Service{path: path, now: time.Now} }
|
|
|
|
func (s *Service) Get(ctx context.Context) (cudy.Snapshot, bool) {
|
|
if s == nil || s.path == "" {
|
|
return cudy.Snapshot{}, false
|
|
}
|
|
snapshot := cudy.Snapshot{Enabled: true, HasError: true}
|
|
if ctx.Err() != nil {
|
|
return snapshot, true
|
|
}
|
|
file, err := os.Open(s.path)
|
|
if err != nil {
|
|
return snapshot, true
|
|
}
|
|
defer file.Close()
|
|
data, err := io.ReadAll(io.LimitReader(file, 2<<20+1))
|
|
if err != nil || len(data) > 2<<20 || json.Unmarshal(data, &snapshot) != nil {
|
|
return cudy.Snapshot{Enabled: true, HasError: true}, true
|
|
}
|
|
if !snapshot.Enabled {
|
|
return snapshot, false
|
|
}
|
|
stale := snapshot.HasError || snapshot.CollectedAt.IsZero() || s.now().Sub(snapshot.CollectedAt) >= 30*time.Second || snapshot.CollectedAt.After(s.now())
|
|
return snapshot, stale
|
|
}
|