0% found this document useful (0 votes)
10 views16 pages

Laboratory Activity No. 6 - Integrating Firebase Admin With NodeMCU With VueJs Web App Version 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views16 pages

Laboratory Activity No. 6 - Integrating Firebase Admin With NodeMCU With VueJs Web App Version 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Course: CPE 400 Section: CPE41S1

Name/s: Date Performed: 10/30/24


APOLINARIO, GIAN KYLE Date Submitted:10/30/24
IRINGAN, RAYMART
OCARIZA, AARON KYLE
VIERNES, JOICE ANN EISLEY
VINAS, GABRIEL EDMUND
Instructor: Engr. Malbog

Laboratory Activity No. 6


Integrating Firebase Admin with
NodeMCU

1. Objective(s):
This activity helps the student to explore the use of Firebase Admin with NodeMCU,
focusing on real-time data management using Firebase Realtime Database or
Firestore. Students will learn to securely transmit data from NodeMCU to a backend
server that leverages Firebase Admin SDK, allowing robust interaction with Firebase
services.

2. Intended Learning Outcomes (ILOs):

At the end of the activity student shall able to:


● Understand the Firebase Admin SDK’s role in managing data and
authentication.
● Configure NodeMCU to send data to a backend that securely communicates
with Firebase.
● Set up and deploy a simple Node.js server using Firebase Admin to handle
data from IoT devices.
● Securely store and retrieve data from Firebase using NodeMCU.
3. Materials
Hardware:

● NodeMCU ESP8266 or ESP32 module


● DHT11 or other sensor (optional for data
collection) Software:
● Arduino IDE with ESP8266/ESP32 libraries installed
● Firebase Admin SDK
● Node.js and npm
● Firebase Console
● Postman (for
testing) Accounts and
API Keys:
● Firebase project and database URL
● Firebase Admin SDK service account key
4. Discussion
With the growth of IoT devices, managing real-time data securely is essential. The
Firebase Admin SDK provides backend services to interact with Firebase Realtime
Database, Firestore, Authentication, and other Firebase products without using
Firebase directly on the client-side IoT devices, which can be less secure.

In this activity, students will configure NodeMCU to send sensor data to a Node.js
backend server. This server, in turn, uses Firebase Admin SDK to write data securely
to Firebase. This approach offers better control over data security, integrity, and
scalability.
4. Procedures
Step 1: Set Up Firebase Project and Database

1. Create a Firebase Account:


a. Go to the Firebase Console.
b. Sign in with your Google account or create a new one.
2. Create a New Project:
a. Click on Add project.
b. Enter a name for your project (e.g., NodeMCU Project).
c. (Optional) Enable Google Analytics if needed, then click Create project.
3. Access Realtime Database or Firestore:
a. Once your project is created, go to the Build section in the left sidebar.
b. Choose Firestore Database.
c. For Firestore Database, click on Create Database and select the
Start in Test Mode option. This allows read/write access without
security rules for testing (make sure to secure it later).
4. Navigate to Project Settings > Service accounts.
5. Click Generate new private key to download the JSON file containing
your service account key. This will be used in your Node.js backend.

Step 2: Set Up Node.js Backend with Firebase Admin SDK

1. Install Node.js and create a new Node.js project directory.


2. In the terminal, initialize your project:

npm init -y

3. Install necessary packages:

npm install firebase-admin express


body-parser

4. Create a file named server.js and configure Firebase Admin SDK:


const express = require('express');
const bodyParser = require('body-parser');
const admin = require('firebase-admin');

const serviceAccount =
require('./path-to-your-service-account-file.json
'); // Path to your service account key JSON file

// Initialize Firebase Admin SDK with Firestore


admin.initializeApp({
credential:
admin.credential.cert(serviceAccount),
// No need for databaseURL when using Firestore
});

const db = admin.firestore(); // Use Firestore


instead of Realtime Database
const app = express();
app.use(bodyParser.json());

app.post('/data', async (req, res) => {


const data = req.body;

try {
// Add data to Firestore in the 'sensorData'
collection
await db.collection('sensorData').add(data);
res.status(200).send('Data saved
successfully');
} catch (error) {
res.status(500).send(error);
}
});

const PORT = process.env.PORT || 3000;


app.listen(PORT, () => {
console.log(`Server is running on port
${PORT}`);
});
5. Save the code and run the server:

node server.js

6. Use Postman to test the endpoint by sending a POST request to


http://localhost:3000/data with JSON data:

{
"temperature": 22.5,
"humidity": 60
}

7. Go to your Firebase Real-Time Database then you should see the changes
in database value, like this:

Step 3: Write the NodeMCU Code to Send Data to the Backend

1. In Arduino IDE, add code to connect NodeMCU to WiFi and send data to your
Node.js backend:
#include <ESP8266WiFi.h>
#include
<ESP8266HTTPClient.h>

const char* ssid = "your-SSID";


const char* password = "your-PASSWORD";
const char* serverUrl = "http://<your-server-IP>:3000/data";

void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() !=
WL_CONNECTED) { delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}

void loop() {
if (WiFi.status() == WL_CONNECTED)
{ WiFiClient client;
HTTPClient http;
http.begin(client, serverUrl);
http.addHeader("Content-Type", "application/json");

// Example data
String jsonData = "{\"temperature\": 25, \"humidity\": 60}";

int httpResponseCode =
http.POST(jsonData); if
(httpResponseCode > 0) {
Serial.println("Data sent
successfully!");
} else {
Serial.println("Error sending data.");
}
http.end();
}
delay(10000); // Send data every 10 seconds
}
2. Replace <your-SSID>, <your-PASSWORD>, and <your-server-IP>
with actual values.
3. Upload the code to NodeMCU.

Step 4: Check Data in Firebase

1. Go to your Firebase Console and check the Realtime Database or


Firestore. You should see data under the sensorData node.
2. Verify that new entries are being created as NodeMCU sends data every 10
seconds.

6. Supplemental Activity
Supplemental Questions:
1. Why do we use Firebase Admin on the server instead of accessing Firebase
directly from the NodeMCU?

Using Firebase Admin on the server rather than directly on the NodeMCU improves
security and control. By offloading the Firebase interactions to a backend server, the
Firebase Admin SDK can securely handle data and authentication services on behalf of
the device. This setup prevents exposing sensitive credentials directly on the NodeMCU,
minimizes potential security risks, and allows for more scalable data management by
centralizing Firebase interactions.

2. What are the advantages of using HTTPS for data transmission between
NodeMCU and the server?

Using HTTPS for data transmission secures the data exchange between the NodeMCU
and the server by encrypting the transmitted data. This encryption protects against
potential cyber attacks and interception by unauthorized parties, ensuring that sensitive
information like sensor data remains confidential and protected during data
transmission.

3. How can you secure the Firebase database rules to prevent unauthorized
access?

Firebase database rules can be configured to control read and write permissions,
ensuring only authenticated and authorized requests have access. By default, setting the
Firebase database to "Test Mode" allows open access, but once development is
complete, switching to "Locked Mode" and defining strict access rules will limit
database access only to authorized users or applications. Additionally, using Firebase
Authentication along with these rules further restricts access to verified users only.

Supplemental Activity #1:


1. Secure the Firebase credentials by storing them in the
environmental variables.
1.1. install dot env using the command npm install dotenv in your
terminal

1.2. Create a .env File in the Root of Your Vue.js Project. The .env
file stores your sensitive information. Create the file with the
following content:

PORT=3000
FIREBASE_DATABASE_URL=https://<your-database-name>
.firebaseio.com
FIREBASE_SERVICE_ACCOUNT=./path-to-your-service-a
c count-file.json

1.3. To prevent the .env file from being committed to your version control
system, add it to your .gitignore file.
1.4. Modify the server.js file to use these environment variables:
require('dotenv').config(); // Load environment
variables

const express = require('express');


const bodyParser = require('body-parser');
const admin = require('firebase-admin');
// Load the service account key from the path
stored in .env
const serviceAccount =
require(process.env.FIREBASE_SERVICE_ACCOUNT);

admin.initializeApp({
credential:
admin.credential.cert(serviceAccount),
databaseURL: process.env.FIREBASE_DATABASE_URL,
});

const db = admin.database();
const app = express();
app.use(bodyParser.json());

app.post('/data', (req, res) => {


const data = req.body;
db.ref('sensorData')
.push(data)
.then(() => res.status(200).send('Data saved
successfully'))
.catch((error) =>
res.status(500).send(error));
});

const PORT = process.env.PORT || 3000;


app.listen(PORT, () => {
console.log(`Server is running on port
${PORT}`);
});
1.5. Now, when you run your application using node or nodemon, it
shouldl load the environment variables from the .env file.

2. Supplemental Activity #2: Sensor Integration and Data Visualization


2.1. Connect a DHT11 or other environmental sensor to the NodeMCU.
2.2. Modify the NodeMCU code to send real sensor readings, such as
temperature and humidity values, to the Node.js backend.
3. Supplemental Activity #3: Develop a Vue.js Component to Display
Firebase Data in Real-Time
3.1. In your VueJs App, install Firebase SDK

npm install firebase


3.2. Configure Firebase in Vue by creating a Firebase config file
firebaseConfig.js inside the src folder:

// src/firebaseConfig.js
// src/firebaseConfig.js
import firebase from 'firebase/app';
import 'firebase/firestore';

const firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_PROJECT_ID.firebaseapp.com",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_PROJECT_ID.appspot.com",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);

// Export the Firestore instance


const db = firebase.firestore();
export { db };
3.3. Create the Vue Component to Display Firebase Data. This can be
done by creating new Vue component named SensorData.vue
<template>
<div>
<h1>Sensor Data</h1>
<ul>
<li v-for="data in sensorData"
:key="data.id">
Temperature: {{ data.temperature }}°C,
Humidity: {{ data.humidity }}%
</li>
</ul>
</div>
</template>

<script>
import { db } from '../firebase'; // Adjust the
path as needed

export default {
data() {
return {
sensorData: [],
};
},
created() {
this.fetchData();
},
methods: {
async fetchData() {
try {
const snapshot = await
db.collection('sensorData').get();
this.sensorData = snapshot.docs.map(doc =>
({ id: doc.id, ...doc.data() }));
} catch (error) {
console.error("Error fetching sensor data:
", error);
}
},
},
};
</script>

<style scoped>
/* Add any styles you need */
</style>
The Vue component above is designed to fetch and display sensor
data, specifically temperature and humidity, from a Firestore
collection named sensorData. When the component is created, it
automatically calls the fetchData method, which retrieves all
documents from the specified Firestore collection using an
asynchronous call. The retrieved data is then processed to create an
array of objects that include each document's ID alongside its
temperature and humidity values. This array is stored in the
component's reactive state (sensorData), allowing the component to
dynamically update the displayed information. The template renders
this data in an unordered list format, ensuring that each data point is
clearly presented to the user. Additionally, the component includes
error handling to log any issues that occur during the data-fetching
process, enhancing reliability and ease of debugging. Overall, the
component effectively integrates real-time data retrieval with
user-friendly presentation.

3.4. Update App.vue to Use the Component. In your App.vue, update the
code by adding the Sensor Data component.
<template>
<SensorData />
</template>

<script>
import SensorData from
"./components/SensorData.vue";
export default {
name: "App",
components: {
SensorData,
},
};
</script>
3.5. Run the application by starting the Vue Server.

npm run dev


4. Optional - Notification Feature: Implement Firebase Cloud Messaging
(FCM) to send notifications to a mobile app or another client when certain
sensor thresholds are reached.

7. Conclusion:

What conclusion can you make based on the activity?


In a nutshell, Firebase Admin SDK is essential in proper data and authentication
management in IoT applications. Using a NodeMCU that communicates to a Firebase
backend, one can be assured of the secure transfer of data, which will, in turn, preserve
information integrity-the most critical feature of any connected device.

This simple Node.js server deployment by using Firebase Admin streamlines the data
coming from IoT devices and allows for several layers of security during the process.
Real-time data management is also possible, such as in devices that may easily send
and receive information.

Furthermore, to safely store and retrieve information using Firebase, it guarantees to


enable the NodeMCU devices to work dependently within an ecosystem. Along with
improving the overall operation of IoT applications, such integration fosters user
confidence and reliability in data security at large. Ultimately, applying Firebase Admin
SDK with the help of a NodeMCU and a Node.js backend establishes a robust platform
through which the management of IoT data becomes straightforward yet secure.

EMBEDDED LAB 6 - Google Drive


8. Assessment (Rubric for Activity):

Intended Unsatisfact Satisfact Exempla


Score
Learning ory 1 ory 2 ry 3
Outcomes
Configure NodeMCU is NodeMCU is NodeMCU is fully
theNodeMCU for fully configured for configured for secure
Secure Data configured for data data transmission with
Transmission secure data transmission with
clear, secure
transmission minor security
with clear, gaps or setup communication to the
secure issues. backend.
communicatio
n to
the backend.
Setup and Backend is Backend is Backend is fully
Deploy the fully deployed deployed and deployed and securely
Node.js Backend and securely communicates communicates with
communicates with Firebase, Firebase, handling all
with Firebase
with Firebase, but there are data from IoT devices.
Admin minor issues in
handling all
data from IoT handling data.
devices.

Data Storage andData is Data is stored Data is securely


Retrieval from securely and retrieved stored and retrieved
Firebase stored and with minor gaps from Firebase with
retrieved from in security or effective handling of
Firebase with data handling. incoming NodeMCU
effective data.
handling of
incoming
NodeMCU
data.
Other comments/observation: Total
Score
RATING = (total score) x
100% 9

Evaluated by: Date:

Printed Name and Signature of Faculty Member

You might also like