/*
 * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#pragma once

#include <wchar.h>
#include <stdint.h>
#include "esp_err.h"
#include <freertos/FreeRTOS.h>

#ifdef __cplusplus
extern "C" {
#endif

#define ESP_ERR_MSC_HOST_BASE 0x1700                          /*!< MSC host error code base */
#define ESP_ERR_MSC_MOUNT_FAILED (ESP_ERR_MSC_HOST_BASE + 1)  /*!< Failed to mount storage */
#define ESP_ERR_MSC_FORMAT_FAILED (ESP_ERR_MSC_HOST_BASE + 2) /*!< Failed to format storage */
#define ESP_ERR_MSC_INTERNAL (ESP_ERR_MSC_HOST_BASE + 3)      /*!< MSC host internal error */

#define MSC_STR_DESC_SIZE 32

typedef struct msc_host_device *msc_host_device_handle_t; /**< Handle to a Mass Storage Device */

/**
 * @brief USB Mass Storage event containing event type and associated device handle.
 */
typedef struct {
    enum {
        MSC_DEVICE_CONNECTED,    /**< MSC device has been connected to the system.*/
        MSC_DEVICE_DISCONNECTED, /**< MSC device has been disconnected from the system.*/

        CDC_DEVICE_CONNECTED,
        CDC_DEVICE_DISCONNECTED,

        DFU_DEVICE_CONNECTED,
        DFU_DEVICE_DISCONNECTED,
    } event;
    union {
        uint8_t address;                 /**< Address of connected MSC device.*/
        msc_host_device_handle_t handle; /**< MSC device handle to disconnected device.*/
    } device;

    uint16_t vendor_id;
    uint16_t product_id;
} msc_host_event_t;

/**
 * @brief USB Mass Storage event callback.
 *
 * @param[in] event mass storage event
 */
typedef void (*msc_host_event_cb_t)(const msc_host_event_t *event, void *arg);

/**
 * @brief MSC configuration structure.
 */
typedef struct {
    bool create_backround_task;   /**< When set to true, background task handling usb events is created.
                                       Otherwise user has to periodically call msc_host_handle_events function */
    size_t task_priority;         /**< Task priority of crated background task */
    size_t stack_size;            /**< Stack size of crated background task */
    BaseType_t core_id;           /**< Select core on which background task will run or tskNO_AFFINITY  */
    msc_host_event_cb_t callback; /**< Callback invoked when MSC event occurs. Must not be NULL. */
    void *callback_arg;           /**< User provided argument passed to callback */
} msc_host_driver_config_t;

/**
 * @brief MSC device info.
 */
typedef struct {
    uint32_t sector_count;
    uint32_t sector_size;
    uint16_t idProduct;
    uint16_t idVendor;
    wchar_t iManufacturer[MSC_STR_DESC_SIZE];
    wchar_t iProduct[MSC_STR_DESC_SIZE];
    wchar_t iSerialNumber[MSC_STR_DESC_SIZE];
} msc_host_device_info_t;

//////cdc

typedef struct cdc_dev_s *cdc_acm_dev_hdl_t;

/**
 * @brief Line Coding structure
 * @see Table 17, USB CDC-PSTN specification rev. 1.2
 */
typedef struct {
    uint32_t dwDTERate;  // in bits per second
    uint8_t bCharFormat; // 0: 1 stopbit, 1: 1.5 stopbits, 2: 2 stopbits
    uint8_t bParityType; // 0: None, 1: Odd, 2: Even, 3: Mark, 4: Space
    uint8_t bDataBits;   // 5, 6, 7, 8 or 16
} __attribute__((packed)) cdc_acm_line_coding_t;

/**
 * @brief UART State Bitmap
 * @see Table 31, USB CDC-PSTN specification rev. 1.2
 */
