/**
Autor: Fernando Simplicio
Acesso ao serviços do IFTTT;
*/
/*
* Lib C;
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/*
* FreeRtos;
*/
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"
/*
* Lib Arduino;
*/
#include <Arduino.h>
#include <WiFi.h>
#include <WiFiMulti.h>
#include <HTTPClient.h>
/*
* WiFi;
*/
#define WIFISSID "Wokwi-GUEST"
#define PASSWORD ""
/*
* ifttt.com;
*/
#define IFTTT_NAME_SERVICE "esp32_email"
#define IFTTT_TOKEN "cGRPOPTp1QUUW3ToPOOfLr"
/*
* Pin;
*/
#define BUTTON 4
#define LED_BUILTIN 2
/**
* Variáveis Globais
*/
WiFiMulti wifiMulti;
/**
* Declara a variável xSemaphore
* Exemplo:
if( xSemaphoreTake( xSemaphore, ( TickType_t ) 10 ) == pdTRUE ) {
...
xSemaphoreGive( xSemaphore );
}
*/
static SemaphoreHandle_t xSemaphore = NULL;
/**
* Funções
*/
static void wifi_init( void )
{
Serial.begin(115200);
for(uint8_t t = 4; t > 0; t--)
{
Serial.printf("[SETUP] WAIT %d...\n", t);
Serial.flush();
delay(500);
}
wifiMulti.addAP( WIFISSID, PASSWORD );
for(;;){
if(wifiMulti.run() != WL_CONNECTED) {
Serial.println("WiFi not connected!");
delay(1000);
} else break;
}
}
static int send_request(void)
{
char buffer[50] = {0,};
static int count = 0;
/**
* Verifica se o ESP32 está conectado a rede WiFi;
*/
if ((wifiMulti.run() == WL_CONNECTED))
{
Serial.println("[HTTP] begin...");
HTTPClient http;
http.begin("http://maker.ifttt.com/trigger/" IFTTT_NAME_SERVICE "/with/key/" IFTTT_TOKEN);
http.addHeader("HOST", "maker.ifttt.com");
http.addHeader("Content-type", "application/json");
http.addHeader("Connection", "close");
snprintf(buffer, sizeof(buffer)-1, "{\"value1\": \"%d\"}", count);
int httpCode = http.POST(buffer);
/**
* Verifica se houve erro ou não durante o POST;
*/
if (httpCode > 0)
{
Serial.print("[HTTP] Request Code=");
Serial.println(httpCode);
/**
* Caso receba o código 200 é porque o POST foi realizado com sucesso.
*/
if (httpCode == HTTP_CODE_OK)
{
count++;
/**
* Esta função " http.getString()" só pode ser utilizada caso a mensagem recebida
* tenha poucos bytes, pois ela faz o uso da função "reserve()" do Arduino, que por
* ventura reserva bytes via Malloc.
*/
String payload = http.getString();
/**
* Esta é outra função complicada do Arduino, pois para converter uma Objeto String
* para uma "string da linguagem C" é necessário alocar dinamicamente todo o vetor
* novamente. Portanto, payload tem que possuir poucos bytes.
*/
Serial.println(payload.c_str());
http.end();
return 0;
}
} else {
/**
* Imprime os possíveis códigos de erros do http;
*/
Serial.println("[HTTP] POST... failed, error");
}
/**
* Encerra o socket;
*/
http.end();
}
return -1; //error
}
static void vTask_http( void *pvParameters )
{
int count = 0;
int aux = 0;
Serial.println( "vTask_http Init...\n" );
pinMode(BUTTON, INPUT_PULLUP);
pinMode(LED_BUILTIN, OUTPUT);
for (;;)
{
//Botão pressionado?
if (digitalRead(BUTTON) == 0 && aux == 0)
{
vTaskDelay(80/portTICK_PERIOD_MS);
//Botão continua pressionado?
if (digitalRead(BUTTON) == 0 && aux == 0)
{
if(send_request() == 0)
{
Serial.print("OK");
}
aux = 1;
}
}
//botão solto? Porém já foi pressionado?
if (digitalRead(BUTTON) == 1 && aux == 1)
{
vTaskDelay(80/portTICK_PERIOD_MS);
//botão foi realmente solto?
if (digitalRead(BUTTON) == 1 && aux == 1)
{
aux = 0;
vTaskDelay(20/portTICK_PERIOD_MS);
}
}
/**
* Realiza uma requisição POST a cada 10segundos.
*/
vTaskDelay( 100/ portTICK_PERIOD_MS );
}
}
void setup (void)
{
/**
* Cria uma variável do tipo Mutex;
*/
xSemaphore = xSemaphoreCreateMutex();
/**
* No FreeRTOS 9 e 10 os Semáforos iniciam em zero, portanto após sua alocação
* convém, inicialmente, libera-lo.
*/
xSemaphoreGive( xSemaphore );
/**
* Inicializa WiFi;
*/
wifi_init();
/**
* vTask_http;
*/
xTaskCreate(vTask_http, "vTask_http", 1024*8, NULL, 2, NULL);
}
/**
* Task loop;
*/
void loop (void)
{
vTaskDelay( 1000 / portTICK_PERIOD_MS );
}