fridgeDoor.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include <stdio.h>
  2. #include "freertos/FreeRTOS.h"
  3. #include "freertos/task.h"
  4. #include "driver/gpio.h"
  5. #include "esp_log.h"
  6. #include <stdbool.h>
  7. #include "sdkconfig.h"
  8. #include "fridgeDoor.h"
  9. #include "config.h"
  10. #include "sound.h"
  11. #include "mqtt.h"
  12. #ifdef DOOR_SENSOR_ENABLED
  13. static void check_sensor_active_time(bool fridgeDoorClosed) {
  14. static int64_t activeStartTime = 0;
  15. //ESP_EARLY_LOGI("CHECK", "State: %s", fridgeDoorClosed == true ? "CLOSED" : "OPEN");
  16. if (fridgeDoorClosed == false) {
  17. if (activeStartTime == 0) {
  18. activeStartTime = esp_timer_get_time() / 1000; // Convert to milliseconds
  19. ESP_LOGI("CHECK", "Door timer start time: %lld", activeStartTime);
  20. } else {
  21. int64_t elapsedTime = (esp_timer_get_time() / 1000) - activeStartTime;
  22. //ESP_LOGI("CHECK", "Elapsed time: %lld", elapsedTime);
  23. if (elapsedTime > ACTIVE_THRESHOLD_MS) {
  24. enableNotificationSound(true);
  25. }
  26. }
  27. } else {
  28. activeStartTime = 0;
  29. enableNotificationSound(false);
  30. }
  31. }
  32. static void read_photo_sensor_task(void *pvParameters) {
  33. static bool prevState = false;
  34. while (1) {
  35. bool fridgeDoorClosed = gpio_get_level(PHOTO_SENSOR_PIN) == 0 ? false : true;
  36. if (fridgeDoorClosed != prevState) {
  37. prevState = fridgeDoorClosed;
  38. ESP_EARLY_LOGI("PHOTO", "Triggered! State: %s", fridgeDoorClosed == true ? "CLOSED" : "OPEN");
  39. if( fridgeDoorClosed == false ) {
  40. gpio_set_level(BLINK_GPIO, 1);
  41. }
  42. else {
  43. gpio_set_level(BLINK_GPIO, 0);
  44. }
  45. char mqtt_s[50];
  46. char value_s[10];
  47. sprintf(mqtt_s,"kitchen/fridge/doorState");
  48. sprintf(value_s,"%s",fridgeDoorClosed ? "closed" : "open");
  49. sendMQTTMessage(mqtt_s, value_s);
  50. }
  51. check_sensor_active_time(fridgeDoorClosed);
  52. vTaskDelay(pdMS_TO_TICKS(50)); // Delay 50ms (20 times per second)
  53. }
  54. }
  55. void setup_photo_sensor() {
  56. gpio_config_t io_conf = {
  57. .intr_type = GPIO_INTR_ANYEDGE, // Trigger on both rising & falling edges
  58. .pin_bit_mask = (1ULL << PHOTO_SENSOR_PIN),
  59. .mode = GPIO_MODE_INPUT,
  60. .pull_up_en = GPIO_PULLUP_DISABLE,
  61. .pull_down_en = GPIO_PULLDOWN_DISABLE
  62. };
  63. gpio_config(&io_conf);
  64. xTaskCreate(read_photo_sensor_task, "read_sensor_task", 2048, NULL, 10, NULL);
  65. ESP_LOGI("PHOTO", "Photomicrosensor configured on GPIO %d", PHOTO_SENSOR_PIN);
  66. }
  67. #else
  68. void setup_photo_sensor() {};
  69. #endif