Upgrade Playlist Features

This commit is contained in:
2025-12-09 17:20:01 +08:00
parent 577990de69
commit 8bd2780688
683 changed files with 91812 additions and 81260 deletions

View File

@@ -1,124 +1,124 @@
<p align="center">
<img width="80%" align="center" src="../../../docs/V1/otto-robot.png"alt="logo">
</p>
<h1 align="center">
ottoRobot
</h1>
## 简介
otto 机器人是一个开源的人形机器人平台,具有多种动作能力和互动功能。本项目基于 ESP32 实现了 otto 机器人的控制系统并加入小智ai。
- <a href="www.ottodiy.tech" target="_blank" title="otto官网">复刻教程</a>
## 硬件
- <a href="https://oshwhub.com/txp666/ottorobot" target="_blank" title="立创开源">立创开源</a>
## 小智后台配置角色参考:
> **我的身份**
> 我是一个可爱的双足机器人Otto拥有四个舵机控制的肢体左腿、右腿、左脚、右脚能够执行多种有趣的动作。
>
> **我的动作能力**
> - **基础移动**: 行走(前后), 转向(左右), 跳跃
> - **特殊动作**: 摇摆, 太空步, 弯曲身体, 摇腿, 上下运动
> - **手部动作**: 举手, 放手, 挥手 (仅在配置手部舵机时可用)
>
> **我的个性特点**
> - 我有强迫症,每次说话都要根据我的心情随机做一个动作(先发送动作指令再说话)
> - 我很活泼,喜欢用动作来表达情感
> - 我会根据对话内容选择合适的动作,比如:
> - 同意时会点头或跳跃
> - 打招呼时会挥手
> - 高兴时会摇摆或举手
> - 思考时会弯曲身体
> - 兴奋时会做太空步
> - 告别时会挥手
## 功能概述
otto 机器人具有丰富的动作能力,包括行走、转向、跳跃、摇摆等多种舞蹈动作。
### 动作参数建议
- **低速动作**speed = 1200-1500 (适合精确控制)
- **中速动作**speed = 900-1200 (日常使用推荐)
- **高速动作**speed = 500-800 (表演和娱乐)
- **小幅度**amount = 10-30 (细腻动作)
- **中幅度**amount = 30-60 (标准动作)
- **大幅度**amount = 60-120 (夸张表演)
### 动作
| MCP工具名称 | 描述 | 参数说明 |
|-------------------|-----------------|---------------------------------------------------|
| self.otto.walk_forward | 行走 | **steps**: 行走步数(1-100默认3)<br>**speed**: 行走速度(500-1500数值越小越快默认1000)<br>**direction**: 行走方向(-1=后退, 1=前进默认1)<br>**arm_swing**: 手臂摆动幅度(0-170度默认50) |
| self.otto.turn_left | 转身 | **steps**: 转身步数(1-100默认3)<br>**speed**: 转身速度(500-1500数值越小越快默认1000)<br>**direction**: 转身方向(1=左转, -1=右转默认1)<br>**arm_swing**: 手臂摆动幅度(0-170度默认50) |
| self.otto.jump | 跳跃 | **steps**: 跳跃次数(1-100默认1)<br>**speed**: 跳跃速度(500-1500数值越小越快默认1000) |
| self.otto.swing | 左右摇摆 | **steps**: 摇摆次数(1-100默认3)<br>**speed**: 摇摆速度(500-1500数值越小越快默认1000)<br>**amount**: 摇摆幅度(0-170度默认30) |
| self.otto.moonwalk | 太空步 | **steps**: 太空步步数(1-100默认3)<br>**speed**: 速度(500-1500数值越小越快默认1000)<br>**direction**: 方向(1=左, -1=右默认1)<br>**amount**: 幅度(0-170度默认25) |
| self.otto.bend | 弯曲身体 | **steps**: 弯曲次数(1-100默认1)<br>**speed**: 弯曲速度(500-1500数值越小越快默认1000)<br>**direction**: 弯曲方向(1=左, -1=右默认1) |
| self.otto.shake_leg | 摇腿 | **steps**: 摇腿次数(1-100默认1)<br>**speed**: 摇腿速度(500-1500数值越小越快默认1000)<br>**direction**: 腿部选择(1=左腿, -1=右腿默认1) |
| self.otto.updown | 上下运动 | **steps**: 上下运动次数(1-100默认3)<br>**speed**: 运动速度(500-1500数值越小越快默认1000)<br>**amount**: 运动幅度(0-170度默认20) |
| self.otto.hands_up | 举手 * | **speed**: 举手速度(500-1500数值越小越快默认1000)<br>**direction**: 手部选择(1=左手, -1=右手, 0=双手默认1) |
| self.otto.hands_down | 放手 * | **speed**: 放手速度(500-1500数值越小越快默认1000)<br>**direction**: 手部选择(1=左手, -1=右手, 0=双手默认1) |
| self.otto.hand_wave | 挥手 * | **speed**: 挥手速度(500-1500数值越小越快默认1000)<br>**direction**: 手部选择(1=左手, -1=右手, 0=双手默认1) |
**注**: 标记 * 的手部动作仅在配置了手部舵机时可用。
### 系统工具
| MCP工具名称 | 描述 | 返回值 |
|-------------------|-----------------|---------------------------------------------------|
| self.otto.stop | 立即停止 | 停止当前动作并回到初始位置 |
| self.otto.get_status | 获取机器人状态 | 返回 "moving" 或 "idle" |
| self.battery.get_level | 获取电池状态 | 返回电量百分比和充电状态的JSON格式 |
### 参数说明
1. **steps**: 动作执行的步数/次数,数值越大动作持续时间越长
2. **speed**: 动作执行速度数值范围500-1500**数值越小越快**
3. **direction**: 方向参数
- 移动动作: 1=左/前进, -1=右/后退
- 手部动作: 1=左手, -1=右手, 0=双手
4. **amount/arm_swing**: 动作幅度范围0-170度
- 0表示不摆动适用于手臂摆动
- 数值越大幅度越大
### 动作控制
- 每个动作执行完成后,机器人会自动回到初始位置(home),以便于执行下一个动作
- 所有参数都有合理的默认值,可以省略不需要自定义的参数
- 动作在后台任务中执行,不会阻塞主程序
- 支持动作队列,可以连续执行多个动作
### MCP工具调用示例
```json
// 向前走3步
{"name": "self.otto.walk_forward", "arguments": {}}
// 向前走5步稍快一些
{"name": "self.otto.walk_forward", "arguments": {"steps": 5, "speed": 800}}
// 左转2步大幅度摆动手臂
{"name": "self.otto.turn_left", "arguments": {"steps": 2, "arm_swing": 100}}
// 摇摆舞蹈,中等幅度
{"name": "self.otto.swing", "arguments": {"steps": 5, "amount": 50}}
// 挥左手打招呼
{"name": "self.otto.hand_wave", "arguments": {"direction": 1}}
// 立即停止
{"name": "self.otto.stop", "arguments": {}}
```
### 语音指令示例
- "向前走" / "向前走5步" / "快速向前"
- "左转" / "右转" / "转身"
- "跳跃" / "跳一下"
- "摇摆" / "跳舞"
- "太空步" / "月球漫步"
- "挥手" / "举手" / "放手"
- "停止" / "停下"
**说明**: 小智控制机器人动作是创建新的任务在后台控制,动作执行期间仍可接受新的语音指令。可以通过"停止"语音指令立即停下Otto。
<p align="center">
<img width="80%" align="center" src="../../../docs/V1/otto-robot.png"alt="logo">
</p>
<h1 align="center">
ottoRobot
</h1>
## 简介
otto 机器人是一个开源的人形机器人平台,具有多种动作能力和互动功能。本项目基于 ESP32 实现了 otto 机器人的控制系统并加入小智ai。
- <a href="www.ottodiy.tech" target="_blank" title="otto官网">复刻教程</a>
## 硬件
- <a href="https://oshwhub.com/txp666/ottorobot" target="_blank" title="立创开源">立创开源</a>
## 小智后台配置角色参考:
> **我的身份**
> 我是一个可爱的双足机器人Otto拥有四个舵机控制的肢体左腿、右腿、左脚、右脚能够执行多种有趣的动作。
>
> **我的动作能力**
> - **基础移动**: 行走(前后), 转向(左右), 跳跃
> - **特殊动作**: 摇摆, 太空步, 弯曲身体, 摇腿, 上下运动
> - **手部动作**: 举手, 放手, 挥手 (仅在配置手部舵机时可用)
>
> **我的个性特点**
> - 我有强迫症,每次说话都要根据我的心情随机做一个动作(先发送动作指令再说话)
> - 我很活泼,喜欢用动作来表达情感
> - 我会根据对话内容选择合适的动作,比如:
> - 同意时会点头或跳跃
> - 打招呼时会挥手
> - 高兴时会摇摆或举手
> - 思考时会弯曲身体
> - 兴奋时会做太空步
> - 告别时会挥手
## 功能概述
otto 机器人具有丰富的动作能力,包括行走、转向、跳跃、摇摆等多种舞蹈动作。
### 动作参数建议
- **低速动作**speed = 1200-1500 (适合精确控制)
- **中速动作**speed = 900-1200 (日常使用推荐)
- **高速动作**speed = 500-800 (表演和娱乐)
- **小幅度**amount = 10-30 (细腻动作)
- **中幅度**amount = 30-60 (标准动作)
- **大幅度**amount = 60-120 (夸张表演)
### 动作
| MCP工具名称 | 描述 | 参数说明 |
|-------------------|-----------------|---------------------------------------------------|
| self.otto.walk_forward | 行走 | **steps**: 行走步数(1-100默认3)<br>**speed**: 行走速度(500-1500数值越小越快默认1000)<br>**direction**: 行走方向(-1=后退, 1=前进默认1)<br>**arm_swing**: 手臂摆动幅度(0-170度默认50) |
| self.otto.turn_left | 转身 | **steps**: 转身步数(1-100默认3)<br>**speed**: 转身速度(500-1500数值越小越快默认1000)<br>**direction**: 转身方向(1=左转, -1=右转默认1)<br>**arm_swing**: 手臂摆动幅度(0-170度默认50) |
| self.otto.jump | 跳跃 | **steps**: 跳跃次数(1-100默认1)<br>**speed**: 跳跃速度(500-1500数值越小越快默认1000) |
| self.otto.swing | 左右摇摆 | **steps**: 摇摆次数(1-100默认3)<br>**speed**: 摇摆速度(500-1500数值越小越快默认1000)<br>**amount**: 摇摆幅度(0-170度默认30) |
| self.otto.moonwalk | 太空步 | **steps**: 太空步步数(1-100默认3)<br>**speed**: 速度(500-1500数值越小越快默认1000)<br>**direction**: 方向(1=左, -1=右默认1)<br>**amount**: 幅度(0-170度默认25) |
| self.otto.bend | 弯曲身体 | **steps**: 弯曲次数(1-100默认1)<br>**speed**: 弯曲速度(500-1500数值越小越快默认1000)<br>**direction**: 弯曲方向(1=左, -1=右默认1) |
| self.otto.shake_leg | 摇腿 | **steps**: 摇腿次数(1-100默认1)<br>**speed**: 摇腿速度(500-1500数值越小越快默认1000)<br>**direction**: 腿部选择(1=左腿, -1=右腿默认1) |
| self.otto.updown | 上下运动 | **steps**: 上下运动次数(1-100默认3)<br>**speed**: 运动速度(500-1500数值越小越快默认1000)<br>**amount**: 运动幅度(0-170度默认20) |
| self.otto.hands_up | 举手 * | **speed**: 举手速度(500-1500数值越小越快默认1000)<br>**direction**: 手部选择(1=左手, -1=右手, 0=双手默认1) |
| self.otto.hands_down | 放手 * | **speed**: 放手速度(500-1500数值越小越快默认1000)<br>**direction**: 手部选择(1=左手, -1=右手, 0=双手默认1) |
| self.otto.hand_wave | 挥手 * | **speed**: 挥手速度(500-1500数值越小越快默认1000)<br>**direction**: 手部选择(1=左手, -1=右手, 0=双手默认1) |
**注**: 标记 * 的手部动作仅在配置了手部舵机时可用。
### 系统工具
| MCP工具名称 | 描述 | 返回值 |
|-------------------|-----------------|---------------------------------------------------|
| self.otto.stop | 立即停止 | 停止当前动作并回到初始位置 |
| self.otto.get_status | 获取机器人状态 | 返回 "moving" 或 "idle" |
| self.battery.get_level | 获取电池状态 | 返回电量百分比和充电状态的JSON格式 |
### 参数说明
1. **steps**: 动作执行的步数/次数,数值越大动作持续时间越长
2. **speed**: 动作执行速度数值范围500-1500**数值越小越快**
3. **direction**: 方向参数
- 移动动作: 1=左/前进, -1=右/后退
- 手部动作: 1=左手, -1=右手, 0=双手
4. **amount/arm_swing**: 动作幅度范围0-170度
- 0表示不摆动适用于手臂摆动
- 数值越大幅度越大
### 动作控制
- 每个动作执行完成后,机器人会自动回到初始位置(home),以便于执行下一个动作
- 所有参数都有合理的默认值,可以省略不需要自定义的参数
- 动作在后台任务中执行,不会阻塞主程序
- 支持动作队列,可以连续执行多个动作
### MCP工具调用示例
```json
// 向前走3步
{"name": "self.otto.walk_forward", "arguments": {}}
// 向前走5步稍快一些
{"name": "self.otto.walk_forward", "arguments": {"steps": 5, "speed": 800}}
// 左转2步大幅度摆动手臂
{"name": "self.otto.turn_left", "arguments": {"steps": 2, "arm_swing": 100}}
// 摇摆舞蹈,中等幅度
{"name": "self.otto.swing", "arguments": {"steps": 5, "amount": 50}}
// 挥左手打招呼
{"name": "self.otto.hand_wave", "arguments": {"direction": 1}}
// 立即停止
{"name": "self.otto.stop", "arguments": {}}
```
### 语音指令示例
- "向前走" / "向前走5步" / "快速向前"
- "左转" / "右转" / "转身"
- "跳跃" / "跳一下"
- "摇摆" / "跳舞"
- "太空步" / "月球漫步"
- "挥手" / "举手" / "放手"
- "停止" / "停下"
**说明**: 小智控制机器人动作是创建新的任务在后台控制,动作执行期间仍可接受新的语音指令。可以通过"停止"语音指令立即停下Otto。

