/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-03-30     chenyong     first version
 * 2018-04-12     chenyong     add client implement
 * 2018-08-17     chenyong     multiple client support
 * 2021-03-17     Meco Man     fix a buf of leaking memory
 * 2021-07-14     Sszl         fix a buf of leaking memory
 */

#include <at.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "sr_osal.h"


#define LOG_TAG              "at.clnt"
#include "sr_log.h"

#ifdef AT_USING_CLIENT

#define AT_RESP_END_OK                 "OK"
#define AT_RESP_END_ERROR              "ERROR"
#define AT_RESP_END_FAIL               "FAIL"
#define AT_END_CR_LF                   "\r\n"


static struct at_client at_client_table[AT_CLIENT_NUM_MAX] = { 0 };

extern srSize_t at_utils_send(SR_DEVICE_T *dev,
                               srOff_t    pos,
                               const void *buffer,
                               srSize_t   size);
extern srSize_t at_vprintfln(SR_DEVICE_T *device, const char *format, va_list args);
extern void at_print_raw_cmd(const char *type, const char *cmd, srSize_t size);
extern const char *at_get_last_cmd(srSize_t *cmd_size);

/**
 * Create response object.
 *
 * @param buf_size the maximum response buffer size
 * @param line_num the number of setting response lines
 *         = 0: the response data will auto return when received 'OK' or 'ERROR'
 *        != 0: the response data will return when received setting lines number data
 * @param timeout the maximum response time
 *
 * @return != SR_NULL: response object
 *          = SR_NULL: no memory
 */
at_response_t at_create_resp(srSize_t buf_size, srSize_t line_num, int32_t timeout)
{
    at_response_t resp = SR_NULL;

    resp = (at_response_t) SR_OsCalloc(1, sizeof(struct at_response));
    if (resp == SR_NULL)
    {
        SR_LOG(ERR,"AT create response object failed! No memory for response object!");
        return SR_NULL;
    }

    resp->buf = (char *) SR_OsCalloc(1, buf_size);
    if (resp->buf == SR_NULL)
    {
        SR_LOG(ERR,"AT create response object failed! No memory for response buffer!");
        SR_OsFree(resp);
        return SR_NULL;
    }

    resp->buf_size = buf_size;
    resp->line_num = line_num;
    resp->line_counts = 0;
    resp->timeout = timeout;

    return resp;
}

/**
 * Delete and free response object.
 *
 * @param resp response object
 */
void at_delete_resp(at_response_t resp)
{
    if (resp && resp->buf)
    {
        SR_OsFree(resp->buf);
    }

    if (resp)
    {
        SR_OsFree(resp);
        resp = SR_NULL;
    }
}


/**
 * Set response object information
 *
 * @param resp response object
 * @param buf_size the maximum response buffer size
 * @param line_num the number of setting response lines
 *         = 0: the response data will auto return when received 'OK' or 'ERROR'
 *        != 0: the response data will return when received setting lines number data
 * @param timeout the maximum response time
 *
 * @return  != SR_NULL: response object
 *           = SR_NULL: no memory
 */
at_response_t at_resp_set_info(at_response_t resp, srSize_t buf_size, srSize_t line_num, int32_t timeout)
{
    char *p_temp;
    SR_ASSERT_WHILE(resp);

    if (resp->buf_size != buf_size)
    {
        resp->buf_size = buf_size;

        p_temp = (char *) SR_OsRealloc(resp->buf, buf_size);
        if (p_temp == SR_NULL)
        {
            SR_LOG(DEBUG,"No memory for realloc response buffer size(%d).", buf_size);
            return SR_NULL;
        }
        else
        {
            resp->buf = p_temp;
        }
    }

    resp->line_num = line_num;
    resp->timeout = timeout;

    return resp;
}

/**
 * Get one line AT response buffer by line number.
 *
 * @param resp response object
 * @param resp_line line number, start from '1'
 *
 * @return != SR_NULL: response line buffer
 *          = SR_NULL: input response line error
 */
char *at_resp_get_line(at_response_t resp, srSize_t resp_line)
{
    char *resp_buf = resp->buf;
    char *resp_line_buf = SR_NULL;
    srSize_t line_num = 1;

    SR_ASSERT_WHILE(resp);

    if (resp_line > resp->line_counts || resp_line <= 0)
    {
        SR_LOG(ERR,"AT response get line failed! Input response line(%d) error!", resp_line);
        return SR_NULL;
    }

    for (line_num = 1; line_num <= resp->line_counts; line_num++)
    {
        if (resp_line == line_num)
        {
            resp_line_buf = resp_buf;

            return resp_line_buf;
        }

        resp_buf += strlen(resp_buf) + 1;
    }

    return SR_NULL;
}

