跳转至

# 命令模板

本文档描述了 gcode_macro（和其他类似）配置分段中实现 G-Code 命令序列的方法。

## G 代码宏命名

G-Code 宏的名称大小写并不重要。比如，MY_MACRO 和 my_macro 是等效的，可以用大写或小写来调用。如果在宏的名称中使用任何数字，那么它们必须都在名称的末尾（例如，TEST_MACRO25是合法的，但MACRO25_TEST3是不合法的）。

## 配置中 G 代码的格式

在配置文件中定义一个宏时需要注意缩进。在定义多行的G代码序列时每行都要有适当的缩进。例如：

    [gcode_macro blink_led]
    gcode:
      SET_PIN PIN=my_led VALUE=1
      G4 P2000
      SET_PIN PIN=my_led VALUE=0

请注意，`gcode:` 配置选项总是从行首开始，而 G-Code 宏中的后续行从不从行首开始。

## 向宏添加描述

可以通过添加 `description:` 和简短的描述来帮助理解该功能。如果没有指定，默认为"G-Code macro"。例如：

    [gcode_macro blink_led]
    description: Blink my_led one time
    gcode:
      SET_PIN PIN=my_led VALUE=1
      G4 P2000
      SET_PIN PIN=my_led VALUE=0

The terminal will display the description when you use the `HELP` command or the autocomplete function.

## 保存/恢复 G-Code 移动的状态

