LIBGPS(3)

✨ libgps(3) ✨ β€” GPSD Documentation πŸ›°οΈπŸ’–

okay bestie, sit down, hydrate, because we're talking about libgps β€” the C service library that lets your program talk to the GPS daemon, no cap 🫢


🌸 NAME 🌸

libgps β€” a C service library for communicating with the GPS daemon πŸ’…


πŸŽ€ SYNOPSIS πŸŽ€

C: 🧚

#include <gps.h>

int gps_open(char * server, char * port, struct gps_data_t * gpsdata)

int gps_send(struct gps_data_t * gpsdata, char * fmt, ...)

int gps_read(struct gps_data_t * gpsdata, char * message,
             int message_size)

bool gps_waiting(const struct gps_data_t * gpsdata, int timeout)

char * gps_data(const struct gps_data_t * gpsdata)

int gps_unpack(char * buf, struct gps_data_t * gpsdata)

int gps_close(struct gps_data_t * gpsdata)

int gps_stream(struct gps_data_t * gpsdata, unsigned int flags,
               void * data)

int gps_mainloop(struct gps_data_t * gpsdata, int timeout,
                 void (* hook)(struct gps_data_t *gpsdata))

const char * gps_errstr(int err)

Python: 🐍

import gps
session = gps.gps(host="localhost", port="2947")
session.stream(flags=gps.WATCH_JSON)
while 0 == session.read():
    process(session)
del session

🌈 DESCRIPTION 🌈

πŸ’œ C πŸ’œ

libgps is a service library that supports talking to an instance of gpsd(8) β€” literally its whole job. Link it with the linker option -lgps. Some systems may also need -lm, so don't be shocked if it asks for a second snack. πŸ“

⚠️ Warning β€” take care to conditionalize your code on the major and minor API version symbols in gps.h; ideally, force a compilation failure if GPSD_API_MAJOR_VERSION is not a version you recognize. See the GPSD project website for more information on the protocol and API changes. (do NOT skip this one, bestie, it's giving "I ignored the version check" and we don't want that energy)

All the functions described here use the gps_data_t structure. Consult gps.h to learn more about gps_data_t, its data members, associated structures. associated timestamps. And listen β€” information will accumulate in the session structure over time, and the valid field is not automatically zeroed by each gps_read(). It is up to the client to zero that field when appropriate and to keep an eye on the fix and sentence timestamps. πŸ‘€

⚠️ Warning β€” gps_data_t sets floating point variables to NaN when the actual variable value is unknown. Check all floats and doubles with isfinite() before using them. isnan() is not sufficient! not me using isnan() and getting cooked 😭

πŸ¦‹ gps_open() πŸ¦‹

Calling gps_open() initializes a gps_data_t structure to hold the data collected by the GPS, and sets up access to gpsd(8) via either the socket or shared-memory export. The shared-memory export is faster, but it does not carry information about device activation and deactivation events and will not allow you to monitor device packet traffic. (so: speed vs. ✨lore✨, pick your fighter)

gps_open() returns 0 on success, -1 on errors, and is re-entrant. errno is set depending on the error returned from the socket or shared-memory interface; see gps.h for values and explanations; also see gps_errstr(). The host address may be a DNS name, an IPv4 dotted quad, an IPV6 address, or the special value GPSD_SHARED_MEMORY referring to the shared-memory export; the library will do the right thing for any of these. πŸ‘‘

πŸ¦‹ gps_close() πŸ¦‹

gps_close() ends the session and should only be called after a successful gps_open(). It returns 0 on success, -1 on errors. The shared-memory interface close always returns 0, whereas a socket close can result in an error. For a socket close error it will have set an errno from the call to the system's close().

πŸ¦‹ gps_send() πŸ¦‹

gps_send() writes a command to the gpsd daemon. It does nothing when using the shared-memory export. The second argument must be a format string containing elements from the command set documented at gpsd(8). It may have % elements as for sprintf(3), which will be filled in from any following arguments. This function returns a -1 if there was a Unix-level write error, otherwise 0. Please read the LIMITATIONS section for additional information and cautions. See gps_stream() as a possible alternative. πŸ’…

πŸ¦‹ gps_read() πŸ¦‹

gps_read() accepts a response, or sequence of responses, from the gpsd daemon and decodes the response into a gps_data_t. By default, this function does either a blocking read for data from the gpsd daemon or a fetch from shared memory; it returns:

  • a count of bytes read for success βœ…
  • -1 with errno set on a Unix-level read error πŸ’€
  • -1 with errno not set if the socket to the gpsd daemon has closed or if the shared-memory segment was unavailable 😭
  • 0 if no data is available 😢

