1@page page_component_at AT Commands
2
3# Introduction to AT Commands
4
5The AT command set was originally a control protocol invented by Dennis Hayes, initially used to control dial-up modems. Later, with the upgrade of network bandwidth, low-speed dial-up modems with very low speed essentially exited the general market, but the AT command set was retained. However, the AT command set lived on when major mobile phone manufacturers jointly developed a set of commands to control the GSM modules of mobile phones. The AT command set evolved on this basis and added the GSM 07.05 standard and the later GSM 07.07 standard to achieve more robust standardization.
6
7After seeing use in GPRS control, 3G modules and similar devices, AT commands gradually become the de facto standard in product development. Nowadays, AT commands are also widely used in embedded development. AT commands are the protocol interfaces of the main chip and communication module. The hardware interface is usually the serial port, so the main control device can complete various operations through simple commands and hardware design.
8
9**AT commands are a way of facilitating device connections and data communication between an AT Server and an AT Client.** The basic structure is shown below:
10
11![AT Command Set](figures/at_framework.jpg)
12
131. The AT command consists of three parts: prefix, body, and terminator. The prefix consists of the character AT; the body consists of commands, parameters, and possibly used data; the terminator typically is `<CR><LF>` (`"\r\n"`).
14
152. The implementation of AT functionality requires the AT Server and the AT Client to work together.
16
173. An AT Server mainly receives commands sent by the AT Client, interprets the received commands and parameter formats, and delivers corresponding response data or actively sends data.
18
194. An AT Client is mainly used to send commands, wait for the AT Server to respond, and parse the AT Server response data or the actively sent data to obtain related information.
20
215. A variety of data communication methods (UART, SPI, etc.) are supported between an AT Server and an AT Client. Currently, the most commonly used communications protocol is UART.
22
236. The data that the AT Server sends to the AT Client is divided into two types: response data and URC data.
24
25- Response Data: The AT Server response status and information received by the AT Client after sending the command.
26
27- URC Data: Data that the AT Server actively sends to the AT Client generally appears only in some special cases, such as when a WiFi connection is disconnected, while it's receiving TCP data, etc. These situations often require special user handling.
28
29With the popularization of AT commands, more and more embedded products use AT commands. The AT commands are used as the protocol interfaces of the main chip and the communication module. The hardware interface is generally a serial port, so that the master device can performs a variety of operations using simple commands and hardware design.
30
31Although the AT command set has standardization to a certain degree, the AT commands supported by different chips are not completely unified, which directly increases the complexity to use. There is no uniform way to handle the sending and receiving of AT commands and the parsing of data.
32
33In order to facilitate the user to use AT commands which can be easily adapted to different AT modules, RT-Thread provides AT components for AT Device connectivity and data communication. The implementation of the AT components consists of both a client and a server.
34
35# Introduction to AT Components
36
37The AT component is based on the implementation of the `AT Server` and `AT Client` of the RT-Thread system. The component completes the AT command transmission, command format and parameter parsing, command response, response data reception, response data parsing, URC data processing, etc..
38
39**Command data interaction process.**
40
41Through the AT component, the device can use the serial port to connect to other devices to send and receive parsed data. It can be used as an AT Server to allow other devices or even the computer to connect to complete the response of sending data. It can also start the CLI mode in the local shell to enable the device to support AT Server and AT Client at the same time. The usage of both modes simultaneously is mostly used for device development and debugging.
42
43**AT component resource usage:**
44
45- AT Client: 4.6K ROM and 2.0K RAM;
46
47- AT Server: 4.0K ROM and 2.5K RAM;
48
49- AT CLI: 1.5K ROM and almost no RAM is used.
50
51Overall, the AT component resources are extremely small, making them ideal for use in embedded devices with limited resources. The AT component code is primarily located in `rt-thread/components/net/at/`. What follows are the main function of both AT Servers and AT Clients.
52
53**Main Functions of AT Server:**
54
55- Basic commands: A variety of common basic commands are implemented (ATE, ATZ, etc.);
56- Command compatibility: Commands are case-insensitive, which increases command compatibility;
57- Command detection: Commands support custom parameter expressions and implement self-detection of received command parameters;
58- Command registration: User-defined commands can be easily added, in a way, similar to how the  `finsh/msh`  command is added;
59- Debug mode: An AT Server CLI command line interaction mode is provided, which is mainly used for device debugging.
60
61**Main Functions of AT Client:**
62
63- URC data processing: The complete URC data processing method;
64- Data analysis: Supports the analysis of custom response data, and facilitates the acquisition of relevant information in the response data;
65- Debug mode: Provides AT Client CLI command line interaction mode, mainly used for device debugging;
66- AT Socket: An extension of AT Client function, it uses the AT command set to send and receive as the basis. This is implemented through the standard BSD Socket API, which completes the data sending and receiving function, and enables users to implement complete device networking and data communication through AT commands.
67- Multi-client support: The AT component supports multiple clients running simultaneously.
68
69# AT Server
70
71## AT Server Configuration ###
72
73When we use the AT Server feature in the AT component, we need to define the following configuration in rtconfig.h:
74
75| **Macro Definition** | **Description** |
76| ----  | ---- |
77|RT_USING_AT| Enable AT component |
78|AT_USING_SERVER  |Enable AT Server function|
79|AT_SERVER_DEVICE |Define the serial communication device name used by AT Server on the device to ensure that it is not used and the device name is unique, such as `uart3` device.|
80|AT_SERVER_RECV_BUFF_LEN|The maximum length of data received by the AT Server device|
81|AT_CMD_END_MARK_CRLF|Determine the line terminator of the received command |
82|AT_USING_CLI | Enable server-command-line interaction mode |
83|AT_DEBUG|Enable AT component DEBUG mode to display more debug log information |
84|AT_PRINT_RAW_CMD | Enable real-time display AT command communication data mode for easy debugging |
85
86For different AT devices, there are several formats of the line terminator for the sending commands:  `"\r\n"`、`"\r"`、`"\n"` - the user needs to select the corresponding line terminator in accordance to the device type connected to the AT Server and then determine the end of transmission command, defined as follows:
87
88| **Macro Definition** | **Terminator** |
89| ----  | ---- |
90| AT_CMD_END_MARK_CRLF | `"\r\n"` |
91| AT_CMD_END_MARK_CR   | `"\r"`    |
92| AT_CMD_END_MARK_LF   | `"\n"`    |
93
94The above configuration options can be added by Env tool. The specific path in Env is as follows:
95
96```c
97RT-Thread Components  --->
98    Network  --->
99        AT commands  --->
100            [*] Enable AT commands
101            [*]   Enable debug log output
102            [*] Enable AT commands server
103            (uart3) Server device name
104            (256)   The maximum length of server data accepted
105                    The commands new line sign (\r\n)  --->
106            [ ]   Enable AT commands client
107            [*]   Enable command-line interface for AT commands
108            [ ]   Enable print RAW format AT command communication data
109```
110
111After the add configuration is complete, you can use the command line to rebuild the project, or use `scons` to compile.
112
113## AT Server Initialization
114
115After enabling the AT Server in Env, you need to initialize it at startup to enable the AT Server function. If the component has been initialized automatically, no additional initialization is required. Otherwise, you need to call the following function in the initialization task:
116
117```c
118int at_server_init(void);
119```
120The AT Server initialization function, which belongs to the application layer function, needs to be called before using the AT Server function or using the AT Server CLI function. `at_server_init()` function completes initialization of resources stored by AT commands, such as data segment initialization, AT Server device initialization, and semaphore usage by the AT Server. It also creates an at_server thread for parsing the received data in the AT Server.
121
122After the AT Server is successfully initialized, the device can be used as an AT Server to connect to an AT Client's serial device for data communication, or use a serial-to-USB conversion tool to connect to a PC, so that the PC-side serial debugging assistant can communicate with the AT Client.
123
124## Add custom AT commands
125
126At present, the format of the AT command set used by AT devices of different manufacturers does not have a completely uniform standard, so the AT Server in the AT component only supports some basic general AT commands, such as ATE, AT+RST, etc. These commands can only be used to meet the basic operation of the device. If users want to use more functions, they need to implement custom AT Server commands for different AT devices. The AT component provides an AT command addition method similar to the FinSH/msh command addition method, which is convenient for users to implement the required commands.
127
128The basic commands currently supported by AT Server are as follows:
129
130- AT: AT test command;
131- ATZ: The device is restored to factory settings;
132- AT+RST: Reboot device;
133- ATE: ATE1 turns on echo, ATE0 turns off echo;
134- AT&L: List all commands;
135- AT+UART: Set the serial port information.
136
137AT commands can implement different functions depending on the format of the incoming parameters. For each AT command, there are up to four functions, as described below:
138
139- Test Function: `AT+<x>=?`, used to query the command's parameter, format and value range;
140- Query Function: `AT+<x>?`, used to return the current value of the command parameter;
141- Setting Function: `AT+<x>=...`, used for user-defined parameter values;
142- Execution Function: `AT+<x>`, used to perform related operations.
143
144The four functions of each command do not need to be fully implemented. When you add an AT Server command, you can implement one or several of the above functions according to your needs. Unimplemented functions can be represented by `NULL`. Then the custom function can be added to the list of basic commands. The addition method is similar to the way the `finsh/msh` commands are added. The function for adding commands is as follows:
145
146```c
147AT_CMD_EXPORT(_name_, _args_expr_, _test_, _query_, _setup_, _exec_);
148```
149
150|**Parameter**  |**Description**                        |
151| ---------- | ------------------------------- |
152| `_name_ `        | AT command name            |
153| `_args_expr_`    | AT command parameter expression; (NULL means no parameter, `<>` means mandatory parameter and `[]` means optional parameter) |
154| `_test_`     | AT test function name; (NULL means no parameter) |
155| `_query_` | AT query function name; (ibid.) |
156| `_setup_` | AT setup function name; (ibid.) |
157| `_exec_` | AT performs the function name; (ibid.) |
158
159The AT command registration example is as follows. The `AT+TEST` command has two parameters. The first parameter is a mandatory parameter, and the second parameter is an optional parameter. The command implements the query function and the execution function:
160
161```c
162static at_result_t at_test_exec(void)
163{
164    at_server_printfln("AT test commands execute!");
165
166    return 0;
167}
168static at_result_t at_test_query(void)
169{
170    at_server_printfln("AT+TEST=1,2");
171
172    return 0;
173}
174
175AT_CMD_EXPORT("AT+TEST", =<value1>[,<value2>], NULL, at_test_query, NULL, at_test_exec);
176```
177
178## AT Server APIs
179
180### Send Data to the Client (no newline)
181
182```c
183void at_server_printf(const char *format, ...);
184```
185
186This function is used by the AT Server to send fixed-format data to the corresponding AT Client serial device through the serial device. The data ends without a line break. Used to customize the function functions of AT commands in AT Server.
187
188|  **Parameter**  | **D**escription           |
189|------|-------------------------|
190| format | Customize the expression of the input data |
191|   ...  | Input data list, variable parameters |
192
193### Send Data to the Client (newline)
194
195```c
196void at_server_printfln(const char *format, ...);
197```
198
199This function is used by the AT Server to send fixed-format data to the corresponding AT Client serial device through the serial device, with a newline at the end of the data. Used to customize the function functions of AT commands in AT Server.
200
201|  **Parameter**  | **Description**           |
202|------|-------------------------|
203| format | Customize the expression of the input data |
204|   ...  | Input data list, variable parameters |
205
206### Send Command Execution Results to the Client
207
208```c
209void at_server_print_result(at_result_t result);
210```
211
212This function is used by the AT Server to send command execution results to the corresponding AT Client serial device through the serial device. The AT component provides a variety of fixed command execution result types. When you customize a command, you can use the function to return the result directly;
213
214|  **Parameter**  | **Description**   |
215|------|-----------------|
216| result | Command execution result type |
217
218The command execution result type in the AT component is given in the enumerated type, as shown in the following table:
219
220|     Types of Command Execution Result     |        Description        |
221|------------------------|------------------|
222|      AT_RESULT_OK      |    Command Execution Succeeded    |
223|     AT_RESULT_FAILE    |    Command Execution Failed    |
224|     AT_RESULT_NULL     | Command No Result |
225|   AT_RESULT_CMD_ERR   |    Command Input Error    |
226| AT_RESULT_CHECK_FAILE | Parameter Expression Matching Error |
227| AT_RESULT_PARSE_FAILE |    Parameter Parsing Error    |
228
229See the following code to learn how to use the `at_server_print_result` function:
230
231```c
232static at_result_t at_test_setup(const char *args)
233{
234    if(!args)
235    {
236        /* If the parameter error after incoming orders, returns expression match error results */
237        at_server_print_result(AT_RESULT_CHECK_FAILE);
238    }
239
240    /* Return to successful execution under normal conditions */
241    at_server_print_result(AT_RESULT_OK);
242    return 0;
243}
244static at_result_t at_test_exec(void)
245{
246    // execute some functions of the AT command.
247
248    /* This command does not need to return results */
249    at_server_print_result(AT_RESULT_NULL);
250    return 0;
251}
252AT_CMD_EXPORT("AT+TEST", =<value1>,<value2>, NULL, NULL, at_test_setup, at_test_exec);
253```
254
255### Parsing Input Command Parameters
256
257```c
258int at_req_parse_args(const char *req_args, const char *req_expr, ...);
259```
260
261Among the four functions of an AT command, only the setting function has an input parameter, and the input parameter is to remove the rest of the AT command. For example, for a given command input `"AT+TEST=1,2,3,4"`, set the input parameter of the function to the parameter string `"=1,2,3,4"`.
262
263The command parsing function is mainly used in the AT function setting function, which is used to parse the incoming string parameter and obtain corresponding multiple input parameters for performing the following operations. The standard `sscanf` parsing grammar used in parsing grammar here will also be described in detail later in the AT Client parameter parsing function.
264
265|   **Parameter**   | **Description**                                 |
266|---------|-----------------------------------------------|
267| req_args | The incoming parameter string of the request command |
268| req_expr | Custom parameter parsing expression for parsing the above incoming parameter data |
269|    ...    | Output parsing parameter list, which is a variable parameter |
270|   **Return**   | --                                           |
271|    >0    | Successful, returns the number of variable parameters matching the parameter expression |
272|     =0    | Failed, no parameters matching the parameter expression |
273|     -1    | Failed, parameter parsing error |
274
275See the following code to learn how to use the at_server_print_result function:
276
277```c
278static at_result_t at_test_setup(const char *args)
279{
280    int value1,value2;
281
282    /* The input standard format of args should be "=1, 2", "=%d, %d" is a custom parameter parsing expression, and the result is parsed and stored in the value1 and value2 variables. */
283    if (at_req_parse_args(args, "=%d,%d", &value1, &value2) > 0)
284    {
285        /* Data analysis succeeds, echoing data to AT Server serial device */
286        at_server_printfln("value1 : %d, value2 : %d", value1, value2);
287
288        /* The data is parsed successfully. The number of parsing parameters is greater than zero. The execution is successful. */
289        at_server_print_result(AT_RESULT_OK);
290    }
291    else
292    {
293        /* Data parsing failed, the number of parsing parameters is not greater than zero, and the parsing failure result type is returned. */
294        at_server_print_result(AT_RESULT_PARSE_FAILE);
295    }
296    return 0;
297}
298/* Add the "AT+TEST" command to the AT command list. The command parameters are formatted as two mandatory parameters <value1> and <value2>. */
299AT_CMD_EXPORT("AT+TEST", =<value1>,<value2>, NULL, NULL, at_test_setup, NULL);
300```
301
302### Porting-related interfaces
303
304The AT Server supports a variety of basic commands (ATE, ATZ, etc.) by default. The function implementation of some commands is related to hardware or platform and requires user-defined implementation. The AT component source code `src/at_server.c` file gives the weak function definition of the migration file. The user can create a new migration file in the project to implement the following function to complete the migration interface, or modify the weak function to complete the migration interface directly in the file.
305
3061. Device restart function: `void at_port_reset(void);`. This function completes the device soft restart function and is used to implement the basic command AT+RST in AT Server.
307
3082. The device restores the factory settings function: `void at_port_factory_reset(void);`. This function completes the device factory reset function and is used to implement the basic command ATZ in AT Server.
309
3103. Add a command table in the link script (add only in gcc, no need to add in Keil and IAR).
311
312If you use the gcc toolchain in your project, you need to add the *section* corresponding to the AT server command table in the link script. Refer to the following link script:
313
314```c
315/* Constant data goes into FLASH */
316.rodata :
317{
318    ...
319
320    /* section information for RT-thread AT package */
321    . = ALIGN(4);
322    __rtatcmdtab_start = .;
323    KEEP(*(RtAtCmdTab))
324    __rtatcmdtab_end = .;
325    . = ALIGN(4);
326} > CODE
327```
328
329# AT Client
330
331## AT Client Configuration
332
333When using the AT Client feature in the AT component, the following configuration in rtconfig.h needs to be defined:
334
335```c
336#define RT_USING_AT
337#define AT_USING_CLIENT
338#define AT_CLIENT_NUM_MAX 1
339#define AT_USING_SOCKET
340#define AT_USING_CLI
341#define AT_PRINT_RAW_CMD
342```
343
344- `RT_USING_AT`: Used to enable or disable the AT component;
345
346- `AT_USING_CLIENT`: Used to enable the AT Client function;
347
348- `AT_CLIENT_NUM_MAX`: Maximum number of AT clients supported at the same time.
349
350- `AT_USING_SOCKET`: Used by the AT client to support the standard BSD Socket API and enable the AT Socket function.
351
352- `AT_USING_CLI`: Used to enable or disable the client command line interaction mode.
353
354- `AT_PRINT_RAW_CMD`: Used to enable the real-time display mode of AT command communication data for easy debugging.
355
356The above configuration options can be added directly to the `rtconfig.h` file or added by the Env. The specific path in Env is as follows:
357
358```c
359RT-Thread Components  --->
360    Network  --->
361        AT commands  --->
362            [*] Enable AT commands
363            [ ]   Enable debug log output
364            [ ]   Enable AT commands server
365            [*]   Enable AT commands client
366            (1)   The maximum number of supported clients
367            [*]   Enable BSD Socket API support by AT commnads
368            [*]   Enable command-line interface for AT commands
369            [ ]   Enable print RAW format AT command communication data
370```
371
372After the configuration is complete, you can use the command line to rebuild the project, or use `scons` to compile.
373
374## AT Client Initialization
375
376After configuring the AT Client, you need to initialize it at startup to enable the AT Client function. If the component has been initialized automatically, no additional initialization is required. Otherwise, you need to call the following function in the initialization task:
377
378```c
379int at_client_init(const char *dev_name,  rt_size_t recv_bufsz);
380```
381
382The AT Client initialization function, which belongs to the application layer function, needs to be called before using the AT Client function or using the AT Client CLI function. The `at_client_init()` function completes the initialization of the AT Client device, the initialization of the AT Client porting function, the semaphore and mutex used by the AT Client, and other resources, and creates the  `at_client` thread for parsing the data received in the AT Client and for processing the URC data.
383
384## AT Client data receiving and sending
385
386The main function of the AT Client is to send AT commands, receive data, and parse data. The following is an introduction to the processes and APIs related to AT Client data reception and transmission.
387
388Related structure definition:
389
390```c
391struct at_response
392{
393    /* response buffer */
394    char *buf;
395    /* the maximum response buffer size */
396    rt_size_t buf_size;
397    /* the number of setting response lines
398     * == 0: the response data will auto return when received 'OK' or 'ERROR'
399     * != 0: the response data will return when received setting lines number data */
400    rt_size_t line_num;
401    /* the count of received response lines */
402    rt_size_t line_counts;
403    /* the maximum response time */
404    rt_int32_t timeout;
405};
406typedef struct at_response *at_response_t;
407```
408
409In the AT component, this structure is used to define a control block for AT command response data, which is used to store or limit the data format of the AT command response data.
410
411-  `buf` is used to store the received response data. Note that the data stored in the buf is not the original response data, but the data of the original response data removal terminator (`"\r\n"`). Each row of data in the buf is split by '\0' to make it easy to get data by row.
412- `buf_size`  is a user-defined length of the received data that is most supported by this response. The length of the return value is defined by the user according to his own command.
413- `line_num` is the number of rows that the user-defined response data needs to receive. **If there is no response line limit requirement, it can be set to 0.**
414- `line_counts` is used to record the total number of rows of this response data.
415- `timeout` is the user-defined maximum response time for this response data.
416
417`buf_size`, `line_num`, `timeout` parameters in the structure are restricted conditions, which are set when the structure is created, and other parameters are used to store data parameters for later data analysis.
418
419Introduction to related API interfaces:
420
421### Create a Response Structure
422
423```c
424at_response_t at_create_resp(rt_size_t buf_size, rt_size_t line_num, rt_int32_t timeout);
425```
426
427| **Parameter**   | **Description**                             |
428|---------|-----------------------------------------|
429| buf_size | Maximum length of received data supported by this response |
430| line_num | This response requires the number of rows of data to be returned. The number of rows is divided by a standard terminator (such as "\r\n"). If it is 0, it will end the response reception after receiving the "OK" or "ERROR" data; if it is greater than 0, it will return successfully after receiving the data of the current set line number. |
431|  timeout  | The maximum response time of the response data, receiving data timeout will return an error |
432| **Return**   | --                              |
433|  != NULL  | Successful, return a pointer to the response structure |
434|   = NULL  | Failed, insufficient memory |
435
436This function is used to create a custom response data receiving structure for later receiving and parsing the send command response data.
437
438### Delete a Response Structure
439
440```c
441void at_delete_resp(at_response_t resp);
442```
443
444| **Parameter** | **Description**           |
445|----|-------------------------|
446| resp | The response structure pointer to be deleted |
447
448This function is used to delete the created response structure object, which is generally paired with the **at_create_resp** creation function.
449
450### Set the Parameters of Response Structure
451
452```c
453at_response_t at_resp_set_info(at_response_t resp, rt_size_t buf_size, rt_size_t line_num, rt_int32_t timeout);
454```
455
456|   **Parameter**   | **Description**                  |
457|---------|----------------------------------|
458|    resp   | Response structure pointer that has been created |
459| buf_size | Maximum length of received data supported by this response |
460| line_num | This response requires the number of rows of data to be returned. The number of lines is divided by the standard terminator. If it is 0, the response is received after receiving the "OK" or "ERROR" data. If it is greater than 0, the data is successfully returned after receiving the data of the currently set line number. |
461|  timeout  | The maximum response time of the response data, receiving data timeout will return an error. |
462|   **Return**   | --                          |
463|  != NULL  | Successful, return a pointer to the response structure |
464|   = NULL  | Failed, insufficient memory |
465
466This function is used to set the response structure information that has been created. It mainly sets the restriction information on the response data. It is generally used after creating the structure and before sending the AT command. This function is mainly used to send commands when the device is initialized, which can reduce the number of times the response structure is created and reduce the code resource occupation.
467
468### Send a Command and Receive a Response
469
470```c
471rt_err_t at_exec_cmd(at_response_t resp, const char *cmd_expr, ...);
472```
473
474|   **Parameter**   | **Description**            |
475|---------|-----------------------------|
476|    resp   | Response structure body pointer created |
477| cmd_expr | Customize the expression of the input command |
478|    ...    | Enter the command data list, a variable parameter |
479|   **Return**   | --                         |
480|    >=0   | Successful               |
481|     -1    | Failed                    |
482|     -2    | Failed, receive response timed out |
483
484This function is used by the AT Client to send commands to the AT Server and wait for a response. `resp`  is a pointer to the response structure that has been created. The AT command uses the variable argument input of the match expression. **You do not need to add a command terminator at the end of the input command.**
485
486Refer to the following code to learn how to use the above AT commands to send and receive related functions:
487
488```c
489/*
490 * Program listing: AT Client sends commands and receives response routines
491 */
492
493#include <rtthread.h>
494#include <at.h>   /* AT component header file */
495
496int at_client_send(int argc, char**argv)
497{
498    at_response_t resp = RT_NULL;
499
500    if (argc != 2)
501    {
502        LOG_E("at_cli_send [command]  - AT client send commands to AT server.");
503        return -RT_ERROR;
504    }
505
506    /* Create a response structure, set the maximum support response data length to 512 bytes, the number of response data lines is unlimited, and the timeout period is 5 seconds. */
507    resp = at_create_resp(512, 0, rt_tick_from_millisecond(5000));
508    if (!resp)
509    {
510        LOG_E("No memory for response structure!");
511        return -RT_ENOMEM;
512    }
513
514    /* Send AT commands and receive AT Server response data, data and information stored in the resp structure */
515    if (at_exec_cmd(resp, argv[1]) != RT_EOK)
516    {
517        LOG_E("AT client send commands failed, response error or timeout !");
518        return -ET_ERROR;
519    }
520
521    /* Command sent successful */
522    LOG_D("AT Client send commands to AT Server success!");
523
524    /* Delete response structure */
525    at_delete_resp(resp);
526
527    return RT_EOK;
528}
529#ifdef FINSH_USING_MSH
530#include <finsh.h>
531/* Output at_Client_send to msh */
532MSH_CMD_EXPORT(at_Client_send, AT Client send commands to AT Server and get response data);
533#endif
534```
535
536The implementation principle of sending and receiving data is relatively simple. It mainly reads and writes the serial port device bound by the AT client, and sets the relevant number of rows and timeout to limit the response data. It is worth noting that the `res` response needs to be created first. The structure passed `in_exec_cmd` function is for data reception. When the `at_exec_cmd` function's parameter `resp` is NULL, it means that the data sent this time **does not consider processing the response data and directly returns the result**.
537
538## AT Client Data Parsing Method
539
540After the data is normally acquired, the response data needs to be parsed, which is one of the important functions of the AT Client. Parsing of data in the AT Client provides a parsed form of a custom parsing expression whose parsing syntax uses the standard `sscanf` parsing syntax. Developers can use the custom data parsing expression to respond to useful information in the data, provided that the developer needs to review the relevant manual in advance to understand the basic format of the AT Server device response data that the AT Client connects to. The following is a simple AT Client data parsing method through several functions and routines.
541
542### Get Response Data for the Specified Line Number
543
544```c
545const char *at_resp_get_line(at_response_t resp, rt_size_t resp_line);
546```
547
548|    **Parameter**    | **Description**               |
549|----------|-----------------------------|
550|    resp    |Response structure pointer               |
551| resp_line | Required line number for obtaining data |
552|    **Return**    | --                         |
553|   != NULL  | Successful, return a pointer to the corresponding line number data |
554|   = NULL   | Failed, input line number error |
555
556This function is used to get a row of data with the specified line number in the AT Server response data. The line number is judged by the standard data terminator. The above send and receive functions `at_exec_cmd` have recorded and processed the data and line numbers of the response data in the `resp` response structure, where the data information of the corresponding line number can be directly obtained.
557
558### Get Response Data by the Specified Keyword
559
560```c
561const char *at_resp_get_line_by_kw(at_response_t resp, const char *keyword);
562```
563
564|  **Parameter**  | **Description**              |
565|-------|-----------------------------|
566|   resp  |Response structure pointer               |
567| keyword | Keyword information |
568|  **Return**  | --                         |
569| != NULL | Successful, return a pointer to the corresponding line number data |
570|  = NULL | Failed, no keyword information found |
571
572This function is used to get a corresponding row of data by keyword in the AT Server response data.
573
574### Parse Response Data for the Specified Line Number
575
576```c
577int at_resp_parse_line_args(at_response_t resp, rt_size_t resp_line, const char *resp_expr, ...);
578```
579
580|    **Parameter**    | **Description**                  |
581|----------|---------------------------------|
582|    resp    |Response structure pointer                   |
583| resp_line | Parsed data line number required, **from the start line number count 1** |
584| resp_expr | Custom parameter parsing expression |
585|     ...    | Parsing the parameter list as a variable parameter |
586|    **Return**    | --                             |
587|     >0    | Successful, return the number of parameters successfully parsed |
588|     =0     | Failed, no parameters matching the parsing expression |
589|     -1     | Failed, parameter parsing error |
590
591This function is used to get a row of data with the specified line number in the AT Server response data, and parse the parameters in the row data.
592
593### Parse Response Data for a Row with Specified Keyword
594
595```c
596int at_resp_parse_line_args_by_kw(at_response_t resp, const char *keyword, const char *resp_expr, ...);
597```
598
599|    **Parameter**    | **Description**                   |
600|----------|---------------------------------|
601|    resp    |Response structure pointer                   |
602|   keyword  | Keyword information    |
603| resp_expr | Custom parameter parsing expression |
604|     ...    | Parsing the parameter list as a variable parameter |
605|    **Return**    | --                             |
606|     >0    | Successful, return the number of parameters successfully parsed |
607|     =0     | Failed, no parameters matching the parsing expression |
608|     -1     | Failed, parameter parsing error |
609
610This function is used to get a row of data containing a keyword in the AT Server response data and parse the parameters in the row data.
611
612The data parsing syntax uses the standard `sscanf` syntax, the content of the syntax is more, developers can search their parsing syntax, here two procedures are used to introduce the simple use method.
613
614### Serial Port Configuration Information Analysis Example
615
616The data sent by the client:
617
618```c
619AT+UART?
620```
621
622The response data obtained by the client:
623
624```c
625UART=115200,8,1,0,0\r\n
626OK\r\n
627```
628
629The pseudo code is parsed as follows:
630
631```c
632/* Create a server response structure, the maximum length of user-defined receive data is 64 */
633resp = at_create_resp(64, 0, rt_tick_from_millisecond(5000));
634
635/* Send data to the server and receive response data in the resp structure */
636at_exec_cmd(resp, "AT+UART?");
637
638/* Analyze the serial port configuration information, 1 means parsing the first line of response data, '%*[^=]' means ignoring the data before the equal sign */
639at_resp_parse_line_args(resp, 1,"%*[^=]=%d,%d,%d,%d,%d", &baudrate, &databits, &stopbits, &parity, &control);
640printf("baudrate=%d, databits=%d, stopbits=%d, parity=%d, control=%d\n",
641        baudrate, databits, stopbits, parity, control);
642
643/* Delete server response structure */
644at_delete_resp(resp);
645```
646
647### IP and MAC Address Resolution Example
648
649The data sent by the client:
650
651```c
652AT+IPMAC?
653```
654
655The response data obtained by the server:
656
657```c
658IP=192.168.1.10\r\n
659MAC=12:34:56:78:9a:bc\r\n
660OK\r\n
661```
662
663The pseudo code is parsed as follows:
664
665```c
666/* Create a server response structure, the maximum length of user-defined receive data is 128 */
667resp = at_create_resp(128, 0, rt_tick_from_millisecond(5000));
668
669at_exec_cmd(resp, "AT+IPMAC?");
670
671/* Customize the parsing expression to parse the information in the current line number data */
672at_resp_parse_line_args(resp, 1,"IP=%s", ip);
673at_resp_parse_line_args(resp, 2,"MAC=%s", mac);
674printf("IP=%s, MAC=%s\n", ip, mac);
675
676at_delete_resp(resp);
677```
678
679The key to parsing data is to correctly define the expression. Because the response data of the different device manufacturers is not unique to the response data of the AT device, only the form of the custom parsing expression can be obtained to obtain the required information. The design of the `at_resp_parse_line_args` parsing parameter function is based on the `sscanf` data parsing method. Before using it, the developer needs to understand the basic parsing syntax and then design the appropriate parsing syntax in combination with the response data. If the developer does not need to parse the specific parameters, you can use the `at_resp_get_line` function to get the specific data of a row.
680
681## AT Client URC Data Processing
682
683The processing of URC data is another important feature of AT Client. URC data is the data that is actively sent by the server. It cannot be received by the above data sending and receiving functions. The URC data format and function are different for different devices. Therefore, the URC data processing mode needs to be customized. The AT component provides a list management method for the processing of URC data. Users can customize the addition of URC data and its execution functions to the management list, so the processing of URC data is also the main porting work of AT Client.
684
685Related structure:
686
687```c
688struct at_urc
689{
690    const char *cmd_prefix;             // URC data prefix
691    const char *cmd_suffix;             // URC data suffix
692    void (*func)(const char *data, rt_size_t size);     // URC data execution function
693};
694typedef struct at_urc *at_urc_t;
695```
696
697Each URC data has a structure control block that defines and determines the prefix and suffix of the URC data, as well as the execution function of the URC data. A piece of data can be defined as URC data only if it matches the prefix and suffix of the URC exactly. The URC data execution function is executed immediately after the matching URC data is obtained. So developers adding a URC data requires a custom matching prefix, suffix, and execution function.
698
699
700### URC Data List Initialization
701
702```c
703void at_set_urc_table(const struct at_urc *table, rt_size_t size);
704```
705
706| **Parameter** | **Description**         |
707|-----|-----------------------|
708| table | URC data structure array pointer |
709|  size | Number of URC data |
710
711This function is used to initialize the developer-defined URC data list, mainly used in the AT Client porting function.
712
713The example of AT Client migration is given below. This example mainly shows the specific processing of URC data in the `at_client_port_init()` porting function. The developer can directly apply it to his own porting file, or customize the implementation function to complete the AT Client porting.
714
715```c
716static void urc_conn_func(const char *data, rt_size_t size)
717{
718    /* WIFI connection success information */
719    LOG_D("AT Server device WIFI connect success!");
720}
721
722static void urc_recv_func(const char *data, rt_size_t size)
723{
724    /* Received data from the server */
725    LOG_D("AT Client receive AT Server data!");
726}
727
728static void urc_func(const char *data, rt_size_t size)
729{
730    /* Device startup information */
731    LOG_D("AT Server device startup!");
732}
733
734static struct at_urc urc_table[] = {
735    {"WIFI CONNECTED",   "\r\n",     urc_conn_func},
736    {"+RECV",            ":",          urc_recv_func},
737    {"RDY",              "\r\n",     urc_func},
738};
739
740int at_client_port_init(void)
741{
742    /* Add multiple URC data to the URC list and execute the URC function when receiving data that matches both the URC prefix and the suffix */
743    at_set_urc_table(urc_table, sizeof(urc_table) / sizeof(urc_table[0]));
744    return RT_EOK;
745}
746```
747
748## AT Client Other APIs Introduction
749
750### Send Specified Length Data
751
752```c
753rt_size_t at_client_send(const char *buf, rt_size_t size);
754```
755
756| **Parameter** | **Description**               |
757|----|-----------------------------|
758|  buf | Pointer to send data |
759| size | Length of data sent |
760| **Return** | --                         |
761|  >0 | Successful, return the length of the data sent |
762| <=0 | Failed                    |
763
764This function is used to send the specified length data to the AT Server device through the AT Client device, which is mostly used for the AT Socket function.
765
766### Receive Specified Length Data
767
768```c
769rt_size_t at_client_recv(char *buf, rt_size_t size,rt_int32_t timeout);
770```
771
772| **Parameter** | **Description**               |
773|----|-----------------------------|
774|  buf | Pointer to receive data |
775| size | Maximum length for receiving data |
776| timeout | Receive data timeout (tick) |
777| **Return** | --                         |
778|  >0 | Successful, return the length of the data received successfully |
779| <=0 | Failed, receiving data error or timeout |
780
781This function is used to receive data of a specified length through the AT Client device, and is mostly used for the AT Socket function. This function can only be used in URC callback handlers.
782
783### Set the line terminator for receiving data
784
785```c
786void at_set_end_sign(char ch);
787```
788
789| Parameter | 描述                      |
790| -----   | -----                   |
791|ch        | Line terminator   |
792| **Return** | **描述**                  |
793|-        | -                       |
794
795This function is used to set the line terminator, which is used to judge the end of a row of data received by the client, and is mostly used for the AT Socket function.
796
797### Waiting for module initialization to complete
798
799```c
800int at_client_wait_connect(rt_uint32_t timeout);
801```
802
803| Parameter | Description            |
804| -----   | -----                   |
805|timeout   | Waiting timeout |
806| **Return** | **Description**     |
807|0         | Successful          |
808|<0        | Failed, no data returned during the timeout period |
809
810This function is used to cyclically send AT commands when the AT module starts, until the module responds to the data, indicating that the module is successfully started.
811
812## AT Client Multi-Client Support
813
814In general, the device as the AT Client only connects to one AT module (the AT module acts as the AT Server) and can directly use the above functions of data transmission and reception and command parsing. In a few cases, the device needs to connect multiple AT modules as the AT Client. In this case, the multi-client support function of the device is required.
815
816The AT component provides support for multi-client connections and provides two different sets of function interfaces: **Single-Client Mode Functions** and **Multi-Client Mode Functions**.
817
818- Single-Client Mode Function: This type of function interface is mainly used when the device is connected to only one AT module, or when the device is connected to multiple AT modules, it is used in the **first AT client**.
819
820- Multi-Client Mode Function: This type of function interface mainly uses devices to connect multiple AT modules.
821
822The advantages and disadvantages of the two different mode functions and in different application scenarios are as follows:
823
824![at client modes comparison](figures/at_multiple_client.jpg)
825
826The single client mode function definition is mainly different from the single connection mode function. The definition of the incoming client object is different. The single client mode function uses the first initialized AT client object by default, and the multi-client mode function can pass in the user-defined custom client object. The function to get the client object is as follows:
827
828```c
829at_client_t at_client_get(const char *dev_name);
830```
831
832This function obtains the AT client object created by the device through the incoming device name, which is used to distinguish different clients when connecting multiple clients.
833
834The single client mode and multi-client mode function interface definitions differ from the following functions::
835
836| Single-Client Mode Functions | Multi-Client Mode Functions |
837| ----------------------------| ---------------------------------------|
838| at_exec_cmd(...)             | at_obj_exec_cmd(client, ...)            |
839| at_set_end_sign(...)         | at_obj_set_end_sign(client, ...)        |
840| at_set_urc_table(...)        | at_obj_set_urc_table(client, ...)       |
841| at_client_wait_connect(...)  | at_client_obj_wait_connect(client, ...) |
842| at_client_send(...)          | at_client_obj_send(client, ...)         |
843| at_client_recv(...)          | at_client_obj_recv(client, ...)         |
844
845The two modes of client data transmission and parsing are basically the same, and the function usage process is different, as shown below:
846
847```c
848/* Single client mode function usage */
849
850at_response_t resp = RT_NULL;
851
852at_client_init("uart2", 512);
853
854resp = at_create_resp(256, 0, 5000);
855
856/* Send commands using a single client mode function */
857at_exec_cmd(resp, "AT+CIFSR");
858
859at_delete_resp(resp);
860```
861
862```c
863/* Multi-client mode functions usage */
864
865at_response_t resp = RT_NULL;
866at_client_t client = RT_NULL;
867
868/* Initialize two AT clients */
869at_client_init("uart2", 512);
870at_client_init("uart3", 512);
871
872/* Get the corresponding AT client object by name */
873client = at_client_get("uart3");
874
875resp = at_create_resp(256, 0, 5000);
876
877/* Send commands using multi-client mode functions */
878at_obj_exec_cmd(client, resp, "AT+CIFSR");
879
880at_delete_resp(resp);
881```
882
883The process differences used by other functions are similar to the above `at_obj_exec_cmd()` function. The main function is to obtain the client object through the `at_client_get()` function, and then determine which client is the client through the incoming object to achieve multi-client support.
884
885# FAQs
886
887## Q: What should I do if the log on the shell shows an error when enabling the AT command to send and receive data real-time printing function. ?
888
889**A:** Increase the baudrate of the serial port device corresponding to the shell to 921600, improve the serial port printing speed, and prevent the printing error when the data is too large.
890
891## Q: When the AT Socket function is started, the compile prompt "The AT socket device is not selected, please select it through the env menuconfig".
892
893**A:** After the AT Socket function is enabled, the corresponding device model is enabled in the at device package by default. Enter the at device package, configure the device as an ESP8266 device, configure WIFI information, re-generate the project, compile and download.
894
895## Q: AT Socket function data reception timeout or data reception is not complete.
896
897**A:** The error may be that the receive data buffer in the serial device used by the AT is too small (RT_SERIAL_RB_BUFSZ default is 64 bytes), and the data is overwritten after the data is not received in time. The buffer size of the serial port receiving data (such as 256 bytes) is appropriately increased.
898