写一个通过微信小程序通过蓝牙ble,WiFi的账号密码和TCP的IP和端口号发送给esp32-c3的详细的示例程序

// 以下是一个通过微信小程序通过蓝牙 BLE 发送 WiFi 的账号密码和 TCP 的 IP 和端口号到 ESP32-C3 的详细示例程序。
// 本示例将分为微信小程序端的代码和 ESP32-C3 端的代码。

// 1. 微信小程序端代码
// 文件:index.js

Page({
  data: {
    deviceId: '',
    serviceId: '',
    characteristicId: '',
    wifiSSID: 'your_wifi_ssid',
    wifiPassword: 'your_wifi_password',
    tcpIp: '192.168.1.100',
    tcpPort: '8080'
  },

  onLoad() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('Bluetooth adapter initialized', res);
        this.startBluetoothDevicesDiscovery();
      },
      fail: (err) => {
        console.error('Failed to initialize Bluetooth adapter', err);
      }
    });
  },

  startBluetoothDevicesDiscovery() {
    wx.startBluetoothDevicesDiscovery({
      success: (res) => {
        console.log('Started Bluetooth discovery', res);
        wx.onBluetoothDeviceFound((devices) => {
          devices.devices.forEach(device => {
            if (device.name === 'ESP32_C3') { // 假设设备名称为 ESP32_C3
              this.setData({
                deviceId: device.deviceId
              });
              this.connectToDevice();
            }
          });
        });
      },
      fail: (err) => {
        console.error('Failed to start Bluetooth discovery', err);
      }
    });
  },

  connectToDevice() {
    wx.createBLEConnection({
      deviceId: this.data.deviceId,
      success: (res) => {
        console.log('Connected to device', res);
        this.getService();
      },
      fail: (err) => {
        console.error('Failed to connect to device', err);
      }
    });
  },

  getService() {
    wx.getBLEDeviceServices({
      deviceId: this.data.deviceId,
      success: (res) => {
        console.log('Device services', res.services);
        // 假设我们知道服务 UUID
        const serviceId = 'your_service_uuid';
        this.setData({
          serviceId: serviceId
        });
        this.getCharacteristics();
      },
      fail: (err) => {
        console.error('Failed to get device services', err);
      }
    });
  },

  getCharacteristics() {
    wx.getBLEDeviceCharacteristics({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      success: (res) => {
        console.log('Device characteristics', res.characteristics);
        // 假设我们知道特征 UUID
        const characteristicId = 'your_characteristic_uuid';
        this.setData({
          characteristicId: characteristicId
        });
        this.sendDataToESP32();
      },
      fail: (err) => {
        console.error('Failed to get device characteristics', err);
      }
    });
  },

  sendDataToESP32() {
    const wifiData = `${this.data.wifiSSID},${this.data.wifiPassword}`;
    const tcpData = `${this.data.tcpIp},${this.data.tcpPort}`;
    const fullData = `${wifiData};${tcpData}`;
    const buffer = new ArrayBuffer(fullData.length);
    const dataView = new DataView(buffer);
    for (let i = 0; i < fullData.length; i++) {
      dataView.setUint8(i, fullData.charCodeAt(i));
    }

    wx.writeBLECharacteristicValue({
      deviceId: this.data.deviceId,
      serviceId: this.data.serviceId,
      characteristicId: this.data.characteristicId,
      value: buffer,
      success: (res) => {
        console.log('Data sent successfully', res);
      },
      fail: (err) => {
        console.error('Failed to send data', err);
      }
    });
  }
});

// 2. ESP32-C3 端代码
// 使用 Arduino 开发环境编写 ESP32-C3 代码

#include <BLEDevice.h>
#include <BLEServer.h>

BLECharacteristic *pCharacteristic;
String receivedData = "";

void setup() {
  Serial.begin(115200);
  BLEDevice::init("ESP32_C3");
  BLEServer *pServer = BLEDevice::createServer();
  BLEService *pService = pServer->createService("your_service_uuid");
  pCharacteristic = pService->createCharacteristic(
                      "your_characteristic_uuid",
                      BLECharacteristic::PROPERTY_WRITE
                    );
  pCharacteristic->setCallbacks(new MyCallbacks());
  pService->start();
  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->start();
}

void loop() {
  // Do nothing here
}

class MyCallbacks: public BLECharacteristicCallbacks {
  void onWrite(BLECharacteristic *pCharacteristic) {
    std::string value = pCharacteristic->getValue();
    if (value.length() > 0) {
      receivedData = String(value.c_str());
      Serial.println("Received Data: " + receivedData);
      // 解析 WiFi SSID、密码、TCP IP 和端口号
      parseReceivedData(receivedData);
    }
  }
};

void parseReceivedData(String data) {
  int wifiEndIndex = data.indexOf(';');
  String wifiData = data.substring(0, wifiEndIndex);
  String tcpData = data.substring(wifiEndIndex + 1);

  int commaIndex = wifiData.indexOf(',');
  String ssid = wifiData.substring(0, commaIndex);
  String password = wifiData.substring(commaIndex + 1);

  commaIndex = tcpData.indexOf(',');
  String ip = tcpData.substring(0, commaIndex);
  String port = tcpData.substring(commaIndex + 1);

  Serial.println("WiFi SSID: " + ssid);
  Serial.println("WiFi Password: " + password);
  Serial.println("TCP IP: " + ip);
  Serial.println("TCP Port: " + port);

  // 这里可以添加连接 WiFi 和 TCP 服务器的代码
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值