예제 #1
1
/** \brief Initialize whatever structures inside the qth_t stucture for later updates.
 * \param qth the qth data structure to update
 * 
 *Initial intention of this is to open sockets and ports to gpsd 
 *and other like services to update the qth position.
 */
gboolean qth_data_update_init(qth_t * qth)
{
#ifdef HAS_LIBGPS
    char *port;
#endif
    gboolean retval = FALSE;

    switch (qth->type)
    {

    case QTH_STATIC_TYPE:
        /* nothing to do.  the data never updates */
        break;
    case QTH_GPSD_TYPE:
#ifdef HAS_LIBGPS
        switch (GPSD_API_MAJOR_VERSION)
        {
        case 4:
#if GPSD_API_MAJOR_VERSION==4
            /* open the connection to gpsd and start the stream */
            qth->gps_data = g_try_new0(struct gps_data_t, 1);

            port = g_strdup_printf("%d", qth->gpsd_port);
            if (gps_open_r(qth->gpsd_server, port, qth->gps_data) == -1)
            {
                free(qth->gps_data);
                qth->gps_data = NULL;
                sat_log_log(SAT_LOG_LEVEL_ERROR,
                            _("%s: Could not open gpsd at  %s:%d"),
                            __FUNCTION__, qth->gpsd_server, qth->gpsd_port);
                retval = FALSE;
            }
            else
            {
                (void)gps_stream(qth->gps_data, WATCH_ENABLE, NULL);
                retval = TRUE;
            }
            g_free(port);
#endif
            break;
        case 5:
#if GPSD_API_MAJOR_VERSION==5
            /* open the connection to gpsd and start the stream */
            qth->gps_data = g_try_new0(struct gps_data_t, 1);

            port = g_strdup_printf("%d", qth->gpsd_port);
            if (gps_open(qth->gpsd_server, port, qth->gps_data) == -1)
            {
                free(qth->gps_data);
                qth->gps_data = NULL;
                sat_log_log(SAT_LOG_LEVEL_ERROR,
                            _("%s: Could not open gpsd at  %s:%d"),
                            __FUNCTION__, qth->gpsd_server, qth->gpsd_port);
                retval = FALSE;
            }
            else
            {
                (void)gps_stream(qth->gps_data, WATCH_ENABLE, NULL);
                retval = TRUE;
            }
            g_free(port);
#endif
            break;
        default:
            sat_log_log(SAT_LOG_LEVEL_ERROR,
                        _("%s: Unsupported gpsd api major version (%d)"),
                        __FUNCTION__, GPSD_API_MAJOR_VERSION);


            return FALSE;
            break;
        }
#else
        return FALSE;
#endif
        break;

    default:
        break;
    }
    return retval;
}
예제 #2
0
int main(int argc, char** argv)
{
    int ret = 0;

    if (!parse_args(argc, argv))
        return 1;

    GMainLoop *ml =  g_main_loop_new(NULL, FALSE);

    gpsdata = malloc(sizeof(struct gps_data_t));

    printf("Connecting to gpsd server %s, port %s\n", server, port);

    ret = gps_open(server, port, gpsdata);
    if (ret != 0) {
        perror("error connecting to gpsd");
        return 1;
    }

    gps_stream(gpsdata, WATCH_ENABLE, NULL);

    IvyInit ("GPSd2Ivy", "GPSd2Ivy READY", NULL, NULL, NULL, NULL);
    IvyStart(ivy_bus);

    g_timeout_add(TIMEOUT_PERIOD, gps_periodic, NULL);

    g_main_loop_run(ml);

    (void) gps_stream(gpsdata, WATCH_DISABLE, NULL);
    (void) gps_close (gpsdata);

    free(gpsdata);

    return ret;
}
예제 #3
0
int main(int argc, char **argv) {
    bool res;
    int rc;

    /* check the parameters */
    if (argc != 4) {
        fprintf(stderr, "Usage: %s nodeName host port\n", argv[0]);
        exit(1);
    }

    /* Use the parameters */
    gpsNodeName = argv[1];
    int sockfd = create_udp_socket(argv[2], argv[3]);

    do {
        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);

        res = mainLoop(&gps_data, sockfd);

        /* When you are done... */
        gps_stream(&gps_data, WATCH_DISABLE, NULL);
        gps_close (&gps_data);
    } while (res == false);

    return EXIT_SUCCESS;
}
예제 #4
0
int main(int argc, char *argv[])
{
    char *server = NULL, *port = DEFAULT_GPSD_PORT;
    bool running = true;
    int ret = 0;
    GMainLoop *ml =  g_main_loop_new(NULL, FALSE);


    gpsdata = malloc(sizeof(struct gps_data_t));

    ret = gps_open(NULL, port, gpsdata);
    if (ret != 0) {
        perror("error connecting to gpsd");
        return 1;
    }

    gps_stream(gpsdata, WATCH_ENABLE, NULL);

    IvyInit ("GPSd2Ivy", "GPSd2Ivy READY", NULL, NULL, NULL, NULL);
    IvyStart("224.255.255.255:2010");

    g_timeout_add(TIMEOUT_PERIOD, gps_periodic, NULL);

    g_main_loop_run(ml);

    (void) gps_stream(gpsdata, WATCH_DISABLE, NULL);
    (void) gps_close (gpsdata);

    free(gpsdata);

    return ret;
}
예제 #5
0
int main()
{
    char * hostName = "127.0.0.1";
    char * hostPort = "2947";

    // initializes a GPS-data structure to hold the data collected by
    // the GPS, and sets up access to gpsd
    if( -1 == gps_open(hostName, hostPort, &gpsdata) )
    {
        printf("ERROR: gps_open returned -1");
    }

    gps_stream(&gpsdata, WATCH_ENABLE | WATCH_JSON, NULL);

    /* Put this in a loop with a call to a high resolution sleep () in it. */
    while(1)
    {
        /* Used to check whether there is new data from the
         * daemon. The second argument is the maximum amount of time
         * to wait (in microseconds) on input before returning */
        if( gps_waiting(&gpsdata, 500) )
        {
            if( -1 == gps_read (&gpsdata) )
            {
                printf("ERROR: gps_read returned -1");
            }
            else
            {
                /* Display data from the GPS receiver. */
                printf("\nSatellites Used:%d\n", gpsdata.satellites_used);
                
                /* Error estimates are at 95% confidence. */

                printf("Time:%f, Error:%f\n", gpsdata.fix.time, gpsdata.fix.ept);
                printf("Latitude:%f, Error:%f\n", gpsdata.fix.latitude, gpsdata.fix.epy);
                printf("Longitude:%f, Error:%f\n", gpsdata.fix.longitude, gpsdata.fix.epx);
                printf("Altitude:%f, Error:%f\n", gpsdata.fix.altitude, gpsdata.fix.epv);
                printf("Track:%f, Error:%f\n", gpsdata.fix.track, gpsdata.fix.epd);
                printf("Speed:%f, Error:%f\n", gpsdata.fix.speed, gpsdata.fix.eps);
                printf("Climb:%f, Error:%f\n", gpsdata.fix.climb, gpsdata.fix.epc);
            }
        }
        
        usleep(250000);
    }

    /* When you are done... */
    (void) gps_stream(&gpsdata, WATCH_DISABLE, NULL);
    (void) gps_close (&gpsdata);
}
예제 #6
0
파일: s52ais.c 프로젝트: MasterLivens/S52
static int           _connectGPSD(void)
// return FALSE if _ais_list is NULL or 10 failed attempt to connect else TRUE
{
    int nWait = 0;

    g_print("s52ais:_gpsdClientRead(): start looping ..\n");
    memset(&_gpsdata, 0, sizeof(_gpsdata));

    while (0 != gps_open(GPSD_HOST, GPSD_PORT, &_gpsdata)) {   // android (gpsd 2.96)
        g_print("s52ais:_gpsdClientRead(): no gpsd running or network error, wait 1 sec: %d, %s\n", errno, gps_errstr(errno));

        // try to connect to GPSD server, bailout after 10 failed attempt
        GMUTEXLOCK(&_ais_list_mutex);

        if ((NULL==_ais_list) || (10 <= ++nWait)) {
            g_print("s52ais:_gpsdClientRead() no AIS list (main exited) or no GPSD server.. terminate _gpsClientRead thread\n");

            GMUTEXUNLOCK(&_ais_list_mutex);

            return FALSE;
        }
        GMUTEXUNLOCK(&_ais_list_mutex);

        g_usleep(1000 * 1000); // 1.0 sec
    }

    if (-1 == gps_stream(&_gpsdata, WATCH_ENABLE|WATCH_NEWSTYLE, NULL)) {
        g_print("s52ais:_gpsdClientRead():gps_stream() failed .. exiting\n");
        return FALSE;
    }

    return TRUE;
}
예제 #7
0
파일: gpxlogger.c 프로젝트: idaohang/gpsd-3
/*@-mustfreefresh -compdestroy@*/
static int socket_mainloop(void)
{
    unsigned int flags = WATCH_ENABLE;

    if (gps_open(source.server, source.port, &gpsdata) != 0) {
	(void)fprintf(stderr,
		      "%s: no gpsd running or network error: %d, %s\n",
		      progname, errno, gps_errstr(errno));
	exit(1);
    }

    if (source.device != NULL)
	flags |= WATCH_DEVICE;
    (void)gps_stream(&gpsdata, flags, source.device);

    print_gpx_header();
    for (;;) {
	if (!gps_waiting(&gpsdata, 5000000)) {
	    (void)fprintf(stderr, "%s: error while waiting\n", progname);
	    break;
	} else {
	    (void)gps_read(&gpsdata);
	    conditionally_log_fix(&gpsdata);
	}
    }
    (void)gps_close(&gpsdata);
    return 0;
}
예제 #8
0
    gpsd_iface_impl(const std::string &addr, uint16_t port)
        : _detected(false), _bthread(), _timeout_cnt(0)
    {
        boost::unique_lock<boost::shared_mutex> l(_d_mutex);

        if (gps_open(addr.c_str(),
            str(boost::format("%u") % port).c_str(),
            &_gps_data) < 0) {
            throw uhd::runtime_error(
                str((boost::format("Failed to connect to gpsd: %s")
                    % gps_errstr(errno))));
        }

        // register for updates, we don't specify a specific device,
        // therefore no WATCH_DEVICE
        gps_stream(&_gps_data, WATCH_ENABLE, NULL);

        // create background thread talking to gpsd
        boost::thread t(boost::bind(&gpsd_iface_impl::_thread_fcn ,this));
        _bthread.swap(t);


        _sensors = boost::assign::list_of<std::string>("gps_locked")("gps_time") \
            ("gps_position")("gps_gpgga")("gps_gprmc").to_container(_sensors);
    }