/**
 * Get one line AT response buffer by keyword
 *
 * @param resp response object
 * @param keyword query keyword
 *
 * @return != SR_NULL: response line buffer
 *          = SR_NULL: no matching data
 */
char *at_resp_get_line_by_kw(at_response_t resp, const char *keyword)
{
    char *resp_buf = resp->buf;
    char *resp_line_buf = SR_NULL;
    srSize_t line_num = 1;

    SR_ASSERT_WHILE(resp);
    SR_ASSERT_WHILE(keyword);

    for (line_num = 1; line_num <= resp->line_counts; line_num++)
    {
        if (strstr(resp_buf, keyword))
        {
            resp_line_buf = resp_buf;

            return resp_line_buf;
        }

        resp_buf += strlen(resp_buf) + 1;
    }

    return SR_NULL;
}

/**
 * Get and parse AT response buffer arguments by line number.
 *
 * @param resp response object
 * @param resp_line line number, start from '1'
 * @param resp_expr response buffer expression
 *
 * @return -1 : input response line number error or get line buffer error
 *          0 : parsed without match
 *         >0 : the number of arguments successfully parsed
 */
int at_resp_parse_line_args(at_response_t resp, srSize_t resp_line, const char *resp_expr, ...)
{
    va_list args;
    int resp_args_num = 0;
    const char *resp_line_buf = SR_NULL;

    SR_ASSERT(resp);
    SR_ASSERT(resp_expr);

    if ((resp_line_buf = at_resp_get_line(resp, resp_line)) == SR_NULL)
    {
        return -1;
    }

    va_start(args, resp_expr);

    resp_args_num = vsscanf(resp_line_buf, resp_expr, args);

    va_end(args);

    return resp_args_num;
}

/**
 * Get and parse AT response buffer arguments by keyword.
 *
 * @param resp response object
 * @param keyword query keyword
 * @param resp_expr response buffer expression
 *
 * @return -1 : input keyword error or get line buffer error
 *          0 : parsed without match
 *         >0 : the number of arguments successfully parsed
 */
int at_resp_parse_line_args_by_kw(at_response_t resp, const char *keyword, const char *resp_expr, ...)
{
    va_list args;
    int resp_args_num = 0;
    const char *resp_line_buf = SR_NULL;

    SR_ASSERT(resp);
    SR_ASSERT(resp_expr);

    if ((resp_line_buf = at_resp_get_line_by_kw(resp, keyword)) == SR_NULL)
    {
        return -1;
    }

    va_start(args, resp_expr);

    resp_args_num = vsscanf(resp_line_buf, resp_expr, args);

    va_end(args);

    return resp_args_num;
}

/**
 * Send commands to AT server and wait response.
 *
 * @param client current AT client object
 * @param resp AT response object, using SR_NULL when you don't care response
 * @param cmd_expr AT commands expression
 *
 * @return 0 : success
 *        -1 : response status error
 *        -2 : wait timeout
 *        -7 : enter AT CLI mode
 */
int at_obj_exec_cmd(at_client_t client, at_response_t resp, const char *cmd_expr, ...)
{
    SR_GET_CT();
    va_list args;
    srSize_t cmd_size = 0;
    int result = SR_OK;
    const char *cmd = SR_NULL;

    SR_ASSERT(cmd_expr);

    if (client == SR_NULL)
    {
        SR_LOG(ERR,"input AT Client object is NULL, please create or get AT Client object!");
        return SR_FAIL;

    }

    /* check AT CLI mode */
    if (client->status == AT_STATUS_CLI && resp)
    {
        return SR_BUSY;
    }

		SR_CT_BEGIN();
		
    //rt_mutex_take(client->lock, OS_WAIT_FOREVER);
		SR_CT_MUTEX_TAKE(ct,&client->lock,OS_WAIT_FOREVER);

    client->resp_status = AT_RESP_OK;

    if (resp != SR_NULL)
    {
        resp->buf_len = 0;
        resp->line_counts = 0;
    }

    client->resp = resp;
    //rt_sem_control(client->resp_notice, RT_IPC_CMD_RESET, SR_NULL);
		SR_CT_SEM_INIT(&client->resp_notice,0);

    va_start(args, cmd_expr);
    at_vprintfln(client->device, cmd_expr, args);
    va_end(args);

    if (resp != SR_NULL)
    {
			  SR_CT_SEM_TAKE(ct,&client->resp_notice, resp->timeout);
        //if (rt_sem_take(client->resp_notice, resp->timeout) != SR_OK)
			  if(SR_CT_IS_TIMEOUT())
        {
            cmd = at_get_last_cmd(&cmd_size);
            SR_LOG(WARN,"execute command (%.*s) timeout (%d ticks)!", cmd_size, cmd, resp->timeout);
            client->resp_status = AT_RESP_TIMEOUT;
            result = SR_TIMEOUT;
            goto __exit;
        }
        if (client->resp_status != AT_RESP_OK)
        {
            cmd = at_get_last_cmd(&cmd_size);
            SR_LOG(ERR,"execute command (%.*s) failed!", cmd_size, cmd);
            result = SR_FAIL;
            goto __exit;
        }
    }

__exit:
    client->resp = SR_NULL;

    //rt_mutex_release(client->lock);
		SR_CT_MUTEX_RELEASE(&client->lock);

    return result;
	
		SR_CT_END();
}

