code:
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "common/input.h"
#include "common/logging/log.h"
#include "input_common/helpers/joycon_protocol/common_protocol.h"

namespace InputCommon::Joycon {
JoyconCommonProtocol::JoyconCommonProtocol(std::shared_ptr<JoyconHandle> hidapi_handle_)
    : hidapi_handle{std::move(hidapi_handle_)} {}

u8 JoyconCommonProtocol::GetCounter() {
    hidapi_handle->packet_counter = (hidapi_handle->packet_counter + 1) & 0x0F;
    return hidapi_handle->packet_counter;
}

void JoyconCommonProtocol::SetBlocking() {
    SDL_hid_set_nonblocking(hidapi_handle->handle, 0);
}

void JoyconCommonProtocol::SetNonBlocking() {
    SDL_hid_set_nonblocking(hidapi_handle->handle, 1);
}

Common::Input::DriverResult JoyconCommonProtocol::GetDeviceType(ControllerType& controller_type) {
    const auto result = ReadSPI(SpiAddress::DEVICE_TYPE, controller_type);

    if (result == Common::Input::DriverResult::Success) {
        // Fallback to 3rd party pro controllers
        if (controller_type == ControllerType::None) {
            controller_type = ControllerType::Pro;
        }
    }

    return result;
}

Common::Input::DriverResult JoyconCommonProtocol::CheckDeviceAccess(
    SDL_hid_device_info* device_info) {
    ControllerType controller_type{ControllerType::None};
    const auto result = GetDeviceType(controller_type);

    if (result != Common::Input::DriverResult::Success || controller_type == ControllerType::None) {
        return Common::Input::DriverResult::UnsupportedControllerType;
    }

    hidapi_handle->handle =
        SDL_hid_open(device_info->vendor_id, device_info->product_id, device_info->serial_number);

    if (!hidapi_handle->handle) {
        LOG_ERROR(Input, "Yuzu can't gain access to this device: ID {:04X}:{:04X}.",
                  device_info->vendor_id, device_info->product_id);
        return Common::Input::DriverResult::HandleInUse;
    }

    SetNonBlocking();
    return Common::Input::DriverResult::Success;
}

Common::Input::DriverResult JoyconCommonProtocol::SetReportMode(ReportMode report_mode) {
    const std::array<u8, 1> buffer{static_cast<u8>(report_mode)};
    return SendSubCommand(SubCommand::SET_REPORT_MODE, buffer);
}

Common::Input::DriverResult JoyconCommonProtocol::SendRawData(std::span<const u8> buffer) {
    const auto result = SDL_hid_write(hidapi_handle->handle, buffer.data(), buffer.size());

    if (result == -1) {
        return Common::Input::DriverResult::ErrorWritingData;
    }

    return Common::Input::DriverResult::Success;
}

Common::Input::DriverResult JoyconCommonProtocol::GetSubCommandResponse(
    SubCommand sc, SubCommandResponse& output) {
    constexpr int timeout_mili = 66;
    constexpr int MaxTries = 10;
    int tries = 0;

    do {
        int result = SDL_hid_read_timeout(hidapi_handle->handle, reinterpret_cast<u8*>(&output),
                                          sizeof(SubCommandResponse), timeout_mili);

        if (result < 1) {
            LOG_ERROR(Input, "No response from joycon");
        }
        if (tries++ > MaxTries) {
            return Common::Input::DriverResult::Timeout;
        }
    } while (output.input_report.report_mode != ReportMode::SUBCMD_REPLY &&
             output.sub_command != sc);

    return Common::Input::DriverResult::Success;
}

Common::Input::DriverResult JoyconCommonProtocol::SendSubCommand(SubCommand sc,
                                                                 std::span<const u8> buffer,
                                                                 SubCommandResponse& output) {
    SubCommandPacket packet{
        .output_report = OutputReport::RUMBLE_AND_SUBCMD,
        .packet_counter = GetCounter(),
        .sub_command = sc,
        .command_data = {},
    };

    if (buffer.size() > packet.command_data.size()) {
        return Common::Input::DriverResult::InvalidParameters;
    }

    memcpy(packet.command_data.data(), buffer.data(), buffer.size());

    auto result = SendData(packet);

    if (result != Common::Input::DriverResult::Success) {
        return result;
    }

    return GetSubCommandResponse(sc, output);
}

Common::Input::DriverResult JoyconCommonProtocol::SendSubCommand(SubCommand sc,
                                                                 std::span<const u8> buffer) {
    SubCommandResponse output{};
    return SendSubCommand(sc, buffer, output);
}

Common::Input::DriverResult JoyconCommonProtocol::SendMCUCommand(SubCommand sc,
                                                                 std::span<const u8> buffer) {
    SubCommandPacket packet{
        .output_report = OutputReport::MCU_DATA,
        .packet_counter = GetCounter(),
        .sub_command = sc,
        .command_data = {},
    };

    if (buffer.size() > packet.command_data.size()) {
        return Common::Input::DriverResult::InvalidParameters;
    }

    memcpy(packet.command_data.data(), buffer.data(), buffer.size());

    return SendData(packet);
}

Common::Input::DriverResult JoyconCommonProtocol::SendVibrationReport(std::span<const u8> buffer) {
    VibrationPacket packet{
        .output_report = OutputReport::RUMBLE_ONLY,
        .packet_counter = GetCounter(),
        .vibration_data = {},
    };

    if (buffer.size() > packet.vibration_data.size()) {
        return Common::Input::DriverResult::InvalidParameters;
    }

    memcpy(packet.vibration_data.data(), buffer.data(), buffer.size());

    return SendData(packet);
}

Common::Input::DriverResult JoyconCommonProtocol::ReadRawSPI(SpiAddress addr,
                                                             std::span<u8> output) {
    constexpr std::size_t HeaderSize = 5;
    constexpr std::size_t MaxTries = 5;
    std::size_t tries = 0;
    SubCommandResponse response{};
    std::array<u8, sizeof(ReadSpiPacket)> buffer{};
    const ReadSpiPacket packet_data{
        .spi_address = addr,
        .size = static_cast<u8>(output.size()),
    };

    memcpy(buffer.data(), &packet_data, sizeof(ReadSpiPacket));
    do {
        const auto result = SendSubCommand(SubCommand::SPI_FLASH_READ, buffer, response);
        if (result != Common::Input::DriverResult::Success) {
            return result;
        }

        if (tries++ > MaxTries) {
            return Common::Input::DriverResult::Timeout;
        }
    } while (response.spi_address != addr);

    if (response.command_data.size() < packet_data.size + HeaderSize) {
        return Common::Input::DriverResult::WrongReply;
    }

    // Remove header from output
    memcpy(output.data(), response.command_data.data() + HeaderSize, packet_data.size);
    return Common::Input::DriverResult::Success;
}

Common::Input::DriverResult JoyconCommonProtocol::EnableMCU(bool enable) {
    const std::array<u8, 1> mcu_state{static_cast<u8>(enable ? 1 : 0)};
    const auto result = SendSubCommand(SubCommand::SET_MCU_STATE, mcu_state);

    if (result != Common::Input::DriverResult::Success) {
        LOG_ERROR(Input, "Failed with error {}", result);
    }

    return result;
}

Common::Input::DriverResult JoyconCommonProtocol::ConfigureMCU(const MCUConfig& config) {
    LOG_DEBUG(Input, "ConfigureMCU");
    std::array<u8, sizeof(MCUConfig)> config_buffer;
    memcpy(config_buffer.data(), &config, sizeof(MCUConfig));
    config_buffer[37] = CalculateMCU_CRC8(config_buffer.data() + 1, 36);

    const auto result = SendSubCommand(SubCommand::SET_MCU_CONFIG, config_buffer);

    if (result != Common::Input::DriverResult::Success) {
        LOG_ERROR(Input, "Failed with error {}", result);
    }

    return result;
}

Common::Input::DriverResult JoyconCommonProtocol::GetMCUDataResponse(ReportMode report_mode,
                                                                     MCUCommandResponse& output) {
    constexpr int TimeoutMili = 200;
    constexpr int MaxTries = 9;
    int tries = 0;

    do {
        int result = SDL_hid_read_timeout(hidapi_handle->handle, reinterpret_cast<u8*>(&output),
                                          sizeof(MCUCommandResponse), TimeoutMili);

        if (result < 1) {
            LOG_ERROR(Input, "No response from joycon attempt {}", tries);
        }
        if (tries++ > MaxTries) {
            return Common::Input::DriverResult::Timeout;
        }
    } while (output.input_report.report_mode != report_mode ||
             output.mcu_report == MCUReport::EmptyAwaitingCmd);

    return Common::Input::DriverResult::Success;
}

Common::Input::DriverResult JoyconCommonProtocol::SendMCUData(ReportMode report_mode,
                                                              MCUSubCommand sc,
                                                              std::span<const u8> buffer,
                                                              MCUCommandResponse& output) {
    SubCommandPacket packet{
        .output_report = OutputReport::MCU_DATA,
        .packet_counter = GetCounter(),
        .mcu_sub_command = sc,
        .command_data = {},
    };

    if (buffer.size() > packet.command_data.size()) {
        return Common::Input::DriverResult::InvalidParameters;
    }

    memcpy(packet.command_data.data(), buffer.data(), buffer.size());

    auto result = SendData(packet);

    if (result != Common::Input::DriverResult::Success) {
        return result;
    }

    result = GetMCUDataResponse(report_mode, output);

    return Common::Input::DriverResult::Success;
}

Common::Input::DriverResult JoyconCommonProtocol::WaitSetMCUMode(ReportMode report_mode,
                                                                 MCUMode mode) {
    MCUCommandResponse output{};
    constexpr std::size_t MaxTries{16};
    std::size_t tries{};

    do {
        const auto result = SendMCUData(report_mode, MCUSubCommand::SetDeviceMode, {}, output);

        if (result != Common::Input::DriverResult::Success) {
            return result;
        }

        if (tries++ > MaxTries) {
            return Common::Input::DriverResult::WrongReply;
        }
    } while (output.mcu_report != MCUReport::StateReport ||
             output.mcu_data[6] != static_cast<u8>(mode));

    return Common::Input::DriverResult::Success;
}

// crc-8-ccitt / polynomial 0x07 look up table
constexpr std::array<u8, 256> mcu_crc8_table = {
    0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
    0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
    0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
    0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
    0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
    0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
    0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
    0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
    0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
    0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
    0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
    0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
    0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
    0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
    0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
    0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3};

u8 JoyconCommonProtocol::CalculateMCU_CRC8(u8* buffer, u8 size) const {
    u8 crc8 = 0x0;

    for (int i = 0; i < size; ++i) {
        crc8 = mcu_crc8_table[static_cast<u8>(crc8 ^ buffer[i])];
    }
    return crc8;
}

} // namespace InputCommon::Joycon


code:
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

// Based on dkms-hid-nintendo implementation, CTCaer joycon toolkit and dekuNukem reverse
// engineering https://github.com/nicman23/dkms-hid-nintendo/blob/master/src/hid-nintendo.c
// https://github.com/CTCaer/jc_toolkit
// https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering

#pragma once

#include <memory>
#include <span>
#include <vector>

#include "common/common_types.h"
#include "input_common/helpers/joycon_protocol/joycon_types.h"

namespace InputCommon::Joycon {

/// Joycon driver functions that handle low level communication
class JoyconCommonProtocol {
public:
    explicit JoyconCommonProtocol(std::shared_ptr<JoyconHandle> hidapi_handle_);

    /**
     * Sets handle to blocking. In blocking mode, SDL_hid_read() will wait (block) until there is
     * data to read before returning.
     */
    void SetBlocking();

    /**
     * Sets handle to non blocking. In non-blocking mode calls to SDL_hid_read() will return
     * immediately with a value of 0 if there is no data to be read
     */
    void SetNonBlocking();

    /**
     * Sends a request to obtain the joycon type from device
     * @returns controller type of the joycon
     */
    Common::Input::DriverResult GetDeviceType(ControllerType& controller_type);

    /**
     * Verifies and sets the joycon_handle if device is valid
     * @param device info from the driver
     * @returns success if the device is valid
     */
    Common::Input::DriverResult CheckDeviceAccess(SDL_hid_device_info* device);

    /**
     * Sends a request to set the polling mode of the joycon
     * @param report_mode polling mode to be set
     */
    Common::Input::DriverResult SetReportMode(Joycon::ReportMode report_mode);

    /**
     * Sends data to the joycon device
     * @param buffer data to be send
     */
    Common::Input::DriverResult SendRawData(std::span<const u8> buffer);

    template <typename Output>
        requires std::is_trivially_copyable_v<Output>
    Common::Input::DriverResult SendData(const Output& output) {
        std::array<u8, sizeof(Output)> buffer;
        std::memcpy(buffer.data(), &output, sizeof(Output));
        return SendRawData(buffer);
    }

    /**
     * Waits for incoming data of the joycon device that matches the subcommand
     * @param sub_command type of data to be returned
     * @returns a buffer containing the response
     */
    Common::Input::DriverResult GetSubCommandResponse(SubCommand sub_command,
                                                      SubCommandResponse& output);

    /**
     * Sends a sub command to the device and waits for it's reply
     * @param sc sub command to be send
     * @param buffer data to be send
     * @returns output buffer containing the response
     */
    Common::Input::DriverResult SendSubCommand(SubCommand sc, std::span<const u8> buffer,
                                               SubCommandResponse& output);

    /**
     * Sends a sub command to the device and waits for it's reply and ignores the output
     * @param sc sub command to be send
     * @param buffer data to be send
     */
    Common::Input::DriverResult SendSubCommand(SubCommand sc, std::span<const u8> buffer);

    /**
     * Sends a mcu command to the device
     * @param sc sub command to be send
     * @param buffer data to be send
     */
    Common::Input::DriverResult SendMCUCommand(SubCommand sc, std::span<const u8> buffer);

    /**
     * Sends vibration data to the joycon
     * @param buffer data to be send
     */
    Common::Input::DriverResult SendVibrationReport(std::span<const u8> buffer);

    /**
     * Reads the SPI memory stored on the joycon
     * @param Initial address location
     * @returns output buffer containing the response
     */
    Common::Input::DriverResult ReadRawSPI(SpiAddress addr, std::span<u8> output);

    /**
     * Reads the SPI memory stored on the joycon
     * @param Initial address location
     * @returns output object containing the response
     */
    template <typename Output>
        requires std::is_trivially_copyable_v<Output>
    Common::Input::DriverResult ReadSPI(SpiAddress addr, Output& output) {
        std::array<u8, sizeof(Output)> buffer;
        output = {};

        const auto result = ReadRawSPI(addr, buffer);
        if (result != Common::Input::DriverResult::Success) {
            return result;
        }

        std::memcpy(&output, buffer.data(), sizeof(Output));
        return Common::Input::DriverResult::Success;
    }

    /**
     * Enables MCU chip on the joycon
     * @param enable if true the chip will be enabled
     */
    Common::Input::DriverResult EnableMCU(bool enable);

    /**
     * Configures the MCU to the corresponding mode
     * @param MCUConfig configuration
     */
    Common::Input::DriverResult ConfigureMCU(const MCUConfig& config);

    /**
     * Waits until there's MCU data available. On timeout returns error
     * @param report mode of the expected reply
     * @returns a buffer containing the response
     */
    Common::Input::DriverResult GetMCUDataResponse(ReportMode report_mode_,
                                                   MCUCommandResponse& output);

    /**
     * Sends data to the MCU chip and waits for it's reply
     * @param report mode of the expected reply
     * @param sub command to be send
     * @param buffer data to be send
     * @returns output buffer containing the response
     */
    Common::Input::DriverResult SendMCUData(ReportMode report_mode, MCUSubCommand sc,
                                            std::span<const u8> buffer, MCUCommandResponse& output);

    /**
     * Wait's until the MCU chip is on the specified mode
     * @param report mode of the expected reply
     * @param MCUMode configuration
     */
    Common::Input::DriverResult WaitSetMCUMode(ReportMode report_mode, MCUMode mode);

    /**
     * Calculates the checksum from the MCU data
     * @param buffer containing the data to be send
     * @param size of the buffer in bytes
     * @returns byte with the correct checksum
     */
    u8 CalculateMCU_CRC8(u8* buffer, u8 size) const;

private:
    /**
     * Increments and returns the packet counter of the handle
     * @param joycon_handle device to send the data
     * @returns packet counter value
     */
    u8 GetCounter();

    std::shared_ptr<JoyconHandle> hidapi_handle;
};

class ScopedSetBlocking {
public:
    explicit ScopedSetBlocking(JoyconCommonProtocol* self) : m_self{self} {
        m_self->SetBlocking();
    }

    ~ScopedSetBlocking() {
        m_self->SetNonBlocking();
    }

private:
    JoyconCommonProtocol* m_self{};
};
} // namespace InputCommon::Joycon

repo_name: litucks/torzu

license: mit


code:
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "common/input.h"
#include "common/logging/log.h"
#include "input_common/helpers/joycon_protocol/generic_functions.h"

namespace InputCommon::Joycon {

GenericProtocol::GenericProtocol(std::shared_ptr<JoyconHandle> handle)
    : JoyconCommonProtocol(std::move(handle)) {}

Common::Input::DriverResult GenericProtocol::EnablePassiveMode() {
    ScopedSetBlocking sb(this);
    return SetReportMode(ReportMode::SIMPLE_HID_MODE);
}

Common::Input::DriverResult GenericProtocol::EnableActiveMode() {
    ScopedSetBlocking sb(this);
    return SetReportMode(ReportMode::STANDARD_FULL_60HZ);
}

Common::Input::DriverResult GenericProtocol::SetLowPowerMode(bool enable) {
    ScopedSetBlocking sb(this);
    const std::array<u8, 1> buffer{static_cast<u8>(enable ? 1 : 0)};
    return SendSubCommand(SubCommand::LOW_POWER_MODE, buffer);
}

Common::Input::DriverResult GenericProtocol::TriggersElapsed() {
    ScopedSetBlocking sb(this);
    return SendSubCommand(SubCommand::TRIGGERS_ELAPSED, {});
}

Common::Input::DriverResult GenericProtocol::GetDeviceInfo(DeviceInfo& device_info) {
    ScopedSetBlocking sb(this);
    SubCommandResponse output{};

    const auto result = SendSubCommand(SubCommand::REQ_DEV_INFO, {}, output);

    device_info = {};
    if (result == Common::Input::DriverResult::Success) {
        device_info = output.device_info;
    }

    return result;
}

Common::Input::DriverResult GenericProtocol::GetControllerType(ControllerType& controller_type) {
    return GetDeviceType(controller_type);
}

Common::Input::DriverResult GenericProtocol::EnableImu(bool enable) {
    ScopedSetBlocking sb(this);
    const std::array<u8, 1> buffer{static_cast<u8>(enable ? 1 : 0)};
    return SendSubCommand(SubCommand::ENABLE_IMU, buffer);
}

Common::Input::DriverResult GenericProtocol::SetImuConfig(GyroSensitivity gsen,
                                                          GyroPerformance gfrec,
                                                          AccelerometerSensitivity asen,
                                                          AccelerometerPerformance afrec) {
    ScopedSetBlocking sb(this);
    const std::array<u8, 4> buffer{static_cast<u8>(gsen), static_cast<u8>(asen),
                                   static_cast<u8>(gfrec), static_cast<u8>(afrec)};
    return SendSubCommand(SubCommand::SET_IMU_SENSITIVITY, buffer);
}

Common::Input::DriverResult GenericProtocol::GetBattery(u32& battery_level) {
    // This function is meant to request the high resolution battery status
    battery_level = 0;
    return Common::Input::DriverResult::NotSupported;
}

Common::Input::DriverResult GenericProtocol::GetColor(Color& color) {
    ScopedSetBlocking sb(this);
    std::array<u8, 12> buffer{};
    const auto result = ReadRawSPI(SpiAddress::COLOR_DATA, buffer);

    color = {};
    if (result == Common::Input::DriverResult::Success) {
        color.body = static_cast<u32>((buffer[0] << 16) | (buffer[1] << 8) | buffer[2]);
        color.buttons = static_cast<u32>((buffer[3] << 16) | (buffer[4] << 8) | buffer[5]);
        color.left_grip = static_cast<u32>((buffer[6] << 16) | (buffer[7] << 8) | buffer[8]);
        color.right_grip = static_cast<u32>((buffer[9] << 16) | (buffer[10] << 8) | buffer[11]);
    }

    return result;
}

Common::Input::DriverResult GenericProtocol::GetSerialNumber(SerialNumber& serial_number) {
    ScopedSetBlocking sb(this);
    std::array<u8, 16> buffer{};
    const auto result = ReadRawSPI(SpiAddress::SERIAL_NUMBER, buffer);

    serial_number = {};
    if (result == Common::Input::DriverResult::Success) {
        memcpy(serial_number.data(), buffer.data() + 1, sizeof(SerialNumber));
    }

    return result;
}

Common::Input::DriverResult GenericProtocol::GetTemperature(u32& temperature) {
    // Not all devices have temperature sensor
    temperature = 25;
    return Common::Input::DriverResult::NotSupported;
}

Common::Input::DriverResult GenericProtocol::GetVersionNumber(FirmwareVersion& version) {
    DeviceInfo device_info{};

    const auto result = GetDeviceInfo(device_info);
    version = device_info.firmware;

    return result;
}

Common::Input::DriverResult GenericProtocol::SetHomeLight() {
    ScopedSetBlocking sb(this);
    static constexpr std::array<u8, 3> buffer{0x0f, 0xf0, 0x00};
    return SendSubCommand(SubCommand::SET_HOME_LIGHT, buffer);
}

Common::Input::DriverResult GenericProtocol::SetLedBusy() {
    return Common::Input::DriverResult::NotSupported;
}

Common::Input::DriverResult GenericProtocol::SetLedPattern(u8 leds) {
    ScopedSetBlocking sb(this);
    const std::array<u8, 1> buffer{leds};
    return SendSubCommand(SubCommand::SET_PLAYER_LIGHTS, buffer);
}

Common::Input::DriverResult GenericProtocol::SetLedBlinkPattern(u8 leds) {
    return SetLedPattern(static_cast<u8>(leds << 4));
}

} // namespace InputCommon::Joycon


code:
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

// Based on dkms-hid-nintendo implementation, CTCaer joycon toolkit and dekuNukem reverse
// engineering https://github.com/nicman23/dkms-hid-nintendo/blob/master/src/hid-nintendo.c
// https://github.com/CTCaer/jc_toolkit
// https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering

#pragma once

#include "input_common/helpers/joycon_protocol/common_protocol.h"
#include "input_common/helpers/joycon_protocol/joycon_types.h"

namespace Common::Input {
enum class DriverResult;
}

namespace InputCommon::Joycon {

/// Joycon driver functions that easily implemented
class GenericProtocol final : private JoyconCommonProtocol {
public:
    explicit GenericProtocol(std::shared_ptr<JoyconHandle> handle);

    /// Enables passive mode. This mode only sends button data on change. Sticks will return digital
    /// data instead of analog. Motion will be disabled
    Common::Input::DriverResult EnablePassiveMode();

    /// Enables active mode. This mode will return the current status every 5-15ms
    Common::Input::DriverResult EnableActiveMode();

    /// Enables or disables the low power mode
    Common::Input::DriverResult SetLowPowerMode(bool enable);

    /// Unknown function used by the switch
    Common::Input::DriverResult TriggersElapsed();

    /**
     * Sends a request to obtain the joycon firmware and mac from handle
     * @returns controller device info
     */
    Common::Input::DriverResult GetDeviceInfo(DeviceInfo& controller_type);

    /**
     * Sends a request to obtain the joycon type from handle
     * @returns controller type of the joycon
     */
    Common::Input::DriverResult GetControllerType(ControllerType& controller_type);

    /**
     * Enables motion input
     * @param enable if true motion data will be enabled
     */
    Common::Input::DriverResult EnableImu(bool enable);

    /**
     * Configures the motion sensor with the specified parameters
     * @param gsen gyroscope sensor sensitivity in degrees per second
     * @param gfrec gyroscope sensor frequency in hertz
     * @param asen accelerometer sensitivity in G force
     * @param afrec accelerometer frequency in hertz
     */
    Common::Input::DriverResult SetImuConfig(GyroSensitivity gsen, GyroPerformance gfrec,
                                             AccelerometerSensitivity asen,
                                             AccelerometerPerformance afrec);

    /**
     * Request battery level from the device
     * @returns battery level
     */
    Common::Input::DriverResult GetBattery(u32& battery_level);

    /**
     * Request joycon colors from the device
     * @returns colors of the body and buttons
     */
    Common::Input::DriverResult GetColor(Color& color);

    /**
     * Request joycon serial number from the device
     * @returns 16 byte serial number
     */
    Common::Input::DriverResult GetSerialNumber(SerialNumber& serial_number);

    /**
     * Request joycon serial number from the device
     * @returns 16 byte serial number
     */
    Common::Input::DriverResult GetTemperature(u32& temperature);

    /**
     * Request joycon serial number from the device
     * @returns 16 byte serial number
     */
    Common::Input::DriverResult GetVersionNumber(FirmwareVersion& version);

    /**
     * Sets home led behaviour
     */
    Common::Input::DriverResult SetHomeLight();

    /**
     * Sets home led into a slow breathing state
     */
    Common::Input::DriverResult SetLedBusy();

    /**
     * Sets the 4 player leds on the joycon on a solid state
     * @params bit flag containing the led state
     */
    Common::Input::DriverResult SetLedPattern(u8 leds);

