sinricpro / esp8266-esp32-sdk

Library for https://sinric.pro - simple way to connect your device to Alexa, Google Home, SmartThings and cloud
https://sinric.pro
228 stars 121 forks source link

My manual switch is nor working without internet can you find the error..here is my code #238

Closed Soorajsharma123 closed 2 years ago

Soorajsharma123 commented 2 years ago
// 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>
#include "SinricPro.h"
#include "SinricProSwitch.h"
#include <IRremote.h>
#include <WiFi.h>
#include <map>

#define WIFI_SSID         "soorajsharma"    
#define WIFI_PASS         "suraj@123"
#define APP_KEY           "type here"      // Should look like "de0bxxxx-1x3x-4x3x-ax2x-5dabxxxxxxxx"
#define APP_SECRET        "type here"   // Should look like "5f36xxxx-x3x7-4x3x-xexe-e86724a9xxxx-4c4axxxx-3x3x-x5xe-x9x3-333d65xxxxxx"
#define IR_RECV_PIN         35 //D35 pin connected with IR Receiver IC

//Enter the device IDs here
#define device_ID_1   "type here"
#define device_ID_2   "type here"
#define device_ID_3   "type here"
#define device_ID_4   "SWITCH_ID_NO_4_HERE"

// define the GPIO connected with Relays and switches
#define RelayPin1 23  //D23
#define RelayPin2 22  //D22
#define RelayPin3 21  //D21
#define RelayPin4 19  //D19
#define RelayPin5 18  //D18
#define RelayPin6 5   //D5

#define SwitchPin1 13  //D13
#define SwitchPin2 12  //D12
#define SwitchPin3 14  //D14
#define SwitchPin4 27  //D27
#define SwitchPin5 33  //D33
#define SwitchPin6 32  //D32

#define wifiLed   2   //D2

// comment the following line if you use a toggle switches instead of tactile buttons
//#define TACTILE_BUTTON 1

#define BAUD_RATE   9600

#define DEBOUNCE_TIME 250
// Replace with your network credentials (STATION)
const char* ssid = "soorajsharma";
const char* password = "suraj@123";

unsigned long previousMillis = 0;
unsigned long interval = 30000;

typedef struct {      // struct for the std::map below
  int relayPIN;
  int flipSwitchPIN;
} deviceConfig_t;

// this is the main configuration
// please put in your deviceId, the PIN for Relay and PIN for flipSwitch
// this can be up to N devices...depending on how much pin's available on your device ;)
// right now we have 4 devicesIds going to 4 relays and 4 flip switches to switch the relay manually
std::map<String, deviceConfig_t> devices = {
    //{deviceId, {relayPIN,  flipSwitchPIN}}
    {device_ID_1, {  RelayPin1, SwitchPin1 }},
    {device_ID_2, {  RelayPin2, SwitchPin2 }},
    {device_ID_3, {  RelayPin3, SwitchPin3 }},
    {device_ID_4, {  RelayPin4, SwitchPin4 }}    
};

typedef struct {      // struct for the std::map below
  String deviceId;
  bool lastFlipSwitchState;
  unsigned long lastFlipSwitchChange;
} flipSwitchConfig_t;

std::map<int, flipSwitchConfig_t> flipSwitches;    // this map is used to map flipSwitch PINs to deviceId and handling debounce and last flipSwitch state checks
                                                  // it will be setup in "setupFlipSwitches" function, using informations from devices map

void setupRelays() {
  for (auto &device : devices) {           // for each device (relay, flipSwitch combination)
    int relayPIN = device.second.relayPIN; // get the relay pin
    pinMode(relayPIN, OUTPUT);             // set relay pin to OUTPUT
    digitalWrite(relayPIN, HIGH);
  }
}

void setupFlipSwitches() {
  for (auto &device : devices)  {                     // for each device (relay / flipSwitch combination)
    flipSwitchConfig_t flipSwitchConfig;              // create a new flipSwitch configuration

    flipSwitchConfig.deviceId = device.first;         // set the deviceId
    flipSwitchConfig.lastFlipSwitchChange = 0;        // set debounce time
    flipSwitchConfig.lastFlipSwitchState = true;     // set lastFlipSwitchState to false (LOW)--

    int flipSwitchPIN = device.second.flipSwitchPIN;  // get the flipSwitchPIN

    flipSwitches[flipSwitchPIN] = flipSwitchConfig;   // save the flipSwitch config to flipSwitches map
    pinMode(flipSwitchPIN, INPUT_PULLUP);                   // set the flipSwitch pin to INPUT
  }
}