/**
 * Waiting for connection to external devices.
 *
 * @param client current AT client object
 * @param timeout millisecond for timeout
 *
 * @return 0 : success
 *        -2 : timeout
 *        -5 : no memory
 */

int at_client_obj_wait_connect(at_client_t client, uint32_t timeout)
{
    SR_GET_CT();
    _AT_CLIENT_STACK_T *stack = (_AT_CLIENT_STACK_T *)SR_ALLOC_STACK(ct,sizeof(_AT_CLIENT_STACK_T));

    int result = SR_OK;
    // resp = SR_NULL;
    //srTick_t start_time = 0;


    if (client == SR_NULL)
    {
        SR_LOG(ERR,"input AT client object is NULL, please create or get AT Client object!");
	
		return SR_INVALID;
    }
		
		SR_CT_BEGIN();
	

		stack->resp = SR_NULL;
    stack->start_time = 0;

    stack->resp = at_create_resp(64, 0, SR_OsMsToTick(300));
    if (stack->resp == SR_NULL)
    {
        SR_LOG(ERR,"no memory for AT client(%s) response object.", client->device->name);
        return SR_NOMEM;

    }

    //rt_mutex_take(client->lock, OS_WAIT_FOREVER);
		SR_CT_MUTEX_TAKE(ct,&client->lock,OS_WAIT_FOREVER);
    client->resp = stack->resp;
    //rt_sem_control(client->resp_notice, RT_IPC_CMD_RESET, SR_NULL);
		SR_CT_SEM_INIT(&client->resp_notice, 0);  //信号量清0

    stack->start_time = SR_OsGetTick();

    while (1)
    {
        /* Check whether it is timeout */
        if (SR_OsGetTick() - stack->start_time > SR_OsMsToTick(timeout))
        {
            SR_LOG(ERR,"wait AT client(%s) connect timeout(%d tick).", client->device->name, timeout);
            result = SR_TIMEOUT;
            break;
        }

        /* Check whether it is already connected */
        stack->resp->buf_len = 0;
        stack->resp->line_counts = 0;
        at_utils_send(client->device, 0, "AT\r\n", 4);

				SR_CT_SEM_TAKE(ct,&client->resp_notice,stack->resp->timeout);	
        //if (rt_sem_take(client->resp_notice, stack->resp->timeout) != SR_OK)
				if(SR_CT_IS_TIMEOUT()==SR_TRUE)
            continue;   //超时，则重试
        else
            break;
    }

    at_delete_resp(stack->resp);

    client->resp = SR_NULL;

    //rt_mutex_release(client->lock);
		SR_CT_MUTEX_RELEASE(&client->lock);

    
		return result;
		
		SR_CT_END();
}

/**
 * Send data to AT server, send data don't have end sign(eg: \r\n).
 *
 * @param client current AT client object
 * @param buf   send data buffer
 * @param size  send fixed data size
 *
 * @return >0: send data size
 *         =0: send failed
 */
#if  1
srSize_t at_client_obj_send(at_client_t client, const char *buf, srSize_t size)
{
	  SR_GET_CT();
    srSize_t len;
	  
//    SR_ASSERT(buf);

//    if (client == SR_NULL)
//    {
//        SR_LOG(ERR,"input AT Client object is NULL, please create or get AT Client object!");
//        return 0;
//    }
		if(client == SR_NULL || buf==SR_NULL) return SR_INVALID;
	 
	SR_CT_BEGIN();

#ifdef AT_PRINT_RAW_CMD
    at_print_raw_cmd("sendline", buf, size);
#endif

    SR_CT_MUTEX_TAKE(ct,&client->lock,OS_WAIT_FOREVER);

    len = at_utils_send(client->device, 0, buf, size);

    SR_CT_MUTEX_RELEASE(&client->lock);

    return len;
		
	SR_CT_END();
}
#endif

