Io connection problems

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
robomiller
 
Posts: 9
Joined: Wed Jun 24, 2020 3:37 am

Io connection problems

Post by robomiller »

Hello,

I am trying to do the pyportal pet planter project. I'm pretty sure i did the guide to completion. But i am having an issue with connecting to Adafruit IO. I'm a complete newb so not sure what to do. So i added a pic of the error and put the code i'm using which is from the guide. anyone have an ideas? Thanks.

Code: Select all

import time

import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi, adafruit_esp32spi_wifimanager
import adafruit_imageload
import displayio
import neopixel
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text.label import Label
from adafruit_io.adafruit_io import IO_MQTT
import adafruit_minimqtt.adafruit_minimqtt as MQTT
from adafruit_pyportal import PyPortal
from adafruit_seesaw.seesaw import Seesaw
from simpleio import map_range

#---| User Config |---------------

# How often to poll the soil sensor, in seconds
DELAY_SENSOR = 30

# How often to send data to adafruit.io, in minutes
DELAY_PUBLISH = 5

# Maximum soil moisture measurement
SOIL_LEVEL_MAX = 500.0

# Minimum soil moisture measurement
SOIL_LEVEL_MIN= 350.0

#---| End User Config |---------------

# Background image
BACKGROUND = "/images/roots.bmp"
# Icons for water level and temperature
ICON_LEVEL = "/images/icon-wetness.bmp"
ICON_TEMP = "/images/icon-temp.bmp"
WATER_COLOR = 0x16549E

# Audio files
wav_water_high = "/sounds/water-high.wav"
wav_water_low = "/sounds/water-low.wav"

# the current working directory (where this file is)
cwd = ("/"+__file__).rsplit('/', 1)[0]

# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

# Set up i2c bus
i2c_bus = busio.I2C(board.SCL, board.SDA)

# Initialize soil sensor (s.s)
ss = Seesaw(i2c_bus, addr=0x36)

# PyPortal ESP32 AirLift Pins
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)

# Initialize PyPortal Display
display = board.DISPLAY

WIDTH = board.DISPLAY.width
HEIGHT = board.DISPLAY.height

# Initialize new PyPortal object
pyportal = PyPortal(esp=esp,
                    external_spi=spi)

# Set backlight level
pyportal.set_backlight(0.5)

# Create a new DisplayIO group
splash = displayio.Group(max_size=15)

# show splash group
display.show(splash)

# Palette for water bitmap
palette = displayio.Palette(2)
palette[0] = 0x000000
palette[1] = WATER_COLOR
palette.make_transparent(0)

# Create water bitmap
water_bmp = displayio.Bitmap(display.width, display.height, len(palette))
water = displayio.TileGrid(water_bmp, pixel_shader=palette)
splash.append(water)

print("drawing background..")
# Load background image
try:
    bg_bitmap, bg_palette = adafruit_imageload.load(BACKGROUND,
                                                    bitmap=displayio.Bitmap,
                                                    palette=displayio.Palette)
# Or just use solid color
except (OSError, TypeError):
    BACKGROUND = BACKGROUND if isinstance(BACKGROUND, int) else 0x000000
    bg_bitmap = displayio.Bitmap(display.width, display.height, 1)
    bg_palette = displayio.Palette(1)
    bg_palette[0] = BACKGROUND
bg_palette.make_transparent(0)
background = displayio.TileGrid(bg_bitmap, pixel_shader=bg_palette)

# Add background to display
splash.append(background)

print('loading fonts...')
# Fonts within /fonts/ folder
font = cwd+"/fonts/GothamBlack-50.bdf"
font_small = cwd+"/fonts/GothamBlack-25.bdf"

# pylint: disable=syntax-error
data_glyphs = b'0123456789FC-* '
font = bitmap_font.load_font(font)
font.load_glyphs(data_glyphs)

font_small = bitmap_font.load_font(font_small)
full_glyphs = b'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-,.: '
font_small.load_glyphs(full_glyphs)

# Label to display Adafruit IO status
label_status = Label(font_small, max_glyphs=20)
label_status.x = 305
label_status.y = 10
splash.append(label_status)

# Create a label to display the temperature
label_temp = Label(font, max_glyphs=4)
label_temp.x = 35
label_temp.y = 300
splash.append(label_temp)

# Create a label to display the water level
label_level = Label(font, max_glyphs=4)
label_level.x = display.width - 130
label_level.y = 300
splash.append(label_level)

print('loading icons...')
# Load temperature icon
icon_tmp_bitmap, icon_palette = adafruit_imageload.load(ICON_TEMP,
                                                        bitmap=displayio.Bitmap,
                                                        palette=displayio.Palette)
icon_palette.make_transparent(0)
icon_tmp_bitmap = displayio.TileGrid(icon_tmp_bitmap,
                                     pixel_shader=icon_palette,
                                     x=0, y=280)
