Smart home scripts for raspberry pi 3. DIY smart home on Raspberry Pi

Hello, friends

In my reviews of smart home devices of the Xiaomi ecosystem - I have already mentioned the name Domoticz several times. Finally, I got around to sharing my best practices on this topic, and tell what it is and how it is possible to supplement the standard capabilities of a smart home from Xiaomi using this system. It's impossible to tell 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?
It 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. What Xiaomi devices can be controlled by Domoticz?
I will only talk about those 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 device's activity, 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.
The scripts created in Domoticz do not depend on Chinese servers and the presence of the Internet.
Domoticz expands the functionality of devices - for example, new actions "free fall" or "alert" for a cube, or "Long Click Release" for a button.
4. If I use Domoticz will I be unable to work with MiHome?
Both systems live perfectly in parallel - the functionality of MiHome is fully preserved, just part of the scripts will live in one system - part in the other. Basically all scenarios can live in Domoticz.
5. Why do I need MiHome if I will be using Domoticz?
At least for adding new devices. The choice is yours - but in my opinion - at the moment Domoticz is best used as an add-on to MiHome
6. What do you need to connect Xiaomi devices to Domoticz?
I want to reassure you right away - you don't need soldering irons, programmers and dancing with tambourines. You also don't need Linux or virtual machines - you can try everything right on your working Windows, and if you like it, 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 publics - on a Raspberry Pi Model 3 B - a compact but powerful single-board computer based on a Soc BCM2837 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 modifications - Chinese and English. At the time of purchase, the Chinese one cost $ 7 cheaper, and I took it. What is Chinese there is, to be honest, a mystery to me.
Case for Raspberry Pi Model 3 B -
Power supply unit HN - 528i AC / DC 5V 2A -
Copper heatsinks for Raspberry Pi -
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 store, so I didn't buy it.

What's in the package

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


Let's take a closer look. Power supply with Type C plug and micro-USB connector.


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


Test turn-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 raspberry image on the lid


Case dimensions - approximately 90 x 65 mm




The case can be disassembled into 5 parts - everything is held by latches, no screws.


The accessories are over - 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 is endowed with better performance and new communication tools:
64-bit quad-core ARM Cortex-A53 processor with a clock speed of 1.2 GHz on a Broadcom BCM2837 single-chip 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
The number of processor cores - 4
GPU - VideoCore IV 3D
RAM - 1 GB
Storage - microSD
Networking capabilities
Ethernet 10/100
WiFi 2.4G 150 mb / s
Video Output - HDMI
USB ports - 4
Wireless Capabilities - 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 bag of thick brown paper with a computer.


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


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


The other side of the motherboard has 40 General Purpose I / O (GPIO) pins


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


On the underside of the board there is a LPDDR2 SDRAM memory module - EDB8132B4PB-8D-F


And micro-SD card slot


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 into the case


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


All cutouts on the case match exactly with the connectors on the computer




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

Installing the operating system

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, load the utility for formatting the SD card - SD Card Formatter -. This distribution kit is much more compact - only 6 MB, so without wasting time, we install the program


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


