commit 93b6e779b5254001626e20132c047155da917954 Author: redfast00 Date: Wed Sep 15 19:48:13 2021 +0200 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8768dd8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,140 @@ +config.py + +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3675c8a --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2021 Zeus WPI + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..a063340 --- /dev/null +++ b/app/__init__.py @@ -0,0 +1 @@ +from app.app import app diff --git a/app/app.py b/app/app.py new file mode 100644 index 0000000..c4f21c8 --- /dev/null +++ b/app/app.py @@ -0,0 +1,71 @@ +import config + +from flask import Flask, request +from multiprocessing import Lock +from multiprocessing.managers import AcquirerProxy, BaseManager, DictProxy +import subprocess +from enum import Enum +import appdirs, argparse +from tradfricoap.config import get_config, host_config, ConfigNotFoundError + +CONFIGFILE = "{0}/gateway.json".format(appdirs.user_config_dir(appname="tradfri")) +CONF = get_config(CONFIGFILE).configuation + +import tradfricoap.device + +ikea_devices, plugs, blinds, groups, others, batteries = get_sorted_devices(groups=True) + +supergroup = next(filter(lambda x: x.Description == "SuperGroup", groups), None) +assert supergroup is not None, "SuperGroup not found" + + + +class LockState(Enum): + LOCKED = '0' + OPEN = '1' + INBETWEEN = '2' + + +def get_shared_state(host, port, key): + shared_dict = {} + shared_lock = Lock() + manager = BaseManager((host, port), key) + manager.register("get_dict", lambda: shared_dict, DictProxy) + manager.register("get_lock", lambda: shared_lock, AcquirerProxy) + try: + manager.get_server() + manager.start() + except OSError: # Address already in use + manager.connect() + return manager.get_dict(), manager.get_lock() + +def kelder_open(): + subprocess.Popen(["cvlc", "--play-and-exit", "--no-loop", "bootup.m4a"]) + supergroup.State = 1 + +def kelder_close(): + subprocess.Popen(["cvlc", "--play-and-exit", "--no-loop", "shutdown.m4a"]) + supergroup.State = 0 + + +app = Flask(__name__) + +shared_dict, shared_lock = get_shared_state("127.0.0.1", 35791, None) + +shared_dict["last_state"] = 'unknown' + +@app.route("/kelderapi/doorkeeper", methods=["POST"]) +def doorkeeper(): + if request.headers.get("Token") != config.doorkeeper_token: + return abort(401) + content = request.get_json() + with shared_lock: + if content['why'] == 'state': + new_lock_state = content['val'] + if new_lock_state != shared_dict['last_state']: + if new_lock_state == LockState.OPEN.value: + kelder_open() + elif new_lock_state == LockState.LOCKED.value: + kelder_close() + shared_dict['last_state'] = new_lock_state + return "OK" diff --git a/bootup.m4a b/bootup.m4a new file mode 100644 index 0000000..1d2e9ff Binary files /dev/null and b/bootup.m4a differ diff --git a/config.py.example b/config.py.example new file mode 100644 index 0000000..e69de29 diff --git a/deploy.sh b/deploy.sh new file mode 100755 index 0000000..57239b0 --- /dev/null +++ b/deploy.sh @@ -0,0 +1,26 @@ +#!/bin/bash +set -eo pipefail + +if (git status --porcelain=2 -uno | grep '' ); then + echo "You have unstaged changes." + echo "This shouldn't happen in production." + echo "Plsfix. Dank." + exit 1 +fi + +echo "Pulling from remote." +git pull + +if [[ config.py.example -nt config.py ]]; then + echo "Example config file is newer than the current config file. Plsfix." + exit 1 +fi + +echo "Updating dependencies." +~/env/bin/pip install -r requirements.txt + +echo "Migrating database." +~/env/bin/flask db upgrade + +echo "Restarting server using passenger." +passenger-config restart-app . diff --git a/passenger_wsgi.py b/passenger_wsgi.py new file mode 100755 index 0000000..1bdb1c1 --- /dev/null +++ b/passenger_wsgi.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 + +import sys +import os + +INTERP = os.path.expanduser("~/env/bin/python3") +if sys.executable != INTERP: + os.execl(INTERP, INTERP, *sys.argv) + +sys.path.append(os.getcwd()) + +from app import app as application diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..37837a8 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +click==8.0.1 +Flask==2.0.1 +itsdangerous==2.0.1 +Jinja2==3.0.1 +MarkupSafe==2.0.1 +Werkzeug==2.0.1 diff --git a/run_dev.py b/run_dev.py new file mode 100755 index 0000000..fb68785 --- /dev/null +++ b/run_dev.py @@ -0,0 +1,4 @@ +#!/usr/bin/env python3 + +from app import app +app.run(debug=True) diff --git a/setup_database.py b/setup_database.py new file mode 100755 index 0000000..d736e97 --- /dev/null +++ b/setup_database.py @@ -0,0 +1,10 @@ +#!/usr/bin/env python3 + +from app.app import db, models + +db.create_all() + +exists = models.User.query.filter_by(username='admin').first() +if not exists: + db.session.add(models.User('admin', admin=True)) + db.session.commit() diff --git a/shutdown.m4a b/shutdown.m4a new file mode 100644 index 0000000..e2ebaa6 Binary files /dev/null and b/shutdown.m4a differ