//  Copyright (C) 2016, mituhiromatuura all right reserved.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <kernel.h>
#include <t_syslog.h>
#include <t_stdlib.h>
#include "syssvc/serial.h"
#include "syssvc/syslog.h"
#include "kernel_cfg.h"

#include "disp.h"
#include "driverec.h"
#include "fatfs.h"
#define lcd_puts(a, b, c, d, e) 
#include "exbus.h"
#include "gps.h"
#include "lcd.h"

FIL f_gps;
int save_gps = 0;

static
void uart_puts(char *str)
{
	serial_wri_dat(TASK_PORTID, str, strlen(str));
	return;
}

static
void uart_gets(char buf[], int len)
{
	char c;
	int n;

	for(n = 0; n < len - 1; n++)
	{
		serial_rea_dat(GPS_PORTID, &c, 1);

		buf[n] = c;

		if('\n' == c)
		{
			n++;
			break;
		}
	}
	buf[n] = '\0';

	return;
}

void task_gps(intptr_t exinf)
{
	static char rx_buf[128];

	dly_tsk(1000);
	uart_puts("task_gps start\r\n");

	while(1)
	{
		FRESULT res;
		UINT size;

		while(1)
		{
			uart_gets(rx_buf, sizeof(rx_buf));
			uart_puts(rx_buf);

			if(save_gps)
			{
				res = fatfs_write(&f_gps, (const void*)rx_buf, strlen(rx_buf), &size);
				if(FR_OK != res)
				{
					uart_puts("fatfs_write error\r\n");
					break;
				}
			}

			//現在時刻
			gps_get_time(rx_buf);

			//移動速度
			if(gps_get_speed(rx_buf, speed))
			{
				speed[5] = '\0';
				strcat(speed, "km/h");
				uart_puts(speed);
				uart_puts("\r\n");
			}

			//緯度経度
			gps_get_position(rx_buf, latitude, longitude);
		}
	}
	return;
}

DWORD get_fattime (void)
{
	/* Pack date and time into a DWORD variable */
	return	  ((DWORD)(year - 1980) << 25)
			| ((DWORD)month << 21)
			| ((DWORD)day << 16)
			| ((DWORD)hour << 11)
			| ((DWORD)min << 5)
			| ((DWORD)sec >> 1);
}