splash.append(icon_tmp_bitmap)

# Load level icon
icon_lvl_bitmap, icon_palette = adafruit_imageload.load(ICON_LEVEL,
                                                        bitmap=displayio.Bitmap,
                                                        palette=displayio.Palette)
icon_palette.make_transparent(0)
icon_lvl_bitmap = displayio.TileGrid(icon_lvl_bitmap,
                                     pixel_shader=icon_palette,
                                     x=315, y=280)
splash.append(icon_lvl_bitmap)

# Connect to WiFi
label_status.text = "Connecting..."
while not esp.is_connected:
    try:
        wifi.connect()
    except RuntimeError as e:
        print("could not connect to AP, retrying: ",e)
        wifi.reset()
        continue
print("Connected to WiFi!")

# Initialize MQTT interface with the esp interface
MQTT.set_socket(socket, esp)

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

# Adafruit IO Callback Methods
# pylint: disable=unused-argument
def connected(client):
    # Connected function will be called when the client is connected to Adafruit IO.
    print('Connected to Adafruit IO!')

def subscribe(client, userdata, topic, granted_qos):
    # This method is called when the client subscribes to a new feed.
    print('Subscribed to {0} with QOS level {1}'.format(topic, granted_qos))

# pylint: disable=unused-argument
def disconnected(client):
    # Disconnected function will be called if the client disconnects
    # from the Adafruit IO MQTT broker.
    print("Disconnected from Adafruit IO!")

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

# Connect the callback methods defined above to the Adafruit IO MQTT Client
io.on_connect = connected
io.on_subscribe = subscribe
io.on_disconnect = disconnected

# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()
label_status.text = " "
print("Connected!")

fill_val = 0.0
def fill_water(fill_percent):
    """Fills the background water.
    :param float fill_percent: Percentage of the display to fill.

    """
    assert fill_percent <= 1.0, "Water fill value may not be > 100%"
    # pylint: disable=global-statement
    global fill_val

    if fill_val > fill_percent:
        for _y in range(int((board.DISPLAY.height-1) - ((board.DISPLAY.height-1)*fill_val)),
                        int((board.DISPLAY.height-1) - ((board.DISPLAY.height-1)*fill_percent))):
            for _x in range(1, board.DISPLAY.width-1):
                water_bmp[_x, _y] = 0
    else:
        for _y in range(board.DISPLAY.height-1,
                        (board.DISPLAY.height-1) - ((board.DISPLAY.height-1)*fill_percent), -1):
            for _x in range(1, board.DISPLAY.width-1):
                water_bmp[_x, _y] = 1
    fill_val = fill_percent

def display_temperature(temp_val, is_celsius=False):
    """Displays the temperature from the STEMMA soil sensor
    on the PyPortal Titano.
    :param float temp: Temperature value.
    :param bool is_celsius:

    """
    if not is_celsius:
        temp_val = (temp_val * 9 / 5) + 32 - 15
        print('Temperature: %0.0fF'%temp_val)
        label_temp.text = '%0.0fF'%temp_val
        return int(temp_val)
    else:
        print('Temperature: %0.0fC'%temp_val)
        label_temp.text = '%0.0fC'%temp_val
        return int(temp_val)

# initial reference time
initial = time.monotonic()
while True:
    # Explicitly pump the message loop
    # to keep the connection active
    try:
        io.loop()
    except (ValueError, RuntimeError) as e:
        print("Failed to get data, retrying...\n", e)
        wifi.reset()
        continue
    now = time.monotonic()

    print("reading soil sensor...")
    # Read capactive
    moisture = ss.moisture_read()
    label_level.text = str(moisture)

    # Convert into percentage for filling the screen
    moisture_percentage = map_range(float(moisture), SOIL_LEVEL_MIN, SOIL_LEVEL_MAX, 0.0, 1.0)

    # Read temperature
    temp = ss.get_temp()
    temp = display_temperature(temp)

    # fill display
    print("filling disp..")
    fill_water(moisture_percentage)
    print("disp filled..")

    print("temp: " + str(temp) + "  moisture: " + str(moisture))

    # Play water level alarms
    if moisture <= SOIL_LEVEL_MIN:
        print("Playing low water level warning...")
        pyportal.play_file(wav_water_low)
    elif moisture >= SOIL_LEVEL_MAX:
        print("Playing high water level warning...")
        pyportal.play_file(wav_water_high)


    if now - initial > (DELAY_PUBLISH * 60):
        try:
            print("Publishing data to Adafruit IO...")
            label_status.text = "Sending to IO..."
            io.publish("moisture", moisture)
            io.publish("temperature", temp)
            print("Published")
            label_status.text = "Data Sent!"

            # reset timer
            initial = now
        except (ValueError, RuntimeError) as e:
            label_status.text = "ERROR!"
            print("Failed to get data, retrying...\n", e)
            wifi.reset()
    time.sleep(DELAY_SENSOR)