    /**
     * Sets the 4 player leds on the joycon on a blinking state
     * @returns bit flag containing the led state
     */
    Common::Input::DriverResult SetLedBlinkPattern(u8 leds);
};
} // namespace InputCommon::Joycon


code:
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "common/input.h"
#include "common/logging/log.h"
#include "input_common/helpers/joycon_protocol/irs.h"

namespace InputCommon::Joycon {

IrsProtocol::IrsProtocol(std::shared_ptr<JoyconHandle> handle)
    : JoyconCommonProtocol(std::move(handle)) {}

Common::Input::DriverResult IrsProtocol::EnableIrs() {
    LOG_INFO(Input, "Enable IRS");
    ScopedSetBlocking sb(this);
    Common::Input::DriverResult result{Common::Input::DriverResult::Success};

    if (result == Common::Input::DriverResult::Success) {
        result = SetReportMode(ReportMode::NFC_IR_MODE_60HZ);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = EnableMCU(true);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitSetMCUMode(ReportMode::NFC_IR_MODE_60HZ, MCUMode::Standby);
    }
    if (result == Common::Input::DriverResult::Success) {
        const MCUConfig config{
            .command = MCUCommand::ConfigureMCU,
            .sub_command = MCUSubCommand::SetMCUMode,
            .mode = MCUMode::IR,
            .crc = {},
        };

        result = ConfigureMCU(config);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitSetMCUMode(ReportMode::NFC_IR_MODE_60HZ, MCUMode::IR);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = ConfigureIrs();
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WriteRegistersStep1();
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WriteRegistersStep2();
    }

    is_enabled = true;

    return result;
}

Common::Input::DriverResult IrsProtocol::DisableIrs() {
    LOG_DEBUG(Input, "Disable IRS");
    ScopedSetBlocking sb(this);
    Common::Input::DriverResult result{Common::Input::DriverResult::Success};

    if (result == Common::Input::DriverResult::Success) {
        result = EnableMCU(false);
    }

    is_enabled = false;

    return result;
}

Common::Input::DriverResult IrsProtocol::SetIrsConfig(IrsMode mode, IrsResolution format) {
    irs_mode = mode;
    switch (format) {
    case IrsResolution::Size320x240:
        resolution_code = IrsResolutionCode::Size320x240;
        fragments = IrsFragments::Size320x240;
        resolution = IrsResolution::Size320x240;
        break;
    case IrsResolution::Size160x120:
        resolution_code = IrsResolutionCode::Size160x120;
        fragments = IrsFragments::Size160x120;
        resolution = IrsResolution::Size160x120;
        break;
    case IrsResolution::Size80x60:
        resolution_code = IrsResolutionCode::Size80x60;
        fragments = IrsFragments::Size80x60;
        resolution = IrsResolution::Size80x60;
        break;
    case IrsResolution::Size20x15:
        resolution_code = IrsResolutionCode::Size20x15;
        fragments = IrsFragments::Size20x15;
        resolution = IrsResolution::Size20x15;
        break;
    case IrsResolution::Size40x30:
    default:
        resolution_code = IrsResolutionCode::Size40x30;
        fragments = IrsFragments::Size40x30;
        resolution = IrsResolution::Size40x30;
        break;
    }

    // Restart feature
    if (is_enabled) {
        DisableIrs();
        return EnableIrs();
    }

    return Common::Input::DriverResult::Success;
}

Common::Input::DriverResult IrsProtocol::RequestImage(std::span<u8> buffer) {
    const u8 next_packet_fragment =
        static_cast<u8>((packet_fragment + 1) % (static_cast<u8>(fragments) + 1));

    if (buffer[0] == 0x31 && buffer[49] == 0x03) {
        u8 new_packet_fragment = buffer[52];
        if (new_packet_fragment == next_packet_fragment) {
            packet_fragment = next_packet_fragment;
            memcpy(buf_image.data() + (300 * packet_fragment), buffer.data() + 59, 300);

            return RequestFrame(packet_fragment);
        }

        if (new_packet_fragment == packet_fragment) {
            return RequestFrame(packet_fragment);
        }

        return ResendFrame(next_packet_fragment);
    }

    return RequestFrame(packet_fragment);
}

Common::Input::DriverResult IrsProtocol::ConfigureIrs() {
    LOG_DEBUG(Input, "Configure IRS");
    constexpr std::size_t max_tries = 28;
    SubCommandResponse output{};
    std::size_t tries = 0;

    const IrsConfigure irs_configuration{
        .command = MCUCommand::ConfigureIR,
        .sub_command = MCUSubCommand::SetDeviceMode,
        .irs_mode = IrsMode::ImageTransfer,
        .number_of_fragments = fragments,
        .mcu_major_version = 0x0500,
        .mcu_minor_version = 0x1800,
        .crc = {},
    };
    buf_image.resize((static_cast<u8>(fragments) + 1) * 300);

    std::array<u8, sizeof(IrsConfigure)> request_data{};
    memcpy(request_data.data(), &irs_configuration, sizeof(IrsConfigure));
    request_data[37] = CalculateMCU_CRC8(request_data.data() + 1, 36);
    do {
        const auto result = SendSubCommand(SubCommand::SET_MCU_CONFIG, request_data, output);

        if (result != Common::Input::DriverResult::Success) {
            return result;
        }
        if (tries++ >= max_tries) {
            return Common::Input::DriverResult::WrongReply;
        }
    } while (output.command_data[0] != 0x0b);

    return Common::Input::DriverResult::Success;
}

Common::Input::DriverResult IrsProtocol::WriteRegistersStep1() {
    LOG_DEBUG(Input, "WriteRegistersStep1");
    Common::Input::DriverResult result{Common::Input::DriverResult::Success};
    constexpr std::size_t max_tries = 28;
    SubCommandResponse output{};
    std::size_t tries = 0;

    const IrsWriteRegisters irs_registers{
        .command = MCUCommand::ConfigureIR,
        .sub_command = MCUSubCommand::WriteDeviceRegisters,
        .number_of_registers = 0x9,
        .registers =
            {
                IrsRegister{IrRegistersAddress::Resolution, static_cast<u8>(resolution_code)},
                {IrRegistersAddress::ExposureLSB, static_cast<u8>(exposure & 0xff)},
                {IrRegistersAddress::ExposureMSB, static_cast<u8>(exposure >> 8)},
                {IrRegistersAddress::ExposureTime, 0x00},
                {IrRegistersAddress::Leds, static_cast<u8>(leds)},
                {IrRegistersAddress::DigitalGainLSB, static_cast<u8>((digital_gain & 0x0f) << 4)},
                {IrRegistersAddress::DigitalGainMSB, static_cast<u8>((digital_gain & 0xf0) >> 4)},
                {IrRegistersAddress::LedFilter, static_cast<u8>(led_filter)},
                {IrRegistersAddress::WhitePixelThreshold, 0xc8},
            },
        .crc = {},
    };

    std::array<u8, sizeof(IrsWriteRegisters)> request_data{};
    memcpy(request_data.data(), &irs_registers, sizeof(IrsWriteRegisters));
    request_data[37] = CalculateMCU_CRC8(request_data.data() + 1, 36);

    std::array<u8, 38> mcu_request{0x02};
    mcu_request[36] = CalculateMCU_CRC8(mcu_request.data(), 36);
    mcu_request[37] = 0xFF;

    if (result != Common::Input::DriverResult::Success) {
        return result;
    }

    do {
        result = SendSubCommand(SubCommand::SET_MCU_CONFIG, request_data, output);

        // First time we need to set the report mode
        if (result == Common::Input::DriverResult::Success && tries == 0) {
            result = SendMCUCommand(SubCommand::SET_REPORT_MODE, mcu_request);
        }
        if (result == Common::Input::DriverResult::Success && tries == 0) {
            GetSubCommandResponse(SubCommand::SET_MCU_CONFIG, output);
        }

        if (result != Common::Input::DriverResult::Success) {
            return result;
        }
        if (tries++ >= max_tries) {
            return Common::Input::DriverResult::WrongReply;
        }
    } while (!(output.command_data[0] == 0x13 && output.command_data[2] == 0x07) &&
             output.command_data[0] != 0x23);

    return Common::Input::DriverResult::Success;
}

Common::Input::DriverResult IrsProtocol::WriteRegistersStep2() {
    LOG_DEBUG(Input, "WriteRegistersStep2");
    constexpr std::size_t max_tries = 28;
    SubCommandResponse output{};
    std::size_t tries = 0;

    const IrsWriteRegisters irs_registers{
        .command = MCUCommand::ConfigureIR,
        .sub_command = MCUSubCommand::WriteDeviceRegisters,
        .number_of_registers = 0x8,
        .registers =
            {
                IrsRegister{IrRegistersAddress::LedIntensityMSB,
                            static_cast<u8>(led_intensity >> 8)},
                {IrRegistersAddress::LedIntensityLSB, static_cast<u8>(led_intensity & 0xff)},
                {IrRegistersAddress::ImageFlip, static_cast<u8>(image_flip)},
                {IrRegistersAddress::DenoiseSmoothing, static_cast<u8>((denoise >> 16) & 0xff)},
                {IrRegistersAddress::DenoiseEdge, static_cast<u8>((denoise >> 8) & 0xff)},
                {IrRegistersAddress::DenoiseColor, static_cast<u8>(denoise & 0xff)},
                {IrRegistersAddress::UpdateTime, 0x2d},
                {IrRegistersAddress::FinalizeConfig, 0x01},
            },
        .crc = {},
    };

    std::array<u8, sizeof(IrsWriteRegisters)> request_data{};
    memcpy(request_data.data(), &irs_registers, sizeof(IrsWriteRegisters));
    request_data[37] = CalculateMCU_CRC8(request_data.data() + 1, 36);
    do {
        const auto result = SendSubCommand(SubCommand::SET_MCU_CONFIG, request_data, output);

        if (result != Common::Input::DriverResult::Success) {
            return result;
        }
        if (tries++ >= max_tries) {
            return Common::Input::DriverResult::WrongReply;
        }
    } while (output.command_data[0] != 0x13 && output.command_data[0] != 0x23);

    return Common::Input::DriverResult::Success;
}

Common::Input::DriverResult IrsProtocol::RequestFrame(u8 frame) {
    std::array<u8, 38> mcu_request{};
    mcu_request[3] = frame;
    mcu_request[36] = CalculateMCU_CRC8(mcu_request.data(), 36);
    mcu_request[37] = 0xFF;
    return SendMCUCommand(SubCommand::SET_REPORT_MODE, mcu_request);
}

Common::Input::DriverResult IrsProtocol::ResendFrame(u8 frame) {
    std::array<u8, 38> mcu_request{};
    mcu_request[1] = 0x1;
    mcu_request[2] = frame;
    mcu_request[3] = 0x0;
    mcu_request[36] = CalculateMCU_CRC8(mcu_request.data(), 36);
    mcu_request[37] = 0xFF;
    return SendMCUCommand(SubCommand::SET_REPORT_MODE, mcu_request);
}

std::vector<u8> IrsProtocol::GetImage() const {
    return buf_image;
}

IrsResolution IrsProtocol::GetIrsFormat() const {
    return resolution;
}

bool IrsProtocol::IsEnabled() const {
    return is_enabled;
}

} // namespace InputCommon::Joycon


code:
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

// Based on dkms-hid-nintendo implementation, CTCaer joycon toolkit and dekuNukem reverse
// engineering https://github.com/nicman23/dkms-hid-nintendo/blob/master/src/hid-nintendo.c
// https://github.com/CTCaer/jc_toolkit
// https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering

#pragma once

#include <vector>

#include "input_common/helpers/joycon_protocol/common_protocol.h"
#include "input_common/helpers/joycon_protocol/joycon_types.h"

namespace Common::Input {
enum class DriverResult;
}

namespace InputCommon::Joycon {

class IrsProtocol final : private JoyconCommonProtocol {
public:
    explicit IrsProtocol(std::shared_ptr<JoyconHandle> handle);

    Common::Input::DriverResult EnableIrs();

    Common::Input::DriverResult DisableIrs();

    Common::Input::DriverResult SetIrsConfig(IrsMode mode, IrsResolution format);

    Common::Input::DriverResult RequestImage(std::span<u8> buffer);

    std::vector<u8> GetImage() const;

    IrsResolution GetIrsFormat() const;

    bool IsEnabled() const;

private:
    Common::Input::DriverResult ConfigureIrs();

    Common::Input::DriverResult WriteRegistersStep1();
    Common::Input::DriverResult WriteRegistersStep2();

    Common::Input::DriverResult RequestFrame(u8 frame);
    Common::Input::DriverResult ResendFrame(u8 frame);

    IrsMode irs_mode{IrsMode::ImageTransfer};
    IrsResolution resolution{IrsResolution::Size40x30};
    IrsResolutionCode resolution_code{IrsResolutionCode::Size40x30};
    IrsFragments fragments{IrsFragments::Size40x30};
    IrLeds leds{IrLeds::BrightAndDim};
    IrExLedFilter led_filter{IrExLedFilter::Enabled};
    IrImageFlip image_flip{IrImageFlip::Normal};
    u8 digital_gain{0x01};
    u16 exposure{0x2490};
    u16 led_intensity{0x0f10};
    u32 denoise{0x012344};

    u8 packet_fragment{};
    std::vector<u8> buf_image; // 8bpp greyscale image.

    bool is_enabled{};
};

} // namespace InputCommon::Joycon


code:
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

// Based on dkms-hid-nintendo implementation, CTCaer joycon toolkit and dekuNukem reverse
// engineering https://github.com/nicman23/dkms-hid-nintendo/blob/master/src/hid-nintendo.c
// https://github.com/CTCaer/jc_toolkit
// https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering

#pragma once

#include <array>
#include <functional>
#include <SDL_hidapi.h>

#include "common/bit_field.h"
#include "common/common_funcs.h"
#include "common/common_types.h"

namespace InputCommon::Joycon {
constexpr u32 MaxErrorCount = 50;
constexpr u32 MaxBufferSize = 368;
constexpr std::array<u8, 8> DefaultVibrationBuffer{0x0, 0x1, 0x40, 0x40, 0x0, 0x1, 0x40, 0x40};

using MacAddress = std::array<u8, 6>;
using SerialNumber = std::array<u8, 15>;
using TagUUID = std::array<u8, 7>;
using MifareUUID = std::array<u8, 4>;

enum class ControllerType : u8 {
    None = 0x00,
    Left = 0x01,
    Right = 0x02,
    Pro = 0x03,
    Dual = 0x05, // TODO: Verify this id
    LarkHvc1 = 0x07,
    LarkHvc2 = 0x08,
    LarkNesLeft = 0x09,
    LarkNesRight = 0x0A,
    Lucia = 0x0B,
    Lagon = 0x0C,
    Lager = 0x0D,
};

enum class PadAxes {
    LeftStickX,
    LeftStickY,
    RightStickX,
    RightStickY,
    Undefined,
};

enum class PadMotion {
    LeftMotion,
    RightMotion,
    Undefined,
};

enum class PadButton : u32 {
    Down = 0x000001,
    Up = 0x000002,
    Right = 0x000004,
    Left = 0x000008,
    LeftSR = 0x000010,
    LeftSL = 0x000020,
    L = 0x000040,
    ZL = 0x000080,
    Y = 0x000100,
    X = 0x000200,
    B = 0x000400,
    A = 0x000800,
    RightSR = 0x001000,
    RightSL = 0x002000,
    R = 0x004000,
    ZR = 0x008000,
    Minus = 0x010000,
    Plus = 0x020000,
    StickR = 0x040000,
    StickL = 0x080000,
    Home = 0x100000,
    Capture = 0x200000,
};

enum class PassivePadButton : u32 {
    Down_A = 0x0001,
    Right_X = 0x0002,
    Left_B = 0x0004,
    Up_Y = 0x0008,
    SL = 0x0010,
    SR = 0x0020,
    Minus = 0x0100,
    Plus = 0x0200,
    StickL = 0x0400,
    StickR = 0x0800,
    Home = 0x1000,
    Capture = 0x2000,
    L_R = 0x4000,
    ZL_ZR = 0x8000,
};

enum class PassivePadStick : u8 {
    Right = 0x00,
    RightDown = 0x01,
    Down = 0x02,
    DownLeft = 0x03,
    Left = 0x04,
    LeftUp = 0x05,
    Up = 0x06,
    UpRight = 0x07,
    Neutral = 0x08,
};

enum class OutputReport : u8 {
    RUMBLE_AND_SUBCMD = 0x01,
    FW_UPDATE_PKT = 0x03,
    RUMBLE_ONLY = 0x10,
    MCU_DATA = 0x11,
    USB_CMD = 0x80,
};

enum class FeatureReport : u8 {
    Last_SUBCMD = 0x02,
    OTA_GW_UPGRADE = 0x70,
    SETUP_MEM_READ = 0x71,
    MEM_READ = 0x72,
    ERASE_MEM_SECTOR = 0x73,
    MEM_WRITE = 0x74,
    LAUNCH = 0x75,
};

enum class SubCommand : u8 {
    STATE = 0x00,
    MANUAL_BT_PAIRING = 0x01,
    REQ_DEV_INFO = 0x02,
    SET_REPORT_MODE = 0x03,
    TRIGGERS_ELAPSED = 0x04,
    GET_PAGE_LIST_STATE = 0x05,
    SET_HCI_STATE = 0x06,
    RESET_PAIRING_INFO = 0x07,
    LOW_POWER_MODE = 0x08,
    SPI_FLASH_READ = 0x10,
    SPI_FLASH_WRITE = 0x11,
    SPI_SECTOR_ERASE = 0x12,
    RESET_MCU = 0x20,
    SET_MCU_CONFIG = 0x21,
    SET_MCU_STATE = 0x22,
    SET_PLAYER_LIGHTS = 0x30,
    GET_PLAYER_LIGHTS = 0x31,
    SET_HOME_LIGHT = 0x38,
    ENABLE_IMU = 0x40,
    SET_IMU_SENSITIVITY = 0x41,
    WRITE_IMU_REG = 0x42,
    READ_IMU_REG = 0x43,
    ENABLE_VIBRATION = 0x48,
    GET_REGULATED_VOLTAGE = 0x50,
    SET_EXTERNAL_CONFIG = 0x58,
    GET_EXTERNAL_DEVICE_INFO = 0x59,
    ENABLE_EXTERNAL_POLLING = 0x5A,
    DISABLE_EXTERNAL_POLLING = 0x5B,
    SET_EXTERNAL_FORMAT_CONFIG = 0x5C,
};

enum class UsbSubCommand : u8 {
    CONN_STATUS = 0x01,
    HADSHAKE = 0x02,
    BAUDRATE_3M = 0x03,
    NO_TIMEOUT = 0x04,
    EN_TIMEOUT = 0x05,
    RESET = 0x06,
    PRE_HANDSHAKE = 0x91,
    SEND_UART = 0x92,
};

enum class CalibrationMagic : u8 {
    USR_MAGIC_0 = 0xB2,
    USR_MAGIC_1 = 0xA1,
};

enum class SpiAddress : u16 {
    MAGIC = 0x0000,
    MAC_ADDRESS = 0x0015,
    PAIRING_INFO = 0x2000,
    SHIPMENT = 0x5000,
    SERIAL_NUMBER = 0x6000,
    DEVICE_TYPE = 0x6012,
    FORMAT_VERSION = 0x601B,
    FACT_IMU_DATA = 0x6020,
    FACT_LEFT_DATA = 0x603d,
    FACT_RIGHT_DATA = 0x6046,
    COLOR_DATA = 0x6050,
    DESIGN_VARIATION = 0x605C,
    SENSOR_DATA = 0x6080,
    USER_LEFT_MAGIC = 0x8010,
    USER_LEFT_DATA = 0x8012,
    USER_RIGHT_MAGIC = 0x801B,
    USER_RIGHT_DATA = 0x801D,
    USER_IMU_MAGIC = 0x8026,
    USER_IMU_DATA = 0x8028,
};

enum class ReportMode : u8 {
    ACTIVE_POLLING_NFC_IR_CAMERA_DATA = 0x00,
    ACTIVE_POLLING_NFC_IR_CAMERA_CONFIGURATION = 0x01,
    ACTIVE_POLLING_NFC_IR_CAMERA_DATA_CONFIGURATION = 0x02,
    ACTIVE_POLLING_IR_CAMERA_DATA = 0x03,
    SUBCMD_REPLY = 0x21,
    MCU_UPDATE_STATE = 0x23,
    STANDARD_FULL_60HZ = 0x30,
    NFC_IR_MODE_60HZ = 0x31,
    SIMPLE_HID_MODE = 0x3F,
    INPUT_USB_RESPONSE = 0x81,
};

enum class GyroSensitivity : u8 {
    DPS250,
    DPS500,
    DPS1000,
    DPS2000, // Default
};

enum class AccelerometerSensitivity : u8 {
    G8, // Default
    G4,
    G2,
    G16,
};

enum class GyroPerformance : u8 {
    HZ833,
    HZ208, // Default
};

enum class AccelerometerPerformance : u8 {
    HZ200,
    HZ100, // Default
};

enum class MCUCommand : u8 {
    ConfigureMCU = 0x21,
    ConfigureIR = 0x23,
};

enum class MCUSubCommand : u8 {
    SetMCUMode = 0x0,
    SetDeviceMode = 0x1,
    ReadDeviceMode = 0x02,
    WriteDeviceRegisters = 0x4,
};

enum class MCUMode : u8 {
    Suspend = 0,
    Standby = 1,
    Ringcon = 3,
    NFC = 4,
    IR = 5,
    MaybeFWUpdate = 6,
};

enum class MCURequest : u8 {
    GetMCUStatus = 1,
    GetNFCData = 2,
    GetIRData = 3,
};

enum class MCUReport : u8 {
    Empty = 0x00,
    StateReport = 0x01,
    IRData = 0x03,
    BusyInitializing = 0x0b,
    IRStatus = 0x13,
    IRRegisters = 0x1b,
    NFCState = 0x2a,
    NFCReadData = 0x3a,
    EmptyAwaitingCmd = 0xff,
};

enum class MCUPacketFlag : u8 {
    MorePacketsRemaining = 0x00,
    LastCommandPacket = 0x08,
};

enum class NFCCommand : u8 {
    CancelAll = 0x00,
    StartPolling = 0x01,
    StopPolling = 0x02,
    StartWaitingReceive = 0x04,
    ReadNtag = 0x06,
    WriteNtag = 0x08,
    Mifare = 0x0F,
};

enum class NFCTagType : u8 {
    AllTags = 0x00,
    Ntag215 = 0x01,
};

enum class NFCPages {
    Block0 = 0,
    Block3 = 3,
    Block45 = 45,
    Block135 = 135,
    Block231 = 231,
};

enum class NFCStatus : u8 {
    Ready = 0x00,
    Polling = 0x01,
    LastPackage = 0x04,
    WriteDone = 0x05,
    TagLost = 0x07,
    WriteReady = 0x09,
    MifareDone = 0x10,
};

enum class MifareCmd : u8 {
    None = 0x00,
    Read = 0x30,
    AuthA = 0x60,
    AuthB = 0x61,
    Write = 0xA0,
    Transfer = 0xB0,
    Decrement = 0xC0,
    Increment = 0xC1,
    Store = 0xC2
};

enum class IrsMode : u8 {
    None = 0x02,
    Moment = 0x03,
    Dpd = 0x04,
    Clustering = 0x06,
    ImageTransfer = 0x07,
    Silhouette = 0x08,
    TeraImage = 0x09,
    SilhouetteTeraImage = 0x0A,
};

enum class IrsResolution {
    Size320x240,
    Size160x120,
    Size80x60,
    Size40x30,
    Size20x15,
    None,
};

enum class IrsResolutionCode : u8 {
    Size320x240 = 0x00, // Full pixel array
    Size160x120 = 0x50, // Sensor Binning [2 X 2]
    Size80x60 = 0x64,   // Sensor Binning [4 x 2] and Skipping [1 x 2]
    Size40x30 = 0x69,   // Sensor Binning [4 x 2] and Skipping [2 x 4]
    Size20x15 = 0x6A,   // Sensor Binning [4 x 2] and Skipping [4 x 4]
};

// Size of image divided by 300
enum class IrsFragments : u8 {
    Size20x15 = 0x00,
    Size40x30 = 0x03,
    Size80x60 = 0x0f,
    Size160x120 = 0x3f,
    Size320x240 = 0xFF,
};

enum class IrLeds : u8 {
    BrightAndDim = 0x00,
    Bright = 0x20,
    Dim = 0x10,
    None = 0x30,
};

enum class IrExLedFilter : u8 {
    Disabled = 0x00,
    Enabled = 0x03,
};

enum class IrImageFlip : u8 {
    Normal = 0x00,
    Inverted = 0x02,
};

enum class IrRegistersAddress : u16 {
    UpdateTime = 0x0400,
    FinalizeConfig = 0x0700,
    LedFilter = 0x0e00,
    Leds = 0x1000,
    LedIntensityMSB = 0x1100,
    LedIntensityLSB = 0x1200,
    ImageFlip = 0x2d00,
    Resolution = 0x2e00,
    DigitalGainLSB = 0x2e01,
    DigitalGainMSB = 0x2f01,
    ExposureLSB = 0x3001,
    ExposureMSB = 0x3101,
    ExposureTime = 0x3201,
    WhitePixelThreshold = 0x4301,
    DenoiseSmoothing = 0x6701,
    DenoiseEdge = 0x6801,
    DenoiseColor = 0x6901,
};

enum class ExternalDeviceId : u16 {
    RingController = 0x2000,
    Starlink = 0x2800,
};

struct MotionSensorCalibration {
    s16 offset;
    s16 scale;
};

struct MotionCalibration {
    std::array<MotionSensorCalibration, 3> accelerometer;
    std::array<MotionSensorCalibration, 3> gyro;
};

// Basic motion data containing data from the sensors and a timestamp in microseconds
struct MotionData {
    float gyro_x{};
    float gyro_y{};
    float gyro_z{};
    float accel_x{};
    float accel_y{};
    float accel_z{};
    u64 delta_timestamp{};
};

// Output from SPI read command containing user calibration magic
struct MagicSpiCalibration {
    CalibrationMagic first;
    CalibrationMagic second;
};
static_assert(sizeof(MagicSpiCalibration) == 0x2, "MagicSpiCalibration is an invalid size");

// Output from SPI read command containing left joystick calibration
struct JoystickLeftSpiCalibration {
    std::array<u8, 3> max;
    std::array<u8, 3> center;
    std::array<u8, 3> min;
};
static_assert(sizeof(JoystickLeftSpiCalibration) == 0x9,
              "JoystickLeftSpiCalibration is an invalid size");

// Output from SPI read command containing right joystick calibration
struct JoystickRightSpiCalibration {
    std::array<u8, 3> center;
    std::array<u8, 3> min;
    std::array<u8, 3> max;
};
static_assert(sizeof(JoystickRightSpiCalibration) == 0x9,
              "JoystickRightSpiCalibration is an invalid size");

struct JoyStickAxisCalibration {
    u16 max;
    u16 min;
    u16 center;
};

struct JoyStickCalibration {
    JoyStickAxisCalibration x;
    JoyStickAxisCalibration y;
};

struct ImuSpiCalibration {
    std::array<s16, 3> accelerometer_offset;
    std::array<s16, 3> accelerometer_scale;
    std::array<s16, 3> gyroscope_offset;
    std::array<s16, 3> gyroscope_scale;
};
static_assert(sizeof(ImuSpiCalibration) == 0x18, "ImuSpiCalibration is an invalid size");

struct RingCalibration {
    s16 default_value;
    s16 max_value;
    s16 min_value;
};

struct Color {
    u32 body;
    u32 buttons;
    u32 left_grip;
    u32 right_grip;
};

struct Battery {
    union {
        u8 raw{};

        BitField<0, 4, u8> unknown;
        BitField<4, 1, u8> charging;
        BitField<5, 3, u8> status;
    };
};

struct VibrationValue {
    f32 low_amplitude;
    f32 low_frequency;
    f32 high_amplitude;
    f32 high_frequency;
};

struct JoyconHandle {
    SDL_hid_device* handle = nullptr;
    u8 packet_counter{};
};

struct MCUConfig {
    MCUCommand command;
    MCUSubCommand sub_command;
    MCUMode mode;
    INSERT_PADDING_BYTES(0x22);
    u8 crc;
};
static_assert(sizeof(MCUConfig) == 0x26, "MCUConfig is an invalid size");

#pragma pack(push, 1)
struct InputReportPassive {
    ReportMode report_mode;
    u16 button_input;
    u8 stick_state;
    std::array<u8, 10> unknown_data;
};
static_assert(sizeof(InputReportPassive) == 0xE, "InputReportPassive is an invalid size");

struct InputReportActive {
    ReportMode report_mode;
    u8 packet_id;
    Battery battery_status;
    std::array<u8, 3> button_input;
    std::array<u8, 3> left_stick_state;
    std::array<u8, 3> right_stick_state;
    u8 vibration_code;
    std::array<s16, 6 * 2> motion_input;
    INSERT_PADDING_BYTES(0x2);
    s16 ring_input;
};
static_assert(sizeof(InputReportActive) == 0x29, "InputReportActive is an invalid size");

struct InputReportNfcIr {
    ReportMode report_mode;
    u8 packet_id;
    Battery battery_status;
    std::array<u8, 3> button_input;
    std::array<u8, 3> left_stick_state;
    std::array<u8, 3> right_stick_state;
    u8 vibration_code;
    std::array<s16, 6 * 2> motion_input;
    INSERT_PADDING_BYTES(0x4);
};
static_assert(sizeof(InputReportNfcIr) == 0x29, "InputReportNfcIr is an invalid size");
#pragma pack(pop)

struct NFCReadBlock {
    u8 start;
    u8 end;
};
static_assert(sizeof(NFCReadBlock) == 0x2, "NFCReadBlock is an invalid size");

struct NFCReadBlockCommand {
    u8 block_count{};
    std::array<NFCReadBlock, 4> blocks{};
};
static_assert(sizeof(NFCReadBlockCommand) == 0x9, "NFCReadBlockCommand is an invalid size");

struct NFCReadCommandData {
    u8 unknown;
    u8 uuid_length;
    TagUUID uid;
    NFCTagType tag_type;
    NFCReadBlockCommand read_block;
};
static_assert(sizeof(NFCReadCommandData) == 0x13, "NFCReadCommandData is an invalid size");

#pragma pack(push, 1)
struct NFCWriteCommandData {
    u8 unknown;
    u8 uuid_length;
    TagUUID uid;
    NFCTagType tag_type;
    u8 unknown2;
    u8 unknown3;
    u8 unknown4;
    u8 unknown5;
    u8 unknown6;
    u8 unknown7;
    u8 unknown8;
    u8 magic;
    u16_be write_count;
    u8 amiibo_version;
};
static_assert(sizeof(NFCWriteCommandData) == 0x15, "NFCWriteCommandData is an invalid size");
#pragma pack(pop)

struct MifareCommandData {
    u8 unknown1;
    u8 unknown2;
    u8 number_of_short_bytes;
    MifareUUID uid;
};
static_assert(sizeof(MifareCommandData) == 0x7, "MifareCommandData is an invalid size");

struct NFCPollingCommandData {
    u8 enable_mifare;
    u8 unknown_1;
    u8 unknown_2;
    u8 unknown_3;
    u8 unknown_4;
};
static_assert(sizeof(NFCPollingCommandData) == 0x05, "NFCPollingCommandData is an invalid size");

struct NFCRequestState {
    NFCCommand command_argument;
    u8 block_id;
    u8 packet_id;
    MCUPacketFlag packet_flag;
    u8 data_length;
    union {
        std::array<u8, 0x1F> raw_data;
        NFCReadCommandData nfc_read;
        NFCPollingCommandData nfc_polling;
    };
    u8 crc;
    INSERT_PADDING_BYTES(0x1);
};
static_assert(sizeof(NFCRequestState) == 0x26, "NFCRequestState is an invalid size");

struct NFCDataChunk {
    u8 nfc_page;
    u8 data_size;
    std::array<u8, 0xFF> data;
};

struct NFCWritePackage {
    NFCWriteCommandData command_data;
    u8 number_of_chunks;
    std::array<NFCDataChunk, 4> data_chunks;
};

struct MifareReadChunk {
    MifareCmd command;
    std::array<u8, 0x6> sector_key;
    u8 sector;
};

struct MifareWriteChunk {
    MifareCmd command;
    std::array<u8, 0x6> sector_key;
    u8 sector;
    std::array<u8, 0x10> data;
};

struct MifareReadData {
    u8 sector;
    std::array<u8, 0x10> data;
};

struct MifareReadPackage {
    MifareCommandData command_data;
    std::array<MifareReadChunk, 0x10> data_chunks;
};

struct MifareWritePackage {
    MifareCommandData command_data;
    std::array<MifareWriteChunk, 0x10> data_chunks;
};

struct TagInfo {
    u8 uuid_length;
    u8 protocol;
    u8 tag_type;
    std::array<u8, 10> uuid;
};

struct IrsConfigure {
    MCUCommand command;
    MCUSubCommand sub_command;
    IrsMode irs_mode;
    IrsFragments number_of_fragments;
    u16 mcu_major_version;
    u16 mcu_minor_version;
    INSERT_PADDING_BYTES(0x1D);
    u8 crc;
};
static_assert(sizeof(IrsConfigure) == 0x26, "IrsConfigure is an invalid size");

#pragma pack(push, 1)
struct IrsRegister {
    IrRegistersAddress address;
    u8 value;
};
static_assert(sizeof(IrsRegister) == 0x3, "IrsRegister is an invalid size");

struct IrsWriteRegisters {
    MCUCommand command;
    MCUSubCommand sub_command;
    u8 number_of_registers;
    std::array<IrsRegister, 9> registers;
    INSERT_PADDING_BYTES(0x7);
    u8 crc;
};
static_assert(sizeof(IrsWriteRegisters) == 0x26, "IrsWriteRegisters is an invalid size");
#pragma pack(pop)

struct FirmwareVersion {
    u8 major;
    u8 minor;
};
static_assert(sizeof(FirmwareVersion) == 0x2, "FirmwareVersion is an invalid size");

struct DeviceInfo {
    FirmwareVersion firmware;
    std::array<u8, 2> unknown_1;
    MacAddress mac_address;
    std::array<u8, 2> unknown_2;
};
static_assert(sizeof(DeviceInfo) == 0xC, "DeviceInfo is an invalid size");

struct MotionStatus {
    bool is_enabled;
    u64 delta_time;
    GyroSensitivity gyro_sensitivity;
    AccelerometerSensitivity accelerometer_sensitivity;
};

struct RingStatus {
    bool is_enabled;
    s16 default_value;
    s16 max_value;
    s16 min_value;
};

struct VibrationPacket {
    OutputReport output_report;
    u8 packet_counter;
    std::array<u8, 0x8> vibration_data;
};
static_assert(sizeof(VibrationPacket) == 0xA, "VibrationPacket is an invalid size");

struct SubCommandPacket {
    OutputReport output_report;
    u8 packet_counter;
    INSERT_PADDING_BYTES(0x8); // This contains vibration data
    union {
        SubCommand sub_command;
        MCUSubCommand mcu_sub_command;
    };
    std::array<u8, 0x26> command_data;
};
static_assert(sizeof(SubCommandPacket) == 0x31, "SubCommandPacket is an invalid size");

#pragma pack(push, 1)
struct ReadSpiPacket {
    SpiAddress spi_address;
    INSERT_PADDING_BYTES(0x2);
    u8 size;
};
static_assert(sizeof(ReadSpiPacket) == 0x5, "ReadSpiPacket is an invalid size");

struct SubCommandResponse {
    InputReportPassive input_report;
    SubCommand sub_command;
    union {
        std::array<u8, 0x30> command_data;
        SpiAddress spi_address;              // Reply from SPI_FLASH_READ subcommand
        ExternalDeviceId external_device_id; // Reply from GET_EXTERNAL_DEVICE_INFO subcommand
        DeviceInfo device_info;              // Reply from REQ_DEV_INFO subcommand
    };
    u8 crc; // This is never used
};
static_assert(sizeof(SubCommandResponse) == 0x40, "SubCommandResponse is an invalid size");
#pragma pack(pop)

struct MCUCommandResponse {
    InputReportNfcIr input_report;
    INSERT_PADDING_BYTES(0x8);
    MCUReport mcu_report;
    std::array<u8, 0x13D> mcu_data;
    u8 crc;
};
static_assert(sizeof(MCUCommandResponse) == 0x170, "MCUCommandResponse is an invalid size");

struct JoyconCallbacks {
    std::function<void(Battery)> on_battery_data;
    std::function<void(Color)> on_color_data;
    std::function<void(int, bool)> on_button_data;
    std::function<void(int, f32)> on_stick_data;
    std::function<void(int, const MotionData&)> on_motion_data;
    std::function<void(f32)> on_ring_data;
    std::function<void(const Joycon::TagInfo&)> on_amiibo_data;
    std::function<void(const std::vector<u8>&, IrsResolution)> on_camera_data;
};

} // namespace InputCommon::Joycon


code:
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include "common/input.h"
#include "common/logging/log.h"
#include "input_common/helpers/joycon_protocol/nfc.h"

