Building an Azure IoT Central “Gateway” using Node-RED

I control a few devices from the Internet, but I don’t want all devices exposed and connected to IoT Central. One solution is to build a gateway locally which routes request messages to switch things on or off to the correct device locally.

In this post we will look at how to send commands from IoT Central and route them using Node-RED to the automation device via MQTT.

Home Automation Gateway Architecture

This architure uses Node-RED as a gateway, and then uses Eclipse Mosquito as a MQTT server. The Grow Light and Air Conditioner in the diagram is an off the shelf Sonoff POW-R2 device flashed with Tasmota.

Flashing with Tasmota

Installing Eclipse Mosquitto in a Container

Installing Node-RED in a Container

“Gateway” flow in Node-RED

With Node-RED you can visually map the flow / sequence of events. Node-RED supports Azure IoT Hubs and Azure IoT Central, so it’s perfect for this job to do quickly and easily without having to write code.

Gateway device created in IoT Central’s Command Capabilities

In Azure IoT Central we have a single device linked with a command. The command accepts a parameter, which will be the device name / topic name on the local MQTT server.

Executing a command on IoT Central

The diagram above shows the command with the parameter.

Defined Methods to IoT Central Commands

The Node-RED Azure component supports Direct Methods. These are commands that you can directly invoke on a device. In this case, the device is the gateway itself created within Node-RED.

It supports two methods (as per Azure IoT Central template)

  • turngatewaydeviceon
  • turngatewaydeviceoff
Switch to determine flow based on Direct Method Invoked from IoT Central

With a Node-Red switch statement we can controll the flow with whichever method name was invoked from IoT Central.

Switch Home Automation On flow

If it’s the “DeviceOn” flow, then the device parameter name (payload) is used to build up the topic for the Sonoff device via MQTT. The payload of the message will be “on”.

Switch Home Automation Device Off Flow

If it’s the “DeviceOff” flow, then the device parameter name (payload) is used to build up the topic for the Sonoff device via MQTT. The payload of the message will be “off”.

apead

I am a Xamarin Most Valueable Professional (MVP), Microsoft Developer Technologies MVP, Microsoft Internet of Things MVP, Microsoft Azure MVP, Architect, Software Developer, Organizer and Sponsor of the CPTMSDUG, JHBMSDUG and DBNMSDUG User Groups and father of 2.