实现自动按键功能

This commit is contained in:
zqm
2026-04-08 14:07:37 +08:00
parent d2fe260c30
commit acfc82f04b
23 changed files with 15626 additions and 6144 deletions

View File

@@ -4,6 +4,7 @@
//! that interacts with the USB HID interface implemented in C/TinyUSB.
#![no_std]
#![no_main]
use esp_backtrace as _;
@@ -17,23 +18,40 @@ fn panic(_info: &core::panic::PanicInfo) -> ! {
// HID 键码常量
const HID_KEY_A: u8 = 0x04;
const REPORT_ID_KEYBOARD: u8 = 1;
const PD_MS_TO_TICKS: u32 = 1;
// FFI 函数声明
extern "C" {
fn rust_is_usb_mounted() -> bool;
fn rust_send_keyboard_report(report_id: u8, modifier: u8, keycode: *const u8);
fn rust_vTaskDelay(xTicksToDelay: u32);
fn rust_esp_log_i(tag: *const u8, format: *const u8);
}
/// 日志函数
fn log_info(message: &'static str) {
// 转换 Rust 静态字符串为 C 字符串
let tag = b"RustApp\0";
// 直接使用静态字符串的指针,确保它在整个程序生命周期内有效
// 注意Rust 的字符串字面量已经以 null 结尾
let msg_ptr = message.as_ptr();
unsafe {
rust_esp_log_i(tag.as_ptr(), msg_ptr);
}
}
#[no_mangle]
extern "C" fn rust_app_main() {
// 初始化代码
log_info("Rust app started");
loop {
log_info("Sending random key...");
send_random_key();
// 等待 5 秒
// 等待 5 秒 (5000ms / 10ms per tick = 500 ticks)
log_info("Waiting for 5 seconds...");
unsafe {
rust_vTaskDelay(5000 * PD_MS_TO_TICKS);
rust_vTaskDelay(500);
}
}
}
@@ -51,11 +69,13 @@ fn send_random_key() {
rust_is_usb_mounted()
};
if mounted {
log_info("USB mounted!");
break;
}
// 等待 100ms
// 等待 100ms (100ms / 10ms per tick = 10 ticks)
log_info("USB not mounted yet");
unsafe {
rust_vTaskDelay(100 * PD_MS_TO_TICKS);
rust_vTaskDelay(10);
}
}
@@ -66,20 +86,25 @@ fn send_random_key() {
// 发送随机键按下事件
let keycode = [random_key, 0, 0, 0, 0, 0];
log_info("Sending key press event");
unsafe {
rust_send_keyboard_report(REPORT_ID_KEYBOARD, 0, keycode.as_ptr());
}
// 等待 50ms
// 等待 50ms (50ms / 10ms per tick = 5 ticks)
log_info("Waiting for 50ms...");
unsafe {
rust_vTaskDelay(50 * PD_MS_TO_TICKS);
rust_vTaskDelay(5);
}
// 发送随机键释放事件
let keycode = [0, 0, 0, 0, 0, 0];
log_info("Sending key release event");
unsafe {
rust_send_keyboard_report(REPORT_ID_KEYBOARD, 0, keycode.as_ptr());
}
} else {
log_info("USB not mounted after 10 attempts");
}
}