ESP8266 WIFI_AP_STA and NTP Clien

I’ve just begun messing around with the ESP8266 so I’m pretty confident I’m missing something obvious, but whenever I try to configure the ESP as both a station and an Access Point I can no longer get valid responses from an NTP server.

Through testing I’ve found that the problem is these two lines:

  // Turn on local Access Point
  WiFi.softAPConfig(ip,gateway,subnet);
  WiFi.softAP(localAPSSID, tempPass, apChannel);

The ip and gateway are the same address and are well outside the IP address range assigned to the ESP when it connects in station mode to my home’s access point.

My guess is that when I sent the udp packet to get a response from the NTP server, it’s looking to itself (as the gateway) and failing rather than looking to the access point it is connected to in station mode. Is there a way I can specify the route to use?

I’ve confirmed that I get a valid IP address when I do “WiFi.hostByName(ntpServerName, timeServerIP);” I just never get the packet back for some reason.

Here is the full code (and apologies in advance, I know its rough, I’ve been copy/pasting to track down my point of failure and haven’t had a chance to clean up):

#include <Wire.h>
#include <RtcDS3231.h>
//#include <TimeLib.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>

// Only needed if storing SSID and Password to EEPROM
#include <EEPROM.h>
#include "mbFunctions.h"
RtcDS3231<TwoWire> Rtc(Wire);
ESP8266WebServer server;

//char ssid[] = "";  //  your network SSID (name)
//char pass[] = "";       // your network password


unsigned int localPort = 2390;      // local port to listen for UDP packets

/* Don't hardwire the IP address or we won't get the benefits of the pool.
 *  Lookup the IP address for the host name instead */
//IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server
IPAddress timeServerIP; // time.nist.gov NTP server address
const char* ntpServerName = "north-america.pool.ntp.org";

const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message

byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets

// A UDP instance to let us send and receive packets over UDP
WiFiUDP udp;

// Set a static ip address for the Access point mode
// This can be used to directly connect to it instead of having to have a local network
IPAddress ip(192,16,1,1);
IPAddress gateway(192,16,1,1);
IPAddress subnet(255,255,255,0);
int apChannel = 11;

void setup()
{
  Serial.begin(115200);
  Serial.println();
  Serial.println();

  ////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////
  //  This section only needed if storing SSID and Password to EEPROM   //
  //  Delete or comment out if unneded                                  //
  ////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////

  EEPROM.begin(512);

  // Uncomment the following line to empty EEPROM Values
  //clearEeprom();
  
  // Only need to call the writeEeprom when updating SSID or Password
  //writeEeprom(ssid, password);

  // Read SSID and password from EEPROM
  String setupArray[2];
  readEeprom(&setupArray[0]);

  // Convert Strings to Char Array
  char tempSsid[setupArray[0].length()+1];
  char tempPass[setupArray[1].length()+1];

  setupArray[0].toCharArray(tempSsid,setupArray[0].length()+1);
  setupArray[1].toCharArray(tempPass,setupArray[1].length()+1);

  // Diag Delete when working
  Serial.println(tempSsid);
  Serial.println(tempPass);

  // Local Access point SSID is setup to be the same as the SSID of the network you connect to
  // with the number "2" at the end of it.  
  
  //If not storing data to EEPROM this part will need to be changed
  char localAPSSID[setupArray[0].length()+2];
  strcpy(localAPSSID, tempSsid);
  strcat(localAPSSID, "2");
  
  EEPROM.end();
  
  ////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////
  //  End of EEPROM section                                             //
  ////////////////////////////////////////////////////////////////////////
  ////////////////////////////////////////////////////////////////////////

  // We start by connecting to a WiFi network
  Serial.print("Connecting to ");
  Serial.println(tempSsid);
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(tempSsid,tempPass);
  
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  Serial.println("Starting UDP");
  udp.begin(localPort);
  Serial.print("Local port: ");
  Serial.println(udp.localPort());

    // Diag Needs to be replaced with real code
  server.on("/",[](){server.send(200,"text/plain","Hello World!");});
  server.begin();

  // Turn on local Access Point
  WiFi.softAPConfig(ip,gateway,subnet);
  WiFi.softAP(localAPSSID, tempPass, apChannel);  
}

