Hi all, today we will learn how to create an Express Server using Nodejs, Front-end HTML landing page using Angular, to manipulate server data and We will use ESP8266 to communicate to the server and fetch results.
Before starting to look at the code, please make sure you have node.js installed in your system.
1. Creating Express Server:
At first we need to create package.json file for the Express poject, so open the command prompt and upon going to the desired folder path, run the command
npm init -y.
This will create a blank package.json file for your express server project.
Then, we need to install dependencies for the project, for this project we require express, body-parser, cors dependencies, so we will run the following command:
npm install --save express body-parser cors
This will download, and install the dependencies in the folder named node_modules and also list them under the package.json file.
Now we are ready to write our server code:
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const port = 3000;
const app = express();
app.use(cors(port));
app.use(bodyParser.json({ type: 'application/json' }));
var led = true;
app.post('/',(req,res) =>{// Angular service will hit this api to toggle the led value console.log(led);
console.log("in");
res.set('Content-Type', 'text/plain');
res.send({value : !led});
led = !led;//every time we click the button value is toggled console.log("out");
console.log(led);
})
app.get('/api',(req,res)=>{// used to receive data from server
// esp8266 will hit this api to get the led status
console.log("in");// for testing purpose only
console.log(led);// log the value of led onto console
res.set('Content-Type', 'text/plain');// set the headers
if(led){ res.send({value : 1});// if led is on or true, send value=1
} else{ res.send({value : 0});//else send value = 0
}
console.log(led);
console.log("out");// log the console.
})
//this tells the server to listen to request on port 3000
// and host can be either localhost or 192.168.43.161
app.listen(port,'192.168.43.161' | 'localhost', function(){
console.log("Server running on localhost port : " + port);
})
After writing the code, we will save the file as server.js and run it using the following command:
node server
This will start the server at localhost:3000
2. Creating Angular Code for Front End:
Now to change the value of LED variable in the server, we need a mechanism to connect to it first. Here we will use Angular framework to connect to the server we just made and toggle the value of Led on each Button Click event.
Just like we created Express server, we will use of node command line tool to create Angular project. So after navigating to your desired directory, open command prompt and type in the following command:
npm install --save @angular/cli@latest
// This is used to install angular cli latest version
ng new IOT
// This command is used to create new Angular project with name IOT
Once the project is created, change your directory using cd IOT command.
Now once you come inside your project folder, we will edit the app.component.html file to display our desired HTML output on browser.
<div >
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<a class="navbar-brand" href="#">Navbar</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">LED 1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">LED 2</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">LED 3</a>
</li>
</ul>
</div>
</nav>
</div>
<div class="container">
<div class="btn-group col-xs-3" >
<button class="btn btn-primary btn-block" type="submit" name="submit" value="1" (click)="onSubmit1()">LED 1 </button>
</div>
<br>
<br>
<div class="btn-group" > {{response}}</div>
</div>
You can see in the html, with the Button element we Binded the Click event.
<button class="btn btn-primary btn-block" type="submit" name="submit" value="1" (click)="onSubmit1()">LED 1 </button>
What this does it, whenever we will Click the button, it will read the Click Event, and call the onSubmit1() function. This function is defined in app.component.ts file.
In app.component.ts file, we will declare the following function
import { Component } from '@angular/core';
import { ApiService } from './api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'iot';
response : boolean ;
constructor(private _apiservice : ApiService){}
onSubmit1(){
this._apiservice.callLed().subscribe((res)=>{// calls the api service
console.log(res.value);
this.response = res.value;//either true or false
});
}}
In the function you can see, we are callling a Service called ApiService which we imported using import { ApiService } from './api.service';
and injected into the class using constructor(private _apiservice : ApiService){}
and we called the service using
this._apiservice.callLed().subscribe((res)=>{// calls the api service
console.log(res.value);
this.response = res.value;//either true or false
});
What this does is, it calls the function in the service, and subscribes to the observable received from the service, which is then manipulated to fetch the response.
Now we will create the api.service.ts class using command prompt. Type in the following command:
ng g s api this will tell the angular to create the service named ApiService. and it we will write the following code into it:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({ providedIn: 'root'})
export class ApiService {
private _url = "http://localhost:3000/";
constructor(private _http : HttpClient) { }
callLed(){
return this._http.post<any>(this._url,{});
}
}
In the service, we will use HttpClient and HttpHeader modules, so we will import it first. Then, we will declare a variable which contains the url we need to hit, to post the request. we will do this by following statement:
private _url = "http://localhost:3000/";
Also we will inject the HttpClient module in the constructor:
constructor(private _http : HttpClient) { }
Finally we will declare a function to send a POST request to the above mentioned url. In this case it will just be an empty request as we just need to toggle the led value.
callLed(){
return this._http.post<any>(this._url,{});
}
Now our front-end code is complete, we can run this application by using the command
ng serve
It will start our application and by default, it will be accessible on localhost:4200 in the browser. Make sure to start your server also, in order for the service to communicate with the server.
3. ESP8266 Code:
Now, we need to code our ESP8266 module so as to connect it to our network, and then send request to our server and receive data from it.
Following is the code for ESP8266 module:
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#define USE_SERIAL Serial
ESP8266WiFiMulti WiFiMulti;
void setup() {
USE_SERIAL.begin(9600);
// USE_SERIAL.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
for(uint8_t t = 4; t > 0; t--) {
// USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
WiFi.mode(WIFI_STA);
// provide our SSID and Password for WIFI network connection
WiFiMulti.addAP("Your SSID ", "Your Password");
}
void loop() {
// wait for WiFi connection
if((WiFiMulti.run() == WL_CONNECTED)) {
HTTPClient http;
USE_SERIAL.println("Sending Get Request to Server.......");
http.begin("http://192.168.43.161:3000/api"); //HTTP URL for hosted server(local server)
//192.168.43.161 - HOST PORT: 3000 and /api is the target api we need to hit to get response
int httpCode = http.GET();
// USE_SERIAL.println("After GET Request");
// httpCode will be negative on error
if(httpCode > 0) {
if(httpCode == HTTP_CODE_OK) {
//HTTP_CODE_OK means code == 200
String payload = http.getString();// gives us the message received by the GET Request
USE_SERIAL.println(payload);// Displays the message onto the Serial Monitor
}
} else {
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
delay(5000);// repeat the cycle every 5 seconds.
}
Just make sure to provide your IPv4Address in http.begin("http://192.168.43.161:3000/api");
This
you can get by typing ipconfig /all
in your command prompt. Also make sure to provide the same address in your server.js code at following location: app.listen(port,'192.168.43.161' | 'localhost', function(){
Also provide your network SSID and password here:
WiFiMulti.addAP("Your
SSID", "Your
Password");
Now upload the code to ESP8266, then it will connect to your provided network with the credentials provided. Also make sure to connect your laptop/PC to the same network for the complete code to work properly. Thus, when you will open your serial monitor in Arduino IDE, you can see the current value of LED as 1 or 0.
Now try clicking the button on UI and check the value in Serial monitor again, It will change accordingly.
You can view the working of the project here:Make sure to note following important points:
Thus, we finally completed the project. Hurrayy.
Stay Connected for more exciting projects like these. Thanks and Happy Learning.
Comments