#if  0
static int at_client_getchar(at_client_t client, char *ch, int32_t timeout)
{
    int result = SR_OK;

    while (rt_device_read(client->device, 0, ch, 1) == 0)
    {
        result = rt_sem_take(client->rx_notice, rt_tick_from_millisecond(timeout));
        if (result != SR_OK)
        {
            return result;
        }

        rt_sem_control(client->rx_notice, RT_IPC_CMD_RESET, SR_NULL);
    }

    return SR_OK;
}
#endif

/**
 * AT client receive fixed-length data.
 *
 * @param client current AT client object
 * @param buf   receive data buffer
 * @param size  receive fixed data size
 * @param timeout  receive data timeout (ms)
 *
 * @note this function can only be used in execution function of URC data
 *
 * @return >0: receive data size
 *         =0: receive failed
 */
#if   0
srSize_t at_client_obj_recv(at_client_t client, char *buf, srSize_t size, int32_t timeout)
{
    srSize_t len = 0;

    SR_ASSERT(buf);

    if (client == SR_NULL)
    {
        SR_LOG(ERR,"input AT Client object is NULL, please create or get AT Client object!");
        return 0;
    }

    while (1)
    {
        srSize_t read_len;

        rt_sem_control(client->rx_notice, RT_IPC_CMD_RESET, SR_NULL);

        read_len = rt_device_read(client->device, 0, buf + len, size);
        if(read_len > 0)
        {
            len += read_len;
            size -= read_len;
            if(size == 0)
                break;

            continue;
        }

        if(rt_sem_take(client->rx_notice, rt_tick_from_millisecond(timeout)) != SR_OK)
            break;
    }

#ifdef AT_PRINT_RAW_CMD
    at_print_raw_cmd("urc_recv", buf, len);
#endif

    return len;
}
#endif

/**
 *  AT client set end sign.
 *
 * @param client current AT client object
 * @param ch the end sign, can not be used when it is '\0'
 */
void at_obj_set_end_sign(at_client_t client, char ch)
{
    if (client == SR_NULL)
    {
        SR_LOG(ERR,"input AT Client object is NULL, please create or get AT Client object!");
        return;
    }

    client->end_sign = ch;
}

/**
 * set URC(Unsolicited Result Code) table
 *
 * @param client current AT client object
 * @param table URC table
 * @param size table size
 */
int at_obj_set_urc_table(at_client_t client, const struct at_urc *urc_table, srSize_t table_sz)
{
    srSize_t idx;

    if (client == SR_NULL)
    {
        SR_LOG(ERR,"input AT Client object is NULL, please create or get AT Client object!");
        return SR_FAIL;
    }

    for (idx = 0; idx < table_sz; idx++)
    {
        SR_ASSERT(urc_table[idx].cmd_prefix);
        SR_ASSERT(urc_table[idx].cmd_suffix);
    }

    if (client->urc_table_size == 0)
    {
        client->urc_table = (struct at_urc_table *) SR_OsCalloc(1, sizeof(struct at_urc_table));
        if (client->urc_table == SR_NULL)
        {
            return SR_NOMEM;
        }

        client->urc_table[0].urc = urc_table;
        client->urc_table[0].urc_size = table_sz;
        client->urc_table_size++;
    }
    else
    {
        struct at_urc_table *new_urc_table = SR_NULL;

        /* realloc urc table space */
        new_urc_table = (struct at_urc_table *) SR_OsRealloc(client->urc_table,client->urc_table_size * sizeof(struct at_urc_table) + sizeof(struct at_urc_table));
        if (new_urc_table == SR_NULL)
        {
            return SR_NOMEM;
        }
        client->urc_table = new_urc_table;
        client->urc_table[client->urc_table_size].urc = urc_table;
        client->urc_table[client->urc_table_size].urc_size = table_sz;
        client->urc_table_size++;

    }

    return SR_OK;
}

/**
 * get AT client object by AT device name.
 *
 * @dev_name AT client device name
 *
 * @return AT client object
 */
at_client_t at_client_get(const char *dev_name)
{
    int idx = 0;

    SR_ASSERT_WHILE(dev_name);

    for (idx = 0; idx < AT_CLIENT_NUM_MAX; idx++)
    {
        if (strcmp(at_client_table[idx].device->name, dev_name) == 0)
        {
            return &at_client_table[idx];
        }
    }

    return SR_NULL;
}

/**
 * get first AT client object in the table.
 *
 * @return AT client object
 */
at_client_t at_client_get_first(void)
{
    if (at_client_table[0].device == SR_NULL)
    {
        return SR_NULL;
    }

    return &at_client_table[0];
}

