jonnyp1970
Posts: 3
Joined: Fri May 10, 2019 11:37 am

Python3 boot script Pimoroni BMP280 feed to Adafruit IO

Fri May 10, 2019 12:38 pm

Hello - this is my first post and with so many topics in this forum not sure if Beginners forum the right home. Apologies if I got this wrong.

Objective:
- Create an environment monitor for my home network cabinet to monitor temperature etc. using a Raspberry Pi with BMP280 Breakout and send the results a cloud service to view private data remotely

Hardware & Software:
- Raspberry Pi Zero, running Raspbian and powered by USB 2.0 from a device within network cabinet
- Pimoroni BMP280 breakout - soldered at 90 degrees away from GPIO board to reduce CPU heat on BMP280 sensor
- Code written in Python 3 using Pimoroni BMP280 Library (as per Pimoroni website recommendations) and Adafruit IO library
- Send BMP280 Temperature &, Pressure (and altitude for fun) sensor data and CPU temperature data [using open('/sys/class/thermal/thermal_zone0/temp') ], as feeds to pre-configured Adafruit IO Dashboard & feeds.

So the python code works and the results can be seen via my own private Adafruit IO dashboard plus I also send same data using various print statements to terminal for debugging. So all good. The only niggle is that the BMP280 temperature is out by +4 degree C (?) but thats for another post!

Script runs in in terminal as: python3 myscript.py >> log.txt

MY ISSUE IS : I wish to leave the Pi Zero running 24/7 and only occasionally access the device remotely using either a terminal shell from MacOS or or via VNCServer. The Pi has no keyboard or mouse physically connected. I don't want to keep the Mac switched on all the time using an active terminal shell to execute the Python 3 script. However no matter what I do I cannot seem to execute the same Python 3 ".py' script on boot (plus pipe output to a log file). I only want the script to run when the Pi Zero is rebooted not run multiple times upon opening a terminal shell too

Have tried my two preferred methods (as don't wish to go down paths of adding script to .bashrc, init.d or SYSTEMD) being:

A) /etc/rc.local - where I added line sudo python3 /home/pi/myscript.py >> /home/pi/log.txt &"

B) crontab - @reboot python3 /home/pi/myscript.py >> /home/pi/log.txt &. For noting Cron is working as a number appears when I check.

Any advice on what I'm doing wrong would be greatly appreciated please?

For those interested main loop of code as follows with feeds and variables setup further up the code. Note LOOP_DELAY has value = 10:

# MAIN - GETS SENSOR DATA AND SENDS TO ADAFRUIT IO DASHBOARD

while True:
print('Reading sensors...')
# Read Pimoroni BMP280 breakout
temp_data = bmp280.get_temperature()
pressure_data = bmp280.get_pressure()
alt_data = bmp280.get_altitude(qnh=baseline_pressure)

# Get Pi CPU temperature from Bash system call
cpu_temp_data = int(open('/sys/class/thermal/thermal_zone0/temp').read()) / 1e3

print('sending data to adafruit io...')

# Send BMP280 breakout and Pi Zero CPU data to Adafruit IO.
print('Temperature: %0.1f C' % temp_data)
aio.send(temperature_feed.key, round(temp_data,1))
time.sleep(2)

print("CPU Temperature: %0.1f hPa" % cpu_temp_data)
aio.send(cpu_temperature_feed.key, round(cpu_temp_data,1))

print("Pressure: %0.1f hPa" % pressure_data)
aio.send(pressure_feed.key, int(pressure_data))

print("Altitude = %0.2f meters" % alt_data)
aio.send(altitude_feed.key, round(alt_data,2))

# avoid timeout from adafruit io
time.sleep(LOOP_DELAY * 60)

Andyroo
Posts: 2823
Joined: Sat Jun 16, 2018 12:49 am
Location: Lincs U.K.

Re: Python3 boot script Pimoroni BMP280 feed to Adafruit IO

Fri May 10, 2019 6:37 pm

I would use the CRON and reboot option to only have one program running.

Python has a logging module that can help keeping track of messages in the background https://realpython.com/python-logging/ has an intro.

For debugging CRON issues have a look at https://garyhall.org.uk/troubleshooting ... ry-pi.html for a great series of steps to checking jobs that are failing. Section two may help :D

One area of your code you may need to look at is the web link to Adafruit. If the fails can you handle it and backdate data or will your program crash out?
Need Pi spray - these things are breeding in my house...

jonnyp1970
Posts: 3
Joined: Fri May 10, 2019 11:37 am

Re: Python3 boot script Pimoroni BMP280 feed to Adafruit IO

Fri May 17, 2019 10:22 am

Hi Andyroo

Thanks for responding. The python logging link was helpful however for my experience might take me awhile to understand correct logging code to use and where.

The Gary Hall cron stuff helpful. I added full path to @reboot but still this didn't work (well certainly nothing being written to a log file.) What I'm not clear on is which cronfile is used on reboot? Reason is that I've noticed that if I use sudo crontab -e this is a different cronfile to that used by plain 'crontab -e'. Trial and error required I think...

The Adafruit IO seems to be temperamental and connection does crash. I'm unable to locate the 'how-to' technical documentation to handle/capture Adafruit aio on web link failures. As per your suggestion below are you aware of a known coded example for this please?

<<One area of your code you may need to look at is the web link to Adafruit. If the fails can you handle it and backdate data or will your program crash out?>>

Thanks

Andyroo
Posts: 2823
Joined: Sat Jun 16, 2018 12:49 am
Location: Lincs U.K.

Re: Python3 boot script Pimoroni BMP280 feed to Adafruit IO

Fri May 17, 2019 12:11 pm

Using SUDO CRONTAB adds the task to run as the root user whereas using CRONTAB adds the task to run as the current user. This determines which user the job runs under when started.

That may be your issue - if the job needs access to something the Pi user owns so I would add it the Pi user tasks by just using CRONTAB without the sudo.

If the program needs networking / screen etc to start first before it can run, you could add a delay into the entry

Code: Select all

@reboot sleep 10; /usr/bin/python3 /home/pi/myscript.py
Error handling in Python is based around the try...except statement block (untested):

Code: Select all

sent_to_web = False
while not sent_to_web:
    try:
        post_to_web()
        sent_to_to_web = True
    except:
       print('Could not send to the web\nTrying again')
This is very very crude but gives you a basic idea. If the post_to_web() function has an error (no internet for example) an exception is raised (the dreaded error message) but it does not kill the program as it’s in a ‘try’ block so the error handling jumps to the except part and does that.

In real life though you need to think about how you get out of the error - maybe try 5 or so times and then give up, write the data to a local file for recovery later etc...

You can also ‘trap’ different errors and do different things - have a look at https://www.pythonforbeginners.com/erro ... nd-except/ for some details of errors and handling them. Corey Shafer has a video https://youtu.be/NIWwJbo-9_8 on this - I’ve not seen it to be honest but found his others fine to watch.

Edit: Tried to sort out note on cron...
Need Pi spray - these things are breeding in my house...

jonnyp1970
Posts: 3
Joined: Fri May 10, 2019 11:37 am

Re: Python3 boot script Pimoroni BMP280 feed to Adafruit IO

Sun May 26, 2019 6:54 pm

AndyRoo - many thanks for all your help, advice and examples. Much appreciated

After working through the error handling and adding some code I decided that the Adafruit IO was too unstable. So after a search came up with alternative cloud service with Corlysis.com. They provide both InfluxDB and Grafana with simple interfacing. Once I worked through some example scripts and re-worked by code got a really great result. Sweet! :)

Still having problems with cron but know that CRONTAB is ok. Have tried creating a .sh script to call the python script which works fine when run from prompt but not once added to CRONTAB as a @REBOOT command :(.

Also tried an executable python script but again works fine from prompt but again not in CRONTAB under @REBOOT.

For the time being I'll just run it as a background process and home the pi zero doesn't reboot itself (other than power failure). Its not going to be used other than for the purpose I intended....

Andyroo
Posts: 2823
Joined: Sat Jun 16, 2018 12:49 am
Location: Lincs U.K.

Re: Python3 boot script Pimoroni BMP280 feed to Adafruit IO

Mon May 27, 2019 12:05 am

Have a look at tmux as this lets you have multiple terminal sessions open at once and you can disconnect the Mac and reconnect later.

Very handy if like me you forget to use owly to hold the sleep function off :lol:
Need Pi spray - these things are breeding in my house...

Return to “Beginners”