Smart home scripts for raspberry pi 3. Do-it-yourself smart home on Raspberry Pi

Hello, friends

In my reviews of smart home devices of the Xiaomi ecosystem - I have repeatedly mentioned the name Domoticz. Finally, I got around to share my experience on this topic, and tell you what it is and how you can supplement the standard capabilities of a smart home from Xiaomi using this system. It is impossible to tell this within the framework of one review, but you need to start somewhere - let's go ...

Introduction - a few words about Domoticz

1. What is Domoticz?
This is a multi-platform open source software focused on creating a smart home control system. Supports a large number of different devices from different vendors, including works with Xiaomi devices.
2. Which Xiaomi devices can be controlled by Domoticz?
I will only talk about devices that I have personally tested. At the moment, you can control the Xiaomi Gateway - and all the devices it controls - buttons, opening and motion sensors, ZigBee sockets, Aqara switches. Yeelight lighting gadgets are also supported - RGBW and White lamps, Celling Light ceiling lamp.
I read about working with miflora bluetooth sensors.
3. Why do I need Domoticz?
The system has more flexible options for configuring scripts - for example, checking the activity of the device, which is not in MiHome, or creating variables - which allow one condition - for example, pressing a key - to perform different actions, depending on the value of the variable.
Scenarios created in Domoticz do not depend on Chinese servers and Internet access.
Domoticz expands the functionality of devices - for example, new "free fall" or "alert" actions for a die, or "Long Click Release" for a button.
4. If I use Domoticz, will I not be able to work with MiHome?
Both systems live perfectly in parallel - the functionality of MiHome is completely preserved, it's just that some of the scripts will live in one system - some in another. Basically all scripts can live in Domoticz.
5. Why do I need MiHome if I use Domoticz?
At least for adding new devices. The choice is yours - but my opinion - at the moment Domoticz is best used as an add-on to MiHome
6. What do I need to connect Xiaomi devices to Domoticz?
I want to reassure you right away - there is no need for soldering irons, programmers and dances with tambourines. Also, you will not need Linux or virtual machines - you can try everything right on your working Windows, and if you like it, then it makes sense to allocate a separate hardware platform for it, for example, the hero of today's review.
Literally after the first successful experiments on my desktop PC, I got excited about the idea of ​​a separate hardware base for Domoticz. I stopped my choice, after studying the public - on the Raspberry Pi Model 3 B - a compact but powerful single-board computer based on the BCM2837 Soc processor with 4 Cortex-A53 cores operating at a frequency of 1.2GHz, 1GB of RAM and Wi-Fi and Bluetoth 4.1 wireless modules .

Set

I included 4 items in my order -

Payment screen


Raspberry Pi Model 3 B Motherboard -
Interestingly, the store has two versions - Chinese and English. At the time of purchase, the Chinese one cost $ 7 cheaper, and I took it. What is there Chinese - to be honest, it's a mystery to me.
Case for Raspberry Pi Model 3 B -
Power supply HN - 528i AC / DC 5V 2A -
Copper Heatsinks for Raspberry Pi -
Also for a complete set you will need a microSD card - at least 4 GB and an HDMI cable. I had both a cable and a 32 GB card in my stash, so I didn’t buy it.

What's in the package

After the due date - a little over two weeks, the courier brought the package with my order.


Let's consider in more detail. Power supply with Type C plug and micro-USB connector.


The declared maximum current is 2A at a voltage of 5 V.


Test switching on with a load of 2A - shows some voltage drop, but within the permissible range, the power supply is more or less honest.


A set of three copper radiators in a bag for passive cooling.


All radiators have a square shape, two radiators with pins and a side length of about 12 mm and one flat with a side of about 15 mm.


Dark plastic case with an embossed image of a raspberry on the lid


Case dimensions - approximately 90 by 65 mm




The case is disassembled into 5 parts - all latches hold, no screws.


Finished with accessories - it's time to move on to the most important thing
RASPBERRY PI 3 MODEL B
The Raspberry Pi 3 Model B is the direct successor to the Raspberry Pi 2 Model B. The board is fully compatible with its predecessor, but comes with better performance and new communication features:
64-bit quad-core ARM Cortex-A53 processor with a clock frequency of 1.2 GHz on a single-chip Broadcom BCM2837 chip; built-in Wi-Fi 802.11n and Bluetooth 4.1.
In addition, the processor has an ARMv53 architecture, which means you can use your favorite operating system: Debian Wheezy, Ubuntu Mate, Fedora Remix, and even MS Windows 10.


Specifications more
CPU - Broadcom BCM2837, ARM Cortex-A53 Quad Core, 1.2 GHz
Number of processor cores - 4
GPU - VideoCore IV 3D
RAM - 1 GB
Storage - microSD
Networking
Ethernet 10/100
WiFi 2.4G 150mb/s
Video output - HDMI
USB ports - 4
Wireless - Bluetooth
Audio Output - 3.5 Jack
85.6 x 53.98 x 17mm, 45 grams


The box contains documentation and a quick installation booklet - by the way, in English, as well as a thick brown paper bag with a computer.


On one of the long sides of the computer there are micro USB ports for power supply, a full-sized HDMI port, CSI-2 Camera port - for connecting a camera via MIPI interface, 3.5 mm audio jack. Also on the top side is the processor module and Ethernet / USB Hub lan9514-jzx


On the front side there are 4 USB ports and an Ethernet port


There are 40 General Purpose Input/Output (GPIO) pins on the other side of the motherboard.


On the second end side - there is a DSI Display Port for connecting a standard display


On the bottom side of the board is an LPDDR2 SDRAM memory module - EDB8132B4PB-8D-F


And a micro-SD slot for a memory card


Copper heatsinks are placed on the USB / Ethernet Hub and the processor on one side


And on the memory chip on the other. This heatsink is flat - does not interfere with the installation of the computer board in the case


Everything fits perfectly into the case, there are no screw connections - it sits on plastic ledges.


All cutouts on the case exactly match the computer connectors




To start, we need an external monitor (TV) with an HDMI input, a USB keyboard, it will be more convenient if there is also a mouse and power supply. Monitor, keyboard and mouse - will be needed only at the time of installation, then only the power supply will be enough.

Operating system installation

To install the operating system, the first step is to download the archive with distributions - . While almost one and a half gigabyte archive is being downloaded, we load the utility for formatting the SD card - SD Card Formatter -. This distribution is much more compact - only 6 MB, so without wasting time, install the program