static const struct at_urc *get_urc_obj(at_client_t client)
{
    srSize_t i, j, prefix_len, suffix_len;
    srSize_t bufsz;
    char *buffer = SR_NULL;
    const struct at_urc *urc = SR_NULL;
    struct at_urc_table *urc_table = SR_NULL;

    if (client->urc_table == SR_NULL)
    {
        return SR_NULL;
    }

    buffer = client->recv_line_buf;
    bufsz = client->recv_line_len;

    for (i = 0; i < client->urc_table_size; i++)
    {
        for (j = 0; j < client->urc_table[i].urc_size; j++)
        {
            urc_table = client->urc_table + i;
            urc = urc_table->urc + j;

            prefix_len = strlen(urc->cmd_prefix);
            suffix_len = strlen(urc->cmd_suffix);
            if (bufsz < prefix_len + suffix_len)
            {
                continue;
            }
            if ((prefix_len ? !strncmp(buffer, urc->cmd_prefix, prefix_len) : 1)
                    && (suffix_len ? !strncmp(buffer + bufsz - suffix_len, urc->cmd_suffix, suffix_len) : 1))
            {
                return urc;
            }
        }
    }

    return SR_NULL;
}

static int at_recv_readline(at_client_t client)
{
    //srSize_t read_len = 0;  //(下次进来不需要保持上次值)
    SR_GET_CT();
    uint8_t ch = 0, last_ch = 0;
    srBool_t is_full = SR_FALSE;
	
	
		SR_CT_BEGIN();
	
    memset(client->recv_line_buf, 0x00, client->recv_bufsz);
    client->recv_line_len = 0;   //(client指向是全局的）
	

    while (1)
    {
        //at_client_getchar(client, &ch, OS_WAIT_FOREVER);
			  while (SR_RbReadByte(client->ringbuff,&ch) ==0)
        {
					//rt_sem_take(client->rx_notice, rt_tick_from_millisecond(timeout));
					//rt_sem_control(client->rx_notice, RT_IPC_CMD_RESET, RT_NULL);
					SR_CT_SEM_TAKE(ct, &client->rx_notice, OS_WAIT_FOREVER);
					SR_CT_SEM_INIT(&client->rx_notice, 0);  //信号量重置为0
					
					memset(client->recv_line_buf, 0x00, client->recv_bufsz);
          client->recv_line_len = 0;   
        }

				last_ch = (client->recv_line_len>=1)? client->recv_line_buf[client->recv_line_len-1]:0;
        if (client->recv_line_len < client->recv_bufsz)
        {
            client->recv_line_buf[client->recv_line_len++] = ch;
            //client->recv_line_len = read_len;
        }
        else
        {
            is_full = SR_TRUE;
        }

        /* is newline or URC data */
        if ((ch == '\n' && last_ch == '\r') || (client->end_sign != 0 && ch == client->end_sign)
                || get_urc_obj(client))
        {
            if (is_full)
            {
                SR_LOG(ERR,"read line failed. The line data length is out of buffer size(%d)!", client->recv_bufsz);
                memset(client->recv_line_buf, 0x00, client->recv_bufsz);
                client->recv_line_len = 0;
                
				return SR_FULL;

            }
            break;
        }
        //last_ch = ch;
    }

#ifdef AT_PRINT_RAW_CMD
    at_print_raw_cmd("recvline", client->recv_line_buf, read_len);
#endif

    //return read_len;
		//SR_CT_SET_RETURN(client->recv_line_len); //设置返回值
		return client->recv_line_len; 
		
		SR_CT_END();
}

