0e5e30eb1916e811142e3b75193a36527c457a69
[gregoa/zavai.git] / src / gps.vala
1 /*
2  * gps - gps resource for zavai
3  *
4  * Copyright (C) 2009  Enrico Zini <enrico@enricozini.org>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 using GLib;
22
23 namespace zavai {
24 namespace gps {
25
26 // For a list of dbus services, look in /etc/dbus-1/system.d/
27 public class GPS: zavai.Service
28 {
29         public dynamic DBus.Object usage;
30         public dynamic DBus.Object device;
31
32         public GPS()
33         {
34                 name = "gps";
35
36                 // see mdbus -s org.freesmartphone.ousaged /org/freesmartphone/Usage
37                 usage = zavai.registry.sbus.get_object(
38                         "org.freesmartphone.ousaged",
39                         "/org/freesmartphone/Usage",
40                         "org.freesmartphone.Usage");
41
42                 device = zavai.registry.sbus.get_object(
43                         "org.freesmartphone.ogpsd", 
44                         "/org/freedesktop/Gypsy",
45                         "org.freedesktop.Gypsy.Device");
46         }
47
48     public void power_cycle(bool aggressive)
49     {
50         usage.SetResourcePolicy("GPS", "disabled");
51         if (aggressive)
52             // Sometimes the GPS crashes because its state contains something
53             // that makes it crash, so we need to remove the saved state or it
54             // crashes again quite soon
55             FileUtils.unlink("/var/lib/freesmartphone/ogpsd.pickle");
56         usage.SetResourcePolicy("GPS", "auto");
57     }
58
59         /// Request GPS resource
60         public override void start()
61         {
62                 if (started) return;
63                 try {
64                         usage.RequestResource("GPS");
65                         zavai.log.info("Acquired GPS");
66                         base.start();
67                 } catch (GLib.Error e) {
68                         zavai.log.error(e.message);
69                 }
70                 base.start();
71         }
72
73         // Release usage of GPS
74         public override void stop()
75         {
76                 if (!started) return;
77                 try {
78                         usage.ReleaseResource("GPS");
79                         zavai.log.info("Released GPS");
80                         base.stop();
81                 } catch (GLib.Error e) {
82                         zavai.log.error(e.message);
83                 }
84                 base.stop();
85         }
86 }
87
88 public class Position : zavai.Service
89 {
90         dynamic DBus.Object position;
91
92         public signal void position_changed(int fields, int tstamp, double lat, double lon, double alt);
93
94         public Position()
95         {
96                 name = "gps.position";
97                 position = zavai.registry.sbus.get_object(
98                         "org.freesmartphone.ogpsd",
99                         "/org/freedesktop/Gypsy",
100                         "org.freedesktop.Gypsy.Position");
101         }
102
103         public void on_position_changed(dynamic DBus.Object pos, int fields, int tstamp, double lat, double lon, double alt)
104         {
105                 zavai.log.info("gps position: position changed");
106                 position_changed(fields, tstamp, lat, lon, alt);
107         }
108
109         public override void start()
110         {
111                 if (started) return;
112                 zavai.log.info("Starting GPS position tracking");
113                 gps.request("gps.position");
114                 position.PositionChanged += on_position_changed;
115                 base.start();
116         }
117
118         public override void stop()
119         {
120                 if (!started) return;
121                 zavai.log.info("Stopping GPS position tracking");
122                 position.PositionChanged -= on_position_changed;
123                 gps.release("gps.position");
124                 base.stop();
125         }
126 }
127
128 // #    def wait_for_fix(self, callback):
129 // #        status = self.gps.GetFixStatus()
130 // #        if status in [2, 3]:
131 // #            zavai.info("We already have a fix, good.")
132 // #            callback()
133 // #            return True
134 // #        else:
135 // #            zavai.info("Waiting for a fix...")
136 // #            self.waiting_for_fix = callback
137 // #            self.bus.add_signal_receiver(
138 // #                self.on_fix_status_changed, 'FixStatusChanged', 'org.freedesktop.Gypsy.Device',
139 // #                'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
140 // #            return False
141 // #
142 // #    def start_recording(self):
143 // #        if self.gps_monitor:
144 // #            self.gps_monitor.stop()
145 // #            self.gps_monitor = None
146 // #
147 // #        if not self.audio:
148 // #            return
149 // #
150 // #        # Sync system time
151 // #        gpstime = self.gps.gps_time.GetTime()
152 // #        subprocess.call(["date", "-s", "@%d" % gpstime])
153 // #        subprocess.call(["hwclock", "--systohc"])
154 // #
155 // #        # Compute basename for output files
156 // #        self.basename = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(gpstime))
157 // #        self.basename = os.path.join(AUDIODIR, self.basename)
158 // #
159 // #        # Start recording the GPX track
160 // #        self.gpx = GPX(self.basename)
161 // #        self.gps.track_position(self.on_position_changed)
162 // #
163 // #        # Start recording in background forking arecord
164 // #        self.audio.set_basename(self.basename)
165 // #        self.audio.start_recording()
166 // #
167
168 // Write GPX track and waypoint files
169 public class GPX : Service
170 {
171         public bool tracking {
172                 get { return trk != null; }
173                 set {}
174         }
175         public signal void tracking_changed(bool tracking);
176
177         FileStream trk = null;
178         FileStream wpt = null;
179         int wpt_seq = 1;
180         bool last_valid = false;
181         int last_fields;
182         time_t last_tstamp;
183         double last_lat;
184         double last_lon;
185         double last_alt;
186
187         public GPX()
188         {
189                 name = "gps.gpx";
190         }
191
192         public override void start()
193         {       
194                 if (!started)
195                 {
196                         log.info("Starting GPX trace subsystem");
197                         position.request("gps.gpx");
198                         position.position_changed += on_position_changed;
199                         base.start();
200                 }
201         }
202
203         public override void stop()
204         {
205                 if (started)
206                 {
207                         log.info("Stopping GPX trace subsystem");
208                         position.release("gps.gpx");
209                         position.position_changed -= on_position_changed;
210                         stop_track();
211                         base.stop();
212                 }
213         }
214
215         public void on_position_changed(Position pos, int fields, int tstamp, double lat, double lon, double alt)
216         {
217                 last_fields = fields;
218                 last_tstamp = tstamp;
219                 last_lat = lat;
220                 last_lon = lon;
221                 last_alt = alt;
222                 last_valid = true;
223                 trackpoint();
224         }
225
226         public void start_track(time_t tstamp = 0, string? basename = null)
227         {
228                 string fname;
229                 if (basename != null)
230                         fname = basename;
231                 else
232                 {
233                         time_t now = tstamp == 0 ? time_t() : tstamp;
234
235                         // Compute basename for output files
236                         var t = Time.local(now);
237                         char[] res = new char[25];
238                         t.strftime(res, "%Y-%m-%d-%H-%M-%S");
239                         fname = zavai.config.homedir + "/" + (string)res;
240                 }
241  
242                 trk = FileStream.open(fname + "-trk.gpx", "wt");
243                 trk.puts("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
244                 trk.puts(" <gpx");
245                 trk.puts("     version=\"1.0\"");
246                 trk.printf("     creator=\"zavai %s\"\n", zavai.config.version);
247                 trk.puts("     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
248                 trk.puts("     xmlns=\"http://www.topografix.com/GPX/1/0\"");
249                 trk.puts("     xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">");
250                 trk.puts("   <trk>");
251                 trk.puts("     <trkseg>");
252  
253                 wpt = FileStream.open(fname + "-wpt.gpx", "wt");
254                 wpt.puts("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
255                 wpt.puts(" <gpx");
256                 wpt.puts("     version=\"1.0\"");
257                 wpt.printf("     creator=\"zavai %s\"", zavai.config.version);
258                 wpt.puts("     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
259                 wpt.puts("     xmlns=\"http://www.topografix.com/GPX/1/0\"");
260                 wpt.puts("     xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">");
261  
262                 wpt_seq = 1;
263                 tracking_changed(true);
264         }
265  
266         public void stop_track()
267         {
268                 if (trk != null)
269                 {
270                         trk.puts("</trkseg></trk></gpx>");
271                         trk.flush();
272                         trk = null;
273                 }
274                 if (wpt != null)
275                 {
276                         wpt.puts("</gpx>");
277                         wpt.flush();
278                         wpt = null;
279                 }
280                 last_valid = false;
281                 tracking_changed(false);
282         }
283
284         // Mark a track point
285         public void trackpoint()
286         {
287                 if (!last_valid) return;
288                 if (trk == null)
289                         start_track(last_tstamp);
290
291                 trk.printf("<trkpt lat=\"%f\" lon=\"%f\">\n", last_lat, last_lon);
292                 var t = Time.local(last_tstamp);
293                 char[] ts = new char[25];
294                 t.strftime(ts, "%Y-%m-%dT%H:%M:%SZ");
295                 trk.printf("  <time>%s</time>\n", (string)ts);
296                 trk.printf("  <ele>%f</ele>\n", last_alt);
297                 // if course is not None: print >>self.trk, "    <course>%f</course>" % course
298                 // if speed is not None: print >>self.trk, "    <speed>%f</speed>" % speed
299                 // if fix is not None: print >>self.trk, "    <fix>%f</fix>" % fix
300                 // if hdop is not None: print >>self.trk, "    <hdop>%f</hdop>" % hdop
301                 trk.puts("</trkpt>");
302         }
303
304         // Mark a waypoint
305         public void waypoint(string? name = null)
306         {
307                 if (!last_valid) return;
308                 if (wpt == null)
309                         start_track(last_tstamp);
310
311                 string wptname;
312                 if (name == null)
313                 {
314                         wptname = "wpt_%d".printf(wpt_seq);
315                         wpt_seq += 1;
316                 } else {
317                         wptname = name;
318                 }
319
320                 wpt.printf("<wpt lat=\"%f\" lon=\"%f\">\n", last_lat, last_lon);
321                 wpt.printf("  <name>%s</name>\n", wptname);
322                 var t = Time.local(last_tstamp);
323                 char[] ts = new char[25];
324                 t.strftime(ts, "%Y-%m-%dT%H:%M:%SZ");
325                 wpt.printf("  <time>%s</time>\n", (string)ts);
326                 wpt.printf("  <ele>%f</ele>\n", last_alt);
327                 wpt.puts("</wpt>");
328         }
329 }
330
331 public zavai.gps.GPS gps = null;
332 public zavai.gps.Position position = null;
333 public zavai.gps.GPX gpx = null;
334
335 public void init()
336 {
337         gps = new GPS();
338         position = new Position();
339         gpx = new GPX();
340
341         zavai.registry.register_service(gps);
342         zavai.registry.register_service(position);
343         zavai.registry.register_service(gpx);
344 }
345
346 }
347 }