julianschill / klipper-led_effect

LED effects plugin for klipper
GNU General Public License v3.0
645 stars 117 forks source link

Set effect on Klipper event #189

Closed cime closed 1 month ago

cime commented 2 months ago

I needed a way to change LED effect when using Danger Klipper's sensorless homing, so I created this module which changes LED effect whenever a Klipper event is triggered. Not sure if something like this belongs to the main LED module or not, but if you see it fit feel free to use or I can create a PR.

Example usage:

[led_effect_event homing_start]
event: homing:home_rails_begin
effect: homing

[led_effect_event homing_end]
event: homing:home_rails_end
effect: idle

led_effect_event.py:

import logging

class LedEffectEvent:
    name = None
    event = None
    effect = None
    stop = True

    def __init__(self, config):
        self.printer = config.get_printer()
        self.gcode = self.printer.lookup_object("gcode")
        self.name = config.get_name()
        self.stop = config.getboolean("stop", True)

        if config.fileconfig.has_option(config.section, "event"):
            self.event = config.get("event")
        else:
            raise self.printer.config_error("LED event %s: event is missing" % self.name)

        if config.fileconfig.has_option(config.section, "effect"):
            self.effect = config.get("effect")
        else:
            raise self.printer.config_error("LED event %s: effect is missing" % self.name)

        self.printer.register_event_handler(self.event, self._handle_event)

    def _handle_event(self, *args, **kwargs):
        logging.info("LED event: %s triggered" % self.event)
        if self.stop:
            self._stopEffects()
        self._startEffects(self.effect)

    def _stopEffects(self):
        self.gcode.run_script_from_command("STOP_LED_EFFECTS")

    def _startEffects(self, effect):
        self.gcode.run_script_from_command("SET_LED_EFFECT EFFECT=%s" % effect)

def load_config_prefix(config):
    return LedEffectEvent(config)
julianschill commented 2 months ago

That's a neat idea, but I am thinking if it wouldn't make more sense to define a gcode instead of an effect. Then it could be used more universally. In that case I also wouldn't add it to LED effect.

julianschill commented 1 month ago

I imagine it like this:

[event homing_start]
event: homing:home_rails_begin
gcode: SET_LED_EFFECT EFFECT=homing