Files
glass/glass-mouse/scripts/ble_bind_pyobjc.py
T
admin 2840e82685 Initial commit: Android GlassMouse + iOS GlassRemote 智能眼镜遥控项目
包含本次会话修复:
- iOS clickReady 警告 bug(默认 false 永远显示)
- BLE 'handle is invalid' 排查(stale handle auto-retry 实验 + 回退)

项目结构:
- glass-mouse/: 眼镜端原生 Kotlin App,前台服务 MouseService + 自定义 BLE GATT 桥接 ProxyBleServer + 无障碍 GestureDescription 注入
- ios/GlassRemote/: iPhone 端 SwiftUI + CoreBluetooth,通过 BLE 直连眼镜
- HTTP 投屏服务(:8000) 接 PPT/WPS 备注宏 POST 推送

技术栈: Android Kotlin (gradle 8.14.4, compileSdk 34), iOS Swift 5.10 (Xcode 26.5)
2026-08-26 10:34:23 +08:00

247 lines
9.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
用 pyobjc 的 CoreBluetooth 直接「搭车」系统已建立的 INMO 连接(系统已配对→链路已加密),
绕过 bleak 在『设备已被系统连着』时 connect() 超时空报错的问题。
目的:订阅 0x2022/0x2023 通知(回传),发 BleConnectBind.QUERY_BIND_STATE / UNBIND
的多种 aa55 包裹,看哪种被眼镜回传 → 锁定包裹格式 + 判定绑定状态。
"""
import sys, time, binascii
from Foundation import NSObject, NSRunLoop, NSDate, NSData
import CoreBluetooth
from CoreBluetooth import CBCentralManager, CBUUID
SVC_UUID = "00002020-0000-1000-8000-00805F9B34FB"
WRITE_UUID = "00002021-0000-1000-8000-00805F9B34FB"
NOTIFY_UUIDS = [
"00002022-0000-1000-8000-00805F9B34FB",
"00002023-0000-1000-8000-00805F9B34FB",
]
def crc8(data, poly=0x8C):
crc = 0
for b in data:
crc ^= b
for _ in range(8):
crc = ((crc << 1) ^ poly) & 0xff if (crc & 0x80) else (crc << 1) & 0xff
return crc
def wrappers(p):
w = []
w.append(("raw", p))
w.append(("aa55+crc8_0x8C(payload)", b"\xaa\x55" + p + bytes([crc8(p, 0x8C)])))
w.append(("aa55+sum(payload)", b"\xaa\x55" + p + bytes([(sum(p)) & 0xff])))
w.append(("aa55+comp(payload)", b"\xaa\x55" + p + bytes([(0x100 - sum(p)) & 0xff])))
w.append(("aa55+crc8_0x8C(aa55+p)", b"\xaa\x55" + p + bytes([crc8(b"\xaa\x55" + p, 0x8C)])))
w.append(("aa55+len+crc8(payload)", b"\xaa\x55" + bytes([len(p)]) + p + bytes([crc8(p, 0x8C)])))
w.append(("aa55+00+len+crc8(all)", b"\xaa\x55" + bytes([0x00, len(p)]) + p + bytes([crc8(bytes([0x00, len(p)]) + p, 0x8C)])))
return w
BIND_QUERY = bytes([0x08, 0x00])
BIND_UNBIND = bytes([0x08, 0x06])
# 控制命令正确字节(依据 ControlCommand.proto)
MOUSE_MODE_ENTER = bytes([0x08, 0x17])
CLICK_DOWN = bytes([0x08, 0x17, 0x82, 0x01, 0x0c, 0x08, 0x00, 0x15, 0x00, 0x00, 0x00, 0x3f, 0x1d, 0x00, 0x00, 0x00, 0x3f])
CLICK_UP = bytes([0x08, 0x17, 0x82, 0x01, 0x0c, 0x08, 0x01, 0x15, 0x00, 0x00, 0x00, 0x3f, 0x1d, 0x00, 0x00, 0x00, 0x3f])
class D(NSObject):
def centralManagerDidUpdateState_(self, mgr):
self.manager = mgr
print("central state:", mgr.state())
def centralManager_didConnectPeripheral_(self, mgr, perp):
print("didConnect", perp.name())
perp.discoverServices_([CBUUID.UUIDWithString_(SVC_UUID)])
print("discoverServices(2020) called")
def centralManager_didFailToConnectPeripheral_error_(self, mgr, perp, err):
print("didFailToConnect", err)
def peripheral_didDiscoverServices_(self, perp, err):
try:
print("didDiscoverServices fired; err=", err)
if err:
print("discoverServices err:", err)
return
for svc in perp.services():
su = short_uuid(svc)
print(" svc:", svc.UUID().UUIDString(), "short=", su)
if su == "2020":
svc.retain()
self.svc_2020 = svc
self.services_discovered = True
print("found svc 2020 (retained)")
except Exception:
import traceback
traceback.print_exc()
def peripheral_didDiscoverCharacteristicsForService_error_(self, perp, svc, err):
try:
if err:
print("discoverChars err:", err)
return
for ch in svc.characteristics():
u = short_uuid(ch)
if u == "2021":
self.write_char = ch
print("write char:", ch.UUID().UUIDString())
elif u == "2022" or u == "2023":
self.notify_chars.append(ch)
print("notify char:", ch.UUID().UUIDString())
if self.write_char and self.notify_chars:
self.ready = True
except Exception as e:
import traceback
traceback.print_exc()
def peripheral_didUpdateNotificationStateForCharacteristic_error_(self, perp, ch, err):
if err:
print("notify state err:", err)
else:
print("subscribed notify:", ch.UUID().UUIDString())
def peripheral_didUpdateValueForCharacteristic_error_(self, perp, ch, err):
if err:
print("value err:", err)
return
v = ch.value()
if v is None:
return
h = binascii.hexlify(bytes(v)).decode()
self.responses.append(h)
print(" [notify %s] %s" % (ch.UUID().UUIDString(), h))
def nsdata(p):
return NSData.alloc().initWithBytes_length_(p, len(p))
def short_uuid(obj):
"""CoreBluetooth 对 16-bit UUID 返回短形式 '2020',对 128-bit 返回完整串。统一取 16-bit 部分。
obj 可以是 CBUUID / CBService / CBCharacteristic。"""
if hasattr(obj, "UUID"):
s = obj.UUID().UUIDString().lower()
else:
s = obj.UUIDString().lower()
if '-' in s:
first = s.split('-')[0]
return first[4:] if first.startswith("0000") else first
return s
def main():
d = D.alloc().init()
d.manager = None
d.peripheral = None
d.write_char = None
d.notify_chars = []
d.ready = False
d.responses = []
d.svc_2020 = None
d.services_discovered = False
mgr = CBCentralManager.alloc().initWithDelegate_queue_options_(d, None, None)
loop = NSRunLoop.currentRunLoop()
t0 = time.time()
while d.manager is None or d.manager.state() != 5:
loop.runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.1))
if time.time() - t0 > 10:
print("central not powered on")
return
connected = mgr.retrieveConnectedPeripheralsWithServices_([CBUUID.UUIDWithString_(SVC_UUID)])
perp = None
for c in connected:
name = c.name()
print("connected dev:", name, c.identifier().UUIDString())
if name and "INMO" in name.upper():
perp = c
break
if perp is None and len(connected) > 0:
perp = connected[0]
if perp is None:
print("no connected INMO via system. 不能搭车,放弃。")
return
d.peripheral = perp
perp.setDelegate_(d)
# 系统已连接 → 仍需由本 manager 显式 connect 认领,才能收到 didConnect/服务发现回调
mgr.connectPeripheral_options_(perp, None)
# didConnect 里会调用 discoverServices;先等服务发现完成
t0 = time.time()
while not d.services_discovered:
loop.runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.1))
if time.time() - t0 > 15:
print("services not discovered")
return
# 在主 run loop(非回调内)发起特征发现,避免 pyobjc 段错误
char_uuids = [CBUUID.UUIDWithString_(WRITE_UUID)] + [CBUUID.UUIDWithString_(x) for x in NOTIFY_UUIDS]
perp.discoverCharacteristics_forService_(char_uuids, d.svc_2020)
print("discoverCharacteristics called")
# 再等特征就绪(ready)
t0 = time.time()
while not d.ready:
loop.runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.1))
if time.time() - t0 > 15:
print("not ready; write_char?", d.write_char, "notify:", len(d.notify_chars))
return
for ch in d.notify_chars:
perp.setNotifyValue_forCharacteristic_(True, ch)
loop.runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.6))
print("\n== BIND_QUERY (msg_type=0) ==")
q_hits = []
for idx, (name, p) in enumerate(wrappers(BIND_QUERY), 1):
before = len(d.responses)
print(">>> Q%d %s : %s" % (idx, name, binascii.hexlify(p).decode()))
perp.writeValue_forCharacteristic_type_(nsdata(p), d.write_char, 0)
loop.runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.7))
if len(d.responses) > before:
q_hits.append((idx, name, d.responses[-1]))
print(" ✅ got response!")
print("\n== BIND_UNBIND (msg_type=6) ==")
u_hits = []
for idx, (name, p) in enumerate(wrappers(BIND_UNBIND), 1):
before = len(d.responses)
print(">>> U%d %s" % (idx, name))
perp.writeValue_forCharacteristic_type_(nsdata(p), d.write_char, 0)
loop.runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.7))
if len(d.responses) > before:
u_hits.append((idx, name, d.responses[-1]))
print(" ✅ got response!")
loop.runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(2.0))
print("\n== CONTROL: 发『进入鼠标模式 08 17』各包裹,请盯眼镜是否出现光标 ==")
for idx, (name, p) in enumerate(wrappers(MOUSE_MODE_ENTER), 1):
print(">>> C%d enter-mouse %s : %s" % (idx, name, binascii.hexlify(p).decode()))
perp.writeValue_forCharacteristic_type_(nsdata(p), d.write_char, 0)
loop.runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(1.0))
print("\n== CONTROL: 发『点击 DOWN/UP』各包裹 ==")
for idx, (name, p) in enumerate(wrappers(CLICK_DOWN), 1):
cu = wrappers(CLICK_UP)[idx - 1][1]
print(">>> K%d click %s" % (idx, name))
perp.writeValue_forCharacteristic_type_(nsdata(p), d.write_char, 0)
loop.runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.1))
perp.writeValue_forCharacteristic_type_(nsdata(cu), d.write_char, 0)
loop.runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.8))
loop.runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(2.0))
print("\n请现在看眼镜屏幕:是否出现了可移动的光标?是否发生了点击?把结果告诉我。")
print("(若 C1..C7 都没反应,则绑定墙对所有命令生效,BLE 直连控鼠不可行)")
print("\n== 汇总 ==")
print(" QUERY 命中:", [("Q%d/%s" % (q[0], q[1])) for q in q_hits] or "无")
print(" UNBIND 命中:", [("U%d/%s" % (u[0], u[1])) for u in u_hits] or "无")
print(" 全部回传帧:")
for h in d.responses:
print(" ", h)
if __name__ == "__main__":
main()