1. December 2016

ESP8266 WiFiManager gotchas

Thanks to PlatformIO it is very easy to add further functionality from libraries to the code for ESP8266. When you need to install library, just start Library Manager from ide and type:

pio lib install WiFiManager

PlatformIO will resolve dependencies and download all necessary stuff. Even better option is to add dependency to platformio.ini file:

platform = espressif8266
board = d1_mini
framework = arduino
lib_deps =

PlatformIO will manage the installation after you save the file. That is very neat.

Then new problems occurred when I started with integration of WiFiManager. Do not take me wrong. WiFiManager is very handy library, but you may experience some tricky issues.

The first problem that I hit was that WiFiManager interface was not visible at port 80. ESP was apparently running in AP mode for configuration, but there was no web interface. This issue was caused by this line in my code:

ESP8266WebServer server(80);

I had web server in the main code before I merged the code from WiFiManager. Web server was serving simple REST API for controlling relay. Unfortunately this construct blocked the port so the AutoConnect web server. The server was not able to bind the port. Solution was simple. It was sufficient to instantiate web server after WiFi was working.

The second problem was that AutoConnect from WiFiManager was always turning in AP mode. I was hunting the problem for several hours without any result. One idea was that WiFiManager is not saving the password. That was not true. Other idea was that the memory is corrupted and reformat would help. Unfortunately it didn’t. I gave up.

That solved the problem. Seriously. I gave up and that solved the problem. I let the device running and then ding. It was online. For some strange reason ESP8266 was not able to establish connection with particular WiFi router at first shot. Then it turned on AP mode and after timeout of Config Portal it connected to the WiFi network. Remedy? Just shorten ConfigPortalTimeout:


The third problem was that Config Portal was not displaying information stored as extra custom parameters. I stored there host name of MQTT broker and other options so they won’t be hardcoded. The problem was caused by WiFiManagerParameter constructed in global scope. Issue was similar the first problem with web server.

Solution was to move construction of WiFiManagerParameter to the method after loading configuration values from file config.json stored on file system.

File configFile = SPIFFS.open("/config.json", "r");
WiFiManagerParameter custom_mqtt_host("mqtt_host", "MQTT host", configMqttHost, 40);

After resolving these issues WiFiManager is working and it is possible to set values for configuration via Config Portal and there is no need to hardcode them anymore.

Original code is stored at GitHub – LampESP branch v0.1. The new version is at Github – LampESP branch master. I made also small refactoring and the functionality was divided into smaller files which resembles modules for better code maintenance.

27. November 2016

Controlling relay connected to ESP8266 via MQTT from Android

After successful implementation of MQTT into Lamp Relay with ESP8266 there was one remaining challenge. Communication of Android Lamp App with ESP8266 via MQTT. It was little bit harder than I expected, because examples were not very clear.

Sending commands to MQTT broker was relatively easy. There was just a catch. It is necessary to declare the MQTT service in AndroidManifest.xml:

<service android:name="org.eclipse.paho.android.service.MqttService">

Thanks to tutorial from HiveMQ I was able to send messages to MQTT broker.

The problem was the opposite direction. How to receive messages?

Well, there is support in the same MQTT library for topic subscriptions. The issue is that incoming message is being processed on background thread and it’s not possible to update UI. It took me some time to realize the source of problem. I was hunting ghosts. I thought that there is some problem in ImageButton or TobbleButton.

Correct solution was to move communication to Android service class. Then bind the service so UI can send commands to the service and the last part was to add broadcast receiver to pass message from service to UI.

Here is small schema which describes delivery of message from broker to app.


It was necessary to make also small update in ESP8266 in order to tell Mosquitto to persist the state of a lamp (the last bool parameter):

mqttClient.publish(topicName("relay"), "off", true);

The result is nice. I can turn on the lamp via web interface and all connected Android apps are updated and user can see the state of the lamp.


The code for Android app is available at Github – LampApp. Previous code with REST API was moved to branch v0.1. The code for ESP8266 module is also at Github – LampESP. Feel free to customize the app. You can find instructions in README.md.

I see the next challenge for LampApp: display lamp control widget at lock screen. Maybe I’ll be more successful than the last time.

22. November 2016

IoT and waiting for the sun

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 😉

19. November 2016

Programming ESP8266 in Go language? Not yet. November 2016

I was wondering if it would be possible to use Go language to write code for ESP8266.

The very first search result seemed to be the right choice – Gobot.

I read the instructions and typed:

go get -d -u github.com/hybridgroup/gobot/...

After a while Go asked for password to git.eclipse.org. I had no account there so I registered the account. And again:

go get -d -u github.com/hybridgroup/gobot/...

New error:

package git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git: cannot download, git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang uses insecure protocol

