at_client.c 25.7 KB
Newer Older
Lawlieta's avatar
Lawlieta 已提交
1
/*
2
 * Copyright (c) 2006-2021, RT-Thread Development Team
Lawlieta's avatar
Lawlieta 已提交
3
 *
4
 * SPDX-License-Identifier: Apache-2.0
Lawlieta's avatar
Lawlieta 已提交
5 6 7 8 9
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-03-30     chenyong     first version
 * 2018-04-12     chenyong     add client implement
10
 * 2018-08-17     chenyong     multiple client support
11
 * 2021-03-17     Meco Man     fix a buf of leaking memory
S
sszl 已提交
12
 * 2021-07-14     Sszl         fix a buf of leaking memory
Lawlieta's avatar
Lawlieta 已提交
13 14 15 16 17 18 19
 */

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

20 21 22 23 24
#define LOG_TAG              "at.clnt"
#include <at_log.h>

#ifdef AT_USING_CLIENT

Lawlieta's avatar
Lawlieta 已提交
25 26 27 28 29
#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"

30
static struct at_client at_client_table[AT_CLIENT_NUM_MAX] = { 0 };
Lawlieta's avatar
Lawlieta 已提交
31

Comeon_fly's avatar
Comeon_fly 已提交
32 33 34 35
extern rt_size_t at_utils_send(rt_device_t dev,
                               rt_off_t    pos,
                               const void *buffer,
                               rt_size_t   size);
Lawlieta's avatar
Lawlieta 已提交
36 37 38 39 40
extern rt_size_t at_vprintfln(rt_device_t device, const char *format, va_list args);
extern void at_print_raw_cmd(const char *type, const char *cmd, rt_size_t size);
extern const char *at_get_last_cmd(rt_size_t *cmd_size);

/**
41
 * Create response object.
Lawlieta's avatar
Lawlieta 已提交
42 43 44 45 46 47 48
 *
 * @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
 *
49
 * @return != RT_NULL: response object
Lawlieta's avatar
Lawlieta 已提交
50 51 52 53 54 55 56
 *          = RT_NULL: no memory
 */
at_response_t at_create_resp(rt_size_t buf_size, rt_size_t line_num, rt_int32_t timeout)
{
    at_response_t resp = RT_NULL;

    resp = (at_response_t) rt_calloc(1, sizeof(struct at_response));
57
    if (resp == RT_NULL)
Lawlieta's avatar
Lawlieta 已提交
58
    {
59
        LOG_E("AT create response object failed! No memory for response object!");
Lawlieta's avatar
Lawlieta 已提交
60 61 62 63
        return RT_NULL;
    }

    resp->buf = (char *) rt_calloc(1, buf_size);
64
    if (resp->buf == RT_NULL)
Lawlieta's avatar
Lawlieta 已提交
65
    {
66
        LOG_E("AT create response object failed! No memory for response buffer!");
Lawlieta's avatar
Lawlieta 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79
        rt_free(resp);
        return RT_NULL;
    }

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

    return resp;
}

/**
80
 * Delete and free response object.
Lawlieta's avatar
Lawlieta 已提交
81
 *
82
 * @param resp response object
Lawlieta's avatar
Lawlieta 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
 */
void at_delete_resp(at_response_t resp)
{
    if (resp && resp->buf)
    {
        rt_free(resp->buf);
    }

    if (resp)
    {
        rt_free(resp);
        resp = RT_NULL;
    }
}

/**
99
 * Set response object information
Lawlieta's avatar
Lawlieta 已提交
100
 *
101
 * @param resp response object
Lawlieta's avatar
Lawlieta 已提交
102 103 104 105 106 107
 * @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
 *
108
 * @return  != RT_NULL: response object
Lawlieta's avatar
Lawlieta 已提交
109 110 111 112
 *           = RT_NULL: no memory
 */
