Through /dev/uinput create a virtual HID device, inject precise event sequences, and verify input subsystem behavior.
When to Use
- Verify the behavior of input event streams (mouse movement, key presses, touchpad) on real devices
- Test device binding (BindDeviceToDisplayGroupByDisplay) and state isolation
- Simulate hot-plug scenarios
- When physical peripherals are not needed or not available
Device creation
Key constraints
- bustype must use
BUS_USB(0x03)。BUS_VIRTUALwill be filtered by MMI and will not trigger the device discovery callback - vendor/product must be unique, to avoid conflicts with real devices. Recommended vendor=0x93a, product customized
- The mouse must register both
EV_KEY+EV_REL, otherwise it will not be recognized as a pointer device
Mouse
int fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
ioctl(fd, UI_SET_EVBIT, EV_KEY);
ioctl(fd, UI_SET_EVBIT, EV_REL);
ioctl(fd, UI_SET_KEYBIT, BTN_LEFT);
ioctl(fd, UI_SET_KEYBIT, BTN_RIGHT); // 可选
ioctl(fd, UI_SET_KEYBIT, BTN_MIDDLE); // 可选
ioctl(fd, UI_SET_RELBIT, REL_X);
ioctl(fd, UI_SET_RELBIT, REL_Y);
ioctl(fd, UI_SET_RELBIT, REL_WHEEL); // 可选
struct uinput_user_dev ud = {};
strncpy(ud.name, "TestMouseA", UINPUT_MAX_NAME_SIZE - 1);
ud.id.bustype = BUS_USB; // 必须
ud.id.vendor = 0x93a;
ud.id.product = 0xAA01; // 每个虚拟设备用不同值
ud.id.version = 1;
write(fd, &ud, sizeof(ud));
ioctl(fd, UI_DEV_CREATE);
Keyboard
int fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
ioctl(fd, UI_SET_EVBIT, EV_KEY);
// 不注册 EV_REL —— 确保被识别为键盘而非鼠标
for (int k = KEY_ESC; k <= KEY_RIGHTMETA; k++) {
ioctl(fd, UI_SET_KEYBIT, k);
}
// ... 同上构造 uinput_user_dev, bustype=BUS_USB
Event injection
Every event sequence must end with SYN_REPORT :
// 鼠标相对移动
void InjectMotion(int fd, int dx, int dy) {
struct input_event ev = {};
ev.type = EV_REL; ev.code = REL_X; ev.value = dx;
write(fd, &ev, sizeof(ev));
ev.code = REL_Y; ev.value = dy;
write(fd, &ev, sizeof(ev));
ev.type = EV_SYN; ev.code = SYN_REPORT; ev.value = 0;
write(fd, &ev, sizeof(ev));
}
// 按键/按钮(鼠标按钮和键盘按键共用)
void InjectKey(int fd, int code, int pressed) {
struct input_event ev = {};
ev.type = EV_KEY; ev.code = code; ev.value = pressed;
write(fd, &ev, sizeof(ev));
ev.type = EV_SYN; ev.code = SYN_REPORT; ev.value = 0;
write(fd, &ev, sizeof(ev));
}
// code: BTN_LEFT, BTN_RIGHT (鼠标按钮)
// KEY_A, KEY_LEFTCTRL, KEY_LEFTSHIFT (键盘按键)
// pressed: 1=按下, 0=释放
InputManager device discovery
GetDeviceIds / GetDevice is an asynchronous callback. After creating a uinput device, you need to wait for MMI enumeration:
static int FindDevice(const std::string &name) {
struct FindState {
std::mutex mtx;
std::condition_variable cv;
int foundId = -1;
int pending = 0;
bool done = false;
};
for (int attempt = 0; attempt < 30; ++attempt) {
auto state = std::make_shared<FindState>();
InputManager::GetInstance()->GetDeviceIds([state, name](std::vector<int32_t> &ids) {
{
std::lock_guard<std::mutex> lock(state->mtx);
state->pending = static_cast<int>(ids.size());
if (state->pending == 0) {
state->done = true;
state->cv.notify_one();
return;
}
}
for (auto id : ids) {
InputManager::GetInstance()->GetDevice(id,
[state, id, name](std::shared_ptr<InputDevice> dev) {
bool notify = false;
{
std::lock_guard<std::mutex> lock(state->mtx);
if (dev && dev->GetName() == name && state->foundId < 0) {
state->foundId = id;
}
if (--state->pending == 0) {
state->done = true;
notify = true;
}
}
if (notify) {
state->cv.notify_one();
}
});
}
});
std::unique_lock<std::mutex> lock(state->mtx);
state->cv.wait_for(lock, std::chrono::milliseconds(500), [&]{ return state->done; });
if (state->foundId >= 0) return state->foundId;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
return -1;
}
After creation, wait at least 3 secondsbefore calling FindDevice, to give libinput and MMI time to enumerate.
Hot-plug simulation
ioctl(fd, UI_DEV_DESTROY);
close(fd);
// MMI 的 OnInputDeviceRemoved 会自动清理绑定
// 等 2 秒后 dump 验证 RuntimeBindings 已清理
State isolation verification mode
Standard mode when testing per-group isolation:
1. 创建 2 个虚拟设备,绑定到不同 group
2. warm-up:每个设备注入 2-3 个事件触发懒初始化
3. 对设备 A 注入值 X(如 +20,+10 移动),对设备 B 注入值 Y(如 -15,-8)
4. dump → 验证 group0 反映 X,group1 反映 Y,互不影响
Necessity of warm-up: after binding, the first event triggers EnsureGroupState and cursorPosMap_ initialization. Skipping warm-up will cause the group state in the dump to be empty.
Phase-marker + hidumper state snapshot
The test code writes markers, and the background script captures hidumper:
// 测试代码中
static void DumpPhase(const char *label) {
FILE *f = fopen("/data/local/tmp/phase.txt", "w");
if (f) { fprintf(f, "%s\n", label); fclose(f); }
std::this_thread::sleep_for(std::chrono::seconds(3));
}
#!/system/bin/sh
# run_with_dump.sh — 后台捕获 hidumper
DUMP=/data/local/tmp/dump.txt
PHASE=/data/local/tmp/phase.txt
rm -f "$DUMP" "$PHASE"
$TEST_BIN &
PID=$!
LAST=""
while kill -0 $PID 2>/dev/null; do
if [ -f "$PHASE" ]; then
CUR=$(cat "$PHASE" 2>/dev/null)
if [ "$CUR" != "$LAST" ] && [ -n "$CUR" ]; then
echo "===== DUMP: $CUR =====" >> "$DUMP"
hidumper -s MultimodalInput -a '-G' >> "$DUMP" 2>&1
LAST="$CUR"
fi
fi
sleep 1
done
wait $PID 2>/dev/null
Cleanup
// 必须在测试退出前销毁所有虚拟设备
ioctl(fd, UI_DEV_DESTROY);
close(fd);
Virtual devices that are not destroyed will be automatically cleaned up when the process exits, but the MMI device removal notification may be delayed.
Common Mistakes
| Error | Consequence | Fix |
|---|---|---|
bustype = BUS_VIRTUAL |
Device is not recognized by MMI | Use BUS_USB |
Missing SYN_REPORT |
Events are not processed | Add SYN_REPORT at the end of every event sequence |
| FindDevice immediately after creation | Device cannot be found | Wait 3 seconds |
| Skip warm-up events | per-group state is not initialized | Inject 2-3 movement events after binding |
Mouse does not register EV_REL |
Not recognized as a pointer device | Register EV_KEY + EV_REL at the same time |
| Multiple devices use the same product ID | May confuse device discovery | Use a different product for each device |