Added option to take waypoints
[gregoa/zavai.git] / zavai / gps.py
1 # gps - gps resource for zavai
2 #
3 # Copyright (C) 2009  Enrico Zini <enrico@enricozini.org>
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
19 #import sys
20 import os
21 import os.path
22 import time
23 import dbus
24 import zavai
25
26 class GPSMonitor():
27     def __init__(self, gps):
28         self.gps = gps
29         self.gps_ubx = gps.gps_ubx
30
31         # This piece of machinery is taken from Zhone
32         self.debug_busy = None
33         self.debug_want = set( ["NAV-STATUS", "NAV-SVINFO"] )
34         self.debug_have = set()
35         self.debug_error = set()
36
37         self.callbacks = set()
38
39     def debug_update(self):
40         if self.debug_busy is None:
41             pending = self.debug_want - self.debug_have - self.debug_error
42             if pending:
43                 self.debug_busy = pending.pop()
44                 self.gps_ubx.SetDebugFilter(
45                     self.debug_busy,
46                     True,
47                     reply_handler=self.on_debug_reply,
48                     error_handler=self.on_debug_error,
49                 )
50
51     def debug_request(self):
52         self.debug_have = set()
53         self.debug_update()
54
55     def on_debug_reply(self):
56         self.debug_have.add(self.debug_busy)
57         self.debug_busy = None
58         self.debug_update()
59
60     def on_debug_error(self, e):
61         zavai.info(e, "error while requesting debug packet %s" % self.debug_busy)
62         self.debug_error.add(self.debug_busy)
63         self.debug_busy = None
64         self.debug_update()
65
66     def on_satellites_changed(self, satellites):
67         zavai.info("gps monitor: satellites changed")
68         self.debug_request()
69
70     def on_ubxdebug_packet(self, clid, length, data):
71         zavai.info("gps monitor: UBX debug packet")
72         for c in self.callbacks:
73             c(clid, length, data)
74
75     def _start_listening(self):
76         self.gps.request(self)
77         # TODO: find out how come sometimes these events are not sent
78         self.gps.bus.add_signal_receiver(
79             self.on_satellites_changed, 'SatellitesChanged', 'org.freedesktop.Gypsy.Satellite',
80             'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
81         self.gps.bus.add_signal_receiver(
82             self.on_ubxdebug_packet, 'DebugPacket', 'org.freesmartphone.GPS.UBX',
83             'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
84         self.debug_request()
85
86     def _stop_listening(self):
87         self.gps.bus.remove_signal_receiver(
88             self.on_satellites_changed, 'SatellitesChanged', 'org.freedesktop.Gypsy.Satellite',
89             'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
90         self.gps.bus.remove_signal_receiver(
91             self.on_ubxdebug_packet, 'DebugPacket', 'org.freesmartphone.GPS.UBX',
92             'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
93         self.gps.release(self)
94
95     def connect(self, callback):
96         "Send UBX debug packets to the given callback"
97         do_start = not self.callbacks
98         self.callbacks.add(callback)
99         if do_start:
100             self._start_listening()
101
102     def disconnect(self, callback):
103         "Stop sending UBX debug packets to the given callback"
104         if not self.callbacks: return
105         self.callbacks.discard(callback)
106         if not self.callbacks:
107             self._stop_listening()
108
109 class GPSPosition():
110     def __init__(self, gps):
111         self.gps = gps
112         self.callbacks = set()
113
114     def on_position_changed(self, fields, tstamp, lat, lon, alt):
115         zavai.info("gps position: position changed")
116         for c in self.callbacks:
117             c(fields, tstamp, lat, lon, alt)
118
119     def _start_listening(self):
120         self.gps.request(self)
121         self.gps.bus.add_signal_receiver(
122             self.on_position_changed, 'PositionChanged', 'org.freedesktop.Gypsy.Position',
123             'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
124
125     def _stop_listening(self):
126         self.gps.bus.remove_signal_receiver(
127             self.on_position_changed, 'PositionChanged', 'org.freedesktop.Gypsy.Position',
128             'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
129         self.gps.release(self)
130
131     def connect(self, callback):
132         "Send position changed messages to the given callback"
133         do_start = not self.callbacks
134         self.callbacks.add(callback)
135         if do_start:
136             self._start_listening()
137
138     def disconnect(self, callback):
139         "Stop sending position changed messages to the given callback"
140         if not self.callbacks: return
141         self.callbacks.discard(callback)
142         if not self.callbacks:
143             self._stop_listening()
144
145
146 # For a list of dbus services, look in /etc/dbus-1/system.d/
147 class GPS(zavai.Resource):
148     def __init__(self, registry, name):
149         self.bus = registry.resource("dbus.system_bus")
150
151         # see mdbus -s org.freesmartphone.ousaged /org/freesmartphone/Usage
152         self.usage = self.bus.get_object('org.freesmartphone.ousaged', '/org/freesmartphone/Usage')
153         self.usage = dbus.Interface(self.usage, "org.freesmartphone.Usage")
154
155         # see mdbus -s org.freesmartphone.ogpsd /org/freedesktop/Gypsy
156         gps = self.bus.get_object('org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy') 
157         self.gps = dbus.Interface(gps, "org.freedesktop.Gypsy.Device")
158         self.gps_time = dbus.Interface(gps, "org.freedesktop.Gypsy.Time")
159         self.gps_position = dbus.Interface(gps, 'org.freedesktop.Gypsy.Position')
160         self.gps_ubx = dbus.Interface(gps, 'org.freesmartphone.GPS.UBX')
161
162         self.monitor = GPSMonitor(self)
163         self.position = GPSPosition(self)
164
165         self.requestors = set()
166
167     def request(self, tag):
168         "Request usage of GPS by the subsystem with the given tag"
169         do_start = not self.requestors
170         self.requestors.add(tag)
171         if do_start:
172             # Request GPS resource
173             self.usage.RequestResource('GPS')
174             zavai.info("Acquired GPS")
175
176     def release(self, tag):
177         "Release usage of GPS by the subsystem with the given tag"
178         if not self.requestors: return
179         self.requestors.discard(tag)
180         if not self.requestors:
181             self.usage.ReleaseResource('GPS')
182             zavai.info("Released GPS")
183
184     def shutdown(self):
185         if self.requestors:
186             self.requestors.clear()
187             self.usage.ReleaseResource('GPS')
188             zavai.info("Released GPS")
189
190 #    def wait_for_fix(self, callback):
191 #        status = self.gps.GetFixStatus()
192 #        if status in [2, 3]:
193 #            zavai.info("We already have a fix, good.")
194 #            callback()
195 #            return True
196 #        else:
197 #            zavai.info("Waiting for a fix...")
198 #            self.waiting_for_fix = callback
199 #            self.bus.add_signal_receiver(
200 #                self.on_fix_status_changed, 'FixStatusChanged', 'org.freedesktop.Gypsy.Device',
201 #                'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
202 #            return False
203 #
204 #    def on_fix_status_changed(self, status):
205 #        if status not in [2, 3]: return
206 #
207 #        zavai.info("Got GPS fix")
208 #        self.bus.remove_signal_receiver(
209 #            self.on_fix_status_changed, 'FixStatusChanged', 'org.freedesktop.Gypsy.Device',
210 #            'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
211 #
212 #        if self.waiting_for_fix:
213 #            self.waiting_for_fix()
214 #            self.waiting_for_fix = None
215 #
216
217 #    def start_recording(self):
218 #        if self.gps_monitor:
219 #            self.gps_monitor.stop()
220 #            self.gps_monitor = None
221 #
222 #        if not self.audio:
223 #            return
224 #
225 #        # Sync system time
226 #        gpstime = self.gps.gps_time.GetTime()
227 #        subprocess.call(["date", "-s", "@%d" % gpstime])
228 #        subprocess.call(["hwclock", "--systohc"])
229 #
230 #        # Compute basename for output files
231 #        self.basename = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(gpstime))
232 #        self.basename = os.path.join(AUDIODIR, self.basename)
233 #
234 #        # Start recording the GPX track
235 #        self.gpx = GPX(self.basename)
236 #        self.gps.track_position(self.on_position_changed)
237 #
238 #        # Start recording in background forking arecord
239 #        self.audio.set_basename(self.basename)
240 #        self.audio.start_recording()
241 #
242
243 class GPX(zavai.Resource):
244     "Write GPX track and waypoint files"
245     def __init__(self, registry, name):
246         self.registry = registry
247         self.trk = None
248         self.wpt = None
249         self.last_pos = None
250         self.requestors = set()
251         conf = registry.resource("conf")
252         self.trackdir = os.path.expanduser("~/.zavai")
253         if conf.has_section("gps"):
254             if conf.has_option("gps", "trackdir"):
255                 self.trackdir = conf.get("gps", "trackdir")
256         if not os.path.isdir(self.trackdir):
257             zavai.info("Creating directory", self.trackdir)
258             os.makedirs(self.trackdir)
259         self.activity_monitors = set()
260
261     def add_activity_monitor(self, cb):
262         self.activity_monitors.add(cb)
263         cb(self, self.last_pos is not None)
264
265     def del_activity_monitor(self, cb):
266         self.activity_monitors.discard(cb)
267
268     def notify_activity_monitors(self):
269         for mon in self.activity_monitors:
270             mon(self, self.last_pos is not None)
271
272     def request(self, tag):
273         "Request the GPX trace to be taken"
274         do_start = not self.requestors
275         self.requestors.add(tag)
276         if do_start:
277             zavai.info("Starting GPX trace subsystem")
278             gps = self.registry.resource("gps")
279             gps.position.connect(self.on_position_changed)
280
281     def release(self, tag):
282         "Release a GPX trace request"
283         if not self.requestors: return
284         self.requestors.discard(tag)
285         if not self.requestors:
286             zavai.info("Stopping GPX trace subsystem")
287             gps = self.registry.resource("gps")
288             gps.position.disconnect(self.on_position_changed)
289             self.stop()
290
291     def on_position_changed(self, fields, tstamp, lat, lon, alt):
292         self.last_pos = (fields, tstamp, lat, lon, alt)
293         self.trackpoint()
294
295     def start(basename = None, tstamp = None):
296         if basename is None:
297             # Compute basename for output files
298             basename = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(tstamp))
299             basename = os.path.join(self.trackdir, self.basename)
300
301         self.trk = open(basename + "-trk.gpx", "wt")
302         print >>self.trk, """<?xml version="1.0" encoding="UTF-8"?>
303 <gpx
304     version="1.0"
305     creator="audiomap %s"
306     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
307     xmlns="http://www.topografix.com/GPX/1/0"
308     xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd">
309   <trk>
310     <trkseg>""" % VERSION
311
312         self.wpt = open(basename + "-wpt.gpx", "wt")
313         print >>self.wpt, """<?xml version="1.0" encoding="UTF-8"?>
314 <gpx
315     version="1.0"
316     creator="audiomap %s"
317     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
318     xmlns="http://www.topografix.com/GPX/1/0"
319     xsi:schemaLocation="http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd">""" % VERSION
320
321         self.wpt_seq = 1;
322         self.notify_activity_monitors()
323
324     def stop(self):
325         if self.trk is not None:
326             print >>self.trk, "</trkseg></trk></gpx>"
327             self.trk.close()
328             self.trk = None
329         if self.wpt is not None:
330             print >>self.wpt, "</gpx>"
331             self.wpt.close()
332             self.wpt = None
333         self.last_pos = None
334         self.notify_activity_monitors()
335
336     def shutdown(self):
337         self.stop()
338
339     def trackpoint(self):
340         "Mark a track point"
341         if self.last_pos is None:
342             return
343
344         fields, tstamp, lat, lon, ele = self.last_pos
345
346         if not self.trk:
347             self.start(tstamp)
348
349         print >>self.trk, """<trkpt lat="%f" lon="%f">
350   <time>%s</time>
351   <ele>%f</ele>""" % (lat, lon, time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(tstamp)), ele)
352         #if course is not None: print >>self.trk, "    <course>%f</course>" % course
353         #if speed is not None: print >>self.trk, "    <speed>%f</speed>" % speed
354         #if fix is not None: print >>self.trk, "    <fix>%f</fix>" % fix
355         #if hdop is not None: print >>self.trk, "    <hdop>%f</hdop>" % hdop
356         print >>self.trk, "</trkpt>"
357
358     def waypoint(self, name = None):
359         "Mark a waypoint"
360         if self.last_pos is None:
361             return
362
363         fields, tstamp, lat, lon, ele = self.last_pos
364
365         if not self.wpt:
366             self.start(tstamp)
367
368         if name is None:
369             name = "wpt_%d" % self.wpt_seq
370             self.wpt_seq += 1
371
372         print >>self.wpt, """<wpt lat="%f" lon="%f">
373     <name>%s</name>
374     <time>%s</time>
375     <ele>%f</ele>
376 </wpt>""" % (
377             lat, lon, name, time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(tstamp)), ele)
378
379
380 #    def record(self):
381 #        self.audio = Audio(self.make_waypoint)
382 #        self.gps = GPS()
383 #        # Get a fix and start recording
384 #        if not self.gps.wait_for_fix(self.start_recording):
385 #            self.gps_monitor = GPSMonitor(self.gps)
386 #            self.gps_monitor.start()
387 #
388 #    def monitor(self):
389 #        self.audio = None
390 #        self.gps = GPS()
391 #        self.gps_monitor = GPSMonitor(self.gps)
392 #        self.gps_monitor.start()
393 #
394 #
395 #    def make_waypoint(self):
396 #        if self.gpx is None:
397 #            return
398 #        if self.last_pos is None:
399 #            self.last_pos = self.gps.gps_position.GetPosition()
400 #        (fields, tstamp, lat, lon, alt) = self.last_pos
401 #        self.gpx.waypoint(tstamp, lat, lon, alt)
402 #        zavai.info("Making waypoint at %s: %f, %f, %f" % (
403 #            time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(tstamp)), lat, lon, alt))