Homeautomation system created with Raspberry Pi 3 and Firebase.

Overview

Homeautomation System - Raspberry Pi 3

SmartHome

Desenvolvido com Python, Flask com AJAX e Firebase permite o controle local e remoto

Itens necessários

  • Raspberry Pi3 Modelo B
  • Relé
  • 1 dispositivo para ser controlado (Usei uma lâmpada, mas pode ser qualquer outro)
  • Jumpers
  • Sensores (Se quiser melhorar ainda mais)

Getting start

Cenário 1: Clonar e executar
Cenário 2: Criar sua própria app seguindo o passo a passo

Clonar e executar

1. Instalação do sistema operacional

Se o seu Rasp for novo acompanhe o seguinte manual para instalação e configuração:
Instalação do SO Ou acompanhe o minicurso do Curso em vídeo

2. Conexõs físicas

Desligue seu Rasp antes de continuar para evitar danos.
Faça um esquema no Fritzing para definir qual pino será usado em qual dispositivo. Como na figura:
Esquema -O pino com conexão vermelha é o VCC, alimenta com 5V
-O pino com conexão preta é o GND (terra)
-O pino com conexão amarela é o 13 (GPIO), o que vamos conectar ao dispositivo a ser controlado
-O relé contém módulos, estamos utilizando o primeiro, atenção no processo das conexões para não danificar o Rasp nem causar mal funcionamento.
Para saber mais sobre as GPIO consulte Raspberry Pi GPIO

3. Instale o git com o comando

apt install git

4. Clone este repositório com

git clone https://github.com/joselinosantosti/homeautomation-raspberrypi.git

5. Execute a aplicação com o comando

python app.py

6. Acesse o browser e digite

localhost:5000
Faça o login com admin admin e teste seus dispositivos

Projeto Step by step

Realize os passos 1 e 2 se ainda não realizou, são pré-requisitos

1. Criando virtualenv e instalando os pacotes necessários

Abra o terminal e digite os comandos:
sudo su(digite a senha)
apt-get update && apt-get upgrade
apt install virtualenv

Crie o virtualenv com o comando
virtualenv venv

Instale o flask
pip install flask

2. Estruturando o projeto Flask

Crie uma pasta com o nome smarthome ou outro que achar mais conveniente.
Crie as subpastas
-static (para arquivos de imagens, estilos css e Javascript)
-templates (para os arquivos html)
-models
Crie o arquivo app.py e adicione os códigos para as rotas de acordo com seu projeto. A seguinte rota aceita os método GET e POST e retorna a renderização da página index.html que por sua vez tem uma lógica para incorporar o código html da página lighting.html presente na pasta templates.

def lighting():
	return render_template('index.html', module='lighting')

Arquivo html com os inputs Crie um formulário que chama outra rota e com os inputs que achar convenientes. O csrf_token é obrigatório nos formulários Flask.

Classe Device Crie um arquivo com o nome Device e adicione a classe:

gpio.setmode(gpio.BOARD)

class Device:
def __init__(self, pino, status):
    self.pino = pino
    self.status = status

    gpio.setup(self.pino, gpio.OUT)
    gpio.output(self.pino, self.status)

Com essa classe reaproveitamos o código para controlar uma grande quantidade de dispositivos de forma simples e enxuta.

3. Controlando dispositivos com AJAX

No seu arquivo principal importe a classe com o código:
from models.Device import Device
Crie um arquivo scripts.js na pasta /static/js e adicione o código AJAX

{ slider.addEventListener("click", (e) => { const pino = slider.getAttribute("name") control(pino) }) }) })">
$(document).ready(function() {
    function control(pino) {

        $.ajax({
            url: `/control/${pino}`,
            data: $('form').serialize(),
            type: 'POST',
            success: (response) => {
                console.log(response)
            },
            error: (error) => {
                console.log(error)
            }
        })
    }
   //Selecionar todos os inputs e adicionar evento de click
    document.querySelectorAll(".device").forEach(slider => {
        slider.addEventListener("click", (e) => {
            const pino = slider.getAttribute("name")
            control(pino)
          })
    })
})

É um código AJAX convencional. A cada clique no botão do dispositivo é capturado o name(numero do pino) e executada a função control() passando o valor capturado como parâmetro

O código AJAX chama a rota '/control' passando o valor como parâmetro para ser usado no código Python.

Código Python
O seguinte código recebe a requisição via AJAX, instancia a classe Dispositivo passando o pino e ação. Em seguida retorna os dados para fins de debug.

