Sending code snippets to a remote nodemcu using MQTT

NodeMCU

Lua allows to load a string and execute it as code at runtime. We can use this feature to send code snippets to the NodeMCU. There are several ways to transport the code to the NodeMCU. I will be using MQTT to transfer the code from a remote client to the NodeMCU.

You can even get back a result from the node, just you have to add a return statement , for example the following code prints a message to the NodeMCU uart and return the state of GPIO 1.

print(“Hello NodeMCU !!”) return gpio.read(1)

NodeMCU_remote_exe

You can send this snippet to the NodeMCU and NodeMCU will execute the code snippet and send back the return value in different channel.

This is possible because lua allows to parse a string as code and execute it.

loadstring(‘print(“this is code snippet stored as String’)”)()

Channels structure:

You need to publish the code to the following channel

/node/v1/{chipid}/code/tonode

NodeMCU will publish the return value of your code in the following channel

/node/v1/{chipid}/code/fromnode

NodeMCU_remote_exe

You can get the chipid of your NodeMCU by executing the following statement.

print(node.chipid())

NodeMCU_chipid

The code is available on the Github, The project contains 4 files, you need to load all of them to NodeMCU. You can follow this guide if you are not aware how to flash files.

You need to have access to MQTT broker, there are many public MQTT brokers available, you can use this guide to create one on cloudMQTT.

Once you MQTT broker is ready, update your MQTT broker details along with the WiFi AP details in the config.lua file.

You need to MQTT client program to send and receive messages to borker. There are many android apps available in play store , you can use any of them . I am using mqtt-spy on windows machine .

Here we are passing a simple print statement and a GPIO return statement. We can also set GPIO, read ADC values by sending appropriate code snippets. for example follwing code returns available free memory

print(“Hello NodeMCU !!”)  return node.heap()

Add a Comment

Your email address will not be published. Required fields are marked *