simon

simon

github

DIY HomeKit Smart Home

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 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 drawbacks are evident: 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, unverified smart devices can be connected to HomeKit.

Goals#

  1. Build a high-experience smart home at low cost, with voice control.
  2. Create a relatively complete smart home experience.
  3. Transform old devices that do not support smart home features into smart devices.
  4. 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, which is a preparation 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 section

    @周子韧

  • Logitech Harmony Hub (controls all infrared devices in the home: air conditioner, TV, speakers, fans, air purifiers, electric drying racks): 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 Image on Windows
  • Linux users... you can 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.

  • 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 subsequent Homebridge configuration file, but it can only be obtained from the "Mi Home" App on an Android phone.

  • Click into the gateway option in the App -> enter the "..." in the upper right corner of the screen -> go to "About" -> continuously press the version number area at the bottom of the screen to activate developer mode
  • Click on the "LAN Communication Protocol" option, enable the LAN communication protocol, and note down the password
  • Return to the previous menu, and 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, primarily using the Linux-based Raspbian system, but can also install Debian GNU/Linux, Fedora, Arch Linux, RISC OS, and supports Windows 10 IoT for 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 those unfamiliar with Linux commands, just copy and paste the commands.

Install the System#

I chose to have the vendor copy the system onto the SD card when I purchased it, but you can also download it yourself and burn it onto the SD card.

  1. Download the Raspbian Jessie version system (now upgraded to the latest Stretch). [Raspberry Pi System Download Link](Index of /raspbian/images)
  2. On Windows, you can use SDFormatter to format the SD card, then use Win32 Disk Image to burn the system onto the SD card. On Mac, ApplePi is recommended for burning the system and backing up.
  3. The Raspberry Pi has SSH disabled by default, and it can be easily enabled by creating an empty ssh file in the root directory of the system on the SD card.
  4. 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.
  5. Connect the Raspberry Pi to your computer via Ethernet, and log in using SSH. The default password is raspberry

ssh [email protected]

  1. Configure Wi-Fi; otherwise, you need to connect the Raspberry Pi to the router with an Ethernet cable.

For those unfamiliar with vi, you can use the nano text editor to edit source files, 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.

  1. 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

  1. Update the repository and reorganize dependencies

sudo apt-get update && sudo apt-get upgrade

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 still 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 devices 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 they will need to be written into the configuration file.

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]

Use the above miio --discover --sync command 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.

  1. Download the MyHarmony client for your computer, available for both Mac and Windows.
  2. Connect the Hub to the computer via USB, and it will recognize the Hub. Connect to the 2.4GHz Wi-Fi.
  3. Once the Wi-Fi is recognized, enter the Wi-Fi password.
  4. Register an account to manage settings across different devices; it is recommended to use an email.
  5. It prompts you to connect the Remote control to continue; click the Skip button in the lower right corner. Although it states that Skip is only for when the Remote is present, it also applies when only the Hub is present.
  6. Once recognition is complete, enter the management interface. It will prompt you to name your Hub, then prompt you to add devices.
  7. 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.
  8. The left menu has Activities, where you can set up automated control activities. For example: Watching TV = Turn on TV + Set-top Box + Speakers + Adjust to your favorite channel. Finally, each Activity will be added to HomeKit as a socket-type device.
  9. 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 simply by entering it in the terminal. However, it will close when the terminal is closed, and in case of a power outage and restart, the service will close. Therefore, we need to configure a startup for HomeKit. The Homebridge GitHub page recommends three methods, and 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 below. Note: The position after cmd should be filled with the directory where your Homebridge is located. Use the following command to find the location of Homebridge:

`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 for using the Home app on iPhone, iPad, and iPod touch.

Connect your iPhone to the same local network, open the Home app, create a new home, and you can add Homebridge.

At this point, you will find that the app asks you for a verification code to verify the device. Official HomeKit devices have this, but ours do not. I spent 5 minutes looking for this, only to find that the verification code is generated when the Homebridge server starts, and we can 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 when you are outside the home.

If you do not have these devices, it is fine; the Mi Home app also has remote control capabilities (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

THEN: 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

THEN: Turn on the air conditioner, set to cooling mode at 25 degrees. Requires Xiaomi Air Conditioner Companion or universal remote control.

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 with burning software before continuing to tinker with other things; don't ask me how I know this...
  • Unless there are special needs, 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 the inability to control the bulb. Thanks to Yeelight's staff for actively communicating with me at 8 PM to help me find the problem.
  • 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 area 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 the Raspberry Pi; fan cooling is not very effective and can be noisy.

Final Effect#

Finally, here is a small video recorded during the first successful attempt.

https://pic4.zhimg.com/80/v2-63ece8d4d3ef454657b83b3bafdb08ab_1440w.jpg

https://pic4.zhimg.com/80/v2-7b0b6543c3f352bf692c496849cf1c2b_1440w.jpg

https://pic2.zhimg.com/80/v2-f97c6bc17afa418786f8e632db36c529_1440w.jpg

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.