#include "common.h"
#include "infrared_gun.h"
// 初始化
int infrared_Init() {
    pinMode(IR_PIN, OUTPUT);
    pinMode(IR_PIN_rec, INPUT);
    return 0;
}

// 字符串补零并转为uint32数组
void pad_and_convert(const char* hex_str, uint32_t* data_out, int* count) {
    char padded[17] = {0};
    int len = strlen(hex_str);
    int pad_len = 16 - len;
    
    for (int i = 0; i < pad_len; i++) {
        padded[i] = '0';
    }
    strcpy(padded + pad_len, hex_str);

    *count = 0;
    for (int i = 0; i < 16; i += 8) {
        char temp[9] = {0};
        strncpy(temp, padded + i, 8);
        sscanf(temp, "%x", &data_out[*count]);
        (*count)++;
    }
}

// 发送32位数据（NEC协议）
void sendNEC(uint32_t data) {
    // 起始码
    digitalWrite(IR_PIN, HIGH);
    delay_us(START_PULSE_HIGH);
    digitalWrite(IR_PIN, LOW);
    delay_us(START_PULSE_LOW);

    // 发送32位数据
    for (int i = 31; i >= 0; i--) {
        if ((data >> i) & 1) {
            digitalWrite(IR_PIN, HIGH);
            delay_us(ONE_PULSE_HIGH);
            digitalWrite(IR_PIN, LOW);
            delay_us(ONE_PULSE_LOW);
        } else {
            digitalWrite(IR_PIN, HIGH);
            delay_us(ZERO_PULSE_HIGH);
            digitalWrite(IR_PIN, LOW);
            delay_us(ZERO_PULSE_LOW);
        }
    }

    // 停止码
    digitalWrite(IR_PIN_rec, LOW);
    delay_us(STOP_PULSE);
}

// 发送完整字符串数据（如“00020200000000”）
void sendHexString(const char* hex_str) {
    uint32_t data_arr[2];
    int count = 0;
    pad_and_convert(hex_str, data_arr, &count);
    for (int i = 0; i < count; i++) {
        sendNEC(data_arr[i]);
              // 适当延时两次发送间隔
    }
}

// 接收多段NEC数据（128位 = 4次）
void receiveNEC_Multi(int num_blocks) {
    uint32_t data_arr[4] = {0};

    for (int j = 0; j < num_blocks; j++) {
        uint32_t data = 0;

        // 等待高电平（起始码）
        while (digitalRead(IR_PIN_rec) == LOW);
        delay_us(START_PULSE_MIN);

        for (int i = 31; i >= 0; i--) {
            while (digitalRead(IR_PIN_rec) == LOW);
           delay_us(ZERO_PULSE_MIN);

            if (digitalRead(IR_PIN_rec) == HIGH) {
                delay_us(ONE_PULSE_MIN);
                data |= (1 << i);
            } else {
                delay_us(ZERO_PULSE_MIN);
            }
        }
        data_arr[j] = data;
    }

    // 输出结果
    printf("Received HEX: ");
    for (int i = 0; i < num_blocks; i++) {
        printf("%08X", data_arr[i]);
    }
    printf("\n");
}