Hi Guys,
I have my Pico W network date update code working consistently now. It includes a Time Zone offset and ignores day light saving.
I have found that this process can make more sense if you turn off time sync within Thonny. Details are in the main program comments.
I have left my debugging code in. Just set the debug level to zero to disable it. I usually do my debugging this way as it is sometimes useful to turn it back on down the track. There is also a debug to file option when running without a console.
I have included several methods in separate files as they will be useful to include in other programs.
I notice when I execute the program directly on the Pico as main.py, if I inspect the log file (datalog.scv) the initial date is 01/01/2021. I have not see this date mentioned in any discussion posts anywhere.
Even with the Thonny date time settings disabled I still get different result when running within Thonny.
Anyway, the code below is now working and will be useful in my project as will the reusable debugging and date formatting code.
Hope this helps someone else.
main.py
# A simple example that:
# - Connects to a WiFi Network defined by "ssid" and "password" in secrets.py
# - Sets the system time from the internet using ntp protocol.
# - Optional
# - Performs a GET request (loads a webpage)
# - Queries the current time from a server
# Thonny automatically sets the device clock every time the the program is executed.
# To avoid total confusion during testing change the following settings to false
# From the menut - Tools -> Open Thonny Data Folder
# Edit the Configuration.ini
# Change these two settings
# sync_time = True
# local_rtc = True
# Found another example here
# https://gist.github.com/aallan/581ecf4dc92cd53e3a415b7c33a1147c
# That has been modified and saved into a module ntpClient.py
# It accepts a time zone offset and saves the time to the system clock.
import network # handles connecting to WiFi
import urequests # handles making and servicing network requests
import secrets # file containing ssud='' and password=''
import time
import ntpClientTZ
import machine
import debug
import errno
import formatDateTime
#import socket
#import struct
#import sys
# Debug
# 0=off
# 1=Low
# 2=Med
# 3=Rediculous
DEBUG = 3
LOGTOFILE = True
TIMEZONE = 10
NtpServer = "au.pool.ntp.org"
debugCounter = 0 # Continuous global counter of debug log entries
# Connect to network
# Fill in your network name ssid and password in secrets.py
if(DEBUG >=1):
debugCounter = debug.debug(1, debugCounter, "main() ", "Connect to WIFI", LOGTOFILE)
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
try:
wlan.connect(secrets.ssid, secrets.password)
time.sleep(5)
except Exception as errorMsg:
debugCounter = debug.debug("ERROR", debugCounter, "main() ", "Connect to Network: Error=" + str(errorMsg))
# Set the date time from the network.
if(DEBUG >=1):
timeStamp=str(formatDateTime.formattedTime())
debugCounter = debug.debug(1, debugCounter, "main() ", "Time before update=" + str(timeStamp), LOGTOFILE)
dateStamp=str(formatDateTime.formattedDate())
debugCounter = debug.debug(1, debugCounter, "main() ", "Date before update=" + str(dateStamp), LOGTOFILE)
attempts=1
while attempts <=3:
try:
if(DEBUG >=1):
debugCounter = debug.debug(1, debugCounter, "main() ", "Update Attempt=" + str(attempts), LOGTOFILE)
ntpClientTZ.setTime(TIMEZONE, NtpServer, DEBUG, LOGTOFILE)
break
except Exception as errorMsg:
attempts=attempts+1
debugCounter = debug.debug("ERROR", debugCounter, "main() ", "Set Time from Network: Attempt="+ str(attempts) +"Error=" + str(errorMsg), LOGTOFILE)
if(DEBUG >=1):
#print("Local time after synchronizationďź%s" %str(time.localtime()))
timeStamp=str(formatDateTime.formattedTime())
debugCounter = debug.debug(1, debugCounter, "main() ", "Time after update=" + str(timeStamp), LOGTOFILE)
dateStamp=str(formatDateTime.formattedDate())
debugCounter = debug.debug(1, debugCounter, "main() ", "Date after update=" + str(dateStamp), LOGTOFILE)
# Example 1. Make a GET request for google.com and print HTML
# Print the html content from google.com
# print("1. Querying google.com:")
# r = urequests.get("http://www.google.com")
# print(r.content)
# r.close()
# Example 2. urequests can also handle basic json support! Let's get the current time from a server
# print("\n\n2. Querying the current GMT+0 time:")
# r = urequests.get("http://date.jsontest.com") # Server that returns the current GMT+0 time.
# print(r.json())
ntpClientTZ.py
import time
def debug(debugLevel, debugCounter, methodName, details, logToFile):
if(debugCounter==0):
logText="Count\tLevel\tMethodName\tDetails"
print(logText)
if(logToFile):
filelog(logText)
logText="=================================================================================="
print(logText)
if(logToFile):
filelog(logText)
debugCounter = debugCounter + 1
logText=str(debugCounter) + "\t" + str(debugLevel) + "\t" + methodName + "\t" + str(details)
print(logText)
if(logToFile):
filelog(logText)
return debugCounter
def filelog(logtext):
file=open("datalog.csv","a") # creation and opening of a CSV file in Write mode
file.write((str(time.ticks_ms())+"~")+str(logtext)+"\n") # Writing data in the opened file
file.close() # The file is closed
formatDateTime.py
import time
import ntptime
def formattedTime():
now=time.localtime()
timeString=zfl(str(now[3]),2) + ":" + zfl(str(now[4]),2) + ":" + zfl(str(now[5]),2)
return timeString
def formattedDate():
now=time.localtime()
dateString=zfl(str(now[2]),2) + "/" + zfl(str(now[1]),2) + "/" + zfl(str(now[0]),2)
return dateString
def zfl(inputString, width):
# Zero padd the specified number of digits
padded = '{:0>{w}}'.format(inputString, w=width)
return padded
debug.py
import time
import ntptime
def formattedTime():
now=time.localtime()
timeString=zfl(str(now[3]),2) + ":" + zfl(str(now[4]),2) + ":" + zfl(str(now[5]),2)
return timeString
def formattedDate():
now=time.localtime()
dateString=zfl(str(now[2]),2) + "/" + zfl(str(now[1]),2) + "/" + zfl(str(now[0]),2)
return dateString
def zfl(inputString, width):
# Zero padd the specified number of digits
padded = '{:0>{w}}'.format(inputString, w=width)
return padded
secrets.py
ssid = 'YourNetworkName'
password = 'YourNetworkPassword'