Lagos, Nigeria

Tech projects for IT leaders: How to build a home automation project with RESTful APIs in Node-RED

In the previous installment of this home lab series, we used low-code programming to connect to an API to get local weather data. Now, we’ll use that data to run our IoT devices.

API concept

Image: iStock/Melpomenem

If you haven’t read the previous installment of this tech project series, it’s worth revisiting because it explains the benefit of RESTful APIs and how to access them, and it creates an example using the Node-RED tool. In this article, we’ll extend the functionality that we built to retrieve current weather, create a data conversion function and then act on the data that we retrieved, which will tell us how to dress.

SEE: COVID-19 workplace policy (TechRepublic Premium)

Editor’s note: Catch up on the previous installments of this five-part home lab series: How to build a home lab, Software for your home lab, How and why to add Node-RED to your home lab and How to use RESTful APIs with Node-RED. Stay tuned for more tech projects for IT leaders in the future.

Reusing functionality when building programs is nothing new, but the power of RESTful APIs is that they provide a standardized and easily accessible means to access and extend that functionality. In our case, now that we can access the weather at our location, we can add rudimentary intelligence to determine if we should wear a jacket.

To accomplish this, let’s start by extracting the current temperature from our msg.payload object. We can accomplish this through the Change Function node in Node-RED. If you drag this node onto the wire connecting your Weather and Debug nodes, the wire will change to a dashed line, and releasing the mouse button will automatically insert this node into your flow, so it looks like Figure A.

Figure A

Screenshot of a Node-RED flow

By reviewing the debug panel, we can determine that the current temperature is in the Temp field of the Main Object. Since our Debug node is displaying the contents of msg.payload, adding these object names together as we go down, the hierarchy indicates that the temperature value we’d like to access is stored in msg.payload.main.temp.

To replace the contents of msg.payload with the current temperature, double-click the Change node. The node is already set up to change the contents of msg.payload; however, the default is to change it to an arbitrary string as indicated by the “a..z” selection in the dropdown. Change this to “msg.” which indicates that we want to change msg.payload to something within the msg object. In this case, we’ll change this value to msg.payload.main.temp, so your Edit window will look like Figure B (note that I also changed the name of the node).

Figure B

screenshot of API

Once I click the Deploy button to save my changes, I can click the button on the Timestamp node to activate my flow. In the Debug panel on the right, I should see the output of my previous run of the flow that provided the full weather object from Open Weather, followed by my new Debug message, which displays only the current temperature, which is highlighted in Figure C.

Figure C

screenshot of API code

You may be wondering whether Charlotte is at risk of evaporating due to what seems like an impossibly high temperature, but if you examine the Open Weather API documentation, you’ll find that all temperatures are provided in degrees Kelvin. It’s not unusual to find that APIs you access don’t always provide information in the exact format or unit of measure that you’re looking for and may require manipulation or conversion. Temperature in degrees Kelvin isn’t overly helpful for most people, and if you live in the United States or another metric laggard country, it would probably be helpful to convert this temperature into degrees Fahrenheit.

There are multiple ways to accomplish this conversion in Node-RED, but we’ll use a simple JavaScript function to perform the conversion. This will also demonstrate Node-RED’s ability to allow you to manipulate data through JavaScript, allowing for essentially unlimited possibilities for manipulating data. If talk of functions and JavaScript makes you nervous, don’t worry. Writing simple code is easy, and JavaScript is one of the easier and most common programming languages in use today, so it’s worth at least seeing some simple code.

As we did with the Change node, drop a Function node onto the wire after your change node, resulting in a flow that looks like Figure D (feel free to move the existing nodes around to make room. The order of the nodes is driven by how they’re wired not by where they appear on the screen).

Figure D

Screenshot of a Node-RED flow

The blue dots indicate that I’ve changed a node and not yet clicked the Deploy button to save those changes to the server. In this case, I added the function node and reorganized several of the other nodes. We’re going to write some basic JavaScript that will do the following:

  • Copy the temperature in Kelvin to a new variable
  • Convert the temperature to degrees celsius by subtracting 273.15 (remember those high-school physics classes?)
  • Continue to deploy high school physics (or a Google search for the formula) and convert the temperature to degrees Fahrenheit using the formula F = (C * 9/5) + 32
  • Replace the contents of msg.payload with the resulting temperature in Fahrenheit
  • Return the msg object to the flow for further processing

