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 ingps.h; ideally, force a compilation failure ifGPSD_API_MAJOR_VERSIONis 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_tsets floating point variables toNaNwhen the actual variable value is unknown. Check all floats and doubles withisfinite()before using them.isnan()is not sufficient! not me usingisnan()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 β
-1witherrnoset on a Unix-level read error π-1witherrnonot set if the socket to the gpsd daemon has closed or if the shared-memory segment was unavailable π0if 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 betweengps_waiting()and a followinggps_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 otherWATCH_flags.WATCH_ENABLEβ Enable the reporting modes specified by the otherWATCH_flags. This is the default.WATCH_JSONβ Enable JSON reporting of data. IfWATCH_ENABLEis set, and no otherWATCHflags 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 aWorRcommand 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 π
- GPSD Client Example Code <https://gpsd.io/gpsd-client-example-code.html> β an annotated example client. lowkey the best starting point fr fr
- GPSD Client HOWTO <https://gpsd.io/client-howto.html> β a GPS client HOWTO.
- Project web site: https://gpsd.io/ β the main character's home address π
π 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 πβ¨
π¦ where this page comes from
- arch rolling: gpsd 3.27.5-1 Β· BSD
- fedora 44: gpsd-devel 1:3.27.5-3.fc44 Β· BSD-2-Clause
- fedora 44: gpsd-devel 1:3.27.5-3.fc44 Β· BSD-2-Clause
- fedora 44: gpsd-devel 1:3.27.5-5.fc44 Β· BSD-2-Clause
- fedora 44: gpsd-devel 1:3.27.5-5.fc44 Β· BSD-2-Clause
- nixos 26.05: gpsd 3.27.5
- nixpkgs unstable: gpsd 3.27.5
- opensuse-leap 16.0: gpsd-devel 3.27.5-160000.1.1 Β· BSD-3-Clause
- opensuse-leap 16.0: gpsd-devel 3.27.5-160000.1.1 Β· BSD-3-Clause
- opensuse-leap 16.0: gpsd-devel 3.27.5-160000.1.1 Β· BSD-3-Clause
- opensuse-leap 16.0: gpsd-devel 3.27.5-160000.1.1 Β· BSD-3-Clause
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms