#pragma once #include namespace esphome { namespace hoermann_door { class HoermannMainComponent; } } #include "hciemulator.h" #include "esphome/components/uart/uart.h" namespace esphome { namespace hoermann_door { static const char *const COMP_TAG = "Hoermann"; void dispatcherFn(void *arg); class HoermannMainComponent: public Component{ protected: HCIEmulator* emulator; TaskHandle_t modBusTask; int log_level = 3; // Defaults to INFO uart::UARTComponent* _uart; InternalGPIOPin* _tx_on; volatile bool set_continue_ = true; volatile unsigned long lastCall = 0; volatile unsigned long maxPeriod = 0; public: void set_seriel_connection(uart::UARTComponent* uart){ this->_uart = uart; } void set_tx_on_pin(InternalGPIOPin* pin){ this->_tx_on = pin; } void set_log_level(int level){ this->log_level = level; } HCIEmulator* getEmulator(){ return emulator; } void setup() override { this->_tx_on->setup(); this->emulator = new HCIEmulator(this->_tx_on, this->_uart); this->emulator->setLogLevel(this->log_level); this->start_polling(); } void stop_polling(){ this->set_continue_ = false; if(modBusTask != NULL){ // Wait for the task to be deleted while(eTaskGetState(modBusTask) != eDeleted){ vTaskDelay(1); } modBusTask = NULL; } this->_tx_on->digital_write(false); } void start_polling() { if(modBusTask == NULL){ this->_tx_on->digital_write(false); this->set_continue_ = true; xTaskCreatePinnedToCore( dispatcherFn, // Function to implement the task "ModBusTask", // Name of the task 10000, // Stack size in words this, // Task input parameter // 1, // Priority of the task configMAX_PRIORITIES - 1, &modBusTask, // Task handle. 1 // Core where the task should run ); } } void modBusPolling(void *parameter) { while (set_continue_) { if (lastCall > 0) { maxPeriod = std::max((micros() - lastCall), (unsigned long)maxPeriod); } lastCall = micros(); emulator->poll(); vTaskDelay(1); } vTaskDelete(NULL); } void dump_config() override { ESP_LOGCONFIG(COMP_TAG, "hoermann_door_component:"); ESP_LOGCONFIG(COMP_TAG, " UART: "); ESP_LOGCONFIG(COMP_TAG, " UART is configured"); LOG_PIN(" TX_ON_PIN", this->_tx_on); ESP_LOGCONFIG(COMP_TAG, " Log Level: %d", this->log_level); } }; void dispatcherFn(void *arg) { HoermannMainComponent *x = (HoermannMainComponent *)arg; x->modBusPolling(arg); } template class StopPollingAction: public Action { public: StopPollingAction(HoermannMainComponent *motor) : motor_(motor) {} void play(Ts... x) override { this->motor_->stop_polling(); } protected: HoermannMainComponent *motor_; }; template class StartPollingAction: public Action { public: StartPollingAction(HoermannMainComponent *motor) : motor_(motor) {} void play(Ts... x) override { this->motor_->start_polling(); } protected: HoermannMainComponent *motor_; }; } }