/**********************************************************************
 
	Copyright (C) 2003-2004
	Hirohisa MORI <joshua@nichibun.ac.jp>
	Tomoki SEKIYAMA <sekiyama@yahoo.co.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	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.

**********************************************************************/


#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <time.h>

#include "task.h"
#include "init.h"
#include "memory_debug.h"
#include "utils.h"
#include "serial_port.h"
#include "locator.h"
#include "gps.h"


int start;

void
listen_func(LOCATOR_INFO* li, const LOCATION_INFO *info)
{
	printf("GPS : type : %d\n", info->locator_type);
	if ( ! (info->state & LS_LOC_UNABLE) ) {
		printf("    x %f %s  y %f %s  z %f %s\n", 
			info->x, info->x_unit, info->y, info->y_unit, info->z, info->z_unit);
		printf("      accuracy : x %f %s  y %f %s  z %f %s\n",
			info->sx, info->sx_unit, info->sy, info->sy_unit, info->sz, info->sz_unit);
	}
	else
		printf("    x ???  y ???  z ???\n");
	if ( ! (info->state & LS_TIME_UNABLE) ) {
		char buf[40];
		time_t time = (time_t)info->t + UTC_00_00_00_01_01_2001;
		strftime(buf, 40, "%a, %d %b %Y %H:%M:%S %z", localtime(&time));
		printf("      time : [%.2f] %s\n", info->t, buf);
	}
	else
		printf("    time ???\n");
	printf("\n");
	
	if ( start + 30 < get_xltime() )
		kill_locator(li);
}

void
close_func(LOCATOR_INFO *info)
{
	wakeup_task((int)&start);
}

int
_main(int argc, char **argv)
{
int i = 0;
char buffer[10];
SERIAL_PORT_INFO *list, *target;
LOCATOR_INIT init;
	
	ss_printf("test\n\n");

	list = lookup_serial_port();
	if ( list == 0 ) {
		printf("No GPS port\n");
		exit(1);
	}
	
	for ( target = list ; target ; target = target->next )
		printf("%d [ %s ]\n", ++i, target->name);
	printf("Please select GPS port (1-%d) > ", i);
	fgets(buffer, sizeof(buffer), stdin);
	i = atoi(buffer);
	
	target = list;
	while ( target && --i )
		target = target->next;
	if ( target == 0 ) {
		printf("No GPS port\n");
		exit(1);
	}
	printf("\nGPS port : %s\n", target->name);
	
	start = get_xltime();
	
	init.locator_type = LT_ALLOW_ALL;
	init.listen_func = listen_func;
	init.close_func = close_func;
	init.listen_interval = 0;
	init.st = open_serial_port(target, 4800);
	init_locator_gps(&init);
	
	sleep_task((int)&start, SEM_NULL);
	ss_printf("\n\ntest end\n\n");
	return 0;
}