at_response_t at_resp_set_info(at_response_t resp, rt_size_t buf_size, rt_size_t line_num, rt_int32_t timeout)
{
mysterywolf's avatar
mysterywolf 已提交
113
    char *p_temp;
Lawlieta's avatar
Lawlieta 已提交
114 115
    RT_ASSERT(resp);

116
    if (resp->buf_size != buf_size)
Lawlieta's avatar
Lawlieta 已提交
117 118 119
    {
        resp->buf_size = buf_size;

mysterywolf's avatar
mysterywolf 已提交
120 121
        p_temp = (char *) rt_realloc(resp->buf, buf_size);
        if (p_temp == RT_NULL)
Lawlieta's avatar
Lawlieta 已提交
122 123 124 125
        {
            LOG_D("No memory for realloc response buffer size(%d).", buf_size);
            return RT_NULL;
        }
mysterywolf's avatar
mysterywolf 已提交
126 127 128 129
        else
        {
            resp->buf = p_temp;
        }
Lawlieta's avatar
Lawlieta 已提交
130 131 132 133 134 135 136 137 138 139 140
    }

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

    return resp;
}

/**
 * Get one line AT response buffer by line number.
 *
141
 * @param resp response object
Lawlieta's avatar
Lawlieta 已提交
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178
 * @param resp_line line number, start from '1'
 *
 * @return != RT_NULL: response line buffer
 *          = RT_NULL: input response line error
 */
const char *at_resp_get_line(at_response_t resp, rt_size_t resp_line)
{
    char *resp_buf = resp->buf;
    char *resp_line_buf = RT_NULL;
    rt_size_t line_num = 1;

    RT_ASSERT(resp);

    if (resp_line > resp->line_counts || resp_line <= 0)
    {
        LOG_E("AT response get line failed! Input response line(%d) error!", resp_line);
        return RT_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 RT_NULL;
}

/**
 * Get one line AT response buffer by keyword
 *
179
 * @param resp response object
Lawlieta's avatar
Lawlieta 已提交
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
 * @param keyword query keyword
 *
 * @return != RT_NULL: response line buffer
 *          = RT_NULL: no matching data
 */
const char *at_resp_get_line_by_kw(at_response_t resp, const char *keyword)
{
    char *resp_buf = resp->buf;
    char *resp_line_buf = RT_NULL;
    rt_size_t line_num = 1;

    RT_ASSERT(resp);
    RT_ASSERT(keyword);

    for (line_num = 1; line_num <= resp->line_counts; line_num++)
    {
196
        if (strstr(resp_buf, keyword))
Lawlieta's avatar
Lawlieta 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
        {
            resp_line_buf = resp_buf;

            return resp_line_buf;
        }

        resp_buf += strlen(resp_buf) + 1;
    }

    return RT_NULL;
}

/**
 * Get and parse AT response buffer arguments by line number.
 *
212
 * @param resp response object
Lawlieta's avatar
Lawlieta 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
 * @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, rt_size_t resp_line, const char *resp_expr, ...)
{
    va_list args;
    int resp_args_num = 0;
    const char *resp_line_buf = RT_NULL;

    RT_ASSERT(resp);
    RT_ASSERT(resp_expr);

    if ((resp_line_buf = at_resp_get_line(resp, resp_line)) == RT_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.
 *
246
 * @param resp response object
Lawlieta's avatar
Lawlieta 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
 * @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 = RT_NULL;

    RT_ASSERT(resp);
    RT_ASSERT(resp_expr);

    if ((resp_line_buf = at_resp_get_line_by_kw(resp, keyword)) == RT_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.
 *
280 281
 * @param client current AT client object
 * @param resp AT response object, using RT_NULL when you don't care response
Lawlieta's avatar
Lawlieta 已提交
282 283 284 285 286
 * @param cmd_expr AT commands expression
 *
 * @return 0 : success
 *        -1 : response status error
 *        -2 : wait timeout
287
 *        -7 : enter AT CLI mode
Lawlieta's avatar
Lawlieta 已提交
288
 */
289
int at_obj_exec_cmd(at_client_t client, at_response_t resp, const char *cmd_expr, ...)
Lawlieta's avatar
Lawlieta 已提交
290 291 292 293 294 295 296 297
{
    va_list args;
    rt_size_t cmd_size = 0;
    rt_err_t result = RT_EOK;
    const char *cmd = RT_NULL;

    RT_ASSERT(cmd_expr);

298 299 300 301 302 303
    if (client == RT_NULL)
    {
        LOG_E("input AT Client object is NULL, please create or get AT Client object!");
        return -RT_ERROR;
    }

304 305 306 307 308 309
    /* check AT CLI mode */
    if (client->status == AT_STATUS_CLI && resp)
    {
        return -RT_EBUSY;
    }

Lawlieta's avatar
Lawlieta 已提交
310 311 312 313 314
    rt_mutex_take(client->lock, RT_WAITING_FOREVER);

    client->resp_status = AT_RESP_OK;
    client->resp = resp;

315 316 317 318 319 320
    if (resp != RT_NULL)
    {
        resp->buf_len = 0;
        resp->line_counts = 0;
    }

Lawlieta's avatar
Lawlieta 已提交
321 322 323 324
    va_start(args, cmd_expr);
    at_vprintfln(client->device, cmd_expr, args);
    va_end(args);

325
    if (resp != RT_NULL)
Lawlieta's avatar
Lawlieta 已提交
326 327 328 329
    {
        if (rt_sem_take(client->resp_notice, resp->timeout) != RT_EOK)
        {
            cmd = at_get_last_cmd(&cmd_size);
330
            LOG_D("execute command (%.*s) timeout (%d ticks)!", cmd_size, cmd, resp->timeout);
Lawlieta's avatar
Lawlieta 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
            client->resp_status = AT_RESP_TIMEOUT;
            result = -RT_ETIMEOUT;
            goto __exit;
        }
        if (client->resp_status != AT_RESP_OK)
        {
            cmd = at_get_last_cmd(&cmd_size);
            LOG_E("execute command (%.*s) failed!", cmd_size, cmd);
            result = -RT_ERROR;
            goto __exit;
        }
    }

__exit:
    client->resp = RT_NULL;

    rt_mutex_release(client->lock);

    return result;
}

Z
zylx 已提交
352 353 354
/**
 * Waiting for connection to external devices.
 *
355
 * @param client current AT client object
Z
zylx 已提交
356 357 358 359 360 361
 * @param timeout millisecond for timeout
 *
 * @return 0 : success
 *        -2 : timeout
 *        -5 : no memory
 */
362
int at_client_obj_wait_connect(at_client_t client, rt_uint32_t timeout)
Z
zylx 已提交
363 364 365 366
{
    rt_err_t result = RT_EOK;
    at_response_t resp = RT_NULL;
    rt_tick_t start_time = 0;
367
    char *client_name = client->device->parent.name;
Z
zylx 已提交
368

369 370
    if (client == RT_NULL)
    {
371
        LOG_E("input AT client object is NULL, please create or get AT Client object!");
372
        return -RT_ERROR;
373 374
    }

375
    resp = at_create_resp(64, 0, rt_tick_from_millisecond(300));
376
    if (resp == RT_NULL)
Z
zylx 已提交
377
    {
378
        LOG_E("no memory for AT client(%s) response object.", client_name);
Z
zylx 已提交
379 380 381 382 383 384 385 386 387 388 389
        return -RT_ENOMEM;
    }

    rt_mutex_take(client->lock, RT_WAITING_FOREVER);
    client->resp = resp;

    start_time = rt_tick_get();

    while (1)
    {
        /* Check whether it is timeout */
390
        if (rt_tick_get() - start_time > rt_tick_from_millisecond(timeout))
Z
zylx 已提交
391
        {
392
            LOG_E("wait AT client(%s) connect timeout(%d tick).", client_name, timeout);
Z
zylx 已提交
393 394 395 396 397
            result = -RT_ETIMEOUT;
            break;
        }

        /* Check whether it is already connected */
398
        resp->buf_len = 0;
Z
zylx 已提交
399
        resp->line_counts = 0;
Comeon_fly's avatar
Comeon_fly 已提交
400
        at_utils_send(client->device, 0, "AT\r\n", 4);
Z
zylx 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416

        if (rt_sem_take(client->resp_notice, resp->timeout) != RT_EOK)
            continue;
        else
            break;
    }

    at_delete_resp(resp);

    client->resp = RT_NULL;

    rt_mutex_release(client->lock);

    return result;
}

Lawlieta's avatar
Lawlieta 已提交
417 418 419
/**
 * Send data to AT server, send data don't have end sign(eg: \r\n).
 *
420
 * @param client current AT client object
Lawlieta's avatar
Lawlieta 已提交
421 422 423
 * @param buf   send data buffer
 * @param size  send fixed data size
 *
424 425
 * @return >0: send data size
 *         =0: send failed
Lawlieta's avatar
Lawlieta 已提交
426
 */
427
rt_size_t at_client_obj_send(at_client_t client, const char *buf, rt_size_t size)
Lawlieta's avatar
Lawlieta 已提交
428 429 430
{
    RT_ASSERT(buf);

431 432 433 434 435 436
    if (client == RT_NULL)
    {
        LOG_E("input AT Client object is NULL, please create or get AT Client object!");
        return 0;
    }

Lawlieta's avatar
Lawlieta 已提交
437
#ifdef AT_PRINT_RAW_CMD
438
    at_print_raw_cmd("sendline", buf, size);
Lawlieta's avatar
Lawlieta 已提交
439 440
#endif

Comeon_fly's avatar
Comeon_fly 已提交
441 442 443 444 445 446 447
    rt_mutex_take(client->lock, RT_WAITING_FOREVER);

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

    rt_mutex_release(client->lock);

    return len;
Lawlieta's avatar
Lawlieta 已提交
448 449
}

450
static rt_err_t at_client_getchar(at_client_t client, char *ch, rt_int32_t timeout)
Lawlieta's avatar
Lawlieta 已提交
451
{
452
    rt_err_t result = RT_EOK;
Lawlieta's avatar
Lawlieta 已提交
453

454
    while (rt_device_read(client->device, 0, ch, 1) == 0)
455
    {
456 457 458 459 460
        result = rt_sem_take(client->rx_notice, rt_tick_from_millisecond(timeout));
        if (result != RT_EOK)
        {
            return result;
        }
W
Wayne Lin 已提交
461 462

        rt_sem_control(client->rx_notice, RT_IPC_CMD_RESET, RT_NULL);
463
    }
464 465

    return RT_EOK;
Lawlieta's avatar
Lawlieta 已提交
466 467 468 469 470
}

/**
 * AT client receive fixed-length data.
 *
471
 * @param client current AT client object
Lawlieta's avatar
Lawlieta 已提交
472 473
 * @param buf   receive data buffer
 * @param size  receive fixed data size
474
 * @param timeout  receive data timeout (ms)
Lawlieta's avatar
Lawlieta 已提交
475 476 477
 *
 * @note this function can only be used in execution function of URC data
 *
478 479
 * @return >0: receive data size
 *         =0: receive failed
Lawlieta's avatar
Lawlieta 已提交
480
 */
481
rt_size_t at_client_obj_recv(at_client_t client, char *buf, rt_size_t size, rt_int32_t timeout)
Lawlieta's avatar
Lawlieta 已提交
482 483
{
    rt_size_t read_idx = 0;
484
    rt_err_t result = RT_EOK;
Lawlieta's avatar
Lawlieta 已提交
485 486 487 488
    char ch;

    RT_ASSERT(buf);

489 490 491 492 493 494
    if (client == RT_NULL)
    {
        LOG_E("input AT Client object is NULL, please create or get AT Client object!");
        return 0;
    }

Lawlieta's avatar
Lawlieta 已提交
495 496 497 498
    while (1)
    {
        if (read_idx < size)
        {
499 500 501 502 503 504
            result = at_client_getchar(client, &ch, timeout);
            if (result != RT_EOK)
            {
                LOG_E("AT Client receive failed, uart device get data error(%d)", result);
                return 0;
            }
Lawlieta's avatar
Lawlieta 已提交
505 506 507 508 509 510 511 512 513 514 515 516 517 518

            buf[read_idx++] = ch;
        }
        else
        {
            break;
        }
    }

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

    return read_idx;
519 520 521 522 523 524 525 526 527 528
}

/**
 *  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)
{
529 530 531 532 533
    if (client == RT_NULL)
    {
        LOG_E("input AT Client object is NULL, please create or get AT Client object!");
        return;
    }
Lawlieta's avatar
Lawlieta 已提交
534

535
    client->end_sign = ch;
Lawlieta's avatar
Lawlieta 已提交
536 537 538
}

/**
539
 * set URC(Unsolicited Result Code) table
Lawlieta's avatar
Lawlieta 已提交
540
 *
541 542 543
 * @param client current AT client object
 * @param table URC table
 * @param size table size
Lawlieta's avatar
Lawlieta 已提交
544
 */
545
int at_obj_set_urc_table(at_client_t client, const struct at_urc *urc_table, rt_size_t table_sz)
Lawlieta's avatar
Lawlieta 已提交
546
{
547 548
    rt_size_t idx;

549 550 551
    if (client == RT_NULL)
    {
        LOG_E("input AT Client object is NULL, please create or get AT Client object!");
552
        return -RT_ERROR;
553 554
    }

555 556 557 558 559
    for (idx = 0; idx < table_sz; idx++)
    {
        RT_ASSERT(urc_table[idx].cmd_prefix);
        RT_ASSERT(urc_table[idx].cmd_suffix);
    }
Lawlieta's avatar
Lawlieta 已提交
560

561 562 563 564 565 566 567 568 569 570 571 572 573 574
    if (client->urc_table_size == 0)
    {
        client->urc_table = (struct at_urc_table *) rt_calloc(1, sizeof(struct at_urc_table));
        if (client->urc_table == RT_NULL)
        {
            return -RT_ENOMEM;
        }

        client->urc_table[0].urc = urc_table;
        client->urc_table[0].urc_size = table_sz;
        client->urc_table_size++;
    }
    else
    {
S
sszl 已提交
575
        struct at_urc_table *new_urc_table = RT_NULL;
576

577
        /* realloc urc table space */
S
sszl 已提交
578 579
        new_urc_table = (struct at_urc_table *) rt_realloc(client->urc_table,client->urc_table_size * sizeof(struct at_urc_table) + sizeof(struct at_urc_table));
        if (new_urc_table == RT_NULL)
580 581 582
        {
            return -RT_ENOMEM;
        }
S
sszl 已提交
583
        client->urc_table = new_urc_table;
584 585 586
        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++;
587

588 589 590
    }

    return RT_EOK;
Lawlieta's avatar
Lawlieta 已提交
591 592 593
}

/**
594
 * get AT client object by AT device name.
Lawlieta's avatar
Lawlieta 已提交
595
 *
596
 * @dev_name AT client device name
Lawlieta's avatar
Lawlieta 已提交
597
 *
598
 * @return AT client object
Lawlieta's avatar
Lawlieta 已提交
599
 */
600
at_client_t at_client_get(const char *dev_name)
Lawlieta's avatar
Lawlieta 已提交
601
{
602
    int idx = 0;
Lawlieta's avatar
Lawlieta 已提交
603

604 605 606 607 608 609 610 611 612 613 614
    RT_ASSERT(dev_name);

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

    return RT_NULL;
Lawlieta's avatar
Lawlieta 已提交
615 616
}

617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
/**
 * 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 == RT_NULL)
    {
        return RT_NULL;
    }

    return &at_client_table[0];
}

static const struct at_urc *get_urc_obj(at_client_t client)
Lawlieta's avatar
Lawlieta 已提交
633
{
634 635
    rt_size_t i, j, prefix_len, suffix_len;
    rt_size_t bufsz;
636
    char *buffer = RT_NULL;
637 638
    const struct at_urc *urc = RT_NULL;
    struct at_urc_table *urc_table = RT_NULL;
Lawlieta's avatar
Lawlieta 已提交
639 640 641 642 643 644

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

645 646
    buffer = client->recv_line_buf;
    bufsz = client->recv_line_len;
647

Lawlieta's avatar
Lawlieta 已提交
648 649
    for (i = 0; i < client->urc_table_size; i++)
    {
650
        for (j = 0; j < client->urc_table[i].urc_size; j++)
Lawlieta's avatar
Lawlieta 已提交
651
        {
652 653 654 655 656 657 658 659 660 661 662 663 664 665
            urc_table = client->urc_table + i;
            urc = urc_table->urc + j;

            prefix_len = rt_strlen(urc->cmd_prefix);
            suffix_len = rt_strlen(urc->cmd_suffix);
            if (bufsz < prefix_len + suffix_len)
            {
                continue;
            }
            if ((prefix_len ? !rt_strncmp(buffer, urc->cmd_prefix, prefix_len) : 1)
                    && (suffix_len ? !rt_strncmp(buffer + bufsz - suffix_len, urc->cmd_suffix, suffix_len) : 1))
            {
                return urc;
            }
Lawlieta's avatar
Lawlieta 已提交
666 667 668 669 670 671
        }
    }

    return RT_NULL;
}

672
static int at_recv_readline(at_client_t client)
Lawlieta's avatar
Lawlieta 已提交
673 674 675 676 677
{
    rt_size_t read_len = 0;
    char ch = 0, last_ch = 0;
    rt_bool_t is_full = RT_FALSE;

678 679
    rt_memset(client->recv_line_buf, 0x00, client->recv_bufsz);
    client->recv_line_len = 0;
Lawlieta's avatar
Lawlieta 已提交
680 681 682

    while (1)
    {
683
        at_client_getchar(client, &ch, RT_WAITING_FOREVER);
Lawlieta's avatar
Lawlieta 已提交
684

685
        if (read_len < client->recv_bufsz)
Lawlieta's avatar
Lawlieta 已提交
686
        {
687 688
            client->recv_line_buf[read_len++] = ch;
            client->recv_line_len = read_len;
Lawlieta's avatar
Lawlieta 已提交
689 690 691 692 693 694 695
        }
        else
        {
            is_full = RT_TRUE;
        }

        /* is newline or URC data */
696 697
        if ((ch == '\n' && last_ch == '\r') || (client->end_sign != 0 && ch == client->end_sign)
                || get_urc_obj(client))
Lawlieta's avatar
Lawlieta 已提交
698 699 700
        {
            if (is_full)
            {
701
                LOG_E("read line failed. The line data length is out of buffer size(%d)!", client->recv_bufsz);
702 703
                rt_memset(client->recv_line_buf, 0x00, client->recv_bufsz);
                client->recv_line_len = 0;
Lawlieta's avatar
Lawlieta 已提交
704 705 706 707 708 709 710 711
                return -RT_EFULL;
            }
            break;
        }
        last_ch = ch;
    }

#ifdef AT_PRINT_RAW_CMD
712
    at_print_raw_cmd("recvline", client->recv_line_buf, read_len);
Lawlieta's avatar
Lawlieta 已提交
713 714 715 716 717 718 719 720 721 722 723
#endif

    return read_len;
}

static void client_parser(at_client_t client)
{
    const struct at_urc *urc;

    while(1)
    {
724
        if (at_recv_readline(client) > 0)
Lawlieta's avatar
Lawlieta 已提交
725
        {
726
            if ((urc = get_urc_obj(client)) != RT_NULL)
Lawlieta's avatar
Lawlieta 已提交
727 728 729 730
            {
                /* current receive is request, try to execute related operations */
                if (urc->func != RT_NULL)
                {
731
                    urc->func(client, client->recv_line_buf, client->recv_line_len);
Lawlieta's avatar
Lawlieta 已提交
732 733 734 735
                }
            }
            else if (client->resp != RT_NULL)
            {
736 737
                at_response_t resp = client->resp;

738 739
                char end_ch = client->recv_line_buf[client->recv_line_len - 1];

Lawlieta's avatar
Lawlieta 已提交
740
                /* current receive is response */
741 742
                client->recv_line_buf[client->recv_line_len - 1] = '\0';
                if (resp->buf_len + client->recv_line_len < resp->buf_size)
Lawlieta's avatar
Lawlieta 已提交
743 744
                {
                    /* copy response lines, separated by '\0' */
745
                    rt_memcpy(resp->buf + resp->buf_len, client->recv_line_buf, client->recv_line_len);
Lawlieta's avatar
Lawlieta 已提交
746

747 748 749
                    /* update the current response information */
                    resp->buf_len += client->recv_line_len;
                    resp->line_counts++;
Lawlieta's avatar
Lawlieta 已提交
750 751 752 753
                }
                else
                {
                    client->resp_status = AT_RESP_BUFF_FULL;
754
                    LOG_E("Read response buffer failed. The Response buffer size is out of buffer size(%d)!", resp->buf_size);
Lawlieta's avatar
Lawlieta 已提交
755 756
                }
                /* check response result */
757 758 759 760 761 762
                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 (rt_memcmp(client->recv_line_buf, AT_RESP_END_OK, rt_strlen(AT_RESP_END_OK)) == 0
763
                        && resp->line_num == 0)
Lawlieta's avatar
Lawlieta 已提交
764 765 766 767
                {
                    /* get the end data by response result, return response state END_OK. */
                    client->resp_status = AT_RESP_OK;
                }
768 769
                else if (rt_strstr(client->recv_line_buf, AT_RESP_END_ERROR)
                        || (rt_memcmp(client->recv_line_buf, AT_RESP_END_FAIL, rt_strlen(AT_RESP_END_FAIL)) == 0))
Lawlieta's avatar
Lawlieta 已提交
770 771 772
                {
                    client->resp_status = AT_RESP_ERROR;
                }
773
                else if (resp->line_counts == resp->line_num && resp->line_num)
Lawlieta's avatar
Lawlieta 已提交
774 775 776 777 778 779 780 781 782 783 784 785 786 787
                {
                    /* get the end data by response line, return response state END_OK.*/
                    client->resp_status = AT_RESP_OK;
                }
                else
                {
                    continue;
                }

                client->resp = RT_NULL;
                rt_sem_release(client->resp_notice);
            }
            else
            {
788
//                log_d("unrecognized line: %.*s", client->recv_line_len, client->recv_line_buf);
Lawlieta's avatar
Lawlieta 已提交
789 790 791 792 793 794 795
            }
        }
    }
}

