Machine Learning In IoT By Node.js

In this article, I will tell you how to use Scikit-learn with Python scripts for IoT applications by using Node.js. First, to know more, you have to read my previous articles about IoT with Node.js. Let’s look at these articles briefly:

  1. Node.js in IoT Part-1
  2. Node.js in IoT Part-2

My first article is an introduction for IoT developers who want to use in their projects. The second one is a simple experimental project to show NoSQL+Node.js+Arduino usage together.

Now in the third article, I am going to tell you how to use Redis (NoSQL db)+ASP.NET Web API + Node.js + + Python + Arduino. I believe that it is a kind of industry 4.0 article to understand the scope of industry 4.0. that I explained previously.

What is Redis?

As defined by Wikipedia,

"Redis is an in-memory database open-source software project implementing a networked, in-memory key-value store with optional durability. Redis supports different kinds of abstract data structures, such as strings, lists, maps, sets, sorted sets, hyperlog logs, bitmaps and spatial indexes. The project is mainly developed by Salvatore Sanfilippo and is currently sponsored by Redis Labs.


The name Redis means Remote Dictionary Server. Salvatore Sanfilippo, the original developer of Redis, was hired by VMware in March, 2010. In May, 2013, Redis was sponsored by Pivotal Software (a VMware spin-off).[9] In June 2015, development became sponsored by Redis Labs.According to monthly rankings by, Redis is often ranked the most popular key-value database.Redis has also been ranked the NoSQL database in user satisfaction and market presence based on user reviews, the most popular NoSQL database in containers, and the NoSQL database among Top 50 Developer Tools & Services.

Supported languages

Many languages have Redis bindings, including: ActionScript, C, C++, C#, Chicken Scheme, Clojure, Common Lisp, D, Dart, Erlang, Go, Haskell, Haxe, Io, Java, JavaScript (Node.js), Julia, Lua, Objective-C, OCaml, Perl, PHP, Pure Data, Python, R, Racket, Ruby, Rust, Scala, Smalltalk and Tcl."

Simple usage

In C#
  1. [HttpGet]  
  2. public HttpResponseMessage GetCalculatedVal(int val1, int val2) {  
  3.         using(var redis = new RedisClient("localhost")) {  
  4.             redis.StartPipe();  
  5.             redis.StartPipeTransaction();  
  6.             redis.Set("val1", val1);  
  7.             redis.Set("val2", val2);  
  8.             object[] result = redis.EndPipe();  
  9.         }   

In the above code, you can see that setting a value inside of a key is simple in Redis. You can get the value of “val1” by using the "get" keyword using the same method.

In Python

  1. import redis  
  2. r_server = redis.Redis('localhost'#this line creates a new Redis object and  
  3. #connects to our redis server  
  4. r_server.set('test_key''test_value'#with the created redis object we can  
  5. #submits redis commands as its methods  
  6. print 'previous set key ' + r_server.get('test_key'# the previous set key is fetched   

Like in C#, you can use Redis inside the Python environment. It also is simple.

Why do we need Redis?

We use Redis because Redis can be a bridge between Node.js IoT applications that have fired Arduino com ports and Python over ASP.NET WebAPI. Also, you can use zeroMQ, RabbitMQ to make pipelines. Redis can be used as a message broker too.


We will prepare our breadboard for measuring the distance using HC-S04, which is a kind of module for proximity measurement. You have to follow the below instructions.

PingFirmata must be loaded onto Arduino-compatible boards to enable this component. PingFirmata DOES NOT APPLY TO NON-ARDUINO PLATFORMS.

The most straightforward method for enabling this module is to use the Ping I2C Backpack. If you still want/need to use a custom firmata, then the easiest way to get the firmata onto your board is to use interchange. Follow the directions mentioned below.

npm install nodebots-interchange

With your Arduino plugged in, issue the following instruction, using the serial port your arduino is plugged into. (COM3, /dev/ttyUSB0 etc).

interchange install hc-sr04 -a uno -p <port> --firmata

The latest firmware will be downloaded and installed on your board.

The final alternative is to copy and paste the source into the Arduino IDE and click the Upload button.


The above picture is simple sketching of HC-SR04 usage with Arduino Uno. We will have to add two LEDs to show the Python Machine Learning algorithm how to decide which LED will blink. We use ASP.NET Web API to send distance values to Python ML algorithms.

After that, you can see in the below image there is a handmade drawing description to teach you my logic of calling Python over Node.js. 


Python File


You can easily see that we use Redis and SciKitlearn together.

  1. Features means your accumulated data of situations; they include your previous experiences.
  2. Labels are a kind of result set; these are the descriptions of features.
  3. You have to use DecisionTree algorithms and you have to bind features and labels before predicting method.

Let’s look at the Node.js side.

  1. var five = require("johnny-five");  
  2. var unirest = require('unirest');  
  3. var board = new five.Board();  
  4. board.on("ready"function() {  
  5.     var ledgreen = new five.Led(3);  
  6.     var ledred = new five.Led(5);  
  7.     var cm = 0;  
  8.     var result = 0;  
  9.     this.repl.inject({  
  10.         led: ledgreen,  
  11.         ledred  
  12.     });  
  13.     var proximity = new five.Proximity({  
  14.         controller: "HCSR04",  
  15.         pin: "7"  
  16.     });  
  17.     proximity.on("data"function() {  
  18.         cm =;  
  19.     });  
  20.     proximity.on("change"function() {  
  21.         unirest.get('http://localhost:56842/api/CallPythonFuncForIOT/?val=' + cm).end(function(response) {  
  22.             console.log(response.body);  
  23.             result = response.body;  
  24.         });  
  25.         if (parseInt(result) == 1) {  
  26.             console.log("RED BLINK!")  
  27.             console.log('\x1b[36m%s\x1b[31m''cm:' + cm)  
  28.             ledred.blink();  
  29.             ledgreen.stop();  
  30.         } else {  
  31.             console.log("GREEN BLINK!")  
  32.             console.log('\x1b[36m%s\x1b[32m''cm:' + cm)  
  33.             ledgreen.blink();  
  34.             ledred.stop();  
  35.         }  
  36.     });  
  37. });  

If you look at calling the Web API RESTful service, there are two kinds of result call-back.

  1. proximity.on("change"function()  
  2.              {  
  3.             unirest.get('http://localhost:56842/api/CallPythonFuncForIOT/?val=' + cm)  
  4.             if (parseInt(result) == 1) {  
  5.                 // RED   
  6.             }  
  7.             lse {  
  8.                 // GREEN  
  9.             }  

RESTful service will set parameters inside of the Redis DB key-value pair. Then, it will call the Python file to run the Machine Learning decision tree algorithm by using SciKitlearn.

  1. import redis  
  2. from sklearn import tree  
  3. #features   
  4. features = [[25],[24],[23],[22],[21],[20],[19],[18],[17],[16],[15],[14],[13],[12],[11],[10],[9]]  
  5. #labels = ["green","red","green","red". . . . . ]  
  6. labels = [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0]  
  7. clf = tree.DecisionTreeClassifier()  
  8. clf =,labels)  
  9. r = redis.StrictRedis(host='localhost', port=6379, db=0)  
  10. val = r.get('valueIOT')  
  11. print (clf.predict([[val]]))  

In this article, I tried to show you how to use Node.js by using Arduino and how to call ASP.NET WebAPI RESTful service. Also, you learned how can we call Python file from C# codes. We used a HC-SR04 measurement to send distance between sensor and obstacle, and then decided which LED will blink by using Python ML decision tree algorithms.