-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathhttp_webserver.py
More file actions
81 lines (60 loc) · 2.06 KB
/
Copy pathhttp_webserver.py
File metadata and controls
81 lines (60 loc) · 2.06 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
#!/usr/bin/env python3
import RPi.GPIO as GPIO
import os
from http.server import BaseHTTPRequestHandler, HTTPServer
host_name = '10.0.0.184' # IP Address of Raspberry Pi
host_port = 8000
def setupGPIO():
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18, GPIO.OUT)
def getTemperature():
temp = os.popen("/opt/vc/bin/vcgencmd measure_temp").read()
return temp
class MyServer(BaseHTTPRequestHandler):
def do_HEAD(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def _redirect(self, path):
self.send_response(303)
self.send_header('Content-type', 'text/html')
self.send_header('Location', path)
self.end_headers()
def do_GET(self):
html = '''
<html>
<body
style="width:960px; margin: 20px auto;">
<h1>Welcome to my Raspberry Pi</h1>
<p>Current GPU temperature is {}</p>
<form action="/" method="POST">
Turn LED :
<input type="submit" name="submit" value="On">
<input type="submit" name="submit" value="Off">
</form>
</body>
</html>
'''
temp = getTemperature()
self.do_HEAD()
self.wfile.write(html.format(temp[5:]).encode("utf-8"))
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode("utf-8")
post_data = post_data.split("=")[1]
setupGPIO()
if post_data == 'On':
GPIO.output(18, GPIO.HIGH)
else:
GPIO.output(18, GPIO.LOW)
print("LED is {}".format(post_data))
self._redirect('/') # Redirect back to the root url
# # # # # Main # # # # #
if __name__ == '__main__':
http_server = HTTPServer((host_name, host_port), MyServer)
print("Server Starts - %s:%s" % (host_name, host_port))
try:
http_server.serve_forever()
except KeyboardInterrupt:
http_server.server_close()