bool onPowerState(String deviceId, bool &state)
{
  Serial.printf("%s: %s\r\n", deviceId.c_str(), state ? "on" : "off");
  int relayPIN = devices[deviceId].relayPIN; // get the relay pin for corresponding device
  digitalWrite(relayPIN, !state);             // set the new relay state
  return true;
}

void handleFlipSwitches() {
  unsigned long actualMillis = millis();                                          // get actual millis
  for (auto &flipSwitch : flipSwitches) {                                         // for each flipSwitch in flipSwitches map
    unsigned long lastFlipSwitchChange = flipSwitch.second.lastFlipSwitchChange;  // get the timestamp when flipSwitch was pressed last time (used to debounce / limit events)

    if (actualMillis - lastFlipSwitchChange > DEBOUNCE_TIME) {                    // if time is > debounce time...

      int flipSwitchPIN = flipSwitch.first;                                       // get the flipSwitch pin from configuration
      bool lastFlipSwitchState = flipSwitch.second.lastFlipSwitchState;           // get the lastFlipSwitchState
      bool flipSwitchState = digitalRead(flipSwitchPIN);                          // read the current flipSwitch state
      if (flipSwitchState != lastFlipSwitchState) {                               // if the flipSwitchState has changed...
#ifdef TACTILE_BUTTON
        if (flipSwitchState) {                                                    // if the tactile button is pressed
#endif      
          flipSwitch.second.lastFlipSwitchChange = actualMillis;                  // update lastFlipSwitchChange time
          String deviceId = flipSwitch.second.deviceId;                           // get the deviceId from config
          int relayPIN = devices[deviceId].relayPIN;                              // get the relayPIN from config
          bool newRelayState = !digitalRead(relayPIN);                            // set the new relay State
          digitalWrite(relayPIN, newRelayState);                                  // set the trelay to the new state

          SinricProSwitch &mySwitch = SinricPro[deviceId];                        // get Switch device from SinricPro
          mySwitch.sendPowerStateEvent(!newRelayState);                            // send the event
#ifdef TACTILE_BUTTON
        }
#endif      
        flipSwitch.second.lastFlipSwitchState = flipSwitchState;                  // update lastFlipSwitchState
      }
    }
  }
}

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

void setupSinricPro()
{
  for (auto &device : devices)
  {
    const char *deviceId = device.first.c_str();
    SinricProSwitch &mySwitch = SinricPro[deviceId];
    mySwitch.onPowerState(onPowerState);
  }

  SinricPro.begin(APP_KEY, APP_SECRET);
  SinricPro.restoreDeviceStates(true);
}
IRrecv irrecv(IR_RECV_PIN);
decode_results results;

int toggleState_1 = 1; //Define integer to remember the toggle state for relay 1
int toggleState_2 = 1; //Define integer to remember the toggle state for relay 2
int toggleState_3 = 1; //Define integer to remember the toggle state for relay 3
int toggleState_4 = 1; //Define integer to remember the toggle state for relay 4
int toggleState_5 = 1; //Define integer to remember the toggle state for relay 5
int toggleState_6 = 1; //Define integer to remember the toggle state for relay 6

void ir_remote_control(){
  if (irrecv.decode(&results)) {

      switch(results.value){
          case 0x1FE50AF:  relayOnOff(1); break;
          case 0x1FED827:  relayOnOff(2); break;
          case 0x1FEF807:  relayOnOff(3); break;
          case 0x1FE30CF:  relayOnOff(4); break;
          case 0x1FEB04F:  relayOnOff(5); break;
          case 0x1FE708F:  relayOnOff(6); break;
          case 0x1FE48B7:  all_Switch_OFF(); break;
          case 0x1FE7887:  all_Switch_ON(); break;
          default : break;        
        }  
        //Serial.println(results.value, HEX);    
        irrecv.resume();  
  }
}

