WeChat applet Bluetooth + WiFi dual control Anxinke ESP32-C3 module application demonstration

Insert picture description here

I. Introduction

At present, the more and more popular Combo solutions ( Ble+WiFi ) in the market, such as Pingtou's TG7100C solution, Espressif's ESP32, etc., how to efficiently use Bluetooth and wifi communication has become an inevitable trend, so I did this Quick start demo for everyone, dedicated to the Internet of Things;

The suitable modules for this project are: ESP32-S series/ESP32-C3 series/ESP32-S3 series modules ;

The technical points used in this open source project are:

  1. Familiar with the freeRtos real-time operating system of Espressif's Internet of Things operating framework esp-idf, including task creation/message queue/inter-process communication;
  2. WeChat applet development foundation, including the use of MQTT library/Bluetooth low energy API interface, including search/connection/communication;
  3. Use Espressif's package RMT driver layer to drive WS2812B in a single line to achieve rainbow and other effects;
  4. Familiar with the peripheral development of ESP32/C3 chip, familiar with the use of BLE API interface, including custom broadcast/name/custom UUID;

2. Device core code

2.1 Bluetooth control

Set Bluetooth broadcast name

esp_ble_gap_set_device_name(TEST_DEVICE_NAME);

Set service UUID

 gl_profile_tab[0].service_id.is_primary = true;
 gl_profile_tab[0].service_id.id.inst_id = 0x00;
 gl_profile_tab[0].service_id.id.uuid.len = ESP_UUID_LEN_16;
 gl_profile_tab[0].service_id.id.uuid.uuid.uuid16 = GATTS_SERVICE_UUID_TEST_A;

Actively notify the host computer of data changes:

 case ESP_GATTS_READ_EVT:
    {
    
    
        esp_gatt_rsp_t rsp;
        memset(&rsp, 0, sizeof(esp_gatt_rsp_t));
        rsp.attr_value.handle = param->read.handle;
        rsp.attr_value.len = 3;
        rsp.attr_value.value[0] = red;
        rsp.attr_value.value[1] = green;
        rsp.attr_value.value[2] = blue;
        esp_ble_gatts_send_response(gatts_if, param->read.conn_id, param->read.trans_id, ESP_GATT_OK, &rsp);
        break;
    }

The host computer actively sends data here and makes corresponding processing:

 case ESP_GATTS_WRITE_EVT:
    {
    
    
        if (!param->write.is_prep)
        {
    
    
            ESP_LOGI(GATTS_TAG, "GATT_WRITE_EVT, value len %d, value :", param->write.len);
            esp_log_buffer_hex(GATTS_TAG, param->write.value, param->write.len);
            //发送数据到队列
            struct __User_data *pTmper;
            sprintf(user_data.allData, "{\"red\":%d,\"green\":%d,\"blue\":%d}", param->write.value[0], param->write.value[1], param->write.value[2]);
            pTmper = &user_data;
            user_data.dataLen = strlen(user_data.allData);
            xQueueSend(ParseJSONQueueHandler, (void *)&pTmper, portMAX_DELAY);

            ESP_LOGI(GATTS_TAG, "%02x %02x %02x ", param->write.value[0], param->write.value[1], param->write.value[2]);
        }
        example_write_event_env(gatts_if, &a_prepare_write_env, param);
        break;
    }

2.2 WiFi control

Set the parameters of MQTT remote connection

/* 
 * @Description: MQTT参数连接的配置
 * @param: 
 * @return: 
*/
void TaskXMqttRecieve(void *p)
{
    
    
    //连接的配置参数
    esp_mqtt_client_config_t mqtt_cfg = {
    
    
        .host = "www.xuhong.com",  //连接的域名 ,请务必修改为您的
        .port = 1883,              //端口,请务必修改为您的
        .username = "admin",       //用户名,请务必修改为您的
        .password = "xuhong123456",   //密码,请务必修改为您的
        .client_id = deviceUUID,
        .event_handle = MqttCloudsCallBack, //设置回调函数
        .keepalive = 120,                   //心跳
        .disable_auto_reconnect = false,    //开启自动重连
        .disable_clean_session = false,     //开启 清除会话
    };
    client = esp_mqtt_client_init(&mqtt_cfg);
    esp_mqtt_client_start(client);

    vTaskDelete(NULL);
}