//static void client_parser(at_client_t client)
//int client_parser(SR_CT_T *ct,at_client_t client)
int client_parser(void *args)
{
    const struct at_urc *urc;    
	  int ret;
	  SR_GET_CT();
	  at_client_t client = (at_client_t)args;
	
		SR_CT_BEGIN();

    while(1)
    { 
			  SR_CT_CHILD_RET(ret,at_recv_readline(client));  //调用子协程
			  //ret = SR_CT_GET_RETURN();
			  if (ret > 0)
        //if (at_recv_readline(client) > 0)
        {
            if ((urc = get_urc_obj(client)) != SR_NULL)
            {
                /* current receive is request, try to execute related operations */
                if (urc->func != SR_NULL)
                {
                    urc->func(client, client->recv_line_buf, client->recv_line_len);
                }
            }
            else if (client->resp != SR_NULL)
            {
                at_response_t resp = client->resp;

                char end_ch = client->recv_line_buf[client->recv_line_len - 1];
							
							  //SR_LOG(INFO,"recv: %s",client->recv_line_buf);

                /* current receive is response */
                client->recv_line_buf[client->recv_line_len - 1] = '\0';
                if (resp->buf_len + client->recv_line_len < resp->buf_size)
                {
                    /* copy response lines, separated by '\0' */
                    memcpy(resp->buf + resp->buf_len, client->recv_line_buf, client->recv_line_len);

                    /* update the current response information */
                    resp->buf_len += client->recv_line_len;
                    resp->line_counts++;
                }
                else
                {
                    client->resp_status = AT_RESP_BUFF_FULL;
                    SR_LOG(ERR,"Read response buffer failed. The Response buffer size is out of buffer size(%d)!", resp->buf_size);
                }
                /* check response result */
                if ((client->end_sign != 0) && (end_ch == client->end_sign) && (resp->line_num == 0))
                {
                    /* get the end sign, return response state END_OK.*/
                    client->resp_status = AT_RESP_OK;
                }
                //else if (memcmp(client->recv_line_buf, AT_RESP_END_OK, strlen(AT_RESP_END_OK)) == 0 && resp->line_num == 0)
                else if ((client->end_sign == 0)&&(resp->line_num == 0)&& memcmp(client->recv_line_buf, AT_RESP_END_OK, strlen(AT_RESP_END_OK)) == 0 )
								{
                    /* get the end data by response result, return response state END_OK. */
                    client->resp_status = AT_RESP_OK;
                }
                else if (strstr(client->recv_line_buf, AT_RESP_END_ERROR)
                        || (memcmp(client->recv_line_buf, AT_RESP_END_FAIL, strlen(AT_RESP_END_FAIL)) == 0))
                {
                    client->resp_status = AT_RESP_ERROR;
                }
                else if (resp->line_counts == resp->line_num && resp->line_num)
                {
                    /* get the end data by response line, return response state END_OK.*/
                    client->resp_status = AT_RESP_OK;
                }
                else
                {
									  
                    continue;
                }

                client->resp = SR_NULL;
                //rt_sem_release(client->resp_notice);
								SR_CT_SEM_RELEASE(&client->resp_notice);
            }
            else
            {
//                log_d("unrecognized line: %.*s", client->recv_line_len, client->recv_line_buf);
            }
        }
    }
		
		SR_CT_END();
}

//static int at_client_rx_ind(SR_DEVICE_T dev, srSize_t size)
static void at_client_rx_ind(SR_DEVICE_T *dev, SR_UART_EVENT_E event, uint32_t size, void *args)
{
    int tmpLen=0;
	  uint8_t buffer[720];
	  at_client_t client = (at_client_t)args;  //获取at client

//    for (idx = 0; idx < AT_CLIENT_NUM_MAX; idx++)
//    {
//        if (at_client_table[idx].device == dev && size > 0)
//        {
            //rt_sem_release(at_client_table[idx].rx_notice);
					
						//放进ringbuff
					  tmpLen = SR_HalUartRead(dev, buffer, size);
					  SR_RbWriteLen(client->ringbuff,buffer,tmpLen);
					
						//发信号量
					  SR_CT_SEM_RELEASE(&client->rx_notice);

//        }
//    }

}

