at_server.c 14.1 KB
Newer Older
Lawlieta's avatar
Lawlieta 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 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 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 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 246 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 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
/*
 * File      : at_server.c
 * This file is part of RT-Thread RTOS
 * COPYRIGHT (C) 2006 - 2018, RT-Thread Development Team
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Change Logs:
 * Date           Author       Notes
 * 2018-03-30     chenyong     first version
 * 2018-04-14     chenyong     modify parse arguments
 */

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

#include <rthw.h>

#define AT_CMD_CHAR_0                  '0'
#define AT_CMD_CHAR_9                  '9'
#define AT_CMD_QUESTION_MARK           '?'
#define AT_CMD_EQUAL_MARK              '='
#define AT_CMD_L_SQ_BRACKET            '['
#define AT_CMD_R_SQ_BRACKET            ']'
#define AT_CMD_L_ANGLE_BRACKET         '<'
#define AT_CMD_R_ANGLE_BRACKET         '>'
#define AT_CMD_COMMA_MARK              ','
#define AT_CMD_SEMICOLON               ';'
#define AT_CMD_CR                      '\r'
#define AT_CMD_LF                      '\n'

static at_server_t at_server_local = RT_NULL;
static at_cmd_t cmd_table = RT_NULL;
static rt_size_t cmd_num;

extern void at_vprintf(rt_device_t device, const char *format, va_list args);
extern void at_vprintfln(rt_device_t device, const char *format, va_list args);

/**
 * AT server send data to AT device
 *
 * @param format the input format
 */
void at_server_printf(const char *format, ...)
{
    va_list args;

    va_start(args, format);

    at_vprintf(at_server_local->device, format, args);

    va_end(args);
}

/**
 * AT server send data and newline to AT device
 *
 * @param format the input format
 */
void at_server_printfln(const char *format, ...)
{
    va_list args;

    va_start(args, format);

    at_vprintfln(at_server_local->device, format, args);

    va_end(args);
}


/**
 * AT server request arguments parse arguments
 *
 * @param req_args request arguments
 * @param req_expr request expression
 *
 * @return  -1 : parse arguments failed
 *           0 : parse without match
 *          >0 : The number of arguments successfully parsed
 */
int at_req_parse_args(const char *req_args, const char *req_expr, ...)
{
    va_list args;
    int req_args_num = 0;

    RT_ASSERT(req_args);
    RT_ASSERT(req_expr);

    va_start(args, req_expr);

    req_args_num = vsscanf(req_args, req_expr, args);

    va_end(args);

    return req_args_num;
}

/**
 * AT server send command execute result to AT device
 *
 * @param result AT command execute result
 */
void at_server_print_result(at_result_t result)
{
    switch (result)
    {
    case AT_RESULT_OK:
        at_server_printfln("");
        at_server_printfln("OK");
        break;

    case AT_RESULT_FAILE:
        at_server_printfln("");
        at_server_printfln("ERROR");
        break;

    case AT_RESULT_NULL:
        break;

    case AT_RESULT_CMD_ERR:
        at_server_printfln("ERR CMD MATCH FAILED!");
        at_server_print_result(AT_RESULT_FAILE);
        break;

    case AT_RESULT_CHECK_FAILE:
        at_server_printfln("ERR CHECK ARGS FORMAT FAILED!");
        at_server_print_result(AT_RESULT_FAILE);
        break;

    case AT_RESULT_PARSE_FAILE:
        at_server_printfln("ERR PARSE ARGS FAILED!");
        at_server_print_result(AT_RESULT_FAILE);
        break;

    default:
        break;
    }
}

/**
 *  AT server print all commands to AT device
 */
void rt_at_server_print_all_cmd(void)
{
    rt_size_t i = 0;

    at_server_printfln("Commands list : ");

    for (i = 0; i < cmd_num; i++)
    {
        at_server_printf("%s", cmd_table[i].name);

        if (cmd_table[i].args_expr)
        {
            at_server_printfln("%s", cmd_table[i].args_expr);
        }
        else
        {
            at_server_printf("%c%c", AT_CMD_CR, AT_CMD_LF);
        }
    }
}

