blob: f712fd909b97d7aec2d0c8aad3c7523456061fbe [file] [log] [blame]
Charlie Mooneybbc05f52015-03-24 13:36:22 -07001# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""This module launches the cherrypy server for webplot and sets up
6web sockets to handle the messages between the clients and the server.
7"""
8
9import argparse
10import base64
11import json
12import logging
13import os
Charlie Mooneybf469942015-07-09 11:21:12 -070014import pwd
Charlie Mooneybbc05f52015-03-24 13:36:22 -070015import re
16import subprocess
Charlie Mooneyc68f9c32015-04-16 15:23:22 -070017import time
Charlie Mooneybbc05f52015-03-24 13:36:22 -070018import threading
Charlie Mooney54e2f2e2015-07-09 10:53:38 -070019import webbrowser
Charlie Mooneybbc05f52015-03-24 13:36:22 -070020
21import cherrypy
22
Charlie Mooneybbc05f52015-03-24 13:36:22 -070023from ws4py import configure_logger
24from ws4py.messaging import TextMessage
25from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
26from ws4py.websocket import WebSocket
27
Charlie Mooney04b41532015-04-02 12:41:37 -070028from remote import ChromeOSTouchDevice, AndroidTouchDevice
Charlie Mooneybbc05f52015-03-24 13:36:22 -070029
30
31# The WebSocket connection state object.
32state = None
33
34# The touch events are saved in this file as default.
Charlie Mooneybf469942015-07-09 11:21:12 -070035current_username = pwd.getpwuid(os.getuid()).pw_name
36SAVED_FILE = '/tmp/webplot_%s.dat' % current_username
37SAVED_IMAGE = '/tmp/webplot_%s.png' % current_username
Charlie Mooneybbc05f52015-03-24 13:36:22 -070038
39
Joseph Hwang4782a042015-04-08 17:15:50 +080040def SimpleSystem(cmd):
41 """Execute a system command."""
42 ret = subprocess.call(cmd, shell=True)
43 if ret:
44 logging.warning('Command (%s) failed (ret=%s).', cmd, ret)
45 return ret
46
47
48def SimpleSystemOutput(cmd):
49 """Execute a system command and get its output."""
50 try:
51 proc = subprocess.Popen(
52 cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
53 stdout, _ = proc.communicate()
54 except Exception, e:
55 logging.warning('Command (%s) failed (%s).', cmd, e)
56 else:
57 return None if proc.returncode else stdout.strip()
58
59
60def IsDestinationPortEnabled(port):
61 """Check if the destination port is enabled in iptables.
62
63 If port 8000 is enabled, it looks like
64 ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 ctstate NEW tcp dpt:8000
65 """
66 pattern = re.compile('ACCEPT\s+tcp.+\s+ctstate\s+NEW\s+tcp\s+dpt:%d' % port)
67 rules = SimpleSystemOutput('sudo iptables -L INPUT -n --line-number')
68 for rule in rules.splitlines():
69 if pattern.search(rule):
70 return True
71 return False
72
73
74def EnableDestinationPort(port):
75 """Enable the destination port for input traffic in iptables."""
76 if IsDestinationPortEnabled(port):
77 cherrypy.log('Port %d has been already enabled in iptables.' % port)
78 else:
Charlie Mooneye15a5552015-07-10 13:48:03 -070079 cherrypy.log('Adding a rule to accept incoming connections on port %d in '
80 'iptables.' % port)
Joseph Hwang4782a042015-04-08 17:15:50 +080081 cmd = ('sudo iptables -A INPUT -p tcp -m conntrack --ctstate NEW '
82 '--dport %d -j ACCEPT' % port)
83 if SimpleSystem(cmd) != 0:
84 raise Error('Failed to enable port in iptables: %d.' % port)
85
86
Charlie Mooneybbc05f52015-03-24 13:36:22 -070087def InterruptHandler():
88 """An interrupt handler for both SIGINT and SIGTERM
89
90 The stop procedure triggered is as follows:
91 1. This handler sends a 'quit' message to the listening client.
92 2. The client sends the canvas image back to the server in its quit message.
93 3. WebplotWSHandler.received_message() saves the image.
94 4. WebplotWSHandler.received_message() handles the 'quit' message.
95 The cherrypy engine exits if this is the last client.
96 """
97 cherrypy.log('Cherrypy engine is sending quit message to clients.')
Joseph Hwang95bf52a2015-04-14 13:09:39 +080098 state.QuitAndShutdown()
99
100
101def _IOError(e, filename):
102 err_msg = ['\n', '!' * 60, str(e),
103 'It is likely that %s is owned by root.' % filename,
104 'Please remove the file and then run webplot again.',
105 '!' * 60, '\n']
106 cherrypy.log('\n'.join(err_msg))
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700107
Charlie Mooneyc68f9c32015-04-16 15:23:22 -0700108image_lock = threading.Event()
109image_string = ''
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700110
111class WebplotWSHandler(WebSocket):
112 """The web socket handler for webplot."""
113
114 def opened(self):
115 """This method is called when the handler is opened."""
116 cherrypy.log('WS handler is opened!')
117
118 def received_message(self, msg):
119 """A callback for received message."""
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700120 data = msg.data.split(':', 1)
121 mtype = data[0].lower()
122 content = data[1] if len(data) == 2 else None
Joseph Hwang0c1fa7d2015-04-09 17:01:45 +0800123
124 # Do not print the image data since it is too large.
125 if mtype != 'save':
126 cherrypy.log('Received message: %s' % str(msg.data))
127
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700128 if mtype == 'quit':
129 # A shutdown message requested by the user.
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700130 cherrypy.log('The user requests to shutdown the cherrypy server....')
131 state.DecCount()
132 elif mtype == 'save':
Charlie Mooneyb476e892015-04-02 13:25:49 -0700133 cherrypy.log('All data saved to "%s"' % SAVED_FILE)
134 self.SaveImage(content, SAVED_IMAGE)
135 cherrypy.log('Plot image saved to "%s"' % SAVED_IMAGE)
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700136 else:
137 cherrypy.log('Unknown message type: %s' % mtype)
138
139 def closed(self, code, reason="A client left the room."):
140 """This method is called when the handler is closed."""
141 cherrypy.log('A client requests to close WS.')
142 cherrypy.engine.publish('websocket-broadcast', TextMessage(reason))
143
144 @staticmethod
145 def SaveImage(image_data, image_file):
146 """Decoded the base64 image data and save it in the file."""
Charlie Mooneyc68f9c32015-04-16 15:23:22 -0700147 global image_string
148 image_string = base64.b64decode(image_data)
149 image_lock.set()
Joseph Hwangafc092c2015-04-21 11:32:45 +0800150 try:
151 with open(image_file, 'w') as f:
152 f.write(image_string)
153 except IOError as e:
154 _IOError(e, image_file)
155 state.QuitAndShutdown()
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700156
157
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700158class ConnectionState(object):
159 """A ws connection state object for shutting down the cherrypy server.
160
161 It shuts down the cherrypy server when the count is down to 0 and is not
162 increased before the shutdown_timer expires.
163
164 Note that when a page refreshes, it closes the WS connection first and
165 then re-connects immediately. This is why we would like to wait a while
166 before actually shutting down the server.
167 """
168 TIMEOUT = 1.0
169
170 def __init__(self):
171 self.count = 0;
172 self.lock = threading.Lock()
173 self.shutdown_timer = None
Joseph Hwang95bf52a2015-04-14 13:09:39 +0800174 self.quit_flag = False
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700175
176 def IncCount(self):
177 """Increase the connection count, and cancel the shutdown timer if exists.
178 """
179 self.lock.acquire()
180 self.count += 1;
181 cherrypy.log(' WS connection count: %d' % self.count)
182 if self.shutdown_timer:
183 self.shutdown_timer.cancel()
184 self.shutdown_timer = None
185 self.lock.release()
186
187 def DecCount(self):
188 """Decrease the connection count, and start a shutdown timer if no other
189 clients are connecting to the server.
190 """
191 self.lock.acquire()
192 self.count -= 1;
193 cherrypy.log(' WS connection count: %d' % self.count)
194 if self.count == 0:
195 self.shutdown_timer = threading.Timer(self.TIMEOUT, self.Shutdown)
196 self.shutdown_timer.start()
197 self.lock.release()
198
Joseph Hwang3f561d32015-04-09 16:33:56 +0800199 def ShutdownWhenNoConnections(self):
200 """Shutdown cherrypy server when there is no client connection."""
201 self.lock.acquire()
202 if self.count == 0 and self.shutdown_timer is None:
203 self.Shutdown()
204 self.lock.release()
205
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700206 def Shutdown(self):
207 """Shutdown the cherrypy server."""
208 cherrypy.log('Shutdown timer expires. Cherrypy server for Webplot exits.')
209 cherrypy.engine.exit()
210
Joseph Hwang95bf52a2015-04-14 13:09:39 +0800211 def QuitAndShutdown(self):
212 """The server notifies clients to quit and then shuts down."""
213 if not self.quit_flag:
214 self.quit_flag = True
215 cherrypy.engine.publish('websocket-broadcast', TextMessage('quit'))
216 self.ShutdownWhenNoConnections()
217
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700218
Johny Lin908b92a2015-08-27 21:59:30 +0800219class TouchRoot(object):
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700220 """A class to handle requests about docroot."""
221
222 def __init__(self, ip, port, touch_min_x, touch_max_x, touch_min_y,
Jingkui Wang55115ef2017-06-17 13:44:33 -0700223 touch_max_y, touch_min_pressure, touch_max_pressure,
224 tilt_min_x, tilt_max_x, tilt_min_y, tilt_max_y):
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700225 self.ip = ip
226 self.port = port
227 self.touch_min_x = touch_min_x
228 self.touch_max_x = touch_max_x
229 self.touch_min_y = touch_min_y
230 self.touch_max_y = touch_max_y
231 self.touch_min_pressure = touch_min_pressure
232 self.touch_max_pressure = touch_max_pressure
Jingkui Wang55115ef2017-06-17 13:44:33 -0700233 self.tilt_min_x = tilt_min_x
234 self.tilt_max_x = tilt_max_x
235 self.tilt_min_y = tilt_min_y
236 self.tilt_max_y = tilt_max_y
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700237 self.scheme = 'ws'
238 cherrypy.log('Root address: (%s, %s)' % (ip, str(port)))
239 cherrypy.log('scheme: %s' % self.scheme)
240
241 @cherrypy.expose
242 def index(self):
243 """This is the default index.html page."""
244 websocket_dict = {
245 'websocketUrl': '%s://%s:%s/ws' % (self.scheme, self.ip, self.port),
246 'touchMinX': str(self.touch_min_x),
247 'touchMaxX': str(self.touch_max_x),
248 'touchMinY': str(self.touch_min_y),
249 'touchMaxY': str(self.touch_max_y),
250 'touchMinPressure': str(self.touch_min_pressure),
251 'touchMaxPressure': str(self.touch_max_pressure),
Jingkui Wang55115ef2017-06-17 13:44:33 -0700252 'tiltMinX': str(self.tilt_min_x),
253 'tiltMaxX': str(self.tilt_max_x),
254 'tiltMinY': str(self.tilt_min_y),
255 'tiltMaxY': str(self.tilt_max_y),
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700256 }
257 root_page = os.path.join(os.path.abspath(os.path.dirname(__file__)),
258 'webplot.html')
259 with open(root_page) as f:
260 return f.read() % websocket_dict
261
262 @cherrypy.expose
Jingkui Wang7ed915f2017-06-22 17:31:54 -0700263 def linechart(self):
264 """This is the default linechart.html page."""
265 websocket_dict = {
266 'websocketUrl': '%s://%s:%s/ws' % (self.scheme, self.ip, self.port),
267 'touchMinX': str(self.touch_min_x),
268 'touchMaxX': str(self.touch_max_x),
269 'touchMinY': str(self.touch_min_y),
270 'touchMaxY': str(self.touch_max_y),
271 'touchMinPressure': str(self.touch_min_pressure),
272 'touchMaxPressure': str(self.touch_max_pressure),
273 'tiltMinX': str(self.tilt_min_x),
274 'tiltMaxX': str(self.tilt_max_x),
275 'tiltMinY': str(self.tilt_min_y),
276 'tiltMaxY': str(self.tilt_max_y),
277 }
278 root_page = os.path.join(os.path.abspath(os.path.dirname(__file__)),
279 'linechart/linechart.html')
280 with open(root_page) as f:
281 return f.read() % websocket_dict
282
283 @cherrypy.expose
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700284 def ws(self):
285 """This handles the request to create a new web socket per client."""
286 cherrypy.log('A new client requesting for WS')
287 cherrypy.log('WS handler created: %s' % repr(cherrypy.request.ws_handler))
288 state.IncCount()
289
290
Johny Lin908b92a2015-08-27 21:59:30 +0800291class CentroidingRoot(object):
292 """A class to handle requests about docroot."""
293
294 def __init__(self, ip, port, data_scale, data_offset,
295 data_width, data_height):
296 self.ip = ip
297 self.port = port
298 self.data_scale = data_scale
299 self.data_offset = data_offset
300 self.data_width = data_width
301 self.data_height = data_height
302 self.scheme = 'ws'
303 cherrypy.log('Root address: (%s, %s)' % (ip, str(port)))
304 cherrypy.log('scheme: %s' % self.scheme)
305
306 @cherrypy.expose
307 def index(self):
308 """This is the default index.html page."""
309 websocket_dict = {
310 'websocketUrl': '%s://%s:%s/ws' % (self.scheme, self.ip, self.port),
311 'dataScale': str(self.data_scale),
312 'dataOffset': str(self.data_offset),
313 'dataWidth': str(self.data_width),
314 'dataHeight': str(self.data_height),
315 }
316 print websocket_dict
317 root_page = os.path.join(os.path.abspath(os.path.dirname(__file__)),
318 'centroiding.html')
319 with open(root_page) as f:
320 return f.read() % websocket_dict
321
322 @cherrypy.expose
323 def ws(self):
324 """This handles the request to create a new web socket per client."""
325 cherrypy.log('A new client requesting for WS')
326 cherrypy.log('WS handler created: %s' % repr(cherrypy.request.ws_handler))
327 state.IncCount()
328
329
Joseph Hwang4782a042015-04-08 17:15:50 +0800330class Webplot(threading.Thread):
331 """The server handling the Plotting of finger traces.
332
333 Use case 1: embedding Webplot as a plotter in an application
334
335 # Instantiate a webplot server and starts the daemon.
336 plot = Webplot(server_addr, server_port, device)
337 plot.start()
338
339 # Repeatedly get a snapshot and add it for plotting.
340 while True:
341 # GetSnapshot() is essentially device.NextSnapshot()
342 snapshot = plot.GetSnapshot()
343 if not snapshot:
344 break
345 # Add the snapshot to the plotter for plotting.
346 plot.AddSnapshot(snapshot)
347
348 # Save a screen dump
349 plot.Save()
350
351 # Notify the browser to clear the screen.
352 plot.Clear()
353
354 # Notify both the browser and the cherrypy engine to quit.
355 plot.Quit()
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700356
357
Joseph Hwang4782a042015-04-08 17:15:50 +0800358 Use case 2: using webplot standalone
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700359
Joseph Hwang4782a042015-04-08 17:15:50 +0800360 # Instantiate a webplot server and starts the daemon.
361 plot = Webplot(server_addr, server_port, device)
362 plot.start()
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700363
Joseph Hwang4782a042015-04-08 17:15:50 +0800364 # Get touch snapshots from the touch device and have clients plot them.
365 webplot.GetAndPlotSnapshots()
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700366 """
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700367
Joseph Hwange9cfd642015-04-20 16:00:33 +0800368 def __init__(self, server_addr, server_port, device, saved_file=SAVED_FILE,
Johny Lin908b92a2015-08-27 21:59:30 +0800369 logging=False, is_behind_iptables_firewall=False,
370 is_centroiding=False):
Joseph Hwang4782a042015-04-08 17:15:50 +0800371 self._server_addr = server_addr
372 self._server_port = server_port
373 self._device = device
374 self._saved_file = saved_file
Johny Lin908b92a2015-08-27 21:59:30 +0800375 self._is_centroiding = is_centroiding
Joseph Hwang4782a042015-04-08 17:15:50 +0800376 super(Webplot, self).__init__(name='webplot thread')
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700377
Joseph Hwang4782a042015-04-08 17:15:50 +0800378 self.daemon = True
379 self._prev_tids = []
380
Joseph Hwange9cfd642015-04-20 16:00:33 +0800381 # The logging is turned off by default when imported as a module so that
382 # it does not mess up the screen.
383 if not logging:
384 cherrypy.log.screen = None
385
Charlie Mooneye15a5552015-07-10 13:48:03 -0700386 # Allow input traffic in iptables, if the user has specified. This setting
387 # should be used if webplot is being run directly on a chromebook, but it
388 # requires root access, so we don't want to use it all the time.
389 if is_behind_iptables_firewall:
390 EnableDestinationPort(self._server_port)
Joseph Hwang4782a042015-04-08 17:15:50 +0800391
392 # Create a ws connection state object to wait for the condition to
393 # shutdown the whole process.
394 global state
395 state = ConnectionState()
396
397 cherrypy.config.update({
398 'server.socket_host': self._server_addr,
399 'server.socket_port': self._server_port,
400 })
401
402 WebSocketPlugin(cherrypy.engine).subscribe()
403 cherrypy.tools.websocket = WebSocketTool()
404
405 # If the cherrypy server exits for whatever reason, close the device
406 # for required cleanup. Otherwise, there might exist local/remote
407 # zombie processes.
Johny Lin908b92a2015-08-27 21:59:30 +0800408 if not self._is_centroiding:
409 cherrypy.engine.subscribe('exit', self._device.__del__)
Joseph Hwang4782a042015-04-08 17:15:50 +0800410
411 cherrypy.engine.signal_handler.handlers['SIGINT'] = InterruptHandler
412 cherrypy.engine.signal_handler.handlers['SIGTERM'] = InterruptHandler
413
414 def run(self):
415 """Start the cherrypy engine."""
Johny Lin908b92a2015-08-27 21:59:30 +0800416 if not self._is_centroiding:
417 x_min, x_max = self._device.RangeX()
418 y_min, y_max = self._device.RangeY()
419 p_min, p_max = self._device.RangeP()
Jingkui Wang55115ef2017-06-17 13:44:33 -0700420 tilt_x_min, tilt_x_max = self._device.RangeTiltX()
421 tilt_y_min, tilt_y_max = self._device.RangeTiltY()
Johny Lin908b92a2015-08-27 21:59:30 +0800422 root = TouchRoot(self._server_addr, self._server_port,
Jingkui Wang55115ef2017-06-17 13:44:33 -0700423 x_min, x_max, y_min, y_max, p_min, p_max, tilt_x_min,
424 tilt_x_max, tilt_y_min, tilt_y_max)
Johny Lin908b92a2015-08-27 21:59:30 +0800425 else:
426 data_scale = self._device.data_scale
427 data_offset = self._device.data_offset
428 data_width = self._device.width
429 data_height = self._device.height
Jingkui Wang55115ef2017-06-17 13:44:33 -0700430 tilt_x_min, tilt_x_max = self._device.RangeTiltX()
431 tilt_y_min, tilt_y_max = self._device.RangeTiltY()
Johny Lin908b92a2015-08-27 21:59:30 +0800432 root = CentroidingRoot(self._server_addr, self._server_port,
Jingkui Wang55115ef2017-06-17 13:44:33 -0700433 data_scale, data_offset, data_width, data_height,
434 tilt_x_min, tilt_x_max, tilt_y_min, tilt_y_max)
Joseph Hwang4782a042015-04-08 17:15:50 +0800435
436 cherrypy.quickstart(
Johny Lin908b92a2015-08-27 21:59:30 +0800437 root,
Joseph Hwang4782a042015-04-08 17:15:50 +0800438 '',
439 config={
440 '/': {
441 'tools.staticdir.root':
442 os.path.abspath(os.path.dirname(__file__)),
443 'tools.staticdir.on': True,
444 'tools.staticdir.dir': '',
445 },
446 '/ws': {
447 'tools.websocket.on': True,
448 'tools.websocket.handler_cls': WebplotWSHandler,
449 },
450 }
451 )
452
453 def _ConvertNamedtupleToDict(self, snapshot):
454 """Convert namedtuples to ordinary dictionaries and add leaving slots.
455
456 This is to make a snapshot json serializable. Otherwise, the namedtuples
457 would be transmitted as arrays which is less readable.
458
459 A snapshot looks like
460 MtSnapshot(
461 syn_time=1420524008.368854,
462 button_pressed=False,
Jingkui Wangcfabdd52017-06-27 10:28:20 -0700463 fingers=[
464 MtFinger(tid=162, slot=0, syn_time=1420524008.368854, x=524,
Jingkui Wang55115ef2017-06-17 13:44:33 -0700465 y=231, pressure=45, tilt_x=0, tilt_y=0),
Jingkui Wangcfabdd52017-06-27 10:28:20 -0700466 MtFinger(tid=163, slot=1, syn_time=1420524008.368854, x=677,
Jingkui Wang55115ef2017-06-17 13:44:33 -0700467 y=135, pressure=57, tilt_x=0, tilt_y=0)
Joseph Hwang4782a042015-04-08 17:15:50 +0800468 ]
469 )
470
471 Note:
472 1. that there are two levels of namedtuples to convert.
473 2. The leaving slots are used to notify javascript that a finger is leaving
474 so that the corresponding finger color could be released for reuse.
475 """
476 # Convert MtSnapshot.
477 converted = dict(snapshot.__dict__.items())
478
Jingkui Wangcfabdd52017-06-27 10:28:20 -0700479 # Convert MtFinger.
480 converted['fingers'] = [dict(finger.__dict__.items())
481 for finger in converted['fingers']]
Joseph Hwang4782a042015-04-08 17:15:50 +0800482 converted['raw_events'] = [str(event) for event in converted['raw_events']]
483
484 # Add leaving fingers to notify js for reclaiming the finger colors.
Jingkui Wangcfabdd52017-06-27 10:28:20 -0700485 curr_tids = [finger['tid'] for finger in converted['fingers']]
Joseph Hwang4782a042015-04-08 17:15:50 +0800486 for tid in set(self._prev_tids) - set(curr_tids):
487 leaving_finger = {'tid': tid, 'leaving': True}
Jingkui Wangcfabdd52017-06-27 10:28:20 -0700488 converted['fingers'].append(leaving_finger)
Joseph Hwang4782a042015-04-08 17:15:50 +0800489 self._prev_tids = curr_tids
490
Joseph Hwang02e829c2015-04-13 17:09:07 +0800491 # Convert raw events from a list of classes to a list of its strings
492 # so that the raw_events is serializable.
493 converted['raw_events'] = [str(event) for event in converted['raw_events']]
494
Joseph Hwang4782a042015-04-08 17:15:50 +0800495 return converted
496
497 def GetSnapshot(self):
498 """Get a snapshot from the touch device."""
Charlie Mooneyc68f9c32015-04-16 15:23:22 -0700499 return self._device.NextSnapshot()
Joseph Hwang4782a042015-04-08 17:15:50 +0800500
501 def AddSnapshot(self, snapshot):
502 """Convert the snapshot to a proper format and publish it to clients."""
Johny Lin908b92a2015-08-27 21:59:30 +0800503 if not self._is_centroiding:
504 snapshot = self._ConvertNamedtupleToDict(snapshot)
Joseph Hwang4782a042015-04-08 17:15:50 +0800505 cherrypy.engine.publish('websocket-broadcast', json.dumps(snapshot))
Joseph Hwang02e829c2015-04-13 17:09:07 +0800506 return snapshot
Joseph Hwang4782a042015-04-08 17:15:50 +0800507
508 def GetAndPlotSnapshots(self):
509 """Get and plot snapshots."""
510 cherrypy.log('Start getting the live stream snapshots....')
Joseph Hwang95bf52a2015-04-14 13:09:39 +0800511 try:
512 with open(self._saved_file, 'w') as f:
513 while True:
514 try:
515 snapshot = self.GetSnapshot()
516 if not snapshot:
517 cherrypy.log('webplot is terminated.')
518 break
519 converted_snapshot = self.AddSnapshot(snapshot)
520 f.write('\n'.join(converted_snapshot['raw_events']) + '\n')
521 f.flush()
522 except KeyboardInterrupt:
523 cherrypy.log('Keyboard Interrupt accepted')
524 cherrypy.log('webplot is being terminated...')
525 state.QuitAndShutdown()
526 except IOError as e:
527 _IOError(e, self._saved_file)
528 state.QuitAndShutdown()
Joseph Hwang4782a042015-04-08 17:15:50 +0800529
530 def Publish(self, msg):
531 """Publish a message to clients."""
532 cherrypy.engine.publish('websocket-broadcast', TextMessage(msg))
533
534 def Clear(self):
535 """Notify clients to clear the display."""
536 self.Publish('clear')
537
538 def Quit(self):
539 """Notify clients to quit.
540
541 Note that the cherrypy engine would quit accordingly.
542 """
Joseph Hwang95bf52a2015-04-14 13:09:39 +0800543 state.QuitAndShutdown()
Joseph Hwang4782a042015-04-08 17:15:50 +0800544
Charlie Mooneybf469942015-07-09 11:21:12 -0700545 def Save(self):
546 """Notify clients to save the screen, then wait for the image file to be
547 created, and return the image.
Charlie Mooneyc68f9c32015-04-16 15:23:22 -0700548 """
549 global image_lock
550 global image_string
551
552 # Trigger a save action
Joseph Hwang4782a042015-04-08 17:15:50 +0800553 self.Publish('save')
554
Charlie Mooneyc68f9c32015-04-16 15:23:22 -0700555 # Block until the server has completed saving it to disk
556 image_lock.wait()
557 image_lock.clear()
558 return image_string
559
Joseph Hwang4782a042015-04-08 17:15:50 +0800560 def Url(self):
561 """The url the server is serving at."""
562 return 'http://%s:%d' % (self._server_addr, self._server_port)
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700563
564
Joseph Hwanga1c84782015-04-14 15:07:00 +0800565def _CheckLegalUser():
566 """If this program is run in chroot, it should not be run as root for security
567 reason.
568 """
569 if os.path.exists('/etc/cros_chroot_version') and os.getuid() == 0:
570 print ('You should run webplot in chroot as a regular user '
571 'instead of as root.\n')
572 exit(1)
573
574
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700575def _ParseArguments():
576 """Parse the command line options."""
577 parser = argparse.ArgumentParser(description='Webplot Server')
Charlie Mooney8026f2a2015-04-02 13:01:28 -0700578 parser.add_argument('-d', '--dut_addr', default=None,
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700579 help='the address of the dut')
Joseph Hwang59db4412015-04-09 12:43:16 +0800580
581 # Make an exclusive group to make the webplot.py command option
582 # consistent with the webplot.sh script command option.
583 # What is desired:
584 # When no command option specified in webplot.sh/webplot.py: grab is True
585 # When '--grab' option specified in webplot.sh/webplot.py: grab is True
586 # When '--nograb' option specified in webplot.sh/webplot.py: grab is False
587 grab_group = parser.add_mutually_exclusive_group()
588 grab_group.add_argument('--grab', help='grab the device exclusively',
589 action='store_true')
590 grab_group.add_argument('--nograb', help='do not grab the device',
591 action='store_true')
592
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700593 parser.add_argument('--is_touchscreen', help='the DUT is touchscreen',
594 action='store_true')
Charlie Mooneye15a5552015-07-10 13:48:03 -0700595 parser.add_argument('-p', '--server_port', default=8080, type=int,
596 help='the port the web server listens to (default: 8080)')
597 parser.add_argument('--behind_firewall', action='store_true',
598 help=('With this flag set, you tell webplot to add a '
599 'rule to iptables to allow incoming traffic to '
600 'the webserver. If you are running webplot on '
601 'a chromebook, this is needed.'))
602 parser.add_argument('-s', '--server_addr', default='127.0.0.1',
Joseph Hwang59db4412015-04-09 12:43:16 +0800603 help='the address the webplot http server listens to')
604 parser.add_argument('-t', '--dut_type', default='chromeos', type=str.lower,
Johny Lin908b92a2015-08-27 21:59:30 +0800605 help='dut type: chromeos, android, centroiding')
Charlie Mooney54e2f2e2015-07-09 10:53:38 -0700606 parser.add_argument('--automatically_start_browser', action='store_true',
607 help=('When this flag is set the script will try to '
608 'start a web browser automatically once webplot '
609 'is ready, instead of waiting for the user to.'))
Charlie Mooney60b56a72016-09-26 12:35:53 -0700610 parser.add_argument('--protocol',type=str, default='auto',
611 choices=['auto', 'stylus', 'MTB', 'MTA'],
612 help=('Which protocol does the device use? Choose from '
613 'auto, MTB, MTA, or stylus'))
Johny Lin908b92a2015-08-27 21:59:30 +0800614
615 # Arguments especial for centroiding visualizing tool.
616 # Please set "--dut_type centroiding" for centroiding utility.
617 parser.add_argument('-f', '--dut_forward_port', default=12345, type=int,
618 help='the forwarding port for centroiding socket server '
619 '(default: 12345) (only needed for centroiding)')
620 parser.add_argument('-c', '--config', default='tango.conf', type=str,
621 help='Config file name of device for centroiding '
622 'visualizing tool parameters.')
623 parser.add_argument('--fps', default=0, type=int,
624 help='the target frame rate of visualizer plotting, set '
625 '0 for keeping same as centroiding processing frame '
626 'rate.')
627
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700628 args = parser.parse_args()
Joseph Hwang59db4412015-04-09 12:43:16 +0800629
630 args.grab = not args.nograb
631
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700632 return args
633
634
635def Main():
636 """The main function to launch webplot service."""
Joseph Hwanga1c84782015-04-14 15:07:00 +0800637 _CheckLegalUser()
638
Joseph Hwange9cfd642015-04-20 16:00:33 +0800639 configure_logger(level=logging.ERROR)
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700640 args = _ParseArguments()
641
Johny Lin04d970a2015-12-08 03:20:13 +0800642 # Specify Webplot for centroiding purpose.
643 is_centroiding = args.dut_type == 'centroiding'
644
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700645 print '\n' + '-' * 70
Johny Lin04d970a2015-12-08 03:20:13 +0800646 if is_centroiding:
Johny Lin908b92a2015-08-27 21:59:30 +0800647 cherrypy.log('**** Centroiding Data Visualizing Tool ****')
648 cherrypy.log('dut config file: %s' % args.config)
649 cherrypy.log('dut address: %s' % args.dut_addr)
650 cherrypy.log('dut socket forwarding port: %d' % args.dut_forward_port)
651 else:
652 cherrypy.log('dut machine type: %s' % args.dut_type)
653 cherrypy.log('dut\'s touch device: %s' %
654 ('touchscreen' if args.is_touchscreen else 'touchpad'))
655 cherrypy.log('dut address: %s' % args.dut_addr)
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700656 cherrypy.log('web server address: %s' % args.server_addr)
657 cherrypy.log('web server port: %s' % args.server_port)
Joseph Hwang59db4412015-04-09 12:43:16 +0800658 cherrypy.log('grab the touch device: %s' % args.grab)
659 if args.dut_type == 'android' and args.grab:
660 cherrypy.log('Warning: the grab option is not supported on Android devices'
661 ' yet.')
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700662 cherrypy.log('touch events are saved in %s' % SAVED_FILE)
663 print '-' * 70 + '\n\n'
664
665 if args.server_port == 80:
Charlie Mooney54e2f2e2015-07-09 10:53:38 -0700666 url = 'http://%s' % args.server_addr
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700667 else:
Charlie Mooney54e2f2e2015-07-09 10:53:38 -0700668 url = 'http://%s:%d' % (args.server_addr, args.server_port)
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700669
670 msg = 'Type "%s" in browser %s to see finger traces.\n'
Charlie Mooneye15a5552015-07-10 13:48:03 -0700671 if args.server_addr == '127.0.0.1':
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700672 which_machine = 'on the webplot server machine'
673 else:
674 which_machine = 'on any machine'
675
676 print '*' * 70
677 print msg % (url, which_machine)
678 print 'Press \'q\' on the browser to quit.'
679 print '*' * 70 + '\n\n'
680
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700681 # Instantiate a touch device.
Charlie Mooneyc68f9c32015-04-16 15:23:22 -0700682 if args.dut_type == 'chromeos':
683 addr = args.dut_addr if args.dut_addr else '127.0.0.1'
Charlie Mooney60b56a72016-09-26 12:35:53 -0700684 device = ChromeOSTouchDevice(addr, args.is_touchscreen, grab=args.grab,
685 protocol=args.protocol)
Johny Lin908b92a2015-08-27 21:59:30 +0800686 elif args.dut_type == 'android':
Charlie Mooney60b56a72016-09-26 12:35:53 -0700687 device = AndroidTouchDevice(args.dut_addr, True, protocol=args.protocol)
Johny Lin04d970a2015-12-08 03:20:13 +0800688 elif is_centroiding: # args.dut_type == 'centroiding'
689 # Import centroiding library conditionally to avoid missing dependency.
690 from centroiding import CentroidingDataReceiver, CentroidingDevice
Johny Lin908b92a2015-08-27 21:59:30 +0800691 device = CentroidingDevice(args.config)
Johny Lin04d970a2015-12-08 03:20:13 +0800692 else:
693 print 'Unrecognized dut_type: %s. Webplot is aborted...' % args.dut_type
694 exit(1)
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700695
Joseph Hwang4782a042015-04-08 17:15:50 +0800696 # Instantiate a webplot server daemon and start it.
Charlie Mooneye15a5552015-07-10 13:48:03 -0700697 webplot = Webplot(args.server_addr, args.server_port, device, logging=True,
Johny Lin908b92a2015-08-27 21:59:30 +0800698 is_behind_iptables_firewall=args.behind_firewall,
699 is_centroiding=is_centroiding)
Joseph Hwang4782a042015-04-08 17:15:50 +0800700 webplot.start()
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700701
Charlie Mooney54e2f2e2015-07-09 10:53:38 -0700702 if args.automatically_start_browser:
703 opened_successfully = webbrowser.open(url)
704 if opened_successfully:
705 print 'Web browser opened successfully!'
706 else:
707 print '!' * 80
708 print 'Sorry, we were unable to automatically open a web browser for you'
709 print 'Please navigate to "%s" in a browser manually, instead' % url
710 print '!' * 80
711
Johny Lin908b92a2015-08-27 21:59:30 +0800712 if not is_centroiding:
713 # Get touch snapshots from the touch device and have clients plot them.
714 webplot.GetAndPlotSnapshots()
715 else:
716 receiver = CentroidingDataReceiver(
717 '127.0.0.1', args.dut_forward_port, webplot, plot_fps=args.fps)
718 receiver.StartReceive()
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700719
720
721if __name__ == '__main__':
722 Main()