typedef union {
    struct {
        uint16_t bRxCarrier : 1;  // State of receiver carrier detection mechanism of device. This signal corresponds to V.24 signal 109 and RS-232 signal DCD.
        uint16_t bTxCarrier : 1;  // State of transmission carrier. This signal corresponds to V.24 signal 106 and RS-232 signal DSR.
        uint16_t bBreak : 1;      // State of break detection mechanism of the device.
        uint16_t bRingSignal : 1; // State of ring signal detection of the device.
        uint16_t bFraming : 1;    // A framing error has occurred.
        uint16_t bParity : 1;     // A parity error has occurred.
        uint16_t bOverRun : 1;    // Received data has been discarded due to overrun in the device.
        uint16_t reserved : 9;
    };
    uint16_t val;
} cdc_acm_uart_state_t;

/**
 * @brief CDC-ACM Device Event types to upper layer
 *
 */
typedef enum {
    CDC_ACM_HOST_ERROR,
    CDC_ACM_HOST_SERIAL_STATE,
    CDC_ACM_HOST_NETWORK_CONNECTION,
    CDC_ACM_HOST_DEVICE_DISCONNECTED
} cdc_acm_host_dev_event_t;

/**
 * @brief CDC-ACM Device Event data structure
 *
 */
typedef struct {
    cdc_acm_host_dev_event_t type;
    union {
        int error;                         // Error code from USB Host
        cdc_acm_uart_state_t serial_state; // Serial (UART) state
        bool network_connected;            // Network connection event
    } data;
} cdc_acm_host_dev_event_data_t;

/**
 * @brief Data receive callback type
 */
typedef void (*cdc_acm_data_callback_t)(uint8_t *data, size_t data_len, void *user_arg);

/**
 * @brief Device event callback type
 * @see cdc_acm_host_dev_event_t
 */
typedef void (*cdc_acm_host_dev_callback_t)(cdc_acm_dev_hdl_t cdc_hdl, const cdc_acm_host_dev_event_data_t *event, void *user_ctx);

/**
 * @brief Configuration structure of USB Host CDC-ACM driver
 *
 */
typedef struct {
    size_t driver_task_stack_size; /**< Stack size of the driver's task */
    unsigned driver_task_priority; /**< Priority of the driver's task */
    int xCoreID;                   /**< Core affinity of the driver's task */
} cdc_acm_host_driver_config_t;

/**
 * @brief Configuration structure of CDC-ACM device
 *
 */
typedef struct {
    uint32_t connection_timeout_ms;       /**< Timeout for USB device connection in [ms] */
    size_t out_buffer_size;               /**< Maximum size of USB bulk out transfer, set to 0 for read-only devices */
    cdc_acm_host_dev_callback_t event_cb; /**< Device's event callback function. Can be NULL */
    cdc_acm_data_callback_t data_cb;      /**< Device's data RX callback function. Can be NULL for write-only devices */
    void *user_arg;                       /**< User's argument that will be passed to the callbacks */
} cdc_acm_host_device_config_t;

/////end cdc

//  stm32 dfu update

#define STM32_DFU_REQUEST_DETACH 0x00
#define STM32_DFU_REQUEST_DNLOAD 0x01
#define STM32_DFU_REQUEST_UPLOAD 0x02
#define STM32_DFU_REQUEST_GETSTATUS 0x03
#define STM32_DFU_REQUEST_CLRSTATUS 0x04
#define STM32_DFU_REQUEST_GETSTATE 0x05
#define STM32_DFU_REQUEST_ABORT 0x06

#define STM32_DFU_STATE_APP_IDLE 0
#define STM32_DFU_STATE_APP_DETACH 1
#define STM32_DFU_STATE_DFU_IDLE 2
#define STM32_DFU_STATE_DNLOAD_SYNC 3
#define STM32_DFU_STATE_DNBUSY 4
#define STM32_DFU_STATE_DNLOAD_IDLE 5
#define STM32_DFU_STATE_MAINFES_SYNC 6
#define STM32_DFU_STATE_MAINFEST 7
#define STM32_DFU_STATE_MAINFEST_WAIT_RESET 8
#define STM32_DFU_STATE_UPLOAD_IDLE 9
#define STM32_DFU_STATE_ERROR 10

////

/**
 * @brief Install USB Host Mass Storage Class driver
 *
 * @param[in] config configuration structure MSC to create
 * @return esp_err_r
 */
esp_err_t msc_host_install(const msc_host_driver_config_t *config);