不幸的是，G-Code 命令语言在使用上有些难度。移动工具头的标准机制是通过 `G1` 命令（`G0` 命令是 `G1` 的别名，它们互换使用）。然而，这个命令依赖于由`M82`、`M83`、`G90`、`G91`、`G92`, 以及先前的`G1`命令所设置的"G-Code解析状态"。在创建 G-Code 宏时，最好在发出`G1`命令之前，先明确 G-Code 解析状态。(否则，`G1` 命令就有可能提出一个不符合预期的请求。）

实现这一目标的常见方法是将 `G1` 移动包装在 `SAVE_GCODE_STATE`、`G91`和`RESTORE_GCODE_STATE`中。例如：

    [gcode_macro MOVE_UP]
    gcode:
      SAVE_GCODE_STATE NAME=my_move_up_state
      G91
      G1 Z10 F300
      RESTORE_GCODE_STATE NAME=my_move_up_state

`G91` 命令将G代码解析状态放入 "相对移动模式"，`RESTORE_GCODE_STATE` 命令将状态恢复到进入宏之前的状态。请确保在第一条`G1` 命令中指定一个明确的速度（通过`F` 参数）。

## 模板扩展

gcode_macro`gcode:` 配置部分是使用的是Jinja2模板语言。人们可以通过用`{ }` 字符包装来在运行时使用表达式，或者使用用`{% %}` 包装的条件语句。参考Jinja2文档以了解更多关于语法的信息。

一个更复杂的宏示例：

    [gcode_macro clean_nozzle]
    gcode:
      {% set wipe_count = 8 %}
      SAVE_GCODE_STATE NAME=clean_nozzle_state
      G90
      G0 Z15 F300
      {% for wipe in range(wipe_count) %}
        {% for coordinate in [(275, 4),(235, 4)] %}
          G0 X{coordinate[0]} Y{coordinate[1] + 0.25 * wipe} Z9.7 F12000
        {% endfor %}
      {% endfor %}
      RESTORE_GCODE_STATE NAME=clean_nozzle_state

### 宏观参数

当macro被调用时，检查传递给它的参数往往是有用的。这些参数可以通过`params` 伪变量（pseudo-variable）获得。类似于以下macro：

    [gcode_macro SET_PERCENT]
    gcode:
      M117 Now at { params.VALUE|float * 100 }%

如果以`SET_PERCENT VALUE=.2` 的方式调用，则会评估为`M117 现在为 20%` 。需要注意的是在宏（macro）中进行评估时，参数名称始终使用大写字母，并且始终以字符串（strings）形式传递。如果执行数学运算，则必须明确地将其转换为整数（integers）或浮点数（floats）。

通常使用Jinja2的`set` 指令来使用一个默认参数，并将结果分配给一个本地名称。比如说：

    [gcode_macro SET_BED_TEMPERATURE]
    gcode:
      {% set bed_temp = params.TEMPERATURE|default(40)|float %}
      M140 S{bed_temp}

### The "rawparams" variable

The full unparsed parameters for the running macro can be access via the `rawparams` pseudo-variable.

This is quite useful if you want to change the behavior of certain commands like the `M117`. For example:

    [gcode_macro M117]
    rename_existing: M117.1
    gcode:
      {% if rawparams %}
        {% set escaped_msg = rawparams|replace('"', '\\"') %}
        SET_DISPLAY_TEXT MSG="{escaped_msg}"
        RESPOND TYPE=command MSG="{escaped_msg}"
      {% else %}
        SET_DISPLAY_TEXT
      {% endif %}

### "printer"变量

可以通过`printer` 的pseudo-variable来检查（和变更）打印机的当前状态。比如说：

    [gcode_macro slow_fan]
    gcode:
      M106 S{ printer.fan.speed * 0.9 * 255}

Status Reference 文档中定义了可用字段。

Important! Macros are first evaluated in entirety and only then are the resulting commands executed. If a macro issues a command that alters the state of the printer, the results of that state change will not be visible during the evaluation of the macro. This can also result in subtle behavior when a macro generates commands that call other macros, as the called macro is evaluated when it is invoked (which is after the entire evaluation of the calling macro).

By convention, the name immediately following `printer` is the name of a config section. So, for example, `printer.fan` refers to the fan object created by the `[fan]` config section. There are some exceptions to this rule - notably the `gcode_move` and `toolhead` objects. If the config section contains spaces in it, then one can access it via the `[ ]` accessor - for example: `printer["generic_heater my_chamber_heater"].temperature`.

Note that the Jinja2 `set` directive can assign a local name to an object in the `printer` hierarchy. This can make macros more readable and reduce typing. For example:

    [gcode_macro QUERY_HTU21D]
    gcode:
        {% set sensor = printer["htu21d my_sensor"] %}
        M117 Temp:{sensor.temperature} Humidity:{sensor.humidity}

## Actions

There are some commands available that can alter the state of the printer. For example, `{ action_emergency_stop() }` would cause the printer to go into a shutdown state. Note that these actions are taken at the time that the macro is evaluated, which may be a significant amount of time before the generated g-code commands are executed.

Available "action" commands:

- `action_respond_info(msg)`: Write the given `msg` to the /tmp/printer pseudo-terminal. Each line of `msg` will be sent with a "// " prefix.
- `action_raise_error(msg)`: Abort the current macro (and any calling macros) and write the given `msg` to the /tmp/printer pseudo-terminal. The first line of `msg` will be sent with a "!! " prefix and subsequent lines will have a "// " prefix.
- `action_emergency_stop(msg)`: Transition the printer to a shutdown state. The `msg` parameter is optional, it may be useful to describe the reason for the shutdown.
- `action_call_remote_method(method_name)`: Calls a method registered by a remote client. If the method takes parameters they should be provided via keyword arguments, ie: `action_call_remote_method("print_stuff", my_arg="hello_world")`

## Variables

The SET_GCODE_VARIABLE command may be useful for saving state between macro calls. Variable names may not contain any upper case characters. For example:

    [gcode_macro start_probe]
    variable_bed_temp: 0
    gcode:
      # Save target temperature to bed_temp variable
      SET_GCODE_VARIABLE MACRO=start_probe VARIABLE=bed_temp VALUE={printer.heater_bed.target}
      # Disable bed heater
      M140
      # Perform probe
      PROBE
      # Call finish_probe macro at completion of probe
      finish_probe

    [gcode_macro finish_probe]
    gcode:
      # Restore temperature
      M140 S{printer["gcode_macro start_probe"].bed_temp}

Be sure to take the timing of macro evaluation and command execution into account when using SET_GCODE_VARIABLE.

## Delayed Gcodes

The [delayed_gcode] configuration option can be used to execute a delayed gcode sequence:

    [delayed_gcode clear_display]
    gcode:
      M117

    [gcode_macro load_filament]
    gcode:
     G91
     G1 E50
     G90
     M400
     M117 Load Complete!
     UPDATE_DELAYED_GCODE ID=clear_display DURATION=10

When the `load_filament` macro above executes, it will display a "Load Complete!" message after the extrusion is finished. The last line of gcode enables the "clear_display" delayed_gcode, set to execute in 10 seconds.

The `initial_duration` config option can be set to execute the delayed_gcode on printer startup. The countdown begins when the printer enters the "ready" state. For example, the below delayed_gcode will execute 5 seconds after the printer is ready, initializing the display with a "Welcome!" message:

    [delayed_gcode welcome]
    initial_duration: 5.
    gcode:
      M117 Welcome!

Its possible for a delayed gcode to repeat by updating itself in the gcode option:

    [delayed_gcode report_temp]
    initial_duration: 2.
    gcode:
      {action_respond_info("Extruder Temp: %.1f" % (printer.extruder0.temperature))}
      UPDATE_DELAYED_GCODE ID=report_temp DURATION=2

The above delayed_gcode will send "// Extruder Temp: [ex0_temp]" to Octoprint every 2 seconds. This can be canceled with the following gcode:

    UPDATE_DELAYED_GCODE ID=report_temp DURATION=0

## Menu templates

If a display config section is enabled, then it is possible to customize the menu with menu config sections.

The following read-only attributes are available in menu templates:

- `menu.width` - element width (number of display columns)
- `menu.ns` - element namespace
- `menu.event` - name of the event that triggered the script
- `menu.input` - input value, only available in input script context

The following actions are available in menu templates:

- `menu.back(force, update)`: will execute menu back command, optional boolean parameters `<force>` and `<update>`.
  - When `<force>` is set True then it will also stop editing. Default value is False.
  - When `<update>` is set False then parent container items are not updated. Default value is True.
- `menu.exit(force)` - will execute menu exit command, optional boolean parameter `<force>` default value False.
  - When `<force>` is set True then it will also stop editing. Default value is False.

## Save Variables to disk

If a save_variables config section has been enabled, `SAVE_VARIABLE VARIABLE=<name> VALUE=<value>` can be used to save the variable to disk so that it can be used across restarts. All stored variables are loaded into the `printer.save_variables.variables` dict at startup and can be used in gcode macros. to avoid overly long lines you can add the following at the top of the macro:

    {% set svv = printer.save_variables.variables %}

As an example, it could be used to save the state of 2-in-1-out hotend and when starting a print ensure that the active extruder is used, instead of T0:

    [gcode_macro T1]
    gcode:
      ACTIVATE_EXTRUDER extruder=extruder1
      SAVE_VARIABLE VARIABLE=currentextruder VALUE='"extruder1"'

    [gcode_macro T0]
    gcode:
      ACTIVATE_EXTRUDER extruder=extruder
      SAVE_VARIABLE VARIABLE=currentextruder VALUE='"extruder"'

    [gcode_macro START_GCODE]
    gcode:
      {% set svv = printer.save_variables.variables %}
      ACTIVATE_EXTRUDER extruder={svv.currentextruder}

回到页面顶部