blob: f5e2dc49238c5cd487807f05d89037e200bbed5c [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
14import re
15import subprocess
Charlie Mooneyc68f9c32015-04-16 15:23:22 -070016import time
Charlie Mooneybbc05f52015-03-24 13:36:22 -070017import threading
18
19import cherrypy
20
Charlie Mooneybbc05f52015-03-24 13:36:22 -070021from ws4py import configure_logger
22from ws4py.messaging import TextMessage
23from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool
24from ws4py.websocket import WebSocket
25
Charlie Mooney04b41532015-04-02 12:41:37 -070026from remote import ChromeOSTouchDevice, AndroidTouchDevice
Charlie Mooneybbc05f52015-03-24 13:36:22 -070027
28
29# The WebSocket connection state object.
30state = None
31
32# The touch events are saved in this file as default.
33SAVED_FILE = '/tmp/webplot.dat'
34SAVED_IMAGE = '/tmp/webplot.png'
35
36
Joseph Hwang4782a042015-04-08 17:15:50 +080037def 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
45def 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
57def 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
71def 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 Mooneye15a5552015-07-10 13:48:03 -070076 cherrypy.log('Adding a rule to accept incoming connections on port %d in '
77 'iptables.' % port)
Joseph Hwang4782a042015-04-08 17:15:50 +080078 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 Mooneybbc05f52015-03-24 13:36:22 -070084def 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 Hwang95bf52a2015-04-14 13:09:39 +080095 state.QuitAndShutdown()
96
97
98def _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 Mooneybbc05f52015-03-24 13:36:22 -0700104
Charlie Mooneyc68f9c32015-04-16 15:23:22 -0700105image_lock = threading.Event()
106image_string = ''
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700107
108class 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 Mooneybbc05f52015-03-24 13:36:22 -0700117 data = msg.data.split(':', 1)
118 mtype = data[0].lower()
119 content = data[1] if len(data) == 2 else None
Joseph Hwang0c1fa7d2015-04-09 17:01:45 +0800120
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 Mooneybbc05f52015-03-24 13:36:22 -0700125 if mtype == 'quit':
126 # A shutdown message requested by the user.
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700127 cherrypy.log('The user requests to shutdown the cherrypy server....')
128 state.DecCount()
129 elif mtype == 'save':
Charlie Mooneyb476e892015-04-02 13:25:49 -0700130 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 Mooneybbc05f52015-03-24 13:36:22 -0700133 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 Mooneyc68f9c32015-04-16 15:23:22 -0700144 global image_string
145 image_string = base64.b64decode(image_data)
146 image_lock.set()
Joseph Hwangafc092c2015-04-21 11:32:45 +0800147 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 Mooneybbc05f52015-03-24 13:36:22 -0700153
154
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700155class 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 Hwang95bf52a2015-04-14 13:09:39 +0800171 self.quit_flag = False
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700172
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 Hwang3f561d32015-04-09 16:33:56 +0800196 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 Mooneybbc05f52015-03-24 13:36:22 -0700203 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 Hwang95bf52a2015-04-14 13:09:39 +0800208 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 Mooneybbc05f52015-03-24 13:36:22 -0700215
216class 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 Hwang4782a042015-04-08 17:15:50 +0800258class 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 Mooneybbc05f52015-03-24 13:36:22 -0700284
285
Joseph Hwang4782a042015-04-08 17:15:50 +0800286 Use case 2: using webplot standalone
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700287
Joseph Hwang4782a042015-04-08 17:15:50 +0800288 # Instantiate a webplot server and starts the daemon.
289 plot = Webplot(server_addr, server_port, device)
290 plot.start()
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700291
Joseph Hwang4782a042015-04-08 17:15:50 +0800292 # Get touch snapshots from the touch device and have clients plot them.
293 webplot.GetAndPlotSnapshots()
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700294 """
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700295
Joseph Hwange9cfd642015-04-20 16:00:33 +0800296 def __init__(self, server_addr, server_port, device, saved_file=SAVED_FILE,
Charlie Mooneye15a5552015-07-10 13:48:03 -0700297 logging=False, is_behind_iptables_firewall=False):
Joseph Hwang4782a042015-04-08 17:15:50 +0800298 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 Mooneybbc05f52015-03-24 13:36:22 -0700303
Joseph Hwang4782a042015-04-08 17:15:50 +0800304 self.daemon = True
305 self._prev_tids = []
306
Joseph Hwange9cfd642015-04-20 16:00:33 +0800307 # 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 Mooneye15a5552015-07-10 13:48:03 -0700312 # 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 Hwang4782a042015-04-08 17:15:50 +0800317
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 Mooneyc68f9c32015-04-16 15:23:22 -0700334 cherrypy.engine.subscribe('exit', self._device.__del__)
Joseph Hwang4782a042015-04-08 17:15:50 +0800335
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 Mooneyc68f9c32015-04-16 15:23:22 -0700341 x_min, x_max = self._device.RangeX()
342 y_min, y_max = self._device.RangeY()
343 p_min, p_max = self._device.RangeP()
Joseph Hwang4782a042015-04-08 17:15:50 +0800344
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 Hwang02e829c2015-04-13 17:09:07 +0800401 # 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 Hwang4782a042015-04-08 17:15:50 +0800405 return converted
406
407 def GetSnapshot(self):
408 """Get a snapshot from the touch device."""
Charlie Mooneyc68f9c32015-04-16 15:23:22 -0700409 return self._device.NextSnapshot()
Joseph Hwang4782a042015-04-08 17:15:50 +0800410
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 Hwang02e829c2015-04-13 17:09:07 +0800415 return snapshot
Joseph Hwang4782a042015-04-08 17:15:50 +0800416
417 def GetAndPlotSnapshots(self):
418 """Get and plot snapshots."""
419 cherrypy.log('Start getting the live stream snapshots....')
Joseph Hwang95bf52a2015-04-14 13:09:39 +0800420 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 Hwang4782a042015-04-08 17:15:50 +0800438
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 Hwang95bf52a2015-04-14 13:09:39 +0800452 state.QuitAndShutdown()
Joseph Hwang4782a042015-04-08 17:15:50 +0800453
Charlie Mooneyc68f9c32015-04-16 15:23:22 -0700454 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 Hwang4782a042015-04-08 17:15:50 +0800462 self.Publish('save')
463
Charlie Mooneyc68f9c32015-04-16 15:23:22 -0700464 # Block until the server has completed saving it to disk
465 image_lock.wait()
466 image_lock.clear()
467 return image_string
468
Joseph Hwang4782a042015-04-08 17:15:50 +0800469 def Url(self):
470 """The url the server is serving at."""
471 return 'http://%s:%d' % (self._server_addr, self._server_port)
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700472
473
Joseph Hwanga1c84782015-04-14 15:07:00 +0800474def _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 Mooneybbc05f52015-03-24 13:36:22 -0700484def _ParseArguments():
485 """Parse the command line options."""
486 parser = argparse.ArgumentParser(description='Webplot Server')
Charlie Mooney8026f2a2015-04-02 13:01:28 -0700487 parser.add_argument('-d', '--dut_addr', default=None,
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700488 help='the address of the dut')
Joseph Hwang59db4412015-04-09 12:43:16 +0800489
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 Mooneybbc05f52015-03-24 13:36:22 -0700502 parser.add_argument('--is_touchscreen', help='the DUT is touchscreen',
503 action='store_true')
Charlie Mooneye15a5552015-07-10 13:48:03 -0700504 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 Hwang59db4412015-04-09 12:43:16 +0800512 help='the address the webplot http server listens to')
513 parser.add_argument('-t', '--dut_type', default='chromeos', type=str.lower,
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700514 help='dut type: chromeos, android')
515 args = parser.parse_args()
Joseph Hwang59db4412015-04-09 12:43:16 +0800516
517 args.grab = not args.nograb
518
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700519 return args
520
521
522def Main():
523 """The main function to launch webplot service."""
Joseph Hwanga1c84782015-04-14 15:07:00 +0800524 _CheckLegalUser()
525
Joseph Hwange9cfd642015-04-20 16:00:33 +0800526 configure_logger(level=logging.ERROR)
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700527 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 Hwang59db4412015-04-09 12:43:16 +0800536 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 Mooneybbc05f52015-03-24 13:36:22 -0700540 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 Mooneye15a5552015-07-10 13:48:03 -0700549 if args.server_addr == '127.0.0.1':
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700550 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 Mooneybbc05f52015-03-24 13:36:22 -0700559 # Instantiate a touch device.
Charlie Mooneyc68f9c32015-04-16 15:23:22 -0700560 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 Mooneybbc05f52015-03-24 13:36:22 -0700566
Joseph Hwang4782a042015-04-08 17:15:50 +0800567 # Instantiate a webplot server daemon and start it.
Charlie Mooneye15a5552015-07-10 13:48:03 -0700568 webplot = Webplot(args.server_addr, args.server_port, device, logging=True,
569 is_behind_iptables_firewall=args.behind_firewall)
Joseph Hwang4782a042015-04-08 17:15:50 +0800570 webplot.start()
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700571
Joseph Hwang4782a042015-04-08 17:15:50 +0800572 # Get touch snapshots from the touch device and have clients plot them.
573 webplot.GetAndPlotSnapshots()
Charlie Mooneybbc05f52015-03-24 13:36:22 -0700574
575
576if __name__ == '__main__':
577 Main()