Scan QR code with client/server model using Node.js

QR code is an image on client side. It is capturing by camera and sends to the server to read its data. So this work can be divided in to three parts.

  1. Capture image on client side
  2. Transfer image data to server
  3. Analyse image data on server and send output to client

 

Capture Image Using JavaScript & HTML5

HTML5 to the rescue. It might not be apparent, but the rise of HTML5 has brought a surge of access to device hardware. Geolocation (GPS), the Orientation API(accelerometer), WebGL (GPU), and the Web Audio API (audio hardware) are perfect examples. These features are ridiculously powerful, exposing high level JavaScript APIs that sit on top of the system’s underlying hardware capabilities.

Taking screenshots

The <canvas> API’s ctx.drawImage(video, 0, 0) method makes it trivial to draw<video> frames to <canvas>. Of course, now that we have video input via getUserMedia(), it’s just as easy to create a photo booth application with realtime video:

HTML5

Screenshot (54)

JavaScript


function handleError(error) {
console.error(‘navigator.getUserMedia error: ‘, error);
}
const constraints = {video: true};

(function() {
const captureVideoButton =
document.querySelector(‘#screenshot .capture-button’);
const screenshotButton = document.querySelector(‘#screenshot-button’);

const img = document.querySelector(‘#screenshot img’);
const video = document.querySelector(‘#screenshot video’);

const canvas = document.createElement(‘canvas’);

captureVideoButton.onclick = function() {
navigator.mediaDevices.getUserMedia(constraints).
then(handleSuccess).catch(handleError);
};

screenshotButton.onclick = video.onclick = function() {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext(‘2d’).drawImage(video, 0, 0);
// Other browsers will fall back to image/png
img.src = canvas.toDataURL(‘image/png’);

//alert(“save image”);
};

function handleSuccess(stream) {
screenshotButton.disabled = false;
video.srcObject = stream;
}
})();

Full code: https://github.com/shehanshaman/Assignment/blob/master/tutorial/Capturing%20video.html

Transfer Image Data to server from client

Captured image saved on browser dynamically(local).

Client

img.src has base64 encoded data in the format of 
data:image/jpeg;base64,/9j/4AAQSkZJRgABA...

So you need to get rid of the mime type and encoding information at the 
front.
var contents = img.src.split(',')[1];

Now you can send this base64 encoded data to server.
var xhr = new XMLHttpRequest();

xhr.open("POST", "http://localhost:3000/identify/qr", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
    value: contents
}));

 

Server

Since you’re receiving base64 encoded data, you can convert it buffer and write to file:

fs.writeFile('public/images/tmp/qr.jpeg',JSON.stringify(req.body.value), 'base64' , function (err) {
    if (err) throw err;
    console.log('Saved!');
})

 

Scan image data and get output

Installation

npm install --save jimp                                                     

npm install qrcode-reader

var Jimp = require(“jimp”);
var fs = require(‘fs’);
var QrCode = require(‘qrcode-reader’);

var buffer = fs.readFileSync(‘qrcode.jpg’);

Jimp.read(buffer, function(err, image) {
if (err) {
console.error(err);
// TODO handle error
}
var qr = new QrCode();
qr.callback = function(err, value) {
if (err) {
console.error(err);
// TODO handle error
}
console.log(value.result);
console.log(value);
};
qr.decode(image.bitmap);
});

Full code: https://github.com/shehanshaman/Assignment/blob/master/tutorial/readqr.js

 

Screenshot (52)Screenshot (53)

How to add mongoDB to Heroku using Node.js

What is Heroku?

Image result for heroku without background

Heroku is a cloud platform as a service supporting several programming languages which are Java, Node.js, Scala, Clojure, Python, PHP, and Go. It supports many databe programs which are mongoDB, Mysql, PostgreSQL etc.

What is mongoDB?

MongoDB is a free and open-source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schemata. MongoDB is developed by MongoDB Inc., and is published under a combination of the Server Side Public License and the Apache License. MongoDB can be host on mLab or compose mongoDB.

What is mLab?

Image result for mlab without background

mLab is a fully managed cloud database service that hosts MongoDB databases. mLab runs on cloud providers Amazon, Google, and Microsoft Azure, and has partnered with platform-as-a-service providers. Why I choose it ? Because it is free up to 496MB on heroku.

Screenshot (36)

 

  • Go to the Heroku dashboard

Screenshot (37)

  •  Select your app & Click on Find more add-ons on app’s resources tab

Screenshot (38)

  •  Select mLab MongoDB

Screenshot (39)

  • Install mLab MongoDB

Screenshot (40)

 

screenshot-42.png

  • Click on mLab link

Screenshot (43)

  • mLab created database

Screenshot (44)

Getting your connection URI

The mLab add-on contributes one config variable to your Heroku environment:

MONGODB_URI

To connect using a driver via the standard MongoDB URI:
mongodb://<dbuser>:<dbpassword>@ds151393.mlab.com:51393/heroku_q472zkvg

The URI contains all the MongoDB connection information you will need to connect to your database. Most client libraries support using the URI directly. However, some libraries will require pulling the components of the URI apart. In case you need to do that for your library, the MONGODB_URI is in the format below.

URI format for Single-node plan:

mongodb://dbuser:dbpass@host:port/dbname

URI format for Cluster plan:

mongodb://dbuser:dbpass@host1:port1,host2:port2/dbname

Screenshot (45)

 

  • Change url variable

Screenshot (46)

  • Change database name of local file’s database name to mLab database name(heroku_***)

screenshot-47.png

Screenshot (48)

  • Commit & push to heroku
  • Create collections and add data to the database

Screenshot (49)

 

Simple Sorting Algorithms

Implementation of sorting algorithms

  1. Bubble Sort

1.PNG

2. Selection Sort

2.PNG

3. Insertion Sort

12.PNG

Out of these three algorithm which one is better? How can you measure this?

Important influence factors to the performance of a sorting algorithm can be separated into two main parts:

  • Memory Consumption of the algorithm
  • Total runtime of an algorithm

 

In case the program is to some case a program which interacts with others also the response time is a very important fact of the performance of a program.

How to measure Memory Consumption?

The total used / free memory of an program can be obtained in the program via java.lang.Runtime.getRuntime(); The runtime has several met

3.PNG

hod which relates to the memory. The following code example demonstrate its usage.

 

 

 

 

 

  • Calculate memory consumption for above sorting algorithms using above function for 100 arrays.

4.PNG

 

 

 

 

 

 

 

 

 

  • Bubble sort algorithm has the minimum number of standard deviation

5.PNG

  • But Insertion sort algorithm has the minimum memory usage. (298.98KB)
  • Difference of standard deviation between bubble and insertion has 9.452, but average has 136. So, insertion algorithm is good for memory consumption

6.PNG

Performance of algorithm according to memory usage

From https://en.wikipedia.org/wiki/Sorting_algorithm

7.PNG

How to measure runtime of an algorithm?

Use System.nanoTime(); to get the start time and the end time and calculate the difference.8.PNG

  • Calculate run-time for above sorting algorithms using above function for 100 arrays.

9.PNG

 

Summary

10.PNG

Conclusion

The response time is a very important fact of the performance of a program. So, insertion algorithm has the minimum run time.

Considering runtime and memory consumption, insertion algorithm is the best sorting algorithm.

 

Performance of algorithm according to response time

From https://en.wikipedia.org/wiki/Sorting_algorithm

11.PNG

 

Google Home With Arduino | NodeMCU

In this article I am showing you how to connect your device to google assistant or amazon alexa via NodeMCU.

tp-link1-1000x500

Step 1: Collect stuff

  • NodeMCU esp8266
  • Realy Module
  • Wifi Connection
  • 5v Power Supply

Step 2: Assemble

  • I used two way relay module and Connected their in pins to D5 & D6 of nodemcu board.
  • Connect the nodemcu to power supply through Vin pin.

Step 3: Adafruit & ifttt

Adafruit

  1. Create account in adafruit.io
  2. Create a new dashboard

adafruit dashboard

3.Create two feeds

  • Click on create a new block

Capture2

  • Then click on Toggle block

Capture4

  • Create two feeds “light1” & “light2”

Capture5

  • Then select one feed and go to next step

Capture6

  • Then change their on and off text

Capture7

  • Do this for light2 also and finally you will have bellow interface at the created dashboard

Capture8

 

IFTTT

  1. Create account in ifttt.com
  2. Create new applet(Turn on light 1)

10

11

3.Then click +this link and select google assistant in services

12

4.Then give google voice command and its reply

13

5.Next choose adafruit (send data to Adafruit IO)

14

6.Then select light1 in the feed name and 1 for the data(To turn on light)

  • 1 – ON
  • 0 – OFF

15

Create applet for following commands as shown above 

  • Turn off light 1
  • Turn on light 2
  • Turn off light 2

 

Step 4: Code

 

Step 5:

This slideshow requires JavaScript.

 

Tutorial Video

 

HASH TABLES & HASH FUNCTION COMPARISON

Read the words in two sample files and construct two hash tables. Then see how the words are distributed.

Then target is finding  best hash function for this particular purpose

Words Distribution

1

 

Hash Function 1

Hash Function 2

  sample-text1 sample-text2 sample-text1 sample-text2

Bucket 1

96 27 236 321

Bucket 2

129 110 199 123

Bucket 3

963 342 573 190

Bucket 4

967 611 328 211

Bucket 5

480 452 369

178

Bucket 6 656 265 315

165

Bucket 7 454 197 837

334

Bucket 8 331 143 829

374

Bucket 9 209 69 285

170

Bucket 10

175 55 489

205

  • Total words in sample-text1 : 4460
  • Total words in sample-text2 : 2271

 

Hash Functions

public int HashFun(String s,int buckets,int hashFunNo){

        int key = 0;

        if(hashFunNo==1){

            key = s.length() % buckets; //Hash function 1

          }else if(hashFunNo == 2){

            //Hash function 2

            int sum=0;

            char[] chars = s.toCharArray();

            int i=0;

            for(;i<chars.length;i++){

                sum += chars[i];

            }

      }

        return key

 }

Different number of buckets

Hash Function 1

2

3.PNG

4

  • Smallest searching time found in 20 bucket hash function but their standard deviation is more than 5 buckets, so 5 bucket hash method is good for the hashing.

Hash function 2

5

6

7

  • 2nd hash function’s standard deviation is less than first hash function’s standard deviation for all buckets.
  • Considering above all hash functions, minimum standard deviation found in 5 bucket hash function. So 2nd hash function is good for hashing.

 

Different number of hash functions

8

9

  • 2nd hash function’s searching time is more than 1st hash function’s searching time.
  • Hash function’s standard deviation must be smallest to get perfect hash function performance.
  • Considering above hash functions, 2nd function standard deviation is less than 1st function, so 2nd hash function is the best hash function for these purposes.

 

Different text files

10

11

Control Things Using Remote

Switch on and off lights (any kind of electronic device) using existing remote control with Arduino.

Screenshot (12).png

 

Step 1 : Collect Stuff

  • Arduino board(I used pro mini)
  • Relay module
  • IR receiver

 

Step 2 : Assemble

Screenshot (23).png

There are many different manufacturers of IR Receivers and some have different pin-outs:

IR-Receiver

 

Step 3 : Code

First, we have to identify the remote key’s values. For that upload this code (IR_CODE_DECO).

 

Step 4 : Identify remote button

Screenshot (25).png

Step 5 : Control Stuff

Then change remote key values on code. There I used 12 key values in 3 remote for control 4 devices(bulbs).

Step 6: Finishing & Testing

 

Send GPS location to server using GSM module

We are using SIM808 GSM module and now sending longitude and latitude of the device to main server’s database (000webhost).

SIM808 GSM Module

SIM808 module is a GSM and GPS two-in-one function module. It is based on the latest GSM/GPS module SIM808 from SIMCOM, supports GSM/GPRS Quad-Band network and combines GPS technology for satellite navigation

pasted-image-0-e1530125650110.png

We write function called getGPSCOR(), It wants meter ID and password then it will get latitude and longitude and sent those information to the main server using sendGPS() function.

void getGPSCOR(String id, String pwd) ;

void sendGPS(char * lat, char * lon, char * id , char * pwd) ;

More Details