import json import requests import sys from configparser import ConfigParser from gpiozero import Button from signal import pause from signal import signal from signal import SIGTERM from threading import Lock threadLock = Lock() stateFile = 'www/garage.json' state = {'east-door': 'opened', 'west-door': 'opened'} config = ConfigParser() config.read('garage.cfg') eastPin = config['garage'].getint('east-pin') westPin = config['garage'].getint('west-pin') ntfy = config['push'].get('ntfy') topic = config['push'].get('topic') def main(): eastButton = Button(eastPin) westButton = Button(westPin) state['east-door'] = 'closed' if eastButton.is_pressed else 'open' state['west-door'] = 'closed' if westButton.is_pressed else 'open' persistState() eastButton.when_pressed = eastDoorClosed eastButton.when_released = eastDoorOpened westButton.when_pressed = westDoorClosed westButton.when_released = westDoorOpened pause() def eastDoorOpened(): with threadLock: state['east-door'] = 'opened' persistState() sendNotification() def eastDoorClosed(): with threadLock: state['east-door'] = 'closed' persistState() sendNotification() def westDoorOpened(): with threadLock: state['west-door'] = 'opened' persistState() sendNotification() def westDoorClosed(): with threadLock: state['west-door'] = 'closed' persistState() sendNotification() def persistState(): with open(stateFile, 'w') as file: json.dump(state, file) def sendNotification(): requests.post( url=f'https://{ntfy}/{topic}', data='update'.encode(encoding='utf-8') ) if __name__ == '__main__': main()