0% found this document useful (0 votes)
4 views11 pages

Tutorial Exercise 9

This tutorial teaches how to implement conditional logic, arrays, and data visualization using Node-RED for a smart fan control system that reacts to temperature changes via MQTT. Users will learn to use if-else statements to control the fan's state, display data in a table, and visualize temperature readings in real-time. The tutorial includes detailed code explanations for function nodes that manage temperature data and its visualization.

Uploaded by

awethufana06
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

Tutorial Exercise 9

This tutorial teaches how to implement conditional logic, arrays, and data visualization using Node-RED for a smart fan control system that reacts to temperature changes via MQTT. Users will learn to use if-else statements to control the fan's state, display data in a table, and visualize temperature readings in real-time. The tutorial includes detailed code explanations for function nodes that manage temperature data and its visualization.

Uploaded by

awethufana06
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Node-RED Tutorial: Conditional Logic and Data Visualization with MQTT

Introduction

In this tutorial, we will explore three essential concepts in programming: conditional


logic, arrays and data visualization. We will use Node-RED to implement a smart fan
control system that utilizes if-else logic to control the fan's state based on temperature
values. Additionally, we will learn how to display data in a table using Node-RED's built-
in nodes. It is also assumed that data is being remotely transmitted using the MQTT
protocol. To ensure that your MQTT messages are not intercepted give your topic unique
names. It is suggested that you precede your topic name with your student number eg

12345678/FAN

How the functionality should be implemented

The user should adjust a slider that will simulate the variation of temperature. This
temperature value is then published via MQTT to a subscriber. Once received the
temperature should be checked to determine if it is above a certain threshold value. If it
is above this value it should indicate in the dashboard, “Fan On” and if below “FAN OFF”.

Also, a LED should indicate the status as well. If it is below the threshold it should be
“green” and above the threshold it should be red.

A chart and gauge should also constantly display the temperature value.

Lastly a table should constantly record the last ten values of the temperature.

Objective

By the end of this tutorial, you will:

• Understand how to implement if-else logic in Node-RED using function nodes

• Learn how to display data in a table using Node-RED's table node

• Apply conditional logic and data visualization concepts to real-world IoT


applications

Let's Get Started!

In this first part of the tutorial, we will focus on implementing the if-else logic for the
smart fan control system. We will analyze the code used in the function nodes and
understand how it controls the fan's state based on temperature values.
1. Lets start with the “Check Temperature” function node

[Link] = [Link];
if ([Link] > 25) {
[Link] = "fan_on";
[Link] = true;
} else {
[Link] = "fan_off";
[Link] = false;
}
return msg;

Here's a thorough explanation of each line in the code:

Line 1: [Link] = [Link];

• This line assigns the value of [Link] to a new property called [Link].

• In Node-RED, msg represents the message object that is being processed.

• [Link] typically contains the main data being processed, which in this case
is the temperature value.

• By assigning [Link] to [Link], we are essentially creating a new variable


[Link] to hold the temperature value.
Line 2: if ([Link] > 25) {

• This line starts an if statement that checks whether the temperature value
([Link]) is greater than 25.

• The if statement is used to make decisions based on conditions.

• In this case, the condition is [Link] > 25, which means "if the temperature is
greater than 25".

Line 3: [Link] = "fan_on";

• If the condition [Link] > 25 is true, this line assigns the string value "fan_on" to
[Link].

• This means that if the temperature is greater than 25, the message payload will be
set to "fan_on", indicating that the fan should be turned on.

Line 4: [Link] = true;

• This line assigns the boolean value true to a new property called [Link].

• The [Link] property is likely used elsewhere in the flow to control the fan's
state.

Line 5: } else {

• This line marks the end of the if statement and begins the else clause.

• The else clause is executed when the condition [Link] > 25 is false.

Line 6: [Link] = "fan_off";

• If the temperature is not greater than 25, this line assigns the string value "fan_off"
to [Link].

• This means that if the temperature is 25 or less, the message payload will be set
to "fan_off", indicating that the fan should be turned off.

Line 7: [Link] = false;

• This line assigns the boolean value false to [Link].

• This is likely used elsewhere in the flow to control the fan's state.

Line 8: }

• This line marks the end of the else clause.

Line 9: return msg;


• This line returns the modified msg object, which now contains the updated
[Link] and [Link] properties.

• The return statement is used to pass the modified message object to the next node
in the flow.

