-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPIface2Control.py
108 lines (91 loc) · 3.83 KB
/
PIface2Control.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
"""
simplewebcontrol.py
Controls PiFace Digital through a web browser. Returns the status of the
input port and the output port in a JSON string. Set the output with GET
variables.
Copyright (C) 2013 Thomas Preston <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import sys
import subprocess
import http.server
import urllib.parse
import pifacedigitalio
JSON_FORMAT = "{{'input_port': {input}, 'output_port': {output}}}"
DEFAULT_PORT = 8000
OUTPUT_PORT_GET_STRING = "output_port"
GET_IP_CMD = "hostname -I"
class PiFaceWebHandler(http.server.BaseHTTPRequestHandler):
"""Handles PiFace web control requests"""
def do_GET(self):
output_value = self.pifacedigital.output_port.value
input_value = self.pifacedigital.input_port.value
# parse the query string
qs = urllib.parse.urlparse(self.path).query
query_components = urllib.parse.parse_qs(qs)
# set the output
if OUTPUT_PORT_GET_STRING in query_components:
new_output_value = query_components["output_port"][0]
output_value = self.set_output_port(new_output_value, output_value)
# create the JSON content
content = bytes(JSON_FORMAT.format(
input=input_value,
output=output_value,
), 'UTF-8')
# reply with JSON
self.send_response(200)
self.send_header("Content-type", "application/json")
self.send_header("Content-length", str(len(content)))
self.end_headers()
self.wfile.write(content)
# Uncomment this function if you want to access this PiFace server
# from a web app (Web app is loaded from another server, not from this PiFace server).
# Normally this is not allowed. Uncomment this to allow this scenario.
def end_headers (self):
self.send_header('Access-Control-Allow-Origin', '*')
http.server.BaseHTTPRequestHandler.end_headers(self)
def set_output_port(self, new_value, old_value=0):
"""Sets the output port value to new_value, defaults to old_value."""
print("Setting output port to {}.".format(new_value))
port_value = old_value
try:
port_value = int(new_value) # dec
except ValueError:
port_value = int(new_value, 16) # hex
finally:
self.pifacedigital.output_port.value = port_value
return port_value
def get_my_ip():
"""Returns this computers IP address as a string."""
ip = subprocess.check_output(GET_IP_CMD, shell=True).decode('utf-8')[:-1]
return ip.strip()
if __name__ == "__main__":
# get the port
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = DEFAULT_PORT
# set up PiFace Digital
PiFaceWebHandler.pifacedigital = pifacedigitalio.PiFaceDigital()
print("Starting simple PiFace web control at:\n\n"
"\thttp://{addr}:{port}\n\n"
"Change the output_port with:\n\n"
"\thttp://{addr}:{port}?output_port=0xAA\n"
.format(addr=get_my_ip(), port=port))
# run the server
server_address = ('', port)
try:
httpd = http.server.HTTPServer(server_address, PiFaceWebHandler)
httpd.serve_forever()
except KeyboardInterrupt:
print('^C received, shutting down server')
httpd.socket.close()