-
Notifications
You must be signed in to change notification settings - Fork 2
/
go.py
executable file
·170 lines (135 loc) · 4.26 KB
/
go.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
#!/usr/bin/env python
import logging
import tornado.escape
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import os.path
import uuid
import mimetypes
import threading
import time
import random
import signal
import sys
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class Point:
def __init__(self, graph_id, timestamp, value):
self.graph_id, self.timestamp, self.value = graph_id, timestamp, value
class Event:
def __init__(self):
self.handlers = set()
def handle(self, handler):
self.handlers.add(handler)
return self
def unhandle(self, handler):
try:
self.handlers.remove(handler)
except:
raise ValueError("Handler is not handling this event, so cannot unhandle it.")
return self
def fire(self, *args, **kargs):
for handler in self.handlers:
handler(*args, **kargs)
def getHandlerCount(self):
return len(self.handlers)
__iadd__ = handle
__isub__ = unhandle
__call__ = fire
__len__ = getHandlerCount
class Timeseries:
def __init__(self):
self.onAdd = Event()
self.points = []
self.max_size = 200
def add(self, point):
self.points.append(point)
self.onAdd(point)
if len(self.points) > self.max_size:
self.points = self.points[-self.max_size:]
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/GraphSocket", GraphSocketHandler),
(r"/(.*)", OtherHandler),
]
settings = dict(
cookie_secret="afjdiwoehfu12hfiuwenfisndf",
static_path=os.path.dirname(__file__),
xsrf_cookies=True,
)
tornado.web.Application.__init__(self, handlers, **settings)
class OtherHandler(tornado.web.RequestHandler):
def get(self, path):
if not path:
path = 'index.html'
if not os.path.exists(path) or os.path.isdir(path):
path = os.path.join(path, 'index.html')
if not os.path.exists(path):
raise tornado.web.HTTPError(404)
mime_type = mimetypes.guess_type(path)
self.set_header("Content-Type", mime_type[0] or 'text/plain')
outfile = open(path)
for line in outfile:
self.write(line)
self.finish()
waiters = set()
timeseries = Timeseries()
def send_updates(point):
for waiter in waiters:
try:
waiter.write_message(point.__dict__)
except:
logging.error("Error sending message", exc_info=True)
def send_history(waiter):
try:
for point in timeseries.points:
waiter.write_message(point.__dict__)
except:
logging.error("Error sending message", exc_info=True)
class GraphSocketHandler(tornado.websocket.WebSocketHandler):
def allow_draft76(self):
# for iOS 5.0 Safari
return True
def open(self):
waiters.add(self)
logging.info("connected")
send_history(self)
def on_close(self):
waiters.remove(self)
logging.info("disconnected")
def on_message(self, message):
logging.info("ping")
class TimerClass(threading.Thread):
def __init__(self, timeseries):
threading.Thread.__init__(self)
self.timeseries = timeseries
self.event = threading.Event()
self.current = 0
def run(self):
while not self.event.is_set():
self.current += random.randrange(-2, 3);
self.current = min(10, max(0, self.current))
self.timeseries.add(Point("foo", int(round(time.time() * 1000.0)), self.current))
self.event.wait( 1 )
def stop(self):
self.event.set()
timer = []
timer = TimerClass(timeseries)
def main():
tornado.options.parse_command_line()
app = Application()
app.listen(options.port)
timeseries.onAdd += send_updates
timer.start()
signal.signal(signal.SIGINT, signal_handler)
logging.info("Listening on http://localhost:%i/" % options.port)
tornado.ioloop.IOLoop.instance().start()
def signal_handler(signal, frame):
timer.stop()
print ""
sys.exit(0)
if __name__ == "__main__":
main()