Descrição de códigos para devices e coletas

  • Code Client Device
  • ESP8266 Runing program language LUA.

-- Campainha IoT - LHC - v1.1 -- ESP Inicializa pinos, Configura e Conecta no Wifi, Cria conexão TCP -- e na resposta de um "Tocou" coloca o ESP em modo DeepSleep para economizar bateria. -- Se nenhuma resposta for recebida em 15 segundos coloca o ESP em DeepSleep. led_pin = 3 status_led = gpio.LOW ip_servidor = "192.168.1.10" ip_campainha = "192.168.1.20" voltagem=3333

function desliga_circuito() print("Colocando ESP em Deep Sleep") node.dsleep(0) end

function read_voltage() -- Desconecta do wifi para poder ler a voltagem de alimentação do ESP. wifi.sta.disconnect()

voltagem = adc.readvdd33()            
print("Voltagem: "..voltagem)

-- Inicializa o Wifi e conecta no servidor
print("Inicializando WiFi")
init_wifi()

end

function pisca_led() gpio.write(led_pin, status_led)

if status_led == gpio.LOW then
    status_led = gpio.HIGH
else
    status_led = gpio.LOW
end

end

function init_pins() gpio.mode(led_pin, gpio.OUTPUT) gpio.write(led_pin, status_led) end

function init_wifi() wifi.setmode(wifi.STATION) wifi.sta.config("SSID", "password") wifi.sta.connect() wifi.sta.setip({ip=ip_campainha,netmask="255.255.255.0",gateway="192.168.1.1"})

-- Aguarda conexão com Wifi antes de enviar o request.
function try_connect()        
    if (wifi.sta.status() == 5) then
        tmr.stop(0)
        print("Conectado, mandando request")
        manda_request()
        -- Se nenhuma confirmação for recebida em 15 segundos, desliga o ESP.
        tmr.alarm(2,15000,0, desliga_circuito)
    else
        print("Conectando...")
    end
end

tmr.alarm(0,1000,1, function() try_connect() end )

end

function manda_request() tmr.alarm(1, 200, 1, pisca_led) print("Request enviado") -- Cria a conexão TCP conn=net.createConnection(net.TCP,false) -- Envia o toque da campainha e voltagem para o servidor conn:on("connection", function(conn) conn:send("GET /?bateria=" ..voltagem.. " HTTP/1.0\r\n\r\n") end)

-- Se receber "Tocou" do servidor, desliga o ESP.
conn:on("receive", function(conn, data)
    if data:find("Tocou") ~= nil then
        desliga_circuito()
    end
end)

-- Conectar no servidor
conn:connect(9999,ip_servidor)

end

print("Inicializando pinos") init_pins()

print ("Lendo voltagem") read_voltage()

  • Server Local : Runing soun local area.
  • Program Python
# !/usr/bin/python2 import time import BaseHTTPServer import os import random import string import requests from urlparse import parse_qs, urlparse HOST_NAME = '0.0.0.0' PORT_NUMBER = 9999 # A variável MP3_DIR será construida tendo como base o diretório HOME do usuário + Music/Campainha # (e.g: /home/usuario/Music/Campainha) MP3_DIR = os.path.join(os.getenv('HOME'), 'Music', 'Campainha') VALID_CHARS = set(string.ascii_letters + string.digits + '_.') CHAVE_THINGSPEAK = 'XYZ11ZYX99XYZ1XX' # Salva o arquivo de log no diretório do usuário (e.g: /home/usuário/campainha.log) ARQUIVO_LOG = os.path.join(os.getenv('HOME'), 'campainha.log') def filtra(mp3): if not mp3.endswith('.mp3'): return False for c in mp3: if not c in VALID_CHARS: return False return True def log(msg, output_file=None): if output_file is None: output_file = open(ARQUIVO_LOG, 'a') output_file.write('%s: %s\n' % (time.asctime(), msg)) output_file.flush() class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(s): s.send_header("Content-type", "text/plain") query = urlparse(s.path).query if not query: s.send_response(404) s.end_headers() s.wfile.write('Not found') return components = dict(qc.split('=') for qc in query.split('&')) if not 'bateria' in components: s.send_response(404) s.end_headers() s.wfile.write('Not found') return s.send_response(200) s.end_headers() s.wfile.write('Tocou') s.wfile.flush() log("Atualizando thingspeak") r = requests.post('https://api.thingspeak.com/update', data={'api_key': CHAVE_THINGSPEAK, 'field1': components['bateria']}) log("Thingspeak retornou: %d" % r.status_code) log("Tocando MP3") mp3s = [f for f in os.listdir(MP3_DIR) if filtra(f)] mp3 = random.choice(mp3s) os.system("mpv " + os.path.join(MP3_DIR, mp3)) if __name__ == '__main__': server_class = BaseHTTPServer.HTTPServer httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler) log("Server Starts - %s:%s" % (HOST_NAME, PORT_NUMBER)) try: httpd.serve_forever() except KeyboardInterrupt: pass httpd.server_close() log("Server Stops - %s:%s" % (HOST_NAME, PORT_NUMBER))