and, after installation, insert the memory card into the card reader (you have a card reader, don't you) and run the SD Card Formatter. In the Options menu, you need to set “FORMAT SIZE ADJUSTMENT” to “ON”


After waiting for the download of a large distribution kit to complete, open the received archive and unpack its contents onto a freshly formatted USB flash drive.
The next step is the first launch of the Raspberry Pi (a flash drive with a recorded distribution kit, of course, we install it into it). Sorry for the quality of the next few photos - from the TV screen :(
At the first start, the operating system selection menu starts - what to install, and the list even has a version of WIndows 10 for Raspberry Pi. At this stage, you can select the language (at the bottom of the screen) - Russian is available and will connect to the Wi-Fi network - Wi-Fi networks button


The option I need - Raspbian based on Linux Debian - comes in two flavors, lite AND full, with a graphical interface. I chose the full version


After that, we can safely go to drink tea with bagels, the installation will take quite a long time.


Periodically measuring the temperature during installation, the maximum that I have seen is 38 degrees.
After the installation is complete and the computer restarts, the Raspbian desktop loads


The only thing I did here was to enable SSH in the settings - in order to manage the system from a desktop PC, I already did everything else through the terminal.


To control the Raspberry from a desktop PC, we need any terminal program, I use the good old Putty


Default username and password - pi And raspberries. To change the password, use the command passwd.


I recommend immediately setting a static IP address for Raspberry. You can find out the current addresses using the command ifconfig , where
eth0 is ethernet
lo is the local interface 127.0.0.1
wlan0 is the wi-fi interface

And in order to edit the file with the settings - enter the command
sudo nano /etc/dhcpcd.conf
and in the file that opens, scrolling to the end, add the necessary settings, depending on which interface we will use.
For example, we want to use the address 192.168.0.222, the mask is 255.255.255.0, the gateway and DNS address is 192.168.0.1
For Ethernet we insert
interface eth0

static routers=192.168.0.1

for wifi
interface wlan0
static ip_address=192.168.0.222/24
static routers=192.168.0.1
static domain_name_servers=192.168.0.1


Press ctrl+x to exit the editor
To save changes - press “Y” and then enter

Domoticz installation
Most of the setup work is already done, now we need to install the Domoticz system. This is done with one command -
sudo curl -L install.domoticz.com | sudo bash
Which initializes the process of booting and installing the system


During the installation process, the installer will ask questions about the installation location, etc. - I left all these moments by default.


After successful installation, the installer will write the addresses and ports of the web interface of the Domoticz system


But, to work with the Xiaomi gateway, we need a beta version of the system. Upgrading to the latest beta version is done by the commands
cd ~/domoticz
sudo ./updatebeta



Now the Domoticz system is available via the web interface:

Now is the time to start adding Xiaomi devices. But first -

Preparatory work

So, what do you need to start working with Domoticz?
Reservation of IP addresses
The first step is to set static IP addresses for the devices that you plan to manage - for now it's a gateway and lamps. This is done on your home router using a DHCP client table that looks something like this -


and information from the Network info tabs of the gateway and lamp control plugins, where the MAC addresses of the devices are indicated


Using this information, you need to register the issuance of permanent IP addresses to these devices - since they will be controlled exactly by IP, and if the address is changed, Domoticz will lose contact with it. The address reservation table looks something like this -

Developer Mode

Developer mode must be enabled. For the Xiaomi Gateway, you need to go to the menu, select the about option, at the bottom of the screen where the version is written (I have 2.23) - click on it until two new options appear in the menu, they can be in Chinese, in my example - in English. Click on the first of the two - local area network communication protocol, activate the top switch in the menu and write down the gateway password.


For lamps, everything is simpler - you need to install the Yeelight application, if you have not installed it yet, and for each lamp - go to the menu, developer mode - enable

Adding Devices

To add devices, go to the tab Settings - Equipment
127.0.0.1:8080/#/Hardware (instead of 127.0.0.1 - the address of your Domoticz)
We select the type of Xiaomi Gateway device, name it somehow, indicate its IP address, which we reserved on the router, enter the password received in the developer mode window. Port - works for me on port 54321. The domotics wiki describes a connection with port 9898


To add lamps - just add the YeeLight LED device - you do not need to specify addresses, the lamps will pull themselves up.


The sensors connected to the gateway will not be pulled up all at once, this process can take an hour or more - you need to wait. This is due to the fact that ZigBee devices are activated only at the moment of data transmission. You can push the process a little - by opening and closing windows with sensors, breathing on temperature sensors, turning sockets on and off - in a word, forcing devices to transmit data.

Devices

Devices will be added MUCH more than you expect :) A list of them is available on the tab Settings - Devices.
127.0.0.1:8080/#/Devices


For example, each temperature and humidity sensor will be added as three devices, separately temperature, separately humidity, and all together. Sockets - a separate socket (controlled device) separately - as a power consumption sensor. But the gateway - a separate backlight, a separate alarm siren, a separate alarm clock, a doorbell and a volume control. In order to add a device to the list of used devices, click the green arrow at the end of the line. Remove from used - blue arrow. What we don't need, we don't add.
Devices added to use are located on several tabs -

Switches

This tab contains all managed devices
127.0.0.1:8080/#/LightSwitches
Switches, buttons, lamps, and more. Here we can turn on, turn off, and do any actions with devices in manual mode.

For example, choose the sound that will sound on the gateway, or the color of the glow on the RGB lamp or the brightness on the white lamp.

Temperature

On this tab climate sensors are grouped - humidity and temperature
127.0.0.1:8080/#/Temperature
At first, they are all called the same, you can determine where which is by their testimony and checking with the Mi Home application, after which they can be renamed accordingly.

Auxiliary

The gateway's light sensor is grouped here - although its readings are very strange, and the power consumption meters of the sockets.
127.0.0.1:8080/#/Utility

Scenarios

To create scripts, you need to go to the tab - Settings - Advanced - Events. Scripting is available in two versions - block scripting and lua scripting.

Script examples

Learning to work with Domoticz is better to start with blocks. Here everything is divided into groups and writing scripts is quite simple. An example of a simple scenario on the blocks is to turn on the light when motion is detected, and turn it off a minute after the motion sensor switches to the off status. After creating the script, you need to name it, check the box Event active: - to enable it and save it.

Exactly the same script on lua

Examples of using

I will pay more attention to specific scenarios in other reviews, here as an example I will give a scenario that IMPOSSIBLE implement in Mi Home, namely, a two-button Aqara switch with opening wires - the left button will work as intended - break and connect the phase, and the right one - not connected to the line (to power the switch, it is enough to connect only one of the buttons) - it will turn on and off Yeelight lamp, which has no physical connection to the switch.
In this scenario, the status of the Yeelight lamp will be checked, the value of the On or Off switch itself will not matter. If the status of the lamp is different from Off, then it is working and will be turned off, and if it is off, it will be turned on.

On this, I will complete the introductory part on Domoticz, if the topic is interesting, then I will continue, there is still a lot of interesting things.

Video version of the review (2 parts) -



Thanks for attention. I plan to buy +170 Add to favourites Liked the review +99 +231

The model immediately gained wide popularity among users, as evidenced by the ever-increasing volume of its sales.

Structural diagram of the "Smart Home" system based on Raspberry Pi 3

Built on the basis of Raspberry Pi 3, Smart Home allows not only to take control and management of almost all communications in the home, but also to arbitrarily increase functionality during operation.

Key Features of Raspberry Pi 3

The new microcomputer received:

  1. ARM Cortex-A53 processor;
  2. one gigabyte RAM;
  3. built-in WiFi and Bluetooth 4.1;
  4. full compatibility with previous models.

The processor has four cores, 64 bits, frequency 1.2 GHz, which is 10 times higher than the performance of the first model.

WiFi standard 802.11b / g / n with the ability to transfer data at speeds up to 600 Mb / s at a frequency of 5.0 GHz.

By order of the Raspberry Pi, Broadcom developed and released a new BCM2837 single crystal with an architecture similar to the BCM2835 and BCM2836 crystals, which ensured compatibility with previous models.

Raspberry Pi 3 and Arduino Single Board Computers - Main Differences

Comparing these platforms is not entirely correct. First of all, because the Raspberry Pi 3 in its content is a computer with a full range of functions, and it is rather problematic to classify Arduino as a computer.

The Raspberry Pi 3 is powered by a powerful quad-core processor that runs 40 times faster than the Arduino clock. Raspberry Pi 3 RAM has a capacity of 128,000 times the capacity of Arduino RAM.

But these figures do not mean that the Raspberry Pi 3 is superior to the Arduino, but that these devices are designed to solve different problems.

The tasks that the Raspberry Pi 3 can solve with software are beyond the power of a simple Arduino. But it does an excellent job with the tasks of purely hardware projects, with the reading and processing of analog signals.

Processing of analog signals is carried out in real time, and these signals can come from chips of any type and manufacturer. In order for the Raspberry Pi 3 to process analog signals in the same way, it needs additional hardware.

Implementation of the "Smart Home" project based on Raspberry Pi 3

For those who decide to create a Raspberry Pi 3 "Smart Home" with their own hands, you first need to decide what functions will be implemented, how they will be included in the working configuration. And, in accordance with this, complete the future system with the necessary devices.

Smart Home Peripherals

To implement the Raspberry Pi 3 Smart Home project, you will need the following modules:

  • module ;
  • wireless communication support module;
  • humidity measurement sensor and ;

In addition, the Raspberry Pi 3 Smart Home system will require a 32 GB MicroSD memory card, a power supply, a five-volt relay.

One of the most important additional devices for the implementation of the Raspberry Smart Home project is the NodeMCU ESP-12E module with a Wi-Fi radio interface and a microstrip antenna integrated into the module board.

Operating Systems

Like any computer, a Raspberry Pi 3 without software is just a useless collection of electronic components.

In order to turn this set into a tool that implements its functionality, it needs to be “breathed into life”, that is, filled with the appropriate software.

This process is carried out in several stages. First you need to select and download for Raspberry Pi 3 "Smart Home" iOS - a mobile operating system.

The Raspberry Pi 3 uses a micro SD memory card as a carrier for the OS and hosting programs on it. You can choose one of three ways to install the OS:

  1. buy an SD card on which the OS has already been pre-installed;
  2. download NOOBS (New Out Of the Box Software) - OS installer to the memory card, and then install the OS directly from the card;
  3. mount the OS image directly to the SD card.

More than 40 different operating systems have been developed for the Raspberry Smart Home system. The most commonly used OS are Raspbian OS, Ubuntu Mate, Windows 10 IoT, RICS OS.

Most adapted to Raspberry Pi 3 hardware

The operating system is Raspbian OS, installed from the NOOBS installer downloaded to the SD card.

Operating system installation

Before you start working with the microcomputer, you should prepare the necessary devices and accessories.

For the very first run you will need:

  • microSD card with a capacity of at least four gigabytes (preferably 32 gigabytes);
  • five volt power supply;
  • cable with HDMI connectors;
  • monitor with HDMI connection;
  • keyboard and mouse with USB connection;
  • computer with SD card slot;
  • Internet connection - Ethernet.

The next steps are:

  1. formatting the SD card;
  2. downloading the NOOBS installer archive and extracting it to the root directory of the SD card;
  3. the card is inserted into the microcomputer slot, all devices are connected, the power supply is turned on;
  4. at the first start, the required OS is selected from the list and its installation starts;
  5. upon completion of the installation, install and configure the Raspberry Pi 3 "Smart Home" programs.

Installing the Homebridge Server and Configuring Modules

The Smart Home system works with Home Kit technology, which combines all smart home devices in one application and accepts voice commands given in Russian. But there are not so many such devices, especially those that “understand” the Russian language, and besides, they are very expensive.

The Homebridge server acts as a kind of bridge between all devices at home and the Home Kit. This server emulates the Home Kit API.

Hundreds of various plug-ins are available to the server, thanks to which it has become possible to manage all home devices that are not even structurally designed to work with the Home Kit. The main advantage of Homebridge is that it can run on any computer, including the Raspberry Pi 3.

When you connect a new module, you should update the software, because from the moment you purchase the module until it is included in the working configuration, drivers may be updated, and the module may not work on older versions.

After the update, in the list of proposed modules, find the one you need and add it to the working configuration. At the physical level, observe the recommended precautions (for example, remove static electricity from yourself).

Conclusion

A do-it-yourself “Smart Home” system based on Raspberry Pi 3 will cost several times cheaper than a similar ready-made system, and its functionality can be increased almost unlimitedly.

Video: Raspberry Pi Model 3 B - installing the Domoticz smart home control system

In this project, we launch our own iOS, Android or Web application, and also write (or rather, add a little) a python chat bot that controls sockets through a radio module connected to the Raspberry Pi.

As a result, we can manage home appliances and receive statuses from them remotely and jointly with other users through a common chat.

Interesting?

What for?

The question “why is this necessary?” it is not always acute for projects from the “smart home” series and all kinds of Internet of Things, here a lot of time and money are often spent on automating something that in practice is more convenient to switch in the old fashioned way with an ordinary wall switch :-) But at the same time you get a lot of fun and useful experience in the process, and then you rejoice at the correct operation of the mechanism that you made yourself.

But besides the above-mentioned pleasures, it seems to me that home control and device communication via chat, more specifically the XMPP protocol, has the right to life for the following reasons:

  • Human language- It's pretty easy to get a chatbot to talk to you in human language, which is pretty handy, especially for less technical family members. It also allows you to connect voice control in the future.
  • Universal remote access- XMPP chat server can be connected from anywhere and from any Jabber compatible IM client. It is convenient for people, and how to connect devices is described in this article.
  • Convenient controls for the whole family- connect your family members to a single group chat, where the bots responsible for the house or appliances in the house sit. You can discuss your family matters and manage the house at the same time. Everyone can see who gave what commands to the devices, you can see their (bots) answers and reports, view the previous history, etc. It's comfortable.
  • System of independent distributed agents. Each device or set of sensors that has a representation (essentially, a user) in the chat, respectively, are independent agents and can communicate with other devices and be controlled by them or you directly. A single server is not required. You can set up your own chat bot for each important device or sensor, as well as set up a main bot with AI elements, such as a “butler” or “majordomo”, which will control all devices, and they will communicate in a chat available to you and other family members on in a language you understand, so you can always track what happened or intervene in the process.

Props

For this mini-project, we need the following components:

1. Raspberry P.
I have model B, I ordered it literally the day before the announcement of the release of B +, but in principle, any model will work here, the main thing is to make sure that the GPIO pins are compatible with the control module that you choose. More on that below.
Well, the main requirement is to run a python chat bot.

