Skip to content

Python API

Automatically generated from the source docstrings with mkdocstrings. Run mkdocs serve to render this page locally.

Plugin

The OctoPrint plugin implementation: mixins, settings, webcam provider and the simple API.

BambucamPlugin

BambucamPlugin()

Bases: TimelapseOpsMixin, AutoSyncMixin, IpcamSyncMixin, RawFilesOpsMixin, AutoLedMixin, StartupPlugin, ShutdownPlugin, SettingsPlugin, TemplatePlugin, AssetPlugin, SimpleApiPlugin, EventHandlerPlugin, WebcamProviderPlugin

Manage the BambuCam webcamd daemon and expose it to OctoPrint.

Note: several OctoPrint mixin hooks (the SimpleApiPlugin methods, is_template_autoescaped) are annotated with overly narrow return types in OctoPrint's base classes (-> None / Literal[False]) even though the real plugin API expects Flask responses / dicts / bools. We return the correct values here; reportIncompatibleMethodOverride is disabled in pyrightconfig.json so those accurate overrides do not get flagged.

Source code in octoprint_bambucam/__init__.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def __init__(self):
    super().__init__()
    self._manager: Optional[WebcamdManager] = None
    self._webcam_name = "bambucam"
    self._ftp_lock = threading.Lock()
    self._ftp_busy = False
    self._thumb_lock = threading.Lock()
    self._led_busy = False
    self._led_lock = threading.Lock()
    self._led_monitor: Optional[BambuMqttMonitor] = None
    self._led_state: Optional[bool] = None
    self._init_autosync()
    self._init_ipcam_sync()
    self._init_raw_files()
    self._init_auto_led()

get_additional_backup_excludes

get_additional_backup_excludes(excludes, *args, **kwargs)

Exclude bulky render dirs from OctoPrint backups.

Chunks are re-harvestable from the printer's /ipcam folder and the work/trash dirs are transient, so backing them up only bloats the archive. When the user excludes "timelapse" from the backup the rendered videos are gone anyway, so the whole render tree (incl. thumbs/metadata) is dropped for consistency.

Source code in octoprint_bambucam/__init__.py
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
def get_additional_backup_excludes(self, excludes, *args, **kwargs):
    """Exclude bulky render dirs from OctoPrint backups.

    Chunks are re-harvestable from the printer's ``/ipcam`` folder and
    the work/trash dirs are transient, so backing them up only bloats
    the archive. When the user excludes "timelapse" from the backup the
    rendered videos are gone anyway, so the whole render tree (incl.
    thumbs/metadata) is dropped for consistency.
    """
    if "timelapse" in (excludes or []):
        return [RENDER_ROOT]
    return [
        os.path.join(RENDER_ROOT, RAW_CHUNKS_DIRNAME),
        os.path.join(RENDER_ROOT, WORK_DIRNAME),
        os.path.join(RENDER_ROOT, TRASH_DIRNAME),
    ]

get_timelapse_extensions

get_timelapse_extensions()

Teach OctoPrint's native Timelapse tab to also list .avi files.

Bambu P1/A1 printers record timelapses as .avi (alongside .mp4 on some firmware). OctoPrint's built-in tab only recognizes mpg/mpeg/mp4/m4v/mkv (see octoprint.timelapse._extensions), so a copied .avi would land in the folder but never appear. Registering this octoprint.timelapse.extensions hook adds avi to the allow-list. .mp4 is already covered upstream.

Source code in octoprint_bambucam/__init__.py
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
def get_timelapse_extensions(self):
    """Teach OctoPrint's native Timelapse tab to also list ``.avi`` files.

    Bambu P1/A1 printers record timelapses as ``.avi`` (alongside ``.mp4``
    on some firmware). OctoPrint's built-in tab only recognizes
    ``mpg/mpeg/mp4/m4v/mkv`` (see ``octoprint.timelapse._extensions``), so a
    copied ``.avi`` would land in the folder but never appear. Registering
    this ``octoprint.timelapse.extensions`` hook adds ``avi`` to the
    allow-list. ``.mp4`` is already covered upstream.
    """
    return ["avi"]

get_update_information

get_update_information()

Software-update hook config consumed by OctoPrint's updater.

Source code in octoprint_bambucam/__init__.py
980
981
982
983
984
985
986
987
988
989
990
991
992
993
def get_update_information(self):
    """Software-update hook config consumed by OctoPrint's updater."""
    return {
        "bambucam": {
            "displayName": "BambuCam",
            "displayVersion": self._plugin_version,
            "type": "github_release",
            "user": "Ajimaru",
            "repo": "OctoPrint-BambuCam",
            "current": self._plugin_version,
            "pip": "https://github.com/Ajimaru/OctoPrint-BambuCam"
            "/archive/{target_version}.zip",
        }
    }

on_event

on_event(event, payload) -> None

Fan a printer event out to the post-print pipelines.

AutoSyncMixin.on_event drives the render-gate flags and the serial post-print pipeline; on_ipcam_event snapshots the /ipcam baseline at PrintStarted for pipeline stage 3; on_auto_led_event switches the chamber light on/off around the job.

Called explicitly rather than through super() because the mixins each own the hook name; adding a consumer means adding a call here.

