Getting Your Location

As the most useful thing a GPS can do is tell you its location, the most common interface implemented by the GPS object is Position. This interface has a method called GetPosition which will return the current position, and a signal called PositionChanged which is emitted when the position has changed. Note that although the GPS device itself will report a new position every second, Gypsy will only emit PositionChanged signals if the position has actually changed since the last emission.

However, before you can use the GPS object for anything useful, you must tell Gypsy to activate the GPS. This is done via the Start method on the Device interface.

device = dbus.Interface(gps, dbus_interface="org.freedesktop.Gypsy.Device")
device.Start()

The GetPosition method and PositionChanged signal both have the same arguments. The first argument is a bitset of fields which are valid. This is very important because often the GPS will only be able to get a longitude/latitude fix, and not be able to determine the altitude. Next is a Unix-style timestamp, so the application can know when the location was obtained. Next are the longitude and latitude, in fractional degrees. Finally the altitude, in meters.

# Some constants we'll need later
POSITION_FIELDS_NONE = 0
POSITION_FIELDS_LATITUDE = 1 << 0
POSITION_FIELDS_LONGITUDE = 1 << 1
POSITION_FIELDS_ALTITUDE = 1 << 2
# Get a proxy to the Position interface, and listen for position changed signals
position = dbus.Interface(gps, dbus_interface="org.freedesktop.Gypsy.Position")
def position_changed(fields_set, timestamp, latitude, longitude, altitude):
    print "%+2f, %+2f (%1fm)" % (
      (fields_set & POSITION_FIELDS_LATITUDE) and latitude or -1.0,
      (fields_set & POSITION_FIELDS_LONGITUDE) and longitude or -1.0,
      (fields_set & POSITION_FIELDS_ALTITUDE) and altitude or -1.0)
position.connect_to_signal("PositionChanged", position_changed)

Finally, we can enter the main loop. As the location changes we'll get signals, which result in the position_changed callback being called, which prints out the current position.