ESP8266 WIFI事件處理
之前用ESP8266判讀wifi狀態使用定時器回調調用wifi_station_get_connect_status()獲取。這種不方便及時處理某些事情,比如WIFI斷開。
現在使用
wifi_set_event_handler_cb(wifi_handle_event_cb);
註冊wifi事件處理函數,這裏面進行WIFI狀態改變的一些操作。
比如在EVENT_STAMODE_GOT_IP裏進行MQTT連接。
在EVENT_STAMODE_DISCONNECTED裏進行切換WIFI。
void wifi_handle_event_cb(System_Event_t *evt)
{
//os_printf("event %x\n", evt->event);
switch (evt->event) {
case EVENT_STAMODE_CONNECTED:
os_printf("connect to ssid %s, channel %d\n",
evt->event_info.connected.ssid,
evt->event_info.connected.channel);
break;
case EVENT_STAMODE_DISCONNECTED:
os_printf("disconnect from ssid %s, reason %d\n",
evt->event_info.disconnected.ssid,
evt->event_info.disconnected.reason);
break;
case EVENT_STAMODE_AUTHMODE_CHANGE:
os_printf("mode: %d -> %d\n",
evt->event_info.auth_change.old_mode,
evt->event_info.auth_change.new_mode);
break;
case EVENT_STAMODE_GOT_IP: //WIFI連接成功,
os_printf("ip:" IPSTR ",mask:" IPSTR ",gw:" IPSTR,
IP2STR(&evt->event_info.got_ip.ip),
IP2STR(&evt->event_info.got_ip.mask),
IP2STR(&evt->event_info.got_ip.gw));
INFO("MQTT:start connect mqtt...\r\n");
update_verify(); //WiFi連接成功更新證書
MQTT_Connect(&mqttClient);
creat_web_servser(); //建立TCP偵聽
creat_root_server(); //創建設備服務端,一個店裏的設備全部連到這裏,通過無線通訊控制店內設備
os_printf("\n");
break;
case EVENT_SOFTAPMODE_STACONNECTED:
os_printf("station: " MACSTR "join, AID = %d\n",
MAC2STR(evt->event_info.sta_connected.mac),
evt->event_info.sta_connected.aid);
break;
case EVENT_SOFTAPMODE_STADISCONNECTED:
os_printf("station: " MACSTR "leave, AID = %d\n",
MAC2STR(evt->event_info.sta_disconnected.mac),
evt->event_info.sta_disconnected.aid);
break;
default:
break;
}
}
附上原來處理WIFI狀態的方法:
/*連接WiFi*/
void ICACHE_FLASH_ATTR
wifi_connect()
{
os_timer_disarm(&wifi_connect_timer);
wifi_state = wifi_station_get_connect_status();
INFO("wifi_state = %d \r\n",wifi_state);
if(wifi_state == STATION_GOT_IP)
{
INFO("WIFI CONNECTED!\r\n");
update_verify(); //WiFi連接成功更新證書
MQTT_Connect(&mqttClient);
creat_web_servser(); //建立TCP偵聽
creat_root_server(); //創建設備服務端,一個店裏的設備全部連到這裏,通過無線通訊控制店內設備
return;
}
os_timer_arm(&wifi_connect_timer,2000,0);
}
void ICACHE_FLASH_ATTR
WIFI_CONNECT()
{
wifi_set_opmode(STATIONAP_MODE); //設置模式
wifi_station_set(NORMAL); //配置wifi,station和softap信息
wifi_station_connect();
os_timer_setfn(&wifi_connect_timer,wifi_connect,NULL); //開始連接wifi
os_timer_arm(&wifi_connect_timer,1000,0);
}