Source code in octoprint_bambucam/__init__.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
def on_event(self, event, payload) -> None:
    """Fan a printer event out to the post-print pipelines.

    ``AutoSyncMixin.on_event`` drives the render-gate flags and the serial
    post-print pipeline; ``on_ipcam_event`` snapshots the ``/ipcam``
    baseline at ``PrintStarted`` for pipeline stage 3; ``on_auto_led_event``
    switches the chamber light on/off around the job.

    Called explicitly rather than through ``super()`` because the mixins
    each own the hook name; adding a consumer means adding a call here.
    """
    AutoSyncMixin.on_event(self, event, payload)
    self.on_ipcam_event(event, payload)
    self.on_auto_led_event(event, payload)

on_settings_migrate

on_settings_migrate(target, current)

Drop settings that no longer back anything (OctoPrint hook).

current is None for a config written before this plugin had a settings version — which is every install carrying the dead keys.

Source code in octoprint_bambucam/__init__.py
293
294
295
296
297
298
299
300
301
302
303
304
305
def on_settings_migrate(self, target, current):
    """Drop settings that no longer back anything (OctoPrint hook).

    ``current`` is ``None`` for a config written before this plugin had a
    settings version — which is every install carrying the dead keys.
    """
    if current is not None and current >= target:
        return
    for key in self._OBSOLETE_SETTINGS:
        if self._settings.get([key]) is None:
            continue
        self._settings.remove([key])
        self._logger.info("settings: removed obsolete key %r", key)

options: show_root_heading: true members_order: source

Daemon supervisor

The supervised process manager for the vendored MJPEG daemon.

WebcamdManager

WebcamdManager(logger, on_state_change=None, http_logger=None)

Supervise the vendored webcamd child process.

Handles start/stop/restart, pumps the child's output into the plugin logger, and runs a generation-tracked watchdog that restarts the daemon with exponential backoff after unexpected exits while guaranteeing only one daemon ever runs at a time.

:param logger: plugin logger; child output is forwarded here :param on_state_change: optional callable(state: str, detail: dict) called on "started", "stopped", "crashed", "gave_up" :param http_logger: optional logger for the daemon's --loghttp output; those lines are routed here instead of the main plugin log

Source code in octoprint_bambucam/daemon.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def __init__(self, logger, on_state_change=None, http_logger=None):
    """
    :param logger: plugin logger; child output is forwarded here
    :param on_state_change: optional callable(state: str, detail: dict)
           called on "started", "stopped", "crashed", "gave_up"
    :param http_logger: optional logger for the daemon's --loghttp output;
           those lines are routed here instead of the main plugin log
    """
    self._logger = logger
    self._on_state_change = on_state_change
    self._http_logger = http_logger

    self._process = None
    self._lock = threading.RLock()
    self._stop_requested = False
    self._started_at = None
    self._restart_count = 0
    self._restart_timestamps = []
    self._watchdog_thread = None
    self._last_error = None
    self._generation = 0
    self._config = {}

fetch_info

fetch_info()

GET /?info from the daemon (always via loopback).

Returns a dict or None. The vendored daemon already redacts the access code, but strip it again here so the frontend can never receive it even if the vendor patch is lost in an upstream update.

Source code in octoprint_bambucam/daemon.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def fetch_info(self):
    """GET /?info from the daemon (always via loopback).

    Returns a dict or None. The vendored daemon already redacts the access
    code, but strip it again here so the frontend can never receive it even
    if the vendor patch is lost in an upstream update."""
    port = self._config.get("port")
    if not port:
        return None
    # fixed http://127.0.0.1 loopback URL, not user-controlled
    url = f"http://127.0.0.1:{int(port)}/?info"
    parsed = urllib.parse.urlsplit(url)
    if parsed.scheme != "http" or parsed.hostname != "127.0.0.1":
        return None
    try:
        # scheme/host checked above — no file:// or foreign-host access
        opened = urllib.request.urlopen(url, timeout=3)  # nosec B310
        with opened as response:
            info = json.load(response)
        if isinstance(info.get("config"), dict):
            info["config"].pop("password", None)
        return info
    except (urllib.error.URLError, OSError, ValueError):
        return None

is_running

is_running()

Return True while the daemon process is alive.

Source code in octoprint_bambucam/daemon.py
132
133
134
135
def is_running(self):
    """Return True while the daemon process is alive."""
    process = self._process
    return process is not None and process.poll() is None

port_in_use staticmethod

port_in_use(port, bind_address='127.0.0.1')

Return True if the given port is already bound on the host.

Source code in octoprint_bambucam/daemon.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
@staticmethod
def port_in_use(port, bind_address="127.0.0.1"):
    """Return True if the given port is already bound on the host."""

    try:
        is_wildcard = ipaddress.ip_address(bind_address).is_unspecified
    except ValueError:
        is_wildcard = False
    probe_address = "127.0.0.1" if is_wildcard else bind_address
    probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        probe.bind((probe_address, int(port)))
        return False
    except OSError:
        return True
    finally:
        probe.close()

restart

restart(config=None)

Stop and start again, reusing the last config unless one is given.

Returns (ok, error_message).

Source code in octoprint_bambucam/daemon.py
123
124
125
126
127
128
129
130
def restart(self, config=None):
    """Stop and start again, reusing the last config unless one is given.

    Returns (ok, error_message)."""
    self.stop()
    with self._lock:
        self._restart_timestamps = []
    return self.start(config if config is not None else self._config)

start

start(config)

Start the daemon with the given config dict (see plugin settings).

Returns (ok, error_message).

Source code in octoprint_bambucam/daemon.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def start(self, config):
    """Start the daemon with the given config dict (see plugin settings).

    Returns (ok, error_message)."""

    self.stop()

    with self._lock:
        self._stop_requested = False
        self._config = dict(config)
        self._last_error = None

        error = self._validate(self._config)
        if error:
            self._last_error = error
            return False, error

        ok, error = self._spawn()
        if not ok:
            self._last_error = error
            return False, error

        return True, None

