Getting Current Time of Day From Adafruit IO

Moderators: adafruit_support_bill, adafruit

Forum rules
If you're posting code, please make sure your code does not include your Adafruit IO Active Key or WiFi network credentials.
Locked
User avatar
chagrincyclist
 
Posts: 30
Joined: Sun Jun 07, 2020 10:03 am

Getting Current Time of Day From Adafruit IO

Post by chagrincyclist »

I am building a stock ticker and want to put the device to sleep when the stock market is closed. To do that I am using Adafruit IO to get the current time. I tried using time.localtime() (see code below) and the following output comes back

Code: Select all

struct_time(tm_year=2000, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=19, tm_sec=3, tm_wday=5, tm_yday=1, tm_isdst=-1)
.

Everything I read says this should give me the current time but this time is obviously incorrect. I know my connection to Adafruit IO is good because I am able to send and receive temperature test data. Please help, thanks!

Code: Select all

# adafruit_circuitpython_adafruitio usage with an esp32spi_socket
from random import randint
import board
import time
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests
from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError

# Add a secrets.py to your filesystem that has a dictionary called secrets with "ssid" and
# "password" keys with your WiFi credentials. DO NOT share that file or commit it into Git or other
# source control.
# pylint: disable=no-name-in-module,wrong-import-order
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.A5)
esp32_ready = DigitalInOut(board.A4)
esp32_reset = DigitalInOut(board.A3)


spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

print("Connecting to AP...")
while not esp.is_connected:
    try:
        esp.connect_AP(secrets["ssid"], secrets["password"])
    except RuntimeError as e:
        print("could not connect to AP, retrying: ", e)
        continue
print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi)

socket.set_interface(esp)
requests.set_socket(socket, esp)

# Set your Adafruit IO Username and Key in secrets.py
# (visit io.adafruit.com if you need to create an account,
# or if you need your Adafruit IO key.)
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]

# Initialize an Adafruit IO HTTP API object
io = IO_HTTP(aio_username, aio_key, requests)
timenow = time.localtime()
print(timenow)
try:
    # Get the 'temperature' feed from Adafruit IO
    temperature_feed = io.get_feed("temperature")
except AdafruitIO_RequestError:
    # If no 'temperature' feed exists, create one
    temperature_feed = io.create_new_feed("temperature")

# Send random integer values to the feed
random_value = randint(0, 50)
print("Sending {0} to temperature feed...".format(random_value))
io.send_data(temperature_feed["key"], random_value)
print("Data sent!")

# Retrieve data value from the feed
print("Retrieving data from temperature feed...")
received_data = io.receive_data(temperature_feed["key"])
print("Data from temperature feed: ", received_data["value"])

timenow = time.localtime()
print(timenow)

User avatar
dastels
 
Posts: 15831
Joined: Tue Oct 20, 2015 3:22 pm

Re: Getting Current Time of Day From Adafruit IO

Post by dastels »

The function time.localtime() doesn't get time from Adafruit IO, just from what the MCU thinks the time is, with no external reference. You need to query Adafruit IO directly for the time. That can be done via MQTT if you're using that. See https://io.adafruit.com/api/docs/mqtt.html#time-topics. Another option is to use the IO_HTTP.receive_time() function. See the bottom of https://github.com/adafruit/Adafruit_Ci ... ruit_io.py.

Dave

User avatar
chagrincyclist
 
Posts: 30
Joined: Sun Jun 07, 2020 10:03 am

Re: Getting Current Time of Day From Adafruit IO

Post by chagrincyclist »

Thanks Dave. I'm trying the IO_HTTP.receive_time() function but I'm getting an error as it's asking for 1 positional argument and am giving none; but I only don't see any defined in the adafruit_IO.py file. What am I missing? Thanks for your help!

User avatar
brubell
Learn User Page
 
Posts: 2017
Joined: Fri Jul 17, 2015 10:33 pm

Re: Getting Current Time of Day From Adafruit IO

Post by brubell »

chagrincyclist wrote:Thanks Dave. I'm trying the IO_HTTP.receive_time() function but I'm getting an error as it's asking for 1 positional argument and am giving none; but I only don't see any defined in the adafruit_IO.py file. What am I missing? Thanks for your help!
Could you please post the error output from the REPL?

User avatar
chagrincyclist
 
Posts: 30
Joined: Sun Jun 07, 2020 10:03 am

Re: Getting Current Time of Day From Adafruit IO

Post by chagrincyclist »

Thanks for your help I've posted my code below. Here is the error message I'm getting (the temperature data shows that I'm successfully connecting to Adafruit IO but I'm stumbiing in getting the time. Appreciate your assistance.

Connecting to AP...
could not connect to AP, retrying: ('No such ssid', b'Obie')
Connected to Obie RSSI: -73
Sending 42 to temperature feed...
Data sent!
Retrieving data from temperature feed...
Data from temperature feed: 42
Traceback (most recent call last):
File "code.py", line 70, in <module>
TypeError: function takes 1 positional arguments but 0 were given

[code

Code: Select all

from random import randint
import board
import time
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests
from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError

# Add a secrets.py to your filesystem that has a dictionary called secrets with "ssid" and
# "password" keys with your WiFi credentials. DO NOT share that file or commit it into Git or other
# source control.
# pylint: disable=no-name-in-module,wrong-import-order
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.A5)
esp32_ready = DigitalInOut(board.A4)
esp32_reset = DigitalInOut(board.A3)


spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

print("Connecting to AP...")
while not esp.is_connected:
    try:
        esp.connect_AP(secrets["ssid"], secrets["password"])
    except RuntimeError as e:
        print("could not connect to AP, retrying: ", e)
        continue
print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi)

socket.set_interface(esp)
requests.set_socket(socket, esp)

# Set your Adafruit IO Username and Key in secrets.py
# (visit io.adafruit.com if you need to create an account,
# or if you need your Adafruit IO key.)
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]

# Initialize an Adafruit IO HTTP API object
io = IO_HTTP(aio_username, aio_key, requests)

try:
    # Get the 'temperature' feed from Adafruit IO
    temperature_feed = io.get_feed("temperature")
except AdafruitIO_RequestError:
    # If no 'temperature' feed exists, create one
    temperature_feed = io.create_new_feed("temperature")

# Send random integer values to the feed
random_value = randint(0, 50)
print("Sending {0} to temperature feed...".format(random_value))
io.send_data(temperature_feed["key"], random_value)
print("Data sent!")

# Retrieve data value from the feed
print("Retrieving data from temperature feed...")
received_data = io.receive_data(temperature_feed["key"])
print("Data from temperature feed: ", received_data["value"])

t=IO_HTTP.receive_time()
print(t)
][/code]

User avatar
brubell
Learn User Page
 
Posts: 2017
Joined: Fri Jul 17, 2015 10:33 pm

Re: Getting Current Time of Day From Adafruit IO

Post by brubell »

Code: Select all

t=IO_HTTP.receive_time()
should be

Code: Select all

t=io.receive_time()

User avatar
chagrincyclist
 
Posts: 30
Joined: Sun Jun 07, 2020 10:03 am

Re: Getting Current Time of Day From Adafruit IO

Post by chagrincyclist »

Boom! Magic, works great, thank you!

User avatar
chagrincyclist
 
Posts: 30
Joined: Sun Jun 07, 2020 10:03 am

Re: Getting Current Time of Day From Adafruit IO

Post by chagrincyclist »

Thanks to your help I'm off working with structured time very happily. However, I found something odd. When I retrieved the structured time from Adafruit's IO server it said today, November 18 was week day # 4! The docs all say that weekday starts on Monday as 0, Tuesday 1, Wednesday 2, Thursday 3, so today, 11/18/2021 Thursday should be weekday #3!
See the result below. What gives? Thanks.

Code: Select all

Auto-reload is on. Simply save files over USB to run them or enter REPL to disable.
code.py output:
Connecting to AP...
could not connect to AP, retrying:  ('No such ssid', b'Obie')
Connected to Obie 	RSSI: -25
struct_time(tm_year=2021, tm_mon=11, tm_mday=18, tm_hour=17, tm_min=46, tm_sec=33, tm_wday=4, tm_yday=322, tm_isdst=0)

Code done running.

Press any key to enter the REPL. Use CTRL-D to reload.

User avatar
jwcooper
 
Posts: 1004
Joined: Tue May 01, 2012 9:08 pm

Re: Getting Current Time of Day From Adafruit IO

Post by jwcooper »

Oh, so that's an interesting language issue.

The struct.json is processed on the server by ruby, which the DOW starts on Sunday as 0.

You can see that here:
https://ruby-doc.org/core-3.0.2/Time.html#method-i-wday

I'll file an issue on this, as it will likely need to be handled by the IO Python library.

Locked
Forum rules
If you're posting code, please make sure your code does not include your Adafruit IO Active Key or WiFi network credentials.

Return to “Internet of Things: Adafruit IO and Wippersnapper”