ab3db5338938a79862340761ba043a1e994ef8a1
[gigfinder] / locator.py
1 import gobject
2 import location
3
4 class LocationUpdater:
5
6     def __init__(self):
7         self.lat = None
8         self.long = None
9         self.loop = gobject.MainLoop()
10         self.fix_count = 0
11
12         self.control = location.GPSDControl.get_default()
13         self.control.set_properties(preferred_method=location.METHOD_USER_SELECTED,
14                                preferred_interval=location.INTERVAL_DEFAULT)
15         self.control.connect("error-verbose", self.on_error, self.loop)
16         self.control.connect("gpsd-stopped", self.on_stop, self.loop)
17
18         self.device = location.GPSDevice()
19         self.device.connect("changed", self.on_changed, self.control)
20
21     def update_location(self):
22         """ Run the loop and update lat and long """
23         self.reset()
24         gobject.idle_add(self.start_location, self.control)
25         self.loop.run()
26
27     def on_error(self, control, error, data):
28         """ Handle errors """
29         print "location error: %d... quitting" % error
30         data.quit()
31
32     def on_changed(self, device, data):
33         """ Set long and lat """
34         if not device:
35             return
36         if device.fix:
37             # once fix is found and long, lat available set long lat
38             if device.fix[1] & location.GPS_DEVICE_LATLONG_SET:
39                 self.fix_count += 1
40                 if self.fix_count > 1:
41                     self.lat, self.long = device.fix[4:6]
42                     data.stop()
43
44     def on_stop(self, control, data):
45         """ Stop the location service """
46         print "quitting"
47         data.quit()
48
49     def start_location(self, data):
50         """ Start the location service """
51         self.fix_count = 0
52         data.start()
53         return False
54
55     def reset(self):
56         """ Reset coordinates """
57         self.lat = None
58         self.long = None
59         self.device.reset_last_known()
60