-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcc2http.py
More file actions
executable file
·93 lines (80 loc) · 2.71 KB
/
Copy pathcc2http.py
File metadata and controls
executable file
·93 lines (80 loc) · 2.71 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
#!/usr/bin/python
import BaseHTTPServer
import chipcap2
import json
import datetime
import os
import sys
import time
import httplib
import logging
FORMAT = '%(asctime)-15s %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)
logging.info('logging initialized')
childpid = os.fork()
if childpid != 0:
print 'PARENT EUID={}'.format(os.geteuid())
time.sleep(1)
c = httplib.HTTPConnection('localhost', 8000)
c.request('GET', '/')
r = c.getresponse()
if r.status == 200:
print 'ChipCap2 exporter is RUNNING'
sys.exit(0)
else:
print 'Failed to start, killing'
os.kill(childpid, 9)
sys.exit(1)
print 'CHILD EUID={}'.format(os.geteuid())
loc = sys.argv[1]
try:
with open('/var/run/chipcap2.pid', 'w') as fp:
fp.write('{}'.format(os.getpid()))
except:
pass
def trim(s):
return s.strip().lower()
class RHTempRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
try:
logging.info('inside GET handler')
with chipcap2.Sensor(1) as s:
logging.info('s=%s', s)
rh, tempF = s.read()
accept = map(trim, (self.headers.get("Accept") or '').split(','))
self.send_response(200)
print accept
if 'application/json' in accept:
self.send_header("Content-Type", "application/json")
self.end_headers()
data = {
"ts": str(datetime.datetime.now()),
"rh": rh,
"tempF": tempF,
"tempC": s.tempC,
"chipcap2_raw_data": s_.data
}
self.wfile.write(json.dumps(data))
else:
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write('rh{location="%s"} %f\n'
'tempF{location="%s"} %f\n'
'tempC{location="%s"} %f\n'
% (loc, rh, loc, tempF, loc, s.tempC))
for i in range(len(s._data)):
self.wfile.write('chipcap2_raw_data{location="%s", offset="%02d"} %d\n' % (loc, i, s._data[i]))
self.wfile.flush()
self.wfile.close_connection = 1
except Exception as e:
print 'Error: {}'.format(e)
self.send_response(503)
def run(host="0.0.0.0",
port=8000,
server_class=BaseHTTPServer.HTTPServer,
handler_class=RHTempRequestHandler):
server_address = (host, port)
httpd = server_class(server_address, handler_class)
httpd.serve_forever()
if __name__ == "__main__":
run()