MCPcopy Create free account
hub / github.com/SmingHub/Sming / onReceive

Method onReceive

Sming/Components/Network/src/Network/NtpClient.cpp:121–169  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

119}
120
121void NtpClient::onReceive(pbuf* buf, [[maybe_unused]] IpAddress remoteIP, [[maybe_unused]] uint16_t remotePort)
122{
123 debug_d("NtpClient::onReceive(%s:%u)", remoteIP.toString().c_str(), remotePort);
124
125 stopTimer();
126 auto retry = [this]() { startTimer(NTP_RESPONSE_TIMEOUT_MS); };
127
128 // We do some basic check to see if it really is a ntp packet we receive.
129 // NTP version should be set to same as we used to send, NTP_VERSION
130 // NTP_VERSION 3 has time in same location so accept that too
131 // Mode should be set to NTP_MODE_SERVER
132
133 uint8_t versionMode = pbuf_get_at(buf, 0);
134 uint8_t ver = (versionMode & 0b00111000) >> 3;
135 uint8_t mode = (versionMode & 0x07);
136
137 if(mode != NTP_MODE_SERVER) {
138 // Received response from another client - retry
139 return retry();
140 }
141
142 if(ver != NTP_VERSION && ver != (NTP_VERSION - 1)) {
143 // Received an unsupported version - retry
144 return retry();
145 }
146
147 uint32_t timestamp;
148 pbuf_copy_partial(buf, &timestamp, sizeof(timestamp), 40); // Copy only timestamp.
149 timestamp = ntohl(timestamp);
150
151 if(timestamp == 0) {
152 // Timestamp is not valid
153 return retry();
154 }
155
156 // Unix time starts on Jan 1 1970, subtract 70 years:
157 uint32_t epoch = timestamp - 0x83AA7E80;
158
159 if(autoUpdateSystemClock) {
160 SystemClock.setTime(epoch, eTZ_UTC); // update systemclock utc value
161 }
162
163 if(delegateCompleted) {
164 delegateCompleted(*this, epoch);
165 }
166
167 // If auto query is enabled, schedule the next check
168 setAutoQuery(autoQueryEnabled);
169}

Callers

nothing calls this directly

Calls 3

c_strMethod · 0.45
toStringMethod · 0.45
setTimeMethod · 0.45

Tested by

no test coverage detected