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
227 stars 121 forks source link

I'm stuck coding for multiple devices. (ESP8266) #378

Closed joeljana closed 1 month ago

joeljana commented 1 month ago

Help me please. I'm stuck coding for multiple devices. Im using ESP8266 Where I want to control two relays (PIN 5,4) by two push switches (PIN 12,14). Also want to add a DHT11 temperature and humidity sensor(PIN 13).

sivar2311 commented 1 month ago

Please show your code and name the exact places where you are stuck.

sivar2311 commented 1 month ago

Very hard to read unformated code :(

Please edit your post and use the code tags. Or even better: Create a repo

And please name the points where you get stuck. Right now this is just code

sivar2311 commented 1 month ago

Looks messy again. You can edit your post - no need to post the code again.

Put your code in three backticks. See quoting-code

joeljana commented 1 month ago

// ****This Is my Code for 2relay and 2 Push Switch *****

//#define ENABLE_DEBUG

#ifdef ENABLE_DEBUG
#define DEBUG_ESP_PORT Serial
#define NODEBUG_WEBSOCKETS
#define NDEBUG
#endif

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "SinricPro.h"
#include "SinricProSwitch.h"

#include

#define WIFI_SSID "JOEL"
#define WIFI_PASS "mi123456"
#define APP_KEY "01583a71-43e5-450c-a884-61cd03f0e1fb" // Should look like "de0bxxxx-1x3x-4x3x-ax2x-5dabxxxxxxxx"
#define APP_SECRET "b177b2a6-3de4-4653-81a1-02619ae7bbe2-b123c5ad-de1d-4f07-99d9-3ae23cc9f609" // Should look like "5f36xxxx-x3x7-4x3x-xexe-e86724a9xxxx-4c4axxxx-3x3x-x5xe-x9x3-333d65xxxxxx"

//Enter the device IDs here
#define device_ID_1 "663c8693202b1b3e1f5689dd"
#define device_ID_2 "663c86e76443b9bfe2b6a4a9"

// define the GPIO connected with Relays and switches
#define RelayPin1 5
#define RelayPin2 4

#define SwitchPin1 14
#define SwitchPin2 12

#define wifiLed 16 //D0

// 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 }}

};

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, LOW);
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, HIGH);

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

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

// ****This is my my code for temp/humidity Sensor **

#ifdef ENABLE_DEBUG
#define DEBUG_ESP_PORT Serial
#define NODEBUG_WEBSOCKETS
#define NDEBUG
#endif

#include <ESP8266WiFi.h>
#include "SinricPro.h"
#include "SinricProTemperaturesensor.h"
#include "DHT.h" // https://github.com/markruys/arduino-DHT

#define WIFI_SSID "JOEL"
#define WIFI_PASS "mi123456"
#define APP_KEY "01583a71-43e5-450c-a884-61cd03f0e1fb"
#define APP_SECRET "b177b2a6-3de4-4653-81a1-02619ae7bbe2-b123c5ad-de1d-4f07-99d9-3ae23cc9f609"
#define TEMP_SENSOR_ID "663c8753fb874c7486d02723"
#define BAUD_RATE 115200 // Change baudrate to your need (used for serial monitor)
#define EVENT_WAIT_TIME 65000 // send event every 60 seconds

#define DHT_PIN 13

DHT dht; // DHT sensor

bool deviceIsOn; // Temeprature sensor on/off state
float temperature; // actual temperature
float humidity; // actual humidity
float lastTemperature; // last known temperature (for compare)
float lastHumidity; // last known humidity (for compare)
unsigned long lastEvent = (-EVENT_WAIT_TIME); // last time event has been sent

/* bool onPowerState(String deviceId, bool &state)
*

Callback for setPowerState request
parameters
String deviceId (r)
contains deviceId (useful if this callback used by multiple devices)
bool &state (r/w)
contains the requested state (true:on / false:off)
must return the new state
return
true if request should be marked as handled correctly / false if not
*/
bool onPowerState(const String &deviceId, bool &state) {
Serial.printf("Temperaturesensor turned %s (via SinricPro) \r\n", state?"on":"off");
deviceIsOn = state; // turn on / off temperature sensor
return true; // request handled properly
}
/* handleTemperatatureSensor()

Checks if Temperaturesensor is turned on
Checks if time since last event > EVENT_WAIT_TIME to prevent sending too much events
Get actual temperature and humidity and check if these values are valid
Compares actual temperature and humidity to last known temperature and humidity
Send event to SinricPro Server if temperature or humidity changed
*/
void handleTemperaturesensor() {
if (deviceIsOn == false) return; // device is off...do nothing
unsigned long actualMillis = millis();
if (actualMillis - lastEvent < EVENT_WAIT_TIME) return; //only check every EVENT_WAIT_TIME milliseconds

temperature = dht.getTemperature(); // get actual temperature in °C
// temperature = dht.getTemperature() * 1.8f + 32; // get actual temperature in °F
humidity = dht.getHumidity(); // get actual humidity

if (isnan(temperature) || isnan(humidity)) { // reading failed...
Serial.printf("DHT reading failed!\r\n"); // print error message
return; // try again next time
}

if (temperature == lastTemperature || humidity == lastHumidity) return; // if no values changed do nothing...

SinricProTemperaturesensor &mySensor = SinricPro[TEMP_SENSOR_ID]; // get temperaturesensor device
bool success = mySensor.sendTemperatureEvent(temperature, humidity); // send event
if (success) { // if event was sent successfuly, print temperature and humidity to serial
Serial.printf("Temperature: %2.1f Celsius\tHumidity: %2.1f%%\r\n", temperature, humidity);
} else { // if sending event failed, print error message
Serial.printf("Something went wrong...could not send Event to server!\r\n");
}

lastTemperature = temperature; // save actual temperature for next compare
lastHumidity = humidity; // save actual humidity for next compare
lastEvent = actualMillis; // save actual time for next compare
}

// setup function for WiFi connection
void setupWiFi() {
Serial.printf("\r\n[Wifi]: Connecting");
WiFi.begin(WIFI_SSID, WIFI_PASS);

while (WiFi.status() != WL_CONNECTED) {
Serial.printf(".");
delay(250);
}
IPAddress localIP = WiFi.localIP();
Serial.printf("connected!\r\n[WiFi]: IP-Address is %d.%d.%d.%d\r\n", localIP[0], localIP[1], localIP[2], localIP[3]);
}

// setup function for SinricPro
void setupSinricPro() {
// add device to SinricPro
SinricProTemperaturesensor &mySensor = SinricPro[TEMP_SENSOR_ID];
mySensor.onPowerState(onPowerState);

// setup SinricPro
SinricPro.onConnected({ Serial.printf("Connected to SinricPro\r\n"); });
SinricPro.onDisconnected({ Serial.printf("Disconnected from SinricPro\r\n"); });

SinricPro.begin(APP_KEY, APP_SECRET);
}

// main setup function
void setup() {
Serial.begin(BAUD_RATE); Serial.printf("\r\n\r\n");
dht.setup(DHT_PIN);

setupWiFi();
setupSinricPro();
}

void loop() {
SinricPro.handle();
handleTemperaturesensor();
}

//** Both code are working fine individually *** // but unable to combine both code for one esp8266 device

sivar2311 commented 1 month ago

but unable to combine both code for one esp8266 device

Ok, where exactly do you have issues with combining them? What have you tried so far?

joeljana commented 1 month ago

I tried a lot but failed

sivar2311 commented 1 month ago

I tried a lot but failed

But unfortunately that doesn't help me to help you. I need to know exact where you get stuck. What exact issues do you have when combining them?

joeljana commented 1 month ago

Let me write the code again. I try to combine by myself. Then I will share the problem.

sivar2311 commented 1 month ago

I try to combine by myself

Sounds like a fist step in the right direction 👍 Let me know when you have a question.

joeljana commented 1 month ago

Thanks for your guidance sir.