Build a smart home gateway on the Raspberry Pi

The smart home system uses a large number of Internet of Things devices (such as temperature and humidity sensors, security systems, lighting systems) to monitor the internal state of the home in real time, complete intelligent adjustment, and human-machine interaction. With the development of the Internet of Things technology, its application scope, data scale, and market share will further expand, and the intelligent linkage between smart home devices will become more and more difficult. At the same time, due to the privacy of family data, user data will be uploaded to the cloud There are still certain security issues to deal with.

To this end, we will use Raspberry Pi + EMQ X Edge + EMQ X Kuiper to build a smart home gateway to realize edge computing and processing of smart home device data and reduce the outflow of private household data.

In this article, we will use the BH1750FVI light intensity sensor to collect household light intensity data, use EMQ X Kuiper to analyze and process the light intensity data, and control the LED lights accordingly according to the predefined data rules.

Required components

Raspberry Pi 3b+ and higher

Raspberry Pi 3 Generation B+ is an ARM-based microcomputer motherboard, which uses SD/MicroSD card for storage. The motherboard provides USB and Ethernet interfaces, which can be connected to a keyboard, mouse and network cable. The motherboard has the basic functions of a PC. At the same time, the Raspberry Pi integrates Wi-Fi, Bluetooth and a large number of GPIOs, making it an ideal choice for smart home gateways.

EMQ X Edge

The communication protocols between smart home devices include MQTT , Wi-Fi , Bluetooth, etc. Among them, the MQTT protocol is an Internet of Things communication protocol based on the publish/subscribe model. It is simple and easy to implement, supports QoS, and has small messages. In this article, we will use the MQTT protocol as the communication protocol between smart home devices.

Raspberry Pi Due to limited memory and processing power, we chose the EMQ open source EMQ X Edge as MQTT broker, EMQ X Edge is a lightweight messaging middleware computing edge of things, to support the deployment of things in resource-constrained edge hardware.

EMQ X Kuiper

The data transmission format between smart home devices is different, and the data has volatility, we need to process the data reported by the device. In this article we will use the EMQ open source EMQ X Kuiper be marginalized data processing equipment for the smart home, EMQ X Kuiper is SQL-based lightweight edge streaming message processing engine can run on resource-constrained edge equipment .

Through real-time analysis of various data of smart home equipment, real-time state management and control of the equipment can be realized.

Other components

  • BH1750FVI light intensity sensor
  • LED
  • 330 Ω resistor
  • Breadboard, several jumpers

Project schematic

Insert picture description here

Environment setup

Circuit connection

Insert picture description here

Raspberry Pi configuration

We choose raspbian 8 as the Raspberry Pi operating system and python 3 as the project programming language

# 创建名为 smart-home-hubs 的项目目录
mkdir ~/smart-home-hubs

EMQ X Edge installation and operation

$ cd ~/smart-home-hubs
# 下载软件包
$ wget https://www.emqx.io/downloads/edge/v4.1.0/emqx-edge-raspbian8-v4.1.0.zip
$ unzip emqx-edge-raspbian8-v4.1.0.zip
$ cd ./emqx
# 运行 EMQ X Edge
$ ./bin/emqx start

EMQ X Kuiper installation and operation

$ cd ~/smart-home-hubs
# 下载软件包
$ wget https://github.com/emqx/kuiper/releases/download/0.4.2/kuiper-0.4.2-linux-armv7l.zip
$ unzip kuiper-0.4.2-linux-armv7l.zip
$ mv kuiper-0.4.2-linux-armv7l ./kuiper
$ cd ./kuiper
# 创建 rules 目录,用来存放规则文件
$ mkdir ./rules
# 运行 EMQ X Kuiper
$ ./bin/server

Code writing

BH1750FVI light sensor data upload

Write code to read and calculate the light intensity data of the BH1750FVI sensor , and publish the light intensity data to the smartHomeHubs/light topic through the MQTT protocol at a frequency of 1 time/second .

# gy30.py
import json
import time

import smbus
from paho.mqtt import client as mqtt


# BH1750FVI config
DEVICE = 0x23  # Default device I2C address
POWER_DOWN = 0x00
POWER_ON = 0x01
RESET = 0x07
CONTINUOUS_LOW_RES_MODE = 0x13
CONTINUOUS_HIGH_RES_MODE_1 = 0x10
CONTINUOUS_HIGH_RES_MODE_2 = 0x11
ONE_TIME_HIGH_RES_MODE_1 = 0x20
ONE_TIME_HIGH_RES_MODE_2 = 0x21
ONE_TIME_LOW_RES_MODE = 0x23
bus = smbus.SMBus(1)

# MQTT broker config
broker = '127.0.0.1'
port = 1883
topic = 'smartHomeHubs/light'

def read_light():
    data = bus.read_i2c_block_data(DEVICE, ONE_TIME_HIGH_RES_MODE_1)
    light_level = round((data[1] + (256 * data[0])) / 1.2, 2)
    return light_level