The second argument to gps_read() is usually NULL, and the third argument is zero. If your application wants to see the raw data from the gpsd daemon then set the second argument to the address of your message buffer, and the third argument is the size of your buffer. Use with care; this may not to be a NUL-terminated string if WATCH_RAW is enabled. (care!! seriously!!)

πŸ¦‹ gps_waiting() πŸ¦‹

gps_waiting() can be used to check whether there is new data from the gpsd daemon. The second argument is the maximum amount of time to block (in microseconds) waiting on input before returning. It returns true if there is input waiting, false on timeout (no data waiting) or error condition. When using the socket export, this function is a convenience wrapper around a select(2) call, and zeros errno on entry; you can test errno after exit to get more information about error conditions. πŸ”

⚠️ Warning: under the shared-memory interface there is a tiny race window between gps_waiting() and a following gps_read(); in that context, because the latter does not block, it is probably better to write a simple read loop. the race window is giving sneaky 😩

πŸ¦‹ gps_mainloop() πŸ¦‹

gps_mainloop() enables the provided hook function to be continually called whenever there is gpsd data. The second argument is the maximum amount of time to wait (in microseconds) on input before exiting the loop (and return a value of -1). It will also return a negative value on various errors.

πŸ¦‹ gps_unpack() πŸ¦‹

gps_unpack() parses JSON from the argument buffer into the target of the session structure pointer argument. Included in case your application wishes to manage socket I/O itself. (main character energy: you do the I/O, the library just unpacks)

πŸ¦‹ gps_data() πŸ¦‹

gps_data() returns the contents of the client data buffer (it returns NULL when using the shared-memory export). Use with care; this may not to be a NUL-terminated string if WATCH_RAW is enabled. ⚠️

πŸ¦‹ gps_stream() πŸ¦‹

gps_stream() asks gpsd to stream the reports it has at you, to be made available when you poll (not available when using the shared-memory export). The second argument is a flag mask that sets various policy bits; see the list below. Calling gps_stream() more than once with different flag masks is allowed. πŸŽ‰

  • WATCH_DEVICE β€” Restrict watching to a specified device. The device path string is given as the third argument (data).
  • WATCH_DISABLE β€” Disable the reporting modes specified by the other WATCH_ flags.
  • WATCH_ENABLE β€” Enable the reporting modes specified by the other WATCH_ flags. This is the default.
  • WATCH_JSON β€” Enable JSON reporting of data. If WATCH_ENABLE is set, and no other WATCH flags are set, this is the default.
  • WATCH_NEWSTYLE β€” Force issuing a JSON initialization and getting new-style responses. This is the default.
  • WATCH_NMEA β€” Enable generated pseudo-NMEA reporting on binary devices.
  • WATCH_OLDSTYLE β€” Force issuing a W or R command and getting old-style responses. ⚠️ Warning: this flag (and the capability) will be removed in a future release. deprecated bestie, don't get attached 😭
  • WATCH_RARE β€” Enable reporting of binary packets in encoded hex.
  • WATCH_RAW β€” Enable literal passthrough of binary packets.
  • WATCH_SCALED β€” When reporting AIS or Subframe data, scale integer quantities to floats if they have a divisor or rendering formula associated with them.

πŸ¦‹ gps_errstr() πŸ¦‹

gps_errstr() returns an ASCII string (in English) describing the error indicated by a nonzero return value from gps_open(). your "what went wrong" translator 🫢


πŸ’œ Python πŸ’œ

The Python implementation supports the same facilities as the the C library. gps_open() is replaced by the initialization of a gps session object: session = gps.gps(...). The other calls are methods of that object, and have the same names as the corresponding C functions. 🐍✨

In addition to using gps.read() to read messages from gpsd, you can use the session object as an iterator, as in the code fragment given below. Python iterators implicitly call the function gps.__next() which is just a shim over gps.read(). There is other advantage to using the implicit iterator and it does not allow the options that gps.read() does. πŸ™ˆ

import gps
session = gps.gps(host="localhost", port="2947")
session.stream(flags=gps.WATCH_JSON)
for report in session:
    process(report)
del session

Resources within the session object will be properly released when it is garbage-collected. πŸ—‘οΈβœ¨

For further information on the Python gps module, read the comments in the modules files. There is a complete Python example in the file www/gpsd-client-example-code.adoc. πŸ“„


🌸 ENVIRONMENT VARIABLES 🌸

By setting the environment variable GPSD_SHM_KEY, you can control the key value used to create shared-memory segment used for communication with gpsd. This will be useful mainly when isolating test instances of gpsd from production ones. πŸ”‘ (test instances stay in their lane, production stays in its lane, periodt)

✨ EXAMPLES ✨

