#include <termios.h>
#include <linux/serial.h>

#include "common.h"

int modem_send_data(int fd, char *buf, int len, char *expect)
{
    char rcv_buf[64] = {0};
    int ret = 0;
    int retry_cnt = 0;
    int ret_len = 0;
    char print_buf[4096];

    if (fd < 0)
        return -1;
retry:
    tcflush(fd, TCIFLUSH);
    dy_syslog_hex(LOG_DEBUG, buf, len, "send buf:");
    ret_len = uart_send(fd, buf, len);
    if (ret_len <= 0)
    {
        dy_syslog(LOG_ERR, "set buf to BLE failed");
        ret = -1;
    }
    else
    {
        ret_len = uart_recv(fd, rcv_buf, sizeof(rcv_buf));
        if (ret_len > 0)
        {
            dy_syslog_hex(LOG_DEBUG, rcv_buf, ret_len, "rcv back");
            if (expect != NULL && strlen(expect) > 0)
            {
                int t = ViolentMatch(rcv_buf, ret_len, expect, strlen(expect));
                if (t != -1)
                {
                    ret = 0;
                }
                else
                {
                    ret = -1;
                    retry_cnt++;
                    if (retry_cnt < 10)
                    {
                        goto retry;
                    }
                }
            }
        }
    }

    return ret;
}