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
🎃 Some spooky code samples to hack yourself a pumpkin 👻

🎃 Tech Or Treat 👻 It's spooky season for those who celebrate Halloween, and to get in the spirit (spirit - get it? 👻 ) we thought it would be fun t

Jim Bennett 5 Feb 07, 2022
Isaac Gym Environments for Legged Robots

Isaac Gym Environments for Legged Robots This repository provides the environment used to train ANYmal (and other robots) to walk on rough terrain usi

Robotic Systems Lab - Legged Robotics at ETH Zürich 372 Jan 08, 2023
LUNA: a USB multitool & nMigen library

LUNA is a full toolkit for working with USB using FPGA technology; and provides hardware, gateware, and software to enable USB applications.

Great Scott Gadgets 750 Dec 28, 2022
a fork of the OnionShare software better optimized for lower spec lightweight machines and ARM processors

OnionShare-Optimized A fork of the OnionShare software better optimized for lower spec lightweight machines and ARM processors such as Raspberry Pi or

ALTPORT 4 Aug 05, 2021
Imbalaced Classification and Robust Semantic Segmentation

Imbalaced Classification and Robust Semantic Segmentation This repo implements two algoritms. The imbalance clibration (IC) algorithm for image classi

24 Jul 23, 2022
HomeAssistant - Polyaire AirTouch 4 Integration

HomeAssistant - Polyaire AirTouch 4 Integration Custom integration to add an AirTouch 4 AC Controller Installation: Copy contents of custom_components

7 Aug 05, 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
This is a python script to grab data from Zyxel NSA310 NAS and display in Home Asisstant as sensors.

Home-Assistant Python Scripts Python Scripts for Home-Assistant (http://www.home-assistant.io) Zyxel-NSA310-Home-Assistant Monitoring This is a python

6 Oct 31, 2022
Hardware: CTWingSKIT_BC28 Development Toolkit

IoT Portal Monitor Tools hardware: CTWingSKIT_BC28 Development Toolkit serial port driver: ST-LINK hardware development environment: Keli 5 MDK IoT pl

Fengming Zhang 1 Nov 07, 2021
Simple Weather Check base on Hefeng api, Work on raspberry Pi

Simple Weather Check base on Hefeng api, Work on raspberry Pi

Retr0mous 28 Sep 17, 2022
A iot Bike sytem based on RaspberryPi, Ardiuino

Cyclic 's Kernel ---- A iot Bike sytem based on RaspberryPi, Ardiuino, etc 0x1 What is This? Cyclic 's Kernel is an independent System With self-produ

Retr0mous 2 Oct 09, 2022
Red Light Green Light Robot

Red Light Green Light Robot The primary problem addressed by our project is robotic follower behavior i.e. maintaining distance from a moving target.

Will Romano 2 Nov 20, 2021
Custom component for Home Assistant that integrates Candy/Haier Wi-Fi washing machines (also known as Simply-Fi).

Candy Home Assistant component Custom component for Home Assistant that integrates Candy/Haier Wi-Fi washing machines (also known as Simply-Fi). This

Olivér Falvai 61 Dec 29, 2022
Simple Microservice to control 433Mhz wireless sockets over HTTP, e.g. on a RaspberryPi

REST-light is a simple microservice to control 433Mhz wireless sockets over HTTP, e.g. on a RaspberryPi. The main usage is an easy integration of 433M

Pascal Höhnel 1 Jan 09, 2022
A rubiks cube timer using a distance sensor and a raspberry pi 4, and possibly the pi pico to reduce size and cost.

distance sensor cube timer A rubiks cube timer using a distance sensor and a raspberry pi 4, and possibly the pi pico to reduce size and cost. How to

3 Feb 21, 2022
Scripts for measuring and displaying thermal behavior on Voron 3D printers

Thermal Profiling Measuring gantry deflection and frame expansion This script runs a series of defined homing and probing routines designed to charact

Jon Sanders 30 Nov 27, 2022
Doughskript interpreter for converting simple command sequences into executable Arduino C++ code.

Doughskript interpreter for converting simple command sequences into executable Arduino C++ code.

Svjatoslav 2 Jan 11, 2022
Technical Answers to Real-World Problems. Evolution of Watering Manually to Watering Automatically.

Automatic Watering System using Soil Moisture Sensor and RTC Timer with Arduino Technical Answers to Real-World Problems Know the plant, Grow the plan

NelakurthiSudheer 3 Jan 03, 2022
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
Sleep Functionality for Adafruit MacroPad RP2040

Adafruit-MacroPad-RP2040 Sleep Functionality for Adafruit MacroPad RP2040 Details This is a modification of AdaFruit project bundle found here specifi

9 Dec 18, 2022