/**
 * @brief Uninstall Mass Storage Class driver
 * @return esp_err_t
 */
esp_err_t msc_host_uninstall(void);

/**
 * @brief Initialization of MSC device.
 *
 * @param[in]  device_address  Device address obtained from MSC callback provided upon connection and enumeration
 * @param[out] device          Mass storage device handle to be used for subsequent calls.
 * @return esp_err_t
 */
esp_err_t msc_host_install_device(uint8_t device_address, msc_host_device_handle_t *device);

/**
 * @brief Deinitialization of MSC device.
 *
 * @param[in]  device  Device handle obtained from msc_host_install_device function
 * @return esp_err_t
 */
esp_err_t msc_host_uninstall_device(msc_host_device_handle_t device);

/**
 * @brief Helper function for reading sector from mass storage device.
 *
 * @warning This call is not thread safe and should not be combined
 *          with accesses to storage through file system.
 *
 * @note  Provided sector and size cannot exceed
 *        sector_count and sector_size obtained from msc_host_device_info_t
 *
 * @param[in]  device Device handle
 * @param[in]  sector Number of sector to be read
 * @param[out] data   Buffer into which data will be written
 * @param[in]  size   Number of bytes to be read
 * @return esp_err_t
 */
esp_err_t msc_host_read_sector(msc_host_device_handle_t device, size_t sector, void *data, size_t size);

/**
 * @brief Helper function for writing sector to mass storage device.
 *
 * @warning This call is not thread safe and should not be combined
 *          with accesses to storare through file system.
 *
 * @note  Provided sector and size cannot exceed
 *        sector_count and sector_size obtained from msc_host_device_info_t
 *
 * @param[in]  device Device handle
 * @param[in]  sector Number of sector to be read
 * @param[in]  data   Data to be written to the sector
 * @param[in]  size   Number of bytes to be written
 * @return esp_err_t
 */
esp_err_t msc_host_write_sector(msc_host_device_handle_t device, size_t sector, const void *data, size_t size);

/**
 * @brief Handle MSC HOST events.
 *
 * @param[in]  timeout_ms  Timeout in miliseconds
 * @return esp_err_t
 */
esp_err_t msc_host_handle_events(uint32_t timeout_ms);

/**
 * @brief Gets devices information.
 *
 * @warning This call is not thread safe and should not be combined
 *          with accesses to storare through file system.
 *
 * @param[in]  device  Handle to device
 * @param[out] info  Structure to be populated with device info
 * @return esp_err_t
 */
esp_err_t msc_host_get_device_info(msc_host_device_handle_t device, msc_host_device_info_t *info);

/**
 * @brief Print configuration descriptor.
 *
 * @param[in]  device  Handle of MSC device
 * @return esp_err_t
 */
esp_err_t msc_host_print_descriptors(msc_host_device_handle_t device);

esp_err_t cdc_host_open(uint16_t vid, uint16_t pid, uint8_t interface_idx, const cdc_acm_host_device_config_t *dev_config, cdc_acm_dev_hdl_t *cdc_hdl_ret);
void cdc_host_desc_print(cdc_acm_dev_hdl_t cdc_hdl);
void cdc_submit_transfer_in(cdc_acm_dev_hdl_t cdc_hdl);
int cdc_write_bytes(const uint8_t *buf, size_t length);
esp_err_t cdc_host_close(cdc_acm_dev_hdl_t cdc_hdl);

esp_err_t dfu_host_open(uint16_t vid, uint16_t pid, uint8_t interface_idx, const cdc_acm_host_device_config_t *dev_config, cdc_acm_dev_hdl_t *cdc_hdl_ret);
esp_err_t dfu_host_close(cdc_acm_dev_hdl_t cdc_hdl);

esp_err_t usbh_stm32_get_status_ex(uint8_t *out_result_data /*[6]*/, uint16_t timeout);
esp_err_t usbh_stm32_get_status(uint8_t *out_result_data /*[6]*/);
void usbh_stm32_get_chipinfo(char *descriptors, uint8_t count, uint8_t *actual_desc_count);
uint16_t usbh_stm32_get_transfer_block_size();

#ifdef __cplusplus
}
#endif //__cplusplus
