garage/garage.py

80 lines
1.7 KiB
Python

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')
ntfyList = json.loads(config['push'].get('ntfy'))
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():
for ntfy in ntfyList:
requests.post(
url=f'https://{ntfy["host"]}/{ntfy["topic"]}?auth={ntfy["auth"]}',
data='update'.encode(encoding='utf-8')
)
if __name__ == '__main__':
main()