2. Accessories for your Pi.
WiFi module, simple USB keyboard and mouse, SD memory card with Raspbian distribution, power supply, optional plastic case.
This is the standard for "raspberries", but since I bought it for the first time, specifically for this project, I did not know that WiFi and an SD card were not included in the standard package, and I had to order more, so keep in mind. You will also need a monitor or TV with an HDMI cable to set up.

3. Control module (RF transmitter) and sockets or other devices with a receiver (RF receiver).
Here I must say that I took the fast or lazy route and ordered a ready-made RF module for the Pi and a set of radio-controlled sockets from Energenie. The kit comes with a ready-made RF transmitter that connects to the GPIO pins of your raspberry. For those who don’t like this path, there are alternatives, there are a lot of guides on the Internet on how to find a code for existing radio-controlled devices and control them through a simple cheap Chinese RF transmitter. Alternatively, the Pi can be controlled directly by a direct wired GPIO connection, as well as via WiFi and other channels.

Here is a photo of my Energenie kit:

4. Chat client.
This tutorial uses Q-municate , which is an open source messenger from our QuickBlox platform, which can be downloaded from github and built for iOS, Android, or run the Web version on desktop and other platforms. The advantage of using Q-municate is that you can customize the interface for yourself and make your own application, for example, just for your family.
But this is absolutely not necessary. You can use any Jabber/XMPP compatible client such as Adium.

So, let's begin.

Installing distributions / dependencies for Raspbian

Log in to raspberry and put the following things under the root:
apt-get install python-dev pip install sleekxmpp pip install dnspython pip install pyasn1 pyasn1-modules apt-get install python-rpi.gpio
We actually need sleekxmpp, this is the base project for the chat bot, and the rest solves issues with various dependencies for this project. Well, plus python-rpi.gpio will allow you to control the GPIO pins of the raspberry from our python script.

We connect and check the radio control module

If you are using a module other than Energenie, then you will have to explore this part yourself.

When using a ready-made Pi-mote module, everything is simple and well described in the official instructions from the manufacturer: energenie4u.co.uk/res/pdfs/ENER314%20UM.pdf

Personally, I spent an unacceptably long time trying to determine if my set of radio-controlled sockets was working, measuring the voltage on a raspberry, trying unofficial scripts, etc., since for some reason Energenie sockets did not want to be controlled by a script, as described by the manufacturer and on multiple blogs. It didn’t immediately come to me to look into the manual again and read it carefully this time, but there it says in English and white that the sockets must be started first in the training mode. Logically. In my defense, I can only say that the project was done early in the morning on weekends, while the family was sleeping, apparently, lack of sleep affected :-)

So, we teach. According to the instructions, run the script

sudo python ENER002.py
insert the sockets into the sockets) and if the lights on them do not blink, then we switch to the learning mode by pressing the off button for 5 seconds. The lights blinked, press “Enter” on the keyboard to send a signal from the script and see the quick blinking of the light, which means that the training was successful. Repeat the same with the rest of the sockets. One Pi-mote module can supply 4 different codes, i.e. You can control 4 different sets of Energenie sockets, while no one bothers to use one code for several sockets at the same time.

Raising a chat server

We need an XMPP / Jabber compatible chat server with the ability to create a MUC (group chat or chat room) in it to connect our chat bot and human users there.

In principle, you can set up your own chat server on the Pi, for example, here http://box.matto.nl/raspberryjabberd.html describes how to install ejabberd on the Raspberri Pi.

In this article, we again follow the path of least resistance and use the ready-made free chat server from QuickBlox. You just need to create an account to get your own chat server and web admin.

The steps below describe the registration and at the same time the creation of a user for our chat bot and MUC chat room.

Next, we need to take and modify it to fit our needs.
If you are also using Energenie for controlled outlets and QuickBlox for chat server, then you can get my finished script here: https://github.com/QuickBlox/sample-powerbot-python-rpi .
You will only need to change the credentials at the beginning of the script, adding your application and user keys (the one we created above) there.

Below we will go over the changes in more detail, but briefly what was done (I apologize in advance for the level of python code - I have not been a programmer for a long time, and even more so not a pythonist - I will be grateful for any improvements and pull requests):

1. Added auto-join by invitation to other chat rooms.

2. Improved compatibility with QuickBlox and Q-municate (little things like chat room name format, etc.)

3. The actual parsing of commands for controlling devices has been added - in our case, these are “lamp on”, “lamp off”, “all on” and “all off” - and calling the switch_on / switch_off functions from the energenie python module, which already issues commands to radio transmitter board via GPIO.
Who works directly with GPIO, look in energenie.py for how GPIO is implemented.

Auto-join to other chat rooms
An optional feature, but I personally missed it, for example, when you have this butler bot as a friend in the messenger and you can create new chats and invite him there. Without this, it will work, but then the bot will be tied to the chat you launched it into.

How to implement auto-attachment - parsing stanzas of incoming XML messages, tk. we will definitely receive a message stating that such and such a MUC chat has been created, if this user was invited there.

In our case, we are using the QuickBlox platform and a specific Q-municate application, in which an invitation to a new group chat looks something like this:
RECV: Taras Filatov created new chat<_id>53b78c0c535c12798d0050551234040,1258466,126535021404538064Yanus Poluektovich, Sergey Fedunets[email protected]1

We track the phrase “created new chat” in XMPP stanzas, and if it occurs, then we parse xmpp_room_jid from there, this will be the id of the newly created room.
Then we start the process with the same script
Keep in mind, in order for this to work, you need to make the script executable:

Chmod +x powerbot.py
The implementation code is shown below:

If msg["mucnick"] != self.nick and "Create new chat" in msg["body"]: from bs4 import BeautifulSoup y = BeautifulSoup(str(msg)) roomToJoin = y.xmpp_room_jid.string print ("Got an invite to join room") botId = subprocess.Popen(, shell=True) print "spawned new bot ID=" print botId self.send_message(mto=msg["from"].bare, mbody="Thank you for your kind invitation, joining your new room now!", mtype="groupchat")

Greeting + Instructions
We define a code word, in this case “powerbot”, and issue a greeting in response and a hint on how to use / communicate with our bot.
The “if msg["from"] != self.nick” check is needed so that the bot does not react to messages from itself.

# # Reply to help request (any message containing "powerbot" in it) # if msg["mucnick"] != self.nick and "powerbot" in msg["body"]: reply_test_message = self.make_message(mto=msg ["from"].bare, mbody="Powerbot is greeting you, %s! Usage: lamp to control socket 1, all to control all sockets. Example: "lamp on" switched socket 1 on." % msg["mucnick "], mtype="groupchat") self.copy_dialog_id(msg, reply_test_message) reply_test_message.send() print "Sent help text: " + str(reply_test_message)

Turning on / off the lamp and other devices
We track the “lamp on” command (turn on the lamp), if the command is received, then turn on the switch_on (lampSocket) socket and report on the execution.

# # Handle "lamp on" command # if msg["mucnick"] != self.nick and "lamp on" in msg["body"]: switch_on(lampSocket) confirmation_message = self.make_message(mto=msg["from "].bare, mbody="Lamp has been switched on, %s." % msg["mucnick"], mtype="groupchat") self.copy_dialog_id(msg, confirmation_message) confirmation_message.send() print "Lamp switched on , sent confirmation: " + str(confirmation_message)
“Lamp off”, “all on” and “all off” are implemented in a similar way (the latter are responsible for turning on or off all controlled sockets).

Launching a chat bot
From bash on raspberry, we execute a simple command:

sudo python powerbot.py -d -r<адрес начальной MUC комнаты>
Sudo is needed to access the GPIO. If you used QuickBlox, then just copy the JID address from the Chat Dialogs plate as the MUC address of the room.

As a result, authentication logs and XMPP status exchange with the server will appear on the screen:

That's it, the bot is ready and waiting for your instructions in the chat room.

By the way, you might have noticed that the command response functions are duplicated simultaneously in
def message(self, msg):
And
def muc_message(self, msg):
the first block processes private messages 1:1, and the second - group messages.
That is, you can control the bot in a private chat, although in my opinion, this is less interesting.

Building a chat client for iOS (options: Android, Web)

As I wrote above, you can communicate with the bot through any Jabber / XMPP - compatible chat client.
We are not looking for easy ways, so we are building our own application - a client to control the bot and at the same time to communicate with family and friends.
Your own messenger with a bot and group chats :-)

However, as you will see, here we also follow the fast and lazy path and take a ready-made open-source project of our own development,
which is called Q-municate.

1. We pull the project from the gita for the corresponding platform:
iOS: bitbucket.org/quickblox/qmunicate-ios
Android: github.com/QuickBlox/q-municate-android
Web: github.com/QuickBlox/q-municate-web

2. Open in IDE.

3. Edit credentials - change the standard constants with application keys to those copied from the QuickBlox admin panel. On iOS this changes in AppDelegate.m, on Android in Consts.java.

4. Compile, build on the device.
Optionally, we can customize the interface and so on.

Demonstration

Screenshots:


I proudly named my Q-municate build "Q-Power"


find a bot in friends or group chat


chatting with the bot

Lamp control video via chat:

Thank you for your attention, I hope it will come in handy, and even better if this “proof of concept” inspires someone to realize the idea to the end, and the microwave suddenly speaks to the toaster, and the wife will give them all commands by voice through your home Siri :-)

Introduction

This project originates in 2014, when I faced the task of providing remote control of heating devices in my country house. The fact is that almost every weekend my family and I spend at the dacha. And if in summer we, having lingered for one reason or another in the city, arrived at the house, we could immediately go to bed, then in winter, when the temperature drops to -30 degrees, I had to spend 3-4 hours heating the house. I have seen the following solutions to this problem:

    "Crazy Decision"- heaters with built-in thermostats can be left on at the minimum keep warm temperature. Actually, there is nothing "smart" in this decision, but 24/7 heating devices in a wooden country house do not inspire confidence. I wanted at least minimal control over their state, automation and some kind of feedback;

    GSM sockets- this solution is used by my neighbors in their summer cottage. If someone is not familiar with them, then this is just an adapter controlled by SMS commands, which is plugged into the outlet, and the heater itself is turned on. Not the most budget solution if you need to provide heating for the whole house - a link to the market. I see it as the simplest and least labor-intensive to implement, but it has disadvantages during operation, such as: a whole bunch of SIM cards and work to maintain their positive balance, since each room needs at least one heater, limited and inconvenient control over means of SMS;

  1. "Smart House"- the actual solutions built on the implementation of "smart home".

As the most promising solution, I chose the third option and the next question on the agenda was - "Which platform for implementation to choose?".


I don’t remember how much time I spent looking for suitable options, but in the end, from budget solutions available in stores, I found the following systems: NooLite and CoCo (now renamed to Trust). When comparing them, the decisive role for me was played by the fact that NooLite has an open and documented API for managing any of its blocks. At that time there was no need for it, but I immediately noted what flexibility it could give in the future. And the price of NooLite was significantly lower. In the end, I opted for NooLite.

Implementation 1 - NooLite Automation

