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
Other
236 stars 125 forks source link

AC Unit #395

Closed abdoshamma closed 3 months ago

abdoshamma commented 3 months ago

Hi pls help me of window AC Unit example I tried to add dht11 and i can read the temp only through the serial monitor I'm not able to see the real temp in the app, second thing is how to add relay pins for on and off ac or to control the cooling mode or the fan, could u pls give me a hint how to do it?

abdoshamma commented 3 months ago
#include <Arduino.h>
#if defined(ESP8266)
  #include <ESP8266WiFi.h>
#elif defined(ESP32) || defined(ARDUINO_ARCH_RP2040)
  #include <WiFi.h>
#endif

#include "SinricPro.h"
#include "SinricProWindowAC.h"
#include "DHT.h"

// WiFi credentials
#define WIFI_SSID         "YOUR_WIFI_SSID"    
#define WIFI_PASS         "YOUR_WIFI_PASSWORD"

// SinricPro credentials
#define APP_KEY           "YOUR_APP_KEY_HERE"      // Should look like "de0bxxxx-1x3x-4x3x-ax2x-5dabxxxxxxxx"
#define APP_SECRET        "YOUR_APP_SECRET_HERE"   // Should look like "5f36xxxx-x3x7-4x3x-xexe-e86724a9xxxx-4c4axxxx-3x3x-x5xe-x9x3-333d65xxxxxx"
#define ACUNIT_ID         "YOUR_DEVICE_ID_HERE"    // Should look like "5dc1564130xxxxxxxxxxxxxx"

// DHT sensor settings
#define DHTPIN 2          // Change to the actual GPIO pin you're using for the DHT sensor
#define DHTTYPE DHT22     // Change to DHT11 if you're using a DHT11 sensor

// Relay GPIO pins
#define RELAY_PIN_POWER 5    // GPIO pin for power relay
#define RELAY_PIN_FAN_SPEED 4 // GPIO pin for fan speed relay

float globalTemperature;
bool globalPowerState;
int globalFanSpeed;

DHT dht(DHTPIN, DHTTYPE);

bool onPowerState(const String &deviceId, bool &state) {
  Serial.printf("Thermostat %s turned %s\r\n", deviceId.c_str(), state?"on":"off");
  globalPowerState = state; 
  digitalWrite(RELAY_PIN_POWER, state ? LOW : HIGH); // Assuming LOW to turn ON the relay and HIGH to turn it OFF
  return true; // request handled properly
}

bool onTargetTemperature(const String &deviceId, float &temperature) {
  Serial.printf("Thermostat %s set temperature to %f\r\n", deviceId.c_str(), temperature);
  globalTemperature = temperature;
  return true;
}

bool onAdjustTargetTemperature(const String & deviceId, float &temperatureDelta) {
  globalTemperature += temperatureDelta;  // calculate absolute temperature
  Serial.printf("Thermostat %s changed temperature about %f to %f\r\n", deviceId.c_str(), temperatureDelta, globalTemperature);
  temperatureDelta = globalTemperature; // return absolute temperature
  return true;
}

bool onThermostatMode(const String &deviceId, String &mode) {
  Serial.printf("Thermostat %s set to mode %s\r\n", deviceId.c_str(), mode.c_str());
  return true;
}

bool onRangeValue(const String &deviceId, int &rangeValue) {
  Serial.printf("Fan speed set to %d\r\n", rangeValue);
  globalFanSpeed = rangeValue;
  digitalWrite(RELAY_PIN_FAN_SPEED, rangeValue ? LOW : HIGH); // Assuming LOW to turn ON the relay and HIGH to turn it OFF
  return true;
}

bool onAdjustRangeValue(const String &deviceId, int &valueDelta) {
  globalFanSpeed += valueDelta;
  Serial.printf("Fan speed changed about %d to %d\r\n", valueDelta, globalFanSpeed);
  digitalWrite(RELAY_PIN_FAN_SPEED, globalFanSpeed ? LOW : HIGH); // Adjust relay based on fan speed
  return true;
}

void setupWiFi() {
  Serial.printf("\r\n[Wifi]: Connecting");

  #if defined(ESP8266)
    WiFi.setSleepMode(WIFI_NONE_SLEEP); 
    WiFi.setAutoReconnect(true);
  #elif defined(ESP32)
    WiFi.setSleep(false); 
    WiFi.setAutoReconnect(true);
  #endif

  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]);
}