/* initialize the client object parameters */
static int at_client_para_init(at_client_t client)
{
#define AT_CLIENT_LOCK_NAME            "at_c"
#define AT_CLIENT_SEM_NAME             "at_cs"
#define AT_CLIENT_RESP_NAME            "at_cr"
#define AT_CLIENT_THREAD_NAME          "at_clnt"

    int result = SR_OK;
    static int at_client_num = 0;
    //char name[RT_NAME_MAX];

    client->status = AT_STATUS_UNINITIALIZED;

    client->recv_line_len = 0;
    client->recv_line_buf = (char *) SR_OsCalloc(1, client->recv_bufsz);
    if (client->recv_line_buf == SR_NULL)
    {
        SR_LOG(ERR,"AT client initialize failed! No memory for receive buffer.");
        result = SR_NOMEM;
        goto __exit;
    }
		
		//创建ringbuff
		client->ringbuff = SR_RbCreate(client->recv_bufsz);
		if (client->ringbuff == SR_NULL)
    {
        SR_LOG(ERR,"AT client initialize failed! No memory(%d) for ringbuff.",client->recv_bufsz);
        result = SR_NOMEM;
        goto __exit;
    }

#ifdef SR_USE_OS
    snprintf(name, RT_NAME_MAX, "%s%d", AT_CLIENT_LOCK_NAME, at_client_num);
    client->lock = rt_mutex_create(name, RT_IPC_FLAG_PRIO);
    if (client->lock == SR_NULL)
    {
        SR_LOG(ERR,"AT client initialize failed! at_client_recv_lock create failed!");
        result = SR_NOMEM;
        goto __exit;
    }

    snprintf(name, RT_NAME_MAX, "%s%d", AT_CLIENT_SEM_NAME, at_client_num);
    client->rx_notice = rt_sem_create(name, 0, RT_IPC_FLAG_FIFO);
    if (client->rx_notice == SR_NULL)
    {
        SR_LOG(ERR,"AT client initialize failed! at_client_notice semaphore create failed!");
        result = SR_NOMEM;
        goto __exit;
    }

    snprintf(name, RT_NAME_MAX, "%s%d", AT_CLIENT_RESP_NAME, at_client_num);
    client->resp_notice = rt_sem_create(name, 0, RT_IPC_FLAG_FIFO);
    if (client->resp_notice == SR_NULL)
    {
        SR_LOG(ERR,"AT client initialize failed! at_client_resp semaphore create failed!");
        result = SR_NOMEM;
        goto __exit;
    }

    client->urc_table = SR_NULL;
    client->urc_table_size = 0;

    snprintf(name, RT_NAME_MAX, "%s%d", AT_CLIENT_THREAD_NAME, at_client_num);
    client->parser = rt_thread_create(name,
                                     (void (*)(void *parameter))client_parser,
                                     client,
                                     1024 + 512,
                                     RT_THREAD_PRIORITY_MAX / 3 - 1,
                                     5);
    if (client->parser == SR_NULL)
    {
        result = SR_NOMEM;
        goto __exit;
    }
		
#else

    //信号量、互斥量初始化
		SR_CT_SEM_INIT(&client->rx_notice, 0);
		SR_CT_SEM_INIT(&client->resp_notice, 0);
		SR_CT_MUTEX_INIT(&client->lock);
		
		//解析协程初始化
		//SR_CT_INIT(&client->ctParser);
		SR_OsThreadCreate("parser",client_parser,client,128,1);
		

#endif
		
__exit:
    if (result != SR_OK)
    {
#ifdef SR_USE_OS
        if (client->lock)
        {
            rt_mutex_delete(client->lock);
        }

        if (client->rx_notice)
        {
            rt_sem_delete(client->rx_notice);
        }

        if (client->resp_notice)
        {
            rt_sem_delete(client->resp_notice);
        }

        if (client->device)
        {
            rt_device_close(client->device);
        }
#endif
        if (client->recv_line_buf)
        {
            SR_OsFree(client->recv_line_buf);
        }
				
				if (client->ringbuff)
        {
            SR_RbDestroy(client->ringbuff);
        }

        memset(client, 0x00, sizeof(struct at_client));
    }
    else
    {
        at_client_num++;
    }

    return result;
}

/**
 * AT client initialize.
 *
 * @param dev_name AT client device name
 * @param recv_bufsz the maximum number of receive buffer length
 *
 * @return 0 : initialize success
 *        -1 : initialize failed
 *        -5 : no memory
 */
int at_client_init(struct at_client *client,uint8_t uartId, SR_UART_CFG_T *config,srSize_t recv_bufsz)
{
    //int idx = 0;
    int result = SR_OK;
    int open_result = SR_OK;
    //at_client_t client = SR_NULL;

    //SR_ASSERT(dev_name);
    SR_ASSERT(recv_bufsz > 0);
#if  0
    if (at_client_get(dev_name) != SR_NULL)
    {
        return result;
    }

    for (idx = 0; idx < AT_CLIENT_NUM_MAX && at_client_table[idx].device; idx++);

    if (idx >= AT_CLIENT_NUM_MAX)
    {
        SR_LOG(ERR,"AT client initialize failed! Check the maximum number(%d) of AT client.", AT_CLIENT_NUM_MAX);
        result = SR_FULL;
        goto __exit;
    }

		
    client = &at_client_table[idx];
#endif
    client->recv_bufsz = recv_bufsz;


    result = at_client_para_init(client);  //LW_ERR 考虑初始化失败场景资源释放
    if (result != SR_OK)
    {
        goto __exit;
    }

    /* find and open command device */
    client->device = SR_HalUartOpen((SR_UART_ID_E)uartId);
    if (client->device)
    {
        //SR_ASSERT(client->device->type == RT_Device_Class_Char);

        /* using DMA mode first */
        //open_result = rt_device_open(client->device, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_DMA_RX);
			  SR_HalUartSetCb(client->device, at_client_rx_ind, client);  //client作为用户参数
        open_result = SR_HalUartConfig(client->device, config);
			  (void )open_result;
        /* using interrupt mode when DMA mode not supported */
//        if (open_result == SR_EIO)
//        {
//            open_result = rt_device_open(client->device, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX);
//        }
//        SR_ASSERT(open_result == SR_OK);

        //rt_device_set_rx_indicate(client->device, at_client_rx_ind);
    }
    else
    {
        SR_LOG(ERR,"AT client initialize failed! Not find the uart(%d).", uartId);
        result = SR_FAIL;
        goto __exit;
    }

__exit:
    if (result == SR_OK)
    {
        client->status = AT_STATUS_INITIALIZED;

        //rt_thread_startup(client->parser);

        SR_LOG(INFO,"AT client(V%s) initialize success.", AT_SW_VERSION);
    }
    else
    {
        SR_LOG(ERR,"AT client(V%s) initialize failed(%d).", AT_SW_VERSION, result);
    }

    return result;
}





