/*
 * udp_test.c
 *
 *  Created on: 2022. 1. 10.
 *      Author: wonki
 */

#include "udp_test.h"
#include "socket.h"
#include "loopback.h"
#include <string.h>
#include <stdio.h>
#include "app_log.h"
#include "task_def.h"
#include "sl_emlib_gpio_init_w5500_reset_config.h"
#include "em_gpio.h"
#include "spidrv.h"
#include "sl_spidrv_instances.h"
//
#define DHCP_SOCKET		5

void TestTask(void *);

void SPI_Select(void) {
	GPIO_PinOutClear(sl_spidrv_w5500_handle->portCs,
			sl_spidrv_w5500_handle->pinCs);
}

void SPI_Unselect(void) {
	GPIO_PinOutSet(sl_spidrv_w5500_handle->portCs,
			sl_spidrv_w5500_handle->pinCs);
}

void SPI_ReadBuf(uint8_t *buf, uint16_t len) {
	Ecode_t status = SPIDRV_MReceiveB(sl_spidrv_w5500_handle, buf, len);
	if (status != ECODE_EMDRV_SPIDRV_OK) {
		printf("read tatus:%d\r\n", status);
	}
}

void SPI_WriteBuf(uint8_t *buf, uint16_t len) {
	Ecode_t status = SPIDRV_MTransmitB(sl_spidrv_w5500_handle, buf, len);
	if (status != ECODE_EMDRV_SPIDRV_OK) {
		printf("write tatus:%d\r\n", status);
	}
}

uint8_t SPI_ReadByte(void) {
	uint8_t byte;
	SPI_ReadBuf(&byte, sizeof(byte));
	return byte;
}

void SPI_WriteByte(uint8_t byte) {
	SPI_WriteBuf(&byte, sizeof(byte));
}

void test_udp(void) {
	CreateTask(TestTask,
			"TestTask",
			BASE_STACK_DEPTH * 8,
			(void*) 1,
			PRIORITY_1,
			NULL, NULL, NULL);


}

void TestTask(void *pvParameters) {
	configASSERT((uint32_t ) pvParameters == 1);

	GPIO_PinOutClear(SL_EMLIB_GPIO_INIT_W5500_RESET_PORT,
	SL_EMLIB_GPIO_INIT_W5500_RESET_PIN);
	vTaskDelay(pdMS_TO_TICKS(50));
	GPIO_PinOutSet(SL_EMLIB_GPIO_INIT_W5500_RESET_PORT,
	SL_EMLIB_GPIO_INIT_W5500_RESET_PIN);
	vTaskDelay(pdMS_TO_TICKS(500));

	GPIO_PinModeSet(sl_spidrv_w5500_handle->portCs,
			sl_spidrv_w5500_handle->pinCs, gpioModePushPull, 1);

	printf("Registering W5500 callbacks...\r\n");
	reg_wizchip_cs_cbfunc(SPI_Select, SPI_Unselect);
	reg_wizchip_spi_cbfunc(SPI_ReadByte, SPI_WriteByte);
	reg_wizchip_spiburst_cbfunc(SPI_ReadBuf, SPI_WriteBuf);

	wizphy_reset();
	printf("Ethernet PHY Link Check...\r\n");
	int8_t tmp;
	do {
	   if(ctlwizchip(CW_GET_PHYLINK, (void*)&tmp) == -1)
		   printf("Unknown PHY Link stauts.\r\n");
	} while(tmp == PHY_LINK_OFF);
	printf("PHY LINK OK\r\n");

	vTaskDelay(pdMS_TO_TICKS(500));

	printf("wizchip_init()\r\n");
	uint8_t rx_tx_buff_sizes[] = { 2, 2, 2, 2, 2, 2, 2, 2 };
	wizchip_init(rx_tx_buff_sizes, rx_tx_buff_sizes);

	uint8_t version = getVERSIONR();
	printf("Chip Version:0x%.2x\r\n", version);

	uint8_t mac_addr[6] = { 0x18, 0xeb, 0x74, 0x42, 0x3c, 0xe7 }; //flash memory에서 불러오는 것으로 변경해야 한다.
	setSHAR(mac_addr);
	uint8_t buf[6] = { 0, };
	getSHAR(buf);
	printf("MAC ADDRESS: ");
	for (int i = 0; i < 6; i++) {
		app_log_append("0x%.2x\t", buf[i]);
	}
	app_log_append("\r\n");

	socket(DHCP_SOCKET, Sn_MR_UDP, 60960, 0x00);
	char udp_buf[2048];
	int32_t ret = 0;
	while ((ret = loopback_udps(DHCP_SOCKET, (uint8_t *)udp_buf, 60960)) > 0) {
		vTaskDelay(pdMS_TO_TICKS(10));
	}
	printf("ret>%ld\r\n", ret);
}
