#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "./SYSTEM/usart/usart.h"
#include "./hmi_cmd_example.h"
#include "./hmi/hmi_cmd.h"
#include "./hmi/hmi_rx_parse.h"
#include "./BSP/USART2/usart2.h"
#include "./SYSTEM/delay/delay.h"


void caddsend_sine(char *name, uint8_t ch)
{
    int x, y;
    float k;
    for (x = 0; x <= 999999; x++)
    {
        k = sin(0.1 * x);
        y = 80 * k + 125;
        api_cadd(name, ch, y);
    }
}

bool caddtsend_sine(char *name, uint8_t ch, uint16_t points)
{
    int y;
    float k;

    bool res = api_caddt(name, ch, points);
    if (!res) return false;

    cmd_res_t *back_res = hmi_cmd_back_res();
    if (!strstr(back_res->val.str, "start"))
    {
        return false;
    }

    for (int x = 0; x < points; x++)
    {
        k = sin(0.1 * x); //波形大小
        y = 80 * k + 125; //垂直幅度
        usart2_send_data((uint8_t *)&y, 1);
    }

    res = hmi_cmd_wait_parse(RET_CADDT);
    if (!res) return false;

    back_res = hmi_cmd_back_res();
    if (!strstr(back_res->val.str, "end"))
    {
        return false;
    }

    return true;
}

void hmi_cmd_example(void)
{
    bool res;
    cmd_res_t *back;
    
    printf("\r\n--------------------------->\r\n");
    API_REST();
    HAL_Delay(5000);

    res = API_ACK();
    if (!res)
    {
        printf("HMI DEVICE NO ACK!");
    }
    res = API_VERSION();
    if (res)
    {
        back = hmi_cmd_back_res();
        printf("%s\r\n", back->val.str);
    }

    res = API_GET_CODE();
    if (res)
    {
        back = hmi_cmd_back_res();
        printf("%s\r\n", back->val.str);
    }

    API_PAGE(12);
    HAL_Delay(50);
    API_MOVE(t0, 5, 212, 150, 212, 200, 0);
    HAL_Delay(50);
    API_PLAY("/1.ATKA", 1);
    HAL_Delay(2000);
    hmi_cmd_send("sys.audio0=0;");
    API_CLICK(b2, 0);
    HAL_Delay(2000);
    hmi_cmd_send("sys.audio0=0;");
    API_VIS(b4, 0);
    API_TSW(b5, 0);
    for (int i = 0; i < 100; i++)
        API_CADD(c0, 1, 200);
    API_COVX(tn0.val, t7.txt.str, 0, 0);
    API_COVX(t8.txt.str, csl0.val, 0, 0);
    API_RTCS(2023, 8, 21, 10, 40, 0);

    API_BEEP(8, 1000);
    API_RANDSET(1, 10);
    API_CCLEAR(c0, 1);

    caddtsend_sine("c0", 1, 1002);
    HAL_Delay(3000);
    API_CCLEAR(c0, 1);
    res = API_GET(b2.txt.str);
    if (res)
    {
        back = hmi_cmd_back_res();
        printf("%s\r\n", back->val.str);  /* s:播放音乐; */
    }

    res = API_GET(b2.x);
    if (res)
    {
        back = hmi_cmd_back_res();
        printf("%d\r\n", back->val.value);
    }
}