void relayOnOff(int relay) {

  switch (relay) {
    case 1:
      if (toggleState_1 == 0) {
        digitalWrite(RelayPin1, LOW); // turn on relay 1
        toggleState_1 = 1;
        Serial.println("Device1 ON");
      }
      else {
        digitalWrite(RelayPin1, HIGH); // turn off relay 1
        toggleState_1 = 0;
        Serial.println("Device1 OFF");
      }
      delay(100);
      break;
    case 2:
      if (toggleState_2 == 0) {
        digitalWrite(RelayPin2, LOW); // turn on relay 2
        toggleState_2 = 1;
        Serial.println("Device2 ON");
      }
      else {
        digitalWrite(RelayPin2, HIGH); // turn off relay 2
        toggleState_2 = 0;
        Serial.println("Device2 OFF");
      }
      delay(100);
      break;
    case 3:
      if (toggleState_3 == 0) {
        digitalWrite(RelayPin3, LOW); // turn on relay 3
        toggleState_3 = 1;
        Serial.println("Device3 ON");
      } else {
        digitalWrite(RelayPin3, HIGH); // turn off relay 3
        toggleState_3 = 0;
        Serial.println("Device3 OFF");
      }
      delay(100);
      break;
    case 4:
      if (toggleState_4 == 0) {
        digitalWrite(RelayPin4, LOW); // turn on relay 4
        toggleState_4 = 1;
        Serial.println("Device4 ON");
      }
      else {
        digitalWrite(RelayPin4, HIGH); // turn off relay 4
        toggleState_4 = 0;
        Serial.println("Device4 OFF");
      }
      delay(100);
      break;
      case 5:
      if (toggleState_5 == 0) {
        digitalWrite(RelayPin5, LOW); // turn on relay 5
        toggleState_5 = 1;
        Serial.println("Device5 ON");
      }
      else {
        digitalWrite(RelayPin5, HIGH); // turn off relay 5
        toggleState_5 = 0;
        Serial.println("Device5 OFF");
      }
      delay(100);
      break;
      case 6:
      if (toggleState_6 == 0) {
        digitalWrite(RelayPin6, LOW); // turn on relay 6
        toggleState_6 = 1;
        Serial.println("Device6 ON");
      }
      else {
        digitalWrite(RelayPin6, HIGH); // turn off relay 6
        toggleState_6 = 0;
        Serial.println("Device6 OFF");
      }
      delay(100);
      break;
    default : break;
  }
}

void all_Switch_ON(){
  digitalWrite(RelayPin1, LOW); toggleState_1 = 0; delay(100);
  digitalWrite(RelayPin2, LOW); toggleState_2 = 0; delay(100);
  digitalWrite(RelayPin3, LOW); toggleState_3 = 0; delay(100);
  digitalWrite(RelayPin4, LOW); toggleState_4 = 0; delay(100);
  digitalWrite(RelayPin5, LOW); toggleState_5 = 0; delay(100);
  digitalWrite(RelayPin6, LOW); toggleState_6 = 0; delay(100);
}

void all_Switch_OFF(){
  digitalWrite(RelayPin1, HIGH); toggleState_1 = 1; delay(100);
  digitalWrite(RelayPin2, HIGH); toggleState_2 = 1; delay(100);
  digitalWrite(RelayPin3, HIGH); toggleState_3 = 1; delay(100);
  digitalWrite(RelayPin4, HIGH); toggleState_4 = 1; delay(100);
  digitalWrite(RelayPin5, HIGH); toggleState_5 = 1; delay(100);
  digitalWrite(RelayPin6, HIGH); toggleState_6 = 1; delay(100);

}

void setup()
{
  Serial.begin(BAUD_RATE);
  irrecv.enableIRIn();
  pinMode(RelayPin1, OUTPUT);
  pinMode(RelayPin2, OUTPUT);
  pinMode(RelayPin3, OUTPUT);
  pinMode(RelayPin4, OUTPUT);
  pinMode(RelayPin5, OUTPUT);
  pinMode(RelayPin6, OUTPUT);

  // Initially all realy pin will HIGH because relay active low
  digitalWrite(RelayPin1, HIGH);
  digitalWrite(RelayPin2, HIGH);
  digitalWrite(RelayPin3, HIGH);
  digitalWrite(RelayPin4, HIGH);
  digitalWrite(RelayPin5, HIGH);
  digitalWrite(RelayPin6, HIGH);

  pinMode(wifiLed, OUTPUT);
  digitalWrite(wifiLed, HIGH);

  initWiFi();
  Serial.print("RRSI: ");
  Serial.println(WiFi.RSSI());

  setupRelays();
  setupFlipSwitches();
  setupSinricPro();
}

