Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Please click the bottom right corner “Read Original” to obtain better formatting and image quality.

Welcome to join Augix’s official QQ group: 595698697.

I have always wanted to make everything in my home smart, but the prices of smart home products on the market are not low; moreover, there are many brands of smart home products, and if you buy products from different brands, you often need to download many apps, making control even more cumbersome, and products cannot interact with each other.

So since this is the case, can we make smart home devices ourselves, where everything can be modified to our satisfaction? Fortunately, many designs have already been provided by predecessors, making the process less cumbersome.

Although the article is relatively long and looks complicated, it can actually be done in one or two hours.

1. Preparation

Before practicing, we need to have a plan. First, since we need to configure via web/mobile app, we naturally need a machine to consolidate all the smart devices we create, and then access the IP address of that machine, where various control switches will be available. However, we don’t know what system the machine needs to install; this is determined by the software we use to consolidate smart devices. Here, I chose OpenHAB, which is clearer and easier to work with compared to other software; OpenHAB only requires a JAVA environment, so it can run on Windows/Linux/Mac OS. How do we make OpenHAB communicate with smart devices? We need to use MQTT, which is a protocol that allows smart devices and OpenHAB to communicate over a local area network. However, for the MQTT protocol to work, we also need a server, which requires a software setup called Mosquitto, installable on most platforms; setting up this server is just a matter of installing software and is not complicated.

Ultimately, we need to consider how to create this “smart device”. Today, our main device is modifying a light switch (the kind on the wall), and the best solution for controlling the power on/off is to use a relay. Therefore, we need a device to control the relay’s on/off state, and this device must also be able to connect to WiFi, which is what we will use today: NodeMCU.

NodeMCU is a development board, similar to Arduino, which connects to the relay and can control the relay’s on/off state through simple LUA script code. You do not need to learn LUA language specifically; it is very simple.

So today, the hardware we need is NodeMCU, a two-way relay (if it is a single switch (meaning there is only one switch on the panel), a one-way relay is sufficient), and a machine running OpenHAB and Mosquitto, which can be any computer that can connect to the internet (preferably running Linux or Mac OS for easier installation; of course, Windows is also possible, but the installation is a bit more complicated).

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Materials needed

1.1 Driver Installation

Before starting, let’s get the drivers sorted to avoid more trouble later. Note that there are currently two versions of NodeMCU on the market: one is ch340, and the other is CP2102. Most are CP2102, and the difference in use is not significant, but it is said that CP2102 is more stable. For CH340, Windows 10 usually installs the driver automatically, but CP2102 rarely does (there are said to be certain compatibility issues). The CP2012 driver download link is here. I have not found an official link for the CH340 driver, so I will not provide it; you can search for it on Baidu.

1.2 Flashing Firmware to NodeMCU

First, we need to flash a firmware onto the NodeMCU; when you buy the NodeMCU, there is nothing in its flash memory. The firmware download address is here. First, you need to enter your email address, then select the firmware version (just select Master, which is the most stable version), and finally select the features included in the firmware. As for what features to select, here is a reference; for today’s switch modification, it is sufficient. If you want to know all these features, you can go to here (in English) or here (in Chinese, but incomplete).

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Select firmware

Finally, click the bottom button “Start Your Build”, go have a cup of tea, and wait for the email (don’t be anxious; it won’t be that quick, at least a few minutes).

Once compiled, you will receive an email like this.

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Received email

The top two links are the firmware we need, one contains float, and the other does not. However, I have not found any difference in usage between these two; the file with float is slightly larger, so choose either one. Click the link to download it.

There are many flashing tools, but the one recommended in the official documentation, which also has a graphical interface, is Pyflasher, which can be downloaded from here. I downloaded version 2.0beta.

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Download flashing tool

After downloading, open it directly. Connect the NodeMCU to the computer using a Micro USB data cable. If the driver installation step has been done, you can continue directly.

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Flashing

Select the NodeMCU port in the Serial Port section (this port can be found in Device Manager; click on the left list “Ports” (or COM or Port), and you will see a name containing “CP2102” or “CH340”; usually, that is the NodeMCU, and the port number is on the right (for example, COM4); if you don’t want to bother, you can try each port). Select the firmware you downloaded for NodeMCU. Note: Do not click flash NodeMCU immediately because the NodeMCU has not yet entered flashing mode. To enter this mode, press and hold the Flash button on the NodeMCU, then press (not hold) the Reset button; when the blue light flashes, you can release it. Now you can click Flash NodeMCU.