The processing data sent by the server is sent to the message queue for processing:

    //服务器下发消息到本地成功接收回调
    case MQTT_EVENT_DATA:
    {
        printf("TOPIC=%.*s \r\n", event->topic_len, event->topic);
        printf("DATA=%.*s \r\n\r\n", event->data_len, event->data);
        //发送数据到队列
        struct __User_data *pTmper;
        sprintf(user_data.allData, "%s", event->data);
        pTmper = &user_data;
        user_data.dataLen = event->data_len;
        xQueueSend(ParseJSONQueueHandler, (void *)&pTmper, portMAX_DELAY);
        break;
    }

2.3 Peripheral driver

The driver code initialization of colorful light WS2812B:

/**
 * @description:  封装一层设置RGB灯效果
 * @param {uint16_t} Red 入参 红色
 * @param {uint16_t} Green 入参 绿色
 * @param {uint16_t} Blue 入参 蓝色
 * @return {*}
 */
void set_rgb(uint16_t Red, uint16_t Green, uint16_t Blue)
{
    
    
    for (int i = 0; i < 24; i++)
    {
    
    
        strip->set_pixel(strip, i, Red, Green, Blue);
    }
    red = Red;
    green = Green;
    blue = Blue;
    strip->refresh(strip, 10);
}

/**
 * @description: 初始化LED 
 * @param {*}
 * @return {*}
 */
void init_led()
{
    
    
    rmt_config_t config = RMT_DEFAULT_CONFIG_TX(4, RMT_TX_CHANNEL);
    // set counter clock to 40MHz
    config.clk_div = 2;

    ESP_ERROR_CHECK(rmt_config(&config));
    ESP_ERROR_CHECK(rmt_driver_install(config.channel, 0, 0));

    // install ws2812 driver
    led_strip_config_t strip_config = LED_STRIP_DEFAULT_CONFIG(24, (led_strip_dev_t)config.channel);
    strip = led_strip_new_rmt_ws2812(&strip_config);
    if (!strip)
    {
    
    
        ESP_LOGE(TAG, "install WS2812 driver failed");
    }
    // Clear LED strip (turn off all LEDs)
    ESP_ERROR_CHECK(strip->clear(strip, 100));
    set_rgb(0, 254, 0);
}

Message queue processing logic:

/*
 * @Description: 解析下发数据的队列逻辑处理
 * @param: null
 * @return: 
*/
void Task_ParseJSON(void *pvParameters)
{
    
    
    printf("[SY] Task_ParseJSON_Message creat ... \n");

    while (1)
    {
    
    
        struct __User_data *pMqttMsg;

        printf("Task_ParseJSON_Message xQueueReceive wait [%d] ... \n", esp_get_free_heap_size());
        xQueueReceive(ParseJSONQueueHandler, &pMqttMsg, portMAX_DELAY);

        printf("Task_ParseJSON_Message xQueueReceive get [%s] ... \n", pMqttMsg->allData);

        首先整体判断是否为一个json格式的数据
        cJSON *pJsonRoot = cJSON_Parse(pMqttMsg->allData);
        //如果是否json格式数据
        if (pJsonRoot == NULL)
        {
    
    
            printf("[SY] Task_ParseJSON_Message xQueueReceive not json ... \n");
            goto __cJSON_Delete;
        }

        cJSON *pJSON_Item_Red = cJSON_GetObjectItem(pJsonRoot, "red");
        cJSON *pJSON_Item_Green = cJSON_GetObjectItem(pJsonRoot, "green");
        cJSON *pJSON_Item_Blue = cJSON_GetObjectItem(pJsonRoot, "blue");

        set_rgb(pJSON_Item_Red->valueint, pJSON_Item_Green->valueint, pJSON_Item_Blue->valueint);

    __cJSON_Delete:
        cJSON_Delete(pJsonRoot);
    }
}

Three, WeChat applet core code

Code structure, UI mainly uses third-party libraries: WeUI and Vant-UI libraries, among which the MQTT library uses the open source MQTT.JS library.

Banner

3.1 Bluetooth search

 wx.onBluetoothDeviceFound(function (devices) {
      var isnotexist = true
      if (devices.deviceId) {
        if (devices.advertisData) {
          devices.advertisData = app.buf2hex(devices.advertisData)
        } else {
          devices.advertisData = ''
        }
        for (var i = 0; i < that.data.devicesList.length; i++) {
          if (devices.deviceId == that.data.devicesList[i].deviceId) {
            isnotexist = false
          }
        }
        if (isnotexist && devices[0].name === that.data.filterName ) {
          that.data.devicesList.push(devices[0])
        }
      }
      that.setData({
        devicesList: that.data.devicesList
      })
    })
  }

