Open ssbb33 opened 1 year ago
tentei mas nao funciona da erro ao compilar
@robertonolimit Your comment doesn't contain enough information to help you. Please show your code and the detailed compiler error message
/* This is a demo of an elegant way to run as many relays you want to
* please check the notes in configuration section below!
*
* If you encounter any issues:
* - check the readme.md at https://github.com/sinricpro/esp8266-esp32-sdk/blob/master/README.md
* - ensure all dependent libraries are installed
* - see https://github.com/sinricpro/esp8266-esp32-sdk/blob/master/README.md#arduinoide
* - see https://github.com/sinricpro/esp8266-esp32-sdk/blob/master/README.md#dependencies
* - open serial monitor and check whats happening
* - check full user documentation at https://sinricpro.github.io/esp8266-esp32-sdk
* - visit https://github.com/sinricpro/esp8266-esp32-sdk/issues and check for existing issues or open a new one
*/
// Uncomment the following line to enable serial debug output
//#define ENABLE_DEBUG
#ifdef ENABLE_DEBUG
#define DEBUG_ESP_PORT Serial
#define NODEBUG_WEBSOCKETS
#define NDEBUG
#endif
#include <Arduino.h>
#ifdef ESP8266
#include <ESP8266WiFi.h>
#endif
#ifdef ESP32
#include <WiFi.h>
#endif
#include <SinricPro.h>
#include <SinricProSwitch.h>
struct RelayInfo {
String deviceId;
String name;
int pin;
};
std::vector<RelayInfo> relays = {
{"64174cbd1bb4e19c11bafa6c", "LUZ MIGUEL", 0},};
/* ^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^ ^^^
* | | |
* | | +---> digital PIN or GPIO number (see Note below!)
* | +----------> Name that will be printed to serial monitor
* +--------------------------------> deviceId
*
* In the vector above, you can add as many relays you want to have
* This is only limited to:
* - the number of SinricPro devices you have available
* - the number of pins / GPIOs your board have
*
* Note: Some GPIO's are set to specific level when the board boots up
* This might result in strange behavior if there are relays connected to those pins
* Check your board documentation!
*/
#define WIFI_SSID "+++++++++++++++"
#define WIFI_PASS "+++++++++++++++"
#define APP_KEY "+++++++++++++++" // Should look like "de0bxxxx-1x3x-4x3x-ax2x-5dabxxxxxxxx"
#define APP_SECRET "+++++++++++++++" // Should look like "5f36xxxx-x3x7-4x3x-xexe-e86724a9xxxx-4c4axxxx-3x3x-x5xe-x9x3-333d65xxxxxx"
#define BAUD_RATE 9600 // Change baudrate to your need
bool onPowerState(const String &deviceId, bool &state) {
for (auto &relay : relays) { // for each relay configuration
if (deviceId == relay.deviceId) { // check if deviceId matches
Serial.printf("Device %s turned %s\r\n", relay.name.c_str(), state ? "on" : "off"); // print relay name and state to serial
digitalWrite(relay.pin, state); // set state to digital pin / gpio
return true; // return with success true
}
}
return false; // if no relay configuration was found, return false
}
void setupRelayPins() {
for (auto &relay : relays) { // for each relay configuration
pinMode(relay.pin, OUTPUT); // set pinMode to OUTPUT
}
}
void setupWiFi() {
Serial.printf("\r\n[Wifi]: Connecting");
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
Serial.printf(".");
delay(250);
}
Serial.printf("connected!\r\n[WiFi]: IP-Address is %s\r\n", WiFi.localIP().toString().c_str());
}
void setupSinricPro() {
for (auto &relay : relays) { // for each relay configuration
SinricProSwitch &mySwitch = SinricPro[relay.deviceId]; // create a new device with deviceId from relay configuration
mySwitch.onPowerState(onPowerState); // attach onPowerState callback to the new device
}
SinricPro.onConnected([]() { Serial.printf("Connected to SinricPro\r\n"); });
SinricPro.onDisconnected([]() { Serial.printf("Disconnected from SinricPro\r\n"); });
SinricPro.begin(APP_KEY, APP_SECRET);
}
void setup() {
Serial.begin(BAUD_RATE);
setupRelayPins();
setupWiFi();
setupSinricPro();
}
void loop() {
SinricPro.handle();
}
Edit by sivar2311: Encapsulated the code in code-blocks to make code readable Please use code-blocks next time
Eu uso com aquele modulo que ja vem com o relé , ja tentei de tudo mas ele liga com o relé ligado.
@robertonolimitSeu comentário não contém informações suficientes para ajudá-lo. Por favor, mostre seu código e a mensagem de erro detalhada do compilador
/* Esta é uma demonstração de uma maneira elegante de executar quantos relés você quiser
verifique as notas na seção de configuração abaixo!
Se você encontrar algum problema:
verifique o readme.md em https://github.com/sinricpro/esp8266-esp32-sdk/blob/master/README.md
garantir que todas as bibliotecas dependentes estejam instaladas
consulte https://github.com/sinricpro/esp8266-esp32-sdk/blob/master/README.md#arduinoide
consulte https://github.com/sinricpro/esp8266-esp32-sdk/blob/master/README.md#dependencies
abra o monitor serial e verifique o que está acontecendo
verifique a documentação completa do usuário em https://sinricpro.github.io/esp8266-esp32-sdk
visite https://github.com/sinricpro/esp8266-esp32-sdk/issues e verifique os problemas existentes ou abra um novo
*/
// Descomente a seguinte linha para ativar a saída de depuração serial
//#define ENABLE_DEBUG
#ifdef ENABLE_DEBUG
#define DEBUG_ESP_PORT Serial
#define NODEBUG_WEBSOCKETS
#define NDEBUG
#endif
#include <Arduino.h>
#ifdef ESP8266
#include <ESP8266WiFi.h>
#endif
#ifdef ESP32
#include <WiFi.h>
#endif
#include <SinricPro.h>
#include <SinricProSwitch.h>
struct RelayInfo {
String deviceId;
Nome da cadeia;
pino int;
};
std::vector relés = {
{"64174cbd1bb4e19c11bafa6c", "LUZ MIGUEL", 0},};
/* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^
| | |
| | +---> digital PIN or GPIO number (see Note below!)
| +----------> Name that will be printed to serial monitor
+--------------------------------> deviceId
No vetor acima, você pode adicionar quantos relés quiser ter
Isso é limitado apenas a:
o número de dispositivos SinricPro que você tem disponível
o número de pinos / GPIOs que sua placa possui
Nota: Alguns GPIOs são definidos para um nível específico quando a placa inicializa
This might result in strange behavior if there are relays connected to those pins
Check your board documentation!
*/
#define WIFI_SSID "+++++++++++++++"
#define WIFI_PASS "++++++++++++++++"
#define APP_KEY "++++++ +++++++++" // Deve se parecer com "de0bxxxx-1x3x-4x3x-ax2x-5dabxxxxxxxx"
#define APP_SECRET "++++++++++++++++" // Deve se parecer como "5f36xxxx-x3x7-4x3x-xexe-e86724a9xxxx-4c4axxxx-3x3x-x5xe-x9x3-333d65xxxxxx"
#define BAUD_RATE 9600 // Altere baudrate conforme sua necessidade
bool onPowerState(const String &deviceId, bool &state) {
for (auto &relay : relays) { // para cada configuração de relé
if (deviceId == relay.deviceId) { // verifique se deviceId corresponde a
Serial.printf("Dispositivo %s ativado %s\r\n", relay.name.c_str(), estado ? "on" : "off"); // imprime o nome e o estado do relé para serial
digitalWrite(relay.pin, state); // define o estado para pino digital / gpio
return true; // retorna com sucesso true
}
}
return false; // se nenhuma configuração de relé foi encontrada,
}
void setupRelayPins() {
for (auto &relay : relays) { // para cada configuração de relé
pinMode(relay.pin, OUTPUT); // define pinMode como OUTPUT
}
}
void setupWiFi() {
Serial.printf("\r\n[Wifi]: Conectando");
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
Serial.printf(".");
atraso(250);
}
Serial.printf("conectado!\r\n[WiFi]: Endereço IP é %s\r\n", WiFi.localIP().toString().c_str());
}
void setupSinricPro() {
for (auto &relay : relays) { // para cada configuração de relé
SinricProSwitch &mySwitch = SinricPro[relay.deviceId]; // cria um novo dispositivo com deviceId a partir da configuração do relé
mySwitch.onPowerState(onPowerState); // anexar callback onPowerState ao novo dispositivo
}
SinricPro.onConnected({ Serial.printf("Conectado ao SinricPro\r\n"); });
SinricPro.onDisconnected({ Serial.printf("Desconectado do SinricPro\r\n"); });
SinricPro.begin(APP_KEY, APP_SECRET);
}
void setup() {
Serial.begin(BAUD_RATE);
setupRelayPins();
configuraçãoWiFi();
setupSinricPro();
}
void loop() {
SinricPro.handle();
}
Edit by sivar2311: Encapsulated the code in code-blocks to make code readable Please use code-blocks next time
Eu uso com aquele modulo que ja vem com o relé , ja tentei de tudo mas ele liga com o relé ligado.
Sorry, but my translator does not give a meaningful result. Please use the English language, otherwise I can't understand you.
You have posted the code twice, but the compiler error message is still missing.
What I notice about the code: You use the code for multiple devices, but you only use one device. The devices are initialized using the vector "relays". The vector is not terminated correctly (there is an incorrect comma):
Wrong:
std::vector<RelayInfo> relays = {
{"64174cbd1bb4e19c11bafa6c", "LUZ MIGUEL", 0},};
Correct:
std::vector<RelayInfo> relays = {
{"64174cbd1bb4e19c11bafa6c", "LUZ MIGUEL", 0}
};
o cidigo funciona, mas quando ligo o esp e rele inicia ligado só isto.
De: sivar2311 @.> Enviado: sábado, 1 de abril de 2023 17:54 Para: sinricpro/feature-requests @.> Cc: Roberto Neves de Carvalho @.>; Mention @.> Assunto: Re: [sinricpro/feature-requests] como puedo invertir el estado de salida para un rele que apago, y enciende y viseverza (Issue #8)
You have posted the code twice, but the compiler error message is still missing.
What I notice about the code: You use the code for multiple devices, but you only use one device. The devices are initialized using the vector "relays". The vector is not terminated correctly (there is an incorrect comma):
Wrong:
std::vector
Correct:
std::vector
— Reply to this email directly, view it on GitHubhttps://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.com%2Fsinricpro%2Ffeature-requests%2Fissues%2F8%23issuecomment-1493057679&data=05%7C01%7C%7C5f8a15357f674aa70f3e08db32da3367%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638159684969982143%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=DninCgdP2JJCc5iDgYg4E9h5jS%2BnSPfNw7jUJucdAC8%3D&reserved=0, or unsubscribehttps://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.com%2Fnotifications%2Funsubscribe-auth%2FA6FD2OG6BPYGTOCRGAWPO3DW7BTW5ANCNFSM6AAAAAAQCGV4LA&data=05%7C01%7C%7C5f8a15357f674aa70f3e08db32da3367%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638159684969982143%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=pfrf5taRyOV7%2BdB0W6KSBXLAziuf88ZDsNq%2B9yUyb14%3D&reserved=0. You are receiving this because you were mentioned.Message ID: @.***>
o cidigo funciona, mas quando ligo o esp e rele inicia ligado só isto.
Translated to:
The code works, but when I turn esp on and the relay starts, that's it.
This sounds like a wiring problem to me (normally closed vs. normally open) Please check this link
eu sou tecnico em eletronica ele inia em normalmente fechado esta é a questão.
De: sivar2311 @.> Enviado: sábado, 1 de abril de 2023 18:19 Para: sinricpro/feature-requests @.> Cc: Roberto Neves de Carvalho @.>; Mention @.> Assunto: Re: [sinricpro/feature-requests] como puedo invertir el estado de salida para un rele que apago, y enciende y viseverza (Issue #8)
o cidigo funciona, mas quando ligo o esp e rele inicia ligado só isto.
Translated to:
The code works, but when I turn esp on and the relay starts, that's it.
This sounds like a wiring problem to me (normally closed vs. normally open) Please check this linkhttps://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fwww.swe-check.com.au%2Feditorials%2Funderstanding_relays.php%23relay-pins&data=05%7C01%7C%7C74badda99bc84ffcd22a08db32dd97b6%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638159699537656498%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=TGFkIij%2BDIMzWfBt7EDSu6X9vNuJXYwly67e1aZxo9k%3D&reserved=0
— Reply to this email directly, view it on GitHubhttps://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.com%2Fsinricpro%2Ffeature-requests%2Fissues%2F8%23issuecomment-1493066357&data=05%7C01%7C%7C74badda99bc84ffcd22a08db32dd97b6%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638159699537656498%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=OKhFzGEF5ahbb6vxFHHsXTe32yeTf4ix4ynJ1NCKFDg%3D&reserved=0, or unsubscribehttps://na01.safelinks.protection.outlook.com/?url=https%3A%2F%2Fgithub.com%2Fnotifications%2Funsubscribe-auth%2FA6FD2OEHIX6QZT6DIOGEPQ3W7BWR7ANCNFSM6AAAAAAQCGV4LA&data=05%7C01%7C%7C74badda99bc84ffcd22a08db32dd97b6%7C84df9e7fe9f640afb435aaaaaaaaaaaa%7C1%7C0%7C638159699537656498%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=jY0qyFbZekRM1SB7iYiFKfOKl%2FkAa2s4%2BpLt0Kjitaw%3D&reserved=0. You are receiving this because you were mentioned.Message ID: @.***>
?
Caro amigo, acho que eu nai fui claro em minhas perguntas mas tenho certeza que vc pode me ajudar, o codigo que eu postei esta funcionado , mas o problema é que quando eu coloco energia no circuito o rele aciona o nf e nao o na, com isto exemplo quando acaba a energia e volta a lampada fica ligada, o circuito que eu estou usando é aquele que vem pronto com um rele e um esp 01.
para dixar claro que o problrma nao e no circuito eu testei em outra biblioteca eo mesmo funciona normalmente.
I would be very happy to help you.
Unfortunately, I do not speak Portuguese and my translator does not provide a meaningful translation. Please write in English language.
Dear friend, I think I wasn't clear in my questions but I'm sure you can help me, the code I posted is working, but the problem is that when I put power in the circuit the relay activates the nf and not the na, with this example, when the power goes out and the lamp comes back on, the circuit I am using is the one that comes ready with a relay and a esp 01.
/* Esta é uma demonstração de uma maneira elegante de executar quantos relés você quiser
verifique as notas na seção de configuração abaixo! Se você encontrar algum problema: verifique o readme.md em https://github.com/sinricpro/esp8266-esp32-sdk/blob/master/README.md garantir que todas as bibliotecas dependentes estejam instaladas consulte https://github.com/sinricpro/esp8266-esp32-sdk/blob/master/README.md#arduinoide consulte https://github.com/sinricpro/esp8266-esp32-sdk/blob/master/README.md#dependencies abra o monitor serial e verifique o que está acontecendo verifique a documentação completa do usuário em https://sinricpro.github.io/esp8266-esp32-sdk visite https://github.com/sinricpro/esp8266-esp32-sdk/issues e verifique os problemas existentes ou abra um novo */ // Descomente a seguinte linha para ativar a saída de depuração serial //#define ENABLE_DEBUG
struct RelayInfo { String deviceId; Nome da cadeia; pino int; };
std::vector relés = { {"64174cbd1bb4e19c11bafa6c", "LUZ MIGUEL", 0},};
/* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^
| | |
| | +---> digital PIN or GPIO number (see Note below!)
| +----------> Name that will be printed to serial monitor
+--------------------------------> deviceId
No vetor acima, você pode adicionar quantos relés quiser ter Isso é limitado apenas a: o número de dispositivos SinricPro que você tem disponível o número de pinos / GPIOs que sua placa possui Nota: Alguns GPIOs são definidos para um nível específico quando a placa inicializa This might result in strange behavior if there are relays connected to those pins Check your board documentation! */
bool onPowerState(const String &deviceId, bool &state) { for (auto &relay : relays) { // para cada configuração de relé if (deviceId == relay.deviceId) { // verifique se deviceId corresponde a Serial.printf("Dispositivo %s ativado %s\r\n", relay.name.c_str(), estado ? "on" : "off"); // imprime o nome e o estado do relé para serial digitalWrite(relay.pin, state); // define o estado para pino digital / gpio return true; // retorna com sucesso true } } return false; // se nenhuma configuração de relé foi encontrada, }
void setupRelayPins() { for (auto &relay : relays) { // para cada configuração de relé pinMode(relay.pin, OUTPUT); // define pinMode como OUTPUT } }
void setupWiFi() { Serial.printf("\r\n[Wifi]: Conectando"); WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) { Serial.printf("."); atraso(250); } Serial.printf("conectado!\r\n[WiFi]: Endereço IP é %s\r\n", WiFi.localIP().toString().c_str()); }
void setupSinricPro() { for (auto &relay : relays) { // para cada configuração de relé SinricProSwitch &mySwitch = SinricPro[relay.deviceId]; // cria um novo dispositivo com deviceId a partir da configuração do relé mySwitch.onPowerState(onPowerState); // anexar callback onPowerState ao novo dispositivo }
SinricPro.onConnected({ Serial.printf("Conectado ao SinricPro\r\n"); }); SinricPro.onDisconnected({ Serial.printf("Desconectado do SinricPro\r\n"); });
SinricPro.begin(APP_KEY, APP_SECRET); }
void setup() { Serial.begin(BAUD_RATE); setupRelayPins(); configuraçãoWiFi(); setupSinricPro(); }
void loop() { SinricPro.handle(); }
Dear friend, I think I was not clear in my doubts but I'm sure you can help me, the code I posted is working, but the problem is that when I put power in the circuit the relay activates the nf and not the na, with this example, when the power goes out and the lamp comes back on, the circuit I'm using is the one that comes ready with a relay and an esp 01.
na-normally open nf - normally closed
Dear friend, I think I was not clear in my doubts but I'm sure you can help me, the code I posted is working, but the problem is that when I put power in the circuit the relay activates the nf and not the na, with this example, when the power goes out and the lamp comes back on, the circuit I'm using is the one that comes ready with a relay and an esp 01.
na-normally open nf - normally closed
/* Esta é uma demonstração de uma maneira elegante de executar quantos relés você quiser
verifique as notas na seção de configuração abaixo! Se você encontrar algum problema: verifique o readme.md em https://github.com/sinricpro/esp8266-esp32-sdk/blob/master/README.md garantir que todas as bibliotecas dependentes estejam instaladas consulte https://github.com/sinricpro/esp8266-esp32-sdk/blob/master/README.md#arduinoide consulte https://github.com/sinricpro/esp8266-esp32-sdk/blob/master/README.md#dependencies abra o monitor serial e verifique o que está acontecendo verifique a documentação completa do usuário em https://sinricpro.github.io/esp8266-esp32-sdk visite https://github.com/sinricpro/esp8266-esp32-sdk/issues e verifique os problemas existentes ou abra um novo */ // Descomente a seguinte linha para ativar a saída de depuração serial //#define ENABLE_DEBUG
struct RelayInfo { String deviceId; Nome da cadeia; pino int; };
std::vector relés = { {"64174cbd1bb4e19c11bafa6c", "LUZ MIGUEL", 0},};
/* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^
| | |
| | +---> digital PIN or GPIO number (see Note below!)
| +----------> Name that will be printed to serial monitor
+--------------------------------> deviceId
No vetor acima, você pode adicionar quantos relés quiser ter Isso é limitado apenas a: o número de dispositivos SinricPro que você tem disponível o número de pinos / GPIOs que sua placa possui Nota: Alguns GPIOs são definidos para um nível específico quando a placa inicializa This might result in strange behavior if there are relays connected to those pins Check your board documentation! */
bool onPowerState(const String &deviceId, bool &state) { for (auto &relay : relays) { // para cada configuração de relé if (deviceId == relay.deviceId) { // verifique se deviceId corresponde a Serial.printf("Dispositivo %s ativado %s\r\n", relay.name.c_str(), estado ? "on" : "off"); // imprime o nome e o estado do relé para serial digitalWrite(relay.pin, state); // define o estado para pino digital / gpio return true; // retorna com sucesso true } } return false; // se nenhuma configuração de relé foi encontrada, }
void setupRelayPins() { for (auto &relay : relays) { // para cada configuração de relé pinMode(relay.pin, OUTPUT); // define pinMode como OUTPUT } }
void setupWiFi() { Serial.printf("\r\n[Wifi]: Conectando"); WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) { Serial.printf("."); atraso(250); } Serial.printf("conectado!\r\n[WiFi]: Endereço IP é %s\r\n", WiFi.localIP().toString().c_str()); }
void setupSinricPro() { for (auto &relay : relays) { // para cada configuração de relé SinricProSwitch &mySwitch = SinricPro[relay.deviceId]; // cria um novo dispositivo com deviceId a partir da configuração do relé mySwitch.onPowerState(onPowerState); // anexar callback onPowerState ao novo dispositivo }
SinricPro.onConnected({ Serial.printf("Conectado ao SinricPro\r\n"); }); SinricPro.onDisconnected({ Serial.printf("Desconectado do SinricPro\r\n"); });
SinricPro.begin(APP_KEY, APP_SECRET); }
void setup() { Serial.begin(BAUD_RATE); setupRelayPins(); configuraçãoWiFi(); setupSinricPro(); }
void loop() { SinricPro.handle(); }
De: sivar2311 notifications@github.com Enviado: quarta-feira, 12 de abril de 2023 15:57 Para: sinricpro/feature-requests feature-requests@noreply.github.com Cc: Roberto Neves de Carvalho roberto.nolimit@hotmail.com; Mention mention@noreply.github.com Assunto: Re: [sinricpro/feature-requests] como puedo invertir el estado de salida para un rele que apago, y enciende y viseverza (Issue #8)
I would be very happy to help you.
Unfortunately, I do not speak Portuguese and my translator does not provide a meaningful translation. Please write in English language.
What do you mean by "nf" and "na" ? Which circuit and which other library are you referring to?
So you want to invert the output, right?
If it is so, you have to use in the onPowerState
Callback:
digitalWrite(relay.pin, !state);
Note the !
to invert the output.
And maybe you have to add the following to the setupRelayPins
function
digitalWrite(relay.pin, LOW);
to invert the state right at the beginning (after booting)
sem palavras muito obrigado
You can use
!state