Skip to content

Commit 3d1fbac

Browse files
authored
Merge pull request #21 from makermelissa/time_improvements
get_local_time improvements
2 parents 27a8a43 + f62a2ab commit 3d1fbac

File tree

1 file changed

+49
-25
lines changed

1 file changed

+49
-25
lines changed

adafruit_portalbase/network.py

Lines changed: 49 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -51,9 +51,7 @@
5151
)
5252
# our strftime is %Y-%m-%d %H:%M:%S.%L %j %u %z %Z see http://strftime.net/ for decoding details
5353
# See https://apidock.com/ruby/DateTime/strftime for full options
54-
TIME_SERVICE_STRFTIME = (
55-
"&fmt=%25Y-%25m-%25d+%25H%3A%25M%3A%25S.%25L+%25j+%25u+%25z+%25Z"
56-
)
54+
TIME_SERVICE_FORMAT = "%Y-%m-%d %H:%M:%S.%L %j %u %z %Z"
5755
LOCALFILE = "local.txt"
5856
# pylint: enable=line-too-long
5957

@@ -157,17 +155,27 @@ def add_json_transform(self, json_transform):
157155
else:
158156
self.json_transform.extend(filter(callable, json_transform))
159157

160-
def get_local_time(self, location=None):
161-
# pylint: disable=line-too-long
158+
@staticmethod
159+
def url_encode(url):
162160
"""
163-
Fetch and "set" the local time of this microcontroller to the local time at the location, using an internet time API.
161+
A function to perform minimal URL encoding
162+
"""
163+
url = url.replace(" ", "+")
164+
url = url.replace("%", "%25")
165+
url = url.replace(":", "%3A")
166+
return url
167+
168+
def get_strftime(self, time_format, location=None):
169+
"""
170+
Fetch a custom strftime relative to your location.
164171
165-
:param str location: Your city and country, e.g. ``"New York, US"``.
172+
:param str location: Your city and country, e.g. ``"America/New_York"``.
166173
167174
"""
168-
# pylint: enable=line-too-long
175+
# pylint: disable=line-too-long
169176
self.connect()
170177
api_url = None
178+
reply = None
171179
try:
172180
aio_username = self._secrets["aio_username"]
173181
aio_key = self._secrets["aio_key"]
@@ -184,42 +192,58 @@ def get_local_time(self, location=None):
184192
else: # we'll try to figure it out from the IP address
185193
print("Getting time from IP address")
186194
api_url = TIME_SERVICE % (aio_username, aio_key)
187-
api_url += TIME_SERVICE_STRFTIME
195+
api_url += "&fmt=" + self.url_encode(time_format)
196+
188197
try:
189198
response = self._wifi.requests.get(api_url, timeout=10)
190199
if response.status_code != 200:
200+
print(response)
191201
error_message = (
192-
"Error connection to Adafruit IO. The response was: "
202+
"Error connecting to Adafruit IO. The response was: "
193203
+ response.text
194204
)
195205
raise RuntimeError(error_message)
196206
if self._debug:
197207
print("Time request: ", api_url)
198208
print("Time reply: ", response.text)
199-
times = response.text.split(" ")
200-
the_date = times[0]
201-
the_time = times[1]
202-
year_day = int(times[2])
203-
week_day = int(times[3])
204-
is_dst = None # no way to know yet
209+
reply = response.text
205210
except KeyError:
206211
raise KeyError(
207212
"Was unable to lookup the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones" # pylint: disable=line-too-long
208213
) from KeyError
209-
year, month, mday = [int(x) for x in the_date.split("-")]
210-
the_time = the_time.split(".")[0]
211-
hours, minutes, seconds = [int(x) for x in the_time.split(":")]
212-
now = time.struct_time(
213-
(year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst)
214-
)
215-
if rtc is not None:
216-
rtc.RTC().datetime = now
217-
218214
# now clean up
219215
response.close()
220216
response = None
221217
gc.collect()
222218

219+
return reply
220+
221+
def get_local_time(self, location=None):
222+
# pylint: disable=line-too-long
223+
"""
224+
Fetch and "set" the local time of this microcontroller to the local time at the location, using an internet time API.
225+
226+
:param str location: Your city and country, e.g. ``"America/New_York"``.
227+
228+
"""
229+
reply = self.get_strftime(TIME_SERVICE_FORMAT, location=location)
230+
if reply:
231+
times = reply.split(" ")
232+
the_date = times[0]
233+
the_time = times[1]
234+
year_day = int(times[2])
235+
week_day = int(times[3])
236+
is_dst = None # no way to know yet
237+
year, month, mday = [int(x) for x in the_date.split("-")]
238+
the_time = the_time.split(".")[0]
239+
hours, minutes, seconds = [int(x) for x in the_time.split(":")]
240+
now = time.struct_time(
241+
(year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst)
242+
)
243+
244+
if rtc is not None:
245+
rtc.RTC().datetime = now
246+
223247
def wget(self, url, filename, *, chunk_size=12000):
224248
"""Download a url and save to filename location, like the command wget.
225249

0 commit comments

Comments
 (0)