基于ESP32与MicroPython的实体化代码伴侣 BLE交互与状态机设计实践ESP32 and MicroPython Physical Code Companion: BLE Interaction and State Machine Design in Practice


AI free token/AI免费积分

基于ESP32与MicroPython的实体化代码伴侣 BLE交互与状态机设计实践

本文来源:http://www.mtrt.cn/news/20245
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。

电脑通信的小设备。它静静地趴在你的桌角当你长时间不写代码比如在刷网页、摸鱼时它会通过灯光、表情甚至轻微震动来“提醒”你该干活了。而当你完成一个功能模块、通过测试或者提交了代码它则会给你一个“点赞”的反馈。核心思路就是把Claude Code CLI这种基于文本的、被动的代码辅助体验升级成一种具象的、带有情感化交互的实体陪伴。它适合所有觉得命令行工具有点冰冷希望开发环境更有趣、更有互动感的程序员尤其是那些喜欢物联网IoT和硬件DIY的极客们。2. 核心设计思路与方案选型2.1 为什么是“实体监工”在深入技术细节前我想先聊聊为什么选择这个方向。我们每天面对IDE和终端信息流是单向的、沉默的。Claude Code CLI虽然能交互但它仍然被困在屏幕里。实体化的核心价值在于建立一种超越屏幕的、低侵入性的注意力锚点。它不会像弹窗一样粗暴打断你的思路而是通过外围视觉灯光和触觉震动给你一个温和的提示。

这种体验很像一个真实的搭档坐在旁边轻轻敲下桌子提醒你走神了比任何软件通知都更自然、更人性化。2.2 硬件核心ESP32为何是绝佳选择在硬件选型上我几乎没怎么犹豫就锁定了ESP32。原因有以下几点双核处理器与丰富外设ESP32的主频和内存足够流畅运行MicroPython并同时处理蓝牙通信、传感器数据读取和屏幕/灯光驱动多任务无压力。其内置的DAC、触摸传感器、霍尔传感器等为未来功能扩展如添加环境音监测、磁吸交互留足了空间。低功耗蓝牙BLE是刚需本项目需要与电脑保持长时间、低功耗的无线连接。ESP32的BLE协议栈成熟稳定开发资料丰富能轻松实现设备广播、服务发布和与电脑端CLI工具的数据交换。相比Wi-FiBLE在保持连接时的功耗要低得多适合7x24小时待机。MicroPython开发效率奇高对于这种重交互逻辑、轻底层驱动的创意项目MicroPython是生产力利器。它允许我用Python这

种熟悉的高级语言快速原型迭代直接操作GPIO、驱动屏幕、处理JSON数据省去了嵌入式C语言复杂的编译、烧录和调试周期。强大的社区与生态无论是相关的开发板如合宙ESP32-C3、传感器模块还是遇到问题时的解决方案ESP32的社区支持都是顶级的。这意味着很多功能你不需要从零造轮子。2.3 软件架构双向通信与状态机整个系统的软件架构围绕“状态同步”和“事件驱动”展开。设备端ESP32运行一个状态机。状态包括“空闲”、“工作中”、“提醒中”、“庆祝中”。每个状态对应不同的灯光模式、屏幕动画和是否启用传感器监测。它通过BLE广播自身并提供一个包含“状态写入”和“日志读取”特性的GATT服务。电脑端CLI插件核心是一个后台守护进程Daemon。它做了三件事监听系统与IDE通过文件系统监控如watchdog监听项目目录、进程查询如检测浏览器或游戏进程或IDE插件API来判断开发者的活动状态。与Claud

e Code CLI集成解析CLI的输出或提供钩子hooks当Claude给出“建议开始编码”或“代码审查通过”等指令时能捕获这些事件。BLE通信管理发现并连接我们的ESP32设备根据监听和捕获到的事件向设备写入对应的状态指令例如写入“提醒”状态码。通信协议为了简单高效我设计了一个极简的基于JSON的文本协议。通过BLE的一个可写特征Characteristic传输。例如电脑端发送{cmd: set_state, state: remind}设备端解析后切换到提醒状态。注意电脑端监听活动是一个敏感操作务必在代码中明确告知用户并获得授权仅用于本项目改善工作效率的初衷并确保所有数据处理都在本地完成。3. 硬件搭建与核心电路解析3.1 物料清单与选型考量除了ESP32开发板这个大脑为了让“宠物”有表现力还需要一些外围器件显示单元我选择了一块1.3英寸的IPS LCD彩屏ST7789驱动。为什么不

