/*
 * m5stack_keyboard.c
 *
 *  Created on: Aug 6, 2022
 *      Author: user
 */

#include "m5stack_keyboard.h"
#include "main.h"
#include "i2c.h"

HAL_StatusTypeDef read_keyboard(uint8_t *key_code)
{
	return HAL_I2C_Master_Receive(&CARDKB_I2C, CARDKB_ADDR, key_code, 1,
			I2C_TIMEOUT);
}

char CardKB_code2char(uint8_t key_code)
{
// https://docs.m5stack.com/en/unit/cardkb
	switch (key_code)
	{
	case 0x61:
		return 'a';
	case 0x41:
		return 'A';
	case 0x62:
		return 'b';
	case 0x42:
		return 'B';
	case 0x63:
		return 'c';
	case 0x43:
		return 'C';
	case 0x31:
		return '1';
	case 0x32:
		return '2';
	case 0x33:
		return '3';

		// to be continued... maybe :)
	default:
		return '\0';
	}

}

void KeyboardKeycodes(uint8_t key_code, uint8_t KeyboardReportBuffer[8])
{
	// From
	// https://docs.m5stack.com/en/unit/cardkb
	// to
	// https://www.win.tue.nl/~aeb/linux/kbd/scancodes-14.html
	// https://www.usb.org/sites/default/files/documents/hut1_12v2.pdf
	switch (key_code)
	{
	case 0x31: // 1
		KeyboardReportBuffer[2] = 30;
		break;
	case 0x32: // 2
		KeyboardReportBuffer[2] = 31;
		break;
	case 0x33: // 3
		KeyboardReportBuffer[2] = 32;
		break;
	case 0x61: // a
		KeyboardReportBuffer[2] = 4;
		break;
	case 0x62: // b
		KeyboardReportBuffer[2] = 5;
		break;
	case 0x63: // c
		KeyboardReportBuffer[2] = 6;
		break;
	case 0x41: //A
		KeyboardReportBuffer[0] = 0x02; // Left Shift
		KeyboardReportBuffer[2] = 4;
		break;
	case 0x42: //B
		KeyboardReportBuffer[0] = 0x02; // Left Shift
		KeyboardReportBuffer[2] = 5;
		break;
	case 0x43: //C
		KeyboardReportBuffer[0] = 0x02; // Left Shift
		KeyboardReportBuffer[2] = 6;
		break;
		// to be continued... maybe :)
	default:
		KeyboardReportBuffer[0] = 0x00;
		KeyboardReportBuffer[2] = 0;
		break;
	}
}
