View Single Post
Posts: 5 | Thanked: 0 times | Joined on Mar 2011 @ Canada
#2
I have found the solution.
Here's the sample code for any of you who are still wondering.

Code:
import location as gps
import gobject

class myGPS():
    
    def __init__(self):
        try:
            self.boolLoop = False
            self.loop = gobject.MainLoop()
            
            self.control = gps.GPSDControl.get_default()
            self.device = gps.GPSDevice()
            self.control.set_properties(preferred_method=gps.METHOD_USER_SELECTED,
                                        preferred_interval=gps.INTERVAL_5S)
            
            self.control.connect("error-verbose", self.on_error, self.loop)
            self.device.connect("changed", self.on_changed, self.control)
            self.control.connect("gpsd-stopped", self.on_stop, self.loop)
            print "GPS object created"
        except Exception, err:
            print "Cannot Init:"
    
    def on_error(self, control, error, data):
        print ("location error: %d... quitting" % error)
        data.quit()
    
    def on_changed(self, device, data):
        if not device:
            return
        if device.fix:
            # get all the data needed from device.fix
            if device.fix[1] & gps.GPS_DEVICE_LATLONG_SET:
                print ("lat = %f, long = %f" % device.fix[4:6])
                print ("acc = %f" % device.fix[12])
    
    def on_stop(self, control, data):
        print "GPS stop"
    
    def start_location(self, data):
        data.start()
    
    def start(self):
        print "GPS start"
        if self.boolLoop:
            self.control.start()
        else:
            gobject.idle_add(self.start_location, self.control)
            self.loop.run()
            self.boolLoop = True
        
    def stop(self):
        self.control.stop()
On the other hand, I'm still not sure why I need to use gobject, without it it won't work.
To my understanding, the control.start runs the GPS thread by itself.
If someone could explain about gobject and its mainloop, it'll be appreciated.

Thanks