1 2 3 4 5 6 7 8 9 10 11 | [Unit] Description=Start USB lamp when video camera is used [Service] ExecStart=/home/cweiske/tools/video-lamp/video-lamp /home/cweiske/tools/video-lamp/lamp-example /dev/video0 Restart=always RestartSec=3 [Install] WantedBy=default.target |
Permission setup:
System service setup:
Create ~/.config/systemd/user/video-lamp.service
Enable and start the service:
$ systemctl --user enable video-lamp.service $ systemctl --user start video-lamp.service $ systemctl --user status video-lamp.service
1 2 3 4 | #dream cheeky usb webmail notifier
# LED sysfs attributes: sysfs files stay root:root by default, so chgrp them
ACTION=="add", SUBSYSTEM=="leds", ATTRS{idVendor}=="1d34", ATTRS{idProduct}=="0004", RUN+="/bin/chgrp -R cweiske %S%p", RUN+="/bin/chmod -R g+w %S%p"
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | #!/bin/sh # Do something when lamp shall be switched on or off if [ "$1" = "on" ]; then echo "lamp on" for ledfile in /sys/class/leds/dream_cheeky*:red/brightness; do echo 63 > $ledfile done else echo "lamp off" for ledfile in /sys/class/leds/dream_cheeky*:red/brightness; do echo 0 > $ledfile done fi |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | #!/bin/bash # Calls a script with "on" when a video device is opened and "off" when # the last user closes it. Event-driven via inotify, no polling. set -u if [[ $# -lt 1 ]]; then echo "Usage: $0 LAMP_SCRIPT [VIDEO_DEVICE]" >&2 exit 2 fi lamp_script=$1 dev=${2:-/dev/video0} if [[ ! -x $lamp_script ]]; then echo "Not an executable script: $lamp_script" >&2 exit 2 fi if [[ ! -e $dev ]]; then echo "Device does not exist: $dev" >&2 exit 2 fi command -v inotifywait >/dev/null || { echo "inotifywait missing (package inotify-tools)" >&2; exit 2; } count=0 state="" # video already open? if command -v fuser >/dev/null; then pids=$(fuser "$dev" 2>/dev/null | wc -w) count=$pids fi apply() { local new=off ((count > 0)) && new=on if [[ $new != "$state" ]]; then state=$new "$lamp_script" "$state" || echo "Lamp script failed for '$state'" >&2 fi } apply wanted() { ((count > 0)) && echo on || echo off; } # Debounce: after an event that would change the lamp state, wait until no # further event arrives for $cooldown seconds before calling the script. cooldown=0.5 pending=0 exec 3< <(inotifywait -m -q -e open -e close --format '%e' "$dev") while true; do if ((pending)); then read -r -t "$cooldown" -u 3 ev; rc=$? else read -r -u 3 ev; rc=$? fi if ((rc > 128)); then # timeout: quiet period elapsed apply pending=0 continue fi # EOF: inotifywait ended ((rc != 0)) && break case $ev in OPEN*) ((count++)) ;; CLOSE*) if ((count > 0)); then ((count--)); fi ;; esac if [[ $(wanted) != "$state" ]]; then pending=1; else pending=0; fi done # inotifywait ended (device removed); exit nonzero so systemd restarts us exit 1 |