blob: fd79e606afb6aa83c7e218ff2602bf15bdf14b60 [file] [log] [blame]
/*
*
* Copyright (c) 2021-2023 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "DeviceCallbacks.h"
#include <DeviceEnergyManagementManager.h>
#include <EVSEManufacturerImpl.h>
#include <EnergyEvseManager.h>
#include <EnergyManagementManager.h>
#include <device-energy-management-modes.h>
#include <energy-evse-modes.h>
#include "esp_log.h"
#include <common/CHIPDeviceManager.h>
#include <common/Esp32AppServer.h>
#include <common/Esp32ThreadInit.h>
#if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0)
#include "spi_flash_mmap.h"
#else
#include "esp_spi_flash.h"
#endif
#include "esp_system.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include "shell_extension/launch.h"
#include "shell_extension/openthread_cli_register.h"
#include <app/server/Dnssd.h>
#include <app/server/OnboardingCodesUtil.h>
#include <credentials/DeviceAttestationCredsProvider.h>
#include <credentials/examples/DeviceAttestationCredsExample.h>
#include <platform/ESP32/ESP32Utils.h>
#if CONFIG_ENABLE_ESP32_FACTORY_DATA_PROVIDER
#include <platform/ESP32/ESP32FactoryDataProvider.h>
#endif // CONFIG_ENABLE_ESP32_FACTORY_DATA_PROVIDER
#if CONFIG_ENABLE_PW_RPC
#include "Rpc.h"
#endif
#if CONFIG_ENABLE_ESP32_DEVICE_INFO_PROVIDER
#include <platform/ESP32/ESP32DeviceInfoProvider.h>
#else
#include <DeviceInfoProviderImpl.h>
#endif // CONFIG_ENABLE_ESP32_DEVICE_INFO_PROVIDER
#if CONFIG_SEC_CERT_DAC_PROVIDER
#include <platform/ESP32/ESP32SecureCertDACProvider.h>
#endif
#if CONFIG_ENABLE_ESP_INSIGHTS_TRACE
#include <esp_insights.h>
#include <tracing/esp32_trace/esp32_tracing.h>
#include <tracing/registry.h>
#endif
#define ENERGY_EVSE_ENDPOINT 1
using namespace ::chip;
using namespace chip::app;
using namespace chip::app::Clusters;
using namespace ::chip::Credentials;
using namespace ::chip::DeviceManager;
using namespace ::chip::DeviceLayer;
static std::unique_ptr<EnergyEvseDelegate> gEvseDelegate;
static std::unique_ptr<EnergyEvseManager> gEvseInstance;
static std::unique_ptr<DeviceEnergyManagementDelegate> gDEMDelegate;
static std::unique_ptr<DeviceEnergyManagementManager> gDEMInstance;
static std::unique_ptr<EVSEManufacturer> gEvseManufacturer;
#if CONFIG_ENABLE_ESP_INSIGHTS_TRACE
extern const char insights_auth_key_start[] asm("_binary_insights_auth_key_txt_start");
extern const char insights_auth_key_end[] asm("_binary_insights_auth_key_txt_end");
#endif
static const char * TAG = "energy-management-app";
static AppDeviceCallbacks EchoCallbacks;
static DeviceCallbacksDelegate sAppDeviceCallbacksDelegate;
namespace {
#if CONFIG_ENABLE_ESP32_FACTORY_DATA_PROVIDER
DeviceLayer::ESP32FactoryDataProvider sFactoryDataProvider;
#endif // CONFIG_ENABLE_ESP32_FACTORY_DATA_PROVIDER
#if CONFIG_ENABLE_ESP32_DEVICE_INFO_PROVIDER
DeviceLayer::ESP32DeviceInfoProvider gExampleDeviceInfoProvider;
#else
DeviceLayer::DeviceInfoProviderImpl gExampleDeviceInfoProvider;
#endif // CONFIG_ENABLE_ESP32_DEVICE_INFO_PROVIDER
#if CONFIG_SEC_CERT_DAC_PROVIDER
DeviceLayer::ESP32SecureCertDACProvider gSecureCertDACProvider;
#endif // CONFIG_SEC_CERT_DAC_PROVIDER
chip::Credentials::DeviceAttestationCredentialsProvider * get_dac_provider(void)
{
#if CONFIG_SEC_CERT_DAC_PROVIDER
return &gSecureCertDACProvider;
#elif CONFIG_ENABLE_ESP32_FACTORY_DATA_PROVIDER
return &sFactoryDataProvider;
#else // EXAMPLE_DAC_PROVIDER
return chip::Credentials::Examples::GetExampleDACProvider();
#endif
}
} // namespace
EVSEManufacturer * EnergyEvse::GetEvseManufacturer()
{
return gEvseManufacturer.get();
}
/*
* @brief Creates a Delegate and Instance for DEM
*
* The Instance is a container around the Delegate, so
* create the Delegate first, then wrap it in the Instance
* Then call the Instance->Init() to register the attribute and command handlers
*/
CHIP_ERROR DeviceEnergyManagementInit()
{
if (gDEMDelegate || gDEMInstance)
{
ESP_LOGE(TAG, "DEM Instance or Delegate already exist.");
return CHIP_ERROR_INCORRECT_STATE;
}
gDEMDelegate = std::make_unique<DeviceEnergyManagementDelegate>();
if (!gDEMDelegate)
{
ESP_LOGE(TAG, "Failed to allocate memory for DeviceEnergyManagementDelegate");
return CHIP_ERROR_NO_MEMORY;
}
/* Manufacturer may optionally not support all features, commands & attributes */
gDEMInstance = std::make_unique<DeviceEnergyManagementManager>(
EndpointId(ENERGY_EVSE_ENDPOINT), *gDEMDelegate,
BitMask<DeviceEnergyManagement::Feature, uint32_t>(
DeviceEnergyManagement::Feature::kPowerAdjustment, DeviceEnergyManagement::Feature::kPowerForecastReporting,
DeviceEnergyManagement::Feature::kStateForecastReporting, DeviceEnergyManagement::Feature::kStartTimeAdjustment,
DeviceEnergyManagement::Feature::kPausable, DeviceEnergyManagement::Feature::kForecastAdjustment,
DeviceEnergyManagement::Feature::kConstraintBasedAdjustment));
if (!gDEMInstance)
{
ESP_LOGE(TAG, "Failed to allocate memory for DeviceEnergyManagementManager");
gDEMDelegate.reset();
return CHIP_ERROR_NO_MEMORY;
}
CHIP_ERROR err = gDEMInstance->Init(); /* Register Attribute & Command handlers */
if (err != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "Init failed on gDEMInstance, err:%" CHIP_ERROR_FORMAT, err.Format());
gDEMInstance.reset();
gDEMDelegate.reset();
return err;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR DeviceEnergyManagementShutdown()
{
/* Do this in the order Instance first, then delegate
* Ensure we call the Instance->Shutdown to free attribute & command handlers first
*/
if (gDEMInstance)
{
/* deregister attribute & command handlers */
gDEMInstance->Shutdown();
gDEMInstance.reset();
}
if (gDEMDelegate)
{
gDEMDelegate.reset();
}
return CHIP_NO_ERROR;
}
/*
* @brief Creates a Delegate and Instance for EVSE cluster
*
* The Instance is a container around the Delegate, so
* create the Delegate first, then wrap it in the Instance
* Then call the Instance->Init() to register the attribute and command handlers
*/
CHIP_ERROR EnergyEvseInit()
{
CHIP_ERROR err;
if (gEvseDelegate || gEvseInstance)
{
ESP_LOGE(TAG, "EVSE Instance or Delegate already exist.");
return CHIP_ERROR_INCORRECT_STATE;
}
gEvseDelegate = std::make_unique<EnergyEvseDelegate>();
if (!gEvseDelegate)
{
ESP_LOGE(TAG, "Failed to allocate memory for EnergyEvseDelegate");
return CHIP_ERROR_NO_MEMORY;
}
/* Manufacturer may optionally not support all features, commands & attributes */
gEvseInstance = std::make_unique<EnergyEvseManager>(
EndpointId(ENERGY_EVSE_ENDPOINT), *gEvseDelegate,
BitMask<EnergyEvse::Feature, uint32_t>(EnergyEvse::Feature::kChargingPreferences, EnergyEvse::Feature::kPlugAndCharge,
EnergyEvse::Feature::kRfid, EnergyEvse::Feature::kSoCReporting,
EnergyEvse::Feature::kV2x),
BitMask<EnergyEvse::OptionalAttributes, uint32_t>(EnergyEvse::OptionalAttributes::kSupportsUserMaximumChargingCurrent,
EnergyEvse::OptionalAttributes::kSupportsRandomizationWindow,
EnergyEvse::OptionalAttributes::kSupportsApproximateEvEfficiency),
BitMask<EnergyEvse::OptionalCommands, uint32_t>(EnergyEvse::OptionalCommands::kSupportsStartDiagnostics));
if (!gEvseInstance)
{
ESP_LOGE(TAG, "Failed to allocate memory for EnergyEvseManager");
gEvseDelegate.reset();
return CHIP_ERROR_NO_MEMORY;
}
err = gEvseInstance->Init(); /* Register Attribute & Command handlers */
if (err != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "Init failed on gEvseInstance, err:%" CHIP_ERROR_FORMAT, err.Format());
gEvseInstance.reset();
gEvseDelegate.reset();
return err;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR EnergyEvseShutdown()
{
/* Do this in the order Instance first, then delegate
* Ensure we call the Instance->Shutdown to free attribute & command handlers first
*/
if (gEvseInstance)
{
/* deregister attribute & command handlers */
gEvseInstance->Shutdown();
gEvseInstance.reset();
}
if (gEvseDelegate)
{
gEvseDelegate.reset();
}
return CHIP_NO_ERROR;
}
/*
* @brief Creates a EVSEManufacturer class to hold the EVSE & DEM clusters
*
* The Instance is a container around the Delegate, so
* create the Delegate first, then wrap it in the Instance
* Then call the Instance->Init() to register the attribute and command handlers
*/
CHIP_ERROR EVSEManufacturerInit()
{
CHIP_ERROR err;
if (gEvseManufacturer)
{
ESP_LOGE(TAG, "EvseManufacturer already exist.");
return CHIP_ERROR_INCORRECT_STATE;
}
/* Now create EVSEManufacturer */
gEvseManufacturer = std::make_unique<EVSEManufacturer>(gEvseInstance.get());
if (!gEvseManufacturer)
{
ESP_LOGE(TAG, "Failed to allocate memory for EvseManufacturer");
return CHIP_ERROR_NO_MEMORY;
}
/* Call Manufacturer specific init */
err = gEvseManufacturer->Init();
if (err != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "Init failed on gEvseManufacturer, err:%" CHIP_ERROR_FORMAT, err.Format());
gEvseManufacturer.reset();
return err;
}
return CHIP_NO_ERROR;
}
CHIP_ERROR EVSEManufacturerShutdown()
{
if (gEvseManufacturer)
{
/* Shutdown the EVSEManufacturer */
gEvseManufacturer->Shutdown();
gEvseManufacturer.reset();
}
return CHIP_NO_ERROR;
}
void ApplicationInit()
{
if (DeviceEnergyManagementInit() != CHIP_NO_ERROR)
{
return;
}
if (EnergyEvseInit() != CHIP_NO_ERROR)
{
DeviceEnergyManagementShutdown();
return;
}
if (EVSEManufacturerInit() != CHIP_NO_ERROR)
{
DeviceEnergyManagementShutdown();
EnergyEvseShutdown();
return;
}
}
void ApplicationShutdown()
{
ESP_LOGD(TAG, "Energy Management App: ApplicationShutdown()");
/* Shutdown in reverse order that they were created */
EVSEManufacturerShutdown(); /* Free the EVSEManufacturer */
EnergyEvseShutdown(); /* Free the EnergyEvse */
DeviceEnergyManagementShutdown(); /* Free the DEM */
Clusters::DeviceEnergyManagementMode::Shutdown();
Clusters::EnergyEvseMode::Shutdown();
}
static void InitServer(intptr_t context)
{
// Print QR Code URL
PrintOnboardingCodes(chip::RendezvousInformationFlags(CONFIG_RENDEZVOUS_MODE));
DeviceCallbacksDelegate::Instance().SetAppDelegate(&sAppDeviceCallbacksDelegate);
Esp32AppServer::Init(); // Init ZCL Data Model and CHIP App Server AND Initialize device attestation config
#if CONFIG_ENABLE_ESP_INSIGHTS_TRACE
esp_insights_config_t config = {
.log_type = ESP_DIAG_LOG_TYPE_ERROR | ESP_DIAG_LOG_TYPE_WARNING | ESP_DIAG_LOG_TYPE_EVENT,
.auth_key = insights_auth_key_start,
};
esp_err_t ret = esp_insights_init(&config);
if (ret != ESP_OK)
{
ESP_LOGE(TAG, "Failed to initialize ESP Insights, err:0x%x", ret);
}
static Tracing::Insights::ESP32Backend backend;
Tracing::Register(backend);
#endif
// Application code should always be initialised after the initialisation of server.
ApplicationInit();
}
extern "C" void app_main()
{
// Initialize the ESP NVS layer.
esp_err_t err = nvs_flash_init();
if (err != ESP_OK)
{
ESP_LOGE(TAG, "nvs_flash_init() failed: %s", esp_err_to_name(err));
return;
}
err = esp_event_loop_create_default();
if (err != ESP_OK)
{
ESP_LOGE(TAG, "esp_event_loop_create_default() failed: %s", esp_err_to_name(err));
return;
}
#if CONFIG_ENABLE_PW_RPC
chip::rpc::Init();
#endif
ESP_LOGI(TAG, "==================================================");
ESP_LOGI(TAG, "chip-esp32-energy-management-example starting");
ESP_LOGI(TAG, "==================================================");
#if CONFIG_ENABLE_CHIP_SHELL
#if CONFIG_OPENTHREAD_CLI
chip::RegisterOpenThreadCliCommands();
#endif
chip::LaunchShell();
#endif
#if CHIP_DEVICE_CONFIG_ENABLE_WIFI
if (Internal::ESP32Utils::InitWiFiStack() != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "Failed to initialize WiFi stack");
return;
}
#endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI
DeviceLayer::SetDeviceInfoProvider(&gExampleDeviceInfoProvider);
CHIPDeviceManager & deviceMgr = CHIPDeviceManager::GetInstance();
CHIP_ERROR error = deviceMgr.Init(&EchoCallbacks);
if (error != CHIP_NO_ERROR)
{
ESP_LOGE(TAG, "device.Init() failed: %s", ErrorStr(error));
return;
}
#if CONFIG_ENABLE_ESP32_FACTORY_DATA_PROVIDER
SetCommissionableDataProvider(&sFactoryDataProvider);
#if CONFIG_ENABLE_ESP32_DEVICE_INSTANCE_INFO_PROVIDER
SetDeviceInstanceInfoProvider(&sFactoryDataProvider);
#endif
#endif
SetDeviceAttestationCredentialsProvider(get_dac_provider());
ESPOpenThreadInit();
chip::DeviceLayer::PlatformMgr().ScheduleWork(InitServer, reinterpret_cast<intptr_t>(nullptr));
}