I've been reading this post while trying to optimize the usage of the WiFi module on my ESP8266.
My main goal was to be able to connect/disconnect (respectively turn on/off) the WiFi module so I can optimize electricity consumption of the chip (I am trying to solar power it).
So, the way I integrated the proposed solution is as follows as I am no where calling deepSleep:
#include <RelayModule.h>
#include <ESP8266WIFI.h>
#include <rdm6300.h>
#include <string.h>
#include <ctime>
extern "C" {
#include "user_interface.h" // Required for wifi_station_connect() to work
}
/*...*/
#define RFID_PIN 13
#define RELAY_PIN 10
#define FPM_SLEEP_MAX_TIME 0xFFFFFFF
#define RELAY_OPEN_DURATION 6
RelayModule relay(RELAY_PIN);
Rdm6300 rdm6300;
int relayTurnedOnAt = 0;
void WiFiOn();
void WiFiOff();
void connectToWifi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
}
}
void setup() {
connectToWifi();
rdm6300.begin(RFID_PIN);
/*...*/
}
void openFrontDoor() {
WiFiOn();
if(relay.isOff()){
relay.on();
relayTurnedOnAt = time(0);
}
/*Perform some business logic which makes a reference to Services hosted on the Internet*/
}
void lockFrontDoor() {
relay.off();
WiFiOff();
}
void loop() {
// RFID TAG WAS SCANNED
if (rdm6300.update()){
openFrontDoor();
}
if (relay.isOn() && abs(time(0)-relayTurnedOnAt) > RELAY_OPEN_DURATION)
lockFrontDoor();
}
void WiFiOn() {
wifi_fpm_do_wakeup();
wifi_fpm_close();
//Serial.println("Reconnecting");
wifi_set_opmode(STATION_MODE);
wifi_station_connect();
}
void WiFiOff() {
//Serial.println("diconnecting client and wifi");
//client.disconnect();
wifi_station_disconnect();
wifi_set_opmode(NULL_MODE);
wifi_set_sleep_type(MODEM_SLEEP_T);
wifi_fpm_open();
wifi_fpm_do_sleep(FPM_SLEEP_MAX_TIME);
}
The problem here is that once disconnected, I can not get the WiFi module connected back. I need to reset/restart the chip and then I get connected to the internet once again. I would like to be able to fully disable the module when not needed (and save power) and when I need it to submit some stuff to the internet - wake it up, do the job and then bring it back to suspended mode.
wifi_station_disconnect();
drops you WIFI connection at all. Perhaps you have to performconnectToWifi();
again. But as I don't know theuser_interface.h
, it is just a guess ;-)..