ESP8266 & Apple HomeKit – Let’s get started

There are quite a few different types of smart home systems, also known as smart home. Each has its own advantages and disadvantages, and choosing the right system really depends on the individual user’s preferences. One such system is HomeKit from Apple. In this and subsequent materials in this series, I would like to tell you a little about how to integrate HomeKit and the well-known ESP8266 modules. I will show you how to configure such a module so that its operation can be controlled from an iPhone, MacBook or Apple Watch. In addition, we will connect to the outputs of our microcontroller various peripheral modules, the operation of which will be controlled by ESP.

Also see:

Co-kryje-wnetrze-zarowki-2-1024x576

What is Apple HomeKit?

View of the Home application on your computer

Apple HomeKit is nothing more than one of the systems that allow you to build a smart home. On every piece of hardware from the Cupertino company there is a Home application by default, which allows you to control various accessories and read data from sensors. It supports many types of actuators, which do not necessarily have to bear the logo of the bitten apple.

We can control all accessories from any Apple device connected to the same network. If you want remote access, you need to equip yourself with the original hub, perhaps an Apple HomePod or Apple TV. Unfortunately, without it, there is no way to control devices from anywhere in the world. By adding a hub to the system, we also gain the ability to automate and synchronize, that is, to intelligently control accessories according to a predetermined schedule – the bedside lamp starts at 6 a.m. on weekdays when we turn on the TV, the light dims, and the air conditioner turns off when we open the window. There are quite a few possibilities, and everything really depends on our imagination. Besides, the hub also allows you to control your accessories through the voice assistant – Siri.

Hardware and software, or what will we need?

There are quite a few different kinds of devices supported by Apple HomeKit, but nothing prevents you from building something like this yourself, all you need is an ESP8266 module. This small, Chinese-origin SoC has gained considerable popularity mainly due to its simplicity of use, low price and great capability. The chip supports WIFI in the 802.11 b/g/n standard, making it ideal for building small IoT devices.