static rt_err_t at_client_rx_ind(rt_device_t dev, rt_size_t size)
{
796 797 798
    int idx = 0;

    for (idx = 0; idx < AT_CLIENT_NUM_MAX; idx++)
799
    {
800 801 802 803
        if (at_client_table[idx].device == dev && size > 0)
        {
            rt_sem_release(at_client_table[idx].rx_notice);
        }
804 805
    }

Lawlieta's avatar
Lawlieta 已提交
806 807 808
    return RT_EOK;
}

809 810
/* initialize the client object parameters */
static int at_client_para_init(at_client_t client)
Lawlieta's avatar
Lawlieta 已提交
811
{
812 813 814 815
#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"
Lawlieta's avatar
Lawlieta 已提交
816 817

    int result = RT_EOK;
818 819
    static int at_client_num = 0;
    char name[RT_NAME_MAX];
Lawlieta's avatar
Lawlieta 已提交
820

821 822
    client->status = AT_STATUS_UNINITIALIZED;

823 824 825
    client->recv_line_len = 0;
    client->recv_line_buf = (char *) rt_calloc(1, client->recv_bufsz);
    if (client->recv_line_buf == RT_NULL)
Lawlieta's avatar
Lawlieta 已提交
826
    {
H
HubretXie 已提交
827
        LOG_E("AT client initialize failed! No memory for receive buffer.");
828 829
        result = -RT_ENOMEM;
        goto __exit;
Lawlieta's avatar
Lawlieta 已提交
830 831
    }

832 833 834
    rt_snprintf(name, RT_NAME_MAX, "%s%d", AT_CLIENT_LOCK_NAME, at_client_num);
    client->lock = rt_mutex_create(name, RT_IPC_FLAG_FIFO);
    if (client->lock == RT_NULL)
Lawlieta's avatar
Lawlieta 已提交
835
    {
836 837
        LOG_E("AT client initialize failed! at_client_recv_lock create failed!");
        result = -RT_ENOMEM;
Lawlieta's avatar
Lawlieta 已提交
838 839 840
        goto __exit;
    }

841 842 843
    rt_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 == RT_NULL)
