Trying to improve threading for the location
[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
11         self.control = location.GPSDControl.get_default()
12         self.control.set_properties(preferred_method=location\
13                                             .METHOD_USER_SELECTED,
14                                     preferred_interval=location\
15                                             .INTERVAL_DEFAULT)
16         self.control.connect("error-verbose", self.on_error, self.loop)
17         self.control.connect("gpsd-stopped", self.on_stop, self.loop)
18
19         self.device = location.GPSDevice()
20         self.device.connect("changed", self.on_changed, self.control)
21
22     def update_location(self):
23         """ Run the loop and update lat and long """
24         self.reset()
25         gobject.idle_add(self.start_location, self.control)
26         self.loop.run()
27
28     def on_error(self, control, error, data):
29         """ Handle errors """
30         print "location error: %d... quitting" % error
31         data.quit()
32
33     def on_changed(self, device, data):
34         """ Set long and lat """
35         if not device:
36             return
37         if device.fix:
38             # once fix is found and horizontal accuracy is 1km
39             if location.GPS_DEVICE_LATLONG_SET:
40                 if device.fix[6] <= 100000:
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         data.quit()
47
48     def start_location(self, data):
49         """ Start the location service """
50         data.start()
51         return False
52
53     def reset(self):
54         """ Reset coordinates """
55         self.lat = None
56         self.long = None
57         self.device.reset_last_known()
58