/*
 * echo.c
 *
 *  Created on: Mar 4, 2012
 *      Author: RomanM
 */

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

#include "echo.h"
#include "../../uip.h"
#include "aes/aes.h"

#include "ServicePort/setting.h"
#include "drivers/drivers.h"

extern uint8_t getDoorControlState(void);

extern unsigned char aes_key[];
extern aes_context aes_ctx;

void uip_echo_init(void) {
	uip_listen(HTONS(ECHO_PORT));
}

void uip_echo_call(void) {
	char toSend_plain[32];
	uint8_t toSend_aes[32];

	int day, month, year, hour, minute, second;
	char command[16];

	if (uip_newdata()) {
		if (!memcmp(uip_conn->ripaddr, setting.serverAddress, sizeof(uip_ipaddr_t))) {

			memset(toSend_plain, 0, sizeof(toSend_plain));

			aes_setkey_dec(&aes_ctx, aes_key, 128);
			aes_crypt_ecb(&aes_ctx, AES_DECRYPT, uip_appdata, uip_appdata);
			aes_crypt_ecb(&aes_ctx, AES_DECRYPT, uip_appdata + 16, uip_appdata + 16);

			sscanf(uip_appdata,
					"%d. %d. %d %d:%2d:%2d %s",
					&day,
					&month,
					&year,
					&hour,
					&minute,
					&second,
					command);

			if (!strcmp(command, "GETSTATE")) {
				RTC_SetDay(day);
				RTC_SetMonth(month);
				RTC_SetYear(year);
				RTC_SetHour(hour);
				RTC_SetMinute(minute);
				RTC_SetSecond(second);

				memset(toSend_plain, 0, sizeof(toSend_plain));
				if (getDoorControlState() && DoorLock_GetLockLoop() &&
					ADC1_GetValueFilt(SENSOR1) >= setting.calibCh1 &&
					ADC1_GetValueFilt(SENSOR2) >= setting.calibCh2) {
					sprintf(toSend_plain, "OK %s", setting.devName);
				}
				else {
					sprintf(toSend_plain, "ERR");
				}

			}
			else if (!memcmp(command, "NAME=", 5)) {
				strcpy(setting.devName, command + 5);
				sprintf(toSend_plain, "OK");
			}
			else if (!strcmp(command, "GETDOORTIME")) {
				sprintf(toSend_plain, "%d", setting.doorTimeout);
			}
			else if (!memcmp(command, "DOORTIME=", 9)) {
				setting.doorTimeout = atoi(command + 9);
				sprintf(toSend_plain, "OK");
			}
			else if (!strcmp(command, "CALIBRATION")) {
				setting.calibCh1 = ADC1_GetValueFilt(SENSOR1) - 200;
				setting.calibCh2 = ADC1_GetValueFilt(SENSOR2) - 200;
				sprintf(toSend_plain, "OK");
			}
			else if (!memcmp(command, "SAVESETTING", 5)) {
				Setting_Save();
				sprintf(toSend_plain, "OK");
			}
			else {
				sprintf(toSend_plain, "ERR");
			}

			aes_setkey_enc(&aes_ctx, aes_key, 128);
			aes_crypt_ecb(&aes_ctx, AES_ENCRYPT, (uint8_t*)toSend_plain, toSend_aes);
			aes_crypt_ecb(&aes_ctx, AES_ENCRYPT, (uint8_t*)toSend_plain + 16, toSend_aes + 16);
			uip_send(toSend_aes, sizeof(toSend_aes));
		}
		else {
			uip_close();
		}
	}
	else if (uip_acked()) {
		uip_close();
	}
}