After waiting for the download of a large distribution kit to complete, open the resulting archive and unpack its contents onto a freshly formatted USB flash drive.
The next step is to start the Raspberry Pi for the first time (of course, install the USB flash drive with the recorded distribution into it). Sorry for the quality of several of the following photos - from the TV screen :(
At the first start, the operating system selection menu starts - what to install, and there is even a version of WIndows 10 for the Raspberry Pi in the list. At this stage, you can select the language (at the bottom of the screen) - there is Russian and will connect to the Wi-Fi network - the 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 saw was 38 degrees.
After the installation is complete and the computer is restarted, the Raspbian desktop is loaded


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


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


The default username and password is pi and raspberry... To change the password, use the command passwd.


I recommend setting a static IP address for your Raspberry right away. 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 a 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 255.255.255.0, the gateway and DNS address - 192.168.0.1
For Ethernet, insert
interface eth0

static routers = 192.168.0.1

For wi-fi
interface wlan0
static ip_address = 192.168.0.222 / 24
static routers = 192.168.0.1
static domain_name_servers = 192.168.0.1


To exit the editor, press ctrl + x
To save changes - press "Y" and then enter

Installing Domoticz
Most of the setup work has already been completed, 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 boot and installation process of 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?
IP address reservation
The first step is to set static IP addresses for the devices that you plan to control - while this is 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 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 activated. 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 (2.23 for me) - click on it until two new options appear in the menu, they may be in Chinese, in my example - on 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 easier - 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 Settings - Hardware tab
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, call it something, indicate its IP address, which we reserved on the router, write the password received in the developer mode window. Port - it works for me on port 54321. The wiki domotics describes a connection specifying port 9898


To add lamps - just add the YeeLight LED device - you do not need to specify addresses, the lamps will catch up on their own.


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

Devices

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


For example, each temperature and humidity sensor will be added as three devices, separately the temperature, separately the humidity, and all together. Sockets - separately socket (controlled device) separately - as a power consumption sensor. But the gateway is 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 ones, at the end of the line, press the green arrow. Remove from used - blue arrow. We don't add what we don't need.
The devices added to use are arranged in 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

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

Subsidiary

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

Scripts

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

Sample scripts

Learning to work with Domoticz is better to start with blocks. Everything is divided into groups and it is quite easy to write scripts. An example of a simple scenario on the blocks is turning on the light upon motion detection, and turning it off a minute after the motion sensor switches to the off status. After drawing up the script, you need to name it, check the Event active option: - to enable it and save it.

Exactly the same scenario in 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 - the Aqara two-button switch with wire break - 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) - will turn on and off Yeelight lamp, which does not have a physical connection to the switch.
In this scenario, the state of the Yeelight lamp will be checked, the value of the switch itself On or Off will not matter. If the state 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 finish the introductory part on Domoticz, if the topic is interesting, then I will continue, there are still a lot of interesting things.

Video version of the review (2 parts) -



Thank you for the attention. I plan to buy +170 Add to favourites I liked the review +99 +231

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

Block 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. RAM in one gigabyte;
  3. built-in WiFi and Bluetooth 4.1;
  4. full compatibility with previous models.

The processor has four cores, 64-bit capacity, 1.2 GHz frequency, 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 5.0 GHz.

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

Raspberry Pi 3 and Arduino single board computers - the 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 Arduino is quite problematic to classify as a computer.

The Raspberry Pi 3 is equipped with a powerful quad-core processor that is 40 times faster than the Arduino. The Raspberry Pi 3's RAM has a capacity of 128,000 times that of the Arduino's RAM.

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

The tasks solved by the Raspberry Pi 3 using software cannot be solved by a simple Arduino. But it perfectly copes with the tasks of purely hardware projects, with reading and processing analog signals.

Analog signals are processed in real time, and these signals can come from chips of any type and manufacturer. In order for the Raspberry Pi 3 to also handle analog signals, it needs additional hardware.

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

For those who decided to create a Raspberry Pi 3 "Smart Home" with their own hands, first you should 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 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, and 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.

OS

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

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

This process is carried out in several stages. First, you need to select and download for the 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 placing 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 preinstalled;
  2. download to the memory card NOOBS (New Out Of the Box Software) - OS installer, 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 for Raspberry Pi 3 hardware

This is the Raspbian OS operating system installed from the NOOBS installer loaded onto the SD card.

Installing the operating system

Before starting to work with the microcomputer, you should prepare the necessary devices and accessories.

For the very first launch you will need:

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

The next steps are as follows:

  1. formatting the SD card;
  2. download the NOOBS installer archive and unpack it to the root directory of the SD card;
  3. the card is inserted into the slot of the microcomputer, 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 is started;
  5. upon completion of the installation, install and configure the Raspberry Pi 3 Smart Home software.