Attachments
adaio.jpg
adaio.jpg (409.44 KiB) Viewed 225 times

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

Re: Io connection problems

Post by brubell »

Hi,

Please download the latest library bundle from here: https://circuitpython.org/libraries

and ensure the libraries on your board are up-to-date with the latest versions.

If you're still having errors, please reply to this post and I'll help debug this with you.

User avatar
robomiller
 
Posts: 9
Joined: Wed Jun 24, 2020 3:37 am

Re: Io connection problems

Post by robomiller »

Hello,

Thanks for the reply. I have updated the libraries to no avail unfortunately. I also updated the firmware for the titano screen I got. Did you need me to post any thing else that might help with the trouble shooting?

User avatar
robomiller
 
Posts: 9
Joined: Wed Jun 24, 2020 3:37 am

Re: Io connection problems

Post by robomiller »

Hello,

I'm not sure if this helps but in the "internet connet!" part of the guide under the wifi manager section. When I ran that code its connects to Adafruit IO just fine for the test feed.

To be honest is there a way for me to just not connect to Adafruit IO at all? I don't really need it to post the data from the planter to the IO dashboard. If i could just see the readouts of the water level and temp just on the screen that's all i really need. I wouldn't think it would need to get any information from IO since the sensor is attached to the board. But i'm not sure what i'm looking at with the code. I'm learning as I go along. If you got any advice on how to do that or if its just a quick edit on the code I would appreciate any help on that front.

I was going to try to edit the code after I got everything working when I finished the guide to ditch adafruit.IO. So I didn't edit the code in anyway. other than in line 189 username=secrets["aio_user"] but in the secrets Folder its ["aio_username"]. So i just added the "name" part in line 189. I also tried to just take the "name" out in the secrets folder but i get the same outcome.

For the error i get it lists two lines of code one is 218 for Code.py but that line is just "io.connect()" should there be anything in the "()" I didn't see anything in the guide for it. But then again total newb here so not sure what I'm looking at lol. The other is line 118 From Adafruit_io/adafruit_io.py but i'm not even sure where that code is. I would think its from the Adafruit_io folder in the lib folder on the board but i can't even open that since they are .mpy files which form what i understand are just batches of code that python reads but i could be wrong.

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

Re: Io connection problems

Post by brubell »

Code: Select all

For the error i get it lists two lines of code one is 218 for Code.py but that line is just "io.connect()" should there be anything in the "()" I didn't see anything in the guide for it. But then again total newb here so not sure what I'm looking at lol. The other is line 118 From Adafruit_io/adafruit_io.py but i'm not even sure where that code is. I would think its from the Adafruit_io folder in the lib folder on the board but i can't even open that since they are .mpy files which form what i understand are just batches of code that python reads but i could be wrong.
Could you please install the Mu editor (https://learn.adafruit.com/welcome-to-c ... -mu-editor) and open the REPL (https://learn.adafruit.com/welcome-to-c ... n/the-repl).

When the code throws an error that it can't connect to Adafruit IO, can you copy and paste the output of the REPL to this thread?

User avatar
robomiller
 
Posts: 9
Joined: Wed Jun 24, 2020 3:37 am

Re: Io connection problems

Post by robomiller »

Well it pretty much says the same that the screen says in the screen shot. So I'm not sure if that's what you needed.

Code: Select all

Auto-reload is on. Simply save files over USB to run them or enter REPL to disable.
code.py output:
Set background to  /pyportal_startup.bmp
ESP firmware: bytearray(b'1.2.2\x00')
Set background to  0
No SD card found: no SD card
drawing background..
loading fonts...
loading icons...
Connected to WiFi!
Connecting to Adafruit IO...
Traceback (most recent call last):
  File "code.py", line 218, in <module>
  File "adafruit_io/adafruit_io.py", line 118, in connect
AdafruitIO_MQTTError: MQTT Error: Unable to connect to Adafruit IO.



Press any key to enter the REPL. Use CTRL-D to reload.
Adafruit CircuitPython 5.3.1 on 2020-07-13; Adafruit PyPortal Titano with samd51j20
>>> 

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

Re: Io connection problems

Post by brubell »

Ok, I was able to test this out this morning.

In your code, change:

Code: Select all

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

Code: Select all

# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(broker="io.adafruit.com",
                        username=secrets["aio_user"],
                        password=secrets["aio_key"])
We removed the required https:// prefix in a recent version of MiniMQTT. Should be OK now, I was able to connect and send data.

I'll make a Pull Request update the code in the guide

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

Re: Io connection problems

Post by brubell »

Update: We've made a pull request fixing this issue in the guide here -https://github.com/adafruit/Adafruit_Le ... /pull/1225

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”