Controlling lamp with ESP8266 via WiFi by Android Widget

Two weeks ago I made research about available Smart Home Power Sockets. The result was not very positive.

Week ago I discovered talk about ES8266 which seemed to be the right solution.

And what about this week?

I happy to report success. I am able to control the lamp from mobile phone. :-)

This week I bought WeMos D1 Mini WiFi ESP8266 and relay. Together with friend we soldered few pins and wrote some code. The solution was working immediately after we plugged it into a wall.

Here is the result:

20161105_esp8266-with-relay

Code for Arduino is derrived from esp8266learning.com:

That was the easy part. I was able to control relay directly from mobile phone via web browser which was not very convenient. The widget would serve better.

Writing a widget for Android was real challenge. There is very little documentation about it and even Android Studio does not contain template for writing widget. I spent several hours learning how widget works. It is very different from common application.

The very first gotcha that costed me more than a hour was very common problem with builds:

Yes, it is very clear where is the problem. Or not? :)

It is necessary to fix build.gradle and set proper version of compile dependency. In my case I was targeting API 22, but appcompat was set to 23:

The real fun begins with the widget code. I cobbled together several chunks of code. Primary source was Obaro’s SimpleAndroidWidget and android-async-http.

Here is the very crude code for Android:

That’s not all. When you want to create widget you need to define also special handling in AndroidManifest.xml

Even that is not enough. You’ll need several small files in res directory including graphics. I won’t describe them here. You can download it from GitHub repo georgik/LampAndroidWidget.

The result?

It works perfectly on Samsung Galaxy S5 Neo, but for some reason I was not able to display this widget on Lenovo K5. If you have any idea why Lenovo K5 has such issue, let me know.

I also discovered a bug in the code of widget. When you have more than one widget it starts turning on and off the relay several times depending on number of widgets ;-)

The solution is ok for the time being. I’m already thinking about using MQTT and Node-Red which was discussed this weekend at OpenAlt conference in Brno by guys from McGayver Bastlíři SH.

2 Replies to “Controlling lamp with ESP8266 via WiFi by Android Widget

Comments are closed.