Microtube 文档
EN中文
开发者 / 指南 / Python 集成

Python 集成

使用 HaptGlovePython 库,通过蓝牙(BLE)直接从 Python 驱动 HEXR 手套。

安装

你需要 Python 3.8 至 3.13。该库固定使用 bleak 0.22.3,它无法在 Python 3.14 或更高版本上安装,因此在这些版本上 pip 会报错停止:“No matching distribution found for bleak==0.22.3”。克隆该库并安装其依赖:

shell
git clone https://github.com/MicrotubeTechnologies/HaptGlovePython.git
cd HaptGlovePython
pip install -r requirements.txt
注意

该库使用 bleak 通过 BLE 与手套通信,可在 Windows、macOS 和 Linux 上运行。它需要从克隆的仓库运行——它没有发布到 PyPI,因此不存在 pip install haptglove。

找到你的手套

打开手臂模块的电源。下面的示例通过手套广播的名称 HaptGloveAR Right 或 HaptGloveAR Left 查找手套,因此无需复制地址。如果要查看范围内的所有手套,或在多只同名手套中选择一只,请运行发现脚本,并将它打印出的地址传给 BleakClient,以代替按名称查找:

shell
python AddressDiscovery.py

在 macOS 上,蓝牙报告的是设备 UUID 而不是硬件地址,因此这个值看起来会不同——请使用 AddressDiscovery.py 打印出的值。

你的第一个脉冲

连接手套,以中等强度按压食指两秒,然后释放。释放操作放在 finally 块中,因此即使出现问题,或你在按压中途按下 Ctrl+C,释放指令也会发送。如果没有找到手套,脚本会给出提示,并且不发送任何内容。如果是左手手套,请将 GLOVE_NAME 和 "Right" 改为对应的左手值。

python
import asyncio
from bleak import BleakClient, BleakScanner
from Haptics import Haptics

GLOVE_NAME = "HaptGloveAR Right"   # the left glove is "HaptGloveAR Left"
CHAR_UUID  = "0000ff01-0000-1000-8000-00805f9b34fb"
FINGER     = Haptics.Finger.Index

async def main():
    # Find the glove by the name it advertises; no address to copy.
    glove = await BleakScanner.find_device_by_name(GLOVE_NAME, timeout=10.0)
    if glove is None:
        print(f"No {GLOVE_NAME} found. Is the arm module switched on?")
        return

    haptics = Haptics("Right")
    async with BleakClient(glove) as client:
        # Subscribe to the glove's readings, as ExampleHaptics.py does.
        # This example does not use them, so the callback ignores them.
        await client.start_notify(CHAR_UUID, lambda sender, data: None)
        try:
            # Press: finger, True applies, intensity 0.1-1.0 (0.5 is
            # moderate), ramp speed 0.1-1.0.
            await client.write_gatt_char(CHAR_UUID, haptics.hexr_pressure(FINGER, True, 0.5, 1.0))
            await asyncio.sleep(2)   # hold for two seconds
        finally:
            # Release: False, intensity 0. Runs on success, on an error and
            # on Ctrl+C -- but only while the link is up. If the Bluetooth
            # link itself drops, nothing can reach the glove and it keeps
            # pressing: switch the arm module off.
            if client.is_connected:
                await client.write_gatt_char(CHAR_UUID, haptics.hexr_pressure(FINGER, False, 0, 1.0))

asyncio.run(main())
施加的压力务必释放

手套会持续施加最后收到的压力,直到收到释放命令;手套上没有任何部件会自行松开。自 0.9.4 起,Unity 插件包会在应用退出、暂停或断开手套连接时释放所有通道,但如果应用崩溃或蓝牙连接中断,就没有任何办法释放;Python 库也不会替你释放任何通道。如果手套一直保持按压,请关闭手臂模块。

finally 块无法做到的事

它只在你的脚本运行且连接正常时起作用。如果按压过程中蓝牙连接断开,或进程被终止,释放指令就无法送达手套,手套会一直按压,直到关闭手臂模块。连接丢失时的释放只能由手套固件实现,而目前固件并不具备这一功能。

要在一次写入中按压多个通道,请使用 hexr_pressure_multiple——请参阅为每根手指设置不同的值。仓库中的 ExampleHaptics.py 会对每个通道执行按压与释放,并输出更多日志。