status

status()

Return a snapshot dict of daemon state for the API/frontend.

Source code in octoprint_bambucam/daemon.py
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
def status(self):
    """Return a snapshot dict of daemon state for the API/frontend."""
    with self._lock:
        process = self._process
        running = process is not None and process.poll() is None
        return {
            "running": running,
            "pid": process.pid if running and process else None,
            "uptime": (
                (time.monotonic() - self._started_at)
                if running and self._started_at
                else None
            ),
            "restarts": self._restart_count,
            "last_error": self._last_error,
            "info": self.fetch_info() if running else None,
        }

stop

stop()

Terminate the running daemon (if any) and supersede its watchdog.

Source code in octoprint_bambucam/daemon.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def stop(self):
    """Terminate the running daemon (if any) and supersede its watchdog."""
    with self._lock:
        self._stop_requested = True
        self._generation += 1  # supersede any running watchdog
        process = self._process
        self._process = None

    if process is None or process.poll() is not None:
        return

    process.terminate()
    try:
        process.wait(timeout=5)
    except subprocess.TimeoutExpired:
        self._logger.warning("webcamd did not exit on SIGTERM, killing it")
        process.kill()
        try:
            process.wait(timeout=5)
        except subprocess.TimeoutExpired:
            self._logger.error("webcamd could not be killed")
    self._logger.info("webcamd stopped")
    self._notify("stopped", {})

test_connection staticmethod

test_connection(hostname, access_code, timeout=10.0)

Probe the printer camera port using the §2.2 handshake.

Returns (ok, reason) with reason in ("ok", "unreachable", "auth_failed", "timeout", "error").

Source code in octoprint_bambucam/daemon.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
@staticmethod
def test_connection(hostname, access_code, timeout=10.0):
    """Probe the printer camera port using the §2.2 handshake.

    Returns (ok, reason) with reason in
    ("ok", "unreachable", "auth_failed", "timeout", "error")."""
    username = "bblp"  # fixed Bambu LAN-mode username, not a secret
    auth_data = bytearray()
    auth_data += struct.pack("<I", 0x40)
    auth_data += struct.pack("<I", 0x3000)
    auth_data += struct.pack("<I", 0)
    auth_data += struct.pack("<I", 0)
    auth_data += username.encode("ascii").ljust(32, b"\x00")
    auth_data += access_code.encode("ascii").ljust(32, b"\x00")

    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    ctx.minimum_version = ssl.TLSVersion.TLSv1_2
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE

    try:
        with socket.create_connection(
            (hostname, 6000), timeout=timeout
        ) as sock:
            with ctx.wrap_socket(sock, server_hostname=hostname) as tls:
                tls.settimeout(timeout)
                tls.write(auth_data)
                data = tls.recv(16)
                if len(data) == 0:
                    return False, "auth_failed"
                return True, "ok"
    except socket.timeout:
        return False, "timeout"
    except (ConnectionRefusedError, OSError):
        # OSError also covers ssl.SSLError (a subclass)
        return False, "unreachable"
    except ValueError:
        return False, "error"

options: show_root_heading: true members_order: source

Timelapse operations

Copy/move/delete batches and the .avi → .mp4 transcode, mixed into the plugin.

TimelapseOpsMixin

Timelapse transfer/convert machinery for BambucamPlugin.

options: show_root_heading: true members_order: source

Auto-sync

Pulls the new timelapse after a print, once the printer and OctoPrint are idle.

AutoSyncMixin

Trigger an automatic timelapse pull when a print finishes.

handle_pipeline_status

handle_pipeline_status() -> flask.Response

Return the pipeline busy flag + harvest progress (UI polling).

Source code in octoprint_bambucam/autosync.py
167
168
169
def handle_pipeline_status(self) -> flask.Response:
    """Return the pipeline busy flag + harvest progress (UI polling)."""
    return flask.jsonify(ok=True, pipeline=self._pipeline_snapshot())

note_own_movie

note_own_movie(movie_path: str) -> None

Record a movie path we are about to fire MovieDone for, so the event handler ignores it (otherwise our own copy would look like an OctoPrint render and flip the gate flag).

Source code in octoprint_bambucam/autosync.py
115
116
117
118
119
120
def note_own_movie(self, movie_path: str) -> None:
    """Record a movie path we are about to fire ``MovieDone`` for, so the
    event handler ignores it (otherwise our own copy would look like an
    OctoPrint render and flip the gate flag)."""
    if movie_path:
        self._own_movies.add(os.path.normpath(movie_path))

on_event

on_event(event, payload) -> None

Track OctoPrint's render state and trigger auto-sync on print end.

Source code in octoprint_bambucam/autosync.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def on_event(self, event, payload) -> None:
    """Track OctoPrint's render state and trigger auto-sync on print end."""
    if event == Events.MOVIE_RENDERING:
        if not self._is_own_movie(payload):
            self._octoprint_rendering = True
    elif event in (Events.MOVIE_DONE, Events.MOVIE_FAILED):
        if self._is_own_movie(payload):
            self._forget_own_movie(payload)
        else:
            self._octoprint_rendering = False
    elif event == Events.PRINT_STARTED:
        self._cancel_pending_autosync()
        threading.Thread(
            target=self._snapshot_print_baseline, daemon=True
        ).start()
    elif event == Events.PRINT_DONE:
        self._record_print_date(payload)
        self._on_print_done(payload)

