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