namespace InputCommon::Joycon {

NfcProtocol::NfcProtocol(std::shared_ptr<JoyconHandle> handle)
    : JoyconCommonProtocol(std::move(handle)) {}

Common::Input::DriverResult NfcProtocol::EnableNfc() {
    LOG_INFO(Input, "Enable NFC");
    ScopedSetBlocking sb(this);
    Common::Input::DriverResult result{Common::Input::DriverResult::Success};

    if (result == Common::Input::DriverResult::Success) {
        result = SetReportMode(ReportMode::NFC_IR_MODE_60HZ);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = EnableMCU(true);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitSetMCUMode(ReportMode::NFC_IR_MODE_60HZ, MCUMode::Standby);
    }
    if (result == Common::Input::DriverResult::Success) {
        const MCUConfig config{
            .command = MCUCommand::ConfigureMCU,
            .sub_command = MCUSubCommand::SetMCUMode,
            .mode = MCUMode::NFC,
            .crc = {},
        };

        result = ConfigureMCU(config);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitSetMCUMode(ReportMode::NFC_IR_MODE_60HZ, MCUMode::NFC);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitUntilNfcIs(NFCStatus::Ready);
    }
    if (result == Common::Input::DriverResult::Success) {
        MCUCommandResponse output{};
        result = SendStopPollingRequest(output);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitUntilNfcIs(NFCStatus::Ready);
    }
    if (result == Common::Input::DriverResult::Success) {
        is_enabled = true;
    }

    return result;
}

Common::Input::DriverResult NfcProtocol::DisableNfc() {
    LOG_DEBUG(Input, "Disable NFC");
    ScopedSetBlocking sb(this);
    Common::Input::DriverResult result{Common::Input::DriverResult::Success};

    if (result == Common::Input::DriverResult::Success) {
        result = EnableMCU(false);
    }

    is_enabled = false;
    is_polling = false;

    return result;
}

Common::Input::DriverResult NfcProtocol::StartNFCPollingMode() {
    LOG_DEBUG(Input, "Start NFC polling Mode");
    ScopedSetBlocking sb(this);
    Common::Input::DriverResult result{Common::Input::DriverResult::Success};

    if (result == Common::Input::DriverResult::Success) {
        MCUCommandResponse output{};
        result = SendStartPollingRequest(output);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitUntilNfcIs(NFCStatus::Polling);
    }
    if (result == Common::Input::DriverResult::Success) {
        is_polling = true;
    }

    return result;
}

Common::Input::DriverResult NfcProtocol::StopNFCPollingMode() {
    LOG_DEBUG(Input, "Stop NFC polling Mode");
    ScopedSetBlocking sb(this);
    Common::Input::DriverResult result{Common::Input::DriverResult::Success};

    if (result == Common::Input::DriverResult::Success) {
        MCUCommandResponse output{};
        result = SendStopPollingRequest(output);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitUntilNfcIs(NFCStatus::WriteReady);
    }
    if (result == Common::Input::DriverResult::Success) {
        is_polling = false;
    }

    return result;
}

Common::Input::DriverResult NfcProtocol::GetTagInfo(Joycon::TagInfo& tag_info) {
    if (update_counter++ < AMIIBO_UPDATE_DELAY) {
        return Common::Input::DriverResult::Delayed;
    }
    update_counter = 0;

    LOG_DEBUG(Input, "Scan for amiibos");
    ScopedSetBlocking sb(this);
    Common::Input::DriverResult result{Common::Input::DriverResult::Success};
    TagFoundData tag_data{};

    if (result == Common::Input::DriverResult::Success) {
        result = IsTagInRange(tag_data);
    }

    if (result == Common::Input::DriverResult::Success) {
        tag_info = {
            .uuid_length = tag_data.uuid_size,
            .protocol = 1,
            .tag_type = tag_data.type,
            .uuid = {},
        };

        memcpy(tag_info.uuid.data(), tag_data.uuid.data(), tag_data.uuid_size);

        // Investigate why mifare type is not correct
        if (tag_info.tag_type == 144) {
            tag_info.tag_type = 1U << 6;
        }

        std::string uuid_string;
        for (auto& content : tag_data.uuid) {
            uuid_string += fmt::format(" {:02x}", content);
        }
        LOG_INFO(Input, "Tag detected, type={}, uuid={}", tag_data.type, uuid_string);
    }

    return result;
}

Common::Input::DriverResult NfcProtocol::ReadAmiibo(std::vector<u8>& data) {
    LOG_DEBUG(Input, "Scan for amiibos");
    ScopedSetBlocking sb(this);
    Common::Input::DriverResult result{Common::Input::DriverResult::Success};
    TagFoundData tag_data{};

    if (result == Common::Input::DriverResult::Success) {
        result = IsTagInRange(tag_data, 7);
    }

    if (result == Common::Input::DriverResult::Success) {
        result = GetAmiiboData(data);
    }

    return result;
}

Common::Input::DriverResult NfcProtocol::WriteAmiibo(std::span<const u8> data) {
    LOG_DEBUG(Input, "Write amiibo");
    ScopedSetBlocking sb(this);
    Common::Input::DriverResult result{Common::Input::DriverResult::Success};
    TagUUID tag_uuid = GetTagUUID(data);
    TagFoundData tag_data{};

    if (result == Common::Input::DriverResult::Success) {
        result = IsTagInRange(tag_data, 7);
    }
    if (result == Common::Input::DriverResult::Success) {
        if (tag_data.uuid != tag_uuid) {
            result = Common::Input::DriverResult::InvalidParameters;
        }
    }
    if (result == Common::Input::DriverResult::Success) {
        MCUCommandResponse output{};
        result = SendStopPollingRequest(output);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitUntilNfcIs(NFCStatus::Ready);
    }
    if (result == Common::Input::DriverResult::Success) {
        MCUCommandResponse output{};
        result = SendStartPollingRequest(output, true);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitUntilNfcIs(NFCStatus::WriteReady);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WriteAmiiboData(tag_uuid, data);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitUntilNfcIs(NFCStatus::WriteDone);
    }
    if (result == Common::Input::DriverResult::Success) {
        MCUCommandResponse output{};
        result = SendStopPollingRequest(output);
    }

    return result;
}

Common::Input::DriverResult NfcProtocol::ReadMifare(std::span<const MifareReadChunk> read_request,
                                                    std::span<MifareReadData> out_data) {
    LOG_DEBUG(Input, "Read mifare");
    ScopedSetBlocking sb(this);
    Common::Input::DriverResult result{Common::Input::DriverResult::Success};
    TagFoundData tag_data{};
    MifareUUID tag_uuid{};

    if (result == Common::Input::DriverResult::Success) {
        result = IsTagInRange(tag_data, 7);
    }
    if (result == Common::Input::DriverResult::Success) {
        memcpy(tag_uuid.data(), tag_data.uuid.data(), sizeof(MifareUUID));
        result = GetMifareData(tag_uuid, read_request, out_data);
    }
    if (result == Common::Input::DriverResult::Success) {
        MCUCommandResponse output{};
        result = SendStopPollingRequest(output);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitUntilNfcIs(NFCStatus::Ready);
    }
    if (result == Common::Input::DriverResult::Success) {
        MCUCommandResponse output{};
        result = SendStartPollingRequest(output, true);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitUntilNfcIs(NFCStatus::WriteReady);
    }
    return result;
}

Common::Input::DriverResult NfcProtocol::WriteMifare(
    std::span<const MifareWriteChunk> write_request) {
    LOG_DEBUG(Input, "Write mifare");
    ScopedSetBlocking sb(this);
    Common::Input::DriverResult result{Common::Input::DriverResult::Success};
    TagFoundData tag_data{};
    MifareUUID tag_uuid{};

    if (result == Common::Input::DriverResult::Success) {
        result = IsTagInRange(tag_data, 7);
    }
    if (result == Common::Input::DriverResult::Success) {
        memcpy(tag_uuid.data(), tag_data.uuid.data(), sizeof(MifareUUID));
        result = WriteMifareData(tag_uuid, write_request);
    }
    if (result == Common::Input::DriverResult::Success) {
        MCUCommandResponse output{};
        result = SendStopPollingRequest(output);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitUntilNfcIs(NFCStatus::Ready);
    }
    if (result == Common::Input::DriverResult::Success) {
        MCUCommandResponse output{};
        result = SendStartPollingRequest(output, true);
    }
    if (result == Common::Input::DriverResult::Success) {
        result = WaitUntilNfcIs(NFCStatus::WriteReady);
    }
    return result;
}

bool NfcProtocol::HasAmiibo() {
    if (update_counter++ < AMIIBO_UPDATE_DELAY) {
        return true;
    }
    update_counter = 0;

    ScopedSetBlocking sb(this);
    Common::Input::DriverResult result{Common::Input::DriverResult::Success};
    TagFoundData tag_data{};

    if (result == Common::Input::DriverResult::Success) {
        result = IsTagInRange(tag_data, 7);
    }

    return result == Common::Input::DriverResult::Success;
}

Common::Input::DriverResult NfcProtocol::WaitUntilNfcIs(NFCStatus status) {
    constexpr std::size_t timeout_limit = 10;
    MCUCommandResponse output{};
    std::size_t tries = 0;

    do {
        auto result = SendNextPackageRequest(output, {});

        if (result != Common::Input::DriverResult::Success) {
            return result;
        }
        if (tries++ > timeout_limit) {
            return Common::Input::DriverResult::Timeout;
        }
    } while (output.mcu_report != MCUReport::NFCState ||
             (output.mcu_data[1] << 8) + output.mcu_data[0] != 0x0500 ||
             output.mcu_data[5] != 0x31 || output.mcu_data[6] != static_cast<u8>(status));

    return Common::Input::DriverResult::Success;
}

Common::Input::DriverResult NfcProtocol::IsTagInRange(TagFoundData& data,
                                                      std::size_t timeout_limit) {
    MCUCommandResponse output{};
    std::size_t tries = 0;

    do {
        const auto result = SendNextPackageRequest(output, {});
        if (result != Common::Input::DriverResult::Success) {
            return result;
        }
        if (tries++ > timeout_limit) {
            return Common::Input::DriverResult::Timeout;
        }
    } while (output.mcu_report != MCUReport::NFCState ||
             (output.mcu_data[1] << 8) + output.mcu_data[0] != 0x0500 ||
             (output.mcu_data[6] != 0x09 && output.mcu_data[6] != 0x04));

    data.type = output.mcu_data[12];
    data.uuid_size = std::min(output.mcu_data[14], static_cast<u8>(sizeof(TagUUID)));
    memcpy(data.uuid.data(), output.mcu_data.data() + 15, data.uuid.size());

    return Common::Input::DriverResult::Success;
}

Common::Input::DriverResult NfcProtocol::GetAmiiboData(std::vector<u8>& ntag_data) {
    constexpr std::size_t timeout_limit = 60;
    MCUCommandResponse output{};
    std::size_t tries = 0;

    u8 package_index = 0;
    std::size_t ntag_buffer_pos = 0;
    auto result = SendReadAmiiboRequest(output, NFCPages::Block135);

    if (result != Common::Input::DriverResult::Success) {
        return result;
    }

    // Read Tag data
    while (tries++ < timeout_limit) {
        result = SendNextPackageRequest(output, package_index);
        const auto nfc_status = static_cast<NFCStatus>(output.mcu_data[6]);

        if (result != Common::Input::DriverResult::Success) {
            return result;
        }

        if ((output.mcu_report == MCUReport::NFCReadData ||
             output.mcu_report == MCUReport::NFCState) &&
            nfc_status == NFCStatus::TagLost) {
            return Common::Input::DriverResult::ErrorReadingData;
        }

        if (output.mcu_report == MCUReport::NFCReadData && output.mcu_data[1] == 0x07) {
            std::size_t payload_size = (output.mcu_data[4] << 8 | output.mcu_data[5]) & 0x7FF;
            if (output.mcu_data[2] == 0x01) {
                memcpy(ntag_data.data() + ntag_buffer_pos, output.mcu_data.data() + 66,
                       payload_size - 60);
                ntag_buffer_pos += payload_size - 60;
            } else {
                memcpy(ntag_data.data() + ntag_buffer_pos, output.mcu_data.data() + 6,
                       payload_size);
            }
            package_index++;
            continue;
        }

        if (output.mcu_report == MCUReport::NFCState && nfc_status == NFCStatus::LastPackage) {
            LOG_INFO(Input, "Finished reading amiibo");
            return Common::Input::DriverResult::Success;
        }
    }

    return Common::Input::DriverResult::Timeout;
}

Common::Input::DriverResult NfcProtocol::WriteAmiiboData(const TagUUID& tag_uuid,
                                                         std::span<const u8> data) {
    constexpr std::size_t timeout_limit = 60;
    const auto nfc_data = MakeAmiiboWritePackage(tag_uuid, data);
    const std::vector<u8> nfc_buffer_data = SerializeWritePackage(nfc_data);
    std::span<const u8> buffer(nfc_buffer_data);
    MCUCommandResponse output{};
    u8 block_id = 1;
    u8 package_index = 0;
    std::size_t tries = 0;
    std::size_t current_position = 0;

    LOG_INFO(Input, "Writing amiibo data");

    auto result = SendWriteAmiiboRequest(output, tag_uuid);

    if (result != Common::Input::DriverResult::Success) {
        return result;
    }

    // Read Tag data but ignore the actual sent data
    while (tries++ < timeout_limit) {
        result = SendNextPackageRequest(output, package_index);
        const auto nfc_status = static_cast<NFCStatus>(output.mcu_data[6]);

        if (result != Common::Input::DriverResult::Success) {
            return result;
        }

        if ((output.mcu_report == MCUReport::NFCReadData ||
             output.mcu_report == MCUReport::NFCState) &&
            nfc_status == NFCStatus::TagLost) {
            return Common::Input::DriverResult::ErrorReadingData;
        }

        if (output.mcu_report == MCUReport::NFCReadData && output.mcu_data[1] == 0x07) {
            package_index++;
            continue;
        }

        if (output.mcu_report == MCUReport::NFCState && nfc_status == NFCStatus::LastPackage) {
            LOG_INFO(Input, "Finished reading amiibo");
            break;
        }
    }

    // Send Data. Nfc buffer size is 31, Send the data in smaller packages
    while (current_position < buffer.size() && tries++ < timeout_limit) {
        const std::size_t next_position =
            std::min(current_position + sizeof(NFCRequestState::raw_data), buffer.size());
        const std::size_t block_size = next_position - current_position;
        const bool is_last_packet = block_size < sizeof(NFCRequestState::raw_data);

        SendWriteDataAmiiboRequest(output, block_id, is_last_packet,
                                   buffer.subspan(current_position, block_size));

        const auto nfc_status = static_cast<NFCStatus>(output.mcu_data[6]);

        if ((output.mcu_report == MCUReport::NFCReadData ||
             output.mcu_report == MCUReport::NFCState) &&
            nfc_status == NFCStatus::TagLost) {
            return Common::Input::DriverResult::ErrorReadingData;
        }

        // Increase position when data is confirmed by the joycon
        if (output.mcu_report == MCUReport::NFCState &&
            (output.mcu_data[1] << 8) + output.mcu_data[0] == 0x0500 &&
            output.mcu_data[3] == block_id) {
            block_id++;
            current_position = next_position;
        }
    }

    return result;
}

Common::Input::DriverResult NfcProtocol::GetMifareData(
    const MifareUUID& tag_uuid, std::span<const MifareReadChunk> read_request,
    std::span<MifareReadData> out_data) {
    constexpr std::size_t timeout_limit = 60;
    const auto nfc_data = MakeMifareReadPackage(tag_uuid, read_request);
    const std::vector<u8> nfc_buffer_data = SerializeMifareReadPackage(nfc_data);
    std::span<const u8> buffer(nfc_buffer_data);
    Common::Input::DriverResult result = Common::Input::DriverResult::Success;
    MCUCommandResponse output{};
    u8 block_id = 1;
    u8 package_index = 0;
    std::size_t tries = 0;
    std::size_t current_position = 0;

    LOG_INFO(Input, "Reading Mifare data");

    // Send data request. Nfc buffer size is 31, Send the data in smaller packages
    while (current_position < buffer.size() && tries++ < timeout_limit) {
        const std::size_t next_position =
            std::min(current_position + sizeof(NFCRequestState::raw_data), buffer.size());
        const std::size_t block_size = next_position - current_position;
        const bool is_last_packet = block_size < sizeof(NFCRequestState::raw_data);

        SendReadDataMifareRequest(output, block_id, is_last_packet,
                                  buffer.subspan(current_position, block_size));

        const auto nfc_status = static_cast<NFCStatus>(output.mcu_data[6]);

        if (output.mcu_report == MCUReport::NFCState && nfc_status == NFCStatus::TagLost) {
            return Common::Input::DriverResult::ErrorReadingData;
        }

        // Increase position when data is confirmed by the joycon
        if (output.mcu_report == MCUReport::NFCState &&
            (output.mcu_data[1] << 8) + output.mcu_data[0] == 0x0500 &&
            output.mcu_data[3] == block_id) {
            block_id++;
            current_position = next_position;
        }
    }

    if (result != Common::Input::DriverResult::Success) {
        return result;
    }

    // Wait for reply and save the output data
    while (tries++ < timeout_limit) {
        result = SendNextPackageRequest(output, package_index);
        const auto nfc_status = static_cast<NFCStatus>(output.mcu_data[6]);

        if (result != Common::Input::DriverResult::Success) {
            return result;
        }

        if (output.mcu_report == MCUReport::NFCState && nfc_status == NFCStatus::TagLost) {
            return Common::Input::DriverResult::ErrorReadingData;
        }

        if (output.mcu_report == MCUReport::NFCState && output.mcu_data[1] == 0x10) {
            constexpr std::size_t DATA_LENGTH = 0x10 + 1;
            constexpr std::size_t DATA_START = 11;
            const u8 number_of_elements = output.mcu_data[10];
            for (std::size_t i = 0; i < number_of_elements; i++) {
                out_data[i].sector = output.mcu_data[DATA_START + (i * DATA_LENGTH)];
                memcpy(out_data[i].data.data(),
                       output.mcu_data.data() + DATA_START + 1 + (i * DATA_LENGTH),
                       sizeof(MifareReadData::data));
            }
            package_index++;
            continue;
        }

        if (output.mcu_report == MCUReport::NFCState && nfc_status == NFCStatus::MifareDone) {
            LOG_INFO(Input, "Finished reading mifare");
            break;
        }
    }

    return result;
}

Common::Input::DriverResult NfcProtocol::WriteMifareData(
    const MifareUUID& tag_uuid, std::span<const MifareWriteChunk> write_request) {
    constexpr std::size_t timeout_limit = 60;
    const auto nfc_data = MakeMifareWritePackage(tag_uuid, write_request);
    const std::vector<u8> nfc_buffer_data = SerializeMifareWritePackage(nfc_data);
    std::span<const u8> buffer(nfc_buffer_data);
    Common::Input::DriverResult result = Common::Input::DriverResult::Success;
    MCUCommandResponse output{};
    u8 block_id = 1;
    u8 package_index = 0;
    std::size_t tries = 0;
    std::size_t current_position = 0;

    LOG_INFO(Input, "Writing Mifare data");

    // Send data request. Nfc buffer size is 31, Send the data in smaller packages
    while (current_position < buffer.size() && tries++ < timeout_limit) {
        const std::size_t next_position =
            std::min(current_position + sizeof(NFCRequestState::raw_data), buffer.size());
        const std::size_t block_size = next_position - current_position;
        const bool is_last_packet = block_size < sizeof(NFCRequestState::raw_data);

        SendReadDataMifareRequest(output, block_id, is_last_packet,
                                  buffer.subspan(current_position, block_size));

        const auto nfc_status = static_cast<NFCStatus>(output.mcu_data[6]);

        if (output.mcu_report == MCUReport::NFCState && nfc_status == NFCStatus::TagLost) {
            return Common::Input::DriverResult::ErrorReadingData;
        }

        // Increase position when data is confirmed by the joycon
        if (output.mcu_report == MCUReport::NFCState &&
            (output.mcu_data[1] << 8) + output.mcu_data[0] == 0x0500 &&
            output.mcu_data[3] == block_id) {
            block_id++;
            current_position = next_position;
        }
    }

    if (result != Common::Input::DriverResult::Success) {
        return result;
    }

    // Wait for reply and ignore the output data
    while (tries++ < timeout_limit) {
        result = SendNextPackageRequest(output, package_index);
        const auto nfc_status = static_cast<NFCStatus>(output.mcu_data[6]);

        if (result != Common::Input::DriverResult::Success) {
            return result;
        }

        if (output.mcu_report == MCUReport::NFCState && nfc_status == NFCStatus::TagLost) {
            return Common::Input::DriverResult::ErrorReadingData;
        }

        if (output.mcu_report == MCUReport::NFCState && output.mcu_data[1] == 0x10) {
            package_index++;
            continue;
        }

        if (output.mcu_report == MCUReport::NFCState && nfc_status == NFCStatus::MifareDone) {
            LOG_INFO(Input, "Finished writing mifare");
            break;
        }
    }

    return result;
}

Common::Input::DriverResult NfcProtocol::SendStartPollingRequest(MCUCommandResponse& output,
                                                                 bool is_second_attempt) {
    NFCRequestState request{
        .command_argument = NFCCommand::StartPolling,
        .block_id = {},
        .packet_id = {},
        .packet_flag = MCUPacketFlag::LastCommandPacket,
        .data_length = sizeof(NFCPollingCommandData),
        .nfc_polling =
            {
                .enable_mifare = 0x00,
                .unknown_1 = static_cast<u8>(is_second_attempt ? 0xe8 : 0x00),
                .unknown_2 = static_cast<u8>(is_second_attempt ? 0x03 : 0x00),
                .unknown_3 = 0x2c,
                .unknown_4 = 0x01,
            },
        .crc = {},
    };

    std::array<u8, sizeof(NFCRequestState)> request_data{};
    memcpy(request_data.data(), &request, sizeof(NFCRequestState));
    request_data[36] = CalculateMCU_CRC8(request_data.data(), 36);
    return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, MCUSubCommand::ReadDeviceMode, request_data,
                       output);
}