at_server_t at_get_server(void)
{
    RT_ASSERT(at_server_local);
    RT_ASSERT(at_server_local->status != AT_STATUS_UNINITIALIZED);

    return at_server_local;
}

static rt_err_t at_check_args(const char *args, const char *args_format)
{
    rt_size_t left_sq_bracket_num = 0, right_sq_bracket_num = 0;
    rt_size_t left_angle_bracket_num = 0, right_angle_bracket_num = 0;
    rt_size_t comma_mark_num = 0;
    rt_size_t i = 0;

    RT_ASSERT(args);
    RT_ASSERT(args_format);

    for (i = 0; i < strlen(args_format); i++)
    {
        switch (args_format[i])
        {
        case AT_CMD_L_SQ_BRACKET:
            left_sq_bracket_num++;
            break;

        case AT_CMD_R_SQ_BRACKET:
            right_sq_bracket_num++;
            break;

        case AT_CMD_L_ANGLE_BRACKET:
            left_angle_bracket_num++;
            break;

        case AT_CMD_R_ANGLE_BRACKET:
            right_angle_bracket_num++;
            break;

        default:
            break;
        }
    }

    if (left_sq_bracket_num != right_sq_bracket_num || left_angle_bracket_num != right_angle_bracket_num
            || left_sq_bracket_num > left_angle_bracket_num)
    {
        return -RT_ERROR;
    }

    for (i = 0; i < strlen(args); i++)
    {
        if (args[i] == AT_CMD_COMMA_MARK)
        {
            comma_mark_num++;
        }
    }

    if ((comma_mark_num + 1 < left_angle_bracket_num - left_sq_bracket_num)
            || comma_mark_num + 1 > left_angle_bracket_num)
    {
        return -RT_ERROR;
    }

    return RT_EOK;
}

static rt_err_t at_cmd_process(at_cmd_t cmd, const char *cmd_args)
{
    at_result_t result = AT_RESULT_OK;

    RT_ASSERT(cmd);
    RT_ASSERT(cmd_args);

    if (cmd_args[0] == AT_CMD_EQUAL_MARK && cmd_args[1] == AT_CMD_QUESTION_MARK && cmd_args[2] == AT_CMD_CR)
    {
        if (cmd->test == RT_NULL)
        {
            at_server_print_result(AT_RESULT_CMD_ERR);
            return -RT_ERROR;
        }

        result = cmd->test();
        at_server_print_result(result);
    }
    else if (cmd_args[0] == AT_CMD_QUESTION_MARK && cmd_args[1] == AT_CMD_CR)
    {
        if (cmd->query == RT_NULL)
        {
            at_server_print_result(AT_RESULT_CMD_ERR);
            return -RT_ERROR;
        }

        result = cmd->query();
        at_server_print_result(result);
    }
    else if (cmd_args[0] == AT_CMD_EQUAL_MARK
            || (cmd_args[0] >= AT_CMD_CHAR_0 && cmd_args[0] <= AT_CMD_CHAR_9 && cmd_args[1] == AT_CMD_CR))
    {
        if (cmd->setup == RT_NULL)
        {
            at_server_print_result(AT_RESULT_CMD_ERR);
            return -RT_ERROR;
        }

        if(at_check_args(cmd_args, cmd->args_expr) < 0)
        {
            at_server_print_result(AT_RESULT_CHECK_FAILE);
            return -RT_ERROR;
        }

        result = cmd->setup(cmd_args);
        at_server_print_result(result);
    }
    else if (cmd_args[0] == AT_CMD_CR)
    {
        if (cmd->exec == RT_NULL)
        {
            at_server_print_result(AT_RESULT_CMD_ERR);
            return -RT_ERROR;
        }

        result = cmd->exec();
        at_server_print_result(result);
    }
    else
    {
        return -RT_ERROR;
    }

    return RT_EOK;
}

