import os import tempfile from pathlib import Path def convert_to_bgcode(gcode: str, name_part: str, compress: bool = True) -> bytes: """ Converts a G-code string to binary BGCode using the pybgcode library. Returns the binary content of the converted file. """ try: import pybgcode # pyright: ignore[reportMissingImports] except ImportError: raise ImportError("pybgcode library not found. Ensure wheels are correctly integrated.") with tempfile.TemporaryDirectory() as tmpdir: tmp_gcode_path = Path(tmpdir) / (name_part + ".gcode") tmp_bgcode_path = Path(tmpdir) / (name_part + ".bgcode") tmp_gcode_path.write_text(gcode, encoding="utf-8") infile = pybgcode.open(str(tmp_gcode_path), "r") if not infile: raise RuntimeError(f"Failed to open input G-code file: {tmp_gcode_path}") outfile = pybgcode.open(str(tmp_bgcode_path), "wb") if not outfile: pybgcode.close(infile) raise RuntimeError(f"Failed to open output BGCode file: {tmp_bgcode_path}") config = pybgcode.get_config() # Default config from pybgcode usually has MeatPack + Heatshrink enabled. try: res = pybgcode.from_ascii_to_binary(infile, outfile, config) if res != pybgcode.EResult.Success: # pybgcode.translate_result provides a human-readable error message err_msg = pybgcode.translate_result(res) raise RuntimeError(f"bgcode conversion failed: {err_msg}") finally: pybgcode.close(infile) pybgcode.close(outfile) if tmp_bgcode_path.exists(): return tmp_bgcode_path.read_bytes() else: raise FileNotFoundError("Failed to find generated .bgcode file")