options: show_root_heading: true members_order: source

FTPS client

Implicit-TLS FTPS client for the printer's SD-card timelapses.

BambuTimelapseFtp

BambuTimelapseFtp(logger, hostname: str, access_code: str, *, timeout: int = CONNECT_TIMEOUT)

Lockable, context-managed FTPS service for the printer's timelapses.

One instance manages one connection (the printer allows ~1 at a time). Open it as a context manager (or via open() / close()) and call list_timelapses / download / delete on the open session. All operations are serialized by a per-instance lock.

Source code in octoprint_bambucam/ftp.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def __init__(
    self,
    logger,
    hostname: str,
    access_code: str,
    *,
    timeout: int = CONNECT_TIMEOUT,
):
    self._logger = logger
    self._hostname = hostname
    self._access_code = access_code
    self._timeout = timeout
    self._ftp: Optional[ImplicitFTP_TLS] = None
    self._lock = threading.Lock()

close

close() -> None

Best-effort quit() then close().

Source code in octoprint_bambucam/ftp.py
184
185
186
187
188
189
190
191
192
def close(self) -> None:
    """Best-effort ``quit()`` then ``close()``."""
    if self._ftp is None:
        return
    try:
        self._ftp.quit()
    except (OSError, *ftplib.all_errors):
        self._safe_close(self._ftp)
    self._ftp = None

delete

delete(name: str) -> None

Issue DELE <name> on the open session.

Rejects unsafe names first. Raises on FTP error so the caller can classify/report. The caller (not this method) enforces the §5.9 guards (print-active, confirmation, copy-verified-before-delete).

Source code in octoprint_bambucam/ftp.py
340
341
342
343
344
345
346
347
348
349
350
def delete(self, name: str) -> None:
    """Issue ``DELE <name>`` on the open session.

    Rejects unsafe names first. Raises on FTP error so the caller can
    classify/report. The caller (not this method) enforces the §5.9 guards
    (print-active, confirmation, copy-verified-before-delete).
    """
    _reject_unsafe_name(name)
    with self._lock:
        self._conn.delete(name)
    self._logger.debug("deleted remote %s", name)

download

download(name: str, dest_path: str, *, progress_cb: Optional[Callable[[int, Optional[int]], None]] = None) -> int

Stream RETR <name> to dest_path atomically; return bytes.

Writes to a temp file in the same folder as dest_path (so the final rename is an atomic same-device move), opened with O_EXCL|O_NOFOLLOW so a planted symlink can't redirect the write and an existing file is never clobbered. On any failure the partial temp file is removed. The caller is responsible for building a safe, contained dest_path (see __init__.py / plan §5.7).

progress_cb(transferred, total) is invoked from the chunk callback.

Source code in octoprint_bambucam/ftp.py
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def download(
    self,
    name: str,
    dest_path: str,
    *,
    progress_cb: Optional[Callable[[int, Optional[int]], None]] = None,
) -> int:
    """Stream ``RETR <name>`` to ``dest_path`` atomically; return bytes.

    Writes to a temp file in the **same folder** as ``dest_path`` (so the
    final rename is an atomic same-device move), opened with
    ``O_EXCL|O_NOFOLLOW`` so a planted symlink can't redirect the write and
    an existing file is never clobbered. On any failure the partial temp
    file is removed. The caller is responsible for building a safe,
    contained ``dest_path`` (see ``__init__.py`` / plan §5.7).

    ``progress_cb(transferred, total)`` is invoked from the chunk callback.
    """
    _reject_unsafe_name(name)
    folder = os.path.dirname(dest_path)
    tmp_path = dest_path + ".part"
    total = self.remote_size(name)

    flags = (
        os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
    )
    written = 0
    with self._lock:
        ftp = self._conn
        # Widen the timeout for the transfer only: ftplib passes
        # ``ftp.timeout`` to the passive-mode data connection, and the
        # printer's ~180 KB/s /ipcam link makes a chunk take ~12 min.
        prev_timeout = ftp.timeout
        ftp.timeout = DOWNLOAD_TIMEOUT
        try:
            # RETR with a bare name needs the right cwd; a fresh session
            # starts at "/" and would 550 (observed for /ipcam chunks).
            ftp.cwd(self.LIST_DIR)
            fd = os.open(tmp_path, flags, 0o644)
            with os.fdopen(fd, "wb") as fh:

                def _chunk(data: bytes) -> None:
                    nonlocal written
                    fh.write(data)
                    written += len(data)
                    if progress_cb is not None:
                        progress_cb(written, total)

                ftp.retrbinary(f"RETR {name}", _chunk)
            os.replace(tmp_path, dest_path)
        except Exception:
            self._cleanup(tmp_path)
            raise
        finally:
            ftp.timeout = prev_timeout
    self._logger.debug(
        "downloaded %s (%d bytes) to %s", name, written, folder
    )
    return written

fetch_thumbnail

fetch_thumbnail(name: str) -> Optional[bytes]

Return the JPEG preview bytes for video name, or None.

The printer stores /timelapse/thumbnail/<videostem>.jpg. Streams it into memory (capped at :data:MAX_THUMBNAIL_BYTES). A missing thumbnail is a normal None result, not an error. Rejects unsafe names first.