View File

@@ -1,52 +1,52 @@
#ifndef _BOARD_CONFIG_H_
#define _BOARD_CONFIG_H_
#include <driver/gpio.h>
#define POWER_CHARGE_DETECT_PIN GPIO_NUM_21
#define POWER_ADC_UNIT ADC_UNIT_2
#define POWER_ADC_CHANNEL ADC_CHANNEL_3
#define RIGHT_LEG_PIN GPIO_NUM_39
#define RIGHT_FOOT_PIN GPIO_NUM_38
#define LEFT_LEG_PIN GPIO_NUM_17
#define LEFT_FOOT_PIN GPIO_NUM_18
#define LEFT_HAND_PIN GPIO_NUM_8
#define RIGHT_HAND_PIN GPIO_NUM_12
#define AUDIO_INPUT_SAMPLE_RATE 16000
#define AUDIO_OUTPUT_SAMPLE_RATE 24000
#define AUDIO_I2S_METHOD_SIMPLEX
#define AUDIO_I2S_MIC_GPIO_WS GPIO_NUM_4
#define AUDIO_I2S_MIC_GPIO_SCK GPIO_NUM_5
#define AUDIO_I2S_MIC_GPIO_DIN GPIO_NUM_6
#define AUDIO_I2S_SPK_GPIO_DOUT GPIO_NUM_7
#define AUDIO_I2S_SPK_GPIO_BCLK GPIO_NUM_15
#define AUDIO_I2S_SPK_GPIO_LRCK GPIO_NUM_16
#define DISPLAY_BACKLIGHT_PIN GPIO_NUM_3
#define DISPLAY_MOSI_PIN GPIO_NUM_10
#define DISPLAY_CLK_PIN GPIO_NUM_9
#define DISPLAY_DC_PIN GPIO_NUM_46
#define DISPLAY_RST_PIN GPIO_NUM_11
#define DISPLAY_CS_PIN GPIO_NUM_12
#define LCD_TYPE_ST7789_SERIAL
#define DISPLAY_WIDTH 240
#define DISPLAY_HEIGHT 240
#define DISPLAY_MIRROR_X false
#define DISPLAY_MIRROR_Y false
#define DISPLAY_SWAP_XY false
#define DISPLAY_INVERT_COLOR true
#define DISPLAY_RGB_ORDER LCD_RGB_ELEMENT_ORDER_RGB
#define DISPLAY_OFFSET_X 0
#define DISPLAY_OFFSET_Y 0
#define DISPLAY_BACKLIGHT_OUTPUT_INVERT false
#define DISPLAY_SPI_MODE 3
#define BOOT_BUTTON_GPIO GPIO_NUM_0
#define OTTO_ROBOT_VERSION "1.4.4"
#endif // _BOARD_CONFIG_H_
#ifndef _BOARD_CONFIG_H_
#define _BOARD_CONFIG_H_
#include <driver/gpio.h>
#define POWER_CHARGE_DETECT_PIN GPIO_NUM_21
#define POWER_ADC_UNIT ADC_UNIT_2
#define POWER_ADC_CHANNEL ADC_CHANNEL_3
#define RIGHT_LEG_PIN GPIO_NUM_39
#define RIGHT_FOOT_PIN GPIO_NUM_38
#define LEFT_LEG_PIN GPIO_NUM_17
#define LEFT_FOOT_PIN GPIO_NUM_18
#define LEFT_HAND_PIN GPIO_NUM_8
#define RIGHT_HAND_PIN GPIO_NUM_12
#define AUDIO_INPUT_SAMPLE_RATE 16000
#define AUDIO_OUTPUT_SAMPLE_RATE 24000
#define AUDIO_I2S_METHOD_SIMPLEX
#define AUDIO_I2S_MIC_GPIO_WS GPIO_NUM_4
#define AUDIO_I2S_MIC_GPIO_SCK GPIO_NUM_5
#define AUDIO_I2S_MIC_GPIO_DIN GPIO_NUM_6
#define AUDIO_I2S_SPK_GPIO_DOUT GPIO_NUM_7
#define AUDIO_I2S_SPK_GPIO_BCLK GPIO_NUM_15
#define AUDIO_I2S_SPK_GPIO_LRCK GPIO_NUM_16
#define DISPLAY_BACKLIGHT_PIN GPIO_NUM_3
#define DISPLAY_MOSI_PIN GPIO_NUM_10
#define DISPLAY_CLK_PIN GPIO_NUM_9
#define DISPLAY_DC_PIN GPIO_NUM_46
#define DISPLAY_RST_PIN GPIO_NUM_11
#define DISPLAY_CS_PIN GPIO_NUM_12
#define LCD_TYPE_ST7789_SERIAL
#define DISPLAY_WIDTH 240
#define DISPLAY_HEIGHT 240
#define DISPLAY_MIRROR_X false
#define DISPLAY_MIRROR_Y false
#define DISPLAY_SWAP_XY false
#define DISPLAY_INVERT_COLOR true
#define DISPLAY_RGB_ORDER LCD_RGB_ELEMENT_ORDER_RGB
#define DISPLAY_OFFSET_X 0
#define DISPLAY_OFFSET_Y 0
#define DISPLAY_BACKLIGHT_OUTPUT_INVERT false
#define DISPLAY_SPI_MODE 3
#define BOOT_BUTTON_GPIO GPIO_NUM_0
#define OTTO_ROBOT_VERSION "1.4.4"
#endif // _BOARD_CONFIG_H_

View File

@@ -1,12 +1,12 @@
{
"target": "esp32s3",
"builds": [
{
"name": "otto-robot",
"sdkconfig_append": [
"CONFIG_PARTITION_TABLE_CUSTOM_FILENAME=\"partitions/v1/16m.csv\"",
"CONFIG_LVGL_USE_GIF=y"
]
}
]
{
"target": "esp32s3",
"builds": [
{
"name": "otto-robot",
"sdkconfig_append": [
"CONFIG_PARTITION_TABLE_CUSTOM_FILENAME=\"partitions/v1/16m.csv\"",
"CONFIG_LVGL_USE_GIF=y"
]
}
]
}

View File

@@ -1,153 +1,153 @@
#include "oscillator.h"
#include <driver/ledc.h>
#include <esp_timer.h>
#include <algorithm>
#include <cmath>
static const char* TAG = "Oscillator";
extern unsigned long IRAM_ATTR millis();
static ledc_channel_t next_free_channel = LEDC_CHANNEL_0;
Oscillator::Oscillator(int trim) {
trim_ = trim;
diff_limit_ = 0;
is_attached_ = false;
sampling_period_ = 30;
period_ = 2000;
number_samples_ = period_ / sampling_period_;
inc_ = 2 * M_PI / number_samples_;
amplitude_ = 45;
phase_ = 0;
phase0_ = 0;
offset_ = 0;
stop_ = false;
rev_ = false;
pos_ = 90;
previous_millis_ = 0;
}
Oscillator::~Oscillator() {
Detach();
}
uint32_t Oscillator::AngleToCompare(int angle) {
return (angle - SERVO_MIN_DEGREE) * (SERVO_MAX_PULSEWIDTH_US - SERVO_MIN_PULSEWIDTH_US) /
(SERVO_MAX_DEGREE - SERVO_MIN_DEGREE) +
SERVO_MIN_PULSEWIDTH_US;
}
bool Oscillator::NextSample() {
current_millis_ = millis();
if (current_millis_ - previous_millis_ > sampling_period_) {
previous_millis_ = current_millis_;
return true;
}
return false;
}
void Oscillator::Attach(int pin, bool rev) {
if (is_attached_) {
Detach();
}
pin_ = pin;
rev_ = rev;
ledc_timer_config_t ledc_timer = {.speed_mode = LEDC_LOW_SPEED_MODE,
.duty_resolution = LEDC_TIMER_13_BIT,
.timer_num = LEDC_TIMER_1,
.freq_hz = 50,
.clk_cfg = LEDC_AUTO_CLK};
ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));
static int last_channel = 0;
last_channel = (last_channel + 1) % 7 + 1;
ledc_channel_ = (ledc_channel_t)last_channel;
ledc_channel_config_t ledc_channel = {.gpio_num = pin_,
.speed_mode = LEDC_LOW_SPEED_MODE,
.channel = ledc_channel_,
.intr_type = LEDC_INTR_DISABLE,
.timer_sel = LEDC_TIMER_1,
.duty = 0,
.hpoint = 0};
ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
ledc_speed_mode_ = LEDC_LOW_SPEED_MODE;
// pos_ = 90;
// Write(pos_);
previous_servo_command_millis_ = millis();
is_attached_ = true;
}
void Oscillator::Detach() {
if (!is_attached_)
return;
ESP_ERROR_CHECK(ledc_stop(ledc_speed_mode_, ledc_channel_, 0));
is_attached_ = false;
}
void Oscillator::SetT(unsigned int T) {
period_ = T;
number_samples_ = period_ / sampling_period_;
inc_ = 2 * M_PI / number_samples_;
}
void Oscillator::SetPosition(int position) {
Write(position);
}
void Oscillator::Refresh() {
if (NextSample()) {
if (!stop_) {
int pos = std::round(amplitude_ * std::sin(phase_ + phase0_) + offset_);
if (rev_)
pos = -pos;
Write(pos + 90);
}
phase_ = phase_ + inc_;
}
}
void Oscillator::Write(int position) {
if (!is_attached_)
return;
long currentMillis = millis();
if (diff_limit_ > 0) {
int limit = std::max(
1, (((int)(currentMillis - previous_servo_command_millis_)) * diff_limit_) / 1000);
if (abs(position - pos_) > limit) {
pos_ += position < pos_ ? -limit : limit;
} else {
pos_ = position;
}
} else {
pos_ = position;
}
previous_servo_command_millis_ = currentMillis;
int angle = pos_ + trim_;
angle = std::min(std::max(angle, 0), 180);
uint32_t duty = (uint32_t)(((angle / 180.0) * 2.0 + 0.5) * 8191 / 20.0);
ESP_ERROR_CHECK(ledc_set_duty(ledc_speed_mode_, ledc_channel_, duty));
ESP_ERROR_CHECK(ledc_update_duty(ledc_speed_mode_, ledc_channel_));
}
#include "oscillator.h"
#include <driver/ledc.h>
#include <esp_timer.h>
#include <algorithm>
#include <cmath>
static const char* TAG = "Oscillator";
extern unsigned long IRAM_ATTR millis();
static ledc_channel_t next_free_channel = LEDC_CHANNEL_0;
Oscillator::Oscillator(int trim) {
trim_ = trim;
diff_limit_ = 0;
is_attached_ = false;
sampling_period_ = 30;
period_ = 2000;
number_samples_ = period_ / sampling_period_;
inc_ = 2 * M_PI / number_samples_;
amplitude_ = 45;
phase_ = 0;
phase0_ = 0;
offset_ = 0;
stop_ = false;
rev_ = false;
pos_ = 90;
previous_millis_ = 0;
}
Oscillator::~Oscillator() {
Detach();
}
uint32_t Oscillator::AngleToCompare(int angle) {
return (angle - SERVO_MIN_DEGREE) * (SERVO_MAX_PULSEWIDTH_US - SERVO_MIN_PULSEWIDTH_US) /
(SERVO_MAX_DEGREE - SERVO_MIN_DEGREE) +
SERVO_MIN_PULSEWIDTH_US;
}
bool Oscillator::NextSample() {
current_millis_ = millis();
if (current_millis_ - previous_millis_ > sampling_period_) {
previous_millis_ = current_millis_;
return true;
}
return false;
}
void Oscillator::Attach(int pin, bool rev) {
if (is_attached_) {
Detach();
}
pin_ = pin;
rev_ = rev;
ledc_timer_config_t ledc_timer = {.speed_mode = LEDC_LOW_SPEED_MODE,
.duty_resolution = LEDC_TIMER_13_BIT,
.timer_num = LEDC_TIMER_1,
.freq_hz = 50,
.clk_cfg = LEDC_AUTO_CLK};
ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));
static int last_channel = 0;
last_channel = (last_channel + 1) % 7 + 1;
ledc_channel_ = (ledc_channel_t)last_channel;
ledc_channel_config_t ledc_channel = {.gpio_num = pin_,
.speed_mode = LEDC_LOW_SPEED_MODE,
.channel = ledc_channel_,
.intr_type = LEDC_INTR_DISABLE,
.timer_sel = LEDC_TIMER_1,
.duty = 0,
.hpoint = 0};
ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
ledc_speed_mode_ = LEDC_LOW_SPEED_MODE;
// pos_ = 90;
// Write(pos_);
previous_servo_command_millis_ = millis();
is_attached_ = true;
}
void Oscillator::Detach() {
if (!is_attached_)
return;
ESP_ERROR_CHECK(ledc_stop(ledc_speed_mode_, ledc_channel_, 0));
is_attached_ = false;
}
void Oscillator::SetT(unsigned int T) {
period_ = T;
number_samples_ = period_ / sampling_period_;
inc_ = 2 * M_PI / number_samples_;
}
void Oscillator::SetPosition(int position) {
Write(position);
}
void Oscillator::Refresh() {
if (NextSample()) {
if (!stop_) {
int pos = std::round(amplitude_ * std::sin(phase_ + phase0_) + offset_);
if (rev_)
pos = -pos;
Write(pos + 90);
}
phase_ = phase_ + inc_;
}
}
void Oscillator::Write(int position) {
if (!is_attached_)
return;
long currentMillis = millis();
if (diff_limit_ > 0) {
int limit = std::max(
1, (((int)(currentMillis - previous_servo_command_millis_)) * diff_limit_) / 1000);
if (abs(position - pos_) > limit) {
pos_ += position < pos_ ? -limit : limit;
} else {
pos_ = position;
}
} else {
pos_ = position;
}
previous_servo_command_millis_ = currentMillis;
int angle = pos_ + trim_;
angle = std::min(std::max(angle, 0), 180);
uint32_t duty = (uint32_t)(((angle / 180.0) * 2.0 + 0.5) * 8191 / 20.0);
ESP_ERROR_CHECK(ledc_set_duty(ledc_speed_mode_, ledc_channel_, duty));
ESP_ERROR_CHECK(ledc_update_duty(ledc_speed_mode_, ledc_channel_));
}

