import json import requests from configparser import ConfigParser from gpiozero import Button from signal import pause from threading import Lock threadLock = Lock() stateFile = 'www/garage.json' state = {'east-door': 'init', 'west-door': 'init'} 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') auth = config['push'].get('auth') 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}?auth={auth}', data='update'.encode(encoding='utf-8') ) if __name__ == '__main__': main()