Using a Raspberry Pi Zero W to Add a Camera and a Xiaomi Air Purifier 2 to HomeKit via Homebridge

I recently purchased a Xiaomi Air Purifier 2, to avoid having dirty air in my apartment. Unfortunately, this product does not integrate with HomeKit. I am generally averse to having my “connected” home accessible from the internet, but I did want to use the HomeKit automation features. Setting this whole thing up just for one air purifier did seem like a lot of hassle, until I found out (from Steven Troughton-Smith) that you can get a Raspberry Pi Zero W with a camera module, which also works under HomeKit. Two-in-one? No need to ask me twice.

Please note that the instructions below are specific to the Raspberry Pi Zero W. You will need to adjust them if you are using a different model.

Ingredients

Raspberry Pi Zero W Camera Pack [Adafruit / Botland] or Raspberry Pi Zero W Camera NoIR Pack [Adafruit / Botland ] — 1x.

Xiaomi Air Purifier 2 [Amazon.de] — at least 1x.

microSD card — a fast one is preferable, 8 GB or more (if you want to consider storing images and video).

Downloads

Unless you purchased a microSD card with your Raspberry Pi Zero W Camera Pack, which comes pre-installed with NOOBS1, then you will need to download Raspbian to your Mac or PC:

Raspbian Stretch with Desktop — just get the ZIP file.

Etcher —to burn Raspbian on your microSD card.

You will need to unzip the first file after it’s downloaded.

Burning Raspbian to Your microSD Card

Install Etcher by mounting the DMG file and then copying over the program to your /Applications folder.

Launch Etcher.

Press the big plus symbol and select 2017-11-29-raspbian-stretch.img (or equivalent).

Choose your microSD card under the middle icon — please make sure that you are not erasing the wrong card/drive or any critical data!

Press Flash!

After the process finishes, remove the microSD card and re-insert it into your card reader, to mount it again.

Configuring SSH and Wi-Fi

Since we’re not going to be connecting the Raspberry Pi Zero W to a display or keyboard, you need to setup Wi-Fi and SSH beforehand.

Create a new file in the root directory of the microSD card with Raspbian, named wpa_supplicant.conf.

Edit that file with a text editor (I use BBedit):
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=COUNTRY_CODE

network={
ssid="YOUR_WI-FI_SSID"
psk="YOUR_PASSWORD"
key_mgmt=WPA-PSK
}

Please replace COUNTRY_CODE with your country’s code, e.g. US for USA, PL for Poland, and so on. Replace YOUR_WI-FI_SSID with whatever your SSID is — mine is CIA Surveillance Van 12. Finish off with replacing YOUR_PASSWORD with your Wi-Fi password.

Save the file.

Create another file in the root folder of your microSD card and call it ssh (without an extension). Leave the file empty. This will enable SSH (it’s disabled by default).

Ignition!

We now need to:

Insert the microSD card into the proper slot in the Raspberry Pi.

Connect the Raspberry Pi Camera cable to the Raspberry Pi Zero W.

Insert the Raspberry Pi into the case — it should make a satisfying click.

Insert the camera module into the top half of the case.

Put both halves together.

Connect the Raspberry Pi to the included power adapter.

The RPi Zero W should log onto your Wi-Fi network within a minute or so. You can connect to your router to find its IP address. The next step, is to connect to it via SSH:

Launch Terminal.

SSH to the RPi: ssh pi@xxx.xxx.xxx.xxx (please input the RPi’s IP address).

Enter the password: raspberry.

This should get you in. The first thing you need to do is change the default password:

Enter passwd into Terminal.

Create a new password and save it somewhere safe, like 1Password.

We need to update/upgrade everything now by entering the following commands in Terminal:

Type in sudo apt-get update into Terminal, press Enter and wait for it to finish.

Type in sudo apt-get upgrade, press Enter and wait.

Type in sudo apt-get dist-upgrade.

Type in sudo apt-get clean.

Type in raspi-update.

And now it’s time to reboot: sudo reboot.

This might take a minute or three — be patient.

Installing node 8.9.4

At the time of writing this, I was informed that I will specifically need node 8.9.4. I tried running version 9.x.x and it didn’t work. If you know why this specific version is required for Homebridge, please let me know.

Type node -v to check your current node version — it will probably be 4.x.x.

cd to return to your home folder.