When you see “Hard resetting…” in the black box below, it has finished flashing. Click the Reset button on the NodeMCU.

2. Communicating with NodeMCU & Uploading Code to NodeMCU

2.1 Download

We also need to use software to communicate with NodeMCU, called ESPlorer. This is also recommended in the official documentation. This software does not support high-resolution screens, but we can’t find a better alternative, so we will use ESPlorer.

This software requires a JAVA environment. You need to go to here and click the middle download button to install it step by step.

Download ESPlorer here.

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Download ESPlorer

After downloading, unzip it; double-click “ESPlorer.bat” or “ESPlorer.jar” to open ESPlorer. Let’s take a look at the general layout of the interface.

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

ESPlorer

The right side is where we communicate with NodeMCU. At the bottom, there is a text box where we can input commands to communicate with NodeMCU once we connect it. The top is where we connect to NodeMCU. The left side is where we write code. After writing, we can click Save to ESP below to save it to NodeMCU.

2.2 Connection

First, at the top, select the port where NodeMCU is located (which is the same port we used to flash the firmware; mine is COM4), then change 9600 to 115200 (if you don’t modify it, it will garble when connected successfully, and it will take a few seconds to normalize; it doesn’t significantly affect usage, but it is still recommended to adjust it), then click OPEN below. You will see an interface like this.

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Before connection

Then click the Reset button again:

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

After connection

If you see this interface, it means the connection was successful. Now we can communicate with NodeMCU.

3. Wiring

Note: Please make sure to turn off the power before proceeding to ensure safety. Any issues arising are not my responsibility.

First, let’s remove the original switch.

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Remove the switch

First, confirm which wire connects to the light and which wire is live. There are many methods; I won’t describe them here. In my case, two black wires connect to two lights, and the green wire is the live wire; when connecting to the relay, the live wire connects to the common terminal, and one wire connecting to the light goes to the normally closed terminal (which port is normally closed is usually written; if not, the seller will definitely tell you).

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Connecting to one light

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Connecting to two lights

Next, connect the relay to NodeMCU.

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

NodeMCU wiring

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Relay interface

The VCC1 and VCC on the far left of the relay can be ignored. The VCC on the right connects to the VIN interface of NodeMCU for power supply, and GND connects to the GND interface of NodeMCU (ground). IN1 and IN2 (IN1 controls the first relay, IN2 controls the second relay) connect to D1 and D2 of NodeMCU (both are GPIO interfaces; you can think of these interfaces as data interfaces. After connecting, you can control the relay’s on/off state by controlling the output level of this GPIO port) (actually, you can connect to any of D1-8, but the subsequent code must correspond).

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Wiring completed

This completes the wiring.

4. NodeMCU LUA Script Language for GPIO

When we selected the features for the firmware earlier, we checked GPIO, so we can now use commands related to controlling GPIO.

gpio.mode() Initialize pin to GPIO mode, set the pin in/out direction, and optional internal weak pull-up.
gpio.read() Read digital GPIO pin value.
gpio.serout() Serialize output based on a sequence of delay-times in µs.
gpio.trig() Establish or clear a callback function to run on interrupt for a pin.
gpio.write() Set digital GPIO pin value.

This is the table provided in the official documentation. The only ones we need to know are the first, second, and fifth.

gpio.mode(pin, mode [, pullup])

– pin refers to the GPIO port; since we connected D1 and D2, if we want to control D1, pin is 1

– mode has many types; we only need to understand two: gpio.OUTPUT and gpio.INPUT, one is output, and the other is input. We need output to control the relay

– the pullup is optional; we don’t need it now; if you want to understand, you can search it online (I actually don’t know what it is for)

– so we need to set D1 and D2 as output

gpio.mode(1,gpio.OUTPUT)

print()

gpio.mode(2,gpio.OUTPUT)

– and that’s it

We input the code into the input box at the bottom and click send.

gpio.write(pin, level)

