使用gpsd / libgps C获取gps时间

时间:2016-11-02 04:13:15

标签: c linux gps serial-port gpsd

我正在尝试使用libgps从Adafruit终极gps中读取数据。我找到了一个代码示例,它提供了除gps时间之外我需要的所有信息。我怎样才能获得gps通过串口发送的gps时间,最好是以小时/分钟/秒为单位?

我试过gps_data.fix.time,但我不确定这是系统时间还是gps时间。

#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) {
        /* time to wait to receive data */
        if (gps_waiting (&gps_data, 500000)) {
        /* 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);
                //*****************WOULD LIKE TO PRINT THE TIME HERE.*****************************
                    printf("height: %f, latitude: %f, longitude: %f, speed: %f, timestamp: %f\n", gps_data.fix.altitude, gps_data.fix.latitude, gps_data.fix.longitude, gps_data.fix.speed, gps_data.fix.time/*tv.tv_sec*/);
            } else {
                printf("no GPS data available\n");
            }
        }
    }

    //sleep(1);
}

/* When you are done... */
gps_stream(&gps_data, WATCH_DISABLE, NULL);
gps_close (&gps_data);

return EXIT_SUCCESS;

}

2 个答案:

答案 0 :(得分:1)

我在libgps中跟踪了一些代码,并且gps_data.fix.time似乎是struct timespec类型的变量。定义如下:

struct timespec
    time_t  tv_sec;
    long    tv_nsec;    
};

您可能想尝试打印 gps_data.fix.time.tv_sec 和/或 gps_data.fix.time.tv_nsec

希望这会有所帮助。

答案 1 :(得分:0)

我阅读了我的PC的gps.h,发现timesec_t是两倍。 我尝试如下。

int my_gps_time; // for cast fix.time(double) to int
struct tm *ptm; // for date and time

...
my_gps_time = gps_data.fix.time;
ptm = localtime((time_t *)&my_gps_time);
printf("time: %04d/%02d/%02d,%02d:%02d:%02d\n",\
       ptm->tm_year + 1900, ptm->tm_mon + 1,\
       ptm->tm_mday,ptm->tm_hour, ptm->tm_min, ptm->tm_sec); 
...