It took me some time to implement all features to ESP8266 controlling relay of my lamp.
Thanks to examples from PlatformIO I was able to use all neat features in one code:
You can find complete code at github repo LampESP. Just replace HOST_NAME_HERE and ROOM_NAME_HERE with your MQTT server and your room name.
Once you deploy code to ESP8266 you can use Over-the-air update (OTA). Just change the value in platformio.ini and set upload_port to IP address of your device.
The implementation allows control via simple GET API by accessing the web of device or LampAndroidApp.
As I wrote few weeks ago, my goal was to add MQTT. I’ve installed Mosquitto and connected the device to the server.
It is possible to watch states of device is possible via MQTT client:
mosquitto_sub -v -h HOST_NAME_HERE -t '/#'
Here is example how to change states of relay:
mosquitto_pub -h HOST_NAME_HERE -t '/home/ROOM_NAME_HERE/command' -m 'on' mosquitto_pub -h HOST_NAME_HERE -t '/home/ROOM_NAME_HERE/command' -m 'off'
I had an idea about next cool feature: turn on/off lamp based on sunset and sunrise. I found very simple and elegant solution that I would like to share with you.
Download Sunwait and compile it. The program just starts and waits until the time of sunrise or sunset based on geographic coordinates. You can also specify offset (how long before or after event) should program end.
Now you can put the sunwait into your local cron table and chain it with command that should be executed after sunrise/sunset occurs.
Here is example how to configure cron to turn on the lamp 15 minutes before sunset and turn it off 15 minutes after sunrise.
crontab -e 10 15 * * * /usr/bin/sunwait sun down -0:15:00 49.230738N, 16.576802E; /usr/bin/mosquitto_pub -h HOST_NAME_HERE -t /home/ROOM_NAME_HERE/command -m "on" 4 15 * * * /usr/bin/sunwait sun up +0:15:00 49.230738N, 16.576802E; /usr/bin/mosquitto_pub -h HOST_NAME_HERE -t /home/ROOM_NAME_HERE/command -m "off"
The lamp is now working. The only problem is the Android app. I thought that adding MQTT client to Android app will be as easy as adding it to ESP8266, but it’s far from truth. There are still some challenges ;-)