#include "PN532.h"

int PN532_INIT(void)
{
    // 初始化UART
    uart_init(UART0, BAUD_RATE);
    gpio_set_function(UART0_TX_PIN, GPIO_FUNC_UART);
    gpio_set_function(UART0_RX_PIN, GPIO_FUNC_UART);
    uart_set_hw_flow(UART0, false, false);
    uart_set_format(UART0, DATA_BITS, STOP_BITS, PARITY);

    return 0;
}

void PN532(void *p)
{
    (void)p;
    PN532_INIT();

    while (1) {
        printf("PN532 Module\n");

        uint8_t PN532_DATA[270] = { 0 };
        //int PN532_DATA_LEN = 0;

        // 24
        // 55 55 00 00 00 00 00 00 00 00 00 00 00 00 00 00 FF 03 FD D4 14 01 17 00
        uint8_t _CMD0[24] = { 0X55, 0X55, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0X00, 0XFF, 0X03, 0XFD, 0XD4, 0X14, 0X01, 0X17, 0X00 };

        // 11
        // 00 00 FF 04 FC D4 4A 02 00 E0 00
        uint8_t _CMD1[11] = { 0X00, 0X00, 0XFF, 0X04, 0XFC, 0XD4, 0X4A, 0X02, 0X00, 0XE0, 0X00 };

        uart_write_blocking(UART0, _CMD0, 24);
        sleep_ms(100);
        uart_read_blocking(UART0, PN532_DATA, 15);
        /*
           for (int i = 0; i < 15; i++) {
           printf("0X%X ", PN532_DATA[i]);
           }
           printf("\r\n");
         */
        memset(PN532_DATA, 0, 270);

        uart_write_blocking(UART0, _CMD1, 11);
        sleep_ms(100);
        uart_read_blocking(UART0, PN532_DATA, 6);
        /*
           for (int i = 0; i < 6; i++) {
           printf("0X%X ", PN532_DATA[i]);
           }
           printf("\r\n");
         */
        memset(PN532_DATA, 0, 270);

        uart_read_blocking(UART0, PN532_DATA, 19);
        /*
           for (int i = 0; i < 19; i++) {
           printf("0X%X ", PN532_DATA[i]);
           }
           printf("\r\n");
         */

        printf("UID: 0X%X 0X%X 0X%X 0X%X\r\n", PN532_DATA[14 - 1], PN532_DATA[15 - 1], PN532_DATA[16 - 1], PN532_DATA[17 - 1]);
        
        printf("\n");
        vTaskDelay(pdMS_TO_TICKS(3000)); // 非阻塞延时
    }
    return;
}