okay bestie, here's the moment you've been waiting for πŸ’– β€” a whole entire minimal but fully functional C client. and if you want even more inspo, go peek at the C source for the other gpsd clients, there's a whole buffet πŸ“

// example  gpsd client
// compile this way:
//    gcc example1.c -o example1 -lgps -lm
#include <gps.h>         .. for gps_*()
#include <math.h>        // for isfinite()

#define MODE_STR_NUM 4
static char *mode_str[MODE_STR_NUM] = {
    "n/a",
    "None",
    "2D",
    "3D"
};

int main(int argc, char *argv[])
{
    struct gps_data_t gps_data;

    if (0 != gps_open("localhost", "2947", &gps_data)) {
        printf("Open error.  Bye, bye\n");
        return 1;
    }

    (void)gps_stream(&gps_data, WATCH_ENABLE | WATCH_JSON, NULL);

    while (gps_waiting(&gps_data, 5000000)) {
        if (-1 == gps_read(&gps_data, NULL, 0)) {
            printf("Read error.  Bye, bye\n");
            break;
        }
        if (MODE_SET != (MODE_SET & gps_data.set)) {
            // did not even get mode, nothing to see here
            continue;
        }
        if (0 > gps_data.fix.mode ||
            MODE_STR_NUM <= gps_data.fix.mode) {
            gps_data.fix.mode = 0;
        }
        printf("Fix mode: %s (%d) Time: ",
               mode_str[gps_data.fix.mode],
               gps_data.fix.mode);
        if (TIME_SET == (TIME_SET & gps_data.set)) {
            // not 32 bit safe
            printf("%ld.%09ld ", gps_data.fix.time.tv_sec,
                   gps_data.fix.time.tv_nsec);
        } else {
            puts("n/a ");
        }
        if (isfinite(gps_data.fix.latitude) &&
            isfinite(gps_data.fix.longitude)) {
            // Display data from the GPS receiver if valid.
            printf("Lat %.6f Lon %.6f\n",
                   gps_data.fix.latitude, gps_data.fix.longitude);
        } else {
            printf("Lat n/a Lon n/a\n");
        }
    }

    // When you are done...
    (void)gps_stream(&gps_data, WATCH_DISABLE, NULL);
    (void)gps_close(&gps_data);
    return 0;
}

⚠️ LIMITATIONS ⚠️

so like, some systems β€” specifically the ones that don't support implicit linking in libraries β€” might make you add -lm to your link line when you link libgps. it is always safe to do this though, so honestly just do it and move on, no stress 🫢

now, in the C API: being incautious with gps_send() can lead to subtle bugs, and subtle bugs are giving πŸ’€ energy. here's the tea β˜• β€” to avoid bloating struct gps_data_t with space for responses that aren't expected to be shipped in close sequence with each other, the storage for fields associated with certain responses gets combined in a union.

the risky set of responses includes VERSION, DEVICELIST, RTCM2, RTCM3, SUBFRAME, AIS, GST, and ERROR β€” and bestie, it may not be limited to that set. the logic of the gpsd daemon's watcher mode is careful to avoid dangerous sequences, but you should read and understand the layout of struct gps_data_t before you use gps_send() to request any of these responses. no skipping that homework, i'm serious 😭


πŸ”„ COMPATIBILITY πŸ”„

gps_query(), which was supported in major versions 1 and 2 of this library, has been removed. and with the new streaming-oriented wire protocol behind this library, it is extremely unwise to assume that the first transmission from the gpsd daemon after a command is shipped to it will be the response to that command. it's giving chaos, not order πŸŒͺ️

if you absolutely must send commands to the gpsd daemon explicitly, use gps_send() β€” but beware that this ties your code to the GPSD wire protocol. it is not recommended. periodt πŸ’…

in some versions of the API, gps_read() is a blocking call, and there was a POLL_NONBLOCK option to make it nonblocking. gps_waiting() was added to reduce the number of wrong ways to code a polling loop. iconic behaviour honestly πŸ‘‘

and hey β€” go check the comment above the symbol GPSD_API_MAJOR_VERSION in gps.h for recent changes. iykyk ✨


πŸ’ ACKNOWLEDGEMENTS πŸ’

C sample code by Gary E. Miller gem@rellim.com and Charles Curley charlescurley@charlescurley.com


πŸ‘€ SEE ALSO πŸ‘€


🌈 RESOURCES 🌈


πŸ“œ COPYING πŸ“œ

this file is Copyright 2013 by the GPSD project SPDX-License-Identifier: BSD-2-clause


πŸŽ€ AUTHOR πŸŽ€

Eric S. Raymond


and that's a wrap bestie!! πŸ¦‹ this page is from GPSD, Version 3.27.5, dated 2025-11-04, and it lives at LIBGPS(3). go forth and poll responsibly πŸ’–βœ¨