-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_interface.py
More file actions
99 lines (71 loc) · 2.44 KB
/
http_interface.py
File metadata and controls
99 lines (71 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import json
import os
from pathlib import Path
from typing import Dict, Any
from flask import Flask, request
from automation import (
turn_off_everything,
turn_things_back_on,
toggle_office,
toggle_couch,
)
from pyziggy.message_loop import message_loop
app = Flask(__name__)
# Interprets the provided path constituents relative to the location of this
# script, and returns an absolute Path to the resulting location.
#
# E.g. rel_to_py(".") returns an absolute path to the directory containing this
# script.
def rel_to_py(*paths) -> Path:
return Path(
os.path.realpath(
os.path.join(os.path.realpath(os.path.dirname(__file__)), *paths)
)
)
# ==============================================================================
def http_message_handler(payload):
if "action" in payload:
action = payload["action"]
if action == "turn_off_all_lights":
turn_off_everything()
if action == "turn_things_back_on":
turn_things_back_on()
if action == "toggle_office":
toggle_office()
if action == "toggle_couch":
toggle_couch()
# ==============================================================================
def make_html(description: str, commands: list[Dict[Any, Any]]):
raw_template: str | None = None
with open(rel_to_py("http_interface_html_template.html"), "r") as file:
raw_template = file.read()
if raw_template is None:
return ""
result = ""
for line in raw_template.splitlines(keepends=True):
if "$welcome_text" in line:
result += line.replace("$welcome_text", description)
continue
if "$button_text" in line:
for command in commands:
result += line.replace("$button_text", json.dumps(command))
continue
result += line
return result
@app.route("/pyziggy")
def http_pyziggy_help():
commands = [
{"action": "turn_off_all_lights"},
{"action": "turn_things_back_on"},
{"action": "toggle_office"},
{"action": "toggle_couch"},
]
html = make_html("Send commands to <code>/pyziggy/post</code>.", commands)
return html, 200
@app.route("/pyziggy/post", methods=["POST"])
def http_pyziggy_post():
payload = request.get_json()
def message_callback():
http_message_handler(payload)
message_loop.post_message(message_callback)
return "", 200