Can MagTag send info to 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.
User avatar
aunrea79
 
Posts: 18
Joined: Mon Jan 25, 2021 1:48 pm

Can MagTag send info to Adafruit IO?

Post by aunrea79 »

I am using the MagTag as a Cat Fed Clock using this tutorial: https://learn.adafruit.com/magtag-cat-feeder-clock. It connects to IO to get the time, but can I send the time recorded by the button to an IO feed? I tried using the Digial Input tutorial here: https://learn.adafruit.com/adafruit-io- ... ython-code

My code is:

Code: Select all

import time
import secrets
from adafruit_magtag.magtag import MagTag
import adafruit_requests
# import Adafruit IO REST client.
from Adafruit_IO import Client, Feed, RequestError

aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

USE_AMPM_TIME = True
weekdays = ("mon", "tue", "wed", "thur", "fri", "sat", "sun")
last_sync = None
last_minute = None

magtag = MagTag()

magtag.graphics.set_background("/background.bmp")

mid_x = magtag.graphics.display.width // 2 - 1
magtag.add_text(
    text_font="Lato-Regular-74.bdf",
    text_position=(mid_x,10),
    text_anchor_point=(0.5,0),
    is_data=False,
)
magtag.set_text("00:00a", auto_refresh = False)

magtag.add_text(
    text_font="/BebasNeueRegular-41.bdf",
    text_position=(126,86), #was 141
    text_anchor_point=(0,0),
    is_data=False,
)
magtag.set_text("DAY 00:00a", index = 1, auto_refresh = False)

def hh_mm(time_struct, twelve_hour=True):
    """ Given a time.struct_time, return a string as H:MM or HH:MM, either
        12- or 24-hour style depending on twelve_hour flag.
    """
    postfix = ""
    if twelve_hour:
        if time_struct.tm_hour > 12:
            hour_string = str(time_struct.tm_hour - 12) # 13-23 -> 1-11 (pm)
            postfix = "p"
        elif time_struct.tm_hour > 0:
            hour_string = str(time_struct.tm_hour) # 1-12
            postfix = "a"
        else:
            hour_string = '12' # 0 -> 12 (am)
            postfix = "a"
    else:
        hour_string = '{hh:02d}'.format(hh=time_struct.tm_hour)
    return hour_string + ':{mm:02d}'.format(mm=time_struct.tm_min) + postfix

try: # if we have a 'pet-feeding' feed
    pets = aio.feeds('pet-feeding')
except RequestError: # create a pet-feeding feed
    feed = Feed(name="pet-feeding")
    pets = aio.create_feed(feed)

while True:
    if not last_sync or (time.monotonic() - last_sync) > 3600:
        # at start or once an hour
        magtag.network.get_local_time()
        last_sync = time.monotonic()

    # get current time
    now = time.localtime()

    # minute updated, refresh display!
    if not last_minute or (last_minute != now.tm_min):  # minute has updated
        magtag.set_text(hh_mm(now, USE_AMPM_TIME), index = 0)
        last_minute = now.tm_min

    # timestamp
    if magtag.peripherals.button_a_pressed:
        out = weekdays[now.tm_wday] + " " + hh_mm(now, USE_AMPM_TIME)
        magtag.set_text(out, index = 1)
        while magtag.peripherals.button_a_pressed: # wait till released
            pass
            
            
    aio.send(pets.key, out)
 
    # avoid timeout from adafruit io
    time.sleep(1)
The first thing that gives me trouble is

Code: Select all

from Adafruit_IO import Client, Feed, RequestError
CLIENT can't be found. Is there a different way the code should be written for MagTag?

User avatar
millercommamatt
 
Posts: 837
Joined: Tue Jul 31, 2018 4:57 pm

Re: Can MagTag send info to Adafruit IO?

Post by millercommamatt »

Adafruit IO events are automatically time stamped. If you run the digital input tutorial you mentioned and then look at the feed you'll have in IO, you'll see the datetime stamps.

If you're having trouble with other aspects, post the full code and the full error messages.

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

Re: Can MagTag send info to Adafruit IO?

Post by brubell »