– when buying a relay, it will mention low-level trigger or high-level trigger; mine is high-level trigger, which means the relay will connect when it is high-level, so we control the GPIO port with this command

– high and low levels

– when we need to turn on the first light, we need to set D1 to high level

gpio.write(1,gpio.HIGH)

– to turn off the first light

gpio.write(1,gpio.LOW)

Send it the same way, and the light is now controlled.

gpio.read(pin)

– can read whether the GPIO port is in a low-level state (light off) or high-level state (light on)

– return value is 0 (low level) or 1 (high level)

print(gpio.read(1))

– display the high/low level state of D1 on the screen

5. Installing OPENHAB2 & Mosquitto (MQTT Server)

Take out the computer mentioned at the beginning for installing OpenHAB and Mosquitto.

5.1 OPENHAB2 Installation

5.1.1 Download and Install

The installation of OpenHab2 is relatively simple; here we use the Windows environment, other systems are similar.

This software requires a JAVA environment; you need to go to here and click the middle download button to install it step by step.

Go to www.openhab.org/downloads.html, click the Download button under “Runtime Distribution” to download (in fact, it provides three installation methods; the first is under “Runtime Distribution”, and the difference from the second “Add-ons” is: Add-ons will download all plugins when downloading, meaning you don’t need to be online when installing plugins, while Runtime Distribution does not download plugins, only the main OpenHAB, and you need to be online to download plugins. The third is based on the Add-ons version, which also downloads plugins from OpenHAB1.x (we are installing OpenHAB2.x), which is generally not used).

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

OpenHAB download

The downloaded file should be a zip file; unzip it to any location. Double-click Start.bat (for Linux, execute start.sh, usually in the console Terminal, cd to the unzipped folder, then enter “./start.sh” and press Enter; see which Linux distribution you are using for specifics).

At this point, you will see an “error” prompt like this:

karaf.bat: Ignoring predefined value for KARAF_HOME

You can ignore this; just wait, and soon you will see the big “OPENHAB” logo, which means it was successful.

5.1.2 Configuration

Next, go to the browser, visit “IP address:8080”, which is the IP address of the computer where OpenHAB is installed. You will enter the configuration interface.

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

OpenHAB configuration

It provides four configuration options, just choose “Standard”; the first one is too simple and inconvenient for configuration.

Next, just wait, because the speed of connecting OpenHAB in China is not fast, so it may take a little longer.

Once the installation is complete, it will display like this:

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Main interface

5.2 Mosquitto Installation

The installation of Mosquitto varies across systems; here we demonstrate using the Windows environment. However, this software is more complicated to install on Windows than on other systems. For specific installation instructions for each platform, go to the official website here, and it will tell you what you need to do.

Installing on Windows has some complications.

5.2.1 Installing OpenSSL

As for why we need to install OpenSSL, the official website mentioned that it contains the required dll files. However, the reason it is not integrated into Mosquitto seems to be unexplained by the official site.

Go to here to find Win32 OpenSSL v1.0.2L Light (make sure to select Win32, not Win64, because Mosquitto is a 32-bit software and cannot use 64-bit DLLs. The reason for choosing version 1.0.2 is that version 1.1.0 seems to not have the two required dlls after installation).

Click to download, open the installer, and just keep clicking Next.

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

OpenSSL download

5.2.2 Obtaining pthreadVC2.dll

Another dll needs to be obtained…

Go to ftp://sourceware.org/pub/pthreads-win32/ and find the folder named prebuilt-dll-X-X-X-release (the latest version is fine), click on dll, click x86 (not x64 for the same reason), and download pthreadVC2.dll. After downloading, copy it to C:\Windows\System32.

5.2.3 Installing Mosquitto

Finally, the main character has arrived. Go to here, find Windows, and click to download mosquitto-x.x.x-install-win32.exe (the cygwin version needs to be compiled by yourself, so do not select it).

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Mosquitto download

After downloading, open it and keep clicking Next until you finish the installation.

5.2.4 Starting Mosquitto Service

Right-click on the taskbar, open the task manager, click on “Services”, find Mosquitto, right-click, and start it. The Mosquitto service will start successfully.

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Task manager – Services – Mosquitto – Right-click – Start

Note: By default, Mosquitto uses port 1883. When using MQTT, if you encounter a prompt to enter a port, it is always 1883. If there are issues, it is usually because Windows Firewall does not allow port 1883 (this usually happens on Windows Server; normal Windows will prompt about the firewall, and you can click allow). You can search online to find out how to bypass the firewall for port 1883; I won’t describe it here.

6. Working on OpenHAB Configuration

6.1 Understanding MQTT

Before we begin, let’s understand how MQTT works.

MQTT is not strictly speaking just two parts: one is the publisher, and the other is the subscriber. Of course, they have to go through the Mosquitto server.

For example, sometimes we follow someone on Weibo; after following, we can receive the messages published by that person.

Following is equivalent to subscribing in MQTT.

MQTT is somewhat like this but with some differences; a better example is that there are many Tag labels on Weibo, and these Tags can also be followed (which is also equivalent to subscribing in MQTT).

After following, if someone publishes a post in that Tag (the publisher’s action), you will receive that post.

Similarly, if another person publishes a post in that Tag, you will also receive it.

Even if I subscribed, I can also post in that Tag, and I will also receive the message.

MQTT works in this way; there are no restrictions on the number of subscribers or publishers, and the Tag is equivalent to the “Topic” in MQTT.

Only when the Topic published by the publisher matches the Topic subscribed by the subscriber will the subscriber receive the published message.

Back to today’s topic.

Assuming NodeMCU is the subscriber, OpenHAB is the publisher; first, NodeMCU subscribes to a Topic called “mainlight”, then writes a program that, if someone publishes “1” to the mainlight Topic, it will turn on the light, and if “0” is published, it will turn off the light. Then, in OpenHAB, we set a switch that, when turned on, publishes “1” to mainlight, and when turned off, publishes “0”. This way, we have a smart switch.

Let’s get started.

6.2 Installing MQTT Plugin

First, go back to the OpenHAB page, where you will see three UIs. The first is BASIC UI, which is used for normal control; the second is PAPER UI, which is used to manage some backend tasks of OpenHAB; the third is HABPANEL, which is similar to BASIC UI but uses tile design.

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

Main interface

Click PAPER UI. On the left, select ADD-ONS, then select BINDINGS at the top right, search for MQTT in the search bar, find MQTT Binding, and click INSTALL on the right (the above image shows it has already been installed).

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

PAPER UI

The plugin installation is complete.

6.3 Creating a SiteMap and Item

6.3.1 Item Syntax

First, understand the roles of SiteMap and Item in OpenHAB. SiteMap is the design of a page; through SiteMap, we can create a region, and in this region, there are several switches, with the detailed configuration of these switches in the Item file. If you don’t understand, don’t worry; you will understand through practice later.

First, go to the OpenHAB installation directory, enter the /conf/items folder. At first, there should only be a readme file inside. Then create a file with the suffix .items; I will name it default.items. Open it with any text editor.

The official documentation is at here; I will only explain part of the content; the rest you can explore in the official documentation.

Syntax

itemtype itemname "labeltext" <iconname> (group1, group2, ...) ["tag1", "tag2", ...] {bindingconfig}

itemtype refers to the type of the item (for example, Switch)

itemname is the name of the item (note that this is just an alias, not the name displayed on the page)

“labeltext” is what is displayed on the page; it can be omitted

<iconname> is the icon, for example, <light> (light) can be omitted

(group1, group2, …) are groups; for example, if two switches belong to group1, it can be omitted, but it helps with management

[“tag1”, “tag2”] sets several tags for this item, which can also be omitted

{bindingconfig} is the binding configuration; for example, if we choose to bind the device using MQTT, how to write this will be mentioned in the MQTT plugin documentation later.

6.3.2 Configuring Mosquitto Server

Before that, we need to set up the Mosquitto server in OpenHAB.

First, go to the OpenHAB installation directory, enter the conf\services folder, find mqtt.cfg, and edit it with any text editor.

First, find the line that says …… .url= …

1. Remove the # in front of that line

2. Input the Mosquitto alias (you can choose any name, just remember it for later use) before .url

3. After =, input the IP address of the computer where the Mosquitto server is located:1883 (the default is 1883 unless modified)

For example, I wrote homemqtt.url=192.168.3.21:1883

If OpenHAB and Mosquitto are on the same computer, you can also write Mosquitto’s alias.url=localhost:1883

Do not change anything else; just save it.

6.3.3 Binding MQTT to the Switch

Earlier, when discussing items, we talked about {bindingconfig}; now let’s write this part.

First, note that OpenHAB can also act as a subscriber (for example, sometimes it needs to receive temperature data, which is published by NodeMCU to OpenHAB), but we only need it to act as a publisher now, so we won’t discuss the subscriber part for now; it will be covered in future articles.

Let’s look at an example of a switch, which will make it easier to understand.

Switch mySwitch {mqtt="&gt;[mybroker:myhouse/office/light:command:ON:1],&gt;[mybroker:myhouse/office/light:command:OFF:0]"}

First, Switch is the item type

mySwitch is the item name

Nothing is written for the icon, etc.

Next, look at the content in the curly braces

First, the > sign in quotes is just to distinguish whether it is acting as a subscriber or a publisher; the subscriber uses <, and the publisher uses >

Then, mybroker is the alias we used when configuring mqtt.cfg

myhouse/office/light is the Topic to be published

command indicates that the following “ON” is a command

ON means that when the switch is turned on, it publishes a message to the Topic

Finally, the 1 and 0 are the messages to be published

Putting it all together, when we turn on the switch, it sends a message “1” to the myhouse/office/light Topic, and when we turn it off, it sends “0”. This is exactly what we need.

The final write-up is:

Switch mainlight {mqtt=”>[homemqtt:mainlight:command:ON:1],>[homemqtt:mainlight:command:OFF:0]”}

We just changed the item name to mainlight and the topic to mainlight.

Save it.

6.3.4 Sitemaps

First, go to the OpenHAB installation directory, enter the /conf/sitemaps folder. At first, there should only be a readme file inside. Then create a file with the suffix .sitemap; I will name it default.sitemap. Open it with any text editor.

The official documentation is at here.

We will directly use an example from the documentation to explain.

sitemap demo label=”My home automation” {Frame label=”Date” {Text item=Date}Frame label=”Demo” {Group item=HeatingSwitch item=Lights icon=”big_bulb” mappings=[OFF=”All Off”]Text item=Temperature valuecolor=[>25=”orange”,>15=”green”,<=15=”blue”]Text item=Multimedia_Summary label=”Multimedia” icon=”video” {Selection item=TV_Channel mappings=[0=”off”, 1=”DasErste”, 2=”BBC One”, 3=”Cartoon Network”]}Slider item=Volume}}}

Build Your Own Smart Home System: NodeMCU, MQTT, and OpenHAB for Smart Switches

sitemap_demo_fullexample

This is the effect; the outermost curly braces create a new sitemap called demo, with the title My home automation (this title will be displayed at the top of the page).

Next, there are two frames; the function of a frame is to create sections, and the frame label also serves to display the title.

Inside the frame are the items; the items in the example are a bit complicated and involve linkage; the next article will discuss this.

So we need to write it like this:

sitemap default label=”Will Family”{

Frame label=”Living Room”{

Switch item=mainlight label=”Main Light”

}

}

The sitemaps are complete, which also means the OpenHAB configuration is complete.

7. Final Configuration of NodeMCU

We are finally almost done.

Before we start, we need to understand a few codes.

7.1 Connecting to WiFi

There are many codes for WiFi, and you can see all of them in the official documentation here, but we only need a few codes to connect to WiFi.

wifi.setmode() Configures the WiFi mode to use.

NodeMCU provides four modes to choose from:

  • wifi.STATION Client mode, where NodeMCU connects to the router, acting as a client.

  • wifi.SOFTAP Router mode, where NodeMCU creates a WiFi hotspot.

  • wifi.STATIONAP Both client and router mode enabled simultaneously.

  • wifi.NULLMODE Low power mode, which seems to have no use and is probably for special purposes.

Clearly, wifi.STATION is what we need. In ESPlorer’s lower right input box, enter wifi.setmode(wifi.STATION) and click send.

wifi.sta.config() Sets the WiFi station configuration.

This is to set the WiFi SSID and password for connection.

It is very simple.

wifi.sta.config(“SSID”, “Password”)

That’s it. Send it to NodeMCU in the same way.

Now it is connected. To verify:

