Skip to content

Termination requirement of setPoolServerName() parameter #217

Open
@SnowyDogEngland

Description

@SnowyDogEngland

setPoolServerName() does not accept output from function c_str() as a parameter.

I believe this is because, unlike functions in other related libraries (such as ESP8266WiFi's begin()), NTPClient's setPoolServerName() does not delimit the char array and the null terminator is (perhaps incorrectly) being processed as part of the parameter.

In the following example, I read the desired NTP server name from a file as a String using f.readStringUntil() which returns a String of characters up to but not including delimiter '\n' (0xA), and pass it to setPoolServerName() via c_str(). This does not work (NTPClient fails to set the correct pool server name).

  //-----------------------------------------------------------
  // DOES NOT WORK!
  // Create string to hold NTP server name
  const String sNtpUrl=cfgFile.readStringUntil('\n');

  // Set NTP server pool URL, using String
  timeClient.setPoolServerName(sNtpUrl.c_str());
  Serial.print("NTP URL: ");
  Serial.println(sNtpUrl);
  Serial.print("Length of NTP URL String: ");
  Serial.println(sNtpUrl.length(),DEC);

In the following example, I read the same NTP server name from a file a char at a time into a char array which I then pass to setPoolServerName() and this works fine.

  //-----------------------------------------------------------
  // DOES WORK!  
  // Get NTP server pool URL (as char array) from file
  int i=0;
  char cNtpUrl[20]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
  for (i=0; i < 20; i++) {
    char data=cfgFile.read();
    // Check for delimiter
    if (data==0x0A) {
      break;
    }
    // Check if EoF found
    if (data==-1) {
      Serial.println("Error: EoF found. System HALT!");
      ESP.deepSleep(0);      
    }
    // Write character to array
    cNtpUrl[i]=data;
  }

  // Set NTP server pool URL, using char array
  timeClient.setPoolServerName(cNtpUrl);
  Serial.print("NTP URL: ");
  Serial.println(cNtpUrl);
  Serial.print("Number of chars in array: ");
  Serial.println(i,DEC);

In both examples, the file contains 'time.windows.com' and both examples correctly return a size of 16 characters (the String.length() of course does not count the null terminator).

Metadata

Metadata

Assignees

No one assigned

    Labels

    topic: codeRelated to content of the project itselftype: imperfectionPerceived defect in any part of project

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions