Handle exceptions
[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         // "Have you tried turning it off and on again?"
51                 try {
52             usage.SetResourcePolicy("GPS", "disabled");
53                 } catch (GLib.Error e) {
54                         zavai.log.error(e.message);
55                 }
56         Thread.usleep(500000);
57         if (aggressive)
58             // Sometimes the GPS crashes because its state contains something
59             // that makes it crash, so we need to remove the saved state or it
60             // crashes again quite soon
61             FileUtils.unlink("/var/lib/freesmartphone/ogpsd.pickle");
62                 try {
63             usage.SetResourcePolicy("GPS", "auto");
64                 } catch (GLib.Error e) {
65                         zavai.log.error(e.message);
66                 }
67     }
68
69         /// Request GPS resource
70         public override void start()
71         {
72                 if (started) return;
73                 try {
74                         usage.RequestResource("GPS");
75                         zavai.log.info("Acquired GPS");
76                         base.start();
77                 } catch (GLib.Error e) {
78                         zavai.log.error(e.message);
79                 }
80                 base.start();
81         }
82
83         // Release usage of GPS
84         public override void stop()
85         {
86                 if (!started) return;
87                 try {
88                         usage.ReleaseResource("GPS");
89                         zavai.log.info("Released GPS");
90                         base.stop();
91                 } catch (GLib.Error e) {
92                         zavai.log.error(e.message);
93                 }
94                 base.stop();
95         }
96 }
97
98 public class Position : zavai.Service
99 {
100         dynamic DBus.Object position;
101
102         public signal void position_changed(int fields, int tstamp, double lat, double lon, double alt);
103
104         public Position()
105         {
106                 name = "gps.position";
107                 position = zavai.registry.sbus.get_object(
108                         "org.freesmartphone.ogpsd",
109                         "/org/freedesktop/Gypsy",
110                         "org.freedesktop.Gypsy.Position");
111         }
112
113         public void on_position_changed(dynamic DBus.Object pos, int fields, int tstamp, double lat, double lon, double alt)
114         {
115                 zavai.log.info("gps position: position changed");
116                 position_changed(fields, tstamp, lat, lon, alt);
117         }
118
119         public override void start()
120         {
121                 if (started) return;
122                 zavai.log.info("Starting GPS position tracking");
123                 gps.request("gps.position");
124                 position.PositionChanged += on_position_changed;
125                 base.start();
126         }
127
128         public override void stop()
129         {
130                 if (!started) return;
131                 zavai.log.info("Stopping GPS position tracking");
132                 position.PositionChanged -= on_position_changed;
133                 gps.release("gps.position");
134                 base.stop();
135         }
136 }
137
138 // #    def wait_for_fix(self, callback):
139 // #        status = self.gps.GetFixStatus()
140 // #        if status in [2, 3]:
141 // #            zavai.info("We already have a fix, good.")
142 // #            callback()
143 // #            return True
144 // #        else:
145 // #            zavai.info("Waiting for a fix...")
146 // #            self.waiting_for_fix = callback
147 // #            self.bus.add_signal_receiver(
148 // #                self.on_fix_status_changed, 'FixStatusChanged', 'org.freedesktop.Gypsy.Device',
149 // #                'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
150 // #            return False
151 // #
152 // #    def start_recording(self):
153 // #        if self.gps_monitor:
154 // #            self.gps_monitor.stop()
155 // #            self.gps_monitor = None
156 // #
157 // #        if not self.audio:
158 // #            return
159 // #
160 // #        # Sync system time
161 // #        gpstime = self.gps.gps_time.GetTime()
162 // #        subprocess.call(["date", "-s", "@%d" % gpstime])
163 // #        subprocess.call(["hwclock", "--systohc"])
164 // #
165 // #        # Compute basename for output files
166 // #        self.basename = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(gpstime))
167 // #        self.basename = os.path.join(AUDIODIR, self.basename)
168 // #
169 // #        # Start recording the GPX track
170 // #        self.gpx = GPX(self.basename)
171 // #        self.gps.track_position(self.on_position_changed)
172 // #
173 // #        # Start recording in background forking arecord
174 // #        self.audio.set_basename(self.basename)
175 // #        self.audio.start_recording()
176 // #
177
178 // Write GPX track and waypoint files
179 public class GPX : Service
180 {
181         public bool tracking {
182                 get { return trk != null; }
183                 set {}
184         }
185         public signal void tracking_changed(bool tracking);
186
187         FileStream trk = null;
188         FileStream wpt = null;
189         int wpt_seq = 1;
190         bool last_valid = false;
191         int last_fields;
192         time_t last_tstamp;
193         double last_lat;
194         double last_lon;
195         double last_alt;
196
197         public GPX()
198         {
199                 name = "gps.gpx";
200         }
201
202         public override void start()
203         {       
204                 if (!started)
205                 {
206                         log.info("Starting GPX trace subsystem");
207                         position.request("gps.gpx");
208                         position.position_changed += on_position_changed;
209                         base.start();
210                 }
211         }
212
213         public override void stop()
214         {
215                 if (started)
216                 {
217                         log.info("Stopping GPX trace subsystem");
218                         position.release("gps.gpx");
219                         position.position_changed -= on_position_changed;
220                         stop_track();
221                         base.stop();
222                 }
223         }
224
225         public void on_position_changed(Position pos, int fields, int tstamp, double lat, double lon, double alt)
226         {
227                 last_fields = fields;
228                 last_tstamp = tstamp;
229                 last_lat = lat;
230                 last_lon = lon;
231                 last_alt = alt;
232                 last_valid = true;
233                 trackpoint();
234         }
235
236         public void start_track(time_t tstamp = 0, string? basename = null)
237         {
238                 string fname;
239                 if (basename != null)
240                         fname = basename;
241                 else
242                 {
243                         time_t now = tstamp == 0 ? time_t() : tstamp;
244
245                         // Compute basename for output files
246                         var t = Time.local(now);
247                         char[] res = new char[25];
248                         t.strftime(res, "%Y-%m-%d-%H-%M-%S");
249                         fname = zavai.config.homedir + "/" + (string)res;
250                 }
251  
252                 trk = FileStream.open(fname + "-trk.gpx", "wt");
253                 trk.puts("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
254                 trk.puts(" <gpx");
255                 trk.puts("     version=\"1.0\"");
256                 trk.printf("     creator=\"zavai %s\"\n", zavai.config.version);
257                 trk.puts("     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
258                 trk.puts("     xmlns=\"http://www.topografix.com/GPX/1/0\"");
259                 trk.puts("     xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">");
260                 trk.puts("   <trk>");
261                 trk.puts("     <trkseg>");
262  
263                 wpt = FileStream.open(fname + "-wpt.gpx", "wt");
264                 wpt.puts("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
265                 wpt.puts(" <gpx");
266                 wpt.puts("     version=\"1.0\"");
267                 wpt.printf("     creator=\"zavai %s\"", zavai.config.version);
268                 wpt.puts("     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
269                 wpt.puts("     xmlns=\"http://www.topografix.com/GPX/1/0\"");
270                 wpt.puts("     xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">");
271  
272                 wpt_seq = 1;
273                 tracking_changed(true);
274         }
275  
276         public void stop_track()
277         {
278                 if (trk != null)
279                 {
280                         trk.puts("</trkseg></trk></gpx>");
281                         trk.flush();
282                         trk = null;
283                 }
284                 if (wpt != null)
285                 {
286                         wpt.puts("</gpx>");
287                         wpt.flush();
288                         wpt = null;
289                 }
290                 last_valid = false;
291                 tracking_changed(false);
292         }
293
294         // Mark a track point
295         public void trackpoint()
296         {
297                 if (!last_valid) return;
298                 if (trk == null)
299                         start_track(last_tstamp);
300
301                 trk.printf("<trkpt lat=\"%f\" lon=\"%f\">\n", last_lat, last_lon);
302                 var t = Time.local(last_tstamp);
303                 char[] ts = new char[25];
304                 t.strftime(ts, "%Y-%m-%dT%H:%M:%SZ");
305                 trk.printf("  <time>%s</time>\n", (string)ts);
306                 trk.printf("  <ele>%f</ele>\n", last_alt);
307                 // if course is not None: print >>self.trk, "    <course>%f</course>" % course
308                 // if speed is not None: print >>self.trk, "    <speed>%f</speed>" % speed
309                 // if fix is not None: print >>self.trk, "    <fix>%f</fix>" % fix
310                 // if hdop is not None: print >>self.trk, "    <hdop>%f</hdop>" % hdop
311                 trk.puts("</trkpt>");
312         }
313
314         // Mark a waypoint
315         public void waypoint(string? name = null)
316         {
317                 if (!last_valid) return;
318                 if (wpt == null)
319                         start_track(last_tstamp);
320
321                 string wptname;
322                 if (name == null)
323                 {
324                         wptname = "wpt_%d".printf(wpt_seq);
325                         wpt_seq += 1;
326                 } else {
327                         wptname = name;
328                 }
329
330                 wpt.printf("<wpt lat=\"%f\" lon=\"%f\">\n", last_lat, last_lon);
331                 wpt.printf("  <name>%s</name>\n", wptname);
332                 var t = Time.local(last_tstamp);
333                 char[] ts = new char[25];
334                 t.strftime(ts, "%Y-%m-%dT%H:%M:%SZ");
335                 wpt.printf("  <time>%s</time>\n", (string)ts);
336                 wpt.printf("  <ele>%f</ele>\n", last_alt);
337                 wpt.puts("</wpt>");
338         }
339 }
340
341 public zavai.gps.GPS gps = null;
342 public zavai.gps.Position position = null;
343 public zavai.gps.GPX gpx = null;
344
345 public void init()
346 {
347         gps = new GPS();
348         position = new Position();
349         gpx = new GPX();
350
351         zavai.registry.register_service(gps);
352         zavai.registry.register_service(position);
353         zavai.registry.register_service(gpx);
354 }
355
356 }
357 }