M118 publish to MQTT

I am working on the integration of my 3D Printer (Mainsailos, Moonraker, Klipper) into my home automation with MQTT (Node-Red). I like to send MQTT messages from GCODE and trigger from there actions in Node-Red.
My current working solution is to listen to M117 (display_text). I would prefer to use GCODE M118, but didn’t find a way to get it published to MQTT. Or to use a gcode for publishing MQTT messages. Anybody has solved this or a similar problem?
TIA Markus

1 Like

it is as simple as this:

add this anywhere to one of your *.cfg

[gcode_macro PUBLISH_ALERT]
gcode:
  {% set data = params.PAYLOAD|default(None) %}
  {action_call_remote_method("publish_mqtt_topic",
                             topic="klipper/gcode",
                             payload=data,
                             qos=0,
                             retain=False,
                             use_prefix=True)}

Then you can use this here to publish a message to your node-red, just change MESSAGEyouWANThere => what I didn’t found out, how to send a variable with this

PUBLISH_ALERT PAYLOAD=MESSAGEyouWANThere

Nice, it might be worthwhile to mention that this needs a Moonraker setup with properly configured MQTT host. Ref Configuration - Moonraker

I thought that would be clear, as @FotoFieber already told us that he is able to get the display_text working :smiley:

but maybe someone can tell me how to publish not just a message with a variable with the PUBLISH_ALERT thing

Something like this?

[gcode_macro MYMESSAGE]
variable_my_msg: None
gcode:
  SET_GCODE_VARIABLE MACRO=MYMESSAGE VARIABLE=my_msg VALUE="'Hello World'"
  send_my_message
  
[gcode_macro MYMESSAGE2]
variable_my_msg: None
gcode:
  SET_GCODE_VARIABLE MACRO=MYMESSAGE VARIABLE=my_msg VALUE={printer.heater_bed.temperature}
  send_my_message

[gcode_macro send_my_message]
gcode:
  {% set temp = printer['gcode_macro MYMESSAGE'].my_msg | string %}
  PUBLISH_ALERT PAYLOAD="{temp}"

Beware:

  • I’m not a Klipper macro wizard
  • Most likely there is a more elegant / more “correct” way
1 Like

works like a charm

vote @Sineos for Klipper macro wizard :slight_smile:

image

EDIT: mhhhh this seems not to work, could you help me out once more?

[gcode_macro M117]
rename_existing: M117.1
variable_my_msg: None
gcode:
  M117.1 { rawparams }
  M118 { rawparams }
  {% if printer["gcode_macro RatOS"].mqtt_alerts|lower == 'true' %}
    SET_GCODE_VARIABLE MACRO=MYMESSAGE VARIABLE=my_msg VALUE={ rawparams }
    send_my_message
  {% endif %}

This leads to this error here:

See, we already reached the end of my macro wizardry :rofl: apart from this, the title is already taken by @mental

To be honest I have no clue. “Traditional style” Gcode commands like M117 are parsed differently to Klipper’s “extended style” macros. The rawparams are kind of a special construct, so I’m not sure if or how this is going to work.