print(wifi.sta.getip())

If the correct IP is displayed, the connection is successful.

wifi.sta.autoconnect() Auto connects to AP in station mode.

This code allows WiFi to automatically connect in all situations.

wifi.sta.autoconnect(1) will do.

Note: All WiFi configurations will not change even if NodeMCU is rebooted (only flashing will change them). If autoconnect is used, it will directly connect to WiFi every time it starts, so all the codes edited next will not execute the above codes again.

7.2 MQTT Connection Syntax

There are not many MQTT codes, but each is very useful. I will explain using an example from the official documentation here.

– First, create an MQTT client (only Mosquitto is the server, while others are clients), named “clientid”, with a keep-alive countdown (can be left unchanged) of 120 seconds, and no username or password: m = mqtt.Client(“clientid”, 120)

– When the “connection successful” event is triggered, execute a function (the function is defined as function(…) where the variables to be passed to the function are inside the brackets; if you don’t understand, you can search online; if you really can’t, just ignore it, and it won’t affect this case): m:on(“connect”, function(client) print(“connected”) end)

– When the connection is lost, execute a function: m:on(“offline”, function(client) print(“offline”) end)

– If someone publishes a message in the Topic (regardless of which one, as long as something is published), execute a function – note that the variables client, topic, and data that need to be passed to this function are directly usable, as they are provided in the official documentation or examples; topic is the name of the topic, and data is the content of the message received: m:on(“message”, function(client, topic, data) print(topic .. “:”) if data ~= nil then print(data) end end)

– To summarize, the “on” function creates a trigger event that can be “connect” (when connecting), “offline” (when the connection is lost), or “message” (when a message is received). When triggered, it executes the following function.

– Connect to the Mosquitto server using the “IP address”, “port (default 1883)”, “security, default to 0 (leave it unchanged)”, and the “connection successful” function: m:connect(“192.168.11.118”, 1883, 0, function(client) print(“connected”) end)

– The subscribe command, where the parameters are “topic”, “qos level, default 0 (leave it unchanged)”, and the function executed on successful subscription: client:subscribe(“/topic”, 0, function(client) print(“subscribe success”) end) end, function(client, reason) print(“failed reason: ” .. reason) – the content executed when failing to connect to the Mosquitto server.

m:close(); – ends the connection.

This code may be difficult to understand in some parts; if you really can’t understand it, just use the code below (some parts need to be changed to your own), but it is still recommended to clarify it.

This code is already very suitable for us; we just need to change the m:on(“message”) part to include a conditional check that if data is “0”, turn off the light, and if “1”, turn on the light. This way, we achieve our goal.

if (data == “1”) then gpio.write(1, gpio.HIGH) else gpio.write(1, gpio.LOW) end

7.3 Downloading Code to NodeMCU

First, in ESPlorer, go to the menu bar “File” – “New”, then copy the code below into the code editing area on the left the parts that need to be modified are already marked

Click Save at the top. Note: As mentioned earlier, only saving the file as init.lua will allow it to run automatically when NodeMCU starts; other file names will not work, so make sure to use “init.lua”.

After saving locally, ESPlorer will also download it to NodeMCU at the same time. Wait for the progress bar to complete, and it’s done! Open the OpenHAB page to test it (if the progress bar gets stuck, click the bottom left “Save To Esp” again to try).

m = mqtt.Client(“Modify: MQTT client name”, 120) m:on(“connect”, function(client) print(“connected”) end) m:on(“offline”, function(client) print(“offline”) end) m:on(“message”, function(client, topic, data) if (data == “1”) then gpio.write(1, gpio.HIGH) else gpio.write(1, gpio.LOW) end end)

m:connect(“Modify: Mosquitto IP address”, Modify: port (default 1883), 0, function(client) print(“connected to mosquitto broker”) m:subscribe(“Modify: Topic”, 0, function(conn) print(“subscribe success”) end) end, function(client, reason) print(“failed reason: ” .. reason) dofile(“init.lua”) end)

m:close()

All Done

This article seems long, but many tasks (like installing OpenHAB) are one-time jobs. The next time you do another smart home project, it will be much simpler.

If you have any questions or suggestions, feel free to leave a comment in the comment section.

Leave a Comment

×