smart-house Documentation Release 0.0.2

Douglas Lohmann

December 01, 2016

Contents

1 Licença 3

2 Sobre nós 9

3 Casa inteligente 11

4 Internet das Coisas 13

5 Processo de desenvolvimento de software 15

6 Hardware 17

7 19

8 Estrutura IoT 21

9 Implementação da Estrutura IoT 25

10 Estrutura da Casa Inteligente 31

i ii smart-house Documentation, Release 0.0.2

Este projeto tem como objetivo apresentar os fundamentos computacionais para construção de uma casa inteligente. Nas proximas seçoes serão apresentados todos os passos do desenvolvimento de softawere necessario para construção da casa e todos os conteudos necessesarios para o entendimento dessa. O projeto visa a construção de Recurso educacional aberto (REA). Segundo o Projeto Brasileiro sobre Recursos Educacionais Abertos, REA são materiais de ensino, aprendizado e pesquisa, fixados em qualquer suporte ou mídia, que estejam sob domínio público ou licenciados de maneira aberta, permitindo que sejam utilizados ou adaptados por terceiros. Para maiores informações sobre REA acesse: http://www.rea.net.br/site/. Os arquivos e códigos fonte do projetos estão disponíveis em: https://github.com/hackerspace-utfpr-cm/smarthouse.

Contents 1 smart-house Documentation, Release 0.0.2

2 Contents CHAPTER 1

Licença

Este projeto é um software livre; você pode redistribuí-lo e/ou modificá-lo dentro dos termos da Licença Creative Commons Attribution Share Alike (CC-BY-SA).

1.1 Creative commons Attribution-ShareAlike 4.0 International Public License (CC-BY-SA)

By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-ShareAlike 4.0 International Public License (“Public License”). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.

1.1.1 Section 1 – Definitions.

1. Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or oth- erwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 2. Adapter’s License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 3. BY-SA Compatible License means a license listed at [creativecom- mons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Com- mons as essentially the equivalent of this Public License. 4. Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 5. Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 6. Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.

3 smart-house Documentation, Release 0.0.2

7. License Elements means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution and ShareAlike. 8. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 9. Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 10. Licensor means the individual(s) or entity(ies) granting rights under this Public License. 11. Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, commu- nication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 12. Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the Euro- pean Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 13. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corre- sponding meaning.

1.1.2 Section 2 – Scope.

1. License grant. 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a world- wide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 1. reproduce and Share the Licensed Material, in whole or in part; and 2. produce, reproduce, and Share Adapted Material. 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 3. Term. The term of this Public License is specified in Section 6(a). 4. Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Li- censed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 5. Downstream recipients. 1. Offer from the Licensor – Licensed Material. Every recipient of the Licensed Material auto- matically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 2. Additional offer from the Licensor – Adapted Material. Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply.

4 Chapter 1. Licença smart-house Documentation, Release 0.0.2

3. No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 6. No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or spon- sored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 2. Other rights. 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 2. Patent and trademark rights are not licensed under this Public License. 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties.

1.1.3 Section 3 – License Conditions.

Your exercise of the Licensed Rights is expressly made subject to the following conditions. 1. Attribution. 1. If You Share the Licensed Material (including in modified form), You must: 1. retain the following if it is supplied by the Licensor with the Licensed Material: 1. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 2. a copyright notice; 3. a notice that refers to this Public License; 4. a notice that refers to the disclaimer of warranties; 5. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 2. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 3. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 2. ShareAlike. In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.

1.1. Creative commons Attribution-ShareAlike 4.0 International Public License (CC-BY-SA) 5 smart-house Documentation, Release 0.0.2

1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-SA Compatible License. 2. You must include the text of, or the URI or hyperlink to, the Adapter’s License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material. 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Techno- logical Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter’s License You apply.

1.1.4 Section 4 – Sui Generis Database Rights.

Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 1. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database; 2. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and 3. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.

1.1.5 Section 5 – Disclaimer of Warranties and Limitation of Liability.

1. Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Li- censed Material as-is and as-available, and makes no representations or warranties of any kind concern- ing the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You. 2. To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You. 3. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.

1.1.6 Section 6 – Term and Termination.

1. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 2. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or

6 Chapter 1. Licença smart-house Documentation, Release 0.0.2

2. upon express reinstatement by the Licensor. For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 3. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 4. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.

1.1.7 Section 7 – Other Terms and Conditions.

1. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 2. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.t stated herein are separate from and independent of the terms and conditions of this Public License.

1.1.8 Section 8 – Interpretation.

1. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 2. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 3. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 4. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. ‘‘‘ Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. Creative Commons may be contacted at [creativecommons.org](http://creativecommons.org/). ‘‘‘

1.1. Creative commons Attribution-ShareAlike 4.0 International Public License (CC-BY-SA) 7 smart-house Documentation, Release 0.0.2

8 Chapter 1. Licença CHAPTER 2

Sobre nós

Este trabalho foi desenvolvido no projeto Compute você Mesm@: Conexões de saberes e fazeres para inclusão digital.

2.1 Sobre nós

Copyright © Os autores e as autoras – CC-BY-SA: O trabalho Introdução à computação utilizando IoT no contexto de automação residencial está licenciado com uma Licença Creative Commons - Atribuição - Compartilha Igual 4.0 Internacional. Autores e Autoras deste documento – Douglas Lohmann, Cezar Bertelli, Milene Lauize Silva, Marco Aurélio Gra- ciotto Silva, Paulo Cesar Gonçalves Universidade Tecnológica Federal do Paraná - Câmpus Campo Mourão – Luiz Alberto Pilatti (Reitoria), Maurício Alves Mendes (Pró-Reitoria de Graduação e Educação Profissional), Heron Oliveira dos Santos Lima (Diretoria Geral do Câmpus Campo Mourão), Adriano Lopes Romero (Diretoria de Graduação e Educação Profissional) Departamento Acadêmico de Computação - DACOM – Ivanilton Polato (Chefia do Departamento Acadêmico de Computação 2017-19), Igor Fábio Steinmacher (Coordenação do Bacharelado em Ciência da Computação 2016-2018) Projeto Compute você Mesm@: Conexões de saberes e fazeres para inclusão digital – Marília Abrahão Amaral (Coordenadora) Agradecimentos – Fundação Araucária, Governo do Estado do Paraná/SETI, Governo Federal/Ministério das Comu- nicações

9 smart-house Documentation, Release 0.0.2

10 Chapter 2. Sobre nós CHAPTER 3

Casa inteligente

Uma casa inteligente integra elementos computacionais – hardware e software – para tornar o ambiente doméstico otimizado às pessoas, seja pela automatização de ações rotineiras como pela adaptação do ambiente para as pessoas conforme o contexto – atividades realizantes, condições do ambiente – e com utilização racional e sustentável de recursos.

11 smart-house Documentation, Release 0.0.2

12 Chapter 3. Casa inteligente CHAPTER 4

Internet das Coisas

A Internet pode ser dividida em três fases. A primeira fase é a Internet como uma rede de computadores. A segunda fase a Internet pode ser considerada uma rede de pessoas e comunidades. Atualmente estamos vivendo a evolução para terceira fase, a Internet das Coisas (do inglês, - IoT). Nesta fase a rede passa a interligar vários tipos de objetos e dispositivos inteligentes do nosso cotidiano que vão interagir entre si e conosco.

4.1 Estrutura da Internet das Coisas

A Internet pode ser dividida em três fases. A primeira fase é a Internet como uma rede de computadores. A segunda fase a Internet pode ser considerada uma rede de pessoas e comunidades. Atualmente estamos vivendo a evolução para terceira fase, a Internet das Coisas (do inglês, Internet of Things - IoT). Nesta fase a rede passa a interligar vários tipos de objetos e dispositivos inteligentes do nosso cotidiano que vão interagir entre si e conosco. A Figura 1 mostra o diagrama de blocos que representa as partes e as características de uma coisa (thing) capaz de integrar uma IoT. Independentemente de sua funcionalidade, cada coisa sempre “vive” em um determinado ambiente e terá um processador, um transceptor de comunicação e uma fonte de energia [3]. Desta forma, é notável que existem alguns requisitos para um dispositivo ou aplicações IoT. Os elementos esperados são: • Computação: ter capacidades de processamento e memória que lhes permitam implementar desde a mais simples lógica até complexos algoritmos. • Comunicação: ter pelo menos um meios de comunicação, preferencialmente sem fios, adaptado às necessidades de aplicação, como consumo de energia e taxa de transferência de dados. • Sensores: coletam e processam as informações do mundo real em contextos ambientais. A informação a partir do contexto ambiental é útil para criar uma imagem instantânea do que está acontecendo em cada momento. • Atuadores: fornecem a capacidade de agir sobre o ambiente. Aplicações IoT podem ter de agir sobre o meio am- biente, quando o usuário não é capaz de controlar, não ter conhecimento de situações específicas que necessitem de acionamento ou mesmo simplesmente porque não está presente no ambiente. • Interfaces homem-máquina: incluindo meios de interação de entrada como chaves e botões e saída como leds e display, proporcionando ao usuário informações relevantes sobre eventos. • Fonte de energia: qualquer coisa eletrônica precisa de energia para funcionar, normalmente uma bateria.

13 smart-house Documentation, Release 0.0.2

Fig. 4.1: Figura 1: Diagrama de blocos de uma “coisa” no contexto de IoT.

14 Chapter 4. Internet das Coisas CHAPTER 5

Processo de desenvolvimento de software

Para começarmos o desenvolvimento de sistema de software exitem vários métodos e ferramentas que auxiliam no controle do desenvolvimento do projeto, neste trabalho utilizamos o método kanban, que é uma metódo ágil de desen- volvimento de software baseado nas práticas Lean, e tem como objetivo otimizar o processo de desenvolvimento de software. Para auxiliar na utilização desse metódo vamos usar a ferramenta Waffle.io. Para contrução da casa devemos em primeiro momento realizar um levantamento dos requisitos necessário para que está atenda todas as necessidades desejadas, feito o levantamento dos requisitos dividimos estes em tarefas e as dis- tribuimos no Kanban Board. Board disponível em: https://waffle.io/lohmanndouglas/smarthouse/join

15 smart-house Documentation, Release 0.0.2

16 Chapter 5. Processo de desenvolvimento de software CHAPTER 6

Hardware

• sistemas embarcados • microcontroladores • sensores • atuadores

17 smart-house Documentation, Release 0.0.2

18 Chapter 6. Hardware CHAPTER 7

Arduino

Arduino - https://www.arduino.cc/en/Guide/Introduction - é uma plataforma de prototipagem de código aberto baseada na fácil utilização do software e hardware. As placas Arduino são capazes de efetuarem leitura de uma entrada (sensores) e transformar em uma de saída (Atuadores). O projeto Arduino nasceu no Ivrea Interaction Design Institute como uma ferramenta fácil para prototipagem rápida, destinado a estudantes sem conhecimento aprofundado em eletrônica e programação. A plataforma Arduino possui uma IDE para a programação e para gravar códigos na placa, a IDE está possui suporte a , Mac e Windows. Existem diversas placas de hardware Arduino, sendo a mais comum a Arduino Uno. As placas diferem basicamente no microcontrolador embutido, no número de entradas/saídas, na frequência de processamento e entre outras configu- rações. Neste Material vamos utilizar o Arduino Uno por ser facilmente encontrado no mercado e apresentar baixo custo de aquisição se comparado com outras plataformas de hardware. O Arduino Uno - https://www.arduino.cc/en/Main/ArduinoBoardUno - opera com uma velocidade de clock de 16 MHz, possui 14 pinos de entrada e saída digitais e 6 pinos de entrada e saída analógica, memória flash 32 KB (0.5 KB usados pelo Bootloader), memória SRAM de 2 KB e 1 KB de memória EEPROM. A placa pode ser alimentada pela conexão USB ou por uma fonte de alimentação externa. Para alimentação externa é utilizado um conector Jack com positivo no centro, sendo que a placa suporta alimentação de 6 à 20 volts. Porém, é recomendado que a fonte de alimentação externa possua tensão entre 7 e 12 volts. A Figura 1 ilustra o Arduino Uno utilizado neste projeto, ele tem 14 pinos de entradas/saídas digitais. Alguns desses pinos possuem funções especificas como PWM (pinos 3, 5, 6, 9, 10 e 11 ), comunicação serial (pinos 0 e 1) e interrupção externa (pinos 2 e 3). Para interface com o mundo analógico, a placa Arduino UNO possui 6 entradas, onde cada uma tem a resolução de 10 bits.

19 smart-house Documentation, Release 0.0.2

Fig. 7.1: Figura 1: Arduino Uno.

20 Chapter 7. Arduino CHAPTER 8

Estrutura IoT

A seguir é descrito uma estrutura para IoT, composta pelos componentes de hardware e software citados nos tópicos anteriores.

8.1 Estrutura da Internet das Coisas

Uma característica essencial em IoT é a capacidade dos dispositivos se comunicar, direta ou indiretamente, com a Internet. Uma arquitetura típica para isto consiste na construção de uma rede de dispositivos IoT com uma unidade de controle como dispositivo central, sensores que coletam informação do meio ambiente, atuadores e módulos de comunicação. O dispositivo central, neste caso, é encarregado da comunicação com a Internet. A unidade de controle, no contexto de internet das Coisas, são dispositivos que utilizam um microcontro- lador, o qual é responsável por processar informações. Na oficina utilizamos a plataforma de hardware aberto Arduino, pois este contém uma vasta quantidade de exemplos disponíveis e possui uma comu- nidade ativa para suporte. Os módulos de comunicação são responsáveis pela comunicação entre dispositivos da rede IoT. Alguns dos módulos avaliados foram os módulos WiFi, Bluetooth, nRF24l01 e ZigBee. Um fator importante na escolha do módulo é a existência de uma framework para dar suporte a implementação da rede. Con- siderando tais fatores, nesta implementação foi escolhido o módulo nRF24l01. Ele é um chip transceptor de baixo custo, projetado para aplicações sem fio, de baixa potencia e suportado por um framework com- patível com Arduino, chamado de MySensors. MySensors é uma API que possibilita a construção de uma rede de sensores de baixo custo. Além disso, essa API fornece ferramentas para gerenciar e analisar os dados dos sensores. A biblioteca facilita a implementação por possuir muitos exemplos e abstrair protocolos de comunicação entre os nós da rede. Utilizando a biblioteca e as plataformas descritas, é possível configurar uma infraestrutura para a rede IoT, como ilustra a Figura 2. A rede implementada basicamente é constituída por três componentes: contro- lador, gateway e nós finais, que são nós sensores e atuadores. Os nós sensores e atuadores são responsáveis pela interação com o ambiente, seja pela coleta de informações por meio de sensores, emissão de sinais de alerta ou ativação de certos dispositivos por meio de atuadores, por exemplo o ar condicionado ou uma lâmpada.

8.2 Nó Gateway

O gateway atua na ligação entre o controlador e rede de rádios. Ele traduz as mensagens do rádio para um protocolo que pode ser entendido por um controlador.

21 smart-house Documentation, Release 0.0.2

Fig. 8.1: Figura 2:Estrutura da Internet das Coisas

Na biblioteca MySensors exitem tres implementações de Gateway, o Ethernet Gateway, SerialGateway e MQTTGateway. Nesse material vamos utilizar o SerialGateway pela facilidade de implementação e também pela compatibilidade com o controlador escolhido.

8.3 Nó Sensor

Este tipo de nó é responsavel pela leitura de dados do meio externo e realizar a comunicação com o arduino. Sensor de temperatura, umidade e luminosidade são alguns exemplos de sensores.

8.4 Nó Atuador

Nós atuadores são aqueles que realizam alguma ação no ambiente, um servo motor por exemplo é um nó atuador, podendo ser utilzado para abir uma janela na casa ou mover algum objeto.

8.5 Nó Repetidor

Esse nó só é necessário quando os nós sensores e gateway não conseguem se comunicar, devido à distancia em que estão localizados, por esse motivo não está representado na Figura 2. Esse nó tem como função repetir as dados para outros nós a fim de aumentar a distancia de comunicação entre os nós. Em muitas aplicações esse nó não esta presente.

8.6 Nó Controlador

O controlador é responsável pela comunicação com a Internet. Na Figura 2 podemos observar que o controlador está diretamente conectado ao gateway e à Internet. Diferentemente dos outros nós, este componente da rede necessita de maior poder de processamento e deve ser implementado em hardware mais robusto, como a , BeagleBone ou até mesmo um desktop. O controlador pode realizar as seguintes funções: • Enviar parâmetros de configuração para os sensores na rede de rádio (tempo e identificadores de sensores únicos); • Acompanhar os dados mais recentes enviados pelos sensores e atuadores;

22 Chapter 8. Estrutura IoT smart-house Documentation, Release 0.0.2

• Fornecer informações de status de volta para sensores e atuadores; por exemplo o estado atual (on / off / loadLevel) para uma luz; • Fornecer controles de interface do usuário para atuadores; • Executa horários predefinidos ou cenas; por exemplo. ao pôr do sol acender as luzes do jardim.

8.6. Nó Controlador 23 smart-house Documentation, Release 0.0.2

24 Chapter 8. Estrutura IoT CHAPTER 9

Implementação da Estrutura IoT

Os próximos tópicos descrevem a implementação básica da infraestrutura IoT.

9.1 Implementação da Estrutura da Internet das Coisas

Para a implementação da estrutura de uma rede IoT devemos construir um nó gateway, um con- trolador e nós finais (Sensores e Atuadores). O rádio nRF24l01+ se comunica com Arduino via interface SPI. O rádio deve ser alimentado com uma tensão de 3.3 volts. Como o radio pos- sui conector de 8 pinos não é possível conecta-lo a protoboard. Então devemos utilizar conec- tores macho-fêmea, como ilustra a Figura 3, para fazer ligação ou construir um shield para adap- tação do módulo. Os próximos tópicos descrevem detalhes para construção de cada tipo de nó.

Fig. 9.1: Figura 1: Conectando nRF24l01 no Arduino.

9.2 Implementação Nó Gateway

Neste tópico vamos demostrar a contrução de nó gateway, que como vimos é responsável pela comu- nicação entre os nós finais e o controlador. Para implementação deste nó devemos conectar o rádio nRf24l01+ no arduino e utilizarmos o código:

25 smart-house Documentation, Release 0.0.2

1 /** 2 * The MySensors Arduino library handles the wireless radio link and protocol 3 * between your home built sensors/actuators and HA controller of choice. 4 * The sensors forms a self healing radio network with optional repeaters. Each 5 * repeater and gateway builds a routing tables in EEPROM which keeps track of the 6 * network topology allowing messages to be routed to nodes. 7 * 8 * Created by Henrik Ekblad 9 * Copyright (C) 2013-2015 Sensnology AB 10 * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors 11 * 12 * Documentation: http://www.mysensors.org 13 * Support Forum: http://forum.mysensors.org 14 * 15 * This program is free software; you can redistribute it and/or 16 * modify it under the terms of the GNU General Public License 17 * version 2 as published by the Free Software Foundation. 18 * 19 ******************************* 20 * 21 * DESCRIPTION 22 * The ArduinoGateway prints data received from sensors on the serial link. 23 * The gateway accepts input on seral which will be sent out on radio network. 24 * 25 * The GW code is designed for Arduino Nano 328p / 16MHz 26 * 27 * Wire connections (OPTIONAL): 28 * - Inclusion button should be connected between digital pin 3 and GND 29 * - RX/TX/ERR leds need to be connected between +5V (anode) and digital pin 6/5/4 with resistor 270-330R in a series 30 * 31 * LEDs (OPTIONAL): 32 * - To use the feature, uncomment WITH_LEDS_BLINKING in MyConfig.h 33 * - RX (green) - blink fast on radio message recieved. In inclusion mode will blink fast only on presentation recieved 34 * - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly 35 * - ERR (red) - fast blink on error during transmission error or recieve crc error 36 * 37 */ 38

39 #define NO_PORTB_PINCHANGES

40

41 #include

42 #include

43 #include

44 #include

45 #include

46 #include

47

48 #include

49 #include

50 #include

51 #include

52 #include

53 #include "GatewayUtil.h"

54

55 #define INCLUSION_MODE_TIME 1 // Number of minutes inclusion mode is enabled

56 #define INCLUSION_MODE_PIN 3 // Definição do pino digital para botão

57 #define RADIO_ERROR_LED_PIN 4 // Pino do LED de erro

58 #define RADIO_RX_LED_PIN 6 // Pino do LED de recebimento

26 Chapter 9. Implementação da Estrutura IoT smart-house Documentation, Release 0.0.2

59 #define RADIO_TX_LED_PIN 5 // Pino do LED de transmissão

60

61 // NRFRF24L01 radio driver (transmissão de baixa potência)

62 MyTransportNRF24 transport(RF24_CE_PIN, RF24_CS_PIN, RF24_PA_LEVEL_GW);

63 //MyTransportRFM69 transport;

64

65 // Definição do tipo do Hardware(Microcontrolador)

66 MyHwATMega328 hw;

67

68 // Definição e criação do argumento gw do tipo MySensor a partir do parâmetro WITH_LEDS_BLINKING de MyConfig.h

69 #ifdef WITH_LEDS_BLINKING 70 MySensor gw(transport, hw /*, signer*/, RADIO_RX_LED_PIN, RADIO_TX_LED_PIN, RADIO_ERROR_LED_PIN); 71 #else 72 MySensor gw(transport, hw /*, signer*/); 73 #endif

74

75 char inputString[MAX_RECEIVE_LENGTH]=""; // String para manter comandos de entrada serial/ethernet

76 int inputPos=0;

77 boolean commandComplete= false; // Se a string está completa

78 79 void parseAndSend(char *commandBuffer); 80

81 // Função para saída serial 82 void output(const char *fmt, ... ) { 83 va_list args;

84 va_start (args, fmt );

85 vsnprintf_P(serialBuffer, MAX_SEND_LENGTH, fmt, args);

86 va_end (args);

87 Serial.print(serialBuffer);

88 }

89

90 // Função de configuração

91 void setup()

92 {

93 gw.begin(incomingMessage,0, true,0);

94

95 setupGateway(INCLUSION_MODE_PIN, INCLUSION_MODE_TIME, output);

96

97 // Adicionando interrupção para inclusão de pino.

98 PCintPort::attachInterrupt(pinInclusion, startInclusionInterrupt, RISING);

99

100

101 // Enviar mensagem da inicialização serial.

102 serial(PSTR("0;0;%d;0;%d;Gateway startup complete.\n"), C_INTERNAL, I_GATEWAY_READY);

103 }

104

105 void loop()

106 {

107 gw.process();

108

109 checkButtonTriggeredInclusion();

110 checkInclusionFinished();

111

112 // Verifica se um comando serial foi emitido

113 if (commandComplete) {

114 // Comando serial tentará ser enviado ao atuador

115 parseAndSend(gw, inputString);

116 commandComplete= false;

9.2. Implementação Nó Gateway 27 smart-house Documentation, Release 0.0.2

117 inputPos=0;

118 }

119 }

120

121 122 /* 123 SerialEvent ocorre sempre que for acionado o pino de

124 recebimento(RX). Esta rotina é executada sempre que a

125 função loop() for executada, portanto a resposta pode

126 sofrer atraso. 127 */ 128 void serialEvent() {

129 while (Serial.available()) {

130 // Pega o novo byte:

131 char inChar=( char)Serial.read();

132 // se o caractere de entrada é uma nova linha, gere uma flag (sinalizador).

133 // tratamento no loop principal

134 if (inputPos

135 if (inChar== '\n'){

136 inputString[inputPos]=0;

137 commandComplete= true;

138 } else {

139 // adicionando uma string de entrada (inputString):

140 inputString[inputPos]= inChar;

141 inputPos++;

142 }

143 } else {

144 // Mensagens antigas são deletadas.

145 inputPos=0;

146 }

147 }

148 }

149

150

151

9.3 Implementação Nó Sensor

A implementação de nós sensores consiste básicamente na conexão de arduino com o rádio nRF24l01+ e a ligação do sensor desejado. A Figura 1 ilustra a ligação do arduino com o nRF24l01 a partir desse ligação deve-se adaptar para adicionar o sensor. Nos subtópicos temos a implementação de alguns sensores.

9.3.1 Sensor de Temperatura e Umidade - DTH11

9.3.2 Sensor de Luminosidade - LDR

9.4 Implementação Nó Atuador

Os nós atuadores são responsáveis pela interação com o ambiente, são esses nós que realizam ações sobre os meios externos. Para implementação de um nó atuador devemos primeiro conectar o rádio no arduino, como ilustra a Figura 1 e depois devemos adicionar o atuador. Nos subtópicos temos o exemplo da implementação de alguns atuadores.

28 Chapter 9. Implementação da Estrutura IoT smart-house Documentation, Release 0.0.2

9.4.1 Servo Motor

9.5 Implementação Nó Repetidor

Quando a distancia entre dois nós é maior que a distancia de alcance do rádio é necessário a implemen- tação de um nó repetidor, esse nó utiliza apenas um arduino e um rádio, a comunicação do arduino com o rádio é feita como na Figura 1. Abaixo segue o código utilizado para o nó repetidor.

1 /** 2 * The MySensors Arduino library handles the wireless radio link and protocol 3 * between your home built sensors/actuators and HA controller of choice. 4 * The sensors forms a self healing radio network with optional repeaters. Each 5 * repeater and gateway builds a routing tables in EEPROM which keeps track of the 6 * network topology allowing messages to be routed to nodes. 7 * 8 * Created by Henrik Ekblad 9 * Copyright (C) 2013-2015 Sensnology AB 10 * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors 11 * 12 * Documentation: http://www.mysensors.org 13 * Support Forum: http://forum.mysensors.org 14 * 15 * This program is free software; you can redistribute it and/or 16 * modify it under the terms of the GNU General Public License 17 * version 2 as published by the Free Software Foundation. 18 * 19 ******************************* 20 * 21 * REVISION HISTORY 22 * Version 1.0 - Henrik Ekblad 23 * 24 * DESCRIPTION 25 * Example sketch showing how to create a node thay repeates messages 26 * from nodes far from gateway back to gateway. 27 * It is important that nodes that has enabled repeater mode calls 28 * process() frequently. Repeaters should never sleep. 29 */ 30

31 // Enable debug prints to serial monitor

32 #define MY_DEBUG

33

34 // Enable and select radio type attached

35 #define MY_RADIO_NRF24

36 //#define MY_RADIO_RFM69

37

38 // Enabled repeater feature for this node

39 #define MY_REPEATER_FEATURE

40

41 #include

42 #include

43

44 void setup() {

45

46 }

47

48 void presentation()

49 {

9.5. Implementação Nó Repetidor 29 smart-house Documentation, Release 0.0.2

50 //Send the sensor node sketch version information to the gateway

51 sendSketchInfo("Repeater Node","1.0");

52 }

53

54 void loop()

55 {

56 }

57

9.6 Implementação Nó Controlador

O nó controlador é responsável pela interface entre a rede contruida e a Internet, existem várias opções de controladores disponíveis, neste material utilizamos o MyController.org ou o Pimatic. Ambos podem ser utilizados em um computador pessoal ou até mesmo na raspberry ou na beaglebone.

9.6.1 Pimatic

Pimatic - http://www.mysensors.org/controller/pimatic - é um framework de automação residencial que é executado no Node.js. Ele fornece uma plataforma extensível comum para controle de casa e tarefas de automação A configuração do Pimatic é realizada por meio de somente um arquivo, denominado config.json. Esse arquivo está no formato JSON e é dividido em quatro seções: Configurações (settings), Plugins, Disposi- tivos (devices) e Regras (Rules). A seguir, exemplos das quatro seções são apresentados.

9.6.2 Mycontroller.org

Detalhes para instalação e implementação estão disponíveis em http://www.mycontroller.org/#/home. Uma lista de controladores com suporte para a biblioteca mysensors esta disponível em https://www.mysensors.org/controller/. Conhecida a implementação da estrutura básica IoT podemos facilmente adaptar essa estrutura para o contexto de casas inteligentes. Podemos utilizando a plataforma Waffle.io descrever os requisitos desejaveis em uma casa inteligente no formato de estórias e assim realizarmos a construção do sistema. O próximo tópico apresenta alguns exemplos para auxiliar na implementação de requisitos desejaveis em uma casa inteligente.

30 Chapter 9. Implementação da Estrutura IoT CHAPTER 10

Estrutura da Casa Inteligente

O contexto deste projeto, pode ser muitas vezes considerado amplo, pois o mesmo gera aplicações em praticamente qualquer espaço e necessidade apresentada em uma casa. Para que fosse possível obter resultados, foi necessário focar em alguns objetivos mais específicos e, a partir destes, criar soluções com a utilização de arduíno e outros tipos de componentes. • Planta da casa • Planta da casa com sensores • estorias

31