PythonGCodeCompiler/gcode_compiler/gcode.py
2026-11-23 09:04:45 -05:00

182 lines
6.6 KiB
Python

from dataclasses import dataclass
from typing import Callable, ParamSpec, Protocol, TypeVar, Union, cast, runtime_checkable
from . import compiler
compiler_state: compiler.CompilerState
P = ParamSpec('P')
R = TypeVar("R", covariant=True)
@runtime_checkable
class GCodeFunction(Protocol[P, R]):
gcode_call: Callable[P, str|list[str]]
@staticmethod
def __call__(*args: P.args, **kwargs: P.kwargs) -> R:
raise NotImplementedError
@dataclass
class Expression():
expr: str
py: str | None # python representation
def __repr__(self):
return self.py or self.expr
number = int | float
gcode_param = str | number | bool | Expression | list | tuple | None
def gcode_generator(func: Callable[P, str | list]) -> GCodeFunction[P, str | list]:
gcode_func = cast(GCodeFunction[P, str | list], func)
gcode_func.gcode_call = gcode_func
return gcode_func
def gcode_repr(value):
if isinstance(value, number):
str_value = str(value)
elif isinstance(value, str):
str_value = f'"{value}"'
elif isinstance(value, Expression):
str_value = value.expr
elif value is None:
str_value = 'null'
elif isinstance(value, list | tuple):
str_value = '[' + ', '.join([gcode_repr(i) for i in value]) + ']'
else:
raise Exception(f"Tried to convert non-gcode type {type(value)}")
return str_value
def python_value_to_gcode_value(name, obj: gcode_param):
if isinstance(obj, bool):
return (" " + name) if obj else ""
elif isinstance(obj, Expression):
return f" {name}{'{' + obj.expr + '}'}"
elif isinstance(obj, str):
return f" {name}\"{repr(obj)[1:-1]}\""
elif isinstance(obj, number):
return f" {name}{obj}"
elif obj == None:
return ""
# helper function to generate gcode generators
def gcode_instruction(code: str):
def wrapper(func: Callable[P]):
def actual_func(*args: P.args, **kwargs: P.kwargs) -> str:
for idx, param_name in enumerate(func.__code__.co_varnames[:func.__code__.co_argcount]):
if idx < len(args):
param = args[idx]
elif param_name in kwargs:
param = kwargs[param_name]
elif func.__defaults__ and idx < len(func.__defaults__):
param = func.__defaults__[idx]
else:
raise TypeError(f"{func.__name__}() missing required argument {param_name}")
if not isinstance(param, Expression) and param_name in func.__annotations__ and not isinstance(param, func.__annotations__[param_name]):
t = func.__annotations__[param_name]
raise TypeError("Expected '" +
(str(t) if isinstance(t, Union) else t.__name__) +
f"' but got '{type(param).__name__}' for param '{param_name}'")
func(*args, **kwargs)
ret = code
for i, a in enumerate(args):
if not isinstance(a, gcode_param):
raise TypeError("Parameter MUST be one of str, int, float, or bool (for flags)")
elif i < func.__code__.co_argcount:
ret += python_value_to_gcode_value(func.__code__.co_varnames[i].upper(), a)
else:
raise TypeError("Got extra positional argument")
for k,v in kwargs.items():
if not isinstance(v, gcode_param):
raise TypeError("Parameter MUST be one of str, int, float, or bool (for flags)")
ret += python_value_to_gcode_value(k.upper(), v)
ret += f" ; {func.__name__}({', '.join([repr(i) for i in args] + [f"{k}={repr(v)}" for k,v in kwargs.items()])})"
return ret
new_func = gcode_generator(actual_func)
return new_func
return wrapper
@gcode_instruction("G0")
def move(
x:number|None = None,
y:number|None = None,
z:number|None = None,
e:number|None = None,
p:number|None = None,
q:number|None = None,
r:number|None = None,
i:number|None = None,
j:number|None = None,
k:number|None = None,
l:number|None = None
):
"""
Not all parameters need to be used, but at least one has to be used
X: The position to move to on the X axis
Y: The position to move to on the Y axis
Z: The position to move to on the Z axis
E: The amount to extrude between the starting point and ending point
F: The feedrate per minute of the move between the starting point and ending point (if supplied)
H: (RepRapFirmware) Flag to check if an endstop was hit (H1 to check, H0 to ignore, other Hnnn see note, default is H0)
R: (RepRapFirmware) Restore point number
S: Laser cutter/engraver power. In RepRapFirmware, when not in laser mode S in interpreted the same as H.
"""
if x == None and \
y == None and \
z == None and \
e == None and \
p == None and \
q == None and \
r == None and \
i == None and \
j == None and \
k == None and \
l == None:
raise ValueError("Atleast one parameter must be used when calling `move`")
...
@gcode_instruction("G28")
def home(
x:bool = False,
y:bool = False,
z:bool = False,
i:bool = False,
l:bool = False,
n:bool = False,
o:bool = False,
p:bool = False,
r:number = False,
s:bool = False,
w:bool = False,
c:bool = False
):
"""
This command can be used without any additional parameters.
X: Flag to go back to the X axis origin
Y: Flag to go back to the Y axis origin
Z: Flag to go back to the Z axis origin
I: imprecise: do not perform precise refinement
L: Force leveling state ON (if possible) or OFF after homing (Requires `RESTORE_LEVELING_AFTER_G28` or `ENABLE_LEVELING_AFTER_G28`)
N: No-change mode (do not change any motion setting such as feedrate)
O: Home only if the position is not known and trusted
P: Do not check print sheet presence
R: <linear> Raise by n mm/inches before homing
S: Simulated homing only in MARLIN_DEV_MODE
W: Suppress mesh bed leveling if `X`, `Y` or `Z` are not provided
C: Calibrate X and Y origin (home) - Only on MK3/s
"""
...
@gcode_generator
def comment(text: str) -> list[str]:
return ['; ' + i for i in text.split("\n")]
@gcode_generator
def echo(*text) -> str:
return f'echo {", ".join([gcode_repr(i) for i in text])}'
# basically the `input()` function but gcode
@gcode_generator
def gcode_input(msg: str):
return ['M291' + python_value_to_gcode_value('P', msg), 'set global.ret_val = input']