Exemple #1
0
/** \brief Shutdown and free structures inside the qth_t stucture were used for 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.
 */
void qth_data_update_stop(qth_t * qth)
{
    switch (qth->type)
    {
    case QTH_STATIC_TYPE:
        /* nothing to do.  the data never updates */
        break;
    case QTH_GPSD_TYPE:

        /* close gpsd socket */
        if (qth->gps_data != NULL)
        {
#ifdef HAS_LIBGPS
            switch (GPSD_API_MAJOR_VERSION)
            {
            case 4:
                gps_close(qth->gps_data);
                break;
            case 5:
                gps_close(qth->gps_data);
                break;
            default:
                break;
            }
#endif
            qth->gps_data = NULL;
        }

        break;
    default:
        break;
    }
}
Exemple #2
0
gpsmm::~gpsmm()
{
    if ( to_user != NULL ) {
	gps_close(gps_state());
	delete to_user;
    }
}
Exemple #3
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;
}
Exemple #4
0
/*@-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;
}
Exemple #5
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;
}
int stopLocationServices()
{
 if (!working) { return 0; }
 gps_close(&gpsdata);
 working=0;
return 1;
}
Exemple #7
0
static void callback(struct gps_data_t *gpsdata)
{
	struct timeval tv;
	time_t time;
	int rc;

	if (!(gpsdata->set & TIME_SET))
		return;

	tv.tv_sec = gpsdata->fix.time;
	/* FIXME: use the fractional part for microseconds */
	tv.tv_usec = 0;

	time = tv.tv_sec;

	rc = settimeofday(&tv, NULL);
	gps_close(gpsdata);
	if (rc == 0) {
		syslog(LOG_NOTICE, "Successfully set RTC time to GPSD time:"
			" %s", ctime(&time));
		closelog();
		exit(EXIT_SUCCESS);
	} else {
		syslog(LOG_ERR, "Error setting RTC: %d (%s)\n",
			errno, strerror(errno));
		closelog();
		exit(EXIT_FAILURE);
	}
}
Exemple #8
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;
}
Exemple #9
0
void free_gps()
{
  if (gpsdata)
    {
      gps_del_callback(gpsdata, &handler);
      gps_close(gpsdata);
    }
}
Exemple #10
0
static void gpsd_read_gpsd(struct globals *globals)
{
	ssize_t ret;
	size_t cnt;
	bool eol = false;
	char buf[4096];
	const size_t tpv_size = sizeof(globals->buf) -
				sizeof(*globals->push) -
				sizeof(struct alfred_data) -
				sizeof(*globals->gpsd_data);

	cnt = 0;
	do {
		ret = read(globals->gpsdata.gps_fd, &buf[cnt], 1);
		if (ret != 1) {
			gps_close(&globals->gpsdata);
			globals->gpsdata.gps_fd = -1;
			return;
		}

		switch (buf[cnt]) {
		case '\r':
			cnt--;
			break;
		case '\n':
			eol = true;
			buf[cnt] = '\0';
			break;
		}
	} while (cnt++ < sizeof(buf) - 1 && !eol);

	if (!eol) {
		gps_close(&globals->gpsdata);
		globals->gpsdata.gps_fd = -1;
		return;
	}

#define STARTSWITH(str, prefix)	strncmp(str, prefix, sizeof(prefix)-1)==0
	if (STARTSWITH(buf, "{\"class\":\"TPV\"")) {
		strncpy(globals->gpsd_data->tpv, buf, tpv_size);
		globals->gpsd_data->tpv[tpv_size - 1] = '\0';

		globals->gpsd_data->tpv_len =
			htonl(strlen(globals->gpsd_data->tpv) + 1);
	}
}
Exemple #11
0
static void quit_handler(int signum)
{
    /* don't clutter the logs on Ctrl-C */
    if (signum != SIGINT)
	syslog(LOG_INFO, "exiting, signal %d received", signum);
    print_gpx_footer();
    (void)gps_close(&gpsdata);
    exit(0);
}
Exemple #12
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);
}
Exemple #13
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);
        }
    }
Exemple #14
0
static void
handle_input(XtPointer client_data, int *source, XtInputId *id)
{
	if (gps_poll(gpsdata) < 0) {
		XtRemoveInput(gps_input);
		(void)gps_close(gpsdata);
		XtRemoveTimeOut(timeout);
		XmTextFieldSetString(text_10, "No GPS data available");
		(void)err_dialog(toplevel, "No GPS data available.\n\n"
		    "Check the connection to gpsd and if gpsd is running");
		gps_lost = true;
		gps_timeout = XtAppAddTimeOut(app, 3000, handle_gps, app);
	}
}
Exemple #15
0
/**
 * Shutdown and free structures inside the qth_t stucture were used for 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.
 */
void qth_data_update_stop(qth_t * qth)
{
    if (qth->type != QTH_GPSD_TYPE)
        return;

    /* close gpsd socket */
    if (qth->gps_data != NULL)
    {
#ifdef HAS_LIBGPS
        switch (GPSD_API_MAJOR_VERSION)
        {
        case 4:
            gps_close(qth->gps_data);
            break;
        case 5:
            gps_close(qth->gps_data);
            break;
        default:
            break;
        }
#endif
        qth->gps_data = NULL;
    }
}
Exemple #16
0
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;
}
Exemple #17
0
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 */
Exemple #18
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;
}
Exemple #19
0
static void
gpsd_close(struct gpsd_priv *priv)
{
	GError *error = NULL;

	if (priv->watch) {
		g_source_remove(priv->watch);
		priv->watch = 0;
	}
	if (priv->iochan) {
		g_io_channel_shutdown(priv->iochan, 0, &error);
		priv->iochan = NULL;
	}
	if (priv->gps) {
		gps_close(priv->gps);
		priv->gps = NULL;
	}
	if (priv->timeout) {
		g_source_destroy(priv->timeout);
		priv->timeout = NULL;
	}
}
Exemple #20
0
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);
}
Exemple #21
0
/*@-mustfreefresh -compdestroy@*/
static int shm_mainloop(void)
{
    int status;
    if ((status = gps_open(GPSD_SHARED_MEMORY, NULL, &gpsdata)) != 0) {
	(void)fprintf(stderr,
		      "%s: shm open failed with status %d.\n",
		      progname, status);
	return 1;
    }

    print_gpx_header();
    for (;;) {
	status = gps_read(&gpsdata);

	if (status == -1)
	    break;
	if (status > 0)
	    conditionally_log_fix(&gpsdata);
    }
    (void)gps_close(&gpsdata);
    return 0;
}
Exemple #22
0
/* Function to call when we're all done.  Does a bit of clean-up. */
static void die(int sig)
{
    if (!isendwin())
    {
	/* Move the cursor to the bottom left corner. */
	(void)mvcur(0, COLS - 1, LINES - 1, 0);

	/* Put input attributes back the way they were. */
	(void)echo();

	/* Done with curses. */
	(void)endwin();
    }

    /* We're done talking to gpsd. */
    (void)gps_close(&gpsdata);

    switch (sig) {
    case CGPS_QUIT:
	break;
    case GPS_GONE:
	(void)fprintf(stderr, "cgps: GPS hung up.\n");
	break;
    case GPS_ERROR:
	(void)fprintf(stderr, "cgps: GPS read returned error\n");
	break;
    case GPS_TIMEOUT:
	(void)fprintf(stderr, "cgps: GPS timeout\n");
	break;
    default:
	(void)fprintf(stderr, "cgps: caught signal %d\n", sig);
	break;
    }

    /* Bye! */
    exit(EXIT_SUCCESS);
}
Exemple #23
0
int main(int argc, char **argv)
{
	char *host = "localhost";
	char *port = DEFAULT_GPSD_PORT;
	int num_retries = NUM_RETRIES;
	int retry_sleep = RETRY_SLEEP;
	int i, rc;
	enum state state;

	openlog("gps-wd", LOG_PERROR, LOG_CRON);

	while (1) {
		int option_index = 0, c;
		static struct option long_options[] = {
			{"num-retries", 1, 0, 'n'},
			{"retry-sleep", 1, 0, 's'},
			{"no-detach", 0, 0, 'd'},
			{"timeout", 1, 0, 't'},
			{"service-name", 1, 0, 'r'},
			{0,0,0,0}
		};

		c = getopt_long(argc, argv, "n:s:dt:r:",
				long_options, &option_index);
		if (c == -1)
			break;

		switch (c) {
		case 'n':
			num_retries = atoi(optarg);
			break;
		case 's':
			retry_sleep = atoi(optarg);
			break;
		case 'd':
			no_detach = 1;
			break;
		case 't':
			timeout = atoi(optarg);
			break;
		case 'r':
			service_name = optarg;
			break;
		}
	}

	if (optind < argc)
		host = argv[optind++];
	if (optind < argc)
		port = argv[optind++];

	syslog(LOG_INFO, "starting gps-wd for %s:%s (timeout %ds, service %s)",
		host, port, timeout, service_name);

	/* attempt up to NUM_RETRIES times to connect to gpsd while we are
	 * still running in foreground.  The idea is that we will block the
	 * boot process (init scripts) until we have a connection */
	for (i = 1; i <= num_retries; i++) {
		printf("Attempt #%d to connect to gpsd at %s...\n", i, host);
		rc = attempt_reconnect(host, port, &gpsdata);
		if (rc >= 0)
			break;
		sleep(retry_sleep);
	}

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

	if (!no_detach)
		osmo_daemonize();

	signal(SIGALRM, alarm_hdlr);

	/* 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) {
		switch (state) {
		case S_CONNECTED:
			alarm(timeout);
			rc = my_gps_mainloop(&gpsdata, INT_MAX, callback);
			if (rc < 1) {
				syslog(LOG_ERR, "connection to gpsd was "
					"closed: %d, reconnecting\n", rc);
				gps_close(&gpsdata);
				alarm(0);
				state = S_RECONNECT;
			}
			break;
		case S_RECONNECT:
			rc = attempt_reconnect(host, port, &gpsdata);
			if (rc < 0)
				sleep(RETRY_SLEEP);
			else
				state = S_CONNECTED;
			break;
		}
	}

	gps_close(&gpsdata);

	closelog();
	exit(EXIT_SUCCESS);
}
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;
}
Exemple #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);
}
Exemple #26
0
int main(int argc, char *argv[])
{
    struct gps_data_t collect;
    char buf[BUFSIZ];
    int option;
    bool batchmode = false;
    int debug = 0;

    (void)signal(SIGSEGV, onsig);
    (void)signal(SIGBUS, onsig);

    while ((option = getopt(argc, argv, "bhsD:?")) != -1) {
	switch (option) {
	case 'b':
	    batchmode = true;
	    break;
	case 's':
	    (void)
		printf
		("Sizes: fix=%zd gpsdata=%zd rtcm2=%zd rtcm3=%zd ais=%zd compass=%zd raw=%zd devices=%zd policy=%zd version=%zd, noise=%zd\n",
		 sizeof(struct gps_fix_t),
		 sizeof(struct gps_data_t), sizeof(struct rtcm2_t),
		 sizeof(struct rtcm3_t), sizeof(struct ais_t),
		 sizeof(struct attitude_t), sizeof(struct rawdata_t),
		 sizeof(collect.devices), sizeof(struct policy_t),
		 sizeof(struct version_t), sizeof(struct gst_t));
	    exit(EXIT_SUCCESS);
	case 'D':
	    debug = atoi(optarg);
	    break;
	case '?':
	case 'h':
	default:
	    (void)fputs("usage: test_libgps [-b] [-D lvl] [-s]\n", stderr);
	    exit(EXIT_FAILURE);
	}
    }

    gps_enable_debug(debug, stdout);
    if (batchmode) {
	while (fgets(buf, sizeof(buf), stdin) != NULL) {
	    if (buf[0] == '{' || isalpha(buf[0])) {
		gps_unpack(buf, &gpsdata);
		libgps_dump_state(&gpsdata);
	    }
	}
    } else if (gps_open(NULL, 0, &collect) <= 0) {
	(void)fputs("Daemon is not running.\n", stdout);
	exit(EXIT_FAILURE);
    } else if (optind < argc) {
	(void)strlcpy(buf, argv[optind], BUFSIZ);
	(void)strlcat(buf, "\n", BUFSIZ);
	(void)gps_send(&collect, buf);
	(void)gps_read(&collect);
	libgps_dump_state(&collect);
	(void)gps_close(&collect);
    } else {
	int tty = isatty(0);

	if (tty)
	    (void)fputs("This is the gpsd exerciser.\n", stdout);
	for (;;) {
	    if (tty)
		(void)fputs("> ", stdout);
	    if (fgets(buf, sizeof(buf), stdin) == NULL) {
		if (tty)
		    putchar('\n');
		break;
	    }
	    collect.set = 0;
	    (void)gps_send(&collect, buf);
	    (void)gps_read(&collect);
	    libgps_dump_state(&collect);
	}
	(void)gps_close(&collect);
    }

    return 0;
}
Exemple #27
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;
}
Exemple #28
0
int main(int argc, char *argv[])
{
    struct gps_data_t collect;
    struct fixsource_t source;
    char buf[BUFSIZ];
    int option;
    bool batchmode = false;
    bool forwardmode = false;
    char *fmsg = NULL;
#ifdef CLIENTDEBUG_ENABLE
    int debug = 0;
#endif

    (void)signal(SIGSEGV, onsig);
    (void)signal(SIGBUS, onsig);

    while ((option = getopt(argc, argv, "bf:hsD:?")) != -1) {
	switch (option) {
	case 'b':
	    batchmode = true;
	    break;
	case 'f':
	    forwardmode = true;
	    fmsg = optarg;
	    break;
	case 's':
	    (void)
		printf
		("Sizes: fix=%zd gpsdata=%zd rtcm2=%zd rtcm3=%zd ais=%zd compass=%zd raw=%zd devices=%zd policy=%zd version=%zd, noise=%zd\n",
		 sizeof(struct gps_fix_t),
		 sizeof(struct gps_data_t), sizeof(struct rtcm2_t),
		 sizeof(struct rtcm3_t), sizeof(struct ais_t),
		 sizeof(struct attitude_t), sizeof(struct rawdata_t),
		 sizeof(collect.devices), sizeof(struct policy_t),
		 sizeof(struct version_t), sizeof(struct gst_t));
	    exit(EXIT_SUCCESS);
#ifdef CLIENTDEBUG_ENABLE
	case 'D':
	    debug = atoi(optarg);
	    break;
#endif
	case '?':
	case 'h':
	default:
	    (void)fputs("usage: test_libgps [-b] [-f fwdmsg] [-D lvl] [-s] [server[:port:[device]]]\n", stderr);
	    exit(EXIT_FAILURE);
	}
    }

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

#ifdef CLIENTDEBUG_ENABLE
    gps_enable_debug(debug, stdout);
#endif
    if (batchmode) {
#ifdef SOCKET_EXPORT_ENABLE
	while (fgets(buf, sizeof(buf), stdin) != NULL) {
	    if (buf[0] == '{' || isalpha(buf[0])) {
		gps_unpack(buf, &gpsdata);
		libgps_dump_state(&gpsdata);
	    }
	}
#endif
    } else if (gps_open(source.server, source.port, &collect) != 0) {
	(void)fprintf(stderr,
		      "test_libgps: no gpsd running or network error: %d, %s\n",
		      errno, gps_errstr(errno));
	exit(EXIT_FAILURE);
    } else if (forwardmode) {
	(void)gps_send(&collect, fmsg);
	(void)gps_read(&collect);
#ifdef SOCKET_EXPORT_ENABLE
	libgps_dump_state(&collect);
#endif
	(void)gps_close(&collect);
    } else {
	int tty = isatty(0);

	if (tty)
	    (void)fputs("This is the gpsd exerciser.\n", stdout);
	for (;;) {
	    if (tty)
		(void)fputs("> ", stdout);
	    if (fgets(buf, sizeof(buf), stdin) == NULL) {
		if (tty)
		    putchar('\n');
		break;
	    }
	    collect.set = 0;
	    (void)gps_send(&collect, buf);
	    (void)gps_read(&collect);
#ifdef SOCKET_EXPORT_ENABLE
	    libgps_dump_state(&collect);
#endif
	}
	(void)gps_close(&collect);
    }

    return 0;
}
int main(int argc, char **argv)
{
    int option, status;
    char *device = NULL, *devtype = NULL; 
    char *speed = NULL, *control = NULL, *rate = NULL;
    bool to_binary = false, to_nmea = false, reset = false; 
    bool lowlevel=false, echo=false;
    struct gps_data_t gpsdata;
    const struct gps_type_t *forcetype = NULL;
    const struct gps_type_t **dp;
    unsigned int timeout = 4;
#ifdef ALLOW_CONTROLSEND
    char cooked[BUFSIZ];
    ssize_t cooklen = 0;
#endif /* ALLOW_RECONFIGURE */

#define USAGE	"usage: gpsctl [-l] [-b | -n | -r] [-D n] [-s speed] [-c rate] [-T timeout] [-V] [-t devtype] [-x control] [-e] <device>\n"
    while ((option = getopt(argc, argv, "bec:fhlnrs:t:x:D:T:V")) != -1) {
	switch (option) {
	case 'b':		/* switch to vendor binary mode */
	    to_binary = true;
	    break;
	case 'c':
#ifdef ALLOW_RECONFIGURE
	    rate = optarg;
#else
	    gpsd_report(LOG_ERROR, "cycle-change capability has been conditioned out.\n");
#endif /* ALLOW_RECONFIGURE */
	    break;
	case 'x':		/* ship specified control string */
#ifdef ALLOW_CONTROLSEND
	    control = optarg;
	    lowlevel = true;
	    if ((cooklen = hex_escapes(cooked, control)) <= 0) {
		gpsd_report(LOG_ERROR, 
			    "invalid escape string (error %d)\n", (int)cooklen);
		exit(1);
	    }
#else
	    gpsd_report(LOG_ERROR, "control_send capability has been conditioned out.\n");	    
#endif /* ALLOW_CONTROLSEND */
	    break;
	case 'e':		/* echo specified control string with wrapper */
	    lowlevel = true;
	    echo = true;
	    break;
	case 'f':		/* force direct access to the device */
	    lowlevel = true;
	    break;
        case 'l':		/* list known device types */
	    for (dp = gpsd_drivers; *dp; dp++) {
#ifdef ALLOW_RECONFIGURE
		if ((*dp)->mode_switcher != NULL)
		    (void)fputs("-[bn]\t", stdout);
		else
		    (void)fputc('\t', stdout);
		if ((*dp)->speed_switcher != NULL)
		    (void)fputs("-s\t", stdout);
		else
		    (void)fputc('\t', stdout);
		if ((*dp)->rate_switcher != NULL)
		    (void)fputs("-c\t", stdout);
		else
		    (void)fputc('\t', stdout);
#endif /* ALLOW_RECONFIGURE */
#ifdef ALLOW_CONTROLSEND
		if ((*dp)->control_send != NULL)
		    (void)fputs("-x\t", stdout);
		else
		    (void)fputc('\t', stdout);
#endif /* ALLOW_CONTROLSEND */
		(void)puts((*dp)->type_name);
	    }
	    exit(0);
	case 'n':		/* switch to NMEA mode */
#ifdef ALLOW_RECONFIGURE
	    to_nmea = true;
#else
	    gpsd_report(LOG_ERROR, "speed-change capability has been conditioned out.\n");
#endif /* ALLOW_RECONFIGURE */
	    break;
	case 'r':		/* force-switch to default mode */
#ifdef ALLOW_RECONFIGURE
	    reset = true;
	    lowlevel = false;	/* so we'll abort if the daemon is running */
#else
	    gpsd_report(LOG_ERROR, "reset capability has been conditioned out.\n");
#endif /* ALLOW_RECONFIGURE */
	    break;
	case 's':		/* change output baud rate */
#ifdef ALLOW_RECONFIGURE
	    speed = optarg;
#else
	    gpsd_report(LOG_ERROR, "speed-change capability has been conditioned out.\n");
#endif /* ALLOW_RECONFIGURE */
	    break;
	case 't':		/* force the device type */
	    devtype = optarg;
	    break;
	case 'T':		/* set the timeout on packet recognition */
	    timeout = (unsigned)atoi(optarg);
	    break;
	case 'D':		/* set debugging level */
	    debuglevel = atoi(optarg);
	    gpsd_hexdump_level = debuglevel;
#ifdef CLIENTDEBUG_ENABLE
	    gps_enable_debug(debuglevel, stderr);
#endif /* CLIENTDEBUG_ENABLE */
	    break;
	case 'V':
	    (void)fprintf(stderr, "gpsctl: version %s (revision %s)\n",
			  VERSION, REVISION);
	    break;
	case 'h':
	default:
	    fprintf(stderr, USAGE);
	    break;
	}
    }

    if (optind < argc)
	device = argv[optind];

    if (devtype != NULL) {
	int matchcount = 0;
	for (dp = gpsd_drivers; *dp; dp++) {
	    if (strstr((*dp)->type_name, devtype) != NULL) {
		forcetype = *dp;
		matchcount++;
	    }
	}
	if (matchcount == 0)
	    gpsd_report(LOG_ERROR, "no driver type name matches '%s'.\n", devtype);
	else if (matchcount == 1) {
	    assert(forcetype != NULL);
	    gpsd_report(LOG_PROG, "%s driver selected.\n", forcetype->type_name);
	} else {
	    forcetype = NULL;
	    gpsd_report(LOG_ERROR, "%d driver type names match '%s'.\n",
			matchcount, devtype);
	}
    }    

    if ((int)to_nmea + (int)to_binary + (int)reset > 1) {
	gpsd_report(LOG_ERROR, "make up your mind, would you?\n");
	exit(0);
    }

    (void) signal(SIGINT, onsig);
    (void) signal(SIGTERM, onsig);
    (void) signal(SIGQUIT, onsig);

    /*@-nullpass@*/ /* someday, add null annotation to the gpsopen_r() params */
    if (!lowlevel) {
	/* Try to open the stream to gpsd. */
	if (gps_open_r(NULL, NULL, &gpsdata) != 0) {
	    gpsd_report(LOG_ERROR, "no gpsd running or network error: %s.\n", 
			netlib_errstr(errno));
	    lowlevel = true;
	}
    }
    /*@-nullpass@*/

    /* ^ someday, add out annotation to the gpspoll() param  and remove */
    if (!lowlevel) {
	/* OK, there's a daemon instance running.  Do things the easy way */
	struct devconfig_t *devlistp;
	(void)gps_read(&gpsdata);
	if ((gpsdata.set & DEVICELIST_SET) != 0) {
	    gpsd_report(LOG_ERROR, "no VERSION response received; update your gpsd.\n"); 
	    (void)gps_close(&gpsdata);
	    exit(1);
	}
	(void)gps_query(&gpsdata, "?DEVICES;\n");
	if ((gpsdata.set & DEVICELIST_SET) == 0) {
	    gpsd_report(LOG_ERROR, "no DEVICES response received.\n"); 
	    (void)gps_close(&gpsdata);
	    exit(1);
	}

	if (gpsdata.devices.ndevices == 0) {
	    gpsd_report(LOG_ERROR, "no devices connected.\n"); 
	    (void)gps_close(&gpsdata);
	    exit(1);
	} else if (gpsdata.devices.ndevices > 1 && device == NULL) {
	    gpsd_report(LOG_ERROR, 
			"multiple devices and no device specified.\n");
	    (void)gps_close(&gpsdata);
	    exit(1);
	}
	gpsd_report(LOG_PROG,"%d device(s) found.\n",gpsdata.devices.ndevices);

	if (gpsdata.devices.ndevices == 1) {
	    devlistp = &gpsdata.devices.list[0];
	    device = devlistp->path;
	} else {
	    int i;
	    assert(device != NULL);
	    for (i = 0; i < gpsdata.devices.ndevices; i++)
		if (strcmp(device, gpsdata.devices.list[i].path) == 0)
		    goto foundit;
	    gpsd_report(LOG_ERROR, "specified device not found.\n");
	    (void)gps_close(&gpsdata);
	    exit(1);
	foundit:
	    devlistp = &gpsdata.devices.list[i];
	}

	/* if no control operation was specified, just ID the device */
	if (speed==NULL && rate == NULL && !to_nmea && !to_binary && !reset) {
	    gpsd_report(LOG_SHOUT, "%s identified as %s at %d\n",
			devlistp->path, devlistp->driver, devlistp->baudrate);
	    exit(0);
	}

	status = 0;
#ifdef ALLOW_RECONFIGURE
	if (reset)
	{
	    gpsd_report(LOG_PROG, "cannot reset with gpsd running.\n");
	    exit(0);
	}

	/*@-boolops@*/
	if (to_nmea) {
	    (void)gps_query(&gpsdata, "?DEVICE={\"path\":\"%s\",\"native\":0}\r\n", device); 
	    if ((gpsdata.set & ERROR_SET) || (gpsdata.dev.driver_mode != MODE_NMEA)) {
		gpsd_report(LOG_ERROR, "%s mode change to NMEA failed\n", gpsdata.dev.path);
		status = 1;
	    } else
		gpsd_report(LOG_PROG, "%s mode change succeeded\n", gpsdata.dev.path);
	}
	else if (to_binary) {
	    (void)gps_query(&gpsdata, "?DEVICE={\"path\":\"%s\",\"native\":1}\r\n", device);
	    if ((gpsdata.set & ERROR_SET) || (gpsdata.dev.driver_mode != MODE_BINARY)) {
		gpsd_report(LOG_ERROR, "%s mode change to native mode failed\n", gpsdata.dev.path);
		status = 1;
	    } else
		gpsd_report(LOG_PROG, "%s mode change succeeded\n", gpsdata.dev.path);
	}
	/*@+boolops@*/
	if (speed != NULL) {
	    char parity = 'N';
	    char stopbits = '1';
	    if (strchr(speed, ':') == NULL)
		(void)gps_query(&gpsdata,
				"?DEVICE={\"path\":\"%s\",\"bps\":%s}\r\n", 
				device, speed);
	    else {
		char *modespec = strchr(speed, ':');
		/*@ +charint @*/
		status = 0;
		if (modespec!=NULL) {
		    *modespec = '\0';
		    if (strchr("78", *++modespec) == NULL) {
			gpsd_report(LOG_ERROR, "No support for that word lengths.\n");
			status = 1;
		    }
		    parity = *++modespec;
		    if (strchr("NOE", parity) == NULL) {
			gpsd_report(LOG_ERROR, "What parity is '%c'?\n", parity);
			status = 1;
		    }
		    stopbits = *++modespec;
		    if (strchr("12", stopbits) == NULL) {
			gpsd_report(LOG_ERROR, "Stop bits must be 1 or 2.\n");
			status = 1;
		    }
		}
		if (status == 0)
		    (void)gps_query(&gpsdata, 
				    "?DEVICE={\"path\":\"%s\",\"bps\":%s,\"parity\":\"%c\",\"stopbits\":%c}\r\n", 
				    device, speed, parity, stopbits);
	    }
	    if (atoi(speed) != (int)gpsdata.dev.baudrate) {
		gpsd_report(LOG_ERROR, "%s driver won't support %s%c%c\n", 
			    gpsdata.dev.path,
			    speed, parity, stopbits);
		status = 1;
	    } else
		gpsd_report(LOG_PROG, "%s change to %s%c%c succeeded\n", 
			    gpsdata.dev.path,
			    speed, parity, stopbits);
	}
	if (rate != NULL) {
	    (void)gps_query(&gpsdata, 
			    "?DEVICE={\"path\":\"%s\",\"cycle\":%s}\n", 
			    device, rate);
	}
#endif /* ALLOW_RECONFIGURE */
	(void)gps_close(&gpsdata);
	exit(status);
#ifdef ALLOW_RECONFIGURE
    } else if (reset) {
	/* hard reset will go through lower-level operations */
	const int speeds[] = {2400, 4800, 9600, 19200, 38400, 57600, 115200};
	static struct gps_context_t	context;	/* start it zeroed */
	static struct gps_device_t	session;	/* zero this too */
	int i;

	if (device == NULL || forcetype == NULL) {
		gpsd_report(LOG_ERROR, "device and type must be specified for the reset operation.\n");
		exit(1);
	    }

	/*@ -mustfreeonly -immediatetrans @*/
	session.context = &context;
	gpsd_tty_init(&session);
	(void)strlcpy(session.gpsdata.dev.path, device, sizeof(session.gpsdata.dev.path));
	session.device_type = forcetype;
	(void)gpsd_open(&session);
	(void)gpsd_set_raw(&session);
	(void)session.device_type->speed_switcher(&session, 4800, 'N', 1);
	(void)tcdrain(session.gpsdata.gps_fd);
	for(i = 0; i < (int)(sizeof(speeds) / sizeof(speeds[0])); i++) {
	    (void)gpsd_set_speed(&session, speeds[i], 'N', 1);
	    (void)session.device_type->speed_switcher(&session, 4800, 'N', 1);
	    (void)tcdrain(session.gpsdata.gps_fd);
	}
	gpsd_set_speed(&session, 4800, 'N', 1);
	for (i = 0; i < 3; i++)
	    if (session.device_type->mode_switcher)
		session.device_type->mode_switcher(&session, MODE_NMEA);
	gpsd_wrap(&session);
	exit(0);
	/*@ +mustfreeonly +immediatetrans @*/
#endif /* ALLOW_RECONFIGURE */
    } else {
	/* access to the daemon failed, use the low-level facilities */
	static struct gps_context_t	context;	/* start it zeroed */
	static struct gps_device_t	session;	/* zero this too */
	/*@ -mustfreeonly -immediatetrans @*/
	session.context = &context;	/* in case gps_init isn't called */

	if (echo)
	    context.readonly = true;

	(void) alarm(timeout);
	(void) signal(SIGALRM, onsig);
	/*
	 * Unless the user has forced a type and only wants to see the
	 * string (not send it) we now need to try to open the device
	 * and find out what is actually there.
	 */
	if (!(forcetype != NULL && echo)) {
	    int seq;

	    if (device == NULL) {
		gpsd_report(LOG_ERROR, "device must be specified for low-level access.\n");
		exit(1);
	    }
	    gpsd_init(&session, &context, device);
	    gpsd_report(LOG_PROG, "initialization passed.\n");
	    if (gpsd_activate(&session) == -1) {
		gpsd_report(LOG_ERROR,
			      "activation of device %s failed, errno=%d\n",
			      device, errno);
		exit(2);
	    }
	    /* hunt for packet type and serial parameters */
	    for (seq = 0; session.device_type == NULL; seq++) {
		if (get_packet(&session) == ERROR_SET) {
		    gpsd_report(LOG_ERROR,
				"autodetection failed.\n");
		    exit(2);
		} else {
		    gpsd_report(LOG_IO,
				"autodetection after %d reads.\n", seq);
		    (void) alarm(0);
		    break;
		}
	    }
	    gpsd_report(LOG_PROG, "%s looks like a %s at %d.\n",
			device, gpsd_id(&session), session.gpsdata.dev.baudrate);

	    if (forcetype!=NULL && strcmp("Generic NMEA", session.device_type->type_name) !=0 && strcmp(forcetype->type_name, session.device_type->type_name)!=0) {
		gpsd_report(LOG_ERROR, "'%s' doesn't match non-generic type '%s' of selected device.\n", forcetype->type_name, session.device_type->type_name);
	    }

	    /* 
	     * If we've identified this as an NMEA device, we have to eat
	     * packets for a while to see if one of our probes elicits an
	     * ID response telling us that it's really a SiRF or
	     * something.  If so, the libgpsd(3) layer will automatically
	     * redispatch to the correct driver type.
	     */
	    if (strcmp(session.device_type->type_name, "Generic NMEA") == 0) {
		int dummy;
		for (dummy = 0; dummy < REDIRECT_SNIFF; dummy++) {
		    if ((get_packet(&session) & DEVICEID_SET)!=0)
			break;
		}
	    }
	    gpsd_report(LOG_SHOUT, "%s identified as a %s at %d.\n",
			device, gpsd_id(&session), session.gpsdata.dev.baudrate);
	}

	/* if no control operation was specified, we're done */
	if (speed==NULL && !to_nmea && !to_binary && control==NULL)
	    exit(0);

	/* maybe user wants to see the packet rather than send it */
	if (echo)
	    session.gpsdata.gps_fd = fileno(stdout);

	/* control op specified; maybe we forced the type */
	if (forcetype != NULL)
	    (void)gpsd_switch_driver(&session, forcetype->type_name);

	/* now perform the actual control function */
	status = 0;
#ifdef ALLOW_RECONFIGURE
	/*@ -nullderef @*/
	if (to_nmea || to_binary) {
	    if (session.device_type->mode_switcher == NULL) {
		gpsd_report(LOG_SHOUT, 
			      "%s devices have no mode switch.\n",
			      session.device_type->type_name);
		status = 1;
	    } else {
		int target_mode = to_nmea ? MODE_NMEA : MODE_BINARY;
		int target_type = to_nmea ? NMEA_PACKET : session.device_type->packet_type;

		gpsd_report(LOG_SHOUT, 
			      "switching to mode %s.\n",
			    to_nmea ? "NMEA" : "BINARY");
		session.device_type->mode_switcher(&session, target_mode);


		/* 
		 * Hunt for packet type again (mode might have
		 * changed).  We've found by experiment that you can't
		 * close the connection to the device after a mode
		 * change but before you see a packet of the right
		 * type come back from it - otherwise you can hit a
		 * timing window where the mode-change control message
		 * gets ignored or flushed.
		 */
		if (!echo) {
		    /* suppresses probing for subtypes */
		    context.readonly = true;
		    (void)sleep(1);
		    (void) alarm(timeout);
		    for (;;) {
			if (get_packet(&session) == ERROR_SET) {
			    continue;
			} else if (session.packet.type == target_type) {
			    (void)alarm(0);
			    break;
			}
		    }
		    context.readonly = false;
		}
		/*@ -nullpass @*/
		gpsd_report(LOG_SHOUT, "after mode change, %s looks like a %s at %d.\n",
			    device, gpsd_id(&session), session.gpsdata.dev.baudrate);
		/*@ +nullpass @*/
	    }
	}
	if (speed) {
	    char parity = echo ? 'N': session.gpsdata.dev.parity;
	    int stopbits = echo ? 1 : session.gpsdata.dev.stopbits;
	    char *modespec;

	    modespec = strchr(speed, ':');
	    /*@ +charint @*/
	    status = 0;
	    if (modespec!=NULL) {
		*modespec = '\0';
		if (strchr("78", *++modespec) == NULL) {
		    gpsd_report(LOG_ERROR, "No support for that word lengths.\n");
		    status = 1;
		}
		parity = *++modespec;
		if (strchr("NOE", parity) == NULL) {
		    gpsd_report(LOG_ERROR, "What parity is '%c'?\n", parity);
		    status = 1;
		}
		stopbits = *++modespec;
		if (strchr("12", parity) == NULL) {
		    gpsd_report(LOG_ERROR, "Stop bits must be 1 or 2.\n");
		    status = 1;
		}
		stopbits = (int)(stopbits-'0');
	    }
	    if (status == 0) {
		if (session.device_type->speed_switcher == NULL) {
		    gpsd_report(LOG_ERROR, 
				"%s devices have no speed switch.\n",
				session.device_type->type_name);
		    status = 1;
		}
		else if (session.device_type->speed_switcher(&session, 
							     (speed_t)atoi(speed),
							     parity, 
							     stopbits)) {
		    /*
		     * See the 'deep black magic' comment in
		     * gpsd.c:set_serial() Probably not needed here,
		     * but it can't hurt.
		     */
		    (void)tcdrain(session.gpsdata.gps_fd);
		    (void)usleep(50000);
		    gpsd_report(LOG_PROG, "%s change to %s%c%d succeeded\n", 
			    session.gpsdata.dev.path,
			    speed, parity, stopbits);
		} else {
		    gpsd_report(LOG_ERROR, "%s driver won't support %s%c%d.\n",
				session.gpsdata.dev.path,
				speed, parity, stopbits);
		    status = 1;
		}
	    }
	}
	if (rate) {
	    bool write_enable = context.readonly;
	    context.readonly = false;
	    if (session.device_type->rate_switcher == NULL) {
		gpsd_report(LOG_ERROR, 
			      "%s devices have no rate switcher.\n",
			      session.device_type->type_name);
		status = 1;
	    } else {
		double rate_dbl = strtod(rate, NULL);

		if (!session.device_type->rate_switcher(&session, rate_dbl)) {
		    gpsd_report(LOG_ERROR, "rate switch failed.\n");
		    status = 1;
		}
	    }
	    context.readonly = write_enable;
	}
#endif /* ALLOW_RECONFIGURE */
#ifdef ALLOW_CONTROLSEND
	/*@ -compdef @*/
	if (control) {
	    bool write_enable = context.readonly;
	    context.readonly = false;
	    if (session.device_type->control_send == NULL) {
		gpsd_report(LOG_ERROR, 
			      "%s devices have no control sender.\n",
			      session.device_type->type_name);
		status = 1;
	    } else {
		if (session.device_type->control_send(&session, 
						      cooked, 
						      (size_t)cooklen) == -1) {
		    gpsd_report(LOG_ERROR, "control transmission failed.\n");
		    status = 1;
		}
	    }
	    context.readonly = write_enable;
	}
	/*@ +compdef @*/
#endif /* ALLOW_CONTROLSEND */

	if (forcetype == NULL || !echo) {
	    /*
	     * Give the device time to settle before closing it.  Alas, this is
	     * voodoo programming; we don't know it will have any effect, but
	     * GPSes are notoriously prone to timing-dependent errors.
	     */
	    (void)usleep(300000);

	    gpsd_wrap(&session);
	}
	exit(status);
	/*@ +nullderef @*/
	/*@ +mustfreeonly +immediatetrans @*/
    }
}
Exemple #30
0
/**
 * Thread reading from gpsd.
 */