static at_cmd_t at_find_cmd(const char *cmd)
{
    rt_size_t i = 0;

    RT_ASSERT(cmd_table);

    for (i = 0; i < cmd_num; i++)
    {
        if (!strcasecmp(cmd, cmd_table[i].name))
        {
            return &cmd_table[i];
        }
    }
    return RT_NULL;
}

static rt_err_t at_cmd_get_name(const char *cmd_buffer, char *cmd_name)
{
    rt_size_t cmd_name_len = 0, i = 0;

    RT_ASSERT(cmd_name);
    RT_ASSERT(cmd_buffer);

    for (i = 0; i < strlen(cmd_buffer) + 1; i++)
    {
        if (*(cmd_buffer + i) == AT_CMD_QUESTION_MARK || *(cmd_buffer + i) == AT_CMD_EQUAL_MARK
                || *(cmd_buffer + i) == AT_CMD_CR
                || (*(cmd_buffer + i) >= AT_CMD_CHAR_0 && *(cmd_buffer + i) <= AT_CMD_CHAR_9))
        {
            cmd_name_len = i;
            memcpy(cmd_name, cmd_buffer, cmd_name_len);
            *(cmd_name + cmd_name_len) = '\0';

            return RT_EOK;
        }
    }

    return -RT_ERROR;
}

static char at_server_gerchar(void)
{
    char ch;

    rt_sem_take(at_server_local->rx_notice, RT_WAITING_FOREVER);

    rt_device_read(at_server_local->device, 0, &ch, 1);

    return ch;
}

static void server_parser(at_server_t server)
{
#define ESC_KEY                 0x1B
#define BACKSPACE_KEY           0x08
#define DELECT_KEY              0x7F

    char cur_cmd_name[AT_CMD_NAME_LEN] = { 0 };
    at_cmd_t cur_cmd = RT_NULL;
    char *cur_cmd_args = RT_NULL, ch, last_ch;

    RT_ASSERT(server);
    RT_ASSERT(server->status != AT_STATUS_UNINITIALIZED);

    while (ESC_KEY != (ch = server->get_char()))
    {
        if (server->echo_mode)
        {
            if (ch == AT_CMD_CR || (ch == AT_CMD_LF && last_ch != AT_CMD_CR))
            {
                at_server_printf("%c%c", AT_CMD_CR, AT_CMD_LF);
            }
            else if (ch == BACKSPACE_KEY || ch == DELECT_KEY)
            {
                if (server->cur_recv_len)
                {
                    server->recv_buffer[--server->cur_recv_len] = 0;
                    at_server_printf("\b \b");
                }

                continue;
            }
            else
            {
                at_server_printf("%c", ch);
            }
        }

        server->recv_buffer[server->cur_recv_len++] = ch;
        last_ch = ch;

        if(!strstr(server->recv_buffer, server->end_mark))
        {
            continue;
        }

        if (at_cmd_get_name(server->recv_buffer, cur_cmd_name) < 0)
        {
            at_server_print_result(AT_RESULT_CMD_ERR);
            goto __retry;
        }

        cur_cmd = at_find_cmd(cur_cmd_name);
        if (!cur_cmd)
        {
            at_server_print_result(AT_RESULT_CMD_ERR);
            goto __retry;
        }

        cur_cmd_args = server->recv_buffer + strlen(cur_cmd_name);
        if (at_cmd_process(cur_cmd, cur_cmd_args) < 0)
        {
            goto __retry;
        }

__retry:
        memset(server->recv_buffer, 0x00, AT_SERVER_RECV_BUFF_LEN);
        server->cur_recv_len = 0;
    }
}

static rt_err_t at_rx_ind(rt_device_t dev, rt_size_t size)
{
    rt_sem_release(at_server_local->rx_notice);

    return RT_EOK;
}

#if defined(__ICCARM__) || defined(__ICCRX__)               /* for IAR compiler */
#pragma section="RtAtCmdTab"
#endif