Installing Homebridge Server and Configuring Modules

The Smart Home system works with the Home Kit technology, which unites 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, moreover, they are very expensive.

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

The server has hundreds of various plugins available, thanks to which it became possible to control 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 connecting a new module, you should update the software, since from the moment the module was purchased until it was included in the working configuration, the 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, discharge 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 expanded almost indefinitely.

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

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

As a result, we can control 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 is often spent on automating something that in practice is more convenient to switch the old fashioned way with a regular wall switch :-) But you get a lot of pleasure and useful experience in the process, and then you rejoice in the correct operation of the mechanism that you made yourself.

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

  • Human language It is quite easy to get the chatbot to communicate with you in human language, which is quite convenient, especially for less technical family members. It also allows you to connect voice control in the future.
  • Universal Remote Access- you can connect to the XMPP chat server 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 home to a single group chat, where bots are sitting in charge of the house or appliances in the house. You can discuss your family matters and manage your home at the same time. Everyone can see who gave which commands to the devices, you can see their (bots) responses and reports, view the previous history, etc. It's comfortable.
  • Independent Distributed Agent System... Each device or set of sensors that have a representation (in fact, 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 raise your own chat bot for each important device or sensor, as well as set up a main bot with AI elements, such a “butler” or “majordomo” that 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 that you can always track what was happening or intervene in the process.

Props

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

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

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, especially for this project, I didn’t know that WiFi and SD card are not included in the standard package, and I had to order it, so keep in mind. Also, for setup, you need a monitor or TV with HDMI cable.

3. Control module (RF transmitter) and sockets or other devices with a receiver (RF receiver).
Here I must say that I went the fast or lazy path and ordered a ready-made RF module for the Pi and a set of radio-controlled outlets from Energenie. The kit includes a ready-made RF transmitter that connects to the GPIO pins of your raspberry. Whoever does not like this path, there are alternatives, there are a lot of guides on the internet on how to select a code for existing radio-controlled devices and control them through a simple cheap Chinese RF transmitter. Alternatively, the Pi can control the devices directly with a direct wired GPIO connection, as well as WiFi and other channels.

Here is a photo of my Energenie kit:

4. Chat client.
This tutorial uses Q-municate, an open source messenger from our QuickBlox platform that 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 not necessary at all. You can use any Jabber / XMPP compatible client like Adium.

So, let's begin.

Install distributions / dependencies for Raspbian

Log in to the 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 a basic project for a 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 research 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 outlets was working, measuring the voltage on a malinka, 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 took a while to look at the manual again and read it carefully this time, but it says in English and white that the sockets must be started first in training mode. It is logical. In my defense, I can only say that the project was done early in the mornings on weekends, while the family sleeps, 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 flash, then we transfer to the learning mode by pressing the shutdown button for 5 seconds. The lights blinked, we press “Enter” on the keyboard to send a signal from the script and we see the fast blinking of the light bulb, which means that the training was successful. We 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 outlets at the same time.

We raise the chat server

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

Basically, 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 a ready-made free chat server from QuickBlox. You just need to create an account to get your own chat server and web admin panel for it.

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

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

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

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

2. Fixed compatibility with QuickBlox and Q-municate (trivia such as the format of the name of chat rooms, etc.)

3. Added the actual parsing of commands for controlling devices - in our case, these are "lamp on", "lamp off", "all on" and "all off" - and a call to the switch_on / switch_off functions from the python module energenie, which already gives commands to radio transmitter board via GPIO.
Who works directly with GPIO, see energenie.py how the work with GPIO is implemented.

Auto-join other chat rooms
An optional feature, but personally I missed it, for example, when you have this bot-butler in your friends' 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 in which you launched it.

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

In our case, we use the QuickBlox platform and a specific application Q-municate, 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 stations, 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 that 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 ")

Welcome + instructions
We define the code word, in this case “powerbot”, and we return a greeting and a hint on how to use / communicate with our bot.
The check “if msg [" from "]! = Self.nick” is needed to prevent the bot from responding 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 monitor the "lamp on" command (turn on the lamp), if the command is received, then turn on the switch_on socket (lampSocket) 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)
Similarly, “lamp off”, “all on” and “all off” are implemented (the latter are responsible for turning on or off all controlled outlets).

