Skip to content

Commit

Permalink
String => char*
Browse files Browse the repository at this point in the history
  • Loading branch information
mathieucarbou committed Sep 14, 2024
1 parent cedbb28 commit bc9d0ad
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 13 deletions.
2 changes: 1 addition & 1 deletion examples/NTP/NTP.ino
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ void setup() {
}

void loop() {
Serial.println(Mycila::NTP.isSynced());
struct tm timeInfo;
if (getLocalTime(&timeInfo))
Serial.println(&timeInfo, "%A, %B %d %Y %H:%M:%S");
Serial.println(Mycila::NTP.isSynced());
delay(1000);
}
29 changes: 19 additions & 10 deletions src/MycilaNTP.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,32 +24,41 @@ extern Mycila::Logger logger;

#define TAG "NTP"

bool Mycila::NTPClass::setTimeZone(const String& timezone) {
if (timezone.isEmpty()) {
bool Mycila::NTPClass::setTimeZone(const char* timezone) {
if (!timezone)
return false;

size_t len = strlen(timezone);
if (len == 0)
return false;
}

char* found = strstr(MYCILA_NTP_SPEC, (timezone + "=").c_str());
char* withEqual = new char[len + 2];
memcpy(withEqual, timezone, len);
withEqual[len] = '=';
withEqual[len + 1] = '\0';

char* found = strstr(MYCILA_NTP_SPEC, withEqual);
delete[] withEqual;

if (found == nullptr) {
LOGE(TAG, "Timezone not found: %s", timezone.c_str());
LOGE(TAG, "Timezone not found: %s", timezone);
return false;
}

const char* start = found + timezone.length() + 1;
const char* start = found + len + 1;
_spec = String(start, static_cast<unsigned int>(strstr(start, "\n") - start));

LOGI(TAG, "Set timezone to %s (%s)", timezone.c_str(), _spec.c_str());
LOGI(TAG, "Set timezone to %s (%s)", timezone, _spec.c_str());

setenv("TZ", _spec.c_str(), 1);
tzset();

return true;
}

bool Mycila::NTPClass::sync(const String& server, const uint8_t retryInterval) {
if (server.isEmpty()) {
bool Mycila::NTPClass::sync(const char* server, const uint8_t retryInterval) {
if (!server || strlen(server) == 0)
return false;
}

_server = server;
_ticker.detach();
Expand Down
4 changes: 2 additions & 2 deletions src/MycilaNTP.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ namespace Mycila {
class NTPClass {
public:
// returns false if timezone invalid
bool setTimeZone(const String& timezone);
bool setTimeZone(const char* timezone);

// ge the timezone information used
const String& getTimezoneInfo() const { return _spec; }

// sync with server
bool sync(const String& server, const uint8_t retryInterval = MYCILA_NTP_RETRY_INTERVAL);
bool sync(const char* server, const uint8_t retryInterval = MYCILA_NTP_RETRY_INTERVAL);

// manually sync
bool sync(const timeval& tv);
Expand Down

0 comments on commit bc9d0ad

Please sign in to comment.