wget https://nodejs.org/dist/v8.9.4/node-v8.9.4-linux-armv6l.tar.xz to download node 8.9.4.

You will need to unpack node now: tar -xvf node-v8.9.4-linux-armv6l.tar.xz.

cd node-v8.9.4-linux-armv6l/.

Type in whereis node to discover where node is installed. The result will be similar to this: node: /usr/bin/node /usr/local/bin/node /usr/share/man/man1/node.1.gz Make note of the first item, /usr/bin/node in this case.

If the first item was /usr/bin/node then type in: sudo cp -R * /usr/. If /usr/local/bin/node then type in: cp -R * /usr/local/.

Now check if the installed version is correct: node -v. The result should be v8.9.4.

Install Homebridge and Add Your Xiaomi Air Purifier 2

Homebridge is a service which makes non-HomeKit devices visible under HomeKit.

You need to install a few libraries first: sudo apt-get install libavahi-compat-libdnssd-dev.

And then Homebridge itself: sudo npm install -g --unsafe-perm homebridge.

We will need to edit a few files soon. I personally use nano, but feel free to use your editor of choice.

sudo nano /etc/default/homebridge to edit that file.

Paste the following into the file:
# Defaults / Configuration options for homebridge
# The following settings tells homebridge where to find the config.json file and where to persist the data (i.e. pairing and others)
HOMEBRIDGE_OPTS=-U /var/homebridge

# If you uncomment the following line, homebridge will log more
# You can display this via systemd's journalctl: journalctl -f -u homebridge
# DEBUG=*

Type ^X (Control + X), press y and Enter to save the file.

sudo nano /etc/systemd/system/homebridge.service to edit another file.

Paste:
[Unit]
Description=Node.js HomeKit Server
After=syslog.target network-online.target

[Service]
Type=simple
User=homebridge
EnvironmentFile=/etc/default/homebridge
ExecStart=/usr/local/bin/homebridge $HOMEBRIDGE_OPTS
Restart=on-failure
RestartSec=10
KillMode=process

[Install]
WantedBy=multi-user.target

Type ^X, y and Enter to save.

You’ll want to automate Homebridge, to start automatically if/when the Raspberry Pi is restarted: sudo useradd --system homebridge.

sudo mkdir /var/homebridge.

cp /usr/local/lib/node_modules/homebridge/config-sample.json ~/.homebridge/config.json.

We need to install one more tool, which is required for the Xiaomi Air Purifier 2: sudo npm install -g homebridge-mi-airpurifier miio.

Type in miio discover sync to find your Xiaomi Air Purifier 2 on the network. The result of the search will look like this:
Device ID: xxxxxxxx
Model info: zhimi.airpurifier.m2
Address: 192.168.xxx.xxx
Token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx via auto-token
Support: At least basic

Please copy your Token and Address from the result — we’ll require this information soon.

Press ^C to close miio.

We now need to prepare our configuration file: nano ~/.homebridge/config.json.

Please generate a random MAC address using this tool. You will need it to comply to this format: XX:XX:XX:XX:XX:XX, e.g. F2:4A:25:C1:87:57.

Since the file is empty, please paste the following into it:
{
"bridge": {
"name": "Homebridge",
"username": "XX:XX:XX:XX:XX:XX",
"port": 51826,
"pin": "031-45-154"
},

"description": "HomePi Homebridge.",

"platforms": [
{
"platform": "MiAirPurifierPlatform",
"deviceCfgs": [
{
"type": "MiAirPurifier2",
"ip": "192.168.xxx.xxx",
"token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"airPurifierDisable": false,
"airPurifierName": "MiAirPurifier2",
"silentModeSwitchDisable": false,
"silentModeSwitchName": "MiAirPurifier2 Silent Mode Switch",
"temperatureDisable": false,
"temperatureName": "MiAirPurifier2 Temperature",
"humidityDisable": false,
"humidityName": "MiAirPurifier2 Humidity",
"buzzerSwitchDisable": true,
"buzzerSwitchName": "MiAirPurifier2 Buzzer Switch",
"ledBulbDisable": true,
"ledBulbName": "MiAirPurifier2 LED Switch",
"airQualityDisable": false,
"airQualityName": "MiAirPurifier2 AirQuality"
}]
}]
}

Please replace XX:XX:XX:XX:XX:XX in the file above with the MAC address you generated in step 15.