用OLED虽然OLED更省电但IPS LCD在可视角度和显示丰富的表情动画上更有优势而且成本相差无几。屏幕用于显示“宠物”的各种表情 休眠、 专注、⚠️ 提醒、 庆祝。反馈单元RGB LEDWS2812B环贴在设备外壳内侧用于环境光氛围渲染。不同颜色代表不同状态蓝色-连接中绿色-工作中黄色-闲置红色-提醒。震动马达扁平转子马达用于提供触觉反馈。在提醒状态时短震在庆祝状态时长震两下这种物理反馈比纯视觉更抓人注意力。蜂鸣器有源可选。用于播放简单的提示音但考虑到办公环境我在代码中默认禁用了声音可通过配置开启。输入与感知单元EC11旋转编码器集成了按键功能。旋转可以调节屏幕亮度或切换模式按下按键可以手动切换状态或确认提醒。这给了用户主动交互的入口。温湿度传感器DHT22或SHT30我选择了精度更高的SHT30。初衷是让“宠物”能感知环境比如在温度过高时芯片过热给出“降温”提示增加一点拟人化的趣味性

。电源与结构一枚常见的18650锂电池配合充放电管理模块如TP4056保证无线续航。外壳使用3D打印设计成一个小方块或小机器人的造型让所有传感器和屏幕合理排布。3.2 电路连接要点与避坑指南将这么多模块连接到ESP32需要仔细规划GPIO。下面是我的连接方案及原因模块连接ESP32引脚引脚类型备注与避坑点LCD屏幕 (ST7789)SCL-GPIO18, SDA-GPIO23SPI使用硬件SPI以获得最高刷新率。务必注意有些ESP32板子的默认SPI引脚被闪存占用需要根据具体型号调整。RGB LED (WS2812B)GPIO2数字输出需要一根数据线即可。重要WS2812B对时序要求严最好在代码中禁用此引脚的中断或使用RMT远程控制外设驱动这是ESP32的特色高效驱动方式。震动马达GPIO4数字输出通过一个NPN三极管如8050或MOSFET驱动切勿直接连接ESP32的GPIO驱动电流不足

。EC11编码器CLK-GPIO32, DT-GPIO33, SW-GPIO25数字输入CLK和DT需要配置上拉输入。避坑编码器抖动严重必须在软件中做消抖处理例如设置一个50ms的防抖延时。SHT30传感器SCL-GPIO22, SDA-GPIO21I2C使用硬件I2C。I2C总线可以挂载多个设备注意地址不要冲突。电池管理BAT/-接电池OUT/-接ESP32 Vin/GND-TP4056模块的CHRG和STDBY指示灯引脚可以接到ESP32用于监控充电状态。实操心得在面包板上搭建原型时务必先分模块测试。例如先单独测试屏幕显示再测试LED最后整合。电源管理是关键当所有模块同时工作时尤其是屏幕和LED全亮电流需求可能骤增一个好的稳压电路和足够容量的电池是稳定运行的保障。我曾因电源纹波过大导致ESP32不断重启后来在ESP32的电源输入脚就近加了一个100μF的电解电容才解决。4. 设备端Mi

croPython固件开发详解4.1 开发环境搭建与固件烧录首先你需要为ESP32刷入MicroPython固件。我推荐使用合宙的ESP32-C3开发板性价比极高。获取固件从MicroPython官网下载最新的ESP32通用固件.bin文件。烧录工具使用esptool.py这个Python工具。安装命令pip install esptool。擦除与烧录将开发板通过USB连接电脑进入下载模式通常需要按住Boot键再按Reset键。然后执行以下命令替换COMx为你的实际端口如COM3或/dev/ttyUSB0# 擦除闪存 esptool.py --chip esp32c3 --port COMx erase_flash # 烧录固件 esptool.py --chip esp32c3 --port COMx --baud 460800 write_flash 0x0 micropython-f

irmware.bin验证使用串口工具如PuTTY、VS Code的Serial Monitor连接板子波特率115200如果看到MicroPython的REPL提示符说明成功。4.2 BLE服务与通信实现这是设备端代码的核心。MicroPython的bluetooth模块提供了BLE支持。我们需要创建一个包含自定义服务的BLE外围设备Peripheral。import bluetooth import struct import json from ble_advertising import advertising_payload # 定义自定义服务UUID可以随机生成但确保唯一 _SERVICE_UUID bluetooth.UUID(0xABCD) # 示例UUID _STATE_CHAR_UUID bluetooth.UUID(0xABCE) # 用于接收电脑指令的特征 _L

OG_CHAR_UUID bluetooth.UUID(0xABCF) # 用于发送设备日志的特征可选 class BLEPet: def __init__(self, nameCodeBuddy): self._ble bluetooth.BLE() self._ble.active(True) self._ble.irq(self._irq_handler) self._connections set() self._state_handlers [] # 状态变更回调函数列表 # 注册服务 state_char (bluetooth.UUID(_STATE_CHAR_UUID), bluetooth.FLAG_WRITE | bluetooth.FLAG_NOTIFY,) log_char (bluetooth.UUID(_LOG_CHAR_UUID), bluetoot

h.FLAG_READ | bluetooth.FLAG_NOTIFY,) service (_SERVICE_UUID, (state_char, log_char),) services (service,) ((self._state_handle, self._log_handle),) self._ble.gatts_register_services(services) # 设置特征值的初始数据 self._ble.gatts_write(self._state_handle, b\x00) # 初始状态0 self._ble.gatts_write(self._log_handle, bHello from CodeBuddy!) # 设置可连接广播 payload advertising_payload(namename, services[_SERVICE_UUI

D]) self._ble.gap_advertise(100000, adv_datapayload) print(BLE Advertising started, name:, name) def _irq_handler(self, event, data): # 处理BLE事件连接、断开、写入等 if event 1: # _IRQ_CENTRAL_CONNECTED conn_handle, addr_type, addr data self._connections.add(conn_handle) print(Connected by:, addr) elif event 2: # _IRQ_CENTRAL_DISCONNECTED conn_handle, addr_type, addr data if conn_handle in self._connection

s: self._connections.remove(conn_handle) print(Disconnected:, addr) # 重播广播 self._ble.gap_advertise(100000) elif event 3: # _IRQ_GATTS_WRITE conn_handle, value_handle data if value_handle self._state_handle: # 收到电脑端发来的新状态指令 received_data self._ble.gatts_read(value_handle) self._process_command(received_data) def _process_command(self, data): try: cmd_dict json.loads(data.decode(utf-8)) cmd cm

d_dict.get(cmd) if cmd set_state: new_state cmd_dict.get(state) print(New state received:, new_state) # 触发所有注册的状态处理函数 for handler in self._state_handlers: handler(new_state) except Exception as e: print(Command process error:, e) def register_state_handler(self, handler): 注册一个状态变更处理函数 self._state_handlers.append(handler)这段代码构建了BLE服务的骨架。_process_command方法解析从电脑发来的JSON指令并调用注册的状态处理函数。这些处理函数将负责更新屏幕、灯

光和马达。4.3 多任务管理与状态机实现MicroPython本身支持简单的多线程_thread模块但对于我们这个项目使用异步编程asyncio是更优雅和高效的选择它能更好地处理并发I/O操作如BLE事件、编码器扫描、动画刷新。import uasyncio as asyncio from machine import Pin, PWM import neopixel import st7789 import sht30 class PetStateMachine: def __init__(self): self.current_state idle self.screen st7789.ST7789(...) # 初始化屏幕 self.leds neopixel.NeoPixel(Pin(2), 24) # 24颗LED灯环 self.motor Pin(4, Pin.OUT)

self.encoder RotaryEncoder(pin_clk32, pin_dt33, pin_sw25) self.sensor sht30.SHT30() # 状态与对应处理函数的映射 self.state_actions { idle: self._state_idle, working: self._state_working, remind: self._state_remind, celebrate: self._state_celebrate } async def run(self): 主异步循环 while True: action self.state_actions.get(self.current_state) if action: await action() # 执行当前状态的任务 await asyncio.sleep(0.1) # 释放控制

权 async def _state_idle(self): # 空闲状态屏幕显示睡眠表情灯光缓慢呼吸蓝色 self.screen.display_image(sleep.png) await self._breathing_effect((0, 0, 50)) # 蓝色呼吸 # 检查编码器或传感器事件 if self.encoder.button_pressed(): self.change_state(working) async def _state_working(self): # 工作状态屏幕显示专注表情灯光常亮绿色 self.screen.display_image(working.png) self.leds.fill((0, 50, 0)) self.leds.write() # 可以在这里读取传感器数据比如每10秒读一次温湿度 # temp, humi self.sen

sor.measure() # if temp 30: # self.screen.show_text(Hot!) async def _state_remind(self): # 提醒状态屏幕显示警告表情灯光闪烁红色马达短震 self.screen.display_image(warning.png) for _ in range(5): # 闪烁5次 self.leds.fill((50, 0, 0)) self.leds.write() self.motor.value(1) await asyncio.sleep(0.2) self.leds.fill((0,0,0)) self.leds.write() self.motor.value(0) await asyncio.sleep(0.2) # 提醒结束后自动回到空闲或工作状态 self.change_state(idle)

async def _state_celebrate(self): # 庆祝状态屏幕显示开心表情彩虹灯效马达长震两次 self.screen.display_image(celebrate.png) self.motor.value(1) await asyncio.sleep(0.5) self.motor.value(0) await asyncio.sleep(0.2) self.motor.value(1) await asyncio.sleep(0.5) self.motor.value(0) await self._rainbow_effect(cycles2) self.change_state(working) def change_state(self, new_state): 安全地切换状态 if new_state in self.state_actions: pri