3.2 Bluetooth service discovery

Discovery service list:wx.getBLEDeviceServices()

Find the list of characteristic values:wx.getBLEDeviceCharacteristics()

Sending device, judge whether it is Bluetooth control or wifi control:

 SendTap: function (red, green, blue) {
    
    
    var that = this
    if (!this.data.isCheckOutControl) {
    
    
      if (this.data.connected) {
    
    
        var buffer = new ArrayBuffer(that.data.inputText.length)
        var dataView = new Uint8Array(buffer)
        dataView[0] = red; 
        dataView[1] = green; 
        dataView[2] = blue;
        wx.writeBLECharacteristicValue({
    
    
          deviceId: that.data.connectedDeviceId,
          serviceId: that.data.serviceId,
          characteristicId: "0000FF01-0000-1000-8000-00805F9B34FB",
          value: buffer,
          success: function (res) {
    
    
            console.log('发送成功')
          }, fail() {
    
    
            wx.showModal({
    
    
              title: '提示',
              content: '蓝牙已断开',
              showCancel: false,
              success: function (res) {
    
    
              }
            })
          }
        })
      } else {
    
    
        wx.showModal({
    
    
          title: '提示',
          content: '蓝牙已断开',
          showCancel: false,
          success: function (res) {
    
    
            that.setData({
    
    
              searching: false
            })
          }
        })
      }
    } else {
    
    
      //MQTT通讯发送
      if (this.data.client && this.data.client.connected) {
    
    
        this.data.client.publish('/esp32-c3/7cdfa1322e68/devSub', JSON.stringify({
    
    red,green,blue}));
      } else {
    
    
        wx.showToast({
    
    
          title: '请先连接服务器',
          icon: 'none',
          duration: 2000
        })
      }
    }
  },

Four, thanks

To this end, the following code repositories have also been open sourced for mutual encouragement! !

Open source project address Open source time
WeChat applet connects to mqtt server to control esp8266 smart hardware https://github.com/xuhongv/WeChatMiniEsp8266 2018.11
The realization of WeChat public account airkiss distribution network and near-field discovery in esp8266 rtos3.1 https://github.com/xuhongv/xLibEsp8266Rtos3.1AirKiss 2019.3
The realization of WeChat public account airkiss distribution network and near-field discovery in esp32 esp-idf https://github.com/xuhongv/xLibEsp32IdfAirKiss 2019.9
WeChat applet control esp8266 to achieve colorful effect project source code https://github.com/xuhongv/WCMiniColorSetForEsp8266 2019.9
WeChat applet bluetooth distribution network blufi is implemented in esp32 source code https://github.com/xuhongv/BlufiEsp32WeChat 2019.11
WeChat applet bluetooth ble control esp32 colorful light effect https://blog.csdn.net/xh870189248/article/details/101849759 2019.10
A commercially available event distribution WeChat applet mqtt disconnected reconnection framework https://blog.csdn.net/xh870189248/article/details/88718302 2019.2
WeChat applet connects to the mqtt server of Alibaba Cloud IOT IoT platform via websocket https://blog.csdn.net/xh870189248/article/details/91490697 2019.6
WeChat official account webpage realizes connection to mqtt server https://blog.csdn.net/xh870189248/article/details/100738444 2019.9
Self-developed WeChat applet is connected to Tencent's IoT development platform to realize one-click network distribution + control https://github.com/xuhongv/AiThinkerIoTMini 2020.9
Cloud-Cloud Docking Solution Tmall Elf Xiaoai Classmate Server + Embedded Code Open Source https://github.com/xuhongv/xClouds-php 2020.7

Also, thanks:

  • Espressif IoT operating system: https://github.com/espressif/esp-idf
  • Tencent WeUI framework: https://github.com/Tencent/weui-wxss
  • You like the Vant framework: https://vant-contrib.gitee.io/vant-weapp
  • Download the source code of this blog post: https://github.com/xuhongv/ESP32WiFiBleControlProject

Guess you like

Origin blog.csdn.net/Boantong_/article/details/114983580