/***************************************************************************
 *            linux_gps.c
 *
 *  Copyright  2010 - Steffen Pohle
 *  steffen@gulpe.de
 ****************************************************************************/

/*
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include "gps.h"
#include "system.h"

int gpsdev_fd = 0;
char gpsdev_device[GPS_DEVICELEN];
int gpsdev_baud = 0;

void gps_serial_settings () {
	char *cfg = gps_get_device ();
	char baud[16];
	int i, c, d;

	if (cfg == NULL) return;
	memset (gpsdev_device, 0x0, GPS_DEVICELEN);
	memset (baud, 0x0, 16);

	for (i = 0, c = 0, d = 0; c < GPS_DEVICELEN && cfg[c] != 0; c++) {
		if (cfg[c] == ':') {
			i = 1;
			d = 0;
		}
		else if (cfg[c] == ',') {
			i++;
			d = 0;
		}
		else if (i == 1) { /* gpsdev_device ... tty port */
			gpsdev_device[d++] = cfg[c];
		}
		else if (i == 2 && d < 16) { /* baud rate */
			baud[d++] = cfg[c];
		}
	}
};

int gps_serial_device_open () {
	gps_serial_settings ();
	gpsdev_fd = open(gpsdev_device, O_RDWR | O_NOCTTY | O_NONBLOCK);
	if (gpsdev_fd >= 0) 
		return 1;
	else {
		d_printf ("%s:%d gps_serial_device_open open tty device '%s' failed: %s",
		          __FILE__, __LINE__, gpsdev_device, strerror(errno));
		return 0;
	}
};


void gps_serial_device_close () {
	if (gpsdev_fd <= 0) return;
	close (gpsdev_fd);
	gpsdev_fd = 0;
};


int gps_serial_device_read (char *ptr, int ptrsize) {
	fd_set rfds;
	struct timeval tv;
	int retval;

	if (gpsdev_fd <= 0) return -1;

	/* Watch stdin (fd 0) to see when it has input. */
	FD_ZERO(&rfds);
	FD_SET(gpsdev_fd, &rfds);

	tv.tv_sec = 0;
	tv.tv_usec = 0;

	retval = select(gpsdev_fd+1, &rfds, NULL, NULL, &tv);

	if (retval == -1) {
		d_printf ("%s:%d gps_serial_device_read error: %s", __FILE__, __LINE__, strerror(errno));
		return -1;
	}
	else if (retval) {
		if (FD_ISSET(gpsdev_fd, &rfds)) 
			return read (gpsdev_fd, ptr, ptrsize);
	}
	else
		return 0;

	return -1;
};