Go was trying to get repository from Eclipse using unsecure HTTP. Luckily there was feature request to add switch for accessing insecure repositories by Go get – issue #9637. The solution was just to add “-insecure” parameter:

go get -insecure -d -u github.com/hybridgroup/gobot/...

New error:

# cd .; git clone git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang .../projects/gobot/src/git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git
fatal: repository 'git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang' does not exist
package git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git: exit status 128

Yay, that’s cute. I’ve searched through issue tracking system in hybridgroup/gobot and the answer was issue #339.

The workaround is to change line 4 in github.com/hybridgroup/gobot/platforms/mqtt/mqtt_adaptor.go to:


Ron Evans recommended just to switch to dev branch.

Thanks to Go integration with Git it was very easy:

cd src/github.com/hybridgroup/gobot
git checkout dev
go get -d -u github.com/hybridgroup/gobot/...

Only after this sequence of steps from magic dance Gobot was ready to build application on my computer.

My next step was attempt to build MQTT ping. Easy? Just grab a code from gobot.io documentation, paste it to file and run it.

go run mqtt-ping.go

Another funny error:

# command-line-arguments
./mqtt-ping.go:11: undefined: gobot.NewGobot
./mqtt-ping.go:13: undefined: "github.com/hybridgroup/gobot/platforms/mqtt".NewMqttAdaptor

The documentation on the web is from master. Ou, but I switched to dev branch. What a simple mistake. I grabbed the code from github repo everything was ok.

cp  ./github.com/hybridgroup/gobot/examples/mqtt_ping.go .
go run mqtt_ping.go

The application was able to connect to Mosquitto Broker and send messages.

The last step would be to deploy it to ESP8266. Unfortunately this is not possible yet. The platform is not supported by Gobot and there is issue with plaftom-request #301.

Ok, never mind. It was interesting experiment and I can see potential of Go for programming IoT.

What will be my next experiment? Developing the code for ESP8266 using PlatformIO.

13. November 2016

Silicon Germany – book recommendation

There are many books about startups and lean thinking from USA. They have one big problem in common. These books does not match with situation and environment in Europe. Buying those books and trying to apply them in Europe is in many cases waste of time.

I’ve been searching for books based on European context. I have found only few European authors.

Prof. Günter Faltin wrote book Kopf schlägt Kapital which apply similar thinking like Steve Blank and Lean Canvas.

Stefan Merath wrote several books about customer relationship and how to build working business model. He has similar style like Eric Rise and Lean Startup.

Recently I discovered very intriguing book with the title Silicon Germany written by Christoph Keese. Christoph is investigating reasons why products from German or other European companies are simply bellow average and why they struggle so much to catch with latest products from California.


If you want get better understanding why Europe has so many problems with innovations then I recommend this book to you.


12. November 2016

Android widget not visible on Lenovo K5 – Solved

I’ve created Android Widget for controlling ESP8266 relay the last week.


The only problem was that the widget was not visible on Lenovo K5.

I was searching for the root cause using method: “Once you eliminate the impossible, whatever remains, no matter how improbable, must be the truth.”

I grabbed several other repositories with widgets from Github. Widgets from other projects were working.

To keep long story short. Here is the configuration when widget does not appear:


Here is the configuration when widget properly appears:


Can you spot the difference?

It is very simple. Large number of Android devices displays widget just after installation even when using the first configuration. The problem with Lenovo K5 is that it does not register widget just after installation via adb. You need to launch MainActivity and only after that UI subsystem displays the widget.

Original code from Obaro’s repo is without MainActivity. I took inspiration from Udacity’s Android widget. After I’ve added MainActivity and several other small files into the project the widget appeared even on Lenovo K5.

You can find updated version at GitHub/LampWidget. Thanks to Adusak for a hint about MainActivity.

6. November 2016

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:


Code for Arduino is derrived from esp8266learning.com:

//This example will set up a static IP - in this case
#include <ESP8266WiFi.h>