Source code in octoprint_bambucam/ftp.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def fetch_thumbnail(self, name: str) -> Optional[bytes]:
    """Return the JPEG preview bytes for video ``name``, or ``None``.

    The printer stores ``/timelapse/thumbnail/<videostem>.jpg``. Streams it
    into memory (capped at :data:`MAX_THUMBNAIL_BYTES`). A missing thumbnail
    is a normal ``None`` result, not an error. Rejects unsafe names first.
    """
    _reject_unsafe_name(name)
    stem = name.rsplit(".", 1)[0]
    remote = f"{THUMBNAIL_DIR}/{stem}.jpg"
    buf = bytearray()
    with self._lock:
        ftp = self._conn

        def _chunk(data: bytes) -> None:
            if len(buf) + len(data) > MAX_THUMBNAIL_BYTES:
                raise FtpError("too_large", "thumbnail exceeds cap")
            buf.extend(data)

        try:
            ftp.retrbinary(f"RETR {remote}", _chunk)
        except ftplib.error_temp:
            buf.clear()
            try:
                ftp.retrbinary(f"RETR {remote}", _chunk)
            except ftplib.all_errors:
                return None
        except (ftplib.error_perm, ftplib.error_proto):
            return None
        except FtpError:
            return None
    return bytes(buf)

list_timelapses

list_timelapses() -> list[dict]

Return [{"name", "size", "date"}] for the timelapse videos.

Tries MLSD (size + modify time) first, falls back to NLST + size(). An empty or missing folder is a valid empty result, not an error. Filters to :data:VIDEO_EXTENSIONS. Lists LIST_DIR so subclasses (BambuIpcamFtp) can point at another folder.

Source code in octoprint_bambucam/ftp.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def list_timelapses(self) -> list[dict]:
    """Return ``[{"name", "size", "date"}]`` for the timelapse videos.

    Tries ``MLSD`` (size + modify time) first, falls back to ``NLST`` +
    ``size()``. An empty or missing folder is a valid empty result, not an
    error. Filters to :data:`VIDEO_EXTENSIONS`. Lists ``LIST_DIR`` so
    subclasses (``BambuIpcamFtp``) can point at another folder.
    """
    with self._lock:
        ftp = self._conn
        try:
            ftp.cwd(self.LIST_DIR)
        except ftplib.error_perm:
            return []
        try:
            return self._list_mlsd(ftp)
        except (ftplib.error_perm, ftplib.error_proto):
            return self._list_nlst(ftp)

open

open() -> None

Connect and log in. Idempotent within a batch.

Source code in octoprint_bambucam/ftp.py
145
146
147
148
def open(self) -> None:
    """Connect and log in. Idempotent within a batch."""
    if self._ftp is None:
        self._ftp = self._connect()

remote_size

remote_size(name: str) -> Optional[int]

Return ftp.size(name) for the disk-space pre-check / progress.

Source code in octoprint_bambucam/ftp.py
264
265
266
267
268
269
270
271
def remote_size(self, name: str) -> Optional[int]:
    """Return ``ftp.size(name)`` for the disk-space pre-check / progress."""
    _reject_unsafe_name(name)
    with self._lock:
        try:
            return self._conn.size(name)
        except (ftplib.error_perm, ftplib.error_proto):
            return None

options: show_root_heading: true members_order: source

MQTT client

One-shot MQTT client for the printer's light control.

BambuMqttClient

BambuMqttClient(logger, hostname: str, access_code: str, serial: str, *, timeout: int = CONNECT_TIMEOUT)

One-shot MQTT control client for a single Bambu printer.

Build it with the printer's host/access_code/serial, then call :meth:set_chamber_light. Each call opens its own short-lived connection (the printer tolerates few concurrent clients), serialized per instance.

Source code in octoprint_bambucam/mqtt.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def __init__(
    self,
    logger,
    hostname: str,
    access_code: str,
    serial: str,
    *,
    timeout: int = CONNECT_TIMEOUT,
):
    self._logger = logger
    self._hostname = hostname
    self._access_code = access_code
    self._serial = serial
    self._timeout = timeout
    self._lock = threading.Lock()

set_chamber_light

set_chamber_light(on: bool) -> None

Turn the printer's LED on or off. Raises :class:MqttError.

Source code in octoprint_bambucam/mqtt.py
140
141
142
def set_chamber_light(self, on: bool) -> None:
    """Turn the printer's LED on or off. Raises :class:`MqttError`."""
    self._publish_request(_ledctrl_payload(on))

options: show_root_heading: true members_order: source

MQTT monitor

Standing MQTT connection that tracks the printer's real light state and publishes commands over the same socket. Used only as a fallback when BambuConnector is not the active connection.

BambuMqttMonitor

BambuMqttMonitor(logger, hostname: str, access_code: str, serial: str, on_change: Callable[[Optional[bool]], None])

Long-lived MQTT connection that tracks the printer's light state.

Subscribes to device/{serial}/report, parses the chamber_light state out of each report, and invokes on_change(bool) whenever it changes. Also publishes ledctrl commands over the same connection (:meth:set_chamber_light), so only one socket is ever open.

The connection runs on paho's background loop with automatic reconnect. Start it with :meth:start and always pair it with :meth:stop. The last known state is available via :meth:current_state (None until the first report arrives).

Source code in octoprint_bambucam/mqtt.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
def __init__(
    self,
    logger,
    hostname: str,
    access_code: str,
    serial: str,
    on_change: Callable[[Optional[bool]], None],
):
    self._logger = logger
    self._hostname = hostname
    self._access_code = access_code
    self._serial = serial
    self._on_change = on_change
    self._client: Optional[mqtt.Client] = None
    self._state: Optional[bool] = None
    self._lock = threading.Lock()
    self._req_topic = f"device/{serial}/request"
    self._report_topic = f"device/{serial}/report"

current_state

