feat: update device name

This commit is contained in:
玖叁 2024-12-27 10:16:08 +08:00
parent eda05007cc
commit 821c264400
8 changed files with 61 additions and 2 deletions

View File

@ -17,6 +17,8 @@ public:
static BLECharacteristic *pTxCharacteristic;
static void init(String deviceName);
static void updateDeviceName(const String &newName);
static void restart();
};
#endif

View File

@ -12,6 +12,9 @@
#define CMD_GET_BT_STATUS 0x10
#define CMD_GET_SPIFFS_STATUS 0x11
#define CMD_GET_DISTANCE 0x12
#define CMD_SET_NAME 0xA1
#define CMD_MOTOR_MOVE_CONTROL 0x20
#define CMD_MOTOR_STEER_CONTROL 0x21
#define CMD_MOTOR_SINGLE_CONTROL 0x22
@ -28,6 +31,7 @@ public:
static void getBTStatus(BLECharacteristic &characteristic);
static void getSPIFFSStatus(BLECharacteristic &characteristic);
static void getDistance(BLECharacteristic &characteristic);
static void setName(BLECharacteristic &characteristic, uint8_t *packet);
static void motorMoveControl(BLECharacteristic &characteristic, uint8_t *packet);
static void motorSteerControl(BLECharacteristic &characteristic, uint8_t *packet);
static void motorRotateControl(BLECharacteristic &characteristic, uint8_t *packet);

View File

@ -3,6 +3,7 @@
#include <Arduino.h>
#include <SPIFFS.h>
#include "consts.h"
class Storage
{

View File

@ -110,6 +110,18 @@
控制示例 `00 07 24 01 01 01 FF`
## 设置
### 设置设备名称 `0xA1`
> ⚠️ 注意: 设备名称长度不能超过 16 个字符,此时最大包体长度 20仅支持 ASCII 码
包体 `00 包体长度 A1 设备名称 FF`
> 示例WhiteTiger
设置示例 `00 0E A1 57 68 69 74 65 54 69 67 65 72 FF`
## 状态回报
### 电机状态汇报 `0xE0`

View File

@ -57,3 +57,24 @@ void BLEManager::init(String deviceName)
pService->start();
pServer->getAdvertising()->start();
}
void BLEManager::updateDeviceName(const String &newName) {
// 保存新的设备名称
Storage::setName(newName);
// 停止广播
if (pServer) {
pServer->getAdvertising()->stop();
}
// 更新设备名称
BLEDevice::deinit(true);
BLEDevice::init(newName.c_str());
// 重新初始化 BLE 服务
init(newName);
}
void BLEManager::restart() {
ESP.restart(); // 重启 ESP32
}

View File

@ -42,6 +42,25 @@ void Handlers::getDistance(BLECharacteristic &characteristic)
characteristic.notify();
}
void Handlers::setName(BLECharacteristic &characteristic, uint8_t *packet)
{
unsigned char packetLength = packet[1];
unsigned char nameLength = packetLength - 4;
char name[17];
for (int i = 0; i <= nameLength; i++)
{
if (i == nameLength)
{
name[i] = '\0';
}
else
{
name[i] = packet[i + 3];
}
}
BLEManager::updateDeviceName(name);
}
void Handlers::motorMoveControl(BLECharacteristic &characteristic, uint8_t *packet)
{
uint8_t direction = packet[3];

View File

@ -15,7 +15,7 @@ void setup()
Storage::init();
// 初始化 BLE
BLEManager::init(DEVICE_NAME);
BLEManager::init(Storage::getName());
// 初始化电机
MotorController::init(

View File

@ -75,7 +75,7 @@ void Storage::setName(String name)
String Storage::getName()
{
if (!isMounted)
return "";
return DEVICE_NAME;
File file = SPIFFS.open("/name.txt", "r");
String name = file.readStringUntil('\n');