The NooLite system consists of power modules (for different types of loads), sensors (temperature, humidity, motion) and equipment that controls them: radio remote controls, wall switches, USB adapters for a computer or Ethernet gateway PR1132. All this can be used in various combinations, connected directly to each other or controlled via usb adapters or a gateway, you can read more about this on the official website of the manufacturer.


For my task, I chose the PR1132 Ethernet gateway as the central element of the smart home, which will control power units and receive information from sensors. For the Ethernet gateway to work, you need to connect it to the network with a cable; it does not support Wi-Fi. At that time, a network was already organized in my house, consisting of an Asus rt-n16 WiFi router and a USB modem for accessing the Internet. Therefore, the entire installation of NooLite for me consisted only in connecting the gateway with a cable to the router, placing temperature radio sensors in the house and mounting power units in the central electrical panel.


NooLite has a range of power blocks for different connected loads. The most "powerful" unit can drive loads up to 5000 watts. If you need to control a larger load, as in my case, then you can connect the load through a controlled relay, which, in turn, will be controlled by the NooLite power unit.




Wiring diagram



PR1132 Ethernet gateway and Asus rt-n16 router



Wireless temperature and humidity sensor PT111



Electrical panel and power block for outdoor installation SR211 - in the future, instead of this block, I used the block for indoor installation and placed it directly in the electrical panel


The PR1132 Ethernet gateway has a web interface through which power units, sensors and power units can be linked/unlinked and controlled. The interface itself is made in a rather "clumsy" minimalist style, but this is quite enough to access all the necessary functionality of the system:




Settings




Control




Page of one group of switches


Details about binding and configuring all this are again on the official website.


At that time I could:

  • manage heaters while being in the local network of a country house, which was not very useful, based on the original task;
  • create on/off timers by time and day of the week.

It was the automation timers that solved my initial problem for a while. On Friday mornings and afternoons, the heaters were turned on, and by the evening we arrived at a warm house. In case our plans changed, a second timer was installed, which turned off the batteries closer to the night.

Implementation 2 - smart home remote access

The first implementation allowed me to partially solve my problem, but still I wanted online home management and feedback. I began to look for options for organizing access to the dacha network from outside.


As I mentioned in the previous section, the dacha network has access to the Internet through the usb modem of one of the mobile operators. By default, mobile modems have a gray ip address and you cannot get a white fixed ip without additional monthly expenses. With such a gray IP, various no-ip services will not help either.


The only option that I managed to come up with at that time was VPN. On the city router, I had a VPN server configured, which I used from time to time. I needed to set up a VPN client on the dacha router and register static routes to the dacha network.




Wiring diagram


As a result, the country router constantly kept a VPN connection with the city router, and in order to access the NooLite gateway, I needed to connect from the client device (laptop, phone) via VPN to the city router.


At this stage, I could:

  • access your smart home from anywhere;

In general, this covered the initial task almost 100%. However, I realized that this implementation is far from optimal and easy to use, since each time I had to perform a number of additional steps to connect to the VPN. For me, this was not a particular problem, but for the rest of the family it was not very convenient. Also in this implementation there were a lot of intermediaries, which affected the fault tolerance of the entire system as a whole. However, for a while I settled on this option.

Implementation 3 - Telegram bot

With the advent of bots in Telegram, I took note that this could become a fairly convenient interface for controlling a smart home, and as soon as I had enough free time, I started developing in Python 3.


The bot had to be located somewhere and, as the most energy efficient solution, I chose the Raspberry Pi. Although this was my first experience with it, there were no particular difficulties in setting it up. An image on a memory card, an ethernet cable to the port and via ssh - a full-fledged Linux.


As I already said - NooLite has a documented API, which was useful to me at this stage. To begin with, I wrote a simple wrapper for more convenient interaction with the API:


noolite_api.py

