Replace NextEvent with NextSnapshot

This patch uses NextSnapshot to replace NextEvent, and computes
the leaving TIDs.

Note that NextSnapshot does not return raw events for now. When
it does later, the raw events should be processed accordingly.

BUG=chromium:466552
TEST=Emerge and deploy webplot to a chromebook.
Run webplot on the chromebook and see it execute correctly.
$ webplot
CQ-DEPEND=I7661239218087f6199ef0ce91fb84e08e7bd8ca0

Change-Id: I93cab35aad890795bfa21fcb573dd0b1f328d570
Reviewed-on: https://chromium-review.googlesource.com/260196
Reviewed-by: Charlie Mooney <charliemooney@chromium.org>
Commit-Queue: Shyh-In Hwang <josephsih@chromium.org>
Tested-by: Shyh-In Hwang <josephsih@chromium.org>
diff --git a/webplot/webplot.py b/webplot/webplot.py
index dac746b..8de0643 100755
--- a/webplot/webplot.py
+++ b/webplot/webplot.py
@@ -97,11 +97,11 @@
       self.device = ChromeOSTouchDevice(addr, is_touchscreen)
     else:
       self.device = AndroidTouchDevice(addr, True)
-    self.device.BeginEventStream()
 
   def close(self):
     """ Close the device gracefully. """
-    self.device.EndEventStream()
+    if self.device.event_stream_process:
+      self.device.__del__()
 
   def __str__(self):
     return '\n  '.join(sorted([str(slot) for slot in self.slots.values()]))
@@ -110,7 +110,7 @@
 def ThreadedGetLiveStreamSnapshots(device, saved_file):
   """A thread to poll and get live stream snapshots continuously."""
 
-  def _ConvertNamedtupleToDict(snapshot, leaving_slots):
+  def _ConvertNamedtupleToDict(snapshot, prev_tids):
     """Convert namedtuples to ordinary dictionaries and add leaving slots.
 
     This is to make a snapshot json serializable. Otherwise, the namedtuples
@@ -140,27 +140,31 @@
     converted['fingers'] = [dict(finger.__dict__.items())
                             for finger in converted['fingers']]
 
-    # Add leaving attribute.
-    for finger in converted['fingers']:
-      finger['leaving'] = bool(finger['slot'] in leaving_slots)
+    # Add leaving fingers to notify js for reclaiming the finger colors.
+    curr_tids = [finger['tid'] for finger in converted['fingers']]
+    for tid in set(prev_tids) - set(curr_tids):
+      leaving_finger = {'tid': tid, 'leaving': True}
+      converted['fingers'].append(leaving_finger)
 
-    return converted
+    return converted, curr_tids
 
-  def _GetLiveStreamSnapshots():
+  def _GetSnapshots():
     """Get live stream snapshots."""
     cherrypy.log('Start getting the live stream snapshots....')
-    snapshot_stream = remote.mt.SnapshotStream(device.device)
+    prev_tids = []
     with open(saved_file, 'w') as f:
       while True:
-        snapshot, events, leaving_slots = snapshot_stream.Get()
+        snapshot = device.device.NextSnapshot()
+        # TODO: remove the next line when NextSnapshot returns the raw events.
+        events = []
         if snapshot:
           f.write('\n'.join(events) + '\n')
           f.flush()
-          snapshot = _ConvertNamedtupleToDict(snapshot, leaving_slots)
+          snapshot, prev_tids = _ConvertNamedtupleToDict(snapshot, prev_tids)
           cherrypy.engine.publish('websocket-broadcast', json.dumps(snapshot))
 
-  get_snapshot_thread = threading.Thread(target=_GetLiveStreamSnapshots,
-                                         name='_GetLiveStreamSnapshots')
+  get_snapshot_thread = threading.Thread(target=_GetSnapshots,
+                                         name='_GetSnapshots')
   get_snapshot_thread.daemon = True
   get_snapshot_thread.start()