8ed0ece91a8c41ca9594bf22bde8822edf40e37d
[gigfinder] / src / opt / 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\
14                                             .METHOD_USER_SELECTED,
15                                     preferred_interval=location\
16                                             .INTERVAL_DEFAULT)
17         self.control.connect("error-verbose", self.on_error, self.loop)
18         self.control.connect("gpsd-stopped", self.on_stop, self.loop)
19
20         self.device = location.GPSDevice()
21         self.device.connect("changed", self.on_changed, self.control)
22
23     def update_location(self):
24         """ Run the loop and update lat and long """
25         self.reset()
26         gobject.idle_add(self.start_location, self.control)
27         self.loop.run()
28
29     def on_error(self, control, error, data):
30         """ Handle errors """
31         print "location error: %d... quitting" % error
32         data.quit()
33
34     def on_changed(self, device, data):
35         """ Set long and lat """
36         if not device:
37             return
38         if device.fix:
39             # once fix is found and long, lat available set long lat
40             if device.fix[1] & location.GPS_DEVICE_LATLONG_SET:
41                 # wait for a second fix before exiting
42                 self.fix_count += 1
43                 if self.fix_count > 1:
44                     self.lat, self.long = device.fix[4:6]
45                     data.stop()
46
47     def on_stop(self, control, data):
48         """ Stop the location service """
49         print "quitting"
50         data.quit()
51
52     def start_location(self, data):
53         """ Start the location service """
54         self.fix_count = 0
55         data.start()
56         return False
57
58     def reset(self):
59         """ Reset coordinates """
60         self.lat = None
61         self.long = None
62         self.device.reset_last_known()
63