Files
ESPDocs/public/exemplos/zh-CN/esp-rainmaker.c
T

77 lines
2.3 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
* 面向 ESP32 的 ESP-RainMaker 示例
* 设备:可通过应用和云端控制的智能开关
*
* 依赖(idf_component.yml):
* espressif/esp_rainmaker: "^1.4.0"
*/
#include <stdio.h>
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include <esp_rmaker_core.h>
#include <esp_rmaker_standard_params.h>
#include <esp_rmaker_standard_devices.h>
#include <app_wifi.h>
static const char *TAG = "app_rainmaker";
static esp_rmaker_device_t *switch_device;
/* 用户在移动应用中更改状态时触发的回调 */
static esp_err_t write_cb(const esp_rmaker_device_t *dev, const esp_rmaker_param_val_t val, void *priv_data, esp_rmaker_write_ctx_t *ctx)
{
if (ctx) {
ESP_LOGI(TAG, "Comando recebido via %s", esp_rmaker_device_cb_src_to_str(ctx->src));
}
bool state = val.val.b;
ESP_LOGI(TAG, "Estado do interruptor alterado para: %s", state ? "LIGADO" : "DESLIGADO");
// 更新云端和应用中的参数
esp_rmaker_param_update_and_report(priv_data, val);
return ESP_OK;
}
void app_main(void)
{
// 初始化非易失性存储(NVS)
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
err = nvs_flash_init();
}
ESP_ERROR_CHECK(err);
// 初始化 Wi-Fi 配网
app_wifi_init();
// 配置 RainMaker 节点
esp_rmaker_config_t rainmaker_cfg = {
.enable_time_sync = true,
};
esp_rmaker_node_t *node = esp_rmaker_node_init(&rainmaker_cfg, "ESP32_SmartSwitch", "Switch");
// 创建默认的 'Switch' 设备
switch_device = esp_rmaker_switch_device_create("Living Room Light", NULL, true);
// 注册写回调
esp_rmaker_device_add_cb(switch_device, write_cb, NULL);
esp_rmaker_node_add_device(node, switch_device);
// 启用附加服务(OTA 和时区)
esp_rmaker_ota_enable_default();
esp_rmaker_timezone_service_enable();
// 启动 RainMaker 代理
esp_rmaker_start();
// 通过 BLE 启动 Wi-Fi 配网(在官方 RainMaker 应用中打开)
app_wifi_start(POP_TYPE_RANDOM);
ESP_LOGI(TAG, "RainMaker node ready! Scan the QR code in the ESP RainMaker app.");
}