def connect_mqtt():
    client = mqtt.Client(client_id='light_01')
    client.connect(host=broker, port=port)
    return client


def run():
    mqtt_client = connect_mqtt()
    while True:
        light_level = read_light()
        publish_msg = {
    
    'lightLevel': light_level}
        mqtt_client.publish(
            topic,
            payload=json.dumps(publish_msg)
        )
        print(publish_msg)
        time.sleep(1)


if __name__ == "__main__":
    run()

Configure EMQ X Kuiper stream processing rules

We created on the EMQ X Kuiper named smartHomeHubsstream, and configure rules light intensity data in real time analysis, in order to achieve control of the LED lamp.

In this paper we will calculate the average light intensity, when the average light intensity for 5 seconds turn LED (LED off time is greater than 55) is less than 55.

  • Create flow

    $ cd ~/smart-home-hubs/kuiper
    
    $ ./bin/cli create stream smartHomeHubs '(lightLevel float) WITH (FORMAT="JSON", DATASOURCE="smartHomeHubs/light")'
    
  • Write rules for turning on LEDs (./rules/onLed.rule)

    When the average light intensity for 5 seconds to less than 55, to smartHomeHubs/ledsend the theme "{\"status\": \"on\"}"message opened LED.

    {
       "sql":"SELECT avg(lightLevel) as avg_light from smartHomeHubs group by TUMBLINGWINDOW(ss, 5) having avg_light < 55;",
       "actions":[
          {
             "mqtt":{
                "server":"tcp://127.0.0.1:1883",
                "topic":"smartHomeHubs/led",
                "sendSingle":true,
                "dataTemplate": "{\"status\": \"on\"}"
             }
          }
       ]
    }
    
  • Write off LED rules (./rules/offLed.rule)

    When 5 seconds average light intensity of greater than 55, to smartHomeHubs/ledsend the theme "{\"status\": \"off\"}"message off LED.

    {
       "sql":"SELECT avg(lightLevel) as avg_light from smartHomeHubs group by TUMBLINGWINDOW(ss, 5) having avg_light > 55;",
       "actions":[
          {
             "mqtt":{
                "server":"tcp://127.0.0.1:1883",
                "topic":"smartHomeHubs/led",
                "sendSingle":true,
                "dataTemplate": "{\"status\": \"off\"}"
             }
          }
       ]
    }
    
  • Add rule

    $ ./bin/cli create rule onLed -f ./rules/onLed.rule 
    $ ./bin/cli create rule onLed -f ./rules/offLed.rule 
    
  • View rules

    $  ./bin/cli show rules
    

Insert picture description here

LED light control

Write code to connect to EMQ X Edge, and subscribe to smartHomeHubs/led topics. Monitor the content of subscribed MQTT messages, turn on the LED when the status is on , and turn off the LED when the status is off .

# led.py
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO
import json


# MQTT broker config
broker = '127.0.0.1'
port = 1883
topic = 'smartHomeHubs/led'


def on_connect(client, userdata, flags, rc):
    print("Connecting to the MQTT broker...")
    if rc == 0:
        print("Connection success")
    else:
        print("Connected with result code "+str(rc))
    client.subscribe(topic)


def on_message(client, userdata, msg):
    payload = json.loads(msg.payload)
    led_status = payload.get('status')
    gpio_status = GPIO.input(4)
    if led_status == 'on' and gpio_status == 0:
        GPIO.output(4, True)
        print('LED on')
    elif led_status == 'off' and gpio_status == 1:
        GPIO.output(4, False)
        print('LED off')
    else:
        pass


def run():
    # connect MQTT broker
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect(broker, 1883, 60)
    # set Raspberry Pi GPIO pin
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.setup(4, GPIO.OUT)
    try:
        client.loop_forever()
    except KeyboardInterrupt:
        GPIO.cleanup()


if __name__ == "__main__":
    run()

Run test

  1. python gy30.py Obtain light data and report the data to the **smartHomeHubs/light ** topic.

Insert picture description here

  1. python led.pySubscribe to smartHomeHubs/led topics and monitor LED control information.

Insert picture description here

  1. When we manually lower or raise the light, we can see that the LED lights are also turned on and off at the same time.

Insert picture description here

to sum up

So far, we have successfully built a smart home gateway based on Raspberry Pi + EMQ X Edge + EMQ X Kuiper .

We use Raspberry Pi to provide a rich external communication interface for the gateway, EMQ X Edge to provide the gateway with communication functions between devices, and EMQ X Kuiper to provide the gateway with device data processing and analysis functions.

After that, we use the light sensor to obtain the light intensity, and use the light intensity to control the on and off of the LED. In the whole process, all data is processed and analyzed locally, reducing the risk of family private data leakage.

Copyright statement: This article is EMQ original, please indicate the source for reprinting.

Original link: https://www.emqx.io/cn/blog/smart-home-hub-on-raspberry-pi

Guess you like

Origin blog.csdn.net/emqx_broker/article/details/107366612
Recommended