651.288.7000 info@intertech.com

IoT as a Diagnostic Tool (Part 3): The Code

by | May 4, 2017

As I outlined in the first article of this series, my friend Pat was having problems with a freezer warming up and putting food at risk and it was my task to diagnose the issue. In I discussed the hardware and services used. In this final article I will be showing how I coded Python on the Raspberry Pi to capture the data and store it in the Firebase database.

Program the Raspberry Pi to get sensor input

 

1. Python program to get the current temperature:

  • On the Raspberry Pi open a terminal window and create a new Python file named “getTemperature” with the following code:
    nano getTemperature.py
    
  • In that new file enter the following code:
    import os
    import glob
    import subprocess
    import calendar
    import time
    
    os.system('modprobe w1-gpio')
    os.system('modprobe w1-therm')
    
    # set up temperature sensor
    base_dir = '/sys/bus/w1/devices/'
    device_folder = glob.glob(base_dir + '28*')[0]
    device_file = device_folder + '/w1_slave'
    def read_temp_raw():
        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
    
    # read temperature and return in Fahrenheit
    def read_temp():
        lines = read_temp_raw()
        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_c = float(temp_string) / 1000.0
            temp_f = temp_c * 9.0 / 5.0 + 32.0
            return temp_f
    
  • Ctrl-X to exit the file. “Y” to save.

2. Python program to get door status

  • On the Raspberry Pi open a terminal window and create a new Python file named “door” with the following code:
    nano door.py
    
  • In that new file enter the following code:
    import RPi.GPIO as io 
    io.setmode(io.BCM)
    
    door_pin = 23
    
    io.setup(door_pin, io.IN, pull_up_down=io.PUD_UP) 
    
    # check door 
    def check_door(): 
        if io.input(door_pin): 
            return ("OPEN") 
        else: 
            return ("CLOSED")
    
  • Ctrl-X to exit the file. “Y” to save.

3. Python program to check temp and write record to database

  • On the Raspberry Pi open a terminal window and create a new Python file named “temperatureLog” with the following code:
    nano temperatureLog.py
    
  • In that new file enter the following code:
    import calendar 
    import time 
    import requests 
    import json 
    import getTemperature 
    import door 
    
    #get temperature 
    temperature = getTemperature.read_temp() 
    
    #get door status 
    door = door.check_door() 
    
    # change the following to the url that I called out in the Firebase setup step 1.5:
    url = 'https://FreezerTempAndDoor.firebaseio.com/'
        
    tableName = 'temperatureLog.json'
    finalUrl = url + tableName 
    
    postdata = { 
        'date': str(calendar.timegm(time.gmtime())), 
        'temp': str(temperature), 
        'door': door 
    } 
    
    data = json.dumps(postdata) response = requests.patch(finalUrl, data)
    
  • Ctrl-X to exit the file. “Y” to save.

4. Python program to check temp and write record to database if temperature exceeds 10 degrees F

  • On the Raspberry Pi open a terminal window and create a new Python file named “temperatureAlarm” with the following code:
    nano temperatureAlarm.py
    
  • In that new file enter the following code:
    import calendar 
    import time 
    import requests 
    import json 
    import getTemperature 
    import door 
    
    #get temperature 
    temperature = getTemperature.read_temp() 
    
    if temperature > 10.0: 
        #get door status 
        door = door.check_door() 
    
        # change the following to the url that I called out in the Firebase setup step 1.5:
        url = 'https://FreezerTempAndDoor.firebaseio.com/'
        
        tableName = 'temperatureAlarm.json'
        finalUrl = url + tableName 
    
        postdata = { 
            'date': str(calendar.timegm(time.gmtime())), 
            'temp': str(temperature), 
            'door': door 
        } 
    
        data = json.dumps(postdata) response = requests.patch(finalUrl, data)
    
  • Ctrl-X to exit the file. “Y” to save.

5. Use CRON to run our programs at scheduled intervals

  • In a Raspberry Pi terminal window open the crontab file with the following code:
    crontab -e
    
  • Scroll to the bottom of that file and enter the following code:
    # write temp/door to log database every hour
    0 * * * * /usr/bin/python /home/pi/temperatureLog.py
    
    # check for alarm status (temp is over 10 degrees F) every minute
    * * * * * /usr/bin/python /home/pi/temperatureAlarm.py
    

And that’s it! Your Raspberry Pi should be sending data to Firebase. If you’d like to see it appear in the database more often while testing, warm up the temp sensor or set the temperatureLog program to run more than once an hour.

Here is some of the data that I recorded in the temperatureLog table:

Data recorded in the temperatureLog table

I was able to learn about the freezer’s cycles and diagnose the issue just by watching the log and alarm tables in the database. If you wanted it to alert you could have it email you by following this great article.

During this series of articles I’ve shown you how I was able to solve a church mystery and save them from having to buy a new freezer. I learned quite a bit and had fun tinkering in the process. Would you have approached the problem in a different manner? Please let me know what you would have done in the comments.

Working on an IoT project with your company and need help? Intertech has experienced IoT developers that can help you put the power of connectivity to work for you.

About Intertech

Founded in 1991, Intertech delivers software development consulting to Fortune 500, Government, and Leading Technology institutions, along with real-world based corporate education services. Whether you are a company looking to partner with a team of technology leaders who provide solutions, mentor staff and add true business value, or a developer interested in working for a company that invests in its employees, we’d like to meet you. Learn more about us.