""" NooLite API wrapper """ import requests from requests.auth import HTTPBasicAuth from requests.exceptions import ConnectTimeout, ConnectionError import xml.etree.ElementTree as ET class NooLiteSens: """Class for storing and processing information received from sensors no such processing """ def __init__(self, temperature, humidity, state): self.temperature = float(temperature.replace(",", ".")) if temperature != "-" else None self.humidity = int(humidity) if humidity != "-" else None self.state = state class NooLiteApi: """Basic wrapper for communicating with NooLite""" def __init__(self, login, password, base_api_url, request_timeout=10): self .login = login self.password = password self.base_api_url = base_api_url self.request_timeout = request_timeout def get_sens_data(self): """Getting and parsing xml data from sensors:return: list of NooLiteSens objects for each sensor:rtype: list "" " response = self._send_request("()/sens.xml".format(self.base_api_url)) sen s_states = ( 0: "Sensor bound, information update pending", 1: "Sensor not bound", 2: "No signal from sensor", 3: "Sensor battery needs to be replaced") response_xml_root = ET.fromstring(response. text) sens_list = for sens_number in range(4): sens_list.append(NooLiteSens(response_xml_root.find("snst()".format(sens_number)).text, response_xml_root.find("snsh()".format(sens_number) ).text, sens_states.get(int(response_xml_root.find("snt()".format(sens_number)).text)))) return sens_list def send_command_to_channel(self, data): """Send request to NooLite Send request to NooLite with url parameters from data:param data: url parameters:type data: dict:return: response """ return self._send_request("()/api.htm".format(self.base_api_url), params=data) def _send_request(self, url, **kwargs): """Sending a request to NooLite and handling the returned response Sending a request to a url with parameters from kwargs:param url: url to request:type url: str:return: respo nse from NooLite or exception """ try: response = requests.get(url, auth=HTTPBasicAuth(self.login, self.password), timeout=self.request_timeout, **kwargs) except ConnectTimeout as e: print(e) raise NooLiteConnectionTimeout("Connection timeout: ()".format(self.request_timeout)) except ConnectionError as e: print(e) raise NooLiteConnectionError("Connection timeout: ()".format(self.request_timeout)) if response.status_code ! = 200: raise NooLiteBadResponse("Bad response: ()".format(response)) else: return response # Custom exceptions NooLiteConnectionTimeout = type("NooLiteConnectionTimeout", (Exception,), ()) NooLiteConnectionError = type("NooLiteConnectionError", (Exception,), ()) NooLiteBadResponse = type("NooLiteBadResponse", (Exception,), ()) NooLiteBadRequestMethod = type("NooLiteBadRequestMethod", (Exception,), ())



telegram_bot.py

# Get config data from file config = yaml.load(open("conf.yaml")) # Basic logging setup logger = logging.getLogger() logger.setLevel(logging.INFO) formatter = logging.Formatter("%(asctime) s - %(filename)s:%(lineno)s - %(levelname)s - %(message)s") stream_handler = logging.StreamHandler() stream_handler.setFormatter(formatter) logger.addHandler(stream_handler) # Connect to the bot and NooLite updater = Updater(config["telegtam"]["token"]) noolite_api = NooLiteApi(config["noolite"]["login"], config["noolite"]["password"], config["noolite "]["api_url"]) job_queue = updater.job_queue def auth_requi red(func): """Authentication Decorator""" @functools.wraps(func) def wrapped(bot, update): if update.message.chat_id not in config["telegtam"]["authenticated_users"]: bot. sendMessage(chat_id=update.message.chat_id, text="You are not logged in.\nSend /auth password to log in.") else: return func(bot, update) return wrapped def log(func): """Log decorator"" " @functools.wraps(func) def wrapped(bot, update): logger.info("Received message: ()".format(update.message.text if update.message else update.callback_query.data)) func(bot , update) logger.info("Response was sent") return wrapped def start(bot, update): """Command to start interacting with the bot""" bot.sendMessage(chat_id=update.message.chat_id, text="For log in to get started.\n" "Send /auth password to log in.") def auth(bot, update): """Authentication If the password is correct, the smart home control keyboard will respond """ if config[" telegtam"]["password"] in u pdate.message.text: if update.message.chat_id not in config["telegtam"]["authenticated_users"]: config["telegtam"]["authenticated_users"].append(update.message.chat_id) custom_keyboard = [ [ "/Turn on_heaters", "/Turn off_heaters"], ["/Turn on_spotlight", "/Turn off_spotlight"], ["/Temperature"] ] reply_markup = ReplyKeyboardMarkup(custom_keyboard) bot.sendMessage(chat_id=update.message.chat_id, text= "You are logged in.", reply_markup=reply_markup) else: bot.sendMessage(chat_id=update.message.chat_id, text="Incorrect password. ") def send_command_to_noolite(command): """Processing requests in NooLite. We send a request. If an error is returned, we send the user a response about it. """ try: logger.info("Send command to noolite: ()".format(command)) response = noolite_api.send_command_to_channel(command) except NooLiteConnectionTimeout as e: logger.info(e) return None, "*Dacha not available !*\n`()`".format(e) except NooLiteConnectionError as e: logger.info(e) return None, "*Error!*\n`()`".format(e) except NooLiteBadResponse as e: logger.info(e) return None, "*Could not make request!*\n`()`".format(e) return response.text, None # ============== ============ Commands =============================== @log @auth_required def outdoor_light_on(bot, update): """Turn on outdoor spotlight""" response, error = send_command_to_noolite(("ch": 2, "cmd": 2)) logger.info("Send message: ()".format( response or error)) bot.sendMessage(chat_id=update.message.chat_id, text="()".format(response or error)) @log @auth_required def outdoor_light_off(bot, update): """Outdoor light off" "" response, error = send_command_to_noolite(("ch": 2, "cmd": 0)) log ger.info("Send message: ()".format(response or error)) bot.sendMessage(chat_id=update.message.chat_id, text="()".format(response or error)) @log @auth_required def heaters_on(bot, update): """Turning heaters on""" response, error = send_command_to_noolite(("ch": 0, "cmd": 2)) logger.info("Send message: ()".format(response or error)) bot.sendMessage(chat_id=update.message.chat_id, text="()".format(response or error)) @log @auth_required def heaters_off(bot, update): """Turns off heaters""" response, error = send_command_to_noolite(("ch": 0, "cmd": 0)) logger.info("Send message: ()".format(response or error)) bot.sendMessage(chat_id=update.message.chat_id , text="()".format(response or error)) @log @auth_required def send_temperature(bot, update): """Getting information from sensors""" try: sens_list = noolite_api.get_sens_data() except NooLiteConnectionTimeout as e : logger.info(e) bot.sendMessage(chat_id=update.message.chat_id, text="*The cottage is not available!*\n`()`".fo rmat(e), parse_mode=ParseMode.MARKDOWN) return except NooLiteBadResponse as e: logger.info(e) bot.sendMessage(chat_id=update.message.chat_id, text="*Failed to get data!*\n`() `".format(e), parse_mode=ParseMode.MARKDOWN) return except NooLiteConnectionError as e: logger.info(e) bot.sendMessage(chat_id=update.message.chat_id, text="*Error connecting to noolite! *\n`()`".format(e), parse_mode=ParseMode.MARKDOWN) return if sens_list.temperature and sens_list.humidity: message = "Temperature: *()C*\nHumidity: *()%*". format(sens_list.temperature, sens_list.humidity) else: message = "Failed to get data: ()".format(sens_list.state) logger.info("Send message: ()".format(message)) bot.sendMessage (chat_id=update.message.chat_id, text=message, parse_mode=ParseMode.MARKDOWN) @log @auth_required def send_log(bot, update): """Get debug log""" bot.sendDocument(chat_id=update.message .chat_id, document=open("/var/log/telegram_bot/err.log", "rb")) @log def unknown(bot, update): """Unknown command""" bot.sendMessage(chat_id=update .message.chat_id, text="I don't know such a command") def power_restore(bot, job): """Run once when the bot is started""" for user_chat in config["telegtam"]["authenticated_users"]: bot.sendMessage(user_chat, "Enable after reboot") def check_temperature(bot, job): """Periodic checking temperature from sensors If the temperature is lower than the set minimum, send a notification to registered users """ try: sens_list = noolite_api.get_sens_data() except NooLiteConnectionTimeout as e: print(e) return except NooLiteConnectionError as e: print(e) return except NooLiteBadResponse as e: print(e) return if sens_list.temperature and \ sens_list.temperature< config["noolite"]["temperature_alert"]: for user_chat in config["telegtam"]["authenticated_users"]: bot.sendMessage(chat_id=user_chat, parse_mode=ParseMode.MARKDOWN, text="*Температура ниже {} градусов: {}!*".format(config["noolite"]["temperature_alert"], sens_list.temperature)) def check_internet_connection(bot, job): """Периодическая проверка доступа в интернет Если доступа в интрнет нет и попытки его проверки исчерпаны - то посылаем по telnet команду роутеру для его перезапуска. Если доступ в интернет после этого не появился - перезагружаем Raspberry Pi """ try: requests.get("http://ya.ru") config["noolite"]["internet_connection_counter"] = 0 except ConnectionError: if config["noolite"]["internet_connection_counter"] == 2: tn = telnetlib.Telnet(config["router"]["ip"]) tn.read_until(b"login: ") tn.write(config["router"]["login"].encode("ascii") + b"\n") tn.read_until(b"Password: ") tn.write(config["router"]["password"].encode("ascii") + b"\n") tn.write(b"reboot\n") elif config["noolite"]["internet_connection_counter"] == 4: os.system("sudo reboot") else: config["noolite"]["internet_connection_counter"] += 1 dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("auth", auth)) dispatcher.add_handler(CommandHandler("Температура", send_temperature)) dispatcher.add_handler(CommandHandler("Включить_обогреватели", heaters_on)) dispatcher.add_handler(CommandHandler("Выключить_обогреватели", heaters_off)) dispatcher.add_handler(CommandHandler("Включить_прожектор", outdoor_light_on)) dispatcher.add_handler(CommandHandler("Выключить_прожектор", outdoor_light_off)) dispatcher.add_handler(CommandHandler("log", send_log)) dispatcher.add_handler(MessageHandler(, unknown)) job_queue.put(Job(check_internet_connection, 60*5), next_t=60*5) job_queue.put(Job(check_temperature, 60*30), next_t=60*6) job_queue.put(Job(power_restore, 60, repeat=False)) updater.start_polling(bootstrap_retries=-1)


This bot runs on the Raspberry Pi under Supervisor, which monitors its state and starts it on reboot.




Bot work scheme


When starting the bot:

  • sends a message to registered users that it has turned on and is ready to work;
  • monitors internet connection. In the condition of working through the mobile Internet, there were cases when it disappeared. Therefore, a periodic check of the availability of the connection was added. If the specified number of checks fails, then first the script reboots the router via telnet, and then, if this does not help, the Raspberry Pi itself;
  • monitors the indoor temperature and sends a notification to the user if it falls below the specified threshold;
  • executes commands from registered users.

Commands are hard coded and include:

  • turning heaters on/off;
  • turning on / off the street spotlight;
  • receiving temperature from sensors;
  • getting a log file for debugging.

An example of chatting with a bot:



As a result, I and all family members received a rather convenient smart home control interface via Telegram. All you need to do is install the telegram client on your device and know the password to start communicating with the bot.


As a result, I can:

  • manage your smart home from anywhere from any device with your Telegram account;
  • receive information from sensors located in the house.

This implementation 100% solved the original problem, was convenient and intuitive to use.

Conclusion

Budget (at current prices):

  • NooLite Ethernet Gateway - 6.000 rubles
  • NooLite power sensor for load control - 1.500 rubles
  • NooLite temperature and humidity sensor - 3.000 rubles (without humidity is cheaper)
  • Raspberry Pi - 4.000 rubles

As a result, I got a fairly flexible budget system that can be easily expanded as needed (NooLite gateway supports up to 32 channels). Me and family members can easily use it without the need to perform any additional actions: I went to the telegram - checked the temperature - turned on the heaters.


In fact, this implementation is not the last. Just a week ago, I connected this whole system to Apple HomeKit, which allowed me to add control through the iOS app "Home" and the corresponding integration with Siri for voice control. But the implementation process draws on a separate article. If the community is interested in this topic, then I am ready to prepare another article in the near future.



Thanks to a wide range of additional modules, the Raspberry Pi miniature computer is best suited for those who like to build inexpensive smart home systems (Smart Home) with their own hands.

Raspbian, based on the Linux kernel, can be used as an operating system, along with extensions such as Pimatic. It is even easier to assemble a “smart home” using integrated software and hardware solutions on an “open platform”, such as openHAB, Fhem, SHC (SmartHome Control) or wiButler.

Smart Home Modules for Raspberry Pi

Building a smart home system on the Raspberry Pi makes sense only when it can be used to control various devices, and this requires the appropriate modules.

Since the Raspberry Pi is a popular product for DIY enthusiasts, there is a huge selection of Smart Home modules on the market. We will show you some of the most interesting ones.

433 MHz - receiver and transmitter for Raspberry Pi

The 433 MHz frequency is often used in affordable smart home system components, such as radiator switches and thermostats found in hardware stores.

These transmitters and receivers are ideal for installation in a smart home system built on the Raspberry Pi. A bundle of these two modules can be easily purchased for about 600 rubles.

Camera module for Raspberry Pi


With the camera module attached, the Raspberry Pi can be used as a surveillance system.

The camera is compatible with the Raspbian operating system, it can record video in Full HD resolution and take 5-megapixel photos.

This module is available both with and without an infrared filter at a price of 2000 rubles.

Motion Sensor for Raspberry Pi

If you want lights and other electronic devices (such as a camera) to turn on when motion occurs in an area of ​​your home, you will need a motion sensor connected to your smart home system.

Particularly attractive in price is a pack of five "pyroelectric infrared PIR motion sensors".

You can purchase this package for only 480 rubles.

Humidity and temperature sensor for Raspberry Pi

The functionality of the weather station is basic for Smart Home. Receiving and processing weather data with Raspberry Pi is very easy. All you need is one cheap sensor that you plug into your mini-computer: the DHT11 is ideal, which costs less than 600 rubles.

Enocean module for Rapsberry Pi

Enocean is a wireless technology that does without a power source. The bottom line is this: the energy needed to perform an action comes from a change in state (pressing a button, temperature difference, sunlight, wind blowing, etc.).

Accordingly, often associated modules are switches or temperature sensors.

To control devices with Enocean technology through Rapsberry Pi, you will need a suitable module, which can be purchased for only 3600 rubles.

Fire Alarm for Raspberry Pi

Often, a smart home system is used to increase the level of home comfort, but home protection can also become one of the important functions. In addition to burglar alarms and CCTV cameras, you can install smoke and water leakage detectors.

With a smoke detector that costs only 500 rubles, you can build your own fire alarm. However, when designing such an important security part of a smart home, you must double check the reliability of the system.

Homematic Module for Rapsberry Pi

Homematic is one of the most popular Smart Home systems in Europe. For the interaction of all its components, as a rule, a central control unit CCU2 (MATIC Home Gateway) is required.

Now you can connect the appropriate wireless module to your Raspberry. One of these, from ELV, costs about 1,700 rubles.

With the modules presented in this article, you can build a very versatile Smart Home system. However, there are many other modules for Rapsberry Pi, for example, for working with Z-Wave and Zigbee wireless standards.

A photo: manufacturing companies, CHIP.de