Launch the 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've used QuickBlox, just copy the JID address from the Chat Dialogs nameplate as the room's MUC address.

As a result, logs of authentication and exchange of XMPP statuses 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 may have noticed that the functions of reaction to commands 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 one processes group messages.
That is, you can also control the bot in a private chat, although in my opinion it is less interesting.

Putting together 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 for controlling a bot, and at the same time for communicating with family and friends.
Your own messenger with bot and group chats :-)

However, as you will see, here we are also going along 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 from the gita the project 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.
We can customize the interface, etc., if desired.

Demonstration

Screens:


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


find a bot in friends or group chat


we communicate with the bot

Video of lamp control via chat:

Thank you for your attention, I hope it will come in handy, or even better if this "proof of concept" encourages someone to implement 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 dates back to 2014, when I was faced with 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 the summer we, having lingered for one reason or another in the city, having arrived at the house could immediately go to bed, then in winter, when the temperature dropped to -30 degrees, I had to spend 3-4 hours heating the house. I have seen the following solutions to this problem:

    "Unwise decision"- heaters with built-in thermostats can be left switched on at the minimum temperature for keeping warm. Actually, there is nothing "smart" in this decision, but 24/7 working 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 the summer cottage. If someone is not familiar with them, then this is just an adapter controlled by SMS commands, which is plugged into the socket, and the heater itself is plugged into it. 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 heap of SIM cards and work to maintain their positive balance, since each room needs at least one heater, the limitations and inconveniences of their control by by means of SMS;

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

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


I don’t remember how much time I spent looking for suitable options, but in the end, from the budgetary and available solutions in stores, I found systems: NooLite and CoCo (now they have already renamed Trust). When comparing them, it was decisive for me 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 this could provide in the future. And the price of NooLite was significantly lower. As a result, I settled on NooLite.

Implementation 1 - NooLite Automation

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


For my task, I chose the PR1132 Ethernet gateway as the central element of the smart home, which will control the power units and receive information from the 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, I already had a network 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 the power units in the central switchboard.


NooLite has a range of power blocks for different connected loads. The most "powerful" unit can handle 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.




Connection diagram



PR1132 Ethernet gateway and Asus rt-n16 router



Wireless temperature and humidity sensor PT111



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


Ethernet gateway PR1132 has a web interface through which power units, sensors are linked / uncoupled 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




One switch group page


More details about binding and configuring all this - again on the official website.


At that time, I could:

  • control heaters while 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 morning and afternoon the heaters were turned on, and by the evening we arrived at a warm house. In case our plans change, a second timer was set, which turned off the batteries closer to night.

Implementation 2 - remote access to smart home

The first implementation allowed me to partially solve my problem, but still I wanted online home control and feedback. I started looking 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 via a usb modem from 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. I had a VPN server configured on my city router that 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.




Connection diagram


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


At this point, I could:

  • get access to smart home from anywhere;

In general, this almost 100% covered the original task. However, I realized that this implementation was far from optimal and convenient to use, since each time I had to perform a number of additional steps to connect to the VPN. This was not a big problem for me, but it was not very convenient for the rest of the family. 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 rather 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 to a memory card, ethernet cable to the port and via ssh - full-fledged Linux.


As I 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 While 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 is bound, information update is awaiting", 1: "Sensor is not linked", 2: "No signal from sensor", 3: "It is necessary to replace the battery in the sensor") 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): "" "Sending a request to NooLite Sending a 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 processing the returned response Sending a request to url with parameters from kwargs: param url: url for 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 ("NooLite "ConnectionError (Exception,), ()) NooLiteBadResponse = type ("NooLiteBadResponse", (Exception,), ()) NooLiteBadRequestMethod = type ("NooLiteBadRequestMethod", (Exception,), ())



