Compare commits

..

7 Commits

Author SHA1 Message Date
b54e372342 0.1.8rc10
reduce settings save by refactoring ams data updates
2024-11-14 21:26:41 -05:00
76f706df19 0.1.8rc9
* check for filename in cache subfolder for files started through cloud connected printers
* send 0% progress when in prepare state and progress is 100
* minor UI tweaks
2024-11-09 21:57:17 -05:00
5c8a9787d4 0.1.8rc8
* updates to pybambu module
* update cloud login workflow, #59
2024-11-09 20:01:41 -05:00
e3fda73dd3 0.1.8rc7
* update pybambu module from upstream HA project, groundwork for fixing new cloud authorization process, #59
* potential fix for stuck progress/canceled printing status, #52
2024-11-09 16:15:13 -05:00
5633d6f6ea groundwork for plate processing contained in 3mf file, will store contents of plate_1.json in OctoPrint metadata for that file 2024-11-04 22:32:52 -05:00
884101c0ba bump version 2024-11-04 14:19:27 -05:00
7c87ba9482 fix base path for start print command for non X1 devices 2024-11-04 14:18:46 -05:00
13 changed files with 438 additions and 167 deletions

View File

@ -8,6 +8,8 @@ from contextlib import contextmanager
import flask
import logging.handlers
from urllib.parse import quote as urlquote
import os
import zipfile
import octoprint.printer
import octoprint.server
@ -59,6 +61,7 @@ class BambuPrintPlugin(
_plugin_manager: octoprint.plugin.PluginManager
_bambu_file_system: RemoteSDCardFileList
_timelapse_files_view: CachedFileView
_bambu_cloud: None
def on_settings_initialized(self):
self._bambu_file_system = RemoteSDCardFileList(self._settings)
@ -106,11 +109,17 @@ class BambuPrintPlugin(
"ams_current_tray": 255,
}
def on_settings_save(self, data):
if data.get("local_mqtt", False) is True:
data["auth_token"] = ""
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
def is_api_adminonly(self):
return True
def get_api_commands(self):
return {"register": ["email", "password", "region", "auth_token"]}
return {"register": ["email", "password", "region", "auth_token"],
"verify": ["auth_type", "password"]}
def on_api_command(self, command, data):
if command == "register":
@ -121,20 +130,57 @@ class BambuPrintPlugin(
and "auth_token" in data
):
self._logger.info(f"Registering user {data['email']}")
bambu_cloud = BambuCloud(
self._bambu_cloud = BambuCloud(
data["region"], data["email"], data["password"], data["auth_token"]
)
bambu_cloud.login(data["region"], data["email"], data["password"])
auth_response = self._bambu_cloud.login(data["region"], data["email"], data["password"])
return flask.jsonify(
{
"auth_token": bambu_cloud.auth_token,
"username": bambu_cloud.username,
"auth_response": auth_response,
}
)
elif command == "verify":
auth_response = None
if (
"auth_type" in data
and "password" in data
and self._bambu_cloud is not None
):
self._logger.info(f"Verifying user {self._bambu_cloud._email}")
if data["auth_type"] == "verifyCode":
auth_response = self._bambu_cloud.login_with_verification_code(data["password"])
elif data["auth_type"] == "tfa":
auth_response = self._bambu_cloud.login_with_2fa_code(data["password"])
else:
self._logger.warning(f"Unknown verification type: {data['auth_type']}")
if auth_response == "success":
return flask.jsonify(
{
"auth_token": self._bambu_cloud.auth_token,
"username": self._bambu_cloud.username
}
)
else:
self._logger.info(f"Error verifying: {auth_response}")
return flask.jsonify(
{
"error": "Unable to verify"
}
)
def on_event(self, event, payload):
if event == Events.TRANSFER_DONE:
self._printer.commands("M20 L T", force=True)
elif event == Events.FILE_ADDED:
if payload["operation"] == "add" and "3mf" in payload["type"]:
file_container = os.path.join(self._settings.getBaseFolder("uploads"), payload["path"])
with zipfile.ZipFile(file_container) as z:
with z.open("Metadata/plate_1.json", "r") as json_data:
plate_data = json.load(json_data)
if plate_data:
self._file_manager.set_additional_metadata("sdcard", payload["path"], "plate_data", plate_data, overwrite=True)
def support_3mf_files(self):
return {"machinecode": {"3mf": ["3mf"]}}

View File

@ -170,22 +170,6 @@ class BambuVirtualPrinter:
def change_state(self, new_state: APrinterState):
self._state_change_queue.put(new_state)
def _convert2serialize(self, obj):
if isinstance(obj, dict):
return {k: self._convert2serialize(v) for k, v in obj.items()}
elif hasattr(obj, "_ast"):
return self._convert2serialize(obj._ast())
elif not isinstance(obj, str) and hasattr(obj, "__iter__"):
return [self._convert2serialize(v) for v in obj]
elif hasattr(obj, "__dict__"):
return {
k: self._convert2serialize(v)
for k, v in obj.__dict__.items()
if not callable(v) and not k.startswith('_')
}
else:
return obj
def new_update(self, event_type):
if event_type == "event_hms_errors":
self._update_hms_errors()
@ -196,7 +180,8 @@ class BambuVirtualPrinter:
device_data = self.bambu_client.get_device()
print_job_state = device_data.print_job.gcode_state
temperatures = device_data.temperature
ams_data = self._convert2serialize(device_data.ams.data)
# strip out extra data to avoid unneeded settings updates
ams_data = [{"tray": asdict(x).pop("tray", None)} for x in device_data.ams.data if x is not None]
if self.ams_data != ams_data:
self._log.debug(f"Recieveid AMS Update: {ams_data}")
@ -286,7 +271,7 @@ class BambuVirtualPrinter:
local_mqtt=self._settings.get_boolean(["local_mqtt"]),
region=self._settings.get(["region"]),
email=self._settings.get(["email"]),
auth_token=self._settings.get(["auth_token"]),
auth_token=self._settings.get(["auth_token"]) if self._settings.get_boolean(["local_mqtt"]) is False else "",
)
bambu_client.on_disconnect = self.on_disconnect(bambu_client.on_disconnect)
bambu_client.on_connect = self.on_connect(bambu_client.on_connect)
@ -345,21 +330,21 @@ class BambuVirtualPrinter:
self._selected_project_file = None
def select_project_file(self, file_path: str) -> bool:
self._log.debug(f"Select project file: {file_path}")
file_info = self._project_files_view.get_file_by_stem(
file_path, [".gcode", ".3mf"]
)
file_info = self._project_files_view.get_file_by_name(file_path)
if (
self._selected_project_file is not None
and file_info is not None
and self._selected_project_file.path == file_info.path
):
self._log.debug(f"File already selected: {file_path}")
return True
if file_info is None:
self._log.error(f"Cannot select non-existent file: {file_path}")
return False
self._log.debug(f"Select project file: {file_path}")
self._selected_project_file = file_info
self._send_file_selected_message()
return True

View File

@ -35,8 +35,8 @@ class CachedFileView:
result: list[FileInfo] = []
with self.file_system.get_ftps_client() as ftp:
for filter in self.folder_view.keys():
result.extend(self.file_system.list_files(*filter, ftp, existing_files))
for key in self.folder_view.keys():
result.extend(self.file_system.list_files(*key, ftp, existing_files))
return result
def update(self):
@ -56,6 +56,9 @@ class CachedFileView:
def get_all_cached_info(self):
return list(self._file_data_cache.values())
def get_keys_as_list(self):
return list(self._file_data_cache.keys()) + list(self._file_alias_cache.keys())
def get_file_data(self, file_path: str | Path) -> FileInfo | None:
file_data = self.get_file_data_cached(file_path)
if file_data is None:
@ -73,22 +76,23 @@ class CachedFileView:
file_path = self._file_alias_cache.get(file_path, file_path)
return self._file_data_cache.get(file_path, None)
def get_file_by_stem(self, file_stem: str, allowed_suffixes: list[str]):
if file_stem == "":
def get_file_by_name(self, file_name: str):
if file_name == "":
return None
file_stem = Path(file_stem).with_suffix("").stem
file_data = self._get_file_by_stem_cached(file_stem, allowed_suffixes)
file_list = self.get_keys_as_list()
if not file_name in file_list:
if f"{file_name}.3mf" in file_list:
file_name = f"{file_name}.3mf"
elif f"{file_name}.gcode.3mf" in file_list:
file_name = f"{file_name}.gcode.3mf"
elif f"cache/{file_name}.3mf" in file_list:
file_name = f"cache/{file_name}.3mf"
elif f"cache/{file_name}.gcode.3mf" in file_list:
file_name = f"cache/{file_name}.gcode.3mf"
file_data = self.get_file_data_cached(file_name)
if file_data is None:
self.update()
file_data = self._get_file_by_stem_cached(file_stem, allowed_suffixes)
return self.get_file_by_name(file_name)
return file_data
def _get_file_by_stem_cached(self, file_stem: str, allowed_suffixes: list[str]):
for file_path_str in list(self._file_data_cache.keys()) + list(self._file_alias_cache.keys()):
file_path = Path(file_path_str)
if file_stem == file_path.with_suffix("").stem and any(
suffix in allowed_suffixes for suffix in file_path.suffixes
):
return self.get_file_data_cached(file_path)
return None

View File

@ -1,5 +1,6 @@
from __future__ import annotations
import asyncio
import queue
import json
import math
@ -36,6 +37,7 @@ class WatchdogThread(threading.Thread):
self._stop_event = threading.Event()
self._last_received_data = time.time()
super().__init__()
self.daemon = True
self.setName(f"{self._client._device.info.device_type}-Watchdog-{threading.get_native_id()}")
def stop(self):
@ -70,6 +72,7 @@ class ChamberImageThread(threading.Thread):
self._client = client
self._stop_event = threading.Event()
super().__init__()
self.daemon = True
self.setName(f"{self._client._device.info.device_type}-Chamber-{threading.get_native_id()}")
def stop(self):
@ -178,7 +181,7 @@ class ChamberImageThread(threading.Thread):
# Reset buffer
img = None
# else:
# else:
# Otherwise we need to continue looping without reseting the buffer to receive the remaining data
# and without delaying.
@ -223,6 +226,7 @@ class MqttThread(threading.Thread):
self._client = client
self._stop_event = threading.Event()
super().__init__()
self.daemon = True
self.setName(f"{self._client._device.info.device_type}-Mqtt-{threading.get_native_id()}")
def stop(self):
@ -233,7 +237,7 @@ class MqttThread(threading.Thread):
exceptionSeen = ""
while True:
try:
host = self._client.host if self._client._local_mqtt else self._client.bambu_cloud.cloud_mqtt_host
host = self._client.host if self._client.local_mqtt else self._client.bambu_cloud.cloud_mqtt_host
LOGGER.debug(f"Connect: Attempting Connection to {host}")
self._client.client.connect(host, self._client._port, keepalive=5)
@ -282,10 +286,10 @@ class BambuClient:
_usage_hours: float
def __init__(self, device_type: str, serial: str, host: str, local_mqtt: bool, region: str, email: str,
username: str, auth_token: str, access_code: str, usage_hours: float = 0, manual_refresh_mode: bool = False):
username: str, auth_token: str, access_code: str, usage_hours: float = 0, manual_refresh_mode: bool = False, chamber_image: bool = True):
self.callback = None
self.host = host
self._local_mqtt = local_mqtt
self.local_mqtt = local_mqtt
self._serial = serial
self._auth_token = auth_token
self._access_code = access_code
@ -299,6 +303,7 @@ class BambuClient:
self._device = Device(self)
self.bambu_cloud = BambuCloud(region, email, username, auth_token)
self.slicer_settings = SlicerSettings(self)
self.use_chamber_image = chamber_image
@property
def connected(self):
@ -319,6 +324,10 @@ class BambuClient:
# Reconnect normally
self.connect(self.callback)
def setup_tls(self):
self.client.tls_set(tls_version=ssl.PROTOCOL_TLS, cert_reqs=ssl.CERT_NONE)
self.client.tls_insecure_set(True)
def connect(self, callback):
"""Connect to the MQTT Broker"""
self.client = mqtt.Client()
@ -329,10 +338,11 @@ class BambuClient:
# Set aggressive reconnect polling.
self.client.reconnect_delay_set(min_delay=1, max_delay=1)
self.client.tls_set(tls_version=ssl.PROTOCOL_TLS, cert_reqs=ssl.CERT_NONE)
self.client.tls_insecure_set(True)
# Run the blocking tls_set method in a separate thread
self.setup_tls()
self._port = 8883
if self._local_mqtt:
if self.local_mqtt:
self.client.username_pw_set("bblp", password=self._access_code)
else:
self.client.username_pw_set(self._username, password=self._auth_token)
@ -369,10 +379,14 @@ class BambuClient:
self._watchdog = WatchdogThread(self)
self._watchdog.start()
if self._device.supports_feature(Features.CAMERA_IMAGE):
LOGGER.debug("Starting Chamber Image thread")
self._camera = ChamberImageThread(self)
self._camera.start()
if not self._device.supports_feature(Features.CAMERA_RTSP):
if self._device.supports_feature(Features.CAMERA_IMAGE):
if self.use_chamber_image:
LOGGER.debug("Starting Chamber Image thread")
self._camera = ChamberImageThread(self)
self._camera.start()
elif (self.host == "") or (self._access_code == ""):
LOGGER.debug("Skipping camera setup as local access details not provided.")
def try_on_connect(self,
client_: mqtt.Client,
@ -396,7 +410,7 @@ class BambuClient:
"""Called when MQTT Disconnects"""
LOGGER.warn(f"On Disconnect: Printer disconnected with error code: {result_code}")
self._on_disconnect()
def _on_disconnect(self):
LOGGER.debug("_on_disconnect: Lost connection to the printer")
self._connected = False
@ -451,9 +465,7 @@ class BambuClient:
LOGGER.debug("Got Version Data")
self._device.info_update(data=json_data.get("info"))
except Exception as e:
LOGGER.error("An exception occurred processing a message:")
LOGGER.error(f"Exception type: {type(e)}")
LOGGER.error(f"Exception data: {e}")
LOGGER.error("An exception occurred processing a message:", exc_info=e)
def subscribe(self):
"""Subscribe to report topic"""
@ -516,9 +528,11 @@ class BambuClient:
self.client.on_disconnect = self.on_disconnect
self.client.on_message = on_message
self.client.tls_set(tls_version=ssl.PROTOCOL_TLS, cert_reqs=ssl.CERT_NONE)
self.client.tls_insecure_set(True)
if self._local_mqtt:
# Run the blocking tls_set method in a separate thread
loop = asyncio.get_event_loop()
await loop.run_in_executor(None, self.setup_tls)
if self.local_mqtt:
self.client.username_pw_set("bblp", password=self._access_code)
else:
self.client.username_pw_set(self._username, password=self._auth_token)

View File

@ -2,36 +2,148 @@ from __future__ import annotations
import base64
import json
import httpx
from curl_cffi import requests
from dataclasses import dataclass
from .const import LOGGER
from .const import (
LOGGER,
BambuUrl
)
from .utils import get_Url
IMPERSONATE_BROWSER='chrome'
@dataclass
class BambuCloud:
def __init__(self, region: str, email: str, username: str, auth_token: str):
self._region = region
self._email = email
self._username = username
self._auth_token = auth_token
self._tfaKey = None
def _get_headers_with_auth_token(self) -> dict:
headers = {}
headers['Authorization'] = f"Bearer {self._auth_token}"
return headers
def _get_authentication_token(self) -> dict:
LOGGER.debug("Getting accessToken from Bambu Cloud")
if self._region == "China":
url = 'https://api.bambulab.cn/v1/user-service/user/login'
else:
url = 'https://api.bambulab.com/v1/user-service/user/login'
headers = {'User-Agent' : "OctoPrint Plugin"}
data = {'account': self._email, 'password': self._password}
with httpx.Client(http2=True) as client:
response = client.post(url, headers=headers, json=data, timeout=10)
if response.status_code >= 400:
LOGGER.debug(f"Received error: {response.status_code}")
raise ValueError(response.status_code)
return response.json()['accessToken']
# First we need to find out how Bambu wants us to login.
data = {
"account": self._email,
"password": self._password,
"apiError": ""
}
response = requests.post(get_Url(BambuUrl.LOGIN, self._region), json=data, impersonate=IMPERSONATE_BROWSER)
if response.status_code >= 400:
LOGGER.error(f"Login attempt failed with error code: {response.status_code}")
LOGGER.debug(f"Response: '{response.text}'")
raise ValueError(response.status_code)
LOGGER.debug(f"Response: {response.status_code}")
auth_json = response.json()
accessToken = auth_json.get('accessToken', '')
if accessToken != '':
# We were provided the accessToken directly.
return accessToken
loginType = auth_json.get("loginType", None)
if loginType is None:
LOGGER.error(f"loginType not present")
LOGGER.error(f"Response not understood: '{response.text}'")
return None
elif loginType == 'verifyCode':
LOGGER.debug(f"Received verifyCode response")
elif loginType == 'tfa':
# Store the tfaKey for later use
LOGGER.debug(f"Received tfa response")
self._tfaKey = auth_json.get("tfaKey")
else:
LOGGER.debug(f"Did not understand json. loginType = '{loginType}'")
LOGGER.error(f"Response not understood: '{response.text}'")
return loginType
def _get_email_verification_code(self):
# Send the verification code request
data = {
"email": self._email,
"type": "codeLogin"
}
LOGGER.debug("Requesting verification code")
response = requests.post(get_Url(BambuUrl.EMAIL_CODE, self._region), json=data, impersonate=IMPERSONATE_BROWSER)
if response.status_code == 200:
LOGGER.debug("Verification code requested successfully.")
else:
LOGGER.error(f"Received error trying to send verification code: {response.status_code}")
LOGGER.debug(f"Response: '{response.text}'")
raise ValueError(response.status_code)
def _get_authentication_token_with_verification_code(self, code) -> dict:
LOGGER.debug("Attempting to connect with provided verification code.")
data = {
"account": self._email,
"code": code
}
response = requests.post(get_Url(BambuUrl.LOGIN, self._region), json=data, impersonate=IMPERSONATE_BROWSER)
LOGGER.debug(f"Response: {response.status_code}")
if response.status_code == 200:
LOGGER.debug("Authentication successful.")
elif response.status_code == 400:
LOGGER.debug(f"Response: '{response.json()}'")
if response.json()['code'] == 1:
# Code has expired. Request a new one.
self._get_email_verification_code()
return 'codeExpired'
elif response.json()['code'] == 2:
# Code was incorrect. Let the user try again.
return 'codeIncorrect'
else:
LOGGER.error(f"Response not understood: '{response.json()}'")
raise ValueError(response.json()['code'])
else:
LOGGER.error(f"Received error trying to authenticate with verification code: {response.status_code}")
LOGGER.debug(f"Response: '{response.text}'")
raise ValueError(response.status_code)
return response.json()['accessToken']
def _get_authentication_token_with_2fa_code(self, code: str) -> dict:
LOGGER.debug("Attempting to connect with provided 2FA code.")
data = {
"tfaKey": self._tfaKey,
"tfaCode": code
}
response = requests.post(get_Url(BambuUrl.TFA_LOGIN, self._region), json=data, impersonate=IMPERSONATE_BROWSER)
LOGGER.debug(f"Response: {response.status_code}")
if response.status_code == 200:
LOGGER.debug("Authentication successful.")
else:
LOGGER.error(f"Received error trying to authenticate with verification code: {response.status_code}")
LOGGER.debug(f"Response: '{response.text}'")
raise ValueError(response.status_code)
cookies = response.cookies.get_dict()
token_from_tfa = cookies.get("token")
LOGGER.debug(f"token_from_tfa: {token_from_tfa}")
return token_from_tfa
def _get_username_from_authentication_token(self) -> str:
# User name is in 2nd portion of the auth token (delimited with periods)
b64_string = self._auth_token.split(".")[1]
@ -40,7 +152,7 @@ class BambuCloud:
jsonAuthToken = json.loads(base64.b64decode(b64_string))
# Gives json payload with "username":"u_<digits>" within it
return jsonAuthToken['username']
# Retrieves json description of devices in the form:
# {
# 'message': 'success',
@ -79,7 +191,7 @@ class BambuCloud:
# }
# ]
# }
def test_authentication(self, region: str, email: str, username: str, auth_token: str) -> bool:
self._region = region
self._email = email
@ -91,23 +203,41 @@ class BambuCloud:
return False
return True
def login(self, region: str, email: str, password: str):
def login(self, region: str, email: str, password: str) -> str:
self._region = region
self._email = email
self._password = password
self._auth_token = self._get_authentication_token()
result = self._get_authentication_token()
if result == 'verifyCode':
return result
elif result == 'tfa':
return result
elif result is None:
LOGGER.error("Unable to authenticate.")
return None
else:
self._auth_token = result
self._username = self._get_username_from_authentication_token()
return 'success'
def login_with_verification_code(self, code: str):
result = self._get_authentication_token_with_verification_code(code)
if result == 'codeExpired' or result == 'codeIncorrect':
return result
self._auth_token = result
self._username = self._get_username_from_authentication_token()
return 'success'
def login_with_2fa_code(self, code: str):
result = self._get_authentication_token_with_2fa_code(code)
self._auth_token = result
self._username = self._get_username_from_authentication_token()
return 'success'
def get_device_list(self) -> dict:
LOGGER.debug("Getting device list from Bambu Cloud")
if self._region == "China":
url = 'https://api.bambulab.cn/v1/iot-service/api/user/bind'
else:
url = 'https://api.bambulab.com/v1/iot-service/api/user/bind'
headers = {'Authorization': 'Bearer ' + self._auth_token, 'User-Agent' : "OctoPrint Plugin"}
with httpx.Client(http2=True) as client:
response = client.get(url, headers=headers, timeout=10)
response = requests.get(get_Url(BambuUrl.BIND, self._region), headers=self._get_headers_with_auth_token(), timeout=10, impersonate=IMPERSONATE_BROWSER)
if response.status_code >= 400:
LOGGER.debug(f"Received error: {response.status_code}")
raise ValueError(response.status_code)
@ -182,18 +312,13 @@ class BambuCloud:
def get_slicer_settings(self) -> dict:
LOGGER.debug("Getting slicer settings from Bambu Cloud")
if self._region == "China":
url = 'https://api.bambulab.cn/v1/iot-service/api/slicer/setting?version=undefined'
else:
url = 'https://api.bambulab.com/v1/iot-service/api/slicer/setting?version=undefined'
headers = {'Authorization': 'Bearer ' + self._auth_token, 'User-Agent' : "OctoPrint Plugin"}
with httpx.Client(http2=True) as client:
response = client.get(url, headers=headers, timeout=10)
response = requests.get(get_Url(BambuUrl.SLICER_SETTINGS, self._region), headers=self._get_headers_with_auth_token(), timeout=10, impersonate=IMPERSONATE_BROWSER)
if response.status_code >= 400:
LOGGER.error(f"Slicer settings load failed: {response.status_code}")
LOGGER.error(f"Slicer settings load failed: '{response.text}'")
return None
return response.json()
# The task list is of the following form with a 'hits' array with typical 20 entries.
#
# "total": 531,
@ -237,20 +362,16 @@ class BambuCloud:
# },
def get_tasklist(self) -> dict:
if self._region == "China":
url = 'https://api.bambulab.cn/v1/user-service/my/tasks'
else:
url = 'https://api.bambulab.com/v1/user-service/my/tasks'
headers = {'Authorization': 'Bearer ' + self._auth_token, 'User-Agent' : "OctoPrint Plugin"}
with httpx.Client(http2=True) as client:
response = client.get(url, headers=headers, timeout=10)
url = get_Url(BambuUrl.TASKS, self._region)
response = requests.get(url, headers=self._get_headers_with_auth_token(), timeout=10, impersonate=IMPERSONATE_BROWSER)
if response.status_code >= 400:
LOGGER.debug(f"Received error: {response.status_code}")
LOGGER.debug(f"Received error: '{response.text}'")
raise ValueError(response.status_code)
return response.json()
def get_latest_task_for_printer(self, deviceId: str) -> dict:
LOGGER.debug(f"Getting latest task from Bambu Cloud for Printer: {deviceId}")
LOGGER.debug(f"Getting latest task from Bambu Cloud")
data = self.get_tasklist_for_printer(deviceId)
if len(data) != 0:
return data[0]
@ -258,7 +379,7 @@ class BambuCloud:
return None
def get_tasklist_for_printer(self, deviceId: str) -> dict:
LOGGER.debug(f"Getting task list from Bambu Cloud for Printer: {deviceId}")
LOGGER.debug(f"Getting task list from Bambu Cloud")
tasks = []
data = self.get_tasklist()
for task in data['hits']:
@ -273,8 +394,7 @@ class BambuCloud:
def download(self, url: str) -> bytearray:
LOGGER.debug(f"Downloading cover image: {url}")
with httpx.Client(http2=True) as client:
response = client.get(url, timeout=10)
response = requests.get(url, timeout=10, impersonate=IMPERSONATE_BROWSER)
if response.status_code >= 400:
LOGGER.debug(f"Received error: {response.status_code}")
raise ValueError(response.status_code)
@ -283,11 +403,11 @@ class BambuCloud:
@property
def username(self):
return self._username
@property
def auth_token(self):
return self._auth_token
@property
def cloud_mqtt_host(self):
return "cn.mqtt.bambulab.com" if self._region == "China" else "us.mqtt.bambulab.com"

View File

@ -27,6 +27,7 @@ class Features(Enum):
CAMERA_IMAGE = 15,
DOOR_SENSOR = 16,
MANUAL_MODE = 17,
AMS_FILAMENT_REMAINING = 18,
class FansEnum(Enum):
@ -1220,3 +1221,19 @@ class Home_Flag_Values(IntEnum):
SUPPORTED_PLUS = 0x08000000,
# Gap
class BambuUrl(Enum):
LOGIN = 1,
TFA_LOGIN = 2,
EMAIL_CODE = 3,
BIND = 4,
SLICER_SETTINGS = 5,
TASKS = 6,
BAMBU_URL = {
BambuUrl.LOGIN: 'https://api.bambulab.com/v1/user-service/user/login',
BambuUrl.TFA_LOGIN: 'https://bambulab.com/api/sign-in/tfa',
BambuUrl.EMAIL_CODE: 'https://api.bambulab.com/v1/user-service/user/sendemail/code',
BambuUrl.BIND: 'https://api.bambulab.com/v1/iot-service/api/user/bind',
BambuUrl.SLICER_SETTINGS: 'https://api.bambulab.com/v1/iot-service/api/slicer/setting?version=undefined',
BambuUrl.TASKS: 'https://api.bambulab.com/v1/user-service/my/tasks',
}

View File

@ -78,7 +78,6 @@ class Device:
send_event = send_event | self.home_flag.print_update(data = data)
if send_event and self._client.callback is not None:
LOGGER.debug("event_printer_data_update")
self._client.callback("event_printer_data_update")
if data.get("msg", 0) == 0:
@ -93,7 +92,7 @@ class Device:
def supports_feature(self, feature):
if feature == Features.AUX_FAN:
return True
return self.info.device_type != "A1" and self.info.device_type != "A1MINI"
elif feature == Features.CHAMBER_LIGHT:
return True
elif feature == Features.CHAMBER_FAN:
@ -124,9 +123,12 @@ class Device:
return self.info.device_type == "X1" or self.info.device_type == "X1C" or self.info.device_type == "X1E"
elif feature == Features.MANUAL_MODE:
return self.info.device_type == "P1P" or self.info.device_type == "P1S" or self.info.device_type == "A1" or self.info.device_type == "A1MINI"
elif feature == Features.AMS_FILAMENT_REMAINING:
# Technically this is not the AMS Lite but that's currently tied to only these printer types.
return self.info.device_type != "A1" and self.info.device_type != "A1MINI"
return False
def get_active_tray(self):
if self.supports_feature(Features.AMS):
if self.ams.tray_now == 255:
@ -177,7 +179,7 @@ class Lights:
self.work_light = \
search(data.get("lights_report", []), lambda x: x.get('node', "") == "work_light",
{"mode": self.work_light}).get("mode")
return (old_data != f"{self.__dict__}")
def TurnChamberLightOn(self):
@ -226,7 +228,7 @@ class Camera:
self.recording = data.get("ipcam", {}).get("ipcam_record", self.recording)
self.resolution = data.get("ipcam", {}).get("resolution", self.resolution)
self.rtsp_url = data.get("ipcam", {}).get("rtsp_url", self.rtsp_url)
return (old_data != f"{self.__dict__}")
@dataclass
@ -253,7 +255,7 @@ class Temperature:
self.chamber_temp = round(data.get("chamber_temper", self.chamber_temp))
self.nozzle_temp = round(data.get("nozzle_temper", self.nozzle_temp))
self.target_nozzle_temp = round(data.get("nozzle_target_temper", self.target_nozzle_temp))
return (old_data != f"{self.__dict__}")
@dataclass
@ -314,7 +316,7 @@ class Fans:
self._cooling_fan_speed_override_time = None
self._heatbreak_fan_speed = data.get("heatbreak_fan_speed", self._heatbreak_fan_speed)
self._heatbreak_fan_speed_percentage = fan_percentage(self._heatbreak_fan_speed)
return (old_data != f"{self.__dict__}")
def set_fan_speed(self, fan: FansEnum, percentage: int):
@ -384,7 +386,7 @@ class PrintJob:
values = {}
for i in range(16):
if self._ams_print_weights[i] != 0:
values[f"AMS Slot {i}"] = self._ams_print_weights[i]
values[f"AMS Slot {i+1}"] = self._ams_print_weights[i]
return values
@property
@ -392,7 +394,7 @@ class PrintJob:
values = {}
for i in range(16):
if self._ams_print_lengths[i] != 0:
values[f"AMS Slot {i}"] = self._ams_print_lengths[i]
values[f"AMS Slot {i+1}"] = self._ams_print_lengths[i]
return values
def __init__(self, client):
@ -450,7 +452,8 @@ class PrintJob:
self.gcode_file = data.get("gcode_file", self.gcode_file)
self.print_type = data.get("print_type", self.print_type)
if self.print_type.lower() not in PRINT_TYPE_OPTIONS:
LOGGER.debug(f"Unknown print_type. Please log an issue : '{self.print_type}'")
if self.print_type != "":
LOGGER.debug(f"Unknown print_type. Please log an issue : '{self.print_type}'")
self.print_type = "unknown"
self.subtask_name = data.get("subtask_name", self.subtask_name)
self.file_type_icon = "mdi:file" if self.print_type != "cloud" else "mdi:cloud-outline"
@ -471,9 +474,7 @@ class PrintJob:
if data.get("mc_remaining_time") is not None:
existing_remaining_time = self.remaining_time
self.remaining_time = data.get("mc_remaining_time")
if self.start_time is None:
self.end_time = None
elif existing_remaining_time != self.remaining_time:
if existing_remaining_time != self.remaining_time:
self.end_time = get_end_time(self.remaining_time)
LOGGER.debug(f"END TIME2: {self.end_time}")
@ -665,7 +666,7 @@ class Info:
self.sw_ver = "unknown"
self.online = False
self.new_version_state = 0
self.mqtt_mode = "local" if self._client._local_mqtt else "bambu_cloud"
self.mqtt_mode = "local" if self._client.local_mqtt else "bambu_cloud"
self.nozzle_diameter = 0
self.nozzle_type = "unknown"
self.usage_hours = client._usage_hours
@ -796,6 +797,12 @@ class Info:
@dataclass
class AMSInstance:
"""Return all AMS instance related info"""
serial: str
sw_version: str
hw_version: str
humidity_index: int
temperature: int
tray: list["AMSTray"]
def __init__(self, client):
self.serial = ""
@ -813,11 +820,14 @@ class AMSInstance:
@dataclass
class AMSList:
"""Return all AMS related info"""
tray_now: int
data: list[AMSInstance]
def __init__(self, client):
self._client = client
self.tray_now = 0
self.data = [None] * 4
self._first_initialization_done = False
def info_update(self, data):
old_data = f"{self.__dict__}"
@ -856,10 +866,10 @@ class AMSList:
index = int(name[4])
elif name.startswith("ams_f1/"):
index = int(name[7])
if index != -1:
# Sometimes we get incomplete version data. We have to skip if that occurs since the serial number is
# requires as part of the home assistant device identity.
# required as part of the home assistant device identity.
if not module['sn'] == '':
# May get data before info so create entries if necessary
if self.data[index] is None:
@ -874,6 +884,9 @@ class AMSList:
if self.data[index].hw_version != module['hw_ver']:
data_changed = True
self.data[index].hw_version = module['hw_ver']
elif not self._first_initialization_done:
self._first_initialization_done = True
data_changed = True
data_changed = data_changed or (old_data != f"{self.__dict__}")
@ -969,6 +982,19 @@ class AMSList:
@dataclass
class AMSTray:
"""Return all AMS tray related info"""
empty: bool
idx: int
name: str
type: str
sub_brands: str
color: str
nozzle_temp_min: int
nozzle_temp_max: int
remain: int
k: float
tag_uid: str
tray_uuid: str
def __init__(self, client):
self._client = client
@ -982,7 +1008,8 @@ class AMSTray:
self.nozzle_temp_max = 0
self.remain = 0
self.k = 0
self.tag_uid = "0000000000000000"
self.tag_uid = ""
self.tray_uuid = ""
def print_update(self, data) -> bool:
old_data = f"{self.__dict__}"
@ -998,7 +1025,8 @@ class AMSTray:
self.nozzle_temp_min = 0
self.nozzle_temp_max = 0
self.remain = 0
self.tag_uid = "0000000000000000"
self.tag_uid = ""
self.tray_uuid = ""
self.k = 0
else:
self.empty = False
@ -1011,8 +1039,9 @@ class AMSTray:
self.nozzle_temp_max = data.get('nozzle_temp_max', self.nozzle_temp_max)
self.remain = data.get('remain', self.remain)
self.tag_uid = data.get('tag_uid', self.tag_uid)
self.tray_uuid = data.get('tray_uuid', self.tray_uuid)
self.k = data.get('k', self.k)
return (old_data != f"{self.__dict__}")
@ -1081,7 +1110,7 @@ class Speed:
self._id = int(data.get("spd_lvl", self._id))
self.name = get_speed_name(self._id)
self.modifier = int(data.get("spd_mag", self.modifier))
return (old_data != f"{self.__dict__}")
def SetSpeed(self, option: str):
@ -1133,7 +1162,7 @@ class HMSList:
self._count = 0
self._errors = {}
self._errors["Count"] = 0
def print_update(self, data) -> bool:
# Example payload:
# "hms": [
@ -1172,14 +1201,14 @@ class HMSList:
if self._client.callback is not None:
self._client.callback("event_hms_errors")
return True
return False
@property
def errors(self) -> dict:
#LOGGER.debug(f"PROPERTYCALL: get_hms_errors")
return self._errors
@property
def error_count(self) -> int:
return self._count
@ -1191,18 +1220,19 @@ class PrintErrorList:
_count: int
def __init__(self, client):
self._error = None
self._count = 0
self._client = client
self._error = {}
def print_update(self, data) -> bool:
# Example payload:
# "print_error": 117473286
# "print_error": 117473286
# So this is 07008006 which we make more human readable to 0700-8006
# https://e.bambulab.com/query.php?lang=en
# 'Unable to feed filament into the extruder. This could be due to entangled filament or a stuck spool. If not, please check if the AMS PTFE tube is connected.'
if 'print_error' in data.keys():
errors = {}
errors = None
print_error_code = data.get('print_error')
if print_error_code != 0:
hex_conversion = f'0{int(print_error_code):x}'
@ -1219,11 +1249,11 @@ class PrintErrorList:
# We send the error event directly so always return False for the general data event.
return False
@property
def error(self) -> dict:
return self._error
@property
def on(self) -> int:
return self._error is not None
@ -1232,6 +1262,8 @@ class PrintErrorList:
@dataclass
class HMSNotification:
"""Return an HMS object and all associated details"""
attr: int
code: int
def __init__(self, attr: int = 0, code: int = 0):
self.attr = attr
@ -1267,10 +1299,10 @@ class ChamberImage:
def set_jpeg(self, bytes):
self._bytes = bytes
def get_jpeg(self) -> bytearray:
return self._bytes.copy()
@dataclass
class CoverImage:
"""Returns the cover image from the Bambu API"""
@ -1285,7 +1317,7 @@ class CoverImage:
def set_jpeg(self, bytes):
self._bytes = bytes
self._image_last_updated = datetime.now()
def get_jpeg(self) -> bytearray:
return self._bytes
@ -1298,7 +1330,7 @@ class HomeFlag:
"""Contains parsed _values from the homeflag sensor"""
_value: int
_sw_ver: str
_device_type: str
_device_type: str
def __init__(self, client):
self._value = 0
@ -1327,7 +1359,7 @@ class HomeFlag:
def door_open_available(self) -> bool:
if not self._client._device.supports_feature(Features.DOOR_SENSOR):
return False
if (self._device_type in ["X1", "X1C"] and version.parse(self._sw_ver) < version.parse("01.07.00.00")):
return False
@ -1336,7 +1368,7 @@ class HomeFlag:
@property
def x_axis_homed(self) -> bool:
return (self._value & Home_Flag_Values.X_AXIS) != 0
@property
def y_axis_homed(self) -> bool:
return (self._value & Home_Flag_Values.Y_AXIS) != 0
@ -1372,7 +1404,7 @@ class HomeFlag:
@property
def sdcard_normal(self) -> bool:
return self.sdcard_present and (self._value & Home_Flag_Values.HAS_SDCARD_ABNORMAL) != SdcardState.HAS_SDCARD_ABNORMAL
@property
def ams_auto_switch_filament(self) -> bool:
return (self._value & Home_Flag_Values.AMS_AUTO_SWITCH) != 0
@ -1388,11 +1420,11 @@ class HomeFlag:
@property
def supports_motor_noise_calibration(self) -> bool:
return (self._value & Home_Flag_Values.SUPPORTS_MOTOR_CALIBRATION) != 0
@property
def p1s_upgrade_supported(self) -> bool:
return (self._value & Home_Flag_Values.SUPPORTED_PLUS) != 0
@property
def p1s_upgrade_installed(self) -> bool:
return (self._value & Home_Flag_Values.INSTALLED_PLUS) != 0
@ -1417,7 +1449,7 @@ class SlicerSettings:
def update(self):
self.custom_filaments = {}
if self._client.bambu_cloud.auth_token != "":
if self._client.bambu_cloud.auth_token != "" and self._client.local_mqtt is False:
LOGGER.debug("Loading slicer settings")
slicer_settings = self._client.bambu_cloud.get_slicer_settings()
if slicer_settings is not None:

View File

@ -12,6 +12,7 @@ from .const import (
HMS_MODULES,
LOGGER,
FansEnum,
BAMBU_URL
)
from .commands import SEND_GCODE_TEMPLATE
@ -59,8 +60,8 @@ def get_filament_name(idx, custom_filaments: dict):
result = FILAMENT_NAMES.get(idx, "unknown")
if result == "unknown" and idx != "":
result = custom_filaments.get(idx, "unknown")
if result == "unknown" and idx != "":
LOGGER.debug(f"UNKNOWN FILAMENT IDX: '{idx}'")
# if result == "unknown" and idx != "":
# LOGGER.debug(f"UNKNOWN FILAMENT IDX: '{idx}'")
return result
@ -225,3 +226,10 @@ def round_minute(date: datetime = None, round_to: int = 1):
date = date.replace(second=0, microsecond=0)
delta = date.minute % round_to
return date.replace(minute=date.minute - delta)
def get_Url(url: str, region: str):
urlstr = BAMBU_URL[url]
if region == "China":
urlstr = urlstr.replace('.com', '.cn')
return urlstr

View File

@ -25,7 +25,7 @@ class IdleState(APrinterState):
filesystem_root = (
"file:///mnt/sdcard/"
if self._printer._settings.get(["device_type"]) in ["X1", "X1C"]
else "file:///"
else "file:///sdcard/"
)
print_command = {

View File

@ -22,7 +22,7 @@ class PrintingState(APrinterState):
def __init__(self, printer: BambuVirtualPrinter) -> None:
super().__init__(printer)
self._current_print_job = None
self._printer.current_print_job = None
self._is_printing = False
self._sd_printing_thread = None
@ -40,12 +40,15 @@ class PrintingState(APrinterState):
self._printer.current_print_job = None
def _start_worker_thread(self):
self._is_printing = True
if self._sd_printing_thread is None:
self._is_printing = True
self._sd_printing_thread = threading.Thread(target=self._printing_worker)
self._sd_printing_thread.start()
else:
self._sd_printing_thread.join()
def _printing_worker(self):
self._log.debug(f"_printing_worker before while loop: {self._printer.current_print_job}")
while (
self._is_printing
and self._printer.current_print_job is not None
@ -55,6 +58,7 @@ class PrintingState(APrinterState):
self._printer.report_print_job_status()
time.sleep(3)
self._log.debug(f"_printing_worker after while loop: {self._printer.current_print_job}")
self.update_print_job_info()
if (
self._printer.current_print_job is not None
@ -64,17 +68,21 @@ class PrintingState(APrinterState):
def update_print_job_info(self):
print_job_info = self._printer.bambu_client.get_device().print_job
task_name: str = print_job_info.subtask_name
project_file_info = self._printer.project_files.get_file_by_stem(
task_name, [".gcode", ".3mf"]
)
subtask_name: str = print_job_info.subtask_name
gcode_file: str = print_job_info.gcode_file
self._log.debug(f"update_print_job_info: {print_job_info}")
project_file_info = self._printer.project_files.get_file_by_name(subtask_name) or self._printer.project_files.get_file_by_name(gcode_file)
if project_file_info is None:
self._log.debug(f"No 3mf file found for {print_job_info}")
self._current_print_job = None
self._printer.current_print_job = None
self._printer.change_state(self._printer._state_idle)
return
progress = print_job_info.print_percentage
if print_job_info.gcode_state == "PREPARE" and progress == 100:
progress = 0
self._printer.current_print_job = PrintJob(project_file_info, progress, print_job_info.remaining_time, print_job_info.current_layer, print_job_info.total_layers)
self._printer.select_project_file(project_file_info.path.as_posix())

View File

@ -20,6 +20,16 @@ $(function () {
self.job_info = ko.observable();
self.auth_type = ko.observable("");
self.show_password = ko.pureComputed(function(){
return self.settingsViewModel.settings.plugins.bambu_printer.auth_token() === '';
});
self.show_verification = ko.pureComputed(function(){
return self.auth_type() !== '';
});
self.ams_mapping_computed = function(){
var output_list = [];
var index = 0;
@ -40,16 +50,34 @@ $(function () {
self.getAuthToken = function (data) {
self.settingsViewModel.settings.plugins.bambu_printer.auth_token("");
self.auth_type("");
OctoPrint.simpleApiCommand("bambu_printer", "register", {
"email": self.settingsViewModel.settings.plugins.bambu_printer.email(),
"password": $("#bambu_cloud_password").val(),
"region": self.settingsViewModel.settings.plugins.bambu_printer.region(),
"auth_token": self.settingsViewModel.settings.plugins.bambu_printer.auth_token()
})
.done(function (response) {
self.auth_type(response.auth_response);
});
};
self.verifyCode = function (data) {
self.settingsViewModel.settings.plugins.bambu_printer.auth_token("");
OctoPrint.simpleApiCommand("bambu_printer", "verify", {
"password": $("#bambu_cloud_verify_code").val(),
"auth_type": self.auth_type(),
})
.done(function (response) {
console.log(response);
self.settingsViewModel.settings.plugins.bambu_printer.auth_token(response.auth_token);
self.settingsViewModel.settings.plugins.bambu_printer.username(response.username);
if (response.auth_token) {
self.settingsViewModel.settings.plugins.bambu_printer.auth_token(response.auth_token);
self.settingsViewModel.settings.plugins.bambu_printer.username(response.username);
self.auth_type("");
} else if (response.error) {
self.settingsViewModel.settings.plugins.bambu_printer.auth_token("");
$("#bambu_cloud_verify_code").val("");
}
});
};

View File

@ -40,15 +40,24 @@
<div class="control-group" data-bind="visible: !settingsViewModel.settings.plugins.bambu_printer.local_mqtt()">
<label class="control-label">{{ _('Email') }}</label>
<div class="controls">
<input type="text" class="input-block-level" data-bind="value: settingsViewModel.settings.plugins.bambu_printer.email" title="{{ _('Registered email address') }}"></input>
<input type="text" class="input-block-level" data-bind="value: settingsViewModel.settings.plugins.bambu_printer.email" title="{{ _('Registered email address') }}" autocomplete="off"></input>
</div>
</div>
<div class="control-group" data-bind="visible: !settingsViewModel.settings.plugins.bambu_printer.local_mqtt()">
<div class="control-group" data-bind="visible: !settingsViewModel.settings.plugins.bambu_printer.local_mqtt() && show_password()">
<label class="control-label">{{ _('Password') }}</label>
<div class="controls">
<div class="input-block-level input-append" data-bind="css: {'input-append': !show_verification()}">
<input id="bambu_cloud_password" type="password" class="input-text input-block-level" title="{{ _('Password to generate verification code') }}" autocomplete="new-password"></input>
<span class="btn btn-primary add-on" data-bind="visible: !show_verification(), click: getAuthToken">{{ _('Login') }}</span>
</div>
</div>
</div>
<div class="control-group" data-bind="visible: show_verification()">
<label class="control-label">{{ _('Verify') }}</label>
<div class="controls">
<div class="input-block-level input-append">
<input id="bambu_cloud_password" type="password" class="input-text input-block-level" title="{{ _('Password to generate Auth Token') }}"></input>
<span class="btn btn-primary add-on" data-bind="click: getAuthToken">{{ _('Login') }}</span>
<input id="bambu_cloud_verify_code" type="password" class="input-text input-block-level" title="{{ _('Verification code to generate auth token') }}"></input>
<span class="btn btn-primary add-on" data-bind="click: verifyCode">{{ _('Verify') }}</span>
</div>
</div>
</div>

View File

@ -14,7 +14,7 @@ plugin_package = "octoprint_bambu_printer"
plugin_name = "OctoPrint-BambuPrinter"
# The plugin's version. Can be overwritten within OctoPrint's internal data via __plugin_version__ in the plugin module
plugin_version = "0.1.8rc5"
plugin_version = "0.1.8rc10"
# The plugin's description. Can be overwritten within OctoPrint's internal data via __plugin_description__ in the plugin
# module
@ -33,7 +33,7 @@ plugin_url = "https://github.com/jneilliii/OctoPrint-BambuPrinter"
plugin_license = "AGPLv3"
# Any additional requirements besides OctoPrint should be listed here
plugin_requires = ["paho-mqtt<2", "python-dateutil", "httpx[http2]>=0.27.0"]
plugin_requires = ["paho-mqtt<2", "python-dateutil", "curl_cffi"]
### --------------------------------------------------------------------------------------------------------------------
### More advanced options that you usually shouldn't have to touch follow after this point