/**
 * @brief 清除响应对象内部的数据
 * @note  若使用公共的resp，则在发送下一个新的AT命令时，先清除公共resp对象的数据
 * @param[in] resp AT命令响应对象指针
 * 
 * @return 无
 */
void SR_AtClearRespData(at_response_t resp)
{
    resp->buf_len = 0;     //指示已收到的数据长度，清0
    resp->line_counts = 0; //指示已收到的AT命令响应的行数，清0
    memset(resp->buf,0,resp->buf_size);  //清空数据缓冲区
}


/**
 * @brief 发送AT命令并等待响应，支持重发和回调处理
 *
 * @param[in] client    当前AT Client对象指针
 * @param[in] resp      AT命令响应对象指针，若不关心响应可填SR_NULL。
 * @param[in] cb        AT命令执行OK后的回调处理函数，若不需要回调处理可填SR_NULL。
 * @param[in] timeout   等待响应超时时间，单位ms 
 * @param[in] resendCnt 重发次数
 * @param[in] cmdExpr   AT命令表达式
 * @param[in] ...       AT命令表达式的格式化参数
 *
 * @return SR_OK : AT响应为OK，若回调函数不为空且返回结果为0
 *         SR_FAIL : AT响应为ERROR，或者回调函数不为空且返回结果不为0
 *         SR_TIMEOUT : wait timeout
 *         SR_BUSY : enter AT CLI mode
 *         SR_INVALID : 参数错误
 */
int _AtResendCmdwithCb(at_client_t client, at_response_t resp,int (*cb)(at_client_t client,at_response_t resp),uint16_t timeout, uint8_t resendCnt,const char *cmdExpr, ...)
{
    SR_GET_CT();

    va_list args;
    srSize_t cmd_size = 0;
    const char *cmd = SR_NULL;
    int result = SR_OK;

    if (client == SR_NULL || cmdExpr==SR_NULL)  return SR_INVALID;

    /* check AT CLI mode */
    if (client->status == AT_STATUS_CLI && resp) return SR_BUSY;

	SR_CT_BEGIN();
		
    //获取互斥量
	SR_CT_MUTEX_TAKE(ct,&client->lock,OS_WAIT_FOREVER);

    client->resp_status = AT_RESP_OK;
    client->resendCnt = 0;

    if (resp != SR_NULL)
    {
        resp->buf_len = 0;
        resp->line_counts = 0;

        // 设置cmd发送超时时间
		resp->timeout = timeout; 
    }

__RESEND:
    client->resp = resp;

    //resp内部数据清除       
    SR_AtClearRespData(resp);
    
    //响应通知信号量复位（计数置0）
	SR_CT_SEM_INIT(&client->resp_notice,0);

    //组装格式化命令并发送
    va_start(args, cmdExpr);
    at_vprintfln(client->device, cmdExpr, args);
    va_end(args);

    if (resp != SR_NULL)
    {
        //获取响应通知信号量
        SR_CT_SEM_TAKE(ct,&client->resp_notice, resp->timeout);

        if(SR_CT_IS_TIMEOUT())
        {
            //判断为否超时
            cmd = at_get_last_cmd(&cmd_size);
            SR_LOG(WARN,"execute command (%.*s) timeout (%d ticks)!", cmd_size, cmd, resp->timeout);
            client->resp_status = AT_RESP_TIMEOUT;
            result = SR_TIMEOUT;
            client->resendCnt++;
            goto __exit;
        }
        if (client->resp_status != AT_RESP_OK)
        {
            //判断为ERROR响应
            cmd = at_get_last_cmd(&cmd_size);
            SR_LOG(ERR,"execute command (%.*s) failed!", cmd_size, cmd);
            result = SR_FAIL;
            client->resendCnt++;   
            
            //goto __exit;
        }
        else
        {
            //判断为OK响应
            if(cb != SR_NULL)
            {
                if(cb(client,resp) != 0)
                {
                    result = SR_FAIL;
                    client->resendCnt++;
                }
            }

        }
    }

__exit:
    client->resp = SR_NULL;

    if(result!=SR_OK && client->resendCnt <= resendCnt)   
    {       
        SR_CT_DELAY_MS( 500);
        goto __RESEND;  //重发
    }

    client->resendCnt = 0;

    //释放互斥量
	SR_CT_MUTEX_RELEASE(&client->lock);

    //返回执行结果
	return result;
		
		
	SR_CT_END();
}




#endif /* AT_USING_CLIENT */
