Added sat-monitor python satellite monitor
[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 //         # see mdbus -s org.freesmartphone.ogpsd /org/freedesktop/Gypsy
48 //         gps = self.bus.get_object('org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy') 
49 //         self.gps = dbus.Interface(gps, "org.freedesktop.Gypsy.Device")
50 //         self.gps_time = dbus.Interface(gps, "org.freedesktop.Gypsy.Time")
51 //         self.gps_position = dbus.Interface(gps, 'org.freedesktop.Gypsy.Position')
52 //         self.gps_ubx = dbus.Interface(gps, 'org.freesmartphone.GPS.UBX')
53                 usage.ResourceChanged += on_resourcechanged;
54         }
55
56         public void on_resourcechanged(dynamic DBus.Object pos, string name, bool state, HashTable<string, Value?> attributes)
57         {
58                 zavai.log.info("RESOURCE CHANGED " + name);
59         }
60
61         /// Request GPS resource
62         public override void start()
63         {
64                 if (started) return;
65                 try {
66                         usage.RequestResource("GPS");
67                         zavai.log.info("Acquired GPS");
68                         base.start();
69                 } catch (GLib.Error e) {
70                         zavai.log.error(e.message);
71                 }
72                 base.start();
73         }
74
75         // Release usage of GPS
76         public override void stop()
77         {
78                 if (!started) return;
79                 try {
80                         usage.ReleaseResource("GPS");
81                         zavai.log.info("Released GPS");
82                         base.stop();
83                 } catch (GLib.Error e) {
84                         zavai.log.error(e.message);
85                 }
86                 base.stop();
87         }
88 }
89
90 public class Monitor : zavai.Service
91 {
92         static const int NAV_STATUS=0;
93         static const int NAV_SVINFO=1;
94         static const int NAV_MAX=2;
95
96         dynamic DBus.Object ubx;
97         dynamic DBus.Object time;
98
99     public signal void sat_info(PtrArray< HashTable<string, Value?> > data);
100
101         /*
102         string[] filters = { "NAV-STATUS", "NAV_SVINFO" };
103
104         int debug_busy;
105         int debug_want;
106         int debug_have;
107         int debug_error;
108         */
109
110
111         public Monitor()
112         {
113                 name = "gps.monitor";
114
115                 ubx = zavai.registry.sbus.get_object(
116                         "org.freesmartphone.ogpsd",
117                         "/org/freedesktop/Gypsy",
118                         "org.freesmartphone.GPS.UBX");
119         /*
120                 time = zavai.registry.sbus.get_object(
121                         "org.freesmartphone.ogpsd",
122                         "/org/freedesktop/Gypsy",
123                         "org.freedesktop.Gypsy.Time");
124
125                 zavai.log.info("SETSIG1");
126                 time.TimeChanged += timechanged;
127                 zavai.log.info("SETSIG2");
128          */
129
130                 zavai.log.info("DEBUG1");
131                 ubx.DebugPacket += on_ubxdebug_packet;
132                 zavai.log.info("DEBUG2");
133
134 /*
135                 // This piece of machinery is taken from Zhone
136                 debug_busy = -1;
137                 debug_want = (1 << NAV_STATUS) | (1 << NAV_SVINFO);
138                 debug_have = 0;
139                 debug_error = 0;
140 */
141         }
142
143 /*
144         protected void timechanged(dynamic DBus.Object pos, int t)
145         {
146                 zavai.log.info("TIMECHANGED");
147         }
148 */
149
150 /*
151         protected void debug_update() throws GLib.Error
152         {
153                 zavai.log.debug("UPDATE");
154                 if (debug_busy != -1)
155                         return;
156                 zavai.log.debug("UPD1");
157                 int pending = debug_want & (~debug_have) & (~debug_error);
158                 if (pending == 0)
159                         return;
160                 zavai.log.debug("UPD2");
161                 for (int i = 0; i < NAV_MAX; ++i)
162                         if ((pending & (1<<i)) != 0)
163                         {
164                                 debug_busy = i;
165                                 break;
166                         }
167                 zavai.log.debug("UPD3 " + filters[debug_busy]);
168
169                 ubx.SetDebugFilter(
170                         filters[debug_busy],
171                         true,
172                         on_debug_reply
173 //                      on_debug_error
174                 );
175                 zavai.log.debug("UPD4");
176         }
177
178         protected void debug_request() throws GLib.Error
179         {
180                 debug_have = 0;
181                 debug_update();
182         }
183
184         protected void on_debug_reply() throws GLib.Error
185         {
186                 debug_have |= (1<<debug_busy);
187                 debug_busy = -1;
188                 debug_update();
189         }
190
191         protected void on_debug_error(string e) throws GLib.Error
192         {
193                 string name = debug_busy == -1 ? "none" : filters[debug_busy];
194                 zavai.log.error("error while requesting debug packet " + name + ": " + e);
195                 debug_error |= (1<<debug_busy);
196                 debug_busy = -1;
197                 debug_update();
198         }
199 */
200
201         /*
202         protected void on_satellites_changed(satellites)
203         {
204 //         zavai.info("gps monitor: satellites changed")
205 //         self.debug_request()
206         }
207         */
208
209         protected void on_ubxdebug_packet(dynamic DBus.Object ubx, string clid, int length,
210                         HashTable<string, Value?>[] data)
211         {
212                 zavai.log.info("gps monitor: UBX debug packet");
213                 message("ZAZA %s %d", clid, length);
214                 message("ZAZA %u %lu", data.length, sizeof(HashTable<string, Value?>));
215                 message("ZAZA %p %p", (void*)data.length, this);
216                 message("ZAZA %p", data[0]);
217                 message("ZAZA %p", data[1]);
218                 message("ZAZA %p", data[2]);
219         /*
220         */
221                 /*
222                 message("ZAZA %u", data[0].size());
223                 foreach (string k in data[0].get_keys())
224                         message("ZAZA %s", k);
225                 */
226                 //PtrArray< HashTable<string, Value?> >* prova = (PtrArray< HashTable<string, Value?> >)data;
227                 //message("ZAZA %u", prova->len);
228                 /*
229                 foreach (string k in prova[0].get_keys())
230                         message("ZAZA %s", k);
231                         */
232                 /*
233                 for (int i = 0; data[i] != null; ++i)
234                 {
235                         zavai.log.info("ZAZA");
236                 }
237                 */
238                 //message("Size: %d", data.size());
239 //         self.notify("satellites", clid, length, data)
240         //sat_info(data);
241         }
242
243         protected override void start()
244         {
245                 if (started) return;
246
247                 zavai.log.info("Starting GPS Monitor");
248                 gps.request("gps.monitor");
249 //         # TODO: find out how come sometimes these events are not sent
250 //         self.gps.bus.add_signal_receiver(
251 //             self.on_satellites_changed, 'SatellitesChanged', 'org.freedesktop.Gypsy.Satellite',
252 //             'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
253                 //ubx.DebugPacket += prova;
254                 //try {
255                         //ubx.SetDebugFilter("NAV-STATUS", true);
256                         //ubx.SetDebugFilter("NAV-SVINFO", true);
257                         //debug_request();
258                         base.start();
259                 //} catch (GLib.Error e) {
260                         //zavai.log.error(e.message);
261                 //}
262         }
263
264         protected override void stop()
265         {
266                 if (!started) return;
267                 zavai.log.info("Stopping GPS Monitor");
268 //         self.gps.bus.remove_signal_receiver(
269 //             self.on_satellites_changed, 'SatellitesChanged', 'org.freedesktop.Gypsy.Satellite',
270 //             'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
271                 try {
272                         ubx.SetDebugFilter("NAV-STATUS", false);
273                         ubx.SetDebugFilter("NAV-SVINFO", false);
274                 } catch (GLib.Error e) {
275                         zavai.log.error(e.message);
276                 }
277                 ubx.DebugPacket -= on_ubxdebug_packet;
278                 //ubx.DebugPacket -= prova;
279                 gps.release("gps.monitor");
280                 base.stop();
281         }
282 }
283
284
285 public class Position : zavai.Service
286 {
287         dynamic DBus.Object position;
288
289         public signal void position_changed(int fields, int tstamp, double lat, double lon, double alt);
290
291         public Position()
292         {
293                 name = "gps.position";
294                 position = zavai.registry.sbus.get_object(
295                         "org.freesmartphone.ogpsd",
296                         "/org/freedesktop/Gypsy",
297                         "org.freedesktop.Gypsy.Position");
298         }
299
300         public void on_position_changed(dynamic DBus.Object pos, int fields, int tstamp, double lat, double lon, double alt)
301         {
302                 zavai.log.info("gps position: position changed");
303                 position_changed(fields, tstamp, lat, lon, alt);
304         }
305
306         public override void start()
307         {
308                 if (started) return;
309                 zavai.log.info("Starting GPS position tracking");
310                 gps.request("gps.position");
311                 position.PositionChanged += on_position_changed;
312                 base.start();
313         }
314
315         public override void stop()
316         {
317                 if (!started) return;
318                 zavai.log.info("Stopping GPS position tracking");
319                 position.PositionChanged -= on_position_changed;
320                 gps.release("gps.position");
321                 base.stop();
322         }
323 }
324
325 // #    def wait_for_fix(self, callback):
326 // #        status = self.gps.GetFixStatus()
327 // #        if status in [2, 3]:
328 // #            zavai.info("We already have a fix, good.")
329 // #            callback()
330 // #            return True
331 // #        else:
332 // #            zavai.info("Waiting for a fix...")
333 // #            self.waiting_for_fix = callback
334 // #            self.bus.add_signal_receiver(
335 // #                self.on_fix_status_changed, 'FixStatusChanged', 'org.freedesktop.Gypsy.Device',
336 // #                'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
337 // #            return False
338 // #
339 // #    def on_fix_status_changed(self, status):
340 // #        if status not in [2, 3]: return
341 // #
342 // #        zavai.info("Got GPS fix")
343 // #        self.bus.remove_signal_receiver(
344 // #            self.on_fix_status_changed, 'FixStatusChanged', 'org.freedesktop.Gypsy.Device',
345 // #            'org.freesmartphone.ogpsd', '/org/freedesktop/Gypsy')
346 // #
347 // #        if self.waiting_for_fix:
348 // #            self.waiting_for_fix()
349 // #            self.waiting_for_fix = None
350 // #
351 // 
352 // #    def start_recording(self):
353 // #        if self.gps_monitor:
354 // #            self.gps_monitor.stop()
355 // #            self.gps_monitor = None
356 // #
357 // #        if not self.audio:
358 // #            return
359 // #
360 // #        # Sync system time
361 // #        gpstime = self.gps.gps_time.GetTime()
362 // #        subprocess.call(["date", "-s", "@%d" % gpstime])
363 // #        subprocess.call(["hwclock", "--systohc"])
364 // #
365 // #        # Compute basename for output files
366 // #        self.basename = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(gpstime))
367 // #        self.basename = os.path.join(AUDIODIR, self.basename)
368 // #
369 // #        # Start recording the GPX track
370 // #        self.gpx = GPX(self.basename)
371 // #        self.gps.track_position(self.on_position_changed)
372 // #
373 // #        # Start recording in background forking arecord
374 // #        self.audio.set_basename(self.basename)
375 // #        self.audio.start_recording()
376 // #
377
378 // Write GPX track and waypoint files
379 public class GPX : Service
380 {
381         public bool tracking {
382                 get { return trk != null; }
383                 set {}
384         }
385         public signal void tracking_changed(bool tracking);
386
387         FileStream trk = null;
388         FileStream wpt = null;
389         int wpt_seq = 1;
390         bool last_valid = false;
391         int last_fields;
392         time_t last_tstamp;
393         double last_lat;
394         double last_lon;
395         double last_alt;
396
397         public GPX()
398         {
399                 name = "gps.gpx";
400         }
401
402         public override void start()
403         {       
404                 if (!started)
405                 {
406                         log.info("Starting GPX trace subsystem");
407                         position.request("gps.gpx");
408                         position.position_changed += on_position_changed;
409                         base.start();
410                 }
411         }
412
413         public override void stop()
414         {
415                 if (started)
416                 {
417                         log.info("Stopping GPX trace subsystem");
418                         position.release("gps.gpx");
419                         position.position_changed -= on_position_changed;
420                         stop_track();
421                         base.stop();
422                 }
423         }
424
425         public void on_position_changed(Position pos, int fields, int tstamp, double lat, double lon, double alt)
426         {
427                 last_fields = fields;
428                 last_tstamp = tstamp;
429                 last_lat = lat;
430                 last_lon = lon;
431                 last_alt = alt;
432                 last_valid = true;
433                 trackpoint();
434         }
435
436         public void start_track(time_t tstamp = 0, string? basename = null)
437         {
438                 string fname;
439                 if (basename != null)
440                         fname = basename;
441                 else
442                 {
443                         time_t now = tstamp == 0 ? time_t() : tstamp;
444
445                         // Compute basename for output files
446                         var t = Time.local(now);
447                         char[] res = new char[25];
448                         t.strftime(res, "%Y-%m-%d-%H-%M-%S");
449                         fname = zavai.config.homedir + "/" + (string)res;
450                 }
451  
452                 trk = FileStream.open(fname + "-trk.gpx", "wt");
453                 trk.puts("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
454                 trk.puts(" <gpx");
455                 trk.puts("     version=\"1.0\"");
456                 trk.printf("     creator=\"zavai %s\"\n", zavai.config.version);
457                 trk.puts("     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
458                 trk.puts("     xmlns=\"http://www.topografix.com/GPX/1/0\"");
459                 trk.puts("     xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">");
460                 trk.puts("   <trk>");
461                 trk.puts("     <trkseg>");
462  
463                 wpt = FileStream.open(fname + "-wpt.gpx", "wt");
464                 wpt.puts("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
465                 wpt.puts(" <gpx");
466                 wpt.puts("     version=\"1.0\"");
467                 wpt.printf("     creator=\"zavai %s\"", zavai.config.version);
468                 wpt.puts("     xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
469                 wpt.puts("     xmlns=\"http://www.topografix.com/GPX/1/0\"");
470                 wpt.puts("     xsi:schemaLocation=\"http://www.topografix.com/GPX/1/0 http://www.topografix.com/GPX/1/0/gpx.xsd\">");
471  
472                 wpt_seq = 1;
473                 tracking_changed(true);
474         }
475  
476         public void stop_track()
477         {
478                 if (trk != null)
479                 {
480                         trk.puts("</trkseg></trk></gpx>");
481                         trk.flush();
482                         trk = null;
483                 }
484                 if (wpt != null)
485                 {
486                         wpt.puts("</gpx>");
487                         wpt.flush();
488                         wpt = null;
489                 }
490                 last_valid = false;
491                 tracking_changed(false);
492         }
493
494         // Mark a track point
495         public void trackpoint()
496         {
497                 if (!last_valid) return;
498                 if (trk == null)
499                         start_track(last_tstamp);
500
501                 trk.printf("<trkpt lat=\"%f\" lon=\"%f\">\n", last_lat, last_lon);
502                 var t = Time.local(last_tstamp);
503                 char[] ts = new char[25];
504                 t.strftime(ts, "%Y-%m-%dT%H:%M:%SZ");
505                 trk.printf("  <time>%s</time>\n", (string)ts);
506                 trk.printf("  <ele>%f</ele>\n", last_alt);
507                 // if course is not None: print >>self.trk, "    <course>%f</course>" % course
508                 // if speed is not None: print >>self.trk, "    <speed>%f</speed>" % speed
509                 // if fix is not None: print >>self.trk, "    <fix>%f</fix>" % fix
510                 // if hdop is not None: print >>self.trk, "    <hdop>%f</hdop>" % hdop
511                 trk.puts("</trkpt>");
512         }
513
514         // Mark a waypoint
515         public void waypoint(string? name = null)
516         {
517                 if (!last_valid) return;
518                 if (wpt == null)
519                         start_track(last_tstamp);
520
521                 string wptname;
522                 if (name == null)
523                 {
524                         wptname = "wpt_%d".printf(wpt_seq);
525                         wpt_seq += 1;
526                 } else {
527                         wptname = name;
528                 }
529
530                 wpt.printf("<wpt lat=\"%f\" lon=\"%f\">\n", last_lat, last_lon);
531                 wpt.printf("  <name>%s</name>\n", wptname);
532                 var t = Time.local(last_tstamp);
533                 char[] ts = new char[25];
534                 t.strftime(ts, "%Y-%m-%dT%H:%M:%SZ");
535                 wpt.printf("  <time>%s</time>\n", (string)ts);
536                 wpt.printf("  <ele>%f</ele>\n", last_alt);
537                 wpt.puts("</wpt>");
538         }
539 }
540
541 // #    def record(self):
542 // #        self.audio = Audio(self.make_waypoint)
543 // #        self.gps = GPS()
544 // #        # Get a fix and start recording
545 // #        if not self.gps.wait_for_fix(self.start_recording):
546 // #            self.gps_monitor = GPSMonitor(self.gps)
547 // #            self.gps_monitor.start()
548 // #
549 // #    def monitor(self):
550 // #        self.audio = None
551 // #        self.gps = GPS()
552 // #        self.gps_monitor = GPSMonitor(self.gps)
553 // #        self.gps_monitor.start()
554 // #
555 // #
556 // #    def make_waypoint(self):
557 // #        if self.gpx is None:
558 // #            return
559 // #        if self.last_pos is None:
560 // #            self.last_pos = self.gps.gps_position.GetPosition()
561 // #        (fields, tstamp, lat, lon, alt) = self.last_pos
562 // #        self.gpx.waypoint(tstamp, lat, lon, alt)
563 // #        zavai.info("Making waypoint at %s: %f, %f, %f" % (
564 // #            time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(tstamp)), lat, lon, alt))
565
566 public zavai.gps.GPS gps = null;
567 public zavai.gps.Monitor monitor = null;
568 public zavai.gps.Position position = null;
569 public zavai.gps.GPX gpx = null;
570
571 public void init()
572 {
573         gps = new GPS();
574         monitor = new Monitor();
575         position = new Position();
576         gpx = new GPX();
577
578         zavai.registry.register_service(gps);
579         zavai.registry.register_service(position);
580         zavai.registry.register_service(monitor);
581         zavai.registry.register_service(gpx);
582 }
583
584 }
585 }