예제 #9
0
파일: GPS.cpp 프로젝트: wflk/WarPi
gps_data_t GPS::get_current_location() {
    struct gps_data_t gps_data;
    int rc;

    if ((rc = gps_open("localhost", this->gpsd_port.c_str(), &gps_data)) == -1) {
        this->last_error = "GPS_OPEN";
        this->all_errors.push_back(this->last_error);
        return gps_data;
    }
    gps_stream(&gps_data, WATCH_ENABLE | WATCH_JSON, NULL);

    if (gps_waiting(&gps_data, this->timeout)) {
        if ((rc = gps_read(&gps_data)) == -1) {
            this->last_error == "GPS_READ";
            this->all_errors.push_back(this->last_error);
            return gps_data;
        } else {
            if ((gps_data.status == STATUS_FIX) && (gps_data.fix.mode == MODE_2D || gps_data.fix.mode == MODE_3D) &&
                !std::isnan(gps_data.fix.longitude) && !std::isnan(gps_data.fix.latitude)) {
                return gps_data;
            } else {
                this->last_error == "NO_GPS_DATA";
                this->all_errors.push_back(this->last_error);
                return gps_data;
            }
        }
    } else {
        this->last_error = "TIMEOUT";
        this->all_errors.push_back(this->last_error);
        return gps_data;
    }
}
예제 #10
0
int startLocationServices()
{
  if (working) { return 0.0; }

    gpsdata.status = STATUS_NO_FIX;
    gpsdata.satellites_used = 0;
    gps_clear_fix(&(gpsdata.fix));
    gps_clear_dop(&(gpsdata.dop));

    gpsdata.fix.latitude=0;
    gpsdata.fix.longitude=0;

    logfile=stdout;
	gpsd_source_spec(NULL, &source);


    unsigned int flags = WATCH_ENABLE;

    if (gps_open("127.0.0.1" , "2947", &gpsdata) != 0)
        { fprintf(stderr,"LoacationService : no gpsd running or network error: %d, %s\n", errno, gps_errstr(errno)); return 0; }

    if (source.device != NULL)
	flags |= WATCH_DEVICE;
    gps_stream(&gpsdata, flags, source.device);


    fprintf(stderr,MAGENTA "Polling location services to determine if they will be used in this run : \n" NORMAL);
    fprintf(stderr,MAGENTA "If you don't want to wait use `sudo service gpsd stop`\n" NORMAL);
    unsigned int tries=3;
    unsigned int success=0;
    unsigned int i=0;
    working=1; //lets assume that we are working so that  pollLocationServices will work
    for (i=0; i<tries; i++)
    {
        success+=pollLocationServices();
        usleep(1000*1000);
    }

    if (success==0)
    {
     fprintf(stderr,RED "Location services failed to provide gps coordinates beeing switched off\n" NORMAL);
     working=0;
    } else
    if (success<tries)
    {
     fprintf(stderr,YELLOW "Location services failed to provide gps coordinates beeing switched off\n" NORMAL);
     working=1;
    } else
    if (success==tries)
    {
     fprintf(stderr,GREEN "Location services working fine.. :) \n" NORMAL);
     working=1;
    }

 return working;
}
예제 #11
0
struct gps_data_t* gpsmm::stream(int flags)
{
    if (to_user == NULL)
	return NULL;
    else if (gps_stream(gps_state(),flags, NULL)==-1) {
	return NULL;
    }
    else {
	return backup();
    }
}
예제 #12
0
    virtual ~gpsd_iface_impl(void)
    {
        // interrupt the background thread and wait for it to finish
        _bthread.interrupt();
        _bthread.join();

        // clean up ...
        {
            boost::unique_lock<boost::shared_mutex> l(_d_mutex);

            gps_stream(&_gps_data, WATCH_DISABLE, NULL);
            gps_close(&_gps_data);
        }
    }