telegram_bot.py

import os import logging import functools import yaml import requests import telnetlib from requests.exceptions import ConnectionError from telegram import ReplyKeyboardMarkup, ParseMode from telegram.ext import Updater, CommandHandler, Filters, MessageHandler, Job from noolite_api import NooLiteApi, NooLite, NoConnectionTimerite Get configuration data from file config = yaml.load (open ("conf.yaml")) # Basic logging settings 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. \ nFor authorization, send / auth password.") else: return func (bot, update) return wrapped def log (func): "" "Logging 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 to get started, you need to log in. \ n "" For authorization, send / auth password. ") def auth (bot, update):" "" Authentication If the password is correct, the smart home control keyboard is returned in response "" "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 ).sendMessage (bot_id = update.message.chat_id, text = "You are authorized.", Reply_markup = reply_markup) else: bot.sendMessage (chat_id = update.message.chat_id, text = "Invalid password. ") def send_command_to_noolite (command):" "" Processing requests in NooLite. We send a request. If an error is returned, then 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, "* Request failed! * \ n` ()` ".format (e) return response.text, None # ============== ============ Commands =============================== @log @auth_required def outdoor_light_on (bot, update): "" "Turn on the street light" "" 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): "" "Turn off street light" "" 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 on the heaters" "" 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): "" "Heaters off" "" 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 = "* Noolite connection error! * \ 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 receive 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): "" "Getting a log for debugging" "" 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 this command") def power_restore (bot, job): "" "Executed once when the bot starts" "" for user_chat in config ["telegtam"] ["authenticated_users"]: bot.sendMessage (user_chat, "Power on after reboot") def check_temperature (bot, job): "" "Periodic checking the temperature from the 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 launches it on reboot.




Bot operation scheme


When starting the bot:

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

The commands are hardcoded and include:

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

An example of communication with a bot:



As a result, I and all family members received a fairly convenient interface for controlling a smart home 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:

  • control 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 (the NooLite gateway supports up to 32 channels). My family members and I can easily use it without the need to perform any additional actions: 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 entire system to Apple HomeKit, which allowed us to add control through the Home app for iOS 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 miniature Raspberry Pi computer is best suited for those who like to build inexpensive smart home systems with their own hands.

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

Smart Home Modules for Raspberry Pi

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

Since the Raspberry Pi is a popular product for DIY enthusiasts, there is a huge selection of Smart Home modules on sale. 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 components of affordable Smart Home systems, such as switches and thermostats for radiators found in hardware stores.

These transmitters and receivers are ideal for installation in a smart home system based 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 connected camera module, the Raspberry Pi can be used as a video surveillance system.

The camera is compatible with the Raspbian operating system, it is capable of recording videos in Full HD resolution and taking 5 megapixel photos.

This module is available with or without an infrared filter at a price of 2,000 rubles.

Motion sensor for Raspberry Pi

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

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

You can purchase this package for only 480 rubles.

Air humidity and temperature sensor for Raspberry Pi

The functionality of the weather station refers to the basic one for Smart Home. Receiving and processing weather data with the 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 Rs. 600.

Enocean Module for Rapsberry Pi

Enocean is a wireless technology that dispenses with a power source. The bottom line is this: the energy required to perform an action arises from a change in state (pressing a button, temperature difference, the appearance of sunlight, a breath of wind, etc.).

Accordingly, switches or temperature sensors are often companion modules.

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

Fire Alarm for Raspberry Pi

A smart home system is often 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 security cameras, smoke and water detectors can be installed.

With the help of a smoke detector, which costs only 500 rubles, you will 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 pair the corresponding wireless module with the Raspberry. One of these, from the ELV company, costs about 1,700 rubles.

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

Photo: manufacturing companies, CHIP.de