void loop()
{
  //get a random server from the pool
  WiFi.hostByName(ntpServerName, timeServerIP); 

  sendNTPpacket(timeServerIP); // send an NTP packet to a time server
  // wait to see if a reply is available
  delay(1000);
  
  int cb = udp.parsePacket();
  if (!cb) {
    Serial.println("no packet yet");
  }
  else {
    Serial.print("packet received, length=");
    Serial.println(cb);
    // We've received a packet, read the data from it
    udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer

    //the timestamp starts at byte 40 of the received packet and is four bytes,
    // or two words, long. First, esxtract the two words:

    unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
    unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
    // combine the four bytes (two words) into a long integer
    // this is NTP time (seconds since Jan 1 1900):
    unsigned long secsSince1900 = highWord << 16 | lowWord;
    Serial.print("Seconds since Jan 1 1900 = " );
    Serial.println(secsSince1900);

    // now convert NTP time into everyday time:
    Serial.print("Unix time = ");
    // Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
    const unsigned long seventyYears = 2208988800UL;
    // subtract seventy years:
    unsigned long epoch = secsSince1900 - seventyYears;
    // print Unix time:
    Serial.println(epoch);


    // print the hour, minute and second:
    Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
    Serial.print((epoch  % 86400L) / 3600); // print the hour (86400 equals secs per day)
    Serial.print(':');
    if ( ((epoch % 3600) / 60) < 10 ) {
      // In the first 10 minutes of each hour, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.print((epoch  % 3600) / 60); // print the minute (3600 equals secs per minute)
    Serial.print(':');
    if ( (epoch % 60) < 10 ) {
      // In the first 10 seconds of each minute, we'll want a leading '0'
      Serial.print('0');
    }
    Serial.println(epoch % 60); // print the second
  }
  // wait ten seconds before asking for the time again
  delay(10000);
}

// send an NTP request to the time server at the given address
void sendNTPpacket(IPAddress& address)
{
  Serial.println("sending NTP packet...");
  // set all bytes in the buffer to 0
  memset(packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  // (see URL above for details on the packets)
  packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  packetBuffer[1] = 0;     // Stratum, or type of clock
  packetBuffer[2] = 6;     // Polling Interval
  packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
  packetBuffer[12]  = 49;
  packetBuffer[13]  = 0x4E;
  packetBuffer[14]  = 49;
  packetBuffer[15]  = 52;

  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
  udp.beginPacket(address, 123); //NTP requests are to port 123
  udp.write(packetBuffer, NTP_PACKET_SIZE);
  udp.endPacket();
}

Finally tacked down what was wrong. As pointed out in a comment over here when operating in both station mode and as an access point, then the channel you give the ESP's AP will be overridden by the channel of the access point you are connected to in station mode. When this happens, the ESP's AP will reset causing networking problems.

The immediate fix was for me to hard code the channel to match my home's AP channel. For a more long term goal, I'll look into reading the channel from the connected AP and assigning to the ESP's channel. Another possibility is WiFimulti library. I'm not sure if it can really fix it, but I'll have to check it out.

I compiled and ran your sketch, with a few unrelated sections removed and it seems to work but, it seems this is because your softAP is not starting at all.

You are not checking to see if the softAP is actually operational and once it is, your NTP fetches are failing. This echos my own experience and failures to get NTP working with the ESP8266 as a client and a softAP.

When the client connects to the router, NTP fetches are fine but once the softAP is started, NTP fetches fail 100% of the time.

Have you had any more success with this project?

Sorry, I haven't taken a look at this project since shortly after writing the above post. I do remember at the time that it 100% worked after I hard coded the client's AP channel to match the channel of the AP it was connecting to.

Did you check out the second post I made in this thread and the thread it links to? It explains why the softAP starting causes the client to fail on NTP fetches. As well as how to bypass that issue in the sort term.