CLIENT can't be found. Is there a different way the code should be written for MagTag?
Is there an error log somewhere - could you copy and paste this exact error?

Which libraries are you using?

User avatar
aunrea79
 
Posts: 18
Joined: Mon Jan 25, 2021 1:48 pm

Re: Can MagTag send info to Adafruit IO?

Post by aunrea79 »

The lib I have are:
  • adafruit_bitmap_font
    adafruit_display_text
    adafruit_io
    adafruit_magtag
    adafruit_portalbase
    adafruit_faekrequests.mpy
    adafruit_miniqr.mpy
    adafruit_requests.mpy
    neopixel_mpy
    simpleio.mpy
When I use REPL I get:

Code: Select all

code.py output:
Traceback (most recent call last):
  File "code.py", line 7, in <module>
ImportError: no module named 'Adafruit_IO.Client'

Code done running.

Adafruit CircuitPython 6.2.0 on 2021-04-05; Adafruit MagTag with ESP32S2

User avatar
millercommamatt
 
Posts: 837
Joined: Tue Jul 31, 2018 4:57 pm

Re: Can MagTag send info to Adafruit IO?

Post by millercommamatt »

My guess based on the error is that the Adafruit_IO library is either missing or installed incorrectly.

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

Re: Can MagTag send info to Adafruit IO?

Post by brubell »

The example on https://learn.adafruit.com/adafruit-io- ... ython-code uses the Adafruit IO PYTHON library for Raspberry Pi, it is not compatible with CircuitPython.

The CircuitPython library is here: https://github.com/adafruit/Adafruit_Ci ... AdafruitIO

Examples for this library are within https://github.com/adafruit/Adafruit_Ci ... it_io_mqtt

User avatar
aunrea79
 
Posts: 18
Joined: Mon Jan 25, 2021 1:48 pm

Re: Can MagTag send info to Adafruit IO?

Post by aunrea79 »

I am new to CircuitPython and Adafruit IO so I am not sure what the do. I made some changes which works until the button is pushed then I get an error. I have added the library adafruit_minimqtt. My new code is:

Code: Select all

import board
import digitalio
import time
import wifi
from secrets import secrets
from adafruit_magtag.magtag import MagTag
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_io.adafruit_io import IO_MQTT

USE_AMPM_TIME = True
weekdays = ("mon", "tue", "wed", "thur", "fri", "sat", "sun")
last_sync = None
last_minute = None

magtag = MagTag()

magtag.graphics.set_background("/background.bmp")

mid_x = magtag.graphics.display.width // 2 - 1
magtag.add_text(
    text_font="Lato-Regular-74.bdf",
    text_position=(mid_x, 10),
    text_anchor_point=(0.5, 0),
    is_data=False,
)
magtag.set_text("00:00a", auto_refresh=False)

magtag.add_text(
    text_font="/BebasNeueRegular-41.bdf",
    text_position=(126, 86),  # was 141
    text_anchor_point=(0, 0),
    is_data=False,
)
magtag.set_text("DAY 00:00a", index=1, auto_refresh=False)

def hh_mm(time_struct, twelve_hour=True):
    """Given a time.struct_time, return a string as H:MM or HH:MM, either
    12- or 24-hour style depending on twelve_hour flag.
    """
    postfix = ""
    if twelve_hour:
        if time_struct.tm_hour > 12:
            hour_string = str(time_struct.tm_hour - 12)  # 13-23 -> 1-11 (pm)
            postfix = "p"
        elif time_struct.tm_hour > 0:
            hour_string = str(time_struct.tm_hour)  # 1-12
            postfix = "a"
        else:
            hour_string = "12"  # 0 -> 12 (am)
            postfix = "a"
    else:
        hour_string = "{hh:02d}".format(hh=time_struct.tm_hour)
    return hour_string + ":{mm:02d}".format(mm=time_struct.tm_min) + postfix

# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
    broker="io.adafruit.com",
    username=secrets["aio_username"],
    password=secrets["aio_key"],
)

# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)

