Adafruit Industries, Essential service and business: NYC – Executive Order 202.6 - Read more.
0

OLD aio.send doesn't work - Python 2 vs. 3?
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.
Please be positive and constructive with your questions and comments.

OLD aio.send doesn't work - Python 2 vs. 3?

by stevecook3dw on Thu Feb 20, 2020 1:22 pm

I must say, I really dig the relative ease of use of the adafruit_IO feeds and dashboards. Using a program from 2018 for the garden monitoring I made is awesome to monitor on Adafruit IO.

But when I did a new fresh install of Rasbian Buster lite (instead of cloning my old card) and followed all your new SD card set up for Raspberry pi....my old code doesnt work!? Help me understand. When I look at the new aio feed code, it doesn't seem as straightforward. (I stumbled into some on a tutorial) Is there a "start from scratch tutorial on sending to Adafruit_IO...the new way?

Is there a way I can still use my old code with new OS installs or updates?

Snip20200220_102.png
Snip20200220_102.png (176.47 KiB) Viewed 76 times


thanks

stevecook3dw
 
Posts: 6
Joined: Fri Apr 13, 2018 8:11 pm

Re: OLD aio.send doesn't work - Python 2 vs. 3?

by brubell on Fri Feb 21, 2020 10:22 am

Hi stevecook3dw,

Python 2 has been sunsetted - we do not currently support Python2 in any of our libraries. This includes the Adafruit IO Python library. We recommend using the latest version of Adafruit IO Python.

Could you please post your old code and any errors you receive while running it? It'll help me understand where the code is breaking.

Thanks!

brubell
 
Posts: 792
Joined: Fri Jul 17, 2015 10:33 pm

Re: OLD aio.send doesn't work - Python 2 vs. 3?

by stevecook3dw on Sat Feb 22, 2020 6:20 pm

I took time and did a 2to3 conversion, so we don't waste time with that.

error on first run is
pi@pibasement:~ $ python garden_lite_converted_2to3.py
Traceback (most recent call last):
File "garden_lite_converted_2to3.py", line 26, in <module>
import Adafruit_DHT
ModuleNotFoundError: No module named 'Adafruit_DHT'


I notice this import is used on new tutorials.......but all lower case now?> what other changes from two years should I look out for as I try to use my code on new projects?
thanks

I'm not a programmer or electronics type, but trying to hack together stuff I find and learn how to use Raspberry PI for monitoring and control. My caveat is to say, pardon the possibly messy, against-standards code and comments. It works.



Here is the code (keys to aio edited)

Code: Select all | TOGGLE FULL SIZE
# this is garden_lite_converted_2to3.py
# Steve Cook 22 FEB 2020
# before conversion, works just fine on RPI3 mod B
# with circa 2018 setup (OS and updates)
# sends to Adfruit_IO great
# https://io.adafruit.com/stevecook3dw/dashboards/garden

# SENSORS and DEVICES
# DS18B20 - 1 wire digital thermometer.  Pre-wired and waterproofed version
# - one in the box
# - one in the soil
# - one in the ground deep with water pipe
# - one outside the green house, long cord, hanging on post out of sun for OAT
# BMP180 - JBtek BMP180 Barometric Pressure, Temperature and Altitude Sensor
# AM3202 - temperature and humidity
# Kuman soil moisture module
# TSL2561 Adafruit Digital Luminosity/Lux/Light Sensor
# SainSmart Camera Module Board 5MP Webcam Video 1080p 720p

# libraries
# I have not taken time to go back and see if all these are still being used
import time
import sys
import urllib.request, urllib.error, urllib.parse
import json
import Adafruit_DHT
import Adafruit_BMP.BMP085 as BMP085
import RPi.GPIO as GPIO
import os
import glob
import subprocess
import requests # added this to try the network connection
import datetime
import luxreader

base_dir = '/sys/bus/w1/devices/'

#Instance of TSL2561 Class
luxrdr = luxreader.TSL2561()

# Config the gardhumidity sensor
am2302Pin = 17

# setup GPIO
GPIO.setwarnings(False) #this prevent error when I was toggling LEDs on and off
GPIO.setmode(GPIO.BCM)
GPIO.setup(27, GPIO.OUT, initial=1) #LED on box showing program is running

#set variables
gardruntimestart = time.time() # this is time when starting the program.  Used for runtime calcs
gardexception = "exceptions reset"

