Untitled
c_cpp
2 months ago
3.0 kB
3
Indexable
Never
#include <string> #include "esp_log.h" #include "host/ble_hs.h" #include "esp_adc/adc_oneshot.h" #include "esp_adc/adc_continuous.h" #include "esp_adc/adc_cali.h" #include "esp_adc/adc_cali_scheme.h" #include "DeviceVoltageHandler.hpp" #include "VLSvcsChrs.hpp" #define POWER_PIN_ADC_UNIT ADC_UNIT_1 #define POWER_PIN_ADC_CHANNEL ADC_CHANNEL_0 #define POWER_PIN_ADC_ATTEN ADC_ATTEN_DB_11 static esp_err_t err = ESP_OK; uint16_t DeviceVoltageHandler::vl_voltage_handle = 2; bool DeviceVoltageHandler::vl_voltage_notification_enabled = false; DeviceVoltageHandler::DeviceVoltageHandler() { vl_voltage_value = 0; previous_voltage_value = 0; } DeviceVoltageHandler::~DeviceVoltageHandler() = default; void DeviceVoltageHandler::voltage_change_event(void *arg) { DeviceVoltageHandler *instance = (DeviceVoltageHandler *)arg; uint32_t current_voltage; current_voltage = DeviceVoltageHandler::get_adc_voltage(); if (current_voltage != instance->previous_voltage_value && current_voltage > 0 && DeviceVoltageHandler::vl_voltage_notification_enabled) { instance->vl_voltage_value = current_voltage; ble_gatts_chr_updated(DeviceVoltageHandler::vl_voltage_handle); // Sends notification to any connected and subscribed central device ESP_LOGI("NOTIFICATION", "VOLTAGE CHANGED -> NOTIFICATION SENT"); } } int DeviceVoltageHandler::voltage_chr_access(uint16_t conn_handle, uint16_t attr_handle, struct ble_gatt_access_ctxt *ctxt, void *arg) { DeviceVoltageHandler *instance = (DeviceVoltageHandler *)arg; if (ctxt->op == BLE_GATT_ACCESS_OP_READ_CHR) { ESP_LOGI("DEBUG", "Central device reads the voltage characteristic"); std::string voltage = std::to_string(instance->vl_voltage_value); int rc = os_mbuf_append(ctxt->om, voltage.c_str(), voltage.size()); if (rc != 0) { printf("Error appending data to mbuf!\n"); return BLE_ATT_ERR_INSUFFICIENT_RES; } return 0; } return BLE_ATT_ERR_UNLIKELY; } uint32_t DeviceVoltageHandler::get_adc_voltage() { adc_oneshot_unit_handle_t adc_handle; adc_oneshot_unit_init_cfg_t init_config = { .unit_id = POWER_PIN_ADC_UNIT, }; ESP_ERROR_CHECK(adc_oneshot_new_unit(&init_config, &adc_handle)); // Configure the ADC channel adc_oneshot_chan_cfg_t chan_config = { .atten = POWER_PIN_ADC_ATTEN, .bitwidth = ADC_BITWIDTH_12, }; ESP_ERROR_CHECK(adc_oneshot_config_channel(adc_handle, POWER_PIN_ADC_CHANNEL, &chan_config)); int adc_raw_value = 0; ESP_ERROR_CHECK(adc_oneshot_read(adc_handle, POWER_PIN_ADC_CHANNEL, &adc_raw_value)); float voltage = (adc_raw_value * 3.3) / 4095.0; if (adc_raw_value < 1240) { voltage = 0; } printf("Voltage: %f\n", voltage); ESP_ERROR_CHECK(adc_oneshot_del_unit(adc_handle)); return voltage; }