while True:
    if not last_sync or (time.monotonic() - last_sync) > 3600:
        # at start or once an hour
        magtag.network.get_local_time()
        last_sync = time.monotonic()

    # get current time
    now = time.localtime()

    # minute updated, refresh display!
    if not last_minute or (last_minute != now.tm_min):  # minute has updated
        magtag.set_text(hh_mm(now, USE_AMPM_TIME), index=0)
        last_minute = now.tm_min

    # timestamp
    if magtag.peripherals.button_a_pressed:
        out = weekdays[now.tm_wday] + " " + hh_mm(now, USE_AMPM_TIME)
        magtag.set_text(out, index=1)
        while magtag.peripherals.button_a_pressed:  # wait till released
            pass
        io.publish(secrets["aio_feed"], out)
And my error is:

Code: Select all

Traceback (most recent call last):
  File "code.py", line 85, in <module>
  File "adafruit_io/adafruit_io.py", line 431, in publish
  File "adafruit_minimqtt/adafruit_minimqtt.py", line 564, in publish
  File "adafruit_minimqtt/adafruit_minimqtt.py", line 953, in is_connected
MMQTTException: MiniMQTT is not connected.
Line 85 is the last line of my code: io.publish(secrets["aio_feed"], out)

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

Re: Can MagTag send info to Adafruit IO?

Post by brubell »

After the lines:

Code: Select all

# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)
Add the following line:

Code: Select all

io.connect()

User avatar
aunrea79
 
Posts: 18
Joined: Mon Jan 25, 2021 1:48 pm

Re: Can MagTag send info to Adafruit IO?

Post by aunrea79 »

Adding that line gets:

Code: Select all

Traceback (most recent call last):
  File "code.py", line 65, in <module>
  File "adafruit_io/adafruit_io.py", line 108, in connect
  File "adafruit_io/adafruit_io.py", line 108, in connect
AdafruitIO_MQTTError: MQTT Error: Unable to connect to Adafruit IO.
Line 65 is the io.connect()

User avatar
millercommamatt
 
Posts: 837
Joined: Tue Jul 31, 2018 4:57 pm

Re: Can MagTag send info to Adafruit IO?

Post by millercommamatt »

Maybe it's not getting on the wifi? Can you post a redacted version of your secrets file? I'm assuming all the wifi connect commands are in there.

User avatar
aunrea79
 
Posts: 18
Joined: Mon Jan 25, 2021 1:48 pm

Re: Can MagTag send info to Adafruit IO?

Post by aunrea79 »

Code: Select all

secrets = {
    'ssid' : '****NetworkName****',
    'password' : '****Password****',
    'aio_username' : '****Username****',
    'aio_key' : '****Key****',
    'aio_port' : 8883,
    'aio_feed' : '****Feed-Name****',
    'timezone' : "America/New_York", # http://worldtimeapi.org/timezones
    }

User avatar
aunrea79
 
Posts: 18
Joined: Mon Jan 25, 2021 1:48 pm

Re: Can MagTag send info to Adafruit IO?

Post by aunrea79 »

It is connecting to the internet. Just for some reason it is not connecting to adafruit io. I rechecked my username and key and they are correct.

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

Re: Can MagTag send info to Adafruit IO?

Post by brubell »

Please try this simpler script:
https://github.com/adafruit/Adafruit_Ci ... esp32s2.py

Are you able to connect your magtag to IO using this script?

User avatar
aunrea79
 
Posts: 18
Joined: Mon Jan 25, 2021 1:48 pm

Re: Can MagTag send info to Adafruit IO?

Post by aunrea79 »

I got the following error

Code: Select all

Connected to NetworkName!
Connecting to Adafruit IO...
Connected to Adafruit IO!  Listening for DemoFeed changes...
Traceback (most recent call last):
  File "code.py", line 94, in <module>
  File "adafruit_io/adafruit_io.py", line 108, in connect
  File "adafruit_io/adafruit_io.py", line 108, in connect
AdafruitIO_MQTTError: MQTT Error: Unable to connect to Adafruit IO.

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

Re: Can MagTag send info to Adafruit IO?

Post by brubell »

Do you see any errors on io.adafruit.com/monitor when you connect your device?

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”