The 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.
After 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.
**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:
1. 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"`).
3. 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.
4. 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.
5. 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.
- 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.
With 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.
Although 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.
In 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.
The 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..
Through 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.
Overall, 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.
- Debug mode: Provides AT Client CLI command line interaction mode, mainly used for device debugging;
- 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.
- Multi-client support: The AT component supports multiple clients running simultaneously.
When we use the AT Server feature in the AT component, we need to define the following configuration in rtconfig.h:
| **Macro Definition** | **Description** |
| ---- | ---- |
|RT_USING_AT| Enable AT component |
|AT_USING_SERVER |Enable AT Server function|
|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.|
|AT_SERVER_RECV_BUFF_LEN|The maximum length of data received by the AT Server device|
|AT_CMD_END_MARK_CRLF|Determine the line terminator of the received command |
For 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:
After 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:
The 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.
After 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.
At 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.
AT 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:
The 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:
| `_args_expr_` | AT command parameter expression; (NULL means no parameter, `<>` means mandatory parameter and `[]` means optional parameter) |
| `_test_` | AT test function name; (NULL means no parameter) |
| `_query_` | AT query function name; (ibid.) |
| `_setup_` | AT setup function name; (ibid.) |
| `_exec_` | AT performs the function name; (ibid.) |
The 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:
This 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.
| **Parameter** | **D**escription |
|------|-------------------------|
| format | Customize the expression of the input data |
| ... | Input data list, variable parameters |
#### Send Data to the Client (newline)
```c
void at_server_printfln(const char *format, ...);
```
This 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.
| **Parameter** | **Description** |
|------|-------------------------|
| format | Customize the expression of the input data |
| ... | Input data list, variable parameters |
#### Send Command Execution Results to the Client
```c
void at_server_print_result(at_result_t result);
```
This 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;
| **Parameter** | **Description** |
|------|-----------------|
| result | Command execution result type |
The command execution result type in the AT component is given in the enumerated type, as shown in the following table:
| Types of Command Execution Result | Description |
Among 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"`.
The 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.
/* 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. */
if (at_req_parse_args(args, "=%d,%d", &value1, &value2) > 0)
{
/* Data analysis succeeds, echoing data to AT Server serial device */
The 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.
1. 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.
2. 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.
If 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:
```c
/* Constant data goes into FLASH */
.rodata :
{
...
/* section information for RT-thread AT package */
After 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:
int at_client_init(const char *dev_name, rt_size_t recv_bufsz);
```
The 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.
### AT Client data receiving and sending ###
The 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.
Related structure definition:
```c
struct at_response
{
/* response buffer */
char *buf;
/* the maximum response buffer size */
rt_size_t buf_size;
/* 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 */
rt_size_t line_num;
/* the count of received response lines */
rt_size_t line_counts;
/* the maximum response time */
rt_int32_t timeout;
};
typedef struct at_response *at_response_t;
```
In 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.
-`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.
-`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.
-`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.**
-`line_counts` is used to record the total number of rows of this response data.
-`timeout` is the user-defined maximum response time for this response data.
`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.
| buf_size | Maximum length of received data supported by this response |
| 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. |
| timeout | The maximum response time of the response data, receiving data timeout will return an error |
| **Return** | -- |
| != NULL | Successful, return a pointer to the response structure |
| = NULL | Failed, insufficient memory |
This function is used to create a custom response data receiving structure for later receiving and parsing the send command response data.
#### Delete a Response Structure
```c
void at_delete_resp(at_response_t resp);
```
| **Parameter** | **Description** |
|----|-------------------------|
| resp | The response structure pointer to be deleted |
This function is used to delete the created response structure object, which is generally paired with the **at_create_resp** creation function.
| resp | Response structure pointer that has been created |
| buf_size | Maximum length of received data supported by this response |
| 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. |
| timeout | The maximum response time of the response data, receiving data timeout will return an error. |
| **Return** | -- |
| != NULL | Successful, return a pointer to the response structure |
| = NULL | Failed, insufficient memory |
This 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.
| resp | Response structure body pointer created |
| cmd_expr | Customize the expression of the input command |
| ... | Enter the command data list, a variable parameter |
| **Return** | -- |
| >=0 | Successful |
| -1 | Failed |
| -2 | Failed, receive response timed out |
This 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.**
Refer to the following code to learn how to use the above AT commands to send and receive related functions:
```c
/*
* Program listing: AT Client sends commands and receives response routines
*/
#include <rtthread.h>
#include <at.h> /* AT component header file */
int at_client_send(int argc, char**argv)
{
at_response_t resp = RT_NULL;
if (argc != 2)
{
LOG_E("at_cli_send [command] - AT client send commands to AT server.");
return -RT_ERROR;
}
/* 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. */
The 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**.
After 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.
#### Get Response Data for the Specified Line Number
| resp_line | Required line number for obtaining data |
| **Return** | -- |
| != NULL | Successful, return a pointer to the corresponding line number data |
| = NULL | Failed, input line number error |
This 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.
The 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.
/* Send data to the server and receive response data in the resp structure */
at_exec_cmd(resp, "AT+UART?");
/* Analyze the serial port configuration information, 1 means parsing the first line of response data, '%*[^=]' means ignoring the data before the equal sign */
The 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.
The 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.
Related structure:
```c
struct at_urc
{
const char *cmd_prefix; // URC data prefix
const char *cmd_suffix; // URC data suffix
void (*func)(const char *data, rt_size_t size); // URC data execution function
};
typedef struct at_urc *at_urc_t;
```
Each 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.
This function is used to initialize the developer-defined URC data list, mainly used in the AT Client porting function.
The 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.
| >0 | Successful, return the length of the data sent |
| <=0 | Failed |
This 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.
| >0 | Successful, return the length of the data received successfully |
| <=0 | Failed, receiving data error or timeout |
This 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.
#### Set the line terminator for receiving data ####
```c
void at_set_end_sign(char ch);
```
| Parameter | 描述 |
| ----- | ----- |
|ch | Line terminator |
| **Return** | **描述** |
|- | - |
This 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.
#### Waiting for module initialization to complete ####
```c
int at_client_wait_connect(rt_uint32_t timeout);
```
| Parameter | Description |
| ----- | ----- |
|timeout | Waiting timeout |
| **Return** | **Description** |
|0 | Successful |
|<0|Failed,nodatareturnedduringthetimeoutperiod|
This 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.
### AT Client Multi-Client Support ###
In 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.
The 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**.
- 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**.
- Multi-Client Mode Function: This type of function interface mainly uses devices to connect multiple AT modules.
The advantages and disadvantages of the two different mode functions and in different application scenarios are as follows:
The 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:
This 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.
The single client mode and multi-client mode function interface definitions differ from the following functions::
The 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.
### 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. ?
**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.
### 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".
**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.
### Q: AT Socket function data reception timeout or data reception is not complete.
**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.