- Overview
- Getting Started
- Project Structure
- Key Technologies and Packages
- Running the Project
- Working with the Codebase
- Error Handling
- Logging
- Version Control with Git
- Best Practices
- Debugging Tips
- Additional Resources
- Testing Firebase Directory
HomAlert is an advanced Smart Home Emergency Notification System designed to safeguard households by detecting a wide array of potential emergencies, such as fires, floods, gas leaks, and unauthorized intrusions. The system integrates strategically placed sensors throughout the home, which are interconnected through a central processing unit. The system uses ESP32 due to its robust processing capabilities and built-in Wi-Fi/Bluetooth functionalities. Real-time monitoring and rapid dissemination of alerts are achieved via a user-friendly mobile app or web dashboard, providing early warnings and actionable advice to mitigate risks.
- Vs Code
- Node.js and npm
- Firebase account with configured Realtime Database(Optional if you are interested)
- Git
Check the Section 12 for help! Note: The Git commands can be executed using Git Bash, CMD, or PowerShell.
-
Clone the Repository
git clone https://github.com/ChrysKoum/HomAlert.git cd HomAlert
-
Install Dependencies
npm install
-
Set Up Environment Variables
Create a
.env
file in the root directory and add your Firebase credentials.cp .env-example .env
Fill in the values in the
.env
file with your Firebase configuration:FIREBASE_API_KEY=your_api_key FIREBASE_AUTH_DOMAIN=your_auth_domain FIREBASE_DATABASE_URL=your_database_url FIREBASE_PROJECT_ID=your_project_id FIREBASE_STORAGE_BUCKET=your_storage_bucket FIREBASE_MESSAGING_SENDER_ID=your_messaging_sender_id FIREBASE_APP_ID=your_app_id FIREBASE_MEASUREMENT_ID=your_measurement_id
Tip: This Configurations will need to change. So, you will create Firebase Project, then Web Application to take all the configurations except the FIREBASE_DATABASE_URL. Then create also a realtime firebase database to get the FIREBASE_DATABASE_URL. You will need to create Firebase Auth Service and accept email-password credentials.
-
Set Up Environment Variables Make a logs folder in the main directory with 2 files inside the combined.log and error.log.
-
Run the Application
npm start
The application will start running on
http://localhost:3005
.
Nodemon is used to automatically restart the server when changes are detected. The application can be started with Nodemon using the start
script defined in package.json
.
npm start
HomAlert/
├── .vscode/
│ ├── settings.json
├── controllers/
│ ├── authController.js
│ ├── dashboardController.js
├── Firebase/
│ ├── firebaseAuth.js
│ ├── firebaseConfig.js
├── logs/
│ ├── combined.log
│ ├── error.log
├── middleware/
│ ├── auth.js
│ ├── errorHandler.js
│ ├── logger.js
├── public/
│ ├── assets/
│ │ ├── icons/
│ │ │ ├── sign_up_icon.png
│ │ ├── logo/
│ │ │ ├── logo_transparent_without_text.png
│ │ ├── our_team/
│ │ ├── team_member_1.jpg
│ │ ├── team_member_2.jpg
│ ├── javascripts/
│ │ ├── main.js
│ ├── stylesheets/
│ │ ├── style.css
├── routes/
│ ├── index.js
├── utils/
│ ├── firebaseUtils.js
│ ├── format.js
│ ├── validation.js
├── views/
│ ├── auth/
│ │ ├── forgot-password.ejs
│ │ ├── sign-in.ejs
│ │ ├── sign-up.ejs
│ ├── dashboard/
│ │ ├── dashboard.ejs
│ │ ├── profile-page.ejs
│ ├── layouts/
│ │ ├── boilerplate.ejs
│ ├── partials/
│ │ ├── footer.ejs
│ │ ├── navbar.ejs
│ │ ├── join-us.ejs
│ │ ├── testimonials.ejs
│ ├── errors/
│ │ ├── 404.ejs
│ │ ├── 500.ejs
│ ├── about-us.ejs
│ ├── contact-us.ejs
│ ├── faq.ejs
│ ├── home.ejs
│ ├── product.ejs
│ ├── test.ejs (will be removed only for development help)
├── .env-example
├── .gitignore
├── app.js
├── package-lock.json
├── package.json
├── README.md
├── server.js
- .vscode/: Contains Visual Studio Code settings.
- controllers/: Contains logic for handling requests for different routes.
authController.js
: Handles authentication-related logic.dashboardController.js
: Manages dashboard-related logic.
- Firebase/: Manages Firebase configurations and utilities.
firebaseAuth.js
: Sets up Firebase Authentication.firebaseSetup.js
: Contains Firebase configuration setup.firebaseUtils.js
: Contains utility functions for Firebase operations.
- middleware/: Contains middleware functions for request handling.
auth.js
: Middleware for authentication checks.errorHandler.js
: Middleware for error handling.logger.js
: Middleware for logging requests.
- public/: Contains static assets like images, JavaScript files, and stylesheets.
- routes/: Defines the main application routes.
index.js
: Main route definitions.
- utils/: Contains utility functions for validation, formatting, and Firebase operations.
validation.js
: Utility functions for validating user inputs.format.js
: Utility functions for formatting data.firebaseUtils.js
: Utility functions for Firebase operations.
- views/: Contains EJS templates for rendering HTML pages.
auth/
: Templates related to authentication (e.g., sign-in, sign-up).dashboard/
: Templates related to the dashboard.layouts/
: Layout templates.partials/
: Reusable partial templates (e.g., navbar, footer).- Main pages (e.g., home.ejs, dashboard.ejs, contact-us.ejs).
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine. It is used to build scalable network applications.
Express is a fast, unopinionated, minimalist web framework for Node.js. It is used to create the server and handle routing.
EJS (Embedded JavaScript) is a simple templating language that lets you generate HTML markup with plain JavaScript. Read more Here
Firebase is a platform developed by Google for creating mobile and web applications. It provides a variety of tools and services to help you develop high-quality apps.
- firebase: This is the client-side Firebase SDK.
Winston is a logger for just about everything. It is a versatile logging library for Node.js applications.
Bootstrap is a popular framework for building responsive, mobile-first websites with CSS, JavaScript, and HTML.
To run the project locally:
-
Start the server
npm start
-
Open your browser
Navigate to
http://localhost:3005
to see the application running.
Controllers handle the logic for different routes.
- authController.js: Handles authentication-related logic.
- dashboardController.js: Manages dashboard-related logic.
Manages Firebase configurations and utilities.
- firebaseAuth.js: Sets up Firebase Authentication.
- firebaseConfig.js: Contains Firebase configuration setup.
- firebaseFirestore.js: Manages Firestore interactions.
Middleware functions for request handling.
- auth.js: Middleware for authentication checks.
- errorHandler.js: Middleware for error handling.
- logger.js: Middleware for logging requests.
Contains static assets like images, JavaScript files, and stylesheets.
Defines the main application routes.
- index.js: Main route definitions.
Utility functions for validation, formatting, and Firebase operations.
- firebaseUtils.js: Functions for Firebase operations.
- format.js: Functions for formatting data.
- validation.js: Functions for validating user inputs.
Contains EJS templates for rendering HTML pages.
- auth/: Templates related to authentication (e.g., sign-in, sign-up).
- layouts/: Layout templates.
- partials/: Reusable partial templates (e.g., navbar, footer).
- errors/: Error pages (404 and 500).
- home.ejs: Home page template.
Errors are handled using middleware. There are specific templates for 404 and 500 errors in the views/errors
directory.
Winston is used for logging. Logs are stored in the logs
directory.
- combined.log: Contains both request and error logs.
- error.log: Contains
only error logs.
Note: The Git commands can be executed using Git Bash, CMD, or PowerShell.
-
Pull Latest Changes from Remote Repository
git pull
-
Add Changes to Staging
git add .
-
Check Status of the Repository
git status
-
Commit Changes
git commit -m "Your descriptive commit message"
-
Push Changes to Remote Repository
git push
-
Create a New Branch
To create a new branch, use the following command:
git checkout -b <your-name>
Replace
<your-name>
with your actual name to create a branch namedyour-name
and switch to it. -
Push the New Branch to Remote
Once you have made your changes and committed them, push the new branch to the remote repository:
git push -u origin <your-name>
-
Switch to the Main Branch
Ensure you are on the main branch before pulling the latest changes:
git checkout main
-
Pull the Latest Changes from Main
Pull the latest changes from the remote main branch:
git pull origin main
-
Merge Main into Your Branch
Switch back to your branch and merge the latest changes from main:
git checkout <your-name> git merge main
-
Identify Conflicts
During the merge process, Git will notify you of any conflicts. Open the conflicting files to identify the conflict markers:
<<<<<<< HEAD Your changes ======= Changes from main >>>>>>> main
-
Resolve Conflicts
Edit the files to resolve the conflicts, choosing which changes to keep. Remove the conflict markers after resolving.
-
Mark Conflicts as Resolved
After resolving the conflicts, add the resolved files to the staging area:
git add <file_name>
-
Complete the Merge
Complete the merge process by committing the resolved changes:
git commit
By following these steps, you can effectively create new branches, stay up-to-date with changes from the main branch, and resolve any merge conflicts that arise. Make sure to replace <your-name>
with your actual name when creating and managing your branches.
The GitHub extension in Visual Studio Code (VS Code) makes it easier to manage your GitHub repositories directly from the editor. Here's a guide on how to use it:
-
Open VS Code Extensions View:
- Click on the Extensions icon in the Activity Bar on the side of the window or press
Ctrl+Shift+X
.
- Click on the Extensions icon in the Activity Bar on the side of the window or press
-
Search for GitHub Extension:
- Type
GitHub
in the search bar and look for theGitHub Pull Requests and Issues
extension by Microsoft.
- Type
-
Install the Extension:
- Click the
Install
button to add the extension to your VS Code.
- Click the
-
Open the Command Palette:
- Press
Ctrl+Shift+P
to open the Command Palette.
- Press
-
Sign In:
- Type
GitHub: Sign In
and select the command. Follow the prompts to authenticate and authorize VS Code to access your GitHub account.
- Type
-
Open the Command Palette:
- Press
Ctrl+Shift+P
to open the Command Palette.
- Press
-
Clone Repository:
- Type
Git: Clone
and select the command. Enter the URL of the GitHub repository you want to clone. Choose a local directory where you want to save the repository.
- Type
-
Create a Branch:
- Open the Source Control view by clicking the Source Control icon in the Activity Bar or pressing
Ctrl+Shift+G
. - Click on the
...
menu and selectBranch: Create Branch
. - Enter the new branch name and press
Enter
.
- Open the Source Control view by clicking the Source Control icon in the Activity Bar or pressing
-
Switch Branches:
- Click on the current branch name in the status bar at the bottom-left corner of VS Code.
- Select the branch you want to switch to from the list.
-
Stage Changes:
- Open the Source Control view by clicking the Source Control icon or pressing
Ctrl+Shift+G
. - You will see a list of changes. Click the
+
icon next to the files you want to stage or click+
next to Changes to stage all changes.
- Open the Source Control view by clicking the Source Control icon or pressing
-
Commit Changes:
- Enter a commit message in the text box at the top of the Source Control view.
- Click the checkmark icon to commit the changes.
-
Push Changes:
- Click the
...
menu and selectPush
to push your changes to the remote repository.
- Click the
-
View Pull Requests:
- Click on the GitHub Pull Requests icon in the Activity Bar to view a list of pull requests in the current repository.
- You can click on a pull request to view its details and make comments.
-
Create a Pull Request:
- Click the
+
icon next to the Pull Requests heading. - Follow the prompts to create a new pull request from your current branch.
- Click the
-
Manage Issues:
- Click on the GitHub Issues icon in the Activity Bar to view and manage issues in the current repository.
- You can create new issues, comment on existing issues, and close issues directly from VS Code.
By using the GitHub extension in VS Code, you can streamline your workflow, manage repositories more effectively, and collaborate with your team seamlessly.
-
Consistent Naming Conventions: Use camelCase for variables and functions, PascalCase for classes.
// Bad var my_variable = 10; // Good var myVariable = 10;
-
Commenting and Documentation: Add comments and documentation to explain complex logic.
/** * Calculates the sum of two numbers. * @param {number} a - The first number. * @param {number} b - The second number. * @returns {number} - The sum of a and b. */ function sum(a, b) { return a + b; }
-
Avoid Magic Numbers: Use constants instead of hardcoding numbers.
// Bad for (let i = 0; i < 7; i++) { // ... } // Good const DAYS_IN_WEEK = 7; for (let i = 0; i < DAYS_IN_WEEK; i++) { // ... }
-
Environment Variables: Always use environment variables for sensitive data.
FIREBASE_API_KEY=your_api_key
-
Input Validation: Validate all user inputs to prevent SQL injection and other vulnerabilities.
const validateInput = (input) => { if (typeof input !== "string") { throw new Error("Invalid input"); } };
-
Authentication and Authorization: Ensure that routes are protected and only accessible to authenticated users.
const isAuthenticated = (req, res, next) => { if (req.isAuthenticated()) { return next(); } res.redirect("/login"); };
-
Caching: Use caching strategies to improve performance.
const cache = new Map(); const getData = (key) => { if (cache.has(key)) { return cache.get(key); } const data = fetchDataFromDatabase(key); cache.set(key, data); return data; };
-
Database Optimization: Optimize queries and use indexing.
CREATE INDEX idx_user_id ON users(user_id);
-
Create a
launch.json
FileIn VS Code, go to the Debug view (click the Debug icon or press
Ctrl+Shift+D
), then click the gear icon to configure thelaunch.json
file. Use the following configuration:{ "version": "0.2.0", "configurations": [ { "type": "node", "request": "launch", "name": "Launch Program", "skipFiles": ["<node_internals>/**"], "program": "${workspaceFolder}/app.js" } ] }
-
Add Breakpoints
Set breakpoints in your JavaScript files by clicking in the gutter next to the line numbers.
-
Start Debugging
Press
F5
or click the green play button in the Debug view to start debugging.
- How to Use Breakpoints: Watch Video
-
Logs: Check application logs for error messages. Logs can be found in the
logs
directory (e.g.,combined.log
anderror.log
). You can also useconsole.log
statements for quick debugging.console.log("Debugging message:", variable);
-
Breakpoints: Use breakpoints to step through code and identify issues. In Visual Studio Code, you can set breakpoints in your JavaScript files and run the debugger to step through your code.
-
Inspector: Use the browser's developer tools to inspect and debug front-end issues. You can open the developer tools in most browsers with
F12
orCtrl+Shift+I
. -
Logger: Use the configured logger (Winston) to log detailed information, warnings, and errors. This helps in maintaining a clean and consistent logging strategy.
const logger = require("./middleware/logger"); logger.info("This is an info message"); logger.warn("This is a warning message"); logger.error("This is an error message");
- How to Install npm and node.js W10: Watch Video
- How to Install npm and node.js W11: Watch Video
- Git Walkthrough: Watch Video
- Why to Download Git: Watch Video
- How to connect Git with vs-code: Watch Video
- How to Install and Configure VS Code: Watch Video
- GitHub Extension for VS Code: Watch Video
- Learn a little More about Node.js: Watch Video
Didnt find what you are looking for search the docs to see how it works, youtube tutorials or ask gpt to tell you step by step what is happening
A test endpoint to check the connection with the Firebase Realtime Database. This endpoint allows you to verify that your application can successfully connect and interact with the database.
- Go to
/test
: Navigate to the/test
endpoint in your browser. - Interactive Forms and Buttons: You will find buttons and forms that allow you to:
- Register a user
- Login
- Logout
- Reset password
- Read user data
- Write user data
- Read device data
- Write device data
- Read sensor data
- Demo Data: There is a section with demo data that you can use to fill in the forms.
By interacting with the forms and buttons on the /test
page, you can easily test various functionalities and verify the connection with the Firebase Realtime Database.
By following this guide, you will have a comprehensive understanding of the HomAlert project and be able to work with it effectively. If you have any questions or need further clarification, don't hesitate to ask!!