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
Lego Mindstorms EV3 and Lego Spike Prime

Lego Mindstorms EV3 and Lego Spike Prime What is FLL? The FIRST LEGO League Challenge Robotics Tournament challenges students from 9 to 16 years old t

Danimar Campos da Costa 1 Nov 14, 2021
Projet d'integration SRI 3A ROS

projet-integration-sri-2021-2022 Projet d'intégration ROS SRI 2021 2022 Organization: Planification de tâches Perception Saisie: Cédérick Mouliets Sim

AIP Primeca Occitanie 3 Jan 07, 2022
🔆 A Python module for controlling power and brightness of the official Raspberry Pi 7

rpi-backlight A Python module for controlling power and brightness of the official Raspberry Pi 7" touch display. Note: This GIF was created using the

Linus Groh 238 Jan 08, 2023
E-Ink Magic Calendar that automatically syncs to Google Calendar and runs off a battery powered Raspberry Pi Zero

E-Ink Magic Calendar that automatically syncs to Google Calendar and runs off a battery powered Raspberry Pi Zero

2.8k Dec 30, 2022
Automatic CPU speed & power optimizer for Linux

Automatic CPU speed & power optimizer for Linux based on active monitoring of laptop's battery state, CPU usage, CPU temperature and system load. Ultimately allowing you to improve battery life witho

Adnan Hodzic 3.4k Jan 07, 2023
Automate gate/garage door opening via 433.92MHz emitter with Raspberry Pi, Home Assistant and Homekit.

Automate opening your garage door / gate Summary This project sums up how I automated opening my garage door using a Raspberry PI, a 433Mhz emitter, H

Julien Fouilhé 29 Nov 30, 2022
ModbusTCP2MQTT - Sungrow & SMA Solar Inverter addon for Home Assistant

ModbusTCP2MQTT Sungrow & SMA Solar Inverter addon for Home Assistant This addon will connect directly to your Inverter using Modbus TCP. Support model

Teny Smart 40 Dec 21, 2022
Example code and projects for FeatherS2 and FeatherS2 Neo

FeatherS2 & FeatherS2 Neo This repo is a collection of code, firmware, and files

Unexpected Maker 5 Jan 01, 2023
Open source home automation that puts local control and privacy first.

Home Assistant Open source home automation that puts local control and privacy first. Powered by a worldwide community of tinkerers and DIY enthusiast

Home Assistant 57k Jan 01, 2023
A script that publishes power usage data of iDrac enabled servers to an MQTT broker for integration into automation and power monitoring systems

iDracPowerMonitorMQTT This script publishes iDrac power draw data for iDrac 6 enabled servers to an MQTT broker. This can be used to integrate the pow

Lucas Zanchetta 10 Oct 06, 2022
A simple non-official manager interface I'm using for my Raspberry Pis.

My Raspberry Pi Manager Overview I have two Raspberry Pi 4 Model B devices that I hooked up to my two TVs (one in my bedroom and the other in my new g

Christian Deacon 21 Jan 04, 2023
This Home Assistant custom component adding support for controlling Midea dehumidifiers on local network.

This custom component for Home Assistant adds support for Midea air conditioner and dehumidifier appliances via the local area network. homeassistant-

Nenad Bogojevic 92 Dec 31, 2022
For use with an 8-bit parallel TFT touchscreen using micropython

ILI9341-parallel-TFT-driver-for-micropython For use with an 8-bit parallel TFT touchscreen using micropython. Many thanks to prenticedavid and his MCU

3 Aug 02, 2022
The main aim of this project is to avoid the accidents in shredding ( Waste Recycling Industry )

shredder-Machine-Hand-Safety The main aim of this project is to avoid the accidents in shredding ( Waste Recycling Industry ) . The Basic function of

Shubham Chaudhari 1 Nov 15, 2021
A DUCO (Duino-Coin) miner for GigaDevice ARM boards.

GD32 Duino-Coin Miner Description Contains the firmware and miner software for mining DUCO (Duino-Coin) on GigaDevice GD32 chips. Supported boards GD3

Maximilian Gerhardt 2 Feb 20, 2022
Pylorawan is a Micropython wrapper for lorawan devices from RAK Wireless.

pylorawan Pylorawan is a Micropython wrapper for lorawan devices from RAK Wireless. Tested on a Raspberry PI Pico with a RAK4200(H) Evaluation Board (

Peter Houghton 3 Nov 04, 2022
HACS gives you a powerful UI to handle downloads of all your custom needs.

HACS (Home Assistant Community Store) Manage (Install, track, upgrade) and discover custom elements for Home Assistant directly from the UI. What? HAC

HACS 3.2k Jan 04, 2023
A python script for Homeassistant that counts down the days to birthdays, anniversaries etc

Date Countdown A python script for Homeassistant that counts down the days to birthdays, anniversaries etc Important note I no longer use homeassistan

Marc Forth 21 Mar 12, 2022
An emulated LED scoreboard for Major League Baseball ⚾

An LED scoreboard for Major League Baseball. Displays a live scoreboard for your team's game on that day.

Tyler Porter 8 Apr 08, 2022
Extremely simple PyBadge examples to demonstrate different aspects of CircuitPython using PyBadge hardware.

BeginnerPyBadge I purchased a PyBadge recently. I'm new to hardware. I was surprised how hard it was to find easy examples demonstrating how different

Rubini LaForest 2 Oct 21, 2021