void setupSinricPro() {
  SinricProWindowAC &myAcUnit = SinricPro[ACUNIT_ID];
  myAcUnit.onPowerState(onPowerState);
  myAcUnit.onTargetTemperature(onTargetTemperature);
  myAcUnit.onAdjustTargetTemperature(onAdjustTargetTemperature);
  myAcUnit.onThermostatMode(onThermostatMode);
  myAcUnit.onRangeValue(onRangeValue);
  myAcUnit.onAdjustRangeValue(onAdjustRangeValue);

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

void setup() {
  Serial.begin(BAUD_RATE); 
  Serial.printf("\r\n\r\n");
  setupWiFi();
  setupSinricPro();
  dht.begin();   // Initialize the DHT sensor

  pinMode(RELAY_PIN_POWER, OUTPUT);
  pinMode(RELAY_PIN_FAN_SPEED, OUTPUT);
  digitalWrite(RELAY_PIN_POWER, HIGH);  // Initialize relay as OFF (HIGH)
  digitalWrite(RELAY_PIN_FAN_SPEED, HIGH);  // Initialize relay as OFF (HIGH)

  Serial.println("DHT sensor initialized.");
}

void loop() {
  SinricPro.handle();

  // Read temperature every 2 seconds
  static unsigned long lastReadTime = 0;
  if (millis() - lastReadTime > 2000) {
    lastReadTime = millis();
    float temp = dht.readTemperature();
    if (!isnan(temp)) {
      globalTemperature = temp;
      Serial.printf("Current temperature: %f\r\n", globalTemperature);
    } else {
      Serial.println("Failed to read from DHT sensor!");
    }
  }
}

Edit by sivar2311: code formatted

Please use three backticks for code! Example:

// your code goes here

kakopappa commented 3 months ago

Don’t see the your code sending the temperature values to server.


  bool success = myAcUnit.sendTemperatureEvent(temperature, humidity); // send event
  if (success) {  
    Serial.printf("Sent!\r\n");
  } else {
    Serial.printf("Something went wrong...could not send Event to server!\r\n"); // Enable ENABLE_DEBUG to see why
  }

Please make sure you’re sending once a minute or there’s a noticeable change in the temperature. Don’t send the same values

Take a look at the tutorial https://help.sinric.pro/pages/tutorials/temperature-sensors/DHTx_AMx_RHTx

sivar2311 commented 3 months ago

thing is how to add relay pins for on and off ac or to control the cooling mode or the fan

You "add" relay pins the same way as you did for any other pins:

#define RELAY1_GPIO 12

void setupRelay {
  pinMode(RELAY1_GPIO, OUTPUT);
}

void turnOnRelay1() {
  digitalWrite(RELAY1_GPIO, HIGH);
}

void turnOffRelay1() {
  digitalWrite(RELAY1_GPIO, LOW);
}

The onThermostatMode function will give you a mode String. Possible Values are "OFF", "AUTO", "COOL" and "HEAT". Inside the callback, decide what to do (which relays have to turn on and of etc).

The OnRangeValue will give you a range value (integer 0..n). Again, decide what to do on specific values.

abdoshamma commented 3 months ago

hi i made the below code by combining the temp sensor and ac unit sketch pls check if what iv done is correct or not because I'm getteng errors and not able to solve it "Compilation error: 'using SinricProWindowAC = class SINRICPRO_3_0_1::SinricProWindowAC' {aka 'class SINRICPRO_3_0_1::SinricProWindowAC'} has no member named 'sendTemperatureEvent'; did you mean 'sendTargetTemperatureEvent'?"

/*
 * Example for how to use the AC Unit
 * 
 * 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>
#if defined(ESP8266)
  #include <ESP8266WiFi.h>
#elif defined(ESP32) || defined(ARDUINO_ARCH_RP2040)
  #include <WiFi.h>
#endif

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

#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 ACUNIT_ID         ""    // Should look like "5dc1564130xxxxxxxxxxxxxx"
#define BAUD_RATE         115200                // Change baudrate to your need (used for serial monitor)
#define EVENT_WAIT_TIME   60000               // send event every 60 seconds
#define DHTPIN 2  
#define DHTTYPE DHT11   // DHT 11

DHT dht(DHTPIN, DHTTYPE);                                   // DHT sensor                   // Change baudrate to your need

float globalTemperature;
bool globalPowerState;
int globalFanSpeed;
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(const String &deviceId, bool &state) {
  Serial.printf("Thermostat %s turned %s\r\n", deviceId.c_str(), state?"on":"off");
  globalPowerState = state; 
  return true; // request handled properly
}

bool onTargetTemperature(const String &deviceId, float &temperature) {
  Serial.printf("Thermostat %s set temperature to %f\r\n", deviceId.c_str(), temperature);
  globalTemperature = temperature;
  return true;
}

bool onAdjustTargetTemperature(const String & deviceId, float &temperatureDelta) {
  globalTemperature += temperatureDelta;  // calculate absolut temperature
  Serial.printf("Thermostat %s changed temperature about %f to %f", deviceId.c_str(), temperatureDelta, globalTemperature);
  temperatureDelta = globalTemperature; // return absolut temperature
  return true;
}

bool onThermostatMode(const String &deviceId, String &mode) {
  Serial.printf("Thermostat %s set to mode %s\r\n", deviceId.c_str(), mode.c_str());
  return true;
}

bool onRangeValue(const String &deviceId, int &rangeValue) {
  Serial.printf("Fan speed set to %d\r\n", rangeValue);
  globalFanSpeed = rangeValue;
  return true;
}

bool onAdjustRangeValue(const String &deviceId, int &valueDelta) {
  globalFanSpeed += valueDelta;
  Serial.printf("Fan speed changed about %d to %d\r\n", valueDelta, globalFanSpeed);
  valueDelta = globalFanSpeed;
  return true;
}
void handleTemperaturesensor() {
  unsigned long actualMillis = millis();
  if (actualMillis - lastEvent < EVENT_WAIT_TIME) return; //only check every EVENT_WAIT_TIME milliseconds

 float temperature = dht.readTemperature();          // get actual temperature in °C
//  temperature = dht.getTemperature() * 1.8f + 32;  // get actual temperature in °F
 float humidity = dht.readHumidity();                // 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...
  SinricProWindowAC &myAcUnit = SinricPro[ACUNIT_ID];
  bool success = myAcUnit.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);
// Serial.print("Temperature: %2.1f Celsius\tHumidity: %2.1f%%\r\n", temperature, humidity);
  Serial.print(F("Humidity: "));
  Serial.print(humidity);
  Serial.print(F("%  Temperature: "));
  Serial.print(temperature);
  Serial.print(F("°C "));

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

void setupWiFi() {
  Serial.printf("\r\n[Wifi]: Connecting");

  #if defined(ESP8266)
    WiFi.setSleepMode(WIFI_NONE_SLEEP); 
    WiFi.setAutoReconnect(true);
  #elif defined(ESP32)
    WiFi.setSleep(false); 
    WiFi.setAutoReconnect(true);
  #endif

  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]);
}

void setupSinricPro() {
  SinricProWindowAC &myAcUnit = SinricPro[ACUNIT_ID];
  myAcUnit.onPowerState(onPowerState);
  myAcUnit.onTargetTemperature(onTargetTemperature);
  myAcUnit.onAdjustTargetTemperature(onAdjustTargetTemperature);
  myAcUnit.onThermostatMode(onThermostatMode);
  myAcUnit.onRangeValue(onRangeValue);
  myAcUnit.onAdjustRangeValue(onAdjustRangeValue);

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

void setup() {
  Serial.begin(BAUD_RATE); Serial.printf("\r\n\r\n");
  dht.begin();
  setupWiFi();
  setupSinricPro();
}

void loop() {
  SinricPro.handle();
   handleTemperaturesensor();
}
kakopappa commented 3 months ago

Hello,

Seems sendTemperatureEvent method is not available for SinricProWindowAC type. Can you switch to SinricProThermostat for now?

https://sinricpro.github.io/esp8266-esp32-sdk-documentation/class_s_i_n_r_i_c_p_r_o__3__0__0_1_1_sinric_pro_thermostat.html

You can see all the available methods here

On Fri, 26 Jul 2024 at 1:39 AM abdoshamma @.***> wrote:

hi i made the below code by combining the temp sensor and ac unit sketch pls check if what iv done is correct or not because I'm getteng errors and not able to solve it "Compilation error: 'using SinricProWindowAC = class SINRICPRO_3_0_1::SinricProWindowAC' {aka 'class SINRICPRO_3_0_1::SinricProWindowAC'} has no member named 'sendTemperatureEvent'; did you mean 'sendTargetTemperatureEvent'?"

/*

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

if defined(ESP8266)

include

elif defined(ESP32) || defined(ARDUINO_ARCH_RP2040)

include

endif

include "SinricPro.h"

include "SinricProWindowAC.h"

include "SinricProTemperaturesensor.h"

include "DHT.h" // https://github.com/markruys/arduino-DHT

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 ACUNIT_ID "" // Should look like "5dc1564130xxxxxxxxxxxxxx"

define BAUD_RATE 115200 // Change baudrate to your need (used for serial monitor)

define EVENT_WAIT_TIME 60000 // send event every 60 seconds

define DHTPIN 2

define DHTTYPE DHT11 // DHT 11

DHT dht(DHTPIN, DHTTYPE); // DHT sensor // Change baudrate to your need

float globalTemperature; bool globalPowerState; int globalFanSpeed; 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(const String &deviceId, bool &state) { Serial.printf("Thermostat %s turned %s\r\n", deviceId.c_str(), state?"on":"off"); globalPowerState = state; return true; // request handled properly }

bool onTargetTemperature(const String &deviceId, float &temperature) { Serial.printf("Thermostat %s set temperature to %f\r\n", deviceId.c_str(), temperature); globalTemperature = temperature; return true; }

bool onAdjustTargetTemperature(const String & deviceId, float &temperatureDelta) { globalTemperature += temperatureDelta; // calculate absolut temperature Serial.printf("Thermostat %s changed temperature about %f to %f", deviceId.c_str(), temperatureDelta, globalTemperature); temperatureDelta = globalTemperature; // return absolut temperature return true; }

bool onThermostatMode(const String &deviceId, String &mode) { Serial.printf("Thermostat %s set to mode %s\r\n", deviceId.c_str(), mode.c_str()); return true; }

bool onRangeValue(const String &deviceId, int &rangeValue) { Serial.printf("Fan speed set to %d\r\n", rangeValue); globalFanSpeed = rangeValue; return true; }

bool onAdjustRangeValue(const String &deviceId, int &valueDelta) { globalFanSpeed += valueDelta; Serial.printf("Fan speed changed about %d to %d\r\n", valueDelta, globalFanSpeed); valueDelta = globalFanSpeed; return true; } void handleTemperaturesensor() { unsigned long actualMillis = millis(); if (actualMillis - lastEvent < EVENT_WAIT_TIME) return; //only check every EVENT_WAIT_TIME milliseconds

float temperature = dht.readTemperature(); // get actual temperature in °C // temperature = dht.getTemperature() * 1.8f + 32; // get actual temperature in °F float humidity = dht.readHumidity(); // 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... SinricProWindowAC &myAcUnit = SinricPro[ACUNIT_ID]; bool success = myAcUnit.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); // Serial.print("Temperature: %2.1f Celsius\tHumidity: %2.1f%%\r\n", temperature, humidity); Serial.print(F("Humidity: ")); Serial.print(humidity); Serial.print(F("% Temperature: ")); Serial.print(temperature); Serial.print(F("°C "));

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

void setupWiFi() { Serial.printf("\r\n[Wifi]: Connecting");

if defined(ESP8266)

WiFi.setSleepMode(WIFI_NONE_SLEEP);
WiFi.setAutoReconnect(true);

elif defined(ESP32)

WiFi.setSleep(false);
WiFi.setAutoReconnect(true);

endif

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]); }

void setupSinricPro() { SinricProWindowAC &myAcUnit = SinricPro[ACUNIT_ID]; myAcUnit.onPowerState(onPowerState); myAcUnit.onTargetTemperature(onTargetTemperature); myAcUnit.onAdjustTargetTemperature(onAdjustTargetTemperature); myAcUnit.onThermostatMode(onThermostatMode); myAcUnit.onRangeValue(onRangeValue); myAcUnit.onAdjustRangeValue(onAdjustRangeValue);

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

void setup() { Serial.begin(BAUD_RATE); Serial.printf("\r\n\r\n"); dht.begin(); setupWiFi(); setupSinricPro(); }

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

— Reply to this email directly, view it on GitHub https://github.com/sinricpro/esp8266-esp32-sdk/issues/395#issuecomment-2251167694, or unsubscribe https://github.com/notifications/unsubscribe-auth/ABZAZZTCT4K2VQJIFXJ26STZOFA5DAVCNFSM6AAAAABLOJUGHGVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDENJRGE3DONRZGQ . You are receiving this because you commented.Message ID: @.***>

github-actions[bot] commented 3 months 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!

abdoshamma commented 3 months ago

Thank you