Common::Input::DriverResult NfcProtocol::SendStopPollingRequest(MCUCommandResponse& output) {
    NFCRequestState request{
        .command_argument = NFCCommand::StopPolling,
        .block_id = {},
        .packet_id = {},
        .packet_flag = MCUPacketFlag::LastCommandPacket,
        .data_length = {},
        .raw_data = {},
        .crc = {},
    };

    std::array<u8, sizeof(NFCRequestState)> request_data{};
    memcpy(request_data.data(), &request, sizeof(NFCRequestState));
    request_data[36] = CalculateMCU_CRC8(request_data.data(), 36);
    return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, MCUSubCommand::ReadDeviceMode, request_data,
                       output);
}

Common::Input::DriverResult NfcProtocol::SendNextPackageRequest(MCUCommandResponse& output,
                                                                u8 packet_id) {
    NFCRequestState request{
        .command_argument = NFCCommand::StartWaitingReceive,
        .block_id = {},
        .packet_id = packet_id,
        .packet_flag = MCUPacketFlag::LastCommandPacket,
        .data_length = {},
        .raw_data = {},
        .crc = {},
    };

    std::vector<u8> request_data(sizeof(NFCRequestState));
    memcpy(request_data.data(), &request, sizeof(NFCRequestState));
    request_data[36] = CalculateMCU_CRC8(request_data.data(), 36);
    return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, MCUSubCommand::ReadDeviceMode, request_data,
                       output);
}

Common::Input::DriverResult NfcProtocol::SendReadAmiiboRequest(MCUCommandResponse& output,
                                                               NFCPages ntag_pages) {
    NFCRequestState request{
        .command_argument = NFCCommand::ReadNtag,
        .block_id = {},
        .packet_id = {},
        .packet_flag = MCUPacketFlag::LastCommandPacket,
        .data_length = sizeof(NFCReadCommandData),
        .nfc_read =
            {
                .unknown = 0xd0,
                .uuid_length = sizeof(NFCReadCommandData::uid),
                .uid = {},
                .tag_type = NFCTagType::Ntag215,
                .read_block = GetReadBlockCommand(ntag_pages),
            },
        .crc = {},
    };

    std::array<u8, sizeof(NFCRequestState)> request_data{};
    memcpy(request_data.data(), &request, sizeof(NFCRequestState));
    request_data[36] = CalculateMCU_CRC8(request_data.data(), 36);
    return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, MCUSubCommand::ReadDeviceMode, request_data,
                       output);
}

Common::Input::DriverResult NfcProtocol::SendWriteAmiiboRequest(MCUCommandResponse& output,
                                                                const TagUUID& tag_uuid) {
    NFCRequestState request{
        .command_argument = NFCCommand::ReadNtag,
        .block_id = {},
        .packet_id = {},
        .packet_flag = MCUPacketFlag::LastCommandPacket,
        .data_length = sizeof(NFCReadCommandData),
        .nfc_read =
            {
                .unknown = 0xd0,
                .uuid_length = sizeof(NFCReadCommandData::uid),
                .uid = tag_uuid,
                .tag_type = NFCTagType::Ntag215,
                .read_block = GetReadBlockCommand(NFCPages::Block3),
            },
        .crc = {},
    };

    std::array<u8, sizeof(NFCRequestState)> request_data{};
    memcpy(request_data.data(), &request, sizeof(NFCRequestState));
    request_data[36] = CalculateMCU_CRC8(request_data.data(), 36);
    return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, MCUSubCommand::ReadDeviceMode, request_data,
                       output);
}

Common::Input::DriverResult NfcProtocol::SendWriteDataAmiiboRequest(MCUCommandResponse& output,
                                                                    u8 block_id,
                                                                    bool is_last_packet,
                                                                    std::span<const u8> data) {
    const auto data_size = std::min(data.size(), sizeof(NFCRequestState::raw_data));
    NFCRequestState request{
        .command_argument = NFCCommand::WriteNtag,
        .block_id = block_id,
        .packet_id = {},
        .packet_flag =
            is_last_packet ? MCUPacketFlag::LastCommandPacket : MCUPacketFlag::MorePacketsRemaining,
        .data_length = static_cast<u8>(data_size),
        .raw_data = {},
        .crc = {},
    };
    memcpy(request.raw_data.data(), data.data(), data_size);

    std::array<u8, sizeof(NFCRequestState)> request_data{};
    memcpy(request_data.data(), &request, sizeof(NFCRequestState));
    request_data[36] = CalculateMCU_CRC8(request_data.data(), 36);
    return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, MCUSubCommand::ReadDeviceMode, request_data,
                       output);
}

