-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp_iot_server.py
More file actions
77 lines (69 loc) · 2.96 KB
/
http_iot_server.py
File metadata and controls
77 lines (69 loc) · 2.96 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
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib import parse
class http_handler(BaseHTTPRequestHandler):
def do_GET(self):
self.route()
def do_POST(self):
self.route()
def route(self):
parsed_path = parse.urlparse(self.path) # 예)self.path: /button?status=on
real_path = parsed_path.path # 예)real.path: /button
if real_path == '/':
self.send_html()
elif real_path == '/button':
self.proc_query()
elif real_path == '/form_get':
self.proc_query()
elif real_path == '/form_post':
self.proc_form_post()
else:
self.response(404, '<h1>Not Found</h1>')
def send_html(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
with open('index_button.html', 'r', encoding='utf-8') as f:
#with open('index_get.html', 'r', encoding='utf-8') as f:
#with open('index_post.html', 'r', encoding='utf-8') as f:
msg = f.read()
self.wfile.write(msg.encode())
def proc_query(self):
parsed_path = parse.urlparse(self.path)
query = parsed_path.query
print(query)
parsed_query = parse.parse_qs(query) # 쿼리 status=on을 {'status': ['on']}으로 파싱
print(parsed_query)
status = parsed_query['status'][0]
if status == 'on':
message = '<h2>LED in IoT Device is now turned on</h2>'
#GP.output(18, 1) # 라즈베리파이 LED 제어 코드
elif status == 'off':
message = '<h2>LED in IoT Device is now turned off</h2>'
#GP.output(18, 0) # 라즈베리파이 LED 제어 코드
else:
message = '<h2>Wrong status</h2>'
self.response(200, message)
def proc_form_post(self):
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length).decode() # HTTP Request의 body 읽기
print(body) # body 내용은 쿼리 status=on(또는 off)
parsed_body = body.split('=') # parsed_body = ['status', 'on']
print(parsed_body)
status = parsed_body[1]
if status == 'on':
message = '<h2>LED in IoT Device is now turned on</h2>'
#GP.output(18, 1) # 라즈베리파이 LED 제어 코드
elif status == 'off':
message = '<h2>LED in IoT Device is now turned off</h2>'
#GP.output(18, 0) # 라즈베리파이 LED 제어 코드
else:
message = '<h2>Wrong status</h2>'
self.response(200, message)
def response(self, status_code, body): # 응답 메시지 전송 함수
self.send_response(status_code)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(body.encode())
httpd = HTTPServer(('localhost', 8080), http_handler)
print('Serving HTTP on {}:{}'.format('localhost', 8080))
httpd.serve_forever()