Skip to content

Reading the switches

Mark Niemann-Ross edited this page Jan 18, 2017 · 4 revisions

Reading the Vent, Heat and Light switch

This should be simplicity itself. In box_controls.py I pull 3 volts from the ATX power supply, feed it through the switch, then run it to GPIO pins on the Raspberry Pi. I'm not using zener diodes to limit the voltage because I trust the voltage coming out of the power supply is clean.

But I want to have the switches generate an interrupt, which I'll then catch with a handler to do something interesting. After some trial-and-error (much trial and error!) I've managed to get the following architecture to work:

  • switch_obj.py contains a class - boxSwitch which instantiates for each switch. This implies three objects: one for each switch. The class includes methods for getting the state of the switch (binary) and for setting a callback for GPIO.add_event_detect.
  • LightVentHeatirq.py is run in the background by fish_config.sh in /etc/init.d . This instantiates the boxSwitch objects, defines the callback functions and then sets a while True: loop to keep the python shell active.

I learned that GPIO.add_event_detect only lives as long as the containing thread. Stating that makes it seem obvious - but it was difficult to track that down when debugging with sudo journalctl and functions initiated at startup.

I'm also finding some issues with accessing sqlite across threads. This shows up because I am using BmBB.fishSays() to speak the state of the switch. I've added check_same_thread=False to dbconnect = sqlite3.connect(pathToDB, check_same_thread=False) and this seems to have fixed it - but it introduces the threat that I might corrupt the sqlite database because I am writing to it across multiple threads. The sqlite documentation says that if I write to the database across threads, I'm responsible for serializing writes. I'm going explore removing multiple thread access to see if it was something that doesn't need to be fixed...