Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
544de0ff88 | ||
|
|
3224558ac4 | ||
|
|
6c34cf3c86 | ||
|
|
3c9e209289 | ||
|
|
6e07fad771 | ||
|
|
a46f91f2ad | ||
|
|
65468f6dfb | ||
|
|
72ed8256c8 | ||
|
|
4394c1e332 | ||
|
|
5b06749094 | ||
|
|
0bc6c0a483 | ||
|
|
0aaa9d0110 | ||
|
|
54b6e6a7f8 | ||
|
|
f59ee440af | ||
|
|
7046777fa9 | ||
|
|
66401bec28 | ||
|
|
76cb48be09 | ||
|
|
d24fa7de35 | ||
|
|
6a02d9993d | ||
|
|
f2dc6bc7fb | ||
|
|
d8e469ec9e | ||
|
|
91d50dcbae | ||
|
|
36c7ea2319 | ||
|
|
fda8bf9e49 | ||
|
|
feceb2412d |
@@ -7,26 +7,52 @@
|
||||
objects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
0A7117B3B7CC7112F2527574 /* MMPowerTelemetryProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 02F5FDE260999C39E978D849 /* MMPowerTelemetryProvider.m */; };
|
||||
160334CC765E091A7CBE21AA /* MMCPULoadTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4CE92B1A8D7FDBB6499448E1 /* MMCPULoadTests.swift */; };
|
||||
1879A3DCF6E305D7F2CD472E /* CoreFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2345555FF9780B02A90CC7A9 /* CoreFoundation.framework */; };
|
||||
1B15F48F6B19E9EA4556ECD5 /* MMStorageTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78325870C7CD8312AECA2236 /* MMStorageTests.swift */; };
|
||||
1B3F1C8ABF0ADFAA290FF6F6 /* MMSMCParser.m in Sources */ = {isa = PBXBuildFile; fileRef = 375AA781A2AA0A20B119C7B7 /* MMSMCParser.m */; };
|
||||
22CA7351A745F7837E487051 /* MMPeripheralsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D1486E1512594482380CB492 /* MMPeripheralsTests.swift */; };
|
||||
2C0F7AB93691ED8AA86FBCF0 /* MMProcessDetailInspector.m in Sources */ = {isa = PBXBuildFile; fileRef = 52E641F8A664D456518EDBA4 /* MMProcessDetailInspector.m */; };
|
||||
3BA6709B727B1AAC6C4310B5 /* MMProcessDetailsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7187632FF63B3B0D07FE9194 /* MMProcessDetailsTests.swift */; };
|
||||
3C0AC14F803C813287D8A663 /* IOKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 007F48A5A599AB4E8D216D16 /* IOKit.framework */; };
|
||||
4419FE7554489B23976E2970 /* MMCPULoadProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = D68FC8100D08DB6202F46339 /* MMCPULoadProvider.m */; };
|
||||
4752C49841375B88194F7635 /* MMPeripheralsProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 2E6A10A13A49E22E51862895 /* MMPeripheralsProvider.m */; };
|
||||
4C1A92F4DEF4C824976115C2 /* MMNetworkSocketsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 374B1BF631CC4738CB52CA3B /* MMNetworkSocketsTests.swift */; };
|
||||
57BA02AE1CE24DBD02BD03A4 /* MMComponentThermalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B288C7402E2C00E75F8CD016 /* MMComponentThermalTests.swift */; };
|
||||
5D31906EA986E2BA92E86FA8 /* MMNetworkBandwidthTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27C612287333D757C92A076A /* MMNetworkBandwidthTests.swift */; };
|
||||
6201FD599FED061F6C736E8B /* MMMemoryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 099DCF7EF03A58ADA40A94A1 /* MMMemoryTests.swift */; };
|
||||
655366D7066478A02EDA91BB /* MMFanTelemetryProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = C9ED8F75E082D4F8AC2FF2F5 /* MMFanTelemetryProvider.m */; };
|
||||
6A4FDB46AE5E0DAF85CCAB56 /* MMDiskIOTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9DAC4D5C09C974EE833DC7C /* MMDiskIOTests.swift */; };
|
||||
6D973241BBE61F0B053239DB /* MMGPUTelemetryProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = D61AB99733A4AA52459BA7C4 /* MMGPUTelemetryProvider.m */; };
|
||||
7C9AE2ADAED52E593B52F3AE /* MMProcessTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 52471E871E5CC1E444318070 /* MMProcessTests.swift */; };
|
||||
87818E46CEA5145A8215D0E3 /* MMCPUThermalTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0F2BD3777A674DC4EB442890 /* MMCPUThermalTests.swift */; };
|
||||
87A9E18362486D0D385BBC4A /* MMCPUThermalProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 62C377EFD025D6A6B5563E77 /* MMCPUThermalProvider.m */; };
|
||||
88387CDAE2AC1CC74EF89B57 /* MacMonitorApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = ADEA6BD38BA8D887B1DB64A9 /* MacMonitorApp.swift */; };
|
||||
8EDDC2171C55B6E7FC999DAB /* MMBatteryTelemetryProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 9C92D0D2B62B3081ECCA9920 /* MMBatteryTelemetryProvider.m */; };
|
||||
901EF4853E785A2856E54BC9 /* MMKernelTelemetryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DE40072F9A1F9DBD1C48A3B1 /* MMKernelTelemetryTests.swift */; };
|
||||
925245C5B5F8D8DA3C89C4BA /* MMComponentThermalProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = C65F5835516BC2A65BCE25D2 /* MMComponentThermalProvider.m */; };
|
||||
93EF83FE087C6DEAAE3EC0CC /* MMProcessTelemetryProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 728C692778909D2B7451C07B /* MMProcessTelemetryProvider.m */; };
|
||||
951DBA5D3BBAB753322A5DF9 /* MMLoadAverageProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = B5F2256DF514DD737306302B /* MMLoadAverageProvider.m */; };
|
||||
9B5C651AD2AF7DE2738F0C44 /* MMPowerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D48698681374BD25B980C000 /* MMPowerTests.swift */; };
|
||||
9BCE74C5454F81EF80492E75 /* MacMonitorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EC3EDFCD5C50CB352FCED87 /* MacMonitorTests.swift */; };
|
||||
9D12825C7904FB0DAE664CA0 /* MMAudioTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 10D16E1ABE6D28B676EA83FF /* MMAudioTests.swift */; };
|
||||
A521961E035DD50ED8B0C1A9 /* MMKernelTelemetryProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = F444F4543F0A7421C8F8E636 /* MMKernelTelemetryProvider.m */; };
|
||||
A599E974E56F0B8D94A7E480 /* MMNetworkSocketsProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = D78F76C1996D7FCA241CE532 /* MMNetworkSocketsProvider.m */; };
|
||||
A7609CE56D49EC3419987468 /* SystemTelemetryStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = E4B4E94FB2886C60D5548A2A /* SystemTelemetryStore.swift */; };
|
||||
A9FCAEC0BF27A419DB148C4A /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E142AE61F9B87757997870DD /* ContentView.swift */; };
|
||||
ACC914C61AB3762EB0C40513 /* MMLoadAverageTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7EB05C092C94C3972727AAA7 /* MMLoadAverageTests.swift */; };
|
||||
AE3C28BDC3CEF40A9E8F2B20 /* MMGPUTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 80A0F723121CDF9597316F58 /* MMGPUTests.swift */; };
|
||||
B9C2D6574E808B517BA34C83 /* MMMemoryTelemetryProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 991AEEAF262F3C6BE930BC77 /* MMMemoryTelemetryProvider.m */; };
|
||||
BC487DB86227F09CB0603894 /* MMBatteryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0EB61D811D989279BCBE478 /* MMBatteryTests.swift */; };
|
||||
CD91FC663B19DA1FEA3D49D7 /* MMAppleSMCClient.m in Sources */ = {isa = PBXBuildFile; fileRef = 5555436CD3CB8A73F5D6504F /* MMAppleSMCClient.m */; };
|
||||
D7784A61FE4635275CFB3D6C /* MMAudioTelemetryProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 3189D2403E6E984D4924AE4D /* MMAudioTelemetryProvider.m */; };
|
||||
E3CCE93A7D4D1EB0187D3E52 /* MMNetworkBandwidthProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = C539AEA27C794C6F428EA875 /* MMNetworkBandwidthProvider.m */; };
|
||||
E6F2F695B8D3E7045967C082 /* MMFanTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 336CEE35A745F3C7E9F70F43 /* MMFanTests.swift */; };
|
||||
EAFAF5A10502D4ACC64F4720 /* MMTelemetryCoordinator.m in Sources */ = {isa = PBXBuildFile; fileRef = F9F9AD1268F906761032AF4D /* MMTelemetryCoordinator.m */; };
|
||||
EC9FA3E4A119277B89E73F8D /* MMSMCTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 940D608A1AF80F75584E744E /* MMSMCTests.swift */; };
|
||||
F2F7A141F2452EC1B4FB45D8 /* MMStorageTelemetryProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 6DCBCEA450103E2404761B78 /* MMStorageTelemetryProvider.m */; };
|
||||
FED88F290A2F2FBD63DDEC31 /* MMDiskIOProvider.m in Sources */ = {isa = PBXBuildFile; fileRef = 3E13917CAF525640D856ECD9 /* MMDiskIOProvider.m */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
@@ -42,35 +68,74 @@
|
||||
/* Begin PBXFileReference section */
|
||||
007F48A5A599AB4E8D216D16 /* IOKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = IOKit.framework; path = System/Library/Frameworks/IOKit.framework; sourceTree = SDKROOT; };
|
||||
0130BD1E18972DF9E2955334 /* MMMemoryTelemetryProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMMemoryTelemetryProvider.h; sourceTree = "<group>"; };
|
||||
02F5FDE260999C39E978D849 /* MMPowerTelemetryProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMPowerTelemetryProvider.m; sourceTree = "<group>"; };
|
||||
09475741B5D0D4B89B863C3D /* MMComponentThermalProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMComponentThermalProvider.h; sourceTree = "<group>"; };
|
||||
099DCF7EF03A58ADA40A94A1 /* MMMemoryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMMemoryTests.swift; sourceTree = "<group>"; };
|
||||
0C94CCFBE8C9E1370368A28C /* MMNetworkSocketsProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMNetworkSocketsProvider.h; sourceTree = "<group>"; };
|
||||
0F2BD3777A674DC4EB442890 /* MMCPUThermalTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMCPUThermalTests.swift; sourceTree = "<group>"; };
|
||||
10D16E1ABE6D28B676EA83FF /* MMAudioTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMAudioTests.swift; sourceTree = "<group>"; };
|
||||
1AD9EEE571CD904BBCD1C96B /* MMSMCParser.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMSMCParser.h; sourceTree = "<group>"; };
|
||||
1B07A683AD0EFBA8E1FB6C9D /* MMProcessDetailInspector.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMProcessDetailInspector.h; sourceTree = "<group>"; };
|
||||
2345555FF9780B02A90CC7A9 /* CoreFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreFoundation.framework; path = System/Library/Frameworks/CoreFoundation.framework; sourceTree = SDKROOT; };
|
||||
27C612287333D757C92A076A /* MMNetworkBandwidthTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMNetworkBandwidthTests.swift; sourceTree = "<group>"; };
|
||||
2C55E977DBFBE7FF04621608 /* MMLoadAverageProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMLoadAverageProvider.h; sourceTree = "<group>"; };
|
||||
2DC6E55C9D3F646A1C62133D /* MMBatteryTelemetryProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMBatteryTelemetryProvider.h; sourceTree = "<group>"; };
|
||||
2E6A10A13A49E22E51862895 /* MMPeripheralsProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMPeripheralsProvider.m; sourceTree = "<group>"; };
|
||||
2EC3EDFCD5C50CB352FCED87 /* MacMonitorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MacMonitorTests.swift; sourceTree = "<group>"; };
|
||||
3189D2403E6E984D4924AE4D /* MMAudioTelemetryProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMAudioTelemetryProvider.m; sourceTree = "<group>"; };
|
||||
32340166F6100A08105308D3 /* MMTelemetryCoordinator.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMTelemetryCoordinator.h; sourceTree = "<group>"; };
|
||||
336CEE35A745F3C7E9F70F43 /* MMFanTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMFanTests.swift; sourceTree = "<group>"; };
|
||||
374B1BF631CC4738CB52CA3B /* MMNetworkSocketsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMNetworkSocketsTests.swift; sourceTree = "<group>"; };
|
||||
375AA781A2AA0A20B119C7B7 /* MMSMCParser.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMSMCParser.m; sourceTree = "<group>"; };
|
||||
3A14D7B97200EA4C102FEE67 /* MMNetworkBandwidthProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMNetworkBandwidthProvider.h; sourceTree = "<group>"; };
|
||||
3CFC5B905E428A6B854E0AB4 /* MMFanTelemetryProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMFanTelemetryProvider.h; sourceTree = "<group>"; };
|
||||
3E13917CAF525640D856ECD9 /* MMDiskIOProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMDiskIOProvider.m; sourceTree = "<group>"; };
|
||||
41478843A6B013478D94F739 /* MMProcessTelemetryProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMProcessTelemetryProvider.h; sourceTree = "<group>"; };
|
||||
46DE3AE12DAE26C4FE58034C /* MMStorageTelemetryProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMStorageTelemetryProvider.h; sourceTree = "<group>"; };
|
||||
4CE92B1A8D7FDBB6499448E1 /* MMCPULoadTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMCPULoadTests.swift; sourceTree = "<group>"; };
|
||||
52471E871E5CC1E444318070 /* MMProcessTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMProcessTests.swift; sourceTree = "<group>"; };
|
||||
52E641F8A664D456518EDBA4 /* MMProcessDetailInspector.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMProcessDetailInspector.m; sourceTree = "<group>"; };
|
||||
5555436CD3CB8A73F5D6504F /* MMAppleSMCClient.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMAppleSMCClient.m; sourceTree = "<group>"; };
|
||||
5635101F862DE680856BDE6E /* MMTelemetryDomain.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMTelemetryDomain.h; sourceTree = "<group>"; };
|
||||
56E285A0A1746AE659981F22 /* MacMonitorTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = MacMonitorTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
57845310A3D4EC67E48A3B11 /* MMCPULoadProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMCPULoadProvider.h; sourceTree = "<group>"; };
|
||||
5C45D1EB09E045A53A154136 /* MMAudioTelemetryProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMAudioTelemetryProvider.h; sourceTree = "<group>"; };
|
||||
62C377EFD025D6A6B5563E77 /* MMCPUThermalProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMCPUThermalProvider.m; sourceTree = "<group>"; };
|
||||
6D0E5CAF25DFA9A1D2A698A0 /* MMTelemetryProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMTelemetryProvider.h; sourceTree = "<group>"; };
|
||||
6DCBCEA450103E2404761B78 /* MMStorageTelemetryProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMStorageTelemetryProvider.m; sourceTree = "<group>"; };
|
||||
7187632FF63B3B0D07FE9194 /* MMProcessDetailsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMProcessDetailsTests.swift; sourceTree = "<group>"; };
|
||||
726005CB5A6C86E7D80D3CA0 /* MMAppleSMCClient.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMAppleSMCClient.h; sourceTree = "<group>"; };
|
||||
728C692778909D2B7451C07B /* MMProcessTelemetryProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMProcessTelemetryProvider.m; sourceTree = "<group>"; };
|
||||
78325870C7CD8312AECA2236 /* MMStorageTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMStorageTests.swift; sourceTree = "<group>"; };
|
||||
7EB05C092C94C3972727AAA7 /* MMLoadAverageTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMLoadAverageTests.swift; sourceTree = "<group>"; };
|
||||
80A0F723121CDF9597316F58 /* MMGPUTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMGPUTests.swift; sourceTree = "<group>"; };
|
||||
8FBB436F3D9472194D8C6EDD /* MMSMCDefines.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMSMCDefines.h; sourceTree = "<group>"; };
|
||||
940D608A1AF80F75584E744E /* MMSMCTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMSMCTests.swift; sourceTree = "<group>"; };
|
||||
991AEEAF262F3C6BE930BC77 /* MMMemoryTelemetryProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMMemoryTelemetryProvider.m; sourceTree = "<group>"; };
|
||||
9C92D0D2B62B3081ECCA9920 /* MMBatteryTelemetryProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMBatteryTelemetryProvider.m; sourceTree = "<group>"; };
|
||||
9DC54CCE276F93D5AF0A0C28 /* MMGPUTelemetryProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMGPUTelemetryProvider.h; sourceTree = "<group>"; };
|
||||
ADEA6BD38BA8D887B1DB64A9 /* MacMonitorApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MacMonitorApp.swift; sourceTree = "<group>"; };
|
||||
AFA681E2464EA78CC19B54E0 /* MMDiskIOProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMDiskIOProvider.h; sourceTree = "<group>"; };
|
||||
B0EB61D811D989279BCBE478 /* MMBatteryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMBatteryTests.swift; sourceTree = "<group>"; };
|
||||
B288C7402E2C00E75F8CD016 /* MMComponentThermalTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMComponentThermalTests.swift; sourceTree = "<group>"; };
|
||||
B5F2256DF514DD737306302B /* MMLoadAverageProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMLoadAverageProvider.m; sourceTree = "<group>"; };
|
||||
C539AEA27C794C6F428EA875 /* MMNetworkBandwidthProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMNetworkBandwidthProvider.m; sourceTree = "<group>"; };
|
||||
C65F5835516BC2A65BCE25D2 /* MMComponentThermalProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMComponentThermalProvider.m; sourceTree = "<group>"; };
|
||||
C9ED8F75E082D4F8AC2FF2F5 /* MMFanTelemetryProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMFanTelemetryProvider.m; sourceTree = "<group>"; };
|
||||
CBA91906CA8B7936CC82A36B /* MMPowerTelemetryProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMPowerTelemetryProvider.h; sourceTree = "<group>"; };
|
||||
CDE2777944B8F12EC7D2EAB5 /* MMPeripheralsProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMPeripheralsProvider.h; sourceTree = "<group>"; };
|
||||
D1486E1512594482380CB492 /* MMPeripheralsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMPeripheralsTests.swift; sourceTree = "<group>"; };
|
||||
D48698681374BD25B980C000 /* MMPowerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMPowerTests.swift; sourceTree = "<group>"; };
|
||||
D61AB99733A4AA52459BA7C4 /* MMGPUTelemetryProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMGPUTelemetryProvider.m; sourceTree = "<group>"; };
|
||||
D68FC8100D08DB6202F46339 /* MMCPULoadProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMCPULoadProvider.m; sourceTree = "<group>"; };
|
||||
D73CCC7B5E6BF1825EA68E2B /* MMCPUThermalProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMCPUThermalProvider.h; sourceTree = "<group>"; };
|
||||
D78F76C1996D7FCA241CE532 /* MMNetworkSocketsProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMNetworkSocketsProvider.m; sourceTree = "<group>"; };
|
||||
DE40072F9A1F9DBD1C48A3B1 /* MMKernelTelemetryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMKernelTelemetryTests.swift; sourceTree = "<group>"; };
|
||||
E142AE61F9B87757997870DD /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };
|
||||
E4B4E94FB2886C60D5548A2A /* SystemTelemetryStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SystemTelemetryStore.swift; sourceTree = "<group>"; };
|
||||
E6D9BB71DFE7384D0F0E6AA3 /* MMKernelTelemetryProvider.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = MMKernelTelemetryProvider.h; sourceTree = "<group>"; };
|
||||
E9DAC4D5C09C974EE833DC7C /* MMDiskIOTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MMDiskIOTests.swift; sourceTree = "<group>"; };
|
||||
F444F4543F0A7421C8F8E636 /* MMKernelTelemetryProvider.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMKernelTelemetryProvider.m; sourceTree = "<group>"; };
|
||||
F5EC59DCDA5FABDA409CDBCB /* MacMonitor.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = MacMonitor.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
F9F9AD1268F906761032AF4D /* MMTelemetryCoordinator.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = MMTelemetryCoordinator.m; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
@@ -138,6 +203,15 @@
|
||||
path = Core;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
65251E6B5694734BAAF1C1F1 /* Peripherals */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
CDE2777944B8F12EC7D2EAB5 /* MMPeripheralsProvider.h */,
|
||||
2E6A10A13A49E22E51862895 /* MMPeripheralsProvider.m */,
|
||||
);
|
||||
path = Peripherals;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
78383CED205BCA772701AE48 /* CPU */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -147,18 +221,68 @@
|
||||
path = CPU;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
8719744C366432DD7C2B9644 /* Process */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
1B07A683AD0EFBA8E1FB6C9D /* MMProcessDetailInspector.h */,
|
||||
52E641F8A664D456518EDBA4 /* MMProcessDetailInspector.m */,
|
||||
41478843A6B013478D94F739 /* MMProcessTelemetryProvider.h */,
|
||||
728C692778909D2B7451C07B /* MMProcessTelemetryProvider.m */,
|
||||
);
|
||||
path = Process;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
8B31CE7F9319FEC373E6CDC6 /* Power */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
2DC6E55C9D3F646A1C62133D /* MMBatteryTelemetryProvider.h */,
|
||||
9C92D0D2B62B3081ECCA9920 /* MMBatteryTelemetryProvider.m */,
|
||||
CBA91906CA8B7936CC82A36B /* MMPowerTelemetryProvider.h */,
|
||||
02F5FDE260999C39E978D849 /* MMPowerTelemetryProvider.m */,
|
||||
);
|
||||
path = Power;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
8BF79E3BCB76E7A1669DC930 /* Telemetry */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
92E1EF545807CF318620FEAA /* Audio */,
|
||||
78383CED205BCA772701AE48 /* CPU */,
|
||||
AD2995435E44FA3E1790A4F3 /* Fan */,
|
||||
F99AF003017BA9F19F7AEB1E /* GPU */,
|
||||
CA2F30473D63EC64CBD65437 /* Kernel */,
|
||||
EE2F5EFC9DC33CEDA79A131F /* Memory */,
|
||||
901D54FEAB6E9D6E787E599D /* Network */,
|
||||
65251E6B5694734BAAF1C1F1 /* Peripherals */,
|
||||
8B31CE7F9319FEC373E6CDC6 /* Power */,
|
||||
8719744C366432DD7C2B9644 /* Process */,
|
||||
B6EB3F6545276C40212C2992 /* Storage */,
|
||||
A8658D19E71E34F1DDD87097 /* System */,
|
||||
DBDC37231C01F0A2D4A7FC73 /* Thermal */,
|
||||
);
|
||||
path = Telemetry;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
901D54FEAB6E9D6E787E599D /* Network */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
3A14D7B97200EA4C102FEE67 /* MMNetworkBandwidthProvider.h */,
|
||||
C539AEA27C794C6F428EA875 /* MMNetworkBandwidthProvider.m */,
|
||||
0C94CCFBE8C9E1370368A28C /* MMNetworkSocketsProvider.h */,
|
||||
D78F76C1996D7FCA241CE532 /* MMNetworkSocketsProvider.m */,
|
||||
);
|
||||
path = Network;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
92E1EF545807CF318620FEAA /* Audio */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
5C45D1EB09E045A53A154136 /* MMAudioTelemetryProvider.h */,
|
||||
3189D2403E6E984D4924AE4D /* MMAudioTelemetryProvider.m */,
|
||||
);
|
||||
path = Audio;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
9844EC526E3527F6A582179F /* Hardware */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -167,6 +291,15 @@
|
||||
path = Hardware;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
A8658D19E71E34F1DDD87097 /* System */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
2C55E977DBFBE7FF04621608 /* MMLoadAverageProvider.h */,
|
||||
B5F2256DF514DD737306302B /* MMLoadAverageProvider.m */,
|
||||
);
|
||||
path = System;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
AD2995435E44FA3E1790A4F3 /* Fan */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
@@ -179,6 +312,8 @@
|
||||
B6EB3F6545276C40212C2992 /* Storage */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
AFA681E2464EA78CC19B54E0 /* MMDiskIOProvider.h */,
|
||||
3E13917CAF525640D856ECD9 /* MMDiskIOProvider.m */,
|
||||
46DE3AE12DAE26C4FE58034C /* MMStorageTelemetryProvider.h */,
|
||||
6DCBCEA450103E2404761B78 /* MMStorageTelemetryProvider.m */,
|
||||
);
|
||||
@@ -198,19 +333,43 @@
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
2EC3EDFCD5C50CB352FCED87 /* MacMonitorTests.swift */,
|
||||
10D16E1ABE6D28B676EA83FF /* MMAudioTests.swift */,
|
||||
B0EB61D811D989279BCBE478 /* MMBatteryTests.swift */,
|
||||
B288C7402E2C00E75F8CD016 /* MMComponentThermalTests.swift */,
|
||||
4CE92B1A8D7FDBB6499448E1 /* MMCPULoadTests.swift */,
|
||||
0F2BD3777A674DC4EB442890 /* MMCPUThermalTests.swift */,
|
||||
E9DAC4D5C09C974EE833DC7C /* MMDiskIOTests.swift */,
|
||||
336CEE35A745F3C7E9F70F43 /* MMFanTests.swift */,
|
||||
80A0F723121CDF9597316F58 /* MMGPUTests.swift */,
|
||||
DE40072F9A1F9DBD1C48A3B1 /* MMKernelTelemetryTests.swift */,
|
||||
7EB05C092C94C3972727AAA7 /* MMLoadAverageTests.swift */,
|
||||
099DCF7EF03A58ADA40A94A1 /* MMMemoryTests.swift */,
|
||||
27C612287333D757C92A076A /* MMNetworkBandwidthTests.swift */,
|
||||
374B1BF631CC4738CB52CA3B /* MMNetworkSocketsTests.swift */,
|
||||
D1486E1512594482380CB492 /* MMPeripheralsTests.swift */,
|
||||
D48698681374BD25B980C000 /* MMPowerTests.swift */,
|
||||
7187632FF63B3B0D07FE9194 /* MMProcessDetailsTests.swift */,
|
||||
52471E871E5CC1E444318070 /* MMProcessTests.swift */,
|
||||
940D608A1AF80F75584E744E /* MMSMCTests.swift */,
|
||||
78325870C7CD8312AECA2236 /* MMStorageTests.swift */,
|
||||
);
|
||||
path = Tests;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
CA2F30473D63EC64CBD65437 /* Kernel */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
E6D9BB71DFE7384D0F0E6AA3 /* MMKernelTelemetryProvider.h */,
|
||||
F444F4543F0A7421C8F8E636 /* MMKernelTelemetryProvider.m */,
|
||||
);
|
||||
path = Kernel;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
DBDC37231C01F0A2D4A7FC73 /* Thermal */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
09475741B5D0D4B89B863C3D /* MMComponentThermalProvider.h */,
|
||||
C65F5835516BC2A65BCE25D2 /* MMComponentThermalProvider.m */,
|
||||
D73CCC7B5E6BF1825EA68E2B /* MMCPUThermalProvider.h */,
|
||||
62C377EFD025D6A6B5563E77 /* MMCPUThermalProvider.m */,
|
||||
);
|
||||
@@ -247,6 +406,15 @@
|
||||
path = Memory;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
F99AF003017BA9F19F7AEB1E /* GPU */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
9DC54CCE276F93D5AF0A0C28 /* MMGPUTelemetryProvider.h */,
|
||||
D61AB99733A4AA52459BA7C4 /* MMGPUTelemetryProvider.m */,
|
||||
);
|
||||
path = GPU;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
@@ -322,10 +490,23 @@
|
||||
isa = PBXSourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
9D12825C7904FB0DAE664CA0 /* MMAudioTests.swift in Sources */,
|
||||
BC487DB86227F09CB0603894 /* MMBatteryTests.swift in Sources */,
|
||||
160334CC765E091A7CBE21AA /* MMCPULoadTests.swift in Sources */,
|
||||
87818E46CEA5145A8215D0E3 /* MMCPUThermalTests.swift in Sources */,
|
||||
57BA02AE1CE24DBD02BD03A4 /* MMComponentThermalTests.swift in Sources */,
|
||||
6A4FDB46AE5E0DAF85CCAB56 /* MMDiskIOTests.swift in Sources */,
|
||||
E6F2F695B8D3E7045967C082 /* MMFanTests.swift in Sources */,
|
||||
AE3C28BDC3CEF40A9E8F2B20 /* MMGPUTests.swift in Sources */,
|
||||
901EF4853E785A2856E54BC9 /* MMKernelTelemetryTests.swift in Sources */,
|
||||
ACC914C61AB3762EB0C40513 /* MMLoadAverageTests.swift in Sources */,
|
||||
6201FD599FED061F6C736E8B /* MMMemoryTests.swift in Sources */,
|
||||
5D31906EA986E2BA92E86FA8 /* MMNetworkBandwidthTests.swift in Sources */,
|
||||
4C1A92F4DEF4C824976115C2 /* MMNetworkSocketsTests.swift in Sources */,
|
||||
22CA7351A745F7837E487051 /* MMPeripheralsTests.swift in Sources */,
|
||||
9B5C651AD2AF7DE2738F0C44 /* MMPowerTests.swift in Sources */,
|
||||
3BA6709B727B1AAC6C4310B5 /* MMProcessDetailsTests.swift in Sources */,
|
||||
7C9AE2ADAED52E593B52F3AE /* MMProcessTests.swift in Sources */,
|
||||
EC9FA3E4A119277B89E73F8D /* MMSMCTests.swift in Sources */,
|
||||
1B15F48F6B19E9EA4556ECD5 /* MMStorageTests.swift in Sources */,
|
||||
9BCE74C5454F81EF80492E75 /* MacMonitorTests.swift in Sources */,
|
||||
@@ -338,10 +519,23 @@
|
||||
files = (
|
||||
A9FCAEC0BF27A419DB148C4A /* ContentView.swift in Sources */,
|
||||
CD91FC663B19DA1FEA3D49D7 /* MMAppleSMCClient.m in Sources */,
|
||||
D7784A61FE4635275CFB3D6C /* MMAudioTelemetryProvider.m in Sources */,
|
||||
8EDDC2171C55B6E7FC999DAB /* MMBatteryTelemetryProvider.m in Sources */,
|
||||
4419FE7554489B23976E2970 /* MMCPULoadProvider.m in Sources */,
|
||||
87A9E18362486D0D385BBC4A /* MMCPUThermalProvider.m in Sources */,
|
||||
925245C5B5F8D8DA3C89C4BA /* MMComponentThermalProvider.m in Sources */,
|
||||
FED88F290A2F2FBD63DDEC31 /* MMDiskIOProvider.m in Sources */,
|
||||
655366D7066478A02EDA91BB /* MMFanTelemetryProvider.m in Sources */,
|
||||
6D973241BBE61F0B053239DB /* MMGPUTelemetryProvider.m in Sources */,
|
||||
A521961E035DD50ED8B0C1A9 /* MMKernelTelemetryProvider.m in Sources */,
|
||||
951DBA5D3BBAB753322A5DF9 /* MMLoadAverageProvider.m in Sources */,
|
||||
B9C2D6574E808B517BA34C83 /* MMMemoryTelemetryProvider.m in Sources */,
|
||||
E3CCE93A7D4D1EB0187D3E52 /* MMNetworkBandwidthProvider.m in Sources */,
|
||||
A599E974E56F0B8D94A7E480 /* MMNetworkSocketsProvider.m in Sources */,
|
||||
4752C49841375B88194F7635 /* MMPeripheralsProvider.m in Sources */,
|
||||
0A7117B3B7CC7112F2527574 /* MMPowerTelemetryProvider.m in Sources */,
|
||||
2C0F7AB93691ED8AA86FBCF0 /* MMProcessDetailInspector.m in Sources */,
|
||||
93EF83FE087C6DEAAE3EC0CC /* MMProcessTelemetryProvider.m in Sources */,
|
||||
1B3F1C8ABF0ADFAA290FF6F6 /* MMSMCParser.m in Sources */,
|
||||
F2F7A141F2452EC1B4FB45D8 /* MMStorageTelemetryProvider.m in Sources */,
|
||||
EAFAF5A10502D4ACC64F4720 /* MMTelemetryCoordinator.m in Sources */,
|
||||
|
||||
@@ -2,6 +2,87 @@ import Foundation
|
||||
import SwiftUI
|
||||
import Observation
|
||||
|
||||
// MARK: - Typed Telemetry Models
|
||||
|
||||
public struct CPULoadMetrics: Sendable {
|
||||
public var systemLoad: Double = 0
|
||||
public var userLoad: Double = 0
|
||||
public var idleLoad: Double = 100
|
||||
public var totalLoad: Double = 0
|
||||
public var perCoreLoad: [Double] = []
|
||||
public var cpuFrequencyMHz: Double = 0
|
||||
public var isThrottled: Bool = false
|
||||
}
|
||||
|
||||
public struct MemoryMetrics: Sendable {
|
||||
public var totalBytes: UInt64 = 0
|
||||
public var usedBytes: UInt64 = 0
|
||||
public var freeBytes: UInt64 = 0
|
||||
public var activeBytes: UInt64 = 0
|
||||
public var inactiveBytes: UInt64 = 0
|
||||
public var wiredBytes: UInt64 = 0
|
||||
public var compressedBytes: UInt64 = 0
|
||||
public var swapTotalBytes: UInt64 = 0
|
||||
public var swapUsedBytes: UInt64 = 0
|
||||
public var utilizationPercentage: Double = 0
|
||||
public var pressureLevel: String = "Normal"
|
||||
}
|
||||
|
||||
public struct StorageVolumeItem: Identifiable, Sendable {
|
||||
public var id: String { mountPoint }
|
||||
public let mountPoint: String
|
||||
public let volumeName: String
|
||||
public let fileSystem: String
|
||||
public let totalBytes: UInt64
|
||||
public let freeBytes: UInt64
|
||||
public let usedBytes: UInt64
|
||||
public let usedPercentage: Double
|
||||
public let isReadOnly: Bool
|
||||
}
|
||||
|
||||
public struct CPUThermalMetrics: Sendable {
|
||||
public var packageTemperature: Double = 0
|
||||
public var averageCoreTemperature: Double = 0
|
||||
public var peakCoreTemperature: Double = 0
|
||||
public var coreTemperatures: [(index: Int, key: String, temperature: Double)] = []
|
||||
public var thermalPressureState: String = "Nominal"
|
||||
public var isThrottling: Bool = false
|
||||
}
|
||||
|
||||
public struct FanTelemetryItem: Identifiable, Sendable {
|
||||
public var id: Int { index }
|
||||
public let index: Int
|
||||
public let name: String
|
||||
public let currentRPM: Double
|
||||
public let minRPM: Double
|
||||
public let maxRPM: Double
|
||||
public let targetRPM: Double
|
||||
public let utilization: Double
|
||||
}
|
||||
|
||||
public struct ComponentThermalItem: Identifiable, Sendable {
|
||||
public var id: String { key }
|
||||
public let key: String
|
||||
public let name: String
|
||||
public let category: String
|
||||
public let temperature: Double
|
||||
}
|
||||
|
||||
public struct PowerMetrics: Sendable {
|
||||
public var systemTotalWatts: Double = 0
|
||||
public var cpuWatts: Double = 0
|
||||
public var gpuWatts: Double = 0
|
||||
public var memoryWatts: Double = 0
|
||||
public var cpuVoltage: Double = 0
|
||||
public var cpuCurrent: Double = 0
|
||||
public var powerSource: String = "AC Power"
|
||||
public var isCharging: Bool = false
|
||||
public var batteryLevel: Double = 100.0
|
||||
public var sensorReadings: [(key: String, name: String, value: Double, unit: String)] = []
|
||||
}
|
||||
|
||||
// MARK: - SystemTelemetryStore
|
||||
|
||||
@Observable
|
||||
@MainActor
|
||||
public final class SystemTelemetryStore {
|
||||
@@ -14,6 +95,15 @@ public final class SystemTelemetryStore {
|
||||
/// Raw snapshots organized by provider identifier
|
||||
public private(set) var latestSnapshot: [String: [String: Any]] = [:]
|
||||
|
||||
/// Structured Telemetry Metrics
|
||||
public private(set) var cpuLoad = CPULoadMetrics()
|
||||
public private(set) var memory = MemoryMetrics()
|
||||
public private(set) var storageVolumes: [StorageVolumeItem] = []
|
||||
public private(set) var cpuThermal = CPUThermalMetrics()
|
||||
public private(set) var fans: [FanTelemetryItem] = []
|
||||
public private(set) var componentTemps: [ComponentThermalItem] = []
|
||||
public private(set) var power = PowerMetrics()
|
||||
|
||||
/// System identification
|
||||
public let hostModel: String
|
||||
public let osVersion: String
|
||||
@@ -30,15 +120,154 @@ public final class SystemTelemetryStore {
|
||||
self.physicalCpuCount = SystemTelemetryStore.readSysctlInt("hw.physicalcpu") ?? 1
|
||||
self.logicalCpuCount = SystemTelemetryStore.readSysctlInt("hw.logicalcpu") ?? 1
|
||||
|
||||
registerDefaultProviders()
|
||||
setupCoordinator()
|
||||
}
|
||||
|
||||
private func registerDefaultProviders() {
|
||||
// Register all Primary System & Thermal Telemetry providers (M2)
|
||||
coordinator.register(MMCPULoadProvider())
|
||||
coordinator.register(MMMemoryTelemetryProvider())
|
||||
coordinator.register(MMStorageTelemetryProvider())
|
||||
coordinator.register(MMCPUThermalProvider())
|
||||
coordinator.register(MMFanTelemetryProvider())
|
||||
coordinator.register(MMComponentThermalProvider())
|
||||
coordinator.register(MMPowerTelemetryProvider())
|
||||
}
|
||||
|
||||
private func setupCoordinator() {
|
||||
coordinator.sampleInterval = self.sampleInterval
|
||||
coordinator.snapshotHandler = { [weak self] snapshot in
|
||||
guard let self else { return }
|
||||
self.latestSnapshot = snapshot
|
||||
self.lastUpdateTimestamp = Date()
|
||||
self.decodeSnapshot(snapshot)
|
||||
}
|
||||
}
|
||||
|
||||
private func decodeSnapshot(_ snapshot: [String: [String: Any]]) {
|
||||
// 1. CPU Load
|
||||
if let cpuDict = snapshot["com.i3omb.macmonitor.telemetry.cpu"] {
|
||||
var m = CPULoadMetrics()
|
||||
m.systemLoad = (cpuDict["systemLoad"] as? NSNumber)?.doubleValue ?? 0
|
||||
m.userLoad = (cpuDict["userLoad"] as? NSNumber)?.doubleValue ?? 0
|
||||
m.idleLoad = (cpuDict["idleLoad"] as? NSNumber)?.doubleValue ?? 100
|
||||
m.totalLoad = (cpuDict["totalLoad"] as? NSNumber)?.doubleValue ?? 0
|
||||
if let perCore = cpuDict["perCoreLoad"] as? [NSNumber] {
|
||||
m.perCoreLoad = perCore.map { $0.doubleValue }
|
||||
}
|
||||
m.cpuFrequencyMHz = (cpuDict["cpuFrequencyMHz"] as? NSNumber)?.doubleValue ?? 0
|
||||
m.isThrottled = (cpuDict["isThrottled"] as? NSNumber)?.boolValue ?? false
|
||||
self.cpuLoad = m
|
||||
}
|
||||
|
||||
// 2. Memory
|
||||
if let memDict = snapshot["com.i3omb.macmonitor.telemetry.memory"] {
|
||||
var m = MemoryMetrics()
|
||||
m.totalBytes = (memDict["totalBytes"] as? NSNumber)?.uint64Value ?? 0
|
||||
m.usedBytes = (memDict["usedBytes"] as? NSNumber)?.uint64Value ?? 0
|
||||
m.freeBytes = (memDict["freeBytes"] as? NSNumber)?.uint64Value ?? 0
|
||||
m.activeBytes = (memDict["activeBytes"] as? NSNumber)?.uint64Value ?? 0
|
||||
m.inactiveBytes = (memDict["inactiveBytes"] as? NSNumber)?.uint64Value ?? 0
|
||||
m.wiredBytes = (memDict["wiredBytes"] as? NSNumber)?.uint64Value ?? 0
|
||||
m.compressedBytes = (memDict["compressedBytes"] as? NSNumber)?.uint64Value ?? 0
|
||||
m.swapTotalBytes = (memDict["swapTotalBytes"] as? NSNumber)?.uint64Value ?? 0
|
||||
m.swapUsedBytes = (memDict["swapUsedBytes"] as? NSNumber)?.uint64Value ?? 0
|
||||
m.utilizationPercentage = (memDict["utilizationPercentage"] as? NSNumber)?.doubleValue ?? 0
|
||||
m.pressureLevel = memDict["pressureLevel"] as? String ?? "Normal"
|
||||
self.memory = m
|
||||
}
|
||||
|
||||
// 3. Storage
|
||||
if let stgDict = snapshot["com.i3omb.macmonitor.telemetry.storage"],
|
||||
let volArray = stgDict["volumes"] as? [[String: Any]] {
|
||||
self.storageVolumes = volArray.compactMap { dict in
|
||||
guard let mount = dict["mountPoint"] as? String else { return nil }
|
||||
return StorageVolumeItem(
|
||||
mountPoint: mount,
|
||||
volumeName: dict["volumeName"] as? String ?? mount,
|
||||
fileSystem: dict["fileSystem"] as? String ?? "APFS",
|
||||
totalBytes: (dict["totalBytes"] as? NSNumber)?.uint64Value ?? 0,
|
||||
freeBytes: (dict["freeBytes"] as? NSNumber)?.uint64Value ?? 0,
|
||||
usedBytes: (dict["usedBytes"] as? NSNumber)?.uint64Value ?? 0,
|
||||
usedPercentage: (dict["usedPercentage"] as? NSNumber)?.doubleValue ?? 0,
|
||||
isReadOnly: (dict["isReadOnly"] as? NSNumber)?.boolValue ?? false
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 4. CPU Thermal
|
||||
if let thDict = snapshot["com.i3omb.macmonitor.telemetry.thermal.cpu"] {
|
||||
var m = CPUThermalMetrics()
|
||||
m.packageTemperature = (thDict["packageTemperature"] as? NSNumber)?.doubleValue ?? 0
|
||||
m.averageCoreTemperature = (thDict["averageCoreTemperature"] as? NSNumber)?.doubleValue ?? 0
|
||||
m.peakCoreTemperature = (thDict["peakCoreTemperature"] as? NSNumber)?.doubleValue ?? 0
|
||||
m.thermalPressureState = thDict["thermalPressureState"] as? String ?? "Nominal"
|
||||
m.isThrottling = (thDict["isThrottling"] as? NSNumber)?.boolValue ?? false
|
||||
if let coresList = thDict["coreTemperatures"] as? [[String: Any]] {
|
||||
m.coreTemperatures = coresList.compactMap { d in
|
||||
let idx = (d["coreIndex"] as? NSNumber)?.intValue ?? 0
|
||||
let key = d["key"] as? String ?? "TC\(idx)C"
|
||||
let temp = (d["temperature"] as? NSNumber)?.doubleValue ?? 0
|
||||
return (index: idx, key: key, temperature: temp)
|
||||
}
|
||||
}
|
||||
self.cpuThermal = m
|
||||
}
|
||||
|
||||
// 5. Fans
|
||||
if let fanDict = snapshot["com.i3omb.macmonitor.telemetry.fan"],
|
||||
let fanArray = fanDict["fans"] as? [[String: Any]] {
|
||||
self.fans = fanArray.compactMap { d in
|
||||
let idx = (d["index"] as? NSNumber)?.intValue ?? 0
|
||||
return FanTelemetryItem(
|
||||
index: idx,
|
||||
name: d["name"] as? String ?? "Fan \(idx + 1)",
|
||||
currentRPM: (d["currentRPM"] as? NSNumber)?.doubleValue ?? 0,
|
||||
minRPM: (d["minRPM"] as? NSNumber)?.doubleValue ?? 0,
|
||||
maxRPM: (d["maxRPM"] as? NSNumber)?.doubleValue ?? 0,
|
||||
targetRPM: (d["targetRPM"] as? NSNumber)?.doubleValue ?? 0,
|
||||
utilization: (d["utilization"] as? NSNumber)?.doubleValue ?? 0
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Component Thermals
|
||||
if let compDict = snapshot["com.i3omb.macmonitor.telemetry.thermal.components"],
|
||||
let compArray = compDict["components"] as? [[String: Any]] {
|
||||
self.componentTemps = compArray.compactMap { d in
|
||||
guard let key = d["key"] as? String else { return nil }
|
||||
return ComponentThermalItem(
|
||||
key: key,
|
||||
name: d["name"] as? String ?? key,
|
||||
category: d["category"] as? String ?? "Other",
|
||||
temperature: (d["temperature"] as? NSNumber)?.doubleValue ?? 0
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// 7. Power
|
||||
if let pwrDict = snapshot["com.i3omb.macmonitor.telemetry.power"] {
|
||||
var m = PowerMetrics()
|
||||
m.systemTotalWatts = (pwrDict["systemTotalWatts"] as? NSNumber)?.doubleValue ?? 0
|
||||
m.cpuWatts = (pwrDict["cpuWatts"] as? NSNumber)?.doubleValue ?? 0
|
||||
m.gpuWatts = (pwrDict["gpuWatts"] as? NSNumber)?.doubleValue ?? 0
|
||||
m.memoryWatts = (pwrDict["memoryWatts"] as? NSNumber)?.doubleValue ?? 0
|
||||
m.cpuVoltage = (pwrDict["cpuVoltage"] as? NSNumber)?.doubleValue ?? 0
|
||||
m.cpuCurrent = (pwrDict["cpuCurrent"] as? NSNumber)?.doubleValue ?? 0
|
||||
m.powerSource = pwrDict["powerSource"] as? String ?? "AC Power"
|
||||
m.isCharging = (pwrDict["isCharging"] as? NSNumber)?.boolValue ?? false
|
||||
m.batteryLevel = (pwrDict["batteryLevel"] as? NSNumber)?.doubleValue ?? 100.0
|
||||
if let sensorList = pwrDict["sensors"] as? [[String: Any]] {
|
||||
m.sensorReadings = sensorList.compactMap { d in
|
||||
guard let k = d["key"] as? String else { return nil }
|
||||
let n = d["name"] as? String ?? k
|
||||
let v = (d["value"] as? NSNumber)?.doubleValue ?? 0
|
||||
let u = d["unit"] as? String ?? ""
|
||||
return (key: k, name: n, value: v, unit: u)
|
||||
}
|
||||
}
|
||||
self.power = m
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,5 +17,18 @@
|
||||
#import "MMStorageTelemetryProvider.h"
|
||||
#import "MMCPUThermalProvider.h"
|
||||
#import "MMFanTelemetryProvider.h"
|
||||
#import "MMComponentThermalProvider.h"
|
||||
#import "MMPowerTelemetryProvider.h"
|
||||
#import "MMKernelTelemetryProvider.h"
|
||||
#import "MMLoadAverageProvider.h"
|
||||
#import "MMDiskIOProvider.h"
|
||||
#import "MMNetworkBandwidthProvider.h"
|
||||
#import "MMNetworkSocketsProvider.h"
|
||||
#import "MMProcessTelemetryProvider.h"
|
||||
#import "MMProcessDetailInspector.h"
|
||||
#import "MMGPUTelemetryProvider.h"
|
||||
#import "MMBatteryTelemetryProvider.h"
|
||||
#import "MMPeripheralsProvider.h"
|
||||
#import "MMAudioTelemetryProvider.h"
|
||||
|
||||
#endif /* MacMonitor_Bridging_Header_h */
|
||||
|
||||
@@ -40,6 +40,13 @@
|
||||
(uint32_t)bytes[3];
|
||||
}
|
||||
|
||||
static int hexDigitValue(unichar c) {
|
||||
if (c >= '0' && c <= '9') return c - '0';
|
||||
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
|
||||
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
|
||||
return -1;
|
||||
}
|
||||
|
||||
+ (nullable NSNumber *)decodeValueWithDataType:(NSString *)dataType bytes:(const uint8_t *)bytes size:(NSUInteger)size {
|
||||
if (!bytes || size == 0) return nil;
|
||||
|
||||
@@ -49,7 +56,7 @@
|
||||
if (size >= 2) return @([self decodeSP78:bytes]);
|
||||
} else if ([trimmedType isEqualToString:@"fpe2"]) {
|
||||
if (size >= 2) return @([self decodeFPE2:bytes]);
|
||||
} else if ([trimmedType isEqualToString:@"flt"]) {
|
||||
} else if ([trimmedType isEqualToString:@"flt"] || [trimmedType isEqualToString:@"ioft"]) {
|
||||
if (size >= 4) return @([self decodeFLT:bytes]);
|
||||
} else if ([trimmedType isEqualToString:@"ui8"]) {
|
||||
if (size >= 1) return @([self decodeUI8:bytes]);
|
||||
@@ -59,6 +66,18 @@
|
||||
if (size >= 4) return @([self decodeUI32:bytes]);
|
||||
} else if ([trimmedType isEqualToString:@"flag"]) {
|
||||
if (size >= 1) return @(bytes[0] != 0);
|
||||
} else if (trimmedType.length == 4 && [trimmedType hasPrefix:@"sp"] && size >= 2) {
|
||||
int fracBits = hexDigitValue([trimmedType characterAtIndex:3]);
|
||||
if (fracBits >= 0 && fracBits <= 15) {
|
||||
int16_t raw = (int16_t)(((uint16_t)bytes[0] << 8) | (uint16_t)bytes[1]);
|
||||
return @((float)raw / (float)(1 << fracBits));
|
||||
}
|
||||
} else if (trimmedType.length == 4 && [trimmedType hasPrefix:@"fp"] && size >= 2) {
|
||||
int fracBits = hexDigitValue([trimmedType characterAtIndex:3]);
|
||||
if (fracBits >= 0 && fracBits <= 15) {
|
||||
uint16_t raw = ((uint16_t)bytes[0] << 8) | (uint16_t)bytes[1];
|
||||
return @((float)raw / (float)(1 << fracBits));
|
||||
}
|
||||
}
|
||||
|
||||
return nil;
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
//
|
||||
// MMAudioTelemetryProvider.h
|
||||
// MacMonitor
|
||||
//
|
||||
// Telemetry provider enumerating CoreAudio input/output devices, sample rates, volume, and active status.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MMTelemetryProvider.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface MMAudioDevice : NSObject
|
||||
|
||||
@property (nonatomic, assign) uint32_t deviceID;
|
||||
@property (nonatomic, copy) NSString *name;
|
||||
@property (nonatomic, copy) NSString *manufacturer;
|
||||
@property (nonatomic, copy) NSString *uid;
|
||||
@property (nonatomic, assign) BOOL isInput;
|
||||
@property (nonatomic, assign) BOOL isOutput;
|
||||
@property (nonatomic, assign) BOOL isDefaultInput;
|
||||
@property (nonatomic, assign) BOOL isDefaultOutput;
|
||||
@property (nonatomic, assign) double sampleRate;
|
||||
@property (nonatomic, assign) uint32_t channelCount;
|
||||
@property (nonatomic, assign) float volume;
|
||||
@property (nonatomic, assign) BOOL isMuted;
|
||||
|
||||
- (NSDictionary<NSString *, id> *)toDictionary;
|
||||
|
||||
@end
|
||||
|
||||
@interface MMAudioTelemetryProvider : NSObject <MMTelemetryProvider>
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
+ (NSArray<MMAudioDevice *> *)sampleAudioDevices;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,232 @@
|
||||
//
|
||||
// MMAudioTelemetryProvider.m
|
||||
// MacMonitor
|
||||
//
|
||||
// Telemetry provider enumerating CoreAudio input/output devices, sample rates, volume, and active status.
|
||||
//
|
||||
|
||||
#import "MMAudioTelemetryProvider.h"
|
||||
#import <CoreAudio/CoreAudio.h>
|
||||
|
||||
@implementation MMAudioDevice
|
||||
|
||||
- (NSDictionary<NSString *, id> *)toDictionary {
|
||||
return @{
|
||||
@"deviceID": @(self.deviceID),
|
||||
@"name": self.name ?: @"Unknown Audio Device",
|
||||
@"manufacturer": self.manufacturer ?: @"Unknown",
|
||||
@"uid": self.uid ?: @"",
|
||||
@"isInput": @(self.isInput),
|
||||
@"isOutput": @(self.isOutput),
|
||||
@"isDefaultInput": @(self.isDefaultInput),
|
||||
@"isDefaultOutput": @(self.isDefaultOutput),
|
||||
@"sampleRate": @(self.sampleRate),
|
||||
@"channelCount": @(self.channelCount),
|
||||
@"volume": @(roundf(self.volume * 100.0f) / 100.0f),
|
||||
@"isMuted": @(self.isMuted)
|
||||
};
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MMAudioTelemetryProvider
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
return self;
|
||||
}
|
||||
|
||||
- (MMTelemetryDomain)domain {
|
||||
return MMTelemetryDomainAudio;
|
||||
}
|
||||
|
||||
- (NSString *)providerIdentifier {
|
||||
return @"com.i3omb.macmonitor.telemetry.audio";
|
||||
}
|
||||
|
||||
- (BOOL)isAvailable {
|
||||
return YES;
|
||||
}
|
||||
|
||||
+ (AudioDeviceID)defaultDeviceForProperty:(AudioObjectPropertySelector)selector {
|
||||
AudioObjectPropertyAddress address = {
|
||||
.mSelector = selector,
|
||||
.mScope = kAudioObjectPropertyScopeGlobal,
|
||||
.mElement = kAudioObjectPropertyElementMain
|
||||
};
|
||||
AudioDeviceID deviceID = kAudioObjectUnknown;
|
||||
UInt32 size = sizeof(AudioDeviceID);
|
||||
OSStatus status = AudioObjectGetPropertyData(kAudioObjectSystemObject, &address, 0, NULL, &size, &deviceID);
|
||||
if (status == noErr) {
|
||||
return deviceID;
|
||||
}
|
||||
return kAudioObjectUnknown;
|
||||
}
|
||||
|
||||
+ (NSArray<MMAudioDevice *> *)sampleAudioDevices {
|
||||
AudioObjectPropertyAddress address = {
|
||||
.mSelector = kAudioHardwarePropertyDevices,
|
||||
.mScope = kAudioObjectPropertyScopeGlobal,
|
||||
.mElement = kAudioObjectPropertyElementMain
|
||||
};
|
||||
|
||||
UInt32 dataSize = 0;
|
||||
OSStatus status = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &address, 0, NULL, &dataSize);
|
||||
if (status != noErr || dataSize == 0) {
|
||||
return @[];
|
||||
}
|
||||
|
||||
UInt32 deviceCount = dataSize / sizeof(AudioDeviceID);
|
||||
AudioDeviceID *deviceIDs = (AudioDeviceID *)malloc(dataSize);
|
||||
if (!deviceIDs) return @[];
|
||||
|
||||
status = AudioObjectGetPropertyData(kAudioObjectSystemObject, &address, 0, NULL, &dataSize, deviceIDs);
|
||||
if (status != noErr) {
|
||||
free(deviceIDs);
|
||||
return @[];
|
||||
}
|
||||
|
||||
AudioDeviceID defaultIn = [self defaultDeviceForProperty:kAudioHardwarePropertyDefaultInputDevice];
|
||||
AudioDeviceID defaultOut = [self defaultDeviceForProperty:kAudioHardwarePropertyDefaultOutputDevice];
|
||||
|
||||
NSMutableArray<MMAudioDevice *> *devices = [NSMutableArray arrayWithCapacity:deviceCount];
|
||||
|
||||
for (UInt32 i = 0; i < deviceCount; i++) {
|
||||
AudioDeviceID devID = deviceIDs[i];
|
||||
|
||||
// Name
|
||||
CFStringRef nameRef = NULL;
|
||||
UInt32 propSize = sizeof(CFStringRef);
|
||||
AudioObjectPropertyAddress nameAddr = {
|
||||
.mSelector = kAudioObjectPropertyName,
|
||||
.mScope = kAudioObjectPropertyScopeGlobal,
|
||||
.mElement = kAudioObjectPropertyElementMain
|
||||
};
|
||||
NSString *name = @"Audio Device";
|
||||
if (AudioObjectGetPropertyData(devID, &nameAddr, 0, NULL, &propSize, &nameRef) == noErr && nameRef) {
|
||||
name = (__bridge_transfer NSString *)nameRef;
|
||||
}
|
||||
|
||||
// Manufacturer
|
||||
CFStringRef mfrRef = NULL;
|
||||
propSize = sizeof(CFStringRef);
|
||||
AudioObjectPropertyAddress mfrAddr = {
|
||||
.mSelector = kAudioObjectPropertyManufacturer,
|
||||
.mScope = kAudioObjectPropertyScopeGlobal,
|
||||
.mElement = kAudioObjectPropertyElementMain
|
||||
};
|
||||
NSString *mfr = @"Apple Inc.";
|
||||
if (AudioObjectGetPropertyData(devID, &mfrAddr, 0, NULL, &propSize, &mfrRef) == noErr && mfrRef) {
|
||||
mfr = (__bridge_transfer NSString *)mfrRef;
|
||||
}
|
||||
|
||||
// UID
|
||||
CFStringRef uidRef = NULL;
|
||||
propSize = sizeof(CFStringRef);
|
||||
AudioObjectPropertyAddress uidAddr = {
|
||||
.mSelector = kAudioDevicePropertyDeviceUID,
|
||||
.mScope = kAudioObjectPropertyScopeGlobal,
|
||||
.mElement = kAudioObjectPropertyElementMain
|
||||
};
|
||||
NSString *uid = @"";
|
||||
if (AudioObjectGetPropertyData(devID, &uidAddr, 0, NULL, &propSize, &uidRef) == noErr && uidRef) {
|
||||
uid = (__bridge_transfer NSString *)uidRef;
|
||||
}
|
||||
|
||||
// Channels & Input / Output determination
|
||||
AudioObjectPropertyAddress inputStreamsAddr = {
|
||||
.mSelector = kAudioDevicePropertyStreams,
|
||||
.mScope = kAudioDevicePropertyScopeInput,
|
||||
.mElement = kAudioObjectPropertyElementMain
|
||||
};
|
||||
UInt32 inStreamSize = 0;
|
||||
AudioObjectGetPropertyDataSize(devID, &inputStreamsAddr, 0, NULL, &inStreamSize);
|
||||
BOOL isInput = (inStreamSize > 0);
|
||||
|
||||
AudioObjectPropertyAddress outputStreamsAddr = {
|
||||
.mSelector = kAudioDevicePropertyStreams,
|
||||
.mScope = kAudioDevicePropertyScopeOutput,
|
||||
.mElement = kAudioObjectPropertyElementMain
|
||||
};
|
||||
UInt32 outStreamSize = 0;
|
||||
AudioObjectGetPropertyDataSize(devID, &outputStreamsAddr, 0, NULL, &outStreamSize);
|
||||
BOOL isOutput = (outStreamSize > 0);
|
||||
|
||||
// Sample rate
|
||||
Float64 sampleRate = 0.0;
|
||||
propSize = sizeof(Float64);
|
||||
AudioObjectPropertyAddress rateAddr = {
|
||||
.mSelector = kAudioDevicePropertyNominalSampleRate,
|
||||
.mScope = kAudioObjectPropertyScopeGlobal,
|
||||
.mElement = kAudioObjectPropertyElementMain
|
||||
};
|
||||
AudioObjectGetPropertyData(devID, &rateAddr, 0, NULL, &propSize, &sampleRate);
|
||||
|
||||
// Volume
|
||||
Float32 volume = 0.0f;
|
||||
AudioObjectPropertyScope volScope = isOutput ? kAudioDevicePropertyScopeOutput : kAudioDevicePropertyScopeInput;
|
||||
AudioObjectPropertyAddress volAddr = {
|
||||
.mSelector = kAudioDevicePropertyVolumeScalar,
|
||||
.mScope = volScope,
|
||||
.mElement = kAudioObjectPropertyElementMain
|
||||
};
|
||||
propSize = sizeof(Float32);
|
||||
if (AudioObjectHasProperty(devID, &volAddr)) {
|
||||
AudioObjectGetPropertyData(devID, &volAddr, 0, NULL, &propSize, &volume);
|
||||
}
|
||||
|
||||
// Mute status
|
||||
UInt32 mute = 0;
|
||||
AudioObjectPropertyAddress muteAddr = {
|
||||
.mSelector = kAudioDevicePropertyMute,
|
||||
.mScope = volScope,
|
||||
.mElement = kAudioObjectPropertyElementMain
|
||||
};
|
||||
propSize = sizeof(UInt32);
|
||||
if (AudioObjectHasProperty(devID, &muteAddr)) {
|
||||
AudioObjectGetPropertyData(devID, &muteAddr, 0, NULL, &propSize, &mute);
|
||||
}
|
||||
|
||||
MMAudioDevice *device = [[MMAudioDevice alloc] init];
|
||||
device.deviceID = devID;
|
||||
device.name = name;
|
||||
device.manufacturer = mfr;
|
||||
device.uid = uid;
|
||||
device.isInput = isInput;
|
||||
device.isOutput = isOutput;
|
||||
device.isDefaultInput = (devID == defaultIn);
|
||||
device.isDefaultOutput = (devID == defaultOut);
|
||||
device.sampleRate = (double)sampleRate;
|
||||
device.channelCount = (inStreamSize / sizeof(AudioStreamID)) + (outStreamSize / sizeof(AudioStreamID));
|
||||
device.volume = volume;
|
||||
device.isMuted = (mute != 0);
|
||||
|
||||
[devices addObject:device];
|
||||
}
|
||||
|
||||
free(deviceIDs);
|
||||
return devices;
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
|
||||
NSArray<MMAudioDevice *> *devices = [MMAudioTelemetryProvider sampleAudioDevices];
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *deviceList = [NSMutableArray arrayWithCapacity:devices.count];
|
||||
|
||||
MMAudioDevice *defaultIn = nil;
|
||||
MMAudioDevice *defaultOut = nil;
|
||||
|
||||
for (MMAudioDevice *d in devices) {
|
||||
[deviceList addObject:[d toDictionary]];
|
||||
if (d.isDefaultInput) defaultIn = d;
|
||||
if (d.isDefaultOutput) defaultOut = d;
|
||||
}
|
||||
|
||||
return @{
|
||||
@"devices": deviceList,
|
||||
@"deviceCount": @(devices.count),
|
||||
@"defaultInputDevice": defaultIn ? [defaultIn toDictionary] : [NSNull null],
|
||||
@"defaultOutputDevice": defaultOut ? [defaultOut toDictionary] : [NSNull null]
|
||||
};
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,31 @@
|
||||
#ifndef MMGPUTelemetryProvider_h
|
||||
#define MMGPUTelemetryProvider_h
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MMTelemetryProvider.h"
|
||||
#import "MMAppleSMCClient.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* MMGPUTelemetryProvider
|
||||
* Samples Intel Integrated Graphics (Iris/UHD) and AMD Discrete Graphics (Radeon/Vega)
|
||||
* utilization, VRAM allocation, and thermal metrics via IOKit and Metal.
|
||||
*/
|
||||
@interface MMGPUTelemetryProvider : NSObject <MMTelemetryProvider>
|
||||
|
||||
@property (nonatomic, strong, readonly) MMAppleSMCClient *smcClient;
|
||||
|
||||
- (instancetype)init;
|
||||
- (instancetype)initWithSMCClient:(MMAppleSMCClient *)client;
|
||||
|
||||
/**
|
||||
* Pure calculator method for deterministic unit testing.
|
||||
*/
|
||||
+ (NSDictionary<NSString *, id> *)calculateGPUMetricsWithDevices:(NSArray<NSDictionary<NSString *, id> *> *)gpuDevices;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif /* MMGPUTelemetryProvider_h */
|
||||
@@ -0,0 +1,184 @@
|
||||
#import "MMGPUTelemetryProvider.h"
|
||||
#import <IOKit/IOKitLib.h>
|
||||
#import <Metal/Metal.h>
|
||||
|
||||
@interface MMGPUTelemetryProvider () {
|
||||
MMAppleSMCClient *_smcClient;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation MMGPUTelemetryProvider
|
||||
|
||||
- (instancetype)init {
|
||||
return [self initWithSMCClient:[MMAppleSMCClient sharedClient]];
|
||||
}
|
||||
|
||||
- (instancetype)initWithSMCClient:(MMAppleSMCClient *)client {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_smcClient = client;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (MMTelemetryDomain)domain {
|
||||
return MMTelemetryDomainGPU;
|
||||
}
|
||||
|
||||
- (NSString *)providerIdentifier {
|
||||
return @"com.i3omb.macmonitor.telemetry.gpu";
|
||||
}
|
||||
|
||||
- (BOOL)isAvailable {
|
||||
return YES;
|
||||
}
|
||||
|
||||
- (MMAppleSMCClient *)smcClient {
|
||||
return _smcClient;
|
||||
}
|
||||
|
||||
+ (NSDictionary<NSString *, id> *)calculateGPUMetricsWithDevices:(NSArray<NSDictionary<NSString *, id> *> *)gpuDevices {
|
||||
double totalUtil = 0.0;
|
||||
double peakUtil = 0.0;
|
||||
NSString *activeGPU = @"None";
|
||||
|
||||
for (NSDictionary<NSString *, id> *gpu in gpuDevices) {
|
||||
double util = [gpu[@"utilization"] doubleValue];
|
||||
totalUtil += util;
|
||||
if (util > peakUtil) {
|
||||
peakUtil = util;
|
||||
activeGPU = gpu[@"name"] ?: @"GPU";
|
||||
}
|
||||
}
|
||||
|
||||
double avgUtil = gpuDevices.count > 0 ? (totalUtil / (double)gpuDevices.count) : 0.0;
|
||||
if ([activeGPU isEqualToString:@"None"] && gpuDevices.count > 0) {
|
||||
activeGPU = gpuDevices[0][@"name"] ?: @"GPU";
|
||||
}
|
||||
|
||||
return @{
|
||||
@"gpuCount": @(gpuDevices.count),
|
||||
@"averageUtilization": @(avgUtil),
|
||||
@"peakUtilization": @(peakUtil),
|
||||
@"activeGPUName": activeGPU,
|
||||
@"devices": gpuDevices
|
||||
};
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
|
||||
// 1. Query IOKit IOAccelerator performance statistics
|
||||
NSMutableDictionary<NSString *, NSDictionary *> *accelStatsByName = [NSMutableDictionary dictionary];
|
||||
|
||||
CFMutableDictionaryRef matching = IOServiceMatching("IOAccelerator");
|
||||
io_iterator_t iterator = IO_OBJECT_NULL;
|
||||
if (IOServiceGetMatchingServices(kIOMainPortDefault, matching, &iterator) == KERN_SUCCESS && iterator != IO_OBJECT_NULL) {
|
||||
io_registry_entry_t entry;
|
||||
while ((entry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) {
|
||||
CFMutableDictionaryRef props = NULL;
|
||||
if (IORegistryEntryCreateCFProperties(entry, &props, kCFAllocatorDefault, 0) == KERN_SUCCESS && props) {
|
||||
NSDictionary *dict = (__bridge NSDictionary *)props;
|
||||
NSDictionary *stats = dict[@"PerformanceStatistics"];
|
||||
io_name_t entryName;
|
||||
if (IORegistryEntryGetName(entry, entryName) == KERN_SUCCESS && stats) {
|
||||
accelStatsByName[[NSString stringWithUTF8String:entryName]] = stats;
|
||||
}
|
||||
CFRelease(props);
|
||||
}
|
||||
IOObjectRelease(entry);
|
||||
}
|
||||
IOObjectRelease(iterator);
|
||||
}
|
||||
|
||||
// 2. Query SMC for GPU temperature fallback
|
||||
NSNumber *smcGpuTemp = nil;
|
||||
if (_smcClient.isAvailable) {
|
||||
smcGpuTemp = [_smcClient readNumericValueForKey:@"TG0D" error:nil];
|
||||
if (!smcGpuTemp) {
|
||||
smcGpuTemp = [_smcClient readNumericValueForKey:@"TG0P" error:nil];
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Enumerate Metal devices
|
||||
NSArray<id<MTLDevice>> *metalDevices = MTLCopyAllDevices();
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *deviceList = [NSMutableArray array];
|
||||
|
||||
for (id<MTLDevice> dev in metalDevices) {
|
||||
NSString *name = dev.name;
|
||||
BOOL isLowPower = dev.isLowPower;
|
||||
BOOL isRemovable = dev.isRemovable;
|
||||
uint64_t maxMem = dev.recommendedMaxWorkingSetSize;
|
||||
|
||||
// Find matching stats
|
||||
double util = 0.0;
|
||||
uint64_t vramUsed = 0;
|
||||
uint64_t vramTotal = maxMem;
|
||||
double temp = smcGpuTemp ? [smcGpuTemp doubleValue] : 0.0;
|
||||
|
||||
for (NSString *accelName in accelStatsByName) {
|
||||
NSDictionary *stats = accelStatsByName[accelName];
|
||||
|
||||
// Check Intel stats
|
||||
if ([name containsString:@"Intel"] || [accelName containsString:@"Intel"]) {
|
||||
if (stats[@"Device Utilization %"]) {
|
||||
util = [stats[@"Device Utilization %"] doubleValue];
|
||||
}
|
||||
if (stats[@"gartUsedBytes"]) {
|
||||
vramUsed = [stats[@"gartUsedBytes"] unsignedLongLongValue];
|
||||
}
|
||||
if (stats[@"gartSizeBytes"]) {
|
||||
vramTotal = [stats[@"gartSizeBytes"] unsignedLongLongValue];
|
||||
}
|
||||
} else {
|
||||
// AMD / Discrete stats
|
||||
if (stats[@"GPU Activity(%)"]) {
|
||||
util = [stats[@"GPU Activity(%)"] doubleValue];
|
||||
} else if (stats[@"Device Utilization %"]) {
|
||||
util = [stats[@"Device Utilization %"] doubleValue];
|
||||
}
|
||||
if (stats[@"vramUsedBytes"]) {
|
||||
vramUsed = [stats[@"vramUsedBytes"] unsignedLongLongValue];
|
||||
}
|
||||
if (stats[@"vramFreeBytes"]) {
|
||||
uint64_t freeBytes = [stats[@"vramFreeBytes"] unsignedLongLongValue];
|
||||
vramTotal = vramUsed + freeBytes;
|
||||
}
|
||||
if (stats[@"Temperature(C)"]) {
|
||||
temp = [stats[@"Temperature(C)"] doubleValue];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
NSString *gpuType = isLowPower || [name containsString:@"Intel"] ? @"Integrated" : @"Discrete";
|
||||
|
||||
[deviceList addObject:@{
|
||||
@"name": name,
|
||||
@"type": gpuType,
|
||||
@"utilization": @(util),
|
||||
@"vramUsedBytes": @(vramUsed),
|
||||
@"vramTotalBytes": @(vramTotal),
|
||||
@"temperature": @(temp),
|
||||
@"isLowPower": @(isLowPower),
|
||||
@"isRemovable": @(isRemovable),
|
||||
@"recommendedMaxWorkingSetBytes": @(maxMem)
|
||||
}];
|
||||
}
|
||||
|
||||
// Fallback if no Metal devices enumerated (headless / virtualization)
|
||||
if (deviceList.count == 0) {
|
||||
[deviceList addObject:@{
|
||||
@"name": @"Default GPU",
|
||||
@"type": @"Integrated",
|
||||
@"utilization": @(0.0),
|
||||
@"vramUsedBytes": @(0),
|
||||
@"vramTotalBytes": @(1024 * 1024 * 1024),
|
||||
@"temperature": @(0.0),
|
||||
@"isLowPower": @(YES),
|
||||
@"isRemovable": @(NO),
|
||||
@"recommendedMaxWorkingSetBytes": @(1024 * 1024 * 1024)
|
||||
}];
|
||||
}
|
||||
|
||||
return [MMGPUTelemetryProvider calculateGPUMetricsWithDevices:deviceList];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,30 @@
|
||||
#ifndef MMKernelTelemetryProvider_h
|
||||
#define MMKernelTelemetryProvider_h
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MMTelemetryProvider.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* MMKernelTelemetryProvider
|
||||
* Samples low-level Mach kernel performance counters: context switches, system calls,
|
||||
* page faults (soft, COW, zero-fill), pageins/pageouts, and computes instantaneous rates per second.
|
||||
*/
|
||||
@interface MMKernelTelemetryProvider : NSObject <MMTelemetryProvider>
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
* Static calculator method for deterministic unit testing.
|
||||
* Computes event rates per second based on previous and current cumulative counters over delta time.
|
||||
*/
|
||||
+ (NSDictionary<NSString *, id> *)calculateRatesWithCurrentCounters:(NSDictionary<NSString *, NSNumber *> *)current
|
||||
previousCounters:(nullable NSDictionary<NSString *, NSNumber *> *)previous
|
||||
timeDelta:(NSTimeInterval)timeDelta;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif /* MMKernelTelemetryProvider_h */
|
||||
@@ -0,0 +1,131 @@
|
||||
#import "MMKernelTelemetryProvider.h"
|
||||
#import <mach/mach.h>
|
||||
#import <mach/mach_time.h>
|
||||
#import <libproc.h>
|
||||
#import <os/lock.h>
|
||||
|
||||
@interface MMKernelTelemetryProvider () {
|
||||
os_unfair_lock _lock;
|
||||
NSDictionary<NSString *, NSNumber *> *_previousCounters;
|
||||
uint64_t _previousTimestamp;
|
||||
mach_timebase_info_data_t _timebase;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation MMKernelTelemetryProvider
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_lock = OS_UNFAIR_LOCK_INIT;
|
||||
_previousCounters = nil;
|
||||
_previousTimestamp = 0;
|
||||
mach_timebase_info(&_timebase);
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (MMTelemetryDomain)domain {
|
||||
return MMTelemetryDomainSystem;
|
||||
}
|
||||
|
||||
- (NSString *)providerIdentifier {
|
||||
return @"com.i3omb.macmonitor.telemetry.kernel.counters";
|
||||
}
|
||||
|
||||
- (BOOL)isAvailable {
|
||||
return YES;
|
||||
}
|
||||
|
||||
+ (NSDictionary<NSString *, id> *)calculateRatesWithCurrentCounters:(NSDictionary<NSString *, NSNumber *> *)current
|
||||
previousCounters:(nullable NSDictionary<NSString *, NSNumber *> *)previous
|
||||
timeDelta:(NSTimeInterval)timeDelta {
|
||||
NSMutableDictionary<NSString *, id> *result = [NSMutableDictionary dictionary];
|
||||
|
||||
// Copy all current cumulative counters into result
|
||||
[current enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSNumber *val, BOOL *stop) {
|
||||
result[[@"cumulative_" stringByAppendingString:key]] = val;
|
||||
}];
|
||||
|
||||
NSArray<NSString *> *rateKeys = @[
|
||||
@"contextSwitches", @"syscalls", @"pageFaults", @"cowFaults",
|
||||
@"zeroFills", @"pageins", @"pageouts", @"decompressions", @"compressions"
|
||||
];
|
||||
|
||||
for (NSString *key in rateKeys) {
|
||||
double currentVal = [current[key] doubleValue];
|
||||
double prevVal = previous ? [previous[key] doubleValue] : currentVal;
|
||||
double delta = (currentVal >= prevVal) ? (currentVal - prevVal) : 0.0;
|
||||
double rate = (timeDelta > 0.0001) ? (delta / timeDelta) : 0.0;
|
||||
result[[key stringByAppendingString:@"Rate"]] = @(rate);
|
||||
}
|
||||
|
||||
result[@"timeDelta"] = @(timeDelta);
|
||||
return result;
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
|
||||
uint64_t now = mach_absolute_time();
|
||||
|
||||
// 1. Query Mach VM Statistics for page faults, COW, zero fills, pageins/outs
|
||||
vm_statistics64_data_t vmStats;
|
||||
mach_msg_type_number_t count = HOST_VM_INFO64_COUNT;
|
||||
kern_return_t kr = host_statistics64(mach_host_self(), HOST_VM_INFO64, (host_info64_t)&vmStats, &count);
|
||||
if (kr != KERN_SUCCESS) {
|
||||
if (error) {
|
||||
*error = [NSError errorWithDomain:@"com.i3omb.macmonitor.kernel"
|
||||
code:kr
|
||||
userInfo:@{NSLocalizedDescriptionKey: @"Failed to query host_statistics64"}];
|
||||
}
|
||||
return nil;
|
||||
}
|
||||
|
||||
// 2. Query process table for cumulative context switches and system calls
|
||||
int pids[4096];
|
||||
int bytes = proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids));
|
||||
int pidCount = bytes / sizeof(int);
|
||||
|
||||
uint64_t totalCSW = 0;
|
||||
uint64_t totalSyscalls = 0;
|
||||
|
||||
for (int i = 0; i < pidCount; i++) {
|
||||
if (pids[i] <= 0) continue;
|
||||
struct proc_taskinfo ti;
|
||||
if (proc_pidinfo(pids[i], PROC_PIDTASKINFO, 0, &ti, sizeof(ti)) == sizeof(ti)) {
|
||||
totalCSW += ti.pti_csw;
|
||||
totalSyscalls += (uint64_t)ti.pti_syscalls_unix + (uint64_t)ti.pti_syscalls_mach;
|
||||
}
|
||||
}
|
||||
|
||||
NSDictionary<NSString *, NSNumber *> *currentCounters = @{
|
||||
@"contextSwitches": @(totalCSW),
|
||||
@"syscalls": @(totalSyscalls),
|
||||
@"pageFaults": @(vmStats.faults),
|
||||
@"cowFaults": @(vmStats.cow_faults),
|
||||
@"zeroFills": @(vmStats.zero_fill_count),
|
||||
@"pageins": @(vmStats.pageins),
|
||||
@"pageouts": @(vmStats.pageouts),
|
||||
@"decompressions": @(vmStats.decompressions),
|
||||
@"compressions": @(vmStats.compressions)
|
||||
};
|
||||
|
||||
os_unfair_lock_lock(&_lock);
|
||||
NSDictionary<NSString *, NSNumber *> *prev = _previousCounters;
|
||||
uint64_t prevTime = _previousTimestamp;
|
||||
|
||||
_previousCounters = currentCounters;
|
||||
_previousTimestamp = now;
|
||||
os_unfair_lock_unlock(&_lock);
|
||||
|
||||
NSTimeInterval timeDelta = 1.0;
|
||||
if (prevTime > 0) {
|
||||
uint64_t elapsed = now - prevTime;
|
||||
timeDelta = (double)elapsed * _timebase.numer / _timebase.denom / 1e9;
|
||||
}
|
||||
|
||||
return [MMKernelTelemetryProvider calculateRatesWithCurrentCounters:currentCounters
|
||||
previousCounters:prev
|
||||
timeDelta:timeDelta];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,30 @@
|
||||
#ifndef MMNetworkBandwidthProvider_h
|
||||
#define MMNetworkBandwidthProvider_h
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MMTelemetryProvider.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* MMNetworkBandwidthProvider
|
||||
* Samples real-time network download and upload throughput, packets/sec, and error counts
|
||||
* across physical (Wi-Fi, Ethernet) and virtual (VPN, bridge) network interfaces.
|
||||
*/
|
||||
@interface MMNetworkBandwidthProvider : NSObject <MMTelemetryProvider>
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
* Pure calculator method for deterministic unit testing.
|
||||
*/
|
||||
+ (NSDictionary<NSString *, id> *)calculateBandwidthMetricsWithCurrentSnapshots:(NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)current
|
||||
previousSnapshots:(nullable NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)previous
|
||||
timeDelta:(NSTimeInterval)timeDelta
|
||||
ipAddresses:(nullable NSDictionary<NSString *, NSString *> *)ipAddresses;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif /* MMNetworkBandwidthProvider_h */
|
||||
@@ -0,0 +1,211 @@
|
||||
#import "MMNetworkBandwidthProvider.h"
|
||||
#import <sys/sysctl.h>
|
||||
#import <net/if.h>
|
||||
#import <net/if_dl.h>
|
||||
#import <net/route.h>
|
||||
#import <ifaddrs.h>
|
||||
#import <arpa/inet.h>
|
||||
#import <mach/mach_time.h>
|
||||
#import <os/lock.h>
|
||||
|
||||
@interface MMNetworkBandwidthProvider () {
|
||||
os_unfair_lock _lock;
|
||||
NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *_previousSnapshots;
|
||||
uint64_t _previousTimestamp;
|
||||
mach_timebase_info_data_t _timebase;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation MMNetworkBandwidthProvider
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_lock = OS_UNFAIR_LOCK_INIT;
|
||||
_previousSnapshots = nil;
|
||||
_previousTimestamp = 0;
|
||||
mach_timebase_info(&_timebase);
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (MMTelemetryDomain)domain {
|
||||
return MMTelemetryDomainNetwork;
|
||||
}
|
||||
|
||||
- (NSString *)providerIdentifier {
|
||||
return @"com.i3omb.macmonitor.telemetry.network.bandwidth";
|
||||
}
|
||||
|
||||
- (BOOL)isAvailable {
|
||||
return YES;
|
||||
}
|
||||
|
||||
+ (NSDictionary<NSString *, id> *)calculateBandwidthMetricsWithCurrentSnapshots:(NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)current
|
||||
previousSnapshots:(nullable NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)previous
|
||||
timeDelta:(NSTimeInterval)timeDelta
|
||||
ipAddresses:(nullable NSDictionary<NSString *, NSString *> *)ipAddresses {
|
||||
double totalDownBps = 0.0;
|
||||
double totalUpBps = 0.0;
|
||||
double totalDownPps = 0.0;
|
||||
double totalUpPps = 0.0;
|
||||
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *interfaces = [NSMutableArray arrayWithCapacity:current.count];
|
||||
NSArray<NSString *> *sortedNames = [current.allKeys sortedArrayUsingSelector:@selector(compare:)];
|
||||
|
||||
NSString *primaryInterface = @"";
|
||||
double maxActivity = -1.0;
|
||||
|
||||
for (NSString *name in sortedNames) {
|
||||
// Skip loopback for aggregate statistics
|
||||
BOOL isLoopback = [name hasPrefix:@"lo"];
|
||||
|
||||
NSDictionary<NSString *, NSNumber *> *curr = current[name];
|
||||
NSDictionary<NSString *, NSNumber *> *prev = previous ? previous[name] : nil;
|
||||
|
||||
uint64_t currInBytes = [curr[@"inBytes"] unsignedLongLongValue];
|
||||
uint64_t currOutBytes = [curr[@"outBytes"] unsignedLongLongValue];
|
||||
uint64_t currInPackets = [curr[@"inPackets"] unsignedLongLongValue];
|
||||
uint64_t currOutPackets = [curr[@"outPackets"] unsignedLongLongValue];
|
||||
uint64_t inErrors = [curr[@"inErrors"] unsignedLongLongValue];
|
||||
uint64_t outErrors = [curr[@"outErrors"] unsignedLongLongValue];
|
||||
|
||||
uint64_t prevInBytes = prev ? [prev[@"inBytes"] unsignedLongLongValue] : currInBytes;
|
||||
uint64_t prevOutBytes = prev ? [prev[@"outBytes"] unsignedLongLongValue] : currOutBytes;
|
||||
uint64_t prevInPackets = prev ? [prev[@"inPackets"] unsignedLongLongValue] : currInPackets;
|
||||
uint64_t prevOutPackets = prev ? [prev[@"outPackets"] unsignedLongLongValue] : currOutPackets;
|
||||
|
||||
double deltaInBytes = (currInBytes >= prevInBytes) ? (double)(currInBytes - prevInBytes) : 0.0;
|
||||
double deltaOutBytes = (currOutBytes >= prevOutBytes) ? (double)(currOutBytes - prevOutBytes) : 0.0;
|
||||
double deltaInPackets = (currInPackets >= prevInPackets) ? (double)(currInPackets - prevInPackets) : 0.0;
|
||||
double deltaOutPackets = (currOutPackets >= prevOutPackets) ? (double)(currOutPackets - prevOutPackets) : 0.0;
|
||||
|
||||
double downBps = (timeDelta > 0.0001) ? (deltaInBytes / timeDelta) : 0.0;
|
||||
double upBps = (timeDelta > 0.0001) ? (deltaOutBytes / timeDelta) : 0.0;
|
||||
double downPps = (timeDelta > 0.0001) ? (deltaInPackets / timeDelta) : 0.0;
|
||||
double upPps = (timeDelta > 0.0001) ? (deltaOutPackets / timeDelta) : 0.0;
|
||||
|
||||
if (!isLoopback) {
|
||||
totalDownBps += downBps;
|
||||
totalUpBps += upBps;
|
||||
totalDownPps += downPps;
|
||||
totalUpPps += upPps;
|
||||
|
||||
double activity = downBps + upBps;
|
||||
if (activity > maxActivity) {
|
||||
maxActivity = activity;
|
||||
primaryInterface = name;
|
||||
}
|
||||
}
|
||||
|
||||
NSString *ip = ipAddresses[name] ?: @"";
|
||||
|
||||
[interfaces addObject:@{
|
||||
@"name": name,
|
||||
@"downloadBytesPerSec": @(downBps),
|
||||
@"uploadBytesPerSec": @(upBps),
|
||||
@"downloadPacketsPerSec": @(downPps),
|
||||
@"uploadPacketsPerSec": @(upPps),
|
||||
@"cumulativeInBytes": @(currInBytes),
|
||||
@"cumulativeOutBytes": @(currOutBytes),
|
||||
@"cumulativeInPackets": @(currInPackets),
|
||||
@"cumulativeOutPackets": @(currOutPackets),
|
||||
@"inErrors": @(inErrors),
|
||||
@"outErrors": @(outErrors),
|
||||
@"ipv4Address": ip,
|
||||
@"isLoopback": @(isLoopback)
|
||||
}];
|
||||
}
|
||||
|
||||
if (primaryInterface.length == 0 && current[@"en0"]) {
|
||||
primaryInterface = @"en0";
|
||||
}
|
||||
|
||||
return @{
|
||||
@"interfaces": interfaces,
|
||||
@"totalDownloadBytesPerSec": @(totalDownBps),
|
||||
@"totalUploadBytesPerSec": @(totalUpBps),
|
||||
@"totalDownloadPacketsPerSec": @(totalDownPps),
|
||||
@"totalUploadPacketsPerSec": @(totalUpPps),
|
||||
@"primaryInterface": primaryInterface,
|
||||
@"timeDelta": @(timeDelta)
|
||||
};
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
|
||||
uint64_t now = mach_absolute_time();
|
||||
|
||||
// 1. Read 64-bit interface stats via NET_RT_IFLIST2
|
||||
NSMutableDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *currentSnapshots = [NSMutableDictionary dictionary];
|
||||
|
||||
int mib[] = { CTL_NET, PF_ROUTE, 0, 0, NET_RT_IFLIST2, 0 };
|
||||
size_t len = 0;
|
||||
if (sysctl(mib, 6, NULL, &len, NULL, 0) == 0 && len > 0) {
|
||||
char *buf = malloc(len);
|
||||
if (buf && sysctl(mib, 6, buf, &len, NULL, 0) == 0) {
|
||||
char *next = buf;
|
||||
char *lim = buf + len;
|
||||
while (next < lim) {
|
||||
struct if_msghdr *ifm = (struct if_msghdr *)next;
|
||||
next += ifm->ifm_msglen;
|
||||
if (ifm->ifm_type == RTM_IFINFO2) {
|
||||
struct if_msghdr2 *if2m = (struct if_msghdr2 *)ifm;
|
||||
struct sockaddr_dl *sdl = (struct sockaddr_dl *)(if2m + 1);
|
||||
if (sdl->sdl_nlen > 0 && sdl->sdl_nlen < 32) {
|
||||
char nameBuf[33] = {0};
|
||||
memcpy(nameBuf, sdl->sdl_data, sdl->sdl_nlen);
|
||||
NSString *name = [NSString stringWithUTF8String:nameBuf];
|
||||
|
||||
currentSnapshots[name] = @{
|
||||
@"inBytes": @(if2m->ifm_data.ifi_ibytes),
|
||||
@"outBytes": @(if2m->ifm_data.ifi_obytes),
|
||||
@"inPackets": @(if2m->ifm_data.ifi_ipackets),
|
||||
@"outPackets": @(if2m->ifm_data.ifi_opackets),
|
||||
@"inErrors": @(if2m->ifm_data.ifi_ierrors),
|
||||
@"outErrors": @(if2m->ifm_data.ifi_oerrors)
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (buf) free(buf);
|
||||
}
|
||||
|
||||
// 2. Query IPv4 addresses via getifaddrs
|
||||
NSMutableDictionary<NSString *, NSString *> *ipDict = [NSMutableDictionary dictionary];
|
||||
struct ifaddrs *ifap = NULL;
|
||||
if (getifaddrs(&ifap) == 0) {
|
||||
for (struct ifaddrs *ifa = ifap; ifa != NULL; ifa = ifa->ifa_next) {
|
||||
if (ifa->ifa_addr && ifa->ifa_addr->sa_family == AF_INET) {
|
||||
char ipBuf[INET_ADDRSTRLEN] = {0};
|
||||
struct sockaddr_in *sin = (struct sockaddr_in *)ifa->ifa_addr;
|
||||
if (inet_ntop(AF_INET, &sin->sin_addr, ipBuf, sizeof(ipBuf))) {
|
||||
NSString *name = [NSString stringWithUTF8String:ifa->ifa_name];
|
||||
ipDict[name] = [NSString stringWithUTF8String:ipBuf];
|
||||
}
|
||||
}
|
||||
}
|
||||
freeifaddrs(ifap);
|
||||
}
|
||||
|
||||
os_unfair_lock_lock(&_lock);
|
||||
NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *prev = _previousSnapshots;
|
||||
uint64_t prevTime = _previousTimestamp;
|
||||
|
||||
_previousSnapshots = currentSnapshots;
|
||||
_previousTimestamp = now;
|
||||
os_unfair_lock_unlock(&_lock);
|
||||
|
||||
NSTimeInterval timeDelta = 1.0;
|
||||
if (prevTime > 0) {
|
||||
uint64_t elapsed = now - prevTime;
|
||||
timeDelta = (double)elapsed * _timebase.numer / _timebase.denom / 1e9;
|
||||
}
|
||||
|
||||
return [MMNetworkBandwidthProvider calculateBandwidthMetricsWithCurrentSnapshots:currentSnapshots
|
||||
previousSnapshots:prev
|
||||
timeDelta:timeDelta
|
||||
ipAddresses:ipDict];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,27 @@
|
||||
#ifndef MMNetworkSocketsProvider_h
|
||||
#define MMNetworkSocketsProvider_h
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MMTelemetryProvider.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* MMNetworkSocketsProvider
|
||||
* Inspects system-wide open TCP and UDP sockets, local/remote endpoints, connection states,
|
||||
* and owning processes.
|
||||
*/
|
||||
@interface MMNetworkSocketsProvider : NSObject <MMTelemetryProvider>
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
* Pure calculator / summarizer method for deterministic unit testing.
|
||||
*/
|
||||
+ (NSDictionary<NSString *, id> *)calculateSocketSummaryWithSocketList:(NSArray<NSDictionary<NSString *, id> *> *)sockets;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif /* MMNetworkSocketsProvider_h */
|
||||
@@ -0,0 +1,152 @@
|
||||
#import "MMNetworkSocketsProvider.h"
|
||||
#import <libproc.h>
|
||||
#import <sys/proc_info.h>
|
||||
#import <arpa/inet.h>
|
||||
|
||||
@implementation MMNetworkSocketsProvider
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
return self;
|
||||
}
|
||||
|
||||
- (MMTelemetryDomain)domain {
|
||||
return MMTelemetryDomainNetwork;
|
||||
}
|
||||
|
||||
- (NSString *)providerIdentifier {
|
||||
return @"com.i3omb.macmonitor.telemetry.network.sockets";
|
||||
}
|
||||
|
||||
- (BOOL)isAvailable {
|
||||
return YES;
|
||||
}
|
||||
|
||||
static NSString *tcpStateString(int state) {
|
||||
switch (state) {
|
||||
case 0: return @"CLOSED";
|
||||
case 1: return @"LISTEN";
|
||||
case 2: return @"SYN_SENT";
|
||||
case 3: return @"SYN_RCVD";
|
||||
case 4: return @"ESTABLISHED";
|
||||
case 5: return @"CLOSE_WAIT";
|
||||
case 6: return @"FIN_WAIT_1";
|
||||
case 7: return @"CLOSING";
|
||||
case 8: return @"LAST_ACK";
|
||||
case 9: return @"FIN_WAIT_2";
|
||||
case 10: return @"TIME_WAIT";
|
||||
default: return @"UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
+ (NSDictionary<NSString *, id> *)calculateSocketSummaryWithSocketList:(NSArray<NSDictionary<NSString *, id> *> *)sockets {
|
||||
NSUInteger tcpCount = 0;
|
||||
NSUInteger udpCount = 0;
|
||||
NSUInteger listenCount = 0;
|
||||
NSUInteger establishedCount = 0;
|
||||
|
||||
for (NSDictionary<NSString *, id> *sock in sockets) {
|
||||
NSString *proto = sock[@"protocol"];
|
||||
NSString *state = sock[@"state"];
|
||||
|
||||
if ([proto isEqualToString:@"TCP"]) {
|
||||
tcpCount++;
|
||||
if ([state isEqualToString:@"LISTEN"]) {
|
||||
listenCount++;
|
||||
} else if ([state isEqualToString:@"ESTABLISHED"]) {
|
||||
establishedCount++;
|
||||
}
|
||||
} else if ([proto isEqualToString:@"UDP"]) {
|
||||
udpCount++;
|
||||
}
|
||||
}
|
||||
|
||||
return @{
|
||||
@"socketCount": @(sockets.count),
|
||||
@"tcpCount": @(tcpCount),
|
||||
@"udpCount": @(udpCount),
|
||||
@"listenCount": @(listenCount),
|
||||
@"establishedCount": @(establishedCount),
|
||||
@"sockets": sockets
|
||||
};
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
|
||||
int pids[2048];
|
||||
int bytes = proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids));
|
||||
int pidCount = bytes / sizeof(int);
|
||||
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *sockets = [NSMutableArray array];
|
||||
|
||||
for (int i = 0; i < pidCount; i++) {
|
||||
pid_t pid = pids[i];
|
||||
if (pid <= 0) continue;
|
||||
|
||||
int sz = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0);
|
||||
if (sz <= 0) continue;
|
||||
|
||||
struct proc_fdinfo *fds = malloc(sz);
|
||||
if (!fds) continue;
|
||||
|
||||
int actual = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, fds, sz);
|
||||
int fdCount = actual / sizeof(struct proc_fdinfo);
|
||||
|
||||
char procNameBuf[256] = {0};
|
||||
BOOL procNameFetched = NO;
|
||||
|
||||
for (int j = 0; j < fdCount; j++) {
|
||||
if (fds[j].proc_fdtype == PROX_FDTYPE_SOCKET) {
|
||||
struct socket_fdinfo si;
|
||||
if (proc_pidfdinfo(pid, fds[j].proc_fd, PROC_PIDFDSOCKETINFO, &si, sizeof(si)) == sizeof(si)) {
|
||||
int family = si.psi.soi_family;
|
||||
if (family == AF_INET || family == AF_INET6) {
|
||||
if (!procNameFetched) {
|
||||
proc_name(pid, procNameBuf, sizeof(procNameBuf));
|
||||
procNameFetched = YES;
|
||||
}
|
||||
|
||||
char localIP[INET6_ADDRSTRLEN] = {0};
|
||||
char remoteIP[INET6_ADDRSTRLEN] = {0};
|
||||
int lport = 0, rport = 0;
|
||||
NSString *familyStr = (family == AF_INET) ? @"IPv4" : @"IPv6";
|
||||
NSString *proto = (si.psi.soi_type == SOCK_STREAM) ? @"TCP" : @"UDP";
|
||||
NSString *state = @"NONE";
|
||||
|
||||
if (family == AF_INET) {
|
||||
inet_ntop(AF_INET, &si.psi.soi_proto.pri_in.insi_laddr.ina_46.i46a_addr4, localIP, sizeof(localIP));
|
||||
inet_ntop(AF_INET, &si.psi.soi_proto.pri_in.insi_faddr.ina_46.i46a_addr4, remoteIP, sizeof(remoteIP));
|
||||
lport = ntohs(si.psi.soi_proto.pri_in.insi_lport);
|
||||
rport = ntohs(si.psi.soi_proto.pri_in.insi_fport);
|
||||
} else {
|
||||
inet_ntop(AF_INET6, &si.psi.soi_proto.pri_in.insi_laddr.ina_6, localIP, sizeof(localIP));
|
||||
inet_ntop(AF_INET6, &si.psi.soi_proto.pri_in.insi_faddr.ina_6, remoteIP, sizeof(remoteIP));
|
||||
lport = ntohs(si.psi.soi_proto.pri_in.insi_lport);
|
||||
rport = ntohs(si.psi.soi_proto.pri_in.insi_fport);
|
||||
}
|
||||
|
||||
if (si.psi.soi_type == SOCK_STREAM) {
|
||||
state = tcpStateString(si.psi.soi_proto.pri_tcp.tcpsi_state);
|
||||
}
|
||||
|
||||
[sockets addObject:@{
|
||||
@"pid": @(pid),
|
||||
@"processName": [NSString stringWithUTF8String:procNameBuf],
|
||||
@"protocol": proto,
|
||||
@"family": familyStr,
|
||||
@"localAddress": [NSString stringWithUTF8String:localIP],
|
||||
@"localPort": @(lport),
|
||||
@"remoteAddress": [NSString stringWithUTF8String:remoteIP],
|
||||
@"remotePort": @(rport),
|
||||
@"state": state
|
||||
}];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
free(fds);
|
||||
}
|
||||
|
||||
return [MMNetworkSocketsProvider calculateSocketSummaryWithSocketList:sockets];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,45 @@
|
||||
//
|
||||
// MMPeripheralsProvider.h
|
||||
// MacMonitor
|
||||
//
|
||||
// Telemetry provider enumerating connected USB, Thunderbolt, and PCI peripheral devices via IOKit.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MMTelemetryProvider.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
typedef NS_ENUM(NSInteger, MMPeripheralBusType) {
|
||||
MMPeripheralBusTypeUSB,
|
||||
MMPeripheralBusTypeThunderbolt,
|
||||
MMPeripheralBusTypePCI
|
||||
};
|
||||
|
||||
@interface MMPeripheralDevice : NSObject
|
||||
|
||||
@property (nonatomic, copy) NSString *name;
|
||||
@property (nonatomic, assign) MMPeripheralBusType busType;
|
||||
@property (nonatomic, copy) NSString *vendorName;
|
||||
@property (nonatomic, assign) uint32_t vendorID;
|
||||
@property (nonatomic, assign) uint32_t productID;
|
||||
@property (nonatomic, copy, nullable) NSString *serialNumber;
|
||||
@property (nonatomic, copy, nullable) NSString *deviceClass;
|
||||
@property (nonatomic, assign) uint64_t locationID;
|
||||
@property (nonatomic, assign) BOOL isBuiltIn;
|
||||
|
||||
- (NSDictionary<NSString *, id> *)toDictionary;
|
||||
|
||||
@end
|
||||
|
||||
@interface MMPeripheralsProvider : NSObject <MMTelemetryProvider>
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
+ (NSArray<MMPeripheralDevice *> *)sampleUSBDevices;
|
||||
+ (NSArray<MMPeripheralDevice *> *)sampleThunderboltDevices;
|
||||
+ (NSArray<MMPeripheralDevice *> *)samplePCIDevices;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,255 @@
|
||||
//
|
||||
// MMPeripheralsProvider.m
|
||||
// MacMonitor
|
||||
//
|
||||
// Telemetry provider enumerating connected USB, Thunderbolt, and PCI peripheral devices via IOKit.
|
||||
//
|
||||
|
||||
#import "MMPeripheralsProvider.h"
|
||||
#import <IOKit/IOKitLib.h>
|
||||
|
||||
@implementation MMPeripheralDevice
|
||||
|
||||
- (NSDictionary<NSString *, id> *)toDictionary {
|
||||
NSString *busStr = @"USB";
|
||||
if (self.busType == MMPeripheralBusTypeThunderbolt) {
|
||||
busStr = @"Thunderbolt";
|
||||
} else if (self.busType == MMPeripheralBusTypePCI) {
|
||||
busStr = @"PCI";
|
||||
}
|
||||
|
||||
return @{
|
||||
@"name": self.name ?: @"Unknown Device",
|
||||
@"busType": busStr,
|
||||
@"vendorName": self.vendorName ?: @"Unknown",
|
||||
@"vendorID": @(self.vendorID),
|
||||
@"productID": @(self.productID),
|
||||
@"serialNumber": self.serialNumber ?: @"",
|
||||
@"deviceClass": self.deviceClass ?: @"",
|
||||
@"locationID": @(self.locationID),
|
||||
@"isBuiltIn": @(self.isBuiltIn)
|
||||
};
|
||||
}
|
||||
|
||||
@end
|
||||
|
||||
@implementation MMPeripheralsProvider
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
return self;
|
||||
}
|
||||
|
||||
- (MMTelemetryDomain)domain {
|
||||
return MMTelemetryDomainPeripherals;
|
||||
}
|
||||
|
||||
- (NSString *)providerIdentifier {
|
||||
return @"com.i3omb.macmonitor.telemetry.peripherals";
|
||||
}
|
||||
|
||||
- (BOOL)isAvailable {
|
||||
return YES;
|
||||
}
|
||||
|
||||
+ (NSArray<MMPeripheralDevice *> *)sampleUSBDevices {
|
||||
NSMutableArray<MMPeripheralDevice *> *devices = [NSMutableArray array];
|
||||
|
||||
// Query both IOUSBHostDevice (macOS modern) and IOUSBDevice (legacy/fallback)
|
||||
const char *classes[] = { "IOUSBHostDevice", "IOUSBDevice" };
|
||||
NSMutableSet<NSNumber *> *seenRegistryIDs = [NSMutableSet set];
|
||||
|
||||
for (int i = 0; i < 2; i++) {
|
||||
CFMutableDictionaryRef matching = IOServiceMatching(classes[i]);
|
||||
if (!matching) continue;
|
||||
|
||||
io_iterator_t iterator = IO_OBJECT_NULL;
|
||||
kern_return_t kr = IOServiceGetMatchingServices(kIOMainPortDefault, matching, &iterator);
|
||||
if (kr != KERN_SUCCESS || iterator == IO_OBJECT_NULL) continue;
|
||||
|
||||
io_service_t service = IO_OBJECT_NULL;
|
||||
while ((service = IOIteratorNext(iterator)) != IO_OBJECT_NULL) {
|
||||
uint64_t regID = 0;
|
||||
IORegistryEntryGetRegistryEntryID(service, ®ID);
|
||||
if ([seenRegistryIDs containsObject:@(regID)]) {
|
||||
IOObjectRelease(service);
|
||||
continue;
|
||||
}
|
||||
[seenRegistryIDs addObject:@(regID)];
|
||||
|
||||
CFMutableDictionaryRef props = NULL;
|
||||
if (IORegistryEntryCreateCFProperties(service, &props, kCFAllocatorDefault, 0) == KERN_SUCCESS && props) {
|
||||
NSDictionary *dict = (__bridge NSDictionary *)props;
|
||||
|
||||
NSString *name = dict[@"USB Product Name"] ?: (dict[@"kUSBProductString"] ?: dict[@"IOName"]);
|
||||
if (!name || name.length == 0) {
|
||||
name = @"USB Device";
|
||||
}
|
||||
|
||||
NSString *vendor = dict[@"USB Vendor Name"] ?: (dict[@"kUSBVendorString"] ?: @"");
|
||||
uint32_t vendorID = [dict[@"idVendor"] unsignedIntValue];
|
||||
uint32_t productID = [dict[@"idProduct"] unsignedIntValue];
|
||||
NSString *serial = dict[@"USB Serial Number"] ?: dict[@"kUSBSerialNumberString"];
|
||||
uint64_t locID = [dict[@"locationID"] unsignedLongLongValue];
|
||||
|
||||
BOOL builtIn = NO;
|
||||
if (dict[@"Built-In"]) {
|
||||
builtIn = [dict[@"Built-In"] boolValue];
|
||||
} else if ([dict[@"non-removable"] isKindOfClass:[NSString class]]) {
|
||||
builtIn = [dict[@"non-removable"] isEqualToString:@"yes"];
|
||||
}
|
||||
|
||||
MMPeripheralDevice *dev = [[MMPeripheralDevice alloc] init];
|
||||
dev.name = name;
|
||||
dev.busType = MMPeripheralBusTypeUSB;
|
||||
dev.vendorName = vendor;
|
||||
dev.vendorID = vendorID;
|
||||
dev.productID = productID;
|
||||
dev.serialNumber = serial;
|
||||
dev.locationID = locID;
|
||||
dev.isBuiltIn = builtIn;
|
||||
|
||||
[devices addObject:dev];
|
||||
CFRelease(props);
|
||||
}
|
||||
IOObjectRelease(service);
|
||||
}
|
||||
IOObjectRelease(iterator);
|
||||
}
|
||||
|
||||
return devices;
|
||||
}
|
||||
|
||||
+ (NSArray<MMPeripheralDevice *> *)sampleThunderboltDevices {
|
||||
NSMutableArray<MMPeripheralDevice *> *devices = [NSMutableArray array];
|
||||
|
||||
CFMutableDictionaryRef matching = IOServiceMatching("IOThunderboltDevice");
|
||||
if (!matching) return devices;
|
||||
|
||||
io_iterator_t iterator = IO_OBJECT_NULL;
|
||||
kern_return_t kr = IOServiceGetMatchingServices(kIOMainPortDefault, matching, &iterator);
|
||||
if (kr != KERN_SUCCESS || iterator == IO_OBJECT_NULL) return devices;
|
||||
|
||||
io_service_t service = IO_OBJECT_NULL;
|
||||
while ((service = IOIteratorNext(iterator)) != IO_OBJECT_NULL) {
|
||||
CFMutableDictionaryRef props = NULL;
|
||||
if (IORegistryEntryCreateCFProperties(service, &props, kCFAllocatorDefault, 0) == KERN_SUCCESS && props) {
|
||||
NSDictionary *dict = (__bridge NSDictionary *)props;
|
||||
|
||||
NSString *name = dict[@"Device Name"] ?: dict[@"IOName"];
|
||||
if (!name) name = @"Thunderbolt Device";
|
||||
|
||||
NSString *vendor = dict[@"Vendor Name"] ?: @"";
|
||||
uint32_t vendorID = [dict[@"Vendor ID"] unsignedIntValue];
|
||||
uint32_t productID = [dict[@"Device ID"] unsignedIntValue];
|
||||
|
||||
MMPeripheralDevice *dev = [[MMPeripheralDevice alloc] init];
|
||||
dev.name = name;
|
||||
dev.busType = MMPeripheralBusTypeThunderbolt;
|
||||
dev.vendorName = vendor;
|
||||
dev.vendorID = vendorID;
|
||||
dev.productID = productID;
|
||||
dev.isBuiltIn = NO;
|
||||
|
||||
[devices addObject:dev];
|
||||
CFRelease(props);
|
||||
}
|
||||
IOObjectRelease(service);
|
||||
}
|
||||
IOObjectRelease(iterator);
|
||||
return devices;
|
||||
}
|
||||
|
||||
static uint32_t ParseDataUInt32(NSData *data) {
|
||||
if (![data isKindOfClass:[NSData class]] || data.length == 0) return 0;
|
||||
uint32_t val = 0;
|
||||
size_t copyLen = MIN(sizeof(val), data.length);
|
||||
memcpy(&val, data.bytes, copyLen);
|
||||
return val;
|
||||
}
|
||||
|
||||
+ (NSArray<MMPeripheralDevice *> *)samplePCIDevices {
|
||||
NSMutableArray<MMPeripheralDevice *> *devices = [NSMutableArray array];
|
||||
|
||||
CFMutableDictionaryRef matching = IOServiceMatching("IOPCIDevice");
|
||||
if (!matching) return devices;
|
||||
|
||||
io_iterator_t iterator = IO_OBJECT_NULL;
|
||||
kern_return_t kr = IOServiceGetMatchingServices(kIOMainPortDefault, matching, &iterator);
|
||||
if (kr != KERN_SUCCESS || iterator == IO_OBJECT_NULL) return devices;
|
||||
|
||||
io_service_t service = IO_OBJECT_NULL;
|
||||
while ((service = IOIteratorNext(iterator)) != IO_OBJECT_NULL) {
|
||||
CFMutableDictionaryRef props = NULL;
|
||||
if (IORegistryEntryCreateCFProperties(service, &props, kCFAllocatorDefault, 0) == KERN_SUCCESS && props) {
|
||||
NSDictionary *dict = (__bridge NSDictionary *)props;
|
||||
|
||||
NSString *name = nil;
|
||||
if ([dict[@"model"] isKindOfClass:[NSData class]]) {
|
||||
name = [[NSString alloc] initWithData:dict[@"model"] encoding:NSUTF8StringEncoding];
|
||||
name = [name stringByTrimmingCharactersInSet:[NSCharacterSet controlCharacterSet]];
|
||||
}
|
||||
if (!name || name.length == 0) {
|
||||
name = dict[@"IOName"];
|
||||
}
|
||||
if (!name || name.length == 0) {
|
||||
name = @"PCI Device";
|
||||
}
|
||||
|
||||
uint32_t vendorID = 0;
|
||||
if ([dict[@"vendor-id"] isKindOfClass:[NSData class]]) {
|
||||
vendorID = ParseDataUInt32(dict[@"vendor-id"]);
|
||||
}
|
||||
|
||||
uint32_t deviceID = 0;
|
||||
if ([dict[@"device-id"] isKindOfClass:[NSData class]]) {
|
||||
deviceID = ParseDataUInt32(dict[@"device-id"]);
|
||||
}
|
||||
|
||||
MMPeripheralDevice *dev = [[MMPeripheralDevice alloc] init];
|
||||
dev.name = name;
|
||||
dev.busType = MMPeripheralBusTypePCI;
|
||||
dev.vendorID = vendorID;
|
||||
dev.productID = deviceID;
|
||||
dev.isBuiltIn = YES;
|
||||
|
||||
[devices addObject:dev];
|
||||
CFRelease(props);
|
||||
}
|
||||
IOObjectRelease(service);
|
||||
}
|
||||
IOObjectRelease(iterator);
|
||||
return devices;
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
|
||||
NSArray<MMPeripheralDevice *> *usb = [MMPeripheralsProvider sampleUSBDevices];
|
||||
NSArray<MMPeripheralDevice *> *tb = [MMPeripheralsProvider sampleThunderboltDevices];
|
||||
NSArray<MMPeripheralDevice *> *pci = [MMPeripheralsProvider samplePCIDevices];
|
||||
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *usbList = [NSMutableArray arrayWithCapacity:usb.count];
|
||||
for (MMPeripheralDevice *d in usb) {
|
||||
[usbList addObject:[d toDictionary]];
|
||||
}
|
||||
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *tbList = [NSMutableArray arrayWithCapacity:tb.count];
|
||||
for (MMPeripheralDevice *d in tb) {
|
||||
[tbList addObject:[d toDictionary]];
|
||||
}
|
||||
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *pciList = [NSMutableArray arrayWithCapacity:pci.count];
|
||||
for (MMPeripheralDevice *d in pci) {
|
||||
[pciList addObject:[d toDictionary]];
|
||||
}
|
||||
|
||||
NSUInteger totalCount = usb.count + tb.count + pci.count;
|
||||
|
||||
return @{
|
||||
@"totalDeviceCount": @(totalCount),
|
||||
@"usbDevices": usbList,
|
||||
@"thunderboltDevices": tbList,
|
||||
@"pciDevices": pciList
|
||||
};
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,23 @@
|
||||
//
|
||||
// MMBatteryTelemetryProvider.h
|
||||
// MacMonitor
|
||||
//
|
||||
// Telemetry provider for AppleSmartBattery health, cycle count, capacity, and adapter info.
|
||||
//
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MMTelemetryProvider.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
@interface MMBatteryTelemetryProvider : NSObject <MMTelemetryProvider>
|
||||
|
||||
@property (nonatomic, readonly) BOOL hasBattery;
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
+ (NSDictionary<NSString *, id> *)calculateBatteryHealthWithProperties:(nullable NSDictionary<NSString *, id> *)rawProps;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,179 @@
|
||||
//
|
||||
// MMBatteryTelemetryProvider.m
|
||||
// MacMonitor
|
||||
//
|
||||
// Telemetry provider for AppleSmartBattery health, cycle count, capacity, and adapter info.
|
||||
//
|
||||
|
||||
#import "MMBatteryTelemetryProvider.h"
|
||||
#import <IOKit/IOKitLib.h>
|
||||
#import <IOKit/ps/IOPowerSources.h>
|
||||
#import <IOKit/ps/IOPSKeys.h>
|
||||
|
||||
@implementation MMBatteryTelemetryProvider
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
return self;
|
||||
}
|
||||
|
||||
- (MMTelemetryDomain)domain {
|
||||
return MMTelemetryDomainPower;
|
||||
}
|
||||
|
||||
- (NSString *)providerIdentifier {
|
||||
return @"com.i3omb.macmonitor.telemetry.battery";
|
||||
}
|
||||
|
||||
- (BOOL)isAvailable {
|
||||
io_service_t service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery"));
|
||||
if (service != IO_OBJECT_NULL) {
|
||||
IOObjectRelease(service);
|
||||
return YES;
|
||||
}
|
||||
return NO;
|
||||
}
|
||||
|
||||
- (BOOL)hasBattery {
|
||||
return [self isAvailable];
|
||||
}
|
||||
|
||||
+ (NSDictionary<NSString *, id> *)calculateBatteryHealthWithProperties:(nullable NSDictionary<NSString *, id> *)rawProps {
|
||||
if (!rawProps || rawProps.count == 0) {
|
||||
return @{
|
||||
@"hasBattery": @(NO),
|
||||
@"installed": @(NO),
|
||||
@"healthCondition": @"No Battery",
|
||||
@"healthPercent": @(0.0),
|
||||
@"cycleCount": @(0),
|
||||
@"designCycleCount": @(0),
|
||||
@"currentCapacity": @(0),
|
||||
@"maxCapacity": @(0),
|
||||
@"designCapacity": @(0),
|
||||
@"temperature": @(0.0),
|
||||
@"voltage": @(0.0),
|
||||
@"amperage": @(0.0),
|
||||
@"watts": @(0.0),
|
||||
@"isCharging": @(NO),
|
||||
@"isCharged": @(NO),
|
||||
@"externalConnected": @(NO),
|
||||
@"timeRemainingMinutes": @(-1),
|
||||
@"manufacturer": @"N/A",
|
||||
@"serial": @"N/A",
|
||||
@"deviceName": @"N/A"
|
||||
};
|
||||
}
|
||||
|
||||
BOOL installed = [rawProps[@"BatteryInstalled"] boolValue];
|
||||
NSInteger cycleCount = [rawProps[@"CycleCount"] integerValue];
|
||||
NSInteger designCycleCount = rawProps[@"DesignCycleCount9C"] ? [rawProps[@"DesignCycleCount9C"] integerValue] : 1000;
|
||||
|
||||
NSInteger currentCapacity = [rawProps[@"CurrentCapacity"] integerValue];
|
||||
NSInteger maxCapacity = [rawProps[@"MaxCapacity"] integerValue];
|
||||
|
||||
// DesignCapacity might be at top level or inside BatteryData
|
||||
NSInteger designCapacity = [rawProps[@"DesignCapacity"] integerValue];
|
||||
if (designCapacity <= 0 && [rawProps[@"BatteryData"] isKindOfClass:[NSDictionary class]]) {
|
||||
designCapacity = [rawProps[@"BatteryData"][@"DesignCapacity"] integerValue];
|
||||
}
|
||||
|
||||
// Health percentage = (MaxCapacity / DesignCapacity) * 100.0
|
||||
double healthPercent = 0.0;
|
||||
if (designCapacity > 0) {
|
||||
healthPercent = ((double)maxCapacity / (double)designCapacity) * 100.0;
|
||||
if (healthPercent > 100.0) healthPercent = 100.0;
|
||||
} else if (maxCapacity > 0) {
|
||||
healthPercent = 100.0;
|
||||
}
|
||||
|
||||
// Health condition evaluation
|
||||
NSString *condition = @"Normal";
|
||||
BOOL permanentFailure = [rawProps[@"PermanentFailureStatus"] integerValue] != 0;
|
||||
if (permanentFailure) {
|
||||
condition = @"Permanent Failure";
|
||||
} else if (healthPercent < 70.0 || (designCycleCount > 0 && cycleCount > designCycleCount)) {
|
||||
condition = @"Service Recommended";
|
||||
} else if (healthPercent < 80.0) {
|
||||
condition = @"Fair";
|
||||
} else {
|
||||
condition = @"Normal";
|
||||
}
|
||||
|
||||
// Temperature: AppleSmartBattery returns in units of 0.01 deg C or 0.1 deg C (e.g. 3151 = 31.51 deg C)
|
||||
double rawTemp = [rawProps[@"Temperature"] doubleValue];
|
||||
double tempC = rawTemp > 1000.0 ? (rawTemp / 100.0) : (rawTemp > 100.0 ? rawTemp / 10.0 : rawTemp);
|
||||
|
||||
double voltage = [rawProps[@"Voltage"] doubleValue] / 1000.0; // mV -> V
|
||||
|
||||
// Amperage can be signed 64-bit stored as unsigned in dict
|
||||
int64_t rawAmp = [rawProps[@"InstantAmperage"] longLongValue];
|
||||
if (rawAmp == 0) {
|
||||
rawAmp = [rawProps[@"Amperage"] longLongValue];
|
||||
}
|
||||
int32_t signedAmp = (int32_t)rawAmp; // standard cast from uint32/uint64 representation
|
||||
double amperage = ((double)signedAmp) / 1000.0; // mA -> A
|
||||
double watts = fabs(voltage * amperage);
|
||||
|
||||
BOOL isCharging = [rawProps[@"IsCharging"] boolValue];
|
||||
BOOL fullyCharged = [rawProps[@"FullyCharged"] boolValue];
|
||||
BOOL externalConnected = [rawProps[@"ExternalConnected"] boolValue];
|
||||
NSInteger timeRemaining = [rawProps[@"TimeRemaining"] integerValue];
|
||||
if (timeRemaining == 65535) {
|
||||
timeRemaining = -1;
|
||||
}
|
||||
|
||||
NSString *manufacturer = rawProps[@"Manufacturer"] ?: @"Apple";
|
||||
NSString *serial = rawProps[@"Serial"] ?: @"";
|
||||
NSString *deviceName = rawProps[@"DeviceName"] ?: @"";
|
||||
|
||||
// Power adapter details
|
||||
NSDictionary *adapterDetails = [rawProps[@"AdapterDetails"] isKindOfClass:[NSDictionary class]] ? rawProps[@"AdapterDetails"] : nil;
|
||||
NSInteger adapterWatts = 0;
|
||||
if (adapterDetails && adapterDetails[@"Watts"]) {
|
||||
adapterWatts = [adapterDetails[@"Watts"] integerValue];
|
||||
}
|
||||
|
||||
return @{
|
||||
@"hasBattery": @(YES),
|
||||
@"installed": @(installed),
|
||||
@"healthCondition": condition,
|
||||
@"healthPercent": @(round(healthPercent * 10.0) / 10.0),
|
||||
@"cycleCount": @(cycleCount),
|
||||
@"designCycleCount": @(designCycleCount),
|
||||
@"currentCapacity": @(currentCapacity),
|
||||
@"maxCapacity": @(maxCapacity),
|
||||
@"designCapacity": @(designCapacity),
|
||||
@"temperature": @(round(tempC * 10.0) / 10.0),
|
||||
@"voltage": @(round(voltage * 100.0) / 100.0),
|
||||
@"amperage": @(round(amperage * 100.0) / 100.0),
|
||||
@"watts": @(round(watts * 10.0) / 10.0),
|
||||
@"isCharging": @(isCharging),
|
||||
@"isCharged": @(fullyCharged),
|
||||
@"externalConnected": @(externalConnected),
|
||||
@"timeRemainingMinutes": @(timeRemaining),
|
||||
@"manufacturer": manufacturer,
|
||||
@"serial": serial,
|
||||
@"deviceName": deviceName,
|
||||
@"adapterWatts": @(adapterWatts)
|
||||
};
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
|
||||
io_service_t service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery"));
|
||||
if (service == IO_OBJECT_NULL) {
|
||||
return [MMBatteryTelemetryProvider calculateBatteryHealthWithProperties:nil];
|
||||
}
|
||||
|
||||
CFMutableDictionaryRef props = NULL;
|
||||
kern_return_t kr = IORegistryEntryCreateCFProperties(service, &props, kCFAllocatorDefault, 0);
|
||||
IOObjectRelease(service);
|
||||
|
||||
if (kr != KERN_SUCCESS || !props) {
|
||||
return [MMBatteryTelemetryProvider calculateBatteryHealthWithProperties:nil];
|
||||
}
|
||||
|
||||
NSDictionary *dict = (__bridge_transfer NSDictionary *)props;
|
||||
return [MMBatteryTelemetryProvider calculateBatteryHealthWithProperties:dict];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,45 @@
|
||||
#ifndef MMPowerTelemetryProvider_h
|
||||
#define MMPowerTelemetryProvider_h
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MMTelemetryProvider.h"
|
||||
#import "MMAppleSMCClient.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* MMPowerTelemetryProvider
|
||||
* Samples system power draw, CPU/GPU package wattage, rail voltages, and currents
|
||||
* via AppleSMC and AppleSmartBattery IOKit interfaces.
|
||||
*/
|
||||
@interface MMPowerTelemetryProvider : NSObject <MMTelemetryProvider>
|
||||
|
||||
@property (nonatomic, strong, readonly) MMAppleSMCClient *smcClient;
|
||||
@property (nonatomic, readonly) NSArray<NSString *> *discoveredPowerKeys;
|
||||
@property (nonatomic, readonly) NSArray<NSString *> *discoveredVoltageKeys;
|
||||
@property (nonatomic, readonly) NSArray<NSString *> *discoveredCurrentKeys;
|
||||
|
||||
- (instancetype)init;
|
||||
- (instancetype)initWithSMCClient:(MMAppleSMCClient *)client;
|
||||
|
||||
/**
|
||||
* Friendly name for power, voltage, and current SMC keys.
|
||||
*/
|
||||
+ (NSString *)humanReadableNameForKey:(NSString *)key;
|
||||
|
||||
/**
|
||||
* Unit of measurement for SMC key ("W", "V", "A").
|
||||
*/
|
||||
+ (NSString *)unitForKey:(NSString *)key;
|
||||
|
||||
/**
|
||||
* Pure calculator method for deterministic unit testing.
|
||||
*/
|
||||
+ (NSDictionary<NSString *, id> *)calculatePowerMetricsWithReadings:(NSDictionary<NSString *, NSNumber *> *)readings
|
||||
batteryInfo:(nullable NSDictionary<NSString *, id> *)batteryInfo;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif /* MMPowerTelemetryProvider_h */
|
||||
@@ -0,0 +1,314 @@
|
||||
#import "MMPowerTelemetryProvider.h"
|
||||
#import <IOKit/IOKitLib.h>
|
||||
#import <IOKit/ps/IOPowerSources.h>
|
||||
#import <IOKit/ps/IOPSKeys.h>
|
||||
|
||||
@interface MMPowerTelemetryProvider () {
|
||||
MMAppleSMCClient *_smcClient;
|
||||
NSMutableArray<NSString *> *_discoveredPowerKeys;
|
||||
NSMutableArray<NSString *> *_discoveredVoltageKeys;
|
||||
NSMutableArray<NSString *> *_discoveredCurrentKeys;
|
||||
BOOL _probed;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation MMPowerTelemetryProvider
|
||||
|
||||
- (instancetype)init {
|
||||
return [self initWithSMCClient:[MMAppleSMCClient sharedClient]];
|
||||
}
|
||||
|
||||
- (instancetype)initWithSMCClient:(MMAppleSMCClient *)client {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_smcClient = client;
|
||||
_discoveredPowerKeys = [NSMutableArray array];
|
||||
_discoveredVoltageKeys = [NSMutableArray array];
|
||||
_discoveredCurrentKeys = [NSMutableArray array];
|
||||
[self probeSensors];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)probeSensors {
|
||||
if (!_smcClient.isAvailable) return;
|
||||
|
||||
NSArray<NSString *> *powerCandidates = @[
|
||||
@"PSTR", @"PDTR", @"PCPR", @"PCTR", @"PC0C", @"PCPT",
|
||||
@"PG0R", @"PGTR", @"PMSR", @"PM0R", @"PCPC"
|
||||
];
|
||||
|
||||
NSArray<NSString *> *voltageCandidates = @[
|
||||
@"VC0C", @"VD0R", @"VN0C", @"VM0R", @"VP0R"
|
||||
];
|
||||
|
||||
NSArray<NSString *> *currentCandidates = @[
|
||||
@"IC0C", @"ID0R", @"IG0C", @"IM0R"
|
||||
];
|
||||
|
||||
[_discoveredPowerKeys removeAllObjects];
|
||||
for (NSString *key in powerCandidates) {
|
||||
NSNumber *val = [_smcClient readNumericValueForKey:key error:nil];
|
||||
if (val && [val doubleValue] > 0.0 && [val doubleValue] < 5000.0) {
|
||||
[_discoveredPowerKeys addObject:key];
|
||||
}
|
||||
}
|
||||
|
||||
[_discoveredVoltageKeys removeAllObjects];
|
||||
for (NSString *key in voltageCandidates) {
|
||||
NSNumber *val = [_smcClient readNumericValueForKey:key error:nil];
|
||||
if (val && [val doubleValue] > 0.0) {
|
||||
[_discoveredVoltageKeys addObject:key];
|
||||
}
|
||||
}
|
||||
|
||||
[_discoveredCurrentKeys removeAllObjects];
|
||||
for (NSString *key in currentCandidates) {
|
||||
NSNumber *val = [_smcClient readNumericValueForKey:key error:nil];
|
||||
if (val && [val doubleValue] > 0.0) {
|
||||
[_discoveredCurrentKeys addObject:key];
|
||||
}
|
||||
}
|
||||
|
||||
_probed = YES;
|
||||
}
|
||||
|
||||
- (MMTelemetryDomain)domain {
|
||||
return MMTelemetryDomainPower;
|
||||
}
|
||||
|
||||
- (NSString *)providerIdentifier {
|
||||
return @"com.i3omb.macmonitor.telemetry.power";
|
||||
}
|
||||
|
||||
- (BOOL)isAvailable {
|
||||
return _smcClient.isAvailable;
|
||||
}
|
||||
|
||||
- (MMAppleSMCClient *)smcClient {
|
||||
return _smcClient;
|
||||
}
|
||||
|
||||
- (NSArray<NSString *> *)discoveredPowerKeys {
|
||||
return [_discoveredPowerKeys copy];
|
||||
}
|
||||
|
||||
- (NSArray<NSString *> *)discoveredVoltageKeys {
|
||||
return [_discoveredVoltageKeys copy];
|
||||
}
|
||||
|
||||
- (NSArray<NSString *> *)discoveredCurrentKeys {
|
||||
return [_discoveredCurrentKeys copy];
|
||||
}
|
||||
|
||||
+ (NSString *)unitForKey:(NSString *)key {
|
||||
if ([key hasPrefix:@"P"]) return @"W";
|
||||
if ([key hasPrefix:@"V"]) return @"V";
|
||||
if ([key hasPrefix:@"I"]) return @"A";
|
||||
return @"";
|
||||
}
|
||||
|
||||
+ (NSString *)humanReadableNameForKey:(NSString *)key {
|
||||
static NSDictionary<NSString *, NSString *> *names = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
names = @{
|
||||
@"PSTR": @"Total System Power",
|
||||
@"PDTR": @"DC-In Total Power",
|
||||
@"PCPR": @"CPU Package Power",
|
||||
@"PCTR": @"CPU Total Power",
|
||||
@"PC0C": @"CPU Core Power",
|
||||
@"PCPT": @"CPU Package Total Power",
|
||||
@"PG0R": @"GPU 0 Power",
|
||||
@"PGTR": @"GPU Total Power",
|
||||
@"PMSR": @"Memory Subsystem Power",
|
||||
@"PM0R": @"Memory Rail Power",
|
||||
@"PCPC": @"Power Supply In / AC",
|
||||
@"VC0C": @"CPU Core Voltage",
|
||||
@"VD0R": @"DC-In Rail Voltage",
|
||||
@"VN0C": @"PCH Rail Voltage",
|
||||
@"VM0R": @"Memory Rail Voltage",
|
||||
@"VP0R": @"Power Supply Voltage",
|
||||
@"IC0C": @"CPU Core Current",
|
||||
@"ID0R": @"DC-In Rail Current",
|
||||
@"IG0C": @"GPU Rail Current",
|
||||
@"IM0R": @"Memory Rail Current"
|
||||
};
|
||||
});
|
||||
|
||||
NSString *match = names[key];
|
||||
return match ?: key;
|
||||
}
|
||||
|
||||
+ (NSDictionary<NSString *, id> *)calculatePowerMetricsWithReadings:(NSDictionary<NSString *, NSNumber *> *)readings
|
||||
batteryInfo:(nullable NSDictionary<NSString *, id> *)batteryInfo {
|
||||
// Determine system total power
|
||||
double systemTotal = 0.0;
|
||||
if (readings[@"PSTR"]) {
|
||||
systemTotal = [readings[@"PSTR"] doubleValue];
|
||||
} else if (readings[@"PDTR"]) {
|
||||
systemTotal = [readings[@"PDTR"] doubleValue];
|
||||
} else if (batteryInfo[@"batteryWatts"]) {
|
||||
systemTotal = [batteryInfo[@"batteryWatts"] doubleValue];
|
||||
}
|
||||
|
||||
// CPU wattage
|
||||
double cpuWatts = 0.0;
|
||||
if (readings[@"PCPR"]) {
|
||||
cpuWatts = [readings[@"PCPR"] doubleValue];
|
||||
} else if (readings[@"PCTR"]) {
|
||||
cpuWatts = [readings[@"PCTR"] doubleValue];
|
||||
} else if (readings[@"PC0C"]) {
|
||||
cpuWatts = [readings[@"PC0C"] doubleValue];
|
||||
} else if (readings[@"PCPT"]) {
|
||||
cpuWatts = [readings[@"PCPT"] doubleValue];
|
||||
}
|
||||
|
||||
// Voltage & Current
|
||||
double cpuVoltage = readings[@"VC0C"] ? [readings[@"VC0C"] doubleValue] : 0.0;
|
||||
double cpuCurrent = readings[@"IC0C"] ? [readings[@"IC0C"] doubleValue] : 0.0;
|
||||
|
||||
// Fallback: calculate cpuWatts from V * I if SMC didn't provide direct wattage
|
||||
if (cpuWatts == 0.0 && cpuVoltage > 0.0 && cpuCurrent > 0.0) {
|
||||
cpuWatts = cpuVoltage * cpuCurrent;
|
||||
}
|
||||
|
||||
// GPU wattage
|
||||
double gpuWatts = 0.0;
|
||||
if (readings[@"PG0R"]) {
|
||||
gpuWatts = [readings[@"PG0R"] doubleValue];
|
||||
} else if (readings[@"PGTR"]) {
|
||||
gpuWatts = [readings[@"PGTR"] doubleValue];
|
||||
}
|
||||
|
||||
// Memory wattage
|
||||
double memoryWatts = 0.0;
|
||||
if (readings[@"PMSR"]) {
|
||||
memoryWatts = [readings[@"PMSR"] doubleValue];
|
||||
} else if (readings[@"PM0R"]) {
|
||||
memoryWatts = [readings[@"PM0R"] doubleValue];
|
||||
}
|
||||
|
||||
// Collect all individual sensor entries
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *sensors = [NSMutableArray arrayWithCapacity:readings.count];
|
||||
NSArray<NSString *> *sortedKeys = [readings.allKeys sortedArrayUsingSelector:@selector(compare:)];
|
||||
for (NSString *k in sortedKeys) {
|
||||
double val = [readings[k] doubleValue];
|
||||
[sensors addObject:@{
|
||||
@"key": k,
|
||||
@"name": [self humanReadableNameForKey:k],
|
||||
@"value": @(val),
|
||||
@"unit": [self unitForKey:k]
|
||||
}];
|
||||
}
|
||||
|
||||
NSString *powerSource = batteryInfo[@"powerSource"] ?: @"AC Power";
|
||||
BOOL isCharging = [batteryInfo[@"isCharging"] boolValue];
|
||||
double batteryLevel = [batteryInfo[@"batteryLevel"] doubleValue];
|
||||
|
||||
return @{
|
||||
@"systemTotalWatts": @(systemTotal),
|
||||
@"cpuWatts": @(cpuWatts),
|
||||
@"gpuWatts": @(gpuWatts),
|
||||
@"memoryWatts": @(memoryWatts),
|
||||
@"cpuVoltage": @(cpuVoltage),
|
||||
@"cpuCurrent": @(cpuCurrent),
|
||||
@"powerSource": powerSource,
|
||||
@"isCharging": @(isCharging),
|
||||
@"batteryLevel": @(batteryLevel),
|
||||
@"sensors": sensors
|
||||
};
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleBatteryInfo {
|
||||
CFTypeRef psInfo = IOPSCopyPowerSourcesInfo();
|
||||
if (!psInfo) return nil;
|
||||
|
||||
CFArrayRef psList = IOPSCopyPowerSourcesList(psInfo);
|
||||
if (!psList) {
|
||||
CFRelease(psInfo);
|
||||
return nil;
|
||||
}
|
||||
|
||||
NSString *stateStr = @"AC Power";
|
||||
BOOL isCharging = NO;
|
||||
double capacity = 100.0;
|
||||
|
||||
if (CFArrayGetCount(psList) > 0) {
|
||||
CFTypeRef ps = CFArrayGetValueAtIndex(psList, 0);
|
||||
CFDictionaryRef desc = IOPSGetPowerSourceDescription(psInfo, ps);
|
||||
if (desc) {
|
||||
NSDictionary *dict = (__bridge NSDictionary *)desc;
|
||||
stateStr = dict[@"Power Source State"] ?: @"AC Power";
|
||||
isCharging = [dict[@"Is Charging"] boolValue];
|
||||
if (dict[@"Current Capacity"]) {
|
||||
capacity = [dict[@"Current Capacity"] doubleValue];
|
||||
}
|
||||
}
|
||||
}
|
||||
CFRelease(psList);
|
||||
CFRelease(psInfo);
|
||||
|
||||
// Sample AppleSmartBattery for instantaneous voltage and current
|
||||
double batteryWatts = 0.0;
|
||||
double batteryVoltage = 0.0;
|
||||
double batteryAmperage = 0.0;
|
||||
|
||||
io_service_t service = IOServiceGetMatchingService(kIOMainPortDefault, IOServiceMatching("AppleSmartBattery"));
|
||||
if (service != IO_OBJECT_NULL) {
|
||||
CFMutableDictionaryRef props = NULL;
|
||||
if (IORegistryEntryCreateCFProperties(service, &props, kCFAllocatorDefault, 0) == KERN_SUCCESS && props) {
|
||||
NSDictionary *dict = (__bridge NSDictionary *)props;
|
||||
double v_mV = [dict[@"Voltage"] doubleValue];
|
||||
double a_mA = dict[@"InstantAmperage"] ? [dict[@"InstantAmperage"] doubleValue] : [dict[@"Amperage"] doubleValue];
|
||||
|
||||
batteryVoltage = v_mV / 1000.0;
|
||||
batteryAmperage = fabs(a_mA) / 1000.0;
|
||||
batteryWatts = batteryVoltage * batteryAmperage;
|
||||
|
||||
CFRelease(props);
|
||||
}
|
||||
IOObjectRelease(service);
|
||||
}
|
||||
|
||||
return @{
|
||||
@"powerSource": stateStr,
|
||||
@"isCharging": @(isCharging),
|
||||
@"batteryLevel": @(capacity),
|
||||
@"batteryVoltage": @(batteryVoltage),
|
||||
@"batteryAmperage": @(batteryAmperage),
|
||||
@"batteryWatts": @(batteryWatts)
|
||||
};
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
|
||||
if (!_probed && _smcClient.isAvailable) {
|
||||
[self probeSensors];
|
||||
}
|
||||
|
||||
NSMutableDictionary<NSString *, NSNumber *> *readings = [NSMutableDictionary dictionary];
|
||||
|
||||
NSMutableArray<NSString *> *allKeys = [NSMutableArray arrayWithArray:_discoveredPowerKeys];
|
||||
[allKeys addObjectsFromArray:_discoveredVoltageKeys];
|
||||
[allKeys addObjectsFromArray:_discoveredCurrentKeys];
|
||||
|
||||
for (NSString *key in allKeys) {
|
||||
NSNumber *val = [_smcClient readNumericValueForKey:key error:nil];
|
||||
if (val) {
|
||||
double v = [val doubleValue];
|
||||
// Normalize mV or mA if values appear raw
|
||||
if ([key hasPrefix:@"V"] && v > 100.0) {
|
||||
v /= 1000.0;
|
||||
} else if ([key hasPrefix:@"I"] && v > 500.0) {
|
||||
v /= 1000.0;
|
||||
}
|
||||
readings[key] = @(v);
|
||||
}
|
||||
}
|
||||
|
||||
NSDictionary<NSString *, id> *batteryInfo = [self sampleBatteryInfo];
|
||||
return [MMPowerTelemetryProvider calculatePowerMetricsWithReadings:readings
|
||||
batteryInfo:batteryInfo];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,32 @@
|
||||
#ifndef MMProcessDetailInspector_h
|
||||
#define MMProcessDetailInspector_h
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* MMProcessDetailInspector
|
||||
* Provides deep per-process inspection: open file descriptors, vnode file paths,
|
||||
* active network sockets, and thread states.
|
||||
*/
|
||||
@interface MMProcessDetailInspector : NSObject
|
||||
|
||||
/**
|
||||
* Inspects a running process by PID.
|
||||
*/
|
||||
+ (nullable NSDictionary<NSString *, id> *)inspectProcessWithPID:(pid_t)pid;
|
||||
|
||||
/**
|
||||
* Pure summarizer method for deterministic unit testing.
|
||||
*/
|
||||
+ (NSDictionary<NSString *, id> *)summarizeInspectionResultsWithPID:(pid_t)pid
|
||||
threads:(NSArray<NSDictionary<NSString *, id> *> *)threads
|
||||
fds:(NSArray<NSDictionary<NSString *, id> *> *)fds
|
||||
sockets:(NSArray<NSDictionary<NSString *, id> *> *)sockets;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif /* MMProcessDetailInspector_h */
|
||||
@@ -0,0 +1,176 @@
|
||||
#import "MMProcessDetailInspector.h"
|
||||
#import <libproc.h>
|
||||
#import <sys/proc_info.h>
|
||||
#import <arpa/inet.h>
|
||||
|
||||
@implementation MMProcessDetailInspector
|
||||
|
||||
+ (NSDictionary<NSString *, id> *)summarizeInspectionResultsWithPID:(pid_t)pid
|
||||
threads:(NSArray<NSDictionary<NSString *, id> *> *)threads
|
||||
fds:(NSArray<NSDictionary<NSString *, id> *> *)fds
|
||||
sockets:(NSArray<NSDictionary<NSString *, id> *> *)sockets {
|
||||
return @{
|
||||
@"pid": @(pid),
|
||||
@"threadCount": @(threads.count),
|
||||
@"openFDCount": @(fds.count),
|
||||
@"socketCount": @(sockets.count),
|
||||
@"threads": threads,
|
||||
@"fileDescriptors": fds,
|
||||
@"sockets": sockets
|
||||
};
|
||||
}
|
||||
|
||||
static NSString *runStateString(int state) {
|
||||
switch (state) {
|
||||
case 1: return @"Running";
|
||||
case 2: return @"Stopped";
|
||||
case 3: return @"Waiting";
|
||||
case 4: return @"Uninterruptible";
|
||||
case 5: return @"Halted";
|
||||
default: return @"Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
static NSString *tcpStateString(int state) {
|
||||
switch (state) {
|
||||
case 0: return @"CLOSED";
|
||||
case 1: return @"LISTEN";
|
||||
case 2: return @"SYN_SENT";
|
||||
case 3: return @"SYN_RCVD";
|
||||
case 4: return @"ESTABLISHED";
|
||||
case 5: return @"CLOSE_WAIT";
|
||||
case 6: return @"FIN_WAIT_1";
|
||||
case 7: return @"CLOSING";
|
||||
case 8: return @"LAST_ACK";
|
||||
case 9: return @"FIN_WAIT_2";
|
||||
case 10: return @"TIME_WAIT";
|
||||
default: return @"UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
+ (nullable NSDictionary<NSString *, id> *)inspectProcessWithPID:(pid_t)pid {
|
||||
if (pid <= 0) return nil;
|
||||
|
||||
// 1. Enumerate threads
|
||||
uint64_t threadIds[512];
|
||||
int threadBytes = proc_pidinfo(pid, PROC_PIDLISTTHREADS, 0, threadIds, sizeof(threadIds));
|
||||
int threadCount = threadBytes / sizeof(uint64_t);
|
||||
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *threads = [NSMutableArray arrayWithCapacity:threadCount];
|
||||
for (int t = 0; t < threadCount; t++) {
|
||||
uint64_t tid = threadIds[t];
|
||||
struct proc_threadinfo thi;
|
||||
if (proc_pidinfo(pid, PROC_PIDTHREADINFO, tid, &thi, sizeof(thi)) == sizeof(thi)) {
|
||||
[threads addObject:@{
|
||||
@"threadId": @(tid),
|
||||
@"userTimeNs": @(thi.pth_user_time),
|
||||
@"systemTimeNs": @(thi.pth_system_time),
|
||||
@"cpuPercent": @(thi.pth_cpu_usage),
|
||||
@"state": runStateString(thi.pth_run_state),
|
||||
@"priority": @(thi.pth_priority),
|
||||
@"currentPriority": @(thi.pth_curpri)
|
||||
}];
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Enumerate File Descriptors & Sockets
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *fdsList = [NSMutableArray array];
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *socketsList = [NSMutableArray array];
|
||||
|
||||
int sz = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, NULL, 0);
|
||||
if (sz > 0) {
|
||||
struct proc_fdinfo *fds = malloc(sz);
|
||||
if (fds) {
|
||||
int actual = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, fds, sz);
|
||||
int fdCount = actual / sizeof(struct proc_fdinfo);
|
||||
|
||||
for (int j = 0; j < fdCount; j++) {
|
||||
int fd = fds[j].proc_fd;
|
||||
uint32_t fdType = fds[j].proc_fdtype;
|
||||
|
||||
if (fdType == PROX_FDTYPE_VNODE) {
|
||||
struct vnode_fdinfowithpath vi;
|
||||
if (proc_pidfdinfo(pid, fd, PROC_PIDFDVNODEPATHINFO, &vi, sizeof(vi)) == sizeof(vi)) {
|
||||
NSString *path = [NSString stringWithUTF8String:vi.pvip.vip_path];
|
||||
[fdsList addObject:@{
|
||||
@"fd": @(fd),
|
||||
@"type": @"File",
|
||||
@"path": path ?: @"(unknown)"
|
||||
}];
|
||||
}
|
||||
} else if (fdType == PROX_FDTYPE_SOCKET) {
|
||||
struct socket_fdinfo si;
|
||||
if (proc_pidfdinfo(pid, fd, PROC_PIDFDSOCKETINFO, &si, sizeof(si)) == sizeof(si)) {
|
||||
int family = si.psi.soi_family;
|
||||
if (family == AF_INET || family == AF_INET6) {
|
||||
char localIP[INET6_ADDRSTRLEN] = {0};
|
||||
char remoteIP[INET6_ADDRSTRLEN] = {0};
|
||||
int lport = 0, rport = 0;
|
||||
NSString *proto = (si.psi.soi_type == SOCK_STREAM) ? @"TCP" : @"UDP";
|
||||
NSString *state = @"NONE";
|
||||
|
||||
if (family == AF_INET) {
|
||||
inet_ntop(AF_INET, &si.psi.soi_proto.pri_in.insi_laddr.ina_46.i46a_addr4, localIP, sizeof(localIP));
|
||||
inet_ntop(AF_INET, &si.psi.soi_proto.pri_in.insi_faddr.ina_46.i46a_addr4, remoteIP, sizeof(remoteIP));
|
||||
lport = ntohs(si.psi.soi_proto.pri_in.insi_lport);
|
||||
rport = ntohs(si.psi.soi_proto.pri_in.insi_fport);
|
||||
} else {
|
||||
inet_ntop(AF_INET6, &si.psi.soi_proto.pri_in.insi_laddr.ina_6, localIP, sizeof(localIP));
|
||||
inet_ntop(AF_INET6, &si.psi.soi_proto.pri_in.insi_faddr.ina_6, remoteIP, sizeof(remoteIP));
|
||||
lport = ntohs(si.psi.soi_proto.pri_in.insi_lport);
|
||||
rport = ntohs(si.psi.soi_proto.pri_in.insi_fport);
|
||||
}
|
||||
|
||||
if (si.psi.soi_type == SOCK_STREAM) {
|
||||
state = tcpStateString(si.psi.soi_proto.pri_tcp.tcpsi_state);
|
||||
}
|
||||
|
||||
NSDictionary<NSString *, id> *sockDict = @{
|
||||
@"fd": @(fd),
|
||||
@"protocol": proto,
|
||||
@"localAddress": [NSString stringWithUTF8String:localIP],
|
||||
@"localPort": @(lport),
|
||||
@"remoteAddress": [NSString stringWithUTF8String:remoteIP],
|
||||
@"remotePort": @(rport),
|
||||
@"state": state
|
||||
};
|
||||
|
||||
[socketsList addObject:sockDict];
|
||||
[fdsList addObject:@{
|
||||
@"fd": @(fd),
|
||||
@"type": @"Socket",
|
||||
@"path": [NSString stringWithFormat:@"%@ %@:%d -> %@:%d", proto, [NSString stringWithUTF8String:localIP], lport, [NSString stringWithUTF8String:remoteIP], rport]
|
||||
}];
|
||||
} else {
|
||||
[fdsList addObject:@{
|
||||
@"fd": @(fd),
|
||||
@"type": @"Socket (Unix/Other)",
|
||||
@"path": @"Unix Domain Socket"
|
||||
}];
|
||||
}
|
||||
}
|
||||
} else if (fdType == PROX_FDTYPE_PIPE) {
|
||||
[fdsList addObject:@{
|
||||
@"fd": @(fd),
|
||||
@"type": @"Pipe",
|
||||
@"path": @"FIFO/Pipe"
|
||||
}];
|
||||
} else {
|
||||
[fdsList addObject:@{
|
||||
@"fd": @(fd),
|
||||
@"type": @"Other",
|
||||
@"path": @""
|
||||
}];
|
||||
}
|
||||
}
|
||||
free(fds);
|
||||
}
|
||||
}
|
||||
|
||||
return [MMProcessDetailInspector summarizeInspectionResultsWithPID:pid
|
||||
threads:threads
|
||||
fds:fdsList
|
||||
sockets:socketsList];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,34 @@
|
||||
#ifndef MMProcessTelemetryProvider_h
|
||||
#define MMProcessTelemetryProvider_h
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MMTelemetryProvider.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* MMProcessTelemetryProvider
|
||||
* Live process explorer sampling CPU utilization, resident memory (RSS),
|
||||
* virtual memory, thread counts, and process hierarchy.
|
||||
*/
|
||||
@interface MMProcessTelemetryProvider : NSObject <MMTelemetryProvider>
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
* Safely terminates a process via SIGTERM or SIGKILL.
|
||||
*/
|
||||
+ (BOOL)terminateProcessWithPID:(pid_t)pid force:(BOOL)force;
|
||||
|
||||
/**
|
||||
* Pure calculator method for deterministic unit testing.
|
||||
*/
|
||||
+ (NSArray<NSDictionary<NSString *, id> *> *)calculateProcessListWithRawProcesses:(NSArray<NSDictionary<NSString *, id> *> *)rawProcesses
|
||||
previousCPUTimes:(nullable NSDictionary<NSNumber *, NSNumber *> *)previousCPUTimes
|
||||
timeDelta:(NSTimeInterval)timeDelta;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif /* MMProcessTelemetryProvider_h */
|
||||
@@ -0,0 +1,160 @@
|
||||
#import "MMProcessTelemetryProvider.h"
|
||||
#import <libproc.h>
|
||||
#import <sys/proc_info.h>
|
||||
#import <pwd.h>
|
||||
#import <signal.h>
|
||||
#import <mach/mach_time.h>
|
||||
#import <os/lock.h>
|
||||
|
||||
@interface MMProcessTelemetryProvider () {
|
||||
os_unfair_lock _lock;
|
||||
NSMutableDictionary<NSNumber *, NSNumber *> *_previousCPUTimes;
|
||||
uint64_t _previousTimestamp;
|
||||
mach_timebase_info_data_t _timebase;
|
||||
NSMutableDictionary<NSNumber *, NSString *> *_usernameCache;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation MMProcessTelemetryProvider
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_lock = OS_UNFAIR_LOCK_INIT;
|
||||
_previousCPUTimes = [NSMutableDictionary dictionary];
|
||||
_previousTimestamp = 0;
|
||||
_usernameCache = [NSMutableDictionary dictionary];
|
||||
mach_timebase_info(&_timebase);
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (MMTelemetryDomain)domain {
|
||||
return MMTelemetryDomainProcess;
|
||||
}
|
||||
|
||||
- (NSString *)providerIdentifier {
|
||||
return @"com.i3omb.macmonitor.telemetry.process";
|
||||
}
|
||||
|
||||
- (BOOL)isAvailable {
|
||||
return YES;
|
||||
}
|
||||
|
||||
+ (BOOL)terminateProcessWithPID:(pid_t)pid force:(BOOL)force {
|
||||
int sig = force ? SIGKILL : SIGTERM;
|
||||
return kill(pid, sig) == 0;
|
||||
}
|
||||
|
||||
+ (NSArray<NSDictionary<NSString *, id> *> *)calculateProcessListWithRawProcesses:(NSArray<NSDictionary<NSString *, id> *> *)rawProcesses
|
||||
previousCPUTimes:(nullable NSDictionary<NSNumber *, NSNumber *> *)previousCPUTimes
|
||||
timeDelta:(NSTimeInterval)timeDelta {
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *processed = [NSMutableArray arrayWithCapacity:rawProcesses.count];
|
||||
|
||||
for (NSDictionary<NSString *, id> *raw in rawProcesses) {
|
||||
NSNumber *pidNum = raw[@"pid"];
|
||||
uint64_t currCPUTime = [raw[@"cpuTimeNs"] unsignedLongLongValue];
|
||||
|
||||
double cpuPercent = 0.0;
|
||||
if (previousCPUTimes && previousCPUTimes[pidNum]) {
|
||||
uint64_t prevCPUTime = [previousCPUTimes[pidNum] unsignedLongLongValue];
|
||||
if (currCPUTime >= prevCPUTime && timeDelta > 0.001) {
|
||||
uint64_t deltaNs = currCPUTime - prevCPUTime;
|
||||
double deltaSec = (double)deltaNs / 1e9;
|
||||
cpuPercent = (deltaSec / timeDelta) * 100.0;
|
||||
}
|
||||
}
|
||||
|
||||
NSMutableDictionary<NSString *, id> *entry = [raw mutableCopy];
|
||||
entry[@"cpuPercent"] = @(cpuPercent);
|
||||
[processed addObject:entry];
|
||||
}
|
||||
|
||||
// Sort descending by cpuPercent
|
||||
[processed sortUsingComparator:^NSComparisonResult(NSDictionary<NSString *, id> *obj1, NSDictionary<NSString *, id> *obj2) {
|
||||
NSNumber *c1 = obj1[@"cpuPercent"];
|
||||
NSNumber *c2 = obj2[@"cpuPercent"];
|
||||
return [c2 compare:c1];
|
||||
}];
|
||||
|
||||
return processed;
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
|
||||
uint64_t now = mach_absolute_time();
|
||||
|
||||
int pids[4096];
|
||||
int bytes = proc_listpids(PROC_ALL_PIDS, 0, pids, sizeof(pids));
|
||||
int pidCount = bytes / sizeof(int);
|
||||
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *rawList = [NSMutableArray arrayWithCapacity:pidCount];
|
||||
NSMutableDictionary<NSNumber *, NSNumber *> *currentCPUTimes = [NSMutableDictionary dictionaryWithCapacity:pidCount];
|
||||
|
||||
NSUInteger totalThreads = 0;
|
||||
|
||||
for (int i = 0; i < pidCount; i++) {
|
||||
pid_t pid = pids[i];
|
||||
if (pid <= 0) continue;
|
||||
|
||||
struct proc_taskallinfo tai;
|
||||
if (proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &tai, sizeof(tai)) != sizeof(tai)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
uint64_t cpuTimeNs = tai.ptinfo.pti_total_user + tai.ptinfo.pti_total_system;
|
||||
currentCPUTimes[@(pid)] = @(cpuTimeNs);
|
||||
|
||||
totalThreads += tai.ptinfo.pti_threadnum;
|
||||
|
||||
// Resolve username
|
||||
NSNumber *uidNum = @(tai.pbsd.pbi_uid);
|
||||
NSString *username = _usernameCache[uidNum];
|
||||
if (!username) {
|
||||
struct passwd *pw = getpwuid(tai.pbsd.pbi_uid);
|
||||
username = pw ? [NSString stringWithUTF8String:pw->pw_name] : [uidNum stringValue];
|
||||
_usernameCache[uidNum] = username;
|
||||
}
|
||||
|
||||
NSString *pname = [NSString stringWithUTF8String:tai.pbsd.pbi_name];
|
||||
|
||||
[rawList addObject:@{
|
||||
@"pid": @(pid),
|
||||
@"ppid": @(tai.pbsd.pbi_ppid),
|
||||
@"uid": uidNum,
|
||||
@"username": username,
|
||||
@"name": pname,
|
||||
@"cpuTimeNs": @(cpuTimeNs),
|
||||
@"residentBytes": @(tai.ptinfo.pti_resident_size),
|
||||
@"virtualBytes": @(tai.ptinfo.pti_virtual_size),
|
||||
@"threadCount": @(tai.ptinfo.pti_threadnum),
|
||||
@"runningThreads": @(tai.ptinfo.pti_numrunning)
|
||||
}];
|
||||
}
|
||||
|
||||
os_unfair_lock_lock(&_lock);
|
||||
NSDictionary<NSNumber *, NSNumber *> *prev = [_previousCPUTimes copy];
|
||||
uint64_t prevTime = _previousTimestamp;
|
||||
|
||||
_previousCPUTimes = currentCPUTimes;
|
||||
_previousTimestamp = now;
|
||||
os_unfair_lock_unlock(&_lock);
|
||||
|
||||
NSTimeInterval timeDelta = 1.0;
|
||||
if (prevTime > 0) {
|
||||
uint64_t elapsed = now - prevTime;
|
||||
timeDelta = (double)elapsed * _timebase.numer / _timebase.denom / 1e9;
|
||||
}
|
||||
|
||||
NSArray<NSDictionary<NSString *, id> *> *processed = [MMProcessTelemetryProvider calculateProcessListWithRawProcesses:rawList
|
||||
previousCPUTimes:prev
|
||||
timeDelta:timeDelta];
|
||||
|
||||
return @{
|
||||
@"processCount": @(processed.count),
|
||||
@"totalThreads": @(totalThreads),
|
||||
@"processes": processed,
|
||||
@"timeDelta": @(timeDelta)
|
||||
};
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,29 @@
|
||||
#ifndef MMDiskIOProvider_h
|
||||
#define MMDiskIOProvider_h
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MMTelemetryProvider.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* MMDiskIOProvider
|
||||
* Samples real-time storage disk transfer rates (read/write bytes per second)
|
||||
* and transaction rates (read/write IOPS) across internal and external block storage devices.
|
||||
*/
|
||||
@interface MMDiskIOProvider : NSObject <MMTelemetryProvider>
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
* Pure calculator method for deterministic unit testing.
|
||||
*/
|
||||
+ (NSDictionary<NSString *, id> *)calculateDiskIOMetricsWithCurrentSnapshots:(NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)current
|
||||
previousSnapshots:(nullable NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)previous
|
||||
timeDelta:(NSTimeInterval)timeDelta;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif /* MMDiskIOProvider_h */
|
||||
@@ -0,0 +1,170 @@
|
||||
#import "MMDiskIOProvider.h"
|
||||
#import <IOKit/IOKitLib.h>
|
||||
#import <IOKit/storage/IOBlockStorageDriver.h>
|
||||
#import <mach/mach_time.h>
|
||||
#import <os/lock.h>
|
||||
|
||||
@interface MMDiskIOProvider () {
|
||||
os_unfair_lock _lock;
|
||||
NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *_previousSnapshots;
|
||||
uint64_t _previousTimestamp;
|
||||
mach_timebase_info_data_t _timebase;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation MMDiskIOProvider
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_lock = OS_UNFAIR_LOCK_INIT;
|
||||
_previousSnapshots = nil;
|
||||
_previousTimestamp = 0;
|
||||
mach_timebase_info(&_timebase);
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (MMTelemetryDomain)domain {
|
||||
return MMTelemetryDomainStorage;
|
||||
}
|
||||
|
||||
- (NSString *)providerIdentifier {
|
||||
return @"com.i3omb.macmonitor.telemetry.storage.io";
|
||||
}
|
||||
|
||||
- (BOOL)isAvailable {
|
||||
return YES;
|
||||
}
|
||||
|
||||
+ (NSDictionary<NSString *, id> *)calculateDiskIOMetricsWithCurrentSnapshots:(NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)current
|
||||
previousSnapshots:(nullable NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *)previous
|
||||
timeDelta:(NSTimeInterval)timeDelta {
|
||||
double totalReadBps = 0.0;
|
||||
double totalWriteBps = 0.0;
|
||||
double totalReadIOPS = 0.0;
|
||||
double totalWriteIOPS = 0.0;
|
||||
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *disks = [NSMutableArray arrayWithCapacity:current.count];
|
||||
NSArray<NSString *> *sortedBsdNames = [current.allKeys sortedArrayUsingSelector:@selector(compare:)];
|
||||
|
||||
for (NSString *bsdName in sortedBsdNames) {
|
||||
NSDictionary<NSString *, NSNumber *> *curr = current[bsdName];
|
||||
NSDictionary<NSString *, NSNumber *> *prev = previous ? previous[bsdName] : nil;
|
||||
|
||||
uint64_t currReadBytes = [curr[@"readBytes"] unsignedLongLongValue];
|
||||
uint64_t currWriteBytes = [curr[@"writeBytes"] unsignedLongLongValue];
|
||||
uint64_t currReadOps = [curr[@"readOps"] unsignedLongLongValue];
|
||||
uint64_t currWriteOps = [curr[@"writeOps"] unsignedLongLongValue];
|
||||
|
||||
uint64_t prevReadBytes = prev ? [prev[@"readBytes"] unsignedLongLongValue] : currReadBytes;
|
||||
uint64_t prevWriteBytes = prev ? [prev[@"writeBytes"] unsignedLongLongValue] : currWriteBytes;
|
||||
uint64_t prevReadOps = prev ? [prev[@"readOps"] unsignedLongLongValue] : currReadOps;
|
||||
uint64_t prevWriteOps = prev ? [prev[@"writeOps"] unsignedLongLongValue] : currWriteOps;
|
||||
|
||||
double deltaReadBytes = (currReadBytes >= prevReadBytes) ? (double)(currReadBytes - prevReadBytes) : 0.0;
|
||||
double deltaWriteBytes = (currWriteBytes >= prevWriteBytes) ? (double)(currWriteBytes - prevWriteBytes) : 0.0;
|
||||
double deltaReadOps = (currReadOps >= prevReadOps) ? (double)(currReadOps - prevReadOps) : 0.0;
|
||||
double deltaWriteOps = (currWriteOps >= prevWriteOps) ? (double)(currWriteOps - prevWriteOps) : 0.0;
|
||||
|
||||
double readBps = (timeDelta > 0.0001) ? (deltaReadBytes / timeDelta) : 0.0;
|
||||
double writeBps = (timeDelta > 0.0001) ? (deltaWriteBytes / timeDelta) : 0.0;
|
||||
double readIOPS = (timeDelta > 0.0001) ? (deltaReadOps / timeDelta) : 0.0;
|
||||
double writeIOPS = (timeDelta > 0.0001) ? (deltaWriteOps / timeDelta) : 0.0;
|
||||
|
||||
totalReadBps += readBps;
|
||||
totalWriteBps += writeBps;
|
||||
totalReadIOPS += readIOPS;
|
||||
totalWriteIOPS += writeIOPS;
|
||||
|
||||
[disks addObject:@{
|
||||
@"bsdName": bsdName,
|
||||
@"readBytesPerSec": @(readBps),
|
||||
@"writeBytesPerSec": @(writeBps),
|
||||
@"readIOPS": @(readIOPS),
|
||||
@"writeIOPS": @(writeIOPS),
|
||||
@"cumulativeReadBytes": @(currReadBytes),
|
||||
@"cumulativeWriteBytes": @(currWriteBytes),
|
||||
@"cumulativeReadOps": @(currReadOps),
|
||||
@"cumulativeWriteOps": @(currWriteOps)
|
||||
}];
|
||||
}
|
||||
|
||||
return @{
|
||||
@"disks": disks,
|
||||
@"totalReadBytesPerSec": @(totalReadBps),
|
||||
@"totalWriteBytesPerSec": @(totalWriteBps),
|
||||
@"totalReadIOPS": @(totalReadIOPS),
|
||||
@"totalWriteIOPS": @(totalWriteIOPS),
|
||||
@"timeDelta": @(timeDelta)
|
||||
};
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
|
||||
uint64_t now = mach_absolute_time();
|
||||
|
||||
NSMutableDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *currentSnapshots = [NSMutableDictionary dictionary];
|
||||
|
||||
CFMutableDictionaryRef matching = IOServiceMatching(kIOBlockStorageDriverClass);
|
||||
io_iterator_t iterator = IO_OBJECT_NULL;
|
||||
if (IOServiceGetMatchingServices(kIOMainPortDefault, matching, &iterator) == KERN_SUCCESS && iterator != IO_OBJECT_NULL) {
|
||||
io_registry_entry_t entry;
|
||||
while ((entry = IOIteratorNext(iterator)) != IO_OBJECT_NULL) {
|
||||
NSString *bsdName = nil;
|
||||
io_iterator_t childIterator;
|
||||
if (IORegistryEntryGetChildIterator(entry, kIOServicePlane, &childIterator) == KERN_SUCCESS) {
|
||||
io_registry_entry_t child;
|
||||
while ((child = IOIteratorNext(childIterator)) != IO_OBJECT_NULL) {
|
||||
CFTypeRef nameRef = IORegistryEntryCreateCFProperty(child, CFSTR("BSD Name"), kCFAllocatorDefault, 0);
|
||||
if (nameRef) {
|
||||
bsdName = CFBridgingRelease(nameRef);
|
||||
IOObjectRelease(child);
|
||||
break;
|
||||
}
|
||||
IOObjectRelease(child);
|
||||
}
|
||||
IOObjectRelease(childIterator);
|
||||
}
|
||||
|
||||
if (bsdName) {
|
||||
CFTypeRef statsRef = IORegistryEntryCreateCFProperty(entry, CFSTR("Statistics"), kCFAllocatorDefault, 0);
|
||||
if (statsRef) {
|
||||
NSDictionary *stats = CFBridgingRelease(statsRef);
|
||||
NSNumber *readBytes = stats[@"Bytes (Read)"] ?: @0;
|
||||
NSNumber *writeBytes = stats[@"Bytes (Write)"] ?: @0;
|
||||
NSNumber *readOps = stats[@"Operations (Read)"] ?: @0;
|
||||
NSNumber *writeOps = stats[@"Operations (Write)"] ?: @0;
|
||||
|
||||
currentSnapshots[bsdName] = @{
|
||||
@"readBytes": readBytes,
|
||||
@"writeBytes": writeBytes,
|
||||
@"readOps": readOps,
|
||||
@"writeOps": writeOps
|
||||
};
|
||||
}
|
||||
}
|
||||
IOObjectRelease(entry);
|
||||
}
|
||||
IOObjectRelease(iterator);
|
||||
}
|
||||
|
||||
os_unfair_lock_lock(&_lock);
|
||||
NSDictionary<NSString *, NSDictionary<NSString *, NSNumber *> *> *prev = _previousSnapshots;
|
||||
uint64_t prevTime = _previousTimestamp;
|
||||
|
||||
_previousSnapshots = currentSnapshots;
|
||||
_previousTimestamp = now;
|
||||
os_unfair_lock_unlock(&_lock);
|
||||
|
||||
NSTimeInterval timeDelta = 1.0;
|
||||
if (prevTime > 0) {
|
||||
uint64_t elapsed = now - prevTime;
|
||||
timeDelta = (double)elapsed * _timebase.numer / _timebase.denom / 1e9;
|
||||
}
|
||||
|
||||
return [MMDiskIOProvider calculateDiskIOMetricsWithCurrentSnapshots:currentSnapshots
|
||||
previousSnapshots:prev
|
||||
timeDelta:timeDelta];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,33 @@
|
||||
#ifndef MMLoadAverageProvider_h
|
||||
#define MMLoadAverageProvider_h
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MMTelemetryProvider.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* MMLoadAverageProvider
|
||||
* Samples 1m, 5m, and 15m system load averages, Mach concurrency factors,
|
||||
* and system-wide task and thread counts.
|
||||
*/
|
||||
@interface MMLoadAverageProvider : NSObject <MMTelemetryProvider>
|
||||
|
||||
- (instancetype)init;
|
||||
|
||||
/**
|
||||
* Pure calculator method for deterministic unit testing.
|
||||
*/
|
||||
+ (NSDictionary<NSString *, id> *)calculateLoadMetricsWithLoad1:(double)load1
|
||||
load5:(double)load5
|
||||
load15:(double)load15
|
||||
taskCount:(int)taskCount
|
||||
threadCount:(int)threadCount
|
||||
cpuCount:(int)cpuCount
|
||||
machFactor:(double)machFactor;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif /* MMLoadAverageProvider_h */
|
||||
@@ -0,0 +1,92 @@
|
||||
#import "MMLoadAverageProvider.h"
|
||||
#import <mach/mach.h>
|
||||
#import <mach/processor_info.h>
|
||||
#import <sys/sysctl.h>
|
||||
#import <stdlib.h>
|
||||
|
||||
@implementation MMLoadAverageProvider
|
||||
|
||||
- (instancetype)init {
|
||||
self = [super init];
|
||||
return self;
|
||||
}
|
||||
|
||||
- (MMTelemetryDomain)domain {
|
||||
return MMTelemetryDomainSystem;
|
||||
}
|
||||
|
||||
- (NSString *)providerIdentifier {
|
||||
return @"com.i3omb.macmonitor.telemetry.system.load";
|
||||
}
|
||||
|
||||
- (BOOL)isAvailable {
|
||||
return YES;
|
||||
}
|
||||
|
||||
+ (NSDictionary<NSString *, id> *)calculateLoadMetricsWithLoad1:(double)load1
|
||||
load5:(double)load5
|
||||
load15:(double)load15
|
||||
taskCount:(int)taskCount
|
||||
threadCount:(int)threadCount
|
||||
cpuCount:(int)cpuCount
|
||||
machFactor:(double)machFactor {
|
||||
int safeCpus = cpuCount > 0 ? cpuCount : 1;
|
||||
double norm1 = load1 / (double)safeCpus;
|
||||
double norm5 = load5 / (double)safeCpus;
|
||||
double norm15 = load15 / (double)safeCpus;
|
||||
|
||||
return @{
|
||||
@"load1m": @(load1),
|
||||
@"load5m": @(load5),
|
||||
@"load15m": @(load15),
|
||||
@"normalizedLoad1m": @(norm1),
|
||||
@"normalizedLoad5m": @(norm5),
|
||||
@"normalizedLoad15m": @(norm15),
|
||||
@"taskCount": @(taskCount),
|
||||
@"threadCount": @(threadCount),
|
||||
@"logicalCpuCount": @(safeCpus),
|
||||
@"machFactor": @(machFactor),
|
||||
@"isOverloaded": @(norm1 > 1.0)
|
||||
};
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
|
||||
// 1. Get BSD load averages
|
||||
double load[3] = {0.0, 0.0, 0.0};
|
||||
int ret = getloadavg(load, 3);
|
||||
if (ret <= 0) {
|
||||
load[0] = 0.0;
|
||||
load[1] = 0.0;
|
||||
load[2] = 0.0;
|
||||
}
|
||||
|
||||
// 2. Query Mach processor set for task & thread counts and mach factor
|
||||
mach_port_t host = mach_host_self();
|
||||
processor_set_name_port_t pset = MACH_PORT_NULL;
|
||||
processor_set_load_info_data_t loadInfo = {0};
|
||||
mach_msg_type_number_t count = PROCESSOR_SET_LOAD_INFO_COUNT;
|
||||
|
||||
kern_return_t kr = processor_set_default(host, &pset);
|
||||
if (kr == KERN_SUCCESS && MACH_PORT_VALID(pset)) {
|
||||
kr = processor_set_statistics(pset, PROCESSOR_SET_LOAD_INFO, (processor_set_info_t)&loadInfo, &count);
|
||||
mach_port_deallocate(mach_task_self(), pset);
|
||||
}
|
||||
|
||||
double machFactor = (double)loadInfo.mach_factor / (double)LOAD_SCALE;
|
||||
|
||||
// 3. Query logical CPU core count
|
||||
int cpuCount = 1;
|
||||
size_t size = sizeof(cpuCount);
|
||||
sysctlbyname("hw.logicalcpu", &cpuCount, &size, NULL, 0);
|
||||
if (cpuCount <= 0) cpuCount = 1;
|
||||
|
||||
return [MMLoadAverageProvider calculateLoadMetricsWithLoad1:load[0]
|
||||
load5:load[1]
|
||||
load15:load[2]
|
||||
taskCount:loadInfo.task_count
|
||||
threadCount:loadInfo.thread_count
|
||||
cpuCount:cpuCount
|
||||
machFactor:machFactor];
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,42 @@
|
||||
#ifndef MMComponentThermalProvider_h
|
||||
#define MMComponentThermalProvider_h
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
#import "MMTelemetryProvider.h"
|
||||
#import "MMAppleSMCClient.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/**
|
||||
* MMComponentThermalProvider
|
||||
* Samples motherboard, PCH chipset, heatsink, memory, and enclosure ambient temperatures
|
||||
* via AppleSMC.
|
||||
*/
|
||||
@interface MMComponentThermalProvider : NSObject <MMTelemetryProvider>
|
||||
|
||||
@property (nonatomic, strong, readonly) MMAppleSMCClient *smcClient;
|
||||
@property (nonatomic, readonly) NSArray<NSString *> *discoveredKeys;
|
||||
|
||||
- (instancetype)init;
|
||||
- (instancetype)initWithSMCClient:(MMAppleSMCClient *)client;
|
||||
|
||||
/**
|
||||
* Categorize SMC temperature key into component domain (e.g., PCH / Chipset, Heatsink, Memory, etc.)
|
||||
*/
|
||||
+ (NSString *)categoryForKey:(NSString *)key;
|
||||
|
||||
/**
|
||||
* Human-readable friendly name for known component SMC keys.
|
||||
*/
|
||||
+ (NSString *)humanReadableNameForKey:(NSString *)key;
|
||||
|
||||
/**
|
||||
* Static calculator method for deterministic unit testing.
|
||||
*/
|
||||
+ (NSDictionary<NSString *, id> *)calculateComponentMetricsFromDictionary:(NSDictionary<NSString *, NSNumber *> *)readings;
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
|
||||
#endif /* MMComponentThermalProvider_h */
|
||||
@@ -0,0 +1,174 @@
|
||||
#import "MMComponentThermalProvider.h"
|
||||
|
||||
@interface MMComponentThermalProvider () {
|
||||
MMAppleSMCClient *_smcClient;
|
||||
NSMutableArray<NSString *> *_discoveredKeys;
|
||||
BOOL _probed;
|
||||
}
|
||||
@end
|
||||
|
||||
@implementation MMComponentThermalProvider
|
||||
|
||||
- (instancetype)init {
|
||||
return [self initWithSMCClient:[MMAppleSMCClient sharedClient]];
|
||||
}
|
||||
|
||||
- (instancetype)initWithSMCClient:(MMAppleSMCClient *)client {
|
||||
self = [super init];
|
||||
if (self) {
|
||||
_smcClient = client;
|
||||
_discoveredKeys = [NSMutableArray array];
|
||||
[self probeSensors];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (void)probeSensors {
|
||||
if (!_smcClient.isAvailable) return;
|
||||
|
||||
NSArray<NSString *> *candidates = @[
|
||||
@"TPCD", @"TP0P", @"TP0D",
|
||||
@"Th0H", @"Th1H", @"Th2H", @"Th3H",
|
||||
@"TM0P", @"TM1P", @"TM2P", @"TM3P", @"TM0S", @"TM1S",
|
||||
@"Tp0P", @"Tp1P", @"Tp2P", @"Tp0C",
|
||||
@"TA0P", @"TA1P", @"TA0S", @"TA1S",
|
||||
@"TTLD", @"TT1D", @"TB0T", @"TB1T"
|
||||
];
|
||||
|
||||
[_discoveredKeys removeAllObjects];
|
||||
for (NSString *key in candidates) {
|
||||
NSNumber *val = [_smcClient readNumericValueForKey:key error:nil];
|
||||
if (val && [val doubleValue] > 0.0 && [val doubleValue] < 125.0) {
|
||||
[_discoveredKeys addObject:key];
|
||||
}
|
||||
}
|
||||
|
||||
_probed = YES;
|
||||
}
|
||||
|
||||
- (MMTelemetryDomain)domain {
|
||||
return MMTelemetryDomainThermal;
|
||||
}
|
||||
|
||||
- (NSString *)providerIdentifier {
|
||||
return @"com.i3omb.macmonitor.telemetry.thermal.components";
|
||||
}
|
||||
|
||||
- (BOOL)isAvailable {
|
||||
return _smcClient.isAvailable;
|
||||
}
|
||||
|
||||
- (MMAppleSMCClient *)smcClient {
|
||||
return _smcClient;
|
||||
}
|
||||
|
||||
- (NSArray<NSString *> *)discoveredKeys {
|
||||
return [_discoveredKeys copy];
|
||||
}
|
||||
|
||||
+ (NSString *)categoryForKey:(NSString *)key {
|
||||
if ([key hasPrefix:@"TP"]) return @"PCH / Chipset";
|
||||
if ([key hasPrefix:@"Th"]) return @"Heatsink";
|
||||
if ([key hasPrefix:@"TM"]) return @"Memory";
|
||||
if ([key hasPrefix:@"Tp"]) return @"Power Supply";
|
||||
if ([key hasPrefix:@"TA"]) return @"Ambient / Enclosure";
|
||||
if ([key hasPrefix:@"TT"] || [key hasPrefix:@"TB"] || [key hasPrefix:@"TI"]) return @"Thunderbolt / IO";
|
||||
return @"Other";
|
||||
}
|
||||
|
||||
+ (NSString *)humanReadableNameForKey:(NSString *)key {
|
||||
static NSDictionary<NSString *, NSString *> *names = nil;
|
||||
static dispatch_once_t onceToken;
|
||||
dispatch_once(&onceToken, ^{
|
||||
names = @{
|
||||
@"TPCD": @"Platform Controller Hub (Die)",
|
||||
@"TP0P": @"Platform Controller Hub (Proximity)",
|
||||
@"TP0D": @"Platform Controller Hub (Die Alternate)",
|
||||
@"Th0H": @"Main Heatsink A",
|
||||
@"Th1H": @"Main Heatsink B",
|
||||
@"Th2H": @"Main Heatsink C",
|
||||
@"Th3H": @"Main Heatsink D",
|
||||
@"TM0P": @"Memory Bank 0 Proximity",
|
||||
@"TM1P": @"Memory Bank 1 Proximity",
|
||||
@"TM2P": @"Memory Bank 2 Proximity",
|
||||
@"TM3P": @"Memory Bank 3 Proximity",
|
||||
@"TM0S": @"Memory Module 0",
|
||||
@"TM1S": @"Memory Module 1",
|
||||
@"Tp0P": @"Power Supply Primary",
|
||||
@"Tp1P": @"Power Supply Secondary",
|
||||
@"Tp2P": @"Power Supply Tertiary",
|
||||
@"Tp0C": @"Power Supply Core",
|
||||
@"TA0P": @"Ambient Air Intake",
|
||||
@"TA1P": @"Ambient Air Exhaust",
|
||||
@"TA0S": @"Ambient Air Enclosure",
|
||||
@"TA1S": @"Ambient Air Secondary",
|
||||
@"TTLD": @"Thunderbolt Controller Die",
|
||||
@"TT1D": @"Thunderbolt Controller Secondary",
|
||||
@"TB0T": @"Thunderbolt Port 0",
|
||||
@"TB1T": @"Thunderbolt Port 1"
|
||||
};
|
||||
});
|
||||
|
||||
NSString *match = names[key];
|
||||
return match ?: key;
|
||||
}
|
||||
|
||||
+ (NSDictionary<NSString *, id> *)calculateComponentMetricsFromDictionary:(NSDictionary<NSString *, NSNumber *> *)readings {
|
||||
NSMutableArray<NSDictionary<NSString *, id> *> *components = [NSMutableArray arrayWithCapacity:readings.count];
|
||||
NSMutableDictionary<NSString *, NSMutableArray<NSDictionary<NSString *, id> *> *> *categorized = [NSMutableDictionary dictionary];
|
||||
|
||||
NSArray<NSString *> *sortedKeys = [readings.allKeys sortedArrayUsingSelector:@selector(compare:)];
|
||||
double peak = 0.0;
|
||||
double sum = 0.0;
|
||||
|
||||
for (NSString *k in sortedKeys) {
|
||||
double temp = [readings[k] doubleValue];
|
||||
if (temp > peak) peak = temp;
|
||||
sum += temp;
|
||||
|
||||
NSString *cat = [self categoryForKey:k];
|
||||
NSString *name = [self humanReadableNameForKey:k];
|
||||
|
||||
NSDictionary<NSString *, id> *entry = @{
|
||||
@"key": k,
|
||||
@"name": name,
|
||||
@"category": cat,
|
||||
@"temperature": @(temp)
|
||||
};
|
||||
|
||||
[components addObject:entry];
|
||||
|
||||
if (!categorized[cat]) {
|
||||
categorized[cat] = [NSMutableArray array];
|
||||
}
|
||||
[categorized[cat] addObject:entry];
|
||||
}
|
||||
|
||||
double avg = readings.count > 0 ? (sum / (double)readings.count) : 0.0;
|
||||
|
||||
return @{
|
||||
@"components": components,
|
||||
@"categorized": categorized,
|
||||
@"sensorCount": @(readings.count),
|
||||
@"peakTemperature": @(peak),
|
||||
@"averageTemperature": @(avg)
|
||||
};
|
||||
}
|
||||
|
||||
- (nullable NSDictionary<NSString *, id> *)sampleTelemetryWithError:(NSError **)error {
|
||||
if (!_probed && _smcClient.isAvailable) {
|
||||
[self probeSensors];
|
||||
}
|
||||
|
||||
NSMutableDictionary<NSString *, NSNumber *> *readings = [NSMutableDictionary dictionary];
|
||||
for (NSString *key in _discoveredKeys) {
|
||||
NSNumber *temp = [_smcClient readNumericValueForKey:key error:nil];
|
||||
if (temp) {
|
||||
readings[key] = temp;
|
||||
}
|
||||
}
|
||||
|
||||
return [MMComponentThermalProvider calculateComponentMetricsFromDictionary:readings];
|
||||
}
|
||||
|
||||
@end
|
||||
+495
-82
@@ -2,6 +2,7 @@ import SwiftUI
|
||||
|
||||
public struct ContentView: View {
|
||||
@State private var store = SystemTelemetryStore.shared
|
||||
@State private var selectedTab: String = "Dashboard"
|
||||
|
||||
public init() {}
|
||||
|
||||
@@ -11,59 +12,111 @@ public struct ContentView: View {
|
||||
} detail: {
|
||||
detailContent
|
||||
}
|
||||
.frame(minWidth: 800, minHeight: 520)
|
||||
.frame(minWidth: 900, minHeight: 650)
|
||||
.onAppear {
|
||||
store.start()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Sidebar
|
||||
private var sidebarContent: some View {
|
||||
List {
|
||||
Section("System Status") {
|
||||
List(selection: $selectedTab) {
|
||||
Section("Overview") {
|
||||
Label("Dashboard", systemImage: "gauge.with.needle")
|
||||
Label("Architecture", systemImage: "cpu")
|
||||
.tag("Dashboard")
|
||||
Label("Hardware Architecture", systemImage: "cpu")
|
||||
.tag("Architecture")
|
||||
}
|
||||
|
||||
Section("Telemetry Domains") {
|
||||
Label("CPU & Thermals", systemImage: "flame")
|
||||
Section("Primary Telemetry") {
|
||||
Label("CPU Load & Cores", systemImage: "chart.bar.xaxis")
|
||||
.tag("CPU")
|
||||
Label("Thermal Matrix", systemImage: "flame")
|
||||
.tag("Thermals")
|
||||
Label("Fans & Cooling", systemImage: "fanblades")
|
||||
.tag("Fans")
|
||||
Label("Memory & Swap", systemImage: "memorychip")
|
||||
Label("Disks & Volumes", systemImage: "internaldrive")
|
||||
Label("Processes", systemImage: "list.bullet.rectangle")
|
||||
Label("Network", systemImage: "network")
|
||||
Label("Graphics (GPU)", systemImage: "display")
|
||||
.tag("Memory")
|
||||
Label("Storage Volumes", systemImage: "internaldrive")
|
||||
.tag("Storage")
|
||||
Label("Power & Voltage", systemImage: "bolt.fill")
|
||||
.tag("Power")
|
||||
}
|
||||
}
|
||||
.listStyle(.sidebar)
|
||||
.navigationSplitViewColumnWidth(min: 200, ideal: 220, max: 280)
|
||||
.navigationSplitViewColumnWidth(min: 200, ideal: 230, max: 280)
|
||||
}
|
||||
|
||||
// MARK: - Detail Content Router
|
||||
@ViewBuilder
|
||||
private var detailContent: some View {
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 20) {
|
||||
// Header Banner
|
||||
headerCard
|
||||
|
||||
// Telemetry Engine Control
|
||||
engineControlCard
|
||||
|
||||
// System Specifications
|
||||
specsCard
|
||||
|
||||
// Providers Status
|
||||
providersCard
|
||||
switch selectedTab {
|
||||
case "Dashboard":
|
||||
dashboardView
|
||||
case "Architecture":
|
||||
specsCard
|
||||
providersCard
|
||||
case "CPU":
|
||||
cpuLoadCard
|
||||
specsCard
|
||||
case "Thermals":
|
||||
cpuThermalCard
|
||||
componentThermalCard
|
||||
case "Fans":
|
||||
fansCard
|
||||
case "Memory":
|
||||
memoryCard
|
||||
case "Storage":
|
||||
storageCard
|
||||
case "Power":
|
||||
powerCard
|
||||
default:
|
||||
dashboardView
|
||||
}
|
||||
}
|
||||
.padding(24)
|
||||
}
|
||||
.navigationTitle("MacMonitor Dashboard")
|
||||
.navigationTitle("MacMonitor — \(selectedTab)")
|
||||
}
|
||||
|
||||
// MARK: - Dashboard Composite View
|
||||
private var dashboardView: some View {
|
||||
VStack(alignment: .leading, spacing: 20) {
|
||||
// Top Row: CPU & Memory Summary Cards
|
||||
HStack(alignment: .top, spacing: 16) {
|
||||
cpuLoadCard
|
||||
memoryCard
|
||||
}
|
||||
|
||||
// Middle Row: Thermals & Fans Summary Cards
|
||||
HStack(alignment: .top, spacing: 16) {
|
||||
cpuThermalCard
|
||||
fansCard
|
||||
}
|
||||
|
||||
// Power & Storage Summary
|
||||
HStack(alignment: .top, spacing: 16) {
|
||||
powerCard
|
||||
storageCard
|
||||
}
|
||||
|
||||
// Detailed Component Thermals Matrix
|
||||
componentThermalCard
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Header Banner
|
||||
private var headerCard: some View {
|
||||
HStack(alignment: .center, spacing: 16) {
|
||||
Image(systemName: "macpro.gen3.fill")
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
.frame(width: 48, height: 48)
|
||||
.frame(width: 44, height: 44)
|
||||
.foregroundStyle(.blue)
|
||||
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
@@ -80,7 +133,7 @@ public struct ContentView: View {
|
||||
Circle()
|
||||
.fill(store.isRunning ? Color.green : Color.red)
|
||||
.frame(width: 10, height: 10)
|
||||
Text(store.isRunning ? "ENGINE ACTIVE" : "ENGINE PAUSED")
|
||||
Text(store.isRunning ? "ACTIVE" : "PAUSED")
|
||||
.font(.caption.bold())
|
||||
.foregroundStyle(store.isRunning ? .green : .secondary)
|
||||
}
|
||||
@@ -93,55 +146,307 @@ public struct ContentView: View {
|
||||
.overlay(RoundedRectangle(cornerRadius: 12).stroke(.separator, lineWidth: 1))
|
||||
}
|
||||
|
||||
// MARK: - Telemetry Coordinator Controls
|
||||
private var engineControlCard: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Telemetry Coordinator Engine")
|
||||
.font(.headline)
|
||||
HStack(spacing: 16) {
|
||||
Button(action: {
|
||||
if store.isRunning { store.stop() } else { store.start() }
|
||||
}) {
|
||||
Label(store.isRunning ? "Pause Engine" : "Start Engine",
|
||||
systemImage: store.isRunning ? "pause.fill" : "play.fill")
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.tint(store.isRunning ? .orange : .green)
|
||||
|
||||
HStack(spacing: 16) {
|
||||
Button(action: {
|
||||
if store.isRunning {
|
||||
store.stop()
|
||||
} else {
|
||||
store.start()
|
||||
}
|
||||
}) {
|
||||
Label(store.isRunning ? "Pause Engine" : "Start Engine",
|
||||
systemImage: store.isRunning ? "pause.fill" : "play.fill")
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.tint(store.isRunning ? .orange : .green)
|
||||
|
||||
Button(action: {
|
||||
store.triggerManualSample()
|
||||
}) {
|
||||
Label("Sample Now", systemImage: "arrow.clockwise")
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
|
||||
Button(action: { store.triggerManualSample() }) {
|
||||
Label("Sample Now", systemImage: "arrow.clockwise")
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
|
||||
Spacer()
|
||||
|
||||
Picker("Interval:", selection: Binding(
|
||||
get: { store.sampleInterval },
|
||||
set: { store.setSampleInterval($0) }
|
||||
)) {
|
||||
Text("0.5s").tag(0.5)
|
||||
Text("1.0s").tag(1.0)
|
||||
Text("2.0s").tag(2.0)
|
||||
Text("5.0s").tag(5.0)
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
.frame(width: 220)
|
||||
|
||||
Text("Updated: \(store.lastUpdateTimestamp.formatted(date: .omitted, time: .standard))")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.padding(14)
|
||||
.background(.background, in: RoundedRectangle(cornerRadius: 12))
|
||||
.overlay(RoundedRectangle(cornerRadius: 12).stroke(.separator, lineWidth: 1))
|
||||
}
|
||||
|
||||
// MARK: - CPU Load Card
|
||||
private var cpuLoadCard: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
Label("CPU Activity", systemImage: "cpu")
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
|
||||
Picker("Polling Interval:", selection: Binding(
|
||||
get: { store.sampleInterval },
|
||||
set: { store.setSampleInterval($0) }
|
||||
)) {
|
||||
Text("0.5s").tag(0.5)
|
||||
Text("1.0s").tag(1.0)
|
||||
Text("2.0s").tag(2.0)
|
||||
Text("5.0s").tag(5.0)
|
||||
if store.cpuLoad.isThrottled {
|
||||
Text("THROTTLED")
|
||||
.font(.caption.bold())
|
||||
.foregroundStyle(.red)
|
||||
.padding(.horizontal, 6)
|
||||
.padding(.vertical, 2)
|
||||
.background(Color.red.opacity(0.15), in: Capsule())
|
||||
}
|
||||
.pickerStyle(.segmented)
|
||||
.frame(width: 220)
|
||||
Text(String(format: "%.1f%%", store.cpuLoad.totalLoad))
|
||||
.font(.title3.bold().monospacedDigit())
|
||||
}
|
||||
|
||||
ProgressView(value: min(store.cpuLoad.totalLoad / 100.0, 1.0))
|
||||
.tint(store.cpuLoad.totalLoad > 85 ? .red : (store.cpuLoad.totalLoad > 60 ? .orange : .blue))
|
||||
|
||||
HStack {
|
||||
Text("Last Sample Cycle: \(store.lastUpdateTimestamp.formatted(date: .omitted, time: .standard))")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
Text("User: \(String(format: "%.1f%%", store.cpuLoad.userLoad))")
|
||||
Spacer()
|
||||
Text("Queue: com.i3omb.macmonitor.telemetry (QOS_UTILITY)")
|
||||
Text("System: \(String(format: "%.1f%%", store.cpuLoad.systemLoad))")
|
||||
Spacer()
|
||||
Text("Idle: \(String(format: "%.1f%%", store.cpuLoad.idleLoad))")
|
||||
}
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
|
||||
if !store.cpuLoad.perCoreLoad.isEmpty {
|
||||
Divider()
|
||||
Text("Per-Core Utilization (\(store.cpuLoad.perCoreLoad.count) Cores)")
|
||||
.font(.caption.bold())
|
||||
.foregroundStyle(.secondary)
|
||||
|
||||
LazyVGrid(columns: [GridItem(.adaptive(minimum: 70))], spacing: 8) {
|
||||
ForEach(Array(store.cpuLoad.perCoreLoad.enumerated()), id: \.offset) { idx, load in
|
||||
VStack(spacing: 4) {
|
||||
Text("Core \(idx)")
|
||||
.font(.system(size: 10))
|
||||
.foregroundStyle(.secondary)
|
||||
ProgressView(value: min(load / 100.0, 1.0))
|
||||
.tint(load > 85 ? .red : .blue)
|
||||
Text(String(format: "%.0f%%", load))
|
||||
.font(.system(size: 10, weight: .bold, design: .monospaced))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
.frame(maxWidth: .infinity, alignment: .topLeading)
|
||||
.background(.background, in: RoundedRectangle(cornerRadius: 12))
|
||||
.overlay(RoundedRectangle(cornerRadius: 12).stroke(.separator, lineWidth: 1))
|
||||
}
|
||||
|
||||
// MARK: - Memory & Swap Card
|
||||
private var memoryCard: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
Label("Memory & Swap", systemImage: "memorychip")
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Text(store.memory.pressureLevel)
|
||||
.font(.caption.bold())
|
||||
.foregroundStyle(pressureColor(store.memory.pressureLevel))
|
||||
.padding(.horizontal, 6)
|
||||
.padding(.vertical, 2)
|
||||
.background(pressureColor(store.memory.pressureLevel).opacity(0.15), in: Capsule())
|
||||
Text(String(format: "%.1f%%", store.memory.utilizationPercentage))
|
||||
.font(.title3.bold().monospacedDigit())
|
||||
}
|
||||
|
||||
ProgressView(value: min(store.memory.utilizationPercentage / 100.0, 1.0))
|
||||
.tint(pressureColor(store.memory.pressureLevel))
|
||||
|
||||
Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 6) {
|
||||
GridRow {
|
||||
Text("Physical RAM:").foregroundStyle(.secondary)
|
||||
Text(formatBytes(store.memory.totalBytes)).bold()
|
||||
Text("Used:").foregroundStyle(.secondary)
|
||||
Text(formatBytes(store.memory.usedBytes)).bold()
|
||||
}
|
||||
GridRow {
|
||||
Text("Wired:").foregroundStyle(.secondary)
|
||||
Text(formatBytes(store.memory.wiredBytes))
|
||||
Text("Compressed:").foregroundStyle(.secondary)
|
||||
Text(formatBytes(store.memory.compressedBytes))
|
||||
}
|
||||
GridRow {
|
||||
Text("Active:").foregroundStyle(.secondary)
|
||||
Text(formatBytes(store.memory.activeBytes))
|
||||
Text("Free / Inactive:").foregroundStyle(.secondary)
|
||||
Text(formatBytes(store.memory.freeBytes + store.memory.inactiveBytes))
|
||||
}
|
||||
if store.memory.swapTotalBytes > 0 {
|
||||
GridRow {
|
||||
Text("Swap Total:").foregroundStyle(.secondary)
|
||||
Text(formatBytes(store.memory.swapTotalBytes))
|
||||
Text("Swap Used:").foregroundStyle(.secondary)
|
||||
Text(formatBytes(store.memory.swapUsedBytes))
|
||||
}
|
||||
}
|
||||
}
|
||||
.font(.caption)
|
||||
}
|
||||
.padding(16)
|
||||
.frame(maxWidth: .infinity, alignment: .topLeading)
|
||||
.background(.background, in: RoundedRectangle(cornerRadius: 12))
|
||||
.overlay(RoundedRectangle(cornerRadius: 12).stroke(.separator, lineWidth: 1))
|
||||
}
|
||||
|
||||
// MARK: - CPU Thermal Card
|
||||
private var cpuThermalCard: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
Label("CPU Thermals", systemImage: "flame.fill")
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Text(store.cpuThermal.thermalPressureState)
|
||||
.font(.caption.bold())
|
||||
.foregroundStyle(store.cpuThermal.isThrottling ? .red : .green)
|
||||
.padding(.horizontal, 6)
|
||||
.padding(.vertical, 2)
|
||||
.background((store.cpuThermal.isThrottling ? Color.red : Color.green).opacity(0.15), in: Capsule())
|
||||
Text(String(format: "%.1f°C", store.cpuThermal.packageTemperature))
|
||||
.font(.title3.bold().monospacedDigit())
|
||||
}
|
||||
|
||||
HStack(spacing: 24) {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text("Package Temp").font(.caption).foregroundStyle(.secondary)
|
||||
Text(String(format: "%.1f°C", store.cpuThermal.packageTemperature)).bold()
|
||||
}
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text("Peak Core").font(.caption).foregroundStyle(.secondary)
|
||||
Text(String(format: "%.1f°C", store.cpuThermal.peakCoreTemperature)).bold()
|
||||
}
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text("Average Core").font(.caption).foregroundStyle(.secondary)
|
||||
Text(String(format: "%.1f°C", store.cpuThermal.averageCoreTemperature)).bold()
|
||||
}
|
||||
}
|
||||
|
||||
if !store.cpuThermal.coreTemperatures.isEmpty {
|
||||
Divider()
|
||||
Text("Core Temperature Breakdown")
|
||||
.font(.caption.bold())
|
||||
.foregroundStyle(.secondary)
|
||||
|
||||
LazyVGrid(columns: [GridItem(.adaptive(minimum: 80))], spacing: 8) {
|
||||
ForEach(store.cpuThermal.coreTemperatures, id: \.key) { core in
|
||||
VStack(spacing: 2) {
|
||||
Text("Core \(core.index)")
|
||||
.font(.system(size: 10))
|
||||
.foregroundStyle(.secondary)
|
||||
Text(String(format: "%.1f°C", core.temperature))
|
||||
.font(.system(size: 11, weight: .bold, design: .monospaced))
|
||||
.foregroundStyle(core.temperature > 85 ? .red : (core.temperature > 70 ? .orange : .primary))
|
||||
}
|
||||
.padding(6)
|
||||
.background(.quaternary, in: RoundedRectangle(cornerRadius: 6))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
.frame(maxWidth: .infinity, alignment: .topLeading)
|
||||
.background(.background, in: RoundedRectangle(cornerRadius: 12))
|
||||
.overlay(RoundedRectangle(cornerRadius: 12).stroke(.separator, lineWidth: 1))
|
||||
}
|
||||
|
||||
// MARK: - Fans & Tachometers Card
|
||||
private var fansCard: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
Label("Cooling Fans", systemImage: "fanblades.fill")
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Text("\(store.fans.count) Detected")
|
||||
.font(.caption.bold())
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
|
||||
if store.fans.isEmpty {
|
||||
Text("No active AppleSMC fans detected or passive cooling chassis.")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
.padding(.vertical, 8)
|
||||
} else {
|
||||
ForEach(store.fans) { fan in
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
HStack {
|
||||
Text(fan.name).bold()
|
||||
Spacer()
|
||||
Text(String(format: "%.0f RPM (%.0f%%)", fan.currentRPM, fan.utilization))
|
||||
.font(.subheadline.bold().monospacedDigit())
|
||||
}
|
||||
ProgressView(value: min(fan.utilization / 100.0, 1.0))
|
||||
.tint(fan.utilization > 80 ? .red : .blue)
|
||||
HStack {
|
||||
Text("Min: \(Int(fan.minRPM)) RPM")
|
||||
Spacer()
|
||||
Text("Target: \(Int(fan.targetRPM)) RPM")
|
||||
Spacer()
|
||||
Text("Max: \(Int(fan.maxRPM)) RPM")
|
||||
}
|
||||
.font(.system(size: 10))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.padding(8)
|
||||
.background(.quaternary, in: RoundedRectangle(cornerRadius: 8))
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
.frame(maxWidth: .infinity, alignment: .topLeading)
|
||||
.background(.background, in: RoundedRectangle(cornerRadius: 12))
|
||||
.overlay(RoundedRectangle(cornerRadius: 12).stroke(.separator, lineWidth: 1))
|
||||
}
|
||||
|
||||
// MARK: - Component Thermals Matrix Card
|
||||
private var componentThermalCard: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
Label("Chassis & Component Thermals", systemImage: "thermometer.medium")
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Text("\(store.componentTemps.count) Sensors")
|
||||
.font(.caption.bold())
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
|
||||
if store.componentTemps.isEmpty {
|
||||
Text("Awaiting component thermal probe...")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
} else {
|
||||
LazyVGrid(columns: [GridItem(.adaptive(minimum: 160))], spacing: 10) {
|
||||
ForEach(store.componentTemps) { item in
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(item.name)
|
||||
.font(.system(size: 11, weight: .semibold))
|
||||
.lineLimit(1)
|
||||
HStack {
|
||||
Text(item.category)
|
||||
.font(.system(size: 9))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Text(String(format: "%.1f°C", item.temperature))
|
||||
.font(.system(size: 11, weight: .bold, design: .monospaced))
|
||||
.foregroundStyle(item.temperature > 75 ? .red : .primary)
|
||||
}
|
||||
}
|
||||
.padding(8)
|
||||
.background(.quaternary, in: RoundedRectangle(cornerRadius: 8))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
@@ -149,6 +454,108 @@ public struct ContentView: View {
|
||||
.overlay(RoundedRectangle(cornerRadius: 12).stroke(.separator, lineWidth: 1))
|
||||
}
|
||||
|
||||
// MARK: - Storage Volumes Card
|
||||
private var storageCard: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
Label("Storage Volumes", systemImage: "internaldrive")
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
Text("\(store.storageVolumes.count) Mounted")
|
||||
.font(.caption.bold())
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
|
||||
if store.storageVolumes.isEmpty {
|
||||
Text("No mounted APFS/HFS volumes discovered.")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
} else {
|
||||
ForEach(store.storageVolumes) { vol in
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
HStack {
|
||||
Text(vol.volumeName).bold()
|
||||
Text("(\(vol.fileSystem))").font(.caption).foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Text("\(formatBytes(vol.usedBytes)) / \(formatBytes(vol.totalBytes))")
|
||||
.font(.caption.monospacedDigit())
|
||||
}
|
||||
ProgressView(value: min(vol.usedPercentage / 100.0, 1.0))
|
||||
.tint(vol.usedPercentage > 90 ? .red : .blue)
|
||||
HStack {
|
||||
Text("Mount: \(vol.mountPoint)").font(.system(size: 10)).foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Text(String(format: "%.1f%% Used", vol.usedPercentage)).font(.system(size: 10, weight: .bold))
|
||||
}
|
||||
}
|
||||
.padding(8)
|
||||
.background(.quaternary, in: RoundedRectangle(cornerRadius: 8))
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
.frame(maxWidth: .infinity, alignment: .topLeading)
|
||||
.background(.background, in: RoundedRectangle(cornerRadius: 12))
|
||||
.overlay(RoundedRectangle(cornerRadius: 12).stroke(.separator, lineWidth: 1))
|
||||
}
|
||||
|
||||
// MARK: - Power & Voltage Card
|
||||
private var powerCard: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
Label("Power & Voltage", systemImage: "bolt.fill")
|
||||
.font(.headline)
|
||||
Spacer()
|
||||
HStack(spacing: 4) {
|
||||
Image(systemName: store.power.powerSource.contains("Battery") ? "battery.75" : "powerplug.fill")
|
||||
Text(store.power.powerSource)
|
||||
}
|
||||
.font(.caption.bold())
|
||||
.foregroundStyle(.secondary)
|
||||
|
||||
Text(String(format: "%.1f W", store.power.systemTotalWatts))
|
||||
.font(.title3.bold().monospacedDigit())
|
||||
}
|
||||
|
||||
Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 6) {
|
||||
GridRow {
|
||||
Text("Total Draw:").foregroundStyle(.secondary)
|
||||
Text(String(format: "%.1f W", store.power.systemTotalWatts)).bold()
|
||||
Text("CPU Package:").foregroundStyle(.secondary)
|
||||
Text(String(format: "%.1f W", store.power.cpuWatts)).bold()
|
||||
}
|
||||
GridRow {
|
||||
Text("CPU Core Voltage:").foregroundStyle(.secondary)
|
||||
Text(store.power.cpuVoltage > 0 ? String(format: "%.3f V", store.power.cpuVoltage) : "N/A")
|
||||
Text("CPU Current:").foregroundStyle(.secondary)
|
||||
Text(store.power.cpuCurrent > 0 ? String(format: "%.2f A", store.power.cpuCurrent) : "N/A")
|
||||
}
|
||||
if store.power.gpuWatts > 0 || store.power.memoryWatts > 0 {
|
||||
GridRow {
|
||||
Text("GPU Draw:").foregroundStyle(.secondary)
|
||||
Text(String(format: "%.1f W", store.power.gpuWatts))
|
||||
Text("Memory Subsystem:").foregroundStyle(.secondary)
|
||||
Text(String(format: "%.1f W", store.power.memoryWatts))
|
||||
}
|
||||
}
|
||||
if store.power.powerSource.contains("Battery") {
|
||||
GridRow {
|
||||
Text("Battery Level:").foregroundStyle(.secondary)
|
||||
Text(String(format: "%.0f%% %@", store.power.batteryLevel, store.power.isCharging ? "(Charging)" : ""))
|
||||
Text("Status:").foregroundStyle(.secondary)
|
||||
Text(store.power.isCharging ? "Charging" : "Discharging")
|
||||
}
|
||||
}
|
||||
}
|
||||
.font(.caption)
|
||||
}
|
||||
.padding(16)
|
||||
.frame(maxWidth: .infinity, alignment: .topLeading)
|
||||
.background(.background, in: RoundedRectangle(cornerRadius: 12))
|
||||
.overlay(RoundedRectangle(cornerRadius: 12).stroke(.separator, lineWidth: 1))
|
||||
}
|
||||
|
||||
// MARK: - Hardware Specs Card
|
||||
private var specsCard: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
Text("Host Architecture & Kernel")
|
||||
@@ -180,6 +587,7 @@ public struct ContentView: View {
|
||||
.overlay(RoundedRectangle(cornerRadius: 12).stroke(.separator, lineWidth: 1))
|
||||
}
|
||||
|
||||
// MARK: - Providers Card
|
||||
private var providersCard: some View {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
HStack {
|
||||
@@ -195,33 +603,38 @@ public struct ContentView: View {
|
||||
.clipShape(Capsule())
|
||||
}
|
||||
|
||||
if store.latestSnapshot.isEmpty {
|
||||
HStack(spacing: 12) {
|
||||
Image(systemName: "info.circle")
|
||||
.foregroundStyle(.secondary)
|
||||
Text("Telemetry coordinator initialized. Awaiting provider metrics.")
|
||||
.font(.subheadline)
|
||||
ForEach(Array(store.latestSnapshot.keys.sorted()), id: \.self) { key in
|
||||
HStack {
|
||||
Image(systemName: "checkmark.circle.fill")
|
||||
.foregroundStyle(.green)
|
||||
Text(key)
|
||||
.font(.system(.body, design: .monospaced))
|
||||
Spacer()
|
||||
Text("\(store.latestSnapshot[key]?.count ?? 0) metrics")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.padding(.vertical, 8)
|
||||
} else {
|
||||
ForEach(Array(store.latestSnapshot.keys.sorted()), id: \.self) { key in
|
||||
HStack {
|
||||
Image(systemName: "checkmark.circle.fill")
|
||||
.foregroundStyle(.green)
|
||||
Text(key)
|
||||
.font(.system(.body, design: .monospaced))
|
||||
Spacer()
|
||||
Text("\(store.latestSnapshot[key]?.count ?? 0) metrics")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.padding(.vertical, 4)
|
||||
}
|
||||
.padding(.vertical, 4)
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
.background(.background, in: RoundedRectangle(cornerRadius: 12))
|
||||
.overlay(RoundedRectangle(cornerRadius: 12).stroke(.separator, lineWidth: 1))
|
||||
}
|
||||
|
||||
// MARK: - Formatting Helpers
|
||||
private func formatBytes(_ bytes: UInt64) -> String {
|
||||
let formatter = ByteCountFormatter()
|
||||
formatter.allowedUnits = [.useGB, .useMB]
|
||||
formatter.countStyle = .memory
|
||||
return formatter.string(fromByteCount: Int64(bytes))
|
||||
}
|
||||
|
||||
private func pressureColor(_ level: String) -> Color {
|
||||
switch level {
|
||||
case "Critical": return .red
|
||||
case "Warning": return .orange
|
||||
default: return .green
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
//
|
||||
// MMAudioTests.swift
|
||||
// MacMonitorTests
|
||||
//
|
||||
// Unit and integration tests for MMAudioTelemetryProvider.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMAudioTests: XCTestCase {
|
||||
var provider: MMAudioTelemetryProvider!
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
provider = MMAudioTelemetryProvider()
|
||||
}
|
||||
|
||||
override func tearDown() {
|
||||
provider = nil
|
||||
super.tearDown()
|
||||
}
|
||||
|
||||
func testDomainAndIdentifier() {
|
||||
XCTAssertEqual(provider.domain, .audio)
|
||||
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.audio")
|
||||
XCTAssertTrue(provider.isAvailable)
|
||||
}
|
||||
|
||||
func testSampleAudioDevicesLive() {
|
||||
do {
|
||||
let sample = try provider.sampleTelemetry()
|
||||
XCTAssertNotNil(sample)
|
||||
|
||||
let count = sample["deviceCount"] as? Int ?? 0
|
||||
XCTAssertGreaterThanOrEqual(count, 0)
|
||||
|
||||
let devices = sample["devices"] as? [[String: Any]] ?? []
|
||||
XCTAssertEqual(devices.count, count)
|
||||
|
||||
if count > 0 {
|
||||
for dev in devices {
|
||||
XCTAssertNotNil(dev["name"])
|
||||
XCTAssertNotNil(dev["deviceID"])
|
||||
XCTAssertNotNil(dev["isInput"])
|
||||
XCTAssertNotNil(dev["isOutput"])
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
XCTFail("sampleTelemetry threw error: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
func testAudioDeviceModel() {
|
||||
let dev = MMAudioDevice()
|
||||
dev.deviceID = 42
|
||||
dev.name = "External USB DAC"
|
||||
dev.manufacturer = "FiiO"
|
||||
dev.uid = "USB:1234"
|
||||
dev.isInput = false
|
||||
dev.isOutput = true
|
||||
dev.isDefaultOutput = true
|
||||
dev.isDefaultInput = false
|
||||
dev.sampleRate = 96000.0
|
||||
dev.channelCount = 2
|
||||
dev.volume = 0.75
|
||||
dev.isMuted = false
|
||||
|
||||
let dict = dev.toDictionary()
|
||||
XCTAssertEqual(dict["deviceID"] as? UInt32, 42)
|
||||
XCTAssertEqual(dict["name"] as? String, "External USB DAC")
|
||||
XCTAssertEqual(dict["manufacturer"] as? String, "FiiO")
|
||||
XCTAssertEqual(dict["isOutput"] as? Bool, true)
|
||||
XCTAssertEqual(dict["isDefaultOutput"] as? Bool, true)
|
||||
XCTAssertEqual(dict["sampleRate"] as? Double, 96000.0)
|
||||
XCTAssertEqual(dict["channelCount"] as? UInt32, 2)
|
||||
XCTAssertEqual(dict["volume"] as? Float, 0.75)
|
||||
XCTAssertEqual(dict["isMuted"] as? Bool, false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
//
|
||||
// MMBatteryTests.swift
|
||||
// MacMonitorTests
|
||||
//
|
||||
// Unit and integration tests for MMBatteryTelemetryProvider.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMBatteryTests: XCTestCase {
|
||||
var provider: MMBatteryTelemetryProvider!
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
provider = MMBatteryTelemetryProvider()
|
||||
}
|
||||
|
||||
override func tearDown() {
|
||||
provider = nil
|
||||
super.tearDown()
|
||||
}
|
||||
|
||||
func testDomainAndIdentifier() {
|
||||
XCTAssertEqual(provider.domain, .power)
|
||||
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.battery")
|
||||
}
|
||||
|
||||
func testCalculateBatteryHealthWithSimulatedNormalBattery() {
|
||||
let raw: [String: Any] = [
|
||||
"BatteryInstalled": true,
|
||||
"CycleCount": 250,
|
||||
"DesignCycleCount9C": 1000,
|
||||
"CurrentCapacity": 3000,
|
||||
"MaxCapacity": 4000,
|
||||
"DesignCapacity": 4400,
|
||||
"Temperature": 3150, // 31.5 C
|
||||
"Voltage": 11100, // 11.1 V
|
||||
"Amperage": -1500, // -1.5 A
|
||||
"IsCharging": false,
|
||||
"FullyCharged": false,
|
||||
"ExternalConnected": false,
|
||||
"TimeRemaining": 120,
|
||||
"Manufacturer": "SMP",
|
||||
"Serial": "TEST123456",
|
||||
"DeviceName": "bq20z451"
|
||||
]
|
||||
|
||||
let health = MMBatteryTelemetryProvider.calculateBatteryHealth(withProperties: raw)
|
||||
XCTAssertEqual(health["hasBattery"] as? Bool, true)
|
||||
XCTAssertEqual(health["installed"] as? Bool, true)
|
||||
XCTAssertEqual(health["healthCondition"] as? String, "Normal")
|
||||
|
||||
let healthPercent = (health["healthPercent"] as? Double) ?? 0.0
|
||||
XCTAssertEqual(healthPercent, 90.9, accuracy: 0.1)
|
||||
XCTAssertEqual(health["cycleCount"] as? Int, 250)
|
||||
XCTAssertEqual(health["designCycleCount"] as? Int, 1000)
|
||||
XCTAssertEqual(health["temperature"] as? Double, 31.5)
|
||||
let watts = (health["watts"] as? Double) ?? 0.0
|
||||
XCTAssertEqual(watts, 16.7, accuracy: 0.2)
|
||||
XCTAssertEqual(health["manufacturer"] as? String, "SMP")
|
||||
}
|
||||
|
||||
func testCalculateBatteryHealthWithServiceRecommended() {
|
||||
let raw: [String: Any] = [
|
||||
"BatteryInstalled": true,
|
||||
"CycleCount": 1100,
|
||||
"DesignCycleCount9C": 1000,
|
||||
"CurrentCapacity": 1500,
|
||||
"MaxCapacity": 2500,
|
||||
"DesignCapacity": 4400, // ~56.8% health
|
||||
"Temperature": 3200,
|
||||
"Voltage": 10800,
|
||||
"Amperage": -1000,
|
||||
"IsCharging": false,
|
||||
"FullyCharged": false,
|
||||
"ExternalConnected": false,
|
||||
"TimeRemaining": 90,
|
||||
"Manufacturer": "Apple"
|
||||
]
|
||||
|
||||
let health = MMBatteryTelemetryProvider.calculateBatteryHealth(withProperties: raw)
|
||||
XCTAssertEqual(health["healthCondition"] as? String, "Service Recommended")
|
||||
let healthPercent = (health["healthPercent"] as? Double) ?? 0.0
|
||||
XCTAssertLessThan(healthPercent, 70.0)
|
||||
}
|
||||
|
||||
func testCalculateBatteryHealthWithNil() {
|
||||
let health = MMBatteryTelemetryProvider.calculateBatteryHealth(withProperties: nil)
|
||||
XCTAssertEqual(health["hasBattery"] as? Bool, false)
|
||||
XCTAssertEqual(health["installed"] as? Bool, false)
|
||||
XCTAssertEqual(health["healthCondition"] as? String, "No Battery")
|
||||
}
|
||||
|
||||
func testLiveSampleBattery() {
|
||||
do {
|
||||
let sample = try provider.sampleTelemetry()
|
||||
XCTAssertNotNil(sample)
|
||||
if provider.hasBattery {
|
||||
XCTAssertEqual(sample["hasBattery"] as? Bool, true)
|
||||
XCTAssertNotNil(sample["cycleCount"])
|
||||
XCTAssertNotNil(sample["healthPercent"])
|
||||
XCTAssertNotNil(sample["healthCondition"])
|
||||
}
|
||||
} catch {
|
||||
XCTFail("sampleTelemetry threw error: \(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMComponentThermalTests: XCTestCase {
|
||||
|
||||
func testCategoryClassification() {
|
||||
XCTAssertEqual(MMComponentThermalProvider.category(forKey: "TPCD"), "PCH / Chipset")
|
||||
XCTAssertEqual(MMComponentThermalProvider.category(forKey: "TP0P"), "PCH / Chipset")
|
||||
XCTAssertEqual(MMComponentThermalProvider.category(forKey: "Th0H"), "Heatsink")
|
||||
XCTAssertEqual(MMComponentThermalProvider.category(forKey: "Th1H"), "Heatsink")
|
||||
XCTAssertEqual(MMComponentThermalProvider.category(forKey: "TM0P"), "Memory")
|
||||
XCTAssertEqual(MMComponentThermalProvider.category(forKey: "TM1S"), "Memory")
|
||||
XCTAssertEqual(MMComponentThermalProvider.category(forKey: "Tp0P"), "Power Supply")
|
||||
XCTAssertEqual(MMComponentThermalProvider.category(forKey: "TA0P"), "Ambient / Enclosure")
|
||||
XCTAssertEqual(MMComponentThermalProvider.category(forKey: "TTLD"), "Thunderbolt / IO")
|
||||
XCTAssertEqual(MMComponentThermalProvider.category(forKey: "TB0T"), "Thunderbolt / IO")
|
||||
XCTAssertEqual(MMComponentThermalProvider.category(forKey: "ZZ99"), "Other")
|
||||
}
|
||||
|
||||
func testHumanReadableNames() {
|
||||
XCTAssertEqual(MMComponentThermalProvider.humanReadableName(forKey: "TPCD"), "Platform Controller Hub (Die)")
|
||||
XCTAssertEqual(MMComponentThermalProvider.humanReadableName(forKey: "Th0H"), "Main Heatsink A")
|
||||
XCTAssertEqual(MMComponentThermalProvider.humanReadableName(forKey: "TA0P"), "Ambient Air Intake")
|
||||
XCTAssertEqual(MMComponentThermalProvider.humanReadableName(forKey: "CUSTOM"), "CUSTOM")
|
||||
}
|
||||
|
||||
func testComponentMetricsCalculation() {
|
||||
let readings: [String: NSNumber] = [
|
||||
"TPCD": NSNumber(value: 65.5),
|
||||
"Th0H": NSNumber(value: 48.0),
|
||||
"TM0P": NSNumber(value: 42.0),
|
||||
"TA0P": NSNumber(value: 28.5)
|
||||
]
|
||||
|
||||
let metrics = MMComponentThermalProvider.calculateComponentMetrics(from: readings)
|
||||
|
||||
let peak = metrics["peakTemperature"] as? Double ?? 0
|
||||
let avg = metrics["averageTemperature"] as? Double ?? 0
|
||||
let count = metrics["sensorCount"] as? Int ?? 0
|
||||
let components = metrics["components"] as? [[String: Any]] ?? []
|
||||
let categorized = metrics["categorized"] as? [String: [[String: Any]]] ?? [:]
|
||||
|
||||
XCTAssertEqual(peak, 65.5, accuracy: 0.1)
|
||||
XCTAssertEqual(avg, (65.5 + 48.0 + 42.0 + 28.5) / 4.0, accuracy: 0.1)
|
||||
XCTAssertEqual(count, 4)
|
||||
XCTAssertEqual(components.count, 4)
|
||||
|
||||
let pchList = categorized["PCH / Chipset"]
|
||||
XCTAssertNotNil(pchList)
|
||||
let firstPchName = pchList?.first?["name"] as? String
|
||||
XCTAssertEqual(firstPchName, "Platform Controller Hub (Die)")
|
||||
XCTAssertEqual(categorized["Heatsink"]?.count, 1)
|
||||
XCTAssertEqual(categorized["Memory"]?.count, 1)
|
||||
XCTAssertEqual(categorized["Ambient / Enclosure"]?.count, 1)
|
||||
}
|
||||
|
||||
func testEmptyReadingsCalculation() {
|
||||
let metrics = MMComponentThermalProvider.calculateComponentMetrics(from: [:])
|
||||
|
||||
let peak = metrics["peakTemperature"] as? Double ?? -1
|
||||
let avg = metrics["averageTemperature"] as? Double ?? -1
|
||||
let count = metrics["sensorCount"] as? Int ?? -1
|
||||
|
||||
XCTAssertEqual(peak, 0.0)
|
||||
XCTAssertEqual(avg, 0.0)
|
||||
XCTAssertEqual(count, 0)
|
||||
}
|
||||
|
||||
func testLiveComponentThermalProvider() throws {
|
||||
let provider = MMComponentThermalProvider()
|
||||
XCTAssertEqual(provider.domain, .thermal)
|
||||
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.thermal.components")
|
||||
|
||||
let sample = try provider.sampleTelemetry()
|
||||
XCTAssertNotNil(sample)
|
||||
XCTAssertNotNil(sample["sensorCount"])
|
||||
XCTAssertNotNil(sample["components"])
|
||||
XCTAssertNotNil(sample["categorized"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMDiskIOTests: XCTestCase {
|
||||
|
||||
func testDiskIOMetricsCalculation() {
|
||||
let prev: [String: [String: NSNumber]] = [
|
||||
"disk0": [
|
||||
"readBytes": NSNumber(value: 10_000_000),
|
||||
"writeBytes": NSNumber(value: 5_000_000),
|
||||
"readOps": NSNumber(value: 1_000),
|
||||
"writeOps": NSNumber(value: 500)
|
||||
],
|
||||
"disk1": [
|
||||
"readBytes": NSNumber(value: 2_000_000),
|
||||
"writeBytes": NSNumber(value: 1_000_000),
|
||||
"readOps": NSNumber(value: 200),
|
||||
"writeOps": NSNumber(value: 100)
|
||||
]
|
||||
]
|
||||
|
||||
let curr: [String: [String: NSNumber]] = [
|
||||
"disk0": [
|
||||
"readBytes": NSNumber(value: 20_000_000), // delta = 10,000,000 bytes
|
||||
"writeBytes": NSNumber(value: 7_000_000), // delta = 2,000,000 bytes
|
||||
"readOps": NSNumber(value: 1_200), // delta = 200 ops
|
||||
"writeOps": NSNumber(value: 600) // delta = 100 ops
|
||||
],
|
||||
"disk1": [
|
||||
"readBytes": NSNumber(value: 4_000_000), // delta = 2,000,000 bytes
|
||||
"writeBytes": NSNumber(value: 1_000_000), // delta = 0
|
||||
"readOps": NSNumber(value: 250), // delta = 50 ops
|
||||
"writeOps": NSNumber(value: 100) // delta = 0 ops
|
||||
]
|
||||
]
|
||||
|
||||
let timeDelta: TimeInterval = 2.0 // 2 seconds
|
||||
|
||||
let metrics = MMDiskIOProvider.calculateDiskIOMetrics(
|
||||
withCurrentSnapshots: curr,
|
||||
previousSnapshots: prev,
|
||||
timeDelta: timeDelta
|
||||
)
|
||||
|
||||
let totalReadBps = metrics["totalReadBytesPerSec"] as? Double ?? 0
|
||||
let totalWriteBps = metrics["totalWriteBytesPerSec"] as? Double ?? 0
|
||||
let totalReadIOPS = metrics["totalReadIOPS"] as? Double ?? 0
|
||||
let totalWriteIOPS = metrics["totalWriteIOPS"] as? Double ?? 0
|
||||
let disks = metrics["disks"] as? [[String: Any]] ?? []
|
||||
|
||||
// (10MB + 2MB) / 2s = 6,000,000 B/s
|
||||
XCTAssertEqual(totalReadBps, 6_000_000.0, accuracy: 1.0)
|
||||
// (2MB + 0) / 2s = 1,000,000 B/s
|
||||
XCTAssertEqual(totalWriteBps, 1_000_000.0, accuracy: 1.0)
|
||||
// (200 + 50) / 2s = 125 IOPS
|
||||
XCTAssertEqual(totalReadIOPS, 125.0, accuracy: 0.1)
|
||||
// (100 + 0) / 2s = 50 IOPS
|
||||
XCTAssertEqual(totalWriteIOPS, 50.0, accuracy: 0.1)
|
||||
XCTAssertEqual(disks.count, 2)
|
||||
}
|
||||
|
||||
func testLiveDiskIOProvider() throws {
|
||||
let provider = MMDiskIOProvider()
|
||||
XCTAssertEqual(provider.domain, .storage)
|
||||
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.storage.io")
|
||||
|
||||
let sample = try provider.sampleTelemetry()
|
||||
XCTAssertNotNil(sample)
|
||||
XCTAssertNotNil(sample["totalReadBytesPerSec"])
|
||||
XCTAssertNotNil(sample["totalWriteBytesPerSec"])
|
||||
XCTAssertNotNil(sample["disks"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMGPUTests: XCTestCase {
|
||||
|
||||
func testGPUMetricsCalculation() {
|
||||
let mockGPUs: [[String: Any]] = [
|
||||
[
|
||||
"name": "Intel Iris Plus Graphics 655",
|
||||
"type": "Integrated",
|
||||
"utilization": 15.0,
|
||||
"vramUsedBytes": 500_000_000,
|
||||
"vramTotalBytes": 1_500_000_000,
|
||||
"temperature": 45.0,
|
||||
"isLowPower": true,
|
||||
"isRemovable": false
|
||||
],
|
||||
[
|
||||
"name": "AMD Radeon Pro 560X",
|
||||
"type": "Discrete",
|
||||
"utilization": 75.0,
|
||||
"vramUsedBytes": 3_000_000_000,
|
||||
"vramTotalBytes": 4_000_000_000,
|
||||
"temperature": 68.0,
|
||||
"isLowPower": false,
|
||||
"isRemovable": false
|
||||
]
|
||||
]
|
||||
|
||||
let metrics = MMGPUTelemetryProvider.calculateGPUMetrics(withDevices: mockGPUs)
|
||||
|
||||
let count = metrics["gpuCount"] as? Int ?? 0
|
||||
let avg = metrics["averageUtilization"] as? Double ?? 0
|
||||
let peak = metrics["peakUtilization"] as? Double ?? 0
|
||||
let active = metrics["activeGPUName"] as? String ?? ""
|
||||
|
||||
XCTAssertEqual(count, 2)
|
||||
XCTAssertEqual(avg, 45.0, accuracy: 0.1)
|
||||
XCTAssertEqual(peak, 75.0, accuracy: 0.1)
|
||||
XCTAssertEqual(active, "AMD Radeon Pro 560X")
|
||||
}
|
||||
|
||||
func testLiveGPUProvider() throws {
|
||||
let provider = MMGPUTelemetryProvider()
|
||||
XCTAssertEqual(provider.domain, .gpu)
|
||||
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.gpu")
|
||||
|
||||
let sample = try provider.sampleTelemetry()
|
||||
XCTAssertNotNil(sample)
|
||||
XCTAssertNotNil(sample["gpuCount"])
|
||||
XCTAssertNotNil(sample["devices"])
|
||||
XCTAssertNotNil(sample["activeGPUName"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMKernelTelemetryTests: XCTestCase {
|
||||
|
||||
func testKernelRatesCalculation() {
|
||||
let prev: [String: NSNumber] = [
|
||||
"contextSwitches": NSNumber(value: 100_000),
|
||||
"syscalls": NSNumber(value: 200_000),
|
||||
"pageFaults": NSNumber(value: 50_000),
|
||||
"cowFaults": NSNumber(value: 1_000),
|
||||
"zeroFills": NSNumber(value: 10_000),
|
||||
"pageins": NSNumber(value: 500),
|
||||
"pageouts": NSNumber(value: 100),
|
||||
"decompressions": NSNumber(value: 200),
|
||||
"compressions": NSNumber(value: 300)
|
||||
]
|
||||
|
||||
let curr: [String: NSNumber] = [
|
||||
"contextSwitches": NSNumber(value: 102_500), // delta = 2,500
|
||||
"syscalls": NSNumber(value: 210_000), // delta = 10,000
|
||||
"pageFaults": NSNumber(value: 51_000), // delta = 1,000
|
||||
"cowFaults": NSNumber(value: 1_050), // delta = 50
|
||||
"zeroFills": NSNumber(value: 10_200), // delta = 200
|
||||
"pageins": NSNumber(value: 520), // delta = 20
|
||||
"pageouts": NSNumber(value: 105), // delta = 5
|
||||
"decompressions": NSNumber(value: 210), // delta = 10
|
||||
"compressions": NSNumber(value: 315) // delta = 15
|
||||
]
|
||||
|
||||
let timeDelta: TimeInterval = 2.0 // 2 seconds
|
||||
|
||||
let rates = MMKernelTelemetryProvider.calculateRates(
|
||||
withCurrentCounters: curr,
|
||||
previousCounters: prev,
|
||||
timeDelta: timeDelta
|
||||
)
|
||||
|
||||
let cswRate = rates["contextSwitchesRate"] as? Double ?? 0
|
||||
let syscallRate = rates["syscallsRate"] as? Double ?? 0
|
||||
let faultRate = rates["pageFaultsRate"] as? Double ?? 0
|
||||
let cowRate = rates["cowFaultsRate"] as? Double ?? 0
|
||||
let zeroFillRate = rates["zeroFillsRate"] as? Double ?? 0
|
||||
let pageinsRate = rates["pageinsRate"] as? Double ?? 0
|
||||
|
||||
XCTAssertEqual(cswRate, 1250.0, accuracy: 0.1)
|
||||
XCTAssertEqual(syscallRate, 5000.0, accuracy: 0.1)
|
||||
XCTAssertEqual(faultRate, 500.0, accuracy: 0.1)
|
||||
XCTAssertEqual(cowRate, 25.0, accuracy: 0.1)
|
||||
XCTAssertEqual(zeroFillRate, 100.0, accuracy: 0.1)
|
||||
XCTAssertEqual(pageinsRate, 10.0, accuracy: 0.1)
|
||||
|
||||
let cumCSW = rates["cumulative_contextSwitches"] as? UInt64 ?? 0
|
||||
XCTAssertEqual(cumCSW, 102_500)
|
||||
}
|
||||
|
||||
func testLiveKernelProvider() throws {
|
||||
let provider = MMKernelTelemetryProvider()
|
||||
XCTAssertEqual(provider.domain, .system)
|
||||
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.kernel.counters")
|
||||
|
||||
let sample = try provider.sampleTelemetry()
|
||||
XCTAssertNotNil(sample)
|
||||
XCTAssertNotNil(sample["cumulative_contextSwitches"])
|
||||
XCTAssertNotNil(sample["cumulative_syscalls"])
|
||||
XCTAssertNotNil(sample["cumulative_pageFaults"])
|
||||
XCTAssertNotNil(sample["contextSwitchesRate"])
|
||||
XCTAssertNotNil(sample["syscallsRate"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMLoadAverageTests: XCTestCase {
|
||||
|
||||
func testLoadMetricsCalculation() {
|
||||
let metrics = MMLoadAverageProvider.calculateLoadMetrics(
|
||||
withLoad1: 4.0,
|
||||
load5: 3.5,
|
||||
load15: 2.5,
|
||||
taskCount: 500,
|
||||
threadCount: 2200,
|
||||
cpuCount: 8,
|
||||
machFactor: 1.25
|
||||
)
|
||||
|
||||
let load1 = metrics["load1m"] as? Double ?? 0
|
||||
let norm1 = metrics["normalizedLoad1m"] as? Double ?? 0
|
||||
let norm5 = metrics["normalizedLoad5m"] as? Double ?? 0
|
||||
let taskCount = metrics["taskCount"] as? Int ?? 0
|
||||
let threadCount = metrics["threadCount"] as? Int ?? 0
|
||||
let isOverloaded = metrics["isOverloaded"] as? Bool ?? true
|
||||
|
||||
XCTAssertEqual(load1, 4.0, accuracy: 0.01)
|
||||
XCTAssertEqual(norm1, 4.0 / 8.0, accuracy: 0.01)
|
||||
XCTAssertEqual(norm5, 3.5 / 8.0, accuracy: 0.01)
|
||||
XCTAssertEqual(taskCount, 500)
|
||||
XCTAssertEqual(threadCount, 2200)
|
||||
XCTAssertFalse(isOverloaded)
|
||||
}
|
||||
|
||||
func testOverloadedStateDetection() {
|
||||
let metrics = MMLoadAverageProvider.calculateLoadMetrics(
|
||||
withLoad1: 12.0,
|
||||
load5: 10.0,
|
||||
load15: 8.0,
|
||||
taskCount: 650,
|
||||
threadCount: 3100,
|
||||
cpuCount: 8,
|
||||
machFactor: 0.4
|
||||
)
|
||||
|
||||
let isOverloaded = metrics["isOverloaded"] as? Bool ?? false
|
||||
let norm1 = metrics["normalizedLoad1m"] as? Double ?? 0
|
||||
|
||||
XCTAssertTrue(isOverloaded)
|
||||
XCTAssertEqual(norm1, 1.5, accuracy: 0.01)
|
||||
}
|
||||
|
||||
func testLiveLoadAverageProvider() throws {
|
||||
let provider = MMLoadAverageProvider()
|
||||
XCTAssertEqual(provider.domain, .system)
|
||||
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.system.load")
|
||||
|
||||
let sample = try provider.sampleTelemetry()
|
||||
XCTAssertNotNil(sample)
|
||||
XCTAssertNotNil(sample["load1m"])
|
||||
XCTAssertNotNil(sample["taskCount"])
|
||||
XCTAssertNotNil(sample["threadCount"])
|
||||
XCTAssertNotNil(sample["normalizedLoad1m"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMNetworkBandwidthTests: XCTestCase {
|
||||
|
||||
func testNetworkBandwidthCalculation() {
|
||||
let prev: [String: [String: NSNumber]] = [
|
||||
"en0": [
|
||||
"inBytes": NSNumber(value: 50_000_000),
|
||||
"outBytes": NSNumber(value: 10_000_000),
|
||||
"inPackets": NSNumber(value: 40_000),
|
||||
"outPackets": NSNumber(value: 20_000),
|
||||
"inErrors": NSNumber(value: 0),
|
||||
"outErrors": NSNumber(value: 0)
|
||||
],
|
||||
"lo0": [
|
||||
"inBytes": NSNumber(value: 5_000_000),
|
||||
"outBytes": NSNumber(value: 5_000_000),
|
||||
"inPackets": NSNumber(value: 5_000),
|
||||
"outPackets": NSNumber(value: 5_000),
|
||||
"inErrors": NSNumber(value: 0),
|
||||
"outErrors": NSNumber(value: 0)
|
||||
]
|
||||
]
|
||||
|
||||
let curr: [String: [String: NSNumber]] = [
|
||||
"en0": [
|
||||
"inBytes": NSNumber(value: 60_000_000), // delta in = 10,000,000 bytes
|
||||
"outBytes": NSNumber(value: 12_000_000), // delta out = 2,000,000 bytes
|
||||
"inPackets": NSNumber(value: 48_000), // delta in = 8,000 pkts
|
||||
"outPackets": NSNumber(value: 24_000), // delta out = 4,000 pkts
|
||||
"inErrors": NSNumber(value: 0),
|
||||
"outErrors": NSNumber(value: 0)
|
||||
],
|
||||
"lo0": [
|
||||
"inBytes": NSNumber(value: 7_000_000),
|
||||
"outBytes": NSNumber(value: 7_000_000),
|
||||
"inPackets": NSNumber(value: 7_000),
|
||||
"outPackets": NSNumber(value: 7_000),
|
||||
"inErrors": NSNumber(value: 0),
|
||||
"outErrors": NSNumber(value: 0)
|
||||
]
|
||||
]
|
||||
|
||||
let timeDelta: TimeInterval = 2.0 // 2 seconds
|
||||
let ipDict: [String: String] = ["en0": "192.168.1.100", "lo0": "127.0.0.1"]
|
||||
|
||||
let metrics = MMNetworkBandwidthProvider.calculateBandwidthMetrics(
|
||||
withCurrentSnapshots: curr,
|
||||
previousSnapshots: prev,
|
||||
timeDelta: timeDelta,
|
||||
ipAddresses: ipDict
|
||||
)
|
||||
|
||||
let totalDownBps = metrics["totalDownloadBytesPerSec"] as? Double ?? 0
|
||||
let totalUpBps = metrics["totalUploadBytesPerSec"] as? Double ?? 0
|
||||
let totalDownPps = metrics["totalDownloadPacketsPerSec"] as? Double ?? 0
|
||||
let totalUpPps = metrics["totalUploadPacketsPerSec"] as? Double ?? 0
|
||||
let primary = metrics["primaryInterface"] as? String ?? ""
|
||||
let interfaces = metrics["interfaces"] as? [[String: Any]] ?? []
|
||||
|
||||
// en0 delta in = 10MB / 2s = 5,000,000 B/s (lo0 is excluded from total)
|
||||
XCTAssertEqual(totalDownBps, 5_000_000.0, accuracy: 1.0)
|
||||
// en0 delta out = 2MB / 2s = 1,000,000 B/s
|
||||
XCTAssertEqual(totalUpBps, 1_000_000.0, accuracy: 1.0)
|
||||
// en0 delta in pkts = 8,000 / 2s = 4,000 pps
|
||||
XCTAssertEqual(totalDownPps, 4000.0, accuracy: 0.1)
|
||||
// en0 delta out pkts = 4,000 / 2s = 2,000 pps
|
||||
XCTAssertEqual(totalUpPps, 2000.0, accuracy: 0.1)
|
||||
XCTAssertEqual(primary, "en0")
|
||||
XCTAssertEqual(interfaces.count, 2)
|
||||
}
|
||||
|
||||
func testLiveNetworkBandwidthProvider() throws {
|
||||
let provider = MMNetworkBandwidthProvider()
|
||||
XCTAssertEqual(provider.domain, .network)
|
||||
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.network.bandwidth")
|
||||
|
||||
let sample = try provider.sampleTelemetry()
|
||||
XCTAssertNotNil(sample)
|
||||
XCTAssertNotNil(sample["totalDownloadBytesPerSec"])
|
||||
XCTAssertNotNil(sample["totalUploadBytesPerSec"])
|
||||
XCTAssertNotNil(sample["interfaces"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMNetworkSocketsTests: XCTestCase {
|
||||
|
||||
func testSocketSummaryCalculation() {
|
||||
let testSockets: [[String: Any]] = [
|
||||
[
|
||||
"pid": 100,
|
||||
"processName": "web_server",
|
||||
"protocol": "TCP",
|
||||
"family": "IPv4",
|
||||
"localAddress": "0.0.0.0",
|
||||
"localPort": 8080,
|
||||
"remoteAddress": "0.0.0.0",
|
||||
"remotePort": 0,
|
||||
"state": "LISTEN"
|
||||
],
|
||||
[
|
||||
"pid": 200,
|
||||
"processName": "browser",
|
||||
"protocol": "TCP",
|
||||
"family": "IPv4",
|
||||
"localAddress": "192.168.1.50",
|
||||
"localPort": 54321,
|
||||
"remoteAddress": "142.250.190.46",
|
||||
"remotePort": 443,
|
||||
"state": "ESTABLISHED"
|
||||
],
|
||||
[
|
||||
"pid": 300,
|
||||
"processName": "dns_daemon",
|
||||
"protocol": "UDP",
|
||||
"family": "IPv4",
|
||||
"localAddress": "0.0.0.0",
|
||||
"localPort": 53,
|
||||
"remoteAddress": "0.0.0.0",
|
||||
"remotePort": 0,
|
||||
"state": "NONE"
|
||||
]
|
||||
]
|
||||
|
||||
let summary = MMNetworkSocketsProvider.calculateSocketSummary(withSocketList: testSockets)
|
||||
|
||||
let total = summary["socketCount"] as? Int ?? 0
|
||||
let tcp = summary["tcpCount"] as? Int ?? 0
|
||||
let udp = summary["udpCount"] as? Int ?? 0
|
||||
let listen = summary["listenCount"] as? Int ?? 0
|
||||
let established = summary["establishedCount"] as? Int ?? 0
|
||||
|
||||
XCTAssertEqual(total, 3)
|
||||
XCTAssertEqual(tcp, 2)
|
||||
XCTAssertEqual(udp, 1)
|
||||
XCTAssertEqual(listen, 1)
|
||||
XCTAssertEqual(established, 1)
|
||||
}
|
||||
|
||||
func testLiveNetworkSocketsProvider() throws {
|
||||
let provider = MMNetworkSocketsProvider()
|
||||
XCTAssertEqual(provider.domain, .network)
|
||||
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.network.sockets")
|
||||
|
||||
let sample = try provider.sampleTelemetry()
|
||||
XCTAssertNotNil(sample)
|
||||
XCTAssertNotNil(sample["socketCount"])
|
||||
XCTAssertNotNil(sample["sockets"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//
|
||||
// MMPeripheralsTests.swift
|
||||
// MacMonitorTests
|
||||
//
|
||||
// Unit and integration tests for MMPeripheralsProvider.
|
||||
//
|
||||
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMPeripheralsTests: XCTestCase {
|
||||
var provider: MMPeripheralsProvider!
|
||||
|
||||
override func setUp() {
|
||||
super.setUp()
|
||||
provider = MMPeripheralsProvider()
|
||||
}
|
||||
|
||||
override func tearDown() {
|
||||
provider = nil
|
||||
super.tearDown()
|
||||
}
|
||||
|
||||
func testDomainAndIdentifier() {
|
||||
XCTAssertEqual(provider.domain, .peripherals)
|
||||
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.peripherals")
|
||||
XCTAssertTrue(provider.isAvailable)
|
||||
}
|
||||
|
||||
func testSamplePeripheralsLive() {
|
||||
do {
|
||||
let sample = try provider.sampleTelemetry()
|
||||
XCTAssertNotNil(sample)
|
||||
|
||||
let total = sample["totalDeviceCount"] as? Int ?? 0
|
||||
XCTAssertGreaterThan(total, 0, "Host system should have at least 1 PCI/USB device")
|
||||
|
||||
let pci = sample["pciDevices"] as? [[String: Any]] ?? []
|
||||
XCTAssertGreaterThan(pci.count, 0, "Intel Mac should have PCI devices (host bridge, GPU, etc.)")
|
||||
|
||||
if let firstPCI = pci.first {
|
||||
XCTAssertNotNil(firstPCI["name"])
|
||||
XCTAssertEqual(firstPCI["busType"] as? String, "PCI")
|
||||
}
|
||||
|
||||
let usb = sample["usbDevices"] as? [[String: Any]] ?? []
|
||||
for dev in usb {
|
||||
XCTAssertEqual(dev["busType"] as? String, "USB")
|
||||
XCTAssertNotNil(dev["name"])
|
||||
}
|
||||
} catch {
|
||||
XCTFail("sampleTelemetry threw error: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
func testPeripheralDeviceModel() {
|
||||
let dev = MMPeripheralDevice()
|
||||
dev.name = "Magic Trackpad"
|
||||
dev.busType = .USB
|
||||
dev.vendorName = "Apple Inc."
|
||||
dev.vendorID = 0x05ac
|
||||
dev.productID = 0x0265
|
||||
dev.isBuiltIn = false
|
||||
|
||||
let dict = dev.toDictionary()
|
||||
XCTAssertEqual(dict["name"] as? String, "Magic Trackpad")
|
||||
XCTAssertEqual(dict["busType"] as? String, "USB")
|
||||
XCTAssertEqual(dict["vendorName"] as? String, "Apple Inc.")
|
||||
XCTAssertEqual(dict["vendorID"] as? UInt32, 0x05ac)
|
||||
XCTAssertEqual(dict["productID"] as? UInt32, 0x0265)
|
||||
XCTAssertEqual(dict["isBuiltIn"] as? Bool, false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMPowerTests: XCTestCase {
|
||||
|
||||
func testUnitsAndNames() {
|
||||
XCTAssertEqual(MMPowerTelemetryProvider.unit(forKey: "PSTR"), "W")
|
||||
XCTAssertEqual(MMPowerTelemetryProvider.unit(forKey: "VC0C"), "V")
|
||||
XCTAssertEqual(MMPowerTelemetryProvider.unit(forKey: "IC0C"), "A")
|
||||
XCTAssertEqual(MMPowerTelemetryProvider.unit(forKey: "UNKNOWN"), "")
|
||||
|
||||
XCTAssertEqual(MMPowerTelemetryProvider.humanReadableName(forKey: "PSTR"), "Total System Power")
|
||||
XCTAssertEqual(MMPowerTelemetryProvider.humanReadableName(forKey: "VC0C"), "CPU Core Voltage")
|
||||
XCTAssertEqual(MMPowerTelemetryProvider.humanReadableName(forKey: "IC0C"), "CPU Core Current")
|
||||
}
|
||||
|
||||
func testPowerMetricsCalculationFromSMC() {
|
||||
let readings: [String: NSNumber] = [
|
||||
"PSTR": NSNumber(value: 45.2),
|
||||
"PCPR": NSNumber(value: 28.4),
|
||||
"PG0R": NSNumber(value: 8.5),
|
||||
"PMSR": NSNumber(value: 3.1),
|
||||
"VC0C": NSNumber(value: 1.15),
|
||||
"IC0C": NSNumber(value: 24.5)
|
||||
]
|
||||
|
||||
let batteryInfo: [String: Any] = [
|
||||
"powerSource": "AC Power",
|
||||
"isCharging": false,
|
||||
"batteryLevel": 100.0,
|
||||
"batteryWatts": 0.0
|
||||
]
|
||||
|
||||
let metrics = MMPowerTelemetryProvider.calculatePowerMetrics(
|
||||
withReadings: readings,
|
||||
batteryInfo: batteryInfo
|
||||
)
|
||||
|
||||
let systemWatts = metrics["systemTotalWatts"] as? Double ?? 0
|
||||
let cpuWatts = metrics["cpuWatts"] as? Double ?? 0
|
||||
let gpuWatts = metrics["gpuWatts"] as? Double ?? 0
|
||||
let memWatts = metrics["memoryWatts"] as? Double ?? 0
|
||||
let cpuV = metrics["cpuVoltage"] as? Double ?? 0
|
||||
let cpuI = metrics["cpuCurrent"] as? Double ?? 0
|
||||
let powerSource = metrics["powerSource"] as? String ?? ""
|
||||
let sensors = metrics["sensors"] as? [[String: Any]] ?? []
|
||||
|
||||
XCTAssertEqual(systemWatts, 45.2, accuracy: 0.1)
|
||||
XCTAssertEqual(cpuWatts, 28.4, accuracy: 0.1)
|
||||
XCTAssertEqual(gpuWatts, 8.5, accuracy: 0.1)
|
||||
XCTAssertEqual(memWatts, 3.1, accuracy: 0.1)
|
||||
XCTAssertEqual(cpuV, 1.15, accuracy: 0.01)
|
||||
XCTAssertEqual(cpuI, 24.5, accuracy: 0.1)
|
||||
XCTAssertEqual(powerSource, "AC Power")
|
||||
XCTAssertEqual(sensors.count, 6)
|
||||
}
|
||||
|
||||
func testBatteryFallbackCalculation() {
|
||||
// No PSTR, no PCPR, but VC0C and IC0C are present
|
||||
let readings: [String: NSNumber] = [
|
||||
"VC0C": NSNumber(value: 1.2),
|
||||
"IC0C": NSNumber(value: 10.0)
|
||||
]
|
||||
|
||||
let batteryInfo: [String: Any] = [
|
||||
"powerSource": "Battery Power",
|
||||
"isCharging": false,
|
||||
"batteryLevel": 75.0,
|
||||
"batteryWatts": 18.5
|
||||
]
|
||||
|
||||
let metrics = MMPowerTelemetryProvider.calculatePowerMetrics(
|
||||
withReadings: readings,
|
||||
batteryInfo: batteryInfo
|
||||
)
|
||||
|
||||
let systemWatts = metrics["systemTotalWatts"] as? Double ?? 0
|
||||
let cpuWatts = metrics["cpuWatts"] as? Double ?? 0
|
||||
let powerSource = metrics["powerSource"] as? String ?? ""
|
||||
let isCharging = metrics["isCharging"] as? Bool ?? true
|
||||
|
||||
// System watts falls back to batteryWatts (18.5)
|
||||
XCTAssertEqual(systemWatts, 18.5, accuracy: 0.1)
|
||||
// CPU watts calculated from V * I = 1.2 * 10.0 = 12.0 W
|
||||
XCTAssertEqual(cpuWatts, 12.0, accuracy: 0.1)
|
||||
XCTAssertEqual(powerSource, "Battery Power")
|
||||
XCTAssertFalse(isCharging)
|
||||
}
|
||||
|
||||
func testLivePowerProvider() throws {
|
||||
let provider = MMPowerTelemetryProvider()
|
||||
XCTAssertEqual(provider.domain, .power)
|
||||
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.power")
|
||||
|
||||
let sample = try provider.sampleTelemetry()
|
||||
XCTAssertNotNil(sample)
|
||||
XCTAssertNotNil(sample["systemTotalWatts"])
|
||||
XCTAssertNotNil(sample["powerSource"])
|
||||
XCTAssertNotNil(sample["sensors"])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMProcessDetailsTests: XCTestCase {
|
||||
|
||||
func testInspectionSummaryCalculation() {
|
||||
let mockThreads: [[String: Any]] = [
|
||||
["threadId": 1, "state": "Running"],
|
||||
["threadId": 2, "state": "Waiting"]
|
||||
]
|
||||
|
||||
let mockFDs: [[String: Any]] = [
|
||||
["fd": 0, "type": "File", "path": "/dev/null"],
|
||||
["fd": 1, "type": "File", "path": "/tmp/test.log"],
|
||||
["fd": 3, "type": "Socket", "path": "TCP 127.0.0.1:80 -> 127.0.0.1:50000"]
|
||||
]
|
||||
|
||||
let mockSockets: [[String: Any]] = [
|
||||
["fd": 3, "protocol": "TCP", "localAddress": "127.0.0.1", "localPort": 80, "state": "LISTEN"]
|
||||
]
|
||||
|
||||
let summary = MMProcessDetailInspector.summarizeInspectionResults(
|
||||
withPID: 1234,
|
||||
threads: mockThreads,
|
||||
fds: mockFDs,
|
||||
sockets: mockSockets
|
||||
)
|
||||
|
||||
let pid = summary["pid"] as? Int ?? 0
|
||||
let threadCount = summary["threadCount"] as? Int ?? 0
|
||||
let openFDCount = summary["openFDCount"] as? Int ?? 0
|
||||
let socketCount = summary["socketCount"] as? Int ?? 0
|
||||
|
||||
XCTAssertEqual(pid, 1234)
|
||||
XCTAssertEqual(threadCount, 2)
|
||||
XCTAssertEqual(openFDCount, 3)
|
||||
XCTAssertEqual(socketCount, 1)
|
||||
}
|
||||
|
||||
func testLiveProcessInspection() {
|
||||
let currentPid = getpid()
|
||||
let result = MMProcessDetailInspector.inspectProcess(withPID: currentPid)
|
||||
|
||||
XCTAssertNotNil(result)
|
||||
let threadCount = result?["threadCount"] as? Int ?? 0
|
||||
XCTAssertGreaterThan(threadCount, 0)
|
||||
let fds = result?["fileDescriptors"] as? [[String: Any]]
|
||||
XCTAssertNotNil(fds)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import XCTest
|
||||
@testable import MacMonitor
|
||||
|
||||
final class MMProcessTests: XCTestCase {
|
||||
|
||||
func testProcessCPUPercentCalculation() {
|
||||
let prevCPUTimes: [NSNumber: NSNumber] = [
|
||||
100: NSNumber(value: 1_000_000_000), // 1.0s
|
||||
200: NSNumber(value: 500_000_000) // 0.5s
|
||||
]
|
||||
|
||||
let rawProcesses: [[String: Any]] = [
|
||||
[
|
||||
"pid": 100,
|
||||
"ppid": 1,
|
||||
"uid": 501,
|
||||
"username": "tester",
|
||||
"name": "cpu_hog",
|
||||
"cpuTimeNs": NSNumber(value: 2_000_000_000), // delta = 1.0s over 2.0s = 50% CPU
|
||||
"residentBytes": NSNumber(value: 50_000_000),
|
||||
"virtualBytes": NSNumber(value: 100_000_000),
|
||||
"threadCount": 4,
|
||||
"runningThreads": 1
|
||||
],
|
||||
[
|
||||
"pid": 200,
|
||||
"ppid": 1,
|
||||
"uid": 501,
|
||||
"username": "tester",
|
||||
"name": "idle_app",
|
||||
"cpuTimeNs": NSNumber(value: 520_000_000), // delta = 0.02s over 2.0s = 1% CPU
|
||||
"residentBytes": NSNumber(value: 20_000_000),
|
||||
"virtualBytes": NSNumber(value: 50_000_000),
|
||||
"threadCount": 2,
|
||||
"runningThreads": 0
|
||||
]
|
||||
]
|
||||
|
||||
let timeDelta: TimeInterval = 2.0
|
||||
|
||||
let results = MMProcessTelemetryProvider.calculateProcessList(
|
||||
withRawProcesses: rawProcesses,
|
||||
previousCPUTimes: prevCPUTimes,
|
||||
timeDelta: timeDelta
|
||||
)
|
||||
|
||||
XCTAssertEqual(results.count, 2)
|
||||
// First entry should be highest CPU
|
||||
XCTAssertEqual(results[0]["name"] as? String, "cpu_hog")
|
||||
let hogCPU = results[0]["cpuPercent"] as? Double ?? 0
|
||||
XCTAssertEqual(hogCPU, 50.0, accuracy: 0.1)
|
||||
|
||||
let idleCPU = results[1]["cpuPercent"] as? Double ?? 0
|
||||
XCTAssertEqual(idleCPU, 1.0, accuracy: 0.1)
|
||||
}
|
||||
|
||||
func testLiveProcessProvider() throws {
|
||||
let provider = MMProcessTelemetryProvider()
|
||||
XCTAssertEqual(provider.domain, .process)
|
||||
XCTAssertEqual(provider.providerIdentifier, "com.i3omb.macmonitor.telemetry.process")
|
||||
|
||||
let sample = try provider.sampleTelemetry()
|
||||
XCTAssertNotNil(sample)
|
||||
let processCount = sample["processCount"] as? Int ?? 0
|
||||
XCTAssertGreaterThan(processCount, 0)
|
||||
XCTAssertNotNil(sample["processes"])
|
||||
XCTAssertNotNil(sample["totalThreads"])
|
||||
}
|
||||
}
|
||||
@@ -23,4 +23,15 @@ final class MacMonitorCoreTests: XCTestCase {
|
||||
let thermalStr = MMTelemetryDomainToString(.thermal)
|
||||
XCTAssertEqual(thermalStr, "Thermal")
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func testSystemTelemetryStoreInitialStateAndProviders() {
|
||||
let store = SystemTelemetryStore.shared
|
||||
XCTAssertNotNil(store)
|
||||
XCTAssertEqual(store.registeredProviderCount, 7)
|
||||
XCTAssertFalse(store.hostModel.isEmpty)
|
||||
XCTAssertFalse(store.kernelVersion.isEmpty)
|
||||
XCTAssertGreaterThanOrEqual(store.physicalCpuCount, 1)
|
||||
XCTAssertGreaterThanOrEqual(store.logicalCpuCount, 1)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user