ESD4IOT LabEx2 1

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Embedded System Design for Internet of Things

May 30th to June 3rd, 2018

Day 2, May 31st, 2018

Lab Exercise 2

Connecting smart IoT sensor with cloud

(Firebase Integration with Python)

Firebase is a backend platform for building Web, Android and IOS applications. It offers storage, real time database,
different APIs, multiple authentication types and hosting platform. This manual will guide on

- Setup Firebase

- Post data to firebase realtime database using python

- Retreive data from firebase realtime database using python

Firebase Realtime Database is used for storing JSON application data, like chat messages or sensor's data, and
synchronizes changes instantly across all connected devices.

Setting up Firebase

Now follow the below steps for Firebase integration with Python.

1. If you don’t have Firebase account, create account from Firebase home (https://firebase.google.com/) with your
Google account.

2. Once your Firebase account is created, go to Firebase console. In Firebase console, click on + icon as shown in
figure 1.
Figure 1 Firebase Console

3. Form will be popped up. Enter the project name ( e.g. oblu-iot ) and select Country/Region(e.g India) like in below
figure. Accept the terms and click on Create Project button.
Figure 2 Create project

4. Project oblu-iot will be created. Navigate to Develop > Database. Click on Get Started button in RealTime
Database panel.
5. Dialog box for Security Rules for Realtime database will be popped up. Choose the Start in test mode and click on
Enable button.

6. Now click on setting icon ( ) and choose Project Setting .

Figure 3 Project Setting

7. In setting page, click on Service accounts and click on the Generate New Private Key button at the bottom of
the Firebase Admin SDK section. After that json file (e.g. oblu-iot-firebase.json ) will be downloaded which contains
your service account’s credential’s details. Save it to your local folder (e.g. C:\firebase_ credential\ oblu-iot-firebase.json
). This file will be used in firebase integration with python.

Figure 4 download service credential json file

8. For firebase integration with python,need value of some parameters like api_key, authDomain, databaseURL and
storageBucket is required. Visit your oblu-iot project in your Firebase console. Navigate to Develop section and click
on Authentication . Click on Web Setup on right side as shown in below figure. Click on Copy button and paste in
notepad. These details will be used later
Figure 5 Authentication details

9. Installing the Pyrebase

Pyrebase is simple Python wrapper for Firebase API. In this manual, will use the pyrebase modules to post data to
firebase realtime database. The documentation for Pyrebase can be found at https://github.com/thisbejim/Pyrebase .

First check whether pyrebase modules is already installed or not. Enter below command on command prompt. If it show
output something like Pyrebase==… , then it means that pyrebase modules is already installed and go to step # 11
otherwise go to step #10.

>cd C:\Python27\Scripts

> pip freeze | findstr –i pyrebase

10. Open command prompt and enter below commands. It will install module pyrebase and its dependencies.

> cd C:\Python27
> python -m pip install --upgrade pip

> cd Scripts

> pip install pyrebase

Note: pyrebase is specially developed for python3 so some features will not work in
python2 e.g. storage.child("pdf/oblu-iot.pdf").get_url()

10. Open PyCharm IDE. Click on Create New Project as show in below figure.
11. Set Project Interpreter to C:\Python27\python.exe under Existing Interpreter and click on Create Project
button.
12. Click on File menu , then click on New and choose Python File. Form will be popped up and enter the name of file
firebase_db and click on OK button

13. Post data to firebase realtime database.

In below example code is explaining the usage of pyrebase to post data to firebase realtime database

Copy below code and paste in firebase_db.py which created in previous step..

Change the value of apiKey, authDomain, databaseURL, storageBucket and serviceAccount as you get in step # 7.
serviceAccount is full path of oblu-iot-firebase.json as you downloaded in step # 5. Run it.
import pyrebase

# Firebase initialization
config = { "apiKey": "AIzaSyBz1hAWSNYMIRH-O_bC9mIDSoqkcOXX6WE",
"authDomain": "oblu-iot.firebaseapp.com",
"databaseURL": "https://oblu-iot.firebaseio.com",
"storageBucket": "oblu-iot.appspot.com",
"serviceAccount": "C:/firebase_credential/oblu-iot-firebase.json" }

app = pyrebase.initialize_app(config)

# Get a reference to the database service


db = app.database()

# data to save
data = { "name": "Mortimer 'Morty' Smith"}

# Post data to firebase database


results = db.child("users").push(data)

print "Succesfully posted data to firebase :", results

14. Now you can see your data from Firebase console. Go to oblu-iot project and navigate to Develop > Database. See
below figure.

15. Retrieve data from firebase realtime database


In below example code is explaining the usage of pyrebase to retrieve data from firebase realtime database.

Create a new python file with name retrieve_data_from_db and copy below code and paste in this python file.

Change the value of apiKey, authDomain, databaseURL, storageBucket and serviceAccount as you get in step # 7.
serviceAccount is full path of oblu-iot-firebase.json as you downloaded in step # 5. Run it.

import pyrebase

# Firebase initialization
config = { "apiKey": "AIzaSyBz1hAWSNYMIRH-O_bC9mIDSoqkcOXX6WE",
"authDomain": "oblu-iot.firebaseapp.com",
"databaseURL": "https://oblu-iot.firebaseio.com",
"storageBucket": "oblu-iot.appspot.com",
"serviceAccount": "C:/firebase_credential/oblu-iot-firebase.json" }

app = pyrebase.initialize_app(config)

# Get a reference to the database service


db = app.database()

# Retrieve data from firebase database


users = db.child("users").get()

print "Retreive data from firebase database", users.val()


Lab Exercise

Get ObluIoT.py Python script from zip file(ObluWiFiCloud_Problem.zip) which covers below functionality.
- Connect to oblu sensor
- TCP/IP communication with oblu sensor using socket programming
- Receive oblu’s location data and processing it
- Display the location data in below format and also write it to file(steps.txt)
StepNumber, X, Y, Z, orientation

On running this script, it display sensor’s realtime data on console but you have to post these data to Firebase realtime
database.

Solution
1. Open the ObluIoT.py with PyCharm IDE or notepad or any text editor you wish.
2. Change the value of device_ip with your oblu’s ip address.
3. Run the script. It will display the location data in console as you move the oblu device(one standstill position
to other standstill position). Verify whether platform receiving data or not. After sometime, you should stop the
running program.
4. Type import pyrebase in top of ObluIoT.py script.
5. Go to putDataToCloud(data_queue) function in ObluIoT.py script.
6. Replace comment “# Firebase Cloud Initilization” with below code and modify the value of apiKey,
authDomain, databaseURL, storageBucket & serviceAccount.

config = { "apiKey": "AIzaSyBz1hAWSNYMIRH-O_bC9mIDSoqkcOXX6WE",


"authDomain": "oblu-iot.firebaseapp.com",
"databaseURL": "https://oblu-iot.firebaseio.com",
"storageBucket": "oblu-iot.appspot.com",
"serviceAccount": "C:/firebase_credential/oblu-iot-firebase.json" }

app = pyrebase.initialize_app(config)

# Get a reference to the database service


db = app.database()
step_counter = 1

7. In putDataToCloud(data_queue) function. Replace comment # Put data to Firebase Database with


below code.
try:
data = {str(step_counter): data}
# Pass the user's idToken to the push method
db.child("oblu_data").push(data)
step_counter += 1
except Exception as ex:
print "Exception :", ex.message
8. Run the script and check data in firebase realtime database(Firebase console). As you move oblu device (one
standstill position to other standstill position), it will post data to Firebase realtime database.

You might also like