void loop()
{
  SinricPro.handle();
  handleFlipSwitches();
  ir_remote_control();

  unsigned long currentMillis = millis();
  // if WiFi is down, try reconnecting every CHECK_WIFI_TIME seconds
  if ((WiFi.status() != WL_CONNECTED) && (currentMillis - previousMillis >=interval)) {
    Serial.print(millis());
    Serial.println("Reconnecting to WiFi...");
    WiFi.disconnect();
    WiFi.reconnect();
    previousMillis = currentMillis;
  }
}
sivar2311 commented 2 years ago

I think the sample code used does not fit very well with your project. Several adjustments are needed here.

Can you describe your project a bit more detailed?

Soorajsharma123 commented 2 years ago

I have to made a home automation using esp32 which contain manual switches and ir remote with Google home (Sinric pro) but the problem is ones I connect the esp 32 to wifi than manual switches and ir remote work it doesn't work without internet .

Here is my code

Edit: Code removed (allready posted above)

sivar2311 commented 2 years ago

Ok, here is what i can see:

Please share your original Sketch (without SinricPro) that worked before.

Soorajsharma123 commented 2 years ago

Sir here is my previous code but in this code the same problem is arises, the manual switches is not working without connecting to the wifi ones the esp32 connects then the manual switches work automatically Here is my code

// 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 #include #include "SinricPro.h"#include

"SinricProSwitch.h"

include

define WIFI_SSID "YOUR-WIFI-NAME" #define WIFI_PASS

"YOUR-WIFI-PASSWORD"#define APP_KEY "YOUR-APP-KEY" // Should look like "de0bxxxx-1x3x-4x3x-ax2x-5dabxxxxxxxx"#define APP_SECRET "YOUR-APP-SECRET" // Should look like "5f36xxxx-x3x7-4x3x-xexe-e86724a9xxxx-4c4axxxx-3x3x-x5xe-x9x3-333d65xxxxxx" //Enter the device IDs here#define device_ID_1 "SWITCH_ID_NO_1_HERE"#define device_ID_2 "SWITCH_ID_NO_2_HERE"#define device_ID_3 "SWITCH_ID_NO_3_HERE"#define device_ID_4 "SWITCH_ID_NO_4_HERE" // define the GPIO connected with Relays and switches#define RelayPin1 23 //D23#define RelayPin2 22 //D22#define RelayPin3 21 //D21#define RelayPin4 19 //D19

define SwitchPin1 13 //D13#define SwitchPin2 12 //D12#define

SwitchPin3 14 //D14#define SwitchPin4 27 //D27

define wifiLed 2 //D2

// comment the following line if you use a toggle switches instead of tactile buttons//#define TACTILE_BUTTON 1

define BAUD_RATE 9600

define DEBOUNCE_TIME 250

typedef struct { // struct for the std::map below int relayPIN; int flipSwitchPIN;} deviceConfig_t;

// this is the main configuration// please put in your deviceId, the PIN for Relay and PIN for flipSwitch// this can be up to N devices...depending on how much pin's available on your device ;)// right now we have 4 devicesIds going to 4 relays and 4 flip switches to switch the relay manually std::map<String, deviceConfig_t> devices = { //{deviceId, {relayPIN, flipSwitchPIN}} {device_ID_1, { RelayPin1, SwitchPin1 }}, {device_ID_2, { RelayPin2, SwitchPin2 }}, {device_ID_3, { RelayPin3, SwitchPin3 }}, {device_ID_4, { RelayPin4, SwitchPin4 }} }; typedef struct { // struct for the std::map below String deviceId; bool lastFlipSwitchState; unsigned long lastFlipSwitchChange;} flipSwitchConfig_t;

std::map<int, flipSwitchConfig_t> flipSwitches; // this map is used to map flipSwitch PINs to deviceId and handling debounce and last flipSwitch state checks // it will be setup in "setupFlipSwitches" function, using informations from devices map void setupRelays() { for (auto &device : devices) { // for each device (relay, flipSwitch combination) int relayPIN = device.second.relayPIN; // get the relay pin pinMode(relayPIN, OUTPUT); // set relay pin to OUTPUT digitalWrite(relayPIN, HIGH); }} void setupFlipSwitches() { for (auto &device : devices) { // for each device (relay / flipSwitch combination) flipSwitchConfig_t flipSwitchConfig; // create a new flipSwitch configuration

flipSwitchConfig.deviceId = device.first;         // set the deviceId
flipSwitchConfig.lastFlipSwitchChange = 0;        // set debounce time
flipSwitchConfig.lastFlipSwitchState = true;     // set

lastFlipSwitchState to false (LOW)--

int flipSwitchPIN = device.second.flipSwitchPIN;  // get the flipSwitchPIN

flipSwitches[flipSwitchPIN] = flipSwitchConfig;   // save the

flipSwitch config to flipSwitches map pinMode(flipSwitchPIN, INPUT_PULLUP); // set the flipSwitch pin to INPUT }} bool onPowerState(String deviceId, bool &state){ Serial.printf("%s: %s\r\n", deviceId.c_str(), state ? "on" : "off"); int relayPIN = devices[deviceId].relayPIN; // get the relay pin for corresponding device digitalWrite(relayPIN, !state); // set the new relay state return true;} void handleFlipSwitches() { unsigned long actualMillis = millis(); // get actual millis for (auto &flipSwitch : flipSwitches) { // for each flipSwitch in flipSwitches map unsigned long lastFlipSwitchChange = flipSwitch.second.lastFlipSwitchChange; // get the timestamp when flipSwitch was pressed last time (used to debounce / limit events)

if (actualMillis - lastFlipSwitchChange > DEBOUNCE_TIME) {
       // if time is > debounce time...

  int flipSwitchPIN = flipSwitch.first;
       // get the flipSwitch pin from configuration
  bool lastFlipSwitchState =

flipSwitch.second.lastFlipSwitchState; // get the lastFlipSwitchState bool flipSwitchState = digitalRead(flipSwitchPIN); // read the current flipSwitch state if (flipSwitchState != lastFlipSwitchState) { // if the flipSwitchState has changed...#ifdef TACTILE_BUTTON if (flipSwitchState) { // if the tactile button is pressed #endif flipSwitch.second.lastFlipSwitchChange = actualMillis; // update lastFlipSwitchChange time String deviceId = flipSwitch.second.deviceId; // get the deviceId from config int relayPIN = devices[deviceId].relayPIN; // get the relayPIN from config bool newRelayState = !digitalRead(relayPIN); // set the new relay State digitalWrite(relayPIN, newRelayState); // set the trelay to the new state

      SinricProSwitch &mySwitch = SinricPro[deviceId];
       // get Switch device from SinricPro
      mySwitch.sendPowerStateEvent(!newRelayState);
        // send the event#ifdef TACTILE_BUTTON
    }#endif
    flipSwitch.second.lastFlipSwitchState = flipSwitchState;
       // update lastFlipSwitchState
  }
}

}} void setupWiFi(){ Serial.printf("\r\n[Wifi]: Connecting"); WiFi.begin(WIFI_SSID, WIFI_PASS);

while (WiFi.status() != WL_CONNECTED) { Serial.printf("."); delay(250); } digitalWrite(wifiLed, HIGH); Serial.printf("connected!\r\n[WiFi]: IP-Address is %s\r\n", WiFi.localIP().toString().c_str());} void setupSinricPro(){ for (auto &device : devices) { const char *deviceId = device.first.c_str(); SinricProSwitch &mySwitch = SinricPro[deviceId]; mySwitch.onPowerState(onPowerState); }

SinricPro.begin(APP_KEY, APP_SECRET); SinricPro.restoreDeviceStates(true);} void setup(){ Serial.begin(BAUD_RATE);

pinMode(wifiLed, OUTPUT); digitalWrite(wifiLed, LOW);

setupRelays(); setupFlipSwitches(); setupWiFi(); setupSinricPro();} void loop(){ SinricPro.handle(); handleFlipSwitches();}

On Fri, Dec 31, 2021, 10:41 Boris Jäger @.***> wrote:

Ok, here is what i can see:

  • It looks like, two sketches are copied togheter.
  • There are no modifications in the onPowerState function that meets the logic of the (other) sketch
    • onPowerState does write directly to the gpio and does not respect the toggleState_X logic
  • At least 2 gpio's are dangerous to use
  • You need 6 SinricPro deviceId's but it seems only 3 are provided
    • Do you have 6 deviceId's ?

Please share your original Sketch (without SinricPro) that worked before.

— Reply to this email directly, view it on GitHub https://github.com/sinricpro/esp8266-esp32-sdk/issues/238#issuecomment-1003271496, or unsubscribe https://github.com/notifications/unsubscribe-auth/AXDDU6IWYTL5KWDJLF55MPLUTU3PJANCNFSM5K72KLDA . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.

You are receiving this because you authored the thread.Message ID: @.***>

