我用小程序给设备蓝牙配网,但是每一次我都要需要进行配网,然后我看AT指令,有一个自动连接指令,但是还是不行,需要每次手动配网?有什么办法可以首次配网成功后,不需要再次进行配网?是我代码逻辑的问题?
void ai_wb2_01s_init(void)
{
int timeout = 0;
char mqtt_cfg[256];
char conn_cmd[128];
char sub_cmd[128];
// int wifi_state = ai_wb2_check_wifi_state();
__HAL_UART_ENABLE_IT(&huart2,UART_IT_RXNE); //打开串口2接收中断
printf("1.SETTING STATION MODE\r\n");
while(ai_wb2_01s_send_cmd((uint8_t *)"AT+CWMODE=1,1\r\n",strlen("AT+CWMODE=1,1\r\n"),"OK")!=0)
{
HAL_Delay(1000);
}
printf("2.CLOSE ai_wb2_01s ECHO\r\n"); //关闭回显的指令,就是串口发送会返回上一个指令并返回OK值,不要这个功能就叫关闭回显指令
while(ai_wb2_01s_send_cmd((uint8_t *)"ATE0\r\n",strlen("ATE0\r\n"),"OK")!=0)
{
HAL_Delay(1000);
}
// 新增的判断WiFi是否联网的代码
{
int check_timeout = 0;
while (1)
{
if (strstr((const char*)receive_buf, "WIFI GOT IP"))
{
// 如果找到 "WIFI GOT IP",说明WiFi已联网
printf("WiFi is already connected.\n");
uart2_receiver_clear(receive_count);
goto MQTT_INIT;
}
if (check_timeout++ > 10)
{
// 如果多次检查都没有找到,认为未联网,进入蓝牙配网
printf("WiFi is not connected, enter BLUFI mode.\n");
uart2_receiver_clear(receive_count);
goto BLUFI_INIT;
}
HAL_Delay(1000);
}
}
BLUFI_INIT:
// 进入蓝牙配网模式(原有逻辑)
printf("Starting BLUFI provisioning...\n");
// 配置蓝牙名称
while(ai_wb2_01s_send_cmd((uint8_t *)"AT+BLUFINAME=\"040\"\r\n",
strlen("AT+BLUFINAME=\"040\"\r\n"), "OK") != 0) {
HAL_Delay(2000);
}
// 开启蓝牙配网
while(ai_wb2_01s_send_cmd((uint8_t *)"AT+BLUFI=1\r\n",
strlen("AT+BLUFI=1\r\n"), "OK") != 0) {
HAL_Delay(1000);
}
printf("Waiting for provisioning...\n");
timeout = 0;
// 等待配网(带超时)
while(1) {
if(strstr((const char*)receive_buf, "WIFI CONNECTED")) {
printf("Provisioning Success! Credentials saved in module.\n");
uart2_receiver_clear(receive_count);
break;
}
if(timeout++ > 120) {
printf("Timeout! Rebooting...\n");
NVIC_SystemReset();
}
HAL_Delay(5000);
}
printf("3. AUTO CONNECT WIFI\r\n"); //需要自动连接wifi
while(ai_wb2_01s_send_cmd((uint8_t *)"AT+CWAUTOCONN=1\r\n",strlen("AT+CWAUTOCONN=1\r\n"),"OK")!=0)
{
HAL_Delay(1000);
}
MQTT_INIT:
// 3. MQTT初始化
printf("Configuring MQTT...\n");
// MQTT用户配置
sprintf(mqtt_cfg, "AT+MQTTUSERCFG=0,1,\"%s\",\"%s\",\"%s\",0,0,\"\"\r\n",
MQTT_CLIENT_ID, MQTT_USER_NAME, MQTT_PASSWD);
while(ai_wb2_01s_send_cmd((uint8_t*)mqtt_cfg, strlen(mqtt_cfg), "OK") != 0) {
HAL_Delay(2000);
}