Please add the IP address of your Xiaomi Air Purifier 2 from step 11 under ip.

Please add the token of your Xiaomi Air Purifier 2 from step 11 under token.

Save the file: ^X, y and Enter.

Launch Homebridge, to make sure the configuration file works correctly: homebridge. In case of any errors, you can verify (and format) your JSON using this tool.

If everything works correctly, you should see a QR code, a PIN number and some text, stating that everything loaded correctly. If it does, close Homebridge by typing in ^C.

You will now complete automating Homebridge, to launch by itself: cp ~/.homebridge/config.json /var/homebridge.

sudo cp -r ~/.homebridge/persist /var/homebridge.

sudo chmod -R 0777 /var/homebridge.

sudo systemctl daemon-reload.

sudo systemctl enable homebridge.

sudo systemctl start homebridge.

sudo systemctl status homebridge.

You can press q to exit the command from step 29 and repeat it, until you see that everything loaded correctly — it only displays the last few lines of text of it loading.

Installing the Raspberry Pi Camera

You will now proceed to installing the Raspberry Pi camera itself.

Type in sudo raspi-config.

Go to Interfacing options.

Go to P1 Camera.

Set it to Yes.

Exit the configuration program.

Type in sudo modprobe bcm2835-v4l2.

We will need to install ffmpeg: sudo apt install ffmpeg.

And the camera plugin: sudo npm install -g homebridge-camera-rpi.

cd /opt.

sudo mkdir homebridge-camera-rpi.

sudo chown pi homebridge-camera-rpi.

git clone https://github.com/moritzmhmk/homebridge-camera-rpi.

cd homebridge-camera-rpi.

npm install.

Create a new file: sudo nano /etc/systemd/system/hap-camera-rpi.service.

Paste the following into it:
[Unit]
Description=HAP Camera RPi

[Service]
ExecStart=/usr/local/bin/node /opt/homebridge-camera-rpi/standalone.js -c /etc/homebridge-camera-rpi.conf.json
WorkingDirectory=/opt/homebridge-camera-rpi
Restart=always
RestartSec=10
User=pi

[Install]
WantedBy=multi-user.target

Save the file: ^X, y and Enter.

Create another new file: sudo nano /etc/homebridge-camera-rpi.conf.json.

Paste the following, replacing XX:XX:XX:XX:XX:XX with a MAC address generated from this tool:
{
"name": "Pi Camera",
"id": "Pi Camera",
"pincode": "031-45-154",
"username": "XX:XX:XX:XX:XX:XX",
"rotation": 0,
"verticalFlip": false
}

Please note that you can change rotation to 180, should you mount your Raspberry Pi Zero W upside down. You can also change verticalFlip to true.

Save the file: ^X, y and Enter.

sudo systemctl enable hap-camera-rpi.

sudo systemctl start hap-camera-rpi.

sudo systemctl restart homebridge.

To complete the camera service launching automatically, we need to edit a file: sudo nano /etc/modules.

Please paste bcm2835-v4l2 into a new line, at the end of the file.

Save the file: ^X, y and Enter.

Configuring HomeKit

Do you remember that QR code from earlier? Normally we would use that to configure HomeKit — it’s much quicker that way — but since Homebridge is running as a service, it will be easier just to enter the PIN code that you used in your configuration file. If you didn’t change it from my examples above, it should be 031-45-154.

Launch HomeKit on your iPad or iPhone.

Find the option to add your device via a PIN code (it should be somewhere towards the bottom of the screen).

Enter your PIN code.

When adding all your devices, you can change their names in HomeKit, e.g. I renamed MiAirPurifier2 to Air Purifier.

If you would like to use the automation features of HomeKit, you will need to have and Apple TV 4, Apple TV 4K or iPad running iOS 11. You will find more information on the subject here and here.

All your devices — the camera and air purifier — should be visible in HomeKit, either in the room you assigned them too, or in the list of favourites. You can of course control them via Siri, should you wish to.

And if you’re feeling a bit more adventurous, you can try to add a few more virtual devices to your Homebridge/HomeKit setup. I use Weather Underground to display the weather forecast for my street, as an example2.

Let me know if you got everything up and running!

New Out Of Box Software. ↩

Please note that the Living Room temperature is actually the outside temperature — I guess I should move it to another “room”. ↩