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
Shotgrid Toolkit Engine for Gaffer

Shotgun toolkit engine for Gaffer Contact : Diego Garcia Huerta Overview Implementation of a shotgun engine for Gaffer. It supports the classic bootst

Diego Garcia Huerta 12 May 21, 2022
Make your MacOS keyboard brightness fade in and out

Make your MacOS keyboard brightness fade in and out. (It's working depends on the Kbrightness file, which only works for 2015 Macs, so this will only work on 2015 Macs.)

1 Dec 16, 2021
Custom component for interacting with Octopus Energy

Home Assistant Octopus Energy ** WARNING: This component is currently a work in progress ** Custom component built from the ground up to bring your Oc

David Kendall 116 Jan 02, 2023
A simple Python script for toggling Philips Hue Lights by clapping

LightsClap A simple Python script for toggling Philips Hue Lights by clapping Usage pip3 install -r requirements.txt python3 main.py and press the Ent

Flux Industries 2 Nov 16, 2021
An open source two key macro-pad modeled to look like a cartoony melting popsicle

macropopsicle An open source two key macro-pad modeled to look like a cartoony melting popsicle. Build instructions Parts List -1x Top case half (3D p

17 Aug 18, 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
Add filters (background blur, etc) to your webcam on Linux.

webcam-filters Add filters (background blur, etc) to your webcam on Linux. Video conferencing applications tend to either lack video effects altogethe

Jashandeep Sohi 480 Dec 14, 2022
A simple Picobot project implemented in Python

Python-Picobot A simple Picobot project implemented in Python About Explanation This is my first programming project. Picobot use rules.txt file which

Shayan Shiravani 0 Apr 03, 2022
Repo for the esp32s2 version of the Wi-Fi Nugget

Repo for the esp32s2 version of the Wi-Fi Nugget

HakCat 30 Nov 05, 2022
Python information display framework aimed at e-ink devices

My display, using a Raspberry Pi Zero W and Waveshare 6" e-paper hat infodisplay Modular information display framework aimed at e-ink devices. Built u

Niek Blankers 3 Apr 08, 2022
LT-OCF: Learnable-Time ODE-based Collaborative Filtering, CIKM'21

LT-OCF: Learnable-Time ODE-based Collaborative Filtering Our proposed LT-OCF Our proposed dual co-evolving ODE Setup Python environment for LT-OCF Ins

Jeongwhan Choi 15 Dec 28, 2022
GUI wrapper designed for convenient service work with TI CC1352/CC2538/CC2652 based Zigbee sticks or gateways. Packed into single executable file

ZigStar GW Multi tool is GUI wrapper firtsly designed for convenient service work with Zig Star LAN GW, but now supports any TI CC1352/CC2538/CC2652 b

133 Jan 01, 2023
Home Assistant custom integration to fetch data from Powerpal

Powerpal custom component for Home Assistant Component to integrate with powerpal. This repository and integration is not affiliated with Powerpal. Th

Lawrence 32 Jan 07, 2023
Brogrammer-keyboard - FIrmware for the Brogrammer Keyboard v1.0

Brogrammer Keyboard Firmware The package contains the firmware that runs on the Brogrammer Keyboard v1.0 See https://imgur.com/a/oY5QZ14 This keyboard

Devin Hartleben 1 Apr 21, 2022
Keystroke logging, often referred to as keylogging or keyboard capturing

Keystroke logging, often referred to as keylogging or keyboard capturing, is the action of recording the keys struck on a keyboard, typically covertly, so that a person using the keyboard is unaware

Bhumika R 2 Jan 11, 2022
A DiY holiday project to demonstrate how you can send data from adafruitIO cloud to a balena edge device

holiday-star balena ❤️ adafruitIO Introduction A DiY holiday project to demonstrate how you can send data from adafruitIO cloud to a balena edge devic

Ayan Pahwa 3 Dec 20, 2021
Control DJI Tello with Raspberry Pi and PS4 Controller

Control-DJI-Tello-with-Raspberry-Pi-and-PS4-Controller Demo of this project see

MohammadReza Sharifi 24 Aug 11, 2022
Simple Python script to decode and verify an European Health Certificate QR-code

A simple Python script to decode and verify an European Health Certificate QR-code.

Mathias Panzenböck 61 Oct 05, 2022
My 500 LED xmas tree

xmastree2020 This repository contains the code used for Matt's Christmas tree, as featured in "I wired my tree with 500 LED lights and calculated thei

Stand-up Maths 581 Jan 07, 2023
Aqara Camera G3 integration for Home Assistant

Aqara Camera G3 integration for Home Assistant ATTENTION: The component only works after enabled telnet. Only supportd stream. Not support still image

14 Dec 18, 2022