-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
111 lines (80 loc) · 3.41 KB
/
server.py
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
100
101
102
103
104
105
106
107
108
109
110
111
"""Main thread which spawns a web server and a browser, and starts the sensor reading thread"""
import io
import os
import sys
import threading
import http.server
import socketserver
import json
import webbrowser
import raspberry
import ota
PORT = 8000
# Write errors to a log file
file_path = './logs/errors.txt'
os.makedirs(os.path.dirname(file_path), exist_ok=True) # Create logs directory if not exist
sys.stderr = open(file_path, 'w')
class Handler(http.server.SimpleHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.end_headers()
def do_POST(self):
"""Handle POST request."""
request_path = self.path
# print("\n----- Request Start ----->\n")
print("request_path: %s", request_path)
request_headers = self.headers
content_length = request_headers.get('content-length')
length = int(content_length) if content_length else 0
json_content_string = self.rfile.read(length)
# print("length :", length)
print("request_headers: %s" % request_headers)
print("content: %s" % json_content_string)
# print("<----- Request End -----\n")
json_content = json.loads(json_content_string) if json_content_string else {} # Dictionary containing data sent in POST request
action = json_content["action"]
payload = json_content["payload"] if "payload" in json_content else None
print("Action: %s" % action)
print("Payload: %s" % payload)
response = raspberry.do_action( action, payload )
json_response_string = json.dumps(response)
self._set_headers()
self.wfile.write(json_response_string.encode(encoding='utf-8'))
def log_message(self, format, *args):
# Overwrite log_message function to prevent logging each request in the error log
#http.server.SimpleHTTPRequestHandler.log_message(self, format, *args)
return
def is_raspberrypi():
"""Check whether this code is running on a Raspberry Pi or not"""
try:
with io.open('/sys/firmware/devicetree/base/model', 'r') as m:
file_content = m.read().lower()
if 'raspberry pi' in file_content: return True
except Exception: pass
return False
def open_browser():
"""Start a browser showing the dashboard after waiting for half a second."""
def _open_browser():
if is_raspberrypi() == True:
os.system('rm -r ~/.cache/chromium/Default/Cache/*') # Clear Chrome cache before opening the browser
os.system('chromium-browser --noerrdialogs --disable-infobars --check-for-update-interval=31536000 --kiosk "http://localhost:%s/" & ' % (PORT))
else:
webbrowser.open('http://localhost:%s/' % (PORT))
thread = threading.Timer(0.5, _open_browser)
thread.start()
def start_server():
"""Start the server."""
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
def init_raspberry():
"""Initialize the Raspberry Pi sensors"""
thread = threading.Timer(0.5, raspberry.init)
thread.start()
if __name__ == "__main__":
"""These functions are run on startup of the Pi"""
ota.run() # Place a hashtag (#) in front of this line to disable over-the-air updates
init_raspberry()
open_browser()
start_server()