rfidac.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #! /usr/bin/python3
  2. """
  3. rfid action commander deamon
  4. """
  5. import os
  6. import subprocess
  7. import logging
  8. from shutil import copyfile
  9. from datetime import datetime
  10. from evdev import InputDevice, ecodes
  11. logging.basicConfig(level=logging.DEBUG)
  12. def read_rfid():
  13. combined_string = ""
  14. for event in InputDevice("/dev/input/event0").read_loop():
  15. if event.type == ecodes.EV_KEY and event.value == 0: # value 0 = release key
  16. if event.code == 28: # code 28 = KEY_ENTER
  17. return combined_string
  18. # [4:5]? .. KEY[] starts with 'KEY_' and we expect one char
  19. combined_string += ecodes.KEY[event.code][4:5]
  20. def run_action(script: str):
  21. logging.info(f"RFID action: run {script}")
  22. try:
  23. r = subprocess.call(["/bin/bash", script])
  24. except Exception as err:
  25. logging.info(err)
  26. last_rfid = None
  27. last_rfid = None
  28. last_ts = datetime.now()
  29. while True:
  30. rfid = read_rfid()
  31. seconds_gone = (datetime.now() - last_ts).total_seconds()
  32. script = f"/opt/{rfid}"
  33. if os.path.islink(script): # special RFID - alsways run!
  34. logging.info(f"RFID {rfid} is special. {script} is a link")
  35. run_action(script)
  36. continue
  37. if not os.path.exists(script):
  38. copyfile("/opt/_action_template", script)
  39. logging.info(f"RFID action: empty {script} created from template")
  40. continue
  41. if rfid == last_rfid and seconds_gone <= 5:
  42. logging.info(f"Same RFID after {seconds_gone:.1f} seconds. Do nothing.")
  43. continue
  44. last_ts = datetime.now()
  45. last_rfid = rfid
  46. run_action(script)