sivar2311 commented 2 years ago

I meant your sketch without SinricPro stuff. The code you have used before trying to inttegrate SinricPro. The one that was working.

Soorajsharma123 commented 2 years ago

Can you plzz make it correct so that I can use sinric pro for my home automation also with manual switches...

On Fri, Dec 31, 2021, 11:18 Boris Jäger @.***> wrote:

I meant your sketch without SinricPro stuff. The code you have used before trying to inttegrate SinricPro. The one that was working.

— Reply to this email directly, view it on GitHub https://github.com/sinricpro/esp8266-esp32-sdk/issues/238#issuecomment-1003277223, or unsubscribe https://github.com/notifications/unsubscribe-auth/AXDDU6OMWC4NTJYGA24JQUTUTU73LANCNFSM5K72KLDA . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.

You are receiving this because you authored the thread.Message ID: @.***>

sivar2311 commented 2 years ago

I can't help you if i don't understand the problem and the code. The more information you provide, the better I can help you.

Please answer all questions:

sivar2311 commented 2 years ago

I highly recommend to use the beginner's multiswitch example as base for your project. This example meets your programming style and should be easier for you to understand.

Soorajsharma123 commented 2 years ago

1st Yes I had checked GPIOs 5 and 12 but I do not find any problem in this

2nd

I do not use any other sketch for operating appliance with Google but I had used blynk app to control the appliance and also using bluetooth . But I want to operate this with Google using Sinric pro, and also with manual switches and IR remote.

3rd

The Sinric pro provides us only 3 device's I'd so I can use the three only . For more device's I'd I have to subscribe the SINRICPRO..

The code that I had given you is working fine it works with Google home (app) and the manual switches is also works fine when I first connect the wifi to ESP32 but the manual switch is not working without connecting to the wifi first , that mean first I have to connect the wifi than the manual switches work otherwise not. Here is my code ,

// 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 #include #include "SinricPro.h"#include

"SinricProSwitch.h"

include

define WIFI_SSID "YOUR-WIFI-NAME" #define WIFI_PASS

"YOUR-WIFI-PASSWORD"#define APP_KEY "YOUR-APP-KEY" // Should look like "de0bxxxx-1x3x-4x3x-ax2x-5dabxxxxxxxx"#define APP_SECRET "YOUR-APP-SECRET" // Should look like "5f36xxxx-x3x7-4x3x-xexe-e86724a9xxxx-4c4axxxx-3x3x-x5xe-x9x3-333d65xxxxxx" //Enter the device IDs here#define device_ID_1 "SWITCH_ID_NO_1_HERE"#define device_ID_2 "SWITCH_ID_NO_2_HERE"#define device_ID_3 "SWITCH_ID_NO_3_HERE"#define device_ID_4 "SWITCH_ID_NO_4_HERE" // define the GPIO connected with Relays and switches#define RelayPin1 23 //D23#define RelayPin2 22 //D22#define RelayPin3 21 //D21#define RelayPin4 19 //D19

define SwitchPin1 13 //D13#define SwitchPin2 12 //D12#define

SwitchPin3 14 //D14#define SwitchPin4 27 //D27

define wifiLed 2 //D2

// comment the following line if you use a toggle switches instead of tactile buttons//#define TACTILE_BUTTON 1

define BAUD_RATE 9600

define DEBOUNCE_TIME 250

