Commit Graph
12 Commits
Author SHA1 Message Date
maziggy 134847a3bd feat(camera): in-app diagnostic for "Connection lost" (#1395 follow-up)
Step 2 of the camera architecture overhaul agreed after #1395. When
  the camera viewer hits its error state OR before a print at any
  time, a Diagnose button runs a staged check against the printer and
  renders the result inline: which stage failed, how long it took,
  and a translated remediation hint. Cuts off the "user opens a
  'camera broken' ticket → ask for support bundle → triage" loop at
  the user's screen.

  Backend

  - New `backend/app/services/camera_diagnose.py` orchestrator with
    CameraDiagnoseResult / CameraDiagnoseStage dataclasses.
  - New POST /printers/{id}/camera/diagnose route in camera.py.
  - Stages:
      tcp_reachable — TCP socket open to 322 (RTSP) / 6000 (chamber)
        with 3 s timeout. Distinguishes timeout, refused, and host-
        unreachable into distinct summary codes so the frontend can
        show a precise remediation (firewall vs LAN-only off vs
        wrong IP).
      first_frame — captures one JPEG end-to-end via the existing
        capture_camera_frame_bytes pipeline. Auth + RTSP handshake +
        first keyframe collapse into one stage; the user-facing
        answer is the same regardless of which sub-layer failed.
  - Live-stream shortcut: when a viewer is currently watching the
    camera with a buffered frame < 10 s old, the diagnostic skips
    the real test and returns live_stream_active_healthy. Opening a
    fresh socket would kick the live viewer off on single-camera-
    connection firmwares (the #1348 reconnect-storm trigger), so we
    trust the real-world evidence instead.
  - Response surfaces protocol, port, and profile name for support
    triage — lets us ask "what does your modal say?" instead of
    "send the support bundle".

  Frontend

  - New CameraDiagnoseModal renders one row per stage with green-
    check / red-X / grey-skipped icons, the per-stage duration in
    ms, a remediation banner styled by overall status, and a Run
    again button.
  - Two entry points:
      1. The viewer's error overlay grows a Diagnose button next to
         Retry. Retry stays the primary action; Diagnose is the
         escape hatch for users who can't see what's wrong.
      2. A stethoscope icon in the viewer's always-visible control
         bar, between Refresh and Fullscreen. Pre-flight testing
         ("did my firmware update break the camera?", "is the
         camera up before I send a print?") doesn't require waiting
         for the stream to fail first.
  - Also lifted the previously-hard-coded "Camera unavailable" /
    "Retry" strings into camera.unavailable / camera.retry so the
    error UI is fully translated alongside the new keys.
2026-05-18 10:52:02 +02:00
maziggy 29379e3be7 fix(camera): plate-detection UI now uses the external camera when configured (#1359)
Reporter @Andlar94 hit a permanent "Build plate not empty" on every print
  start on an A1 with an external RTSP camera. The runtime auto-check at
  main.py:1819 called check_plate_empty with use_external=external_camera_enabled,
  but the manual UI routes (camera.py) declared use_external: bool = False
  and the frontend client always sent use_external=false. So calibration
  captured a built-in frame and stamped it as the reference; the runtime
  check captured an external frame and diffed it against that reference --
  a permanent mismatch.

  Centralise the default on the backend: both routes now take bool | None,
  deriving the default from the printer's external_camera_enabled +
  external_camera_url + external_camera_type. The frontend client stops
  sending the flag unless the caller explicitly sets it, so the existing
  UI call sites immediately benefit and any future caller gets the right
  camera automatically. Explicit overrides still win.

  Adds 4 regression tests pinning the new default for both the
  external-enabled and external-disabled cases, plus the explicit override
  path so a future "always built-in" caller stays supported.
2026-05-15 14:32:18 +02:00
maziggy c097140e4c fix(camera): share broadcaster buffered frame with Obico + /camera/snapshot (#1271)
The MJPEG fan-out broadcaster from #1089 only solved viewer-side
  concurrency. Obico polling (every 5s) and the manual /camera/snapshot
  endpoint kept opening their own fresh RTSP sockets, which X1/H2/P2
  firmwares tolerated but X2D firmware 01.01.00.00 enforces strict
  single-connection on — every poll kicked the live stream.

  Add try_get_active_buffered_frame(printer_id): returns the broadcaster's
  last buffered frame when a viewer is connected, None otherwise. Obico
  and /camera/snapshot consult it before opening a fresh socket. When no
  viewer is active they fall through to the existing fresh-capture path.

  plate_detection and layer_timelapse intentionally not converted.
2026-05-12 08:36:08 +02:00
maziggy 1e3ad697f2 fix(#1089): camera stream fan-out broadcaster
Most Bambu Lab printers only allow one concurrent camera connection, but
  GET /printers/{id}/camera/stream opened a fresh upstream per viewer.
  Two browser tabs → second viewer fails or kicks the first off.

  New MjpegBroadcaster (services/camera_fanout.py) owns one upstream per
  printer and fans MJPEG chunks out to N subscribers. 5 s grace window
  absorbs tab refreshes without reconnecting. Bounded subscriber queues
  drop frames for slow viewers rather than blocking the broadcaster.

  Audit-pass fixes:
  - _stream_start_times set with setdefault() so stream_uptime reflects
    the shared upstream's age, not the most-recent viewer's
  - subscribe() retried once on RuntimeError to close a tiny grace race
  - unsubscribe() returns post-removal count atomically so the detach log
    no longer races with concurrent leavers

  Permission gates unchanged; broadcaster has no FastAPI surface.

  Tests: 13 broadcaster unit tests + 2 integration tests on /camera/stop.
  External-camera path untouched.
2026-04-25 09:56:45 +02:00
maziggy 1eeeb37b42 Updated commit message (now includes the test fix):
Fix camera button permissions & ffmpeg process leak (#550)

  Camera button on printer card was clickable without camera:view
  permission. ffmpeg processes (~240MB each) accumulated after closing
  camera streams because: (1) stop endpoint called terminate() without
  wait()/kill(), (2) HTTP disconnect detection only ran between frames
  so was blocked when the generator was stuck on stdout read, and
  (3) no mechanism caught processes orphaned by generator abandonment
  or app restarts.

  - Add camera:view permission check + tooltip to camera button
  - Fix stop endpoint: terminate() → wait(2s) → kill() → wait()
  - Add background disconnect monitor (polls every 2s, kills ffmpeg
    directly on disconnect)
  - Add periodic /proc scan (every 60s) that SIGKILLs any ffmpeg
    with rtsps://bblp: not in an active stream
  - Add noCamera i18n key to all 6 locales
  - Fix camera API test mocks for async wait() and pid attribute
2026-02-28 12:58:31 +01:00
maziggy 09d8e7d682 Fix external camera not used for snapshot + stream dropping (#325)
The snapshot endpoint always used the internal printer camera even when
an external camera was configured. Now checks for external camera first,
matching the stream endpoint pattern. Also added retry logic (3 attempts,
2s delay) to MJPEG and RTSP stream generators so they reconnect on
timeout instead of silently ending the stream.
2026-02-11 07:09:39 +01:00
maziggy b99536cc33 Remove unused imports, variables, and fix minor CodeQL findings
- Remove 28 unused imports across 22 test files
- Prefix 4 unused local variables with _ in app code
  (archives, bambu_mqtt, main) and remove 1 dead store
- Consolidate import/import-from in test_plate_detection.py
- Fix unreachable statement in test_archive_service.py
- Simplify redundant comparison in timelapse_processor.py

Resolves ~50 CodeQL py/unused-import, py/unused-local-variable,
py/import-and-import-from, py/unreachable-statement, and
py/redundant-comparison findings.
2026-02-06 12:19:17 +01:00
maziggy c937e6781b Improved docker tests 2026-01-30 13:54:20 +01:00
maziggy 9d6164ab1c Add USB camera support (V4L2)
- Add USB camera type to external camera service
- Auto-detect available V4L2 devices on Linux
- New API endpoint: GET /api/v1/printers/usb-cameras
- Use ffmpeg for USB camera capture and streaming
- Add "USB Camera (V4L2)" option in Settings UI
- Debounce camera URL input to avoid saving on every keystroke

Closes #143
2026-01-27 06:40:14 +01:00
maziggy 888891fdc6 Add build plate empty detection feature
Automatically detect if objects are on the build plate before printing
and pause the print immediately if detected.

Features:
- Per-printer toggle to enable/disable plate detection
- Multi-reference calibration: store up to 5 reference images per printer
  for different plate types (textured, smooth, high-temp, etc.)
- Automatic print pause when objects detected at print start
- Push notification and WebSocket alert when print is paused
- ROI (Region of Interest) calibration UI with sliders to adjust
  detection area
- Reference management: view thumbnails, add labels, delete references
- Works with both built-in and external cameras
- Uses buffered camera frames when stream is active (no blocking)
- Split button UI: main button opens modal, chevron toggles on/off
- Green visual indicator when plate detection is enabled
- Included in backup/restore
2026-01-26 13:04:29 +01:00
maziggy 83cbac04b7 - Add interactive API Browser to Settings > API Keys
- New APIBrowser component with full OpenAPI schema integration
    - Fetches and parses /openapi.json automatically
    - Groups endpoints by API tags (printers, archives, settings, etc.)
    - Expandable endpoint sections with color-coded method badges
    - Path parameter, query parameter, and JSON body editors
    - Auto-populates request body with schema examples
    - Live API request execution with response display
    - Response shows status code, timing, and formatted JSON
    - Copy response button with clipboard fallback
    - Search to filter endpoints across all categories
    - Expand All / Collapse All buttons
    - Link to Swagger UI (/docs)

  - Two-column layout for API Keys tab
    - Left: API key management + webhook documentation
    - Right: API Browser with dedicated test key input

  - Parameter validation
    - Shows warning for missing required parameters
    - Validates before sending requests to avoid 422 errors

  - UX improvements
    - "Use in API Browser" button on newly created keys
    - Responsive layout (stacked on mobile, side-by-side on xl+)
2026-01-02 15:00:21 +01:00
maziggy f7cde95bbb Tests Added Summary:
Backend Tests (New Files)

  1. backend/tests/integration/test_camera_api.py - 13 tests
    - Camera stop endpoint (GET and POST methods)
    - Active stream termination
    - Printer-specific stream stopping
    - Camera test endpoint
    - Camera snapshot endpoint
    - Camera stream validation
  2. backend/tests/integration/test_system_api.py - 16 tests
    - System info endpoint structure
    - App, database, storage, memory, CPU sections
    - Helper functions (format_bytes, format_uptime)
    - Archive statistics
    - Printer connection info
  3. backend/tests/unit/services/test_telemetry.py - 16 tests
    - Installation ID creation/retrieval
    - Telemetry enabled/disabled checks
    - Telemetry URL configuration
    - Heartbeat sending and rate limiting
    - Exception handling
  4. backend/tests/unit/services/test_notification_service.py (updated) - Added TestNotificationVariableFallbacks class with 9 tests
    - Duration formatting with None values
    - Print complete fallback values
    - Estimated time and remaining time fallbacks
    - Filename fallback to "Unknown"

  Frontend Tests (New Files)

  5. frontend/src/__tests__/pages/SystemInfoPage.test.tsx - 14 tests
    - Loading and error states
    - Application, database, storage, memory, CPU sections
    - Connected printers display
    - Disk usage warning/danger colors
    - Refresh button
  6. frontend/src/__tests__/components/AMSHistoryModal.test.tsx - 21 tests
    - Modal open/close behavior
    - Humidity/temperature mode switching
    - Time range selection
    - Statistics cards (current, avg, min, max)
    - Loading and error states
    - Trend calculation
  7. frontend/src/__tests__/components/NotificationProviderCard.test.tsx (updated) - Added NotificationProviderCard AMS toggles describe block with 11 tests
    - AMS humidity/temperature notification toggles
    - AMS-HT humidity/temperature notification toggles
    - Independence of AMS and AMS-HT toggles
    - Default values

  Total New Tests: ~100 tests covering:
  - Camera API endpoints
  - System info API
  - Anonymous telemetry service
  - Notification variable fallbacks
  - System Info page UI
  - AMS History modal UI
  - AMS/AMS-HT notification toggle settings

  Tests Added - Complete Summary:

  Backend Tests (4 new files, 1 updated)

  | File                                                       | Tests | Description                                                     |
  |------------------------------------------------------------|-------|-----------------------------------------------------------------|
  | tests/integration/test_camera_api.py                       | 13    | Camera stop (GET/POST), snapshot, stream, test endpoints        |
  | tests/integration/test_system_api.py                       | 16    | System info API, helper functions (format_bytes, format_uptime) |
  | tests/unit/services/test_telemetry.py                      | 16    | Installation ID, telemetry toggle, heartbeat sending            |
  | tests/unit/services/test_notification_service.py (updated) | +10   | Variable fallbacks for duration, filename, estimated_time       |

  Frontend Tests (2 new files, 1 updated)

  | File                                                                 | Tests | Description                                           |
  |----------------------------------------------------------------------|-------|-------------------------------------------------------|
  | src/__tests__/pages/SystemInfoPage.test.tsx                          | 14    | System info page UI, sections, loading/error states   |
  | src/__tests__/components/AMSHistoryModal.test.tsx                    | 21    | AMS history modal, mode switching, time ranges, stats |
  | src/__tests__/components/NotificationProviderCard.test.tsx (updated) | +11   | AMS/AMS-HT notification toggle independence           |

  Total: 101 new tests
  - Backend: 335 tests total (all passing)
  - Frontend: 124 tests total (all passing)
2025-12-12 11:15:59 +01:00