ESP32在阿里云平台使用MQTT协议控制RGB灯_esp32 mqtt event->topic 点灯 b"on

};


##### 1.2.2创建client


根据上一步配置信息来创建一个client。



esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);


##### 1.2.3: 注册mqtt句柄



esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client);


mqtt相关事件处理都在此函数中,后详述。


##### 1.2.4: 根据句柄启动mqtt



esp_mqtt_client_start(client);


#### 1.3mqtt\_event\_handler处理函数


此函数实际操作的是`mqtt_event_handler_cb()`回调函数。由于控制RGB事件比较小,只用到了连接、订阅两个控制事件。



static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event)
{
esp_mqtt_client_handle_t client = event->client;
int msg_id;
switch (event->event_id) {
case MQTT_EVENT_CONNECTED: //连接
msg_id = esp_mqtt_client_subscribe(client, “/sys/a1Swb0u95bV/XP001/thing/service/property/set”, 0);//订阅主题
ESP_LOGI(TAG, “sent subscribe successful, msg_id=%d”, msg_id);
break;
case MQTT_EVENT_DISCONNECTED:
//…
break;

    case MQTT_EVENT_SUBSCRIBED:
       	//...
        break;
    case MQTT_EVENT_UNSUBSCRIBED:
        //...
        break;
    case MQTT_EVENT_PUBLISHED:
       	//...
        break;
    case MQTT_EVENT_DATA:   //从服务器发送过来的数据
        ESP_LOGI(TAG, "MQTT_EVENT_DATA");
        printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
        printf("DATA=%.*s\r\n", event->data_len, event->data);

        cJSON *root = cJSON_Parse(event->data);
        if (!root) {
            printf("JSON format error:%s \r\n", cJSON_GetErrorPtr());
        } else {
            cJSON *item = cJSON_GetObjectItem(root, "params");    //解析JSON数据
            cJSON *rgb_item = cJSON_GetObjectItem(item, "HSVColor");
            int32_t red = cJSON_GetObjectItem(rgb_item, "r_val")->valueint;
            int32_t green = cJSON_GetObjectItem(rgb_item, "g_val")->valueint;
            int32_t blue = cJSON_GetObjectItem(rgb_item, "b_val")->valueint;	            
            cJSON_Delete(root);

            if (red != g_red || green != g_green || blue != g_blue) {  //根据接收的数据设置RGB
                g_red = red;
                g_green = green;
                g_blue = blue;
                ESP_LOGI(TAG, "Light control: red = %d, green = %d, blue = %d", g_red, g_green, g_blue);
                ESP_ERROR_CHECK(g_leds->set_rgb(g_leds, g_red, g_green, g_blue));
            }
        
        }     
        break;
    case MQTT_EVENT_ERROR:
       	//..
        break;
    default:
        //...
        break;
}
return ESP_OK;

}


在JSON解析需要知道数据格式,在RGB控制中,数据格式如下所示:



{
“method” : “thing.service.property.set”,
“id” : “1664271450”,
“params” : {
“HSVColor”: {“r_val”: 255, “g_val”: 100,“b_val”: 100}
},
“version” : “1.0.0”
}


### 2 调试


首先打开设备的在线调试,如下图所示:  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200907161546729.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzk1MjE5Mg==,size_16,color_FFFFFF,t_70#pic_center)


然后发送RGB数据,数据格式见下图:  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/2020090716160212.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzk1MjE5Mg==,size_16,color_FFFFFF,t_70#pic_center)


实验结果如下图:  
 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200907161613140.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80Mzk1MjE5Mg==,size_16,color_FFFFFF,t_70#pic_center)


### 3 源程序


为了方便学习与记忆,附上主程序。



static const char *TAG = “MQTT_EXAMPLE”;
static led_rgb_t *g_leds = NULL;
static uint8_t g_red;
static uint8_t g_green;
static uint8_t g_blue;
static TaskHandle_t g_breath_light_task_handle = NULL;

//static const char *public_aliyun[] = {};

