Riding the iot wave with esp8266.

This is a short write-up of my recent esp8266 / MQTT / RF switch project, providing an MQTT interface to control ac loads (in this case lights).

The objective is to MQTT enable a radio remote controlled (RF) switch.
“yam” multifunction digital remote switch as pictured here.


This particular device has three relays, switched by a 315mhz remote.

I used an Arduino to capture the code for each button to be used later. There are plenty posts explaining this (like this one on instructables.com). There is no difference in the code using a radio with a different frequency.

The RF radio kit (seperate rx and tx prints) is rated 5v, but works also with 3v3. when 5v is desired for a longer range, a simple transistor circuit should be added to protect the 3v3 on the mcu.

Any esp8266 or nodeMCU can be used, but for development I find a model with built in usb more  practical. The RF-TX is connected to gpio0 (pin D3).
The code consists of snippets from the RF send demo, and from the pubsubclient documentation.

The MQTT broker can run anywhere, using a raspberry pi is a popular way to go, I installed it on a Synology NAS which is running 24/7 anyway.

Once the MQTT broker is running, get familiar with it, using a cli mqtt-client like mosquitto pub/sub.

The code for the nodeMCU (using arduino ide) can be found on my GitHub page https://github.com/Jaapk/mqtt-rf-switch/tree/master

Debugging information can be read on the serial console.

One example on switching the using the MQTT broker:
This is to turn the nodeMCU led on/off (with resp. -m “1” and -m “0”)

$ mosquitto_pub -h broker_ip -d -u user -P password -t topic -m "1"

Now this works, it can for example be integrated into Domoticz by using virtual hardware and virtual switches.
link the on/off actions to a script . A simple example for Relay A in my case (ToggleA.sh)

#!/bin/bash
/usr/bin/mosquitto_pub -h broker_ip -d -u user \
-P password -t topic -m "A"

Note that this particular RC switch does only toggle the single channels, there is no way to know the current state. Since there are codes for “all on” and “all off”, one could simply send this command followed by the settings for the separate channels. One should also set the switches after a power failure, since the default state may be “on”.

Thank for reading my page. I hope it has been informative, and got you some ideas.

Nice to add:
-Device fallback to wifi access point when the default access point is unavailable – wifimanager
-Over-the-air updating – ota
-Use remote as “middleman”. This would require the RX to send different codes, have the NodeMCU received these codes and forward to the MSTT broker allowing some more automation like scenes.

Links to hardware / software used:
3 way RF switch Aliexpress
nodeMCU Aliexpress

315Mhz radio Aliexpress

Mosquitto docs.
nodeMCU / arduino ide crash course