Hands On...


NodeMCU

Communications


By: BEEVA Research Lab

Modularize your code!


It is a good practice to store configuration constants on a separated file.

Modify the file "config.lua" to your needs

Configuration file



Upload "config.lua" to the board


# Copy the configuration file
nodemcu file add config.lua config.lua
# Verify the file is copied
nodemcu file ls
# See the configuration file
nodemcu file cat config.lua
						

Import the configuration


require "config"

--Your program
print(THING_ID)
...
						

WiFi module




The "wifi" module handles all the WiFi capabilities.

Some features:

Code


MQTT



  • MQTT -> Message Queue Telemetry Transport
  • Publish - subscribe model
  • Simple, lightweight, low-bandwidth
  • QoS: reliability and assurance of delivery
  • Ideal for M2M or IoT communications

MQTT module




The "mqtt" module handles the MQTT capabilities.

Some features:

Programs

MQTT BROKER & CLIENT


# Client
apt-get install mosquitto-clients
# Broker
docker pull eclipse-mosquitto  # Docker image
docker create -p 1883:1883 -p 9001:9001 --name iot-test-mqtt eclipse-mosquitto  # Create image
						

Broker operative


docker start iot-test-mqtt  # Start the container
docker stop iot-test-mqtt  # Stop the container
docker rm iot-test-mqtt  # Delete the container
						

Test


# Terminal A
mosquitto_sub -h localhost -p 1883 -t '#' -v
# Terminal B
mosquitto_pub -h localhost -p 1883 -t "topic/subtopic" -m "This is a message"
						

Code

Tests


Start the MQTT broker

docker start test-mqtt
						

Open a listener terminal.

mosquitto_sub -h localhost -p 1883 -t '#' -v
# Press the NodeMCU button and see the message
						

Open a writer terminal

# Switch the LED on
mosquitto_pub -h localhost -p 1883 -t '<THING_ID>/LED' -m "1"

# Switch the LED off
mosquitto_pub -h localhost -p 1883 -t '<THING_ID>/LED' -m "0"
						

THE END