Initial commit

This commit is contained in:
redfast00 2021-09-15 19:48:13 +02:00
commit 93b6e779b5
No known key found for this signature in database
GPG Key ID: 5946E0E34FD0553C
12 changed files with 292 additions and 0 deletions

140
.gitignore vendored Normal file
View File

@ -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/

22
LICENSE Normal file
View File

@ -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.

1
app/__init__.py Normal file
View File

@ -0,0 +1 @@
from app.app import app

71
app/app.py Normal file
View File

@ -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"

BIN
bootup.m4a Normal file

Binary file not shown.

0
config.py.example Normal file
View File

26
deploy.sh Executable file
View File

@ -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 .

12
passenger_wsgi.py Executable file
View File

@ -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

6
requirements.txt Normal file
View File

@ -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

4
run_dev.py Executable file
View File

@ -0,0 +1,4 @@
#!/usr/bin/env python3
from app import app
app.run(debug=True)

10
setup_database.py Executable file
View File

@ -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()

BIN
shutdown.m4a Normal file

Binary file not shown.