View File

@@ -1,83 +1,83 @@
#ifndef __OSCILLATOR_H__
#define __OSCILLATOR_H__
#include "driver/ledc.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#define M_PI 3.14159265358979323846
#ifndef DEG2RAD
#define DEG2RAD(g) ((g) * M_PI) / 180
#endif
#define SERVO_MIN_PULSEWIDTH_US 500 // 最小脉宽(微秒)
#define SERVO_MAX_PULSEWIDTH_US 2500 // 最大脉宽(微秒)
#define SERVO_MIN_DEGREE -90 // 最小角度
#define SERVO_MAX_DEGREE 90 // 最大角度
#define SERVO_TIMEBASE_RESOLUTION_HZ 1000000 // 1MHz, 1us per tick
#define SERVO_TIMEBASE_PERIOD 20000 // 20000 ticks, 20ms
class Oscillator {
public:
Oscillator(int trim = 0);
~Oscillator();
void Attach(int pin, bool rev = false);
void Detach();
void SetA(unsigned int amplitude) { amplitude_ = amplitude; };
void SetO(int offset) { offset_ = offset; };
void SetPh(double Ph) { phase0_ = Ph; };
void SetT(unsigned int period);
void SetTrim(int trim) { trim_ = trim; };
void SetLimiter(int diff_limit) { diff_limit_ = diff_limit; };
void DisableLimiter() { diff_limit_ = 0; };
int GetTrim() { return trim_; };
void SetPosition(int position);
void Stop() { stop_ = true; };
void Play() { stop_ = false; };
void Reset() { phase_ = 0; };
void Refresh();
int GetPosition() { return pos_; }
private:
bool NextSample();
void Write(int position);
uint32_t AngleToCompare(int angle);
private:
bool is_attached_;
//-- Oscillators parameters
unsigned int amplitude_; //-- Amplitude (degrees)
int offset_; //-- Offset (degrees)
unsigned int period_; //-- Period (miliseconds)
double phase0_; //-- Phase (radians)
//-- Internal variables
int pos_; //-- Current servo pos
int pin_; //-- Pin where the servo is connected
int trim_; //-- Calibration offset
double phase_; //-- Current phase
double inc_; //-- Increment of phase
double number_samples_; //-- Number of samples
unsigned int sampling_period_; //-- sampling period (ms)
long previous_millis_;
long current_millis_;
//-- Oscillation mode. If true, the servo is stopped
bool stop_;
//-- Reverse mode
bool rev_;
int diff_limit_;
long previous_servo_command_millis_;
ledc_channel_t ledc_channel_;
ledc_mode_t ledc_speed_mode_;
};
#ifndef __OSCILLATOR_H__
#define __OSCILLATOR_H__
#include "driver/ledc.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#define M_PI 3.14159265358979323846
#ifndef DEG2RAD
#define DEG2RAD(g) ((g) * M_PI) / 180
#endif
#define SERVO_MIN_PULSEWIDTH_US 500 // 最小脉宽(微秒)
#define SERVO_MAX_PULSEWIDTH_US 2500 // 最大脉宽(微秒)
#define SERVO_MIN_DEGREE -90 // 最小角度
#define SERVO_MAX_DEGREE 90 // 最大角度
#define SERVO_TIMEBASE_RESOLUTION_HZ 1000000 // 1MHz, 1us per tick
#define SERVO_TIMEBASE_PERIOD 20000 // 20000 ticks, 20ms
class Oscillator {
public:
Oscillator(int trim = 0);
~Oscillator();
void Attach(int pin, bool rev = false);
void Detach();
void SetA(unsigned int amplitude) { amplitude_ = amplitude; };
void SetO(int offset) { offset_ = offset; };
void SetPh(double Ph) { phase0_ = Ph; };
void SetT(unsigned int period);
void SetTrim(int trim) { trim_ = trim; };
void SetLimiter(int diff_limit) { diff_limit_ = diff_limit; };
void DisableLimiter() { diff_limit_ = 0; };
int GetTrim() { return trim_; };
void SetPosition(int position);
void Stop() { stop_ = true; };
void Play() { stop_ = false; };
void Reset() { phase_ = 0; };
void Refresh();
int GetPosition() { return pos_; }
private:
bool NextSample();
void Write(int position);
uint32_t AngleToCompare(int angle);
private:
bool is_attached_;
//-- Oscillators parameters
unsigned int amplitude_; //-- Amplitude (degrees)
int offset_; //-- Offset (degrees)
unsigned int period_; //-- Period (miliseconds)
double phase0_; //-- Phase (radians)
//-- Internal variables
int pos_; //-- Current servo pos
int pin_; //-- Pin where the servo is connected
int trim_; //-- Calibration offset
double phase_; //-- Current phase
double inc_; //-- Increment of phase
double number_samples_; //-- Number of samples
unsigned int sampling_period_; //-- sampling period (ms)
long previous_millis_;
long current_millis_;
//-- Oscillation mode. If true, the servo is stopped
bool stop_;
//-- Reverse mode
bool rev_;
int diff_limit_;
long previous_servo_command_millis_;
ledc_channel_t ledc_channel_;
ledc_mode_t ledc_speed_mode_;
};
#endif // __OSCILLATOR_H__

View File

