feat: 开放 Rust 补丁程序源代码和编译说明

This commit is contained in:
Del Wang
2025-04-08 23:07:26 +08:00
parent 0e43eefd38
commit d170fadbcc
26 changed files with 2510 additions and 0 deletions
+1
View File
@@ -26,6 +26,7 @@ coverage
out/
build
dist
target
# Debug
+757
View File
@@ -0,0 +1,757 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "addr2line"
version = "0.24.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dfbe277e56a376000877090da837660b4427aad530e3028d44e0bffe4f89a1c1"
dependencies = [
"gimli",
]
[[package]]
name = "adler2"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "512761e0bb2578dd7380c6baaa0f4ce03e84f95e960231d1dec8bf4d7d6e2627"
[[package]]
name = "autocfg"
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]]
name = "backtrace"
version = "0.3.74"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d82cb332cdfaed17ae235a638438ac4d4839913cc2af585c3c6746e8f8bee1a"
dependencies = [
"addr2line",
"cfg-if",
"libc",
"miniz_oxide",
"object",
"rustc-demangle",
"windows-targets",
]
[[package]]
name = "bitflags"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]]
name = "bytes"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3"
dependencies = [
"generic-array",
"typenum",
]
[[package]]
name = "data-encoding"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "575f75dfd25738df5b91b8e43e14d44bda14637a58fae779fd2b064f8bf3e010"
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]]
name = "fnv"
version = "1.0.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
[[package]]
name = "futures"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65bc07b1a8bc7c85c5f2e110c476c7389b4554ba72af57d8445ea63a576b0876"
dependencies = [
"futures-channel",
"futures-core",
"futures-executor",
"futures-io",
"futures-sink",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-channel"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10"
dependencies = [
"futures-core",
"futures-sink",
]
[[package]]
name = "futures-core"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
[[package]]
name = "futures-executor"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f"
dependencies = [
"futures-core",
"futures-task",
"futures-util",
]
[[package]]
name = "futures-io"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6"
[[package]]
name = "futures-macro"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "162ee34ebcb7c64a8abebc059ce0fee27c2262618d7b60ed8faf72fef13c3650"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "futures-sink"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7"
[[package]]
name = "futures-task"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"
[[package]]
name = "futures-util"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"
dependencies = [
"futures-channel",
"futures-core",
"futures-io",
"futures-macro",
"futures-sink",
"futures-task",
"memchr",
"pin-project-lite",
"pin-utils",
"slab",
]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]]
name = "getrandom"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73fea8450eea4bac3940448fb7ae50d91f034f941199fcd9d909a5a07aa455f0"
dependencies = [
"cfg-if",
"libc",
"r-efi",
"wasi 0.14.2+wasi-0.2.4",
]
[[package]]
name = "gimli"
version = "0.31.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07e28edb80900c19c28f1072f2e8aeca7fa06b23cd4169cefe1af5aa3260783f"
[[package]]
name = "http"
version = "1.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565"
dependencies = [
"bytes",
"fnv",
"itoa",
]
[[package]]
name = "httparse"
version = "1.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
[[package]]
name = "itoa"
version = "1.0.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
[[package]]
name = "libc"
version = "0.2.171"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6"
[[package]]
name = "lock_api"
version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07af8b9cdd281b7915f413fa73f29ebd5d55d0d3f0155584dade1ff18cea1b17"
dependencies = [
"autocfg",
"scopeguard",
]
[[package]]
name = "log"
version = "0.4.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
[[package]]
name = "memchr"
version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "miniz_oxide"
version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff70ce3e48ae43fa075863cef62e8b43b71a4f2382229920e0df362592919430"
dependencies = [
"adler2",
]
[[package]]
name = "mio"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2886843bf800fba2e3377cff24abf6379b4c4d5c6681eaf9ea5b0d15090450bd"
dependencies = [
"libc",
"wasi 0.11.0+wasi-snapshot-preview1",
"windows-sys",
]
[[package]]
name = "object"
version = "0.36.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87"
dependencies = [
"memchr",
]
[[package]]
name = "open-xiaoai"
version = "1.0.0"
dependencies = [
"futures",
"serde",
"serde_json",
"tokio",
"tokio-tungstenite",
"uuid",
]
[[package]]
name = "parking_lot"
version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1bf18183cf54e8d6059647fc3063646a1801cf30896933ec2311622cc4b9a27"
dependencies = [
"lock_api",
"parking_lot_core",
]
[[package]]
name = "parking_lot_core"
version = "0.9.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1e401f977ab385c9e4e3ab30627d6f26d00e2c73eef317493c4ec6d468726cf8"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
"windows-targets",
]
[[package]]
name = "pin-project-lite"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
[[package]]
name = "pin-utils"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]]
name = "ppv-lite86"
version = "0.2.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
dependencies = [
"zerocopy",
]
[[package]]
name = "proc-macro2"
version = "1.0.94"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "5.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "74765f6d916ee2faa39bc8e68e4f3ed8949b48cccdac59983d287a7cb71ce9c5"
[[package]]
name = "rand"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94"
dependencies = [
"rand_chacha",
"rand_core",
"zerocopy",
]
[[package]]
name = "rand_chacha"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38"
dependencies = [
"getrandom",
]
[[package]]
name = "redox_syscall"
version = "0.5.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2f103c6d277498fbceb16e84d317e2a400f160f46904d5f5410848c829511a3"
dependencies = [
"bitflags",
]
[[package]]
name = "rustc-demangle"
version = "0.1.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "719b953e2095829ee67db738b3bfa9fa368c94900df327b3f07fe6e794d2fe1f"
[[package]]
name = "ryu"
version = "1.0.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "serde"
version = "1.0.219"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.219"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.140"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20068b6e96dc6c9bd23e01df8827e6c7e1f2fddd43c21810382803c136b99373"
dependencies = [
"itoa",
"memchr",
"ryu",
"serde",
]
[[package]]
name = "sha1"
version = "0.10.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]]
name = "signal-hook-registry"
version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9e9e0b4211b72e7b8b6e85c807d36c212bdb33ea8587f7569562a84df5465b1"
dependencies = [
"libc",
]
[[package]]
name = "slab"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
dependencies = [
"autocfg",
]
[[package]]
name = "smallvec"
version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8917285742e9f3e1683f0a9c4e6b57960b7314d0b08d30d1ecd426713ee2eee9"
[[package]]
name = "socket2"
version = "0.5.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4f5fd57c80058a56cf5c777ab8a126398ece8e442983605d280a44ce79d0edef"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "syn"
version = "2.0.100"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "2.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "567b8a2dae586314f7be2a752ec7474332959c6460e02bde30d702a66d488708"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f7cf42b4507d8ea322120659672cf1b9dbb93f8f2d4ecfd6e51350ff5b17a1d"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio"
version = "1.44.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6b88822cbe49de4185e3a4cbf8321dd487cf5fe0c5c65695fef6346371e9c48"
dependencies = [
"backtrace",
"bytes",
"libc",
"mio",
"parking_lot",
"pin-project-lite",
"signal-hook-registry",
"socket2",
"tokio-macros",
"windows-sys",
]
[[package]]
name = "tokio-macros"
version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e06d43f1345a3bcd39f6a56dbb7dcab2ba47e68e8ac134855e7e2bdbaf8cab8"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "tokio-tungstenite"
version = "0.26.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a9daff607c6d2bf6c16fd681ccb7eecc83e4e2cdc1ca067ffaadfca5de7f084"
dependencies = [
"futures-util",
"log",
"tokio",
"tungstenite",
]
[[package]]
name = "tungstenite"
version = "0.26.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4793cb5e56680ecbb1d843515b23b6de9a75eb04b66643e256a396d43be33c13"
dependencies = [
"bytes",
"data-encoding",
"http",
"httparse",
"log",
"rand",
"sha1",
"thiserror",
"utf-8",
]
[[package]]
name = "typenum"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1dccffe3ce07af9386bfd29e80c0ab1a8205a2fc34e4bcd40364df902cfa8f3f"
[[package]]
name = "unicode-ident"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512"
[[package]]
name = "utf-8"
version = "0.7.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"
[[package]]
name = "uuid"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "458f7a779bf54acc9f347480ac654f68407d3aab21269a6e3c9f922acd9e2da9"
dependencies = [
"getrandom",
]
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasi"
version = "0.14.2+wasi-0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9683f9a5a998d873c0d21fcbe3c083009670149a8fab228644b8bd36b2c48cb3"
dependencies = [
"wit-bindgen-rt",
]
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "wit-bindgen-rt"
version = "0.39.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6f42320e61fe2cfd34354ecb597f86f413484a798ba44a8ca1165c58d42da6c1"
dependencies = [
"bitflags",
]
[[package]]
name = "zerocopy"
version = "0.8.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2586fea28e186957ef732a5f8b3be2da217d65c5969d4b1e17f973ebbe876879"
dependencies = [
"zerocopy-derive",
]
[[package]]
name = "zerocopy-derive"
version = "0.8.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a996a8f63c5c4448cd959ac1bab0aaa3306ccfd060472f85943ee0750f0169be"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "open-xiaoai"
version = "1.0.0"
edition = "2021"
[profile.release]
lto = true
opt-level = "s"
codegen-units = 1
panic = "abort"
strip = true
debug = false
[workspace.metadata.cross.target.armv7-unknown-linux-gnueabihf]
image = "ghcr.io/cross-rs/armv7-unknown-linux-gnueabihf:0.2.5"
[dependencies]
futures = "0.3.31"
tokio = { version = "1.0", features = ["full"] }
tokio-tungstenite = "0.26.2"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
uuid = { version = "1.15.1", features = ["v4"] }
+92
View File
@@ -0,0 +1,92 @@
# Rust Client
这是使用 Rust 编写的小爱音箱补丁程序,主要负责:
- 共享通信协议(Server 端和 Client 端实时双向通信)
- 转发小爱音箱的麦克风输入音频流到 Server 端进行识别处理
- 转发小爱音箱上的事件到 Server 端(语音识别结果、播放状态等)
- 响应来自 Server 端的指令调用(执行脚本、播放音频流、系统升级等)
## 编译运行
> [!IMPORTANT]
> 本项目仅作为挖掘小爱音箱潜力的一个演示,并未提供任何预构建产物,仅适合有动手能力的人自行编译运行。你可以按需修改源代码,增删自己想要的功能。
首先,你需要在电脑上安装 `Rust` 开发环境 👉 [传送门](https://www.rust-lang.org/)
为了构建能够在小爱音箱上运行的 ARMv7 应用,你还需要安装 `cross` 👉 [传送门](https://github.com/cross-rs/cross)
```shell
# 安装依赖
cargo fetch
# 交叉编译
cross build --release --target armv7-unknown-linux-gnueabihf
```
> [!NOTE]
> 以下操作需要先将小爱音箱刷机, 然后 SSH 连接到小爱音箱。
编译成功后,将构建好的补丁程序 `client` 复制到小爱音箱上
```shell
# client 文件路径
./target/armv7-unknown-linux-gnueabihf/release/client
```
如果你是 macOS 系统,可以直接使用 `dd` + `ssh` 命令复制文件到小爱音箱
```shell
dd if=target/armv7-unknown-linux-gnueabihf/release/client \
| ssh -o HostKeyAlgorithms=+ssh-rsa root@你的小爱音箱IP地址 "dd of=/data/client"
```
> 注意:替换你自己的小爱音箱局域网 IP 地址,比如: root@192.168.31.227
你也可以先把 `client` 文件上传到一个地方,然后 SSH 连接到小爱音箱后,再用 `curl` 命令下载到本地。
```shell
# 连接到小爱音箱
ssh -o HostKeyAlgorithms=+ssh-rsa root@你的小爱音箱IP地址
# 下载文件到 /data/client
curl -# -o /data/client https://你的client文件下载链接
```
最后,在小爱音箱上授予 `client` 文件运行权限,然后运行:
```shell
# 授权
chmod +x /data/client
# 运行
/data/client ws://你的 server 端地址
# 比如:/data/client ws://192.168.31.227:4399
```
## 注意事项
> [!TIP]
> 旧版小爱音箱 Pro 的可用 RAM 和 ROM 均为 10MB 左右
>
> 新版 Xiaomi 智能音箱 Pro 约为 100MB(升级为旧版的 10 倍!)
当前 Client 端使用 Rust 编写,只负责转发和被动响应 Server 端的调用,不实现具体的业务逻辑。
一方面,小爱音箱的内存算力和存储空间极为有限,语音识别之类的任务并不适合放在 Client 端侧运行。
另一方面,使用 Rust 编写一些业务逻辑,不如 Python 和 Node.js 灵活开发效率高,后者的应用生态也更丰富一些。
> [!CAUTION]
> 当你在公网上运行本项目时,应当提高警惕。🚨
如上所言,本项目仅作为一个基础的演示程序。诸如多设备连接管理、身份认证、通信数据加密、音频压缩传输等均未做处理。
尤其是其提供了执行任意脚本的能力演示,虽然在启动 client 端时需要由你本人指定可信的 server 端连接地址,但还是要务必小心!
毕竟再怎么小心都不为过 :)
你也可以 Fork 本项目,在此基础上将 MiGPT 和小智 AI 等业务逻辑完全放在 Client 端运行,不需要将数据转发到 Server 端处理,这样就不存在隐私数据泄露的风险了,也不需要额外的服务器或 NAS 设备去部署运行。
+3
View File
@@ -0,0 +1,3 @@
pub type AppError = Box<dyn std::error::Error>;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
+155
View File
@@ -0,0 +1,155 @@
use open_xiaoai::services::audio::config::AudioConfig;
use serde_json::json;
use std::time::Duration;
use tokio::time::sleep;
use tokio_tungstenite::connect_async;
use open_xiaoai::base::AppError;
use open_xiaoai::base::VERSION;
use open_xiaoai::services::audio::play::AudioPlayer;
use open_xiaoai::services::audio::record::AudioRecorder;
use open_xiaoai::services::connect::data::{Event, Request, Response, Stream};
use open_xiaoai::services::connect::handler::MessageHandler;
use open_xiaoai::services::connect::message::{MessageManager, WsStream};
use open_xiaoai::services::connect::rpc::RPC;
use open_xiaoai::services::monitor::instruction::InstructionMonitor;
use open_xiaoai::services::monitor::playing::PlayingMonitor;
struct AppClient;
impl AppClient {
pub async fn connect(url: &str) -> Result<WsStream, AppError> {
let (ws_stream, _) = connect_async(url).await?;
Ok(WsStream::Client(ws_stream))
}
pub async fn run() {
let url = std::env::args().nth(1).expect("❌ 请输入服务器地址");
println!("✅ 已启动");
loop {
let Ok(ws_stream) = AppClient::connect(&url).await else {
sleep(Duration::from_secs(1)).await;
continue;
};
println!("✅ 已连接: {:?}", url);
AppClient::init(ws_stream).await;
if let Err(e) = MessageManager::instance().process_messages().await {
eprintln!("❌ 消息处理异常: {}", e);
}
AppClient::dispose().await;
eprintln!("❌ 已断开连接");
}
}
async fn init(ws_stream: WsStream) {
MessageManager::instance().init(ws_stream).await;
MessageHandler::<Event>::instance()
.set_handler(on_event)
.await;
MessageHandler::<Stream>::instance()
.set_handler(on_stream)
.await;
let rpc = RPC::instance();
rpc.add_command("get_version", get_version).await;
rpc.add_command("run_shell", run_shell).await;
rpc.add_command("start_play", start_play).await;
rpc.add_command("stop_play", stop_play).await;
rpc.add_command("start_recording", start_recording).await;
rpc.add_command("stop_recording", stop_recording).await;
InstructionMonitor::start(|event| async move {
MessageManager::instance()
.send_event("instruction", Some(json!(event)))
.await
})
.await;
PlayingMonitor::instance()
.start(|event| async move {
MessageManager::instance()
.send_event("playing", Some(json!(event)))
.await
})
.await;
}
async fn dispose() {
MessageManager::instance().dispose().await;
let _ = AudioPlayer::instance().stop().await;
let _ = AudioRecorder::instance().stop_recording().await;
InstructionMonitor::stop().await;
PlayingMonitor::instance().stop().await;
}
}
async fn get_version(_: Request) -> Result<Response, AppError> {
let data = json!(VERSION.to_string());
Ok(Response::from_data(data))
}
async fn start_play(request: Request) -> Result<Response, AppError> {
let config = request
.payload
.and_then(|payload| serde_json::from_value::<AudioConfig>(payload).ok());
AudioPlayer::instance().start(config).await?;
Ok(Response::success())
}
async fn stop_play(_: Request) -> Result<Response, AppError> {
AudioPlayer::instance().stop().await?;
Ok(Response::success())
}
async fn start_recording(request: Request) -> Result<Response, AppError> {
let config = request
.payload
.and_then(|payload| serde_json::from_value::<AudioConfig>(payload).ok());
AudioRecorder::instance()
.start_recording(
|bytes| async {
MessageManager::instance()
.send_stream("record", bytes, None)
.await
},
config,
)
.await?;
Ok(Response::success())
}
async fn stop_recording(_: Request) -> Result<Response, AppError> {
AudioRecorder::instance().stop_recording().await?;
Ok(Response::success())
}
async fn run_shell(request: Request) -> Result<Response, AppError> {
let script = match request.payload {
Some(payload) => serde_json::from_value::<String>(payload)?,
_ => return Err("empty command".into()),
};
let res = open_xiaoai::utils::shell::run_shell(script.as_str()).await?;
Ok(Response::from_data(json!(res)))
}
async fn on_event(event: Event) -> Result<(), AppError> {
println!("🔥 收到事件: {:?}", event);
Ok(())
}
async fn on_stream(stream: Stream) -> Result<(), AppError> {
let Stream { tag, bytes, .. } = stream;
match tag.as_str() {
"play" => {
// 播放接收到的音频流
let _ = AudioPlayer::instance().play(bytes).await;
}
_ => {}
}
Ok(())
}
#[tokio::main]
async fn main() {
AppClient::run().await;
}
+3
View File
@@ -0,0 +1,3 @@
pub mod base;
pub mod services;
pub mod utils;
@@ -0,0 +1,22 @@
use std::sync::LazyLock;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AudioConfig {
pub pcm: String,
pub channels: u16,
pub bits_per_sample: u16,
pub sample_rate: u32,
pub period_size: u32,
pub buffer_size: u32,
}
pub static AUDIO_CONFIG: LazyLock<AudioConfig> = LazyLock::new(|| AudioConfig {
pcm: "noop".into(),
channels: 1,
bits_per_sample: 16,
sample_rate: 24000,
period_size: 1440 / 4,
buffer_size: 1440,
});
@@ -0,0 +1,3 @@
pub mod config;
pub mod play;
pub mod record;
@@ -0,0 +1,117 @@
use std::process::Stdio;
use std::sync::{Arc, LazyLock};
use tokio::io::AsyncWriteExt;
use tokio::process::{Child, ChildStdin, Command};
use tokio::sync::{mpsc, Mutex};
use tokio::task::JoinHandle;
use crate::base::AppError;
use super::config::{AudioConfig, AUDIO_CONFIG};
pub struct AudioPlayer {
aplay_thread: Arc<Mutex<Option<Child>>>,
write_thread: Arc<Mutex<Option<ChildStdin>>>,
sender: Arc<Mutex<Option<mpsc::Sender<Vec<u8>>>>>,
player_task: Arc<Mutex<Option<JoinHandle<()>>>>,
}
static INSTANCE: LazyLock<AudioPlayer> = LazyLock::new(AudioPlayer::new);
impl AudioPlayer {
fn new() -> Self {
Self {
aplay_thread: Arc::new(Mutex::new(None)),
write_thread: Arc::new(Mutex::new(None)),
sender: Arc::new(Mutex::new(None)),
player_task: Arc::new(Mutex::new(None)),
}
}
pub fn instance() -> &'static Self {
&INSTANCE
}
pub async fn stop(&self) -> Result<(), AppError> {
let mut sender_guard = self.sender.lock().await;
if let Some(sender) = sender_guard.take() {
drop(sender);
}
if let Some(task) = self.player_task.lock().await.take() {
let _ = task.abort();
}
if let Some(mut write_thread) = self.write_thread.lock().await.take() {
let _ = write_thread.shutdown().await;
drop(write_thread);
}
if let Some(mut aplay_thread) = self.aplay_thread.lock().await.take() {
let _ = aplay_thread.kill().await;
}
Ok(())
}
pub async fn start(&self, config: Option<AudioConfig>) -> Result<(), AppError> {
let is_started = self.sender.lock().await.is_some();
if is_started {
self.stop().await?;
}
let config = config.unwrap_or_else(|| (*AUDIO_CONFIG).clone());
let mut aplay_thread = Command::new("aplay")
.args([
"--quiet",
"-t",
"raw",
"-f",
&format!("S{}_LE", config.bits_per_sample),
"-r",
&config.sample_rate.to_string(),
"-c",
&config.channels.to_string(),
"--buffer-size",
&config.buffer_size.to_string(),
"--period-size",
&config.period_size.to_string(),
"-",
])
.stdin(Stdio::piped())
.spawn()?;
let stdin = aplay_thread.stdin.take().unwrap();
self.aplay_thread.lock().await.replace(aplay_thread);
self.write_thread.lock().await.replace(stdin);
let (tx, mut rx) = mpsc::channel::<Vec<u8>>(100);
let write_thread_clone = self.write_thread.clone();
let player_task = tokio::spawn(async move {
while let Some(bytes) = rx.recv().await {
let mut write_guard = write_thread_clone.lock().await;
if let Some(write_thread) = write_guard.as_mut() {
let _ = write_thread.write_all(&bytes).await;
} else {
break;
}
}
});
self.player_task.lock().await.replace(player_task);
self.sender.lock().await.replace(tx);
Ok(())
}
pub async fn play(&self, bytes: Vec<u8>) -> Result<(), AppError> {
let sender_guard = self.sender.lock().await;
if let Some(sender) = sender_guard.as_ref() {
sender.send(bytes).await?;
}
Ok(())
}
}
@@ -0,0 +1,126 @@
use std::future::Future;
use std::process::Stdio;
use std::sync::{Arc, LazyLock};
use tokio::io::AsyncReadExt;
use tokio::process::{Child, Command};
use tokio::sync::Mutex;
use tokio::task::JoinHandle;
use crate::base::AppError;
use super::config::{AudioConfig, AUDIO_CONFIG};
#[derive(PartialEq)]
enum State {
Idle,
Recording,
}
pub struct AudioRecorder {
state: Arc<Mutex<State>>,
arecord_thread: Arc<Mutex<Option<Child>>>,
read_thread: Arc<Mutex<Option<JoinHandle<()>>>>,
}
static INSTANCE: LazyLock<AudioRecorder> = LazyLock::new(AudioRecorder::new);
impl AudioRecorder {
fn new() -> Self {
Self {
state: Arc::new(Mutex::new(State::Idle)),
arecord_thread: Arc::new(Mutex::new(None)),
read_thread: Arc::new(Mutex::new(None)),
}
}
pub fn instance() -> &'static Self {
&INSTANCE
}
pub async fn stop_recording(&self) -> Result<(), AppError> {
let mut state = self.state.lock().await;
if *state == State::Idle {
return Ok(());
}
if let Some(read_thread) = self.read_thread.lock().await.take() {
read_thread.abort();
}
if let Some(mut arecord_thread) = self.arecord_thread.lock().await.take() {
let _ = arecord_thread.kill().await;
}
*state = State::Idle;
Ok(())
}
pub async fn start_recording<F, Fut>(
&self,
on_stream: F,
config: Option<AudioConfig>,
) -> Result<(), AppError>
where
F: Fn(Vec<u8>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
let mut state = self.state.lock().await;
if *state == State::Recording {
return Ok(());
}
let config = config.unwrap_or_else(|| (*AUDIO_CONFIG).clone());
let mut arecord_thread = Command::new("arecord")
.args([
"--quiet",
"-t",
"raw",
"-D",
&config.pcm,
"-f",
&format!("S{}_LE", config.bits_per_sample),
"-r",
&config.sample_rate.to_string(),
"-c",
&config.channels.to_string(),
"--buffer-size",
&config.buffer_size.to_string(),
"--period-size",
&config.period_size.to_string(),
])
.stdout(Stdio::piped())
.spawn()?;
let mut stdout = arecord_thread.stdout.take().unwrap();
let read_thread = tokio::spawn(async move {
let size = (config.bits_per_sample / 8) as usize;
let target_size = config.buffer_size as usize * size;
let mut accumulated_data = Vec::new();
let mut buffer = vec![0u8; config.period_size as usize * size];
loop {
match stdout.read(&mut buffer).await {
Ok(size) if size > 0 => {
accumulated_data.extend_from_slice(&buffer[..size]);
if accumulated_data.len() >= target_size {
let data_to_send =
accumulated_data.drain(..target_size).collect::<Vec<u8>>();
let _ = on_stream(data_to_send).await;
}
}
_ => break,
}
}
let _ = AudioRecorder::instance().stop_recording().await;
});
self.arecord_thread.lock().await.replace(arecord_thread);
self.read_thread.lock().await.replace(read_thread);
*state = State::Recording;
Ok(())
}
}
@@ -0,0 +1,96 @@
use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;
#[derive(Debug, Serialize, Deserialize)]
pub enum AppMessage {
Request(Request),
Response(Response),
Event(Event),
Stream(Stream),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Stream {
pub id: String,
pub tag: String,
pub bytes: Vec<u8>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub data: Option<Value>,
}
impl Stream {
pub fn new(tag: &str, bytes: Vec<u8>, data: Option<Value>) -> Self {
Self {
id: Uuid::new_v4().to_string(),
tag: tag.to_string(),
bytes,
data,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Event {
pub id: String,
pub event: String,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub data: Option<Value>,
}
impl Event {
pub fn new(event: &str, data: Option<Value>) -> Self {
Self {
id: Uuid::new_v4().to_string(),
event: event.to_string(),
data,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Request {
pub id: String,
pub command: String,
pub payload: Option<Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Response {
pub id: String,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub code: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub msg: Option<String>,
#[serde(skip_serializing_if = "Option::is_none", default)]
pub data: Option<Value>,
}
impl Response {
pub fn success() -> Self {
Self {
id: 0.to_string(),
code: Some(0),
msg: Some("success".to_string()),
data: None,
}
}
pub fn from_data(data: Value) -> Self {
Self {
id: 0.to_string(),
code: None,
msg: None,
data: Some(data),
}
}
pub fn from_error(id: &str, e: impl std::fmt::Display) -> Self {
Self {
id: id.to_string(),
code: Some(-1),
msg: Some(e.to_string()),
data: None,
}
}
}
@@ -0,0 +1,93 @@
use futures::future::BoxFuture;
use std::future::Future;
use std::sync::{Arc, LazyLock};
use tokio::sync::Mutex;
use tokio_tungstenite::tungstenite::Message;
use crate::base::AppError;
use super::data::{AppMessage, Event, Request, Response, Stream};
use super::message::MessageManager;
use super::rpc::RPC;
type Handler<T> = Arc<dyn Fn(T) -> BoxFuture<'static, Result<(), AppError>> + Send + Sync>;
pub struct MessageHandler<T> {
handler: Arc<Mutex<Option<Handler<T>>>>,
}
static REQUEST_INSTANCE: LazyLock<MessageHandler<Request>> = LazyLock::new(MessageHandler::new);
static RESPONSE_INSTANCE: LazyLock<MessageHandler<Response>> = LazyLock::new(MessageHandler::new);
static EVENT_INSTANCE: LazyLock<MessageHandler<Event>> = LazyLock::new(MessageHandler::new);
static BYTES_INSTANCE: LazyLock<MessageHandler<Stream>> = LazyLock::new(MessageHandler::new);
impl<T> MessageHandler<T> {
fn new() -> Self {
Self {
handler: Arc::new(Mutex::new(None)),
}
}
pub async fn set_handler<F, Fut>(&self, handler: F)
where
F: Fn(T) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
*self.handler.lock().await = Some(Arc::new(move |data| Box::pin(handler(data))));
}
pub async fn on(&self, data: T) -> Result<(), AppError> {
let handler = {
let guard = self.handler.lock().await;
match &*guard {
Some(h) => Arc::clone(h),
None => return Err("handler is not initialized".into()),
}
};
handler(data).await
}
}
impl MessageHandler<Request> {
pub fn instance() -> &'static MessageHandler<Request> {
&REQUEST_INSTANCE
}
pub async fn on_request(&self, request: Request) -> Result<(), AppError> {
println!("🚗 收到指令: {:?}", request);
let id = request.id.clone();
let response: Response = match RPC::instance().on_request(request).await {
Ok(resp) => Response { id, ..resp },
Err(e) => Response::from_error(&id, e),
};
if let Ok(data) = serde_json::to_string(&AppMessage::Response(response)) {
MessageManager::instance()
.send(Message::Text(data.into()))
.await?;
}
Ok(())
}
}
impl MessageHandler<Response> {
pub fn instance() -> &'static MessageHandler<Response> {
&RESPONSE_INSTANCE
}
pub async fn on_response(&self, response: Response) -> Result<(), AppError> {
RPC::instance().on_response(response).await;
Ok(())
}
}
impl MessageHandler<Event> {
pub fn instance() -> &'static MessageHandler<Event> {
&EVENT_INSTANCE
}
}
impl MessageHandler<Stream> {
pub fn instance() -> &'static MessageHandler<Stream> {
&BYTES_INSTANCE
}
}
@@ -0,0 +1,203 @@
use futures::stream::{SplitSink, SplitStream};
use futures::{SinkExt, StreamExt};
use serde_json::Value;
use std::future::Future;
use std::sync::{Arc, LazyLock};
use tokio::net::TcpStream;
use tokio::sync::{Mutex, Semaphore};
use tokio_tungstenite::MaybeTlsStream;
use tokio_tungstenite::{tungstenite::Message, WebSocketStream};
use super::rpc::RPC;
use crate::base::AppError;
use crate::utils::task::TaskManager;
use super::data::{AppMessage, Event, Request, Response, Stream};
use super::handler::MessageHandler;
pub enum WsStream {
Server(WebSocketStream<TcpStream>),
Client(WebSocketStream<MaybeTlsStream<TcpStream>>),
}
pub enum WsReader {
Server(SplitStream<WebSocketStream<TcpStream>>),
Client(SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>),
}
pub enum WsWriter {
Server(SplitSink<WebSocketStream<TcpStream>, Message>),
Client(SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>),
}
pub struct MessageManager {
semaphore: Arc<Semaphore>,
reader: Arc<Mutex<Option<WsReader>>>,
writer: Arc<Mutex<Option<WsWriter>>>,
}
static INSTANCE: LazyLock<MessageManager> = LazyLock::new(MessageManager::new);
impl MessageManager {
fn new() -> Self {
Self {
reader: Arc::new(Mutex::new(None)),
writer: Arc::new(Mutex::new(None)),
semaphore: Arc::new(Semaphore::new(32)),
}
}
pub fn instance() -> &'static Self {
&INSTANCE
}
pub async fn init(&self, ws_stream: WsStream) {
match ws_stream {
WsStream::Client(stream) => {
let (tx, rx) = stream.split();
self.reader.lock().await.replace(WsReader::Client(rx));
self.writer.lock().await.replace(WsWriter::Client(tx));
}
WsStream::Server(stream) => {
let (tx, rx) = stream.split();
self.reader.lock().await.replace(WsReader::Server(rx));
self.writer.lock().await.replace(WsWriter::Server(tx));
}
}
RPC::instance()
.init(|request| async {
let data = serde_json::to_string(&AppMessage::Request(request)).unwrap();
MessageManager::instance()
.send(Message::Text(data.into()))
.await
})
.await;
}
pub async fn dispose(&self) {
*self.reader.lock().await = None;
*self.writer.lock().await = None;
RPC::instance().dispose().await;
TaskManager::instance().dispose("MessageManager").await;
}
pub async fn send(&self, msg: Message) -> Result<(), AppError> {
let mut writer_guard = self.writer.lock().await;
let Some(writer) = &mut *writer_guard else {
return Err("WebSocket writer is not initialized".into());
};
match writer {
WsWriter::Client(w) => w.send(msg).await?,
WsWriter::Server(w) => w.send(msg).await?,
}
Ok(())
}
pub async fn send_event(&self, event: &str, data: Option<Value>) -> Result<(), AppError> {
let event: Event = Event::new(event, data);
let data = serde_json::to_string(&AppMessage::Event(event)).unwrap();
MessageManager::instance()
.send(Message::Text(data.into()))
.await
}
pub async fn send_stream(
&self,
tag: &str,
bytes: Vec<u8>,
data: Option<Value>,
) -> Result<(), AppError> {
let stream = serde_json::to_vec(&Stream::new(tag, bytes, data)).unwrap();
MessageManager::instance()
.send(Message::Binary(stream.into()))
.await
}
pub async fn process_messages(&self) -> Result<(), AppError> {
if self.reader.lock().await.is_none() {
return Err("WebSocket reader is not initialized".into());
}
loop {
let next_msg = {
let mut reader = self.reader.lock().await;
match reader.as_mut() {
None => break,
Some(WsReader::Client(reader)) => reader.next().await,
Some(WsReader::Server(reader)) => reader.next().await,
}
};
match next_msg {
None => break,
Some(Ok(Message::Close(_))) => break,
Some(Err(e)) => return Err(e.into()),
Some(Ok(msg)) => {
match msg {
Message::Text(text) => {
let _ = self.on_text(text.to_string()).await;
}
Message::Binary(bytes) => {
let _ = self.on_bytes(bytes.into()).await;
}
_ => {}
};
}
}
}
Ok(())
}
async fn on_bytes(&self, bytes: Vec<u8>) -> Result<(), AppError> {
let data = serde_json::from_slice::<Stream>(&bytes)?;
MessageHandler::<Stream>::instance().on(data).await
}
async fn on_text(&self, text: String) -> Result<(), AppError> {
let msg = serde_json::from_str::<AppMessage>(&text)?;
match msg {
AppMessage::Request(request) => {
self.run_concurrently(move || {
let request = request.clone();
async move {
MessageHandler::<Request>::instance()
.on_request(request)
.await?;
Ok(())
}
})
.await
}
AppMessage::Response(response) => {
MessageHandler::<Response>::instance()
.on_response(response)
.await
}
AppMessage::Event(event) => MessageHandler::<Event>::instance().on(event).await,
_ => Ok(()),
}
}
async fn run_concurrently<F, Fut>(&self, run: F) -> Result<(), AppError>
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
let permit = match self.semaphore.clone().try_acquire_owned() {
Ok(permit) => permit,
Err(_) => self.semaphore.clone().acquire_owned().await?,
};
let task = tokio::spawn(async move {
let _ = run().await;
drop(permit);
});
TaskManager::instance().add("MessageManager", task).await;
Ok(())
}
}
@@ -0,0 +1,4 @@
pub mod data;
pub mod handler;
pub mod message;
pub mod rpc;
@@ -0,0 +1,150 @@
use futures::future::BoxFuture;
use std::collections::HashMap;
use std::future::Future;
use std::sync::{Arc, LazyLock};
use tokio::sync::{oneshot, Mutex, RwLock};
use tokio::time::{timeout, Duration};
use uuid::Uuid;
use crate::base::AppError;
use super::data::{Request, Response};
type SendRequestFn = Arc<dyn Fn(Request) -> BoxFuture<'static, Result<(), AppError>> + Send + Sync>;
type RequestHandler =
Arc<dyn Fn(Request) -> BoxFuture<'static, Result<Response, AppError>> + Send + Sync>;
static INSTANCE: LazyLock<RPC> = LazyLock::new(RPC::new);
pub struct RPC {
send_request: Arc<RwLock<Option<SendRequestFn>>>,
request_handlers: Arc<RwLock<HashMap<String, RequestHandler>>>,
pending_requests: Arc<Mutex<HashMap<String, oneshot::Sender<Response>>>>,
}
impl RPC {
fn new() -> Self {
Self {
send_request: Arc::new(RwLock::new(None)),
request_handlers: Arc::new(RwLock::new(HashMap::new())),
pending_requests: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn instance() -> &'static Self {
&INSTANCE
}
pub async fn init<F, Fut>(&self, send_request: F)
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
let mut lock = self.send_request.write().await;
*lock = Some(Arc::new(move |msg| Box::pin(send_request(msg))));
}
pub async fn dispose(&self) {
{
let mut lock = self.send_request.write().await;
*lock = None;
}
{
let mut lock = self.request_handlers.write().await;
lock.clear();
}
{
let mut lock = self.pending_requests.lock().await;
lock.clear();
}
}
/// 添加 local 方法
pub async fn add_command<F, Fut>(&self, command: &str, handler: F)
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Response, AppError>> + Send + 'static,
{
let mut handlers = self.request_handlers.write().await;
handlers.insert(
command.to_string(),
Arc::new(move |request| Box::pin(handler(request))),
);
}
/// local 收到 remote 调用
pub async fn on_request(&self, request: Request) -> Result<Response, AppError> {
let handler = self.get_request_handler(&request.command).await;
match handler {
Some(handler) => handler(request).await,
None => Err("command not found".into()),
}
}
/// local 收到 remote 响应
pub async fn on_response(&self, response: Response) {
let tx = {
let mut pending = self.pending_requests.lock().await;
pending.remove(&response.id)
};
if let Some(tx) = tx {
let _ = tx.send(response);
}
}
/// 调用 remote 方法
pub async fn call_remote(
&self,
command: &str,
payload: Option<serde_json::Value>,
timeout_millis: Option<u64>,
) -> Result<Response, AppError> {
let send_request = self.get_send_request().await;
let Some(send_request) = send_request else {
return Err("send_request is not initialized".into());
};
let uid = Uuid::new_v4().to_string();
let (tx, rx) = oneshot::channel();
let request = Request {
id: uid.clone(),
command: command.to_string(),
payload,
};
send_request(request).await?;
{
let mut pending = self.pending_requests.lock().await;
pending.insert(uid.clone(), tx);
}
let timeout_duration = Duration::from_millis(timeout_millis.unwrap_or(10 * 1000));
match timeout(timeout_duration, rx).await {
Ok(Ok(response)) => Ok(response),
Ok(Err(_)) => {
let mut pending = self.pending_requests.lock().await;
pending.remove(&uid);
Err("response channel closed".into())
}
Err(_) => {
let mut pending = self.pending_requests.lock().await;
pending.remove(&uid);
Err("request timeout".into())
}
}
}
async fn get_send_request(&self) -> Option<SendRequestFn> {
let send_request = self.send_request.read().await;
send_request.clone()
}
async fn get_request_handler(&self, event: &str) -> Option<RequestHandler> {
let handlers = self.request_handlers.read().await;
handlers.get(event).cloned()
}
}
+4
View File
@@ -0,0 +1,4 @@
pub mod audio;
pub mod connect;
pub mod monitor;
pub mod speaker;
@@ -0,0 +1,106 @@
use serde::{Deserialize, Serialize};
use std::future::Future;
use std::path::Path;
use std::sync::LazyLock;
use tokio::fs::OpenOptions;
use tokio::io::{AsyncBufReadExt, AsyncSeekExt, BufReader, SeekFrom};
use tokio::time::{sleep, Duration};
use crate::base::AppError;
use crate::utils::task::TaskManager;
#[derive(Debug, Serialize, Deserialize)]
pub enum FileMonitorEvent {
NewFile,
NewLine(String),
}
pub struct FileMonitor;
static INSTANCE: LazyLock<FileMonitor> = LazyLock::new(FileMonitor::new);
impl FileMonitor {
fn new() -> Self {
Self {}
}
pub fn instance() -> &'static Self {
&INSTANCE
}
pub async fn start<F, Fut>(&self, file_path: &str, on_update: F)
where
F: Fn(FileMonitorEvent) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
let file_path_clone = file_path.to_string();
let monitor = tokio::spawn(async move {
let _ = FileMonitor::start_monitor(file_path_clone.as_str(), on_update).await;
});
TaskManager::instance()
.add(&format!("FileMonitor-{}", file_path), monitor)
.await;
}
pub async fn stop(&self, file_path: &str) {
TaskManager::instance()
.dispose(&format!("FileMonitor-{}", file_path))
.await;
}
async fn start_monitor<F, Fut>(file_path: &str, on_update: F) -> Result<(), AppError>
where
F: Fn(FileMonitorEvent) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
while !Path::new(file_path).exists() {
sleep(Duration::from_millis(100)).await;
}
let file = OpenOptions::new().read(true).open(file_path).await?;
let mut reader = BufReader::new(file);
let metadata = reader.get_ref().metadata().await.unwrap();
let mut position = metadata.len();
loop {
let metadata = reader.get_ref().metadata().await.unwrap();
let current_size = metadata.len();
if current_size < position {
position = 0;
let _ = on_update(FileMonitorEvent::NewFile).await;
}
if reader.stream_position().await? != position {
reader.seek(SeekFrom::Start(position)).await?;
}
let mut line = String::new();
let mut new_content_found = false;
while let Ok(bytes_read) = reader.read_line(&mut line).await {
if bytes_read == 0 {
break;
}
let trimmed_line = line.trim();
if !trimmed_line.is_empty() {
new_content_found = true;
let _ = on_update(FileMonitorEvent::NewLine(trimmed_line.to_string())).await;
}
position = reader.stream_position().await?;
line.clear();
}
if !new_content_found {
sleep(Duration::from_millis(100)).await;
} else {
sleep(Duration::from_millis(10)).await;
}
}
}
}
@@ -0,0 +1,134 @@
use std::future::Future;
use serde::{Deserialize, Serialize};
use crate::base::AppError;
use super::file::{FileMonitor, FileMonitorEvent};
pub struct InstructionMonitor;
static INSTRUCTION_FILE_PATH: &str = "/tmp/mico_aivs_lab/instruction.log";
impl InstructionMonitor {
pub async fn start<F, Fut>(on_update: F)
where
F: Fn(FileMonitorEvent) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
FileMonitor::instance()
.start(INSTRUCTION_FILE_PATH, on_update)
.await;
}
pub async fn stop() {
FileMonitor::instance().stop(INSTRUCTION_FILE_PATH).await;
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Header {
pub dialog_id: String,
pub id: String,
pub name: String,
pub namespace: String,
}
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct RecognizeResult {
#[serde(default)]
pub confidence: f64,
#[serde(default)]
pub text: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub asr_binary_offset: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub begin_offset: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub end_offset: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_nlp_request: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub is_stop: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub origin_text: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum Payload {
RecognizeResultPayload {
is_final: bool,
is_vad_begin: bool,
results: Vec<RecognizeResult>,
},
StopCapturePayload {
stop_time: u64,
},
SpeakPayload {
text: String,
#[serde(skip_serializing_if = "Option::is_none")]
emotion: Option<Emotion>,
},
PlayPayload {
audio_items: Vec<AudioItem>,
audio_type: String,
loadmore_token: String,
needs_loadmore: bool,
origin_id: String,
play_behavior: String,
},
SetPropertyPayload {
name: String,
value: String,
},
InstructionControlPayload {
behavior: String,
},
EmptyPayload {},
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Emotion {
pub category: String,
pub level: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct AudioItem {
pub item_id: ItemId,
pub log: Log,
pub stream: Stream,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct ItemId {
pub audio_id: String,
pub cp: Cp,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Cp {
pub id: String,
pub name: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Log {
pub eid: String,
pub refer: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Stream {
pub authentication: bool,
pub duration_in_ms: u64,
pub offset_in_ms: u64,
pub url: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LogMessage {
pub header: Header,
pub payload: Payload,
}
@@ -0,0 +1,3 @@
pub mod file;
pub mod instruction;
pub mod playing;
@@ -0,0 +1,70 @@
use serde::{Deserialize, Serialize};
use std::future::Future;
use std::sync::LazyLock;
use tokio::time::{sleep, Duration};
use crate::base::AppError;
use crate::utils::shell::run_shell;
use crate::utils::task::TaskManager;
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
pub enum PlayingMonitorEvent {
Playing,
Paused,
Idle,
}
pub struct PlayingMonitor;
static INSTANCE: LazyLock<PlayingMonitor> = LazyLock::new(PlayingMonitor::new);
impl PlayingMonitor {
fn new() -> Self {
Self {}
}
pub fn instance() -> &'static Self {
&INSTANCE
}
pub async fn start<F, Fut>(&self, on_update: F)
where
F: Fn(PlayingMonitorEvent) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
let monitor = tokio::spawn(async move {
let _ = PlayingMonitor::start_monitor(on_update).await;
});
TaskManager::instance().add("PlayingMonitor", monitor).await;
}
pub async fn stop(&self) {
TaskManager::instance().dispose("PlayingMonitor").await;
}
async fn start_monitor<F, Fut>(on_update: F) -> Result<(), AppError>
where
F: Fn(PlayingMonitorEvent) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
let mut last_status = PlayingMonitorEvent::Idle;
loop {
let res = run_shell("mphelper mute_stat").await?;
let status = if res.stdout.contains("1") {
PlayingMonitorEvent::Playing
} else if res.stdout.contains("2") {
PlayingMonitorEvent::Paused
} else {
PlayingMonitorEvent::Idle
};
if last_status != status {
last_status = status.clone();
let _ = on_update(status).await;
}
sleep(Duration::from_millis(100)).await;
}
}
}
@@ -0,0 +1,174 @@
use serde_json::json;
use crate::utils::shell::CommandResult;
use crate::{base::AppError, services::connect::rpc::RPC};
pub struct SpeakerManager;
impl SpeakerManager {
/// 获取启动分区
pub async fn get_boot() -> Result<String, AppError> {
const COMMAND: &str = r#"
echo $(fw_env -g boot_part)
"#;
let res = SpeakerManager::run_shell(COMMAND).await?;
Ok(res.stdout.trim().to_string())
}
/// 设置启动分区
pub async fn set_boot(boot_part: &str) -> Result<bool, AppError> {
const COMMAND: &str = r#"
fw_env -s boot_part %s >/dev/null 2>&1 && echo $(fw_env -g boot_part)
"#;
let script = COMMAND.replace("%s", boot_part);
let res = SpeakerManager::run_shell(&script).await?;
Ok(res.stdout.contains(boot_part))
}
/// 获取设备型号
pub async fn get_device_model() -> Result<String, AppError> {
const COMMAND: &str = r#"
echo $(micocfg_model)
"#;
let res = SpeakerManager::run_shell(COMMAND).await?;
Ok(res.stdout.trim().to_string())
}
/// 获取设备序列号
pub async fn get_device_sn() -> Result<String, AppError> {
const COMMAND: &str = r#"
echo $(micocfg_sn)
"#;
let res = SpeakerManager::run_shell(COMMAND).await?;
Ok(res.stdout.trim().to_string())
}
/// 获取播放状态
pub async fn get_play_status() -> Result<String, AppError> {
const COMMAND: &str = r#"
mphelper mute_stat
"#;
let res = SpeakerManager::run_shell(COMMAND).await?;
let status = if res.stdout.contains("1") {
"playing"
} else if res.stdout.contains("2") {
"paused"
} else {
"idle"
};
Ok(status.to_string())
}
/// 播放
pub async fn play() -> Result<bool, AppError> {
const COMMAND: &str = r#"
mphelper play
"#;
let res = SpeakerManager::run_shell(COMMAND).await?;
Ok(res.stdout.contains("\"code\": 0"))
}
/// 暂停
pub async fn pause() -> Result<bool, AppError> {
const COMMAND: &str = r#"
mphelper pause
"#;
let res = SpeakerManager::run_shell(COMMAND).await?;
Ok(res.stdout.contains("\"code\": 0"))
}
/// TTS
pub async fn play_text(text: &str) -> Result<bool, AppError> {
const COMMAND: &str = r#"
/usr/sbin/tts_play2.sh '%s'
"#;
let script = COMMAND.replace("%s", text);
let res = SpeakerManager::run_shell(&script).await?;
Ok(res.stdout.contains("\"code\": 0"))
}
/// 播放音频
pub async fn play_url(url: &str) -> Result<bool, AppError> {
const COMMAND: &str = r#"
ubus call mediaplayer player_play_url '{"url":"%s","type": 1}'
"#;
let script = COMMAND.replace("%s", url);
let res = SpeakerManager::run_shell(&script).await?;
Ok(res.stdout.contains("\"code\": 0"))
}
/// 获取麦克风状态
pub async fn get_mic_status() -> Result<String, AppError> {
const COMMAND: &str = r#"
[ ! -f /tmp/mipns/mute ] && echo on || echo off
"#;
let res = SpeakerManager::run_shell(COMMAND).await?;
let status = if res.stdout.contains("on") {
"on"
} else {
"off"
};
Ok(status.to_string())
}
/// 打开麦克风
pub async fn mic_on() -> Result<bool, AppError> {
const COMMAND: &str = r#"
ubus -t1 -S call pnshelper event_notify '{"src":3, "event":7}' 2>&1
"#;
let res = SpeakerManager::run_shell(COMMAND).await?;
Ok(res.stdout.contains("\"code\":0"))
}
/// 关闭麦克风
pub async fn mic_off() -> Result<bool, AppError> {
const COMMAND: &str = r#"
ubus -t1 -S call pnshelper event_notify '{"src":3, "event":8}' 2>&1
"#;
let res = SpeakerManager::run_shell(COMMAND).await?;
Ok(res.stdout.contains("\"code\":0"))
}
/// 执行命令
pub async fn ask_xiaoai(text: &str) -> Result<bool, AppError> {
const COMMAND: &str = r#"
ubus call mibrain ai_service '{"tts":1,"nlp":1,"nlp_text":"%s"}'
"#;
let script = COMMAND.replace("%s", text);
let res = SpeakerManager::run_shell(&script).await?;
Ok(res.stdout.contains("\"code\": 0"))
}
/// 中断运行
pub async fn abort_xiaoai() -> Result<bool, AppError> {
const COMMAND: &str = r#"
/etc/init.d/mico_aivs_lab restart >/dev/null 2>&1
"#;
let res = SpeakerManager::run_shell(COMMAND).await?;
Ok(res.exit_code == 0)
}
/// 唤醒
pub async fn wake_up(flag: bool) -> Result<bool, AppError> {
let command = if flag {
r#"
ubus call pnshelper event_notify '{"src":1,"event":0}'
"#
} else {
r#"
ubus call pnshelper event_notify '{"src":3, "event":7}'
sleep 0.1
ubus call pnshelper event_notify '{"src":3, "event":8}'
"#
};
let res = SpeakerManager::run_shell(command).await?;
Ok(res.stdout.contains("\"code\": 0"))
}
async fn run_shell(script: &str) -> Result<CommandResult, AppError> {
let res = RPC::instance()
.call_remote("run_shell", Some(json!(script)), None)
.await?;
Ok(serde_json::from_value::<CommandResult>(res.data.unwrap()).unwrap())
}
}
+81
View File
@@ -0,0 +1,81 @@
use futures::future::BoxFuture;
use std::{
collections::HashMap,
future::Future,
sync::{Arc, LazyLock},
};
use tokio::sync::Mutex;
use crate::{base::AppError, services::connect::data::Event};
use super::task::TaskManager;
type EventCallback = Arc<dyn Fn(Event) -> BoxFuture<'static, Result<(), AppError>> + Send + Sync>;
pub struct EventBus {
subscribers: Arc<Mutex<HashMap<String, Vec<EventCallback>>>>,
}
static INSTANCE: LazyLock<EventBus> = LazyLock::new(EventBus::new);
impl EventBus {
fn new() -> Self {
EventBus {
subscribers: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn instance() -> &'static Self {
&INSTANCE
}
pub async fn subscribe<F, Fut>(&self, event: &str, callback: F)
where
F: Fn(Event) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<(), AppError>> + Send + 'static,
{
let mut subscribers = self.subscribers.lock().await;
subscribers
.entry(event.to_string())
.or_insert_with(Vec::new)
.push(Arc::new(move |event| Box::pin(callback(event))));
}
pub async fn unsubscribe(&self, event: &str) {
self.subscribers.lock().await.remove(event);
let tag = format!("EventBus-{}", event);
TaskManager::instance().dispose(&tag).await;
}
pub async fn publish(&self, event: Event) {
let Some(callbacks) = self.get_callbacks(&event.event).await else {
return;
};
for callback in callbacks {
let event = event.clone();
let _ = callback(event).await;
}
}
pub async fn publish_async(&self, event: Event) {
let Some(callbacks) = self.get_callbacks(&event.event).await else {
return;
};
let tag = format!("EventBus-{}", event.event);
for callback in callbacks {
let event = event.clone();
let task = tokio::spawn(async move {
let _ = callback(event).await;
});
TaskManager::instance().add(&tag, task).await;
}
}
async fn get_callbacks(&self, event: &str) -> Option<Vec<EventCallback>> {
let subscribers = self.subscribers.lock().await;
match subscribers.get(event) {
Some(callbacks) => Some(callbacks.clone()),
None => None,
}
}
}
+3
View File
@@ -0,0 +1,3 @@
pub mod event;
pub mod shell;
pub mod task;
+29
View File
@@ -0,0 +1,29 @@
use serde::{Deserialize, Serialize};
use tokio::process::Command;
use crate::base::AppError;
#[derive(Debug, Serialize, Deserialize)]
pub struct CommandResult {
pub stdout: String,
pub stderr: String,
pub exit_code: i32,
}
pub async fn run_shell(script: &str) -> Result<CommandResult, AppError> {
let output = Command::new("/bin/sh")
.arg("-c")
.arg(script)
.output()
.await?;
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
let exit_code = output.status.code().unwrap_or(-1);
Ok(CommandResult {
stdout,
stderr,
exit_code,
})
}
+58
View File
@@ -0,0 +1,58 @@
use std::{
collections::HashMap,
future::Future,
sync::{Arc, LazyLock},
};
use tokio::{sync::Mutex, task::JoinHandle};
/// 批量管理异步任务,在合适的时机终止
pub struct TaskManager {
tasks: Arc<Mutex<HashMap<String, Vec<JoinHandle<()>>>>>,
}
static INSTANCE: LazyLock<TaskManager> = LazyLock::new(TaskManager::new);
impl TaskManager {
fn new() -> Self {
Self {
tasks: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn instance() -> &'static Self {
&INSTANCE
}
pub async fn add(&self, tag: &str, handle: JoinHandle<()>) {
let mut tasks = self.tasks.lock().await;
let handles = tasks.entry(tag.to_string()).or_insert_with(Vec::new);
handles.retain(|h| !h.is_finished());
handles.push(handle);
}
pub async fn dispose(&self, tag: &str) {
let mut tasks = self.tasks.lock().await;
if let Some(handles) = tasks.remove(tag) {
for handle in handles {
let _ = handle.abort();
}
}
}
pub async fn run_async<F>(future: F)
where
F: Future + Send + 'static,
F::Output: Send + 'static,
{
let task = tokio::spawn(async move {
let _ = future.await;
});
TaskManager::instance().add("async", task).await;
}
pub async fn dispose_async() {
TaskManager::instance().dispose("async").await;
}
}