current_state() -> Optional[bool]

Return the last known chamber-light state, or None if unknown.

Source code in octoprint_bambucam/mqtt.py
230
231
232
233
def current_state(self) -> Optional[bool]:
    """Return the last known chamber-light state, or ``None`` if unknown."""
    with self._lock:
        return self._state

set_chamber_light

set_chamber_light(on: bool) -> None

Publish a ledctrl command over the live connection.

Source code in octoprint_bambucam/mqtt.py
291
292
293
294
295
296
297
298
299
300
301
def set_chamber_light(self, on: bool) -> None:
    """Publish a ledctrl command over the live connection."""
    client = self._client
    if client is None:
        raise MqttError("unreachable", "monitor not connected")
    info = client.publish(
        self._req_topic, json.dumps(_ledctrl_payload(on)), qos=1
    )
    info.wait_for_publish(timeout=CONNECT_TIMEOUT)
    if not info.is_published():
        raise MqttError("publish_failed", "publish not acked")

start

start() -> None

Connect, subscribe to reports, and request a full state dump.

Raises :class:MqttError if the printer is unreachable, the serial is missing, or the access code is rejected.

Source code in octoprint_bambucam/mqtt.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
def start(self) -> None:
    """Connect, subscribe to reports, and request a full state dump.

    Raises :class:`MqttError` if the printer is unreachable, the serial is
    missing, or the access code is rejected.
    """
    if not self._serial:
        raise MqttError("no_serial", "printer serial is required for MQTT")
    if not self._hostname or not self._access_code:
        raise MqttError("unreachable", "missing host or access code")

    connected = threading.Event()
    rc_box: dict = {"rc": None}

    client = _new_client()
    client.username_pw_set(MQTT_USER, self._access_code)
    client.tls_set_context(_build_ssl_context())
    client.reconnect_delay_set(min_delay=1, max_delay=30)

    def on_connect(c, _u, _flags, rc, *_args):
        rc_box["rc"] = int(rc)
        if int(rc) == 0:
            c.subscribe(self._report_topic, qos=0)
            c.publish(
                self._req_topic,
                json.dumps({"pushing": {"command": "pushall"}}),
                qos=0,
            )
        connected.set()

    def on_message(_c, _u, msg):
        self._handle_report(msg.payload)

    client.on_connect = on_connect
    client.on_message = on_message

    try:
        client.connect(self._hostname, MQTT_PORT, keepalive=30)
    except (OSError, ssl.SSLError) as exc:
        raise MqttError("unreachable", str(exc)) from exc

    client.loop_start()
    if not connected.wait(timeout=CONNECT_TIMEOUT):
        self._teardown(client)
        raise MqttError("timeout", "broker did not respond")
    rc = rc_box["rc"]
    if rc == _RC_NOT_AUTHORISED:
        self._teardown(client)
        raise MqttError("auth_failed", "bad access code")
    if rc != 0:
        self._teardown(client)
        raise MqttError("unreachable", f"connect rc={rc}")

    self._client = client
    self._logger.debug("MQTT monitor connected")

stop

stop() -> None

Disconnect and tear down the background loop. Idempotent.

Source code in octoprint_bambucam/mqtt.py
303
304
305
306
307
308
def stop(self) -> None:
    """Disconnect and tear down the background loop. Idempotent."""
    client, self._client = self._client, None
    if client is not None:
        self._teardown(client)
        self._logger.debug("MQTT monitor stopped")

options: show_root_heading: true members_order: source

Connector light path

Drives the light over OctoPrint-BambuConnector's already-open connection (its bpm.BambuPrinter.light_state), avoiding a second socket to the printer's slot-limited broker. The preferred path for light control + state.

connector_led

Drive the printer light through OctoPrint-BambuConnector's connection.

The Bambu A1 mini's local MQTT broker tolerates only ~1-2 connections, and OctoPrint-BambuConnector keeps one open permanently to drive the printer. Opening a second connection from BambuCam therefore fails intermittently with a TLS handshake timeout — which is what the standalone :mod:octoprint_bambucam.mqtt client hits.

When BambuConnector is the active connection we instead drive the light over its already-open connection: it wraps the printer with bambu_printer_manager (bpm), whose BambuPrinter object exposes a light_state property (getter = real state, setter publishes the toggle over the open socket). We reach it through OctoPrint 2.0 internals (printer.current_connection / printer._connection → ConnectedBambuPrinter._client → bpm.BambuPrinter).

Every access is best-effort and defensive: any missing attribute or wrong type means "not available" rather than a crash, so the caller can fall back to the standalone MQTT client.

available

available(printer, logger=None) -> bool

True when the light can be driven via BambuConnector's connection.

Source code in octoprint_bambucam/connector_led.py
110
111
112
def available(printer, logger=None) -> bool:
    """True when the light can be driven via BambuConnector's connection."""
    return _bambu_printer(printer, logger) is not None

current_state

current_state(printer, logger=None) -> Optional[bool]

Return the real light state from BambuConnector, or None.

Reads bpm.BambuPrinter.light_state (a bool). Any missing attribute or error yields None (state unknown).

Source code in octoprint_bambucam/connector_led.py
134
135
136
137
138
139
140
141
142
143
144
145
146
def current_state(printer, logger=None) -> Optional[bool]:
    """Return the real light state from BambuConnector, or ``None``.

    Reads ``bpm.BambuPrinter.light_state`` (a bool). Any missing attribute or
    error yields ``None`` (state unknown).
    """
    client = _bambu_printer(printer, logger)
    if client is None:
        return None
    try:
        return bool(client.light_state)
    except _CONNECTOR_ERRORS:
        return None