typedef struct { // struct for the std::map below int relayPIN; int flipSwitchPIN;} deviceConfig_t;

// this is the main configuration// please put in your deviceId, the PIN for Relay and PIN for flipSwitch// this can be up to N devices...depending on how much pin's available on your device ;)// right now we have 4 devicesIds going to 4 relays and 4 flip switches to switch the relay manually std::map<String, deviceConfig_t> devices = { //{deviceId, {relayPIN, flipSwitchPIN}} {device_ID_1, { RelayPin1, SwitchPin1 }}, {device_ID_2, { RelayPin2, SwitchPin2 }}, {device_ID_3, { RelayPin3, SwitchPin3 }}, {device_ID_4, { RelayPin4, SwitchPin4 }} }; typedef struct { // struct for the std::map below String deviceId; bool lastFlipSwitchState; unsigned long lastFlipSwitchChange;} flipSwitchConfig_t;

std::map<int, flipSwitchConfig_t> flipSwitches; // this map is used to map flipSwitch PINs to deviceId and handling debounce and last flipSwitch state checks // it will be setup in "setupFlipSwitches" function, using informations from devices map void setupRelays() { for (auto &device : devices) { // for each device (relay, flipSwitch combination) int relayPIN = device.second.relayPIN; // get the relay pin pinMode(relayPIN, OUTPUT); // set relay pin to OUTPUT digitalWrite(relayPIN, HIGH); }} void setupFlipSwitches() { for (auto &device : devices) { // for each device (relay / flipSwitch combination) flipSwitchConfig_t flipSwitchConfig; // create a new flipSwitch configuration

flipSwitchConfig.deviceId = device.first;         // set the deviceId
flipSwitchConfig.lastFlipSwitchChange = 0;        // set debounce time
flipSwitchConfig.lastFlipSwitchState = true;     // set

lastFlipSwitchState to false (LOW)--

int flipSwitchPIN = device.second.flipSwitchPIN;  // get the flipSwitchPIN

flipSwitches[flipSwitchPIN] = flipSwitchConfig;   // save the

flipSwitch config to flipSwitches map pinMode(flipSwitchPIN, INPUT_PULLUP); // set the flipSwitch pin to INPUT }} bool onPowerState(String deviceId, bool &state){ Serial.printf("%s: %s\r\n", deviceId.c_str(), state ? "on" : "off"); int relayPIN = devices[deviceId].relayPIN; // get the relay pin for corresponding device digitalWrite(relayPIN, !state); // set the new relay state return true;} void handleFlipSwitches() { unsigned long actualMillis = millis(); // get actual millis for (auto &flipSwitch : flipSwitches) { // for each flipSwitch in flipSwitches map unsigned long lastFlipSwitchChange = flipSwitch.second.lastFlipSwitchChange; // get the timestamp when flipSwitch was pressed last time (used to debounce / limit events)

if (actualMillis - lastFlipSwitchChange > DEBOUNCE_TIME) {
       // if time is > debounce time...

  int flipSwitchPIN = flipSwitch.first;
       // get the flipSwitch pin from configuration
  bool lastFlipSwitchState =

flipSwitch.second.lastFlipSwitchState; // get the lastFlipSwitchState bool flipSwitchState = digitalRead(flipSwitchPIN); // read the current flipSwitch state if (flipSwitchState != lastFlipSwitchState) { // if the flipSwitchState has changed...#ifdef TACTILE_BUTTON if (flipSwitchState) { // if the tactile button is pressed #endif flipSwitch.second.lastFlipSwitchChange = actualMillis; // update lastFlipSwitchChange time String deviceId = flipSwitch.second.deviceId; // get the deviceId from config int relayPIN = devices[deviceId].relayPIN; // get the relayPIN from config bool newRelayState = !digitalRead(relayPIN); // set the new relay State digitalWrite(relayPIN, newRelayState); // set the trelay to the new state

      SinricProSwitch &mySwitch = SinricPro[deviceId];
       // get Switch device from SinricPro
      mySwitch.sendPowerStateEvent(!newRelayState);
        // send the event#ifdef TACTILE_BUTTON
    }#endif
    flipSwitch.second.lastFlipSwitchState = flipSwitchState;
       // update lastFlipSwitchState
  }
}

}} void setupWiFi(){ Serial.printf("\r\n[Wifi]: Connecting"); WiFi.begin(WIFI_SSID, WIFI_PASS);

while (WiFi.status() != WL_CONNECTED) { Serial.printf("."); delay(250); } digitalWrite(wifiLed, HIGH); Serial.printf("connected!\r\n[WiFi]: IP-Address is %s\r\n", WiFi.localIP().toString().c_str());} void setupSinricPro(){ for (auto &device : devices) { const char *deviceId = device.first.c_str(); SinricProSwitch &mySwitch = SinricPro[deviceId]; mySwitch.onPowerState(onPowerState); }

SinricPro.begin(APP_KEY, APP_SECRET); SinricPro.restoreDeviceStates(true);} void setup(){ Serial.begin(BAUD_RATE);

pinMode(wifiLed, OUTPUT); digitalWrite(wifiLed, LOW);

setupRelays(); setupFlipSwitches(); setupWiFi(); setupSinricPro();} void loop(){ SinricPro.handle(); handleFlipSwitches();}

On Sat, Jan 1, 2022, 15:38 Boris Jäger @.***> wrote:

I can't help you if i don't understand the problem and the code. The more information you provide, the better I can help you.

