Motion lights outside the G-code queue (extras/motion_lights.py)

The AM312 case light and nozzle LEDs waited for long commands (heat waits,
AFC loads, QGL) because [gcode_button] runs through the G-code queue. The
new module reads the pin itself, keeps the timeout on a reactor timer and
sets the case light with output_pin's send_async_request and the nozzle
LEDs directly on the led_effect object. CASELIGHT and _LIGHTS_ON keep
working; _STATUS_SHOW reads printer.motion_lights.near.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mangavalkandClaude Opus 5.5 committed 2026-11-02 00:35:26 +01:00
1 parent 55b04a7cef
commit f25f348d0b
4 files changed
+269 -100

No files matched your search

+245
View File
@@ -0,0 +1,245 @@
# Case light and nozzle LEDs from a PIR motion sensor, outside the G-code
# queue.
#
# [gcode_button] runs its press/release G-code through the G-code queue, so
# the lights waited for whatever command was running (M109/M190 heat waits,
# heat soak, AFC loads and cuts, QGL, mesh, purge check). This module reads
# the sensor pin itself, keeps the timeout on its own reactor timer and sets
# the lights directly:
# case light - output_pin's send_async_request (the path Klipper's own
# SET_PIN TEMPLATE= uses): not tied to the G-code queue or
# the move queue
# nozzle LEDs - led_effect's set_enabled/set_fade_time, as SET_LED_EFFECT
# does; led_effect animates on its own reactor timer
# Only the optional status_gcode (logo night mode) goes through the G-code
# queue, from a reactor callback, so it can lag without holding up the light.
#
# The AM312 keeps its output on as long as it sees movement: press = motion,
# release = no more motion. The timeout starts at the release.
#
# someone near: case light near_value, nozzle LEDs on
# nobody near, print/pause: case light print_value, nozzle LEDs off
# nobody near, idle: case light idle_value, nozzle LEDs off
#
# Install: link to ~/klipper/klippy/extras/motion_lights.py (install.sh);
# needs a Klipper service restart, not just RESTART.
#
# Config (replaces [gcode_button am312] - one pin cannot be used twice):
# [motion_lights]
# pin: !PC0
# light: caselight # [output_pin caselight]
# nozzle_effect: sb_nozzle_light # [led_effect sb_nozzle_light]; optional
# timeout: 60 # s without motion before dimming
# near_value: 1.0
# print_value: 0.1
# idle_value: 0.0
# on_value: 1.0 # CASELIGHT MODE=ON without VALUE
# fade_time: 0.5 # nozzle LED fade (s)
# status_gcode: _STATUS # run when 'near' changes; optional
# startup_delay: 2 # s after ready: lights on as after motion
#
# Commands:
# CASELIGHT [MODE=AUTO|ON|OFF] [VALUE=0-1] no MODE: report the state
# _LIGHTS_ON lights on as if someone walked by (print start/end, resume)
# MOTION_LIGHTS_DEBUG [ENABLE=0|1] report every change
#
# Status (printer.motion_lights): mode, present, near, motion (sensor pin),
# value (the case light value last set by this module), timeout, on_value.
#
# The desired light is applied only when it changes, so a value set with
# SET_PIN in Mainsail lasts until the next change (motion, timeout or print
# state), as before.
import logging
POLL_TIME = 1.0
class MotionLights:
def __init__(self, config):
self.printer = printer = config.get_printer()
self.reactor = printer.get_reactor()
self.light_name = config.get('light', 'caselight')
self.effect_name = config.get('nozzle_effect', None)
self.timeout = config.getfloat('timeout', 60., minval=0.)
self.near_value = config.getfloat('near_value', 1., minval=0., maxval=1.)
self.print_value = config.getfloat('print_value', 0.1, minval=0.,
maxval=1.)
self.idle_value = config.getfloat('idle_value', 0., minval=0., maxval=1.)
self.on_value = config.getfloat('on_value', 1., minval=0., maxval=1.)
self.fade_time = config.getfloat('fade_time', 0.5, minval=0.)
self.status_gcode = config.get('status_gcode', None)
self.startup_delay = config.getfloat('startup_delay', 2., minval=0.)
self.mode = 'auto'
self.present = False
self.near = False
self.motion = False
self.off_time = self.reactor.NEVER
self.applied = None # (value, lit) last applied
self.ready = False
self.debug = False
self.light = self.effect = self.print_stats = None
self.timer = None
buttons = printer.load_object(config, 'buttons')
buttons.register_debounce_button(config.get('pin'),
self._button_callback, config)
self.gcode = printer.lookup_object('gcode')
self.gcode.register_command('CASELIGHT', self.cmd_CASELIGHT,
desc=self.cmd_CASELIGHT_help)
self.gcode.register_command('_LIGHTS_ON', self.cmd_LIGHTS_ON,
desc=self.cmd_LIGHTS_ON_help)
self.gcode.register_command('MOTION_LIGHTS_DEBUG',
self.cmd_MOTION_LIGHTS_DEBUG,
desc=self.cmd_MOTION_LIGHTS_DEBUG_help)
printer.register_event_handler('klippy:connect', self._handle_connect)
printer.register_event_handler('klippy:ready', self._handle_ready)
def _handle_connect(self):
# Missing objects are a config error: raising here (connect, not a
# runtime callback) stops Klipper with a clear message
self.light = self.printer.lookup_object('output_pin ' + self.light_name)
if self.effect_name:
self.effect = self.printer.lookup_object(
'led_effect ' + self.effect_name)
self.print_stats = self.printer.lookup_object('print_stats', None)
def _handle_ready(self):
self.timer = self.reactor.register_timer(
self._poll, self.reactor.monotonic() + self.startup_delay)
# Sensor and timeout -------------------------------------------------
def _button_callback(self, eventtime, state):
# Runs in the reactor; must never raise
try:
self.motion = bool(state)
if state:
self.present = True
self.off_time = self.reactor.NEVER
else:
self.off_time = self.reactor.monotonic() + self.timeout
self._update()
except Exception:
logging.exception("motion_lights: button callback")
def _wake(self):
self.present = True
self.off_time = (self.reactor.NEVER if self.motion
else self.reactor.monotonic() + self.timeout)
self._update()
def _poll(self, eventtime):
try:
if not self.ready:
self.ready = True # first run, startup_delay after ready
self._wake()
if self.present and eventtime >= self.off_time:
self.present = False
self.off_time = self.reactor.NEVER
self._update()
except Exception:
logging.exception("motion_lights: poll")
return eventtime + POLL_TIME
# Applying -----------------------------------------------------------
def _busy(self):
if self.print_stats is None:
return False
try:
state = self.print_stats.get_status(
self.reactor.monotonic())['state']
except Exception:
return False
return state in ('printing', 'paused')
def _desired(self):
if self.mode == 'on':
return self.on_value, True
if self.mode == 'off':
return 0., False
if self.present:
return self.near_value, True
return (self.print_value if self._busy() else self.idle_value), False
def _update(self):
if not self.ready or self.printer.is_shutdown():
return
value, lit = self._desired()
if (value, lit) == self.applied:
return
self.applied = (value, lit)
if self.debug:
self._respond("Lights: mode=%s present=%s busy=%s: case light %.2f,"
" nozzle %s" % (self.mode, self.present, self._busy(),
value, 'on' if lit else 'off'))
try:
self.light.gcrq.send_async_request(value / self.light.scale)
except Exception:
logging.exception("motion_lights: setting %s", self.light_name)
if self.effect is not None:
try:
if self.effect.enabled != lit:
self.effect.set_fade_time(self.fade_time)
self.effect.set_enabled(lit)
except Exception:
logging.exception("motion_lights: setting %s", self.effect_name)
if self.near != lit:
self.near = lit
if self.status_gcode:
self.reactor.register_callback(self._run_status_gcode)
def _run_status_gcode(self, eventtime):
# Waits for the G-code queue in its own reactor greenlet
try:
self.gcode.run_script(self.status_gcode)
except Exception:
logging.exception("motion_lights: status_gcode")
def _respond(self, msg):
try:
self.gcode.respond_info(msg)
except Exception:
pass
# Commands -----------------------------------------------------------
cmd_CASELIGHT_help = ("Case light and nozzle LEDs: MODE=AUTO (motion"
" sensor), ON [VALUE=0-1] or OFF; no MODE: show the"
" mode")
def cmd_CASELIGHT(self, gcmd):
mode = gcmd.get('MODE', '').lower()
if not mode:
gcmd.respond_info(
"Case light: mode %s, %s, value %.2f"
% (self.mode, 'someone near' if self.present else 'nobody near',
self.light.get_status(None)['value'] * self.light.scale))
return
if mode not in ('auto', 'on', 'off'):
raise gcmd.error("CASELIGHT: MODE must be AUTO, ON or OFF")
value = gcmd.get_float('VALUE', None)
if value is not None:
self.on_value = min(max(value, 0.), 1.)
self.mode = mode
self.applied = None # apply even if the value is unchanged
self._update()
cmd_LIGHTS_ON_help = "Lights on as if someone walked by"
def cmd_LIGHTS_ON(self, gcmd):
self._wake()
cmd_MOTION_LIGHTS_DEBUG_help = "Report every motion light change"
def cmd_MOTION_LIGHTS_DEBUG(self, gcmd):
self.debug = bool(gcmd.get_int('ENABLE', 1))
gcmd.respond_info("motion_lights debug %s"
% ('on' if self.debug else 'off'))
def get_status(self, eventtime):
value = self.applied[0] if self.applied else 0.
return {'mode': self.mode, 'present': self.present, 'near': self.near,
'motion': self.motion, 'value': value,
'timeout': self.timeout, 'on_value': self.on_value}
def load_config(config):
return MotionLights(config)