set_chamber_light

set_chamber_light(printer, on: bool, logger=None) -> bool

Set the printer light over BambuConnector's connection.

Returns True on success, False when the connector path is unavailable (so the caller can fall back to the standalone client). Never raises.

Source code in octoprint_bambucam/connector_led.py
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def set_chamber_light(printer, on: bool, logger=None) -> bool:
    """Set the printer light over BambuConnector's connection.

    Returns ``True`` on success, ``False`` when the connector path is
    unavailable (so the caller can fall back to the standalone client). Never
    raises.
    """
    client = _bambu_printer(printer, logger)
    if client is None:
        return False
    try:
        client.light_state = bool(on)
        _dbg(logger, "set light_state=%s via connector", bool(on))
        return True
    except _CONNECTOR_ERRORS as exc:  # any failure → fall back to MQTT
        _dbg(logger, "set light_state failed: %r", exc)
        return False

options: show_root_heading: true members_order: source filters: ["!^_"]

Transcoder

Wraps OctoPrint's ffmpeg for the .avi → .mp4 re-encode.

TimelapseTranscoder

TimelapseTranscoder(logger, *, ffmpeg_path: Optional[str], videocodec: str = 'libx264', bitrate: str = '10000k', threads: int = 1, thumbnail_commandline: Optional[str] = None, runner=None)

Re-encode an .avi to .mp4 using OctoPrint's ffmpeg settings.

Construct with the resolved ffmpeg parameters (so the plugin pulls them from self._settings and this class stays unit-testable with a fake runner). ffmpeg_path of None/empty means ffmpeg is not configured and :meth:available is False.

Source code in octoprint_bambucam/transcode.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def __init__(
    self,
    logger,
    *,
    ffmpeg_path: Optional[str],
    videocodec: str = "libx264",
    bitrate: str = "10000k",
    threads: int = 1,
    thumbnail_commandline: Optional[str] = None,
    runner=None,
):
    self._logger = logger
    self._ffmpeg = (ffmpeg_path or "").strip() or None
    self._videocodec = videocodec or "libx264"
    self._bitrate = bitrate or "10000k"
    # 0 = let ffmpeg use all cores; keep it (a plain ``or 1`` would cap the
    # intended 0 to a single core). Only a missing/negative value → 1.
    self._threads = 1 if threads is None or threads < 0 else threads
    self._thumb_cmd = thumbnail_commandline
    self._runner = runner or _run_command  # injection seam for tests

available

available() -> bool

True when ffmpeg is configured (path set in OctoPrint webcam).

Source code in octoprint_bambucam/transcode.py
62
63
64
def available(self) -> bool:
    """True when ffmpeg is configured (path set in OctoPrint webcam)."""
    return self._ffmpeg is not None

create_gcode_thumbnail

create_gcode_thumbnail(src_png: str, thumb_path: str) -> bool

Write thumb_path from a gcode preview PNG; return success.

Scales the slicer plate preview down to a list-friendly size. Best- effort — a failure returns False so the caller can fall back to a video-frame thumbnail.

Source code in octoprint_bambucam/transcode.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def create_gcode_thumbnail(self, src_png: str, thumb_path: str) -> bool:
    """Write ``thumb_path`` from a gcode preview PNG; return success.

    Scales the slicer plate preview down to a list-friendly size. Best-
    effort — a failure returns False so the caller can fall back to a
    video-frame thumbnail.
    """
    if not self.available() or not src_png:
        return False
    cmd = [
        self._ffmpeg,
        "-i",
        src_png,
        "-vf",
        "scale=640:-1",
        "-frames:v",
        "1",
        "-q:v",
        "3",
        "-y",
        thumb_path,
    ]
    try:
        rc, _err = self._runner(cmd, TRANSCODE_TIMEOUT, None)
        return rc == 0 and os.path.isfile(thumb_path)
    except (TranscodeError, OSError, ValueError):
        self._logger.warning("gcode thumbnail failed for %s", src_png)
        return False

create_thumbnail

create_thumbnail(mp4_path: str, thumb_path: str) -> bool

Best-effort <mp4>.thumb.jpg from the last frame.

A timelapse's first frame is an empty bed (a blank white tile in the native Timelapse list); the last frame shows the finished print, which makes a far more useful thumbnail. We therefore grab a frame near the end with our own ffmpeg command (-sseof), independent of whether OctoPrint has an ffmpegThumbnailCommandline configured — on recent OctoPrint that template is often unset, so relying on it produced no thumbnail at all. Returns True on success; a failure is non-fatal.

