Hi all,
I have gpsd and libgps installed on my Ubuntu 14.04 using the apt-get install command. The gpsd version is 3.9 (Ubuntu software center does not have gpsd updated to the latest version).
I use the following code (from
stackoverflow) to get the coordinates (latitude and longitude). This code uses socket to communicate with the gpsd daemon process, generally it works well.
But I often find that the gps_waiting function returns false, and after that even I re-run this code, the coordinates can no longer be obtained (still fail at gps_waiting). I tried several methods, like killing the gpsd process and restart it, removing the /var/run/gpsd.sock, all didn't work. The only thing I can do is to reboot the computer. I have got two questions:
1. How to avoid this problem.
2. This is only a toy program. In my project, I need to have the latest coordinates immediately whenever I want, I dont want to wait for any time before I can have the coordinates, also not in a loop as in this toy program. How could I achieve this?
I am very happy to see some sample code in real projects. Your help are very much appreciated. Thank you!
Best wishes,
David
#include <gps.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
int main() {
int rc;
struct timeval tv;
struct gps_data_t gps_data;
if ((rc = gps_open("localhost", "2947", &gps_data)) == -1) {
printf("code: %d, reason: %s\n", rc, gps_errstr(rc));
return EXIT_FAILURE;
}
gps_stream(&gps_data, WATCH_ENABLE | WATCH_JSON, NULL);
while (1) {
/* wait for 2 seconds to receive data */
if (gps_waiting (&gps_data, 2000000)) {
/* read data */
if ((rc = gps_read(&gps_data)) == -1) {
printf("error occured reading gps data. code: %d, reason: %s\n", rc, gps_errstr(rc));
} else {
/* Display data from the GPS receiver. */
if ((gps_data.status == STATUS_FIX) &&
(gps_data.fix.mode == MODE_2D || gps_data.fix.mode == MODE_3D) &&
!isnan(gps_data.fix.latitude) &&
!isnan(gps_data.fix.longitude)) {
//gettimeofday(&tv, NULL); EDIT: tv.tv_sec isn't actually the timestamp!
printf("latitude: %f, longitude: %f, speed: %f, timestamp: %ld\n", gps_data.fix.latitude, gps_data.fix.longitude, gps_data.fix.speed, gps_data.fix.time); //EDIT: Replaced tv.tv_sec with gps_data.fix.time
} else {
printf("no GPS data available\n");
}
}
}
else printf("waiting failed.\n");
}
/* When you are done... */
gps_stream(&gps_data, WATCH_DISABLE, NULL);
gps_close (&gps_data);
return EXIT_SUCCESS;
}
--
==================================================
David Huichen Dai, PhD
Research assistant
Lab of Broadband Network Switching Technology and Communication
Dept. of Computer Science and Technology
Tsinghua University, Beijing, P.R. China, 100084
Tel: 86-010-6277-3441
Email: address@hidden; address@hidden
==================================================