int at_server_init(void)
{
    rt_err_t result = RT_EOK;

    if (at_server_local)
    {
        return result;
    }

    /* initialize the AT commands table.*/
#if defined(__CC_ARM)                                 /* ARM C Compiler */
    extern const int RtAtCmdTab$$Base;
    extern const int RtAtCmdTab$$Limit;
    cmd_table = (at_cmd_t)&RtAtCmdTab$$Base;
    cmd_num = (at_cmd_t)&RtAtCmdTab$$Limit - cmd_table;
#elif defined (__ICCARM__) || defined(__ICCRX__)      /* for IAR Compiler */
    cmd_table = (at_cmd_t)__section_begin("RtAtCmdTab");
    cmd_num = (at_cmd_t)__section_end("RtAtCmdTab") - cmd_table;
#elif defined (__GNUC__)                             /* for GCC Compiler */
    extern const int __rtatcmdtab_start;
    extern const int __rtatcmdtab_end;
    cmd_table = (at_cmd_t)&__rtatcmdtab_start;
    cmd_num = (at_cmd_t) &__rtatcmdtab_end - cmd_table;
#endif /* defined(__CC_ARM) */

    at_server_local = (at_server_t) rt_calloc(1, sizeof(struct at_server));
    if (!at_server_local)
    {
        result = -RT_ENOMEM;
        LOG_E("AT server session initialize failed! No memory for at_server structure !");
        goto __exit;
    }

    at_server_local->echo_mode = 1;
    at_server_local->status = AT_STATUS_UNINITIALIZED;

    memset(at_server_local->recv_buffer, 0x00, AT_SERVER_RECV_BUFF_LEN);
    at_server_local->cur_recv_len = 0;

    at_server_local->rx_notice = rt_sem_create("at_server_notice", 0, RT_IPC_FLAG_FIFO);
    if (!at_server_local->rx_notice)
    {
        LOG_E("AT server session initialize failed! at_rx_notice semaphore create failed!");
        result = -RT_ENOMEM;
        goto __exit;
    }

    /* Find and open command device */
    at_server_local->device = rt_device_find(AT_SERVER_DEVICE);
    if (at_server_local->device)
    {
        RT_ASSERT(at_server_local->device->type == RT_Device_Class_Char);

        rt_device_open(at_server_local->device, RT_DEVICE_OFLAG_RDWR | RT_DEVICE_FLAG_INT_RX);

        rt_device_set_rx_indicate(at_server_local->device, at_rx_ind);
    }
    else
    {
        LOG_E("AT device initialize failed! Not find the device : %s.", AT_SERVER_DEVICE);
        result = -RT_ERROR;
        goto __exit;
    }

    at_server_local->get_char = at_server_gerchar;
    memcpy(at_server_local->end_mark, AT_CMD_END_MARK, sizeof(AT_CMD_END_MARK));

    at_server_local->parser_entry = server_parser;
    at_server_local->parser = rt_thread_create("at_server",
                                         (void (*)(void *parameter))server_parser,
                                         at_server_local,
                                         2 * 1024,
                                         RT_THREAD_PRIORITY_MAX / 3 - 1,
                                         5);
    if (at_server_local->parser == RT_NULL)
    {
        result = -RT_ENOMEM;
        goto __exit;
    }

__exit:
    if (!result)
    {
        at_server_local->status = AT_STATUS_INITIALIZED;

        rt_thread_startup(at_server_local->parser);

        LOG_I("RT-Thread AT server (V%s) initialize success.", AT_SW_VERSION);
    }
    else
    {
        if (at_server_local)
        {
            rt_free(at_server_local);
        }

        LOG_E("RT-Thread AT server (V%s) initialize failed(%d).", AT_SW_VERSION, result);
    }

    return result;
}
INIT_COMPONENT_EXPORT(at_server_init);

RT_WEAK void at_port_reset(void)
{
    LOG_E("The reset for AT server is not implement.");
}

RT_WEAK void at_port_factory_reset(void)
{
    LOG_E("The factory reset for AT server is not implement.");
}