50块的ESP32-S3,人走自动锁屏、靠近无感解锁、重启免敲密码
零外接零件 · iPhone 免装任何 App · 毫秒级纯硬件响应 · 成本约 ¥45
平时在工位用 Mac,总有几个不大不小但天天烦人的痛点:
- 起身去倒水、上厕所,总忘了按
Ctrl + Cmd + Q锁屏; - 走回工位要重新敲密码(有时手湿或者外接显示器合盖用不了 Touch ID);
- 重启电脑时,无论平时多丝滑,开机登录界面必须手动敲一遍密码;
- 写代码一投入就是两三个小时不起身,腰酸背痛。
最近买了一块大拇指大小的 Seeed Studio XIAO ESP32S3(约 45 元),利用它自带的 原生 USB-OTG + BLE 5.0 + 硬件 AES 加速,不焊一根线、不在 iPhone 上装任何 App,做了一套稳定跑在日常桌面上的 「蓝牙无感锁屏/解锁 + 重启自动输开机密码 + 45 分钟久坐提醒」 系统。
这篇文章把整套架构、最容易踩的 3 个硬核深坑,以及最终的解法完整复盘出来。
一、 最终实现了什么效果?
插在 Mac(或桌面拓展坞)的 USB-C 口上,平时几乎感觉不到它的存在:
- 人走自动锁屏:带着 iPhone 离开工位,板载橙灯从常亮变为闪烁,满 6 秒后自动模拟
Ctrl + Cmd + Q锁屏。 - 人来无感解锁:走回工位,橙灯瞬间恢复常亮并快闪 3 下,自动唤醒屏幕、输入密码并回车进入桌面。
- 重启免输开机密码:重启电脑卡在开机登录 / FileVault 界面时,只要你的手机就在桌前,等待约 14 秒自动帮你把开机密码 + 回车敲进去(软件方案做不到,因为此时系统还没进桌面)。
- 45 分钟久坐提醒 & 工位出勤报告:记录每天几点到达、几点离座/拔线开会、累计在座时长;连续坐满 45 分钟弹出 macOS 原生系统通知提醒起身喝水。
- 零侵入体验:iPhone 不装 App、不占虚拟键盘、不影响 AirPods/Apple Watch;带 MacBook 拔掉拓展坞去开会时,后台自动暂停计时并静默休眠。
二、 整体架构设计
核心思路是把 XIAO ESP32S3 变成一个 USB 复合设备(USB HID 键盘 + USB CDC 串口),同时运行 BLE 被动扫描器,与 Mac 端一个仅几十行的轻量 Python 心跳守护进程配合:
iPhone(锁屏放兜里)
│ BLE 随机 MAC 广播(~0.3s)
▼
XIAO ESP32S3(硬件 AES + IRK 解析实时距离 RSSI)
│ 三态状态机(BOOT_WAIT / LOCKED / UNLOCKED)
├──▶ USB HID 键盘 ──▶ Mac 登录框 / 桌面(自动输密码 / Ctrl+Cmd+Q 锁屏)
└──◀ USB 串口心跳 ◀── Mac LaunchAgent(每 1.5s 汇报锁屏状态 + 45 分钟久坐提醒 + 工位日志)三、 最核心的 3 个技术深坑与解法
真正动手做时,有三个坑是几乎所有同类 DIY 都会撞上的:
坑 1:iPhone 蓝牙 MAC 随机变化,且离开后不会自动回连
踩坑现象:
- iPhone 为了防追踪,BLE 广播地址(RPA)每 15 分钟随机更换一次,直接扫固定 MAC 地址根本行不通。
- 如果只做一个普通 BLE 从机让 iPhone 连接,离开断开后,iOS 系统默认不会在后台自动回连普通 BLE 服务(除非伪装成蓝牙键盘,但那样又会隐藏 iPhone 的屏幕输入法,严重影响手机正常使用)。
终极解法:BLE 一次配对拿 IRK + 硬件 AES 被动扫描
- XIAO 广播一个最简单的非 HID 电池服务(
0x180F),iPhone 在系统蓝牙里配对一次(只需一次,之后哪怕彻底断开连接也没关系)。配对时,iPhone 会把它的 16 字节 IRK(身份解析密钥) 安全存入 XIAO 的 NVS Flash。 - 固件开启 持续被动 BLE 扫描,每收到一条广播包,利用 ESP32-S3 的 硬件 AES-128(
mbedtls_aes_crypt_ecb,耗时仅数微秒)实时验证该随机地址是否由主人的 IRK 派生(同时兼容 BLE 控制器硬件解析后的 Identity Address)。 - 效果:iPhone 即使锁屏放在裤兜里、蓝牙完全不保持连接,因为苹果生态的 Continuity/FindMy 广播每 ~0.3 秒就会发一次包,XIAO 依然能以 ~300ms 延迟 精准锁定主人的实时距离(RSSI)!
- XIAO 广播一个最简单的非 HID 电池服务(
坑 2:怎么确保绝不在微信聊天框里误输入密码?
硬件键盘最大的安全隐患,就是状态判断失误,在正常聊天或写代码时把密码敲出去。
- 解法:三态状态机 + Mac 端零依赖心跳
Mac 端通过LaunchAgent开机自启一个纯标准库 Python 脚本,每 1.5 秒用系统自带的ioreg -n Root -d1读取CGSSessionScreenIsLocked状态,通过 USB 串口发给 XIAO:
| 当前状态 | 判定依据 | 行为策略 |
|---|---|---|
UNLOCKED(正常用电脑) | 持续收到 HB UNLOCKED 心跳 | 彻底锁死输密码功能,绝不误触发;若开启 auto_lock,离座闪烁满 6 秒发 Ctrl+Cmd+Q 锁屏 |
LOCKED(平时锁屏) | 收到 HB LOCKED 心跳 | 必须先检测到离开(橙灯闪烁 ≥ 2 秒)再走回桌前(常亮),才触发自动输密码解锁,避免和手动锁屏打架 |
BOOT_WAIT(重启开机密码) | USB 重新上电(或心跳中断 > 15s)且 14 秒内未收到任何桌面心跳 | 确认卡在开机登录界面 + 检测到主人在面前 → 自动唤醒并输密码回车(最多安全重试 2 次) |
- 开会拔掉拓展坞怎么处理?
拔掉拓展坞时,心跳脚本捕获串口OSError,自动将此前在座时长结算并记为[拔线/开会],暂停久坐计时后安静休眠;开完会插回拓展坞,2 秒内即恢复HB UNLOCKED(远早于 14 秒的开机触发阈值),绝不会误输密码。
坑 3:唤醒密码框的细节 & 安全防护
- 千万别用空格键唤醒屏幕:如果密码框已经聚焦,按空格会把一个空格输进密码框导致密码错误。
- 正确姿势:用
Left Shift唤醒屏幕 → 等待 700ms → 发送Cmd + A+Backspace清空可能存在的误触字符 → 逐字符输入密码(每键间隔 18ms)→Return回车。 - 密码存储安全:密码不写死在源码里,而是通过命令行
getpass隐藏输入后直接写入 XIAO 的 NVS Flash;且只有主人的 IRK 处于近距离时才会触发输入,别人拔走板子也按不出密码。
四、 零刷机叠 Buff:45 分钟久坐提醒 & 工位报告
既然 Mac 后台已经在和 XIAO 通信,顺手每 5 秒轮询一次板子的 STATUS(读取 near 和 rssi),直接利用 Mac 的精准系统时钟,就能不重刷固件实现工位健康助手:
- 日志存储:本地追加写入极简
presence_log.jsonl,只记录状态切换事件(arrive、leave、unplug、sedentary_alert),一年不到 1MB,零损耗板子 Flash。 - 久坐提醒:连续在座满 45 分钟,通过
osascript弹出 macOS 原生系统通知提醒起身喝水;真正离开或拔线满 2 分钟自动重置计时。 - 终端报告:一行命令
python3 xiao_ctl.py report即可看到清晰的时间轴:
=== 今日工位报告 (2026-11-26 ~ 2026-11-26) ===
首次到达:2026-11-26 15:00:51
累计在座:0 小时 4 分钟
离座/开会:1 次 | 最长连续:3.9 分钟 | 久坐提醒:0 次
当前状态:在座中(已连续 3.9 分钟,45 分钟触发提醒)
时间段明细:
15:00 - 15:01 (0.5 分钟) [拔线/开会]
15:16 - 进行中 (3.9 分钟) [在座中]五、 性能消耗:大炮打蚊子
这套全功能系统跑在 XIAO ESP32S3 上,连芯片 5% 的功力都没用到:
- CPU(双核 240MHz):
< 3% - Flash(8MB):仅占
636 KB(19%) - 内存:内部 SRAM 仅占
66 KB(20%),板载 8MB PSRAM 占用 0% - Wi-Fi 模块 & 剩余 9 个 GPIO:完全闲置
后续还可以非常轻松地在这块板子上继续叠 Buff:接一颗 ¥2 的 WS2812 RGB 彩灯 做呼吸状态灯、接一颗 ¥5 的 EC11 旋钮 兼职桌面音量控制器,甚至用闲置的 Wi-Fi 联动家里台灯实现「人来亮灯解锁、人走关灯锁屏」。
六、 快速复刻清单与注意事项
- 硬件:Seeed Studio XIAO ESP32S3(普通版即可,记得扣上盒子里自带的 U.FL 小天线,无需焊接排针)。
- 工具链:
arduino-cli+esp32:[email protected]+[email protected]。 macOS 系统设置:
系统设置 → 隐私与安全性 → 允许配件连接设为 「始终」(确保重启到开机密码界面时系统第一秒就信任 USB 键盘)。- 如果有多个登录账号导致开机停在选头像界面,可将多余账号在登录窗口隐藏。
首次配置:
- iPhone 蓝牙配对
MacAutoUnlock; - 终端执行
xiao_ctl.py set-pwd写入密码、xiao_ctl.py install-agent安装开机自启心跳; 用
xiao_ctl.py watch看一眼自己工位的 RSSI 数值,按需用set-rssi微调距离阈值即可。
- iPhone 蓝牙配对
七、 完整源码(点击展开复制)
整套方案只有 3 个文件,全部零第三方 Python 依赖、无硬编码敏感信息,直接复制即可复刻:
1. XIAO ESP32S3 固件:
firmware/firmware.ino(约 460 行)
/*
* XIAO ESP32S3 - Mac BLE Proximity Auto-Unlock & Reboot Password Typer
*
* v2: Hardware-AES IRK Passive BLE Scanning!
* - Even after iPhone disconnects from BLE GATT, XIAO passively scans Apple Continuity
* BLE advertisements and resolves your bonded iPhone's rotating random MAC address
* using its stored 16-byte IRK (Identity Resolving Key) via ESP32 hardware AES.
* - Zero connection drops! Zero reliance on iOS background auto-reconnect!
* - Zero iPhone App needed! Never hides iPhone on-screen keyboard!
*/
#include <Arduino.h>
#include <Preferences.h>
#include <NimBLEDevice.h>
#include <host/ble_gap.h>
#include <host/ble_store.h>
#include <mbedtls/aes.h>
#include "USB.h"
#include "USBHIDKeyboard.h"
// XIAO ESP32S3 pins
static const int LED_PIN = 21; // Active LOW
static const int BTN_PIN = 0; // BOOT button, Active LOW
// USB HID Keyboard (global so TinyUSB registers it before app_main USB.begin)
USBHIDKeyboard Keyboard;
Preferences prefs;
enum MacState {
STATE_BOOT_WAIT = 0,
STATE_MAC_LOCKED = 1,
STATE_MAC_UNLOCKED = 2
};
static MacState macState = STATE_BOOT_WAIT;
static unsigned long bootStartMs = 0;
static unsigned long lastHeartbeatMs = 0;
static unsigned long lockedSinceMs = 0;
static unsigned long lastUnlockAttemptMs = 0;
static unsigned long notNearSinceMs = 0;
static int bootAttempts = 0;
static bool everGotHeartbeat = false;
static bool wasAwayWhileLocked = false;
static bool autoLockTriggered = false;
// Settings (persisted in NVS)
static String storedPassword = "";
static int rssiNear = -72; // dBm: closer than this = near (~1.5m)
static int rssiAway = -86; // dBm: weaker than this = away
static unsigned long bootWaitMs = 14000;
static bool optBootUnlock = true;
static bool optAutoUnlock = true;
static bool optAutoLock = false;
// BLE & IRK Passive Scan State
static NimBLEServer* pServer = nullptr;
static volatile bool bleConnected = false;
static volatile bool bleBonded = false;
static volatile uint16_t bleConnHandle = BLE_HS_CONN_HANDLE_NONE;
static volatile int8_t currentRssi = -127;
static volatile int8_t smoothRssi = -127;
static volatile unsigned long lastOwnerSeenMs = 0;
static unsigned long lastRssiReadMs = 0;
static unsigned long lastDisconnectMs = 0;
// Stored peer IRKs & identity addresses (up to 4 bonded devices)
static uint8_t peerIrks[4][16];
static uint8_t peerAddrs[4][6];
static volatile int peerIrkCount = 0;
static volatile unsigned long scanPktCount = 0;
// Button debounce
static bool lastBtnState = HIGH;
static unsigned long lastBtnChangeMs = 0;
// Serial line buffer
static String serialBuf = "";
static void setLed(bool on) {
digitalWrite(LED_PIN, on ? LOW : HIGH);
}
static void blinkLed(int count, int ms = 80) {
for (int i = 0; i < count; i++) {
setLed(true);
delay(ms);
setLed(false);
delay(ms);
}
}
static int irkStoreCb(int obj_type, union ble_store_value* val, void* cookie) {
if (obj_type == BLE_STORE_OBJ_TYPE_PEER_SEC && val->sec.irk_present && peerIrkCount < 4) {
memcpy(peerIrks[peerIrkCount], val->sec.irk, 16);
memcpy(peerAddrs[peerIrkCount], val->sec.peer_addr.val, 6);
peerIrkCount++;
}
return 0;
}
static void reloadPeerIrks() {
peerIrkCount = 0;
ble_store_iterate(BLE_STORE_OBJ_TYPE_PEER_SEC, irkStoreCb, nullptr);
}
static bool matchRpaWithIrks(const uint8_t addr_le[6]) {
int count = peerIrkCount;
if (count <= 0) return false;
// 1. Direct match against bonded Identity Address (when BLE controller resolves RPA in hardware)
for (int idx = 0; idx < count; idx++) {
if (memcmp(addr_le, peerAddrs[idx], 6) == 0) {
return true;
}
}
// 2. Software RPA resolution: RPA must have two MSBs = 01 (0x40)
if ((addr_le[5] & 0xC0) != 0x40) return false;
uint8_t pt[16] = {0};
pt[13] = addr_le[5];
pt[14] = addr_le[4];
pt[15] = addr_le[3];
uint8_t key_rev[16];
uint8_t out[16];
mbedtls_aes_context aes;
mbedtls_aes_init(&aes);
bool matched = false;
for (int idx = 0; idx < count; idx++) {
// Try reversed IRK (little-endian -> big-endian)
for (int i = 0; i < 16; i++) {
key_rev[i] = peerIrks[idx][15 - i];
}
if (mbedtls_aes_setkey_enc(&aes, key_rev, 128) == 0 &&
mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_ENCRYPT, pt, out) == 0) {
if (out[13] == addr_le[2] && out[14] == addr_le[1] && out[15] == addr_le[0]) {
matched = true;
break;
}
}
// Also try raw IRK order
if (mbedtls_aes_setkey_enc(&aes, peerIrks[idx], 128) == 0 &&
mbedtls_aes_crypt_ecb(&aes, MBEDTLS_AES_ENCRYPT, pt, out) == 0) {
if (out[13] == addr_le[2] && out[14] == addr_le[1] && out[15] == addr_le[0]) {
matched = true;
break;
}
}
}
mbedtls_aes_free(&aes);
return matched;
}
static void updateRssiSample(int8_t r) {
if (r >= 0 || r <= -120) return;
currentRssi = r;
lastOwnerSeenMs = millis();
if (smoothRssi == -127) {
smoothRssi = r;
} else {
smoothRssi = (int8_t)((smoothRssi * 3 + r) / 4);
}
}
static bool isOwnerRecentlySeen() {
if (bleConnected && (NimBLEDevice::getNumBonds() == 0 || bleBonded)) return true;
if (peerIrkCount > 0 && lastOwnerSeenMs > 0 && (millis() - lastOwnerSeenMs) < 7000UL) return true;
return false;
}
static bool isOwnerNear() {
if (!isOwnerRecentlySeen()) return false;
if (smoothRssi == -127) return false;
return smoothRssi >= rssiNear;
}
static bool isOwnerAway() {
if (!isOwnerRecentlySeen()) {
unsigned long lastSeen = lastOwnerSeenMs;
unsigned long ref = (lastDisconnectMs > lastSeen) ? lastDisconnectMs : lastSeen;
return (millis() - ref) > 4000UL;
}
if (smoothRssi == -127) return false;
return smoothRssi <= rssiAway;
}
static void typePasswordAndEnter(const char* reason) {
if (storedPassword.length() == 0) {
Serial.println("{\"event\":\"skip\",\"reason\":\"no_password_set\"}");
return;
}
Serial.printf("{\"event\":\"typing_password\",\"reason\":\"%s\",\"rssi\":%d}\n", reason, (int)smoothRssi);
blinkLed(3, 60);
// 1. Wake screen safely with Left Shift (never inserts a stray space)
Keyboard.press(KEY_LEFT_SHIFT);
delay(80);
Keyboard.releaseAll();
delay(700);
// 2. Clear any accidental characters in password box (Cmd+A, Backspace)
Keyboard.press(KEY_LEFT_GUI);
Keyboard.press('a');
delay(50);
Keyboard.releaseAll();
delay(60);
Keyboard.write(KEY_BACKSPACE);
delay(120);
// 3. Type password character by character
for (size_t i = 0; i < storedPassword.length(); i++) {
Keyboard.write((uint8_t)storedPassword[i]);
delay(18);
}
delay(120);
// 4. Press Enter
Keyboard.write(KEY_RETURN);
delay(80);
Keyboard.releaseAll();
lastUnlockAttemptMs = millis();
}
static void triggerMacLock() {
Serial.println("{\"event\":\"auto_lock\"}");
// macOS lock shortcut: Ctrl + Cmd + Q
Keyboard.press(KEY_LEFT_CTRL);
Keyboard.press(KEY_LEFT_GUI);
Keyboard.press('q');
delay(80);
Keyboard.releaseAll();
}
class ScanCallbacks : public NimBLEScanCallbacks {
void handleDev(const NimBLEAdvertisedDevice* dev) {
scanPktCount++;
if (peerIrkCount <= 0) return;
const uint8_t* addr = dev->getAddress().getBase()->val;
if (matchRpaWithIrks(addr)) {
updateRssiSample((int8_t)dev->getRSSI());
}
}
void onDiscovered(const NimBLEAdvertisedDevice* dev) override {
handleDev(dev);
}
void onResult(const NimBLEAdvertisedDevice* dev) override {
handleDev(dev);
}
};
class ServerCallbacks : public NimBLEServerCallbacks {
void onConnect(NimBLEServer* srv, NimBLEConnInfo& connInfo) override {
bleConnHandle = connInfo.getConnHandle();
bleConnected = true;
bleBonded = connInfo.isBonded();
if (!connInfo.isEncrypted()) {
NimBLEDevice::startSecurity(bleConnHandle);
}
Serial.printf("{\"event\":\"ble_connect\",\"bonded\":%s}\n", bleBonded ? "true" : "false");
}
void onAuthenticationComplete(NimBLEConnInfo& connInfo) override {
bleBonded = connInfo.isBonded() || connInfo.isEncrypted();
reloadPeerIrks();
Serial.printf("{\"event\":\"ble_auth\",\"bonded\":%s,\"irks\":%d}\n",
bleBonded ? "true" : "false", (int)peerIrkCount);
}
void onDisconnect(NimBLEServer* srv, NimBLEConnInfo& connInfo, int reason) override {
bleConnected = false;
bleBonded = false;
bleConnHandle = BLE_HS_CONN_HANDLE_NONE;
lastDisconnectMs = millis();
Serial.printf("{\"event\":\"ble_disconnect\",\"reason\":%d}\n", reason);
NimBLEDevice::startAdvertising();
}
};
static void loadConfig() {
prefs.begin("autounlock", true);
storedPassword = prefs.getString("pwd", "");
rssiNear = prefs.getInt("rssi_in", -72);
rssiAway = prefs.getInt("rssi_out", -86);
bootWaitMs = (unsigned long)prefs.getInt("boot_ms", 14000);
optBootUnlock = prefs.getBool("boot_u", true);
optAutoUnlock = prefs.getBool("auto_u", true);
optAutoLock = prefs.getBool("auto_l", false);
prefs.end();
}
static void saveConfig() {
prefs.begin("autounlock", false);
prefs.putString("pwd", storedPassword);
prefs.putInt("rssi_in", rssiNear);
prefs.putInt("rssi_out", rssiAway);
prefs.putInt("boot_ms", (int)bootWaitMs);
prefs.putBool("boot_u", optBootUnlock);
prefs.putBool("auto_u", optAutoUnlock);
prefs.putBool("auto_l", optAutoLock);
prefs.end();
}
static const char* stateName(MacState s) {
switch (s) {
case STATE_BOOT_WAIT: return "BOOT_WAIT";
case STATE_MAC_LOCKED: return "LOCKED";
case STATE_MAC_UNLOCKED: return "UNLOCKED";
default: return "UNKNOWN";
}
}
static void printStatus() {
unsigned long seenAge = lastOwnerSeenMs > 0 ? (millis() - lastOwnerSeenMs) : 999999UL;
Serial.printf(
"{\"ok\":true,\"state\":\"%s\",\"ble_connected\":%s,\"irks\":%d,\"scan_pkts\":%lu,\"seen_age_ms\":%lu,"
"\"rssi\":%d,\"near\":%s,\"pwd_set\":%s,\"rssi_near\":%d,\"rssi_away\":%d,"
"\"boot_ms\":%lu,\"boot_unlock\":%s,\"auto_unlock\":%s,\"auto_lock\":%s,"
"\"uptime_ms\":%lu,\"hb_age_ms\":%lu}\n",
stateName(macState),
bleConnected ? "true" : "false",
(int)peerIrkCount,
(unsigned long)scanPktCount,
seenAge,
(int)smoothRssi,
isOwnerNear() ? "true" : "false",
storedPassword.length() > 0 ? "true" : "false",
rssiNear,
rssiAway,
bootWaitMs,
optBootUnlock ? "true" : "false",
optAutoUnlock ? "true" : "false",
optAutoLock ? "true" : "false",
millis(),
everGotHeartbeat ? (millis() - lastHeartbeatMs) : 0UL
);
}
static void handleCommand(String line) {
line.trim();
if (line.length() == 0) return;
if (line == "HB UNLOCKED") {
everGotHeartbeat = true;
lastHeartbeatMs = millis();
if (macState != STATE_MAC_UNLOCKED) {
macState = STATE_MAC_UNLOCKED;
wasAwayWhileLocked = false;
autoLockTriggered = false;
bootAttempts = 0;
}
return;
}
if (line == "HB LOCKED") {
everGotHeartbeat = true;
lastHeartbeatMs = millis();
if (macState != STATE_MAC_LOCKED) {
macState = STATE_MAC_LOCKED;
lockedSinceMs = millis();
wasAwayWhileLocked = !isOwnerNear();
autoLockTriggered = false;
}
return;
}
if (line == "STATUS") {
printStatus();
return;
}
if (line.startsWith("SET_PWD ")) {
storedPassword = line.substring(8);
saveConfig();
Serial.println("{\"ok\":true,\"msg\":\"password saved to NVS\"}");
return;
}
if (line == "CLEAR_PWD") {
storedPassword = "";
saveConfig();
Serial.println("{\"ok\":true,\"msg\":\"password cleared\"}");
return;
}
if (line.startsWith("SET_RSSI ")) {
int sp = line.indexOf(' ', 9);
if (sp > 0) {
rssiNear = line.substring(9, sp).toInt();
rssiAway = line.substring(sp + 1).toInt();
saveConfig();
Serial.printf("{\"ok\":true,\"rssi_near\":%d,\"rssi_away\":%d}\n", rssiNear, rssiAway);
} else {
Serial.println("{\"ok\":false,\"error\":\"usage: SET_RSSI <near> <away>\"}");
}
return;
}
if (line.startsWith("SET_BOOT_MS ")) {
bootWaitMs = (unsigned long)line.substring(12).toInt();
saveConfig();
Serial.printf("{\"ok\":true,\"boot_ms\":%lu}\n", bootWaitMs);
return;
}
if (line.startsWith("SET_OPT ")) {
int sp = line.indexOf(' ', 8);
if (sp > 0) {
String k = line.substring(8, sp);
bool v = (line.substring(sp + 1).toInt() != 0);
if (k == "boot_unlock") optBootUnlock = v;
else if (k == "auto_unlock") optAutoUnlock = v;
else if (k == "auto_lock") optAutoLock = v;
saveConfig();
printStatus();
}
return;
}
if (line == "CLEAR_BONDS") {
NimBLEDevice::deleteAllBonds();
reloadPeerIrks();
lastOwnerSeenMs = 0;
smoothRssi = -127;
Serial.println("{\"ok\":true,\"msg\":\"all BLE bonds cleared\"}");
return;
}
if (line == "TEST_WAKE") {
Keyboard.press(KEY_LEFT_SHIFT);
delay(60);
Keyboard.releaseAll();
Serial.println("{\"ok\":true,\"msg\":\"sent left shift\"}");
return;
}
Serial.println("{\"ok\":false,\"error\":\"unknown command\"}");
}
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BTN_PIN, INPUT_PULLUP);
setLed(false);
Serial.begin(115200);
Keyboard.begin();
USB.begin();
loadConfig();
bootStartMs = millis();
// Initialize NimBLE (Peripheral for one-time pairing + Passive Scanner for IRK tracking)
NimBLEDevice::init("MacAutoUnlock");
NimBLEDevice::setPower(ESP_PWR_LVL_P9);
NimBLEDevice::setSecurityAuth(true, false, true); // bond=true, mitm=false, sc=true
NimBLEDevice::setSecurityIOCap(BLE_HS_IO_NO_INPUT_OUTPUT);
reloadPeerIrks();
pServer = NimBLEDevice::createServer();
pServer->setCallbacks(new ServerCallbacks());
NimBLEService* batSvc = pServer->createService(NimBLEUUID((uint16_t)0x180F));
NimBLECharacteristic* batChar = batSvc->createCharacteristic(
NimBLEUUID((uint16_t)0x2A19),
NIMBLE_PROPERTY::READ | NIMBLE_PROPERTY::READ_ENC | NIMBLE_PROPERTY::NOTIFY
);
uint8_t level = 100;
batChar->setValue(&level, 1);
batSvc->start();
NimBLEAdvertising* adv = NimBLEDevice::getAdvertising();
adv->addServiceUUID(NimBLEUUID((uint16_t)0x180F));
adv->setName("MacAutoUnlock");
adv->enableScanResponse(true);
adv->start();
// Continuous passive BLE scan to resolve bonded iPhone's rotating RPA via IRK
NimBLEScan* pScan = NimBLEDevice::getScan();
pScan->setScanCallbacks(new ScanCallbacks(), true); // wantDuplicates = true
pScan->setActiveScan(false);
pScan->setInterval(100);
pScan->setWindow(60);
pScan->setMaxResults(0);
pScan->start(0, false);
blinkLed(2, 100);
}
void loop() {
unsigned long now = millis();
// 1. Read USB Serial commands & heartbeats
while (Serial.available()) {
char c = (char)Serial.read();
if (c == '\n' || c == '\r') {
if (serialBuf.length() > 0) {
handleCommand(serialBuf);
serialBuf = "";
}
} else if (serialBuf.length() < 256) {
serialBuf += c;
}
}
// 2. Also poll connection RSSI if actively connected
if (bleConnected && bleConnHandle != BLE_HS_CONN_HANDLE_NONE && (now - lastRssiReadMs >= 500)) {
lastRssiReadMs = now;
int8_t r = -127;
if (ble_gap_conn_rssi(bleConnHandle, &r) == 0) {
updateRssiSample(r);
}
}
// Expire stale smoothRssi if owner hasn't been seen for > 10s
if (!isOwnerRecentlySeen() && lastOwnerSeenMs > 0 && (now - lastOwnerSeenMs > 10000UL)) {
smoothRssi = -127;
}
// 3. Track "not near" duration (matches LED blinking -> WYSIWYG!)
if (!isOwnerNear()) {
if (notNearSinceMs == 0) notNearSinceMs = now;
} else {
notNearSinceMs = 0;
}
// 4. Physical BOOT button manual trigger (only when NOT unlocked)
bool btn = digitalRead(BTN_PIN);
if (btn != lastBtnState && (now - lastBtnChangeMs > 50)) {
lastBtnChangeMs = now;
lastBtnState = btn;
if (btn == LOW && macState != STATE_MAC_UNLOCKED) {
if (isOwnerNear() || peerIrkCount == 0) {
typePasswordAndEnter("manual_button");
}
}
}
// 5. State machine automation
if (macState == STATE_BOOT_WAIT) {
if (optBootUnlock && !everGotHeartbeat && storedPassword.length() > 0) {
unsigned long waitNeeded = (bootAttempts == 0) ? bootWaitMs : 18000UL;
unsigned long refTime = (bootAttempts == 0) ? bootStartMs : lastUnlockAttemptMs;
if (bootAttempts < 2 && (now - refTime >= waitNeeded) && isOwnerNear()) {
bootAttempts++;
typePasswordAndEnter("reboot_login");
}
}
} else if (macState == STATE_MAC_LOCKED) {
// WYSIWYG: as soon as LED blinks (!isOwnerNear) for >= 2s while locked, returning to solid LED unlocks!
if (notNearSinceMs > 0 && (now - notNearSinceMs >= 2000UL)) {
wasAwayWhileLocked = true;
}
if (optAutoUnlock && wasAwayWhileLocked && isOwnerNear() && storedPassword.length() > 0) {
if (now - lastUnlockAttemptMs >= 10000UL) {
wasAwayWhileLocked = false;
typePasswordAndEnter("proximity_return");
}
}
} else if (macState == STATE_MAC_UNLOCKED) {
if (everGotHeartbeat && (now - lastHeartbeatMs > 15000UL)) {
macState = STATE_BOOT_WAIT;
everGotHeartbeat = false;
bootStartMs = now;
bootAttempts = 0;
}
if (optAutoLock && !autoLockTriggered && notNearSinceMs > 0 && (now - notNearSinceMs >= 6000UL)) {
autoLockTriggered = true;
triggerMacLock();
}
}
// 6. LED status: solid ON when owner near, slow blink otherwise
if (isOwnerNear()) {
setLed(true);
} else {
setLed(((now / 1000) % 2) == 0);
}
delay(20);
}2. Mac 后台心跳 + 45 分钟久坐提醒:
mac_heartbeat.py(约 170 行)
#!/usr/bin/env python3
"""
Lightweight macOS heartbeat + presence logger + 45-min sedentary reminder
for XIAO ESP32S3 Auto-Unlock.
Zero third-party dependencies (stdlib + macOS ioreg/osascript).
"""
import glob
import json
import os
import re
import select
import subprocess
import termios
import time
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
LOG_FILE = os.path.join(SCRIPT_DIR, "presence_log.jsonl")
SEDENTARY_MINUTES = 45
ALERT_REPEAT_MINUTES = 15
REST_RESET_SECONDS = 120 # Leave >= 2 min to reset sitting timer
LEAVE_CONFIRM_SECONDS = 10 # Avoid logging brief 1-2s RSSI flickers
def is_screen_locked() -> bool:
try:
out = subprocess.check_output(["ioreg", "-n", "Root", "-d1"], text=True, timeout=3)
return bool(re.search(r'CGSSessionScreenIsLocked["\']?\s*=\s*(Yes|1|true)', out, re.I))
except Exception:
return False
def find_xiao_port():
ports = sorted(glob.glob("/dev/cu.usbmodem*"))
return ports[0] if ports else None
def open_serial(port_path: str) -> int:
fd = os.open(port_path, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
attrs = termios.tcgetattr(fd)
attrs[4] = attrs[5] = termios.B115200
attrs[3] &= ~(termios.ECHO | termios.ICANON)
termios.tcsetattr(fd, termios.TCSANOW, attrs)
return fd
def log_event(event: str, **extra):
rec = {
"ts": time.strftime("%Y-%m-%d %H:%M:%S"),
"epoch": round(time.time(), 1),
"event": event,
}
rec.update(extra)
try:
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
except OSError:
pass
def notify_sedentary(sit_min: int):
msg = f"你已连续在工位坐满 {sit_min} 分钟,起来喝口水活动 2 分钟吧!"
script = f'display notification "{msg}" with title "久坐提醒 · XIAO" sound name "Glass"'
try:
subprocess.run(["osascript", "-e", script], timeout=5, stderr=subprocess.DEVNULL)
except Exception:
pass
def query_status(fd: int):
# Drain stale bytes
try:
while True:
chunk = os.read(fd, 4096)
if not chunk:
break
except BlockingIOError:
pass
os.write(fd, b"STATUS\n")
buf = b""
end = time.time() + 0.4
while time.time() < end:
r, _, _ = select.select([fd], [], [], 0.1)
if r:
try:
buf += os.read(fd, 4096)
except BlockingIOError:
pass
if b"\n" in buf:
break
for line in buf.decode("utf-8", errors="replace").splitlines():
line = line.strip()
if line.startswith("{") and '"ok":true' in line:
try:
return json.loads(line)
except Exception:
pass
return None
def main():
fd = None
tick = 0
in_seat = False
sit_start_ts = 0.0
not_near_since = 0.0
away_since = 0.0
last_alert_ts = 0.0
while True:
try:
if fd is None:
port = find_xiao_port()
if port:
fd = open_serial(port)
tick = 0
else:
time.sleep(2.0)
continue
locked = is_screen_locked()
os.write(fd, b"HB LOCKED\n" if locked else b"HB UNLOCKED\n")
tick += 1
if tick % 3 == 1:
st = query_status(fd)
if st and isinstance(st.get("near"), bool):
now = time.time()
near = st["near"]
rssi = st.get("rssi", -127)
if near:
not_near_since = 0.0
if not in_seat:
in_seat = True
if away_since == 0.0 or (now - away_since) >= REST_RESET_SECONDS:
sit_start_ts = now
last_alert_ts = 0.0
away_since = 0.0
log_event("arrive", rssi=rssi)
else:
# Check 45-min sedentary threshold while actively at desk (unlocked)
if not locked and sit_start_ts > 0:
sit_min = (now - sit_start_ts) / 60.0
if sit_min >= SEDENTARY_MINUTES:
if last_alert_ts == 0.0 or (now - last_alert_ts) >= ALERT_REPEAT_MINUTES * 60:
last_alert_ts = now
notify_sedentary(int(round(sit_min)))
log_event("sedentary_alert", sit_min=round(sit_min, 1))
else:
if in_seat:
if not_near_since == 0.0:
not_near_since = now
elif (now - not_near_since) >= LEAVE_CONFIRM_SECONDS:
in_seat = False
away_since = not_near_since
sit_min = round((away_since - sit_start_ts) / 60.0, 1) if sit_start_ts > 0 else 0.0
log_event("leave", sit_min=sit_min, rssi=rssi)
else:
try:
os.read(fd, 1024)
except BlockingIOError:
pass
time.sleep(1.5)
except OSError:
# USB hub / XIAO unplugged (e.g., taking MacBook to a meeting)
if in_seat:
now = time.time()
sit_min = round((now - sit_start_ts) / 60.0, 1) if sit_start_ts > 0 else 0.0
log_event("unplug", sit_min=sit_min)
in_seat = False
away_since = now
not_near_since = 0.0
if fd is not None:
try:
os.close(fd)
except OSError:
pass
fd = None
time.sleep(2.0)
except KeyboardInterrupt:
break
if __name__ == "__main__":
main()3. 命令行配置 & 工位报告工具:
xiao_ctl.py(约 210 行)
#!/usr/bin/env python3
"""
CLI configurator for XIAO ESP32S3 Mac Auto-Unlock.
Usage:
python3 xiao_ctl.py status # View live BLE/RSSI/state
python3 xiao_ctl.py watch # Live-monitor RSSI every 1s (great for tuning distance)
python3 xiao_ctl.py set-pwd # Securely prompt & store Mac password in XIAO NVS Flash
python3 xiao_ctl.py clear-pwd # Erase stored password from XIAO Flash
python3 xiao_ctl.py set-rssi -72 -86 # Set near / away dBm thresholds
python3 xiao_ctl.py set-opt auto_lock 1 # Toggle boot_unlock / auto_unlock / auto_lock (0 or 1)
python3 xiao_ctl.py clear-bonds # Forget paired iPhone
python3 xiao_ctl.py install-agent # Install macOS LaunchAgent (auto-starts heartbeat on login)
python3 xiao_ctl.py uninstall-agent # Remove macOS LaunchAgent
python3 xiao_ctl.py report [today|week] # Show desk presence & sedentary report
"""
import datetime
import getpass
import glob
import json
import os
import select
import subprocess
import sys
import termios
import time
PLIST_LABEL = "com.xiao.mac-autounlock"
PLIST_PATH = os.path.expanduser(f"~/Library/LaunchAgents/{PLIST_LABEL}.plist")
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
HEARTBEAT_SCRIPT = os.path.join(SCRIPT_DIR, "mac_heartbeat.py")
LOG_FILE = os.path.join(SCRIPT_DIR, "presence_log.jsonl")
def find_port():
ports = sorted(glob.glob("/dev/cu.usbmodem*"))
if not ports:
raise SystemExit("未检测到 XIAO ESP32S3(/dev/cu.usbmodem*),请确认已插好 USB-C 线。")
return ports[0]
def send_cmd(cmd: str, wait_s: float = 2.0) -> str:
port = find_port()
fd = os.open(port, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
try:
attrs = termios.tcgetattr(fd)
attrs[4] = attrs[5] = termios.B115200
attrs[3] &= ~(termios.ECHO | termios.ICANON)
termios.tcsetattr(fd, termios.TCSANOW, attrs)
# Drain stale bytes
try:
os.read(fd, 4096)
except BlockingIOError:
pass
os.write(fd, (cmd + "\n").encode("utf-8"))
buf = b""
end = time.time() + wait_s
while time.time() < end:
r, _, _ = select.select([fd], [], [], 0.2)
if r:
buf += os.read(fd, 4096)
if b"\n" in buf:
break
return buf.decode("utf-8", errors="replace").strip()
finally:
os.close(fd)
def install_agent():
plist = f"""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>{PLIST_LABEL}</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/python3</string>
<string>{HEARTBEAT_SCRIPT}</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
<key>StandardErrorPath</key>
<string>/tmp/{PLIST_LABEL}.err</string>
</dict>
</plist>
"""
os.makedirs(os.path.dirname(PLIST_PATH), exist_ok=True)
with open(PLIST_PATH, "w", encoding="utf-8") as f:
f.write(plist)
subprocess.run(["launchctl", "unload", PLIST_PATH], stderr=subprocess.DEVNULL)
subprocess.run(["launchctl", "load", PLIST_PATH], check=True)
print(f"已安装并启动 Mac 心跳守护进程:{PLIST_PATH}")
def show_report(scope: str = "today"):
if not os.path.exists(LOG_FILE):
print("暂无工位记录(等心跳进程记录第一条在座事件后即可查看)。")
return
today = datetime.date.today()
cutoff = today if scope == "today" else (today - datetime.timedelta(days=6))
events = []
with open(LOG_FILE, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
rec = json.loads(line)
d = datetime.date.fromisoformat(rec["ts"][:10])
if d >= cutoff:
events.append(rec)
except Exception:
continue
if not events:
print(f"范围 [{scope}] 内暂无记录。")
return
sessions = []
cur_start = None
alerts = 0
for e in events:
ev = e.get("event")
if ev == "arrive":
if cur_start is None:
cur_start = e
elif ev in ("leave", "unplug"):
if cur_start is not None:
dur = max(0.0, (e["epoch"] - cur_start["epoch"]) / 60.0)
sessions.append((cur_start["ts"], e["ts"], dur, ev))
cur_start = None
elif ev == "sedentary_alert":
alerts += 1
now_epoch = time.time()
ongoing_min = 0.0
if cur_start is not None:
ongoing_min = max(0.0, (now_epoch - cur_start["epoch"]) / 60.0)
sessions.append((cur_start["ts"], "进行中", ongoing_min, "active"))
total_min = sum(s[2] for s in sessions)
max_min = max((s[2] for s in sessions), default=0.0)
leave_cnt = sum(1 for s in sessions if s[3] in ("leave", "unplug"))
title = "今日工位报告" if scope == "today" else "近 7 天工位报告"
print(f"=== {title} ({cutoff} ~ {today}) ===")
print(f"首次到达:{sessions[0][0] if sessions else '-'}")
print(f"累计在座:{int(total_min // 60)} 小时 {int(total_min % 60)} 分钟")
print(f"离座/开会:{leave_cnt} 次 | 最长连续:{max_min:.1f} 分钟 | 久坐提醒:{alerts} 次")
if cur_start is not None:
print(f"当前状态:在座中(已连续 {ongoing_min:.1f} 分钟,45 分钟触发提醒)")
print("\n时间段明细:")
for st, ed, dur, kind in sessions:
tag = {"leave": "离座", "unplug": "拔线/开会", "active": "在座中"}.get(kind, kind)
st_short = st[5:16] if scope != "today" else st[11:16]
ed_short = ed if ed == "进行中" else (ed[5:16] if scope != "today" else ed[11:16])
print(f" {st_short} - {ed_short} ({dur:.1f} 分钟) [{tag}]")
def uninstall_agent():
subprocess.run(["launchctl", "unload", PLIST_PATH], stderr=subprocess.DEVNULL)
if os.path.exists(PLIST_PATH):
os.remove(PLIST_PATH)
print("已卸载 Mac 心跳守护进程。")
def main():
if len(sys.argv) < 2:
print(__doc__)
return
cmd = sys.argv[1]
if cmd == "status":
print(send_cmd("STATUS"))
elif cmd == "watch":
print("按 Ctrl+C 退出实时监控...")
try:
while True:
print(send_cmd("STATUS"))
time.sleep(1.0)
except KeyboardInterrupt:
pass
elif cmd == "set-pwd":
p1 = getpass.getpass("请输入 Mac 登录密码(不会回显,直接写入 XIAO 内部 Flash): ")
p2 = getpass.getpass("请再次确认密码: ")
if p1 != p2:
raise SystemExit("两次输入不一致,已取消。")
if not p1:
raise SystemExit("密码不能为空。")
print(send_cmd(f"SET_PWD {p1}"))
elif cmd == "clear-pwd":
print(send_cmd("CLEAR_PWD"))
elif cmd == "set-rssi" and len(sys.argv) == 4:
print(send_cmd(f"SET_RSSI {sys.argv[2]} {sys.argv[3]}"))
elif cmd == "set-boot-ms" and len(sys.argv) == 3:
print(send_cmd(f"SET_BOOT_MS {sys.argv[2]}"))
elif cmd == "set-opt" and len(sys.argv) == 4:
print(send_cmd(f"SET_OPT {sys.argv[2]} {sys.argv[3]}"))
elif cmd == "clear-bonds":
print(send_cmd("CLEAR_BONDS"))
elif cmd == "test-wake":
print(send_cmd("TEST_WAKE"))
elif cmd == "install-agent":
install_agent()
elif cmd == "uninstall-agent":
uninstall_agent()
elif cmd == "report":
scope = sys.argv[2] if len(sys.argv) >= 3 else "today"
show_report(scope)
else:
print(__doc__)
if __name__ == "__main__":
main()一键编译烧录 & 启用命令
# 1. 安装 arduino-cli 与 ESP32 Core 3.3.x + NimBLE-Arduino 2.5.1
brew install arduino-cli
arduino-cli config init --overwrite
arduino-cli config add board_manager.additional_urls https://espressif.github.io/arduino-esp32/package_esp32_index.json
arduino-cli core update-index
arduino-cli core install esp32:[email protected]
arduino-cli lib install "[email protected]"
# 2. 编译并烧录到 XIAO ESP32S3
FQBN="esp32:esp32:esp32s3:USBMode=default,CDCOnBoot=cdc,FlashSize=8M,PSRAM=opi,PartitionScheme=default_8MB"
arduino-cli compile -b "$FQBN" --output-dir build firmware
arduino-cli upload -b "$FQBN" -p /dev/cu.usbmodem* --input-dir build firmware
# 3. iPhone 蓝牙配对 "MacAutoUnlock" 后,写入密码并启用开机自启心跳
python3 xiao_ctl.py set-pwd
python3 xiao_ctl.py set-opt auto_lock 1
python3 xiao_ctl.py install-agent
# 4. 查看实时信号 / 工位报告
python3 xiao_ctl.py watch
python3 xiao_ctl.py report电脑端目录结构
新建一个目录(例如 ~/xiao-mac-autounlock/),把上面折叠块里的 3 个文件按如下结构放好即可:
xiao-mac-autounlock/
├── firmware/
│ └── firmware.ino # 烧录到 XIAO ESP32S3 的固件
├── mac_heartbeat.py # Mac 后台心跳 + 45 分钟久坐提醒守护进程
└── xiao_ctl.py # Mac 命令行配置 & 工位报告工具电脑端常用运行脚本速查
cd ~/xiao-mac-autounlock
# 1. 写入 / 清空板子里的 Mac 开机密码(隐藏输入,不落盘)
python3 xiao_ctl.py set-pwd
python3 xiao_ctl.py clear-pwd
# 2. 安装 / 卸载 Mac 开机自启心跳守护进程(LaunchAgent)
python3 xiao_ctl.py install-agent
python3 xiao_ctl.py uninstall-agent
# 3. 实时监控蓝牙信号强度(RSSI)与在座状态(用于按工位微调距离)
python3 xiao_ctl.py watch
# 4. 调整靠近/离开信号阈值(默认 -72 dBm 靠近,-86 dBm 离开)
python3 xiao_ctl.py set-rssi -72 -86
# 5. 功能开关(1=开启,0=关闭)
python3 xiao_ctl.py set-opt auto_lock 1 # 离开工位 6 秒自动锁屏
python3 xiao_ctl.py set-opt auto_unlock 1 # 回到工位自动输入密码解锁
python3 xiao_ctl.py set-opt boot_unlock 1 # 重启开机界面自动输入密码
# 6. 调整重启开机等待时间(默认 14000 毫秒 = 14 秒)
python3 xiao_ctl.py set-boot-ms 14000
# 7. 查看工位出勤 & 久坐统计报告
python3 xiao_ctl.py report # 今日报告
python3 xiao_ctl.py report week # 近 7 天报告
# 8. 更换绑定的 iPhone(清除旧蓝牙绑定)
python3 xiao_ctl.py clear-bonds
# 9. (可选)如果开机画面有多余账号导致停在选头像界面,仅从登录界面隐藏该账号
sudo dscl . create /Users/<多余用户名> IsHidden 1