Skip to content

Instantly share code, notes, and snippets.

@A6GibKm
Created July 19, 2020 00:39
Show Gist options
  • Save A6GibKm/9bb1ead82b20b99e3579bc2eeb71d87e to your computer and use it in GitHub Desktop.
Save A6GibKm/9bb1ead82b20b99e3579bc2eeb71d87e to your computer and use it in GitHub Desktop.
Manage your pi-hole with asyncio and GPIOs.
#!/usr/bin/env python3
"""
Manage your pi-hole with asyncio and GPIOs.
"""
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
import pihole as ph
import atexit
import sys
import asyncio
import keyring
from keyrings.alt.file import PlaintextKeyring
# PiHole
pihole_addr = "PIHOLE_ADDR"
time_limit = 30 # Disable for at most 30 seconds
pihole_password = "PIHOLE_PASSWORD" # Set the password for first use
## GPIO setup
red = 7 # Red using pin 7
green = 15 # Green using pin 15
blue = 12 # Blue using pin 12
## Async
loop = None
timer = None
# Timer
bouncetime = 500 # in ms
class Timer:
def __init__(self, timeout, callback):
self._timeout = timeout
self._callback = callback
self._task = asyncio.ensure_future(self._job())
async def _job(self):
await asyncio.sleep(self._timeout)
await self._callback()
def cancel(self):
self._task.cancel()
async def timeout_callback():
pihole.enable()
GPIO.output(blue, GPIO.LOW)
def button_pushed(pin):
if loop is None:
print("Loop ended")
return # should not come to this
if pin == green:
loop.call_soon_threadsafe(green_action)
if pin == red:
loop.call_soon_threadsafe(red_action)
def red_action():
print("Red button was pushed!")
GPIO.output(blue, GPIO.HIGH)
pihole.disable(time_limit)
timer = Timer(time_limit, timeout_callback)
def green_action():
print("Green button was pushed!")
if timer is not None:
timer.cancel()
GPIO.output(blue, GPIO.LOW)
pihole.enable()
def exit_handler():
print('py-hole-ui closed')
GPIO.cleanup()
pihole.enable()
loop.close()
# Get password
keyring.set_keyring(PlaintextKeyring())
password = keyring.get_password("pihole", pihole_addr)
if password is None:
keyring.set_password("pihole", pihole_addr, pihole_password)
password = pihole_password
# Pihole
pihole = ph.PiHole(pihole_addr)
pihole.authenticate(password)
version = pihole.getVersion()['core_current']
status = pihole.status
print("Runing pihole", version)
print("Status:", pihole.status)
# GPIO
try:
GPIO.setwarnings(True) # Set warnings
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
# Set pins to input/output
GPIO.setup(red, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(green, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(blue, GPIO.OUT)
GPIO.add_event_detect(
green, GPIO.RISING, callback=button_pushed, bouncetime=bouncetime,
)
GPIO.add_event_detect(
red, GPIO.RISING, callback=button_pushed, bouncetime=bouncetime,
)
atexit.register(exit_handler)
loop = asyncio.get_event_loop()
loop.run_forever()
except:
print("Error:", sys.exc_info()[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment