package monitor import ( "context" "log" "os/exec" "strings" "sync" "sync/atomic" "time" "tinygo.org/x/bluetooth" ) // App manages the daemon lifecycle, BLE scanning, watchdog, and publishing. type App struct { lastSeen int64 // MUST be first field for 64-bit alignment on 32-bit platforms (e.g. Raspberry Pi Zero W) config *Config adapter *bluetooth.Adapter riemann *RiemannPublisher mu sync.Mutex lastPublish map[string]time.Time } // NewApp instantiates the App. func NewApp(config *Config) (*App, error) { publisher, err := NewRiemannPublisher(config) if err != nil { return nil, err } return &App{ config: config, adapter: bluetooth.DefaultAdapter, riemann: publisher, lastSeen: time.Now().UnixNano(), lastPublish: make(map[string]time.Time), }, nil } // Run starts the app watchdog and the BLE scan loop. func (app *App) Run(ctx context.Context) error { // Connect to Riemann initially (errors are non-fatal, it will auto-retry on publish) if err := app.riemann.Connect(); err != nil { log.Printf("[WARN] Initial Riemann connection failed: %v. Will retry on metrics publication.", err) } defer func() { _ = app.riemann.Close() }() // Start the watchdog go app.runWatchdog(ctx) // Run BLE scan loop app.runScanLoop(ctx) return nil } func (app *App) runScanLoop(ctx context.Context) { for { select { case <-ctx.Done(): return default: } app.logInfo("Enabling BLE stack on %s...", app.config.BluetoothInterface) err := app.adapter.Enable() if err != nil { log.Printf("[ERROR] Failed to enable BLE adapter: %v. Retrying in 10s...", err) select { case <-ctx.Done(): return case <-time.After(10 * time.Second): } continue } app.logInfo("Starting BLE scan for SwitchBot Monitor Pro (CO2)...") err = app.adapter.Scan(app.scanCallback) if err != nil { log.Printf("[ERROR] BLE scan stopped with error: %v. Retrying in 5s...", err) } else { app.logInfo("BLE scan stopped normally.") } select { case <-ctx.Done(): return case <-time.After(5 * time.Second): } } } func (app *App) scanCallback(adapter *bluetooth.Adapter, result bluetooth.ScanResult) { mac := result.Address.String() // Filter by MAC address if configured if app.config.SwitchbotMac != "" && !strings.EqualFold(app.config.SwitchbotMac, mac) { return } // Extract Manufacturer Data and Service Data var mfrData []byte var mfrCompanyID uint16 for _, m := range result.ManufacturerData() { if m.CompanyID == switchbotCompanyID { mfrCompanyID = m.CompanyID mfrData = m.Data break } } var serviceData []byte hasServiceUUID := false for _, s := range result.ServiceData() { if strings.EqualFold(s.UUID.String(), "0000fd3d-0000-1000-8000-00805f9b34fb") { hasServiceUUID = true serviceData = s.Data break } } // Verify advertisement properties if !IsSwitchBotCO2Advertisement(hasServiceUUID, mfrCompanyID, len(mfrData)) { return } // Update last seen watchdog timer atomic.StoreInt64(&app.lastSeen, time.Now().UnixNano()) // Parse metrics metrics, err := ParseMetrics(mfrData, serviceData) if err != nil { app.logDebug("Failed to parse metrics from %s: %v", mac, err) return } // Apply publish interval throttling app.mu.Lock() lastPub, exists := app.lastPublish[mac] if exists && time.Since(lastPub) < app.config.PublishInterval { app.mu.Unlock() return } app.lastPublish[mac] = time.Now() app.mu.Unlock() log.Printf("[INFO] Decoded metrics from %s: Temp=%.1f°C, Hum=%d%%, CO2=%dppm, Battery=%d%%", mac, metrics.Temperature, metrics.Humidity, metrics.CO2, metrics.Battery) // Publish to Riemann err = app.riemann.Publish(metrics, mac) if err != nil { log.Printf("[ERROR] Failed to publish metrics to Riemann: %v", err) } else { app.logDebug("Published metrics for %s to Riemann successfully", mac) } } func (app *App) runWatchdog(ctx context.Context) { ticker := time.NewTicker(30 * time.Second) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-ticker.C: last := atomic.LoadInt64(&app.lastSeen) since := time.Since(time.Unix(0, last)) app.logDebug("Watchdog: time since last valid packet: %v (timeout: %v)", since, app.config.WatchdogTimeout) if since > app.config.WatchdogTimeout { log.Printf("[WARN] Watchdog triggered: no data received for %v. Resetting Bluetooth adapter.", since) app.resetBluetooth() } } } } func (app *App) resetBluetooth() { // Stop active scan to release resources _ = app.adapter.StopScan() if app.config.ResetCommand == "" { app.logInfo("No reset command configured, skipping hardware reset.") atomic.StoreInt64(&app.lastSeen, time.Now().UnixNano()) return } app.logInfo("Executing reset command: %s", app.config.ResetCommand) cmd := exec.Command("sh", "-c", app.config.ResetCommand) output, err := cmd.CombinedOutput() if err != nil { log.Printf("[ERROR] Reset command failed: %v. Output: %s", err, string(output)) } else { app.logInfo("Reset command completed successfully. Output: %s", string(output)) } // Give driver/hardware a moment to initialize time.Sleep(3 * time.Second) // Reset watchdog timer to allow normal startup atomic.StoreInt64(&app.lastSeen, time.Now().UnixNano()) } func (app *App) logDebug(format string, v ...any) { if app.config.LogLevel == "debug" { log.Printf("[DEBUG] "+format, v...) } } func (app *App) logInfo(format string, v ...any) { if app.config.LogLevel == "debug" || app.config.LogLevel == "info" { log.Printf("[INFO] "+format, v...) } }