Common::Input::DriverResult NfcProtocol::SendReadDataMifareRequest(MCUCommandResponse& output,
                                                                   u8 block_id, bool is_last_packet,
                                                                   std::span<const u8> data) {
    const auto data_size = std::min(data.size(), sizeof(NFCRequestState::raw_data));
    NFCRequestState request{
        .command_argument = NFCCommand::Mifare,
        .block_id = block_id,
        .packet_id = {},
        .packet_flag =
            is_last_packet ? MCUPacketFlag::LastCommandPacket : MCUPacketFlag::MorePacketsRemaining,
        .data_length = static_cast<u8>(data_size),
        .raw_data = {},
        .crc = {},
    };
    memcpy(request.raw_data.data(), data.data(), data_size);

    std::array<u8, sizeof(NFCRequestState)> request_data{};
    memcpy(request_data.data(), &request, sizeof(NFCRequestState));
    request_data[36] = CalculateMCU_CRC8(request_data.data(), 36);
    return SendMCUData(ReportMode::NFC_IR_MODE_60HZ, MCUSubCommand::ReadDeviceMode, request_data,
                       output);
}

std::vector<u8> NfcProtocol::SerializeWritePackage(const NFCWritePackage& package) const {
    const std::size_t header_size =
        sizeof(NFCWriteCommandData) + sizeof(NFCWritePackage::number_of_chunks);
    std::vector<u8> serialized_data(header_size);
    std::size_t start_index = 0;

    memcpy(serialized_data.data(), &package, header_size);
    start_index += header_size;

    for (const auto& data_chunk : package.data_chunks) {
        const std::size_t chunk_size =
            sizeof(NFCDataChunk::nfc_page) + sizeof(NFCDataChunk::data_size) + data_chunk.data_size;

        serialized_data.resize(start_index + chunk_size);
        memcpy(serialized_data.data() + start_index, &data_chunk, chunk_size);
        start_index += chunk_size;
    }

    return serialized_data;
}

std::vector<u8> NfcProtocol::SerializeMifareReadPackage(const MifareReadPackage& package) const {
    const std::size_t header_size = sizeof(MifareCommandData);
    std::vector<u8> serialized_data(header_size);
    std::size_t start_index = 0;

    memcpy(serialized_data.data(), &package, header_size);
    start_index += header_size;

    for (const auto& data_chunk : package.data_chunks) {
        const std::size_t chunk_size = sizeof(MifareReadChunk);
        if (data_chunk.command == MifareCmd::None) {
            continue;
        }
        serialized_data.resize(start_index + chunk_size);
        memcpy(serialized_data.data() + start_index, &data_chunk, chunk_size);
        start_index += chunk_size;
    }

    return serialized_data;
}

std::vector<u8> NfcProtocol::SerializeMifareWritePackage(const MifareWritePackage& package) const {
    const std::size_t header_size = sizeof(MifareCommandData);
    std::vector<u8> serialized_data(header_size);
    std::size_t start_index = 0;

    memcpy(serialized_data.data(), &package, header_size);
    start_index += header_size;

    for (const auto& data_chunk : package.data_chunks) {
        const std::size_t chunk_size = sizeof(MifareWriteChunk);
        if (data_chunk.command == MifareCmd::None) {
            continue;
        }
        serialized_data.resize(start_index + chunk_size);
        memcpy(serialized_data.data() + start_index, &data_chunk, chunk_size);
        start_index += chunk_size;
    }

    return serialized_data;
}

NFCWritePackage NfcProtocol::MakeAmiiboWritePackage(const TagUUID& tag_uuid,
                                                    std::span<const u8> data) const {
    return {
        .command_data{
            .unknown = 0xd0,
            .uuid_length = sizeof(NFCReadCommandData::uid),
            .uid = tag_uuid,
            .tag_type = NFCTagType::Ntag215,
            .unknown2 = 0x00,
            .unknown3 = 0x01,
            .unknown4 = 0x04,
            .unknown5 = 0xff,
            .unknown6 = 0xff,
            .unknown7 = 0xff,
            .unknown8 = 0xff,
            .magic = data[16],
            .write_count = static_cast<u16>((data[17] << 8) + data[18]),
            .amiibo_version = data[19],
        },
        .number_of_chunks = 3,
        .data_chunks =
            {
                MakeAmiiboChunk(0x05, 0x20, data),
                MakeAmiiboChunk(0x20, 0xf0, data),
                MakeAmiiboChunk(0x5c, 0x98, data),
            },
    };
}

MifareReadPackage NfcProtocol::MakeMifareReadPackage(
    const MifareUUID& tag_uuid, std::span<const MifareReadChunk> read_request) const {
    MifareReadPackage package{
        .command_data{
            .unknown1 = 0xd0,
            .unknown2 = 0x07,
            .number_of_short_bytes = static_cast<u8>(
                ((read_request.size() * sizeof(MifareReadChunk)) + sizeof(MifareUUID)) / 2),
            .uid = tag_uuid,
        },
        .data_chunks = {},
    };

    for (std::size_t i = 0; i < read_request.size() && i < package.data_chunks.size(); ++i) {
        package.data_chunks[i] = read_request[i];
    }

    return package;
}

MifareWritePackage NfcProtocol::MakeMifareWritePackage(
    const MifareUUID& tag_uuid, std::span<const MifareWriteChunk> read_request) const {
    MifareWritePackage package{
        .command_data{
            .unknown1 = 0xd0,
            .unknown2 = 0x07,
            .number_of_short_bytes = static_cast<u8>(
                ((read_request.size() * sizeof(MifareReadChunk)) + sizeof(MifareUUID) + 2) / 2),
            .uid = tag_uuid,
        },
        .data_chunks = {},
    };

    for (std::size_t i = 0; i < read_request.size() && i < package.data_chunks.size(); ++i) {
        package.data_chunks[i] = read_request[i];
    }

    return package;
}

NFCDataChunk NfcProtocol::MakeAmiiboChunk(u8 page, u8 size, std::span<const u8> data) const {
    constexpr u8 NFC_PAGE_SIZE = 4;

    if (static_cast<std::size_t>(page * NFC_PAGE_SIZE) + size >= data.size()) {
        return {};
    }

    NFCDataChunk chunk{
        .nfc_page = page,
        .data_size = size,
        .data = {},
    };
    std::memcpy(chunk.data.data(), data.data() + (page * NFC_PAGE_SIZE), size);
    return chunk;
}

NFCReadBlockCommand NfcProtocol::GetReadBlockCommand(NFCPages pages) const {
    switch (pages) {
    case NFCPages::Block0:
        return {
            .block_count = 1,
        };
    case NFCPages::Block3:
        return {
            .block_count = 1,
            .blocks =
                {
                    NFCReadBlock{0x03, 0x03},
                },
        };
    case NFCPages::Block45:
        return {
            .block_count = 1,
            .blocks =
                {
                    NFCReadBlock{0x00, 0x2C},
                },
        };
    case NFCPages::Block135:
        return {
            .block_count = 3,
            .blocks =
                {
                    NFCReadBlock{0x00, 0x3b},
                    {0x3c, 0x77},
                    {0x78, 0x86},
                },
        };
    case NFCPages::Block231:
        return {
            .block_count = 4,
            .blocks =
                {
                    NFCReadBlock{0x00, 0x3b},
                    {0x3c, 0x77},
                    {0x78, 0x83},
                    {0xb4, 0xe6},
                },
        };
    default:
        return {};
    };
}

TagUUID NfcProtocol::GetTagUUID(std::span<const u8> data) const {
    if (data.size() < 10) {
        return {};
    }

    // crc byte 3 is omitted in this operation
    return {
        data[0], data[1], data[2], data[4], data[5], data[6], data[7],
    };
}

bool NfcProtocol::IsEnabled() const {
    return is_enabled;
}

bool NfcProtocol::IsPolling() const {
    return is_polling;
}

} // namespace InputCommon::Joycon


code:
// SPDX-FileCopyrightText: Copyright 2022 yuzu Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

// Based on dkms-hid-nintendo implementation, CTCaer joycon toolkit and dekuNukem reverse
// engineering https://github.com/nicman23/dkms-hid-nintendo/blob/master/src/hid-nintendo.c
// https://github.com/CTCaer/jc_toolkit
// https://github.com/dekuNukem/Nintendo_Switch_Reverse_Engineering

#pragma once

#include <vector>

#include "input_common/helpers/joycon_protocol/common_protocol.h"
#include "input_common/helpers/joycon_protocol/joycon_types.h"

namespace Common::Input {
enum class DriverResult;
}

namespace InputCommon::Joycon {

class NfcProtocol final : private JoyconCommonProtocol {
public:
    explicit NfcProtocol(std::shared_ptr<JoyconHandle> handle);

    Common::Input::DriverResult EnableNfc();

    Common::Input::DriverResult DisableNfc();

    Common::Input::DriverResult StartNFCPollingMode();

    Common::Input::DriverResult StopNFCPollingMode();

    Common::Input::DriverResult GetTagInfo(Joycon::TagInfo& tag_info);

    Common::Input::DriverResult ReadAmiibo(std::vector<u8>& data);

    Common::Input::DriverResult WriteAmiibo(std::span<const u8> data);

    Common::Input::DriverResult ReadMifare(std::span<const MifareReadChunk> read_request,
                                           std::span<MifareReadData> out_data);

    Common::Input::DriverResult WriteMifare(std::span<const MifareWriteChunk> write_request);

    bool HasAmiibo();

    bool IsEnabled() const;

    bool IsPolling() const;

private:
    // Number of times the function will be delayed until it outputs valid data
    static constexpr std::size_t AMIIBO_UPDATE_DELAY = 15;

    struct TagFoundData {
        u8 type;
        u8 uuid_size;
        TagUUID uuid;
    };

    Common::Input::DriverResult WaitUntilNfcIs(NFCStatus status);

    Common::Input::DriverResult IsTagInRange(TagFoundData& data, std::size_t timeout_limit = 1);

    Common::Input::DriverResult GetAmiiboData(std::vector<u8>& data);

    Common::Input::DriverResult WriteAmiiboData(const TagUUID& tag_uuid, std::span<const u8> data);

    Common::Input::DriverResult GetMifareData(const MifareUUID& tag_uuid,
                                              std::span<const MifareReadChunk> read_request,
                                              std::span<MifareReadData> out_data);

    Common::Input::DriverResult WriteMifareData(const MifareUUID& tag_uuid,
                                                std::span<const MifareWriteChunk> write_request);

    Common::Input::DriverResult SendStartPollingRequest(MCUCommandResponse& output,
                                                        bool is_second_attempt = false);

    Common::Input::DriverResult SendStopPollingRequest(MCUCommandResponse& output);

    Common::Input::DriverResult SendNextPackageRequest(MCUCommandResponse& output, u8 packet_id);

    Common::Input::DriverResult SendReadAmiiboRequest(MCUCommandResponse& output,
                                                      NFCPages ntag_pages);

    Common::Input::DriverResult SendWriteAmiiboRequest(MCUCommandResponse& output,
                                                       const TagUUID& tag_uuid);

    Common::Input::DriverResult SendWriteDataAmiiboRequest(MCUCommandResponse& output, u8 block_id,
                                                           bool is_last_packet,
                                                           std::span<const u8> data);

    Common::Input::DriverResult SendReadDataMifareRequest(MCUCommandResponse& output, u8 block_id,
                                                          bool is_last_packet,
                                                          std::span<const u8> data);

    std::vector<u8> SerializeWritePackage(const NFCWritePackage& package) const;

    std::vector<u8> SerializeMifareReadPackage(const MifareReadPackage& package) const;

    std::vector<u8> SerializeMifareWritePackage(const MifareWritePackage& package) const;

    NFCWritePackage MakeAmiiboWritePackage(const TagUUID& tag_uuid, std::span<const u8> data) const;

    NFCDataChunk MakeAmiiboChunk(u8 page, u8 size, std::span<const u8> data) const;

    MifareReadPackage MakeMifareReadPackage(const MifareUUID& tag_uuid,
                                            std::span<const MifareReadChunk> read_request) const;

    MifareWritePackage MakeMifareWritePackage(const MifareUUID& tag_uuid,
                                              std::span<const MifareWriteChunk> read_request) const;

    NFCReadBlockCommand GetReadBlockCommand(NFCPages pages) const;

    TagUUID GetTagUUID(std::span<const u8> data) const;

    bool is_enabled{};
    bool is_polling{};
    std::size_t update_counter{};
};

} // namespace InputCommon::Joycon