The ESP8266 module, or more precisely the ESP-12E model that I will use in my tutorials, can be programmed, among other things, from the Arduino IDE, which is well known to all electronics engineers. However, the environment must first be properly prepared.

  1. The first step is to add support for the ESP module itself. To do this, open the program’s preferences window and, in the “Additional URLs for the tile manager” field, paste the link I’ve included below. If there are more links, separate them with commas. (https://arduino.esp8266.com/stable/package_esp8266com_index.json)
    After pasting the address, expand the menu of available tiles and open the “Tile Manager”, where you should find the ESP8266 package and install it.
  2. The second step is to add the appropriate library supporting Apple HomeKit to the Arduino IDE. You can download it here, the downloaded zip package should be added to the environment. To do this, in the “Draft” tab, we find the “Add .ZIP library” command and select the downloaded file a moment before.

Thus, we prepared the environment, that is, we added support for ESP8266 modules and support for Apple HomeKit, thanks to an additional library.

ESP8266 output control

Each project that connects the ESP module to Apple HomeKit is based on three files, we will not look at the whole thing, we will only describe to you the main ideas of each of them and the code snippets that you need to modify “under you” to build your own device.

All the code is available on my GitHub profile, if you want to download the project, allowing you to control ESP8266 outputs click here.

As I mentioned earlier, the codes linking ESP and Apple HomeKit actually consist of three files:

  • ESP_HomeKit_Output_control.ino – this is the main file, containing the code executed by the ESP8266 module referring to the other files. This is where the basic configuration parameters are placed. Besides, when we connect peripheral modules to our microcontroller in the future, we will describe their handling here.
  • my_accessory.c – In this file is placed the configuration of our device as a whole. Here we can find information about the name, serial number and access password that allows us to connect to the equipment from HomeKit.
  • wifi_info.h – The last file, which is a header file, contains information about the network we want to connect to. This is where we will put its name and password.

Once we know what our project will consist of, we can move on to running the first project. This will be a simple switch, allowing us to control the output of the ESP from Apple HomeKit. In the example, I connected an LED to the module’s output, but nothing prevents you from connecting a relay there, for example. With it, you can control other, even mains-powered devices.

//==============================
// HomeKit setup and loop
//==============================

// access your HomeKit characteristics defined in my_accessory.c
extern "C" homekit_server_config_t config;
extern "C" homekit_characteristic_t cha_switch_on;

static uint32_t next_heap_millis = 0;

#define PIN_SWITCH 2

In the main code, we really only need to pay attention to one line of code. It is here that the definition of the pin we want to control is placed. In other words, here we choose the number of the output whose state we will modify. In the example, I have placed the number 2, which means that we will control the D4 pinout, because the two actually refers to the GPIO designation, in this case GPIO2, is output to the D4 port.

homekit_accessory_t *accessories[] = {
    HOMEKIT_ACCESSORY(.id=1, 
    .category=homekit_accessory_category_switch, .services=(homekit_service_t*[]) {
        HOMEKIT_SERVICE(ACCESSORY_INFORMATION, 
        .characteristics=(homekit_characteristic_t*[]) {
            HOMEKIT_CHARACTERISTIC(NAME, "LED Switch"),
            HOMEKIT_CHARACTERISTIC(MANUFACTURER, "HomeKit Rafal"),
            HOMEKIT_CHARACTERISTIC(SERIAL_NUMBER, "0123456"),
            HOMEKIT_CHARACTERISTIC(MODEL, "ESP8266"),
            HOMEKIT_CHARACTERISTIC(FIRMWARE_REVISION, "1.0"),
            HOMEKIT_CHARACTERISTIC(IDENTIFY, my_accessory_identify),
            NULL
        }),
		HOMEKIT_SERVICE(SWITCH, 
		.primary=true, .characteristics=(homekit_characteristic_t*[]){
			&cha_switch_on,
			&cha_name,
			NULL
		}),
        NULL
    }),
    NULL
};

homekit_server_config_t config = {
		.accessories = accessories,
		.password = "111-11-111"
};

In the my_accessory.c file we can put the identifiers of our device. The first is the name, which is the text under which the hardware will be visible in the Home application panel. I named the example project simply “LED Switch”, notice that the name occurs in two places.

In the next field there was information about the manufacturer, I put there the text “HomeKit Rafal”. This makes it easy to distinguish the device you built from other equipment from other manufacturers.

The remaining lines of the code contain the serial number of the device, its model and the numerical designation of the program version.

At the end of the file there was a very important piece of information – the password for connecting to the ESP module. In the example it consists of only ones, but when building the target device, it is worth changing it.

const char *ssid = "your-ssid";
const char *password = "your-password";

In the last file we need to put information about the network with which the ESP8266 is to connect. This is its SSID, or name, and password.

After changing the key information in the code, you can prepare the test circuit and program the ESP module. In my example, I connected an LED to pin D4 (GPIO2), the one whose number I put in the main file, so we will be able to see the actual effects of controlling the microcontroller.

Configuring the device in the Home application

Once the ESP module is programmed, we can add it in the Home app. The easiest way is to open it on the iPhone and click on the “+” visible at the top edge. Then select the “Add accessory” option.

In the newly visible window, we select “More options,” since the ESP does not have a QR code that can be scanned.

After a while, the ESP module should be visible on the screen as an LED Switch, when you click it, you may see warnings indicating that the accessory is not certified. Ignore them and select the “Add nevertheless” option.

The next step is to enter the configuration code, we put it at the end of the my_accessory.c file.

Next we will be asked to select a room, that is, the location of the device. For the purpose of the test, I created a special room at my place called “Test”. Next we can name the equipment to be added, by default it will take the name we put earlier in the code.

In the final step we will be asked to choose what our device is. After going through all the configuration steps, we click the “Done” button.

From now on, we can control the ESP8266 module from the Dom app on any hardware from the Cupertino company. In the video above you can see that despite configuring the microcontroller from the iPhone, you can immediately control the module from the MacBook. As you can see, by changing the position of the switch on the computer, the state of the LED connected to the ESP also changes. In this oh-so-simple way we connected this small SoC to Apple HomeKit.

ESP reset and code change

void setup() {
	Serial.begin(115200);
	wifi_connect(); // in wifi_info.h
	//homekit_storage_reset(); // to remove the previous HomeKit
	//pairing storage when you first run this new HomeKit example
	my_homekit_setup();
}

There is one more issue that I need to write about. It is about resetting the ESP8266 module and connecting to it after modifying the code. It is important to remember that after programming the module and connecting to it through the Appel hardware this module is remembered, not only in the Home application, but also ESP itself remembers some configuration data. This results in the fact that after a minor modification of the code, even the name of the device, this one will not be available, in other words, you will not be able to connect to it. Therefore, every time you modify it, you need to follow a predetermined procedure.

Wanting to change the code and reconnect to the device, you need to comment out the homekit_storage_reset(); command found in the .ino file and upload the code. Then wait for a while so that the ESP will boot. After this process, comment back the homekit_storage_reset(); line and upload the new code. This operation erases all configuration data from the ESP and allows you to reconnect to Apple HomeKit.

Also see:

Sources:

  • https://github.com/Mixiaoxiao/Arduino-HomeKit-ESP8266/tree/master
  • https://github.com/esp8266/Arduino

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top