", methods=['GET','POST']) def control(pino): status = 1 if len(request.form) > 1 else 0 dev = Device(pino, status) response = {'response': 200, 'pino': pino, 'status': status} return response">
@app.route("/control/
    
     ", methods=['GET','POST'])
def control(pino):
	status = 1 if len(request.form) > 1 else 0
	dev = Device(pino, status)
	response = {'response': 200, 'pino': pino, 'status': status}
	return response

    

A lógica da variável status retorna 1 se o resultado da requisição for maior que 1, o que só ocorre quando o resultado do input for positivo, no caso do checkbox desmarcado nada será retornado além do csrf_token. Desse modo saberemos que o campo está desmarcado e retorna status = 0.

Conexão com Firebase e controle via Internet

...

Owner
Joselino Santos
Web Developer | Data Analyst
Joselino Santos
Adafruit IO connected smart thermostat based on CircuitPython.

Adafruit IO Thermostat Adafruit IO connected smart thermostat based on CircuitPython. Background and Motivation I have a 24 V Heat-only system with a

Shubham Chaudhary 1 Jan 18, 2022
Universal Xiaomi MIoT integration for Home Assistant

Xiaomi MIoT Raw 简体中文 | English MIoT 协议是小米智能家居从 2018 年起推行的智能设备通信协议规范,此后凡是可接入米家的设备均通过此协议进行通信。此插件按照 MIoT 协议规范与设备通信,实现对设备的状态读取及控制。

1.9k Jan 02, 2023
Python script for printing to the Hanshow price-tag

This repository contains Python code for talking to the ATC_TLSR_Paper open-source firmware for the Hanshow e-paper pricetag. Installation # Clone the

12 Oct 06, 2022
Component for deep integration LedFx from Home Assistant.

LedFX for Home Assistant Component for deep integration LedFx from Home Assistant. Table of Contents FAQ Install Config Performance FAQ Q. What versio

Dmitry Mamontov 28 Dec 13, 2022
Mycodo is open source software for the Raspberry Pi that couples inputs and outputs in interesting ways to sense and manipulate the environment.

Mycodo Environmental Regulation System Latest version: 8.12.9 Mycodo is open source software for the Raspberry Pi that couples inputs and outputs in i

Kyle Gabriel 2.3k Dec 29, 2022
PBA: Pleco Breeding Assistant

A small monitor that reports the external, fishroom and water change parameters to have suitable water parameters and induce breeding. These two features already represent 50% of the "reproductive su

Mirko Mancin 1 Jan 19, 2022
How to configure IOMMU device for nested Proxmox hypervisor (PVE) VM - PCIe Passthrough

Configuring PCIe Passthrough for Nested Virtualization on Proxmox Summary: If you are running bare-metal L0 (level 0) Proxmox (PVE) hypervisor with ne

Travis Johnson 6 Aug 30, 2022
emhass: Energy Management for Home Assistant

emhass EMHASS: Energy Management for Home Assistant Context This module was conceived as an energy management optimization tool for residential electr

David 70 Dec 24, 2022
An open source operating system designed primarily for the Raspberry Pi Pico, written entirely in MicroPython

PycOS An open source operating system designed primarily for the Raspberry Pi Pico, written entirely in MicroPython. "PycOS" is an combination of the

8 Oct 06, 2022
A raspberrypi tools for python

raspberrypi-tools how to install: first clone this project: git clone https://github.com/Ardumine/rpi-tools.git then go to the folder cd rpi-tools and

1 Jan 04, 2022
Turns a compatible Raspberry Pi device into a smart USB drive for PS4/PS5.

PSBerry A WIP project for Raspberry Pi, which turns a compatible RPI device into a smart USB drive for PS4/PS5. Allows for save management of PS4 game

Filip Tomaszewski 2 Jan 15, 2022
Pure micropython ESP32 SPI driver for sdcard and screen at the same SPI bus

micropython-esp32-spi-sdcard-and-screen-driver Proof of concept of Pure micropython espidf SPI driver for sdcard with screen at the same SPI bus (exam

Thomas Favennec 7 Mar 14, 2022
Pinion — Nice-looking interactive diagrams for KiCAD PCBs

Pinion — Nice-looking interactive diagrams for KiCAD PCBs Pinion is a simple tool that allows you to make a nice-looking pinout diagrams for your PCBs

Jan Mrázek 297 Jan 06, 2023
A small Python app to converse between MQTT messages and 433MHz RF signals.

mqtt-rf-bridge A small Python app to converse between MQTT messages and 433MHz RF signals. This acts as a bridge between Paho MQTT and rpi-rf. Require

David Swarbrick 3 Jan 27, 2022
Home assiatant Custom component: Camera Archiver

Camera archiver Archive your ftp camera meadia files on other ftp with files renaming and event creation. Event can be used for send information to el

1 Jan 06, 2022
Jarvis: a personal assistant which can help you to manage your system

Jarvis Jarvis is personal AI based assistant which can help you to manage stuff in your computer. This is demo but I decided to make it more better so

2 Jun 02, 2022
Alternative firmware for ESP8266 with easy configuration using webUI, OTA updates, automation using timers or rules, expandability and entirely local control over MQTT, HTTP, Serial or KNX. Full documentation at

Alternative firmware for ESP8266/ESP32 based devices with easy configuration using webUI, OTA updates, automation using timers or rules, expandability

Theo Arends 59 Dec 26, 2022
Sticklog2heatmap - Draw a heatmap of RC sticks from OpenTX logs or USB HID device

sticklog2heatmap Draw a heatmap of RC sticks from OpenTX logs or USB HID device

2 Feb 02, 2022
PyLog - Simple keylogger that uses pynput to listen to keyboard input.

Simple keylogger that uses pynput to listen to keyboard input. Outputs to a text file and the terminal. Press the escape key to stop.

1 Dec 29, 2021
Raspberry Pi Pico development platform for PlatformIO

Raspberry Pi Pico development platform for PlatformIO A few words in the beginning Before experimental please Reinstall the platform Version: 1.0.0 Th

Georgi Angelov 160 Dec 23, 2022