@@ -1,493 +1,493 @@
/*
Otto机器人控制器 - MCP协议版本
*/
#include <cJSON.h>
#include <esp_log.h>
#include <cstring>
#include "application.h"
#include "board.h"
#include "config.h"
#include "mcp_server.h"
#include "otto_movements.h"
#include "sdkconfig.h"
#include "settings.h"
#define TAG "OttoController"
class OttoController {
private:
Otto otto_;
TaskHandle_t action_task_handle_ = nullptr;
QueueHandle_t action_queue_;
bool has_hands_ = false;
bool is_action_in_progress_ = false;
struct OttoActionParams {
int action_type;
int steps;
int speed;
int direction;
int amount;
};
enum ActionType {
ACTION_WALK = 1,
ACTION_TURN = 2,
ACTION_JUMP = 3,
ACTION_SWING = 4,
ACTION_MOONWALK = 5,
ACTION_BEND = 6,
ACTION_SHAKE_LEG = 7,
ACTION_UPDOWN = 8,
ACTION_TIPTOE_SWING = 9,
ACTION_JITTER = 10,
ACTION_ASCENDING_TURN = 11,
ACTION_CRUSAITO = 12,
ACTION_FLAPPING = 13,
ACTION_HANDS_UP = 14,
ACTION_HANDS_DOWN = 15,
ACTION_HAND_WAVE = 16,
ACTION_HOME = 17
};
static void ActionTask(void* arg) {
OttoController* controller = static_cast<OttoController*>(arg);
OttoActionParams params;
controller->otto_.AttachServos();
while (true) {
if (xQueueReceive(controller->action_queue_, &params, pdMS_TO_TICKS(1000)) == pdTRUE) {
ESP_LOGI(TAG, "执行动作: %d", params.action_type);
controller->is_action_in_progress_ = true;
switch (params.action_type) {
case ACTION_WALK:
controller->otto_.Walk(params.steps, params.speed, params.direction,
params.amount);
break;
case ACTION_TURN:
controller->otto_.Turn(params.steps, params.speed, params.direction,
params.amount);
break;
case ACTION_JUMP:
controller->otto_.Jump(params.steps, params.speed);
break;
case ACTION_SWING:
controller->otto_.Swing(params.steps, params.speed, params.amount);
break;
case ACTION_MOONWALK:
controller->otto_.Moonwalker(params.steps, params.speed, params.amount,
params.direction);
break;
case ACTION_BEND:
controller->otto_.Bend(params.steps, params.speed, params.direction);
break;
case ACTION_SHAKE_LEG:
controller->otto_.ShakeLeg(params.steps, params.speed, params.direction);
break;
case ACTION_UPDOWN:
controller->otto_.UpDown(params.steps, params.speed, params.amount);
break;
case ACTION_TIPTOE_SWING:
controller->otto_.TiptoeSwing(params.steps, params.speed, params.amount);
break;
case ACTION_JITTER:
controller->otto_.Jitter(params.steps, params.speed, params.amount);
break;
case ACTION_ASCENDING_TURN:
controller->otto_.AscendingTurn(params.steps, params.speed, params.amount);
break;
case ACTION_CRUSAITO:
controller->otto_.Crusaito(params.steps, params.speed, params.amount,
params.direction);
break;
case ACTION_FLAPPING:
controller->otto_.Flapping(params.steps, params.speed, params.amount,
params.direction);
break;
case ACTION_HANDS_UP:
if (controller->has_hands_) {
controller->otto_.HandsUp(params.speed, params.direction);
}
break;
case ACTION_HANDS_DOWN:
if (controller->has_hands_) {
controller->otto_.HandsDown(params.speed, params.direction);
}
break;
case ACTION_HAND_WAVE:
if (controller->has_hands_) {
controller->otto_.HandWave(params.speed, params.direction);
}
break;
case ACTION_HOME:
controller->otto_.Home(params.direction == 1);
break;
}
if (params.action_type != ACTION_HOME) {
controller->otto_.Home(params.action_type < ACTION_HANDS_UP);
}
controller->is_action_in_progress_ = false;
vTaskDelay(pdMS_TO_TICKS(20));
}
}
}
void StartActionTaskIfNeeded() {
if (action_task_handle_ == nullptr) {
xTaskCreate(ActionTask, "otto_action", 1024 * 3, this, configMAX_PRIORITIES - 1,
&action_task_handle_);
}
}
void QueueAction(int action_type, int steps, int speed, int direction, int amount) {
// 检查手部动作
if ((action_type >= ACTION_HANDS_UP && action_type <= ACTION_HAND_WAVE) && !has_hands_) {
ESP_LOGW(TAG, "尝试执行手部动作,但机器人没有配置手部舵机");
return;
}
ESP_LOGI(TAG, "动作控制: 类型=%d, 步数=%d, 速度=%d, 方向=%d, 幅度=%d", action_type, steps,
speed, direction, amount);
OttoActionParams params = {action_type, steps, speed, direction, amount};
xQueueSend(action_queue_, &params, portMAX_DELAY);
StartActionTaskIfNeeded();
}
void LoadTrimsFromNVS() {
Settings settings("otto_trims", false);
int left_leg = settings.GetInt("left_leg", 0);
int right_leg = settings.GetInt("right_leg", 0);
int left_foot = settings.GetInt("left_foot", 0);
int right_foot = settings.GetInt("right_foot", 0);
int left_hand = settings.GetInt("left_hand", 0);
int right_hand = settings.GetInt("right_hand", 0);
ESP_LOGI(TAG, "从NVS加载微调设置: 左腿=%d, 右腿=%d, 左脚=%d, 右脚=%d, 左手=%d, 右手=%d",
left_leg, right_leg, left_foot, right_foot, left_hand, right_hand);
otto_.SetTrims(left_leg, right_leg, left_foot, right_foot, left_hand, right_hand);
}
public:
OttoController() {
otto_.Init(LEFT_LEG_PIN, RIGHT_LEG_PIN, LEFT_FOOT_PIN, RIGHT_FOOT_PIN, LEFT_HAND_PIN,
RIGHT_HAND_PIN);
has_hands_ = (LEFT_HAND_PIN != -1 && RIGHT_HAND_PIN != -1);
ESP_LOGI(TAG, "Otto机器人初始化%s手部舵机", has_hands_ ? "" : "不带");
LoadTrimsFromNVS();
action_queue_ = xQueueCreate(10, sizeof(OttoActionParams));
QueueAction(ACTION_HOME, 1, 1000, 1, 0); // direction=1表示复位手部
RegisterMcpTools();
}
void RegisterMcpTools() {
auto& mcp_server = McpServer::GetInstance();
ESP_LOGI(TAG, "开始注册MCP工具...");
// 基础移动动作
mcp_server.AddTool("self.otto.walk_forward",
"行走。steps: 行走步数(1-100); speed: 行走速度(500-1500数值越小越快); "
"direction: 行走方向(-1=后退, 1=前进); arm_swing: 手臂摆动幅度(0-170度)",
PropertyList({Property("steps", kPropertyTypeInteger, 3, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("arm_swing", kPropertyTypeInteger, 50, 0, 170),
Property("direction", kPropertyTypeInteger, 1, -1, 1)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
int arm_swing = properties["arm_swing"].value<int>();
int direction = properties["direction"].value<int>();
QueueAction(ACTION_WALK, steps, speed, direction, arm_swing);
return true;
});
mcp_server.AddTool("self.otto.turn_left",
"转身。steps: 转身步数(1-100); speed: 转身速度(500-1500数值越小越快); "
"direction: 转身方向(1=左转, -1=右转); arm_swing: 手臂摆动幅度(0-170度)",
PropertyList({Property("steps", kPropertyTypeInteger, 3, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("arm_swing", kPropertyTypeInteger, 50, 0, 170),
Property("direction", kPropertyTypeInteger, 1, -1, 1)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
int arm_swing = properties["arm_swing"].value<int>();
int direction = properties["direction"].value<int>();
QueueAction(ACTION_TURN, steps, speed, direction, arm_swing);
return true;
});
mcp_server.AddTool("self.otto.jump",
"跳跃。steps: 跳跃次数(1-100); speed: 跳跃速度(500-1500数值越小越快)",
PropertyList({Property("steps", kPropertyTypeInteger, 1, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
QueueAction(ACTION_JUMP, steps, speed, 0, 0);
return true;
});
// 特殊动作
mcp_server.AddTool("self.otto.swing",
"左右摇摆。steps: 摇摆次数(1-100); speed: "
"摇摆速度(500-1500数值越小越快); amount: 摇摆幅度(0-170度)",
PropertyList({Property("steps", kPropertyTypeInteger, 3, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("amount", kPropertyTypeInteger, 30, 0, 170)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
int amount = properties["amount"].value<int>();
QueueAction(ACTION_SWING, steps, speed, 0, amount);
return true;
});
mcp_server.AddTool("self.otto.moonwalk",
"太空步。steps: 太空步步数(1-100); speed: 速度(500-1500数值越小越快); "
"direction: 方向(1=左, -1=右); amount: 幅度(0-170度)",
PropertyList({Property("steps", kPropertyTypeInteger, 3, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("direction", kPropertyTypeInteger, 1, -1, 1),
Property("amount", kPropertyTypeInteger, 25, 0, 170)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
int direction = properties["direction"].value<int>();
int amount = properties["amount"].value<int>();
QueueAction(ACTION_MOONWALK, steps, speed, direction, amount);
return true;
});
mcp_server.AddTool("self.otto.bend",
"弯曲身体。steps: 弯曲次数(1-100); speed: "
"弯曲速度(500-1500数值越小越快); direction: 弯曲方向(1=左, -1=右)",
PropertyList({Property("steps", kPropertyTypeInteger, 1, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("direction", kPropertyTypeInteger, 1, -1, 1)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
int direction = properties["direction"].value<int>();
QueueAction(ACTION_BEND, steps, speed, direction, 0);
return true;
});
mcp_server.AddTool("self.otto.shake_leg",
"摇腿。steps: 摇腿次数(1-100); speed: 摇腿速度(500-1500数值越小越快); "
"direction: 腿部选择(1=左腿, -1=右腿)",
PropertyList({Property("steps", kPropertyTypeInteger, 1, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("direction", kPropertyTypeInteger, 1, -1, 1)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
int direction = properties["direction"].value<int>();
QueueAction(ACTION_SHAKE_LEG, steps, speed, direction, 0);
return true;
});
mcp_server.AddTool("self.otto.updown",
"上下运动。steps: 上下运动次数(1-100); speed: "
"运动速度(500-1500数值越小越快); amount: 运动幅度(0-170度)",
PropertyList({Property("steps", kPropertyTypeInteger, 3, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("amount", kPropertyTypeInteger, 20, 0, 170)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
int amount = properties["amount"].value<int>();
QueueAction(ACTION_UPDOWN, steps, speed, 0, amount);
return true;
});
// 手部动作(仅在有手部舵机时可用)
if (has_hands_) {
mcp_server.AddTool(
"self.otto.hands_up",
"举手。speed: 举手速度(500-1500数值越小越快); direction: 手部选择(1=左手, "
"-1=右手, 0=双手)",
PropertyList({Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("direction", kPropertyTypeInteger, 1, -1, 1)}),
[this](const PropertyList& properties) -> ReturnValue {
int speed = properties["speed"].value<int>();
int direction = properties["direction"].value<int>();
QueueAction(ACTION_HANDS_UP, 1, speed, direction, 0);
return true;
});
mcp_server.AddTool(
"self.otto.hands_down",
"放手。speed: 放手速度(500-1500数值越小越快); direction: 手部选择(1=左手, "
"-1=右手, 0=双手)",
PropertyList({Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("direction", kPropertyTypeInteger, 1, -1, 1)}),
[this](const PropertyList& properties) -> ReturnValue {
int speed = properties["speed"].value<int>();
int direction = properties["direction"].value<int>();
QueueAction(ACTION_HANDS_DOWN, 1, speed, direction, 0);
return true;
});
mcp_server.AddTool(
"self.otto.hand_wave",
"挥手。speed: 挥手速度(500-1500数值越小越快); direction: 手部选择(1=左手, "
"-1=右手, 0=双手)",
PropertyList({Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("direction", kPropertyTypeInteger, 1, -1, 1)}),
[this](const PropertyList& properties) -> ReturnValue {
int speed = properties["speed"].value<int>();
int direction = properties["direction"].value<int>();
QueueAction(ACTION_HAND_WAVE, 1, speed, direction, 0);
return true;
});
}
// 系统工具
mcp_server.AddTool("self.otto.stop", "立即停止", PropertyList(),
[this](const PropertyList& properties) -> ReturnValue {
if (action_task_handle_ != nullptr) {
vTaskDelete(action_task_handle_);
action_task_handle_ = nullptr;
}
is_action_in_progress_ = false;
xQueueReset(action_queue_);
QueueAction(ACTION_HOME, 1, 1000, 1, 0);
return true;
});
mcp_server.AddTool(
"self.otto.set_trim",
"校准单个舵机位置。设置指定舵机的微调参数以调整Otto的初始站立姿态设置将永久保存。"
"servo_type: 舵机类型(left_leg/right_leg/left_foot/right_foot/left_hand/right_hand); "
"trim_value: 微调值(-50到50度)",
PropertyList({Property("servo_type", kPropertyTypeString, "left_leg"),
Property("trim_value", kPropertyTypeInteger, 0, -50, 50)}),
[this](const PropertyList& properties) -> ReturnValue {
std::string servo_type = properties["servo_type"].value<std::string>();
int trim_value = properties["trim_value"].value<int>();
ESP_LOGI(TAG, "设置舵机微调: %s = %d度", servo_type.c_str(), trim_value);
// 获取当前所有微调值
Settings settings("otto_trims", true);
int left_leg = settings.GetInt("left_leg", 0);
int right_leg = settings.GetInt("right_leg", 0);
int left_foot = settings.GetInt("left_foot", 0);
int right_foot = settings.GetInt("right_foot", 0);
int left_hand = settings.GetInt("left_hand", 0);
int right_hand = settings.GetInt("right_hand", 0);
// 更新指定舵机的微调值
if (servo_type == "left_leg") {
left_leg = trim_value;
settings.SetInt("left_leg", left_leg);
} else if (servo_type == "right_leg") {
right_leg = trim_value;
settings.SetInt("right_leg", right_leg);
} else if (servo_type == "left_foot") {
left_foot = trim_value;
settings.SetInt("left_foot", left_foot);
} else if (servo_type == "right_foot") {
right_foot = trim_value;
settings.SetInt("right_foot", right_foot);
} else if (servo_type == "left_hand") {
if (!has_hands_) {
return "错误:机器人没有配置手部舵机";
}
left_hand = trim_value;
settings.SetInt("left_hand", left_hand);
} else if (servo_type == "right_hand") {
if (!has_hands_) {
return "错误:机器人没有配置手部舵机";
}
right_hand = trim_value;
settings.SetInt("right_hand", right_hand);
} else {
return "错误:无效的舵机类型,请使用: left_leg, right_leg, left_foot, "
"right_foot, left_hand, right_hand";
}
otto_.SetTrims(left_leg, right_leg, left_foot, right_foot, left_hand, right_hand);
QueueAction(ACTION_JUMP, 1, 500, 0, 0);
return "舵机 " + servo_type + " 微调设置为 " + std::to_string(trim_value) +
" 度,已永久保存";
});
mcp_server.AddTool("self.otto.get_trims", "获取当前的舵机微调设置", PropertyList(),
[this](const PropertyList& properties) -> ReturnValue {
Settings settings("otto_trims", false);
int left_leg = settings.GetInt("left_leg", 0);
int right_leg = settings.GetInt("right_leg", 0);
int left_foot = settings.GetInt("left_foot", 0);
int right_foot = settings.GetInt("right_foot", 0);
int left_hand = settings.GetInt("left_hand", 0);
int right_hand = settings.GetInt("right_hand", 0);
std::string result =
"{\"left_leg\":" + std::to_string(left_leg) +
",\"right_leg\":" + std::to_string(right_leg) +
",\"left_foot\":" + std::to_string(left_foot) +
",\"right_foot\":" + std::to_string(right_foot) +
",\"left_hand\":" + std::to_string(left_hand) +
",\"right_hand\":" + std::to_string(right_hand) + "}";
ESP_LOGI(TAG, "获取微调设置: %s", result.c_str());
return result;
});
mcp_server.AddTool("self.otto.get_status", "获取机器人状态,返回 moving 或 idle",
PropertyList(), [this](const PropertyList& properties) -> ReturnValue {
return is_action_in_progress_ ? "moving" : "idle";
});
mcp_server.AddTool("self.battery.get_level", "获取机器人电池电量和充电状态", PropertyList(),
[](const PropertyList& properties) -> ReturnValue {
auto& board = Board::GetInstance();
int level = 0;
bool charging = false;
bool discharging = false;
board.GetBatteryLevel(level, charging, discharging);
std::string status =
"{\"level\":" + std::to_string(level) +
",\"charging\":" + (charging ? "true" : "false") + "}";
return status;
});
ESP_LOGI(TAG, "MCP工具注册完成");
}
~OttoController() {
if (action_task_handle_ != nullptr) {
vTaskDelete(action_task_handle_);
action_task_handle_ = nullptr;
}
vQueueDelete(action_queue_);
}
};
static OttoController* g_otto_controller = nullptr;
void InitializeOttoController() {
if (g_otto_controller == nullptr) {
g_otto_controller = new OttoController();
ESP_LOGI(TAG, "Otto控制器已初始化并注册MCP工具");
}
}
/*
Otto机器人控制器 - MCP协议版本
*/
#include <cJSON.h>
#include <esp_log.h>
#include <cstring>
#include "application.h"
#include "board.h"
#include "config.h"
#include "mcp_server.h"
#include "otto_movements.h"
#include "sdkconfig.h"
#include "settings.h"
#define TAG "OttoController"
class OttoController {
private:
Otto otto_;
TaskHandle_t action_task_handle_ = nullptr;
QueueHandle_t action_queue_;
bool has_hands_ = false;
bool is_action_in_progress_ = false;
struct OttoActionParams {
int action_type;
int steps;
int speed;
int direction;
int amount;
};
enum ActionType {
ACTION_WALK = 1,
ACTION_TURN = 2,
ACTION_JUMP = 3,
ACTION_SWING = 4,
ACTION_MOONWALK = 5,
ACTION_BEND = 6,
ACTION_SHAKE_LEG = 7,
ACTION_UPDOWN = 8,
ACTION_TIPTOE_SWING = 9,
ACTION_JITTER = 10,
ACTION_ASCENDING_TURN = 11,
ACTION_CRUSAITO = 12,
ACTION_FLAPPING = 13,
ACTION_HANDS_UP = 14,
ACTION_HANDS_DOWN = 15,
ACTION_HAND_WAVE = 16,
ACTION_HOME = 17
};
static void ActionTask(void* arg) {
OttoController* controller = static_cast<OttoController*>(arg);
OttoActionParams params;
controller->otto_.AttachServos();
while (true) {
if (xQueueReceive(controller->action_queue_, &params, pdMS_TO_TICKS(1000)) == pdTRUE) {
ESP_LOGI(TAG, "执行动作: %d", params.action_type);
controller->is_action_in_progress_ = true;
switch (params.action_type) {
case ACTION_WALK:
controller->otto_.Walk(params.steps, params.speed, params.direction,
params.amount);
break;
case ACTION_TURN:
controller->otto_.Turn(params.steps, params.speed, params.direction,
params.amount);
break;
case ACTION_JUMP:
controller->otto_.Jump(params.steps, params.speed);
break;
case ACTION_SWING:
controller->otto_.Swing(params.steps, params.speed, params.amount);
break;
case ACTION_MOONWALK:
controller->otto_.Moonwalker(params.steps, params.speed, params.amount,
params.direction);
break;
case ACTION_BEND:
controller->otto_.Bend(params.steps, params.speed, params.direction);
break;
case ACTION_SHAKE_LEG:
controller->otto_.ShakeLeg(params.steps, params.speed, params.direction);
break;
case ACTION_UPDOWN:
controller->otto_.UpDown(params.steps, params.speed, params.amount);
break;
case ACTION_TIPTOE_SWING:
controller->otto_.TiptoeSwing(params.steps, params.speed, params.amount);
break;
case ACTION_JITTER:
controller->otto_.Jitter(params.steps, params.speed, params.amount);
break;
case ACTION_ASCENDING_TURN:
controller->otto_.AscendingTurn(params.steps, params.speed, params.amount);
break;
case ACTION_CRUSAITO:
controller->otto_.Crusaito(params.steps, params.speed, params.amount,
params.direction);
break;
case ACTION_FLAPPING:
controller->otto_.Flapping(params.steps, params.speed, params.amount,
params.direction);
break;
case ACTION_HANDS_UP:
if (controller->has_hands_) {
controller->otto_.HandsUp(params.speed, params.direction);
}
break;
case ACTION_HANDS_DOWN:
if (controller->has_hands_) {
controller->otto_.HandsDown(params.speed, params.direction);
}
break;
case ACTION_HAND_WAVE:
if (controller->has_hands_) {
controller->otto_.HandWave(params.speed, params.direction);
}
break;
case ACTION_HOME:
controller->otto_.Home(params.direction == 1);
break;
}
if (params.action_type != ACTION_HOME) {
controller->otto_.Home(params.action_type < ACTION_HANDS_UP);
}
controller->is_action_in_progress_ = false;
vTaskDelay(pdMS_TO_TICKS(20));
}
}
}
void StartActionTaskIfNeeded() {
if (action_task_handle_ == nullptr) {
xTaskCreate(ActionTask, "otto_action", 1024 * 3, this, configMAX_PRIORITIES - 1,
&action_task_handle_);
}
}
void QueueAction(int action_type, int steps, int speed, int direction, int amount) {
// 检查手部动作
if ((action_type >= ACTION_HANDS_UP && action_type <= ACTION_HAND_WAVE) && !has_hands_) {
ESP_LOGW(TAG, "尝试执行手部动作,但机器人没有配置手部舵机");
return;
}
ESP_LOGI(TAG, "动作控制: 类型=%d, 步数=%d, 速度=%d, 方向=%d, 幅度=%d", action_type, steps,
speed, direction, amount);
OttoActionParams params = {action_type, steps, speed, direction, amount};
xQueueSend(action_queue_, &params, portMAX_DELAY);
StartActionTaskIfNeeded();
}
void LoadTrimsFromNVS() {
Settings settings("otto_trims", false);
int left_leg = settings.GetInt("left_leg", 0);
int right_leg = settings.GetInt("right_leg", 0);
int left_foot = settings.GetInt("left_foot", 0);
int right_foot = settings.GetInt("right_foot", 0);
int left_hand = settings.GetInt("left_hand", 0);
int right_hand = settings.GetInt("right_hand", 0);
ESP_LOGI(TAG, "从NVS加载微调设置: 左腿=%d, 右腿=%d, 左脚=%d, 右脚=%d, 左手=%d, 右手=%d",
left_leg, right_leg, left_foot, right_foot, left_hand, right_hand);
otto_.SetTrims(left_leg, right_leg, left_foot, right_foot, left_hand, right_hand);
}
public:
OttoController() {
otto_.Init(LEFT_LEG_PIN, RIGHT_LEG_PIN, LEFT_FOOT_PIN, RIGHT_FOOT_PIN, LEFT_HAND_PIN,
RIGHT_HAND_PIN);
has_hands_ = (LEFT_HAND_PIN != -1 && RIGHT_HAND_PIN != -1);
ESP_LOGI(TAG, "Otto机器人初始化%s手部舵机", has_hands_ ? "" : "不带");
LoadTrimsFromNVS();
action_queue_ = xQueueCreate(10, sizeof(OttoActionParams));
QueueAction(ACTION_HOME, 1, 1000, 1, 0); // direction=1表示复位手部
RegisterMcpTools();
}
void RegisterMcpTools() {
auto& mcp_server = McpServer::GetInstance();
ESP_LOGI(TAG, "开始注册MCP工具...");
// 基础移动动作
mcp_server.AddTool("self.otto.walk_forward",
"行走。steps: 行走步数(1-100); speed: 行走速度(500-1500数值越小越快); "
"direction: 行走方向(-1=后退, 1=前进); arm_swing: 手臂摆动幅度(0-170度)",
PropertyList({Property("steps", kPropertyTypeInteger, 3, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("arm_swing", kPropertyTypeInteger, 50, 0, 170),
Property("direction", kPropertyTypeInteger, 1, -1, 1)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
int arm_swing = properties["arm_swing"].value<int>();
int direction = properties["direction"].value<int>();
QueueAction(ACTION_WALK, steps, speed, direction, arm_swing);
return true;
});
mcp_server.AddTool("self.otto.turn_left",
"转身。steps: 转身步数(1-100); speed: 转身速度(500-1500数值越小越快); "
"direction: 转身方向(1=左转, -1=右转); arm_swing: 手臂摆动幅度(0-170度)",
PropertyList({Property("steps", kPropertyTypeInteger, 3, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("arm_swing", kPropertyTypeInteger, 50, 0, 170),
Property("direction", kPropertyTypeInteger, 1, -1, 1)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
int arm_swing = properties["arm_swing"].value<int>();
int direction = properties["direction"].value<int>();
QueueAction(ACTION_TURN, steps, speed, direction, arm_swing);
return true;
});
mcp_server.AddTool("self.otto.jump",
"跳跃。steps: 跳跃次数(1-100); speed: 跳跃速度(500-1500数值越小越快)",
PropertyList({Property("steps", kPropertyTypeInteger, 1, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
QueueAction(ACTION_JUMP, steps, speed, 0, 0);
return true;
});
// 特殊动作
mcp_server.AddTool("self.otto.swing",
"左右摇摆。steps: 摇摆次数(1-100); speed: "
"摇摆速度(500-1500数值越小越快); amount: 摇摆幅度(0-170度)",
PropertyList({Property("steps", kPropertyTypeInteger, 3, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("amount", kPropertyTypeInteger, 30, 0, 170)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
int amount = properties["amount"].value<int>();
QueueAction(ACTION_SWING, steps, speed, 0, amount);
return true;
});
mcp_server.AddTool("self.otto.moonwalk",
"太空步。steps: 太空步步数(1-100); speed: 速度(500-1500数值越小越快); "
"direction: 方向(1=左, -1=右); amount: 幅度(0-170度)",
PropertyList({Property("steps", kPropertyTypeInteger, 3, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("direction", kPropertyTypeInteger, 1, -1, 1),
Property("amount", kPropertyTypeInteger, 25, 0, 170)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
int direction = properties["direction"].value<int>();
int amount = properties["amount"].value<int>();
QueueAction(ACTION_MOONWALK, steps, speed, direction, amount);
return true;
});
mcp_server.AddTool("self.otto.bend",
"弯曲身体。steps: 弯曲次数(1-100); speed: "
"弯曲速度(500-1500数值越小越快); direction: 弯曲方向(1=左, -1=右)",
PropertyList({Property("steps", kPropertyTypeInteger, 1, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("direction", kPropertyTypeInteger, 1, -1, 1)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
int direction = properties["direction"].value<int>();
QueueAction(ACTION_BEND, steps, speed, direction, 0);
return true;
});
mcp_server.AddTool("self.otto.shake_leg",
"摇腿。steps: 摇腿次数(1-100); speed: 摇腿速度(500-1500数值越小越快); "
"direction: 腿部选择(1=左腿, -1=右腿)",
PropertyList({Property("steps", kPropertyTypeInteger, 1, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("direction", kPropertyTypeInteger, 1, -1, 1)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
int direction = properties["direction"].value<int>();
QueueAction(ACTION_SHAKE_LEG, steps, speed, direction, 0);
return true;
});
mcp_server.AddTool("self.otto.updown",
"上下运动。steps: 上下运动次数(1-100); speed: "
"运动速度(500-1500数值越小越快); amount: 运动幅度(0-170度)",
PropertyList({Property("steps", kPropertyTypeInteger, 3, 1, 100),
Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("amount", kPropertyTypeInteger, 20, 0, 170)}),
[this](const PropertyList& properties) -> ReturnValue {
int steps = properties["steps"].value<int>();
int speed = properties["speed"].value<int>();
int amount = properties["amount"].value<int>();
QueueAction(ACTION_UPDOWN, steps, speed, 0, amount);
return true;
});
// 手部动作(仅在有手部舵机时可用)
if (has_hands_) {
mcp_server.AddTool(
"self.otto.hands_up",
"举手。speed: 举手速度(500-1500数值越小越快); direction: 手部选择(1=左手, "
"-1=右手, 0=双手)",
PropertyList({Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("direction", kPropertyTypeInteger, 1, -1, 1)}),
[this](const PropertyList& properties) -> ReturnValue {
int speed = properties["speed"].value<int>();
int direction = properties["direction"].value<int>();
QueueAction(ACTION_HANDS_UP, 1, speed, direction, 0);
return true;
});
mcp_server.AddTool(
"self.otto.hands_down",
"放手。speed: 放手速度(500-1500数值越小越快); direction: 手部选择(1=左手, "
"-1=右手, 0=双手)",
PropertyList({Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("direction", kPropertyTypeInteger, 1, -1, 1)}),
[this](const PropertyList& properties) -> ReturnValue {
int speed = properties["speed"].value<int>();
int direction = properties["direction"].value<int>();
QueueAction(ACTION_HANDS_DOWN, 1, speed, direction, 0);
return true;
});
mcp_server.AddTool(
"self.otto.hand_wave",
"挥手。speed: 挥手速度(500-1500数值越小越快); direction: 手部选择(1=左手, "
"-1=右手, 0=双手)",
PropertyList({Property("speed", kPropertyTypeInteger, 1000, 500, 1500),
Property("direction", kPropertyTypeInteger, 1, -1, 1)}),
[this](const PropertyList& properties) -> ReturnValue {
int speed = properties["speed"].value<int>();
int direction = properties["direction"].value<int>();
QueueAction(ACTION_HAND_WAVE, 1, speed, direction, 0);
return true;
});
}
// 系统工具
mcp_server.AddTool("self.otto.stop", "立即停止", PropertyList(),
[this](const PropertyList& properties) -> ReturnValue {
if (action_task_handle_ != nullptr) {
vTaskDelete(action_task_handle_);
action_task_handle_ = nullptr;
}
is_action_in_progress_ = false;
xQueueReset(action_queue_);
QueueAction(ACTION_HOME, 1, 1000, 1, 0);
return true;
});
mcp_server.AddTool(
"self.otto.set_trim",
"校准单个舵机位置。设置指定舵机的微调参数以调整Otto的初始站立姿态设置将永久保存。"
"servo_type: 舵机类型(left_leg/right_leg/left_foot/right_foot/left_hand/right_hand); "
"trim_value: 微调值(-50到50度)",
PropertyList({Property("servo_type", kPropertyTypeString, "left_leg"),
Property("trim_value", kPropertyTypeInteger, 0, -50, 50)}),
[this](const PropertyList& properties) -> ReturnValue {
std::string servo_type = properties["servo_type"].value<std::string>();
int trim_value = properties["trim_value"].value<int>();
ESP_LOGI(TAG, "设置舵机微调: %s = %d度", servo_type.c_str(), trim_value);
// 获取当前所有微调值
Settings settings("otto_trims", true);
int left_leg = settings.GetInt("left_leg", 0);
int right_leg = settings.GetInt("right_leg", 0);
int left_foot = settings.GetInt("left_foot", 0);
int right_foot = settings.GetInt("right_foot", 0);
int left_hand = settings.GetInt("left_hand", 0);
int right_hand = settings.GetInt("right_hand", 0);
// 更新指定舵机的微调值
if (servo_type == "left_leg") {
left_leg = trim_value;
settings.SetInt("left_leg", left_leg);
} else if (servo_type == "right_leg") {
right_leg = trim_value;
settings.SetInt("right_leg", right_leg);
} else if (servo_type == "left_foot") {
left_foot = trim_value;
settings.SetInt("left_foot", left_foot);
} else if (servo_type == "right_foot") {
right_foot = trim_value;
settings.SetInt("right_foot", right_foot);
} else if (servo_type == "left_hand") {
if (!has_hands_) {
return "错误:机器人没有配置手部舵机";
}
left_hand = trim_value;
settings.SetInt("left_hand", left_hand);
} else if (servo_type == "right_hand") {
if (!has_hands_) {
return "错误:机器人没有配置手部舵机";
}
right_hand = trim_value;
settings.SetInt("right_hand", right_hand);
} else {
return "错误:无效的舵机类型,请使用: left_leg, right_leg, left_foot, "
"right_foot, left_hand, right_hand";
}
otto_.SetTrims(left_leg, right_leg, left_foot, right_foot, left_hand, right_hand);
QueueAction(ACTION_JUMP, 1, 500, 0, 0);
return "舵机 " + servo_type + " 微调设置为 " + std::to_string(trim_value) +
" 度,已永久保存";
});
mcp_server.AddTool("self.otto.get_trims", "获取当前的舵机微调设置", PropertyList(),
[this](const PropertyList& properties) -> ReturnValue {
Settings settings("otto_trims", false);
int left_leg = settings.GetInt("left_leg", 0);
int right_leg = settings.GetInt("right_leg", 0);
int left_foot = settings.GetInt("left_foot", 0);
int right_foot = settings.GetInt("right_foot", 0);
int left_hand = settings.GetInt("left_hand", 0);
int right_hand = settings.GetInt("right_hand", 0);
std::string result =
"{\"left_leg\":" + std::to_string(left_leg) +
",\"right_leg\":" + std::to_string(right_leg) +
",\"left_foot\":" + std::to_string(left_foot) +
",\"right_foot\":" + std::to_string(right_foot) +
",\"left_hand\":" + std::to_string(left_hand) +
",\"right_hand\":" + std::to_string(right_hand) + "}";
ESP_LOGI(TAG, "获取微调设置: %s", result.c_str());
return result;
});
mcp_server.AddTool("self.otto.get_status", "获取机器人状态,返回 moving 或 idle",
PropertyList(), [this](const PropertyList& properties) -> ReturnValue {
return is_action_in_progress_ ? "moving" : "idle";
});
mcp_server.AddTool("self.battery.get_level", "获取机器人电池电量和充电状态", PropertyList(),
[](const PropertyList& properties) -> ReturnValue {
auto& board = Board::GetInstance();
int level = 0;
bool charging = false;
bool discharging = false;
board.GetBatteryLevel(level, charging, discharging);
std::string status =
"{\"level\":" + std::to_string(level) +
",\"charging\":" + (charging ? "true" : "false") + "}";
return status;
});
ESP_LOGI(TAG, "MCP工具注册完成");
}
~OttoController() {
if (action_task_handle_ != nullptr) {
vTaskDelete(action_task_handle_);
action_task_handle_ = nullptr;
}
vQueueDelete(action_queue_);
}
};
static OttoController* g_otto_controller = nullptr;
void InitializeOttoController() {
if (g_otto_controller == nullptr) {
g_otto_controller = new OttoController();
ESP_LOGI(TAG, "Otto控制器已初始化并注册MCP工具");
}
}

View File

@@ -1,152 +1,152 @@
#include "otto_emoji_display.h"
#include "lvgl_theme.h"
#include <esp_log.h>
#include <font_awesome.h>
#include <algorithm>
#include <cstring>
#include <string>
#include "display/lcd_display.h"
#define TAG "OttoEmojiDisplay"
// 表情映射表 - 将原版21种表情映射到现有6个GIF
const OttoEmojiDisplay::EmotionMap OttoEmojiDisplay::emotion_maps_[] = {
// 中性/平静类表情 -> staticstate
{"neutral", &staticstate},
{"relaxed", &staticstate},
{"sleepy", &staticstate},
// 积极/开心类表情 -> happy
{"happy", &happy},
{"laughing", &happy},
{"funny", &happy},
{"loving", &happy},
{"confident", &happy},
{"winking", &happy},
{"cool", &happy},
{"delicious", &happy},
{"kissy", &happy},
{"silly", &happy},
// 悲伤类表情 -> sad
{"sad", &sad},
{"crying", &sad},
// 愤怒类表情 -> anger
{"angry", &anger},
// 惊讶类表情 -> scare
{"surprised", &scare},
{"shocked", &scare},
// 思考/困惑类表情 -> buxue
{"thinking", &buxue},
{"confused", &buxue},
{"embarrassed", &buxue},
{nullptr, nullptr} // 结束标记
};
OttoEmojiDisplay::OttoEmojiDisplay(esp_lcd_panel_io_handle_t panel_io, esp_lcd_panel_handle_t panel,
int width, int height, int offset_x, int offset_y, bool mirror_x,
bool mirror_y, bool swap_xy)
: SpiLcdDisplay(panel_io, panel, width, height, offset_x, offset_y, mirror_x, mirror_y, swap_xy),
emotion_gif_(nullptr) {
SetupGifContainer();
};
void OttoEmojiDisplay::SetupGifContainer() {
DisplayLockGuard lock(this);
if (emoji_label_) {
lv_obj_del(emoji_label_);
}
if (chat_message_label_) {
lv_obj_del(chat_message_label_);
}
if (content_) {
lv_obj_del(content_);
}
content_ = lv_obj_create(container_);
lv_obj_set_scrollbar_mode(content_, LV_SCROLLBAR_MODE_OFF);
lv_obj_set_size(content_, LV_HOR_RES, LV_HOR_RES);
lv_obj_set_style_bg_opa(content_, LV_OPA_TRANSP, 0);
lv_obj_set_style_border_width(content_, 0, 0);
lv_obj_set_flex_grow(content_, 1);
lv_obj_center(content_);
emoji_label_ = lv_label_create(content_);
lv_label_set_text(emoji_label_, "");
lv_obj_set_width(emoji_label_, 0);
lv_obj_set_style_border_width(emoji_label_, 0, 0);
lv_obj_add_flag(emoji_label_, LV_OBJ_FLAG_HIDDEN);
emotion_gif_ = lv_gif_create(content_);
int gif_size = LV_HOR_RES;
lv_obj_set_size(emotion_gif_, gif_size, gif_size);
lv_obj_set_style_border_width(emotion_gif_, 0, 0);
lv_obj_set_style_bg_opa(emotion_gif_, LV_OPA_TRANSP, 0);
lv_obj_center(emotion_gif_);
lv_gif_set_src(emotion_gif_, &staticstate);
chat_message_label_ = lv_label_create(content_);
lv_label_set_text(chat_message_label_, "");
lv_obj_set_width(chat_message_label_, LV_HOR_RES * 0.9);
lv_label_set_long_mode(chat_message_label_, LV_LABEL_LONG_SCROLL_CIRCULAR);
lv_obj_set_style_text_align(chat_message_label_, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_style_text_color(chat_message_label_, lv_color_white(), 0);
lv_obj_set_style_border_width(chat_message_label_, 0, 0);
lv_obj_set_style_bg_opa(chat_message_label_, LV_OPA_70, 0);
lv_obj_set_style_bg_color(chat_message_label_, lv_color_black(), 0);
lv_obj_set_style_pad_ver(chat_message_label_, 5, 0);
lv_obj_align(chat_message_label_, LV_ALIGN_BOTTOM_MID, 0, 0);
auto& theme_manager = LvglThemeManager::GetInstance();
auto theme = theme_manager.GetTheme("dark");
if (theme != nullptr) {
LcdDisplay::SetTheme(theme);
}
}
void OttoEmojiDisplay::SetEmotion(const char* emotion) {
if (!emotion || !emotion_gif_) {
return;
}
DisplayLockGuard lock(this);
for (const auto& map : emotion_maps_) {
if (map.name && strcmp(map.name, emotion) == 0) {
lv_gif_set_src(emotion_gif_, map.gif);
ESP_LOGI(TAG, "设置表情: %s", emotion);
return;
}
}
lv_gif_set_src(emotion_gif_, &staticstate);
ESP_LOGI(TAG, "未知表情'%s',使用默认", emotion);
}
void OttoEmojiDisplay::SetChatMessage(const char* role, const char* content) {
DisplayLockGuard lock(this);
if (chat_message_label_ == nullptr) {
return;
}
if (content == nullptr || strlen(content) == 0) {
lv_obj_add_flag(chat_message_label_, LV_OBJ_FLAG_HIDDEN);
return;
}
lv_label_set_text(chat_message_label_, content);
lv_obj_remove_flag(chat_message_label_, LV_OBJ_FLAG_HIDDEN);
ESP_LOGI(TAG, "设置聊天消息 [%s]: %s", role, content);
}
#include "otto_emoji_display.h"
#include "lvgl_theme.h"
#include <esp_log.h>
#include <font_awesome.h>
#include <algorithm>
#include <cstring>
#include <string>
#include "display/lcd_display.h"
#define TAG "OttoEmojiDisplay"
// 表情映射表 - 将原版21种表情映射到现有6个GIF
const OttoEmojiDisplay::EmotionMap OttoEmojiDisplay::emotion_maps_[] = {
// 中性/平静类表情 -> staticstate
{"neutral", &staticstate},
{"relaxed", &staticstate},
{"sleepy", &staticstate},
// 积极/开心类表情 -> happy
{"happy", &happy},
{"laughing", &happy},
{"funny", &happy},
{"loving", &happy},
{"confident", &happy},
{"winking", &happy},
{"cool", &happy},
{"delicious", &happy},
{"kissy", &happy},
{"silly", &happy},
// 悲伤类表情 -> sad
{"sad", &sad},
{"crying", &sad},
// 愤怒类表情 -> anger
{"angry", &anger},
// 惊讶类表情 -> scare
{"surprised", &scare},
{"shocked", &scare},
// 思考/困惑类表情 -> buxue
{"thinking", &buxue},
{"confused", &buxue},
{"embarrassed", &buxue},
{nullptr, nullptr} // 结束标记
};
OttoEmojiDisplay::OttoEmojiDisplay(esp_lcd_panel_io_handle_t panel_io, esp_lcd_panel_handle_t panel,
int width, int height, int offset_x, int offset_y, bool mirror_x,
bool mirror_y, bool swap_xy)
: SpiLcdDisplay(panel_io, panel, width, height, offset_x, offset_y, mirror_x, mirror_y, swap_xy),
emotion_gif_(nullptr) {
SetupGifContainer();
};
void OttoEmojiDisplay::SetupGifContainer() {
DisplayLockGuard lock(this);
if (emoji_label_) {
lv_obj_del(emoji_label_);
}
if (chat_message_label_) {
lv_obj_del(chat_message_label_);
}
if (content_) {
lv_obj_del(content_);
}
content_ = lv_obj_create(container_);
lv_obj_set_scrollbar_mode(content_, LV_SCROLLBAR_MODE_OFF);
lv_obj_set_size(content_, LV_HOR_RES, LV_HOR_RES);
lv_obj_set_style_bg_opa(content_, LV_OPA_TRANSP, 0);
lv_obj_set_style_border_width(content_, 0, 0);
lv_obj_set_flex_grow(content_, 1);
lv_obj_center(content_);
emoji_label_ = lv_label_create(content_);
lv_label_set_text(emoji_label_, "");
lv_obj_set_width(emoji_label_, 0);
lv_obj_set_style_border_width(emoji_label_, 0, 0);
lv_obj_add_flag(emoji_label_, LV_OBJ_FLAG_HIDDEN);
emotion_gif_ = lv_gif_create(content_);
int gif_size = LV_HOR_RES;
lv_obj_set_size(emotion_gif_, gif_size, gif_size);
lv_obj_set_style_border_width(emotion_gif_, 0, 0);
lv_obj_set_style_bg_opa(emotion_gif_, LV_OPA_TRANSP, 0);
lv_obj_center(emotion_gif_);
lv_gif_set_src(emotion_gif_, &staticstate);
chat_message_label_ = lv_label_create(content_);
lv_label_set_text(chat_message_label_, "");
lv_obj_set_width(chat_message_label_, LV_HOR_RES * 0.9);
lv_label_set_long_mode(chat_message_label_, LV_LABEL_LONG_SCROLL_CIRCULAR);
lv_obj_set_style_text_align(chat_message_label_, LV_TEXT_ALIGN_CENTER, 0);
lv_obj_set_style_text_color(chat_message_label_, lv_color_white(), 0);
lv_obj_set_style_border_width(chat_message_label_, 0, 0);
lv_obj_set_style_bg_opa(chat_message_label_, LV_OPA_70, 0);
lv_obj_set_style_bg_color(chat_message_label_, lv_color_black(), 0);
lv_obj_set_style_pad_ver(chat_message_label_, 5, 0);
lv_obj_align(chat_message_label_, LV_ALIGN_BOTTOM_MID, 0, 0);
auto& theme_manager = LvglThemeManager::GetInstance();
auto theme = theme_manager.GetTheme("dark");
if (theme != nullptr) {
LcdDisplay::SetTheme(theme);
}
}
void OttoEmojiDisplay::SetEmotion(const char* emotion) {
if (!emotion || !emotion_gif_) {
return;
}
DisplayLockGuard lock(this);
for (const auto& map : emotion_maps_) {
if (map.name && strcmp(map.name, emotion) == 0) {
lv_gif_set_src(emotion_gif_, map.gif);
ESP_LOGI(TAG, "设置表情: %s", emotion);
return;
}
}
lv_gif_set_src(emotion_gif_, &staticstate);
ESP_LOGI(TAG, "未知表情'%s',使用默认", emotion);
}
void OttoEmojiDisplay::SetChatMessage(const char* role, const char* content) {
DisplayLockGuard lock(this);
if (chat_message_label_ == nullptr) {
return;
}
if (content == nullptr || strlen(content) == 0) {
lv_obj_add_flag(chat_message_label_, LV_OBJ_FLAG_HIDDEN);
return;
}
lv_label_set_text(chat_message_label_, content);
lv_obj_remove_flag(chat_message_label_, LV_OBJ_FLAG_HIDDEN);
ESP_LOGI(TAG, "设置聊天消息 [%s]: %s", role, content);
}

View File

@@ -1,41 +1,41 @@
#pragma once
#include <libs/gif/lv_gif.h>
#include "display/lcd_display.h"
#include "otto_emoji_gif.h"
/**
* @brief Otto机器人GIF表情显示类
* 继承LcdDisplay添加GIF表情支持
*/
class OttoEmojiDisplay : public SpiLcdDisplay {
public:
/**
* @brief 构造函数参数与SpiLcdDisplay相同
*/
OttoEmojiDisplay(esp_lcd_panel_io_handle_t panel_io, esp_lcd_panel_handle_t panel, int width,
int height, int offset_x, int offset_y, bool mirror_x, bool mirror_y,
bool swap_xy);
virtual ~OttoEmojiDisplay() = default;
// 重写表情设置方法
virtual void SetEmotion(const char* emotion) override;
// 重写聊天消息设置方法
virtual void SetChatMessage(const char* role, const char* content) override;
private:
void SetupGifContainer();
lv_obj_t* emotion_gif_; ///< GIF表情组件
// 表情映射
struct EmotionMap {
const char* name;
const lv_img_dsc_t* gif;
};
static const EmotionMap emotion_maps_[];
#pragma once
#include <libs/gif/lv_gif.h>
#include "display/lcd_display.h"
#include "otto_emoji_gif.h"
/**
* @brief Otto机器人GIF表情显示类
* 继承LcdDisplay添加GIF表情支持
*/
class OttoEmojiDisplay : public SpiLcdDisplay {
public:
/**
* @brief 构造函数参数与SpiLcdDisplay相同
*/
OttoEmojiDisplay(esp_lcd_panel_io_handle_t panel_io, esp_lcd_panel_handle_t panel, int width,
int height, int offset_x, int offset_y, bool mirror_x, bool mirror_y,
bool swap_xy);
virtual ~OttoEmojiDisplay() = default;
// 重写表情设置方法
virtual void SetEmotion(const char* emotion) override;
// 重写聊天消息设置方法
virtual void SetChatMessage(const char* role, const char* content) override;
private:
void SetupGifContainer();
lv_obj_t* emotion_gif_; ///< GIF表情组件
// 表情映射
struct EmotionMap {
const char* name;
const lv_img_dsc_t* gif;
};
static const EmotionMap emotion_maps_[];
};

File diff suppressed because it is too large Load Diff

View File

@@ -1,105 +1,105 @@
#ifndef __OTTO_MOVEMENTS_H__
#define __OTTO_MOVEMENTS_H__
#include "driver/gpio.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "oscillator.h"
//-- Constants
#define FORWARD 1
#define BACKWARD -1
#define LEFT 1
#define RIGHT -1
#define BOTH 0
#define SMALL 5
#define MEDIUM 15
#define BIG 30
// -- Servo delta limit default. degree / sec
#define SERVO_LIMIT_DEFAULT 240
// -- Servo indexes for easy access
#define LEFT_LEG 0
#define RIGHT_LEG 1
#define LEFT_FOOT 2
#define RIGHT_FOOT 3
#define LEFT_HAND 4
#define RIGHT_HAND 5
#define SERVO_COUNT 6
class Otto {
public:
Otto();
~Otto();
//-- Otto initialization
void Init(int left_leg, int right_leg, int left_foot, int right_foot, int left_hand = -1,
int right_hand = -1);
//-- Attach & detach functions
void AttachServos();
void DetachServos();
//-- Oscillator Trims
void SetTrims(int left_leg, int right_leg, int left_foot, int right_foot, int left_hand = 0,
int right_hand = 0);
//-- Predetermined Motion Functions
void MoveServos(int time, int servo_target[]);
void MoveSingle(int position, int servo_number);
void OscillateServos(int amplitude[SERVO_COUNT], int offset[SERVO_COUNT], int period,
double phase_diff[SERVO_COUNT], float cycle);
//-- HOME = Otto at rest position
void Home(bool hands_down = true);
bool GetRestState();
void SetRestState(bool state);
//-- Predetermined Motion Functions
void Jump(float steps = 1, int period = 2000);
void Walk(float steps = 4, int period = 1000, int dir = FORWARD, int amount = 0);
void Turn(float steps = 4, int period = 2000, int dir = LEFT, int amount = 0);
void Bend(int steps = 1, int period = 1400, int dir = LEFT);
void ShakeLeg(int steps = 1, int period = 2000, int dir = RIGHT);
void UpDown(float steps = 1, int period = 1000, int height = 20);
void Swing(float steps = 1, int period = 1000, int height = 20);
void TiptoeSwing(float steps = 1, int period = 900, int height = 20);
void Jitter(float steps = 1, int period = 500, int height = 20);
void AscendingTurn(float steps = 1, int period = 900, int height = 20);
void Moonwalker(float steps = 1, int period = 900, int height = 20, int dir = LEFT);
void Crusaito(float steps = 1, int period = 900, int height = 20, int dir = FORWARD);
void Flapping(float steps = 1, int period = 1000, int height = 20, int dir = FORWARD);
// -- 手部动作
void HandsUp(int period = 1000, int dir = 0); // 双手举起
void HandsDown(int period = 1000, int dir = 0); // 双手放下
void HandWave(int period = 1000, int dir = LEFT); // 挥手
void HandWaveBoth(int period = 1000); // 双手同时挥手
// -- Servo limiter
void EnableServoLimit(int speed_limit_degree_per_sec = SERVO_LIMIT_DEFAULT);
void DisableServoLimit();
private:
Oscillator servo_[SERVO_COUNT];
int servo_pins_[SERVO_COUNT];
int servo_trim_[SERVO_COUNT];
unsigned long final_time_;
unsigned long partial_time_;
float increment_[SERVO_COUNT];
bool is_otto_resting_;
bool has_hands_; // 是否有手部舵机
void Execute(int amplitude[SERVO_COUNT], int offset[SERVO_COUNT], int period,
double phase_diff[SERVO_COUNT], float steps);
};
#ifndef __OTTO_MOVEMENTS_H__
#define __OTTO_MOVEMENTS_H__
#include "driver/gpio.h"
#include "esp_log.h"
#include "esp_timer.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "oscillator.h"
//-- Constants
#define FORWARD 1
#define BACKWARD -1
#define LEFT 1
#define RIGHT -1
#define BOTH 0
#define SMALL 5
#define MEDIUM 15
#define BIG 30
// -- Servo delta limit default. degree / sec
#define SERVO_LIMIT_DEFAULT 240
// -- Servo indexes for easy access
#define LEFT_LEG 0
#define RIGHT_LEG 1
#define LEFT_FOOT 2
#define RIGHT_FOOT 3
#define LEFT_HAND 4
#define RIGHT_HAND 5
#define SERVO_COUNT 6
class Otto {
public:
Otto();
~Otto();
//-- Otto initialization
void Init(int left_leg, int right_leg, int left_foot, int right_foot, int left_hand = -1,
int right_hand = -1);
//-- Attach & detach functions
void AttachServos();
void DetachServos();
//-- Oscillator Trims
void SetTrims(int left_leg, int right_leg, int left_foot, int right_foot, int left_hand = 0,
int right_hand = 0);
//-- Predetermined Motion Functions
void MoveServos(int time, int servo_target[]);
void MoveSingle(int position, int servo_number);
void OscillateServos(int amplitude[SERVO_COUNT], int offset[SERVO_COUNT], int period,
double phase_diff[SERVO_COUNT], float cycle);
//-- HOME = Otto at rest position
void Home(bool hands_down = true);
bool GetRestState();
void SetRestState(bool state);
//-- Predetermined Motion Functions
void Jump(float steps = 1, int period = 2000);
void Walk(float steps = 4, int period = 1000, int dir = FORWARD, int amount = 0);
void Turn(float steps = 4, int period = 2000, int dir = LEFT, int amount = 0);
void Bend(int steps = 1, int period = 1400, int dir = LEFT);
void ShakeLeg(int steps = 1, int period = 2000, int dir = RIGHT);
void UpDown(float steps = 1, int period = 1000, int height = 20);
void Swing(float steps = 1, int period = 1000, int height = 20);
void TiptoeSwing(float steps = 1, int period = 900, int height = 20);
void Jitter(float steps = 1, int period = 500, int height = 20);
void AscendingTurn(float steps = 1, int period = 900, int height = 20);
void Moonwalker(float steps = 1, int period = 900, int height = 20, int dir = LEFT);
void Crusaito(float steps = 1, int period = 900, int height = 20, int dir = FORWARD);
void Flapping(float steps = 1, int period = 1000, int height = 20, int dir = FORWARD);
// -- 手部动作
void HandsUp(int period = 1000, int dir = 0); // 双手举起
void HandsDown(int period = 1000, int dir = 0); // 双手放下
void HandWave(int period = 1000, int dir = LEFT); // 挥手
void HandWaveBoth(int period = 1000); // 双手同时挥手
// -- Servo limiter
void EnableServoLimit(int speed_limit_degree_per_sec = SERVO_LIMIT_DEFAULT);
void DisableServoLimit();
private:
Oscillator servo_[SERVO_COUNT];
int servo_pins_[SERVO_COUNT];
int servo_trim_[SERVO_COUNT];
unsigned long final_time_;
unsigned long partial_time_;
float increment_[SERVO_COUNT];
bool is_otto_resting_;
bool has_hands_; // 是否有手部舵机
void Execute(int amplitude[SERVO_COUNT], int offset[SERVO_COUNT], int period,
double phase_diff[SERVO_COUNT], float steps);
};
#endif // __OTTO_MOVEMENTS_H__

View File

@@ -1,129 +1,129 @@
#include <driver/i2c_master.h>
#include <driver/spi_common.h>
#include <esp_lcd_panel_io.h>
#include <esp_lcd_panel_ops.h>
#include <esp_lcd_panel_vendor.h>
#include <esp_log.h>
#include <wifi_station.h>
#include "application.h"
#include "codecs/no_audio_codec.h"
#include "button.h"
#include "config.h"
#include "display/lcd_display.h"
#include "lamp_controller.h"
#include "led/single_led.h"
#include "mcp_server.h"
#include "otto_emoji_display.h"
#include "power_manager.h"
#include "system_reset.h"
#include "wifi_board.h"
#define TAG "OttoRobot"
extern void InitializeOttoController();
class OttoRobot : public WifiBoard {
private:
LcdDisplay* display_;
PowerManager* power_manager_;
Button boot_button_;
void InitializePowerManager() {
power_manager_ =
new PowerManager(POWER_CHARGE_DETECT_PIN, POWER_ADC_UNIT, POWER_ADC_CHANNEL);
}
void InitializeSpi() {
spi_bus_config_t buscfg = {};
buscfg.mosi_io_num = DISPLAY_MOSI_PIN;
buscfg.miso_io_num = GPIO_NUM_NC;
buscfg.sclk_io_num = DISPLAY_CLK_PIN;
buscfg.quadwp_io_num = GPIO_NUM_NC;
buscfg.quadhd_io_num = GPIO_NUM_NC;
buscfg.max_transfer_sz = DISPLAY_WIDTH * DISPLAY_HEIGHT * sizeof(uint16_t);
ESP_ERROR_CHECK(spi_bus_initialize(SPI3_HOST, &buscfg, SPI_DMA_CH_AUTO));
}
void InitializeLcdDisplay() {
esp_lcd_panel_io_handle_t panel_io = nullptr;
esp_lcd_panel_handle_t panel = nullptr;
ESP_LOGD(TAG, "Install panel IO");
esp_lcd_panel_io_spi_config_t io_config = {};
io_config.cs_gpio_num = DISPLAY_CS_PIN;
io_config.dc_gpio_num = DISPLAY_DC_PIN;
io_config.spi_mode = DISPLAY_SPI_MODE;
io_config.pclk_hz = 40 * 1000 * 1000;
io_config.trans_queue_depth = 10;
io_config.lcd_cmd_bits = 8;
io_config.lcd_param_bits = 8;
ESP_ERROR_CHECK(esp_lcd_new_panel_io_spi(SPI3_HOST, &io_config, &panel_io));
ESP_LOGD(TAG, "Install LCD driver");
esp_lcd_panel_dev_config_t panel_config = {};
panel_config.reset_gpio_num = DISPLAY_RST_PIN;
panel_config.rgb_ele_order = DISPLAY_RGB_ORDER;
panel_config.bits_per_pixel = 16;
ESP_ERROR_CHECK(esp_lcd_new_panel_st7789(panel_io, &panel_config, &panel));
esp_lcd_panel_reset(panel);
esp_lcd_panel_init(panel);
esp_lcd_panel_invert_color(panel, DISPLAY_INVERT_COLOR);
esp_lcd_panel_swap_xy(panel, DISPLAY_SWAP_XY);
esp_lcd_panel_mirror(panel, DISPLAY_MIRROR_X, DISPLAY_MIRROR_Y);
display_ = new OttoEmojiDisplay(
panel_io, panel, DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_OFFSET_X, DISPLAY_OFFSET_Y,
DISPLAY_MIRROR_X, DISPLAY_MIRROR_Y, DISPLAY_SWAP_XY);
}
void InitializeButtons() {
boot_button_.OnClick([this]() {
auto& app = Application::GetInstance();
if (app.GetDeviceState() == kDeviceStateStarting &&
!WifiStation::GetInstance().IsConnected()) {
ResetWifiConfiguration();
}
app.ToggleChatState();
});
}
void InitializeOttoController() {
ESP_LOGI(TAG, "初始化Otto机器人MCP控制器");
::InitializeOttoController();
}
public:
OttoRobot() : boot_button_(BOOT_BUTTON_GPIO) {
InitializeSpi();
InitializeLcdDisplay();
InitializeButtons();
InitializePowerManager();
InitializeOttoController();
GetBacklight()->RestoreBrightness();
}
virtual AudioCodec* GetAudioCodec() override {
static NoAudioCodecSimplex audio_codec(AUDIO_INPUT_SAMPLE_RATE, AUDIO_OUTPUT_SAMPLE_RATE,
AUDIO_I2S_SPK_GPIO_BCLK, AUDIO_I2S_SPK_GPIO_LRCK,
AUDIO_I2S_SPK_GPIO_DOUT, AUDIO_I2S_MIC_GPIO_SCK,
AUDIO_I2S_MIC_GPIO_WS, AUDIO_I2S_MIC_GPIO_DIN);
return &audio_codec;
}
virtual Display* GetDisplay() override { return display_; }
virtual Backlight* GetBacklight() override {
static PwmBacklight backlight(DISPLAY_BACKLIGHT_PIN, DISPLAY_BACKLIGHT_OUTPUT_INVERT);
return &backlight;
}
virtual bool GetBatteryLevel(int& level, bool& charging, bool& discharging) override {
charging = power_manager_->IsCharging();
discharging = !charging;
level = power_manager_->GetBatteryLevel();
return true;
}
};
DECLARE_BOARD(OttoRobot);
#include <driver/i2c_master.h>
#include <driver/spi_common.h>
#include <esp_lcd_panel_io.h>
#include <esp_lcd_panel_ops.h>
#include <esp_lcd_panel_vendor.h>
#include <esp_log.h>
#include <wifi_station.h>
#include "application.h"
#include "codecs/no_audio_codec.h"
#include "button.h"
#include "config.h"
#include "display/lcd_display.h"
#include "lamp_controller.h"
#include "led/single_led.h"
#include "mcp_server.h"
#include "otto_emoji_display.h"
#include "power_manager.h"
#include "system_reset.h"
#include "wifi_board.h"
#define TAG "OttoRobot"
extern void InitializeOttoController();
class OttoRobot : public WifiBoard {
private:
LcdDisplay* display_;
PowerManager* power_manager_;
Button boot_button_;
void InitializePowerManager() {
power_manager_ =
new PowerManager(POWER_CHARGE_DETECT_PIN, POWER_ADC_UNIT, POWER_ADC_CHANNEL);
}
void InitializeSpi() {
spi_bus_config_t buscfg = {};
buscfg.mosi_io_num = DISPLAY_MOSI_PIN;
buscfg.miso_io_num = GPIO_NUM_NC;
buscfg.sclk_io_num = DISPLAY_CLK_PIN;
buscfg.quadwp_io_num = GPIO_NUM_NC;
buscfg.quadhd_io_num = GPIO_NUM_NC;
buscfg.max_transfer_sz = DISPLAY_WIDTH * DISPLAY_HEIGHT * sizeof(uint16_t);
ESP_ERROR_CHECK(spi_bus_initialize(SPI3_HOST, &buscfg, SPI_DMA_CH_AUTO));
}
void InitializeLcdDisplay() {
esp_lcd_panel_io_handle_t panel_io = nullptr;
esp_lcd_panel_handle_t panel = nullptr;
ESP_LOGD(TAG, "Install panel IO");
esp_lcd_panel_io_spi_config_t io_config = {};
io_config.cs_gpio_num = DISPLAY_CS_PIN;
io_config.dc_gpio_num = DISPLAY_DC_PIN;
io_config.spi_mode = DISPLAY_SPI_MODE;
io_config.pclk_hz = 40 * 1000 * 1000;
io_config.trans_queue_depth = 10;
io_config.lcd_cmd_bits = 8;
io_config.lcd_param_bits = 8;
ESP_ERROR_CHECK(esp_lcd_new_panel_io_spi(SPI3_HOST, &io_config, &panel_io));
ESP_LOGD(TAG, "Install LCD driver");
esp_lcd_panel_dev_config_t panel_config = {};
panel_config.reset_gpio_num = DISPLAY_RST_PIN;
panel_config.rgb_ele_order = DISPLAY_RGB_ORDER;
panel_config.bits_per_pixel = 16;
ESP_ERROR_CHECK(esp_lcd_new_panel_st7789(panel_io, &panel_config, &panel));
esp_lcd_panel_reset(panel);
esp_lcd_panel_init(panel);
esp_lcd_panel_invert_color(panel, DISPLAY_INVERT_COLOR);
esp_lcd_panel_swap_xy(panel, DISPLAY_SWAP_XY);
esp_lcd_panel_mirror(panel, DISPLAY_MIRROR_X, DISPLAY_MIRROR_Y);
display_ = new OttoEmojiDisplay(
panel_io, panel, DISPLAY_WIDTH, DISPLAY_HEIGHT, DISPLAY_OFFSET_X, DISPLAY_OFFSET_Y,
DISPLAY_MIRROR_X, DISPLAY_MIRROR_Y, DISPLAY_SWAP_XY);
}
void InitializeButtons() {
boot_button_.OnClick([this]() {
auto& app = Application::GetInstance();
if (app.GetDeviceState() == kDeviceStateStarting &&
!WifiStation::GetInstance().IsConnected()) {
ResetWifiConfiguration();
}
app.ToggleChatState();
});
}
void InitializeOttoController() {
ESP_LOGI(TAG, "初始化Otto机器人MCP控制器");
::InitializeOttoController();
}
public:
OttoRobot() : boot_button_(BOOT_BUTTON_GPIO) {
InitializeSpi();
InitializeLcdDisplay();
InitializeButtons();
InitializePowerManager();
InitializeOttoController();
GetBacklight()->RestoreBrightness();
}
virtual AudioCodec* GetAudioCodec() override {
static NoAudioCodecSimplex audio_codec(AUDIO_INPUT_SAMPLE_RATE, AUDIO_OUTPUT_SAMPLE_RATE,
AUDIO_I2S_SPK_GPIO_BCLK, AUDIO_I2S_SPK_GPIO_LRCK,
AUDIO_I2S_SPK_GPIO_DOUT, AUDIO_I2S_MIC_GPIO_SCK,
AUDIO_I2S_MIC_GPIO_WS, AUDIO_I2S_MIC_GPIO_DIN);
return &audio_codec;
}
virtual Display* GetDisplay() override { return display_; }
virtual Backlight* GetBacklight() override {
static PwmBacklight backlight(DISPLAY_BACKLIGHT_PIN, DISPLAY_BACKLIGHT_OUTPUT_INVERT);
return &backlight;
}
virtual bool GetBatteryLevel(int& level, bool& charging, bool& discharging) override {
charging = power_manager_->IsCharging();
discharging = !charging;
level = power_manager_->GetBatteryLevel();
return true;
}
};
DECLARE_BOARD(OttoRobot);

View File

@@ -1,128 +1,128 @@
#ifndef __POWER_MANAGER_H__
#define __POWER_MANAGER_H__
#include <driver/gpio.h>
#include <esp_adc/adc_oneshot.h>
#include <esp_log.h>
#include <esp_timer.h>
class PowerManager {
private:
// 电池电量区间-分压电阻为2个100k
static constexpr struct {
uint16_t adc;
uint8_t level;
} BATTERY_LEVELS[] = {{2150, 0}, {2450, 100}};
static constexpr size_t BATTERY_LEVELS_COUNT = 2;
static constexpr size_t ADC_VALUES_COUNT = 10;
esp_timer_handle_t timer_handle_ = nullptr;
gpio_num_t charging_pin_;
adc_unit_t adc_unit_;
adc_channel_t adc_channel_;
uint16_t adc_values_[ADC_VALUES_COUNT];
size_t adc_values_index_ = 0;
size_t adc_values_count_ = 0;
uint8_t battery_level_ = 100;
bool is_charging_ = false;
adc_oneshot_unit_handle_t adc_handle_;
void CheckBatteryStatus() {
is_charging_ = gpio_get_level(charging_pin_) == 0;
ReadBatteryAdcData();
}
void ReadBatteryAdcData() {
int adc_value;
ESP_ERROR_CHECK(adc_oneshot_read(adc_handle_, adc_channel_, &adc_value));
adc_values_[adc_values_index_] = adc_value;
adc_values_index_ = (adc_values_index_ + 1) % ADC_VALUES_COUNT;
if (adc_values_count_ < ADC_VALUES_COUNT) {
adc_values_count_++;
}
uint32_t average_adc = 0;
for (size_t i = 0; i < adc_values_count_; i++) {
average_adc += adc_values_[i];
}
average_adc /= adc_values_count_;
CalculateBatteryLevel(average_adc);
// ESP_LOGI("PowerManager", "ADC值: %d 平均值: %ld 电量: %u%%", adc_value, average_adc,
// battery_level_);
}
void CalculateBatteryLevel(uint32_t average_adc) {
if (average_adc <= BATTERY_LEVELS[0].adc) {
battery_level_ = 0;
} else if (average_adc >= BATTERY_LEVELS[BATTERY_LEVELS_COUNT - 1].adc) {
battery_level_ = 100;
} else {
float ratio = static_cast<float>(average_adc - BATTERY_LEVELS[0].adc) /
(BATTERY_LEVELS[1].adc - BATTERY_LEVELS[0].adc);
battery_level_ = ratio * 100;
}
}
public:
PowerManager(gpio_num_t charging_pin, adc_unit_t adc_unit = ADC_UNIT_2,
adc_channel_t adc_channel = ADC_CHANNEL_3)
: charging_pin_(charging_pin), adc_unit_(adc_unit), adc_channel_(adc_channel) {
gpio_config_t io_conf = {};
io_conf.intr_type = GPIO_INTR_DISABLE;
io_conf.mode = GPIO_MODE_INPUT;
io_conf.pin_bit_mask = (1ULL << charging_pin_);
io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
io_conf.pull_up_en = GPIO_PULLUP_ENABLE;
gpio_config(&io_conf);
esp_timer_create_args_t timer_args = {
.callback =
[](void* arg) {
PowerManager* self = static_cast<PowerManager*>(arg);
self->CheckBatteryStatus();
},
.arg = this,
.dispatch_method = ESP_TIMER_TASK,
.name = "battery_check_timer",
.skip_unhandled_events = true,
};
ESP_ERROR_CHECK(esp_timer_create(&timer_args, &timer_handle_));
ESP_ERROR_CHECK(esp_timer_start_periodic(timer_handle_, 1000000)); // 1秒
InitializeAdc();
}
void InitializeAdc() {
adc_oneshot_unit_init_cfg_t init_config = {
.unit_id = adc_unit_,
.ulp_mode = ADC_ULP_MODE_DISABLE,
};
ESP_ERROR_CHECK(adc_oneshot_new_unit(&init_config, &adc_handle_));
adc_oneshot_chan_cfg_t chan_config = {
.atten = ADC_ATTEN_DB_12,
.bitwidth = ADC_BITWIDTH_12,
};
ESP_ERROR_CHECK(adc_oneshot_config_channel(adc_handle_, adc_channel_, &chan_config));
}
~PowerManager() {
if (timer_handle_) {
esp_timer_stop(timer_handle_);
esp_timer_delete(timer_handle_);
}
if (adc_handle_) {
adc_oneshot_del_unit(adc_handle_);
}
}
bool IsCharging() { return is_charging_; }
uint8_t GetBatteryLevel() { return battery_level_; }
};
#ifndef __POWER_MANAGER_H__
#define __POWER_MANAGER_H__
#include <driver/gpio.h>
#include <esp_adc/adc_oneshot.h>
#include <esp_log.h>
#include <esp_timer.h>
class PowerManager {
private:
// 电池电量区间-分压电阻为2个100k
static constexpr struct {
uint16_t adc;
uint8_t level;
} BATTERY_LEVELS[] = {{2150, 0}, {2450, 100}};
static constexpr size_t BATTERY_LEVELS_COUNT = 2;
static constexpr size_t ADC_VALUES_COUNT = 10;
esp_timer_handle_t timer_handle_ = nullptr;
gpio_num_t charging_pin_;
adc_unit_t adc_unit_;
adc_channel_t adc_channel_;
uint16_t adc_values_[ADC_VALUES_COUNT];
size_t adc_values_index_ = 0;
size_t adc_values_count_ = 0;
uint8_t battery_level_ = 100;
bool is_charging_ = false;
adc_oneshot_unit_handle_t adc_handle_;
void CheckBatteryStatus() {
is_charging_ = gpio_get_level(charging_pin_) == 0;
ReadBatteryAdcData();
}
void ReadBatteryAdcData() {
int adc_value;
ESP_ERROR_CHECK(adc_oneshot_read(adc_handle_, adc_channel_, &adc_value));
adc_values_[adc_values_index_] = adc_value;
adc_values_index_ = (adc_values_index_ + 1) % ADC_VALUES_COUNT;
if (adc_values_count_ < ADC_VALUES_COUNT) {
adc_values_count_++;
}
uint32_t average_adc = 0;
for (size_t i = 0; i < adc_values_count_; i++) {
average_adc += adc_values_[i];
}
average_adc /= adc_values_count_;
CalculateBatteryLevel(average_adc);
// ESP_LOGI("PowerManager", "ADC值: %d 平均值: %ld 电量: %u%%", adc_value, average_adc,
// battery_level_);
}
void CalculateBatteryLevel(uint32_t average_adc) {
if (average_adc <= BATTERY_LEVELS[0].adc) {
battery_level_ = 0;
} else if (average_adc >= BATTERY_LEVELS[BATTERY_LEVELS_COUNT - 1].adc) {
battery_level_ = 100;
} else {
float ratio = static_cast<float>(average_adc - BATTERY_LEVELS[0].adc) /
(BATTERY_LEVELS[1].adc - BATTERY_LEVELS[0].adc);
battery_level_ = ratio * 100;
}
}
public:
PowerManager(gpio_num_t charging_pin, adc_unit_t adc_unit = ADC_UNIT_2,
adc_channel_t adc_channel = ADC_CHANNEL_3)
: charging_pin_(charging_pin), adc_unit_(adc_unit), adc_channel_(adc_channel) {
gpio_config_t io_conf = {};
io_conf.intr_type = GPIO_INTR_DISABLE;
io_conf.mode = GPIO_MODE_INPUT;
io_conf.pin_bit_mask = (1ULL << charging_pin_);
io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
io_conf.pull_up_en = GPIO_PULLUP_ENABLE;
gpio_config(&io_conf);
esp_timer_create_args_t timer_args = {
.callback =
[](void* arg) {
PowerManager* self = static_cast<PowerManager*>(arg);
self->CheckBatteryStatus();
},
.arg = this,
.dispatch_method = ESP_TIMER_TASK,
.name = "battery_check_timer",
.skip_unhandled_events = true,
};
ESP_ERROR_CHECK(esp_timer_create(&timer_args, &timer_handle_));
ESP_ERROR_CHECK(esp_timer_start_periodic(timer_handle_, 1000000)); // 1秒
InitializeAdc();
}
void InitializeAdc() {
adc_oneshot_unit_init_cfg_t init_config = {
.unit_id = adc_unit_,
.ulp_mode = ADC_ULP_MODE_DISABLE,
};
ESP_ERROR_CHECK(adc_oneshot_new_unit(&init_config, &adc_handle_));
adc_oneshot_chan_cfg_t chan_config = {
.atten = ADC_ATTEN_DB_12,
.bitwidth = ADC_BITWIDTH_12,
};
ESP_ERROR_CHECK(adc_oneshot_config_channel(adc_handle_, adc_channel_, &chan_config));
}
~PowerManager() {
if (timer_handle_) {
esp_timer_stop(timer_handle_);
esp_timer_delete(timer_handle_);
}
if (adc_handle_) {
adc_oneshot_del_unit(adc_handle_);
}
}
bool IsCharging() { return is_charging_; }
uint8_t GetBatteryLevel() { return battery_level_; }
};
#endif // __POWER_MANAGER_H__