102 lines
2.3 KiB
Go
102 lines
2.3 KiB
Go
package app
|
|
|
|
import (
|
|
"embed"
|
|
"log"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/nemunaire/repeater/internal/api"
|
|
"github.com/nemunaire/repeater/internal/device"
|
|
"github.com/nemunaire/repeater/internal/logging"
|
|
"github.com/nemunaire/repeater/internal/models"
|
|
"github.com/nemunaire/repeater/internal/wifi"
|
|
)
|
|
|
|
// App represents the application
|
|
type App struct {
|
|
Status models.SystemStatus
|
|
StatusMutex sync.RWMutex
|
|
StartTime time.Time
|
|
Assets embed.FS
|
|
}
|
|
|
|
// New creates a new application instance
|
|
func New(assets embed.FS) *App {
|
|
return &App{
|
|
Status: models.SystemStatus{
|
|
Connected: false,
|
|
ConnectedSSID: "",
|
|
HotspotEnabled: true,
|
|
ConnectedCount: 0,
|
|
DataUsage: 0.0,
|
|
Uptime: 0,
|
|
},
|
|
StartTime: time.Now(),
|
|
Assets: assets,
|
|
}
|
|
}
|
|
|
|
// Initialize initializes the application
|
|
func (a *App) Initialize() error {
|
|
// Initialize WiFi D-Bus connection
|
|
if err := wifi.Initialize(); err != nil {
|
|
return err
|
|
}
|
|
|
|
// Start periodic tasks
|
|
go a.periodicStatusUpdate()
|
|
go a.periodicDeviceUpdate()
|
|
|
|
logging.AddLog("Système", "Application initialisée")
|
|
return nil
|
|
}
|
|
|
|
// Run starts the HTTP server
|
|
func (a *App) Run(addr string) error {
|
|
router := api.SetupRouter(&a.Status, a.Assets)
|
|
|
|
logging.AddLog("Système", "Serveur API démarré sur "+addr)
|
|
return router.Run(addr)
|
|
}
|
|
|
|
// Shutdown gracefully shuts down the application
|
|
func (a *App) Shutdown() {
|
|
wifi.Close()
|
|
logging.AddLog("Système", "Application arrêtée")
|
|
}
|
|
|
|
// periodicStatusUpdate updates WiFi connection status periodically
|
|
func (a *App) periodicStatusUpdate() {
|
|
ticker := time.NewTicker(5 * time.Second)
|
|
defer ticker.Stop()
|
|
|
|
for range ticker.C {
|
|
a.StatusMutex.Lock()
|
|
a.Status.Connected = wifi.IsConnected()
|
|
if !a.Status.Connected {
|
|
a.Status.ConnectedSSID = ""
|
|
}
|
|
a.Status.Uptime = int64(time.Since(a.StartTime).Seconds())
|
|
a.StatusMutex.Unlock()
|
|
}
|
|
}
|
|
|
|
// periodicDeviceUpdate updates connected devices list periodically
|
|
func (a *App) periodicDeviceUpdate() {
|
|
ticker := time.NewTicker(10 * time.Second)
|
|
defer ticker.Stop()
|
|
|
|
for range ticker.C {
|
|
devices, err := device.GetConnectedDevices()
|
|
if err != nil {
|
|
log.Printf("Error getting connected devices: %v", err)
|
|
continue
|
|
}
|
|
|
|
a.StatusMutex.Lock()
|
|
a.Status.ConnectedDevices = devices
|
|
a.Status.ConnectedCount = len(devices)
|
|
a.StatusMutex.Unlock()
|
|
}
|
|
}
|