This code is essentially a simple temperature control logic that sets the fan's state based
on the temperature value.

2. Next, the “Extract Temp Node”

Let's break down the code and its purpose. It only consists of two lines of code.
[Link] = [Link];
return msg;

Code Explanation

Line 1: [Link] = [Link];

This line assigns the value of [Link] to [Link].

Line 2: return msg;

This line returns the modified msg object.

Why is this necessary?

In the previous function node, "Check Temperature", the temperature value was stored in
[Link]. However, the chart node expects the data to be plotted in [Link].

By creating this separate function node, "Extract Temp Value", we ensure that the
temperature value is extracted from [Link] and assigned to [Link], making it
compatible with the chart node's input requirements.

Question: Is this function node really necessary , or is there an alternative way to


prepare the data before sending to the chart node.
3. Finally the “Log Values” Node

const maxValues = 10;


let values = [Link]('values') || [];
[Link]([Link]);
if ([Link] > maxValues) {
[Link]();
}
[Link]('values', values);

// Format data for table node


let tableData = [];
for (let i = 0; i < [Link]; i++) {
[Link]({
"Index": i,
"Temperature": values[i]
});
}
[Link] = tableData;
return msg;

As we dive into the explanation of this function node's code, you'll encounter a
fundamental programming concept: arrays. An array is a collection of values stored in a
single variable. In this code, you'll see how arrays are used to store and manipulate
temperature readings. Get ready to learn how arrays work and how they're applied in this
specific context. Before the code for this node is explained lets briefly look at the concept
of an array.

What is an Array?

In programming, an array is a collection of values that are stored together in a single


variable. Think of an array like a shopping list or a collection of books on a shelf.

Key Characteristics of Arrays:

• Ordered collection: Arrays store values in a specific order, and each value is
assigned an index or position in the array.

• Multiple values: Arrays can store multiple values, which can be of the same data
type (e.g., numbers, strings) or different data types.

• Single variable: Arrays are stored in a single variable, making it easy to work with
the collection of values.

Example of an Array:
Suppose we want to store the names of five students in an array. We can create an array
like this:

let students = ["John", "Emily", "Michael", "Sarah", "David"];

In this example:

• students is the array variable.

• ["John", "Emily", "Michael", "Sarah", "David"] is the collection of values stored in the
array.

• Each value in the array has an index or position, starting from 0. For example,
"John" is at index 0, "Emily" is at index 1, and so on.

Why Use Arrays?

Arrays are useful when you need to work with a collection of values. They provide an
efficient way to store, manipulate, and access multiple values using a single variable.

In the context of the code for this function node, the values array is used to store a
collection of temperature readings. The array allows us to easily add new readings,
remove old readings, and access the entire collection of readings using a single variable.

In this code:

• The values variable is an array that stores a collection of temperature readings.

• The values array is initialized by retrieving the stored array from the context object
using [Link]('values'). If no array is stored, an empty array [] is used instead.

• The push() method is used to add a new temperature reading ([Link]) to the
end of the values array.

• The length property is used to check the number of elements in the values array.
If the length exceeds the maximum allowed value (maxValues), the oldest reading
is removed from the array using the shift() method.

• The updated values array is then stored back in the context object using
[Link]('values', values).

The values array serves as a buffer to store the last maxValues temperature readings.
This allows us to:

• Keep track of recent temperature readings

• Limit the number of readings stored

• Easily access and manipulate the readings


Later in the code, the tableData array is created to format the data for the table node. This
array stores objects with "Index" and "Temperature" properties, which are used to display
the temperature readings in the table.

What is meant by “context”


In Node-Red, the "context" refers to a shared memory space where you can store and
retrieve data. Think of it like a storage container where you can save variables, arrays,
objects, or even entire data structures.

The context allows you to:

• Share data between different nodes and flows

• Store data that persists even when the flow is restarted

• Access data from anywhere in your Node-Red application

When you see [Link]('values', values) in a Node-Red function, it means that the data
stored in the values variable is being saved to the context. This data can then be retrieved
later using [Link]('values').

Think of the context like a file cabinet where you can store and retrieve papers (data). Just
like how you can access a file from anywhere in the office, you can access data stored in
the context from anywhere in your Node-Red application.

Lets now provide a detailed line-by-line explanation of the code.

Here's a thorough explanation of the code:

Line 1: const maxValues = 10;

• This line declares a constant variable maxValues and assigns it the value 10.

• The const keyword means that the value of maxValues cannot be changed once
it's declared.

• In this context, maxValues represents the maximum number of temperature


values to store.

Line 2: let values = [Link]('values') || [];

• This line declares a variable values and assigns it a value using the OR operator
(||).

• [Link]('values') attempts to retrieve a value from the Node-RED context


object, which is a storage mechanism for persisting data between flows.
• If [Link]('values') returns a value (i.e., it's not null or undefined), that value is
assigned to values.

• If [Link]('values') returns null or undefined, the OR operator (||) kicks in, and
an empty array [] is assigned to values.

• This ensures that values is always an array, even if no value is stored in the context.

Line 3: [Link]([Link]);

• This line adds the current temperature value ([Link]) to the end of the values
array using the push() method.

• [Link] is assumed to be a property of the incoming message object (msg) that


contains the current temperature reading.

Line 4: if ([Link] > maxValues) {

• This line checks whether the length of the values array exceeds the maximum
allowed value (maxValues).

• If the condition is true, the code inside the if block is executed.

Line 5: [Link]();

• This line removes the first element from the values array using the shift() method.

• This is done to maintain a fixed-size array of recent temperature values, discarding


the oldest value when the array reaches its maximum size.

Line 6: [Link]('values', values);

• This line stores the updated values array in the Node-RED context object using the
set() method.

• This ensures that the array of temperature values is persisted between flows and
can be retrieved later.

Line 8: let tableData = [];

• This line declares a new variable tableData and initializes it as an empty array.

• This array will be used to store the formatted data for the table node.

Line 9: for (let i = 0; i < [Link]; i++) {

• This line starts a for loop that iterates over the values array.

• The loop variable i is initialized to 0 and incremented by 1 on each iteration, until


it reaches the length of the values array.
Line 10: [Link]({ "Index": i, "Temperature": values[i] });

• This line adds a new object to the tableData array using the push() method.

• The object has two properties: "Index" and "Temperature".

• The "Index" property is set to the current loop index i.

• The "Temperature" property is set to the corresponding temperature value from


the values array.

Line 12: [Link] = tableData;

• This line assigns the formatted tableData array to the [Link] property.

• This prepares the message object to be sent to the table node.

Line 13: return msg;

• This line returns the modified message object (msg) to the next node in the flow.

• This allows the formatted table data to be displayed in the table node.

Below is an explanation of the iterative procedure of the code:

Let's go through the code step by step, using example temperature values.

Initial Setup

We start with an empty context, and we'll use the following temperature values for this
example:

[Link] = 25

Line 1: const maxValues = 10;

We define a constant maxValues and set it to 10. This will be used later to limit the
number of temperature values we store.

Line 2: let values = [Link]('values') || [];

We try to retrieve the values array from the context. Since the context is empty, it returns
undefined. The || [] part creates a new empty array [] and assigns it to values.

values = []

Line 3: [Link]([Link]);

We add the current temperature value [Link] (25) to the end of the values array.
values = [25]

Line 4-5: if ([Link] > maxValues) { [Link](); }

We check if the length of the values array is greater than maxValues (10). Since it's not,
we skip this block.

values remains [25]

Line 6: [Link]('values', values);

We store the updated values array in the context.

Context:

values = [25]

Line 8: let tableData = [];

We create a new empty array tableData to store the formatted data.

Line 9-12: for (let i = 0; i < [Link]; i++) { ... }

We loop through the values array and create a new object for each temperature value.

i = 0:

tableData = [{ "Index": 0, "Temperature": 25 }]

Since there's only one value in values, the loop only runs once.

Line 13: [Link] = tableData;

We assign the formatted tableData array to the payload property of the msg object.

[Link] = [{ "Index": 0, "Temperature": 25 }]

Line 14: return msg;

We return the updated msg object.

That's the end of the code execution for the first temperature value (25).

Let's say the next temperature value is 26. We'll go through the same process:

[Link] = 26

We'll add 26 to the values array:

values = [25, 26]

We'll store the updated values array in the context:

Context:
values = [25, 26]

We'll create a new tableData array:

tableData = [{ "Index": 0, "Temperature": 25 }, { "Index": 1, "Temperature": 26 }]

And so on...

As we continue adding temperature values, the values array will grow, and the tableData
array will be updated accordingly.

Once the values array reaches its maximum length of 10, the oldest value will be
removed, and the newest value will be added.

You might also like