const int relayPin = D1;
const int chipSelect = D8;
const char* ssid = "MYSSID";
const char* password = "SECRET";
WiFiServer server(80);
IPAddress ip(192, 168, 1, 50); // where xx is the desired IP Address
IPAddress gateway(192, 168, 1, 1); // set gateway to match your network
void setup() {
  pinMode(relayPin, OUTPUT);
  Serial.print(F("Setting static ip to : "));
  // Connect to WiFi network
  Serial.print("Connecting to ");
  IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your network
  WiFi.config(ip, gateway, subnet); 
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
  Serial.println("WiFi connected");
  // Start the server
  Serial.println("Server started");
  // Print the IP address
  Serial.print("Use this URL : ");
void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
  // Wait until the client sends some data
  Serial.println("new client");
  // Read the first line of the request
  String request = client.readStringUntil('\r');
  // Match the request
  int value = LOW;
  if (request.indexOf("/relay=on") != -1) {
    digitalWrite(relayPin, HIGH);
    value = HIGH;
  if (request.indexOf("/relay=off") != -1){
    digitalWrite(relayPin, LOW);
    value = LOW;
  // Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.print("Led pin is now: ");
  if(value == HIGH) {
  } else {
  client.println("<a href=\"/relay=on\">Relay ON</a><br>");
  client.println("Click <a href=\"/relay=off\">Relay OFF</a>");
  Serial.println("Client disconnected");

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:

Error:(3) Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'.

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:

dependencies {
    compile 'com.android.support:appcompat-v7:22.1.1'

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:

package com.sample.foo.simplewidget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.RemoteViews;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import cz.msebera.android.httpclient.Header;

public class SimpleWidgetProvider extends AppWidgetProvider {

    private void getHttpRequest(String state) {
        AsyncHttpClient asyncClient = new AsyncHttpClient();
        asyncClient.get("" + state, new AsyncHttpResponseHandler() {
            public void onStart() {

            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {


            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {



    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        final int count = appWidgetIds.length;

        for (int i = 0; i < count; i++) {
            int widgetId = appWidgetIds[i];
            String value = "off";
            SharedPreferences prefs = context.getSharedPreferences("LampApp", 0);
            boolean isRelayEnabled = prefs.getBoolean("relayState", false);
            isRelayEnabled = !isRelayEnabled;
            SharedPreferences.Editor editor = prefs.edit();
            editor.putBoolean("relayState", isRelayEnabled);

            if (isRelayEnabled) {
                value = "on";

            RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
            remoteViews.setTextViewText(R.id.textView, value.toUpperCase());

            Intent intent = new Intent(context, SimpleWidgetProvider.class);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

            PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
                    0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.actionButton, pendingIntent);

            appWidgetManager.updateAppWidget(widgetId, remoteViews);


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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    <uses-permission android:name="android.permission.INTERNET" />

    <application android:allowBackup="true" android:label="@string/app_name"
        android:icon="@mipmap/ic_launcher" android:theme="@style/AppTheme">

        <receiver android:name="SimpleWidgetProvider" >
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            <meta-data android:name="android.appwidget.provider"
                android:resource="@xml/simple_widget_info" />



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.

28. October 2016

ESP8266 and IoT

The research from the last week about Smart Home was a bitter surprise for me. It seemed that only way how to get IoT is to pay a lot of money to vendors.

Today I sumbled upon great web Open Home Automation where Marco Schwartz publishes articles about home automation in easy to read form. His focus is on open hardware.

One particular piece of tech caught my attention ESP8266.

The problem of building stuff with classic Arduino board is that the price is relatively high. ESP8266 removes even this problem.

Here is great and funny talk from OSCON 2016 – Alasdair Allan

23. October 2016

Smart Home in 2016 – Overview for beginners

So. You want to start with Smart Home?


I spent a weekend researching about this topic. Here you can find extract with several links that might save you some time.

My goal was very simple. I’ve got Salt lamp with 15W light bulb and I would like to control it from mobile phone.

Before we embark on the journey I recommend to read RFC 1925 at least two points:

  • (1) It has to work.
  • (8) It is more complicated than you think.

Keep that in mind. Our journey can begin.

Group #1: Devices which do not care about net

The first group that I discovered were devices which has no integration with network.


It is simple and cheap hardware which allows time based control of power socket for the lamp: Solight time switch.


Price: 339 Kč / 12 EUR

Solight does not support remote control.


Similar solution, but with remote control is RSL2. You can control several sockets with one remote control. The neat feature of this solution is ability to dim the light.

Price: 459 Kč / 17 EUR

The downside for this and several other sockets described in the article is that they’re targeted at German/Western market and you need to buy reduction to Czech/Slovak power plug.


Price: 71 Kč / 3 EUR


Then I found socket with interesting design which has support for remote control and you can turn it on just by pressing button: PowerCube. The button does not require any extra batteries. That’s very useful feature. Just some people on the internet complained that sometimes thay had to push the button twice. The button can be paired with more PowerCubes or more buttons can be paired one PowerCube.


Price: 659 Kč / 24 EUR

Group #2: Devices which do not care about cloud

I found this group at the end of my search.

Ubiquiti mFi mPower

Wow! mFi mPower! It has everything, because it is running on Linux. Wifi and even SSH interface. Android app or any script can interact with the device. The price is very reasonable.


Unfortunately the software development for this platform was placed on hold early this year. That is not good. Just two days ago there was another huge DDOS attack at Dyn which knocked out even GitHub. I’m not saying that it was caused by mFi devices. I just want to stress out that security patches are very important for smart devices.

Price: 1020 Kč / 42 EUR

BeeWi Bluetooth Smart Plug

Another device which is able to operate without cloud is BeeWi socket which communicates via Bluetooth with mobile phone. It is also possible to connect BeeWi to cloud, which requires special gateway from the same vendor.


Price: 1099 Kč / 45 EUR

Group #3: Devices addicted to cloud

There is large group of devices which operates on WiFi, but these devices are dependent on cloud. The dependency is not necessary bad thing, but you should be aware of it. It might very easy happen that the cloud is not accessible and you won’t be able to control the devices.

Isn’t it strange that with every flip of switch you need to generate some command and operation on remote server in the cloud?


The best match for the solution controlled via WiFi seems to be TP-LINK HS110. Android app has very high reviews. Just the iPad version is missing, so you have to use iPhone.


Price: 1079 Kč / 44 EUR

D-Link DSP-W215 SmartPlug

I found very alarming reviews of D-Link DSP-W215. Users were complaining that the device violates Czech electrical standards.


Price: 1399 Kč / 58 EUR

Belkin – WeMo Insight Switch

WeMo solutions seems to be popular, but I found large number of very negative reviews of control app for Android. It reminds me on old bloated Samsung Kies. This solutions works via WiFi and requires connection to the cloud.


Price: 1561 Kč / 65 EUR

Group #4: Devices which talks together

This is the most complex group. These devices implements protocols like Z-Wave or Zigbee which does not operate with the same protocols as BlueTooth or WiFi. It means that you often need a server which controls behavior of devices and which is able to relay instructions from your mobile app to the protocol implemented by devices.

FIBARO – Wall Plug

FIBARO has simply great design, neat functions. Little bit more expensive, but where is the catch?


Price: 1799 Kč / 74 EUR

FIBARO – Home Center 2

Here is the catch. You need FIBARO Home Center 2 to be able to communicate with FIBARO Wall Plug. The device allows you to control and gather report from your smart home network. The only problem is that the price is little bit higher than you would expect.


Price: 16499 Kč / 687 EUR

There is also FIBARO Home Center Lite which has little bit simple HW configuration and it is about half the prices of Home Center 2.


It is possible to use your own server instead of FIBARO Home Center, but you’ll need USB dongle like Aeon Z-Wave which is able to communicate via Z-Wave protocol.


Price: 1320 Kč / 55 EUR


Once you’ve got USB dongle you can set up your own home automation server like OpenHAB. Just unzip the file, copy configuration. Start the Java server and connect to web interface. Then you can use application on your mobile phone to control your home network. OpenHAB is very flexible and authors received Duke’s choice award in 2013.

It is also possible to connect devices described in group “Addicted to cloud” and control these devices just from your own server. There are several other open source home automation systems. You can find the list at OpenSource.com.

Price: 0 Kč / 0 EUR


Zigbee is similar protocol to Z-Wave. It operates in 2.4 Ghz like WiFi or BlueTooth. You need also separate dongle to talk to this network of devices. Zigbee has been adopted also by Samsung Smartthings.

There are also other protocols, but the idea is always the same. You need dongle or special bridge to talk to your network of devices. These devices are often able to talk with each other.


As you can see the market is quite diverse and complex. We started with very simple solutions and gradually continued to very complex server controlled solutions. It is often confusing for beginners to spot difference between socket using WiFi or Z-Wave. I hope that this article shed some light to the topic.

Thank you for reading. If you see that something in article is not correct or misleading, let me know. I’ll be happy to fix it.

And what was my decision after weekend analysis of Smart Home? I will buy just a simple flash light and I will turn the switch manually 😉

11. October 2016

Siriel 05 – Open source game engines

After working with Unity Editor I have realized that it has several drawbacks from my point of view.

  • Build time for HTML5 was extremely long even when the game was very small. It took several minutes to build the application.
  • Personal license always displays logo of Unity and I had to wait for the logo to fade out even when doing small iterations and testing of the game.
  • Unity is close source and even when I found the bug, Unity QA was not able to simulate it and they dropped the issue.

I started to seek for other engines and I was surprised by myriad of engines described at Wikipedia. The list is quite exhaustive and it is little bit hard to recognize the maturity of each project.

There is another list at GitHub which contains just open source engines. Projects are sorted by stars which makes it easier to see how is the project popular.

  • Where’s the fish?

  • Further info

  • Twitter

    • I consider using delay/sleep in IoT methods as bad practice. It reminds me of goto in old days of C. Just try it without delay... Be async
    • I'd like to report IoT success: Temperature -> DHT -> ESP8266 -> WiFi -> MQTT -> Node Red -> Influx DB -> Grafana.
    • Lamp ESP8266 code updated and WiFiManager is working. Here you can read about some gotchas with WiFiManager: t.co/ZlAzCFE5dh

    Follow @jurajmichalek on twitter.

  • Tags

  • Topics

  • Comments