#include <fcntl.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <termios.h>
#include <unistd.h>

#define GPS_DEV "/dev/ttySAC1"

#define GPS_SYNC "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80"

/*
#define GPS_INIT "\xff\x0c\xfd\xc0\x00\xfc" // from the tomtom logs
*/
#define GPS_INIT "\xff\x00\xfd\xc0\x00\xfc" // from gllin -low 1

void power_on_seq(void)
{
	int fd;
	// reset 0
	// pwron 0
	fd = open("/sys/bus/platform/devices/gta01-pm-gps.0/power_lp_io_3v3", O_WRONLY);
	write(fd, "1", 2);
	close(fd);
	fd = open("/sys/bus/platform/devices/gta01-pm-gps.0/power_lp_io_3v3", O_WRONLY);
	write(fd, "1", 2);
	close(fd);	
	fd = open("/sys/bus/platform/devices/gta01-pm-gps.0/reset", O_WRONLY);
	write(fd, "1", 2);
	close(fd);
	usleep(1000);
	fd = open("/sys/bus/platform/devices/gta01-pm-gps.0/power_pll_core_2v5", O_WRONLY);
	write(fd, "1", 2);
	close(fd);
	fd = open("/sys/bus/platform/devices/gta01-pm-gps.0/power_avdd_3v", O_WRONLY);
	write(fd, "1", 2);
	close(fd);
	fd = open("/sys/bus/platform/devices/gta01-pm-gps.0/power_vdd_core_1v5", O_WRONLY);
//	fd = open("/sys/bus/platform/devices/gta01-pm-gps.0/power_core_1v5", O_WRONLY);
	write(fd, "1", 2);
	close(fd);
	usleep(1000);
	fd = open("/sys/bus/platform/devices/gta01-pm-gps.0/pwron", O_WRONLY);
	write(fd, "1", 2);
	close(fd);
	usleep(15900);
}

void power_off_seq(void)
{
	int fd;
	fd = open("/sys/bus/platform/devices/gta01-pm-gps.0/power_pll_core_2v5", O_WRONLY);
	write(fd, "0", 2);
	close(fd);
	fd = open("/sys/bus/platform/devices/gta01-pm-gps.0/power_avdd_3v", O_WRONLY);
	write(fd, "0", 2);
	close(fd);
	fd = open("/sys/bus/platform/devices/gta01-pm-gps.0/power_vdd_core_1v5", O_WRONLY);
//	fd = open("/sys/bus/platform/devices/gta01-pm-gps.0/power_core_1v5", O_WRONLY);
	write(fd, "0", 2);
	close(fd);
	fd = open("/sys/bus/platform/devices/gta01-pm-gps.0/pwron", O_WRONLY);
	write(fd, "0", 2);
	close(fd);
}

int main(int argc, char *argv[])
{
	int fd;
	struct termios t;
	char buf[512];
	char *p;
	int n;

	power_on_seq();

	fd = open(GPS_DEV, O_RDWR);

	ioctl(fd, TCGETS, &t);
	cfsetispeed(&t, B115200);
	cfsetospeed(&t, B115200);
	cfmakeraw(&t);
	t.c_cflag &= ~CRTSCTS;
	t.c_cflag |= 0x80000000;

	ioctl(fd, TCSETS, &t);

	write(fd, GPS_SYNC, 16);
	write(fd, GPS_INIT, 6);

	n = read(fd, buf, sizeof(buf));
	printf("(%d) ", n);
	p = buf;
	while (n--)
		printf("%02x ", *p++);
	printf("\n");

	power_off_seq();
}