Please answer all questions:

  • Did you checked the GPIOs i mentioned above (dangerous gpio 5 and 12) ?
  • Do you have a working sketch without sinric pro?
  • Do you have 6 SinricPro deviceId's?

— Reply to this email directly, view it on GitHub https://github.com/sinricpro/esp8266-esp32-sdk/issues/238#issuecomment-1003535780, or unsubscribe https://github.com/notifications/unsubscribe-auth/AXDDU6JUVYS3KO4T5LJKHDDUT3HB3ANCNFSM5K72KLDA . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.

You are receiving this because you authored the thread.Message ID: @.***>

Soorajsharma123 commented 2 years ago

Sir in this code the function of manual switch is not available so that I can operate the appliance with manually..

On Sat, Jan 1, 2022, 15:56 Boris Jäger @.***> wrote:

I highly recommend to use the beginner's multiswitch example https://github.com/sinricpro/esp8266-esp32-sdk/blob/master/examples/Switch/MultiSwitch_beginner/MultiSwitch_beginner.ino as base for your project. This example meets your programming style and should be easier for you to understand.

— Reply to this email directly, view it on GitHub https://github.com/sinricpro/esp8266-esp32-sdk/issues/238#issuecomment-1003538161, or unsubscribe https://github.com/notifications/unsubscribe-auth/AXDDU6KJIAPVG7M75TZ7UELUT3JDZANCNFSM5K72KLDA . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.

You are receiving this because you authored the thread.Message ID: @.***>

sivar2311 commented 2 years ago

The code that I had given you is working fine it works with Google home (app) and the manual switches is also works fine when I first connect the wifi to ESP32 but the manual switch is not working without connecting to the wifi first , that mean first I have to connect the wifi than the manual switches work otherwise not.

Ah, now i begin to understand.

This is because the setupWiFi() function waits until a connection is established! You have to handle the switches within this while it waits for the wifi connection. One soulution could be this:

while (WiFi.status() != WL_CONNECTED)  {
  handleFlipSwitches();
  yield();
  }
Soorajsharma123 commented 2 years ago

Sir , that mean I have to add this function in WIFI()

while (WiFi.status() != WL_CONNECTED) { handleFlipSwitches(); yield(); }

I also want to add #include IRremote.h so that I can use ir remote to control the appliance

So I have to also add this function to WIFI()

ir_remote_control();

Am I getting it right?

sivar2311 commented 2 years ago

Yes!

The while loop in setupWiFi() is blocking your sketch until a wifi connection has been established.

Everything you want to handle (like buttons, ir etc..) until a wifi connection has been established must be handled in this while loop.

Soorajsharma123 commented 2 years ago

Ok I get it thanku so much sir for your greatness and helping me .I will asking to you such type of problem when I will face the problem thanku ...

On Sat, Jan 1, 2022, 16:21 Boris Jäger @.***> wrote:

Yes!

The while loop in setupWiFi() is blocking your sketch until a wifi connection has been established.

Everything you want to handle (like buttons, ir etc..) until a wifi connection has been established must be handled in this while loop.

— Reply to this email directly, view it on GitHub https://github.com/sinricpro/esp8266-esp32-sdk/issues/238#issuecomment-1003540173, or unsubscribe https://github.com/notifications/unsubscribe-auth/AXDDU6PP3ZIVOZ5J4P2SSPLUT3MCHANCNFSM5K72KLDA . Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub.

You are receiving this because you authored the thread.Message ID: @.***>

sivar2311 commented 2 years ago

If your question is finally answered, please don't forget to close this issue. Feel free to reopen this issue if the problem still exists.

For new questions / problems, please open a new issue.

stale[bot] commented 2 years ago

This issue has gone quiet. Spooky quiet. We currently close issues after 14 days of inactivity. It’s been at least 7 days since the last update here. If we missed this issue or if you want to keep it open, please reply here. As a friendly reminder, the best way to fix this or any other problem is to provide a detailed error description including a serial log. Thanks for being a part of the SinricPro community!

stale[bot] commented 2 years ago

Hey again! It’s been 14 days since anything happened on this issue, so our friendly robot (that’s me!) is going to close it. Please keep in mind that I’m only a robot, so if I’ve closed this issue in error, I’m HUMAN_EMOTION_SORRY. Please feel free to comment on this issue or create a new one if you need anything else. As a friendly reminder, the best way to fix this or any other problem is to provide a detailed error description including a serial log. Thanks again for being a part of the SinricPro community!