Laboratory Activity No. 6 - Integrating Firebase Admin With NodeMCU With VueJs Web App Version 2
Laboratory Activity No. 6 - Integrating Firebase Admin With NodeMCU With VueJs Web App Version 2
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.
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
npm init -y
const serviceAccount =
require('./path-to-your-service-account-file.json
'); // Path to your service account key JSON file
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);
}
});
node server.js
{
"temperature": 22.5,
"humidity": 60
}
7. Go to your Firebase Real-Time Database then you should see the changes
in database value, like this:
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>
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.
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.
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
admin.initializeApp({
credential:
admin.credential.cert(serviceAccount),
databaseURL: process.env.FIREBASE_DATABASE_URL,
});
const db = admin.database();
const app = express();
app.use(bodyParser.json());
// 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);
<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.
7. Conclusion:
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.