To do this, double-click the Function node. You’ll notice there’s already a line of code to “return msg;” which returns an updated message object back to the flow. If you don’t return a message object, the result of all your hard work in the Function node will fade from existence rather than being passed on to the rest of your flow.

Add the following code so your Function node looks like Figure E. Note that the line numbers follow the descriptive steps above, and as you experiment with programming, it’s often helpful to write down what you’re trying to do in plain English, and then create the corresponding code.

Figure E

Screenshot of a function node

Experienced programmers will quickly see there are a half dozen ways I could simplify and optimize this function, but I am aiming for clarity rather than good code.

Once you’ve checked your work, click Done to update the Function node, click the red Deploy button to save your work, and then click the button on the Timestamp node to activate your flow. In the Debug pane, you should now have your current temperature in Fahrenheit, in my case, an early spring 57.88 degrees, but your result should be close to the actual temperature in your area.

Making a decision

So far, we’ve accessed a public API to get the local weather, filtered out the data we need, and converted it into a useful format. Now it’s time to perform an action based on the data. In this case, we’ll decide whether we should wear a jacket if the temperature is below 55 degrees.

To create a decision point in our flow, we’ll add a Switch node. Drop a Switch node toward the end of your flow, and create a new wire from your conversion function to the switch node. Node-RED allows multiple wires to be created from a single point, in this case allowing us to pass the result of our temperature conversion to a Debug node, as well as our Change node. This can be useful for creating multiple Debug nodes in a complex flow, or allowing multiple processing activities to take place concurrently. Your flow should now look like Figure F.

Figure F

Screenshot of nodes

If you double-click the Switch node, you’ll find that it provides a set of matching criteria, using the Property as the basis for comparison. In this case, we want to perform one activity (remind us to wear a jacket) if msg.payload is less than 55 degrees, and not wear a jacket above 55 degrees.

We’ll create a comparison rule for when msg.paylod is less than or equal to 55 by changing the operator to less than or equal (<=) and changing our comparison from string to number, and entering the value 55. We also need a scenario for when the temperature is above 55, which we accomplish by clicking the Add button at the bottom of the panel. We could create another comparison rule, but it’s good practice to have your last rule accommodate all situations, so adding Otherwise from the bottom of the selection list provides an easy shortcut. Your Switch node should look like Figure G when you’re done.

Figure G

Switch node

When you click Done, you’ll notice that your Switch node now has two connecting points on the right side. The top point is for the first rule, when the temperature is below 55, and the bottom one is for all other values. Add two Debug nodes and connect them to the top and bottom connection points. Rename the two Debug nodes to Jacket and No Jacket, so your flow looks like Figure H.

Figure H

jacket flow

Click the garbage can button in the Debug panel to clear any existing data, and deploy and run the flow by clicking the button on the Timestamp node. You should have two results, and if you look carefully, the second result will indicate which node produced the message, in my case, it’s the No Jacket node, as shown in Figure I.

Figure I

No jacket node

Triggering a Debug node is not very exciting, but instead, you could trigger a message to your phone, turn on the light in your coat closet as a reminder to wear your jacket, change the color of an indicator light in your home or any other possibility you can imagine. In most cases, there are nodes available to facilitate these types of interactions.

Hopefully this exercise demonstrates the simplicity and power of RESTful APIs and how a tool like Node-RED allows for simple and straightforward experimentation. I’ve used Node-RED and public APIs for everything from putting the school lunch menu on our family calendar to turning off the sprinklers if it’s raining. In a professional setting, Node-RED can serve as a quick prototyping tool, letting you test different integrations or quickly migrate data between disparate systems. 

Many companies use Node-RED in production, where it excels at grabbing data from sensors and Internet of Things devices, performing some quick manipulations and sending those data to another system or data repository. After finishing this project, you’re now equipped to start using Node-RED and RESTful APIs in your own personal or professional pursuits.

Also see

This post was written by and was first posted to TechRepublic

Do you find this article helpful? Your Friend might too. So, please Share it with them using the Share button above.
Will you like to get notified when I post new updates? Then Follow me on any of my social media handles: Google News, Telegram, WhatsApp, Twitter, Facebook, Pinterest.
You can also drop your email address below if you wish to be notified by mail.

Tags: ,

%d bloggers like this: