Skip to content

Instantly share code, notes, and snippets.

@emre
Created July 24, 2020 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emre/90531b4a501182da62e0207889a0ec12 to your computer and use it in GitHub Desktop.
Save emre/90531b4a501182da62e0207889a0ec12 to your computer and use it in GitHub Desktop.
Restart modem plug if internet is down
import logging
from phue import Bridge
import requests
import time
import sys
logging.basicConfig(filename="/home/pi/scripts/connectivity_logs.txt",
filemode='a',
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
datefmt='%H:%M:%S',
level=logging.INFO)
# Configuration
PLUG_ID = 3
DECONZ_HOST = 'localhost:8090'
logger = logging.getLogger('connectivity')
logger.info("Running Connectivity Check")
def is_internet_up():
try:
r = requests.head("https://google.nl")
return True
except Exception as e:
return False
def activate_plug(bridge, plug):
logger.info("Activating plug")
bridge.set_light(PLUG_ID, 'on', True)
def deactivate_plug(bridge, plug):
logger.info("Deactivating plug")
bridge.set_light(PLUG_ID, 'on', False)
def main():
b = Bridge(DECONZ_HOST)
b.connect()
plug_state = b.get_light(PLUG_ID).get("state", {}).get("on")
logger.info("Plug state is %s" % ("on" if plug_state else "off"))
if not plug_state:
activate_plug(b, PLUG_ID)
sys.exit()
internet_state = is_internet_up()
logger.info("Internet state: %s" % ("up" if internet_state else "down"))
if not internet_state:
deactivate_plug(b, PLUG_ID)
logger.info("Sleeping for 60 seconds")
time.sleep(60)
activate_plug(b, PLUG_ID)
plug_state = b.get_light(PLUG_ID).get("state", {}).get("on")
logger.info("Current state of the plug: %s" %
("on" if plug_state else "off"))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment