Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 1 | # 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 |
| 6 | web sockets to handle the messages between the clients and the server. |
| 7 | """ |
| 8 | |
| 9 | import argparse |
| 10 | import base64 |
| 11 | import json |
| 12 | import logging |
| 13 | import os |
| 14 | import re |
| 15 | import subprocess |
Charlie Mooney | c68f9c3 | 2015-04-16 15:23:22 -0700 | [diff] [blame] | 16 | import time |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 17 | import threading |
| 18 | |
| 19 | import cherrypy |
| 20 | |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 21 | from ws4py import configure_logger |
| 22 | from ws4py.messaging import TextMessage |
| 23 | from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool |
| 24 | from ws4py.websocket import WebSocket |
| 25 | |
Charlie Mooney | 04b4153 | 2015-04-02 12:41:37 -0700 | [diff] [blame] | 26 | from remote import ChromeOSTouchDevice, AndroidTouchDevice |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 27 | |
| 28 | |
| 29 | # The WebSocket connection state object. |
| 30 | state = None |
| 31 | |
| 32 | # The touch events are saved in this file as default. |
| 33 | SAVED_FILE = '/tmp/webplot.dat' |
| 34 | SAVED_IMAGE = '/tmp/webplot.png' |
| 35 | |
| 36 | |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 37 | def SimpleSystem(cmd): |
| 38 | """Execute a system command.""" |
| 39 | ret = subprocess.call(cmd, shell=True) |
| 40 | if ret: |
| 41 | logging.warning('Command (%s) failed (ret=%s).', cmd, ret) |
| 42 | return ret |
| 43 | |
| 44 | |
| 45 | def SimpleSystemOutput(cmd): |
| 46 | """Execute a system command and get its output.""" |
| 47 | try: |
| 48 | proc = subprocess.Popen( |
| 49 | cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) |
| 50 | stdout, _ = proc.communicate() |
| 51 | except Exception, e: |
| 52 | logging.warning('Command (%s) failed (%s).', cmd, e) |
| 53 | else: |
| 54 | return None if proc.returncode else stdout.strip() |
| 55 | |
| 56 | |
| 57 | def IsDestinationPortEnabled(port): |
| 58 | """Check if the destination port is enabled in iptables. |
| 59 | |
| 60 | If port 8000 is enabled, it looks like |
| 61 | ACCEPT tcp -- 0.0.0.0/0 0.0.0.0/0 ctstate NEW tcp dpt:8000 |
| 62 | """ |
| 63 | pattern = re.compile('ACCEPT\s+tcp.+\s+ctstate\s+NEW\s+tcp\s+dpt:%d' % port) |
| 64 | rules = SimpleSystemOutput('sudo iptables -L INPUT -n --line-number') |
| 65 | for rule in rules.splitlines(): |
| 66 | if pattern.search(rule): |
| 67 | return True |
| 68 | return False |
| 69 | |
| 70 | |
| 71 | def EnableDestinationPort(port): |
| 72 | """Enable the destination port for input traffic in iptables.""" |
| 73 | if IsDestinationPortEnabled(port): |
| 74 | cherrypy.log('Port %d has been already enabled in iptables.' % port) |
| 75 | else: |
Charlie Mooney | e15a555 | 2015-07-10 13:48:03 -0700 | [diff] [blame] | 76 | cherrypy.log('Adding a rule to accept incoming connections on port %d in ' |
| 77 | 'iptables.' % port) |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 78 | cmd = ('sudo iptables -A INPUT -p tcp -m conntrack --ctstate NEW ' |
| 79 | '--dport %d -j ACCEPT' % port) |
| 80 | if SimpleSystem(cmd) != 0: |
| 81 | raise Error('Failed to enable port in iptables: %d.' % port) |
| 82 | |
| 83 | |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 84 | def InterruptHandler(): |
| 85 | """An interrupt handler for both SIGINT and SIGTERM |
| 86 | |
| 87 | The stop procedure triggered is as follows: |
| 88 | 1. This handler sends a 'quit' message to the listening client. |
| 89 | 2. The client sends the canvas image back to the server in its quit message. |
| 90 | 3. WebplotWSHandler.received_message() saves the image. |
| 91 | 4. WebplotWSHandler.received_message() handles the 'quit' message. |
| 92 | The cherrypy engine exits if this is the last client. |
| 93 | """ |
| 94 | cherrypy.log('Cherrypy engine is sending quit message to clients.') |
Joseph Hwang | 95bf52a | 2015-04-14 13:09:39 +0800 | [diff] [blame] | 95 | state.QuitAndShutdown() |
| 96 | |
| 97 | |
| 98 | def _IOError(e, filename): |
| 99 | err_msg = ['\n', '!' * 60, str(e), |
| 100 | 'It is likely that %s is owned by root.' % filename, |
| 101 | 'Please remove the file and then run webplot again.', |
| 102 | '!' * 60, '\n'] |
| 103 | cherrypy.log('\n'.join(err_msg)) |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 104 | |
Charlie Mooney | c68f9c3 | 2015-04-16 15:23:22 -0700 | [diff] [blame] | 105 | image_lock = threading.Event() |
| 106 | image_string = '' |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 107 | |
| 108 | class WebplotWSHandler(WebSocket): |
| 109 | """The web socket handler for webplot.""" |
| 110 | |
| 111 | def opened(self): |
| 112 | """This method is called when the handler is opened.""" |
| 113 | cherrypy.log('WS handler is opened!') |
| 114 | |
| 115 | def received_message(self, msg): |
| 116 | """A callback for received message.""" |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 117 | data = msg.data.split(':', 1) |
| 118 | mtype = data[0].lower() |
| 119 | content = data[1] if len(data) == 2 else None |
Joseph Hwang | 0c1fa7d | 2015-04-09 17:01:45 +0800 | [diff] [blame] | 120 | |
| 121 | # Do not print the image data since it is too large. |
| 122 | if mtype != 'save': |
| 123 | cherrypy.log('Received message: %s' % str(msg.data)) |
| 124 | |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 125 | if mtype == 'quit': |
| 126 | # A shutdown message requested by the user. |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 127 | cherrypy.log('The user requests to shutdown the cherrypy server....') |
| 128 | state.DecCount() |
| 129 | elif mtype == 'save': |
Charlie Mooney | b476e89 | 2015-04-02 13:25:49 -0700 | [diff] [blame] | 130 | cherrypy.log('All data saved to "%s"' % SAVED_FILE) |
| 131 | self.SaveImage(content, SAVED_IMAGE) |
| 132 | cherrypy.log('Plot image saved to "%s"' % SAVED_IMAGE) |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 133 | else: |
| 134 | cherrypy.log('Unknown message type: %s' % mtype) |
| 135 | |
| 136 | def closed(self, code, reason="A client left the room."): |
| 137 | """This method is called when the handler is closed.""" |
| 138 | cherrypy.log('A client requests to close WS.') |
| 139 | cherrypy.engine.publish('websocket-broadcast', TextMessage(reason)) |
| 140 | |
| 141 | @staticmethod |
| 142 | def SaveImage(image_data, image_file): |
| 143 | """Decoded the base64 image data and save it in the file.""" |
Charlie Mooney | c68f9c3 | 2015-04-16 15:23:22 -0700 | [diff] [blame] | 144 | global image_string |
| 145 | image_string = base64.b64decode(image_data) |
| 146 | image_lock.set() |
Joseph Hwang | afc092c | 2015-04-21 11:32:45 +0800 | [diff] [blame] | 147 | try: |
| 148 | with open(image_file, 'w') as f: |
| 149 | f.write(image_string) |
| 150 | except IOError as e: |
| 151 | _IOError(e, image_file) |
| 152 | state.QuitAndShutdown() |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 153 | |
| 154 | |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 155 | class ConnectionState(object): |
| 156 | """A ws connection state object for shutting down the cherrypy server. |
| 157 | |
| 158 | It shuts down the cherrypy server when the count is down to 0 and is not |
| 159 | increased before the shutdown_timer expires. |
| 160 | |
| 161 | Note that when a page refreshes, it closes the WS connection first and |
| 162 | then re-connects immediately. This is why we would like to wait a while |
| 163 | before actually shutting down the server. |
| 164 | """ |
| 165 | TIMEOUT = 1.0 |
| 166 | |
| 167 | def __init__(self): |
| 168 | self.count = 0; |
| 169 | self.lock = threading.Lock() |
| 170 | self.shutdown_timer = None |
Joseph Hwang | 95bf52a | 2015-04-14 13:09:39 +0800 | [diff] [blame] | 171 | self.quit_flag = False |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 172 | |
| 173 | def IncCount(self): |
| 174 | """Increase the connection count, and cancel the shutdown timer if exists. |
| 175 | """ |
| 176 | self.lock.acquire() |
| 177 | self.count += 1; |
| 178 | cherrypy.log(' WS connection count: %d' % self.count) |
| 179 | if self.shutdown_timer: |
| 180 | self.shutdown_timer.cancel() |
| 181 | self.shutdown_timer = None |
| 182 | self.lock.release() |
| 183 | |
| 184 | def DecCount(self): |
| 185 | """Decrease the connection count, and start a shutdown timer if no other |
| 186 | clients are connecting to the server. |
| 187 | """ |
| 188 | self.lock.acquire() |
| 189 | self.count -= 1; |
| 190 | cherrypy.log(' WS connection count: %d' % self.count) |
| 191 | if self.count == 0: |
| 192 | self.shutdown_timer = threading.Timer(self.TIMEOUT, self.Shutdown) |
| 193 | self.shutdown_timer.start() |
| 194 | self.lock.release() |
| 195 | |
Joseph Hwang | 3f561d3 | 2015-04-09 16:33:56 +0800 | [diff] [blame] | 196 | def ShutdownWhenNoConnections(self): |
| 197 | """Shutdown cherrypy server when there is no client connection.""" |
| 198 | self.lock.acquire() |
| 199 | if self.count == 0 and self.shutdown_timer is None: |
| 200 | self.Shutdown() |
| 201 | self.lock.release() |
| 202 | |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 203 | def Shutdown(self): |
| 204 | """Shutdown the cherrypy server.""" |
| 205 | cherrypy.log('Shutdown timer expires. Cherrypy server for Webplot exits.') |
| 206 | cherrypy.engine.exit() |
| 207 | |
Joseph Hwang | 95bf52a | 2015-04-14 13:09:39 +0800 | [diff] [blame] | 208 | def QuitAndShutdown(self): |
| 209 | """The server notifies clients to quit and then shuts down.""" |
| 210 | if not self.quit_flag: |
| 211 | self.quit_flag = True |
| 212 | cherrypy.engine.publish('websocket-broadcast', TextMessage('quit')) |
| 213 | self.ShutdownWhenNoConnections() |
| 214 | |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 215 | |
| 216 | class Root(object): |
| 217 | """A class to handle requests about docroot.""" |
| 218 | |
| 219 | def __init__(self, ip, port, touch_min_x, touch_max_x, touch_min_y, |
| 220 | touch_max_y, touch_min_pressure, touch_max_pressure): |
| 221 | self.ip = ip |
| 222 | self.port = port |
| 223 | self.touch_min_x = touch_min_x |
| 224 | self.touch_max_x = touch_max_x |
| 225 | self.touch_min_y = touch_min_y |
| 226 | self.touch_max_y = touch_max_y |
| 227 | self.touch_min_pressure = touch_min_pressure |
| 228 | self.touch_max_pressure = touch_max_pressure |
| 229 | self.scheme = 'ws' |
| 230 | cherrypy.log('Root address: (%s, %s)' % (ip, str(port))) |
| 231 | cherrypy.log('scheme: %s' % self.scheme) |
| 232 | |
| 233 | @cherrypy.expose |
| 234 | def index(self): |
| 235 | """This is the default index.html page.""" |
| 236 | websocket_dict = { |
| 237 | 'websocketUrl': '%s://%s:%s/ws' % (self.scheme, self.ip, self.port), |
| 238 | 'touchMinX': str(self.touch_min_x), |
| 239 | 'touchMaxX': str(self.touch_max_x), |
| 240 | 'touchMinY': str(self.touch_min_y), |
| 241 | 'touchMaxY': str(self.touch_max_y), |
| 242 | 'touchMinPressure': str(self.touch_min_pressure), |
| 243 | 'touchMaxPressure': str(self.touch_max_pressure), |
| 244 | } |
| 245 | root_page = os.path.join(os.path.abspath(os.path.dirname(__file__)), |
| 246 | 'webplot.html') |
| 247 | with open(root_page) as f: |
| 248 | return f.read() % websocket_dict |
| 249 | |
| 250 | @cherrypy.expose |
| 251 | def ws(self): |
| 252 | """This handles the request to create a new web socket per client.""" |
| 253 | cherrypy.log('A new client requesting for WS') |
| 254 | cherrypy.log('WS handler created: %s' % repr(cherrypy.request.ws_handler)) |
| 255 | state.IncCount() |
| 256 | |
| 257 | |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 258 | class Webplot(threading.Thread): |
| 259 | """The server handling the Plotting of finger traces. |
| 260 | |
| 261 | Use case 1: embedding Webplot as a plotter in an application |
| 262 | |
| 263 | # Instantiate a webplot server and starts the daemon. |
| 264 | plot = Webplot(server_addr, server_port, device) |
| 265 | plot.start() |
| 266 | |
| 267 | # Repeatedly get a snapshot and add it for plotting. |
| 268 | while True: |
| 269 | # GetSnapshot() is essentially device.NextSnapshot() |
| 270 | snapshot = plot.GetSnapshot() |
| 271 | if not snapshot: |
| 272 | break |
| 273 | # Add the snapshot to the plotter for plotting. |
| 274 | plot.AddSnapshot(snapshot) |
| 275 | |
| 276 | # Save a screen dump |
| 277 | plot.Save() |
| 278 | |
| 279 | # Notify the browser to clear the screen. |
| 280 | plot.Clear() |
| 281 | |
| 282 | # Notify both the browser and the cherrypy engine to quit. |
| 283 | plot.Quit() |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 284 | |
| 285 | |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 286 | Use case 2: using webplot standalone |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 287 | |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 288 | # Instantiate a webplot server and starts the daemon. |
| 289 | plot = Webplot(server_addr, server_port, device) |
| 290 | plot.start() |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 291 | |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 292 | # Get touch snapshots from the touch device and have clients plot them. |
| 293 | webplot.GetAndPlotSnapshots() |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 294 | """ |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 295 | |
Joseph Hwang | e9cfd64 | 2015-04-20 16:00:33 +0800 | [diff] [blame] | 296 | def __init__(self, server_addr, server_port, device, saved_file=SAVED_FILE, |
Charlie Mooney | e15a555 | 2015-07-10 13:48:03 -0700 | [diff] [blame] | 297 | logging=False, is_behind_iptables_firewall=False): |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 298 | self._server_addr = server_addr |
| 299 | self._server_port = server_port |
| 300 | self._device = device |
| 301 | self._saved_file = saved_file |
| 302 | super(Webplot, self).__init__(name='webplot thread') |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 303 | |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 304 | self.daemon = True |
| 305 | self._prev_tids = [] |
| 306 | |
Joseph Hwang | e9cfd64 | 2015-04-20 16:00:33 +0800 | [diff] [blame] | 307 | # The logging is turned off by default when imported as a module so that |
| 308 | # it does not mess up the screen. |
| 309 | if not logging: |
| 310 | cherrypy.log.screen = None |
| 311 | |
Charlie Mooney | e15a555 | 2015-07-10 13:48:03 -0700 | [diff] [blame] | 312 | # Allow input traffic in iptables, if the user has specified. This setting |
| 313 | # should be used if webplot is being run directly on a chromebook, but it |
| 314 | # requires root access, so we don't want to use it all the time. |
| 315 | if is_behind_iptables_firewall: |
| 316 | EnableDestinationPort(self._server_port) |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 317 | |
| 318 | # Create a ws connection state object to wait for the condition to |
| 319 | # shutdown the whole process. |
| 320 | global state |
| 321 | state = ConnectionState() |
| 322 | |
| 323 | cherrypy.config.update({ |
| 324 | 'server.socket_host': self._server_addr, |
| 325 | 'server.socket_port': self._server_port, |
| 326 | }) |
| 327 | |
| 328 | WebSocketPlugin(cherrypy.engine).subscribe() |
| 329 | cherrypy.tools.websocket = WebSocketTool() |
| 330 | |
| 331 | # If the cherrypy server exits for whatever reason, close the device |
| 332 | # for required cleanup. Otherwise, there might exist local/remote |
| 333 | # zombie processes. |
Charlie Mooney | c68f9c3 | 2015-04-16 15:23:22 -0700 | [diff] [blame] | 334 | cherrypy.engine.subscribe('exit', self._device.__del__) |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 335 | |
| 336 | cherrypy.engine.signal_handler.handlers['SIGINT'] = InterruptHandler |
| 337 | cherrypy.engine.signal_handler.handlers['SIGTERM'] = InterruptHandler |
| 338 | |
| 339 | def run(self): |
| 340 | """Start the cherrypy engine.""" |
Charlie Mooney | c68f9c3 | 2015-04-16 15:23:22 -0700 | [diff] [blame] | 341 | x_min, x_max = self._device.RangeX() |
| 342 | y_min, y_max = self._device.RangeY() |
| 343 | p_min, p_max = self._device.RangeP() |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 344 | |
| 345 | cherrypy.quickstart( |
| 346 | Root(self._server_addr, self._server_port, |
| 347 | x_min, x_max, y_min, y_max, p_min, p_max), |
| 348 | '', |
| 349 | config={ |
| 350 | '/': { |
| 351 | 'tools.staticdir.root': |
| 352 | os.path.abspath(os.path.dirname(__file__)), |
| 353 | 'tools.staticdir.on': True, |
| 354 | 'tools.staticdir.dir': '', |
| 355 | }, |
| 356 | '/ws': { |
| 357 | 'tools.websocket.on': True, |
| 358 | 'tools.websocket.handler_cls': WebplotWSHandler, |
| 359 | }, |
| 360 | } |
| 361 | ) |
| 362 | |
| 363 | def _ConvertNamedtupleToDict(self, snapshot): |
| 364 | """Convert namedtuples to ordinary dictionaries and add leaving slots. |
| 365 | |
| 366 | This is to make a snapshot json serializable. Otherwise, the namedtuples |
| 367 | would be transmitted as arrays which is less readable. |
| 368 | |
| 369 | A snapshot looks like |
| 370 | MtSnapshot( |
| 371 | syn_time=1420524008.368854, |
| 372 | button_pressed=False, |
| 373 | fingers=[ |
| 374 | MtFinger(tid=162, slot=0, syn_time=1420524008.368854, x=524, |
| 375 | y=231, pressure=45), |
| 376 | MtFinger(tid=163, slot=1, syn_time=1420524008.368854, x=677, |
| 377 | y=135, pressure=57) |
| 378 | ] |
| 379 | ) |
| 380 | |
| 381 | Note: |
| 382 | 1. that there are two levels of namedtuples to convert. |
| 383 | 2. The leaving slots are used to notify javascript that a finger is leaving |
| 384 | so that the corresponding finger color could be released for reuse. |
| 385 | """ |
| 386 | # Convert MtSnapshot. |
| 387 | converted = dict(snapshot.__dict__.items()) |
| 388 | |
| 389 | # Convert MtFinger. |
| 390 | converted['fingers'] = [dict(finger.__dict__.items()) |
| 391 | for finger in converted['fingers']] |
| 392 | converted['raw_events'] = [str(event) for event in converted['raw_events']] |
| 393 | |
| 394 | # Add leaving fingers to notify js for reclaiming the finger colors. |
| 395 | curr_tids = [finger['tid'] for finger in converted['fingers']] |
| 396 | for tid in set(self._prev_tids) - set(curr_tids): |
| 397 | leaving_finger = {'tid': tid, 'leaving': True} |
| 398 | converted['fingers'].append(leaving_finger) |
| 399 | self._prev_tids = curr_tids |
| 400 | |
Joseph Hwang | 02e829c | 2015-04-13 17:09:07 +0800 | [diff] [blame] | 401 | # Convert raw events from a list of classes to a list of its strings |
| 402 | # so that the raw_events is serializable. |
| 403 | converted['raw_events'] = [str(event) for event in converted['raw_events']] |
| 404 | |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 405 | return converted |
| 406 | |
| 407 | def GetSnapshot(self): |
| 408 | """Get a snapshot from the touch device.""" |
Charlie Mooney | c68f9c3 | 2015-04-16 15:23:22 -0700 | [diff] [blame] | 409 | return self._device.NextSnapshot() |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 410 | |
| 411 | def AddSnapshot(self, snapshot): |
| 412 | """Convert the snapshot to a proper format and publish it to clients.""" |
| 413 | snapshot = self._ConvertNamedtupleToDict(snapshot) |
| 414 | cherrypy.engine.publish('websocket-broadcast', json.dumps(snapshot)) |
Joseph Hwang | 02e829c | 2015-04-13 17:09:07 +0800 | [diff] [blame] | 415 | return snapshot |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 416 | |
| 417 | def GetAndPlotSnapshots(self): |
| 418 | """Get and plot snapshots.""" |
| 419 | cherrypy.log('Start getting the live stream snapshots....') |
Joseph Hwang | 95bf52a | 2015-04-14 13:09:39 +0800 | [diff] [blame] | 420 | try: |
| 421 | with open(self._saved_file, 'w') as f: |
| 422 | while True: |
| 423 | try: |
| 424 | snapshot = self.GetSnapshot() |
| 425 | if not snapshot: |
| 426 | cherrypy.log('webplot is terminated.') |
| 427 | break |
| 428 | converted_snapshot = self.AddSnapshot(snapshot) |
| 429 | f.write('\n'.join(converted_snapshot['raw_events']) + '\n') |
| 430 | f.flush() |
| 431 | except KeyboardInterrupt: |
| 432 | cherrypy.log('Keyboard Interrupt accepted') |
| 433 | cherrypy.log('webplot is being terminated...') |
| 434 | state.QuitAndShutdown() |
| 435 | except IOError as e: |
| 436 | _IOError(e, self._saved_file) |
| 437 | state.QuitAndShutdown() |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 438 | |
| 439 | def Publish(self, msg): |
| 440 | """Publish a message to clients.""" |
| 441 | cherrypy.engine.publish('websocket-broadcast', TextMessage(msg)) |
| 442 | |
| 443 | def Clear(self): |
| 444 | """Notify clients to clear the display.""" |
| 445 | self.Publish('clear') |
| 446 | |
| 447 | def Quit(self): |
| 448 | """Notify clients to quit. |
| 449 | |
| 450 | Note that the cherrypy engine would quit accordingly. |
| 451 | """ |
Joseph Hwang | 95bf52a | 2015-04-14 13:09:39 +0800 | [diff] [blame] | 452 | state.QuitAndShutdown() |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 453 | |
Charlie Mooney | c68f9c3 | 2015-04-16 15:23:22 -0700 | [diff] [blame] | 454 | def Save(self, wait_for_image=False): |
| 455 | """Notify clients to save the screen, then wait for the file to appear |
| 456 | on disk and return it. |
| 457 | """ |
| 458 | global image_lock |
| 459 | global image_string |
| 460 | |
| 461 | # Trigger a save action |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 462 | self.Publish('save') |
| 463 | |
Charlie Mooney | c68f9c3 | 2015-04-16 15:23:22 -0700 | [diff] [blame] | 464 | # Block until the server has completed saving it to disk |
| 465 | image_lock.wait() |
| 466 | image_lock.clear() |
| 467 | return image_string |
| 468 | |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 469 | def Url(self): |
| 470 | """The url the server is serving at.""" |
| 471 | return 'http://%s:%d' % (self._server_addr, self._server_port) |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 472 | |
| 473 | |
Joseph Hwang | a1c8478 | 2015-04-14 15:07:00 +0800 | [diff] [blame] | 474 | def _CheckLegalUser(): |
| 475 | """If this program is run in chroot, it should not be run as root for security |
| 476 | reason. |
| 477 | """ |
| 478 | if os.path.exists('/etc/cros_chroot_version') and os.getuid() == 0: |
| 479 | print ('You should run webplot in chroot as a regular user ' |
| 480 | 'instead of as root.\n') |
| 481 | exit(1) |
| 482 | |
| 483 | |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 484 | def _ParseArguments(): |
| 485 | """Parse the command line options.""" |
| 486 | parser = argparse.ArgumentParser(description='Webplot Server') |
Charlie Mooney | 8026f2a | 2015-04-02 13:01:28 -0700 | [diff] [blame] | 487 | parser.add_argument('-d', '--dut_addr', default=None, |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 488 | help='the address of the dut') |
Joseph Hwang | 59db441 | 2015-04-09 12:43:16 +0800 | [diff] [blame] | 489 | |
| 490 | # Make an exclusive group to make the webplot.py command option |
| 491 | # consistent with the webplot.sh script command option. |
| 492 | # What is desired: |
| 493 | # When no command option specified in webplot.sh/webplot.py: grab is True |
| 494 | # When '--grab' option specified in webplot.sh/webplot.py: grab is True |
| 495 | # When '--nograb' option specified in webplot.sh/webplot.py: grab is False |
| 496 | grab_group = parser.add_mutually_exclusive_group() |
| 497 | grab_group.add_argument('--grab', help='grab the device exclusively', |
| 498 | action='store_true') |
| 499 | grab_group.add_argument('--nograb', help='do not grab the device', |
| 500 | action='store_true') |
| 501 | |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 502 | parser.add_argument('--is_touchscreen', help='the DUT is touchscreen', |
| 503 | action='store_true') |
Charlie Mooney | e15a555 | 2015-07-10 13:48:03 -0700 | [diff] [blame] | 504 | parser.add_argument('-p', '--server_port', default=8080, type=int, |
| 505 | help='the port the web server listens to (default: 8080)') |
| 506 | parser.add_argument('--behind_firewall', action='store_true', |
| 507 | help=('With this flag set, you tell webplot to add a ' |
| 508 | 'rule to iptables to allow incoming traffic to ' |
| 509 | 'the webserver. If you are running webplot on ' |
| 510 | 'a chromebook, this is needed.')) |
| 511 | parser.add_argument('-s', '--server_addr', default='127.0.0.1', |
Joseph Hwang | 59db441 | 2015-04-09 12:43:16 +0800 | [diff] [blame] | 512 | help='the address the webplot http server listens to') |
| 513 | parser.add_argument('-t', '--dut_type', default='chromeos', type=str.lower, |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 514 | help='dut type: chromeos, android') |
| 515 | args = parser.parse_args() |
Joseph Hwang | 59db441 | 2015-04-09 12:43:16 +0800 | [diff] [blame] | 516 | |
| 517 | args.grab = not args.nograb |
| 518 | |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 519 | return args |
| 520 | |
| 521 | |
| 522 | def Main(): |
| 523 | """The main function to launch webplot service.""" |
Joseph Hwang | a1c8478 | 2015-04-14 15:07:00 +0800 | [diff] [blame] | 524 | _CheckLegalUser() |
| 525 | |
Joseph Hwang | e9cfd64 | 2015-04-20 16:00:33 +0800 | [diff] [blame] | 526 | configure_logger(level=logging.ERROR) |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 527 | args = _ParseArguments() |
| 528 | |
| 529 | print '\n' + '-' * 70 |
| 530 | cherrypy.log('dut machine type: %s' % args.dut_type) |
| 531 | cherrypy.log('dut\'s touch device: %s' % |
| 532 | ('touchscreen' if args.is_touchscreen else 'touchpad')) |
| 533 | cherrypy.log('dut address: %s' % args.dut_addr) |
| 534 | cherrypy.log('web server address: %s' % args.server_addr) |
| 535 | cherrypy.log('web server port: %s' % args.server_port) |
Joseph Hwang | 59db441 | 2015-04-09 12:43:16 +0800 | [diff] [blame] | 536 | cherrypy.log('grab the touch device: %s' % args.grab) |
| 537 | if args.dut_type == 'android' and args.grab: |
| 538 | cherrypy.log('Warning: the grab option is not supported on Android devices' |
| 539 | ' yet.') |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 540 | cherrypy.log('touch events are saved in %s' % SAVED_FILE) |
| 541 | print '-' * 70 + '\n\n' |
| 542 | |
| 543 | if args.server_port == 80: |
| 544 | url = args.server_addr |
| 545 | else: |
| 546 | url = '%s:%d' % (args.server_addr, args.server_port) |
| 547 | |
| 548 | msg = 'Type "%s" in browser %s to see finger traces.\n' |
Charlie Mooney | e15a555 | 2015-07-10 13:48:03 -0700 | [diff] [blame] | 549 | if args.server_addr == '127.0.0.1': |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 550 | which_machine = 'on the webplot server machine' |
| 551 | else: |
| 552 | which_machine = 'on any machine' |
| 553 | |
| 554 | print '*' * 70 |
| 555 | print msg % (url, which_machine) |
| 556 | print 'Press \'q\' on the browser to quit.' |
| 557 | print '*' * 70 + '\n\n' |
| 558 | |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 559 | # Instantiate a touch device. |
Charlie Mooney | c68f9c3 | 2015-04-16 15:23:22 -0700 | [diff] [blame] | 560 | if args.dut_type == 'chromeos': |
| 561 | addr = args.dut_addr if args.dut_addr else '127.0.0.1' |
| 562 | device = ChromeOSTouchDevice(addr, args.is_touchscreen, grab=args.grab) |
| 563 | else: |
| 564 | device = AndroidTouchDevice(args.dut_addr, True) |
| 565 | |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 566 | |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 567 | # Instantiate a webplot server daemon and start it. |
Charlie Mooney | e15a555 | 2015-07-10 13:48:03 -0700 | [diff] [blame] | 568 | webplot = Webplot(args.server_addr, args.server_port, device, logging=True, |
| 569 | is_behind_iptables_firewall=args.behind_firewall) |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 570 | webplot.start() |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 571 | |
Joseph Hwang | 4782a04 | 2015-04-08 17:15:50 +0800 | [diff] [blame] | 572 | # Get touch snapshots from the touch device and have clients plot them. |
| 573 | webplot.GetAndPlotSnapshots() |
Charlie Mooney | bbc05f5 | 2015-03-24 13:36:22 -0700 | [diff] [blame] | 574 | |
| 575 | |
| 576 | if __name__ == '__main__': |
| 577 | Main() |