support ch32v208

This commit is contained in:
gqk
2025-02-13 16:38:19 +08:00
parent dca3e93959
commit ec9bcaefb5
260 changed files with 58756 additions and 411 deletions
@@ -13,3 +13,11 @@ config ADAPTER_EC200A
if ADAPTER_EC200A
source "$APP_DIR/Framework/connection/4g/ec200a/Kconfig"
endif
config ADAPTER_GM800TF
bool "Using 4G adapter device GM800TF"
default n
if ADAPTER_GM800TF
source "$APP_DIR/Framework/connection/4g/gm800tf/Kconfig"
endif
@@ -17,5 +17,9 @@ ifeq ($(CONFIG_ADD_XIZI_FEATURES),y)
SRC_DIR += ec200a
endif
ifeq ($(CONFIG_ADAPTER_GM800TF),y)
SRC_DIR += gm800tf
endif
include $(KERNEL_ROOT)/compiler.mk
endif
@@ -28,6 +28,10 @@ extern AdapterProductInfoType Ec200tAttach(struct Adapter *adapter);
extern AdapterProductInfoType Ec200aAttach(struct Adapter *adapter);
#endif
#ifdef ADAPTER_GM800TF
extern AdapterProductInfoType Gm800tfAttach(struct Adapter *adapter);
#endif
static int Adapter4GRegister(struct Adapter *adapter)
{
int ret = 0;
@@ -92,6 +96,20 @@ int Adapter4GInit(void)
adapter->info = product_info;
adapter->done = product_info->model_done;
#endif
#ifdef ADAPTER_GM800TF
AdapterProductInfoType product_info = Gm800tfAttach(adapter);
if (!product_info) {
printf("Adapter4GInit gm800tf attach error\n");
PrivFree(adapter);
return -1;
}
adapter->product_info_flag = 1;
adapter->info = product_info;
adapter->done = product_info->model_done;
#endif
return ret;
@@ -164,6 +182,106 @@ int Adapter4GTest(void)
}
#endif
#ifdef ADAPTER_GM800TF
uint8 server_addr[64] = "115.238.53.59";
uint8 server_port[64] = "10208";
adapter->socket.socket_id = 0;
AdapterDeviceOpen(adapter);
AdapterDeviceControl(adapter, OPE_INT, &baud_rate);
AdapterDeviceConnect(adapter, CLIENT, server_addr, server_port, IPV4);
// AdapterDeviceDisconnect(adapter, NULL);
// AdapterDeviceConnect(adapter, CLIENT, server_addr, server_port, IPV4);
AdapterDeviceNetstat(adapter);
// char sendData[15] = "Hello World!";
char sendData = 'a';
char receiveData = 0;
int failCount = 0;
for (int i = 0; i < 1024; i++) { // send 1kB data
AdapterDeviceSend(adapter, &sendData, 1);
sendData = sendData + 1 > 'z' ? 'a' : sendData + 1;
}
// AdapterDeviceSend(adapter, sendData, 13);
// while (1) {
// // if (sendData > 'z') {
// // break;
// // }
// AdapterDeviceSend(adapter, &sendData, 1);
// sendData = sendData + 1 > 'z' ? 'a' : sendData + 1;
// // int ret = AdapterDeviceRecv(adapter, &receiveData, 1);
// // printf("receiveData: %d\n", receiveData);
// // if (ret >= 0 && receiveData == sendData) {
// // sendData = sendData + 1 > 'z' ? 'a' : sendData + 1;
// // failCount = 0;
// // } else {
// // failCount++;
// // if (failCount >= 10) {
// // AdapterDeviceConnect(adapter, CLIENT, server_addr, server_port, IPV4);
// // failCount = 0;
// // }
// // }
// // printf("4G recv msg %c\n", receiveData);
// // receiveData = 0;
// }
// PrivTaskDelay(10000);
AdapterDeviceClose(adapter);
#endif
return 0;
}
PRIV_SHELL_CMD_FUNCTION(Adapter4GTest, a EC200T or EC200A adapter sample, PRIV_SHELL_CMD_FUNC_ATTR);
#ifdef ADAPTER_GM800TF
// unsigned char data[1024 * 40];
void *uploadDataTask(void *param) {
int baud_rate = BAUD_RATE_115200;
struct Adapter* adapter = AdapterDeviceFindByName(ADAPTER_4G_NAME);
int reconnectLimit = 3; // try reconnect to server up to 3 times
uint8 server_addr[64] = "115.238.53.59";
uint8 server_port[64] = "10208";
adapter->socket.socket_id = 0;
AdapterDeviceOpen(adapter);
AdapterDeviceControl(adapter, OPE_INT, &baud_rate);
/* try to connect to server */
do {
AdapterDeviceConnect(adapter, CLIENT, server_addr, server_port, IPV4);
AdapterDeviceNetstat(adapter);
if (adapter->network_info.is_connected && adapter->network_info.signal_strength < 99) {
break;
}
} while (--reconnectLimit > 0);
if (reconnectLimit <= 0) {
printf("4G connect to server failed\n");
AdapterDeviceClose(adapter);
return NULL;
}
/* send data to server */
char sendData[15] = "Hello World!";
AdapterDeviceSend(adapter, &sendData, 13);
// char sendData = 'a';
// char receiveData = 0;
// int failCount = 0;
// for (int i = 0; i < 1024; i++) { // send 1kB data
// AdapterDeviceSend(adapter, &sendData, 1);
// sendData = sendData + 1 > 'z' ? 'a' : sendData + 1;
// }
AdapterDeviceClose(adapter);
}
void startUploadDataTask(void) {
pthread_attr_t attr;
attr.schedparam.sched_priority = 20;
attr.stacksize = 8096;
// char task_name[] = "upload_data_task";
pthread_t thread;
PrivTaskCreate(&thread, &attr, uploadDataTask, NULL);
PrivTaskStartup(&thread);
}
#endif
@@ -0,0 +1,21 @@
config ADAPTER_4G_GM800TF
string "GM800TF adapter name"
default "gm800tf"
if ADD_XIZI_FEATURES
config ADAPTER_GM800TF_DEV
string "GM800TF device path"
default "/dev/lte_dev1"
endif
if ADD_NUTTX_FEATURES
config ADAPTER_GM800TF_DEV
string "GM800TF device path"
default "/dev/ttyS8"
endif
if ADD_RTTHREAD_FEATURES
config ADAPTER_GM800TF_DEV
string "GM800TF device path"
default "/dev/usart8"
endif
@@ -0,0 +1,6 @@
############################################################################
# APP_Framework/Framework/connection/4g/gm800tf/Make.defs
############################################################################
ifneq ($(CONFIG_ADAPTER_4G_GM800TF),)
CONFIGURED_APPS += $(APPDIR)/../../../APP_Framework/Framework/connection/4g/gm800tf
endif
@@ -0,0 +1,14 @@
include $(KERNEL_ROOT)/.config
ifeq ($(CONFIG_ADD_NUTTX_FEATURES),y)
include $(APPDIR)/Make.defs
CSRCS += gm800tf.c gm800tf_mqtt.c
include $(APPDIR)/Application.mk
endif
ifeq ($(CONFIG_ADD_XIZI_FEATURES),y)
SRC_FILES := gm800tf.c gm800tf_mqtt.c
include $(KERNEL_ROOT)/compiler.mk
endif
@@ -0,0 +1,10 @@
from building import *
import os
cwd = GetCurrentDir()
src = []
if GetDepend(['ADAPTER_GM800TF']):
src += ['gm800tf.c']
group = DefineGroup('connection 4g gm800tf', src, depend = [], CPPPATH = [cwd])
Return('group')
@@ -0,0 +1,639 @@
/*
* Copyright (c) 2020 AIIT XUOS Lab
* XiUOS is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* @file gm800tf.c
* @brief Implement the connection 4G adapter function, using GM800TF device
* @author Huo Yujia (huoyujia081@126.com)
* @version 1.0
* @date 2024-07-05
*/
#include <adapter.h>
#include <at_agent.h>
#define GM800TF_AT_MODE_CMD "+++"
#define GM800TF_GET_ICCID_CMD "AT+ICCID\r\n"
#define GM800TF_SETUP_SOCKET_CMD "AT+SOCK%c=TCP,%s,%s\r\n"
#define GM800TF_OPEN_SOCKET_CMD "AT+SOCK%cEN=ON\r\n"
#define GM800TF_CLOSE_SOCKET_CMD "AT+SOCK%cEN=OFF\r\n"
#define GM800TF_SET_WKMOD_NET_CMD "AT+WKMOD=NET\r\n"
#define GM800TF_GET_WKMOD_CMD "AT+WKMOD?\r\n"
#define GM800TF_SAVE_CFG_CMD "AT+S\r\n"
#define GM800TF_GET_CSQ_CMD "AT+CSQ\r\n"
#define GM800TF_ENTM_MODE_CMD "AT+ENTM\r\n"
#define GM800TF_GET_SOCKET_PARAM_CMD "AT+SOCK%c?\r\n"
#define GM800TF_GET_SOCKET_STATUS_CMD "AT+SOCK%cLK\r\n"
#define GM800TF_RESET_CMD "AT+CLEAR\r\n"
#define GM800TF_SET_HEART_CMD "AT+HEARTEN=%s\r\n"
#define GM800TF_SET_HEART_DATA_CMD "AT+HEARTDT=%s\r\n"
#define GM800TF_SET_HEART_TIME_CMD "AT+HEARTTM=%d\r\n"
#define GM800TF_GET_MQTT_STATUS_CMD "AT+MQTTSTA?\r\n"
#define GM800TF_GET_MQTT_SERVER_CMD "AT+MQTTSVR?\r\n"
#define GM800TF_GET_MQTT_CLIENTID_CMD "AT+MQTTCID?\r\n"
#define GM800TF_GET_MQTT_USERNAME_CMD "AT+MQTTUSER?\r\n"
#define GM800TF_GET_MQTT_PASSWORD_CMD "AT+MQTTPSW?\r\n"
#define GM800TF_OK_REPLY "OK"
#define GM800TF_READY_REPLY "READY"
#define GM800TF_CREG_REPLY ",1"
#define GM800TF_CONNECT_REPLY "CONNECT"
#define TRY_TIMES 10
/**
* @brief convert string to corresponding hex string
* @param input original string
* @param output hex string
*/
void string_to_hex(const char *input, char *output) {
while (*input) {
sprintf(output, "%02X", (unsigned char)*input);
input++;
output += 2;
}
*output = '\0'; // Null-terminate the output string
}
/**
* @brief enter the configuration mode
* @param adapter
* @return int
*/
int Gm800tfEnterAtMode(struct Adapter *adapter) {
AtSetReplyEndChar(adapter->agent, 'o', 'k');
AtSetReplyCharNum(adapter->agent, 256);
AtSetReplyLrEnd(adapter->agent, 1);
ATOrderSend(adapter->agent, REPLY_TIME_OUT, NULL, "+++");
PrivTaskDelay(500);
ATOrderSend(adapter->agent, REPLY_TIME_OUT, NULL, "a");
PrivTaskDelay(100);
ATOrderSend(adapter->agent, REPLY_TIME_OUT, NULL, "\r\n"); // clear the "+++a", confirm it will not be added to the following command.
PrivTaskDelay(500);
return 0;
}
/**
* @brief open the GM800TF(aka. init the serial) and init the AT agent
* @param adapter
* @return int
*/
static int Gm800tfOpen(struct Adapter *adapter) {
/*step1: open gm800tf serial port*/
adapter->fd = PrivOpen(ADAPTER_GM800TF_DEV, O_RDWR);
if (adapter->fd < 0) {
printf("Gm800tfOpen get serial %s fd error\n", ADAPTER_GM800TF_DEV);
return -1;
}
/*step2: init AT agent*/
if (!adapter->agent) {
char *agent_name = "4G_uart_client";
if (0 != InitATAgent(agent_name, adapter->fd, 256)) {
printf("at agent init failed !\n");
return -1;
}
ATAgentType at_agent = GetATAgent(agent_name);
adapter->agent = at_agent;
}
/* step3: reset gm800tf */
ADAPTER_DEBUG("Gm800tf reseting configuration\n");
Gm800tfEnterAtMode(adapter);
AtSetReplyEndChar(adapter->agent, 'O', 'K');
AtSetReplyCharNum(adapter->agent, 256);
AtSetReplyLrEnd(adapter->agent, 0);
ATOrderSend(adapter->agent, REPLY_TIME_OUT, NULL, "AT+CLEAR\r\n");
PrivTaskDelay(15000); // after reset configuration, wait at least 10s for restarting
/* step4: communication from sockA channel only*/
adapter->socket.socket_id = 0;
ADAPTER_DEBUG("Gm800tf open done\n");
return 0;
}
/**
* @brief close the GM800TF(aka. disable the interrupt) and disconnect the socket
* @param adapter
* @return int
*/
static int Gm800tfClose(struct Adapter *adapter) {
int ret = 0;
uint8_t gm800tf_cmd[64];
if (!adapter->agent) {
printf("Gm800tfClose AT agent NULL\n");
return -1;
}
AtSetReplyEndChar(adapter->agent, 0x4F, 0x4B); //'O', 'K'
/*step1: serial write "+++", quit transparent mode*/
ret = Gm800tfEnterAtMode(adapter);
if (ret < 0) {
goto out;
}
/*step2: serial write "AT+SOCKAEN=OFF" or "AT+SOCKBEN=OFF", close socket connect before open socket*/
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_CLOSE_SOCKET_CMD, 'A' + adapter->socket.socket_id);
ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/*step3: serial write "AT+S", save configuration and restart 4G module*/
ret = AtCmdConfigAndCheck(adapter->agent, GM800TF_SAVE_CFG_CMD, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
PrivTaskDelay(15000); // after save configuration, wait at least 10s for restarting
out:
/*step4: close gm800tf serial port and delete ATAgentReceiveProcess*/
// DeleteATAgent(adapter->agent);
// adapter->agent = NULL;
PrivClose(adapter->fd);
return ret;
}
/**
* @brief config the serial and enable the interrupt
* @param adapter
* @param cmd
* @param args
* @return int
*/
static int Gm800tfIoctl(struct Adapter *adapter, int cmd, void *args) {
if (OPE_INT != cmd) {
printf("Gm800tfIoctl only support OPE_INT, do not support %d\n", cmd);
return -1;
}
uint32_t baud_rate = *((uint32_t *)args);
struct SerialDataCfg serial_cfg;
memset(&serial_cfg, 0, sizeof(struct SerialDataCfg));
serial_cfg.serial_baud_rate = baud_rate;
serial_cfg.serial_data_bits = DATA_BITS_8;
serial_cfg.serial_stop_bits = STOP_BITS_1;
serial_cfg.serial_buffer_size = SERIAL_RB_BUFSZ;
serial_cfg.serial_parity_mode = PARITY_NONE;
serial_cfg.serial_bit_order = STOP_BITS_1;
serial_cfg.serial_invert_mode = NRZ_NORMAL;
#ifdef TOOL_USING_OTA
serial_cfg.serial_timeout = OTA_RX_TIMEOUT;
#else
// serial receive timeout 10s
serial_cfg.serial_timeout = 100000;
#endif
serial_cfg.is_ext_uart = 0;
struct PrivIoctlCfg ioctl_cfg;
ioctl_cfg.ioctl_driver_type = SERIAL_TYPE;
ioctl_cfg.args = &serial_cfg;
PrivIoctl(adapter->fd, OPE_INT, &ioctl_cfg);
return 0;
}
/**
* @brief connect to the server
* @param adapter
* @param net_role
* @param ip
* @param port
* @param ip_type
* @return int
*/
static int Gm800tfConnect(struct Adapter *adapter, enum NetRoleType net_role, const char *ip, const char *port, enum IpType ip_type) {
int ret = 0;
int try = 0;
uint8_t gm800tf_cmd[64];
/*step0: compare ip and port with current configuration, and if they are the same there is no need to connect again*/
AdapterDeviceNetstat(adapter);
if (adapter->network_info.workMode == 1 && strcmp(adapter->network_info.ip_address, ip) == 0 &&
adapter->network_info.port == atoi(port) && adapter->network_info.is_connected && adapter->network_info.signal_strength < 99) {
return 0;
}
/*step1: serial write "+++" and "a", quit transparent mode*/
ret = Gm800tfEnterAtMode(adapter);
if (ret < 0) {
goto out;
}
AtSetReplyEndChar(adapter->agent, 'O', 'K');
AtSetReplyCharNum(adapter->agent, 256);
AtSetReplyLrEnd(adapter->agent, 0);
/*step2: serial write "AT+ICCID", get SIM ID*/
ret = AtCmdConfigAndCheck(adapter->agent, GM800TF_GET_ICCID_CMD, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/*step3: serial write "AT+SOCKA=<protocol>,<address>,<port>" or "AT+SOCKB=<protocol>,<address>,<port>", connect
* socket using TCP*/
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_SETUP_SOCKET_CMD, 'A' + adapter->socket.socket_id, ip, port);
ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/*step4: serial write "AT+SOCKAEN=ON" or "AT+SOCKBEN=ON", connect socket using TCP*/
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_OPEN_SOCKET_CMD, 'A' + adapter->socket.socket_id);
ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/* step5: set up the heartbeat */
// char *heartbeatData = "heartbeat test";
// int heartbeatTime = 30;
// char heartbeatDataHex[65] = {}; // 最多32个字符
// string_to_hex(heartbeatData, heartbeatDataHex);
// memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
// sprintf(gm800tf_cmd, GM800TF_SET_HEART_CMD, "ON");
// ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
// if (ret < 0) {
// goto out;
// }
// memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
// sprintf(gm800tf_cmd, GM800TF_SET_HEART_DATA_CMD, heartbeatDataHex);
// ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
// if (ret < 0) {
// goto out;
// }
// memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
// sprintf(gm800tf_cmd, GM800TF_SET_HEART_TIME_CMD, heartbeatTime);
// ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
// if (ret < 0) {
// goto out;
// }
/* step5: set down the heartbeat */
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_SET_HEART_CMD, "OFF");
ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/* step6: serial write "AT+WKMOD=NET", set the working mode to network transparent transmission mode */
ret = AtCmdConfigAndCheck(adapter->agent, GM800TF_SET_WKMOD_NET_CMD, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/*step7: serial write "AT+S", save configuration and restart 4G module*/
ret = AtCmdConfigAndCheck(adapter->agent, GM800TF_SAVE_CFG_CMD, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
PrivTaskDelay(15000); // after save configuration, wait at least 10s for restarting
ADAPTER_DEBUG("Gm800tf connect TCP done\n");
return 0;
out:
ADAPTER_DEBUG("Gm800tf connect TCP failed.\n");
return -1;
}
/**
* @brief send the data to the server after connect to the server
* @param adapter
* @param buf
* @param len
* @return int
*/
static int Gm800tfSend(struct Adapter *adapter, const void *buf, size_t len) {
/* query for whether socket is connected successfully */
AdapterDeviceNetstat(adapter);
if (adapter->network_info.is_connected == 0) {
printf("[error %s %d]socket has not been connected, please call function AdapterDeviceConnect\n", __func__, __LINE__);
return -1;
}
/* send the buf data */
if (adapter->agent) {
EntmSend(adapter->agent, (const char *)buf, len);
} else {
printf("Gm800tfSend can not find agent\n");
}
return 0;
}
/**
* @brief receive the data from the server after connect to the server
* @param adapter
* @param buf
* @param len
* @return int
*/
static int Gm800tfRecv(struct Adapter *adapter, void *buf, size_t len) {
if (adapter->agent) {
return EntmRecv(adapter->agent, (char *)buf, len, 6);
} else {
printf("Gm800tfRecv can not find agent\n");
}
return -1;
}
/**
* @brief disconnect the server
* @param adapter
* @return int
*/
static int Gm800tfDisconnect(struct Adapter *adapter) {
int ret = 0;
uint8_t gm800tf_cmd[64];
/* query for whether socket is connected successfully */
AdapterDeviceNetstat(adapter);
if (adapter->network_info.is_connected == 0) {
printf("[error %s %d]socket has not been connected, please call function AdapterDeviceConnect\n", __func__, __LINE__);
return 0;
}
/*step1: serial write "+++", quit transparent mode*/
ret = Gm800tfEnterAtMode(adapter);
if (ret < 0) {
goto out;
}
AtSetReplyEndChar(adapter->agent, 'O', 'K');
AtSetReplyCharNum(adapter->agent, 256);
AtSetReplyLrEnd(adapter->agent, 0);
/*step2: serial write "AT+SOCKAEN=OFF" or "AT+SOCKBEN=OFF", close socket connect before open socket*/
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_CLOSE_SOCKET_CMD, 'A' + adapter->socket.socket_id);
ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/*step3: serial write "AT+S", save configuration and restart 4G module*/
ret = AtCmdConfigAndCheck(adapter->agent, GM800TF_SAVE_CFG_CMD, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
PrivTaskDelay(15000); // after save configuration, wait at least 5s for restarting
ADAPTER_DEBUG("Gm800tf disconnect TCP done\n");
return 0;
out:
ADAPTER_DEBUG("Gm800tf disconnect TCP failed. \n");
return -1;
}
/**
* @brief query for the network status
* @param adapter
* @return int
*/
static int Gm800tfNetstat(struct Adapter *adapter) {
char result[96] = {0};
uint8_t gm800tf_cmd[64];
int ret = 0;
int try = 0;
/*step1: serial write "+++", quit transparent mode*/
ret = Gm800tfEnterAtMode(adapter);
if (ret < 0) {
goto out;
}
AtSetReplyEndChar(adapter->agent, 'O', 'K');
AtSetReplyCharNum(adapter->agent, 256);
AtSetReplyLrEnd(adapter->agent, 0);
/*step2: serial write "AT+ICCID", get SIM ID*/
ret = AtCmdConfigAndCheck(adapter->agent, GM800TF_GET_ICCID_CMD, GM800TF_OK_REPLY);
if (ret < 0) {
printf("[error %s %d]AT+ICCID failed, please check the SIM card\n", __func__, __LINE__);
goto out;
}
printf("-*-*-*-*-*-*-*Gm800tfNetstat*-*-*-*-*-*-*\n");
/*step3: serial write "AT+CSQ", get carrier type*/
memset(result, 0, sizeof(result));
ret = AtGetNetworkInfoReply(adapter->agent, GM800TF_GET_CSQ_CMD, result);
if (ret < 0) {
goto out;
}
if (sscanf(strstr(result, "+CSQ:"), "+CSQ: %d", &adapter->network_info.signal_strength) == 1) {
printf("signal strength:\t%d\n", adapter->network_info.signal_strength);
} else {
printf("Failed to parse signal strength\n");
goto out;
}
/*step4: serial write "AT+WKMOD?", get the current work mode*/
memset(result, 0, sizeof(result));
ret = AtGetNetworkInfoReply(adapter->agent, GM800TF_GET_WKMOD_CMD, result);
if (ret < 0) {
goto out;
}
char workMode[10] = {};
if (sscanf(strstr(result, "+WKMOD:"), "+WKMOD:%s", workMode) == 1) {
printf("work mode:\t\t%s\n", workMode);
if (strcmp(workMode, "NET") == 0) {
adapter->network_info.workMode = 1;
} else if (strcmp(workMode, "MQTT,NOR") == 0) {
adapter->network_info.workMode = 2;
} else {
adapter->network_info.workMode = 0;
}
} else {
printf("Failed to parse work mode\n");
goto out;
}
/*step5: serial write "AT+SOCKA=?", get the current server IP address*/
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_GET_SOCKET_PARAM_CMD, 'A' + adapter->socket.socket_id);
ret = AtGetNetworkInfoReply(adapter->agent, gm800tf_cmd, result);
if (ret < 0) {
goto out;
}
if (sscanf(strstr(result, ",") + 1, "%15[^,],%hu", adapter->network_info.ip_address, &adapter->network_info.port) == 2) {
printf("server ip address:\t%s\n", adapter->network_info.ip_address);
printf("server port:\t\t%hu\n", adapter->network_info.port);
} else {
printf("server ip address:\t%s\n", adapter->network_info.ip_address);
printf("server port:\t\t%d\n", adapter->network_info.port);
printf("Failed to parse IP address and port\n");
goto out;
}
/*step6: serial write "AT+SOCKALK" or "AT+SOCKBLK", get socket status*/
memset(result, 0, sizeof(result));
sprintf(gm800tf_cmd, GM800TF_GET_SOCKET_STATUS_CMD, 'A' + adapter->socket.socket_id);
ret = AtGetNetworkInfoReply(adapter->agent, gm800tf_cmd, result);
if (ret < 0) {
goto out;
}
char socket_status[20] = {};
if (sscanf(strstr(result, "LK:"), "LK: %s", socket_status) == 1) {
printf("socket status:\t\t%s\n", socket_status);
adapter->network_info.is_connected = strcmp(socket_status, "Connected") == 0 ? 1 : 0;
} else {
printf("Failed to parse socket status\n");
goto out;
}
/*step7: serial write "AT+MQTTSVR=?", get the current mqtt server IP address and port*/
memset(result, 0, sizeof(result));
ret = AtGetNetworkInfoReply(adapter->agent, GM800TF_GET_MQTT_SERVER_CMD, result);
if (ret < 0) {
goto out;
}
if (sscanf(strstr(result, ":") + 1, "%15[^,],%hu", adapter->network_info.mqttServerIp, &adapter->network_info.mqttServerPort) == 2) {
printf("mqtt server ip address:\t%s\n", adapter->network_info.mqttServerIp);
printf("mqtt server port:\t%hu\n", adapter->network_info.mqttServerPort);
} else {
printf("mqtt server ip address:\t%s\n", adapter->network_info.mqttServerIp);
printf("mqtt server port:\t%d\n", adapter->network_info.mqttServerPort);
printf("Failed to parse IP address and port\n");
goto out;
}
/* step8: serial write "AT+MQTTCID=?", get the current mqtt client id*/
memset(result, 0, sizeof(result));
ret = AtGetNetworkInfoReply(adapter->agent, GM800TF_GET_MQTT_CLIENTID_CMD, result);
if (ret < 0) {
goto out;
}
if (sscanf(strstr(result, "MQTTCID:"), "MQTTCID:%s", adapter->network_info.mqttClientId) == 1) {
printf("mqtt clientid:\t\t%s\n", adapter->network_info.mqttClientId);
} else {
printf("Failed to parse mqtt clientid\n");
goto out;
}
/* step9: serial write "AT+MQTTUSER=?", get the current mqtt username*/
memset(result, 0, sizeof(result));
ret = AtGetNetworkInfoReply(adapter->agent, GM800TF_GET_MQTT_USERNAME_CMD, result);
if (ret < 0) {
goto out;
}
if (sscanf(strstr(result, "MQTTUSER:"), "MQTTUSER:%s", adapter->network_info.mqttUsername) == 1) {
printf("mqtt username:\t\t%s\n", adapter->network_info.mqttUsername);
} else {
printf("Failed to parse mqtt username\n");
goto out;
}
/* step10: serial write "AT+MQTTPSW?", get the current mqtt password */
memset(result, 0, sizeof(result));
ret = AtGetNetworkInfoReply(adapter->agent, GM800TF_GET_MQTT_PASSWORD_CMD, result);
if (ret < 0) {
goto out;
}
if (sscanf(strstr(result, "MQTTPSW:"), "MQTTPSW:%s", adapter->network_info.mqttPassword) == 1) {
printf("mqtt password:\t\t%s\n", adapter->network_info.mqttPassword);
} else {
printf("Failed to parse mqtt password\n");
goto out;
}
/*step11: serial write "AT+MQTTSTA", get the status of mqtt connection*/
memset(result, 0, sizeof(result));
ret = AtGetNetworkInfoReply(adapter->agent, GM800TF_GET_MQTT_STATUS_CMD, result);
if (ret < 0) {
goto out;
}
char mqtt_status[20] = {};
if (sscanf(strstr(result, "STA:"), "STA: %s", mqtt_status) == 1) {
printf("mqtt status:\t\t%s\n", mqtt_status);
adapter->network_info.mqttIsConnected = strcmp(mqtt_status, "\"CONNECTION\"") == 0 ? 1 : 0;
} else {
printf("Failed to parse mqtt status\n");
goto out;
}
/* step12: serial write "AT+ENTM", enter entm mode */
ret = AtCmdConfigAndCheck(adapter->agent, GM800TF_ENTM_MODE_CMD, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
printf("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-\n");
return 0;
out:
printf("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-\n");
ADAPTER_DEBUG("Gm800tf get netstat failed.\n");
return -1;
}
int Gm800tfMqttConnect(struct Adapter *adapter, const char *ip, const char *port, const char *client_id, const char *username,
const char *password);
int Gm800tfMqttDisconnect(struct Adapter *adapter);
int Gm800tfMqttSend(struct Adapter *adapter, const char *topic, const void *buf, size_t len);
int Gm800tfMqttRecv(struct Adapter *adapter, const char *topic, void *buf, size_t len);
static const struct IpProtocolDone gm800tf_done = {
.open = Gm800tfOpen,
.close = Gm800tfClose,
.ioctl = Gm800tfIoctl,
.setup = NULL,
.setdown = NULL,
.setaddr = NULL,
.setdns = NULL,
.setdhcp = NULL,
.ping = NULL,
.netstat = Gm800tfNetstat,
.connect = Gm800tfConnect,
.send = Gm800tfSend,
.recv = Gm800tfRecv,
.disconnect = Gm800tfDisconnect,
.mqttconnect = Gm800tfMqttConnect,
.mqttdisconnect = Gm800tfMqttDisconnect,
.mqttsend = Gm800tfMqttSend,
.mqttrecv = Gm800tfMqttRecv,
};
/**
* @brief expose the behavior of GM800TF to application
* @param adapter
* @return AdapterProductInfoType
*/
AdapterProductInfoType Gm800tfAttach(struct Adapter *adapter) {
struct AdapterProductInfo *product_info = PrivMalloc(sizeof(struct AdapterProductInfo));
if (!product_info) {
printf("Gm800tfAttach malloc product_info error\n");
PrivFree(product_info);
return NULL;
}
strcpy(product_info->model_name, ADAPTER_4G_GM800TF);
product_info->model_done = (void *)&gm800tf_done;
return product_info;
}
@@ -0,0 +1,316 @@
/*
* Copyright (c) 2020 AIIT XUOS Lab
* XiUOS is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* @file gm800tf_mqtt.c
* @brief Implement the connection 4G adapter function about mqtt, using GM800TF device
* @author Huo Yujia (huoyujia081@126.com)
* @version 1.0
* @date 2024-07-26
*/
#include <adapter.h>
#include <at_agent.h>
#define GM800TF_GET_ICCID_CMD "AT+ICCID\r\n"
#define GM800TF_SET_WKMOD_MQTT_CMD "AT+WKMOD=MQTT,NOR\r\n"
#define GM800TF_SET_WKMOD_CMD_CMD "AT+WKMOD=CMD\r\n"
#define GM800TF_GET_MQTT_PUBPARAM_CMD "AT+MQTTPUBTP?\r\n"
#define GM800TF_SET_MQTT_PUBPARAM_CMD "AT+MQTTPUBTP=%d,%d,%s,%d,%d\r\n"
#define GM800TF_SET_MQTT_SUBPARAM_CMD "AT+MQTTSUBTP=%d,%d,%s,%d\r\n"
#define GM800TF_SET_MQTT_SERVER_CMD "AT+MQTTSVR=%s,%s\r\n"
#define GM800TF_SET_MQTT_USERNAME_CMD "AT+MQTTUSER=%s\r\n"
#define GM800TF_SET_MQTT_PASSWORD_CMD "AT+MQTTPSW=%s\r\n"
#define GM800TF_SET_MQTT_CLIID_CMD "AT+MQTTCID=%s\r\n"
#define GM800TF_SET_MQTT_MODE_CMD "AT+MQTTMOD=%d\r\n"
#define GM800TF_SET_HEART_DATA_CMD "AT+HEARTDT=%s\r\n"
#define GM800TF_SET_HEART_TIME_CMD "AT+HEARTTM=%d\r\n"
#define GM800TF_SAVE_CFG_CMD "AT+S\r\n"
#define GM800TF_ENTM_MODE_CMD "AT+ENTM\r\n"
#define GM800TF_OK_REPLY "OK"
#define GM800TF_READY_REPLY "READY"
#define GM800TF_CREG_REPLY ",1"
#define GM800TF_PUBEX_REPLY ">"
#define TRY_TIMES 10
int Gm800tfEnterAtMode(struct Adapter *adapter); // defined in gm800tf.c
/**
* @brief connect to mqtt server
* @param adapter
* @param ip mqtt server ip address
* @param port mqtt server port
* @param client_id mqtt client id
* @param username mqtt username
* @param password mqtt password
* @return int 0: success, -1: failed
*/
int Gm800tfMqttConnect(struct Adapter *adapter, const char *ip, const char *port, const char *client_id, const char *username,
const char *password) {
int ret = 0;
uint8_t gm800tf_cmd[64];
/*step0: compare ip and port with current configuration, and if they are the same there is no need to connect again*/
AdapterDeviceNetstat(adapter);
if (adapter->network_info.workMode == 2 && strcmp(adapter->network_info.mqttServerIp, ip) == 0 &&
adapter->network_info.mqttServerPort == atoi(port) && strcmp(adapter->network_info.mqttClientId, client_id) == 0 &&
strcmp(adapter->network_info.mqttUsername, username) == 0 && strcmp(adapter->network_info.mqttPassword, password) == 0 &&
adapter->network_info.mqttIsConnected && adapter->network_info.signal_strength < 99) {
return 0;
}
/*step1: serial write "+++" and "a", quit transparent mode*/
ret = Gm800tfEnterAtMode(adapter);
if (ret < 0) {
goto out;
}
AtSetReplyEndChar(adapter->agent, 'O', 'K');
AtSetReplyCharNum(adapter->agent, 256);
AtSetReplyLrEnd(adapter->agent, 0);
/*step2: serial write "AT+ICCID", get SIM ID*/
ret = AtCmdConfigAndCheck(adapter->agent, GM800TF_GET_ICCID_CMD, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/*step3: serial write "AT+MQTTSVR=<server>,<port>", config mqtt ip and port*/
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_SET_MQTT_SERVER_CMD, ip, port);
ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/*step4: serial write "AT+MQTTCID=<clientid>", config mqtt client id*/
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_SET_MQTT_CLIID_CMD, client_id);
ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/*step5: serial write "AT+MQTTUSER=<username>", config mqtt username*/
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_SET_MQTT_USERNAME_CMD, username);
ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/*step6: serial write "AT+MQTTPSW=<password>", config mqtt password*/
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_SET_MQTT_PASSWORD_CMD, password);
ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/*step7: serial write "AT+WKMOD=MQTT", set the working mode to mqtt mode*/
ret = AtCmdConfigAndCheck(adapter->agent, GM800TF_SET_WKMOD_MQTT_CMD, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/*step8: serial write "AT+MQTTMOD=<mode>, set the mqtt mode*/
/* mode-0: Send data to all preset enabled topics */
/* mode-1: Send data separately to a specific topic */
int mode = 1;
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_SET_MQTT_MODE_CMD, mode);
ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/*step9: set the heartbeat parameter*/
char *heartbeatData = "heartbeat test";
int heartbeatTime = 30;
char heartbeatDataHex[65] = {}; // 最多32个字符
void string_to_hex(const char *input, char *output);
string_to_hex(heartbeatData, heartbeatDataHex);
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_SET_HEART_DATA_CMD, heartbeatDataHex);
ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_SET_HEART_TIME_CMD, heartbeatTime);
ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/*step10: serial write "AT+S", save configuration and restart mqtt module*/
ret = AtCmdConfigAndCheck(adapter->agent, GM800TF_SAVE_CFG_CMD, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
PrivTaskDelay(20000); // after save configuration, wait at least 10s for restarting
ADAPTER_DEBUG("Gm800tf mqtt connect done\n");
return 0;
out:
ADAPTER_DEBUG("Gm800tf mqtt connect failed. Power down\n");
return -1;
}
/**
* @brief this function has no use
* @param adapter
* @return int
*/
int Gm800tfMqttDisconnect(struct Adapter *adapter) {
int ret = 0;
return 0;
}
/**
* @brief send data to mqtt server
* @param adapter
* @param topic mqtt publish topic
* @param buf data buffer to send to mqtt server
* @param len data length
* @return int 0: success; others: failed
*/
int Gm800tfMqttSend(struct Adapter *adapter, const char *topic, const void *buf, size_t len) {
/* query for whether socket is connected successfully */
AdapterDeviceNetstat(adapter);
if (adapter->network_info.mqttIsConnected == 0) {
printf("[error %s %d]socket has not been connected, please call function AdapterDeviceMqttConnect\n", __func__, __LINE__);
return -1;
}
int ret = 0;
char result[256] = {};
uint8_t gm800tf_cmd[64];
static const char *publishTopics[10] = {NULL}; // save the mqtt publish topics temporarily
static int topicIndex = 0; // the index next mqtt topic to be saved
/* step0: check if the topic in the topics array */
for (int i = 0; i < 10; i++) {
if (publishTopics[i] != NULL && strcmp(publishTopics[i], topic) == 0) {
char num[10];
sprintf(num, "%d,", i + 1);
EntmSend(adapter->agent, num, strlen(num));
EntmSend(adapter->agent, (const char *)buf, len);
return 0;
}
}
topicIndex = topicIndex >= 10 ? 0 : topicIndex;
publishTopics[topicIndex] = topic; // save the topic to the topics array
/* step1: serial send "+++" and "a", quit transparent mode */
ret = Gm800tfEnterAtMode(adapter);
if (ret < 0) {
goto out;
}
AtSetReplyEndChar(adapter->agent, 'O', 'K');
AtSetReplyCharNum(adapter->agent, 256);
AtSetReplyLrEnd(adapter->agent, 0);
/* step2: serial write "AT+MQTTPUBTP=<pubnum>,<puben>,<topic>,<qos>,<retained>", config the publish parameters */
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_SET_MQTT_PUBPARAM_CMD, topicIndex + 1, 1, topic, 2, 0);
ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
/* step3: serial write "AT+S", save the configuration and restart the module */
ret = AtCmdConfigAndCheck(adapter->agent, GM800TF_SAVE_CFG_CMD, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
PrivTaskDelay(15000); // after save configuration, wait at least 10s for restarting
/* step4: send the data to mqtt server */
char num[10];
sprintf(num, "%d,", topicIndex + 1);
EntmSend(adapter->agent, num, strlen(num));
EntmSend(adapter->agent, buf, len);
topicIndex++;
ADAPTER_DEBUG("Gm800tf mqtt send done\n");
return 0;
out:
ADAPTER_DEBUG("Gm800tf mqtt send failed.\n");
return -1;
}
/**
* @brief GM800TF only support transparent mode, so the topic is not used. The Message can't be diffrentiated by
* topic in the received data.
* @param adapter
* @param topic
* @param buf
* @param len
* @return int
* @note 该函数暂时未经过测试
*/
int Gm800tfMqttRecv(struct Adapter *adapter, const char *topic, void *buf, size_t len) {
int ret = 0;
static const char *subscribeTopics[10] = {NULL};
static int topicIndex = 0;
uint8_t gm800tf_cmd[64];
/* check if the topic in the topics array */
for (int i = 0; i < 10; i++) {
if (subscribeTopics[i] != NULL && strcmp(subscribeTopics[i], topic) == 0) {
if (adapter->agent) {
return EntmRecv(adapter->agent, (char *)buf, len, 6);
} else {
printf("Gm800tfRecv can not find agent\n");
return -1;
}
}
}
topicIndex = topicIndex >= 10 ? 0 : topicIndex;
subscribeTopics[topicIndex] = topic;
ret = Gm800tfEnterAtMode(adapter);
if (ret < 0) {
goto out;
}
AtSetReplyEndChar(adapter->agent, 'O', 'K');
AtSetReplyCharNum(adapter->agent, 256);
AtSetReplyLrEnd(adapter->agent, 0);
memset(gm800tf_cmd, 0, sizeof(gm800tf_cmd));
sprintf(gm800tf_cmd, GM800TF_SET_MQTT_SUBPARAM_CMD, topicIndex + 1, 1, topic, 2);
ret = AtCmdConfigAndCheck(adapter->agent, gm800tf_cmd, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
ret = AtCmdConfigAndCheck(adapter->agent, GM800TF_SAVE_CFG_CMD, GM800TF_OK_REPLY);
if (ret < 0) {
goto out;
}
PrivTaskDelay(15000); // after save configuration, wait at least 10s for restarting
if (adapter->agent) {
return EntmRecv(adapter->agent, (char *)buf, len, 6);
} else {
printf("Gm800tfRecv can not find agent\n");
}
out:
ADAPTER_DEBUG("Gm800tf mqtt receive failed.\n");
return -1;
}
@@ -129,6 +129,18 @@ struct NetworkInfo {
enum CarrierType carrier_type;
int signal_strength;
char ip_address[16];
#ifdef ADAPTER_GM800TF
unsigned char workMode; // 工作模式,1为NET2为MQTT,NOR
unsigned short port; // 目的端口号
unsigned char is_connected; // SOCKET连接状态,0为失败,1为成功
unsigned char mqttSwitch; // MQTT开关
char mqttServerIp[16]; // MQTT目的IP地址
unsigned short mqttServerPort; // MQTT目的端口号
char mqttClientId[64]; // MQTT客户端ID
char mqttUsername[64]; // MQTT用户名
char mqttPassword[64]; // MQTT密码
unsigned char mqttIsConnected; // MQTT连接状态,0为失败,1为成功
#endif
};
struct AdapterData
+186 -113
View File
@@ -1,14 +1,14 @@
/*
* Copyright (c) 2020 AIIT XUOS Lab
* XiUOS is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
* Copyright (c) 2020 AIIT XUOS Lab
* XiUOS is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* @file xs_adapterAT_client.c
@@ -18,7 +18,6 @@
* @date 2021.04.22
*/
#include <at_agent.h>
#include <adapter.h>
#include <stdbool.h>
@@ -27,7 +26,7 @@
#include <stdlib.h>
#include <string.h>
#ifdef ADD_XIZI_FEATURES
# include <user_api.h>
#include <user_api.h>
#endif
#ifdef ADD_RTTHREAD_FEATURES
#include <rtthread.h>
@@ -49,9 +48,11 @@ unsigned int IpTint(char *ipstr)
token = strtok(ipstr, ".");
while (token != NULL) {
while (token != NULL)
{
cur = atoi(token);
if (cur >= 0 && cur <= 255) {
if (cur >= 0 && cur <= 255)
{
total += cur * pow(256, i);
}
i--;
@@ -65,8 +66,10 @@ void SwapStr(char *str, int begin, int end)
{
int i, j;
for (i = begin, j = end; i <= j; i++, j--) {
if (str[i] != str[j]) {
for (i = begin, j = end; i <= j; i++, j--)
{
if (str[i] != str[j])
{
str[i] = str[i] ^ str[j];
str[j] = str[i] ^ str[j];
str[i] = str[i] ^ str[j];
@@ -83,7 +86,8 @@ char *IpTstr(unsigned int ipint)
char token[4];
int bt, ed, len, cur;
while (ipint) {
while (ipint)
{
cur = ipint % 256;
sprintf(token, "%d", cur);
strcat(new, token);
@@ -95,8 +99,10 @@ char *IpTstr(unsigned int ipint)
len = strlen(new);
SwapStr(new, 0, len - 1);
for (bt = ed = 0; ed < len;) {
while (ed < len && new[ed] != '.') {
for (bt = ed = 0; ed < len;)
{
while (ed < len && new[ed] != '.')
{
ed++;
}
SwapStr(new, bt, ed - 1);
@@ -125,14 +131,15 @@ void ATSprintf(int fd, const char *format, va_list params)
{
last_cmd_len = vsnprintf(send_buf, sizeof(send_buf), format, params);
#ifdef CONNECTION_FRAMEWORK_DEBUG
printf("AT send %s len %u\n",send_buf, last_cmd_len);
printf("AT send %s len %u\n", send_buf, last_cmd_len);
#endif
PrivWrite(fd, send_buf, last_cmd_len);
PrivWrite(fd, send_buf, last_cmd_len);
}
int ATOrderSend(ATAgentType agent, uint32_t timeout_s, ATReplyType reply, const char *cmd_expr, ...)
{
if (agent == NULL) {
if (agent == NULL)
{
printf("ATAgent is null");
return -1;
}
@@ -158,19 +165,23 @@ int ATOrderSend(ATAgentType agent, uint32_t timeout_s, ATReplyType reply, const
agent->reply = reply;
PrivMutexAbandon(&agent->lock);
if(agent->reply != NULL) {
if (agent->reply != NULL)
{
PrivMutexObtain(&agent->lock);
reply->reply_len = 0;
va_start(params, cmd_expr);
ATSprintf(agent->fd, cmd_expr, params);
va_end(params);
PrivMutexAbandon(&agent->lock);
if (PrivSemaphoreObtainWait(&agent->rsp_sem, &abstime) != 0) {
printf("take sem %d timeout\n",agent->rsp_sem);
if (PrivSemaphoreObtainWait(&agent->rsp_sem, &abstime) != 0)
{
printf("take sem %d timeout\n", agent->rsp_sem);
result = -2;
goto __out;
}
} else {
}
else
{
PrivMutexObtain(&agent->lock);
va_start(params, cmd_expr);
ATSprintf(agent->fd, cmd_expr, params);
@@ -187,35 +198,42 @@ int AtCmdConfigAndCheck(ATAgentType agent, char *cmd, char *check)
{
int ret = 0;
char *result = NULL;
if (NULL == agent || NULL == cmd || NULL == check ) {
if (NULL == agent || NULL == cmd || NULL == check)
{
return -1;
}
ATReplyType reply = CreateATReply(256);
if (NULL == reply) {
printf("%s %d at_create_resp failed!\n",__func__,__LINE__);
if (NULL == reply)
{
printf("%s %d at_create_resp failed!\n", __func__, __LINE__);
ret = -1;
goto __exit;
}
ret = ATOrderSend(agent, REPLY_TIME_OUT, reply, cmd);
if(ret < 0){
printf("%s %d ATOrderSend failed.\n",__func__,__LINE__);
if (ret < 0)
{
printf("%s %d ATOrderSend failed.\n", __func__, __LINE__);
ret = -1;
goto __exit;
}
//PrivTaskDelay(3000);
// PrivTaskDelay(3000);
result = GetReplyText(reply);
if (!result) {
printf("%s %n get reply failed.\n",__func__,__LINE__);
if (!result)
{
printf("%s %n get reply failed.\n", __func__, __LINE__);
ret = -1;
goto __exit;
}
#ifdef CONNECTION_FRAMEWORK_DEBUG
printf("[reply result: %s]\n", result);
if(!strstr(result, check)) {
printf("%s %d check[%s] reply[%s] failed.\n",__func__,__LINE__,check,result);
#endif
if (!strstr(result, check))
{
printf("%s %d check[%s] reply[%s] failed.\n", __func__, __LINE__, check, result);
ret = -1;
goto __exit;
}
@@ -228,34 +246,40 @@ __exit:
int AtGetNetworkInfoReply(ATAgentType agent, char *cmd, char *result)
{
int ret = 0;
if (NULL == agent || NULL == cmd) {
if (NULL == agent || NULL == cmd)
{
return -1;
}
ATReplyType reply = CreateATReply(256);
if (NULL == reply) {
printf("%s %d at_create_resp failed!\n",__func__,__LINE__);
if (NULL == reply)
{
printf("%s %d at_create_resp failed!\n", __func__, __LINE__);
ret = -1;
goto __exit;
}
ret = ATOrderSend(agent, REPLY_TIME_OUT, reply, cmd);
if(ret < 0){
printf("%s %d ATOrderSend failed.\n",__func__,__LINE__);
if (ret < 0)
{
printf("%s %d ATOrderSend failed.\n", __func__, __LINE__);
ret = -1;
goto __exit;
}
const char *replyText = GetReplyText(reply);
if (replyText == NULL || replyText[0] == '\0') {
printf("%s %n get reply failed.\n",__func__,__LINE__);
if (replyText == NULL || replyText[0] == '\0')
{
printf("%s %n get reply failed.\n", __func__, __LINE__);
ret = -1;
goto __exit;
}
strncpy(result, replyText, 63);
result[63] = '\0';
#ifdef CONNECTION_FRAMEWORK_DEBUG
printf("[reply result: %s]\n", result);
#endif
__exit:
DeleteATReply(reply);
@@ -269,7 +293,8 @@ char *GetReplyText(ATReplyType reply)
int AtSetReplyLrEnd(ATAgentType agent, char enable)
{
if (!agent) {
if (!agent)
{
return -1;
}
@@ -280,7 +305,8 @@ int AtSetReplyLrEnd(ATAgentType agent, char enable)
int AtSetReplyEndChar(ATAgentType agent, char last_ch, char end_ch)
{
if (!agent) {
if (!agent)
{
return -1;
}
@@ -292,7 +318,8 @@ int AtSetReplyEndChar(ATAgentType agent, char last_ch, char end_ch)
int AtSetReplyCharNum(ATAgentType agent, unsigned int num)
{
if (!agent) {
if (!agent)
{
return -1;
}
@@ -303,8 +330,9 @@ int AtSetReplyCharNum(ATAgentType agent, unsigned int num)
int EntmSend(ATAgentType agent, const char *data, int len)
{
if(len > 256){
printf("send length %d more then max 256 Bytes.\n",len);
if (len > 256)
{
printf("send length %d more then max 256 Bytes.\n", len);
return -1;
}
char *send_buff = (char *)PrivMalloc(256);
@@ -333,18 +361,20 @@ int EntmRecv(ATAgentType agent, char *rev_buffer, int buffer_len, int timeout_s)
uint32 real_recv_len = 0;
abstime.tv_sec = timeout_s;
if(buffer_len > ENTM_RECV_MAX){
printf("read length more then max length[%d] Bytes",ENTM_RECV_MAX);
return -1;
if (buffer_len > ENTM_RECV_MAX)
{
printf("read length more then max length[%d] Bytes", ENTM_RECV_MAX);
return -1;
}
PrivMutexObtain(&agent->lock);
agent->receive_mode = ENTM_MODE;
agent->read_len = buffer_len;
PrivMutexAbandon(&agent->lock);
//PrivTaskDelay(1000);
if (PrivSemaphoreObtainWait(&agent->entm_rx_notice, &abstime)) {
// PrivTaskDelay(1000);
if (PrivSemaphoreObtainWait(&agent->entm_rx_notice, &abstime))
{
#ifdef CONNECTION_FRAMEWORK_DEBUG
printf("wait sem[%d] timeout\n",agent->entm_rx_notice);
printf("wait sem[%d] timeout\n", agent->entm_rx_notice);
#endif
agent->entm_recv_len = 0;
return -1;
@@ -381,74 +411,86 @@ static int GetCompleteATReply(ATAgentType agent)
PrivMutexAbandon(&agent->lock);
while (1) {
while (1)
{
res = PrivRead(agent->fd, &ch, 1);
#ifdef CONNECTION_FRAMEWORK_DEBUG
if((res == 1) && (ch != 0)) {
if ((res == 1) && (ch != 0))
{
printf(" %c (0x%x)\n", ch, ch);
}
#endif
PrivMutexObtain(&agent->lock);
if (agent->receive_mode == ENTM_MODE) {
if (agent->entm_recv_len < ENTM_RECV_MAX) {
if (agent->receive_mode == ENTM_MODE)
{
if (agent->entm_recv_len < ENTM_RECV_MAX)
{
#ifdef LIB_USING_MQTT
if((res == 1) && (agent->entm_recv_len < agent->read_len))
if ((res == 1) && (agent->entm_recv_len < agent->read_len))
{
agent->entm_recv_buf[agent->entm_recv_len] = ch;
agent->entm_recv_len++;
PrivMutexAbandon(&agent->lock);
continue;
}
}
#else
agent->entm_recv_buf[agent->entm_recv_len] = ch;
agent->entm_recv_len++;
if(agent->entm_recv_len < agent->read_len)
if (agent->entm_recv_len < agent->read_len)
{
PrivMutexAbandon(&agent->lock);
continue;
}
#endif
else
#endif
else
{
#ifdef CONNECTION_FRAMEWORK_DEBUG
printf("ENTM_MODE recv %d Bytes done.\n",agent->entm_recv_len);
printf("ENTM_MODE recv %d Bytes done.\n", agent->entm_recv_len);
#endif
agent->receive_mode = DEFAULT_MODE;
PrivSemaphoreAbandon(&agent->entm_rx_notice);
}
} else {
}
else
{
printf("entm_recv_buf is_full ...\n");
}
}
else if (agent->receive_mode == AT_MODE) {
if (read_len < agent->maintain_max) {
if(ch != 0) { ///< if the char is null then do not save it to the buff
else if (agent->receive_mode == AT_MODE)
{
if (read_len < agent->maintain_max)
{
if (ch != 0)
{ ///< if the char is null then do not save it to the buff
agent->maintain_buffer[read_len] = ch;
read_len++;
agent->maintain_len = read_len;
}
} else {
}
else
{
printf("maintain_len is_full %d ...\n", read_len);
is_full = true;
}
if (((ch == '\n') && (agent->reply_lr_end)) ||
((ch == '\n') && (last_ch == '\r') && (agent->reply_lr_end)) ||
((ch == agent->reply_end_char) && (agent->reply_end_char) &&
(last_ch == agent->reply_end_last_char) && (agent->reply_end_last_char)) ||
((read_len == agent->reply_char_num) && (agent->reply_char_num))) {
if (is_full) {
((ch == agent->reply_end_char) && (agent->reply_end_char) &&
(last_ch == agent->reply_end_last_char) && (agent->reply_end_last_char)) ||
((read_len == agent->reply_char_num) && (agent->reply_char_num)))
{
if (is_full)
{
printf("read line failed. The line data length is out of buffer size(%d)!", agent->maintain_max);
memset(agent->maintain_buffer, 0x00, agent->maintain_max);
agent->maintain_len = 0;
PrivMutexAbandon(&agent->lock);
return -1;
}
#ifdef CONNECTION_FRAMEWORK_DEBUG
printf("GetCompleteATReply done\n");
#endif
agent->receive_mode = DEFAULT_MODE;
PrivMutexAbandon(&agent->lock);
break;
@@ -464,9 +506,11 @@ static int GetCompleteATReply(ATAgentType agent)
ATAgentType GetATAgent(const char *agent_name)
{
struct ATAgent* result = NULL;
for (int i = 0; i < AT_AGENT_MAX; i++) {
if (strcmp(at_agent_table[i].agent_name, agent_name) == 0) {
struct ATAgent *result = NULL;
for (int i = 0; i < AT_AGENT_MAX; i++)
{
if (strcmp(at_agent_table[i].agent_name, agent_name) == 0)
{
result = &at_agent_table[i];
}
}
@@ -474,45 +518,51 @@ ATAgentType GetATAgent(const char *agent_name)
return result;
}
int DeleteATAgent(ATAgentType agent)
{
printf("delete agent->at_handler = %d\n",agent->at_handler);
if(agent->at_handler > 0){
printf("delete agent->at_handler = %d\n", agent->at_handler);
if (agent->at_handler > 0)
{
PrivTaskDelete(agent->at_handler, 0);
}
if (agent->fd > 0) {
printf("close agent fd = %d\n",agent->fd);
if (agent->fd > 0)
{
printf("close agent fd = %d\n", agent->fd);
PrivClose(agent->fd);
}
#ifdef ADD_NUTTX_FEATURES
if (agent->lock.sem.semcount > 0) {
printf("delete agent lock = %d\n",agent->lock.sem.semcount);
if (agent->lock.sem.semcount > 0)
{
printf("delete agent lock = %d\n", agent->lock.sem.semcount);
PrivMutexDelete(&agent->lock);
}
#elif defined ADD_RTTHREAD_FEATURES
#else
if (agent->lock) {
printf("delete agent lock = %d\n",agent->lock);
if (agent->lock)
{
printf("delete agent lock = %d\n", agent->lock);
PrivMutexDelete(&agent->lock);
}
#endif
#ifdef ADD_XIZI_FEATURES
if (agent->entm_rx_notice) {
printf("delete agent entm_rx_notice = %d\n",agent->entm_rx_notice);
if (agent->entm_rx_notice)
{
printf("delete agent entm_rx_notice = %d\n", agent->entm_rx_notice);
PrivSemaphoreDelete(&agent->entm_rx_notice);
}
#else
#endif
#ifdef ADD_XIZI_FEATURES
if (agent->rsp_sem) {
printf("delete agent rsp_sem = %d\n",agent->rsp_sem);
PrivSemaphoreDelete(&agent->rsp_sem);
if (agent->rsp_sem)
{
printf("delete agent rsp_sem = %d\n", agent->rsp_sem);
PrivSemaphoreDelete(&agent->rsp_sem);
}
#endif
if (agent->maintain_buffer) {
if (agent->maintain_buffer)
{
PrivFree(agent->maintain_buffer);
}
@@ -525,18 +575,24 @@ static void *ATAgentReceiveProcess(void *param)
ATAgentType agent = (ATAgentType)param;
const struct at_urc *urc;
while (1) {
if (GetCompleteATReply(agent) > 0) {
while (1)
{
if (GetCompleteATReply(agent) > 0)
{
PrivMutexObtain(&agent->lock);
if (agent->reply != NULL) {
if (agent->reply != NULL)
{
ATReplyType reply = agent->reply;
agent->maintain_buffer[agent->maintain_len] = '\0';
if (agent->maintain_len <= reply->reply_max_len) {
memset(reply->reply_buffer, 0 , reply->reply_max_len);
if (agent->maintain_len <= reply->reply_max_len)
{
memset(reply->reply_buffer, 0, reply->reply_max_len);
memcpy(reply->reply_buffer, agent->maintain_buffer, agent->maintain_len);
reply->reply_len = agent->maintain_len;
} else {
}
else
{
printf("out of memory (%d)!\n", reply->reply_max_len);
}
@@ -555,7 +611,8 @@ static int ATAgentInit(ATAgentType agent)
agent->maintain_len = 0;
agent->maintain_buffer = (char *)PrivMalloc(agent->maintain_max);
if (agent->maintain_buffer == NULL) {
if (agent->maintain_buffer == NULL)
{
printf("ATAgentInit malloc maintain_buffer error\n");
goto __out;
}
@@ -563,18 +620,21 @@ static int ATAgentInit(ATAgentType agent)
memset(agent->maintain_buffer, 0, agent->maintain_max);
result = PrivSemaphoreCreate(&agent->entm_rx_notice, 0, 0);
if (result < 0) {
if (result < 0)
{
printf("ATAgentInit create entm sem error\n");
goto __out;
}
result = PrivSemaphoreCreate(&agent->rsp_sem, 0, 0);
if (result < 0) {
if (result < 0)
{
printf("ATAgentInit create rsp sem error\n");
goto __out;
}
if(PrivMutexCreate(&agent->lock, 0) < 0) {
if (PrivMutexCreate(&agent->lock, 0) < 0)
{
printf("AdapterFrameworkInit mutex create failed.\n");
goto __out;
}
@@ -591,6 +651,10 @@ static int ATAgentInit(ATAgentType agent)
pthread_attr_t attr;
attr.schedparam.sched_priority = 25;
attr.stacksize = 4096;
#ifdef ADAPTER_GM800TF
attr.schedparam.sched_priority = 16;
attr.stacksize = 1800;
#endif
char task_name[] = "at_agent";
pthread_args_t args;
@@ -616,15 +680,18 @@ int InitATAgent(const char *agent_name, int agent_fd, uint32 maintain_max)
int open_result = 0;
struct ATAgent *agent = NULL;
if (GetATAgent(agent_name) != NULL) {
if (GetATAgent(agent_name) != NULL)
{
return result;
}
while (i < AT_AGENT_MAX && at_agent_table[i].fd > 0) {
while (i < AT_AGENT_MAX && at_agent_table[i].fd > 0)
{
i++;
}
if (i >= AT_AGENT_MAX) {
if (i >= AT_AGENT_MAX)
{
printf("agent buffer(%d) is full.", AT_AGENT_MAX);
result = -1;
return result;
@@ -639,7 +706,8 @@ int InitATAgent(const char *agent_name, int agent_fd, uint32 maintain_max)
agent->maintain_max = maintain_max;
result = ATAgentInit(agent);
if (result == 0) {
if (result == 0)
{
PrivTaskStartup(&agent->at_handler);
}
@@ -651,7 +719,8 @@ ATReplyType CreateATReply(uint32 reply_max_len)
ATReplyType reply = NULL;
reply = (ATReplyType)PrivMalloc(sizeof(struct ATReply));
if (reply == NULL) {
if (reply == NULL)
{
printf("no more memory\n");
return NULL;
}
@@ -660,7 +729,8 @@ ATReplyType CreateATReply(uint32 reply_max_len)
reply->reply_max_len = reply_max_len;
reply->reply_buffer = (char *)PrivMalloc(reply_max_len);
if (reply->reply_buffer == NULL) {
if (reply->reply_buffer == NULL)
{
printf("no more memory\n");
PrivFree(reply);
return NULL;
@@ -673,14 +743,17 @@ ATReplyType CreateATReply(uint32 reply_max_len)
void DeleteATReply(ATReplyType reply)
{
if (reply) {
if (reply->reply_buffer) {
if (reply)
{
if (reply->reply_buffer)
{
PrivFree(reply->reply_buffer);
reply->reply_buffer = NULL;
}
}
if (reply) {
if (reply)
{
PrivFree(reply);
reply = NULL;
}
@@ -59,7 +59,11 @@ struct ATAgent
uint32 maintain_max;
#ifdef ADD_XIZI_FEATURES
int lock;
#ifdef ADAPTER_GM800TF
pthread_mutex_t lock;
#else
int lock;
#endif
#else
pthread_mutex_t lock;
#endif
@@ -3,7 +3,13 @@ config ADAPTER_HFA21_ETHERNET
Please check HFA21 can only work for adapter_wifi or adapter_ethernet in the meantime!
bool "Using ethernet adapter device HFA21"
default n
config ADAPTER_WCHNET_ETHERNET
bool "Using ethernet adapter device WCHNET"
default n
if ADAPTER_HFA21_ETHERNET
source "$APP_DIR/Framework/connection/ethernet/hfa21_ethernet/Kconfig"
endif
if ADAPTER_WCHNET_ETHERNET
source "$APP_DIR/Framework/connection/ethernet/wchnet_ethernet/Kconfig"
endif
@@ -3,5 +3,8 @@ SRC_FILES := adapter_ethernet.c
ifeq ($(CONFIG_ADAPTER_HFA21_ETHERNET),y)
SRC_DIR += hfa21_ethernet
endif
ifeq ($(CONFIG_ADAPTER_WCHNET_ETHERNET),y)
SRC_DIR += wchnet_ethernet
endif
include $(KERNEL_ROOT)/compiler.mk
@@ -1,14 +1,14 @@
/*
* Copyright (c) 2020 AIIT XUOS Lab
* XiUOS is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
* Copyright (c) 2020 AIIT XUOS Lab
* XiUOS is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* @file adapter_ethernet.c
@@ -23,9 +23,11 @@
#ifdef ADAPTER_HFA21_ETHERNET
extern AdapterProductInfoType Hfa21EthernetAttach(struct Adapter *adapter);
#endif
#ifdef ADAPTER_WCHNET_ETHERNET
extern AdapterProductInfoType wchnetEthernetAttach(struct Adapter *adapter);
#endif
static int AdapterEthernetRegister(struct Adapter *adapter)
{
static int AdapterEthernetRegister(struct Adapter *adapter) {
int ret = 0;
strncpy(adapter->name, ADAPTER_ETHERNET_NAME, NAME_NUM_MAX);
@@ -42,8 +44,7 @@ static int AdapterEthernetRegister(struct Adapter *adapter)
return ret;
}
int AdapterEthernetInit(void)
{
int AdapterEthernetInit(void) {
int ret = 0;
struct Adapter *adapter = PrivMalloc(sizeof(struct Adapter));
@@ -74,17 +75,28 @@ int AdapterEthernetInit(void)
adapter->info = product_info;
adapter->done = product_info->model_done;
#endif
#ifdef ADAPTER_WCHNET_ETHERNET
AdapterProductInfoType product_info = wchnetEthernetAttach(adapter);
if (!product_info) {
printf("AdapterEthernetInit wchnet attach error\n");
PrivFree(adapter);
return -1;
}
adapter->product_info_flag = 1;
adapter->info = product_info;
adapter->done = product_info->model_done;
#endif
return ret;
}
/******************ethernet TEST*********************/
int AdapterEthernetTest(void)
{
int AdapterEthernetTest(void) {
int baud_rate = BAUD_RATE_57600;
struct Adapter *adapter = AdapterDeviceFindByName(ADAPTER_ETHERNET_NAME);
struct Adapter *adapter = AdapterDeviceFindByName(ADAPTER_ETHERNET_NAME);
#ifdef ADAPTER_HFA21_ETHERNET
@@ -96,30 +108,67 @@ int AdapterEthernetTest(void)
AdapterDeviceControl(adapter, OPE_INT, &baud_rate);
AdapterDeviceSetUp(adapter);
const char *ip = "192.168.131.26";
const char *port = "9999";
enum NetRoleType net_role = CLIENT;//SERVER
enum NetRoleType net_role = CLIENT; // SERVER
enum IpType ip_type = IPV4;
AdapterDeviceConnect(adapter, net_role, ip, port, ip_type);
printf("ready to test data transfer\n");
PrivTaskDelay(2000);
len = strlen(ethernet_msg);
for (i = 0;i < 10; i ++) {
for (i = 0; i < 10; i++) {
printf("AdapterEthernetTest send %s\n", ethernet_msg);
AdapterDeviceSend(adapter, ethernet_msg, len);
PrivTaskDelay(4000);
}
while (1) {
AdapterDeviceRecv(adapter, ethernet_recv_msg, 128);
printf("AdapterEthernetTest recv %s\n", ethernet_recv_msg);
memset(ethernet_recv_msg, 0, 128);
}
#endif
#ifdef ADAPTER_WCHNET_ETHERNET
AdapterDeviceSetUp(adapter);
// AdapterDeviceSetAddr(adapter, "192.168.1.10", "255.255.255.0", "192.168.1.1");
// AdapterDeviceSetDhcp(adapter, 1);
// AdapterDeviceConnect(adapter, CLIENT, "115.238.53.59", "10208", IPV4);
AdapterDeviceConnect(adapter, CLIENT, "192.168.1.100", "1000", IPV4);
AdapterDeviceSend(adapter, "Hello World!", sizeof("Hello World!"));
// /* 测试DHCP连接路由器后,连接因特网 */
// AdapterDeviceSend(adapter,
// "GET /v3/weather/weatherInfo?city=%E9%95%BF%E6%B2%99&key=13cb58f5884f9749287abbead9c658f2 "
// "HTTP/1.1\r\nHost: restapi.amap.com\r\n\r\n",
// sizeof("GET
// /v3/weather/weatherInfo?city=%E9%95%BF%E6%B2%99&key=13cb58f5884f9749287abbead9c658f2 "
// "HTTP/1.1\r\nHost: restapi.amap.com\r\n\r\n"));
char receiveBuffer[128] = {};
PrivTaskDelay(20000);
ssize_t readLength = AdapterDeviceRecv(adapter, receiveBuffer, sizeof(receiveBuffer));
// printf("receiveBuffer:%s\n", receiveBuffer);
printf("[socketid-%d]receiveBuffer:", adapter->socket.socket_id);
for (int i = 0; i < readLength; i++) {
printf("%c", receiveBuffer[i]);
}
printf("\n");
AdapterDeviceDisconnect(adapter, NULL);
// AdapterDeviceConnect(adapter, CLIENT, "115.238.53.59", "10208", IPV4);
AdapterDeviceConnect(adapter, CLIENT, "192.168.1.100", "1000", IPV4);
AdapterDeviceSend(adapter, "Hello World!", sizeof("Hello World!"));
PrivTaskDelay(20000);
readLength = AdapterDeviceRecv(adapter, receiveBuffer, sizeof(receiveBuffer));
printf("[socketid-%d]receiveBuffer:", adapter->socket.socket_id);
for (int i = 0; i < readLength; i++) {
printf("%c", receiveBuffer[i]);
}
printf("\n");
AdapterDeviceSetDown(adapter);
AdapterDeviceClose(adapter);
#endif
return 0;
}
PRIV_SHELL_CMD_FUNCTION(AdapterEthernetTest, a ethernet test sample, PRIV_SHELL_CMD_MAIN_ATTR);
@@ -0,0 +1,3 @@
config ADAPTER_ETHERNET_WCHNET
string "WCHNET ETHERNET adapter name"
default "wchnet_ethernet"
@@ -0,0 +1,3 @@
SRC_FILES := wchnet_ethernet.c
include $(KERNEL_ROOT)/compiler.mk
@@ -0,0 +1,10 @@
from building import *
import os
cwd = GetCurrentDir()
src = []
if GetDepend(['ADAPTER_WCHNET_ETHERNET']):
src += ['wchnet_ethernet.c']
group = DefineGroup('connection ethernet wchnet', src, depend = [], CPPPATH = [cwd])
Return('group')
@@ -0,0 +1,532 @@
/*
* Copyright (c) 2020 AIIT XUOS Lab
* XiUOS is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
/**
* @file wchnet_ethernet.c
* @brief Implement the connection ethernet adapter function, using wchnet device
* @author Huo Yujia (huoyujia081@126.com)
* @version 1.0
* @date 2024-07-17
*/
#include <ModuleConfig.h>
#include <adapter.h>
#include <connect_ether.h>
#include <eth_driver.h>
extern pmodule_cfg CFG; // 从flash中读取的配置信息指针
/* 记录socket会话参数,由于ch32v208内存限制,目前只支持单个会话通信 */
struct WchnetSocketConfiguration wchnetSocketConfiguration;
/**
* @brief wchnet主任务线程,主要用于不断处理以太网中断
* @param argv 参数无意义
* @return void* 返回值无意义
*/
static void *wchnetMainTask(void *argv) {
struct WchnetSocketConfiguration *pWchnetSocketConfiguration = (struct WchnetSocketConfiguration *)argv;
while (1) {
PrivTaskDelay(50);
WCHNET_MainTask();
if (WCHNET_QueryGlobalInt()) {
WCHNET_HandleGlobalInt(pWchnetSocketConfiguration);
}
}
return NULL;
}
/**
* @brief 以太网发送数据
* @param adapter
* @param data 所要发送数据的存储区域指针
* @param len 所要发送数据的长度
* @return int 实际发送的数据长度
*/
static int wchnetEthernetSend(struct Adapter *adapter, const void *data, size_t len) {
struct WchnetSocketConfiguration *pWchnetSocketConfiguration =
(struct WchnetSocketConfiguration *)adapter->adapter_param;
/* 判断是否可以发送数据 */
if (pWchnetSocketConfiguration->wchnetMainThread == 0) { // 判断是否已启动wchnet主任务线程
printf("[error %s %d]wchnetMainThread has not been started, please call function AdapterDeviceSetUp first\n",
__func__, __LINE__);
return -1;
} else if (pWchnetSocketConfiguration->socketStatus != WCHNET_SOCKET_CONNECT_SUCCESS) { // 判断是否已连接socket
printf(
"[error %s %d]socket has not been connected, please call function AdapterDeviceConnect "
"first\n",
__func__, __LINE__);
return -1;
}
/* 发送数据 */
uint32_t tempLen = (uint32_t)len; // 实际发送数据长度
uint8_t res = WCHNET_SocketSend(pWchnetSocketConfiguration->socketId, (uint8_t *)data, &tempLen);
if (res == WCHNET_ERR_SUCCESS) {
printf("[socketid-%d]send data success, len = %d\n", adapter->socket.socket_id, tempLen);
return tempLen;
} else {
mStopIfError(res);
return -1;
}
}
/**
* @brief 以太网接收数据
* @param adapter
* @param rev_buffer 接收数据首地址
* @param buffer_len 期望读取的数据长度
* @return int 实际读取的数据长度
*/
static int wchnetEthernetReceive(struct Adapter *adapter, void *rev_buffer, size_t buffer_len) {
struct WchnetSocketConfiguration *pWchnetSocketConfiguration =
(struct WchnetSocketConfiguration *)adapter->adapter_param;
/* 判断是否可以接收数据 */
if (pWchnetSocketConfiguration->wchnetMainThread == 0) { // 判断是否已启动wchnet主任务线程
printf("[error %s %d]wchnetMainThread has not been started, please call function AdapterDeviceSetUp first\n",
__func__, __LINE__);
return -1;
}
/* 接收数据 */
uint32_t tempLen = (uint32_t)buffer_len; // 实际接收数据长度
uint8_t res = WCHNET_SocketRecv(pWchnetSocketConfiguration->socketId, (u8 *)rev_buffer, &tempLen);
if (res == WCHNET_ERR_SUCCESS) {
printf("[socketid-%d]recv data success, len = %d\n", pWchnetSocketConfiguration->socketId, tempLen);
return tempLen;
} else {
mStopIfError(res);
return -1;
}
}
/**
* @brief 启动wchnet主任务线程,监听以太网中断
* @param adapter
* @return int 0表示线程启动成功,其他表示线程启动失败
*/
static int wchnetEthernetSetUp(struct Adapter *adapter) {
pthread_attr_t wchnetMainTaskAttr;
pthread_args_t wchnetMainTaskArgs;
wchnetMainTaskAttr.schedparam.sched_priority = 16; // 线程优先级
wchnetMainTaskAttr.stacksize = 1100; // 线程栈大小
wchnetMainTaskArgs.pthread_name = "wchnetMainTask"; // 线程名字
wchnetMainTaskArgs.arg = &wchnetSocketConfiguration; // 线程参数
int res = PrivTaskCreate(&wchnetSocketConfiguration.wchnetMainThread, &wchnetMainTaskAttr, wchnetMainTask,
&wchnetMainTaskArgs);
PrivTaskStartup(&wchnetSocketConfiguration.wchnetMainThread);
adapter->adapter_param = &wchnetSocketConfiguration;
return res;
}
/**
* @brief 关闭以太网socket连接
* @param adapter
* @return int 0表示关闭以太网socket连接成功,其他表示关闭以太网socket连接失败
*/
static int wchnetEthernetDisconnect(struct Adapter *adapter) {
struct WchnetSocketConfiguration *pWchnetSocketConfiguration =
(struct WchnetSocketConfiguration *)adapter->adapter_param;
/* 判断是否可以关闭socket */
if (pWchnetSocketConfiguration->wchnetMainThread == 0) { // 判断是否已启动wchnet主任务线程
printf("[error %s %d]wchnetMainThread has not been started, please call function AdapterDeviceSetUp first\n",
__func__, __LINE__);
return -1;
} else if (pWchnetSocketConfiguration->socketStatus !=
WCHNET_SOCKET_CONNECT_SUCCESS) { // 判断当前是否已有socket连接
return WCHNET_ERR_SUCCESS;
}
/* 将目的IP地址和端口号的数组形式转换成字符串形式和unsigned short形式 */
char destinationIpAddress[16]; // 目的IP地址
uint16_t destinationPort; // 目的端口号
sprintf(destinationIpAddress, "%u.%u.%u.%u", pWchnetSocketConfiguration->destinationIpAddress[0],
pWchnetSocketConfiguration->destinationIpAddress[1], pWchnetSocketConfiguration->destinationIpAddress[2],
pWchnetSocketConfiguration->destinationIpAddress[3]);
destinationPort =
(pWchnetSocketConfiguration->destinationPort[1] << 8) + pWchnetSocketConfiguration->destinationPort[0];
/* 关闭socket连接 */
uint8_t res = WCHNET_SocketClose(pWchnetSocketConfiguration->socketId, TCP_CLOSE_NORMAL);
if (res == WCHNET_ERR_SUCCESS) {
while (pWchnetSocketConfiguration->socketStatus == WCHNET_SOCKET_CONNECT_SUCCESS) {
PrivTaskDelay(100); // 每100ms检查一次是否socket关闭完成
}
/* socket关闭完成 */
pWchnetSocketConfiguration->socketStatus = WCHNET_SOCKET_UNDEFINED;
printf("[socketid-%d]socket with %s:%hu has been disconnected\n", pWchnetSocketConfiguration->socketId,
destinationIpAddress, destinationPort);
return WCHNET_ERR_SUCCESS;
} else {
mStopIfError(res);
printf("[socketid-%d]socket with %s:%hu disconnect error\n", pWchnetSocketConfiguration->socketId,
destinationIpAddress, destinationPort);
return res;
}
}
/**
* @brief 建立以太网socket连接
* @param adapter
* @param net_role 网络角色,CLIENT或者SERVER
* @param ip 目的IP地址字符串
* @param port 目的端口号字符串
* @param ip_type IP类型,IPV4或者IPV6
* @return int 0表示建立以太网socket连接成功,其他表示建立以太网socket连接失败
*/
static int wchnetEthernetConnect(struct Adapter *adapter, enum NetRoleType net_role, const char *ip, const char *port,
enum IpType ip_type) {
struct WchnetSocketConfiguration *pWchnetSocketConfiguration =
(struct WchnetSocketConfiguration *)adapter->adapter_param;
/* 由于ch32v208内存限制,当前仅支持IPV4+CLIENT */
if (ip_type != IPV4) {
printf("[error %s %d]wchnetEthernetConnect only support IPV4, do not support IPV6\n", __func__, __LINE__);
return -1;
} else if (net_role != CLIENT) {
printf("[error %s %d]wchnetEthernetConnect only support CLIENT, do not support SERVER\n", __func__, __LINE__);
return -1;
}
/* 将IP地址和端口号的字符串形式转换成数组形式 */
uint8_t destinationIpAddress[4];
uint8_t destinationPort[2];
WCHNET_Aton(ip, destinationIpAddress);
destinationPort[0] = atoi(port) % 256;
destinationPort[1] = atoi(port) / 256;
uint8_t res = WCHNET_ERR_SUCCESS;
if (pWchnetSocketConfiguration->wchnetMainThread == 0) { // 判断是否已启动wchnet主任务线程
printf("[error %s %d]wchnetMainThread has not been started, please call function AdapterDeviceSetUp first\n",
__func__, __LINE__);
return -1;
} else if (pWchnetSocketConfiguration->socketStatus ==
WCHNET_SOCKET_CONNECT_SUCCESS) { // 判断当前是否已有socket连接
if (memcmp(destinationIpAddress, pWchnetSocketConfiguration->destinationIpAddress, 4) == 0 &&
memcmp(destinationPort, pWchnetSocketConfiguration->destinationPort, 2) ==
0) { // 当前连接的socket,目的IP地址和端口号完全一致,无需再次连接
return WCHNET_ERR_SUCCESS;
} else { // 当前连接的socket,目的IP地址和端口号不完全一致,由于ch32v208内存限制,当前仅支持单个socket通信,需断开当前连接
res = wchnetEthernetDisconnect(adapter);
if (res != WCHNET_ERR_SUCCESS) {
mStopIfError(res);
printf("[error %s %d]wchnetEthernetDisconnect fail\n", __func__, __LINE__);
return res;
}
}
}
/* 保存目的IP地址和目的端口号 */
memcpy(pWchnetSocketConfiguration->destinationIpAddress, destinationIpAddress, 4);
memcpy(pWchnetSocketConfiguration->destinationPort, destinationPort, 2);
pWchnetSocketConfiguration->socketStatus = WCHNET_SOCKET_UNDEFINED;
/* 配置socket会话 */
SOCK_INF TmpSocketInf;
memset((void *)&TmpSocketInf, 0, sizeof(SOCK_INF));
memcpy(TmpSocketInf.IPAddr, destinationIpAddress, 4);
TmpSocketInf.SourPort =
(pWchnetSocketConfiguration->sourcePort[1] << 8) + pWchnetSocketConfiguration->sourcePort[0]; // 源端口号
TmpSocketInf.DesPort = (pWchnetSocketConfiguration->destinationPort[1] << 8) +
pWchnetSocketConfiguration->destinationPort[0]; // 目的端口号
TmpSocketInf.ProtoType = PROTO_TYPE_TCP; // 协议类型,TCP
TmpSocketInf.RecvBufLen = RECE_BUF_LEN; // 接收缓冲区大小
/* 创建socket */
res = WCHNET_SocketCreat(&pWchnetSocketConfiguration->socketId, &TmpSocketInf);
if (res == WCHNET_ERR_SUCCESS) {
printf("[socketid-%d]create socketId %d\r\n", pWchnetSocketConfiguration->socketId,
pWchnetSocketConfiguration->socketId);
} else {
mStopIfError(res);
printf("[error %s %d]WCHNET_SocketCreat fail\n", __func__, __LINE__);
return res;
}
/* 连接socket */
res = WCHNET_SocketConnect(pWchnetSocketConfiguration->socketId);
if (res == WCHNET_ERR_SUCCESS) {
printf("[socketid-%d]connecting socketId %d\r\n", pWchnetSocketConfiguration->socketId,
pWchnetSocketConfiguration->socketId);
} else {
mStopIfError(res);
printf("[error %s %d]WCHNET_SocketConnect fail\n", __func__, __LINE__);
return res;
}
/* 每100ms查询一次,直至连接成功或者超时 */
while (pWchnetSocketConfiguration->socketStatus == WCHNET_SOCKET_UNDEFINED) {
printf("[socketid-%d]connecting socketId %d\r\n", pWchnetSocketConfiguration->socketId,
pWchnetSocketConfiguration->socketId);
PrivTaskDelay(1000);
}
if (pWchnetSocketConfiguration->socketStatus == WCHNET_SOCKET_CONNECT_SUCCESS) {
printf("[socketid-%d]socket connect success\n", pWchnetSocketConfiguration->socketId);
return res;
} else if (pWchnetSocketConfiguration->socketStatus == WCHNET_SOCKET_CONNECT_TIMEOUT) {
printf("[socketid-%d]socket connect timeout\n", pWchnetSocketConfiguration->socketId);
return -1;
}
}
/**
* @brief 设置以太网源IP地址,网关地址,子网掩码
* @param adapter
* @param ip 源IP地址
* @param gateway 网关地址
* @param netmask 子网掩码
* @return int 0表示设置成功,其他表示设置失败
*/
static int wchnetEthernetSetAddr(struct Adapter *adapter, const char *ip, const char *gateway, const char *netmask) {
struct WchnetSocketConfiguration *pWchnetSocketConfiguration =
(struct WchnetSocketConfiguration *)adapter->adapter_param;
/* 判断是否已启动wchnet主任务线程 */
if (pWchnetSocketConfiguration->wchnetMainThread == 0) {
printf("[error %s %d]wchnetMainThread has not been started, please call function AdapterDeviceSetUp first\n",
__func__, __LINE__);
return -1;
}
/* 将地址的字符串形式转化为数组形式 */
uint8_t sourceIpAddress[4], sourceGateway[4], sourceSubnetMask[4];
WCHNET_Aton(ip, sourceIpAddress);
WCHNET_Aton(gateway, sourceGateway);
WCHNET_Aton(netmask, sourceSubnetMask);
/* 若配置内容和当前配置保持一致,则无需配置 */
if (memcmp(sourceIpAddress, pWchnetSocketConfiguration->sourceIpAddress, 4) == 0 &&
memcmp(sourceGateway, pWchnetSocketConfiguration->sourceGateway, 4) == 0 &&
memcmp(sourceSubnetMask, pWchnetSocketConfiguration->sourceSubnetMask, 4) == 0) {
return WCHNET_ERR_SUCCESS;
}
/* 若当前有socket正在连接,则需断开socket,再使用新的配置连接socket */
uint8_t socketExists = pWchnetSocketConfiguration->socketStatus == WCHNET_SOCKET_CONNECT_SUCCESS;
if (socketExists) {
wchnetEthernetDisconnect(adapter);
}
/* 进行配置,并重新初始化wchnet */
memcpy(pWchnetSocketConfiguration->sourceIpAddress, sourceIpAddress, 4);
memcpy(pWchnetSocketConfiguration->sourceGateway, sourceGateway, 4);
memcpy(pWchnetSocketConfiguration->sourceSubnetMask, sourceSubnetMask, 4);
uint8_t res = WCHNET_Init(pWchnetSocketConfiguration->sourceIpAddress, pWchnetSocketConfiguration->sourceGateway,
pWchnetSocketConfiguration->sourceSubnetMask, pWchnetSocketConfiguration->macAddress);
if (res == WCHNET_ERR_SUCCESS) { // 初始化wchnet成功
pWchnetSocketConfiguration->dhcpSwitch = 0;
pWchnetSocketConfiguration->dhcpStatus = WCHNET_DHCP_UNDEFINED;
printf("-*-*-*wchnetEthernetSetAddr*-*-*\n");
printf("ip:\t%s\ngateway:%s\nnetmask:%s\n", ip, gateway, netmask);
printf("-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*\n");
if (socketExists) { // 若之前有socket正在连接,则需重新连接
char destinationIpAddress[16], destinationPort[6];
sprintf(destinationIpAddress, "%u.%u.%u.%u", pWchnetSocketConfiguration->destinationIpAddress[0],
pWchnetSocketConfiguration->destinationIpAddress[1],
pWchnetSocketConfiguration->destinationIpAddress[2],
pWchnetSocketConfiguration->destinationIpAddress[3]);
sprintf(
destinationPort, "%hu",
(pWchnetSocketConfiguration->destinationPort[1] << 8) + pWchnetSocketConfiguration->destinationPort[0]);
res = wchnetEthernetConnect(adapter, CLIENT, destinationIpAddress, destinationPort, IPV4);
}
}
mStopIfError(res);
return res;
}
/**
* @brief 删除wchnet主任务线程
* @param adapter
* @return int 0表示删除wchnet主任务线程成功,其他表示删除wchnet主任务线程失败
*/
static int wchnetEthernetSetDown(struct Adapter *adapter) {
struct WchnetSocketConfiguration *pWchnetSocketConfiguration =
(struct WchnetSocketConfiguration *)adapter->adapter_param;
/* 如果wchnet主任务线程已经处于关闭状态 */
if (pWchnetSocketConfiguration->wchnetMainThread == 0) {
return WCHNET_ERR_SUCCESS;
}
uint8_t res = WCHNET_ERR_SUCCESS;
/* 如果仍有socket未关闭,先关闭socket */
if (pWchnetSocketConfiguration->socketStatus == WCHNET_SOCKET_CONNECT_SUCCESS) {
res = wchnetEthernetDisconnect(adapter);
if (res != WCHNET_ERR_SUCCESS) {
return res;
}
}
/* 删除wchnet主任务线程 */
res = PrivTaskDelete(pWchnetSocketConfiguration->wchnetMainThread, 0);
if (res != 0) {
printf("wchnet ethernet set down fail\n");
} else {
pWchnetSocketConfiguration->wchnetMainThread = 0;
printf("wchnet ethernet set down success\n");
}
return res;
}
/**
* @brief 设置DHCP
* @param adapter
* @param enable 0表示关闭DHCP1表示打开DHCP
* @return int 0表示设置成功,其他表示设置失败
* @note 若获得新的动态IP地址,则关闭当前的所有socket连接,并使用新的IP地址建立连接
* @note 若获得的动态IP地址和当前的IP地址一致,则不进行任何操作,继续使用旧的IP地址进行通信
* @note 若获取动态IP地址失败,则继续使用旧的IP地址进行通信
*/
static int wchnetEthernetSetDHCP(struct Adapter *adapter, int enable) {
struct WchnetSocketConfiguration *pWchnetSocketConfiguration =
(struct WchnetSocketConfiguration *)adapter->adapter_param;
if (pWchnetSocketConfiguration->wchnetMainThread == 0) { // 判断是否已启动wchnet主任务线程
printf("[error %s %d]wchnetMainThread has not been started, please call function AdapterDeviceSetUp first\n",
__func__, __LINE__);
return -1;
}
uint8_t res;
switch (enable) {
/* 关闭DHCP */
case 0:
/* 如果原来就没有打开DHCP,无需关闭DHCP */
if (pWchnetSocketConfiguration->dhcpSwitch == 0) {
return WCHNET_ERR_SUCCESS;
}
/* 重新使用静态IP地址初始化,相当于关闭DHCP */
res = WCHNET_Init(pWchnetSocketConfiguration->sourceIpAddress, pWchnetSocketConfiguration->sourceGateway,
pWchnetSocketConfiguration->sourceSubnetMask, pWchnetSocketConfiguration->macAddress);
if (res != WCHNET_ERR_SUCCESS) { // DHCP关闭失败
mStopIfError(res);
} else { // DHCP关闭成功
pWchnetSocketConfiguration->dhcpSwitch = 0;
pWchnetSocketConfiguration->dhcpStatus = WCHNET_DHCP_UNDEFINED;
}
return res;
break;
/* 打开DHCP */
case 1:
/* 如果原来已经打开DHCP */
if (pWchnetSocketConfiguration->dhcpSwitch == 1 &&
(pWchnetSocketConfiguration->dhcpStatus == WCHNET_DHCP_SUCCESS_NEW ||
pWchnetSocketConfiguration->dhcpStatus == WCHNET_DHCP_SUCCESS_OLD)) {
return WCHNET_ERR_SUCCESS;
}
/* 配置DHCP主机名 */
res = WCHNET_DHCPSetHostname("WCHNET");
if (res == WCHNET_ERR_SUCCESS) {
printf("DHCP hostname set success\n");
} else {
mStopIfError(res);
printf("[error %s %d]WCHNET_DHCPSetHostname fail\n", __func__, __LINE__);
}
/* 开启DHCP */
res = WCHNET_DHCPStart(WCHNET_DHCPCallBack);
if (res == WCHNET_ERR_SUCCESS) {
pWchnetSocketConfiguration->dhcpStatus = WCHNET_DHCP_UNDEFINED;
while (pWchnetSocketConfiguration->dhcpStatus == WCHNET_DHCP_UNDEFINED) {
PrivTaskDelay(1000); // 每秒查询一次DHCP状态
printf("DHCP finding IP\n");
}
WCHNET_DHCPStop(); // 停止DHCP
switch (pWchnetSocketConfiguration->dhcpStatus) {
case WCHNET_DHCP_SUCCESS_NEW: // 获取到新的动态IP地址,若之前连接过socket,则重新连接该socket
pWchnetSocketConfiguration->dhcpSwitch = 1;
printf("DHCP set up successfully, getting new IP configuration\n");
if (pWchnetSocketConfiguration->socketStatus == WCHNET_SOCKET_CONNECT_SUCCESS) {
char destinationIpAddress[16];
char destinationPort[6];
sprintf(destinationIpAddress, "%u.%u.%u.%u",
pWchnetSocketConfiguration->destinationIpAddress[0],
pWchnetSocketConfiguration->destinationIpAddress[1],
pWchnetSocketConfiguration->destinationIpAddress[2],
pWchnetSocketConfiguration->destinationIpAddress[3]);
sprintf(destinationPort, "%hu",
(pWchnetSocketConfiguration->destinationPort[1] << 8) +
pWchnetSocketConfiguration->destinationPort[0]);
if (!wchnetEthernetDisconnect(adapter) &&
!wchnetEthernetConnect(adapter, CLIENT, destinationIpAddress, destinationPort, IPV4)) {
printf("[socketid-%d]DHCP: socket with %s:%s has been reset\n",
pWchnetSocketConfiguration->socketId, destinationIpAddress, destinationPort);
} else {
printf("[socketid-%d]DHCP: socket with %s:%s reset failed\n",
pWchnetSocketConfiguration->socketId, pWchnetSocketConfiguration->socketId,
destinationIpAddress, destinationPort);
}
}
return WCHNET_ERR_SUCCESS;
break;
case WCHNET_DHCP_SUCCESS_OLD: // 获取到旧的动态IP地址
pWchnetSocketConfiguration->dhcpSwitch = 1;
printf("DHCP set up successfully, getting the same IP configuration\n");
return WCHNET_ERR_SUCCESS;
break;
case WCHNET_DHCP_FAIL: // 获取动态IP地址错误
pWchnetSocketConfiguration->dhcpSwitch = 0;
printf("[error %s %d]wchnet dhcp fail\n", __func__, __LINE__);
return -1;
}
} else {
mStopIfError(res);
return res;
}
break;
}
}
static const struct IpProtocolDone wchnet_ethernet_done = {
.open = NULL,
.close = NULL,
.ioctl = NULL,
.setup = wchnetEthernetSetUp,
.setdown = wchnetEthernetSetDown,
.setaddr = wchnetEthernetSetAddr,
.setdns = NULL,
.setdhcp = wchnetEthernetSetDHCP,
.ping = NULL,
.netstat = NULL,
.connect = wchnetEthernetConnect,
.send = wchnetEthernetSend,
.recv = wchnetEthernetReceive,
.disconnect = wchnetEthernetDisconnect,
};
/**
* @description: Register ethernet device wchnet
* @return success: product_info, failure: NULL
*/
AdapterProductInfoType wchnetEthernetAttach(struct Adapter *adapter) {
struct AdapterProductInfo *product_info = PrivMalloc(sizeof(struct AdapterProductInfo));
if (!product_info) {
printf("wchnetEthernetAttach Attach malloc product_info error\n");
PrivFree(product_info);
return NULL;
}
strcpy(product_info->model_name, ADAPTER_ETHERNET_WCHNET);
product_info->model_done = (void *)&wchnet_ethernet_done;
return product_info;
}