Lawlieta's avatar
Lawlieta 已提交
844
    {
845
        LOG_E("AT client initialize failed! at_client_notice semaphore create failed!");
Lawlieta's avatar
Lawlieta 已提交
846 847 848 849
        result = -RT_ENOMEM;
        goto __exit;
    }

850 851 852
    rt_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 == RT_NULL)
Lawlieta's avatar
Lawlieta 已提交
853
    {
854
        LOG_E("AT client initialize failed! at_client_resp semaphore create failed!");
Lawlieta's avatar
Lawlieta 已提交
855 856 857 858
        result = -RT_ENOMEM;
        goto __exit;
    }

859 860 861 862 863 864 865 866 867 868 869
    client->urc_table = RT_NULL;
    client->urc_table_size = 0;

    rt_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 == RT_NULL)
Lawlieta's avatar
Lawlieta 已提交
870 871 872 873 874
    {
        result = -RT_ENOMEM;
        goto __exit;
    }

875 876
__exit:
    if (result != RT_EOK)
Lawlieta's avatar
Lawlieta 已提交
877
    {
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897
        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);
        }

898
        if (client->recv_line_buf)
899
        {
900
            rt_free(client->recv_line_buf);
901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
        }

        rt_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(const char *dev_name,  rt_size_t recv_bufsz)
{
    int idx = 0;
    int result = RT_EOK;
    rt_err_t open_result = RT_EOK;
    at_client_t client = RT_NULL;

    RT_ASSERT(dev_name);
    RT_ASSERT(recv_bufsz > 0);

933 934 935 936 937
    if (at_client_get(dev_name) != RT_NULL)
    {
        return result;
    }

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

    if (idx >= AT_CLIENT_NUM_MAX)
    {
L
luofanlu 已提交
942
        LOG_E("AT client initialize failed! Check the maximum number(%d) of AT client.", AT_CLIENT_NUM_MAX);
943 944 945 946 947 948 949
        result = -RT_EFULL;
        goto __exit;
    }

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

950 951 952 953 954 955
    result = at_client_para_init(client);
    if (result != RT_EOK)
    {
        goto __exit;
    }

956 957 958 959 960
    /* find and open command device */
    client->device = rt_device_find(dev_name);
    if (client->device)
    {
        RT_ASSERT(client->device->type == RT_Device_Class_Char);
Lawlieta's avatar
Lawlieta 已提交
961

962
        /* using DMA mode first */
963
        open_result = rt_device_open(client->device, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_DMA_RX);
964 965 966
        /* using interrupt mode when DMA mode not supported */
        if (open_result == -RT_EIO)
        {
967
            open_result = rt_device_open(client->device, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX);
968 969
        }
        RT_ASSERT(open_result == RT_EOK);
Lawlieta's avatar
Lawlieta 已提交
970

971
        rt_device_set_rx_indicate(client->device, at_client_rx_ind);
Lawlieta's avatar
Lawlieta 已提交
972 973 974
    }
    else
    {
975
        LOG_E("AT client initialize failed! Not find the device(%s).", dev_name);
Lawlieta's avatar
Lawlieta 已提交
976 977 978 979 980
        result = -RT_ERROR;
        goto __exit;
    }

__exit:
981
    if (result == RT_EOK)
Lawlieta's avatar
Lawlieta 已提交
982
    {
983
        client->status = AT_STATUS_INITIALIZED;
Lawlieta's avatar
Lawlieta 已提交
984

985
        rt_thread_startup(client->parser);
Lawlieta's avatar
Lawlieta 已提交
986

987
        LOG_I("AT client(V%s) on device %s initialize success.", AT_SW_VERSION, dev_name);
Lawlieta's avatar
Lawlieta 已提交
988 989 990
    }
    else
    {
991
        LOG_E("AT client(V%s) on device %s initialize failed(%d).", AT_SW_VERSION, dev_name, result);
Lawlieta's avatar
Lawlieta 已提交
992 993 994 995
    }

    return result;
}
996
#endif /* AT_USING_CLIENT */