static void * cgps_thread (void * pData)
{
  struct gps_data_t gpsd_conn;
  unsigned int err_count;
  cgps_thread_running = CGPS_TRUE;

  while (CGPS_TRUE)
  {
    pthread_mutex_lock (&cgps_thread_lock);
    if (cgps_thread_shutdown == CGPS_TRUE)
    {
      goto quit;
    }
    pthread_mutex_unlock (&cgps_thread_lock);

    err_count = 0;

#if GPSD_API_MAJOR_VERSION > 4
    int status = gps_open (cgps_config_data.host, cgps_config_data.port, &gpsd_conn);
#else
    int status = gps_open_r (cgps_config_data.host, cgps_config_data.port, &gpsd_conn);
#endif
    if (status < 0)
    {
      WARNING ("gps plugin: connecting to %s:%s failed: %s",
               cgps_config_data.host, cgps_config_data.port, gps_errstr (status));

      // Here we make a pause until a new tentative to connect, we check also if
      // the thread does not need to stop.
      if (cgps_thread_pause(cgps_config_data.pause_connect) == CGPS_FALSE)
      {
        goto quit;
      }

      continue;
    }

    gps_stream (&gpsd_conn, WATCH_ENABLE | WATCH_JSON | WATCH_NEWSTYLE, NULL);
    gps_send (&gpsd_conn, CGPS_CONFIG);

    while (CGPS_TRUE)
    {
      pthread_mutex_lock (&cgps_thread_lock);
      if (cgps_thread_shutdown == CGPS_TRUE)
      {
        goto stop;
      }
      pthread_mutex_unlock (&cgps_thread_lock);

#if GPSD_API_MAJOR_VERSION > 4
      long timeout_us = CDTIME_T_TO_US (cgps_config_data.timeout);
      if (!gps_waiting (&gpsd_conn, (int) timeout_us ))
#else
      if (!gps_waiting (&gpsd_conn))
#endif
      {
        continue;
      }

      if (gps_read (&gpsd_conn) == -1)
      {
        WARNING ("gps plugin: incorrect data! (err_count: %d)", err_count);
        err_count++;

        if (err_count > CGPS_MAX_ERROR)
        {
          // Server is not responding ...
          if (gps_send (&gpsd_conn, CGPS_CONFIG) == -1)
          {
            WARNING ("gps plugin: gpsd seems to be down, reconnecting");
            gps_close (&gpsd_conn);
            break;
          }
          // Server is responding ...
          else
          {
            err_count = 0;
          }
        }

        continue;
      }

      pthread_mutex_lock (&cgps_data_lock);

      // Number of sats in view:
      cgps_data.sats_used = (gauge_t) gpsd_conn.satellites_used;
      cgps_data.sats_visible = (gauge_t) gpsd_conn.satellites_visible;

      // dilution of precision:
      cgps_data.vdop = NAN;
      cgps_data.hdop = NAN;
      if (cgps_data.sats_used > 0)
      {
        cgps_data.hdop = gpsd_conn.dop.hdop;
        cgps_data.vdop = gpsd_conn.dop.vdop;
      }

      DEBUG ("gps plugin: %.0f sats used (of %.0f visible), hdop = %.3f, vdop = %.3f",
             cgps_data.sats_used, cgps_data.sats_visible, cgps_data.hdop, cgps_data.vdop);

      pthread_mutex_unlock (&cgps_data_lock);
    }
  }

stop:
  DEBUG ("gps plugin: thread closing gpsd connection ... ");
  gps_stream (&gpsd_conn, WATCH_DISABLE, NULL);
  gps_close (&gpsd_conn);
quit:
  DEBUG ("gps plugin: thread shutting down ... ");
  cgps_thread_running = CGPS_FALSE;
  pthread_mutex_unlock (&cgps_thread_lock);
  pthread_exit (NULL);
}