static esp_err_t mqtt_event_handler_cb(esp_mqtt_event_handle_t event)
{
esp_mqtt_client_handle_t client = event->client;
int msg_id;
// your_context_t *context = event->context;
switch (event->event_id) {
case MQTT_EVENT_CONNECTED:
ESP_LOGI(TAG, “MQTT_EVENT_CONNECTED”);

         msg_id = esp_mqtt_client_subscribe(client, "/sys/a1Swb0u95bV/XP001/thing/service/property/set", 0);
         ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);

    
        break;
    case MQTT_EVENT_DISCONNECTED:
        ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
        break;

    case MQTT_EVENT_SUBSCRIBED:
        ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
        msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
        ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
        break;
    case MQTT_EVENT_UNSUBSCRIBED:
        ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_PUBLISHED:
        ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_DATA:
        ESP_LOGI(TAG, "MQTT_EVENT_DATA");
        printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
        printf("DATA=%.*s\r\n", event->data_len, event->data);

        cJSON *root = cJSON_Parse(event->data);
        if (!root) {
            printf("JSON format error:%s \r\n", cJSON_GetErrorPtr());
        } else {
            cJSON *item = cJSON_GetObjectItem(root, "params");
            //int32_t val = cJSON_GetObjectItem(item, "PowerSwitch")->valueint;
            cJSON *rgb_item = cJSON_GetObjectItem(item, "HSVColor");
            int32_t red = cJSON_GetObjectItem(rgb_item, "r_val")->valueint;
            int32_t green = cJSON_GetObjectItem(rgb_item, "g_val")->valueint;
            int32_t blue = cJSON_GetObjectItem(rgb_item, "b_val")->valueint;
        
            cJSON_Delete(root);
        
            if (red != g_red || green != g_green || blue != g_blue) {
                g_red = red;
                g_green = green;
                g_blue = blue;
                ESP_LOGI(TAG, "Light control: red = %d, green = %d, blue = %d", g_red, g_green, g_blue);
                ESP_ERROR_CHECK(g_leds->set_rgb(g_leds, g_red, g_green, g_blue));
            }
        
        }   
        break;
    case MQTT_EVENT_ERROR:
        ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
        break;
    default:
        ESP_LOGI(TAG, "Other event id:%d", event->event_id);
        break;
}
return ESP_OK;

}

static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data) {
ESP_LOGD(TAG, “Event dispatched from event loop base=%s, event_id=%d”, base, event_id);
mqtt_event_handler_cb(event_data);
}

static void mqtt_app_start(void)
{
esp_mqtt_client_config_t mqtt_cfg = {
//.uri = CONFIG_BROKER_URL,
.host = “a1Swb0u95bV.iot-as-mqtt.cn-shanghai.aliyuncs.com”,
.port = 1883,
.client_id = “XP001|securemode=3,signmethod=hmacsha1|”,
.username = “XP001&a1Swb0u95bV”,
.password = “df8e0bbf849758e0cedb9d5c5854c345598c52d7”,

};

#if CONFIG_BROKER_URL_FROM_STDIN
char line[128];

if (strcmp(mqtt_cfg.uri, "FROM_STDIN") == 0) {
    int count = 0;
    printf("Please enter url of mqtt broker\n");
    while (count < 128) {
        int c = fgetc(stdin);
        if (c == '\n') {
            line[count] = '\0';
            break;
        } else if (c > 0 && c < 127) {
            line[count] = c;
            ++count;
        }
        vTaskDelay(10 / portTICK_PERIOD_MS);
    }
    mqtt_cfg.uri = line;
    printf("Broker url: %s\n", line);
} else {
    ESP_LOGE(TAG, "Configuration mismatch: wrong broker url");
    abort();
}

#endif /* CONFIG_BROKER_URL_FROM_STDIN */

esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, client);
esp_mqtt_client_start(client);

}

static void breath_light_task(void *arg)
{
uint8_t value = 0;
uint8_t dir = 0;

while (1) {
    ESP_ERROR_CHECK(g_leds->set_hsv(g_leds, 60, 50, 100));
    vTaskDelay(pdMS_TO_TICKS(20));

}

}

void app_main(void)
{
ESP_LOGI(TAG, “[APP] Startup…”);
ESP_LOGI(TAG, “[APP] Free memory: %d bytes”, esp_get_free_heap_size());
ESP_LOGI(TAG, “[APP] IDF version: %s”, esp_get_idf_version());

esp_log_level_set("*", ESP_LOG_INFO);
esp_log_level_set("MQTT_CLIENT", ESP_LOG_VERBOSE);
esp_log_level_set("MQTT_EXAMPLE", ESP_LOG_VERBOSE);
esp_log_level_set("TRANSPORT_TCP", ESP_LOG_VERBOSE);
esp_log_level_set("TRANSPORT_SSL", ESP_LOG_VERBOSE);
esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
esp_log_level_set("OUTBOX", ESP_LOG_VERBOSE);

ESP_ERROR_CHECK(nvs_flash_init());
ESP_ERROR_CHECK(esp_netif_init());
ESP_ERROR_CHECK(esp_event_loop_create_default());


led_rgb_config_t rgb_config = LED_RGB_DEFAULT_CONFIG(BOARD_GPIO_LED_R, BOARD_GPIO_LED_G, BOARD_GPIO_LED_B);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值