예제 #13
0
static int attempt_reconnect(const char *host, const char *port,
			     struct gps_data_t *gpsdata)
{
	int rc;

	rc = gps_open(host, port, gpsdata);
	if (rc)
		return -1;

	syslog(LOG_INFO, "(re)connected to gpsd\n");

	gps_stream(gpsdata, WATCH_ENABLE|WATCH_JSON, NULL);

	return 0;
}
예제 #14
0
파일: gpsd.cpp 프로젝트: buelowp/startrac
void Gpsd::connectToServer(const QString &h, quint16 p, Gpsd::StreamMode m)
{
    if (isConnected()) {          // We're connected
        disconnectFromServer();   // disconnect first
    }

    host = h;
    port = p;
    if (gps_open(h.toLatin1().data(), QString().setNum(p).toLatin1().data(), &gpsdata) == 0) {
        notifier = new QSocketNotifier(gpsdata.gps_fd, QSocketNotifier::Read);
        notifier->setEnabled(true);
        connect(notifier, SIGNAL(activated(int)), this, SLOT(handleInput(int)));
        emit connectionStatus(true);

        gps_stream(&gpsdata, WATCH_ENABLE|m, NULL);
    } else {
예제 #15
0
파일: seegps.c 프로젝트: bkovitz/pru
int main() {
  struct gps_data_t gps_data;
  int err;

  if ((err = gps_open("localhost", DEFAULT_GPSD_PORT, &gps_data)) != 0) {
    fprintf(stderr, gps_errstr(err));
    exit(1);
  }

  gps_stream(&gps_data, WATCH_ENABLE, NULL);

  for (int i = 0; i < NUM_GPS_READS; i++)
    one_gps_cycle(&gps_data);


  return 0;
}
예제 #16
0
파일: s52ais.c 프로젝트: MasterLivens/S52
static gpointer      _gpsdClientStart(gpointer dummy)
{
    int ret = -1;

    while (ret < 0) {
        if (TRUE == _connectGPSD()) {

            ret = _gpsdClientReadLoop();

            // disconnect GPSD
            gps_stream(&_gpsdata, WATCH_DISABLE, NULL);
            gps_close(&_gpsdata);
        }
    }

    return dummy;
}
예제 #17
0
파일: dwgps.c 프로젝트: glneo/direwolf
void dwgps_term (void) {

#if __WIN32__
	
#elif ENABLE_GPS

	if (init_status == INIT_SUCCESS) {

#ifndef USE_GPS_SHM
	  gps_stream(&gpsdata, WATCH_DISABLE, NULL);
#endif
	  gps_close (&gpsdata);
	}
#else 

#endif

} /* end dwgps_term */
예제 #18
0
int main (int argc, gchar *argv[])
{

    GError *error = NULL;
	GIOChannel *gio_read;


    ctx.user = "******";
    ctx.pass = "******";
    ctx.state = APRSIS_DISCONNECTED;
    
//    g_thread_init(NULL);
    g_type_init();
    
    g_message("opening aprs-is");
    start_aprsis(&ctx);

    g_message("opening gpsd");
	// Connect to GPS (FIXME move to thread)
    if (gps_open("localhost", "2947", &gpsdata) != 0) {
		printf("no gpsd: %d, %s\n", errno, gps_errstr(errno));
		exit(2);
    }
    
    printf("%x\n", gpsdata);
    printf("%x\n", flags);
    
    //sleep(1);
    
	gps_stream(&gpsdata, flags, NULL);
	//printf("%s\n", source.device);
	printf("started stream\n");
	gpsd_io_channel = g_io_channel_unix_new(gpsdata.gps_fd);
	g_io_channel_set_flags(gpsd_io_channel, G_IO_FLAG_NONBLOCK, NULL);

	sid3 = g_io_add_watch(gpsd_io_channel, G_IO_IN | G_IO_PRI, gpsd_data_cb, NULL);

    printf("about to start main loop\n");

	main_loop = g_main_loop_new (NULL, FALSE);
	g_main_loop_run (main_loop);

	return 0;
}
예제 #19
0
// Open the stream with the GPSd socket
int gpsdOpenStream() {

	// ... to verify what version
	gpsd_source_spec(NULL, &source); // GPSD_SERVERPORT, &source);
	// gpsd_source_spec(FCD_GPSD_SERVERPORT, &source);
	//
	// Open the stream
    if (gps_open(source.server, source.port, &gpsdata) != 0) {
    	fcdLogErr("No GPSD daemon running or network !",(char *)gps_errstr(errno));
    	__recordStringValue("NO LINK", "GPSstatus");
		return(false);
    }
    // If the device is defined then add a flag
    if (source.device != NULL) flags |= WATCH_DEVICE;
    // Finally connect the device to the stream
    (void)gps_stream(&gpsdata, flags, source.device);
	__recordStringValue("LINK", "GPSstatus");
	return(true);
}
예제 #20
0
static void gpsd_connect_gpsd(struct globals *globals)
{
	unsigned int flags = WATCH_ENABLE | WATCH_JSON;
	int ret;

	ret = gps_open(globals->gpsdsource.server, globals->gpsdsource.port,
		       &globals->gpsdata);

	if (ret) {
		/* Could not connect to gpsd. Set the fd so we don't
		   try to perform select(2) on it. */
		globals->gpsdata.gps_fd = -1;
		return;
	}

	if (globals->gpsdsource.device != NULL)
		flags |= WATCH_DEVICE;

	gps_stream(&globals->gpsdata, flags, globals->gpsdsource.device);
}
예제 #21
0
//Will open a gps data stream
int openStream(){
    static struct fixsource_t source;
    unsigned int flags = WATCH_ENABLE;


    if(gps_open(source.server, source.port, gps_data_ptr) == -1){
        //print failure
        return 0;
    }
    if(source.device == NULL){
        //print failure
        return 0;
    }

    flags |= WATCH_DEVICE;

    gps_stream(gps_data_ptr, flags, source.device);

    return 1;
}
예제 #22
0
int main()
{
	static struct fixsource_t source;
	struct gps_data_t* gpsdata;						
    	unsigned int flag = WATCH_ENABLE | WATCH_JSON;	// Set watch flags
	build_curses(); //build GUI
	gpsdata = (struct gps_data_t*)malloc (sizeof (struct gps_data_t));	// Retrieve a pointer to the structure
	if (gps_open(source.server , source.port, gpsdata) == -1)
	{
		dcgps_error(NO_GPS);
		return 1;
	}

	if(source.device != NULL)
		flag |= WATCH_DEVICE;
	gps_stream(gpsdata, flag, source.device);	// start data report stream from the sensor
	read(gpsdata);
	gps_close(gpsdata);	// close gps stream
	kill_curses();
	return 0;
}
예제 #23
0
파일: gpsdate.c 프로젝트: bofhbug/gpsdate
int main(int argc, char **argv)
{
	char *host = "localhost";
	int i, rc;

	openlog("gpsdate", LOG_PERROR, LOG_CRON);

	if (argc > 1)
		host = argv[1];

	for (i = 1; i <= NUM_RETRIES; i++) {
		printf("Attempt #%d to connect to gpsd at %s...\n", i, host);
		rc = gps_open(host, DEFAULT_GPSD_PORT, &gpsdata);
		if (!rc)
			break;
		sleep(RETRY_SLEEP);
	}

	if (rc) {
		syslog(LOG_ERR, "no gpsd running or network error: %d, %s\n",
			errno, gps_errstr(errno));
		closelog();
		exit(EXIT_FAILURE);
	}

	osmo_daemonize();

	gps_stream(&gpsdata, WATCH_ENABLE|WATCH_JSON, NULL);

	/* We run in an endless loop.  The only reasonable way to exit is after
	 * a correct GPS timestamp has been received in callback() */
	while (1)
		gps_mainloop(&gpsdata, INT_MAX, callback);

	gps_close(&gpsdata);

	closelog();
	exit(EXIT_SUCCESS);
}
예제 #24
0
파일: gpsd2ivy.c 프로젝트: AshuLara/lisa
int main(int argc, char *argv[])
{
    char *server = NULL, *port = DEFAULT_GPSD_PORT;
    GMainLoop *ml =  g_main_loop_new(NULL, FALSE);

    gpsdata = gps_open(server, port);

    if (!gpsdata) perror("error connecting to gpsd");

    gps_set_raw_hook(gpsdata, update_gps);

    gps_stream(gpsdata, WATCH_ENABLE, NULL);
  
    IvyInit ("GPSd2Ivy", "GPSd2Ivy READY", NULL, NULL, NULL, NULL);
    IvyStart("127.255.255.255");
  
    g_timeout_add(TIMEOUT_PERIOD, gps_periodic, NULL);
  
    g_main_loop_run(ml);

    return 0;
}
예제 #25
0
/*@-mustfreefresh -mustfreeonly -branchstate -globstate@*/
int main(int argc, char **argv)
{
    int ch;
    bool daemonize = false;
    unsigned int flags = WATCH_ENABLE;
    struct exportmethod_t *method = NULL;

    progname = argv[0];

    if (export_default() == NULL) {
	(void)fprintf(stderr, "%s: no export methods.\n", progname);
	exit(1);
    }

    logfile = stdout;
    while ((ch = getopt(argc, argv, "dD:e:f:hi:lm:V")) != -1) {
	switch (ch) {
	case 'd':
	    openlog(basename(progname), LOG_PID | LOG_PERROR, LOG_DAEMON);
	    daemonize = true;
	    break;
#ifdef CLIENTDEBUG_ENABLE
	case 'D':
	    debug = atoi(optarg);
	    gps_enable_debug(debug, logfile);
	    break;
#endif /* CLIENTDEBUG_ENABLE */
	case 'e':
	    method = export_lookup(optarg);
	    if (method == NULL) {
		(void)fprintf(stderr,
			      "%s: %s is not a known export method.\n",
			      progname, optarg);
		exit(1);
	    }
	    break;
       case 'f':       /* Output file name. */
            {
                char    fname[PATH_MAX];
                time_t  t;
                size_t  s;

                t = time(NULL);
                s = strftime(fname, sizeof(fname), optarg, localtime(&t));
                if (s == 0) {
                        syslog(LOG_ERR,
                            "Bad template \"%s\", logging to stdout.", optarg);
                        break;
                }
                logfile = fopen(fname, "w");
                if (logfile == NULL)
                        syslog(LOG_ERR,
                            "Failed to open %s: %s, logging to stdout.",
                            fname, strerror(errno));
                break;
            }
	case 'i':		/* set polling interfal */
	    timeout = (time_t) atoi(optarg);
	    if (timeout < 1)
		timeout = 1;
	    if (timeout >= 3600)
		fprintf(stderr,
			"WARNING: track timeout is an hour or more!\n");
	    break;
	case 'l':
	    export_list(stderr);
	    exit(0);
        case 'm':
	    minmove = (double )atoi(optarg);
	    break;
	case 'V':
	    (void)fprintf(stderr, "%s revision " REVISION "\n", progname);
	    exit(0);
	default:
	    usage();
	    /* NOTREACHED */
	}
    }

    if (daemonize && logfile == stdout) {
	syslog(LOG_ERR, "Daemon mode with no valid logfile name - exiting.");
	exit(1);
    }

    if (method != NULL)
	if (method->magic != NULL) {
	    source.server = (char *)method->magic;
	    source.port = NULL;
	}

    if (optind < argc) {
	gpsd_source_spec(argv[optind], &source);
    } else
	gpsd_source_spec(NULL, &source);
#if 0
    (void)fprintf(logfile,"<!-- server: %s port: %s  device: %s -->\n",
		 source.server, source.port, source.device);
#endif

    /* catch all interesting signals */
    (void)signal(SIGTERM, quit_handler);
    (void)signal(SIGQUIT, quit_handler);
    (void)signal(SIGINT, quit_handler);

    /*@-unrecog@*/
    /* might be time to daemonize */
    if (daemonize) {
	/* not SuS/POSIX portable, but we have our own fallback version */
	if (daemon(0, 0) != 0)
	    (void) fprintf(stderr,"demonization failed: %s\n", strerror(errno));
    }
    /*@+unrecog@*/

    //syslog (LOG_INFO, "---------- STARTED ----------");

    if (gps_open(source.server, source.port, &gpsdata) != 0) {
	(void)fprintf(stderr,
		      "%s: no gpsd running or network error: %d, %s\n",
		      progname, errno, gps_errstr(errno));
	exit(1);
    }

    if (source.device != NULL)
	flags |= WATCH_DEVICE;
    (void)gps_stream(&gpsdata, flags, source.device);

    print_gpx_header();
    (int)gps_mainloop(&gpsdata, 5000000, conditionally_log_fix);
    print_gpx_footer();
    (void)gps_close(&gpsdata);

    exit(0);
}
예제 #26
0
파일: lcdgps.c 프로젝트: elfchief/gpsd
int main(int argc, char *argv[])
{
    int option, rc;
    struct sockaddr_in localAddr, servAddr;
    struct hostent *h;

    int n;
    for(n=0;n<CLIMB;n++) climb[n]=0.0;

    switch (gpsd_units())
    {
    case imperial:
	altfactor = METERS_TO_FEET;
	altunits = "ft";
	speedfactor = MPS_TO_MPH;
	speedunits = "mph";
	break;
    case nautical:
	altfactor = METERS_TO_FEET;
	altunits = "ft";
	speedfactor = MPS_TO_KNOTS;
	speedunits = "knots";
	break;
    case metric:
	altfactor = 1;
	altunits = "m";
	speedfactor = MPS_TO_KPH;
	speedunits = "kph";
	break;
    default:
	/* leave the default alone */
	break;
    }

    /* Process the options.  Print help if requested. */
    while ((option = getopt(argc, argv, "Vhl:su:")) != -1) {
	switch (option) {
	case 'V':
	    (void)fprintf(stderr, "lcdgs revision " REVISION "\n");
	    exit(EXIT_SUCCESS);
	case 'h':
	default:
	    usage(argv[0]);
	    break;
	case 'l':
	    switch ( optarg[0] ) {
	    case 'd':
		deg_type = deg_dd;
		continue;
	    case 'm':
		deg_type = deg_ddmm;
		continue;
	    case 's':
		deg_type = deg_ddmmss;
		continue;
	    default:
		(void)fprintf(stderr, "Unknown -l argument: %s\n", optarg);
	    }
	    break;
	case 's':
	    sleep(10);
	    continue;
	case 'u':
	    switch ( optarg[0] ) {
	    case 'i':
		altfactor = METERS_TO_FEET;
		altunits = "ft";
		speedfactor = MPS_TO_MPH;
		speedunits = "mph";
		continue;
	    case 'n':
		altfactor = METERS_TO_FEET;
		altunits = "ft";
		speedfactor = MPS_TO_KNOTS;
		speedunits = "knots";
		continue;
	    case 'm':
		altfactor = 1;
		altunits = "m";
		speedfactor = MPS_TO_KPH;
		speedunits = "kph";
		continue;
	    default:
		(void)fprintf(stderr, "Unknown -u argument: %s\n", optarg);
	    }
	}
    }

    /* Grok the server, port, and device. */
  if (optind < argc) {
      gpsd_source_spec(argv[optind], &source);
  } else
      gpsd_source_spec(NULL, &source);

    /* Daemonize... */
  if (daemon(0, 0) != 0)
      (void)fprintf(stderr,
		    "lcdgps: demonization failed: %s\n",
		    strerror(errno));

    /* Open the stream to gpsd. */
    if (gps_open(source.server, source.port, &gpsdata) != 0) {
	(void)fprintf( stderr,
		       "lcdgps: no gpsd running or network error: %d, %s\n",
		       errno, gps_errstr(errno));
	exit(EXIT_FAILURE);
    }

    /* Connect to LCDd */
    h = gethostbyname(LCDDHOST);
    if (h==NULL) {
	printf("%s: unknown host '%s'\n",argv[0],LCDDHOST);
	exit(EXIT_FAILURE);
    }

    servAddr.sin_family = h->h_addrtype;
    memcpy((char *) &servAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
    servAddr.sin_port = htons(LCDDPORT);

    /* create socket */
    sd = socket(AF_INET, SOCK_STREAM, 0);
    if (BAD_SOCKET(sd)) {
	perror("cannot open socket ");
	exit(EXIT_FAILURE);
    }

    /* bind any port number */
    localAddr.sin_family = AF_INET;
    localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    localAddr.sin_port = htons(0);

    /* coverity[uninit_use_in_call] */
    rc = bind(sd, (struct sockaddr *) &localAddr, sizeof(localAddr));
    if (rc == -1) {
	printf("%s: cannot bind port TCP %u\n",argv[0],LCDDPORT);
	perror("error ");
	exit(EXIT_FAILURE);
    }

    /* connect to server */
    /* coverity[uninit_use_in_call] */
    rc = connect(sd, (struct sockaddr *) &servAddr, sizeof(servAddr));
    if (rc == -1) {
	perror("cannot connect ");
	exit(EXIT_FAILURE);
    }

    /* Do the initial field label setup. */
    reset_lcd();

    /* Here's where updates go. */
    unsigned int flags = WATCH_ENABLE;
    if (source.device != NULL)
	flags |= WATCH_DEVICE;
    (void)gps_stream(&gpsdata, flags, source.device);

    for (;;) { /* heart of the client */
	if (!gps_waiting(&gpsdata, 50000000)) {
	    fprintf( stderr, "lcdgps: error while waiting\n");
	    exit(EXIT_FAILURE);
	} else {
	    (void)gps_read(&gpsdata);
	    update_lcd(&gpsdata);
	}

    }
}
예제 #27
0
파일: argps.c 프로젝트: idaohang/argps
int main( int argc, char **argv )
{
	// Enforce proper command line arguments.
	if( argc != 2 )
	{
		fprintf( stderr, "Usage: %s <hostname>\n", argv[0] );
		exit( EXIT_FAILURE );
	}

	// Connect to remote host.
	int sockfd = createConnection( argv[1], PORT_NUMBER );
	if( sockfd < 0 )
	{
		fprintf( stderr, "Couldn't connect to %s.\n", argv[1] );
		exit( EXIT_FAILURE );
	}
	else
	{
		printf( "Connected to %s\n.", argv[0] );
	}

	// Connect to gpsd.
	if( gps_open( "localhost", DEFAULT_GPSD_PORT, &gpsData ) != 0 )
	{
		fprintf( stderr, "Couldn't connect to gpsd, errno = %d, %s.\n", errno, gps_errstr( errno ) );
		exit( EXIT_FAILURE );
	}
	else
	{
		printf( "Connected to gpsd.\n" );
	}

	// Register for updates from gpsd.
	gps_stream( &gpsData, WATCH_ENABLE | WATCH_JSON, NULL );

	printf( "Waiting for gps lock." );
	for(;;)
	{
		if( !gps_waiting( &gpsData, 5000000 ) )
		{
			fprintf( stderr, "GPS fix timed out.\n" );
			exit( EXIT_FAILURE );
		}
		else
		{
			if( gps_read( &gpsData ) == -1 )
			{
				fprintf( stderr, "gps_read() error, errno = %d\n", errno );
			}
			else
			{
				if( isnan( gpsData.fix.latitude ) || isnan( gpsData.fix.longitude ) )
				{
					fprintf( stderr, "Bad GPS fix.\n" );
				}
				else
				{
					printf( "Latitude: %f\n", gpsData.fix.latitude );
					printf( "Longitude: %f\n", gpsData.fix.longitude );
				}
			}
		}
	}

	close( sockfd );
	return 0;
}
예제 #28
0
int main(){

	int gps_recv;
	struct gps_data_t gps_data;
	struct timeval tv;
	struct tm *tm_info;
	FILE *gps_file_ptr;
	
	int millisec;
	
	char file_path[] = "/home/odroid/Canon_camera/Canon_gps_log.csv";
	
	/* Open GPS device (GPSD) */
	gps_recv = gps_open("localhost", "2947", &gps_data);
	
	if (gps_recv == -1) {
		printf("code: %d, reason %s\n", gps_recv, gps_errstr(gps_recv) );
	}
	
	/* Start streaming GPS data */
	gps_stream(&gps_data, WATCH_ENABLE, NULL);
	
	char lat_marker;
	char lng_marker;

	double latitude;
	double longitude;
	double latitude_min;
	double longitude_min;
	
	gps_file_ptr = fopen (file_path, "a");

	int i;
	for (i=1;i<=50;i++) {
	
		if (gps_waiting(&gps_data, GPS_WAIT)) {
			/* Then GPS data is available, so read the data */
			gps_recv = gps_read(&gps_data);
			/* printf("%d\n", gps_recv); */
			
			/* Check for error in reading data */
			if (gps_recv == -1) {
				printf("Error reading GPS. code: %d, reason %s\n", gps_recv, gps_errstr(gps_recv) );
			}
			
			else {
				/* No problems in reading data, check for GPS fix*/
	
				/* printf("No errors %d -- fix: %d\n", MODE_3D, gps_data.fix.mode); */
				
				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) ) {
					
					latitude = fabs(gps_data.fix.latitude);
					longitude = fabs(gps_data.fix.longitude);

					latitude_min = (latitude - (int) latitude)*60;
					longitude_min = (longitude - (int) longitude)*60;
	
					if (gps_data.fix.latitude >= 0 ) { lat_marker = 'N'; }
					else { lat_marker = 'S'; }
					
					if (gps_data.fix.longitude >= 0 ) { lng_marker = 'E'; }
					else { lng_marker = 'W'; }
					
					printf("%f %c, %f %c \n", fabs(gps_data.fix.latitude), lat_marker, fabs(gps_data.fix.longitude), lng_marker);
					
					/* Write timestamp in YYYY-MM-DD_HH-MM-SS-sss */
					gettimeofday(&tv, NULL);
					char time_buffer[26];
					millisec = (long) (tv.tv_usec/1000.0 + 0.5); // Round to nearest millisec
					
					tm_info = localtime(&tv.tv_sec);
					
					strftime(time_buffer, 26, "%Y-%m-%d_%H-%M-%S-", tm_info);
					
					fprintf(gps_file_ptr, "%s", time_buffer);
					fprintf(gps_file_ptr, "%03d,", millisec);
					
					/* Write latititude and longitude in DD-MM-SS.sss */
					fprintf(gps_file_ptr, "%d-%d-%f,%c,", (int) latitude, (int) latitude_min, (latitude_min - (int) latitude_min )*60, lat_marker);
					fprintf(gps_file_ptr, "%d-%d-%f,%c,", (int) longitude, (int) longitude_min, (longitude_min - (int) longitude_min )*60, lng_marker);
					/* Write Altitude, Heading */
					if (gps_data.fix.mode == MODE_3D) {
						fprintf(gps_file_ptr, "%f,%f\n", gps_data.fix.altitude, gps_data.fix.track);
					}
					else {
						/* if not 3D fix, altitude is not defined */
						fprintf(gps_file_ptr, "%d,%f\n", 0, gps_data.fix.track);
					}
					
					/* fprintf(gps_file_ptr, "%f%c,%f%c\n", fabs(gps_data.fix.latitude), lat_marker, fabs(gps_data.fix.longitude), lng_marker); */
						
				}
			}
		}
		else {
		  printf("-\n");
			/* printf("\n ----- Did not wait long enough ----- \n");*/
		}
	}
	
	/* Close logging file */
	fclose(gps_file_ptr);
	
	/* Stop streaming data and close GPS connection */
	gps_stream(&gps_data, WATCH_DISABLE, NULL);
	gps_close(&gps_data);
	
	printf("GPS -- %d\n", gps_recv);
	
	return 0;
}
예제 #29
0
int main(int argc, char *argv[])
{
	if (argc<0) {
		error(" hostname error\n");
	}

	int socket_fd, port_no, i,j,s;
	uint8_t arr[60];		//buffer to store payload
	memset(arr, 0, 60);
	uint8_t msgNum;	
	srand(time(NULL));
	msgNum=(uint8_t)(rand()%128);
	printf("The random value picked is %u\n",msgNum);
	struct timespec time1,start,stop,diff;
	int64_t t1,t2;
	
	struct BasicSafetyMessage *BSM_head = (struct BasicSafetyMessage *)arr;		//pointer to BSM
	printf("size of BSM is %lu\n", sizeof(struct BasicSafetyMessage));
	struct gps_data_t gpsdata;
	j = gps_open("localhost", "3333", &gpsdata); // can be any port number
	printf("open status is %d\n", j);
	(void)gps_stream(&gpsdata, WATCH_ENABLE | WATCH_JSON, NULL);
	printf("overall status is %d\n", gpsdata.status);

	socket_fd = socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL));	//ethernet header automatically constructed
	if (socket_fd < 0) {
		error("Error opening socket");
	}
	else
	{
		printf("opened socket\n");
	}

	//to determine interface number of the interface to be used
	struct ifreq ifr;
	size_t if_name_len = strlen("wlan0");
	if (if_name_len<sizeof(ifr.ifr_name)) {
		memcpy(ifr.ifr_name, "wlan0", if_name_len);
		ifr.ifr_name[if_name_len] = 0;
	}
	else {
		error("interface name is too long\n");
	}
	
	if (ioctl(socket_fd, SIOCGIFINDEX, &ifr) == -1) {
		error("error in ioctl block\n");
	}
	int ifindex = ifr.ifr_ifindex;	//store interface number in the variable 'ifindex'

	
	const unsigned char ether_broadcast_addr[] = { 0xff,0xff,0xff,0xff,0xff,0xff };	//destination address- broadcast address in this case
	struct sockaddr_ll addr = { 0 };
	addr.sll_family = AF_PACKET;
	addr.sll_ifindex = ifindex;
	addr.sll_halen = ETHER_ADDR_LEN;
	addr.sll_protocol = htons(ETH_P_ALL);
	memcpy(addr.sll_addr, ether_broadcast_addr, ETHER_ADDR_LEN);
	
	int broadcast = 1;
	if (setsockopt(socket_fd, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)) == -1) {	//setting the 'broadcast' option on socket
		error("Error in setting the socket option for broadcast");
	}
	else
	{
		printf("set option broadcast\n");
	}

	//fill structure of BSM
	getFixedData(&BSM_head);

	int tot_len = sizeof(struct BasicSafetyMessage);
	FILE *fp;
	fp = fopen("location.txt","a");
	fprintf(fp,"Timestamp(microsecs)  SeqNum  Latitude  Longitude \n");
	int c;
	for (c=0;c<1800;c++) //to keep broadcasting continuously
	{
		int num_bytes;
		if (gps_read(&gpsdata) == -1){
				printf("error inside read\n");
		}
		// If we have data, gpsdata.status becomes greater than 0
		else if(gpsdata.status > 0){
			getGpsSensorData(&BSM_head,&gpsdata,&msgNum);
		}

		getAnotherSensorData();
		
		clock_gettime(CLOCK_REALTIME, &time1);
		//timestamp in microseconds
		int64_t micros = time1.tv_sec * 1000000;
		// Adding full microseconds 
		micros += time1.tv_nsec/1000;
		// rounding up 
		if (time1.tv_nsec % 1000 >= 500) {
			++micros;
		}
		
		fprintf(fp,"\t");
		fprintf(fp,"%u",micros);
		fprintf(fp,"\t\t");
		fprintf(fp,"%u",BSM_head->blob1.msgCnt);
		fprintf(fp,"\t\t");
		fprintf(fp,"%lf",BSM_head->blob1.lat);
		fprintf(fp,"\t\t");
		fprintf(fp,"%lf",BSM_head->blob1.longi);
		fprintf(fp,"\n");
		
		
		if(c!=0){
			clock_gettime(CLOCK_REALTIME, &stop);			
			//timestamp in nanoseconds
			t2 = stop.tv_sec * 1000000000;
			// Adding full nanoseconds 
			t2 += stop.tv_nsec;
			printf("\n t2 is %u\n",t2);
			diff.tv_sec = 0;
			diff.tv_nsec = (100000000-(t2-t1));
			printf("difference is %u in secs and %u nanosecs\n",diff.tv_sec,diff.tv_nsec);
			nanosleep(&diff,NULL);
			printf("after sleep\n");
		}	
					
		num_bytes = sendto(socket_fd, BSM_head, tot_len, 0, (struct sockaddr*)&addr, sizeof(addr));//sendto() to broadcast the BSM packet
		
		clock_gettime(CLOCK_REALTIME, &start);
		//timestamp in nanoseconds
		t1 = start.tv_sec * 1000000000;
		// Adding full nanoseconds 
		t1 += start.tv_nsec;
		printf("\n t1 is %u\n",t1);
		if (num_bytes <0) {
			error("Error in sending the packet\n");
		}
		else
		{
			printf("Sent %d bytes\n", num_bytes);
		}
/*		
		printf("The contents of the buffer are:\n");
		for(s=0;s<num_bytes;s=s+2){
			printf("%02x %02x\n",arr[s+1],arr[s]);
		}
*/		
		//sleep(1);
	}
	fclose(fp);
	close(socket_fd);
	(void)gps_stream(&gpsdata, WATCH_DISABLE, NULL);
	(void)gps_close(&gpsdata);
	return 0;
}
예제 #30
0
파일: gpspipe.c 프로젝트: elfchief/gpsd
int main(int argc, char **argv)
{
    char buf[4096];
    bool timestamp = false;
    char *format = "%F %T";
    char tmstr[200];
    bool daemonize = false;
    bool binary = false;
    bool sleepy = false;
    bool new_line = true;
    bool raw = false;
    bool watch = false;
    bool profile = false;
    int option_u = 0;                   // option to show uSeconds
    long count = -1;
    int option;
    unsigned int vflag = 0, l = 0;
    FILE *fp;
    unsigned int flags;
    fd_set fds;

    struct fixsource_t source;
    char *serialport = NULL;
    char *outfile = NULL;

    flags = WATCH_ENABLE;
    while ((option = getopt(argc, argv, "?dD:lhrRwStT:vVn:s:o:pPu2")) != -1) {
	switch (option) {
	case 'D':
	    debug = atoi(optarg);
#ifdef CLIENTDEBUG_ENABLE
	    gps_enable_debug(debug, stderr);
#endif /* CLIENTDEBUG_ENABLE */
	    break;
	case 'n':
	    count = strtol(optarg, 0, 0);
	    break;
	case 'r':
	    raw = true;
	    /*
	     * Yes, -r invokes NMEA mode rather than proper raw mode.
	     * This emulates the behavior under the old protocol.
	     */
	    flags |= WATCH_NMEA;
	    break;
	case 'R':
	    flags |= WATCH_RAW;
	    binary = true;
	    break;
	case 'd':
	    daemonize = true;
	    break;
	case 'l':
	    sleepy = true;
	    break;
	case 't':
	    timestamp = true;
	    break;
	case 'T':
	    timestamp = true;
	    format = optarg;
	    break;
	case 'u':
	    timestamp = true;
	    option_u++;
	    break;
	case 'v':
	    vflag++;
	    break;
	case 'w':
	    flags |= WATCH_JSON;
	    watch = true;
	    break;
	case 'S':
	    flags |= WATCH_SCALED;
	    break;
	case 'p':
	    profile = true;
	    break;
	case 'P':
	    flags |= WATCH_PPS;
	    break;
	case 'V':
	    (void)fprintf(stderr, "%s: %s (revision %s)\n",
			  argv[0], VERSION, REVISION);
	    exit(EXIT_SUCCESS);
	case 's':
	    serialport = optarg;
	    break;
	case 'o':
	    outfile = optarg;
	    break;
	case '2':
	    flags |= WATCH_SPLIT24;
	    break;
	case '?':
	case 'h':
	default:
	    usage();
	    exit(EXIT_FAILURE);
	}
    }

    /* Grok the server, port, and device. */
    if (optind < argc) {
	gpsd_source_spec(argv[optind], &source);
    } else
	gpsd_source_spec(NULL, &source);

    if (serialport != NULL && !raw) {
	(void)fprintf(stderr, "gpspipe: use of '-s' requires '-r'.\n");
	exit(EXIT_FAILURE);
    }

    if (outfile == NULL && daemonize) {
	(void)fprintf(stderr, "gpspipe: use of '-d' requires '-o'.\n");
	exit(EXIT_FAILURE);
    }

    if (!raw && !watch && !binary) {
	(void)fprintf(stderr,
		      "gpspipe: one of '-R', '-r', or '-w' is required.\n");
	exit(EXIT_FAILURE);
    }

    /* Daemonize if the user requested it. */
    if (daemonize)
	if (daemon(0, 0) != 0)
	    (void)fprintf(stderr,
			  "gpspipe: demonization failed: %s\n",
			  strerror(errno));

    /* Sleep for ten seconds if the user requested it. */
    if (sleepy)
	(void)sleep(10);

    /* Open the output file if the user requested it.  If the user
     * requested '-R', we use the 'b' flag in fopen() to "do the right
     * thing" in non-linux/unix OSes. */
    if (outfile == NULL) {
	fp = stdout;
    } else {
	if (binary)
	    fp = fopen(outfile, "wb");
	else
	    fp = fopen(outfile, "w");

	if (fp == NULL) {
	    (void)fprintf(stderr,
			  "gpspipe: unable to open output file:  %s\n",
			  outfile);
	    exit(EXIT_FAILURE);
	}
    }

    /* Open the serial port and set it up. */
    if (serialport)
	open_serial(serialport);

    if (gps_open(source.server, source.port, &gpsdata) != 0) {
	(void)fprintf(stderr,
		      "gpspipe: could not connect to gpsd %s:%s, %s(%d)\n",
		      source.server, source.port, gps_errstr(errno), errno);
	exit(EXIT_FAILURE);
    }

    if (profile)
	flags |= WATCH_TIMING;
    if (source.device != NULL)
	flags |= WATCH_DEVICE;
    (void)gps_stream(&gpsdata, flags, source.device);

    if ((isatty(STDERR_FILENO) == 0) || daemonize)
	vflag = 0;

    for (;;) {
	int r = 0;
	struct timeval tv;

	tv.tv_sec = 0;
	tv.tv_usec = 100000;
	FD_ZERO(&fds);
	FD_SET(gpsdata.gps_fd, &fds);
	errno = 0;
	r = select(gpsdata.gps_fd+1, &fds, NULL, NULL, &tv);
	if (r == -1 && errno != EINTR) {
	    (void)fprintf(stderr, "gpspipe: select error %s(%d)\n",
			  strerror(errno), errno);
	    exit(EXIT_FAILURE);
	} else if (r == 0)
		continue;

	if (vflag)
	    spinner(vflag, l++);

	/* reading directly from the socket avoids decode overhead */
	errno = 0;
	r = (int)read(gpsdata.gps_fd, buf, sizeof(buf));
	if (r > 0) {
	    int i = 0;
	    int j = 0;
	    for (i = 0; i < r; i++) {
		char c = buf[i];
		if (j < (int)(sizeof(serbuf) - 1)) {
		    serbuf[j++] = buf[i];
		}
		if (new_line && timestamp) {
		    char tmstr_u[20];            // time with "usec" resolution
		    struct timespec now;
		    struct tm *tmp_now;

		    (void)clock_gettime(CLOCK_REALTIME, &now);
		    tmp_now = localtime((time_t *)&(now.tv_sec));
		    (void)strftime(tmstr, sizeof(tmstr), format, tmp_now);
		    new_line = 0;

		    switch( option_u ) {
		    case 2:
			(void)snprintf(tmstr_u, sizeof(tmstr_u),
				       " %ld.%06ld",
				       (long)now.tv_sec,
				       (long)now.tv_nsec/1000);
			break;
		    case 1:
			(void)snprintf(tmstr_u, sizeof(tmstr_u),
				       ".%06ld", (long)now.tv_nsec/1000);
			break;
		    default:
			*tmstr_u = '\0';
			break;
		    }

		    if (fprintf(fp, "%.24s%s: ", tmstr, tmstr_u) <= 0) {
			(void)fprintf(stderr,
				      "gpspipe: write error, %s(%d)\n",
				      strerror(errno), errno);
			exit(EXIT_FAILURE);
		    }
		}
		if (fputc(c, fp) == EOF) {
		    fprintf(stderr, "gpspipe: write error, %s(%d)\n",
			    strerror(errno), errno);
		    exit(EXIT_FAILURE);
		}

		if (c == '\n') {
		    if (serialport != NULL) {
			if (write(fd_out, serbuf, (size_t) j) == -1) {
			    fprintf(stderr,
				    "gpspipe: serial port write error, %s(%d)\n",
				    strerror(errno), errno);
			    exit(EXIT_FAILURE);
			}
			j = 0;
		    }

		    new_line = true;
		    /* flush after every good line */
		    if (fflush(fp)) {
			(void)fprintf(stderr,
				      "gpspipe: fflush error, %s(%d)\n",
				      strerror(errno), errno);
			exit(EXIT_FAILURE);
		    }
		    if (count > 0) {
			if (0 >= --count) {
			    /* completed count */
			    exit(EXIT_SUCCESS);
			}
		    }
		}
	    }
	} else {
	    if (r == -1) {
		if (errno == EAGAIN)
		    continue;
		else
		    (void)fprintf(stderr, "gpspipe: read error %s(%d)\n",
			      strerror(errno), errno);
		exit(EXIT_FAILURE);
	    } else {
		exit(EXIT_SUCCESS);
	    }
	}
    }

#ifdef __UNUSED__
    if (serialport != NULL) {
	/* Restore the old serial port settings. */
	if (tcsetattr(fd_out, TCSANOW, &oldtio) != 0) {
	    (void)fprintf(stderr, "gpsipe: error restoring serial port settings\n");
	    exit(EXIT_FAILURE);
	}
    }
#endif /* __UNUSED__ */

    exit(EXIT_SUCCESS);
}