Homemade HomeKit Smart Home#
Created: June 22, 2021 3:59 PM
Tags: HomeKit, Smart Home, Raspberry Pi
This article was previously published on Zhihu (https://zhuanlan.zhihu.com/p/31423265) and a few other platforms. This is an archive, and the actual writing time was in 2017.
Introduction#
This article was written when I was tinkering with the Raspberry Pi six months ago. It may not be suitable for this column, as it lacks the technical depth compared to the articles by other experts in my company. However, it is not entirely without merit; at least anyone can easily understand and implement the content in this article and experience the joy of coding.
What is HomeKit?#
HomeKit is a smart home component provided by Apple since iOS 10, allowing third parties to connect certified smart hardware to the iOS system and control it via Siri. It uses end-to-end encryption within the local network, making it quite secure. However, the obvious downside is that certified hardware is expensive and scarce. But this is not a problem because we have Homebridge.
What is HomeBridge?#
According to a paper written by a former employee of Apple's HomeKit team, Homebridge is a server framework that simulates the HomeKit API using NodeJS, which has over 7,000 stars on GitHub. By writing corresponding plugins, unapproved smart devices can be connected to HomeKit.
Goals#
- Build a high-experience smart home at low cost, controllable by voice.
- Create a relatively complete smart home experience.
- Transform old devices that do not support smart home functionality into smart devices.
- Strong portability, easy to take when moving.
Preparation#
Hardware Preparation:#
-
Raspberry Pi 3 Model B: 200 RMB
-
Raspberry Pi Power Supply (5V 2.5A): An Android 2A charger is also fine; 2.5A can support high-power operation, just to prepare for the future.
-
16G SD Card (preferably class 10 speed): 50 RMB
-
One Ethernet cable
-
Yeelight Bulb: 99 RMB
-
Xiaomi Gateway 2nd Generation: 149 RMB
-
Xiaomi Temperature and Humidity Sensor: 49 RMB
-
Xiaomi Human Motion Sensor: 59 RMB
-
Xiaomi Door and Window Sensor: 49 RMB
-
Xiaomi Smart Socket Zigbee Version: Controls water heater: 69 RMB
-
Xiaomi Air Conditioner Companion: Supports Homebridge: 199 RMB Thanks to the reminder in the comments
-
Logitech Harmony Hub (controls all infrared devices in the home: air conditioner, TV, audio, fan, air purifier, electric drying rack): 299 RMB
-
Xiaomi Air Purifier 2nd Generation: 699 RMB
Other Hardware to Prepare#
- A phone or tablet that supports iOS 10.
- An Android phone (to obtain the gateway password, so borrowing one is fine).
- A router.
Future Work:#
- Aqara Wall Switch (poor portability, consider later)
- Door Lock
- Electric Curtains: Infrared remote-controlled electric curtains + Harmony will do, or use Xiaomi's electric curtains
- Camera
- SSH Commands (link)
- Bluetooth Devices (Speakers) (link)
- Home Assistant Supported Devices
Excluding the air conditioner companion and purifier, the total is 1023 RMB.
Software Preparation#
For burning the system onto the SD card
- ApplePi on Mac
- SDFormatter and Win32 Disk Imager on Windows
- Linux users... just use the dd command directly.
Installation#
Yeelight Bulb#
Download the Yeelight App, follow the instructions to connect the bulb, and then enable Geek Mode.
Xiaomi Gateway and Related Sensors#
- Plug in the Xiaomi Gateway, download the "Mi Home" App. Connect your phone to the 2.4GHz Wi-Fi network (most existing smart home devices do not support 5GHz Wi-Fi), follow the instructions to add the gateway, and then add other sensors.
Obtain the Gateway's MAC Address and Communication Password#
The gateway information is needed in the later Homebridge configuration file, but it can only be obtained from the "Mi Home" App on an Android phone.
- Click the App to enter the gateway option -> go to the top right corner of the screen "..." -> enter "About" -> continuously press the version number area at the bottom of the screen to activate developer mode
- Click on "LAN Communication Protocol" option, enable LAN communication protocol, and note down the password
- Return to the previous menu, a "Gateway Information" option will appear in developer mode -> record the MAC address (the string of 6 pairs of alphanumeric characters after the 'mac' field)
Raspberry Pi#
The Raspberry Pi is a hardware project led by a professor at the University of Cambridge, aimed at promoting computer education for children. It primarily uses the Linux-based Raspbian system, but can also run Debian GNU/Linux, Fedora, Arch Linux, RISC OS, and Windows 10 IoT on models B and above.
Configuration of the Raspberry Pi 3 Model B:
- Equipped with a 1.2GHz 64-bit quad-core processor (ARM Cortex-A53 1.2GHz 64-bit quad-core ARMv7 CPU).
- Added 802.11 b/g/n wireless network card.
- Added low-energy Bluetooth 4.1 adapter.
It mainly serves as the server for Homebridge, allowing devices that do not support HomeKit to be recognized by HomeKit.
For friends unfamiliar with Linux commands, just copy and paste the commands as needed.
Install the System#
I chose to have the vendor copy a system onto the SD card when I purchased it, but you can also download it yourself and burn it onto the SD card.
- Download the Raspbian Jessie version system (now upgraded to the latest Stretch). [Raspberry Pi System Download Link](Index of /raspbian/images)
- On Windows, you can use SDFormatter to format the SD card, then use Win32 Disk Imager to burn the system onto the SD card. On Mac, I recommend using ApplePi for system burning and backup.
- The Raspberry Pi has SSH disabled by default; enabling it is simple: just create an empty ssh file in the root directory of the system on the SD card.
- Connect the power line (mini USB), connect the Ethernet cable directly to your home router, and insert the SD card. The system will automatically boot and install.
- Connect the Raspberry Pi to your computer via Ethernet, and use SSH to log in; the default password is raspberry
- Configure Wi-Fi; otherwise, you need to connect the Raspberry Pi to the router via Ethernet.
For those unfamiliar with vi, you can use the nano text editor to edit the source file, which operates similarly to a regular text editor. Use ctrl + O to save and ctrl + X to exit. It is recommended to back up the original file using the cp command before editing. Alternatively, you can use the following command to replace the official Raspberry Pi source and third-party sources with Tsinghua sources in one step.
sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
Add the following content:
network={ ssid="wifiname" psk="password" }
After saving, disconnect the Ethernet cable, and it will connect to Wi-Fi within a few seconds.
- Modify the mirror source; the original system update source is relatively slow in China, causing timeout errors when installing other programs. You can switch to a domestic source or enable SS service.
sudo sed -i 's#://archive.raspberrypi.org/debian#s://mirrors.tuna.tsinghua.edu.cn/raspberrypi#g' /etc/apt/sources.list.d/raspi.list sudo sed -i 's#://archive.raspberrypi.org/debian#s://mirrors.tuna.tsinghua.edu.cn/raspberrypi#g' /etc/apt/sources.list.d/raspi.list
- Update the library and reorganize dependencies
sudo apt-get update && sudo apt-get upgrade
Install NodeJS and Dependencies, Homebridge, and Related Plugins#
Install NodeJS#
First, check the chip version of the Raspberry Pi being used
uname -a
My returned chip version is armv7l:
Linux raspberrypi 4.4.50-v7+ 970 SMP Mon Feb 20 19:18:29 GMT 2017 armv7l GNU/Linux
Use the following command to download and install node6; node7 is not very stable, and node5 is not very compatible with Homebridge.
curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash - sudo apt-get install -y nodejs
Install Avahi#
sudo apt-get install libavahi-compat-libdnssd-dev
Install Homebridge#
sudo npm install -g --unsafe-perm homebridge
If the above command does not run smoothly, it means some additional configuration is needed. Run the following commands:
sudo npm install -g --unsafe-perm homebridge hap-nodejs node-gyp cd /usr/local/lib/node_modules/homebridge/ sudo npm install --unsafe-perm bignum cd /usr/local/lib/node_modules/hap-nodejs/node_modules/mdns sudo node-gyp BUILDTYPE=Release rebuild
Install homebridge-aqara, Aqara Protocol Gateway and Sensors#
sudo npm install -g homebridge-aqara
Install homebridge-yeelight, Yeelight Bulb Plugin#
sudo npm install -g homebridge-yeelight
Install Xiaomi Air Purifier Plugin#
npm install -g homebridge-mi-air-purifier miio
Disconnect other smart devices, leaving only the air purifier. Then enter the following command to obtain the purifier's IP and Token.
miio --discover --sync
It may return multiple device information in the following format:
Device ID: 49466088 Model info: Unknown Address: 192.168.1.8 Token: 6f7a65786550386c700a6b526666744d via auto-token Support: Unknown
Note down the address and token, as you will need to write them into the configuration file later.
Install Xiaomi Air Conditioner Companion Plugin#
The latest version 0.5.1 has a bug and cannot start temporarily; an issue has been raised, waiting for the author to update.
sudo npm install -g [email protected]
Also use the above miio --discover --sync
to discover the air conditioner companion and associated temperature and humidity sensor's device_id (fill in the sensorSid value 'lumi.' after).
Add Infrared Devices to HomeKit#
Later, I discovered the Logitech Harmony Hub infrared remote control device, which supports 280,000 devices (supports infrared learning for new devices) and is under 300 RMB. It also has a plugin to connect to Homebridge. After installation, infrared devices in the home, such as air conditioners, TVs, air purifiers, and electric drying racks, can be controlled via Siri. Follow the instructions to connect infrared devices, with a maximum of 7.
Installation process:
A global scientific internet connection is required throughout.
- Download the MyHarmony client for your computer, available for both Mac and Windows.
- Connect the Hub to the computer via USB, and recognize the Hub. Network connection to 2.4GHz Wi-Fi.
- Recognize the Wi-Fi and enter the Wi-Fi password.
- Register an account to manage settings across different devices, preferably using an email.
- It will prompt you to connect the Remote control to continue; click the Skip button in the lower right corner. Although it states that Skip is only applicable when the Remote is present, it actually applies to the Hub alone as well.
- Recognition is complete, and you will enter the management interface. It will prompt you to name your Hub. Then it will prompt you to add devices.
- Add devices by brand name and model number; if not found in the database, you can add manually and learn the remote control via infrared.
- The left menu has Activities, where you can set up automated control activities. For example: Watching TV = Turn on TV + Set-top Box + Audio + Adjust to your favorite channel. Finally, each Activity will be added to HomeKit as a socket-type device.
- Below are the settings for the Harmony plugin and configuration file.
Access the Raspberry Pi terminal via the terminal, then install the Harmony Hub plugin.
sudo npm -g install homebridge-harmonyhub
Create Homebridge Configuration File config.json#
mkdir /home/pi/.homebridge/ sudo nano /home/pi/.homebridge/config.json
Content and Format of Homebridge Configuration File#
You need to include the gateway's password and MAC address, as well as the configuration information for the Aqara gateway and Yeelight. # Please delete the comment sections.
The pin is used to join the Home app on iPhone
{ "bridge":{ "name":"YeeBridge", "username":"Any MAC address", "port":51827, "pin":"031-45-157" }, "platforms":[ { "platform":"yeelight", "name":"yeelight" }, { "platform":"AqaraPlatform", "sid":[ "Fill in the MAC address of the gateway, in lowercase, without spaces" ], "password":[ "Gateway password" ] }, { "platform":"HarmonyHub", "name":"Harmony Hub" }, { "platform":"XiaoMiAcPartner", "ip":"Air Conditioner Companion IP", "token":"Air Conditioner Companion Token", "accessories":[ { "name":"Ac Partner", "type":"climate", "sensorSid": "lumi.{device_id}" } ] } ], "accessories":[ { "accessory":"MiAirPurifier", "name":"Air Purifier", "ip":"Purifier IP", "token":"ADDRESS_OF_THE_AIR_PURIFIER", "showTemperature":true, "showHumidity":true, "showAirQuality":true } ] }
Configure Homebridge to Start on Boot#
At this point, you can run Homebridge by simply entering homebridge in the terminal. However, it will shut down when the terminal is closed, and in case of a power outage and restart, the service will shut down. Therefore, we need to configure a startup for HomeKit. The Homebridge GitHub page recommends three methods; I chose the most convenient init.d method.
First, download a configuration file from here and copy all the content. Download
Then use the following command to create a Homebridge startup file in the init.d directory:
sudo nano /etc/init.d/homebridge
Directly copy and overwrite the content in the file, Note that the position after cmd should be filled with the directory where Homebridge is located. To find the location of Homebridge, use the following command:
`which homebridge
#!/bin/sh
BEGIN INIT INFO#
Provides: homebridge#
Required-Start: $network $remote_fs $syslog#
Required-Stop: $remote_fs $syslog#
Default-Start: 2 3 4 5#
Default-Stop: 0 1 6#
Short-Description: Start daemon at boot time#
Description: Enable service provided by daemon.#
END INIT INFO#
dir="/home/pi"
cmd="DEBUG=* /usr/local/bin/homebridge"
user="pi"`
Change the file permissions:
sudo chmod 755 /etc/init.d/homebridge sudo update-rc.d homebridge defaults
After rebooting, it will start automatically, or you can start it manually:
sudo /etc/init.d/homebridge start
Add Devices to the Home App#
You can refer to Apple's official [User Guide](Using the Home App on iPhone, iPad, and iPod touch)
Connect the iPhone to the same local network, open the Home App, and create a new home to add Homebridge.
At this point, you will find that the app asks you for a verification code to verify the device. Regular HomeKit devices have this, but ours do not. I spent 5 minutes looking for this code at first, only to realize that the terminal has already generated it when starting the Homebridge server; we just need to find it and enter it manually.
It is the PIN part in the configuration file.
At this point, all devices will appear in the App, and you can press and hold to edit their room and name categories.
Remote Control and Automation#
Remote Control#
To ensure security, HomeKit's default supported environment is within the local network. However, if you have an iPad that can be upgraded to iOS 10 or an Apple TV 4th generation or above, you can configure it as a central control in the settings, allowing you to control these devices while outside the home.
If you do not have these devices, it is fine; the Mi Home app also allows for remote control (though it is quite difficult to use).
Automation#
Automation allows you to set various rules to automatically control devices in your home.
For example:
IF (When): The gateway light sensor detects darkness, and someone enters the bedroom
Execute: Turn on the bedroom light
IF (When): The temperature sensor detects over 30 degrees, and the doors and windows are closed, and someone is detected in the house
Execute: Turn on the air conditioner, set to cooling mode at 25 degrees. Requires Xiaomi Air Conditioner Companion or universal remote.
Pitfalls#
- Read the official documentation! Read the official documentation! Read the official documentation!
- After tinkering, be sure to back up the system on the SD card using burning software before continuing to tinker with other things. Don't ask me how I know this...
- Unless there is a special need, do not set a static IP for the Raspberry Pi, as Yeelight uses TCP for communication. If the router's DHCP assigns a different subnet IP to the Yeelight device, it will lead to an inability to control the bulb. Thanks to Yeelight's staff for actively communicating with me around 8 PM to help me find the issue.
- NodeJs 6 is the most suitable; 5 has compatibility issues, and 7 is still not very stable.
- The progress of adding other Xiaomi devices to Homebridge is not very fast. Follow the engineer responsible for this on Zhihu; he hasn't made significant changes in almost a month. However, he mentioned that support for the air conditioner assistant is coming (finally third-party support), and I think support for the universal remote is more important as it can quickly enhance playability.
- Prepare some heat sinks or metal pillars for cooling; fan cooling is not very effective and can be noisy.
Final Effect#
Finally, here is a small video recorded during my first successful attempt.