Source code in octoprint_bambucam/transcode.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def create_thumbnail(self, mp4_path: str, thumb_path: str) -> bool:
    """Best-effort ``<mp4>.thumb.jpg`` from the **last** frame.

    A timelapse's first frame is an empty bed (a blank white tile in the
    native Timelapse list); the last frame shows the finished print, which
    makes a far more useful thumbnail. We therefore grab a frame near the
    end with our own ffmpeg command (``-sseof``), independent of whether
    OctoPrint has an ``ffmpegThumbnailCommandline`` configured — on recent
    OctoPrint that template is often unset, so relying on it produced no
    thumbnail at all. Returns True on success; a failure is non-fatal.
    """
    if not self.available():
        return False
    # -sseof -1: seek to 1 s before the end, then take one frame. Falls back
    # to frame 0 for a clip shorter than the seek offset, still better than
    # nothing. Overwrite (-y) so a re-render refreshes a stale thumbnail.
    cmd = [
        self._ffmpeg,
        "-sseof",
        "-1",
        "-i",
        mp4_path,
        "-frames:v",
        "1",
        "-q:v",
        "3",
        "-y",
        thumb_path,
    ]
    try:
        rc, _err = self._runner(cmd, TRANSCODE_TIMEOUT, None)
        if rc == 0 and os.path.exists(thumb_path):
            return True
        # Some very short/odd clips fail the end-seek; retry from the start.
        cmd_start = [
            self._ffmpeg,
            "-i",
            mp4_path,
            "-frames:v",
            "1",
            "-q:v",
            "3",
            "-y",
            thumb_path,
        ]
        rc, _err = self._runner(cmd_start, TRANSCODE_TIMEOUT, None)
        return rc == 0 and os.path.exists(thumb_path)
    except (TranscodeError, OSError, ValueError):
        self._logger.warning("thumbnail generation failed for %s", mp4_path)
        return False

status

status() -> dict

Report ffmpeg availability for the settings indicator.

configured is True when OctoPrint has an ffmpeg path set; executable additionally checks that the file exists and is runnable (a stale/typo'd path is configured-but-not-executable). path is the configured path (or "") so the UI can show it.

Source code in octoprint_bambucam/transcode.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def status(self) -> dict:
    """Report ffmpeg availability for the settings indicator.

    ``configured`` is True when OctoPrint has an ffmpeg path set;
    ``executable`` additionally checks that the file exists and is runnable
    (a stale/typo'd path is configured-but-not-executable). ``path`` is the
    configured path (or ``""``) so the UI can show it.
    """
    path = self._ffmpeg or ""
    executable = bool(
        path and os.path.isfile(path) and os.access(path, os.X_OK)
    )
    return {
        "path": path,
        "configured": self._ffmpeg is not None,
        "executable": executable,
    }

transcode

transcode(avi_path: str, mp4_path: str, *, progress_cb: Optional[Callable[[int], None]] = None) -> None

Re-encode avi_path → mp4_path (H.264), atomically.

Writes to a temp .part next to mp4_path then renames, so a failed/interrupted run never leaves a half .mp4 behind. Raises :class:TranscodeError on any failure (caller keeps the .avi and reports a warning). progress_cb(percent) is invoked as ffmpeg reports progress (0-100, whole percents).

Source code in octoprint_bambucam/transcode.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def transcode(
    self,
    avi_path: str,
    mp4_path: str,
    *,
    progress_cb: Optional[Callable[[int], None]] = None,
) -> None:
    """Re-encode ``avi_path`` → ``mp4_path`` (H.264), atomically.

    Writes to a temp ``.part`` next to ``mp4_path`` then renames, so a
    failed/interrupted run never leaves a half ``.mp4`` behind. Raises
    :class:`TranscodeError` on any failure (caller keeps the ``.avi`` and
    reports a warning). ``progress_cb(percent)`` is invoked as ffmpeg
    reports progress (0-100, whole percents).
    """
    if not self.available():
        raise TranscodeError("no_ffmpeg", "ffmpeg path not configured")

    tmp_out = mp4_path + ".part"
    cmd = [
        self._ffmpeg,
        "-i",
        avi_path,
        "-c:v",
        self._videocodec,
        "-pix_fmt",
        "yuv420p",
        "-b:v",
        self._bitrate,
        "-threads",
        str(self._threads),
        "-f",
        "mp4",
        "-y",
        tmp_out,
    ]
    try:
        self._exec(cmd, progress_cb=progress_cb)
        if not os.path.exists(tmp_out) or os.path.getsize(tmp_out) == 0:
            raise TranscodeError("empty_output", "ffmpeg produced no data")
        os.replace(tmp_out, mp4_path)
    except TranscodeError:
        self._cleanup(tmp_out)
        raise
    except OSError as exc:
        self._cleanup(tmp_out)
        raise TranscodeError("io_error", str(exc)) from exc
    self._logger.info("transcoded %s -> %s", avi_path, mp4_path)

options: show_root_heading: true members_order: source

Bambu Connector probe

Best-effort discovery of connection data from OctoPrint-BambuConnector.

ConnectorInfo

ConnectorInfo(*, installed: bool = False, hostname: Optional[str] = None, access_code: Optional[str] = None, serial: Optional[str] = None)

What we could discover about the printer from BambuConnector.

available is True only when the plugin is installed and we found at least a host + access code we can reuse. hostname/access_code/ serial may be None individually.

Source code in octoprint_bambucam/bambu_connector.py
31
32
33
34
35
36
37
38
39
40
41
42
def __init__(
    self,
    *,
    installed: bool = False,
    hostname: Optional[str] = None,
    access_code: Optional[str] = None,
    serial: Optional[str] = None,
):
    self.installed = installed
    self.hostname = hostname or None
    self.access_code = access_code or None
    self.serial = serial or None

available property

available: bool

True when there is enough to auto-fill the connection fields.

as_dict

as_dict() -> dict

Serialize for the frontend. The access code is never sent back to the browser as plaintext — only whether one is present.

Source code in octoprint_bambucam/bambu_connector.py
49
50
51
52
53
54
55
56
57
58
def as_dict(self) -> dict:
    """Serialize for the frontend. The access code is never sent back to
    the browser as plaintext — only whether one is present."""
    return {
        "installed": self.installed,
        "available": self.available,
        "hostname": self.hostname or "",
        "serial": self.serial or "",
        "has_access_code": bool(self.access_code),
    }

options: show_root_heading: true members_order: source