Allow to have more than one notification type in Service
[gregoa/zavai.git] / zavai / gps.py
index ff97253bd589c2d5f240bba2f14fbe298b09f142..bb551097979ec2eb3a247c8c593a3ddb73461c37 100755 (executable)
@@ -23,8 +23,10 @@ import time
 import dbus
 import zavai
 
-class GPSMonitor():
+class GPSMonitor(zavai.Service):
     def __init__(self, gps):
+        super(GPSMonitor, self).__init__(["satellites"])
+
         self.gps = gps
         self.gps_ubx = gps.gps_ubx
 
@@ -34,8 +36,6 @@ class GPSMonitor():
         self.debug_have = set()
         self.debug_error = set()
 
-        self.callbacks = set()
-
     def debug_update(self):
         if self.debug_busy is None:
             pending = self.debug_want - self.debug_have - self.debug_error
@@ -69,11 +69,10 @@ class GPSMonitor():
 
     def on_ubxdebug_packet(self, clid, length, data):
         zavai.info("gps monitor: UBX debug packet")
-        for c in self.callbacks:
-            c(clid, length, data)
+        self.notify("satellites", clid, length, data)
 
-    def _start_listening(self):
-        self.gps.request(self)
+    def start(self):
+        self.gps.connect("gps", self)
         # TODO: find out how come sometimes these events are not sent
         self.gps.bus.add_signal_receiver(
             self.on_satellites_changed, 'SatellitesChanged', 'org.freedesktop.Gypsy.Satellite',
@@ -83,69 +82,42 @@ class GPSMonitor():
             'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
         self.debug_request()
 
-    def _stop_listening(self):
+    def stop(self):
         self.gps.bus.remove_signal_receiver(
             self.on_satellites_changed, 'SatellitesChanged', 'org.freedesktop.Gypsy.Satellite',
             'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
         self.gps.bus.remove_signal_receiver(
             self.on_ubxdebug_packet, 'DebugPacket', 'org.freesmartphone.GPS.UBX',
             'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
-        self.gps.release(self)
-
-    def connect(self, callback):
-        "Send UBX debug packets to the given callback"
-        do_start = not self.callbacks
-        self.callbacks.add(callback)
-        if do_start:
-            self._start_listening()
-
-    def disconnect(self, callback):
-        "Stop sending UBX debug packets to the given callback"
-        if not self.callbacks: return
-        self.callbacks.discard(callback)
-        if not self.callbacks:
-            self._stop_listening()
-
-class GPSPosition():
+        self.gps.disconnect("gps", self)
+
+
+class GPSPosition(zavai.Service):
     def __init__(self, gps):
+        super(GPSPosition, self).__init__(["position"])
         self.gps = gps
-        self.callbacks = set()
 
     def on_position_changed(self, fields, tstamp, lat, lon, alt):
         zavai.info("gps position: position changed")
-        for c in self.callbacks:
-            c(fields, tstamp, lat, lon, alt)
+        self.notify("position", fields, tstamp, lat, lon, alt)
 
-    def _start_listening(self):
-        self.gps.request(self)
+    def start(self):
+        self.gps.connect("gps", self)
         self.gps.bus.add_signal_receiver(
             self.on_position_changed, 'PositionChanged', 'org.freedesktop.Gypsy.Position',
             'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
 
-    def _stop_listening(self):
+    def stop(self):
         self.gps.bus.remove_signal_receiver(
             self.on_position_changed, 'PositionChanged', 'org.freedesktop.Gypsy.Position',
             'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
-        self.gps.release(self)
-
-    def connect(self, callback):
-        "Send position changed messages to the given callback"
-        do_start = not self.callbacks
-        self.callbacks.add(callback)
-        if do_start:
-            self._start_listening()
-
-    def disconnect(self, callback):
-        "Stop sending position changed messages to the given callback"
-        if not self.callbacks: return
-        self.callbacks.discard(callback)
-        if not self.callbacks:
-            self._stop_listening()
-
+        self.gps.disconnect("gps", self)
 
 # For a list of dbus services, look in /etc/dbus-1/system.d/
-class GPS(zavai.Resource):
+class GPS(zavai.Service):
     def __init__(self, registry, name):
+        super(GPS, self).__init__(["gps"])
+
         self.bus = registry.resource("dbus.system_bus")
 
         # see mdbus -s org.freesmartphone.ousaged /org/freesmartphone/Usage
@@ -162,30 +134,15 @@ class GPS(zavai.Resource):
         self.monitor = GPSMonitor(self)
         self.position = GPSPosition(self)
 
-        self.requestors = set()
-
-    def request(self, tag):
-        "Request usage of GPS by the subsystem with the given tag"
-        do_start = not self.requestors
-        self.requestors.add(tag)
-        if do_start:
-            # Request GPS resource
-            self.usage.RequestResource('GPS')
-            zavai.info("Acquired GPS")
-
-    def release(self, tag):
-        "Release usage of GPS by the subsystem with the given tag"
-        if not self.requestors: return
-        self.requestors.discard(tag)
-        if not self.requestors:
-            self.usage.ReleaseResource('GPS')
-            zavai.info("Released GPS")
-
-    def shutdown(self):
-        if self.requestors:
-            self.requestors.clear()
-            self.usage.ReleaseResource('GPS')
-            zavai.info("Released GPS")
+    def start(self):
+        """Request GPS resource"""
+        self.usage.RequestResource('GPS')
+        zavai.info("Acquired GPS")
+
+    def stop(self):
+        """Release usage of GPS"""
+        self.usage.ReleaseResource('GPS')
+        zavai.info("Released GPS")
 
 #    def wait_for_fix(self, callback):
 #        status = self.gps.GetFixStatus()
@@ -240,53 +197,57 @@ class GPS(zavai.Resource):
 #        self.audio.start_recording()
 #
 
-class GPX(zavai.Resource):
+class GPX(zavai.Service):
     "Write GPX track and waypoint files"
     def __init__(self, registry, name):
+        super(GPX, self).__init__(["gpx"])
         self.registry = registry
         self.trk = None
         self.wpt = None
         self.last_pos = None
-        self.requestors = set()
         conf = registry.resource("conf")
-        self.trackdir = os.path.expanduser("~/.zavai")
-        if conf.has_section("gps"):
-            if conf.has_option("gps", "trackdir"):
-                self.trackdir = conf.get("gps", "trackdir")
-        if not os.path.isdir(self.trackdir):
-            zavai.info("Creating directory", self.trackdir)
-            os.makedirs(self.trackdir)
-
-    def request(self, tag):
-        "Request the GPX trace to be taken"
-        do_start = not self.requestors
-        self.requestors.add(tag)
-        if do_start:
-            zavai.info("Starting GPX trace subsystem")
-            gps = self.registry.resource("gps")
-            gps.position.connect(self.on_position_changed)
-
-    def release(self, tag):
-        "Release a GPX trace request"
-        if not self.requestors: return
-        self.requestors.discard(tag)
-        if not self.requestors:
-            zavai.info("Stopping GPX trace subsystem")
-            gps = self.registry.resource("gps")
-            gps.position.disconnect(self.on_position_changed)
-            self.stop()
+        self.trackdir = conf.homedir
+        self.activity_monitors = set()
+        self.started = False
+
+    def add_activity_monitor(self, cb):
+        self.activity_monitors.add(cb)
+        cb(self, self.last_pos is not None)
+
+    def del_activity_monitor(self, cb):
+        self.activity_monitors.discard(cb)
+
+    def notify_activity_monitors(self):
+        for mon in self.activity_monitors:
+            mon(self, self.last_pos is not None)
+
+    def start(self):
+        zavai.info("Starting GPX trace subsystem")
+        self.started = True
+        gps = self.registry.resource("gps")
+        gps.position.connect("gps", self.on_position_changed)
+
+    def stop(self):
+        if not self.started: return
+        zavai.info("Stopping GPX trace subsystem")
+        gps = self.registry.resource("gps")
+        gps.position.disconnect("gps", self.on_position_changed)
+        self.stop_track()
+        self.started = False
 
     def on_position_changed(self, fields, tstamp, lat, lon, alt):
         self.last_pos = (fields, tstamp, lat, lon, alt)
         self.trackpoint()
 
-    def start(basename = None, tstamp = None):
+    def start_track(self, tstamp = None, basename = None):
         if basename is None:
+            self.basename = basename
+        elif tstamp is not None:
             # Compute basename for output files
-            basename = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(tstamp))
-            basename = os.path.join(self.trackdir, self.basename)
+            self.basename = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(tstamp))
+            self.basename = os.path.join(self.trackdir, self.basename)
 
-        self.trk = open(basename + "-trk.gpx", "wt")
+        self.trk = open(self.basename + "-trk.gpx", "wt")
         print >>self.trk, """<?xml version="1.0" encoding="UTF-8"?>
 <gpx
     version="1.0"
@@ -297,7 +258,7 @@ class GPX(zavai.Resource):
   <trk>
     <trkseg>""" % VERSION
 
-        self.wpt = open(basename + "-wpt.gpx", "wt")
+        self.wpt = open(self.basename + "-wpt.gpx", "wt")
         print >>self.wpt, """<?xml version="1.0" encoding="UTF-8"?>
 <gpx
     version="1.0"
@@ -307,8 +268,9 @@ class GPX(zavai.Resource):
     xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd">""" % VERSION
 
         self.wpt_seq = 1;
+        self.notify_activity_monitors()
 
-    def stop(self):
+    def stop_track(self):
         if self.trk is not None:
             print >>self.trk, "</trkseg></trk></gpx>"
             self.trk.close()
@@ -318,9 +280,7 @@ class GPX(zavai.Resource):
             self.wpt.close()
             self.wpt = None
         self.last_pos = None
-
-    def shutdown(self):
-        self.stop()
+        self.notify_activity_monitors()
 
     def trackpoint(self):
         "Mark a track point"
@@ -330,7 +290,7 @@ class GPX(zavai.Resource):
         fields, tstamp, lat, lon, ele = self.last_pos
 
         if not self.trk:
-            self.start(tstamp)
+            self.start_track(tstamp)
 
         print >>self.trk, """<trkpt lat="%f" lon="%f">
   <time>%s</time>
@@ -349,7 +309,7 @@ class GPX(zavai.Resource):
         fields, tstamp, lat, lon, ele = self.last_pos
 
         if not self.wpt:
-            self.start(tstamp)
+            self.start_track(tstamp)
 
         if name is None:
             name = "wpt_%d" % self.wpt_seq