nt(fState change: {self.current_state} - {new_state}) self.current_state new_state # ... 灯光效果函数_breathing_effect, _rainbow_effect ...这个状态机类是整个“宠物”行为逻辑的核心。run()方法是异步任务的主循环它会持续执行当前状态对应的行为函数。状态切换通过change_state方法触发可以由BLE指令、编码器按键或内部条件如传感器超标调用。4.4 主程序整合与启动最后我们需要一个主文件来将所有模块整合并启动。# main.py import uasyncio as asyncio from ble_pet import BLEPet from pet_state_machine import PetStateMachine async def main()

KeyboardInterrupt: print(Program stopped by user.) finally: # 清理工作如关闭灯光 pass将main.py、ble_pet.py、pet_state_machine.py以及相关的驱动库st7789.py,sht30.py等通过串口工具如ampy,rshell或VS Code的MicroPython插件上传到ESP32的文件系统中重启后设备就会开始广播等待连接。5. 电脑端CLI守护进程开发5.1 监听开发者活动状态电脑端程序的核心是判断开发者是否在“有效工作”。这里提供几种思路可以组合使用以提高准确性活动窗口/进程监控使用Python的psutil库周期性地检查当前焦点窗口的进程名。如果检测到浏览器chrome.exe,firefox.exe且标签页非开发相关或检测到游戏进程则判定为“可能摸鱼”。import psutil

def get_active_process(): # 此方法在Windows/macOS/Linux上实现不同以下为简化示例 # 可能需要使用pygetwindow或Quartz(macOS)等库 # 返回进程名或None pass文件系统监控使用watchdog库监听项目目录下源代码文件.py,.js,.go等的修改事件。如果在设定的时间窗口内如15分钟没有任何修改事件则判定为“闲置”。from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class CodeChangeHandler(FileSystemEventHandler): def on_modified(self, event): if not event.is_directory and eve

nt.src_path.endswith((.py, .js)): update_last_activity_time() # 更新最后活动时间戳IDE/编辑器集成这是最精准的方式。可以为VS Code、IntelliJ等编辑器开发插件直接监听编辑器的活动事件如文件保存、输入停止、测试运行。但这需要针对不同编辑器开发复杂度较高。一个折中方案是读取编辑器产生的临时文件或日志。5.2 与Claude Code CLI的交互目标是捕获Claude Code CLI的输出并解析关键信息。一个可行的方法是包装wrapCLI命令。子进程通信你的守护进程启动Claude Code CLI作为一个子进程并实时捕获其标准输出stdout。import subprocess import threading def run_claude_cli(): proc subprocess.Popen([claud

e, code, --your-flags], stdoutsubprocess.PIPE, stderrsubprocess.PIPE, textTrue) for line in iter(proc.stdout.readline, ): if It looks like you havent written code for a while in line: trigger_state(remind) elif Great job! This implementation looks solid. in line: trigger_state(celebrate)使用官方API/SDK如果提供如果Claude Code提供编程接口直接调用是更稳定和高效的方式。需要查阅其官方文档。5.3 BLE通信客户端实现在电脑端我们需要一个BLE中心设备Central来连接ESP32。在Pytho

n中可以使用bleak这个优秀的跨平台BLE库。import asyncio from bleak import BleakClient, BleakScanner import json ESP32_DEVICE_NAME CodeBuddy STATE_CHAR_UUID 0000abce-0000-1000-8000-00805f9b34fb # 需与设备端一致 async def connect_and_control(): device None # 1. 扫描设备 devices await BleakScanner.discover() for d in devices: if d.name and ESP32_DEVICE_NAME in d.name: device d break if not device: print(Device not found.)

return # 2. 连接并发送指令 async with BleakClient(device.address) as client: print(fConnected to {device.name}) # 示例发送“提醒”状态 remind_cmd json.dumps({cmd: set_state, state: remind}).encode(utf-8) await client.write_gatt_char(STATE_CHAR_UUID, remind_cmd) print(Remind command sent.) # 可以保持连接监听设备端发来的通知如日志 # await client.start_notify(LOG_CHAR_UUID, notification_handler) # await asyncio.sleep(60) # 保持连接一段时间 #

await client.stop_notify(LOG_CHAR_UUID) def trigger_state(state_name): 供活动监听模块调用的函数 asyncio.run(send_ble_command(state_name)) async def send_ble_command(state): # 简化的发送函数 cmd json.dumps({cmd: set_state, state: state}).encode(utf-8) # ... 连接并写入的代码同上...5.4 守护进程的整合与自启动将活动监听、CLI交互和BLE通信三个模块整合到一个主守护进程中并使用一个事件循环来协调它们。# daemon_main.py import asyncio import threading from activity_monitor import Activity

ESP32 and MicroPython Physical Code Companion: BLE Interaction and State Machine Design in Practice

本文来源:http://www.mtrt.cn/news/20245
若有版权问题,请来信告知:13951431913#139.com 或在右方提交评论。

...a small device that communicates with the computer. It sits quietly in the corner of your desk; when you go a long time without writing code - say, browsing the web or slacking off - it will "remind" you that it is time to work, through lights, facial expressions, and even a slight vibration. And when you finish a feature module, pass a test, or commit your code, it gives you a "thumbs-up" feedback. The core idea is to upgrade the text-based, passive code-assistance experience of Claude Code CLI into a tangible, emotionally interactive physical companion. It is suited to any programmer who finds command-line tools a bit cold and wants a more fun, more interactive development environment - especially those geeks who love IoT and hardware DIY. 2. Core Design Ideas and Solution Selection 2.1 Why a "Physical Supervisor"? Before diving into technical details, I want to talk about why I chose this direction. Every day we face the IDE and terminal, and the flow of information is one-way and silent. Claude Code CLI, although interactive, is still trapped inside the screen. The core value of an embodied form is to establish a low-intrusion attention anchor that goes beyond the screen. It does not brutally interrupt your train of thought like a pop-up window; instead, it gives you a gentle hint through peripheral visual lighting and tactile vibration.

This experience is much like a real partner sitting next to you, gently tapping the desk to remind you that you have drifted off - more natural and more human than any software notification. 2.2 Hardware Core: Why the ESP32 Is the Perfect Choice In hardware selection, I hardly hesitated before locking onto the ESP32. The reasons are as follows. Dual-core processor and rich peripherals: the ESP32's clock speed and memory are sufficient to run MicroPython smoothly while simultaneously handling Bluetooth communication, sensor data reading, and screen/light driving - multitasking with ease. Its built-in DAC, touch sensor, Hall sensor, etc., leave plenty of room for future feature expansion such as adding ambient sound monitoring or magnetic interaction. Low-power Bluetooth (BLE) is a must: this project needs to maintain a long-term, low-power wireless connection with the computer. The ESP32's BLE protocol stack is mature and stable, with abundant development resources, making it easy to implement device advertising, service publication, and data exchange with the computer-side CLI tool. Compared with Wi-Fi, BLE consumes far less power while maintaining a connection, suitable for 24/7 standby. Extremely high development efficiency with MicroPython: for a creative project like this with heavy interaction logic and light low-level drivers, MicroPython is a productivity weapon. It lets me use Python,

this familiar high-level language, for rapid prototyping and iteration, directly manipulating GPIO, driving the screen, and processing JSON data, eliminating the complex compile-flash-debug cycle of embedded C. Strong community and ecosystem: whether it is related dev boards such as the Heltec ESP32-C3, sensor modules, or solutions when you run into problems, the ESP32's community support is top-tier. This means you do not need to reinvent the wheel for many features. 2.3 Software Architecture: Bidirectional Communication and State Machine The software architecture of the whole system revolves around "state synchronization" and "event-driven" design. The device-side ESP32 runs a state machine. States include "idle", "working", "reminding", and "celebrating". Each state corresponds to a different lighting pattern, screen animation, and whether sensor monitoring is enabled. It advertises itself over BLE and provides a GATT service with "state write" and "log read" characteristics. The computer-side CLI plugin is essentially a background daemon. It does three things: Monitor the system and IDE - using filesystem monitoring such as watchdog on the project directory, process queries such as detecting browser or game processes, or IDE plugin APIs to determine the developer's activity state. Integrate with Claude

Code CLI: parse the CLI's output or provide hooks, so that when Claude gives commands such as "suggest starting to code" or "code review passed", these events can be captured. BLE communication management: discover and connect to our ESP32 device, and write the corresponding state command to the device based on the monitored and captured events - for example, writing the "remind" state code. Communication protocol: for simplicity and efficiency, I designed a minimal JSON-based text protocol, transmitted through a writable BLE Characteristic. For example, the computer side sends {cmd: set_state, state: remind}, and the device parses it and switches to the reminding state. Note that monitoring activity on the computer side is a sensitive operation; be sure to clearly inform the user in the code and obtain authorization, use it only for the original purpose of this project - improving work efficiency - and ensure all data processing is done locally. 3. Hardware Build and Core Circuit Analysis 3.1 Bill of Materials and Selection Considerations Besides the ESP32 dev board as the brain, to give the "pet" expressiveness we need some peripheral components. Display unit: I chose a 1.3-inch IPS LCD color screen driven by ST7789. Why not

use OLED? Although OLED is more power-efficient, IPS LCD has advantages in viewing angles and displaying rich expression animations, and the cost is nearly the same. The screen is used to display the "pet's" various expressions: sleeping, focused, warning (reminding), celebrating. Feedback unit - RGB LED: a WS2812B ring stuck on the inside of the device enclosure, used for ambient lighting effects. Different colors represent different states: blue - connecting; green - working; yellow - idle; red - reminding. Vibration motor: a flat rotor motor used to provide tactile feedback. A short vibration in the reminding state and two long vibrations in the celebrating state - this kind of physical feedback grabs attention better than purely visual cues. Buzzer: active type, optional. Used to play simple prompt sounds, but considering the office environment I disabled sound by default in the code; it can be enabled via configuration. Input and sensing unit - EC11 rotary encoder with integrated button function. Rotating adjusts screen brightness or switches modes; pressing the button manually switches states or confirms a reminder. This gives users an entry point for active interaction. Temperature and humidity sensor - DHT22 or SHT30; I chose the more accurate SHT30. The original intention was to let the "pet" sense the environment - for example, giving a "cool down" hint when the temperature is too high (chip overheating) - adding a bit of anthropomorphic fun.

. Power and structure: a common 18650 lithium battery paired with a charge/discharge management module such as the TP4056 ensures wireless endurance. The enclosure is 3D-printed, designed as a small cube or a little robot, allowing all sensors and the screen to be arranged sensibly. 3.2 Circuit Connection Points and Pitfall Avoidance Guide Connecting so many modules to the ESP32 requires careful GPIO planning. Below is my connection scheme and the reasons. Module - ESP32 pin - pin type - notes and pitfalls. LCD screen (ST7789): SCL-GPIO18, SDA-GPIO23, SPI. Use hardware SPI for the highest refresh rate. Be sure to note that some ESP32 boards have their default SPI pins occupied by flash memory and need adjustment according to the specific model. RGB LED (WS2812B): GPIO2, digital output; a single data line is enough. Important: the WS2812B has strict timing requirements; it is best to disable interrupts on this pin in code or use the RMT (remote control peripheral) driver - a characteristic, efficient driving method of the ESP32. Vibration motor: GPIO4, digital output; drive it through an NPN transistor such as the 8050 or a MOSFET - never connect it directly to the ESP32's GPIO, as the drive current is insufficient.

. EC11 encoder: CLK-GPIO32, DT-GPIO33, SW-GPIO25, digital inputs. CLK and DT need to be configured as pull-up inputs. Pitfall: encoders bounce badly; you must implement debouncing in software, e.g., set a 50 ms debounce delay. SHT30 sensor: SCL-GPIO22, SDA-GPIO21, I2C. Use hardware I2C. The I2C bus can carry multiple devices; just make sure addresses do not conflict. Battery management: BAT+/- to the battery, OUT+/- to ESP32 Vin/GND - the TP4056 module's CHRG and STDBY indicator pins can be connected to the ESP32 to monitor charging status. Practical experience: when building a prototype on a breadboard, be sure to test module by module first. For example, test the screen display alone, then the LED, and finally integrate everything. Power management is key: when all modules work at once, especially with the screen and LED at full brightness, current demand can spike; a good voltage-regulator circuit and a battery of sufficient capacity are the guarantee of stable operation. I once had the ESP32 constantly restarting due to excessive power ripple, and only solved it by adding a 100 uF electrolytic capacitor close to the ESP32's power input pin. 4. Device-Side Micro

Python Firmware Development in Detail 4.1 Development Environment Setup and Firmware Flashing First, you need to flash MicroPython firmware onto the ESP32. I recommend the Heltec ESP32-C3 dev board, which offers excellent value. Getting the firmware: download the latest generic ESP32 firmware .bin file from the official MicroPython website. Flashing tool: use the Python tool esptool.py, installed with pip install esptool. Erase and flash: connect the board to the computer via USB and enter download mode - usually by holding the Boot button and then pressing Reset. Then run the following commands, replacing COMx with your actual port such as COM3 or /dev/ttyUSB0: # erase flash esptool.py --chip esp32c3 --port COMx erase_flash # flash firmware esptool.py --chip esp32c3 --port COMx --baud 460800 write_flash 0x0 micropython-f

irmware.bin Verification: use a serial tool such as PuTTY or VS Code's Serial Monitor to connect to the board at baud rate 115200; if you see the MicroPython REPL prompt, it succeeded. 4.2 BLE Service and Communication Implementation This is the core of the device-side code. MicroPython's bluetooth module provides BLE support. We need to create a BLE Peripheral containing a custom service. import bluetooth import struct import json from ble_advertising import advertising_payload # define custom service UUIDs - can be randomly generated but must be unique _SERVICE_UUID = bluetooth.UUID(0xABCD) # example UUID _STATE_CHAR_UUID = bluetooth.UUID(0xABCE) # characteristic for receiving commands from the computer _L

OG_CHAR_UUID = bluetooth.UUID(0xABCF) # characteristic for sending device logs (optional) class BLEPet: def __init__(self, name="CodeBuddy"): self._ble = bluetooth.BLE() self._ble.active(True) self._ble.irq(self._irq_handler) self._connections = set() self._state_handlers = [] # list of state-change callbacks # register services state_char = (bluetooth.UUID(_STATE_CHAR_UUID), bluetooth.FLAG_WRITE | bluetooth.FLAG_NOTIFY,) log_char = (bluetooth.UUID(_LOG_CHAR_UUID), bluetoot

h.FLAG_READ | bluetooth.FLAG_NOTIFY,) service = (_SERVICE_UUID, (state_char, log_char),) services = (service,) ((self._state_handle, self._log_handle),) = self._ble.gatts_register_services(services) # set initial characteristic values self._ble.gatts_write(self._state_handle, b'\x00') # initial state 0 self._ble.gatts_write(self._log_handle, b'Hello from CodeBuddy!') # set connectable advertising payload = advertising_payload(name=name, services=[_SERVICE_UUI

D]) self._ble.gap_advertise(100000, adv_data=payload) print("BLE Advertising started, name:", name) def _irq_handler(self, event, data): # handle BLE events: connect, disconnect, write, etc. if event == 1: # _IRQ_CENTRAL_CONNECTED conn_handle, addr_type, addr = data self._connections.add(conn_handle) print("Connected by:", addr) elif event == 2: # _IRQ_CENTRAL_DISCONNECTED conn_handle, addr_type, addr = data if conn_handle in self._connection

s: self._connections.remove(conn_handle) print("Disconnected:", addr) # resume advertising self._ble.gap_advertise(100000) elif event == 3: # _IRQ_GATTS_WRITE conn_handle, value_handle = data if value_handle == self._state_handle: # received a new state command from the computer received_data = self._ble.gatts_read(value_handle) self._process_command(received_data) def _process_command(self, data): try: cmd_dict = json.loads(data.decode("utf-8")) cmd = cm

d_dict.get("cmd") if cmd == "set_state": new_state = cmd_dict.get("state") print("New state received:", new_state) # trigger all registered state handlers for handler in self._state_handlers: handler(new_state) except Exception as e: print("Command process error:", e) def register_state_handler(self, handler): # register a state-change handler self._state_handlers.append(handler) This code builds the skeleton of the BLE service. The _process_command method parses the JSON commands sent from the computer and calls the registered state handlers. These handlers will be responsible for updating the screen, lights

and motor. 4.3 Multitasking Management and State Machine Implementation MicroPython itself supports simple multithreading via the _thread module, but for this project using asynchronous programming with asyncio is a more elegant and efficient choice - it handles concurrent I/O operations such as BLE events, encoder scanning, and animation refresh better. import uasyncio as asyncio from machine import Pin, PWM import neopixel import st7789 import sht30 class PetStateMachine: def __init__(self): self.current_state = "idle" self.screen = st7789.ST7789(...) # initialize the screen self.leds = neopixel.NeoPixel(Pin(2), 24) # ring of 24 LEDs self.motor = Pin(4, Pin.OUT)

self.encoder = RotaryEncoder(pin_clk=32, pin_dt=33, pin_sw=25) self.sensor = sht30.SHT30() # mapping of states to their handler functions self.state_actions = { "idle": self._state_idle, "working": self._state_working, "remind": self._state_remind, "celebrate": self._state_celebrate } async def run(self): # main async loop while True: action = self.state_actions.get(self.current_state) if action: await action() # execute the current state's task await asyncio.sleep(0.1) # release control

back async def _state_idle(self): # idle state: screen shows sleeping expression, lights slowly breathe blue self.screen.display_image("sleep.png") await self._breathing_effect((0, 0, 50)) # blue breathing # check encoder or sensor events if self.encoder.button_pressed(): self.change_state("working") async def _state_working(self): # working state: screen shows focused expression, lights steady green self.screen.display_image("working.png") self.leds.fill((0, 50, 0)) self.leds.write() # you can read sensor data here, e.g., temperature and humidity every 10 seconds # temp, humi = self.sen

sor.measure() # if temp > 30: # self.screen.show_text("Hot!") async def _state_remind(self): # reminding state: screen shows warning expression, lights flash red, motor vibrates briefly self.screen.display_image("warning.png") for _ in range(5): # flash 5 times self.leds.fill((50, 0, 0)) self.leds.write() self.motor.value(1) await asyncio.sleep(0.2) self.leds.fill((0, 0, 0)) self.leds.write() self.motor.value(0) await asyncio.sleep(0.2) # after reminding, automatically return to idle or working state self.change_state("idle")

async def _state_celebrate(self): # celebrating state: screen shows happy expression, rainbow light effect, motor vibrates long twice self.screen.display_image("celebrate.png") self.motor.value(1) await asyncio.sleep(0.5) self.motor.value(0) await asyncio.sleep(0.2) self.motor.value(1) await asyncio.sleep(0.5) self.motor.value(0) await self._rainbow_effect(cycles=2) self.change_state("working") def change_state(self, new_state): # safely switch state if new_state in self.state_actions: pri

nt(f"State change: {self.current_state} -> {new_state}") self.current_state = new_state # ... light effect functions _breathing_effect, _rainbow_effect ... This state machine class is the core of the entire "pet" behavior logic. The run() method is the main loop of the async task; it continuously executes the behavior function corresponding to the current state. State switching is triggered via the change_state method, which can be called by BLE commands, encoder button presses, or internal conditions such as sensor thresholds being exceeded. 4.4 Main Program Integration and Startup Finally, we need a main file to integrate all modules and start everything. # main.py import uasyncio as asyncio from ble_pet import BLEPet from pet_state_machine import PetStateMachine async def main():

KeyboardInterrupt: print("Program stopped by user.") finally: # cleanup, e.g., turn off lights pass Upload main.py, ble_pet.py, pet_state_machine.py, and the related driver libraries st7789.py, sht30.py, etc., to the ESP32's filesystem via a serial tool such as ampy, rshell, or the VS Code MicroPython plugin. After restarting, the device will begin advertising and wait for a connection. 5. Computer-Side CLI Daemon Development 5.1 Monitoring the Developer's Activity State The core of the computer-side program is to determine whether the developer is "working effectively". Several approaches are provided here and can be combined to improve accuracy. Active window/process monitoring: use Python's psutil library to periodically check the process name of the currently focused window. If a browser (chrome.exe, firefox.exe) is detected with non-development-related tabs, or a game process is detected, classify it as "possibly slacking off". import psutil

def get_active_process(): # this method is implemented differently on Windows/macOS/Linux; the following is a simplified example # you may need libraries such as pygetwindow or Quartz (macOS) # return the process name or None pass Filesystem monitoring: use the watchdog library to listen for modification events of source code files (.py, .js, .go, etc.) in the project directory. If there are no modification events within a set time window, e.g., 15 minutes, classify it as "idle". from watchdog.observers import Observer from watchdog.events import FileSystemEventHandler class CodeChangeHandler(FileSystemEventHandler): def on_modified(self, event): if not event.is_directory and eve

nt.src_path.endswith((".py", ".js")): update_last_activity_time() # update the last-activity timestamp IDE/editor integration: this is the most accurate approach. You can develop plugins for editors such as VS Code or IntelliJ to directly listen to editor activity events such as file saves, typing pauses, and test runs. However, this requires developing for different editors and is more complex. A compromise is to read temporary files or logs generated by the editor. 5.2 Interaction with Claude Code CLI The goal is to capture the output of Claude Code CLI and parse key information. One feasible method is to wrap the CLI command. Subprocess communication: your daemon starts Claude Code CLI as a subprocess and captures its standard output (stdout) in real time. import subprocess import threading def run_claude_cli(): proc = subprocess.Popen([claud

e", "code", "--your-flags"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) for line in iter(proc.stdout.readline, ""): if "It looks like you haven't written code for a while" in line: trigger_state("remind") elif "Great job! This implementation looks solid." in line: trigger_state("celebrate") Use the official API/SDK if provided: if Claude Code offers a programming interface, calling it directly is a more stable and efficient approach. You will need to consult its official documentation. 5.3 BLE Communication Client Implementation On the computer side, we need a BLE Central device to connect to the ESP32. In Python

you can use the excellent cross-platform BLE library bleak. import asyncio from bleak import BleakClient, BleakScanner import json ESP32_DEVICE_NAME = "CodeBuddy" STATE_CHAR_UUID = "0000abce-0000-1000-8000-00805f9b34fb" # must match the device side async def connect_and_control(): device = None # 1. scan for devices devices = await BleakScanner.discover() for d in devices: if d.name and ESP32_DEVICE_NAME in d.name: device = d break if not device: print("Device not found.")

return # 2. connect and send commands async with BleakClient(device.address) as client: print(f"Connected to {device.name}") # example: send the "remind" state remind_cmd = json.dumps({"cmd": "set_state", "state": "remind"}).encode("utf-8") await client.write_gatt_char(STATE_CHAR_UUID, remind_cmd) print("Remind command sent.") # you can keep the connection to listen for notifications from the device, e.g., logs # await client.start_notify(LOG_CHAR_UUID, notification_handler) # await asyncio.sleep(60) # keep the connection for a while #

await client.stop_notify(LOG_CHAR_UUID) def trigger_state(state_name): # function to be called by the activity monitoring module asyncio.run(send_ble_command(state_name)) async def send_ble_command(state): # simplified send function cmd = json.dumps({"cmd": "set_state", "state": state}).encode("utf-8") # ... the connection and write code is the same as above ... 5.4 Daemon Integration and Auto-Start Integrate the three modules - activity monitoring, CLI interaction, and BLE communication - into one main daemon process, and use an event loop to coordinate them. # daemon_main.py import asyncio import threading from activity_monitor import Activity

暂无评论,快来发表第一条评论吧!No comments yet. Be the first!

📮 需求咨询📮 Inquiry