from flask import Flask, render_template, request from os import system import subprocess app = Flask(__name__) def check_app_states(apps): for app in apps: if not 'default' in app: app['default'] = False if 'state_cmd' in app and len(app['state_cmd']) > 0: if 'state_expect' in app: try: result = subprocess.run(app['state_cmd'], shell=True, check=True) print(result) if result.stdout == app['state_expect']: app['default'] = not app['default'] if result.stdout == app['state_expect'] else app['default'] except subprocess.CalledProcessError: continue # continue with default, current state could not be determined else: exitcode = system(app['state_cmd']) if exitcode == 0: app['default'] = not app['default'] if exitcode == 0 else app['default'] return apps @app.route("/") def index(): if request.args.get('cmd') is not None: exitcode = system(request.args.get('cmd')) if exitcode == 0: return "Command was run", 200 else: return "Command failed (exit code {0})".format(exitcode), 500 templateData = { 'is_local': True if request.remote_addr == "127.0.0.1" else False, 'apps': [ { 'name': 'clock', 'cmd': 'espeak "$text"' }, { 'name': 'toggle', 'text_on': 'ON', 'text_off': 'OFF', 'cmd_on': 'espeak "on"', 'cmd_off': 'espeak "off"', 'cooldown': 3000 }, { 'name': 'toggle', 'text_on': '🔊', 'text_off': '🔇', 'default': False, 'cmd_on': 'mpg123 ~/tng_viewscreen_on.mp3', 'cmd_off': 'mpg123 ~/tng_viewscreen_off.mp3', 'cooldown': 1000, 'show_cooldown': False }, { 'name': 'toggle', 'text_on': 'file exist', 'text_off': 'file gone', 'default': False, 'cmd_on': 'touch ~/testfile.tmp', 'cmd_off': 'rm ~/testfile.tmp', 'state_cmd': 'test -f ~/testfile.tmp', 'cooldown': 1000, 'show_cooldown': False } ] } templateData['apps'] = check_app_states(templateData['apps']) return render_template('index.html', **templateData) @app.route("/configure") def configure(): return render_template('configure.html') if __name__ == "__main__": app.run(host='0.0.0.0', port=8081, debug=True)