#array for temperature inputs DS18B20
sensortemp = ('28-021467d3c7ff','28-00043cce3aff', '28-03173055f9ff')
# 28-021467d3c7ff control box temp
# 28-00043cce3aff pipe ground temp
# 28-03173055f9ff soil temp

try:
   while True:
      # Start Output
      # the sleep times are for screen print limit
      # and also for adafruit 60 data points per minute limit
      now = datetime.datetime.now()
      print((now.strftime("%m-%d-%Y      %H:%M:%S")))
      # AM2302 Humidity & Temp
      time.sleep(2) # giving some warm up time for sensor??
      gardhumidity, gardam2302temp = Adafruit_DHT.read_retry(Adafruit_DHT.AM2302 , am2302Pin)
      time.sleep(2) # giving some read time.  Got a calc error sometimes in line below
      gardam2302temp = (gardam2302temp *9/5)+32 # convert to F

      # DS18B20 Waterproof Temperature Probes
      def read_temp_raw(sensortemp):
         device_folder = glob.glob(base_dir + sensortemp)[0]
         device_file = device_folder + '/w1_slave'
         catdata = subprocess.Popen(['cat',device_file], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
         out,err = catdata.communicate()
         out_decode = out.decode('utf-8')
         lines = out_decode.split('\n')
         return lines
      def read_temp(sensorid):
         lines = read_temp_raw(sensortemp[sensorid])
         while lines[0].strip()[-3:] != 'YES':
            time.sleep(0.2)
            lines = read_temp_raw()
         equals_pos = lines[1].find('t=')
         if equals_pos != -1:
            temp_string = lines[1][equals_pos+2:]
            temp_f = float(temp_string) / 1000.0
            return temp_f
      # Get temperature readings from the read_temp array
      gardboxtemp = read_temp(0)
      gardgroundtemp = read_temp(1)
      gardsoiltemp = read_temp(2)

      gardboxtemp = (gardboxtemp *9/5)+32 #convert to F
      gardgroundtemp = (gardgroundtemp *9/5)+32 #convert to F
      gardsoiltemp = (gardsoiltemp *9/5)+32 #convert to F

      # BMP180 Barometric gardatmpressure Sensor
      gardbmpsensor = BMP085.BMP085()
      #gardbmpsensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRALOWPOWER)
      #gardbmpsensor = BMP085.BMP085(mode=BMP085.BMP085_STANDARD)
      #gardbmpsensor = BMP085.BMP085(mode=BMP085.BMP085_STANDARD)
      #gardbmpsensor = BMP085.BMP085(mode=BMP085.BMP085_HIGHRES)
      #gardbmpsensor = BMP085.BMP085(mode=BMP085.BMP085_ULTRAHIGHRES)
      gardatmpressure = gardbmpsensor.read_pressure()
      gardbmpaltitude = gardbmpsensor.read_altitude()
      gardbmpaltitude = gardbmpaltitude * 3.28084 # conversion from meters to feet
      gardslpressure = gardbmpsensor.read_sealevel_pressure()
      gardbmptemp = gardbmpsensor.read_temperature()
      gardbmptemp = (gardbmptemp *9/5)+32 # convert to F

#      

      ## TSL2561 Lux Sensor
      # removing lux reading because unstable and not accurate
      #gardlux = luxrdr.readLux()      # Auto
      #gardlux = luxrdr.readLux(1)     # Low Gain
      #gardlux = luxrdr.readLux(16)    # High Gain
      #print "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
      #print 'TSL2561:'
      #print 'gardlux: ' + str(gardlux) + '\n'
      #print 'Garden LUX =                       {0:0.0f}'.format(gardlux)

      # Calc Average Temperature
      gardGHavgtemp = ((gardam2302temp + gardbmptemp) / 2)
      gardtempList = [gardam2302temp, gardbmptemp]
      gardhighesttemp = max(gardtempList)
      gardlowesttemp = min(gardtempList)
      gardvariancetemp = (gardhighesttemp - gardlowesttemp)
      #diffinandout = (gardGHavgtemp - gardgroundtemp) # difference between OAT and GH temp
      #varianceBoxTemp = (gardGHavgtemp-gardboxtemp) #difference between box and green house temp
 
      print('AM2302 Green House Humidity =      {0:0.0f}%'.format(gardhumidity))
      print('AM2302 Green House Temp =          {0:0.0f} F'.format(gardam2302temp))
      print('BMP180 Green House Temp =          {0:0.0f} F'.format(gardbmptemp))
      print('Average Garden Temp =              {0:0.0f} F'.format(gardGHavgtemp))
      print('DS18B20 Soil Temp 10 inch =        {0:0.0f} F'.format(gardsoiltemp))     
      print('DS18B20 Garden Pipe Ground Temp =  {0:0.0f} F'.format(gardgroundtemp))
      print('DS18B20 Garden Control Box Temp =  {0:0.0f} F'.format(gardboxtemp))
      
      if gardvariancetemp > 3:
         print('>>>>>>>>>>>>>>>>>>>')
         print('>>>>>>>>>>>>>>>>>>>')
         print('>>>>>>>>>>>>>>>>>>>')
         print('    difference between the two garden temps > 3F\n')
         print('-------------------------------------------------')
         gardalert1 = "difference between the two garden temps > 3F"
         ##########send this to Adfruit
      else:
         gardalert1 = 0

      # Send data to Adafruit IO dashboard
      # Import library and create instance of REST client
      # added this while loop so program will keep running if connection error
      connectionattempts = 0
      while True and connectionattempts<10:
         try:   
            connectionattempts += 1
            #print "\nconnectionattempts = " + connectionattempts + '\n'
            from Adafruit_IO import Client
            aio = Client('c2251----------135cb') # this is my Adafruit login code

            # Send the values to feeds
            aio.send('garden.gardhumidity', gardhumidity) # the first element is the feed name in Adafruit.  Second is variable here.
            time.sleep(2)
            aio.send('garden.gardam2302temp', gardam2302temp)
            time.sleep(2)
            aio.send('garden.gardbmptemp', gardbmptemp)
            time.sleep(2)
            aio.send('garden.gardatmpressure', gardatmpressure)
            time.sleep(2)
            aio.send('garden.gardboxtemp', gardboxtemp)
            time.sleep(2)
            #aio.send('garden.gardlux', gardlux)
            #time.sleep(2)
            aio.send('garden.gardgroundtemp', gardgroundtemp)
            time.sleep(2)
            aio.send('garden.gardsoiltemp', gardsoiltemp)
            time.sleep(2)
            aio.send('garden.gardghavgtemp', gardGHavgtemp)
            time.sleep(2)
            gardruntime = (time.time() - gardruntimestart) /60 #calculates the run time
            print("------------------------------------------------------")
            print('gardruntime = {0:0.0f} min'.format(gardruntime))
            aio.send('garden.gardruntime', gardruntime)
            time.sleep(2)
            # aio.send('gardexception', gardexception)
            # time.sleep(2)
                     
            print("======================================================")
            print("data sent to Adfruit IO")
            print("======================================================\n")       
            break
         except requests.ConnectionError:
            gardexception = "ConnectionError"
            time.sleep(5)
            print(" ")
            print(" ")
            print("```````````````````````````````connectionerror````````````")
            print(" ")
            print(" ")
         except requests.SysCallError:
            gardexception = "SysCallError"
            time.sleep(5)
            print(" ")
            print(" ")
            print(">>>>>>>>>>>>>>>>>>>>>>SysCallError<<<<<<<<<<<<<<<<<<<<<<<")
            print(" ")
            print(" ")

except KeyboardInterrupt: 
   GPIO.output(27, 0) # LED off                       
   gardexception = "KeyboardInterrupt" 
   print("================================")
   print(" keyboard interupt")
   print(" ")
   gardruntime = (time.time() - gardruntimestart) /60     
   print('-----------gardruntime = {0:0.0f} min'.format(gardruntime))
   print("\n\n if you see this and not GPIO cleaned up.......need to edit program ")
   print("================================")
 
   
finally: 
   GPIO.output(27, 0) # LED off                       
   gardexception = "something else happened"
   GPIO.cleanup() # this ensures a clean exit
   print("--------------------------GPIO was cleaned up")   

stevecook3dw
 
Posts: 6
Joined: Fri Apr 13, 2018 8:11 pm

Re: OLD aio.send doesn't work - Python 2 vs. 3?

by stevecook3dw on Sat Feb 22, 2020 7:06 pm

I should mention, I started here with a fresh, clean SD card this year....thinking I would get a fresh install to clean up things before I start to copy my garden program and deploy similar projects. That is when all the trouble started and I've been down too many rabbit holes to mention trying to fix.

https://learn.adafruit.com/circuitpytho ... spberry-pi
Followed all the steps for RASPBIAN LITE and then various updates and configs mentioned.

thanks

stevecook3dw
 
Posts: 6
Joined: Fri Apr 13, 2018 8:11 pm

Re: OLD aio.send doesn't work - Python 2 vs. 3?

by brubell on Tue Feb 25, 2020 9:58 am

Hi Steve,

Code: Select all | TOGGLE FULL SIZE
error on first run is
pi@pibasement:~ $ python garden_lite_converted_2to3.py
Traceback (most recent call last):
File "garden_lite_converted_2to3.py", line 26, in <module>
import Adafruit_DHT
ModuleNotFoundError: No module named 'Adafruit_DHT'

I notice this import is used on new tutorials.......but all lower case now?> what other changes from two years should I look out for as I try to use my code on new projects?
thanks



The Adafruit Python DHT library (https://github.com/adafruit/Adafruit_Py ... or-library) has been deprecated. We are now only supporting the use of our CircuitPython libraries for use with Python.

Check out this guide for info on using DHT sensors with the CircuitPython library: https://learn.adafruit.com/dht-humidity ... thon-setup

brubell
 
Posts: 792
Joined: Fri Jul 17, 2015 10:33 pm

Re: OLD aio.send doesn't work - Python 2 vs. 3?

by stevecook3dw on Tue Feb 25, 2020 10:25 am

In January, I started with a fresh install on and SD card following this (third page into explanation:
https://learn.adafruit.com/circuitpython-on-raspberrypi-linux/overview
I chose Rasbian Lite....since I am only doing ssh access, I assumed that would be a good choice.

I followed all the setup and did the Blinkatest
https://learn.adafruit.com/circuitpython-on-raspberrypi-linux/installing-circuitpython-on-raspberry-pi

Then followed these steps for DHT22
https://learn.adafruit.com/dht-humidity-sensing-on-raspberry-pi-with-gdocs-logging/wiring

Note, for a new learner, having been exposed to pi BOARD vs. BCM a couple years back,
[img]
GPIO%20BCM%20vs%20BOARD.jpg
[/img]

I found your
Code: Select all | TOGGLE FULL SIZE
import board

confusing.........I assumed we were going to use BOARD numbers, not BCM numbers. Not true....you are using BCM numbers.

So I ran my humidity sensor code from above, and get lots of
Checksum
and
Full Buffer
errors.

I did a lot of searching to try to solve with no luck. (I'm barely a programmer and found exhaustive libraries I didn't know how to use)
any help is appreciated. Thanks
Attachments
GPIO BCM vs BOARD.jpg
GPIO BCM vs BOARD.jpg (112.53 KiB) Viewed 54 times
to adafruit1.png
to adafruit1.png (165.14 KiB) Viewed 54 times
GPIO BCM vs BOARD.png
GPIO BCM vs BOARD.png (272.82 KiB) Viewed 54 times

stevecook3dw
 
Posts: 6
Joined: Fri Apr 13, 2018 8:11 pm

Re: OLD aio.send doesn't work - Python 2 vs. 3?

by brubell on Wed Feb 26, 2020 9:27 am

There is an active issue on the DHT library regarding the checkum not validating: https://github.com/adafruit/Adafruit_Ci ... /issues/15

and with the "a full buffer was not returned" error: https://github.com/adafruit/Adafruit_Ci ... /issues/33

Could you post your updated code? We may be able add some code to catch and pass some of the errors since you're able to obtain readings periodically.

brubell
 
Posts: 792
Joined: Fri Jul 17, 2015 10:33 pm

Re: OLD aio.send doesn't work - Python 2 vs. 3?

by stevecook3dw on Wed Feb 26, 2020 10:17 am

The code with the errors was right off the tutorial link above.

FYI - I abandon the new CircuitPython and Blinky install sd card..........went back to a clone of my older stuff started 2018. Deployed the pi to the crawl space and works great. Used a moisture sensor under water heater that will trigger if any water.

Snip20200226_77.png
Snip20200226_77.png (97.22 KiB) Viewed 42 times

moisture1.png
moisture1.png (137.12 KiB) Viewed 42 times



Some want to build a car or overhaul an engine. Others want to take a drive in the mountains.

stevecook3dw
 
Posts: 6
Joined: Fri Apr 13, 2018 8:11 pm

Please be positive and constructive with your questions and comments.