pycom / pycom-micropython-sigfox

A fork of MicroPython with the ESP32 port customized to run on Pycom's IoT multi-network modules.
MIT License
199 stars 167 forks source link

RTC ntp time server not working using DNS on static ip #9

Closed PiAir closed 6 years ago

PiAir commented 7 years ago

When using a static IP address (instead of DHCP), the ntp_sync() doesn't work when using the FQDN 'pool.ntp.org' although it does work when DHCP is used or when an IP-address is used.

>>> import os
>>> os.uname()
(sysname='LoPy', nodename='LoPy', release='1.6.13.b1', version='v1.8.6-607-g9c8a0e9e on 2017-05-01', machine='LoPy with ESP32', lorawan='1.0.0')
>>> wlan.ifconfig()
('192.168.0.191', '255.255.255.0', '192.168.0.1', '213.46.228.196')
>>> import machine
>>> rtc = machine.RTC()
>>> rtc.ntp_sync('pool.ntp.org', 3600)
>>> rtc.now()
(1970, 1, 1, 0, 2, 21, 96633, None)
>>> rtc.ntp_sync('128.199.44.119', 3600)
>>> rtc.now()
(2017, 5, 16, 6, 3, 44, 126771, None)

Also (I am adding it here in this issue because it might be caused by the same problem), socket.getaddrinfo() often returns '0.0.0.0' while using a static IP-address:

>>> wlan.ifconfig() ('192.168.0.191', '255.255.255.0', '192.168.0.1', '213.46.228.196')
>>> socket.getaddrinfo('pool.ntp.org', 80)
[(2, 1, 0, '', ('0.0.0.0', 80))]
>>> socket.getaddrinfo('pool.ntp.org', 80)
[(2, 1, 0, '', ('122.175.14.128', 80))]
>>> socket.getaddrinfo('pool.ntp.org', 80)
[(2, 1, 0, '', ('16.88.252.63', 80))]
>>> socket.getaddrinfo('pool.ntp.org', 80)
[(2, 1, 0, '', ('0.0.0.0', 80))]
>>> socket.getaddrinfo('pool.ntp.org', 80)
[(2, 1, 0, '', ('0.0.0.0', 80))]
>>> socket.getaddrinfo('pool.ntp.org', 80)
[(2, 1, 0, '', ('0.0.0.0', 80))]
>>> socket.getaddrinfo('pool.ntp.org', 80)
[(2, 1, 0, '', ('80.87.252.63', 80))]
oligauc commented 7 years ago

ntp_sync can return before server synchronization has occurred. You can use the function rtc.synced() to check whether the module has successfully synchronized with the ntp server.

rtc = machine.RTC() rtc.ntp_sync('pool.ntp.org', 3600)

while not rtc.synced(): time.sleep_ms(50)

print(rtc.now())

Regarding the second issue, please can you try using google's dns server 8.8.8.8 and see if it is more consistent ?

gretel commented 6 years ago

this works for me:

class TimeUtil:
 global format_time
 def format_time(t_tuple):
    return '{0}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'.format(*t_tuple)

from machine import RTC
import time
import socket

NTP_HOST='ntp.jitter.eu'

# work around first lookup failing
socket.getaddrinfo(NTP_HOST, 23)
rtc = RTC()

rtc.ntp_sync(NTP_HOST, 86400)

while not rtc.synced():
    time.sleep_ms(100)

print("ntp: synced - " + format_time(rtc.now()))
danspndl commented 6 years ago

I think this issue has been resolved, so I'll close this. If you think otherwise, feel free to reopen it and add more details!