This commit is contained in:
2021-02-28 12:51:58 +01:00
parent 7154b0abc3
commit 7addea50a3

View File

@ -17,10 +17,19 @@ static uint8_t sntpBuffer[MAX_SNTP_BUF_SIZE];
static const uint64_t UNIX_NTP_EPOCH_DIFF = 2208988800; static const uint64_t UNIX_NTP_EPOCH_DIFF = 2208988800;
extern const uint8_t SNTP_SOCK; extern const uint8_t SNTP_SOCK;
static uint64_t seconds; static uint64_t seconds;
static enum {
SNTP_STATE_IDLE,
SNTP_STATE_SEND,
SNTP_STATE_DONE,
SNTP_STATE_ERROR
} sntpState = SNTP_STATE_IDLE;
void networkSntpEngine(void *handle) { void networkSntpEngine(void *handle) {
if (isNetworkAvailable()) { if (isNetworkAvailable()) {
coloredMsg(LOG_BLUE, "wizsq, about to call SNTP"); switch (sntpState) {
case SNTP_STATE_SEND:
coloredMsg(LOG_BLUE, "nes, about to call SNTP");
uint8_t ntpServer[4]; uint8_t ntpServer[4];
if (wizDnsQuery(config->ntpServer, ntpServer)) { if (wizDnsQuery(config->ntpServer, ntpServer)) {
@ -32,24 +41,42 @@ void networkSntpEngine(void *handle) {
datetime curTime; datetime curTime;
if (1 == SNTP_run(&curTime)) { if (1 == SNTP_run(&curTime)) {
seconds = curTime.seconds - UNIX_NTP_EPOCH_DIFF; seconds = curTime.seconds - UNIX_NTP_EPOCH_DIFF;
coloredMsg(LOG_BLUE, "wizsq, cycles: %u, curTime: %lu", cycles, seconds); coloredMsg(LOG_BLUE, "nes, cycles: %u, curTime: %lu", cycles, seconds);
uint32_t stopTime = HAL_GetTick(); uint32_t stopTime = HAL_GetTick();
coloredMsg(LOG_BLUE, "wizsq, duration: %u ms", stopTime - startTime); coloredMsg(LOG_BLUE, "nes, duration: %u ms", stopTime - startTime);
sntpState = SNTP_STATE_DONE;
break; break;
} }
} }
if (seconds == 0) { if (seconds == 0) {
coloredMsg(LOG_BLUE, "wizsq, time update failed"); coloredMsg(LOG_BLUE, "nes, time update failed");
sntpState = SNTP_STATE_ERROR;
} }
} else { } else {
coloredMsg(LOG_BLUE, "wizsq, error when querying ntp server name"); coloredMsg(LOG_BLUE, "nes, error when querying ntp server name");
sntpState = SNTP_STATE_ERROR;
}
} }
} }
} }
uint64_t networkSntpQuery() { uint64_t networkSntpQuery() {
networkSntpEngine(NULL); uint64_t res = 0;
if (sntpState == SNTP_STATE_IDLE) {
coloredMsg(LOG_BLUE, "nsq, start sntp request");
sntpState = SNTP_STATE_SEND;
schAdd(networkSntpEngine, NULL, 1, 0);
} else if (sntpState == SNTP_STATE_DONE) {
coloredMsg(LOG_BLUE, "nsq, start sntp done");
res = seconds;
sntpState = SNTP_STATE_IDLE;
} else if (sntpState == SNTP_STATE_ERROR) {
coloredMsg(LOG_BLUE, "nsq, start sntp failed");
sntpState = SNTP_STATE_IDLE;
}
return seconds; return seconds;
} }