Skip to content

Instantly share code, notes, and snippets.

@hashg
Last active August 21, 2019 01:58
Show Gist options
  • Save hashg/f7885e8b27578a41cd3f18e99f2fa771 to your computer and use it in GitHub Desktop.
Save hashg/f7885e8b27578a41cd3f18e99f2fa771 to your computer and use it in GitHub Desktop.
Raspberry PI - Humidty - REST API

Flash a SD Card

Power On and Update Pi

Insert the SD card into the Pi and power it up. Either use a keyboard and attached monitor or connect from another machine via SSH. Update the list of packages using :

sudo apt-get update
sudo apt-get upgrade

Install Required Software

Install NGINX, pip3 and uWSGI using the following commands :

sudo apt-get install nginx
sudo apt-get install python3-dev
sudo apt-get install python3-pip
sudo python3 -m pip install --upgrade pip setuptools wheel
sudo pip3 install flask uwsgi
sudo pip3 install Adafruit_DHT

Create Flask App

Ensure you are in the /home/pi directory using :

cd ~

Create an example Flask app by first creating a folder called "flaskapp" :

mkdir flaskapp

and setting its group owner to "www-data" :

sudo chown www-data /home/pi/flaskapp

Navigate into the directory :

cd flaskapp

Then directly download my example Flask App to the Pi using :

sudo wget https://gist.github.com/hashg/f7885e8b27578a41cd3f18e99f2fa771/archive/21003617c63e854a2e148e077fa033ff63439616.zip

Extract the contents :

sudo unzip 21003617c63e854a2e148e077fa033ff63439616.zip

Goto extracted folder and copy all the files to sudo cp * ~/flaskapp

Find out the IP address of your Pi by using :

ifconfig

I will use the example “192.168.1.99” but you should use what IP address your Pi shows under ifconfig (either against eth0 for wired connections or wlan0 for wireless connections).

Test flask app

sudo python3 sensor.py

http://raspberrypi.local:5000

ctrl + c

Test uWSGI Initialisation File

uwsgi --socket 0.0.0.0:8000 --protocol=http -w sensor:app

http://raspberrypi.local:8000

Test uWSGI Initialisation File

uwsgi --ini uwsgi.ini

ls /tmp

You should see “flaskapp.sock” listed as a file. This file only exists while uWSGI is running.

ctrl + c

Configure NGINX to Use uWSGI

Delete the default site :

sudo rm /etc/nginx/sites-enabled/default

Now copy a configuration file called "flask_proxy" :

sudo cp flask_proxy /etc/nginx/sites-available/

Finally create a link from this file to the "sites-enabled" directory using :

sudo ln -s /etc/nginx/sites-available/flask_proxy /etc/nginx/sites-enabled

Restart NGINX

sudo systemctl restart nginx

Run uwsgi When Pi Boots

sudo cp uwsgi.service /etc/systemd/system

Restart the daemon so it picks up this new unit :

sudo systemctl daemon-reload

Now start the service :

sudo systemctl start uwsgi.service

Finally check on the status the service :

sudo systemctl status uwsgi.service

To make it run on every reboot use the command :

sudo systemctl enable uwsgi.service

import grovepi
import math
# Connect the Grove Temperature & Humidity Sensor Pro to digital port D4
# This example uses the blue colored sensor.
# SIG,NC,VCC,GND
sensor = 4 # The Sensor goes on digital port 4.
# temp_humidity_sensor_type
# Grove Base Kit comes with the blue sensor.
blue = 0 # The Blue colored sensor.
white = 1 # The White colored sensor.
while True:
try:
# This example uses the blue colored sensor.
# The first parameter is the port, the second parameter is the type of sensor.
[temp,humidity] = grovepi.dht(sensor,blue)
if math.isnan(temp) == False and math.isnan(humidity) == False:
print("temp = %.02f C humidity =%.02f%%"%(temp, humidity))
except IOError:
print ("Error")
### sudo nano /etc/nginx/sites-available/flasktest_proxy
server {
listen 80;
server_name localhost;
location / { try_files $uri @app; }
location @app {
include uwsgi_params;
uwsgi_pass unix:/tmp/flaskapp.sock;
}
}

MQ2

#!flask/bin/python
import sys
import datetime
import Adafruit_DHT
from flask import Flask, jsonify
app = Flask(__name__)
sensor_name = 'Sensor'
gpio_pin = 4
last_measurement = (None, None)
last_measurement_time = None
debug_mode = True
debug_measurement = (22.7, 32)
def get_measurement():
global last_measurement
global last_measurement_time
humidity, temperature = Adafruit_DHT.read_retry(Adafruit_DHT.DHT22, gpio_pin) if not debug_mode else debug_measurement
last_measurement_time = datetime.datetime.now()
last_measurement = (humidity, temperature)
return last_measurement
@app.route('/', methods=['GET'])
def welcome():
return '<body>Welcome to ' + sensor_name + '<ul> <li><a href="./api/v1/temperature"> temperature </a></li> <li><a href="./api/v1/humidity"> humidity </a></li> <li><a href="./api/v1/temperature+humidity"> temp + humid </a></li> </ul></body>'
@app.route('/api/v1/temperature', methods=['GET'])
def get_temperature():
temperature = get_measurement()[1]
return jsonify({
'name': sensor_name,
'temperature': temperature,
'timestamp': last_measurement_time.isoformat()
})
@app.route('/api/v1/humidity', methods=['GET'])
def get_humidity():
humidity = get_measurement()[0]
return jsonify({
'name': sensor_name,
'humidity': humidity,
'timestamp': last_measurement_time.isoformat()
})
@app.route('/api/v1/temperature+humidity', methods=['GET'])
def get_temperature_and_humidity():
humidity, temperature = get_measurement()
return jsonify({
'name': sensor_name,
'temperature': temperature,
'humidity': humidity,
'timestamp': last_measurement_time.isoformat()
})
if __name__ == '__main__':
app.run(host='0.0.0.0',debug=True)
[uwsgi]
chdir = /home/pi/flaskapp
module = sensor:app
master = true
processes = 1
threads = 2
uid = www-data
gid = www-data
socket = /tmp/flaskapp.sock
chmod-socket = 664
vacuum = true
die-on-term = true
touch-reload = /home/pi/flaskapp/sensor.py
### /etc/systemd/system/uwsgi.service
[Unit]
Description=uWSGI Service
After=network.target
[Service]
User=www-data
Group=www-data
WorkingDirectory=/home/pi/flaskapp/
ExecStart=/usr/local/bin/uwsgi --ini /home/pi/flaskapp/uwsgi.ini
[Install]
WantedBy=multi-user.target
country=US
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
network={
ssid="NETWORK-NAME"
psk="NETWORK-PASSWORD"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment