A high-performance inference engine for AI models
update keisoku
eugene70463592e0a8
diff --git a/Cargo.lock b/Cargo.lockindex e68023c2c..2d09a08ce 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -138,7 +138,7 @@ version = "1.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"dependencies = [- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -149,7 +149,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"dependencies = ["anstyle","once_cell_polyfill",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -485,7 +485,6 @@ dependencies = ["indicatif","is_close","itertools 0.14.0",- "keisoku","libc","libm","memmap2",@@ -1095,7 +1094,7 @@ checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"dependencies = ["serde","termcolor",- "unicode-width 0.1.14",+ "unicode-width 0.2.2",][[package]]@@ -1116,7 +1115,7 @@ version = "3.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"dependencies = [- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -1799,7 +1798,7 @@ dependencies = ["libc","option-ext","redox_users",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -1943,7 +1942,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -3076,7 +3075,7 @@ checksum = "3640c1c38b8e4e43584d8df18be5fc6b0aa314ce6ebf51b53313d4306cca8e46"dependencies = ["hermit-abi","libc",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -3277,16 +3276,6 @@ dependencies = ["objc2-core-foundation",]-[[package]]-name = "kanshi"-version = "0.5.12"-dependencies = [- "crossterm",- "keisoku",- "ratatui",- "sysinfo",-]-[[package]]name = "kasuari"version = "0.4.12"@@ -3302,12 +3291,12 @@ dependencies = [name = "keisoku"version = "0.5.12"dependencies = [+ "bitflags 2.13.0","kanka","libc","obfstr","objc2-core-foundation","objc2-io-kit",- "ratatui","serde","serde_json","sysinfo",@@ -4013,7 +4002,7 @@ version = "0.50.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"dependencies = [- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -5701,7 +5690,7 @@ dependencies = ["errno","libc","linux-raw-sys",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -5759,7 +5748,7 @@ dependencies = ["security-framework","security-framework-sys","webpki-root-certs",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -6326,7 +6315,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51"dependencies = ["libc",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -6594,7 +6583,7 @@ dependencies = ["getrandom 0.4.2","once_cell","rustix",- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]@@ -6616,7 +6605,7 @@ dependencies = ["parking_lot","rustix","signal-hook",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -8028,7 +8017,7 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.59.0",+ "windows-sys 0.61.2",][[package]]diff --git a/Cargo.toml b/Cargo.tomlindex 9d152fc37..95ec3c170 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -18,7 +18,6 @@ members = ["crates/cli-tools","crates/test-runner","crates/keisoku",- "crates/kanshi","crates/kanka",]resolver = "3"@@ -117,17 +116,10 @@ syn = { version = "2.0", features = ["full", "fold"] }prettyplease = "0.2"rhai = "1.24.0"cbindgen = "0.29"-ctrlc = "3.5"indicatif = "0.18"-inquire = "0.9"-console = "0.16"rocket = { version = "0.5", features = ["json"] }uuid = { version = "1.20", features = ["serde", "v4", "v5"] }comfy-table = { version = "7.2", default-features = false }-autocxx = "0.30"-cxx = "1.0"-cmake = "0.1"-autocxx-build = "0.30"test-tag = "0.1"rstest = "0.26"wiremock = "0.6"@@ -153,7 +145,6 @@ reqwest = { version = "0.13.2", features = ["query",] }tokio-util = { version = "0.7.17", default-features = false, features = ["rt"] }-async-shutdown = "0.2.2"objc-sys = "0.3.5"crc32c = "0.6.8"base64 = "0.22.1"diff --git a/apps/playground/Sources/Extensions/ReplyStatsFormat.swift b/apps/playground/Sources/Extensions/ReplyStatsFormat.swiftindex 2f9b1d098..5bd086c63 100644--- a/apps/playground/Sources/Extensions/ReplyStatsFormat.swift+++ b/apps/playground/Sources/Extensions/ReplyStatsFormat.swift@@ -15,10 +15,9 @@ enum ReplyStatsFormat {// Power/energy values are uncertain on iOS (and unset until a run completes), so the// caller renders these rows only when the values are present — these just format.- static func power(average: Double, maximum: Double) -> String {+ static func power(average: Double) -> String {let avg = measurement.string(from: Measurement(value: average, unit: UnitPower.watts))- let peak = measurement.string(from: Measurement(value: maximum, unit: UnitPower.watts))- return "\(avg) avg · \(peak) peak"+ return "\(avg) avg"}static func energy(_ joules: Double) -> String {diff --git a/apps/playground/Sources/ViewModels/ReplyStats.swift b/apps/playground/Sources/ViewModels/ReplyStats.swiftindex bb9e6e96f..2802518f1 100644--- a/apps/playground/Sources/ViewModels/ReplyStats.swift+++ b/apps/playground/Sources/ViewModels/ReplyStats.swift@@ -5,9 +5,8 @@ struct ReplyStats: Equatable {let timeToFirstToken: Doublelet tokensPerSecond: Doublelet memoryUsedBytes: Int64?- let averagePackagePower: Double?- let maxPackagePower: Double?- let packageEnergy: Double?+ let totalPower: Double?+ let totalEnergy: Double?let tokensCount: Int?let totalTime: Double@@ -15,9 +14,8 @@ struct ReplyStats: Equatable {timeToFirstToken = stats.timeToFirstToken ?? 0.0tokensPerSecond = stats.generateTokensPerSecond ?? 0.0memoryUsedBytes = stats.memoryUsedBytes- averagePackagePower = stats.powerStats?.averagePackageWatts- maxPackagePower = stats.powerStats?.maxPackageWatts- packageEnergy = stats.powerStats?.energyJoules+ totalPower = stats.powerStats?.averageTotalWatts+ totalEnergy = stats.powerStats?.energyJoulesif let input = stats.tokensCountInput, let output = stats.tokensCountOutput {tokensCount = Int(input) + Int(output)} else {diff --git a/apps/playground/Sources/Views/ReplyStatsView.swift b/apps/playground/Sources/Views/ReplyStatsView.swiftindex 464f07e93..00876be80 100644--- a/apps/playground/Sources/Views/ReplyStatsView.swift+++ b/apps/playground/Sources/Views/ReplyStatsView.swift@@ -16,13 +16,13 @@ struct ReplyStatsView: View {metricRow(label: "Tokens per second:", value: String(format: "%.3f t/s", stats.tokensPerSecond))}metricRow(label: "Memory used:", value: ReplyStatsFormat.memory(stats.memoryUsedBytes))- if let average = stats.averagePackagePower, let peak = stats.maxPackagePower {- metricRow(label: ReplyStatsFormat.powerLabel, value: ReplyStatsFormat.power(average: average, maximum: peak))+ if let power = stats.totalPower {+ metricRow(label: ReplyStatsFormat.powerLabel, value: ReplyStatsFormat.power(average: power))}- if let energy = stats.packageEnergy {+ if let energy = stats.totalEnergy {metricRow(label: "Energy:", value: ReplyStatsFormat.energy(energy))}- if let energy = stats.packageEnergy, let tokens = stats.tokensCount, tokens > 0 {+ if let energy = stats.totalEnergy, let tokens = stats.tokensCount, tokens > 0 {metricRow(label: "Energy / token:", value: ReplyStatsFormat.energyPerToken(joules: energy, tokens: tokens))}metricRow(label: "Total time:", value: String(format: "%.3f s", stats.totalTime))diff --git a/bindings/python/uzu/__init__.pyi b/bindings/python/uzu/__init__.pyiindex a3ef47072..24b6f4b3c 100644--- a/bindings/python/uzu/__init__.pyi+++ b/bindings/python/uzu/__init__.pyi@@ -334,20 +334,14 @@ class ChatReplyPowerStats:@propertydef average_gpu_watts(self) -> builtins.float: ...@property- def average_gpu_sram_watts(self) -> builtins.float: ...- @propertydef average_ane_watts(self) -> builtins.float: ...@propertydef average_ram_watts(self) -> builtins.float: ...@propertydef average_total_watts(self) -> builtins.float: ...@property- def average_package_watts(self) -> builtins.float: ...- @property- def max_package_watts(self) -> builtins.float: ...- @propertydef energy_joules(self) -> builtins.float: ...- def __new__(cls, samples_count: builtins.int, average_cpu_watts: builtins.float, average_gpu_watts: builtins.float, average_gpu_sram_watts: builtins.float, average_ane_watts: builtins.float, average_ram_watts: builtins.float, average_total_watts: builtins.float, average_package_watts: builtins.float, max_package_watts: builtins.float, energy_joules: builtins.float) -> ChatReplyPowerStats: ...+ def __new__(cls, samples_count: builtins.int, average_cpu_watts: builtins.float, average_gpu_watts: builtins.float, average_ane_watts: builtins.float, average_ram_watts: builtins.float, average_total_watts: builtins.float, energy_joules: builtins.float) -> ChatReplyPowerStats: ...@typing.finalclass ChatReplyStats:diff --git a/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift b/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swiftindex 723590c83..1a9c9d07a 100644--- a/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift+++ b/bindings/swift/Sources/Uzu/Generated/uzu/shoji.swift@@ -1173,26 +1173,20 @@ public struct ChatReplyPowerStats: Equatable, Hashable, Codable {public var samplesCount: Int64public var averageCpuWatts: Doublepublic var averageGpuWatts: Double- public var averageGpuSramWatts: Doublepublic var averageAneWatts: Doublepublic var averageRamWatts: Doublepublic var averageTotalWatts: Double- public var averagePackageWatts: Double- public var maxPackageWatts: Doublepublic var energyJoules: Double// Default memberwise initializers are never public by default, so we// declare one manually.- public init(samplesCount: Int64, averageCpuWatts: Double, averageGpuWatts: Double, averageGpuSramWatts: Double, averageAneWatts: Double, averageRamWatts: Double, averageTotalWatts: Double, averagePackageWatts: Double, maxPackageWatts: Double, energyJoules: Double) {+ public init(samplesCount: Int64, averageCpuWatts: Double, averageGpuWatts: Double, averageAneWatts: Double, averageRamWatts: Double, averageTotalWatts: Double, energyJoules: Double) {self.samplesCount = samplesCountself.averageCpuWatts = averageCpuWattsself.averageGpuWatts = averageGpuWatts- self.averageGpuSramWatts = averageGpuSramWattsself.averageAneWatts = averageAneWattsself.averageRamWatts = averageRamWattsself.averageTotalWatts = averageTotalWatts- self.averagePackageWatts = averagePackageWatts- self.maxPackageWatts = maxPackageWattsself.energyJoules = energyJoules}@@ -1215,12 +1209,9 @@ public struct FfiConverterTypeChatReplyPowerStats: FfiConverterRustBuffer {samplesCount: FfiConverterInt64.read(from: &buf),averageCpuWatts: FfiConverterDouble.read(from: &buf),averageGpuWatts: FfiConverterDouble.read(from: &buf),- averageGpuSramWatts: FfiConverterDouble.read(from: &buf),averageAneWatts: FfiConverterDouble.read(from: &buf),averageRamWatts: FfiConverterDouble.read(from: &buf),averageTotalWatts: FfiConverterDouble.read(from: &buf),- averagePackageWatts: FfiConverterDouble.read(from: &buf),- maxPackageWatts: FfiConverterDouble.read(from: &buf),energyJoules: FfiConverterDouble.read(from: &buf))}@@ -1229,12 +1220,9 @@ public struct FfiConverterTypeChatReplyPowerStats: FfiConverterRustBuffer {FfiConverterInt64.write(value.samplesCount, into: &buf)FfiConverterDouble.write(value.averageCpuWatts, into: &buf)FfiConverterDouble.write(value.averageGpuWatts, into: &buf)- FfiConverterDouble.write(value.averageGpuSramWatts, into: &buf)FfiConverterDouble.write(value.averageAneWatts, into: &buf)FfiConverterDouble.write(value.averageRamWatts, into: &buf)FfiConverterDouble.write(value.averageTotalWatts, into: &buf)- FfiConverterDouble.write(value.averagePackageWatts, into: &buf)- FfiConverterDouble.write(value.maxPackageWatts, into: &buf)FfiConverterDouble.write(value.energyJoules, into: &buf)}}diff --git a/bindings/typescript/src/napi/index.d.mts b/bindings/typescript/src/napi/index.d.mtsindex b64ba37ea..4f0b60720 100644--- a/bindings/typescript/src/napi/index.d.mts+++ b/bindings/typescript/src/napi/index.d.mts@@ -270,14 +270,11 @@ export declare class ChatReplyPowerStats {samplesCount: numberaverageCpuWatts: numberaverageGpuWatts: number- averageGpuSramWatts: numberaverageAneWatts: numberaverageRamWatts: numberaverageTotalWatts: number- averagePackageWatts: number- maxPackageWatts: numberenergyJoules: number- constructor(samplesCount: number, averageCpuWatts: number, averageGpuWatts: number, averageGpuSramWatts: number, averageAneWatts: number, averageRamWatts: number, averageTotalWatts: number, averagePackageWatts: number, maxPackageWatts: number, energyJoules: number)+ constructor(samplesCount: number, averageCpuWatts: number, averageGpuWatts: number, averageAneWatts: number, averageRamWatts: number, averageTotalWatts: number, energyJoules: number)}export declare class ChatReplyStats {diff --git a/bindings/typescript/src/napi/index.d.ts b/bindings/typescript/src/napi/index.d.tsindex b64ba37ea..4f0b60720 100644--- a/bindings/typescript/src/napi/index.d.ts+++ b/bindings/typescript/src/napi/index.d.ts@@ -270,14 +270,11 @@ export declare class ChatReplyPowerStats {samplesCount: numberaverageCpuWatts: numberaverageGpuWatts: number- averageGpuSramWatts: numberaverageAneWatts: numberaverageRamWatts: numberaverageTotalWatts: number- averagePackageWatts: number- maxPackageWatts: numberenergyJoules: number- constructor(samplesCount: number, averageCpuWatts: number, averageGpuWatts: number, averageGpuSramWatts: number, averageAneWatts: number, averageRamWatts: number, averageTotalWatts: number, averagePackageWatts: number, maxPackageWatts: number, energyJoules: number)+ constructor(samplesCount: number, averageCpuWatts: number, averageGpuWatts: number, averageAneWatts: number, averageRamWatts: number, averageTotalWatts: number, energyJoules: number)}export declare class ChatReplyStats {diff --git a/crates/backend-uzu/Cargo.toml b/crates/backend-uzu/Cargo.tomlindex 398f9f575..9835c8502 100644--- a/crates/backend-uzu/Cargo.toml+++ b/crates/backend-uzu/Cargo.toml@@ -49,8 +49,6 @@ objc2-foundation = { workspace = true, optional = true }bytesize = { workspace = true, optional = true }metal = { workspace = true, optional = true }obfstr = { workspace = true, optional = true }-# Power telemetry: macOS reads SoC IOReport; iOS reports HID charger "wall" power.-keisoku.workspace = true[dev-dependencies]test-tag.workspace = truediff --git a/crates/kanka/src/lib.rs b/crates/kanka/src/lib.rsindex 958904b69..fc8c3be80 100644--- a/crates/kanka/src/lib.rs+++ b/crates/kanka/src/lib.rs@@ -27,7 +27,14 @@ macro_rules! ffi_table {if handle.is_null() {return ::core::option::Option::None;}- ::core::option::Option::Some(Self {+ struct CloseOnDrop(*mut ::core::ffi::c_void);+ impl ::core::ops::Drop for CloseOnDrop {+ fn drop(&mut self) {+ unsafe { $crate::libc::dlclose(self.0); }+ }+ }+ let guard = CloseOnDrop(handle);+ let table = Self {$($field: {let name = ::std::ffi::CString::new($crate::obfstr::obfstr!($symbol)).ok()?;let symbol = unsafe { $crate::libc::dlsym(handle, name.as_ptr()) };@@ -38,7 +45,9 @@ macro_rules! ffi_table {::core::mem::transmute::<*mut ::core::ffi::c_void, $signature>(symbol)}},)*- })+ };+ ::core::mem::forget(guard);+ ::core::option::Option::Some(table)}fn get() -> ::core::option::Option<&'static Self> {diff --git a/crates/kanshi/Cargo.toml b/crates/kanshi/Cargo.tomldeleted file mode 100644index 9b11197ff..000000000--- a/crates/kanshi/Cargo.toml+++ /dev/null@@ -1,24 +0,0 @@-[package]-name = "kanshi"-edition.workspace = true-rust-version.workspace = true-version.workspace = true-authors.workspace = true-homepage.workspace = true-repository.workspace = true-license.workspace = true-description = "mactop-style live system monitor built on keisoku"-readme = "README.md"--[[bin]]-name = "kanshi"-path = "src/main.rs"--[lints]-workspace = true--[dependencies]-keisoku.workspace = true-crossterm.workspace = true-ratatui.workspace = true-sysinfo.workspace = truediff --git a/crates/kanshi/README.md b/crates/kanshi/README.mddeleted file mode 100644index 32ea8dbce..000000000--- a/crates/kanshi/README.md+++ /dev/null@@ -1,24 +0,0 @@-# kanshi--A live terminal system monitor (mactop/asitop-style) built on [`keisoku`](../keisoku).-It samples the SoC on a background thread and renders it in a `ratatui` TUI.--## Run--```bash-cargo run -p kanshi --release-```--Press `q` (or `Ctrl-C`) to quit.--## Shows--- CPU/GPU/ANE power (Watts) and usage, with history charts-- Frequencies, memory and DRAM bandwidth, temperatures-- Top processes, network and disk activity (via `sysinfo`)-- Device summary (chip, GPU cores, RAM)--## Platform--Full power/SoC telemetry is Apple Silicon (macOS) only — that's where keisoku's counters-exist. On other platforms it still runs but power/GPU panels are empty.diff --git a/crates/kanshi/src/chart.rs b/crates/kanshi/src/chart.rsdeleted file mode 100644index cbad6d214..000000000--- a/crates/kanshi/src/chart.rs+++ /dev/null@@ -1,80 +0,0 @@-use std::collections::VecDeque;--use ratatui::{Frame, layout::Rect};--use crate::{- state::{accent, background},- widgets::panel_owned,-};--const BRAILLE_DOTS: [[u16; 4]; 2] = [[0x01, 0x02, 0x04, 0x40], [0x08, 0x10, 0x20, 0x80]];--pub(crate) fn render_chart(- frame: &mut Frame,- area: Rect,- title: String,- history: &VecDeque<f64>,- ceiling: f64,-) {- let block = panel_owned(title);- let inner = block.inner(area);- frame.render_widget(block, area);- if inner.width == 0 || inner.height == 0 {- return;- }-- let columns = inner.width as usize;- let shown: Vec<f64> = history.iter().rev().take(columns).rev().copied().collect();- if shown.is_empty() {- return;- }- let offset = columns - shown.len();- let ceiling = ceiling.max(1e-9);- let cell_rows = inner.height as usize;- let sub_rows = cell_rows * 4;- let last = shown.len() - 1;- let color = accent();- let background = background();-- let fill_at = |sub_x: usize| -> Option<usize> {- let position = sub_x as f64 / 2.0 - offset as f64;- if position < 0.0 {- return None;- }- let low = (position.floor() as usize).min(last);- let high = (low + 1).min(last);- let blend = position - low as f64;- let value = shown[low] * (1.0 - blend) + shown[high] * blend;- Some(((value / ceiling).clamp(0.0, 1.0) * sub_rows as f64).round() as usize)- };-- let buffer = frame.buffer_mut();- for cell_x in 0..columns {- let fills = [fill_at(cell_x * 2), fill_at(cell_x * 2 + 1)];- if fills.iter().all(Option::is_none) {- continue;- }- let x = inner.left() + cell_x as u16;- for row in 0..cell_rows {- let mut dots = 0u16;- for (sub, fill) in fills.iter().enumerate() {- let Some(fill) = fill else {- continue;- };- for internal in 0..4 {- if row * 4 + (3 - internal) < *fill {- dots |= BRAILLE_DOTS[sub][internal];- }- }- }- if dots == 0 {- continue;- }- let symbol = char::from_u32(0x2800 + dots as u32).unwrap_or(' ');- let y = inner.bottom() - 1 - row as u16;- if let Some(cell) = buffer.cell_mut((x, y)) {- cell.set_char(symbol).set_fg(color).set_bg(background);- }- }- }-}diff --git a/crates/kanshi/src/disk_row.rs b/crates/kanshi/src/disk_row.rsdeleted file mode 100644index ee1fa3b12..000000000--- a/crates/kanshi/src/disk_row.rs+++ /dev/null@@ -1,5 +0,0 @@-pub(crate) struct DiskRow {- pub(crate) name: String,- pub(crate) used: u64,- pub(crate) total: u64,-}diff --git a/crates/kanshi/src/format.rs b/crates/kanshi/src/format.rsdeleted file mode 100644index 89d319d28..000000000--- a/crates/kanshi/src/format.rs+++ /dev/null@@ -1,35 +0,0 @@-use keisoku::BatteryMetrics;--pub(crate) fn battery_status(battery: &BatteryMetrics) -> &'static str {- if battery.charging {- "charging"- } else if battery.on_ac_power {- "AC"- } else {- "battery"- }-}--pub(crate) fn human_bytes(bytes: u64) -> String {- const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];- let mut value = bytes as f64;- let mut unit = 0;- while value >= 1024.0 && unit < UNITS.len() - 1 {- value /= 1024.0;- unit += 1;- }- if unit == 0 {- format!("{bytes} B")- } else {- format!("{value:.1} {}", UNITS[unit])- }-}--pub(crate) fn format_uptime(seconds: u64) -> String {- let (hours, minutes) = (seconds / 3600, (seconds % 3600) / 60);- if hours > 0 {- format!("{hours}h {minutes}m")- } else {- format!("{minutes}m")- }-}diff --git a/crates/kanshi/src/host_info.rs b/crates/kanshi/src/host_info.rsdeleted file mode 100644index 33a6a1f5c..000000000--- a/crates/kanshi/src/host_info.rs+++ /dev/null@@ -1,7 +0,0 @@-pub(crate) struct HostInfo {- pub(crate) user: String,- pub(crate) hostname: String,- pub(crate) os: String,- pub(crate) kernel: String,- pub(crate) shell: String,-}diff --git a/crates/kanshi/src/info.rs b/crates/kanshi/src/info.rsdeleted file mode 100644index db8fff5e5..000000000--- a/crates/kanshi/src/info.rs+++ /dev/null@@ -1,170 +0,0 @@-use ratatui::{- Frame,- layout::{Constraint, Rect},- style::{Modifier, Style},- text::{Line, Span},- widgets::Paragraph,-};--use crate::{- format::{battery_status, format_uptime, human_bytes},- state::accent,- telemetry::Telemetry,- widgets::split_horizontal,-};--const APPLE_ART: [&str; 17] = [- " 'c. ",- " ,xNMM. ",- " .OMMMMo ",- " OMMM0, ",- " .;loddo:' loolloddol;. ",- " cKMMMMMMMMMMNWMMMMMMMMMM0: ",- " .KMMMMMMMMMMMMMMMMMMMMMMMWd. ",- " XMMMMMMMMMMMMMMMMMMMMMMMX. ",- ";MMMMMMMMMMMMMMMMMMMMMMMM: ",- ":MMMMMMMMMMMMMMMMMMMMMMMM: ",- ".MMMMMMMMMMMMMMMMMMMMMMMMX. ",- " kMMMMMMMMMMMMMMMMMMMMMMMMWd. ",- " .XMMMMMMMMMMMMMMMMMMMMMMMMMMk ",- " .XMMMMMMMMMMMMMMMMMMMMMMMMK. ",- " kMMMMMMMMMMMMMMMMMMMMMMd ",- " ;KMMMMMMMWXXWMMMMMMMk. ",- " .cooc,. .,coo:. ",-];--pub(crate) fn render_info(- frame: &mut Frame,- area: Rect,- state: &Telemetry,-) {- let art_width = APPLE_ART.iter().map(|line| line.chars().count()).max().unwrap_or(0) as u16 + 2;- let columns = split_horizontal(area, [Constraint::Length(art_width), Constraint::Min(0)]);-- let art: Vec<Line> = APPLE_ART.iter().map(|line| Line::from(*line)).collect();- frame.render_widget(Paragraph::new(art).style(Style::default().fg(accent())), columns[0]);- frame.render_widget(Paragraph::new(build_info_lines(state)).style(Style::default().fg(accent())), columns[1]);-}--fn info_line(- label: &str,- value: String,-) -> Line<'static> {- Line::from(vec![- Span::styled(format!("{label:<11}"), Style::default().fg(accent()).add_modifier(Modifier::BOLD)),- Span::raw(value),- ])-}--fn build_info_lines(state: &Telemetry) -> Vec<Line<'static>> {- let snapshot = state.snapshot.as_ref();- let mut lines = Vec::new();-- if let Some(host) = &state.host {- lines.push(Line::from(Span::styled(- format!("{}@{}", host.user, host.hostname),- Style::default().fg(accent()).add_modifier(Modifier::BOLD),- )));- lines.push(Line::from("-".repeat(25)));- lines.push(info_line("OS", host.os.clone()));- if let Some(device) = &state.device {- lines.push(info_line("Host", device.chip.clone()));- }- lines.push(info_line("Kernel", host.kernel.clone()));- lines.push(info_line("Uptime", format_uptime(state.uptime_seconds)));- lines.push(info_line("Shell", host.shell.clone()));- }- if let Some(device) = &state.device {- lines.push(info_line(- "CPU",- format!("{} ({}E+{}P)", device.chip, device.efficiency_cores, device.performance_cores),- ));- lines.push(info_line("GPU", format!("{} Cores", device.gpu_cores)));- }- if let Some(memory) = snapshot.and_then(|s| s.memory.as_ref()) {- lines.push(info_line(- "Memory",- format!(- "{:.2} GB / {:.2} GB",- memory.ram_usage.value() as f64 / 1e9,- memory.ram_total.value() as f64 / 1e9- ),- ));- lines.push(info_line(- "Swap",- format!(- "{:.2} GB / {:.2} GB",- memory.swap_usage.value() as f64 / 1e9,- memory.swap_total.value() as f64 / 1e9- ),- ));- }-- lines.push(Line::from(""));- if let Some(cpu) = snapshot.and_then(|s| s.cpu.as_ref()) {- lines.push(info_line("CPU Usage", format!("{:.2}%", cpu.usage.value())));- }- if let Some(gpu) = snapshot.and_then(|s| s.gpu.as_ref()) {- lines.push(info_line("GPU Usage", format!("{:.0}%", gpu.usage.value())));- }- if let Some(ane) = snapshot.and_then(|s| s.neural_engine.as_ref()) {- lines.push(info_line("ANE Usage", format!("{:.0}%", ane.active.value())));- }- if let Some(power) = snapshot.and_then(|s| s.power.as_ref()) {- lines.push(info_line("Power", format!("{:.2} W (max {:.2} W)", power.package.value(), state.max_power)));- }- if let Some(temperatures) = snapshot.and_then(|s| s.temperatures.as_ref()) {- let mut parts = Vec::new();- if let Some(cpu) = temperatures.cpu_average {- parts.push(format!("CPU {:.0}°C", cpu.value()));- }- if let Some(gpu) = temperatures.gpu_average {- parts.push(format!("GPU {:.0}°C", gpu.value()));- }- if !parts.is_empty() {- lines.push(info_line("Thermals", parts.join(" ")));- }- }- lines.push(info_line(- "Network",- format!("↑ {}/s ↓ {}/s", human_bytes(state.network_up as u64), human_bytes(state.network_down as u64)),- ));- lines.push(info_line(- "Disk",- format!("R {}/s W {}/s", human_bytes(state.disk_read as u64), human_bytes(state.disk_written as u64)),- ));- if let Some(bandwidth) = snapshot.and_then(|s| s.bandwidth.as_ref()) {- lines.push(info_line(- "DRAM BW",- format!(- "R {:.1} W {:.1} ({:.1}) GB/s",- bandwidth.dram_read.value(),- bandwidth.dram_write.value(),- bandwidth.dram_read.value() + bandwidth.dram_write.value(),- ),- ));- }- if let Some(battery) = snapshot.and_then(|s| s.battery.as_ref()).filter(|battery| battery.present) {- let status = battery_status(battery);- lines.push(info_line("Battery", format!("{:.0}% ({status})", battery.percent.value())));- }-- if let Some(fans) = snapshot.and_then(|s| s.fans.as_ref()).filter(|fans| !fans.fans.is_empty()) {- lines.push(Line::from(""));- for (index, fan) in fans.fans.iter().enumerate() {- lines.push(info_line(- &format!("Fan {}", index + 1),- format!("{:.0} rpm ({:.0}–{:.0})", fan.actual.value(), fan.minimum.value(), fan.maximum.value()),- ));- }- }-- if !state.disks.is_empty() {- lines.push(Line::from("-".repeat(25)));- for disk in &state.disks {- lines.push(info_line(&disk.name, format!("{} / {}", human_bytes(disk.used), human_bytes(disk.total))));- }- }-- lines-}diff --git a/crates/kanshi/src/main.rs b/crates/kanshi/src/main.rsdeleted file mode 100644index 6e8fe9768..000000000--- a/crates/kanshi/src/main.rs+++ /dev/null@@ -1,145 +0,0 @@-mod chart;-mod disk_row;-mod format;-mod host_info;-mod info;-mod net_interface;-mod panels;-mod process_row;-mod sampler;-mod state;-mod telemetry;-mod widgets;--use std::{- io::{self, IsTerminal},- sync::{- Arc, Mutex,- atomic::{AtomicBool, Ordering},- },- time::Duration,-};--use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};-use keisoku::Collector;-use ratatui::DefaultTerminal;--use crate::{- panels::draw,- sampler::sample_loop,- state::{cycle_theme, data_version, slow_down, speed_up, toggle_background, toggle_info},- telemetry::Telemetry,-};--fn main() -> io::Result<()> {- if std::env::args().any(|arg| arg == "--once") || !io::stdout().is_terminal() {- return print_once();- }-- let telemetry = Arc::new(Mutex::new(Telemetry::default()));- let stop = Arc::new(AtomicBool::new(false));-- let sampler = {- let telemetry = Arc::clone(&telemetry);- let stop = Arc::clone(&stop);- std::thread::spawn(move || sample_loop(&telemetry, &stop))- };-- let mut terminal = ratatui::init();- let result = run(&mut terminal, &telemetry);- ratatui::restore();-- stop.store(true, Ordering::Relaxed);- let _ = sampler.join();- result-}--fn print_once() -> io::Result<()> {- let mut collector = Collector::new();- let device = collector.device();- let snapshot = collector.sample(Duration::from_millis(300));- let flag = |present: bool| {- if present {- "yes"- } else {- "--"- }- };-- println!("kanshi — available telemetry");- println!(- "device {} {}E+{}P {} GPU {:.1} GB",- device.chip,- device.efficiency_cores,- device.performance_cores,- device.gpu_cores,- device.ram_total.value() as f64 / 1e9,- );- println!("cpu {}", flag(snapshot.cpu.is_some()));- println!("gpu {}", flag(snapshot.gpu.is_some()));- println!("neural {}", flag(snapshot.neural_engine.is_some()));- println!("power {}", flag(snapshot.power.is_some()));- println!("bandwidth {}", flag(snapshot.bandwidth.is_some()));- println!("memory {}", flag(snapshot.memory.is_some()));- println!("fans {}", flag(snapshot.fans.is_some()));- println!("battery {}", flag(snapshot.battery.is_some()));- println!("temps {}", flag(snapshot.temperatures.is_some()));- println!("sensors {}", snapshot.sensors.len());-- if let Some(memory) = &snapshot.memory {- println!(- " ram {:.2} / {:.2} GB",- memory.ram_usage.value() as f64 / 1e9,- memory.ram_total.value() as f64 / 1e9,- );- }- if let Some(temperatures) = &snapshot.temperatures {- if let Some(cpu) = temperatures.cpu_average {- println!(" cpu temp {:.1}°C", cpu.value());- }- if let Some(gpu) = temperatures.gpu_average {- println!(" gpu temp {:.1}°C", gpu.value());- }- }- for sensor in snapshot.sensors.iter().take(24) {- println!(" {:<26} {:>8.2} [{}]", sensor.name, sensor.value, sensor.component);- }- Ok(())-}--fn run(- terminal: &mut DefaultTerminal,- telemetry: &Arc<Mutex<Telemetry>>,-) -> io::Result<()> {- let mut shown_version = u64::MAX;- let mut redraw = true;- loop {- let version = data_version();- if redraw || version != shown_version {- shown_version = version;- redraw = false;- let state = telemetry.lock().unwrap_or_else(|poisoned| poisoned.into_inner());- terminal.draw(|frame| draw(frame, &state))?;- }- if event::poll(Duration::from_millis(200))? {- match event::read()? {- Event::Key(key) if key.kind == KeyEventKind::Press => {- let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);- match key.code {- KeyCode::Char('q') | KeyCode::Esc => return Ok(()),- KeyCode::Char('c') if ctrl => return Ok(()),- KeyCode::Char('c') => cycle_theme(),- KeyCode::Char('b') => toggle_background(),- KeyCode::Char('i') => toggle_info(),- KeyCode::Char('+') | KeyCode::Char('=') => speed_up(),- KeyCode::Char('-') | KeyCode::Char('_') => slow_down(),- _ => {},- }- redraw = true;- },- Event::Resize(_, _) => redraw = true,- _ => {},- }- }- }-}diff --git a/crates/kanshi/src/net_interface.rs b/crates/kanshi/src/net_interface.rsdeleted file mode 100644index 7474eaca0..000000000--- a/crates/kanshi/src/net_interface.rs+++ /dev/null@@ -1,5 +0,0 @@-pub(crate) struct NetInterface {- pub(crate) name: String,- pub(crate) down: f64,- pub(crate) up: f64,-}diff --git a/crates/kanshi/src/panels.rs b/crates/kanshi/src/panels.rsdeleted file mode 100644index 29f3d784a..000000000--- a/crates/kanshi/src/panels.rs+++ /dev/null@@ -1,303 +0,0 @@-use keisoku::Device;-use ratatui::{- Frame,- layout::{Constraint, Direction, Layout, Rect},- style::Style,- text::Line,- widgets::{Block, BorderType, Borders, List, ListItem, Paragraph},-};--use crate::{- chart::render_chart,- format::{battery_status, format_uptime, human_bytes},- info::render_info,- state::{accent, background, interval_ms, show_info, theme},- telemetry::Telemetry,- widgets::{panel, split_horizontal, split_vertical},-};--pub(crate) fn draw(- frame: &mut Frame,- state: &Telemetry,-) {- let outer = Block::default()- .borders(Borders::ALL)- .border_type(BorderType::Rounded)- .style(Style::default().bg(background()))- .border_style(Style::default().fg(accent()))- .title_style(Style::default().fg(accent()))- .title_top(Line::from(header_title(state.device.as_ref())))- .title_top(Line::from(format!(" {} ", env!("CARGO_PKG_VERSION"))).right_aligned())- .title_bottom(Line::from(format!(" {} ", theme().0)))- .title_bottom(Line::from(" Info: i · Color: c · BG: b · Exit: q ").centered())- .title_bottom(Line::from(format!(" -/+ {}ms ", interval_ms())).right_aligned());- let area = outer.inner(frame.area());- frame.render_widget(outer, frame.area());-- if show_info() {- render_info(frame, area, state);- return;- }-- let rows = Layout::default()- .direction(Direction::Vertical)- .constraints([Constraint::Percentage(25), Constraint::Percentage(50), Constraint::Percentage(25)])- .split(area);-- let top = split_horizontal(rows[0], [Constraint::Percentage(50), Constraint::Percentage(50)]);- render_chart(frame, top[0], cpu_title(state), &state.cpu_history, 100.0);- render_chart(frame, top[1], gpu_title(state), &state.gpu_history, 100.0);-- let middle = split_horizontal(rows[1], [Constraint::Percentage(50), Constraint::Percentage(50)]);-- let left = split_vertical(middle[0], [Constraint::Percentage(50), Constraint::Percentage(50)]);- render_chart(frame, left[0], ane_title(state), &state.ane_history, 100.0);- let left_bottom = split_horizontal(left[1], [Constraint::Percentage(50), Constraint::Percentage(50)]);- render_power(frame, left_bottom[0], state);- render_chart(frame, left_bottom[1], power_title(state), &state.power_history, state.max_power);-- let right = split_vertical(middle[1], [Constraint::Percentage(50), Constraint::Percentage(50)]);- render_chart(frame, right[0], memory_title(state), &state.memory_history, 100.0);- let right_bottom = split_horizontal(right[1], [Constraint::Percentage(50), Constraint::Percentage(50)]);- render_model(frame, right_bottom[0], state);- render_fans(frame, right_bottom[1], state);-- let bottom = split_horizontal(- rows[2],- [- Constraint::Percentage(40),- Constraint::Percentage(20),- Constraint::Percentage(20),- Constraint::Percentage(20),- ],- );- render_processes(frame, bottom[0], state);- render_io(frame, bottom[1], state);- render_disk(frame, bottom[2], state);- render_network(frame, bottom[3], state);-}--fn cpu_title(state: &Telemetry) -> String {- let cpu = state.snapshot.as_ref().and_then(|s| s.cpu.as_ref());- let temperature =- state.snapshot.as_ref().and_then(|s| s.temperatures.as_ref()).and_then(|t| t.cpu_average).map(|c| c.value());- match (cpu, state.device.as_ref()) {- (Some(cpu), Some(device)) => format!(- "{} Cores ({}E/{}P) {:.2}% @ E{:.1}/P{:.1} GHz ({:.0}°C)",- device.efficiency_cores + device.performance_cores,- device.efficiency_cores,- device.performance_cores,- cpu.usage.value(),- cpu.ecpu_frequency.value() as f64 / 1000.0,- cpu.pcpu_frequency.value() as f64 / 1000.0,- temperature.unwrap_or(0.0),- ),- _ => "CPU Usage".to_string(),- }-}--fn gpu_title(state: &Telemetry) -> String {- let temperature =- state.snapshot.as_ref().and_then(|s| s.temperatures.as_ref()).and_then(|t| t.gpu_average).map(|c| c.value());- match state.snapshot.as_ref().and_then(|s| s.gpu.as_ref()) {- Some(gpu) => format!(- "GPU Usage: {:.0}% @ {} MHz ({:.0}°C)",- gpu.usage.value(),- gpu.frequency.value(),- temperature.unwrap_or(0.0),- ),- None => "GPU Usage".to_string(),- }-}--fn ane_title(state: &Telemetry) -> String {- match state.snapshot.as_ref().and_then(|s| s.neural_engine.as_ref()) {- Some(ane) => format!("ANE Usage: {:.2}% @ {:.2} W", ane.active.value(), ane.power.value()),- None => "ANE Usage".to_string(),- }-}--fn memory_title(state: &Telemetry) -> String {- let bandwidth = state- .snapshot- .as_ref()- .and_then(|s| s.bandwidth.as_ref())- .map(|b| b.dram_read.value() + b.dram_write.value())- .unwrap_or(0.0);- match state.snapshot.as_ref().and_then(|s| s.memory.as_ref()) {- Some(memory) => format!(- "Mem: {:.2} GB / {:.2} GB (Swap: {:.2}/{:.2} GB) BW: {:.1} GB/s",- memory.ram_usage.value() as f64 / 1e9,- memory.ram_total.value() as f64 / 1e9,- memory.swap_usage.value() as f64 / 1e9,- memory.swap_total.value() as f64 / 1e9,- bandwidth,- ),- None => "Memory Usage".to_string(),- }-}--fn power_title(state: &Telemetry) -> String {- let current = state.power_history.back().copied().unwrap_or(0.0);- format!("{current:.2} W Total (Max: {:.2} W)", state.max_power)-}--fn render_power(- frame: &mut Frame,- area: Rect,- state: &Telemetry,-) {- let mut lines = Vec::new();- if let Some(power) = state.snapshot.as_ref().and_then(|s| s.power.as_ref()) {- lines.push(Line::from(format!(- "{:<6}{:>6.2} W | {:<5}{:>6.2} W",- "CPU:",- power.cpu.value(),- "GPU:",- power.gpu.value() + power.gpu_sram.value(),- )));- lines.push(Line::from(format!(- "{:<6}{:>6.2} W | {:<5}{:>6.2} W",- "ANE:",- power.ane.value(),- "DRAM:",- power.ram.value(),- )));- lines.push(Line::from(format!("{:<6}{:>6.2} W", "Total:", power.total.value())));- lines.push(Line::from(format!("{:<6}{:>6.2} W", "Pkg:", power.package.value())));- }- let thermals =- state.snapshot.as_ref().and_then(|s| s.thermal_pressure).map(|t| format!("{t:?}")).unwrap_or_default();- lines.push(Line::from(format!("Thermals: {thermals}")));- lines.push(Line::from(format!("Uptime: {}", format_uptime(state.uptime_seconds))));- if let Some(battery) = state.snapshot.as_ref().and_then(|s| s.battery.as_ref()).filter(|b| b.present) {- let status = battery_status(battery);- lines.push(Line::from(format!("Battery: {:.0}% ({status})", battery.percent.value())));- }- frame.render_widget(Paragraph::new(lines).style(Style::default().fg(accent())).block(panel("Power Usage")), area);-}--fn render_model(- frame: &mut Frame,- area: Rect,- state: &Telemetry,-) {- let mut lines = Vec::new();- if let Some(device) = &state.device {- lines.push(Line::from(device.chip.clone()));- lines.push(Line::from(format!("{} Cores", device.efficiency_cores + device.performance_cores)));- lines.push(Line::from(format!("{} E-Cores", device.efficiency_cores)));- lines.push(Line::from(format!("{} P-Cores", device.performance_cores)));- lines.push(Line::from(format!("{} GPU Cores", device.gpu_cores)));- }- frame.render_widget(Paragraph::new(lines).style(Style::default().fg(accent())).block(panel("Apple Silicon")), area);-}--fn render_fans(- frame: &mut Frame,- area: Rect,- state: &Telemetry,-) {- let mut lines = Vec::new();- if let Some(fans) = state.snapshot.as_ref().and_then(|s| s.fans.as_ref()) {- for (index, fan) in fans.fans.iter().enumerate() {- lines.push(Line::from(format!("Fan {}: {:.0} rpm", index + 1, fan.actual.value())));- lines.push(Line::from(format!(- " range {:.0}–{:.0} · target {:.0}",- fan.minimum.value(),- fan.maximum.value(),- fan.target.value(),- )));- }- }- if lines.is_empty() {- lines.push(Line::from("no fans"));- }- frame.render_widget(Paragraph::new(lines).style(Style::default().fg(accent())).block(panel("Fans")), area);-}--fn render_io(- frame: &mut Frame,- area: Rect,- state: &Telemetry,-) {- let lines = vec![- Line::from(format!("R {}/s", human_bytes(state.disk_read as u64))),- Line::from(format!("W {}/s", human_bytes(state.disk_written as u64))),- ];- frame.render_widget(Paragraph::new(lines).style(Style::default().fg(accent())).block(panel("IO")), area);-}--fn render_disk(- frame: &mut Frame,- area: Rect,- state: &Telemetry,-) {- let lines: Vec<Line> = state- .disks- .iter()- .map(|disk| Line::from(format!("{}: {} / {}", disk.name, human_bytes(disk.used), human_bytes(disk.total))))- .collect();- frame.render_widget(Paragraph::new(lines).style(Style::default().fg(accent())).block(panel("Disk")), area);-}--fn render_network(- frame: &mut Frame,- area: Rect,- state: &Telemetry,-) {- let mut lines = vec![- Line::from(format!(- "{:<6}↑ {}/s ↓ {}/s",- "Rate",- human_bytes(state.network_up as u64),- human_bytes(state.network_down as u64),- )),- Line::from(format!("{:<6}↑ {:.0}/s ↓ {:.0}/s", "Pkts", state.network_packets_up, state.network_packets_down,)),- Line::from(format!(- "{:<6}↑ {} ↓ {}",- "Total",- human_bytes(state.network_total_up),- human_bytes(state.network_total_down),- )),- ];- for iface in &state.network_interfaces {- lines.push(Line::from(format!(- "{:<6}↑ {}/s ↓ {}/s",- iface.name,- human_bytes(iface.up as u64),- human_bytes(iface.down as u64),- )));- }- frame.render_widget(Paragraph::new(lines).style(Style::default().fg(accent())).block(panel("Network")), area);-}--fn render_processes(- frame: &mut Frame,- area: Rect,- state: &Telemetry,-) {- let items: Vec<ListItem> = state- .processes- .iter()- .map(|process| {- ListItem::new(format!("{:>6.1}% {:>9} {}", process.cpu, human_bytes(process.memory), process.name))- })- .collect();- frame.render_widget(List::new(items).style(Style::default().fg(accent())).block(panel("Process List")), area);-}--fn header_title(device: Option<&Device>) -> String {- match device {- Some(device) => format!(- " kanshi • {} • {}C ({}E+{}P) • {} GPU • {:.0} GB ",- device.chip,- device.efficiency_cores + device.performance_cores,- device.efficiency_cores,- device.performance_cores,- device.gpu_cores,- device.ram_total.value() as f64 / 1e9,- ),- None => " kanshi ".to_string(),- }-}diff --git a/crates/kanshi/src/process_row.rs b/crates/kanshi/src/process_row.rsdeleted file mode 100644index c8df27966..000000000--- a/crates/kanshi/src/process_row.rs+++ /dev/null@@ -1,5 +0,0 @@-pub(crate) struct ProcessRow {- pub(crate) cpu: f32,- pub(crate) memory: u64,- pub(crate) name: String,-}diff --git a/crates/kanshi/src/sampler.rs b/crates/kanshi/src/sampler.rsdeleted file mode 100644index b5b1c5d78..000000000--- a/crates/kanshi/src/sampler.rs+++ /dev/null@@ -1,174 +0,0 @@-use std::{- collections::{HashSet, VecDeque},- sync::{- Arc, Mutex,- atomic::{AtomicBool, Ordering},- },- time::{Duration, Instant},-};--use keisoku::Collector;-use sysinfo::{Disks, Networks, ProcessRefreshKind, ProcessesToUpdate, System};--use crate::{- disk_row::DiskRow,- host_info::HostInfo,- net_interface::NetInterface,- process_row::ProcessRow,- state::{bump_data_version, interval},- telemetry::Telemetry,-};--const HISTORY: usize = 256;-const PROCESS_ROWS: usize = 8;-const NETWORK_ROWS: usize = 4;-const DISK_REFRESH: Duration = Duration::from_secs(3);--pub(crate) fn sample_loop(- telemetry: &Arc<Mutex<Telemetry>>,- stop: &Arc<AtomicBool>,-) {- let mut collector = Collector::new();- let device = collector.device();- let host = HostInfo {- user: std::env::var("USER").unwrap_or_else(|_| "user".into()),- hostname: System::host_name().unwrap_or_default(),- os: System::long_os_version().unwrap_or_default(),- kernel: System::kernel_version().unwrap_or_default(),- shell: std::env::var("SHELL")- .ok()- .and_then(|path| path.rsplit('/').next().map(str::to_owned))- .unwrap_or_default(),- };- if let Ok(mut state) = telemetry.lock() {- state.device = Some(device);- state.host = Some(host);- }-- let mut system = System::new();- let mut networks = Networks::new_with_refreshed_list();- let mut all_disks = Disks::new_with_refreshed_list();- let mut last_disk_refresh: Option<Instant> = None;-- let process_kind = ProcessRefreshKind::nothing().with_cpu().with_memory().with_disk_usage();-- // Prime so the first sample's rates span the interval rather than reading- // each counter's whole since-boot total as if it accrued in one tick.- system.refresh_processes_specifics(ProcessesToUpdate::All, true, process_kind);- networks.refresh(true);- let mut last_refresh = Instant::now();-- while !stop.load(Ordering::Relaxed) {- let snapshot = collector.sample(interval());-- system.refresh_processes_specifics(ProcessesToUpdate::All, true, process_kind);- networks.refresh(true);- let elapsed = last_refresh.elapsed().as_secs_f64().max(0.001);- last_refresh = Instant::now();-- let (mut received, mut transmitted) = (0u64, 0u64);- let (mut packets_in, mut packets_out) = (0u64, 0u64);- let (mut total_in, mut total_out) = (0u64, 0u64);- let mut interfaces: Vec<NetInterface> = Vec::new();- for (name, data) in networks.iter() {- received += data.received();- transmitted += data.transmitted();- packets_in += data.packets_received();- packets_out += data.packets_transmitted();- total_in += data.total_received();- total_out += data.total_transmitted();-- if data.total_received() > 0 || data.total_transmitted() > 0 {- interfaces.push(NetInterface {- name: name.clone(),- down: data.received() as f64 / elapsed,- up: data.transmitted() as f64 / elapsed,- });- }- }- interfaces.sort_by(|a, b| (b.down + b.up).partial_cmp(&(a.down + a.up)).unwrap_or(std::cmp::Ordering::Equal));- interfaces.truncate(NETWORK_ROWS);-- let disks = last_disk_refresh.is_none_or(|at| at.elapsed() >= DISK_REFRESH).then(|| {- last_disk_refresh = Some(Instant::now());- all_disks.refresh(true);- let mut seen_disks = HashSet::new();- all_disks- .list()- .iter()- .filter(|disk| seen_disks.insert(disk.name().to_os_string()))- .map(|disk| DiskRow {- name: disk.name().to_string_lossy().into_owned(),- used: disk.total_space().saturating_sub(disk.available_space()),- total: disk.total_space(),- })- .collect::<Vec<_>>()- });-- let (mut disk_read, mut disk_written) = (0u64, 0u64);- for process in system.processes().values() {- let io = process.disk_usage();- disk_read += io.read_bytes;- disk_written += io.written_bytes;- }-- let mut processes = system- .processes()- .values()- .map(|process| ProcessRow {- cpu: process.cpu_usage(),- memory: process.memory(),- name: process.name().to_string_lossy().into_owned(),- })- .collect::<Vec<_>>();- processes.sort_by(|a, b| b.cpu.partial_cmp(&a.cpu).unwrap_or(std::cmp::Ordering::Equal));- processes.truncate(PROCESS_ROWS);-- let cpu = snapshot.cpu.as_ref().map(|c| c.usage.value() as f64).unwrap_or(0.0);- let gpu = snapshot.gpu.as_ref().map(|g| g.usage.value() as f64).unwrap_or(0.0);- let ane = snapshot.neural_engine.as_ref().map(|a| a.active.value() as f64).unwrap_or(0.0);- let memory = snapshot- .memory- .as_ref()- .filter(|m| m.ram_total.value() > 0)- .map(|m| m.ram_usage.value() as f64 / m.ram_total.value() as f64 * 100.0)- .unwrap_or(0.0);-- let power = snapshot.power.as_ref().map(|p| p.package.value() as f64).unwrap_or(0.0);-- if let Ok(mut state) = telemetry.lock() {- push_history(&mut state.cpu_history, cpu);- push_history(&mut state.gpu_history, gpu);- push_history(&mut state.ane_history, ane);- push_history(&mut state.memory_history, memory);- push_history(&mut state.power_history, power);- state.max_power = state.max_power.max(power);- state.snapshot = Some(snapshot);- state.uptime_seconds = System::uptime();- state.network_down = received as f64 / elapsed;- state.network_up = transmitted as f64 / elapsed;- state.network_packets_down = packets_in as f64 / elapsed;- state.network_packets_up = packets_out as f64 / elapsed;- state.network_total_down = total_in;- state.network_total_up = total_out;- state.network_interfaces = interfaces;- state.disk_read = disk_read as f64 / elapsed;- state.disk_written = disk_written as f64 / elapsed;- if let Some(disks) = disks {- state.disks = disks;- }- state.processes = processes;- }- bump_data_version();- }-}--fn push_history(- history: &mut VecDeque<f64>,- value: f64,-) {- history.push_back(value);- while history.len() > HISTORY {- history.pop_front();- }-}diff --git a/crates/kanshi/src/state.rs b/crates/kanshi/src/state.rsdeleted file mode 100644index 8a045de96..000000000--- a/crates/kanshi/src/state.rs+++ /dev/null@@ -1,88 +0,0 @@-use std::{- sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},- time::Duration,-};--use ratatui::style::Color;--const THEMES: [(&str, Color); 7] = [- ("green", Color::Green),- ("cyan", Color::Cyan),- ("blue", Color::Blue),- ("magenta", Color::Magenta),- ("yellow", Color::Yellow),- ("red", Color::Red),- ("white", Color::White),-];--const MIN_INTERVAL_MS: u64 = 100;-const MAX_INTERVAL_MS: u64 = 5000;-const INTERVAL_STEP_MS: u64 = 100;--static INTERVAL_MS: AtomicU64 = AtomicU64::new(1000);-static THEME_INDEX: AtomicUsize = AtomicUsize::new(0);-static DARK_BACKGROUND: AtomicBool = AtomicBool::new(true);-static SHOW_INFO: AtomicBool = AtomicBool::new(false);-static DATA_VERSION: AtomicU64 = AtomicU64::new(0);--pub(crate) fn theme() -> (&'static str, Color) {- THEMES[THEME_INDEX.load(Ordering::Relaxed) % THEMES.len()]-}--pub(crate) fn accent() -> Color {- theme().1-}--pub(crate) fn background() -> Color {- if DARK_BACKGROUND.load(Ordering::Relaxed) {- Color::Black- } else {- Color::Reset- }-}--pub(crate) fn interval() -> Duration {- Duration::from_millis(INTERVAL_MS.load(Ordering::Relaxed))-}--pub(crate) fn interval_ms() -> u64 {- INTERVAL_MS.load(Ordering::Relaxed)-}--pub(crate) fn cycle_theme() {- THEME_INDEX.fetch_add(1, Ordering::Relaxed);-}--pub(crate) fn toggle_background() {- DARK_BACKGROUND.fetch_xor(true, Ordering::Relaxed);-}--pub(crate) fn toggle_info() {- SHOW_INFO.fetch_xor(true, Ordering::Relaxed);-}--pub(crate) fn show_info() -> bool {- SHOW_INFO.load(Ordering::Relaxed)-}--pub(crate) fn speed_up() {- adjust(-(INTERVAL_STEP_MS as i64));-}--pub(crate) fn slow_down() {- adjust(INTERVAL_STEP_MS as i64);-}--fn adjust(delta: i64) {- let current = INTERVAL_MS.load(Ordering::Relaxed) as i64;- let next = (current + delta).clamp(MIN_INTERVAL_MS as i64, MAX_INTERVAL_MS as i64) as u64;- INTERVAL_MS.store(next, Ordering::Relaxed);-}--pub(crate) fn bump_data_version() {- DATA_VERSION.fetch_add(1, Ordering::Relaxed);-}--pub(crate) fn data_version() -> u64 {- DATA_VERSION.load(Ordering::Relaxed)-}diff --git a/crates/kanshi/src/telemetry.rs b/crates/kanshi/src/telemetry.rsdeleted file mode 100644index 66e4660cc..000000000--- a/crates/kanshi/src/telemetry.rs+++ /dev/null@@ -1,30 +0,0 @@-use std::collections::VecDeque;--use keisoku::{Device, Snapshot};--use crate::{disk_row::DiskRow, host_info::HostInfo, net_interface::NetInterface, process_row::ProcessRow};--#[derive(Default)]-pub(crate) struct Telemetry {- pub(crate) device: Option<Device>,- pub(crate) host: Option<HostInfo>,- pub(crate) snapshot: Option<Snapshot>,- pub(crate) cpu_history: VecDeque<f64>,- pub(crate) gpu_history: VecDeque<f64>,- pub(crate) ane_history: VecDeque<f64>,- pub(crate) memory_history: VecDeque<f64>,- pub(crate) power_history: VecDeque<f64>,- pub(crate) max_power: f64,- pub(crate) uptime_seconds: u64,- pub(crate) network_down: f64,- pub(crate) network_up: f64,- pub(crate) network_packets_down: f64,- pub(crate) network_packets_up: f64,- pub(crate) network_total_down: u64,- pub(crate) network_total_up: u64,- pub(crate) network_interfaces: Vec<NetInterface>,- pub(crate) disk_read: f64,- pub(crate) disk_written: f64,- pub(crate) disks: Vec<DiskRow>,- pub(crate) processes: Vec<ProcessRow>,-}diff --git a/crates/kanshi/src/widgets.rs b/crates/kanshi/src/widgets.rsdeleted file mode 100644index e2dfe3d16..000000000--- a/crates/kanshi/src/widgets.rs+++ /dev/null@@ -1,37 +0,0 @@-use ratatui::{- layout::{Constraint, Direction, Layout, Rect},- style::Style,- widgets::{Block, Borders},-};--use crate::state::accent;--pub(crate) fn panel(title: &str) -> Block<'_> {- Block::default()- .borders(Borders::ALL)- .border_style(Style::default().fg(accent()))- .title_style(Style::default().fg(accent()))- .title(title)-}--pub(crate) fn panel_owned(title: String) -> Block<'static> {- Block::default()- .borders(Borders::ALL)- .border_style(Style::default().fg(accent()))- .title_style(Style::default().fg(accent()))- .title(title)-}--pub(crate) fn split_horizontal<const N: usize>(- area: Rect,- constraints: [Constraint; N],-) -> std::rc::Rc<[Rect]> {- Layout::default().direction(Direction::Horizontal).constraints(constraints).split(area)-}--pub(crate) fn split_vertical<const N: usize>(- area: Rect,- constraints: [Constraint; N],-) -> std::rc::Rc<[Rect]> {- Layout::default().direction(Direction::Vertical).constraints(constraints).split(area)-}diff --git a/crates/keisoku/Cargo.toml b/crates/keisoku/Cargo.tomlindex 1e7352513..855f72635 100644--- a/crates/keisoku/Cargo.toml+++ b/crates/keisoku/Cargo.toml@@ -18,13 +18,8 @@ path = "src/lib.rs"workspace = true[dependencies]+bitflags.workspace = trueserde = { workspace = true, features = ["derive"] }-serde_json.workspace = true-sysinfo.workspace = true--# Used only by the on-device `table` test to render a snapshot via TestBackend.-[dev-dependencies]-ratatui.workspace = true[target.'cfg(target_vendor = "apple")'.dependencies]kanka.workspace = true@@ -35,3 +30,8 @@ libc.workspace = true# IOReport/SoC traversal is macOS-only; IOKit service iteration via objc2-io-kit.[target.'cfg(target_os = "macos")'.dependencies]objc2-io-kit.workspace = true+serde_json.workspace = true++# Memory stats on non-macOS Apple (iOS) come from sysinfo.+[target.'cfg(not(target_os = "macos"))'.dependencies]+sysinfo.workspace = truediff --git a/crates/keisoku/README.md b/crates/keisoku/README.mdindex e43afa80a..7be096e44 100644--- a/crates/keisoku/README.md+++ b/crates/keisoku/README.md@@ -1,44 +1,31 @@# keisoku-System telemetry collector for Apple platforms — CPU/GPU/ANE power, memory, bandwidth,-frequencies, temperatures and sensors. Power is read from the SoC's IOReport/SMC counters,-so sampling runs off your work thread and adds no measurable load.+System telemetry for Apple platforms — power, energy, memory, temperatures and sensors — read from the SoC's IOReport/SMC counters via [`kanka`](../kanka).-## Two ways to use it--**One-shot** — take a single reading averaged over a window:+## `Device` — device facts and instantaneous gauges```rust-let mut collector = keisoku::Collector::new();-let snapshot = collector.sample(std::time::Duration::from_millis(100));-if let Some(power) = snapshot.power {- println!("gpu {} / total {}", power.gpu, power.total); // Watts-}+use keisoku::Device;++let mut device = Device::new();+println!("{} {} GPU cores", device.chip(), device.gpu_cores());+println!("battery {:?}", device.battery());```-**Background recorder** — sample at an interval while something runs, then collect:+## `interval_measurement` — IOReport channel deltas over a window-```rust-let recorder = keisoku::start(keisoku::Config {- interval: std::time::Duration::from_millis(100),-});-// ... do work ...-let session = recorder.stop(); // stops the sampler, returns what it collected-let samples = session.snapshots.len();-```+Build once per measurement set. The caller owns timing; `start`/`stop` are cheap counter reads.-## What you get back+```rust+use keisoku::{AneBandwidth, Cpu, Device, DramBytes, DramRead, EnergyRail, Gpu, Select};-- `Session { interval, snapshots }` — the snapshots sampled between `start` and `stop`.-- `Snapshot { elapsed, power, memory, cpu, gpu, neural_engine, bandwidth, temperatures, .. }`.-- `PowerMetrics { cpu, gpu, gpu_sram, ane, ram, total, package }` — all `Watts`.-- `Device { chip, gpu_cores, performance_cores, efficiency_cores, ram_total, os }`.+let mut handle = Device::interval_measurement::<Select![EnergyRail<Cpu>, EnergyRail<Gpu>, AneBandwidth, DramBytes<DramRead>]>();+handle.start();+// ... run work ...+let sample = handle.stop().expect("started");+println!("CPU energy: {}", sample.get::<EnergyRail<Cpu>>());+```## Platform-Real numbers on Apple Silicon (macOS, and iOS for the subset exposed there). On other-platforms the power/SoC fields are `None` and the calls are safe no-ops, so code that-depends on keisoku still builds and runs everywhere.--Used by [`kanshi`](../kanshi) (live monitor); reaches Apple's private counters via-[`kanka`](../kanka).+Apple only. `interval_measurement` (IOReport) is macOS-only; iOS exposes the `Device` instant subset.diff --git a/crates/keisoku/src/collector.rs b/crates/keisoku/src/collector.rsdeleted file mode 100644index 2ef715c42..000000000--- a/crates/keisoku/src/collector.rs+++ /dev/null@@ -1,202 +0,0 @@-use std::time::Duration;--#[cfg(target_os = "macos")]-use crate::units::{GigabytesPerSecond, Megahertz, Percent, Watts};-use crate::{- metrics::{BandwidthMetrics, CpuMetrics, GpuMetrics, NeuralEngineMetrics, PowerMetrics, Temperatures},- sensor::{Sensor, SensorKind},- snapshot::Snapshot,- units::{Celsius, Milliseconds},-};--#[derive(Default)]-struct SocMetrics {- cpu: Option<CpuMetrics>,- gpu: Option<GpuMetrics>,- neural_engine: Option<NeuralEngineMetrics>,- power: Option<PowerMetrics>,- bandwidth: Option<BandwidthMetrics>,-}--pub struct Collector {- #[cfg(target_os = "macos")]- soc: Option<crate::soc::SocInfo>,- #[cfg(target_os = "macos")]- ioreport: Option<crate::ioreport::IoReport>,- #[cfg(target_os = "macos")]- cpu_load: crate::cpu_load::CpuLoad,- #[cfg(target_os = "macos")]- smc: Option<crate::smc::Smc>,- #[cfg(target_vendor = "apple")]- temperature_reader: Option<crate::client::SensorReader>,- #[cfg(target_vendor = "apple")]- voltage_reader: Option<crate::client::SensorReader>,- #[cfg(target_vendor = "apple")]- current_reader: Option<crate::client::SensorReader>,-}--impl Default for Collector {- fn default() -> Self {- Self::new()- }-}--impl Collector {- pub fn new() -> Self {- Self {- #[cfg(target_os = "macos")]- soc: crate::soc::SocInfo::new(),- #[cfg(target_os = "macos")]- ioreport: crate::ioreport::IoReport::new(),- #[cfg(target_os = "macos")]- cpu_load: crate::cpu_load::CpuLoad::new(),- #[cfg(target_os = "macos")]- smc: crate::smc::Smc::new(),- #[cfg(target_vendor = "apple")]- temperature_reader: crate::client::SensorReader::new(SensorKind::Temperature),- #[cfg(target_vendor = "apple")]- voltage_reader: crate::client::SensorReader::new(SensorKind::Voltage),- #[cfg(target_vendor = "apple")]- current_reader: crate::client::SensorReader::new(SensorKind::Current),- }- }-- #[cfg(target_os = "macos")]- pub fn soc(&self) -> Option<&crate::soc::SocInfo> {- self.soc.as_ref()- }-- pub fn device(&self) -> crate::Device {- crate::Device::detect(self)- }-- pub fn sample(- &mut self,- interval: Duration,- ) -> Snapshot {- let soc = self.sample_soc(interval);- let memory = crate::metrics::read_memory();- let fans = self.read_fans();- let battery = crate::metrics::read_battery();- let thermal_pressure = crate::metrics::read_thermal_pressure();- #[cfg(target_vendor = "apple")]- let sensors = self.temperature_reader.as_mut().map(crate::client::SensorReader::read).unwrap_or_default();- #[cfg(not(target_vendor = "apple"))]- let sensors = crate::sensors(SensorKind::Temperature);- #[cfg(target_vendor = "apple")]- let voltage = self.voltage_reader.as_mut().map(crate::client::SensorReader::read).unwrap_or_default();- #[cfg(not(target_vendor = "apple"))]- let voltage = crate::sensors(SensorKind::Voltage);- #[cfg(target_vendor = "apple")]- let current = self.current_reader.as_mut().map(crate::client::SensorReader::read).unwrap_or_default();- #[cfg(not(target_vendor = "apple"))]- let current = crate::sensors(SensorKind::Current);- let temperatures = (!sensors.is_empty()).then(|| temperatures_from(&sensors));- Snapshot {- elapsed: Milliseconds(0),- cpu: soc.cpu,- gpu: soc.gpu,- neural_engine: soc.neural_engine,- power: soc.power,- memory,- bandwidth: soc.bandwidth,- fans,- battery,- temperatures,- thermal_pressure,- sensors,- voltage,- current,- }- }-- #[cfg(target_os = "macos")]- fn sample_soc(- &mut self,- interval: Duration,- ) -> SocMetrics {- let (Some(ioreport), Some(soc)) = (&self.ioreport, &self.soc) else {- std::thread::sleep(interval);- return SocMetrics::default();- };- let sample = ioreport.sample(soc, interval);- let per_core = self.cpu_load.sample();- let package = self.smc.as_ref().and_then(|smc| smc.package_watts()).unwrap_or(Watts(sample.total_power));- SocMetrics {- cpu: Some(CpuMetrics {- usage: Percent(sample.cpu_usage_percent * 100.0),- ecpu_frequency: Megahertz(sample.ecpu_usage.0),- ecpu_usage: Percent(sample.ecpu_usage.1 * 100.0),- pcpu_frequency: Megahertz(sample.pcpu_usage.0),- pcpu_usage: Percent(sample.pcpu_usage.1 * 100.0),- per_core,- }),- gpu: Some(GpuMetrics {- frequency: Megahertz(sample.gpu_usage.0),- usage: Percent(sample.gpu_usage.1 * 100.0),- }),- neural_engine: Some(NeuralEngineMetrics {- power: Watts(sample.ane_power),- active: Percent(sample.ane_active_percent),- read_bandwidth: GigabytesPerSecond(sample.ane_read_gbps),- write_bandwidth: GigabytesPerSecond(sample.ane_write_gbps),- }),- power: Some(PowerMetrics {- cpu: Watts(sample.cpu_power),- gpu: Watts(sample.gpu_power),- gpu_sram: Watts(sample.gpu_ram_power),- ane: Watts(sample.ane_power),- ram: Watts(sample.ram_power),- total: Watts(sample.total_power),- package,- }),- bandwidth: Some(BandwidthMetrics {- dram_read: GigabytesPerSecond(sample.dram_read_gbps),- dram_write: GigabytesPerSecond(sample.dram_write_gbps),- }),- }- }-- #[cfg(not(target_os = "macos"))]- fn sample_soc(- &mut self,- interval: Duration,- ) -> SocMetrics {- std::thread::sleep(interval);- SocMetrics::default()- }-- #[cfg(target_os = "macos")]- fn read_fans(&self) -> Option<crate::metrics::FanMetrics> {- self.smc.as_ref().map(|smc| smc.fans())- }-- #[cfg(not(target_os = "macos"))]- fn read_fans(&self) -> Option<crate::metrics::FanMetrics> {- None- }-}--fn average(values: &[f32]) -> f32 {- if values.is_empty() {- 0.0- } else {- values.iter().sum::<f32>() / values.len() as f32- }-}--fn temperatures_from(sensors: &[Sensor]) -> Temperatures {- use crate::Component;- let average_of = |components: &[Component]| {- let values: Vec<f32> = sensors- .iter()- .filter(|sensor| components.contains(&sensor.component) && (1.0..150.0).contains(&sensor.value))- .map(|sensor| sensor.value as f32)- .collect();- (!values.is_empty()).then(|| Celsius(average(&values)))- };- Temperatures {- cpu_average: average_of(&[Component::Cpu, Component::Soc]),- gpu_average: average_of(&[Component::Gpu]),- }-}diff --git a/crates/keisoku/src/component.rs b/crates/keisoku/src/component.rsindex f7020e698..9f4845139 100644--- a/crates/keisoku/src/component.rs+++ b/crates/keisoku/src/component.rs@@ -96,32 +96,3 @@ fn thermal_probe_block(name: &str) -> Option<char> {}})}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn classifies_observed_names() {- assert_eq!(classify("gas gauge battery"), Component::Battery);- assert_eq!(classify("NAND CH0 temp"), Component::Storage);- assert_eq!(classify("PMU TP3g"), Component::Gpu);- assert_eq!(classify("PMU TP1s"), Component::Soc);- assert_eq!(classify("PMU tdie1"), Component::Soc);- assert_eq!(classify("PMU tjunc"), Component::Soc);- assert_eq!(classify("PMU tdev1"), Component::PowerManagementUnit);- assert_eq!(classify("PMU tcal"), Component::PowerManagementUnit);- assert_eq!(classify("PMU vbuck0"), Component::PowerManagementUnit);- assert_eq!(classify("PMU ildo3"), Component::PowerManagementUnit);- assert_eq!(classify("Charger TQ0j"), Component::Charger);- assert_eq!(classify("ANE temp"), Component::NeuralEngine);- assert_eq!(classify("GPU die"), Component::Gpu);- assert_eq!(classify("something weird"), Component::Unknown);- }-- #[test]- fn labels_are_human_readable() {- assert_eq!(Component::NeuralEngine.label(), "Neural Engine");- assert_eq!(Component::PowerManagementUnit.to_string(), "Power Management Unit");- }-}diff --git a/crates/keisoku/src/cpu_load.rs b/crates/keisoku/src/cpu_load.rsdeleted file mode 100644index 371b7693a..000000000--- a/crates/keisoku/src/cpu_load.rs+++ /dev/null@@ -1,86 +0,0 @@-use crate::units::Percent;--const STATES: usize = libc::CPU_STATE_MAX as usize;--pub struct CpuLoad {- last: Vec<[u64; STATES]>,-}--impl CpuLoad {- pub fn new() -> Self {- Self {- last: Vec::new(),- }- }-- pub fn sample(&mut self) -> Vec<Percent> {- let Some(ticks) = read_ticks() else {- return Vec::new();- };- if ticks.len() != self.last.len() {- self.last = ticks;- return vec![Percent(0.0); self.last.len()];- }- let usage = ticks- .iter()- .zip(&self.last)- .map(|(current, previous)| {- let delta = |state: usize| current[state].saturating_sub(previous[state]) as f64;- let active = delta(libc::CPU_STATE_USER as usize)- + delta(libc::CPU_STATE_SYSTEM as usize)- + delta(libc::CPU_STATE_NICE as usize);- let total = active + delta(libc::CPU_STATE_IDLE as usize);- let percent = if total > 0.0 {- (active / total * 100.0) as f32- } else {- 0.0- };- Percent(percent.clamp(0.0, 100.0))- })- .collect();- self.last = ticks;- usage- }-}--#[allow(deprecated)]-fn read_ticks() -> Option<Vec<[u64; STATES]>> {- let mut cpu_count: libc::natural_t = 0;- let mut info: libc::processor_info_array_t = core::ptr::null_mut();- let mut info_count: libc::mach_msg_type_number_t = 0;- let result = unsafe {- libc::host_processor_info(- libc::mach_host_self(),- libc::PROCESSOR_CPU_LOAD_INFO,- &mut cpu_count,- &mut info,- &mut info_count,- )- };- if result != libc::KERN_SUCCESS || info.is_null() {- return None;- }-- let loads =- unsafe { core::slice::from_raw_parts(info as *const libc::processor_cpu_load_info, cpu_count as usize) };- let ticks = loads- .iter()- .map(|load| {- [- load.cpu_ticks[libc::CPU_STATE_USER as usize] as u64,- load.cpu_ticks[libc::CPU_STATE_SYSTEM as usize] as u64,- load.cpu_ticks[libc::CPU_STATE_IDLE as usize] as u64,- load.cpu_ticks[libc::CPU_STATE_NICE as usize] as u64,- ]- })- .collect();-- unsafe {- libc::vm_deallocate(- libc::mach_task_self(),- info as libc::vm_address_t,- info_count as usize * core::mem::size_of::<libc::c_int>(),- );- }- Some(ticks)-}diff --git a/crates/keisoku/src/device/device.rs b/crates/keisoku/src/device/device.rsnew file mode 100644index 000000000..43cf58347--- /dev/null+++ b/crates/keisoku/src/device/device.rs@@ -0,0 +1,85 @@+#[cfg(target_os = "macos")]+use super::IntervalHandle;+#[cfg(target_os = "macos")]+use crate::marker::IntervalSet;+use crate::{+ metrics::{BatteryMetrics, FanMetrics, MemoryMetrics, ThermalPressure},+ sensor::Sensor,+ sources::Sources,+ units::Watts,+};++/// Instantaneous device facts and gauges (chip, memory, sensors, …).+pub struct Device {+ sources: Sources,+}++impl Device {+ pub fn new() -> Self {+ Self {+ sources: Sources::new(),+ }+ }++ pub fn chip(&self) -> String {+ self.sources.chip()+ }++ pub fn efficiency_cores(&self) -> u8 {+ self.sources.efficiency_cores()+ }++ pub fn performance_cores(&self) -> u8 {+ self.sources.performance_cores()+ }++ pub fn gpu_cores(&self) -> u8 {+ self.sources.gpu_cores()+ }++ pub fn memory(&mut self) -> Option<MemoryMetrics> {+ self.sources.memory()+ }++ pub fn battery(&mut self) -> Option<BatteryMetrics> {+ self.sources.battery()+ }++ pub fn thermal(&mut self) -> Option<ThermalPressure> {+ self.sources.thermal()+ }++ pub fn fans(&self) -> Option<FanMetrics> {+ self.sources.fans()+ }++ pub fn temperature_sensors(&mut self) -> Box<[Sensor]> {+ self.sources.temperature_sensors()+ }++ pub fn voltage_sensors(&mut self) -> Box<[Sensor]> {+ self.sources.voltage_sensors()+ }++ pub fn current_sensors(&mut self) -> Box<[Sensor]> {+ self.sources.current_sensors()+ }++ pub fn rail_power(&mut self) -> Option<Watts> {+ self.sources.rail_power()+ }++ /// Starts an IOReport interval measurement for the channels in `M`.+ ///+ /// Call [`IntervalHandle::start`] before work and [`IntervalHandle::stop`] after.+ #[cfg(target_os = "macos")]+ pub fn interval_measurement<M: IntervalSet>() -> IntervalHandle<M> {+ IntervalHandle::new()+ }+}++impl Default for Device {+ fn default() -> Self {+ Self::new()+ }+}diff --git a/crates/keisoku/src/device/interval_handle.rs b/crates/keisoku/src/device/interval_handle.rsnew file mode 100644index 000000000..011a9ac89--- /dev/null+++ b/crates/keisoku/src/device/interval_handle.rs@@ -0,0 +1,54 @@+use core::marker::PhantomData;+use std::time::Instant;++use crate::{+ marker::{IntervalSet, Sample},+ sources::interval::{IntervalEngine, IntervalSession},+};++/// Handle for measuring selected IOReport channels over a time window.+#[must_use]+pub struct IntervalHandle<M: IntervalSet> {+ engine: IntervalEngine,+ session: Option<IntervalSession>,+ started: Option<Instant>,+ marker: PhantomData<M>,+}++// SAFETY: `IntervalHandle` wraps CoreFoundation IOReport objects that are not `Sync`.+// Callers must use a handle only from the thread that created it (same contract as the+// previous `Interval`/`Session` types). `Send` is asserted so `PowerMeter` can live in+// `RefCell` behind `Send` trait objects such as nagare's `PowerRecorder`.+unsafe impl<M: IntervalSet> Send for IntervalHandle<M> {}++impl<M: IntervalSet> IntervalHandle<M> {+ pub(super) fn new() -> Self {+ let _ = M::TYPE_MASK;+ Self {+ engine: IntervalEngine::new(M::GROUPS),+ session: None,+ started: None,+ marker: PhantomData,+ }+ }++ /// Begins an IOReport snapshot. Calling again without [`stop`](Self::stop) restarts the window.+ pub fn start(&mut self) {+ debug_assert!(self.session.is_none(), "start without stop");+ drop(self.session.take());+ self.started = Some(Instant::now());+ self.session = Some(self.engine.begin());+ }++ /// Ends the measurement and returns channel deltas, or `None` if [`start`](Self::start) was not called.+ pub fn stop(&mut self) -> Option<Sample<M>> {+ let session = self.session.take()?;+ let mut values = M::default_values();+ self.engine.fold_end::<M>(session, &mut values);+ Some(Sample::new(values))+ }++ pub(crate) fn elapsed(&self) -> std::time::Duration {+ self.started.map(|started| started.elapsed()).unwrap_or_default()+ }+}diff --git a/crates/keisoku/src/device/mod.rs b/crates/keisoku/src/device/mod.rsnew file mode 100644index 000000000..722ef5bfc--- /dev/null+++ b/crates/keisoku/src/device/mod.rs@@ -0,0 +1,7 @@+mod device;+#[cfg(target_os = "macos")]+mod interval_handle;++pub use device::Device;+#[cfg(target_os = "macos")]+pub use interval_handle::IntervalHandle;diff --git a/crates/keisoku/src/ioreport/bandwidth.rs b/crates/keisoku/src/ioreport/bandwidth.rsdeleted file mode 100644index bce8e9b25..000000000--- a/crates/keisoku/src/ioreport/bandwidth.rs+++ /dev/null@@ -1,171 +0,0 @@-use obfstr::obfstr;--use super::{- SocSample,- channel::{ResidencyState, residency_active_percent, residency_weighted_gbps},-};--#[derive(Clone, Copy)]-enum Flow {- Read,- Write,- Combined,-}--#[derive(Clone, Copy)]-enum Subsystem {- Dram,- NeuralEngine,-}--#[derive(Default)]-pub(super) struct BandwidthAccumulator {- dram_read_bytes: f64,- dram_write_bytes: f64,- dram_combined_bytes: f64,- ane_read_bytes: f64,- ane_write_bytes: f64,- ane_combined_bytes: f64,- dram_read_histogram_gbps: f32,- dram_write_histogram_gbps: f32,- ane_read_histogram_gbps: f32,- ane_write_histogram_gbps: f32,-}--impl BandwidthAccumulator {- fn add_dram_bytes(- &mut self,- flow: Flow,- bytes: f64,- ) {- match flow {- Flow::Read => self.dram_read_bytes += bytes,- Flow::Write => self.dram_write_bytes += bytes,- Flow::Combined => self.dram_combined_bytes += bytes,- }- }-- fn add_ane_bytes(- &mut self,- flow: Flow,- bytes: f64,- ) {- match flow {- Flow::Read => self.ane_read_bytes += bytes,- Flow::Write => self.ane_write_bytes += bytes,- Flow::Combined => self.ane_combined_bytes += bytes,- }- }-- pub(super) fn finish(- mut self,- window_milliseconds: u64,- result: &mut SocSample,- ) {- let window_seconds = (window_milliseconds as f64 / 1000.0).max(0.001);- let to_gbps = |bytes: f64| (bytes / window_seconds / 1e9) as f32;-- if self.dram_read_bytes == 0.0 && self.dram_write_bytes == 0.0 && self.dram_combined_bytes > 0.0 {- self.dram_read_bytes = self.dram_combined_bytes / 2.0;- self.dram_write_bytes = self.dram_combined_bytes / 2.0;- }- if self.ane_read_bytes == 0.0 && self.ane_write_bytes == 0.0 && self.ane_combined_bytes > 0.0 {- self.ane_read_bytes = self.ane_combined_bytes / 2.0;- self.ane_write_bytes = self.ane_combined_bytes / 2.0;- }-- result.dram_read_gbps = if self.dram_read_bytes > 0.0 {- to_gbps(self.dram_read_bytes)- } else {- self.dram_read_histogram_gbps- };- result.dram_write_gbps = if self.dram_write_bytes > 0.0 {- to_gbps(self.dram_write_bytes)- } else {- self.dram_write_histogram_gbps- };- result.ane_read_gbps = if self.ane_read_bytes > 0.0 {- to_gbps(self.ane_read_bytes)- } else {- self.ane_read_histogram_gbps- };- result.ane_write_gbps = if self.ane_write_bytes > 0.0 {- to_gbps(self.ane_write_bytes)- } else {- self.ane_write_histogram_gbps- };- }-}--pub(super) fn accumulate_amc_bandwidth(- bytes: i64,- channel: &str,- bandwidth: &mut BandwidthAccumulator,-) {- let aggregate = strip_die_prefix(channel);- let target = if aggregate == obfstr!("DCS RD") {- (Subsystem::Dram, Flow::Read)- } else if aggregate == obfstr!("DCS WR") {- (Subsystem::Dram, Flow::Write)- } else if aggregate == obfstr!("ANE DCS RD") {- (Subsystem::NeuralEngine, Flow::Read)- } else if aggregate == obfstr!("ANE DCS WR") {- (Subsystem::NeuralEngine, Flow::Write)- } else {- return;- };- let bytes = bytes as f64;- if bytes <= 0.0 {- return;- }- match target.0 {- Subsystem::Dram => bandwidth.add_dram_bytes(target.1, bytes),- Subsystem::NeuralEngine => bandwidth.add_ane_bytes(target.1, bytes),- }-}--pub(super) fn accumulate_pmp(- states: &[ResidencyState],- subgroup: &str,- channel: &str,- bandwidth: &mut BandwidthAccumulator,- result: &mut SocSample,-) {- if subgroup.contains(obfstr!("Floor")) && (channel == obfstr!("ANE-AF-BW") || channel == obfstr!("ANE-DCS-BW")) {- result.ane_active_percent = result.ane_active_percent.max(residency_active_percent(states));- } else if subgroup == obfstr!("AF BW") {- if channel == obfstr!("ANE0 RD") {- bandwidth.ane_read_histogram_gbps = bandwidth.ane_read_histogram_gbps.max(residency_weighted_gbps(states));- } else if channel == obfstr!("ANE0 WR") {- bandwidth.ane_write_histogram_gbps =- bandwidth.ane_write_histogram_gbps.max(residency_weighted_gbps(states));- }- } else if subgroup == obfstr!("DRAM BW") {- let gbps = residency_weighted_gbps(states);- match flow(channel) {- Flow::Read => bandwidth.dram_read_histogram_gbps = bandwidth.dram_read_histogram_gbps.max(gbps),- Flow::Write => bandwidth.dram_write_histogram_gbps = bandwidth.dram_write_histogram_gbps.max(gbps),- Flow::Combined => {},- }- }-}--fn strip_die_prefix(channel: &str) -> &str {- let Some(rest) = channel.strip_prefix(obfstr!("DIE")) else {- return channel;- };- let rest = rest.trim_start_matches(|character: char| character.is_ascii_digit());- rest.strip_prefix(' ').unwrap_or(channel)-}--fn flow(channel: &str) -> Flow {- if channel.contains(obfstr!("RD+WR")) || channel.ends_with(obfstr!("RW")) {- Flow::Combined- } else if channel.contains(obfstr!("WR")) {- Flow::Write- } else if channel.contains(obfstr!("RD")) {- Flow::Read- } else {- Flow::Combined- }-}diff --git a/crates/keisoku/src/ioreport/channel.rs b/crates/keisoku/src/ioreport/channel.rsdeleted file mode 100644index 6feba20a8..000000000--- a/crates/keisoku/src/ioreport/channel.rs+++ /dev/null@@ -1,93 +0,0 @@-use core::ffi::c_void;--use obfstr::obfstr;-use objc2_core_foundation::{CFArray, CFDictionary, CFRetained, CFType};--use super::IoReportFunctions;-use crate::cf::{cf_string_to_string, dictionary_get};--pub(super) struct ResidencyState {- pub name: String,- pub residency: i64,-}--pub(super) struct ChannelSample {- pub group: String,- pub subgroup: String,- pub name: String,- pub unit: String,- pub integer_value: i64,- pub states: Vec<ResidencyState>,-}--pub(super) fn decode_channels(- functions: &IoReportFunctions,- delta: &CFDictionary,-) -> Vec<ChannelSample> {- let Some(channels) = dictionary_get::<CFArray>(delta, obfstr!("IOReportChannels")) else {- return Vec::new();- };- let channels: CFRetained<CFArray<CFType>> = unsafe { CFRetained::from_raw(CFRetained::into_raw(channels).cast()) };- channels.iter().map(|channel| decode_channel(functions, &channel)).collect()-}--fn decode_channel(- functions: &IoReportFunctions,- channel: &CFType,-) -> ChannelSample {- let item: *const c_void = core::ptr::from_ref(channel).cast();- let states = (0..unsafe { (functions.state_get_count)(item) })- .map(|index| ResidencyState {- name: cf_string_to_string(unsafe { (functions.state_get_name_for_index)(item, index) }),- residency: unsafe { (functions.state_get_residency)(item, index) },- })- .collect();- ChannelSample {- group: cf_string_to_string(unsafe { (functions.channel_get_group)(item) }),- subgroup: cf_string_to_string(unsafe { (functions.channel_get_subgroup)(item) }),- name: cf_string_to_string(unsafe { (functions.channel_get_channel_name)(item) }),- unit: cf_string_to_string(unsafe { (functions.channel_get_unit_label)(item) }),- integer_value: unsafe { (functions.simple_get_integer_value)(item, 0) },- states,- }-}--pub(super) fn residency_active_percent(states: &[ResidencyState]) -> f32 {- let total: f64 = states.iter().map(|state| state.residency as f64).sum();- if total <= 0.0 {- return 0.0;- }- let active: f64 =- states.iter().filter(|state| !is_idle_state(&state.name)).map(|state| state.residency as f64).sum();- (active / total * 100.0) as f32-}--pub(super) fn residency_weighted_gbps(states: &[ResidencyState]) -> f32 {- let mut weighted = 0f64;- let mut total = 0f64;- for state in states {- weighted += parse_leading_number(&state.name) * (state.residency as f64);- total += state.residency as f64;- }- if total <= 0.0 {- 0.0- } else {- (weighted / total) as f32- }-}--pub(super) fn is_idle_state(name: &str) -> bool {- name == obfstr!("OFF")- || name == obfstr!("IDLE")- || name == obfstr!("DOWN")- || name == obfstr!("SLEEP")- || name == obfstr!("VMIN")- || name == obfstr!("F1")- || name == obfstr!("0%")-}--fn parse_leading_number(name: &str) -> f64 {- let digits: String =- name.trim().chars().take_while(|character| character.is_ascii_digit() || *character == '.').collect();- digits.parse().unwrap_or(0.0)-}diff --git a/crates/keisoku/src/ioreport/frequency.rs b/crates/keisoku/src/ioreport/frequency.rsdeleted file mode 100644index c19715c39..000000000--- a/crates/keisoku/src/ioreport/frequency.rs+++ /dev/null@@ -1,56 +0,0 @@-use super::channel::{ResidencyState, is_idle_state};--pub(super) fn calculate_frequency(- states: &[ResidencyState],- frequencies: &[u32],-) -> (u32, f32) {- if states.len() <= frequencies.len() || frequencies.is_empty() {- return (0, 0.0);- }-- let Some(offset) = states.iter().position(|state| !is_idle_state(&state.name)) else {- return (0, 0.0);- };- let active: f64 = states.iter().skip(offset).map(|state| state.residency as f64).sum();- let total: f64 = states.iter().map(|state| state.residency as f64).sum();-- let mut average_frequency = 0f64;- for (index, &frequency) in frequencies.iter().enumerate() {- let Some(state) = states.get(index + offset) else {- break;- };- let percent = divide_or_zero(state.residency as f64, active);- average_frequency += percent * frequency as f64;- }- let usage_ratio = divide_or_zero(active, total);- let minimum_frequency = *frequencies.first().unwrap() as f64;- let maximum_frequency = *frequencies.last().unwrap() as f64;- let fraction_of_max = (average_frequency.max(minimum_frequency) * usage_ratio) / maximum_frequency;- (average_frequency as u32, fraction_of_max as f32)-}--pub(super) fn average_cluster_frequency(- readings: &[(u32, f32)],- frequencies: &[u32],-) -> (u32, f32) {- if readings.is_empty() || frequencies.is_empty() {- return (0, 0.0);- }- let average_frequency =- divide_or_zero(readings.iter().map(|reading| reading.0 as f32).sum::<f32>(), readings.len() as f32);- let average_percent = divide_or_zero(readings.iter().map(|reading| reading.1).sum::<f32>(), readings.len() as f32);- let minimum_frequency = *frequencies.first().unwrap() as f32;- (average_frequency.max(minimum_frequency) as u32, average_percent)-}--pub(super) fn divide_or_zero<T: core::ops::Div<Output = T> + Default + PartialEq>(- numerator: T,- denominator: T,-) -> T {- let zero = T::default();- if denominator == zero {- zero- } else {- numerator / denominator- }-}diff --git a/crates/keisoku/src/ioreport/report.rs b/crates/keisoku/src/ioreport/report.rsdeleted file mode 100644index 35cbef54d..000000000--- a/crates/keisoku/src/ioreport/report.rs+++ /dev/null@@ -1,124 +0,0 @@-use std::time::{Duration, Instant};--use obfstr::obfstr;--use super::{- IoReportFunctions, SocSample,- bandwidth::{BandwidthAccumulator, accumulate_amc_bandwidth, accumulate_pmp},- channel::decode_channels,- frequency::{average_cluster_frequency, calculate_frequency, divide_or_zero},- subscription::Subscription,-};-use crate::soc::SocInfo;--const ANE_MAX_POWER_WATTS: f32 = 8.0;--pub struct IoReport {- functions: &'static IoReportFunctions,- subscription: Subscription,-}--impl IoReport {- pub fn new() -> Option<Self> {- let functions = IoReportFunctions::get()?;- let subscription = Subscription::new(functions)?;- Some(Self {- functions,- subscription,- })- }-- pub fn sample(- &self,- soc: &SocInfo,- interval: Duration,- ) -> SocSample {- let functions = self.functions;-- let Some(previous) = self.subscription.snapshot(functions) else {- std::thread::sleep(interval);- return SocSample::default();- };- let started = Instant::now();- std::thread::sleep(interval);- let next = self.subscription.snapshot(functions);- let elapsed = started.elapsed();- let Some(next) = next else {- return SocSample::default();- };- let Some(delta) = functions.create_samples_delta(&previous, &next) else {- return SocSample::default();- };-- let mut result = SocSample::default();- let mut ecpu_readings = Vec::new();- let mut pcpu_readings = Vec::new();- let window_milliseconds = elapsed.as_millis().max(1) as u64;- let mut bandwidth = BandwidthAccumulator::default();-- for channel in decode_channels(functions, &delta) {- if channel.group == obfstr!("CPU Stats") && channel.subgroup == obfstr!("CPU Core Performance States") {- if channel.name.starts_with(obfstr!("PCPU")) {- pcpu_readings.push(calculate_frequency(&channel.states, &soc.pcpu_frequencies));- } else if channel.name.starts_with(obfstr!("ECPU")) || channel.name.starts_with(obfstr!("MCPU")) {- ecpu_readings.push(calculate_frequency(&channel.states, &soc.ecpu_frequencies));- }- } else if channel.group == obfstr!("GPU Stats") && channel.subgroup == obfstr!("GPU Performance States") {- if channel.name == obfstr!("GPUPH") && soc.gpu_frequencies.len() > 1 {- result.gpu_usage = calculate_frequency(&channel.states, &soc.gpu_frequencies[1..]);- }- } else if channel.group == obfstr!("Energy Model") {- let watts = watts(channel.integer_value, channel.unit.trim(), window_milliseconds);- if channel.name == obfstr!("GPU Energy") {- result.gpu_power += watts;- } else if channel.name.ends_with(obfstr!("CPU Energy")) {- result.cpu_power += watts;- } else if channel.name.starts_with(obfstr!("ANE")) {- result.ane_power += watts;- } else if channel.name.starts_with(obfstr!("DRAM")) {- result.ram_power += watts;- } else if channel.name.starts_with(obfstr!("GPU SRAM")) {- result.gpu_ram_power += watts;- }- } else if channel.group == obfstr!("AMC Stats") {- accumulate_amc_bandwidth(channel.integer_value, &channel.name, &mut bandwidth);- } else if channel.group == obfstr!("PMP") {- accumulate_pmp(&channel.states, &channel.subgroup, &channel.name, &mut bandwidth, &mut result);- }- }-- ecpu_readings.retain(|&(_, percent)| percent > 0.0);- result.ecpu_usage = average_cluster_frequency(&ecpu_readings, &soc.ecpu_frequencies);- result.pcpu_usage = average_cluster_frequency(&pcpu_readings, &soc.pcpu_frequencies);- let efficiency_cores = soc.ecpu_cores as f32;- let performance_cores = soc.pcpu_cores as f32;- result.cpu_usage_percent = divide_or_zero(- result.ecpu_usage.1 * efficiency_cores + result.pcpu_usage.1 * performance_cores,- efficiency_cores + performance_cores,- );- result.total_power = result.cpu_power + result.gpu_power + result.ane_power;-- bandwidth.finish(window_milliseconds, &mut result);- if result.ane_active_percent == 0.0 && result.ane_power > 0.0 {- result.ane_active_percent = (result.ane_power / ANE_MAX_POWER_WATTS * 100.0).min(100.0);- }- result- }-}--fn watts(- energy: i64,- unit: &str,- window_milliseconds: u64,-) -> f32 {- let power = energy as f32 / (window_milliseconds as f32 / 1000.0);- if unit == obfstr!("mJ") {- power / 1e3- } else if unit == obfstr!("uJ") {- power / 1e6- } else if unit == obfstr!("nJ") {- power / 1e9- } else {- 0.0- }-}diff --git a/crates/keisoku/src/ioreport/sample.rs b/crates/keisoku/src/ioreport/sample.rsdeleted file mode 100644index 7dc7ea481..000000000--- a/crates/keisoku/src/ioreport/sample.rs+++ /dev/null@@ -1,18 +0,0 @@-#[derive(Debug, Default, Clone)]-pub struct SocSample {- pub cpu_power: f32,- pub gpu_power: f32,- pub ane_power: f32,- pub ram_power: f32,- pub gpu_ram_power: f32,- pub total_power: f32,- pub ecpu_usage: (u32, f32),- pub pcpu_usage: (u32, f32),- pub cpu_usage_percent: f32,- pub gpu_usage: (u32, f32),- pub ane_active_percent: f32,- pub ane_read_gbps: f32,- pub ane_write_gbps: f32,- pub dram_read_gbps: f32,- pub dram_write_gbps: f32,-}diff --git a/crates/keisoku/src/ioreport/subscription.rs b/crates/keisoku/src/ioreport/subscription.rsdeleted file mode 100644index 5b1018fa9..000000000--- a/crates/keisoku/src/ioreport/subscription.rs+++ /dev/null@@ -1,56 +0,0 @@-use obfstr::obfstr;-use objc2_core_foundation::{CFDictionary, CFMutableDictionary, CFRetained, CFString, CFType};--use super::IoReportFunctions;--pub(super) struct Channels(CFRetained<CFMutableDictionary>);--impl Channels {- fn new(functions: &IoReportFunctions) -> Option<Self> {- let mut groups: Vec<CFRetained<CFDictionary>> = Vec::with_capacity(5);- for (group, subgroup) in [- (obfstr!("Energy Model"), None::<&str>),- (obfstr!("CPU Stats"), Some(obfstr!("CPU Core Performance States"))),- (obfstr!("GPU Stats"), Some(obfstr!("GPU Performance States"))),- (obfstr!("AMC Stats"), None),- (obfstr!("PMP"), None),- ] {- let group_name = CFString::from_str(group);- let subgroup_name = subgroup.map(CFString::from_str);- if let Some(group_channels) = functions.copy_channels_in_group(&group_name, subgroup_name.as_deref()) {- groups.push(group_channels);- }- }-- let (first, rest) = groups.split_first()?;- for other in rest {- functions.merge_channels(first, other);- }- let channels = unsafe { CFMutableDictionary::new_copy(None, first.count(), Some(&**first)) }?;- Some(Self(channels))- }-}--pub(super) struct Subscription {- handle: CFRetained<CFType>,- channels: Channels,-}--impl Subscription {- pub(super) fn new(functions: &IoReportFunctions) -> Option<Self> {- let channels = Channels::new(functions)?;- let (handle, subscribed) = functions.create_subscription(&channels.0)?;- drop(subscribed);- Some(Self {- handle,- channels,- })- }-- pub(super) fn snapshot(- &self,- functions: &IoReportFunctions,- ) -> Option<CFRetained<CFDictionary>> {- functions.create_samples(&self.handle, &self.channels.0)- }-}diff --git a/crates/keisoku/src/lib.rs b/crates/keisoku/src/lib.rsindex 67ed5793b..448a1ffc0 100644--- a/crates/keisoku/src/lib.rs+++ b/crates/keisoku/src/lib.rs@@ -1,81 +1,24 @@-mod collector;-mod component;+#[cfg(not(target_vendor = "apple"))]+compile_error!("keisoku supports Apple platforms only (macOS and iOS)");++mod device;+mod marker;mod metrics;-mod recorder;+mod sources;+mod sys;++mod component;+mod power_meter;mod sensor;-mod snapshot;mod units;-#[cfg(target_os = "macos")]-mod cf;-#[cfg(target_vendor = "apple")]-mod client;-#[cfg(target_os = "macos")]-mod cpu_load;-#[cfg(target_os = "macos")]-mod ioreport;-#[cfg(target_os = "macos")]-mod smc;-#[cfg(target_os = "macos")]-mod soc;-#[cfg(target_vendor = "apple")]-mod sys;--pub use collector::Collector;pub use component::{Component, classify};-pub use metrics::{- BandwidthMetrics, BatteryMetrics, CpuMetrics, Fan, FanMetrics, GpuMetrics, MemoryMetrics, NeuralEngineMetrics,- PowerMetrics, Temperatures, ThermalPressure,+pub use device::Device;+#[cfg(target_os = "macos")]+pub use marker::{+ Ane, AneBandwidth, Cons, Cpu, DramBytes, DramHistogram, DramRead, DramWrite, EnergyRail, Gpu, Nil, Ram, Sample,};-pub use recorder::{Config, Device, RecorderHandle, Session, start};-pub use sensor::{Sensor, SensorKind, current_sensors, thermal_sensors, voltage_sensors};-pub use snapshot::Snapshot;-pub use units::{Bytes, Celsius, GigabytesPerSecond, Megahertz, Milliseconds, Percent, Rpm, Watts};--#[cfg(target_vendor = "apple")]-pub fn sensors(kind: SensorKind) -> Vec<Sensor> {- client::collect(kind)-}--#[cfg(target_vendor = "apple")]-pub fn sensors_available() -> bool {- client::is_available()-}--#[cfg(not(target_vendor = "apple"))]-pub fn sensors(_kind: SensorKind) -> Vec<Sensor> {- Vec::new()-}--#[cfg(not(target_vendor = "apple"))]-pub fn sensors_available() -> bool {- false-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn sensor_queries_do_not_panic() {- let _ = sensors_available();- for kind in [SensorKind::Temperature, SensorKind::Voltage, SensorKind::Current] {- for sensor in sensors(kind) {- assert_eq!(sensor.kind, kind);- assert!(sensor.value.is_finite());- }- }- }-- #[test]- fn one_snapshot_is_well_formed() {- let mut collector = Collector::new();- let snapshot = collector.sample(std::time::Duration::from_millis(120));- if let Some(power) = &snapshot.power {- assert!(power.total.value().is_finite() && power.total.value() >= 0.0);- }- if let Some(memory) = &snapshot.memory {- assert!(memory.ram_total >= memory.ram_usage);- }- }-}+pub use metrics::{BatteryMetrics, Fan, FanMetrics, MemoryMetrics, ThermalPressure};+pub use power_meter::{PowerMeter, PowerReading};+pub use sensor::{Sensor, SensorKind, thermal_sensors};+pub use units::{Bytes, GigabytesPerSecond, Joules, Percent, Rpm, Watts};diff --git a/crates/keisoku/src/marker/channel_set.rs b/crates/keisoku/src/marker/channel_set.rsnew file mode 100644index 000000000..f6f15f42b--- /dev/null+++ b/crates/keisoku/src/marker/channel_set.rs@@ -0,0 +1,70 @@+use super::{+ Cons as ConsType, Nil as NilType,+ typelist::{ChannelMetric, ChannelSet, Values},+};+use crate::sys::ioreport::{+ IoReportGroups,+ decode::{Channel, RawChannel},+};++pub trait IntervalChannel: ChannelMetric {+ const CHANNEL: Channel;+ const GROUP: IoReportGroups;++ fn default_value() -> Self::Value;++ fn fold(+ value: &mut Self::Value,+ raw: &RawChannel,+ );+}++pub trait IntervalSet: ChannelSet {+ const GROUPS: IoReportGroups;++ fn default_values() -> Self::Value;++ fn apply(+ channel: Channel,+ raw: &RawChannel,+ values: &mut Self::Value,+ );+}++impl IntervalSet for NilType {+ const GROUPS: IoReportGroups = IoReportGroups::empty();++ fn default_values() -> Self::Value {+ NilType+ }++ fn apply(+ _channel: Channel,+ _raw: &RawChannel,+ _values: &mut Self::Value,+ ) {+ }+}++impl<H, T> IntervalSet for ConsType<H, T>+where+ H: IntervalChannel,+ T: IntervalSet,+{+ const GROUPS: IoReportGroups = H::GROUP.union(T::GROUPS);++ fn default_values() -> Self::Value {+ Values::new(H::default_value(), T::default_values())+ }++ fn apply(+ channel: Channel,+ raw: &RawChannel,+ values: &mut Self::Value,+ ) {+ if channel == H::CHANNEL {+ H::fold(&mut values.head, raw);+ }+ T::apply(channel, raw, &mut values.tail);+ }+}diff --git a/crates/keisoku/src/marker/channels/ane_bandwidth.rs b/crates/keisoku/src/marker/channels/ane_bandwidth.rsnew file mode 100644index 000000000..d601d77c7--- /dev/null+++ b/crates/keisoku/src/marker/channels/ane_bandwidth.rs@@ -0,0 +1,31 @@+use super::super::{channel_set::IntervalChannel, typelist::ChannelMetric};+use crate::{+ sys::ioreport::{+ IoReportGroups,+ decode::{Channel, RawChannel, residency_active_percent},+ },+ units::Percent,+};++pub struct AneBandwidth;++impl ChannelMetric for AneBandwidth {+ type Value = Percent;+ const TYPE_BIT: u128 = 1 << 4;+}++impl IntervalChannel for AneBandwidth {+ const CHANNEL: Channel = Channel::AneBandwidth;+ const GROUP: IoReportGroups = IoReportGroups::PMP;++ fn default_value() -> Self::Value {+ Percent(0.0)+ }++ fn fold(+ value: &mut Self::Value,+ raw: &RawChannel,+ ) {+ *value = Percent(value.value().max(residency_active_percent(&raw.states)));+ }+}diff --git a/crates/keisoku/src/marker/channels/dram_bytes.rs b/crates/keisoku/src/marker/channels/dram_bytes.rsnew file mode 100644index 000000000..0a1d93f35--- /dev/null+++ b/crates/keisoku/src/marker/channels/dram_bytes.rs@@ -0,0 +1,37 @@+use core::marker::PhantomData;++use super::super::{channel_set::IntervalChannel, typelist::ChannelMetric};+use crate::{+ sys::ioreport::{+ IoReportGroups,+ decode::{Channel, RawChannel},+ kinds::FlowKind,+ },+ units::Bytes,+};++pub struct DramBytes<F>(PhantomData<F>);++impl<F: FlowKind> ChannelMetric for DramBytes<F> {+ type Value = Bytes;+ const TYPE_BIT: u128 = F::TYPE_BIT_BYTES;+}++impl<F: FlowKind> IntervalChannel for DramBytes<F> {+ const CHANNEL: Channel = Channel::DramBytes(F::FLOW);+ const GROUP: IoReportGroups = IoReportGroups::AMC_STATS.union(IoReportGroups::PMP);++ fn default_value() -> Self::Value {+ Bytes(0)+ }++ fn fold(+ value: &mut Self::Value,+ raw: &RawChannel,+ ) {+ let bytes = raw.integer_value;+ if bytes > 0 {+ *value = Bytes(value.value() + bytes as u64);+ }+ }+}diff --git a/crates/keisoku/src/marker/channels/dram_histogram.rs b/crates/keisoku/src/marker/channels/dram_histogram.rsnew file mode 100644index 000000000..210dfed4b--- /dev/null+++ b/crates/keisoku/src/marker/channels/dram_histogram.rs@@ -0,0 +1,34 @@+use core::marker::PhantomData;++use super::super::{channel_set::IntervalChannel, typelist::ChannelMetric};+use crate::{+ sys::ioreport::{+ IoReportGroups,+ decode::{Channel, RawChannel, residency_weighted_gbps},+ kinds::FlowKind,+ },+ units::GigabytesPerSecond,+};++pub struct DramHistogram<F>(PhantomData<F>);++impl<F: FlowKind> ChannelMetric for DramHistogram<F> {+ type Value = GigabytesPerSecond;+ const TYPE_BIT: u128 = F::TYPE_BIT_HIST;+}++impl<F: FlowKind> IntervalChannel for DramHistogram<F> {+ const CHANNEL: Channel = Channel::DramHistogram(F::FLOW);+ const GROUP: IoReportGroups = IoReportGroups::PMP;++ fn default_value() -> Self::Value {+ GigabytesPerSecond(0.0)+ }++ fn fold(+ value: &mut Self::Value,+ raw: &RawChannel,+ ) {+ *value = GigabytesPerSecond(value.value().max(residency_weighted_gbps(&raw.states)));+ }+}diff --git a/crates/keisoku/src/marker/channels/energy_rail.rs b/crates/keisoku/src/marker/channels/energy_rail.rsnew file mode 100644index 000000000..59f2788c4--- /dev/null+++ b/crates/keisoku/src/marker/channels/energy_rail.rs@@ -0,0 +1,34 @@+use core::marker::PhantomData;++use super::super::{channel_set::IntervalChannel, typelist::ChannelMetric};+use crate::{+ sys::ioreport::{+ IoReportGroups,+ decode::{Channel, RawChannel, energy_joules},+ kinds::RailKind,+ },+ units::Joules,+};++pub struct EnergyRail<R>(PhantomData<R>);++impl<R: RailKind> ChannelMetric for EnergyRail<R> {+ type Value = Joules;+ const TYPE_BIT: u128 = R::TYPE_BIT;+}++impl<R: RailKind> IntervalChannel for EnergyRail<R> {+ const CHANNEL: Channel = Channel::EnergyRail(R::RAIL);+ const GROUP: IoReportGroups = IoReportGroups::ENERGY_MODEL;++ fn default_value() -> Self::Value {+ Joules(0.0)+ }++ fn fold(+ value: &mut Self::Value,+ raw: &RawChannel,+ ) {+ *value = Joules(value.value() + energy_joules(raw.integer_value, raw.unit) as f32);+ }+}diff --git a/crates/keisoku/src/marker/channels/mod.rs b/crates/keisoku/src/marker/channels/mod.rsnew file mode 100644index 000000000..07d429221--- /dev/null+++ b/crates/keisoku/src/marker/channels/mod.rs@@ -0,0 +1,11 @@+mod ane_bandwidth;+mod dram_bytes;+mod dram_histogram;+mod energy_rail;++pub use ane_bandwidth::AneBandwidth;+pub use dram_bytes::DramBytes;+pub use dram_histogram::DramHistogram;+pub use energy_rail::EnergyRail;++pub use crate::sys::ioreport::kinds::{Ane, Cpu, DramRead, DramWrite, Gpu, Ram};diff --git a/crates/keisoku/src/marker/mod.rs b/crates/keisoku/src/marker/mod.rsnew file mode 100644index 000000000..aad4138f6--- /dev/null+++ b/crates/keisoku/src/marker/mod.rs@@ -0,0 +1,9 @@+mod channel_set;+mod channels;+mod sample;+mod typelist;++pub(crate) use channel_set::IntervalSet;+pub use channels::{Ane, AneBandwidth, Cpu, DramBytes, DramHistogram, DramRead, DramWrite, EnergyRail, Gpu, Ram};+pub use sample::Sample;+pub use typelist::{Cons, Nil};diff --git a/crates/keisoku/src/marker/sample.rs b/crates/keisoku/src/marker/sample.rsnew file mode 100644index 000000000..f2474e812--- /dev/null+++ b/crates/keisoku/src/marker/sample.rs@@ -0,0 +1,28 @@+use core::marker::PhantomData;++use super::typelist::{ChannelMetric, ChannelSet, ValueList};++/// Typed IOReport channel values selected by [`Select!`](crate::Select).+#[must_use]+pub struct Sample<M: ChannelSet> {+ values: M::Value,+ marker: PhantomData<M>,+}++impl<M: ChannelSet> Sample<M> {+ pub(crate) fn new(values: M::Value) -> Self {+ Self {+ values,+ marker: PhantomData,+ }+ }++ /// Returns the value for channel marker `T`.+ ///+ /// # Panics+ ///+ /// Panics if `T` was not included in the `Select!` list used to create this sample.+ pub fn get<T: ChannelMetric>(&self) -> &T::Value {+ self.values.get::<T>().expect("channel not in sample")+ }+}diff --git a/crates/keisoku/src/marker/typelist.rs b/crates/keisoku/src/marker/typelist.rsnew file mode 100644index 000000000..66840b73f--- /dev/null+++ b/crates/keisoku/src/marker/typelist.rs@@ -0,0 +1,91 @@+use core::marker::PhantomData;+use std::any::{Any, TypeId};++pub struct Nil;+pub struct Cons<H, T>(PhantomData<(H, T)>);++pub struct Values<M: ChannelMetric, T> {+ pub(crate) head: M::Value,+ pub(crate) tail: T,+}++impl<M: ChannelMetric, T> Values<M, T> {+ pub(crate) fn new(+ head: M::Value,+ tail: T,+ ) -> Self {+ Self {+ head,+ tail,+ }+ }+}++pub trait ChannelMetric: 'static {+ type Value: 'static;+ const TYPE_BIT: u128;+}++pub trait ChannelSet {+ type Value: ValueList;+ const TYPE_MASK: u128;+}++impl ChannelSet for Nil {+ type Value = Nil;+ const TYPE_MASK: u128 = 0;+}++impl<H, T> ChannelSet for Cons<H, T>+where+ H: ChannelMetric,+ T: ChannelSet,+{+ type Value = Values<H, T::Value>;+ const TYPE_MASK: u128 = {+ assert!(H::TYPE_BIT & T::TYPE_MASK == 0, "duplicate channel in Select!");+ H::TYPE_BIT | T::TYPE_MASK+ };+}++pub trait ValueList {+ fn get<T: ChannelMetric>(&self) -> Option<&T::Value>;+}++impl ValueList for Nil {+ fn get<T: ChannelMetric>(&self) -> Option<&T::Value> {+ None+ }+}++impl<H, Tail> ValueList for Values<H, Tail>+where+ H: ChannelMetric,+ Tail: ValueList,+{+ fn get<T: ChannelMetric>(&self) -> Option<&T::Value> {+ if TypeId::of::<H>() == TypeId::of::<T>() {+ return (&self.head as &dyn Any).downcast_ref::<T::Value>();+ }+ self.tail.get::<T>()+ }+}++/// Builds a compile-time list of IOReport channel markers for [`Device::interval_measurement`](crate::Device::interval_measurement).+///+/// # Examples+///+/// ```ignore+/// use keisoku::{Cpu, Device, EnergyRail, Select};+///+/// let mut handle = Device::interval_measurement::<Select![EnergyRail<Cpu>]>();+/// ```+#[macro_export]+macro_rules! Select {+ () => {+ $crate::Nil+ };+ ($head:ty $(, $rest:ty)* $(,)?) => {+ $crate::Cons<$head, $crate::Select![$($rest),*]>+ };+}diff --git a/crates/keisoku/src/metrics/bandwidth.rs b/crates/keisoku/src/metrics/bandwidth.rsdeleted file mode 100644index d8ec13248..000000000--- a/crates/keisoku/src/metrics/bandwidth.rs+++ /dev/null@@ -1,9 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::units::GigabytesPerSecond;--#[derive(Debug, Default, Clone, Serialize, Deserialize)]-pub struct BandwidthMetrics {- pub dram_read: GigabytesPerSecond,- pub dram_write: GigabytesPerSecond,-}diff --git a/crates/keisoku/src/metrics/battery.rs b/crates/keisoku/src/metrics/battery.rsindex e0f4f0357..0de92101c 100644--- a/crates/keisoku/src/metrics/battery.rs+++ b/crates/keisoku/src/metrics/battery.rs@@ -9,62 +9,3 @@ pub struct BatteryMetrics {pub charging: bool,pub on_ac_power: bool,}--#[cfg(target_os = "macos")]-pub(crate) fn read() -> Option<BatteryMetrics> {- use objc2_core_foundation::{CFBoolean, CFNumber, CFString, CFType};- use objc2_io_kit::{- IOPSCopyPowerSourcesInfo, IOPSCopyPowerSourcesList, IOPSGetPowerSourceDescription, kIOPSCurrentCapacityKey,- kIOPSInternalBatteryType, kIOPSIsChargingKey, kIOPSMaxCapacityKey, kIOPSPowerSourceStateKey, kIOPSTypeKey,- };-- use crate::cf::dictionary_get;-- let info = IOPSCopyPowerSourcesInfo()?;- let info_ref: &CFType = &info;- let list = unsafe { IOPSCopyPowerSourcesList(Some(info_ref)) }?;- let internal = kIOPSInternalBatteryType.to_str().ok()?;-- for index in 0..list.count() {- let source = unsafe { list.value_at_index(index) };- let Some(source) = (unsafe { (source as *const CFType).as_ref() }) else {- continue;- };- let Some(description) = (unsafe { IOPSGetPowerSourceDescription(Some(info_ref), Some(source)) }) else {- continue;- };- let string =- |key: &core::ffi::CStr| dictionary_get::<CFString>(&description, key.to_str().ok()?).map(|s| s.to_string());- let number = |key: &core::ffi::CStr| {- dictionary_get::<CFNumber>(&description, key.to_str().ok()?).and_then(|n| n.as_i64())- };- let boolean =- |key: &core::ffi::CStr| dictionary_get::<CFBoolean>(&description, key.to_str().ok()?).map(|b| b.value());-- if string(kIOPSTypeKey)? != internal {- continue;- }- let current = number(kIOPSCurrentCapacityKey)?;- let maximum = number(kIOPSMaxCapacityKey)?;- let charging = boolean(kIOPSIsChargingKey).unwrap_or(false);- let on_ac_power = string(kIOPSPowerSourceStateKey).is_some_and(|state| state.eq_ignore_ascii_case("AC Power"));- let percent = if maximum > 0 {- (current * 100 / maximum) as f32- } else {- 0.0- };-- return Some(BatteryMetrics {- present: true,- percent: Percent(percent),- charging,- on_ac_power,- });- }- None-}--#[cfg(not(target_os = "macos"))]-pub(crate) fn read() -> Option<BatteryMetrics> {- None-}diff --git a/crates/keisoku/src/metrics/cpu.rs b/crates/keisoku/src/metrics/cpu.rsdeleted file mode 100644index 84f27ab66..000000000--- a/crates/keisoku/src/metrics/cpu.rs+++ /dev/null@@ -1,13 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::units::{Megahertz, Percent};--#[derive(Debug, Default, Clone, Serialize, Deserialize)]-pub struct CpuMetrics {- pub usage: Percent,- pub ecpu_frequency: Megahertz,- pub ecpu_usage: Percent,- pub pcpu_frequency: Megahertz,- pub pcpu_usage: Percent,- pub per_core: Vec<Percent>,-}diff --git a/crates/keisoku/src/metrics/fans.rs b/crates/keisoku/src/metrics/fan.rssimilarity index 100%rename from crates/keisoku/src/metrics/fans.rsrename to crates/keisoku/src/metrics/fan.rsdiff --git a/crates/keisoku/src/metrics/gpu.rs b/crates/keisoku/src/metrics/gpu.rsdeleted file mode 100644index 6d13dd2e5..000000000--- a/crates/keisoku/src/metrics/gpu.rs+++ /dev/null@@ -1,9 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::units::{Megahertz, Percent};--#[derive(Debug, Default, Clone, Serialize, Deserialize)]-pub struct GpuMetrics {- pub frequency: Megahertz,- pub usage: Percent,-}diff --git a/crates/keisoku/src/metrics/memory.rs b/crates/keisoku/src/metrics/memory.rsindex 3eb32ed88..2d556e022 100644--- a/crates/keisoku/src/metrics/memory.rs+++ b/crates/keisoku/src/metrics/memory.rs@@ -9,86 +9,3 @@ pub struct MemoryMetrics {pub swap_total: Bytes,pub swap_usage: Bytes,}--#[cfg(target_os = "macos")]-pub(crate) fn read() -> Option<MemoryMetrics> {- let mut ram_total = 0u64;- unsafe {- let mut name = [libc::CTL_HW, libc::HW_MEMSIZE];- let mut size = core::mem::size_of::<u64>();- if libc::sysctl(- name.as_mut_ptr(),- name.len() as _,- &mut ram_total as *mut _ as *mut _,- &mut size,- core::ptr::null_mut(),- 0,- ) != 0- {- return None;- }- }-- let ram_usage = unsafe {- let mut count: u32 = libc::HOST_VM_INFO64_COUNT as _;- let mut statistics = core::mem::zeroed::<libc::vm_statistics64>();- #[allow(deprecated)]- let result = libc::host_statistics64(- libc::mach_host_self(),- libc::HOST_VM_INFO64,- &mut statistics as *mut _ as *mut _,- &mut count,- );- if result != 0 {- return None;- }- let page_size = libc::sysconf(libc::_SC_PAGESIZE) as u64;- (statistics.active_count as u64- + statistics.inactive_count as u64- + statistics.wire_count as u64- + statistics.speculative_count as u64- + statistics.compressor_page_count as u64- - statistics.purgeable_count as u64- - statistics.external_page_count as u64)- * page_size- };-- let (swap_usage, swap_total) = unsafe {- let mut name = [libc::CTL_VM, libc::VM_SWAPUSAGE];- let mut size = core::mem::size_of::<libc::xsw_usage>();- let mut swap = core::mem::zeroed::<libc::xsw_usage>();- if libc::sysctl(- name.as_mut_ptr(),- name.len() as _,- &mut swap as *mut _ as *mut _,- &mut size,- core::ptr::null_mut(),- 0,- ) == 0- {- (swap.xsu_used, swap.xsu_total)- } else {- (0, 0)- }- };-- Some(MemoryMetrics {- ram_total: Bytes(ram_total),- ram_usage: Bytes(ram_usage),- swap_total: Bytes(swap_total),- swap_usage: Bytes(swap_usage),- })-}--#[cfg(not(target_os = "macos"))]-pub(crate) fn read() -> Option<MemoryMetrics> {- use sysinfo::System;- let mut system = System::new();- system.refresh_memory();- Some(MemoryMetrics {- ram_total: Bytes(system.total_memory()),- ram_usage: Bytes(system.used_memory()),- swap_total: Bytes(system.total_swap()),- swap_usage: Bytes(system.used_swap()),- })-}diff --git a/crates/keisoku/src/metrics/mod.rs b/crates/keisoku/src/metrics/mod.rsindex 0e09cf6cf..09bbbf337 100644--- a/crates/keisoku/src/metrics/mod.rs+++ b/crates/keisoku/src/metrics/mod.rs@@ -1,24 +1,9 @@-mod bandwidth;mod battery;-mod cpu;-mod fans;-mod gpu;+mod fan;mod memory;-mod neural_engine;-mod power;-mod temperatures;mod thermal_pressure;-pub use bandwidth::BandwidthMetrics;pub use battery::BatteryMetrics;-pub(crate) use battery::read as read_battery;-pub use cpu::CpuMetrics;-pub use fans::{Fan, FanMetrics};-pub use gpu::GpuMetrics;+pub use fan::{Fan, FanMetrics};pub use memory::MemoryMetrics;-pub(crate) use memory::read as read_memory;-pub use neural_engine::NeuralEngineMetrics;-pub use power::PowerMetrics;-pub use temperatures::Temperatures;pub use thermal_pressure::ThermalPressure;-pub(crate) use thermal_pressure::read as read_thermal_pressure;diff --git a/crates/keisoku/src/metrics/neural_engine.rs b/crates/keisoku/src/metrics/neural_engine.rsdeleted file mode 100644index 4ae9aee17..000000000--- a/crates/keisoku/src/metrics/neural_engine.rs+++ /dev/null@@ -1,11 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::units::{GigabytesPerSecond, Percent, Watts};--#[derive(Debug, Default, Clone, Serialize, Deserialize)]-pub struct NeuralEngineMetrics {- pub power: Watts,- pub active: Percent,- pub read_bandwidth: GigabytesPerSecond,- pub write_bandwidth: GigabytesPerSecond,-}diff --git a/crates/keisoku/src/metrics/power.rs b/crates/keisoku/src/metrics/power.rsdeleted file mode 100644index d8bc4e67b..000000000--- a/crates/keisoku/src/metrics/power.rs+++ /dev/null@@ -1,16 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::units::Watts;--#[derive(Debug, Default, Clone, Serialize, Deserialize)]-pub struct PowerMetrics {- pub cpu: Watts,- pub gpu: Watts,- pub gpu_sram: Watts,- pub ane: Watts,- pub ram: Watts,-- pub total: Watts,-- pub package: Watts,-}diff --git a/crates/keisoku/src/metrics/temperatures.rs b/crates/keisoku/src/metrics/temperatures.rsdeleted file mode 100644index a89142aec..000000000--- a/crates/keisoku/src/metrics/temperatures.rs+++ /dev/null@@ -1,9 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::units::Celsius;--#[derive(Debug, Default, Clone, Serialize, Deserialize)]-pub struct Temperatures {- pub cpu_average: Option<Celsius>,- pub gpu_average: Option<Celsius>,-}diff --git a/crates/keisoku/src/metrics/thermal_pressure.rs b/crates/keisoku/src/metrics/thermal_pressure.rsindex 0dcac88c4..096860597 100644--- a/crates/keisoku/src/metrics/thermal_pressure.rs+++ b/crates/keisoku/src/metrics/thermal_pressure.rs@@ -8,52 +8,3 @@ pub enum ThermalPressure {Trapping,Sleeping,}--#[cfg(target_vendor = "apple")]-impl ThermalPressure {- fn from_level(level: u64) -> Option<Self> {- match level {- 0 => Some(ThermalPressure::Nominal),- 1 => Some(ThermalPressure::Moderate),- 2 => Some(ThermalPressure::Heavy),- 3 => Some(ThermalPressure::Trapping),- 4 => Some(ThermalPressure::Sleeping),- _ => None,- }- }-}--#[cfg(target_vendor = "apple")]-pub(crate) fn read() -> Option<ThermalPressure> {- use core::ffi::c_char;-- unsafe extern "C" {- fn notify_register_check(- name: *const c_char,- out_token: *mut i32,- ) -> u32;- fn notify_get_state(- token: i32,- out_state: *mut u64,- ) -> u32;- fn notify_cancel(token: i32) -> u32;- }-- let name = std::ffi::CString::new("com.apple.system.thermalpressurelevel").ok()?;- let mut token = 0i32;- if unsafe { notify_register_check(name.as_ptr(), &mut token) } != 0 {- return None;- }- let mut level = 0u64;- let result = unsafe { notify_get_state(token, &mut level) };- unsafe { notify_cancel(token) };- if result != 0 {- return None;- }- ThermalPressure::from_level(level)-}--#[cfg(not(target_vendor = "apple"))]-pub(crate) fn read() -> Option<ThermalPressure> {- None-}diff --git a/crates/keisoku/src/power_meter.rs b/crates/keisoku/src/power_meter.rsnew file mode 100644index 000000000..791981690--- /dev/null+++ b/crates/keisoku/src/power_meter.rs@@ -0,0 +1,181 @@+use crate::units::{Joules, Watts};++pub struct PowerReading {+ pub cpu: Option<Watts>,+ pub gpu: Option<Watts>,+ pub ane: Option<Watts>,+ pub ram: Option<Watts>,+ pub total: Watts,+ pub energy: Joules,+ pub samples: u64,+}++pub struct PowerMeter {+ inner: inner::Inner,+}++impl PowerMeter {+ pub fn new() -> Self {+ Self {+ inner: inner::Inner::new(),+ }+ }++ pub fn start(&mut self) {+ self.inner.start();+ }++ pub fn stop(&mut self) -> Option<PowerReading> {+ self.inner.stop()+ }+}++impl Default for PowerMeter {+ fn default() -> Self {+ Self::new()+ }+}++#[cfg(target_os = "macos")]+mod inner {+ use super::PowerReading;+ use crate::{+ Device, Select,+ marker::{Ane, Cpu, EnergyRail, Gpu, Ram},+ units::{Joules, Watts},+ };++ type Rails = Select![EnergyRail<Cpu>, EnergyRail<Gpu>, EnergyRail<Ane>, EnergyRail<Ram>];++ pub(super) struct Inner {+ handle: Option<crate::device::IntervalHandle<Rails>>,+ }++ impl Inner {+ pub(super) fn new() -> Self {+ Self {+ handle: None,+ }+ }++ pub(super) fn start(&mut self) {+ let mut handle = Device::interval_measurement::<Rails>();+ handle.start();+ self.handle = Some(handle);+ }++ pub(super) fn stop(&mut self) -> Option<PowerReading> {+ let mut handle = self.handle.take()?;+ let elapsed = handle.elapsed().as_secs_f64().max(0.001);+ let sample = handle.stop()?;+ let cpu_j = sample.get::<EnergyRail<Cpu>>().value() as f64;+ let gpu_j = sample.get::<EnergyRail<Gpu>>().value() as f64;+ let ane_j = sample.get::<EnergyRail<Ane>>().value() as f64;+ let ram_j = sample.get::<EnergyRail<Ram>>().value() as f64;+ let total_j = cpu_j + gpu_j + ane_j + ram_j;+ let to_watts = |joules: f64| Watts((joules / elapsed) as f32);+ Some(PowerReading {+ cpu: Some(to_watts(cpu_j)),+ gpu: Some(to_watts(gpu_j)),+ ane: Some(to_watts(ane_j)),+ ram: Some(to_watts(ram_j)),+ total: to_watts(total_j),+ energy: Joules(total_j as f32),+ samples: 1,+ })+ }+ }+}++#[cfg(not(target_os = "macos"))]+mod inner {+ use std::{+ sync::{+ Arc, Mutex,+ atomic::{AtomicBool, Ordering},+ },+ thread::{self, JoinHandle},+ time::{Duration, Instant},+ };++ use super::PowerReading;+ use crate::{+ Device,+ units::{Joules, Watts},+ };++ const SAMPLE_INTERVAL: Duration = Duration::from_millis(100);++ #[derive(Default)]+ struct Accumulator {+ energy_joules: f64,+ elapsed_seconds: f64,+ samples: u64,+ }++ pub(super) struct Inner {+ running: Arc<AtomicBool>,+ accumulator: Arc<Mutex<Accumulator>>,+ worker: Option<JoinHandle<()>>,+ }++ impl Inner {+ pub(super) fn new() -> Self {+ Self {+ running: Arc::new(AtomicBool::new(false)),+ accumulator: Arc::new(Mutex::new(Accumulator::default())),+ worker: None,+ }+ }++ pub(super) fn start(&mut self) {+ *self.accumulator.lock().expect("power meter accumulator poisoned") = Accumulator::default();+ self.running.store(true, Ordering::Relaxed);+ let running = self.running.clone();+ let accumulator = self.accumulator.clone();+ self.worker = Some(thread::spawn(move || {+ let mut device = Device::new();+ let mut last = Instant::now();+ while running.load(Ordering::Relaxed) {+ thread::sleep(SAMPLE_INTERVAL);+ let now = Instant::now();+ let seconds = now.duration_since(last).as_secs_f64();+ last = now;+ let Some(watts) = device.rail_power() else {+ continue;+ };+ let watts = watts.value() as f64;+ let mut accumulator = accumulator.lock().expect("power meter accumulator poisoned");+ accumulator.energy_joules += watts * seconds;+ accumulator.elapsed_seconds += seconds;+ accumulator.samples += 1;+ }+ }));+ }++ pub(super) fn stop(&mut self) -> Option<PowerReading> {+ self.running.store(false, Ordering::Relaxed);+ if let Some(worker) = self.worker.take() {+ let _ = worker.join();+ }+ let accumulator = self.accumulator.lock().expect("power meter accumulator poisoned");+ if accumulator.samples == 0 {+ return None;+ }+ let total = if accumulator.elapsed_seconds > 0.0 {+ (accumulator.energy_joules / accumulator.elapsed_seconds) as f32+ } else {+ 0.0+ };+ Some(PowerReading {+ cpu: None,+ gpu: None,+ ane: None,+ ram: None,+ total: Watts(total),+ energy: Joules(accumulator.energy_joules as f32),+ samples: accumulator.samples,+ })+ }+ }+}diff --git a/crates/keisoku/src/recorder/config.rs b/crates/keisoku/src/recorder/config.rsdeleted file mode 100644index f63797b3a..000000000--- a/crates/keisoku/src/recorder/config.rs+++ /dev/null@@ -1,14 +0,0 @@-use std::time::Duration;--#[derive(Debug, Clone)]-pub struct Config {- pub interval: Duration,-}--impl Default for Config {- fn default() -> Self {- Self {- interval: Duration::from_millis(1000),- }- }-}diff --git a/crates/keisoku/src/recorder/device.rs b/crates/keisoku/src/recorder/device.rsdeleted file mode 100644index 7d908e543..000000000--- a/crates/keisoku/src/recorder/device.rs+++ /dev/null@@ -1,103 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::{Collector, units::Bytes};--#[derive(Debug, Default, Clone, Serialize, Deserialize)]-pub struct Device {- pub os: String,- pub chip: String,- pub ram_total: Bytes,- pub efficiency_cores: u8,- pub performance_cores: u8,- pub gpu_cores: u8,-}--impl Device {- pub(crate) fn detect(#[allow(unused_variables)] collector: &Collector) -> Device {- let os = sysinfo::System::long_os_version().unwrap_or_default();- let mut system = sysinfo::System::new_all();- system.refresh_all();- let chip = system.cpus().first().map(|c| c.brand().trim().to_string()).unwrap_or_default();- let ram_total = Bytes(system.total_memory());-- #[cfg(target_os = "macos")]- if let Some(soc) = collector.soc() {- return Device {- os,- chip: if soc.chip_name.is_empty() {- chip- } else {- soc.chip_name.clone()- },- ram_total,- efficiency_cores: soc.ecpu_cores,- performance_cores: soc.pcpu_cores,- gpu_cores: soc.gpu_cores,- };- }-- #[cfg(all(target_vendor = "apple", not(target_os = "macos")))]- #[allow(clippy::needless_return)]- {- let (performance_cores, efficiency_cores) = perflevel_cores();- return Device {- os,- chip: sysctl_string("hw.machine").filter(|model| !model.is_empty()).unwrap_or(chip),- ram_total,- efficiency_cores,- performance_cores,- gpu_cores: 0,- };- }-- #[cfg(not(all(target_vendor = "apple", not(target_os = "macos"))))]- Device {- os,- chip,- ram_total,- ..Default::default()- }- }-}--#[cfg(all(target_vendor = "apple", not(target_os = "macos")))]-fn sysctl_string(name: &str) -> Option<String> {- let name = std::ffi::CString::new(name).ok()?;- let mut len = 0usize;- let probe = unsafe { libc::sysctlbyname(name.as_ptr(), std::ptr::null_mut(), &mut len, std::ptr::null_mut(), 0) };- if probe != 0 || len == 0 {- return None;- }- let mut buffer = vec![0u8; len];- let read =- unsafe { libc::sysctlbyname(name.as_ptr(), buffer.as_mut_ptr().cast(), &mut len, std::ptr::null_mut(), 0) };- if read != 0 {- return None;- }- if let Some(nul) = buffer.iter().position(|&byte| byte == 0) {- buffer.truncate(nul);- }- String::from_utf8(buffer).ok()-}--#[cfg(all(target_vendor = "apple", not(target_os = "macos")))]-fn sysctl_u32(name: &str) -> Option<u32> {- let name = std::ffi::CString::new(name).ok()?;- let mut value = 0u32;- let mut len = std::mem::size_of::<u32>();- let read = unsafe {- libc::sysctlbyname(name.as_ptr(), std::ptr::addr_of_mut!(value).cast(), &mut len, std::ptr::null_mut(), 0)- };- (read == 0).then_some(value)-}--#[cfg(all(target_vendor = "apple", not(target_os = "macos")))]-fn perflevel_cores() -> (u8, u8) {- let performance = sysctl_u32("hw.perflevel0.logicalcpu").unwrap_or(0);- let efficiency = if sysctl_u32("hw.nperflevels").unwrap_or(1) > 1 {- sysctl_u32("hw.perflevel1.logicalcpu").unwrap_or(0)- } else {- 0- };- (performance as u8, efficiency as u8)-}diff --git a/crates/keisoku/src/recorder/handle.rs b/crates/keisoku/src/recorder/handle.rsdeleted file mode 100644index fb14de1df..000000000--- a/crates/keisoku/src/recorder/handle.rs+++ /dev/null@@ -1,74 +0,0 @@-use std::{- sync::{- Arc, Mutex,- atomic::{AtomicBool, Ordering},- },- time::{Duration, Instant},-};--use super::{Config, Session};-use crate::{Collector, snapshot::Snapshot, units::Milliseconds};--pub struct RecorderHandle {- interval: Duration,- stop_flag: Arc<AtomicBool>,- snapshots: Arc<Mutex<Vec<Snapshot>>>,- // Option so both stop() and Drop can take ownership to join.- worker: Option<std::thread::JoinHandle<()>>,-}--impl RecorderHandle {- pub fn stop(mut self) -> Session {- self.stop_flag.store(true, Ordering::Relaxed);- // Join so the in-flight sample is committed before we read the buffer, and so- // workers can't pile up across back-to-back recorders. Waits up to one interval.- if let Some(worker) = self.worker.take() {- let _ = worker.join();- }- let snapshots = self.snapshots.lock().map(|mut collected| std::mem::take(&mut *collected)).unwrap_or_default();- Session {- interval: Milliseconds(self.interval.as_millis() as u64),- snapshots,- }- }-}--impl Drop for RecorderHandle {- fn drop(&mut self) {- // Reached only when stop() was not called, e.g. an error path.- self.stop_flag.store(true, Ordering::Relaxed);- if let Some(worker) = self.worker.take() {- let _ = worker.join();- }- }-}--pub fn start(config: Config) -> RecorderHandle {- let interval = config.interval;- let stop_flag = Arc::new(AtomicBool::new(false));- let snapshots = Arc::new(Mutex::new(Vec::new()));-- let worker = {- let stop_flag = Arc::clone(&stop_flag);- let snapshots = Arc::clone(&snapshots);- std::thread::spawn(move || {- let mut collector = Collector::new();- // Start the clock after Collector::new() so elapsed excludes init overhead.- let started_at = Instant::now();- while !stop_flag.load(Ordering::Relaxed) {- let mut snapshot = collector.sample(interval);- snapshot.elapsed = Milliseconds(started_at.elapsed().as_millis() as u64);- if let Ok(mut collected) = snapshots.lock() {- collected.push(snapshot);- }- }- })- };-- RecorderHandle {- interval,- stop_flag,- snapshots,- worker: Some(worker),- }-}diff --git a/crates/keisoku/src/recorder/mod.rs b/crates/keisoku/src/recorder/mod.rsdeleted file mode 100644index 6ee7df232..000000000--- a/crates/keisoku/src/recorder/mod.rs+++ /dev/null@@ -1,9 +0,0 @@-mod config;-mod device;-mod handle;-mod session;--pub use config::Config;-pub use device::Device;-pub use handle::{RecorderHandle, start};-pub use session::Session;diff --git a/crates/keisoku/src/recorder/session.rs b/crates/keisoku/src/recorder/session.rsdeleted file mode 100644index 69f8d339c..000000000--- a/crates/keisoku/src/recorder/session.rs+++ /dev/null@@ -1,8 +0,0 @@-use crate::{snapshot::Snapshot, units::Milliseconds};--/// Snapshots collected between `start` and `stop`, with the sampling interval.-#[derive(Debug, Default, Clone)]-pub struct Session {- pub interval: Milliseconds,- pub snapshots: Vec<Snapshot>,-}diff --git a/crates/keisoku/src/sensor/kind.rs b/crates/keisoku/src/sensor/kind.rsindex 016f14314..1707ea60d 100644--- a/crates/keisoku/src/sensor/kind.rs+++ b/crates/keisoku/src/sensor/kind.rs@@ -1,6 +1,5 @@use serde::{Deserialize, Serialize};-#[cfg(target_vendor = "apple")]use crate::sys;#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]@@ -10,17 +9,6 @@ pub enum SensorKind {Current,}-impl SensorKind {- pub fn unit(self) -> &'static str {- match self {- SensorKind::Temperature => "°C",- SensorKind::Voltage => "V",- SensorKind::Current => "A",- }- }-}--#[cfg(target_vendor = "apple")]impl SensorKind {pub(crate) fn matching(self) -> (i32, i32) {match self {diff --git a/crates/keisoku/src/sensor/mod.rs b/crates/keisoku/src/sensor/mod.rsindex ff6735e2d..8e4ad3679 100644--- a/crates/keisoku/src/sensor/mod.rs+++ b/crates/keisoku/src/sensor/mod.rs@@ -4,14 +4,8 @@ mod reading;pub use kind::SensorKind;pub use reading::Sensor;-pub fn thermal_sensors() -> Vec<Sensor> {- crate::sensors(SensorKind::Temperature)-}--pub fn voltage_sensors() -> Vec<Sensor> {- crate::sensors(SensorKind::Voltage)-}+use crate::sys::hid::SensorReader;-pub fn current_sensors() -> Vec<Sensor> {- crate::sensors(SensorKind::Current)+pub fn thermal_sensors() -> Box<[Sensor]> {+ SensorReader::new(SensorKind::Temperature).map(|mut reader| reader.read()).unwrap_or_default()}diff --git a/crates/keisoku/src/snapshot.rs b/crates/keisoku/src/snapshot.rsdeleted file mode 100644index 00b4e791a..000000000--- a/crates/keisoku/src/snapshot.rs+++ /dev/null@@ -1,67 +0,0 @@-use serde::{Deserialize, Serialize};--use crate::{- metrics::{- BandwidthMetrics, BatteryMetrics, CpuMetrics, FanMetrics, GpuMetrics, MemoryMetrics, NeuralEngineMetrics,- PowerMetrics, Temperatures, ThermalPressure,- },- sensor::Sensor,- units::{Milliseconds, Watts},-};--#[derive(Debug, Default, Clone, Serialize, Deserialize)]-pub struct Snapshot {- pub elapsed: Milliseconds,- pub cpu: Option<CpuMetrics>,- pub gpu: Option<GpuMetrics>,- pub neural_engine: Option<NeuralEngineMetrics>,- pub power: Option<PowerMetrics>,- pub memory: Option<MemoryMetrics>,- pub bandwidth: Option<BandwidthMetrics>,- pub fans: Option<FanMetrics>,- pub battery: Option<BatteryMetrics>,- pub temperatures: Option<Temperatures>,- pub thermal_pressure: Option<ThermalPressure>,- pub sensors: Vec<Sensor>,- /// HID voltage rails; on iOS the only un-gated electrical signal, empty elsewhere.- #[serde(default)]- pub voltage: Vec<Sensor>,- /// HID current rails, paired with [`Snapshot::voltage`] by rail code.- #[serde(default)]- pub current: Vec<Sensor>,-}--impl Snapshot {- /// Sum of charger/battery watts from matched HID voltage×current rails- /// (e.g. `Charger VQ0u`×`Charger IQ0u`). An estimate, unlike IOReport [`Snapshot::power`].- pub fn rail_power(&self) -> Option<Watts> {- use crate::component::Component;- // Power magnitude so battery discharge (negative current when unplugged) counts too;- // the ceiling rejects mismatched-unit pairs, well above real charge/discharge.- const MAX_PLAUSIBLE_WATTS: f64 = 1000.0;- let split_area_code = |name: &str| name.rsplit_once(' ').map(|(area, code)| (area.to_owned(), code.to_owned()));- let is_battery_rail = |sensor: &&Sensor| matches!(sensor.component, Component::Charger | Component::Battery);-- let mut total_watts = 0f64;- for voltage_sensor in self.voltage.iter().filter(is_battery_rail) {- let Some((voltage_area, voltage_code)) = split_area_code(&voltage_sensor.name) else {- continue;- };- let Some(rail_code) = voltage_code.strip_prefix('V').filter(|code| !code.is_empty()) else {- continue;- };- for current_sensor in self.current.iter().filter(is_battery_rail) {- let Some((current_area, current_code)) = split_area_code(¤t_sensor.name) else {- continue;- };- if current_area == voltage_area && current_code.strip_prefix('I') == Some(rail_code) {- let watts = (voltage_sensor.value * current_sensor.value).abs();- if (0.0..=MAX_PLAUSIBLE_WATTS).contains(&watts) {- total_watts += watts;- }- }- }- }- (total_watts > 0.0).then_some(Watts(total_watts as f32))- }-}diff --git a/crates/keisoku/src/sources/battery.rs b/crates/keisoku/src/sources/battery.rsnew file mode 100644index 000000000..bb5d712af--- /dev/null+++ b/crates/keisoku/src/sources/battery.rs@@ -0,0 +1,11 @@+use crate::metrics::BatteryMetrics;++#[cfg(target_os = "macos")]+pub(crate) fn read_battery() -> Option<BatteryMetrics> {+ crate::sys::read_battery()+}++#[cfg(not(target_os = "macos"))]+pub(crate) fn read_battery() -> Option<BatteryMetrics> {+ None+}diff --git a/crates/keisoku/src/sources/deferred.rs b/crates/keisoku/src/sources/deferred.rsnew file mode 100644index 000000000..891611ea8--- /dev/null+++ b/crates/keisoku/src/sources/deferred.rs@@ -0,0 +1,18 @@+pub(super) struct Deferred<T> {+ slot: Option<T>,+ init: fn() -> T,+}++impl<T> Deferred<T> {+ pub(super) const fn new(init: fn() -> T) -> Self {+ Self {+ slot: None,+ init,+ }+ }++ pub(super) fn get(&mut self) -> &mut T {+ let init = self.init;+ self.slot.get_or_insert_with(init)+ }+}diff --git a/crates/keisoku/src/sources/interval.rs b/crates/keisoku/src/sources/interval.rsnew file mode 100644index 000000000..55af677e3--- /dev/null+++ b/crates/keisoku/src/sources/interval.rs@@ -0,0 +1,45 @@+use crate::{+ marker::IntervalSet,+ sys::ioreport::{IoReport, IoReportGroups, RawIOReportSample},+};++pub(crate) struct IntervalEngine {+ ioreport: Option<IoReport>,+}++pub(crate) struct IntervalSession {+ begin: Option<RawIOReportSample>,+}++impl IntervalEngine {+ pub(crate) fn new(groups: IoReportGroups) -> Self {+ Self {+ ioreport: (!groups.is_empty()).then(|| IoReport::for_groups(groups)).flatten(),+ }+ }++ pub(crate) fn begin(&self) -> IntervalSession {+ IntervalSession {+ begin: self.ioreport.as_ref().and_then(IoReport::snapshot),+ }+ }++ pub(crate) fn fold_end<M: IntervalSet>(+ &self,+ session: IntervalSession,+ values: &mut M::Value,+ ) {+ let Some(ioreport) = self.ioreport.as_ref() else {+ return;+ };+ let Some(begin) = session.begin.as_ref() else {+ return;+ };+ let Some(end) = ioreport.snapshot() else {+ return;+ };+ ioreport.for_each_channel(begin, &end, |channel, raw| {+ M::apply(channel, raw, values);+ });+ }+}diff --git a/crates/keisoku/src/sources/memory.rs b/crates/keisoku/src/sources/memory.rsnew file mode 100644index 000000000..6cb94f03b--- /dev/null+++ b/crates/keisoku/src/sources/memory.rs@@ -0,0 +1,21 @@+use crate::metrics::MemoryMetrics;++#[cfg(target_os = "macos")]+pub(crate) fn read_memory() -> Option<MemoryMetrics> {+ crate::sys::read_memory()+}++#[cfg(not(target_os = "macos"))]+pub(crate) fn read_memory() -> Option<MemoryMetrics> {+ use sysinfo::System;++ use crate::units::Bytes;+ let mut system = System::new();+ system.refresh_memory();+ Some(MemoryMetrics {+ ram_total: Bytes(system.total_memory()),+ ram_usage: Bytes(system.used_memory()),+ swap_total: Bytes(system.total_swap()),+ swap_usage: Bytes(system.used_swap()),+ })+}diff --git a/crates/keisoku/src/sources/mod.rs b/crates/keisoku/src/sources/mod.rsnew file mode 100644index 000000000..379560d4a--- /dev/null+++ b/crates/keisoku/src/sources/mod.rs@@ -0,0 +1,144 @@+mod battery;+mod deferred;+#[cfg(target_os = "macos")]+pub(crate) mod interval;+mod memory;+mod rail_power;+mod sensors;+mod thermal;++use deferred::Deferred;++#[cfg(target_os = "macos")]+use crate::sys::{smc::Smc, soc::SocInfo};+use crate::{+ metrics::FanMetrics,+ sensor::{Sensor, SensorKind},+ sys::hid::SensorReader,+ units::Watts,+};++pub(crate) struct Sources {+ temperature: Deferred<Option<SensorReader>>,+ voltage: Deferred<Option<SensorReader>>,+ current: Deferred<Option<SensorReader>>,+ #[cfg(target_os = "macos")]+ soc: std::cell::OnceCell<Option<SocInfo>>,+ #[cfg(target_os = "macos")]+ smc: std::cell::OnceCell<Option<Smc>>,+}++impl Sources {+ pub fn new() -> Self {+ Self {+ temperature: Deferred::new(|| sensors::new_reader(SensorKind::Temperature)),+ voltage: Deferred::new(|| sensors::new_reader(SensorKind::Voltage)),+ current: Deferred::new(|| sensors::new_reader(SensorKind::Current)),+ #[cfg(target_os = "macos")]+ soc: std::cell::OnceCell::new(),+ #[cfg(target_os = "macos")]+ smc: std::cell::OnceCell::new(),+ }+ }++ pub(crate) fn chip(&self) -> String {+ #[cfg(target_os = "macos")]+ {+ self.soc().map(|soc| soc.chip_name.clone()).unwrap_or_default()+ }+ #[cfg(not(target_os = "macos"))]+ {+ crate::sys::sysctl_string("hw.machine").unwrap_or_default()+ }+ }++ pub(crate) fn efficiency_cores(&self) -> u8 {+ #[cfg(target_os = "macos")]+ {+ self.soc().map(|soc| soc.ecpu_cores).unwrap_or(0)+ }+ #[cfg(not(target_os = "macos"))]+ {+ crate::sys::perflevel_cores().1+ }+ }++ pub(crate) fn performance_cores(&self) -> u8 {+ #[cfg(target_os = "macos")]+ {+ self.soc().map(|soc| soc.pcpu_cores).unwrap_or(0)+ }+ #[cfg(not(target_os = "macos"))]+ {+ crate::sys::perflevel_cores().0+ }+ }++ pub(crate) fn gpu_cores(&self) -> u8 {+ #[cfg(target_os = "macos")]+ {+ self.soc().map(|soc| soc.gpu_cores).unwrap_or(0)+ }+ #[cfg(not(target_os = "macos"))]+ {+ 0+ }+ }++ pub(crate) fn temperature_sensors(&mut self) -> Box<[Sensor]> {+ self.temperature.get().as_mut().map(sensors::read_reader).unwrap_or_default()+ }++ pub(crate) fn voltage_sensors(&mut self) -> Box<[Sensor]> {+ self.voltage.get().as_mut().map(sensors::read_reader).unwrap_or_default()+ }++ pub(crate) fn current_sensors(&mut self) -> Box<[Sensor]> {+ self.current.get().as_mut().map(sensors::read_reader).unwrap_or_default()+ }++ pub(crate) fn memory(&mut self) -> Option<crate::metrics::MemoryMetrics> {+ memory::read_memory()+ }++ pub(crate) fn battery(&mut self) -> Option<crate::metrics::BatteryMetrics> {+ battery::read_battery()+ }++ pub(crate) fn thermal(&mut self) -> Option<crate::metrics::ThermalPressure> {+ thermal::read_thermal()+ }++ pub(crate) fn rail_power(&mut self) -> Option<Watts> {+ let voltage = self.voltage_sensors();+ let current = self.current_sensors();+ rail_power::rail_power(&voltage, ¤t)+ }++ pub(crate) fn fans(&self) -> Option<FanMetrics> {+ #[cfg(target_os = "macos")]+ {+ self.smc().map(Smc::fans)+ }+ #[cfg(not(target_os = "macos"))]+ {+ None+ }+ }++ #[cfg(target_os = "macos")]+ pub(crate) fn soc(&self) -> Option<&SocInfo> {+ self.soc.get_or_init(SocInfo::new).as_ref()+ }++ #[cfg(target_os = "macos")]+ pub(crate) fn smc(&self) -> Option<&Smc> {+ self.smc.get_or_init(Smc::new).as_ref()+ }+}++impl Default for Sources {+ fn default() -> Self {+ Self::new()+ }+}diff --git a/crates/keisoku/src/sources/rail_power.rs b/crates/keisoku/src/sources/rail_power.rsnew file mode 100644index 000000000..765dd9788--- /dev/null+++ b/crates/keisoku/src/sources/rail_power.rs@@ -0,0 +1,32 @@+use crate::{component::Component, sensor::Sensor, units::Watts};++pub(crate) fn rail_power(+ voltage: &[Sensor],+ current: &[Sensor],+) -> Option<Watts> {+ const MAX_PLAUSIBLE_WATTS: f64 = 1000.0;+ let split_area_code = |name: &str| name.rsplit_once(' ').map(|(area, code)| (area.to_owned(), code.to_owned()));+ let is_battery_rail = |sensor: &&Sensor| matches!(sensor.component, Component::Charger | Component::Battery);++ let mut total_watts = 0f64;+ for voltage_sensor in voltage.iter().filter(is_battery_rail) {+ let Some((voltage_area, voltage_code)) = split_area_code(&voltage_sensor.name) else {+ continue;+ };+ let Some(rail_code) = voltage_code.strip_prefix('V').filter(|code| !code.is_empty()) else {+ continue;+ };+ for current_sensor in current.iter().filter(is_battery_rail) {+ let Some((current_area, current_code)) = split_area_code(¤t_sensor.name) else {+ continue;+ };+ if current_area == voltage_area && current_code.strip_prefix('I') == Some(rail_code) {+ let watts = (voltage_sensor.value * current_sensor.value).abs();+ if (0.0..=MAX_PLAUSIBLE_WATTS).contains(&watts) {+ total_watts += watts;+ }+ }+ }+ }+ (total_watts > 0.0).then_some(Watts(total_watts as f32))+}diff --git a/crates/keisoku/src/sources/sensors.rs b/crates/keisoku/src/sources/sensors.rsnew file mode 100644index 000000000..8f7a90f1f--- /dev/null+++ b/crates/keisoku/src/sources/sensors.rs@@ -0,0 +1,12 @@+use crate::{+ sensor::{Sensor, SensorKind},+ sys::hid::SensorReader,+};++pub(crate) fn new_reader(kind: SensorKind) -> Option<SensorReader> {+ SensorReader::new(kind)+}++pub(crate) fn read_reader(reader: &mut SensorReader) -> Box<[Sensor]> {+ reader.read()+}diff --git a/crates/keisoku/src/sources/thermal.rs b/crates/keisoku/src/sources/thermal.rsnew file mode 100644index 000000000..ecf85c5a2--- /dev/null+++ b/crates/keisoku/src/sources/thermal.rs@@ -0,0 +1,5 @@+use crate::metrics::ThermalPressure;++pub(crate) fn read_thermal() -> Option<ThermalPressure> {+ crate::sys::read_thermal_pressure()+}diff --git a/crates/keisoku/src/sys/battery.rs b/crates/keisoku/src/sys/battery.rsnew file mode 100644index 000000000..473f774ae--- /dev/null+++ b/crates/keisoku/src/sys/battery.rs@@ -0,0 +1,52 @@+use objc2_core_foundation::{CFBoolean, CFNumber, CFString, CFType};+use objc2_io_kit::{+ IOPSCopyPowerSourcesInfo, IOPSCopyPowerSourcesList, IOPSGetPowerSourceDescription, kIOPSCurrentCapacityKey,+ kIOPSInternalBatteryType, kIOPSIsChargingKey, kIOPSMaxCapacityKey, kIOPSPowerSourceStateKey, kIOPSTypeKey,+};++use crate::{metrics::BatteryMetrics, sys::registry::dictionary_get, units::Percent};++pub(crate) fn read_battery() -> Option<BatteryMetrics> {+ let info = IOPSCopyPowerSourcesInfo()?;+ let info_ref: &CFType = &info;+ let list = unsafe { IOPSCopyPowerSourcesList(Some(info_ref)) }?;+ let internal = kIOPSInternalBatteryType.to_str().ok()?;++ for index in 0..list.count() {+ let source = unsafe { list.value_at_index(index) };+ let Some(source) = (unsafe { (source as *const CFType).as_ref() }) else {+ continue;+ };+ let Some(description) = (unsafe { IOPSGetPowerSourceDescription(Some(info_ref), Some(source)) }) else {+ continue;+ };+ let string =+ |key: &core::ffi::CStr| dictionary_get::<CFString>(&description, key.to_str().ok()?).map(|s| s.to_string());+ let number = |key: &core::ffi::CStr| {+ dictionary_get::<CFNumber>(&description, key.to_str().ok()?).and_then(|n| n.as_i64())+ };+ let boolean =+ |key: &core::ffi::CStr| dictionary_get::<CFBoolean>(&description, key.to_str().ok()?).map(|b| b.value());++ if string(kIOPSTypeKey)? != internal {+ continue;+ }+ let current = number(kIOPSCurrentCapacityKey)?;+ let maximum = number(kIOPSMaxCapacityKey)?;+ let charging = boolean(kIOPSIsChargingKey).unwrap_or(false);+ let on_ac_power = string(kIOPSPowerSourceStateKey).is_some_and(|state| state.eq_ignore_ascii_case("AC Power"));+ let percent = if maximum > 0 {+ (current * 100 / maximum) as f32+ } else {+ 0.0+ };++ return Some(BatteryMetrics {+ present: true,+ percent: Percent(percent),+ charging,+ on_ac_power,+ });+ }+ None+}diff --git a/crates/keisoku/src/sys.rs b/crates/keisoku/src/sys/constants.rssimilarity index 100%rename from crates/keisoku/src/sys.rsrename to crates/keisoku/src/sys/constants.rsdiff --git a/crates/keisoku/src/client/event_system_client.rs b/crates/keisoku/src/sys/hid/event_system_client.rssimilarity index 75%rename from crates/keisoku/src/client/event_system_client.rsrename to crates/keisoku/src/sys/hid/event_system_client.rsindex 36ade95ea..2d2c06cfb 100644--- a/crates/keisoku/src/client/event_system_client.rs+++ b/crates/keisoku/src/sys/hid/event_system_client.rs@@ -21,19 +21,16 @@ impl EventSystemClient {})}- /// Match HID services for the given usage page/usage and return them as- /// owning [`ServiceClient`]s. `CFArray::to_vec` retains each element, so the- /// returned clients no longer depend on the matched array staying alive.pub(super) fn services(&self,page: i32,usage: i32,- ) -> Vec<ServiceClient> {+ ) -> Box<[ServiceClient]> {let io_kit = self.io_kit;let Some(array) = self.services_matching(page, usage) else {- return Vec::new();+ return Box::default();};- array.to_vec().into_iter().map(|inner| ServiceClient::new(io_kit, inner)).collect()+ array.to_vec().into_iter().map(|inner| (io_kit, inner).into()).collect()}fn services_matching(@@ -49,8 +46,6 @@ impl EventSystemClient {let _ = unsafe { (self.io_kit.set_matching)(&self.inner, &matching) };- // `CFArray`'s generic is `PhantomData`, so typing the matched array as- // `CFArray<IOHIDServiceClient>` is a layout-sound pointer cast.let services = unsafe { (self.io_kit.copy_services)(&self.inner) };let services = NonNull::new(services.cast::<CFArray<IOHIDServiceClient>>())?;Some(unsafe { CFRetained::from_raw(services) })diff --git a/crates/keisoku/src/client/mod.rs b/crates/keisoku/src/sys/hid/mod.rssimilarity index 79%rename from crates/keisoku/src/client/mod.rsrename to crates/keisoku/src/sys/hid/mod.rsindex 6fd25852a..4bd1d2cb5 100644--- a/crates/keisoku/src/client/mod.rs+++ b/crates/keisoku/src/sys/hid/mod.rs@@ -16,6 +16,18 @@ fn is_hot(component: Component) -> bool {matches!(component, Component::Cpu | Component::Gpu | Component::Soc | Component::NeuralEngine)}+fn is_plausible(+ kind: SensorKind,+ value: f64,+) -> bool {+ value.is_finite()+ && match kind {+ SensorKind::Temperature => true,+ SensorKind::Voltage => value.abs() <= 100.0,+ SensorKind::Current => value.abs() <= 1000.0,+ }+}+kanka::opaque_cf_type!(IOHIDEventSystemClient);kanka::opaque_cf_type!(IOHIDServiceClient);kanka::opaque_cf_type!(IOHIDEvent);@@ -42,38 +54,6 @@ kanka::ffi_table! {mod event_system_client;mod service_client;-pub(crate) fn is_available() -> bool {- IOKit::get().is_some()-}--pub(crate) fn collect(kind: SensorKind) -> Vec<Sensor> {- let Some(client) = EventSystemClient::new() else {- return Vec::new();- };- let (page, usage) = kind.matching();- let event_type = kind.event_type();- let event_field = sys::event_field_base(event_type);-- let mut readings = Vec::new();- for service in client.services(page, usage) {- let Some(value) = service.f64_value(event_type, event_field) else {- continue;- };- let name = service.string(obfstr!("Product")).unwrap_or_default();- readings.push(Sensor {- component: classify(&name),- manufacturer: service.string(obfstr!("Manufacturer")),- category: service.string(obfstr!("Category")),- location_id: service.i64_value(obfstr!("LocationID")),- registry_id: service.registry_id(),- name,- value,- kind,- });- }- readings-}-struct CachedSensor {service: ServiceClient,name: String,@@ -114,7 +94,6 @@ impl SensorReader {category: service.string(obfstr!("Category")),location_id: service.i64_value(obfstr!("LocationID")),registry_id: service.registry_id(),- // Power rails change continuously, so refresh them every read (not just cold).hot: is_hot(component) || matches!(kind, SensorKind::Voltage | SensorKind::Current),component,name,@@ -133,7 +112,7 @@ impl SensorReader {})}- pub(crate) fn read(&mut self) -> Vec<Sensor> {+ pub(crate) fn read(&mut self) -> Box<[Sensor]> {let refresh_cold = self.last_cold_read.is_none_or(|at| at.elapsed() >= COLD_REFRESH);if refresh_cold {self.last_cold_read = Some(Instant::now());@@ -158,6 +137,7 @@ impl SensorReader {kind,}})+ .filter(|sensor| is_plausible(kind, sensor.value)).collect()}}diff --git a/crates/keisoku/src/client/service_client.rs b/crates/keisoku/src/sys/hid/service_client.rssimilarity index 90%rename from crates/keisoku/src/client/service_client.rsrename to crates/keisoku/src/sys/hid/service_client.rsindex b7f26f700..1a93db917 100644--- a/crates/keisoku/src/client/service_client.rs+++ b/crates/keisoku/src/sys/hid/service_client.rs@@ -9,17 +9,16 @@ pub(super) struct ServiceClient {inner: CFRetained<IOHIDServiceClient>,}-impl ServiceClient {- pub(super) fn new(- io_kit: &'static IOKit,- inner: CFRetained<IOHIDServiceClient>,- ) -> Self {+impl From<(&'static IOKit, CFRetained<IOHIDServiceClient>)> for ServiceClient {+ fn from((io_kit, inner): (&'static IOKit, CFRetained<IOHIDServiceClient>)) -> Self {Self {io_kit,inner,}}+}+impl ServiceClient {fn property<T: ConcreteType>(&self,key: &str,diff --git a/crates/keisoku/src/sys/ioreport/channel.rs b/crates/keisoku/src/sys/ioreport/channel.rsnew file mode 100644index 000000000..345583112--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/channel.rs@@ -0,0 +1,75 @@+use core::ffi::c_void;++use obfstr::obfstr;+use objc2_core_foundation::{CFArray, CFDictionary, CFRetained, CFType};++use super::IoReportFunctions;+use crate::sys::{+ ioreport::decode::{Channel, GroupId, RawChannel, ResidencyState},+ registry::{cf_string_to_string, dictionary_get},+};++pub(super) fn for_each_channel(+ functions: &IoReportFunctions,+ delta: &CFDictionary,+ visit: &mut impl FnMut(Channel, &RawChannel),+) {+ let Some(channels) = dictionary_get::<CFArray>(delta, obfstr!("IOReportChannels")) else {+ return;+ };+ let channels: CFRetained<CFArray<CFType>> = unsafe { CFRetained::from_raw(CFRetained::into_raw(channels).cast()) };+ for channel in channels.iter() {+ if let Some((classified, decoded)) = decode_channel(functions, &channel) {+ visit(classified, &decoded);+ }+ }+}++fn decode_channel(+ functions: &IoReportFunctions,+ channel: &CFType,+) -> Option<(Channel, RawChannel)> {+ let item: *const c_void = core::ptr::from_ref(channel).cast();+ let group = GroupId::classify(&cf_string_to_string(unsafe { (functions.channel_get_group)(item) }));+ if group == GroupId::Other {+ return None;+ }++ let mut decoded = RawChannel {+ group,+ name: cf_string_to_string(unsafe { (functions.channel_get_channel_name)(item) }),+ ..Default::default()+ };+ if matches!(group, GroupId::Pmp) {+ decoded.subgroup = cf_string_to_string(unsafe { (functions.channel_get_subgroup)(item) });+ }++ let classified = Channel::classify(&decoded)?;++ match classified {+ Channel::EnergyRail(_) => {+ decoded.unit = unsafe { (functions.channel_get_unit)(item) };+ decoded.integer_value = unsafe { (functions.simple_get_integer_value)(item, 0) };+ },+ Channel::DramBytes(_) => {+ decoded.integer_value = unsafe { (functions.simple_get_integer_value)(item, 0) };+ },+ Channel::AneBandwidth | Channel::DramHistogram(_) => {+ decoded.states = decode_states(functions, item);+ },+ }++ Some((classified, decoded))+}++fn decode_states(+ functions: &IoReportFunctions,+ item: *const c_void,+) -> Vec<ResidencyState> {+ (0..unsafe { (functions.state_get_count)(item) })+ .map(|index| ResidencyState {+ name: cf_string_to_string(unsafe { (functions.state_get_name_for_index)(item, index) }),+ residency: unsafe { (functions.state_get_residency)(item, index) },+ })+ .collect()+}diff --git a/crates/keisoku/src/sys/ioreport/channels.rs b/crates/keisoku/src/sys/ioreport/channels.rsnew file mode 100644index 000000000..87d1f228c--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/channels.rs@@ -0,0 +1,43 @@+use obfstr::obfstr;+use objc2_core_foundation::{CFMutableDictionary, CFRetained, CFString};++use super::IoReportFunctions;+use crate::sys::ioreport::IoReportGroups;++pub(super) struct Channels(pub(super) CFRetained<CFMutableDictionary>);++impl Channels {+ pub(super) fn from_groups(+ groups: IoReportGroups,+ functions: &IoReportFunctions,+ ) -> Option<Self> {+ let mut collected: Vec<CFRetained<CFMutableDictionary>> = Vec::with_capacity(5);+ for (flag, group, subgroup) in [+ (IoReportGroups::ENERGY_MODEL, obfstr!("Energy Model"), None::<&str>),+ (IoReportGroups::AMC_STATS, obfstr!("AMC Stats"), None),+ (IoReportGroups::PMP, obfstr!("PMP"), None),+ ] {+ if !groups.contains(flag) {+ continue;+ }+ let group_name = CFString::from_str(group);+ let subgroup_name = subgroup.map(CFString::from_str);+ if let Some(group_channels) = functions.copy_channels_in_group(&group_name, subgroup_name.as_deref()) {+ collected.push(group_channels);+ }+ }+ Self::merged(&collected, functions)+ }++ fn merged(+ groups: &[CFRetained<CFMutableDictionary>],+ functions: &IoReportFunctions,+ ) -> Option<Self> {+ let (first, rest) = groups.split_first()?;+ for other in rest {+ functions.merge_channels(first, other);+ }+ let channels = unsafe { CFMutableDictionary::new_copy(None, first.count(), Some(&**first)) }?;+ Some(Self(channels))+ }+}diff --git a/crates/keisoku/src/sys/ioreport/decode/channel.rs b/crates/keisoku/src/sys/ioreport/decode/channel.rsnew file mode 100644index 000000000..4eb931efb--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/decode/channel.rs@@ -0,0 +1,32 @@+use obfstr::obfstr;++use super::{GroupId, RawChannel, Subgroup, naming};+use crate::sys::ioreport::kinds::{DramFlow, Rail};++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Channel {+ EnergyRail(Rail),+ AneBandwidth,+ DramBytes(DramFlow),+ DramHistogram(DramFlow),+}++impl Channel {+ pub fn classify(channel: &RawChannel) -> Option<Channel> {+ match channel.group {+ GroupId::EnergyModel => Rail::classify(&channel.name).map(Channel::EnergyRail),+ GroupId::Pmp => match Subgroup::classify(&channel.subgroup) {+ Subgroup::Floor if channel.name == obfstr!("ANE-AF-BW") || channel.name == obfstr!("ANE-DCS-BW") => {+ Some(Channel::AneBandwidth)+ },+ Subgroup::DramBandwidth => naming::read_write_flow(&channel.name).map(Channel::DramBytes),+ Subgroup::DcsBandwidth if channel.name.starts_with(obfstr!("AMCC")) => {+ naming::read_write_flow(&channel.name).map(Channel::DramHistogram)+ },+ _ => None,+ },+ GroupId::AmcStats => naming::dcs_flow(naming::strip_die_prefix(&channel.name)).map(Channel::DramBytes),+ GroupId::Other => None,+ }+ }+}diff --git a/crates/keisoku/src/sys/ioreport/decode/group_id.rs b/crates/keisoku/src/sys/ioreport/decode/group_id.rsnew file mode 100644index 000000000..2a792536d--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/decode/group_id.rs@@ -0,0 +1,24 @@+use obfstr::obfstr;++#[derive(Clone, Copy, PartialEq, Eq, Default)]+pub(crate) enum GroupId {+ EnergyModel,+ AmcStats,+ Pmp,+ #[default]+ Other,+}++impl GroupId {+ pub(crate) fn classify(group: &str) -> GroupId {+ if group == obfstr!("Energy Model") {+ GroupId::EnergyModel+ } else if group == obfstr!("AMC Stats") {+ GroupId::AmcStats+ } else if group == obfstr!("PMP") {+ GroupId::Pmp+ } else {+ GroupId::Other+ }+ }+}diff --git a/crates/keisoku/src/sys/ioreport/decode/mod.rs b/crates/keisoku/src/sys/ioreport/decode/mod.rsnew file mode 100644index 000000000..e9214dfd6--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/decode/mod.rs@@ -0,0 +1,16 @@+mod channel;+mod group_id;+mod naming;+mod raw_channel;+mod residency;+mod residency_state;+mod subgroup;+mod unit;++pub use channel::Channel;+pub(crate) use group_id::GroupId;+pub use raw_channel::RawChannel;+pub(crate) use residency::{residency_active_percent, residency_weighted_gbps};+pub(crate) use residency_state::ResidencyState;+pub(crate) use subgroup::Subgroup;+pub(crate) use unit::energy_joules;diff --git a/crates/keisoku/src/sys/ioreport/decode/naming.rs b/crates/keisoku/src/sys/ioreport/decode/naming.rsnew file mode 100644index 000000000..51aa19d04--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/decode/naming.rs@@ -0,0 +1,31 @@+use obfstr::obfstr;++use crate::sys::ioreport::kinds::DramFlow;++pub(crate) fn strip_die_prefix(channel: &str) -> &str {+ let Some(rest) = channel.strip_prefix(obfstr!("DIE")) else {+ return channel;+ };+ let rest = rest.trim_start_matches(|character: char| character.is_ascii_digit());+ rest.strip_prefix(' ').unwrap_or(channel)+}++pub(crate) fn dcs_flow(aggregate: &str) -> Option<DramFlow> {+ if aggregate == obfstr!("DCS RD") {+ Some(DramFlow::DramRead)+ } else if aggregate == obfstr!("DCS WR") {+ Some(DramFlow::DramWrite)+ } else {+ None+ }+}++pub(crate) fn read_write_flow(name: &str) -> Option<DramFlow> {+ if name.ends_with(obfstr!(" RD")) {+ Some(DramFlow::DramRead)+ } else if name.ends_with(obfstr!(" WR")) {+ Some(DramFlow::DramWrite)+ } else {+ None+ }+}diff --git a/crates/keisoku/src/sys/ioreport/decode/raw_channel.rs b/crates/keisoku/src/sys/ioreport/decode/raw_channel.rsnew file mode 100644index 000000000..4a52bf0b0--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/decode/raw_channel.rs@@ -0,0 +1,11 @@+use super::{group_id::GroupId, residency_state::ResidencyState};++#[derive(Default)]+pub struct RawChannel {+ pub(crate) group: GroupId,+ pub(crate) subgroup: String,+ pub(crate) name: String,+ pub(crate) unit: u64,+ pub(crate) integer_value: i64,+ pub(crate) states: Vec<ResidencyState>,+}diff --git a/crates/keisoku/src/sys/ioreport/decode/residency.rs b/crates/keisoku/src/sys/ioreport/decode/residency.rsnew file mode 100644index 000000000..da07f9b4d--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/decode/residency.rs@@ -0,0 +1,43 @@+use obfstr::obfstr;++use super::residency_state::ResidencyState;++pub(crate) fn residency_active_percent(states: &[ResidencyState]) -> f32 {+ let total: f64 = states.iter().map(|state| state.residency as f64).sum();+ if total <= 0.0 {+ return 0.0;+ }+ let active: f64 =+ states.iter().filter(|state| !is_idle_state(&state.name)).map(|state| state.residency as f64).sum();+ (active / total * 100.0) as f32+}++pub(crate) fn residency_weighted_gbps(states: &[ResidencyState]) -> f32 {+ let mut weighted = 0f64;+ let mut total = 0f64;+ for state in states {+ weighted += parse_leading_number(&state.name) * (state.residency as f64);+ total += state.residency as f64;+ }+ if total <= 0.0 {+ 0.0+ } else {+ (weighted / total) as f32+ }+}++fn parse_leading_number(name: &str) -> f64 {+ let digits: String =+ name.trim().chars().take_while(|character| character.is_ascii_digit() || *character == '.').collect();+ digits.parse().unwrap_or(0.0)+}++pub(crate) fn is_idle_state(name: &str) -> bool {+ name == obfstr!("OFF")+ || name == obfstr!("IDLE")+ || name == obfstr!("DOWN")+ || name == obfstr!("SLEEP")+ || name == obfstr!("VMIN")+ || name == obfstr!("F1")+ || name == obfstr!("0%")+}diff --git a/crates/keisoku/src/sys/ioreport/decode/residency_state.rs b/crates/keisoku/src/sys/ioreport/decode/residency_state.rsnew file mode 100644index 000000000..40654c786--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/decode/residency_state.rs@@ -0,0 +1,5 @@+#[derive(Default)]+pub(crate) struct ResidencyState {+ pub(crate) name: String,+ pub(crate) residency: i64,+}diff --git a/crates/keisoku/src/sys/ioreport/decode/subgroup.rs b/crates/keisoku/src/sys/ioreport/decode/subgroup.rsnew file mode 100644index 000000000..9af4796ea--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/decode/subgroup.rs@@ -0,0 +1,23 @@+use obfstr::obfstr;++#[derive(Clone, Copy, PartialEq, Eq)]+pub(crate) enum Subgroup {+ DcsBandwidth,+ DramBandwidth,+ Floor,+ Other,+}++impl Subgroup {+ pub(crate) fn classify(subgroup: &str) -> Subgroup {+ if subgroup == obfstr!("DCS BW") {+ Subgroup::DcsBandwidth+ } else if subgroup == obfstr!("DRAM BW") {+ Subgroup::DramBandwidth+ } else if subgroup.contains(obfstr!("Floor")) {+ Subgroup::Floor+ } else {+ Subgroup::Other+ }+ }+}diff --git a/crates/keisoku/src/sys/ioreport/decode/unit.rs b/crates/keisoku/src/sys/ioreport/decode/unit.rsnew file mode 100644index 000000000..06f28aa2d--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/decode/unit.rs@@ -0,0 +1,15 @@+const QUANTITY_ENERGY: u64 = 3;+const QUANTITY_SHIFT: u32 = 56;+const SI_SCALE_SHIFT: u32 = 32;+const SI_EXPONENT_BIAS: i32 = 127;++pub(crate) fn energy_joules(+ value: i64,+ unit: u64,+) -> f64 {+ if (unit >> QUANTITY_SHIFT) & 0xff != QUANTITY_ENERGY {+ return 0.0;+ }+ let exponent = (((unit >> SI_SCALE_SHIFT) & 0xff) as i32) - SI_EXPONENT_BIAS;+ value as f64 * 10f64.powi(exponent)+}diff --git a/crates/keisoku/src/sys/ioreport/groups.rs b/crates/keisoku/src/sys/ioreport/groups.rsnew file mode 100644index 000000000..f1d688360--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/groups.rs@@ -0,0 +1,10 @@+use bitflags::bitflags;++bitflags! {+ #[derive(Clone, Copy, PartialEq, Eq, Debug)]+ pub struct IoReportGroups: u8 {+ const ENERGY_MODEL = 1 << 0;+ const AMC_STATS = 1 << 1;+ const PMP = 1 << 2;+ }+}diff --git a/crates/keisoku/src/sys/ioreport/io_report.rs b/crates/keisoku/src/sys/ioreport/io_report.rsnew file mode 100644index 000000000..71944cf09--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/io_report.rs@@ -0,0 +1,39 @@+use super::{+ IoReportFunctions, channel::for_each_channel, raw_ioreport_sample::RawIOReportSample, subscription::Subscription,+};+use crate::sys::ioreport::{+ IoReportGroups,+ decode::{Channel, RawChannel},+};++pub(crate) struct IoReport {+ functions: &'static IoReportFunctions,+ subscription: Subscription,+}++impl IoReport {+ pub fn for_groups(groups: IoReportGroups) -> Option<Self> {+ let functions = IoReportFunctions::get()?;+ let subscription = Subscription::for_groups(groups, functions)?;+ Some(Self {+ functions,+ subscription,+ })+ }++ pub(crate) fn snapshot(&self) -> Option<RawIOReportSample> {+ self.subscription.snapshot(self.functions).map(RawIOReportSample)+ }++ pub(crate) fn for_each_channel(+ &self,+ begin: &RawIOReportSample,+ end: &RawIOReportSample,+ mut visit: impl FnMut(Channel, &RawChannel),+ ) {+ let Some(delta) = self.functions.create_samples_delta(&begin.0, &end.0) else {+ return;+ };+ for_each_channel(self.functions, &delta, &mut visit);+ }+}diff --git a/crates/keisoku/src/sys/ioreport/kinds/flow/mod.rs b/crates/keisoku/src/sys/ioreport/kinds/flow/mod.rsnew file mode 100644index 000000000..02eb72edd--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/kinds/flow/mod.rs@@ -0,0 +1,26 @@+pub(crate) trait FlowKind: 'static {+ const FLOW: DramFlow;+ const TYPE_BIT_BYTES: u128;+ const TYPE_BIT_HIST: u128;+}++#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]+pub enum DramFlow {+ DramRead,+ DramWrite,+}++pub struct DramRead;+pub struct DramWrite;++impl FlowKind for DramRead {+ const FLOW: DramFlow = DramFlow::DramRead;+ const TYPE_BIT_BYTES: u128 = 1 << 5;+ const TYPE_BIT_HIST: u128 = 1 << 7;+}++impl FlowKind for DramWrite {+ const FLOW: DramFlow = DramFlow::DramWrite;+ const TYPE_BIT_BYTES: u128 = 1 << 6;+ const TYPE_BIT_HIST: u128 = 1 << 8;+}diff --git a/crates/keisoku/src/sys/ioreport/kinds/mod.rs b/crates/keisoku/src/sys/ioreport/kinds/mod.rsnew file mode 100644index 000000000..d12366639--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/kinds/mod.rs@@ -0,0 +1,7 @@+mod flow;+mod rail;++pub(crate) use flow::FlowKind;+pub use flow::{DramFlow, DramRead, DramWrite};+pub(crate) use rail::RailKind;+pub use rail::{Ane, Cpu, Gpu, Rail, Ram};diff --git a/crates/keisoku/src/sys/ioreport/kinds/rail/mod.rs b/crates/keisoku/src/sys/ioreport/kinds/rail/mod.rsnew file mode 100644index 000000000..0d7fbd3fa--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/kinds/rail/mod.rs@@ -0,0 +1,58 @@+use obfstr::obfstr;++pub(crate) trait RailKind: 'static {+ const RAIL: Rail;+ const TYPE_BIT: u128;+}++#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub enum Rail {+ Cpu,+ Gpu,+ Ane,+ Ram,+}++impl Rail {+ pub(crate) fn classify(name: &str) -> Option<Rail> {+ if name == obfstr!("GPU Energy") {+ Some(Rail::Gpu)+ } else if name.ends_with(obfstr!("CPU Energy")) {+ Some(Rail::Cpu)+ } else if name.starts_with(obfstr!("ANE")) {+ Some(Rail::Ane)+ } else if name.starts_with(obfstr!("DRAM"))+ || name.starts_with(obfstr!("DCS"))+ || name.starts_with(obfstr!("AMCC"))+ {+ Some(Rail::Ram)+ } else {+ None+ }+ }+}++pub struct Cpu;+pub struct Gpu;+pub struct Ane;+pub struct Ram;++impl RailKind for Cpu {+ const RAIL: Rail = Rail::Cpu;+ const TYPE_BIT: u128 = 1 << 0;+}++impl RailKind for Gpu {+ const RAIL: Rail = Rail::Gpu;+ const TYPE_BIT: u128 = 1 << 1;+}++impl RailKind for Ane {+ const RAIL: Rail = Rail::Ane;+ const TYPE_BIT: u128 = 1 << 2;+}++impl RailKind for Ram {+ const RAIL: Rail = Rail::Ram;+ const TYPE_BIT: u128 = 1 << 3;+}diff --git a/crates/keisoku/src/ioreport/mod.rs b/crates/keisoku/src/sys/ioreport/mod.rssimilarity index 84%rename from crates/keisoku/src/ioreport/mod.rsrename to crates/keisoku/src/sys/ioreport/mod.rsindex e29a03af9..e67b1f1d3 100644--- a/crates/keisoku/src/ioreport/mod.rs+++ b/crates/keisoku/src/sys/ioreport/mod.rs@@ -2,15 +2,19 @@ use core::{ffi::c_void, ptr::NonNull};use objc2_core_foundation::{CFDictionary, CFMutableDictionary, CFRetained, CFString, CFType, Type};-mod bandwidth;+pub mod decode;+pub(crate) mod kinds;+mod channel;-mod frequency;-mod report;-mod sample;+mod channels;+mod groups;+mod io_report;+mod raw_ioreport_sample;mod subscription;-pub use report::IoReport;-pub use sample::SocSample;+pub use groups::IoReportGroups;+pub(crate) use io_report::IoReport;+pub(crate) use raw_ioreport_sample::RawIOReportSample;kanka::ffi_table! {struct IoReportFunctions from "/usr/lib/libIOReport.dylib" {@@ -30,8 +34,8 @@ kanka::ffi_table! {unsafe extern "C" fn(*const c_void) -> *const c_void,channel_get_channel_name = "IOReportChannelGetChannelName":unsafe extern "C" fn(*const c_void) -> *const c_void,- channel_get_unit_label = "IOReportChannelGetUnitLabel":- unsafe extern "C" fn(*const c_void) -> *const c_void,+ channel_get_unit = "IOReportChannelGetUnit":+ unsafe extern "C" fn(*const c_void) -> u64,simple_get_integer_value = "IOReportSimpleGetIntegerValue":unsafe extern "C" fn(*const c_void, i32) -> i64,state_get_count = "IOReportStateGetCount":@@ -48,16 +52,16 @@ impl IoReportFunctions {&self,group: &CFString,subgroup: Option<&CFString>,- ) -> Option<CFRetained<CFDictionary>> {+ ) -> Option<CFRetained<CFMutableDictionary>> {let subgroup_pointer = subgroup.map_or(core::ptr::null_mut(), raw);let channels = unsafe { (self.copy_channels_in_group)(raw(group), subgroup_pointer, 0, 0, 0) };- retained_dictionary(channels)+ retained_mutable_dictionary(channels)}fn merge_channels(&self,- first: &CFDictionary,- other: &CFDictionary,+ first: &CFMutableDictionary,+ other: &CFMutableDictionary,) {unsafe { (self.merge_channels)(raw(first), raw(other), core::ptr::null()) };}@@ -101,3 +105,7 @@ fn raw<T: Type>(value: &T) -> *mut c_void {fn retained_dictionary(value: *const c_void) -> Option<CFRetained<CFDictionary>> {NonNull::new(value.cast_mut().cast::<CFDictionary>()).map(|pointer| unsafe { CFRetained::from_raw(pointer) })}++fn retained_mutable_dictionary(value: *const c_void) -> Option<CFRetained<CFMutableDictionary>> {+ NonNull::new(value.cast_mut().cast::<CFMutableDictionary>()).map(|pointer| unsafe { CFRetained::from_raw(pointer) })+}diff --git a/crates/keisoku/src/sys/ioreport/raw_ioreport_sample.rs b/crates/keisoku/src/sys/ioreport/raw_ioreport_sample.rsnew file mode 100644index 000000000..3d6f20992--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/raw_ioreport_sample.rs@@ -0,0 +1,3 @@+use objc2_core_foundation::{CFDictionary, CFRetained};++pub(crate) struct RawIOReportSample(pub(super) CFRetained<CFDictionary>);diff --git a/crates/keisoku/src/sys/ioreport/subscription.rs b/crates/keisoku/src/sys/ioreport/subscription.rsnew file mode 100644index 000000000..65b400935--- /dev/null+++ b/crates/keisoku/src/sys/ioreport/subscription.rs@@ -0,0 +1,37 @@+use objc2_core_foundation::{CFDictionary, CFRetained, CFType};++use super::{IoReportFunctions, channels::Channels};+use crate::sys::ioreport::IoReportGroups;++pub(super) struct Subscription {+ handle: CFRetained<CFType>,+ channels: Channels,+}++impl Subscription {+ pub(super) fn for_groups(+ groups: IoReportGroups,+ functions: &IoReportFunctions,+ ) -> Option<Self> {+ Self::over(Channels::from_groups(groups, functions)?, functions)+ }++ fn over(+ channels: Channels,+ functions: &IoReportFunctions,+ ) -> Option<Self> {+ let (handle, subscribed) = functions.create_subscription(&channels.0)?;+ drop(subscribed);+ Some(Self {+ handle,+ channels,+ })+ }++ pub(super) fn snapshot(+ &self,+ functions: &IoReportFunctions,+ ) -> Option<CFRetained<CFDictionary>> {+ functions.create_samples(&self.handle, &self.channels.0)+ }+}diff --git a/crates/keisoku/src/sys/memory.rs b/crates/keisoku/src/sys/memory.rsnew file mode 100644index 000000000..dd92f45bb--- /dev/null+++ b/crates/keisoku/src/sys/memory.rs@@ -0,0 +1,70 @@+use crate::{metrics::MemoryMetrics, units::Bytes};++pub(crate) fn read_memory() -> Option<MemoryMetrics> {+ let mut ram_total = 0u64;+ unsafe {+ let mut name = [libc::CTL_HW, libc::HW_MEMSIZE];+ let mut size = core::mem::size_of::<u64>();+ if libc::sysctl(+ name.as_mut_ptr(),+ name.len() as _,+ &mut ram_total as *mut _ as *mut _,+ &mut size,+ core::ptr::null_mut(),+ 0,+ ) != 0+ {+ return None;+ }+ }++ let ram_usage = unsafe {+ let mut count: u32 = libc::HOST_VM_INFO64_COUNT as _;+ let mut statistics = core::mem::zeroed::<libc::vm_statistics64>();+ #[allow(deprecated)]+ let result = libc::host_statistics64(+ libc::mach_host_self(),+ libc::HOST_VM_INFO64,+ &mut statistics as *mut _ as *mut _,+ &mut count,+ );+ if result != 0 {+ return None;+ }+ let page_size = libc::sysconf(libc::_SC_PAGESIZE) as u64;+ (statistics.active_count as u64+ + statistics.inactive_count as u64+ + statistics.wire_count as u64+ + statistics.speculative_count as u64+ + statistics.compressor_page_count as u64+ - statistics.purgeable_count as u64+ - statistics.external_page_count as u64)+ * page_size+ };++ let (swap_usage, swap_total) = unsafe {+ let mut name = [libc::CTL_VM, libc::VM_SWAPUSAGE];+ let mut size = core::mem::size_of::<libc::xsw_usage>();+ let mut swap = core::mem::zeroed::<libc::xsw_usage>();+ if libc::sysctl(+ name.as_mut_ptr(),+ name.len() as _,+ &mut swap as *mut _ as *mut _,+ &mut size,+ core::ptr::null_mut(),+ 0,+ ) == 0+ {+ (swap.xsu_used, swap.xsu_total)+ } else {+ (0, 0)+ }+ };++ Some(MemoryMetrics {+ ram_total: Bytes(ram_total),+ ram_usage: Bytes(ram_usage),+ swap_total: Bytes(swap_total),+ swap_usage: Bytes(swap_usage),+ })+}diff --git a/crates/keisoku/src/sys/mod.rs b/crates/keisoku/src/sys/mod.rsnew file mode 100644index 000000000..0a92f016a--- /dev/null+++ b/crates/keisoku/src/sys/mod.rs@@ -0,0 +1,31 @@+#[cfg(target_os = "macos")]+mod battery;+mod constants;+#[cfg(target_os = "macos")]+mod memory;+#[cfg(not(target_os = "macos"))]+mod sysctl;+mod thermal;++#[cfg(target_os = "macos")]+pub(crate) mod ioreport;+#[cfg(target_os = "macos")]+pub(crate) mod registry;+#[cfg(target_os = "macos")]+pub(crate) mod smc;+#[cfg(target_os = "macos")]+pub(crate) mod soc;++pub(crate) mod hid;++#[cfg(target_os = "macos")]+pub(crate) use battery::read_battery;+pub(crate) use constants::{+ EVENT_TYPE_POWER, EVENT_TYPE_TEMPERATURE, HID_PAGE_APPLE_VENDOR, HID_PAGE_APPLE_VENDOR_POWER,+ HID_USAGE_POWER_CURRENT, HID_USAGE_POWER_VOLTAGE, HID_USAGE_TEMPERATURE_SENSOR, event_field_base,+};+#[cfg(target_os = "macos")]+pub(crate) use memory::read_memory;+#[cfg(not(target_os = "macos"))]+pub(crate) use sysctl::{perflevel_cores, sysctl_string};+pub(crate) use thermal::read_thermal_pressure;diff --git a/crates/keisoku/src/cf/mod.rs b/crates/keisoku/src/sys/registry/mod.rssimilarity index 69%rename from crates/keisoku/src/cf/mod.rsrename to crates/keisoku/src/sys/registry/mod.rsindex 5b80e3838..2181dc18e 100644--- a/crates/keisoku/src/cf/mod.rs+++ b/crates/keisoku/src/sys/registry/mod.rs@@ -6,9 +6,6 @@ mod service_iterator;pub use service_iterator::IoServiceIterator;-/// Convert a borrowed (Get-rule) `CFStringRef` returned by a C accessor into an-/// owned `String`. Used by the IOReport channel accessors, whose C functions-/// hand back a borrowed `CFStringRef` as `*const c_void`.pub fn cf_string_to_string(value: *const c_void) -> String {match NonNull::new(value.cast_mut().cast::<CFString>()) {Some(pointer) => unsafe { pointer.as_ref() }.to_string(),@@ -16,10 +13,6 @@ pub fn cf_string_to_string(value: *const c_void) -> String {}}-/// Look up `key` in a CF dictionary and downcast its value to the concrete CF-/// type `V`. The `<K, V>` generics on `CFDictionary` are `PhantomData`, so-/// viewing the opaque dictionary as `<CFString, CFType>` is a layout-sound-/// reference cast.pub fn dictionary_get<V: ConcreteType>(dictionary: &CFDictionary,key: &str,@@ -28,21 +21,20 @@ pub fn dictionary_get<V: ConcreteType>(dictionary.get(&CFString::from_str(key)).and_then(|value| value.downcast::<V>().ok())}-/// Bytes of a `CFData`-valued key, or `None` if the key is absent or not data.pub fn dictionary_data(dictionary: &CFDictionary,key: &str,-) -> Option<Vec<u8>> {- dictionary_get::<CFData>(dictionary, key).map(|data| cf_data_to_vec(&data))+) -> Option<Box<[u8]>> {+ dictionary_get::<CFData>(dictionary, key).map(|data| cf_data_to_bytes(&data))}-fn cf_data_to_vec(data: &CFData) -> Vec<u8> {+fn cf_data_to_bytes(data: &CFData) -> Box<[u8]> {let length = data.length();let bytes = data.byte_ptr();if length <= 0 || bytes.is_null() {- return Vec::new();+ return Box::default();}- unsafe { core::slice::from_raw_parts(bytes, length as usize) }.to_vec()+ unsafe { core::slice::from_raw_parts(bytes, length as usize) }.into()}pub fn registry_properties(entry: objc2_io_kit::io_registry_entry_t) -> Option<CFRetained<CFDictionary>> {diff --git a/crates/keisoku/src/cf/service_iterator.rs b/crates/keisoku/src/sys/registry/service_iterator.rssimilarity index 100%rename from crates/keisoku/src/cf/service_iterator.rsrename to crates/keisoku/src/sys/registry/service_iterator.rsdiff --git a/crates/keisoku/src/sys/smc/fourcc.rs b/crates/keisoku/src/sys/smc/fourcc.rsnew file mode 100644index 000000000..83928eee8--- /dev/null+++ b/crates/keisoku/src/sys/smc/fourcc.rs@@ -0,0 +1,7 @@+pub(super) fn fourcc(key: &str) -> Option<u32> {+ let bytes = key.as_bytes();+ if bytes.len() != 4 {+ return None;+ }+ Some((bytes[0] as u32) << 24 | (bytes[1] as u32) << 16 | (bytes[2] as u32) << 8 | bytes[3] as u32)+}diff --git a/crates/keisoku/src/sys/smc/key_data.rs b/crates/keisoku/src/sys/smc/key_data.rsnew file mode 100644index 000000000..6f67d5fb8--- /dev/null+++ b/crates/keisoku/src/sys/smc/key_data.rs@@ -0,0 +1,43 @@+#[repr(C)]+#[derive(Clone, Copy, Default)]+pub(super) struct SmcVersion {+ major: u8,+ minor: u8,+ build: u8,+ reserved: u8,+ release: u16,+}++#[repr(C)]+#[derive(Clone, Copy, Default)]+pub(super) struct SmcLimitData {+ version: u16,+ length: u16,+ cpu_plimit: u32,+ gpu_plimit: u32,+ mem_plimit: u32,+}++#[repr(C)]+#[derive(Clone, Copy, Default)]+pub(super) struct SmcKeyInfo {+ pub(super) data_size: u32,+ pub(super) data_type: u32,+ pub(super) data_attributes: u8,+}++#[repr(C)]+#[derive(Clone, Copy, Default)]+pub(super) struct SmcKeyData {+ pub(super) key: u32,+ pub(super) version: SmcVersion,+ pub(super) limit: SmcLimitData,+ pub(super) key_info: SmcKeyInfo,+ pub(super) result: u8,+ pub(super) status: u8,+ pub(super) data8: u8,+ pub(super) data32: u32,+ pub(super) bytes: [u8; 32],+}++const _: () = assert!(core::mem::size_of::<SmcKeyData>() == 80);diff --git a/crates/keisoku/src/smc/mod.rs b/crates/keisoku/src/sys/smc/mod.rssimilarity index 71%rename from crates/keisoku/src/smc/mod.rsrename to crates/keisoku/src/sys/smc/mod.rsindex 80c3dcd96..88b064a24 100644--- a/crates/keisoku/src/smc/mod.rs+++ b/crates/keisoku/src/sys/smc/mod.rs@@ -1,3 +1,6 @@+mod fourcc;+mod key_data;+use core::ffi::c_void;use obfstr::obfstr;@@ -7,59 +10,19 @@ use objc2_io_kit::{IOServiceMatching, IOServiceOpen, io_connect_t, io_iterator_t,};+use self::{+ fourcc::fourcc,+ key_data::{SmcKeyData, SmcKeyInfo},+};use crate::{metrics::{Fan, FanMetrics},- units::{Rpm, Watts},+ units::Rpm,};const KERNEL_INDEX_SMC: u32 = 2;const SMC_CMD_READ_BYTES: u8 = 5;const SMC_CMD_READ_KEYINFO: u8 = 9;-#[repr(C)]-#[derive(Clone, Copy, Default)]-struct SmcVersion {- major: u8,- minor: u8,- build: u8,- reserved: u8,- release: u16,-}--#[repr(C)]-#[derive(Clone, Copy, Default)]-struct SmcLimitData {- version: u16,- length: u16,- cpu_plimit: u32,- gpu_plimit: u32,- mem_plimit: u32,-}--#[repr(C)]-#[derive(Clone, Copy, Default)]-struct SmcKeyInfo {- data_size: u32,- data_type: u32,- data_attributes: u8,-}--#[repr(C)]-#[derive(Clone, Copy, Default)]-struct SmcKeyData {- key: u32,- version: SmcVersion,- limit: SmcLimitData,- key_info: SmcKeyInfo,- result: u8,- status: u8,- data8: u8,- data32: u32,- bytes: [u8; 32],-}--const _: () = assert!(core::mem::size_of::<SmcKeyData>() == 80);-pub struct Smc {connection: io_connect_t,}@@ -87,10 +50,6 @@ impl Smc {})}- pub fn package_watts(&self) -> Option<Watts> {- self.read_f32(obfstr!("PSTR")).map(Watts)- }-pub fn fans(&self) -> FanMetrics {let count = self.read_u8(obfstr!("FNum")).unwrap_or(0);let fans = (0..count)@@ -118,21 +77,23 @@ impl Smc {&self,key: &str,) -> Option<f32> {- let (data_type, bytes) = self.read_key(key)?;- (data_type == fourcc(obfstr!("flt "))?).then(|| f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))+ let (data_type, data_size, bytes) = self.read_key(key)?;+ (data_type == fourcc(obfstr!("flt "))? && data_size >= 4)+ .then(|| f32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))}fn read_u8(&self,key: &str,) -> Option<u8> {- self.read_key(key).map(|(_, bytes)| bytes[0])+ let (_, data_size, bytes) = self.read_key(key)?;+ (data_size >= 1).then_some(bytes[0])}fn read_key(&self,key: &str,- ) -> Option<(u32, [u8; 32])> {+ ) -> Option<(u32, u32, [u8; 32])> {let key = fourcc(key)?;let info = self.call(&SmcKeyData {key,@@ -148,7 +109,7 @@ impl Smc {data8: SMC_CMD_READ_BYTES,..Default::default()})?;- Some((info.key_info.data_type, value.bytes))+ Some((info.key_info.data_type, info.key_info.data_size, value.bytes))}fn call(@@ -176,11 +137,3 @@ impl Drop for Smc {IOServiceClose(self.connection);}}--fn fourcc(key: &str) -> Option<u32> {- let bytes = key.as_bytes();- if bytes.len() != 4 {- return None;- }- Some((bytes[0] as u32) << 24 | (bytes[1] as u32) << 16 | (bytes[2] as u32) << 8 | bytes[3] as u32)-}diff --git a/crates/keisoku/src/soc.rs b/crates/keisoku/src/sys/soc.rssimilarity index 84%rename from crates/keisoku/src/soc.rsrename to crates/keisoku/src/sys/soc.rsindex 23756551a..d02755ab0 100644--- a/crates/keisoku/src/soc.rs+++ b/crates/keisoku/src/sys/soc.rs@@ -1,7 +1,7 @@use objc2_core_foundation::CFDictionary;use serde::Serialize;-use crate::cf::{IoServiceIterator, dictionary_data, registry_properties};+use crate::sys::registry::{IoServiceIterator, dictionary_data, registry_properties};#[derive(Debug, Default, Clone, Serialize)]pub struct SocInfo {@@ -13,15 +13,15 @@ pub struct SocInfo {pub ecpu_label: String,pub pcpu_label: String,pub gpu_cores: u8,- pub ecpu_frequencies: Vec<u32>,- pub pcpu_frequencies: Vec<u32>,- pub gpu_frequencies: Vec<u32>,+ pub ecpu_frequencies: Box<[u32]>,+ pub pcpu_frequencies: Box<[u32]>,+ pub gpu_frequencies: Box<[u32]>,}fn dvfs_frequencies(dictionary: &CFDictionary,key: &str,-) -> Option<Vec<u32>> {+) -> Option<Box<[u32]>> {let bytes = dictionary_data(dictionary, key)?;if bytes.len() < 8 {return None;@@ -35,10 +35,12 @@ fn dvfs_frequencies(Some(frequencies)}-fn to_megahertz(- frequencies: Vec<u32>,- scale: u32,-) -> Vec<u32> {+fn to_megahertz(frequencies: &[u32]) -> Box<[u32]> {+ let scale = if frequencies.iter().copied().max().unwrap_or(0) >= 10_000_000 {+ 1_000_000+ } else {+ 1_000+ };frequencies.iter().map(|frequency| frequency / scale).collect()}@@ -66,10 +68,9 @@ fn cpu_frequencies(dictionary: &CFDictionary,key: &str,is_efficiency_cluster: bool,- scale: u32,-) -> Option<Vec<u32>> {+) -> Option<Box<[u32]>> {if let Some(frequencies) = dvfs_frequencies(dictionary, key) {- return Some(to_megahertz(frequencies, scale));+ return Some(to_megahertz(&frequencies));}let (ecpu_key, pcpu_key) = cluster_voltage_state_keys(dictionary)?;let key = if is_efficiency_cluster {@@ -77,7 +78,7 @@ fn cpu_frequencies(} else {pcpu_key};- Some(to_megahertz(dvfs_frequencies(dictionary, &key)?, scale))+ Some(to_megahertz(&dvfs_frequencies(dictionary, &key)?))}fn parse_cpu_cores(processors: &str) -> (u64, u64, bool) {@@ -124,14 +125,6 @@ impl SocInfo {.and_then(|cores| cores.parse::<u64>().ok()).unwrap_or(0) as u8;- let before_m4 = chip_name.contains("M1") || chip_name.contains("M2") || chip_name.contains("M3");- let cpu_scale: u32 = if before_m4 {- 1000 * 1000- } else {- 1000- };- let gpu_scale: u32 = 1000 * 1000;-let mut soc_info = SocInfo {chip_name,mac_model,@@ -157,14 +150,14 @@ impl SocInfo {continue;}if let Some(properties) = registry_properties(entry) {- if let Some(frequencies) = cpu_frequencies(&properties, "voltage-states1-sram", true, cpu_scale) {+ if let Some(frequencies) = cpu_frequencies(&properties, "voltage-states1-sram", true) {soc_info.ecpu_frequencies = frequencies;}- if let Some(frequencies) = cpu_frequencies(&properties, "voltage-states5-sram", false, cpu_scale) {+ if let Some(frequencies) = cpu_frequencies(&properties, "voltage-states5-sram", false) {soc_info.pcpu_frequencies = frequencies;}if let Some(frequencies) = dvfs_frequencies(&properties, "voltage-states9") {- soc_info.gpu_frequencies = to_megahertz(frequencies, gpu_scale);+ soc_info.gpu_frequencies = to_megahertz(&frequencies);}}}diff --git a/crates/keisoku/src/sys/sysctl.rs b/crates/keisoku/src/sys/sysctl.rsnew file mode 100644index 000000000..2958c1da0--- /dev/null+++ b/crates/keisoku/src/sys/sysctl.rs@@ -0,0 +1,38 @@+pub(crate) fn sysctl_string(name: &str) -> Option<String> {+ let name = std::ffi::CString::new(name).ok()?;+ let mut len = 0usize;+ let probe = unsafe { libc::sysctlbyname(name.as_ptr(), std::ptr::null_mut(), &mut len, std::ptr::null_mut(), 0) };+ if probe != 0 || len == 0 {+ return None;+ }+ let mut buffer = vec![0u8; len];+ let read =+ unsafe { libc::sysctlbyname(name.as_ptr(), buffer.as_mut_ptr().cast(), &mut len, std::ptr::null_mut(), 0) };+ if read != 0 {+ return None;+ }+ if let Some(nul) = buffer.iter().position(|&byte| byte == 0) {+ buffer.truncate(nul);+ }+ String::from_utf8(buffer).ok()+}++fn sysctl_u32(name: &str) -> Option<u32> {+ let name = std::ffi::CString::new(name).ok()?;+ let mut value = 0u32;+ let mut len = std::mem::size_of::<u32>();+ let read = unsafe {+ libc::sysctlbyname(name.as_ptr(), std::ptr::addr_of_mut!(value).cast(), &mut len, std::ptr::null_mut(), 0)+ };+ (read == 0).then_some(value)+}++pub(crate) fn perflevel_cores() -> (u8, u8) {+ let performance = sysctl_u32("hw.perflevel0.logicalcpu").unwrap_or(0);+ let efficiency = if sysctl_u32("hw.nperflevels").unwrap_or(1) > 1 {+ sysctl_u32("hw.perflevel1.logicalcpu").unwrap_or(0)+ } else {+ 0+ };+ (performance as u8, efficiency as u8)+}diff --git a/crates/keisoku/src/sys/thermal.rs b/crates/keisoku/src/sys/thermal.rsnew file mode 100644index 000000000..6afed1ed6--- /dev/null+++ b/crates/keisoku/src/sys/thermal.rs@@ -0,0 +1,43 @@+use core::ffi::c_char;++use crate::metrics::ThermalPressure;++impl ThermalPressure {+ fn from_level(level: u64) -> Option<Self> {+ match level {+ 0 => Some(ThermalPressure::Nominal),+ 1 => Some(ThermalPressure::Moderate),+ 2 => Some(ThermalPressure::Heavy),+ 3 => Some(ThermalPressure::Trapping),+ 4 => Some(ThermalPressure::Sleeping),+ _ => None,+ }+ }+}++pub(crate) fn read_thermal_pressure() -> Option<ThermalPressure> {+ unsafe extern "C" {+ fn notify_register_check(+ name: *const c_char,+ out_token: *mut i32,+ ) -> u32;+ fn notify_get_state(+ token: i32,+ out_state: *mut u64,+ ) -> u32;+ fn notify_cancel(token: i32) -> u32;+ }++ let name = std::ffi::CString::new("com.apple.system.thermalpressurelevel").ok()?;+ let mut token = 0i32;+ if unsafe { notify_register_check(name.as_ptr(), &mut token) } != 0 {+ return None;+ }+ let mut level = 0u64;+ let result = unsafe { notify_get_state(token, &mut level) };+ unsafe { notify_cancel(token) };+ if result != 0 {+ return None;+ }+ ThermalPressure::from_level(level)+}diff --git a/crates/keisoku/src/units.rs b/crates/keisoku/src/units.rsindex 9404d4f24..fe0eea516 100644--- a/crates/keisoku/src/units.rs+++ b/crates/keisoku/src/units.rs@@ -1,15 +1,8 @@use serde::{Deserialize, Serialize};macro_rules! unit {- ($(#[$doc:meta])* $name:ident($inner:ty) = $suffix:literal) => {- $(#[$doc])*- #[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd, Serialize, Deserialize)]- #[serde(transparent)]- #[repr(transparent)]- pub struct $name(pub $inner);-+ (@shared $name:ident($inner:ty) = $suffix:literal) => {impl $name {-pub const fn value(self) -> $inner {self.0}@@ -29,14 +22,80 @@ macro_rules! unit {Self(value)}}++ impl core::ops::Add for $name {+ type Output = Self;++ fn add(+ self,+ other: Self,+ ) -> Self {+ Self(self.0 + other.0)+ }+ }++ impl core::ops::Sub for $name {+ type Output = Self;++ fn sub(+ self,+ other: Self,+ ) -> Self {+ Self(self.0 - other.0)+ }+ }++ impl core::iter::Sum for $name {+ fn sum<I: Iterator<Item = Self>>(iterator: I) -> Self {+ Self(iterator.map(|unit| unit.0).sum())+ }+ }+ };++ (float $name:ident($inner:ty) = $suffix:literal) => {+ #[derive(Clone, Copy, Debug, Default, PartialEq, PartialOrd, Serialize, Deserialize)]+ #[serde(transparent)]+ #[repr(transparent)]+ pub struct $name(pub $inner);++ unit!(@shared $name($inner) = $suffix);++ impl core::ops::Mul<$inner> for $name {+ type Output = Self;++ fn mul(+ self,+ factor: $inner,+ ) -> Self {+ Self(self.0 * factor)+ }+ }++ impl core::ops::Div<$inner> for $name {+ type Output = Self;++ fn div(+ self,+ divisor: $inner,+ ) -> Self {+ Self(self.0 / divisor)+ }+ }+ };++ (int $name:ident($inner:ty) = $suffix:literal) => {+ #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]+ #[serde(transparent)]+ #[repr(transparent)]+ pub struct $name(pub $inner);++ unit!(@shared $name($inner) = $suffix);};}-unit!(Watts(f32) = "W");-unit!(Percent(f32) = "%");-unit!(Celsius(f32) = "°C");-unit!(Megahertz(u32) = "MHz");-unit!(GigabytesPerSecond(f32) = "GB/s");-unit!(Bytes(u64) = "B");-unit!(Milliseconds(u64) = "ms");-unit!(Rpm(f32) = "rpm");+unit!(float Watts(f32) = "W");+unit!(float Joules(f32) = "J");+unit!(float Percent(f32) = "%");+unit!(float GigabytesPerSecond(f32) = "GB/s");+unit!(int Bytes(u64) = "B");+unit!(float Rpm(f32) = "rpm");diff --git a/crates/keisoku/tests/table.rs b/crates/keisoku/tests/table.rsdeleted file mode 100644index cbf5c3f26..000000000--- a/crates/keisoku/tests/table.rs+++ /dev/null@@ -1,78 +0,0 @@-use std::time::Duration;--use keisoku::Collector;-use ratatui::{- Terminal,- backend::TestBackend,- layout::Constraint,- style::{Color, Modifier, Style},- widgets::{Block, Borders, Row, Table},-};--#[test]-fn render_table() {- let mut collector = Collector::new();- let device = collector.device();- let snapshot = collector.sample(Duration::from_millis(300));-- let na = "—";- let mut lines: Vec<[String; 3]> = vec![- ["CPU".into(), snapshot.cpu.as_ref().map_or(na.into(), |c| format!("{:.1} %", c.usage.value())), String::new()],- ["GPU".into(), snapshot.gpu.as_ref().map_or(na.into(), |g| format!("{:.0} %", g.usage.value())), String::new()],- [- "ANE".into(),- snapshot.neural_engine.as_ref().map_or(na.into(), |a| format!("{:.0} %", a.active.value())),- String::new(),- ],- [- "Power".into(),- snapshot.power.as_ref().map_or(na.into(), |p| format!("{:.2} W", p.package.value())),- String::new(),- ],- [- "Memory".into(),- snapshot.memory.as_ref().map_or(na.into(), |m| {- format!("{:.1} / {:.1} GB", m.ram_usage.value() as f64 / 1e9, m.ram_total.value() as f64 / 1e9)- }),- String::new(),- ],- [- "CPU temp".into(),- snapshot- .temperatures- .as_ref()- .and_then(|t| t.cpu_average)- .map_or(na.into(), |c| format!("{:.1} °C", c.value())),- String::new(),- ],- [- "GPU temp".into(),- snapshot- .temperatures- .as_ref()- .and_then(|t| t.gpu_average)- .map_or(na.into(), |g| format!("{:.1} °C", g.value())),- String::new(),- ],- ["────────".into(), "──────".into(), "──────────".into()],- ];- for sensor in &snapshot.sensors {- lines.push([sensor.name.clone(), format!("{:.1}", sensor.value), sensor.component.to_string()]);- }-- let accent = Style::default().fg(Color::Green);- let height = (lines.len() + 4) as u16;- let header = Row::new(["Metric", "Value", "Detail"]).style(accent.add_modifier(Modifier::BOLD));- let rows: Vec<Row> = lines.into_iter().map(Row::new).collect();- let table = Table::new(rows, [Constraint::Length(20), Constraint::Length(16), Constraint::Min(22)])- .header(header)- .block(Block::default().borders(Borders::ALL).border_style(accent).title(format!(- " kanshi · {} · {:.0} GB ",- device.chip,- device.ram_total.value() as f64 / 1e9- )));-- let mut terminal = Terminal::new(TestBackend::new(66, height)).unwrap();- terminal.draw(|frame| frame.render_widget(table, frame.area())).unwrap();- println!("\n{}", terminal.backend());-}diff --git a/crates/keisoku/tests/telemetry.rs b/crates/keisoku/tests/telemetry.rsindex d2d82d76b..d71686332 100644--- a/crates/keisoku/tests/telemetry.rs+++ b/crates/keisoku/tests/telemetry.rs@@ -1,65 +1,100 @@-use std::time::Duration;--use keisoku::Collector;-#[test]fn available_telemetry() {- let mut collector = Collector::new();- let device = collector.device();- let snapshot = collector.sample(Duration::from_millis(300));- let flag = |present: bool| {- if present {- "yes"- } else {- "--"- }- };+ use keisoku::Device;++ let mut device = Device::new();+ let chip = device.chip();+ let efficiency_cores = device.efficiency_cores();+ let performance_cores = device.performance_cores();+ let gpu_cores = device.gpu_cores();+ let memory = device.memory();+ let fans = device.fans();+ let battery = device.battery();+ let thermal = device.thermal();+ let sensors = device.temperature_sensors();+ let voltage = device.voltage_sensors();+ let current = device.current_sensors();+ let rail_power = device.rail_power();println!("--- keisoku available telemetry ---");+ println!("device {} {}E+{}P {} GPU", chip, efficiency_cores, performance_cores, gpu_cores);+ println!("fans {}", fans.as_ref().map(|fans| fans.fans.len()).unwrap_or(0));println!(- "device {} {}E+{}P {} GPU {:.1} GB",- device.chip,- device.efficiency_cores,- device.performance_cores,- device.gpu_cores,- device.ram_total.value() as f64 / 1e9,+ "battery {}",+ battery.as_ref().map(|battery| format!("{:.0}%", battery.percent.value())).unwrap_or_else(|| "--".to_string()),);- println!("cpu {}", flag(snapshot.cpu.is_some()));- println!("gpu {}", flag(snapshot.gpu.is_some()));- println!("neural {}", flag(snapshot.neural_engine.is_some()));- println!("power {}", flag(snapshot.power.is_some()));- println!("bandwidth {}", flag(snapshot.bandwidth.is_some()));- println!("memory {}", flag(snapshot.memory.is_some()));- println!("fans {}", flag(snapshot.fans.is_some()));- println!("battery {}", flag(snapshot.battery.is_some()));- println!("temps {}", flag(snapshot.temperatures.is_some()));- println!("sensors {}", snapshot.sensors.len());- println!("voltage {}", snapshot.voltage.len());- println!("current {}", snapshot.current.len());- println!("rail_power {}", snapshot.rail_power().map_or("--".into(), |w| format!("{:.2} W", w.value())));+ println!("thermal {}", thermal.map_or_else(|| "--".to_string(), |level| format!("{level:?}")));+ println!("sensors {}", sensors.len());+ println!("voltage {}", voltage.len());+ println!("current {}", current.len());+ println!("rail_power {}", rail_power.map_or("--".into(), |watts| format!("{:.2} W", watts.value())));- if let Some(memory) = &snapshot.memory {+ if let Some(memory) = &memory {println!(" ram {:.2} / {:.2} GB",memory.ram_usage.value() as f64 / 1e9,memory.ram_total.value() as f64 / 1e9,);}- if let Some(temperatures) = &snapshot.temperatures {- if let Some(cpu) = temperatures.cpu_average {- println!(" cpu temp {:.1} C", cpu.value());- }- if let Some(gpu) = temperatures.gpu_average {- println!(" gpu temp {:.1} C", gpu.value());- }- }- for sensor in snapshot.sensors.iter().take(24) {+ for sensor in sensors.iter().take(24) {println!(" {:<26} {:>8.2} [{}]", sensor.name, sensor.value, sensor.component);}- for volts in &snapshot.voltage {+ for volts in voltage.iter() {println!(" {:<26} {:>8.3} V [{}]", volts.name, volts.value, volts.component);}- for amps in &snapshot.current {+ for amps in current.iter() {println!(" {:<26} {:>8.3} A [{}]", amps.name, amps.value, amps.component);}++ #[cfg(target_os = "macos")]+ {+ use std::time::Duration;++ use keisoku::{+ Ane, AneBandwidth, Cpu, Device, DramBytes, DramHistogram, DramRead, DramWrite, EnergyRail, Gpu, Ram, Select,+ };++ let mut handle = Device::interval_measurement::<+ Select![+ EnergyRail<Cpu>,+ EnergyRail<Gpu>,+ EnergyRail<Ane>,+ EnergyRail<Ram>,+ AneBandwidth,+ DramBytes<DramRead>,+ DramBytes<DramWrite>,+ DramHistogram<DramRead>,+ DramHistogram<DramWrite>,+ ],+ >();+ handle.start();+ std::thread::sleep(Duration::from_millis(300));+ let sample = handle.stop().expect("interval sample");++ let cpu_energy = sample.get::<EnergyRail<Cpu>>();+ let gpu_energy = sample.get::<EnergyRail<Gpu>>();+ let ane_energy = sample.get::<EnergyRail<Ane>>();+ let ram_energy = sample.get::<EnergyRail<Ram>>();+ let ane = sample.get::<AneBandwidth>();+ let dram_read_bytes = sample.get::<DramBytes<DramRead>>();+ let dram_write_bytes = sample.get::<DramBytes<DramWrite>>();+ let dram_read = sample.get::<DramHistogram<DramRead>>();+ let dram_write = sample.get::<DramHistogram<DramWrite>>();++ println!(+ "energy CPU {:.3} J GPU {:.3} J ANE {:.3} J RAM {:.3} J",+ cpu_energy.value(),+ gpu_energy.value(),+ ane_energy.value(),+ ram_energy.value(),+ );+ println!("neural {:.2}%", ane.value());+ println!(+ "bandwidth R {:.1} GB/s ({} B) W {:.1} GB/s ({} B)",+ dram_read.value(),+ dram_read_bytes.value(),+ dram_write.value(),+ dram_write_bytes.value(),+ );+ }}diff --git a/crates/nagare/src/chat/token.rs b/crates/nagare/src/chat/token.rsindex 6d654706e..6f1c66b8a 100644--- a/crates/nagare/src/chat/token.rs+++ b/crates/nagare/src/chat/token.rs@@ -38,6 +38,7 @@ pub struct Session {encoding: Encoding,input_tokens: Vec<u64>,stop_token_ids: Box<[u64]>,+ power_recorder: Box<dyn PowerRecorder>,}impl Session {@@ -71,6 +72,7 @@ impl Session {encoding,input_tokens: Vec::new(),stop_token_ids,+ power_recorder: <dyn PowerRecorder>::create(),})}@@ -89,7 +91,7 @@ impl Session {cancel_token: CancellationToken,) -> Pin<Box<dyn Stream<Item = Result<Output, ChatSessionError>> + Send + 'a>> {let time_start = Instant::now();- let power_recorder = <dyn PowerRecorder>::start();+ self.power_recorder.begin();let curr_all_tokens = self.encoding.state().tokens.clone();let new_all_tokens = match self.build_input(input) {@@ -127,7 +129,7 @@ impl Session {encoding: &mut self.encoding,max_context_length: self.instance.max_context_length(),stop_token_ids: self.stop_token_ids.clone(),- power_recorder,+ power_recorder: &mut *self.power_recorder,time_start,time_last_token: None,@@ -275,7 +277,7 @@ struct StreamingState<'a> {encoding: &'a mut Encoding,max_context_length: Option<usize>,stop_token_ids: Box<[u64]>,- power_recorder: Box<dyn PowerRecorder>,+ power_recorder: &'a mut dyn PowerRecorder,time_start: Instant,time_last_token: Option<Instant>,@@ -313,7 +315,7 @@ impl StreamingState<'_> {&self,last_stat: bool,) -> ChatReplyStats {- let power_stats = last_stat.then(|| self.power_recorder.stop()).flatten();+ let power_stats = last_stat.then(|| self.power_recorder.finish()).flatten();let total_duration = self.time_last_token.unwrap_or(Instant::now()).duration_since(self.time_start);let ttft_duration = if let (Some(start), Some(finish)) = (self.time_prefill_start, self.time_first_token) {diff --git a/crates/nagare/src/util/power/apple.rs b/crates/nagare/src/util/power/apple.rsindex 4beb079fc..c3442ad68 100644--- a/crates/nagare/src/util/power/apple.rs+++ b/crates/nagare/src/util/power/apple.rs@@ -1,93 +1,43 @@#![cfg(target_vendor = "apple")]-use std::sync::Mutex;+use std::cell::RefCell;+use keisoku::{PowerMeter, PowerReading, Watts};use shoji::types::session::chat::ChatReplyPowerStats;use crate::util::power::PowerRecorder;pub struct ApplePowerRecorder {- // Option so stop() can take ownership of the handle through a shared reference.- handle: Mutex<Option<keisoku::RecorderHandle>>,+ meter: RefCell<PowerMeter>,}impl ApplePowerRecorder {pub fn new() -> Self {Self {- handle: Mutex::new(Some(keisoku::start(keisoku::Config {- interval: std::time::Duration::from_millis(100),- }))),+ meter: RefCell::new(PowerMeter::new()),}}}impl PowerRecorder for ApplePowerRecorder {- fn stop(&self) -> Option<ChatReplyPowerStats> {- let handle = self.handle.lock().ok()?.take()?;- let session = handle.stop();-- let mut samples_count = 0_i64;- // Each accumulator integrates watts over time (watts × seconds); the time-weighted- // average is the integral divided by total_elapsed_secs.- let mut cpu_joules = 0.0_f64;- let mut gpu_joules = 0.0_f64;- let mut gpu_sram_joules = 0.0_f64;- let mut ane_joules = 0.0_f64;- let mut ram_joules = 0.0_f64;- let mut total_joules = 0.0_f64;- let mut energy_joules = 0.0_f64;- let mut max_package_watts = 0.0_f64;- let mut previous_elapsed_secs = 0.0_f64;- let mut total_elapsed_secs = 0.0_f64;-- for snapshot in &session.snapshots {- // elapsed is stamped after each sample, so consecutive gaps partition the- // recording timeline without overlap.- let elapsed_secs = snapshot.elapsed.value() as f64 / 1000.0;- let window_secs = (elapsed_secs - previous_elapsed_secs).max(0.0);- previous_elapsed_secs = elapsed_secs;-- // Prefer SoC IOReport power (macOS); fall back to HID rail power on iOS.- let wall_watts = match snapshot.power.as_ref() {- Some(power) => {- cpu_joules += power.cpu.value() as f64 * window_secs;- gpu_joules += power.gpu.value() as f64 * window_secs;- gpu_sram_joules += power.gpu_sram.value() as f64 * window_secs;- ane_joules += power.ane.value() as f64 * window_secs;- ram_joules += power.ram.value() as f64 * window_secs;- total_joules += power.total.value() as f64 * window_secs;- power.package.value() as f64- },- None => match snapshot.rail_power() {- Some(rail_watts) => {- let rail_watts = rail_watts.value() as f64;- total_joules += rail_watts * window_secs;- rail_watts- },- None => continue,- },- };- samples_count += 1;- max_package_watts = max_package_watts.max(wall_watts);- energy_joules += wall_watts * window_secs;- total_elapsed_secs = elapsed_secs;- }+ fn begin(&self) {+ self.meter.borrow_mut().start();+ }- if samples_count == 0 || total_elapsed_secs <= 0.0 {- return None;- }+ fn finish(&self) -> Option<ChatReplyPowerStats> {+ self.meter.borrow_mut().stop().map(stats)+ }+}- Some(ChatReplyPowerStats {- samples_count,- average_cpu_watts: cpu_joules / total_elapsed_secs,- average_gpu_watts: gpu_joules / total_elapsed_secs,- average_gpu_sram_watts: gpu_sram_joules / total_elapsed_secs,- average_ane_watts: ane_joules / total_elapsed_secs,- average_ram_watts: ram_joules / total_elapsed_secs,- average_total_watts: total_joules / total_elapsed_secs,- average_package_watts: energy_joules / total_elapsed_secs,- max_package_watts,- energy_joules,- })+fn stats(reading: PowerReading) -> ChatReplyPowerStats {+ let watts = |value: Option<Watts>| value.map_or(0.0, |watts| watts.value() as f64);+ ChatReplyPowerStats {+ samples_count: reading.samples as i64,+ average_cpu_watts: watts(reading.cpu),+ average_gpu_watts: watts(reading.gpu),+ average_ane_watts: watts(reading.ane),+ average_ram_watts: watts(reading.ram),+ average_total_watts: reading.total.value() as f64,+ energy_joules: reading.energy.value() as f64,}}diff --git a/crates/nagare/src/util/power/mod.rs b/crates/nagare/src/util/power/mod.rsindex 1b407c7ee..2f9d3901d 100644--- a/crates/nagare/src/util/power/mod.rs+++ b/crates/nagare/src/util/power/mod.rs@@ -6,11 +6,12 @@ mod stub;use shoji::types::session::chat::ChatReplyPowerStats;pub trait PowerRecorder: Send {- fn stop(&self) -> Option<ChatReplyPowerStats>;+ fn begin(&self);+ fn finish(&self) -> Option<ChatReplyPowerStats>;}impl dyn PowerRecorder {- pub fn start() -> Box<dyn PowerRecorder> {+ pub fn create() -> Box<dyn PowerRecorder> {#[cfg(target_vendor = "apple")]{use crate::util::power::apple::ApplePowerRecorder;diff --git a/crates/nagare/src/util/power/stub.rs b/crates/nagare/src/util/power/stub.rsindex c1c00762e..95bbe8a3f 100644--- a/crates/nagare/src/util/power/stub.rs+++ b/crates/nagare/src/util/power/stub.rs@@ -11,7 +11,9 @@ impl StubPowerRecorder {}impl PowerRecorder for StubPowerRecorder {- fn stop(&self) -> Option<ChatReplyPowerStats> {+ fn begin(&self) {}++ fn finish(&self) -> Option<ChatReplyPowerStats> {None}}diff --git a/crates/shoji/src/types/session/chat/reply/stats.rs b/crates/shoji/src/types/session/chat/reply/stats.rsindex b04e89094..75ff80c43 100644--- a/crates/shoji/src/types/session/chat/reply/stats.rs+++ b/crates/shoji/src/types/session/chat/reply/stats.rs@@ -6,12 +6,9 @@ pub struct ChatReplyPowerStats {pub samples_count: i64,pub average_cpu_watts: f64,pub average_gpu_watts: f64,- pub average_gpu_sram_watts: f64,pub average_ane_watts: f64,pub average_ram_watts: f64,pub average_total_watts: f64,- pub average_package_watts: f64,- pub max_package_watts: f64,pub energy_joules: f64,}diff --git a/crates/test-runner/Cargo.toml b/crates/test-runner/Cargo.tomlindex c41ddb424..a904c388e 100644--- a/crates/test-runner/Cargo.toml+++ b/crates/test-runner/Cargo.toml@@ -17,9 +17,11 @@ nightly-harness = [][dependencies]criterion.workspace = true-# for getting gpu temperature-keisoku.workspace = true[target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies]objc2 = { workspace = true, optional = true }objc2-foundation = { workspace = true, optional = true }++# GPU temperature for bench cooldown; keisoku is Apple-only.+[target.'cfg(target_vendor = "apple")'.dependencies]+keisoku.workspace = truediff --git a/crates/test-runner/src/metrics.rs b/crates/test-runner/src/metrics.rsindex cfb29f94f..2b78c4512 100644--- a/crates/test-runner/src/metrics.rs+++ b/crates/test-runner/src/metrics.rs@@ -2,6 +2,7 @@ use std::{thread::sleep, time::Duration};const COOL_GPU_TEMP: f32 = 60.0;+#[cfg(target_vendor = "apple")]fn get_gpu_temp() -> f32 {let (sum, count) = keisoku::thermal_sensors().iter()@@ -14,6 +15,11 @@ fn get_gpu_temp() -> f32 {}}+#[cfg(not(target_vendor = "apple"))]+fn get_gpu_temp() -> f32 {+ 0.0+}+pub fn wait_gpu_cooldown() {let mut gpu_temp = get_gpu_temp();if gpu_temp <= COOL_GPU_TEMP {diff --git a/crates/uzu/src/cli/components/history_cell.rs b/crates/uzu/src/cli/components/history_cell.rsindex 0e1145af9..e974f6feb 100644--- a/crates/uzu/src/cli/components/history_cell.rs+++ b/crates/uzu/src/cli/components/history_cell.rs@@ -196,7 +196,7 @@ fn chat_reply_stats_component(let power = stats.power_stats.as_ref()- .map(|power| format!("{:.2} W avg / {:.2} W max", power.average_package_watts, power.max_package_watts))+ .map(|power| format!("{:.2} W avg", power.average_total_watts)).unwrap_or_else(|| SYMBOL_LONG_DASH.to_string());let energy = stats.power_stats@@ -227,11 +227,11 @@ fn chat_reply_stats_component(color: subtitle_color,)Text(- content: format!("package power: {power}"),+ content: format!("total power: {power}"),color: subtitle_color,)Text(- content: format!("package energy: {energy}"),+ content: format!("total energy: {energy}"),color: subtitle_color,)Text(diff --git a/tools/uv.lock b/tools/uv.lockindex 3846d52ca..2acd4dd0d 100644--- a/tools/uv.lock+++ b/tools/uv.lock@@ -1,6 +1,14 @@version = 1revision = 3requires-python = ">=3.12"+resolution-markers = [+ "python_full_version >= '3.14' and sys_platform == 'win32'",+ "python_full_version >= '3.14' and sys_platform == 'emscripten'",+ "python_full_version >= '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'",+ "python_full_version < '3.14' and sys_platform == 'win32'",+ "python_full_version < '3.14' and sys_platform == 'emscripten'",+ "python_full_version < '3.14' and sys_platform != 'emscripten' and sys_platform != 'win32'",+][[package]]name = "annotated-doc"@@ -185,37 +193,37 @@ wheels = [[package.optional-dependencies]cublas = [- { name = "nvidia-cublas", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },+ { name = "nvidia-cublas" },]cudart = [- { name = "nvidia-cuda-runtime", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },+ { name = "nvidia-cuda-runtime" },]cufft = [- { name = "nvidia-cufft", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },+ { name = "nvidia-cufft" },]cufile = [- { name = "nvidia-cufile", marker = "sys_platform == 'linux'" },+ { name = "nvidia-cufile" },]cupti = [- { name = "nvidia-cuda-cupti", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },+ { name = "nvidia-cuda-cupti" },]curand = [- { name = "nvidia-curand", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },+ { name = "nvidia-curand" },]cusolver = [- { name = "nvidia-cusolver", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },+ { name = "nvidia-cusolver" },]cusparse = [- { name = "nvidia-cusparse", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },+ { name = "nvidia-cusparse" },]nvjitlink = [- { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },+ { name = "nvidia-nvjitlink" },]nvrtc = [- { name = "nvidia-cuda-nvrtc", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },+ { name = "nvidia-cuda-nvrtc" },]nvtx = [- { name = "nvidia-nvtx", marker = "sys_platform == 'linux' or sys_platform == 'win32'" },+ { name = "nvidia-nvtx" },][[package]]