Export database from dashaboard about device IoT

  • Arquivo csv

In [ ]:
import numpy as np

In [2]:
import csv

In [3]:
with open('database.csv', 'rb') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in spamreader:
        print ', '.join(row)


created_at,entry_id,field1,x,amp
2017-01-06, 22:49:19, UTC, 380, 3238
2017-01-07, 14:31:19, UTC, 381, 3238
2017-01-07, 15:32:59, UTC, 382, 3234
2017-01-07, 17:33:27, UTC, 383, 3238
2017-01-07, 20:02:41, UTC, 384, 3230
2017-01-08, 16:04:56, UTC, 385, 3222
2017-01-08, 20:07:52, UTC, 386, 3211
2017-01-08, 21:49:05, UTC, 387, 3237
2017-01-08, 22:49:15, UTC, 388, 3238
2017-01-10, 20:37:57, UTC, 389, 3238
2017-01-10, 21:02:21, UTC, 390, 3238
2017-01-10, 21:08:35, UTC, 391, 3238
2017-01-10, 21:27:09, UTC, 392, 3237
2017-01-10, 21:30:44, UTC, 393, 3238
2017-01-10, 21:35:02, UTC, 394, 3236
2017-01-10, 21:51:12, UTC, 395, 3235
2017-01-11, 21:06:39, UTC, 396, 3236
2017-01-11, 21:25:03, UTC, 397, 3235
2017-01-12, 13:07:17, UTC, 398, 3231
2017-01-12, 13:07:51, UTC, 399, 3230
2017-01-12, 18:47:26, UTC, 400, 3230
2017-01-12, 18:48:13, UTC, 401, 3230
2017-01-12, 18:49:18, UTC, 402, 3230
2017-01-12, 20:56:32, UTC, 403, 3230
2017-01-14, 11:15:14, UTC, 404, 3226
2017-01-14, 11:15:42, UTC, 405, 3226
2017-01-22, 22:19:29, UTC, 406, 3206
2017-01-23, 21:13:22, UTC, 407, 3204
2017-01-23, 21:18:54, UTC, 408, 3207
2017-01-23, 21:28:57, UTC, 409, 3205
2017-01-24, 21:20:48, UTC, 410, 3204
2017-01-24, 21:32:20, UTC, 411, 3203
2017-01-24, 21:40:18, UTC, 412, 3204
2017-01-25, 18:41:05, UTC, 413, 3204
2017-01-26, 16:29:37, UTC, 414, 3197
2017-01-26, 21:59:48, UTC, 415, 3203
2017-01-27, 00:49:57, UTC, 416, 3202
2017-01-29, 18:10:08, UTC, 417, 3191
2017-01-31, 22:47:38, UTC, 418, 3192
2017-02-01, 23:25:51, UTC, 419, 3196
2017-02-01, 23:26:15, UTC, 420, 3190
2017-02-02, 21:42:21, UTC, 421, 3190
2017-02-04, 12:00:49, UTC, 422, 3189
2017-02-04, 14:04:45, UTC, 423, 3187
2017-02-04, 15:29:49, UTC, 424, 3196
2017-02-04, 15:45:48, UTC, 425, 3196

In [ ]:


In [ ]: