Simple RGB LED controller for Mac OS X
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  1. //
  2. // AppDelegate.m
  3. // CaseLights
  4. //
  5. // Created by Thomas Buck on 21.12.15.
  6. // Copyright © 2015 xythobuz. All rights reserved.
  7. //
  8. #import "AppDelegate.h"
  9. #import "Serial.h"
  10. #import "GPUStats.h"
  11. #import "Screenshot.h"
  12. #import "AudioVisualizer.h"
  13. // These are the values stored persistently in the preferences
  14. #define PREF_SERIAL_PORT @"SerialPort"
  15. #define PREF_LIGHTS_STATE @"LightState"
  16. // LED Mode contains the last selected mode as menu item text
  17. #define PREF_LED_MODE @"LEDMode"
  18. #define PREF_BRIGHTNESS @"Brightness"
  19. #define PREF_COLOR @"ManualColor"
  20. #define TEXT_MANUAL @"Select..."
  21. #define TEXT_CPU_USAGE @"CPU Usage"
  22. #define TEXT_RAM_USAGE @"RAM Usage"
  23. #define TEXT_GPU_USAGE @"GPU Usage"
  24. #define TEXT_VRAM_USAGE @"VRAM Usage"
  25. #define TEXT_CPU_TEMPERATURE @"CPU Temperature"
  26. #define TEXT_GPU_TEMPERATURE @"GPU Temperature"
  27. #define TEXT_RGB_FADE @"RGB Fade"
  28. #define TEXT_HSV_FADE @"HSV Fade"
  29. #define TEXT_RANDOM @"Random"
  30. #define TEXT_TEMPLATE_AUDIO @"AudioDevice_%@"
  31. // SMC keys are checked for existence and used for reading
  32. #define KEY_CPU_TEMPERATURE @"TC0D"
  33. #define KEY_GPU_TEMPERATURE @"TG0D"
  34. // Temperature in Celsius
  35. #define CPU_TEMP_MIN 20
  36. #define CPU_TEMP_MAX 90
  37. // HSV Color (S = V = 1)
  38. #define CPU_COLOR_MIN 120
  39. #define CPU_COLOR_MAX 0
  40. #define GPU_TEMP_MIN 20
  41. #define GPU_TEMP_MAX 90
  42. #define GPU_COLOR_MIN 120
  43. #define GPU_COLOR_MAX 0
  44. #define RAM_COLOR_MIN 0
  45. #define RAM_COLOR_MAX 120
  46. // You can play around with these values (skipped pixels, display timer delay) to change CPU usage in display mode
  47. #define AVERAGE_COLOR_PERFORMANCE_INC 10
  48. #define DISPLAY_DELAY 0.1
  49. // Used to identify selected menu items
  50. // displays are all tags >= 0
  51. #define MENU_ITEM_TAG_NOTHING -1
  52. #define MENU_ITEM_TAG_AUDIO -2
  53. @interface AppDelegate ()
  54. @property (weak) IBOutlet NSMenu *statusMenu;
  55. @property (weak) IBOutlet NSMenu *menuColors;
  56. @property (weak) IBOutlet NSMenu *menuAnimations;
  57. @property (weak) IBOutlet NSMenu *menuVisualizations;
  58. @property (weak) IBOutlet NSMenuItem *menuItemDisplays;
  59. @property (weak) IBOutlet NSMenu *menuDisplays;
  60. @property (weak) IBOutlet NSMenuItem *menuItemAudio;
  61. @property (weak) IBOutlet NSMenu *menuAudio;
  62. @property (weak) IBOutlet NSMenu *menuPorts;
  63. @property (weak) IBOutlet NSMenuItem *buttonOff;
  64. @property (weak) IBOutlet NSMenuItem *brightnessItem;
  65. @property (weak) IBOutlet NSSlider *brightnessSlider;
  66. @property (weak) IBOutlet NSMenuItem *brightnessLabel;
  67. @property (weak) IBOutlet NSMenuItem *buttonLights;
  68. @property (strong) NSMenuItem *menuItemColor;
  69. @property (strong) NSStatusItem *statusItem;
  70. @property (strong) NSImage *statusImage;
  71. @property (strong) NSDictionary *staticColors;
  72. @property (strong) NSTimer *animation;
  73. @property (strong) Serial *serial;
  74. @property (strong) NSMenuItem *lastLEDMode;
  75. @end
  76. @implementation AppDelegate
  77. @synthesize statusMenu, application;
  78. @synthesize menuColors, menuAnimations, menuVisualizations, menuPorts;
  79. @synthesize menuItemDisplays, menuDisplays;
  80. @synthesize menuItemAudio, menuAudio;
  81. @synthesize buttonOff, buttonLights;
  82. @synthesize brightnessItem, brightnessSlider, brightnessLabel;
  83. @synthesize statusItem, statusImage;
  84. @synthesize staticColors, animation;
  85. @synthesize serial, lastLEDMode, microphone;
  86. @synthesize menuItemColor;
  87. - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
  88. srand((unsigned)time(NULL));
  89. [AudioVisualizer setDelegate:self];
  90. serial = [[Serial alloc] init];
  91. lastLEDMode = nil;
  92. animation = nil;
  93. microphone = nil;
  94. // Prepare status bar menu
  95. statusImage = [NSImage imageNamed:@"MenuIcon"];
  96. [statusImage setTemplate:YES];
  97. statusItem = [[NSStatusBar systemStatusBar] statusItemWithLength:NSSquareStatusItemLength];
  98. [statusItem setImage:statusImage];
  99. [statusItem setMenu:statusMenu];
  100. // Set default configuration values, load existing ones
  101. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  102. NSMutableDictionary *appDefaults = [NSMutableDictionary dictionaryWithObject:@"" forKey:PREF_SERIAL_PORT];
  103. [appDefaults setObject:[NSNumber numberWithBool:NO] forKey:PREF_LIGHTS_STATE];
  104. [appDefaults setObject:@"" forKey:PREF_LED_MODE];
  105. [appDefaults setObject:[NSNumber numberWithFloat:50.0] forKey:PREF_BRIGHTNESS];
  106. [store registerDefaults:appDefaults];
  107. [store synchronize];
  108. NSString *savedPort = [store stringForKey:PREF_SERIAL_PORT];
  109. BOOL turnOnLights = [store boolForKey:PREF_LIGHTS_STATE];
  110. NSString *lastMode = [store stringForKey:PREF_LED_MODE];
  111. float brightness = [store floatForKey:PREF_BRIGHTNESS];
  112. NSData *lastColorData = [store dataForKey:PREF_COLOR];
  113. NSColor *lastColor = nil;
  114. if (lastColorData != nil) {
  115. lastColor = (NSColor *)[NSUnarchiver unarchiveObjectWithData:lastColorData];
  116. }
  117. // Prepare brightness menu
  118. brightnessItem.view = brightnessSlider;
  119. [brightnessSlider setFloatValue:brightness];
  120. [brightnessLabel setTitle:[NSString stringWithFormat:@"Value: %.0f%%", brightness]];
  121. // Prepare serial port menu
  122. NSArray *ports = [Serial listSerialPorts];
  123. if ([ports count] > 0) {
  124. [menuPorts removeAllItems];
  125. for (int i = 0; i < [ports count]; i++) {
  126. // Add Menu Item for this port
  127. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:[ports objectAtIndex:i] action:@selector(selectedSerialPort:) keyEquivalent:@""];
  128. [item setTag:MENU_ITEM_TAG_NOTHING];
  129. [menuPorts addItem:item];
  130. // Set Enabled if it was used the last time
  131. if ((savedPort != nil) && [[ports objectAtIndex:i] isEqualToString:savedPort]) {
  132. [[menuPorts itemAtIndex:i] setState:NSOnState];
  133. // Try to open serial port
  134. [serial setPortName:savedPort];
  135. if ([serial openPort]) {
  136. // Unselect it when an error occured opening the port
  137. [[menuPorts itemAtIndex:i] setState:NSOffState];
  138. }
  139. }
  140. }
  141. }
  142. // Select "Off" button if it was last selected
  143. if ([lastMode isEqualToString:@""]) {
  144. [buttonOff setState:NSOffState];
  145. [self turnLEDsOff:buttonOff];
  146. }
  147. // Prepare static colors menu
  148. staticColors = [NSDictionary dictionaryWithObjectsAndKeys:
  149. [NSColor colorWithCalibratedRed:1.0f green:0.0f blue:0.0f alpha:0.0f], @"Red",
  150. [NSColor colorWithCalibratedRed:0.0f green:1.0f blue:0.0f alpha:0.0f], @"Green",
  151. [NSColor colorWithCalibratedRed:0.0f green:0.0f blue:1.0f alpha:0.0f], @"Blue",
  152. [NSColor colorWithCalibratedRed:0.0f green:1.0f blue:1.0f alpha:0.0f], @"Cyan",
  153. [NSColor colorWithCalibratedRed:1.0f green:0.0f blue:1.0f alpha:0.0f], @"Magenta",
  154. [NSColor colorWithCalibratedRed:1.0f green:1.0f blue:0.0f alpha:0.0f], @"Yellow",
  155. [NSColor colorWithCalibratedRed:1.0f green:1.0f blue:1.0f alpha:0.0f], @"White",
  156. nil];
  157. for (NSString *key in [staticColors allKeys]) {
  158. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:key action:@selector(selectedVisualization:) keyEquivalent:@""];
  159. [item setTag:MENU_ITEM_TAG_NOTHING];
  160. if ([key isEqualToString:lastMode]) {
  161. [self selectedVisualization:item];
  162. }
  163. [menuColors addItem:item];
  164. }
  165. menuItemColor = [[NSMenuItem alloc] initWithTitle:TEXT_MANUAL action:@selector(setColorSelected:) keyEquivalent:@""];
  166. if ([lastMode isEqualToString:TEXT_MANUAL]) {
  167. if (lastColor != nil) {
  168. // Restore previously set RGB color
  169. [self setLightsColor:lastColor];
  170. }
  171. [menuItemColor setState:NSOnState];
  172. }
  173. [menuItemColor setTag:MENU_ITEM_TAG_NOTHING];
  174. [menuColors addItem:menuItemColor];
  175. // Prepare animations menu
  176. NSArray *animationStrings = [NSArray arrayWithObjects:
  177. TEXT_RGB_FADE,
  178. TEXT_HSV_FADE,
  179. TEXT_RANDOM,
  180. nil];
  181. for (NSString *key in animationStrings) {
  182. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:key action:@selector(selectedVisualization:) keyEquivalent:@""];
  183. [item setTag:MENU_ITEM_TAG_NOTHING];
  184. if ([key isEqualToString:lastMode]) {
  185. [self selectedVisualization:item];
  186. }
  187. [menuAnimations addItem:item];
  188. }
  189. // Add CPU Usage menu item
  190. NSMenuItem *cpuUsageItem = [[NSMenuItem alloc] initWithTitle:TEXT_CPU_USAGE action:@selector(selectedVisualization:) keyEquivalent:@""];
  191. [cpuUsageItem setTag:MENU_ITEM_TAG_NOTHING];
  192. if ([lastMode isEqualToString:TEXT_CPU_USAGE]) {
  193. [self selectedVisualization:cpuUsageItem];
  194. }
  195. [menuVisualizations addItem:cpuUsageItem];
  196. // Add Memory Usage item
  197. NSMenuItem *memoryUsageItem = [[NSMenuItem alloc] initWithTitle:TEXT_RAM_USAGE action:@selector(selectedVisualization:) keyEquivalent:@""];
  198. [memoryUsageItem setTag:MENU_ITEM_TAG_NOTHING];
  199. if ([lastMode isEqualToString:TEXT_RAM_USAGE]) {
  200. [self selectedVisualization:memoryUsageItem];
  201. }
  202. [menuVisualizations addItem:memoryUsageItem];
  203. // Check if GPU Stats are available, add menu items if so
  204. NSNumber *usage;
  205. NSNumber *freeVRAM;
  206. NSNumber *usedVRAM;
  207. if ([GPUStats getGPUUsage:&usage freeVRAM:&freeVRAM usedVRAM:&usedVRAM] != 0) {
  208. NSLog(@"Error reading GPU information\n");
  209. } else {
  210. NSMenuItem *itemUsage = [[NSMenuItem alloc] initWithTitle:TEXT_GPU_USAGE action:@selector(selectedVisualization:) keyEquivalent:@""];
  211. [itemUsage setTag:MENU_ITEM_TAG_NOTHING];
  212. if ([lastMode isEqualToString:TEXT_GPU_USAGE]) {
  213. [self selectedVisualization:itemUsage];
  214. }
  215. [menuVisualizations addItem:itemUsage];
  216. NSMenuItem *itemVRAM = [[NSMenuItem alloc] initWithTitle:TEXT_VRAM_USAGE action:@selector(selectedVisualization:) keyEquivalent:@""];
  217. [itemVRAM setTag:MENU_ITEM_TAG_NOTHING];
  218. if ([lastMode isEqualToString:TEXT_VRAM_USAGE]) {
  219. [self selectedVisualization:itemVRAM];
  220. }
  221. [menuVisualizations addItem:itemVRAM];
  222. }
  223. // Check available temperatures and add menu items
  224. JSKSMC *smc = [JSKSMC smc];
  225. for (int i = 0; i < [[smc workingTempKeys] count]; i++) {
  226. NSString *key = [smc.workingTempKeys objectAtIndex:i];
  227. #ifdef DEBUG
  228. NSString *name = [smc humanReadableNameForKey:key];
  229. NSLog(@"Sensor \"%@\": \"%@\"\n", key, name);
  230. #endif
  231. if ([key isEqualToString:KEY_CPU_TEMPERATURE]) {
  232. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:TEXT_CPU_TEMPERATURE action:@selector(selectedVisualization:) keyEquivalent:@""];
  233. [item setTag:MENU_ITEM_TAG_NOTHING];
  234. if ([lastMode isEqualToString:TEXT_CPU_TEMPERATURE]) {
  235. [self selectedVisualization:item];
  236. }
  237. [menuVisualizations addItem:item];
  238. }
  239. if ([key isEqualToString:KEY_GPU_TEMPERATURE]) {
  240. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:TEXT_GPU_TEMPERATURE action:@selector(selectedVisualization:) keyEquivalent:@""];
  241. [item setTag:MENU_ITEM_TAG_NOTHING];
  242. if ([lastMode isEqualToString:TEXT_GPU_TEMPERATURE]) {
  243. [self selectedVisualization:item];
  244. }
  245. [menuVisualizations addItem:item];
  246. }
  247. }
  248. // Restore previously used lights configuration
  249. if (turnOnLights) {
  250. // Turn on lights
  251. if ([serial isOpen]) {
  252. [serial sendString:@"UV 1\n"];
  253. }
  254. [buttonLights setState:NSOnState];
  255. } else {
  256. // Turn off lights
  257. if ([serial isOpen]) {
  258. [serial sendString:@"UV 0\n"];
  259. }
  260. }
  261. // List available displays and add menu items
  262. [Screenshot init:self];
  263. NSArray *displayIDs = [Screenshot listDisplays];
  264. [self updateDisplayUI:displayIDs];
  265. // List available audio input devices and add menu items
  266. NSArray *inputDevices = [EZAudioDevice inputDevices];
  267. [menuAudio removeAllItems];
  268. for (int i = 0; i < [inputDevices count]; i++) {
  269. EZAudioDevice *dev = [inputDevices objectAtIndex:i];
  270. #ifdef DEBUG
  271. NSLog(@"Audio input device: \"%@\"\n", [dev name]);
  272. #endif
  273. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:[dev name] action:@selector(selectedVisualization:) keyEquivalent:@""];
  274. [item setTag:MENU_ITEM_TAG_AUDIO];
  275. NSString *lastModeString = [NSString stringWithFormat:TEXT_TEMPLATE_AUDIO, [dev name]];
  276. if ([lastModeString isEqualToString:lastMode]) {
  277. [self selectedVisualization:item];
  278. }
  279. [menuAudio addItem:item];
  280. }
  281. if ([inputDevices count] > 0) {
  282. [menuItemAudio setHidden:NO];
  283. }
  284. }
  285. - (void)applicationWillTerminate:(NSNotification *)aNotification {
  286. // Stop previous timer setting
  287. if (animation != nil) {
  288. [animation invalidate];
  289. animation = nil;
  290. }
  291. // Stop previous audio data retrieval
  292. if (microphone != nil) {
  293. [microphone stopFetchingAudio];
  294. }
  295. // Remove display callback
  296. [Screenshot close:self];
  297. // Turn off all lights if possible
  298. if ([serial isOpen]) {
  299. [serial sendString:@"RGB 0 0 0\n"];
  300. [serial sendString:@"UV 0\n"];
  301. [serial closePort];
  302. }
  303. }
  304. - (void)clearDisplayUI {
  305. for (int i = 0; i < [menuDisplays numberOfItems]; i++) {
  306. if ([[menuDisplays itemAtIndex:i] isEnabled] == YES) {
  307. // A display configuration is currently selected. Disable the timer
  308. if (animation != nil) {
  309. [animation invalidate];
  310. animation = nil;
  311. }
  312. }
  313. }
  314. [menuDisplays removeAllItems];
  315. [menuItemDisplays setHidden:YES];
  316. }
  317. - (void)updateDisplayUI:(NSArray *)displayIDs {
  318. if ([displayIDs count] > 0) {
  319. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  320. NSString *lastMode = [store stringForKey:PREF_LED_MODE];
  321. [menuItemDisplays setHidden:NO];
  322. for (int i = 0; i < [displayIDs count]; i++) {
  323. NSString *title = [Screenshot displayNameFromDisplayID:[displayIDs objectAtIndex:i]];
  324. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:title
  325. action:@selector(selectedVisualization:)
  326. keyEquivalent:@""];
  327. [item setTag:[[displayIDs objectAtIndex:i] integerValue]];
  328. if ([title isEqualToString:lastMode]) {
  329. [self selectedVisualization:item];
  330. }
  331. [menuDisplays addItem:item];
  332. }
  333. }
  334. }
  335. - (void)setLightsColor:(NSColor *)color {
  336. CGFloat red, green, blue, alpha;
  337. [color getRed:&red green:&green blue:&blue alpha:&alpha];
  338. [self setLightsR:red * 255 G:green * 255 B:blue * 255];
  339. // Stop previous timer setting
  340. if (animation != nil) {
  341. [animation invalidate];
  342. animation = nil;
  343. }
  344. // Stop previous audio data retrieval
  345. if (microphone != nil) {
  346. [microphone stopFetchingAudio];
  347. }
  348. // Turn off all other LED menu items
  349. if (menuColors != nil) {
  350. for (int i = 0; i < [menuColors numberOfItems]; i++) {
  351. [[menuColors itemAtIndex:i] setState:NSOffState];
  352. }
  353. }
  354. if (menuAnimations != nil) {
  355. for (int i = 0; i < [menuAnimations numberOfItems]; i++) {
  356. [[menuAnimations itemAtIndex:i] setState:NSOffState];
  357. }
  358. }
  359. if (menuVisualizations != nil) {
  360. for (int i = 0; i < [menuVisualizations numberOfItems]; i++) {
  361. [[menuVisualizations itemAtIndex:i] setState:NSOffState];
  362. }
  363. }
  364. if (menuAudio != nil) {
  365. for (int i = 0; i < [menuAudio numberOfItems]; i++) {
  366. [[menuAudio itemAtIndex:i] setState:NSOffState];
  367. }
  368. }
  369. if (menuDisplays != nil) {
  370. for (int i = 0; i < [menuDisplays numberOfItems]; i++) {
  371. [[menuDisplays itemAtIndex:i] setState:NSOffState];
  372. }
  373. }
  374. [buttonOff setState:NSOffState];
  375. [menuItemColor setState:NSOnState];
  376. // Store new manually selected color
  377. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  378. NSData *data = [NSArchiver archivedDataWithRootObject:color];
  379. [store setObject:data forKey:PREF_COLOR];
  380. [store setObject:TEXT_MANUAL forKey:PREF_LED_MODE];
  381. [store synchronize];
  382. }
  383. - (void)setLightsR:(unsigned char)r G:(unsigned char)g B:(unsigned char)b {
  384. if ([serial isOpen]) {
  385. unsigned char red = r * ([brightnessSlider floatValue] / 100.0);
  386. unsigned char green = g * ([brightnessSlider floatValue] / 100.0);
  387. unsigned char blue = b * ([brightnessSlider floatValue] / 100.0);
  388. [serial sendString:[NSString stringWithFormat:@"RGB %d %d %d\n", red, green, blue]];
  389. } else {
  390. #ifdef DEBUG
  391. NSLog(@"Trying to send RGB without opened port!\n");
  392. #endif
  393. }
  394. }
  395. - (IBAction)relistSerialPorts:(id)sender {
  396. // Refill audio device list
  397. NSArray *inputDevices = [EZAudioDevice inputDevices];
  398. [menuAudio removeAllItems];
  399. for (int i = 0; i < [inputDevices count]; i++) {
  400. EZAudioDevice *dev = [inputDevices objectAtIndex:i];
  401. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:[dev name] action:@selector(selectedVisualization:) keyEquivalent:@""];
  402. [item setTag:MENU_ITEM_TAG_AUDIO];
  403. NSString *lastModeString = [NSString stringWithFormat:TEXT_TEMPLATE_AUDIO, [dev name]];
  404. if ([lastModeString isEqualToString:[[NSUserDefaults standardUserDefaults] stringForKey:PREF_LED_MODE]]) {
  405. [self selectedVisualization:item];
  406. }
  407. [menuAudio addItem:item];
  408. }
  409. if ([inputDevices count] > 0) {
  410. [menuItemAudio setHidden:NO];
  411. } else {
  412. [menuItemAudio setHidden:YES];
  413. }
  414. // Refill port list
  415. NSArray *ports = [Serial listSerialPorts];
  416. [menuPorts removeAllItems];
  417. for (int i = 0; i < [ports count]; i++) {
  418. // Add Menu Item for this port
  419. NSMenuItem *item = [[NSMenuItem alloc] initWithTitle:[ports objectAtIndex:i] action:@selector(selectedSerialPort:) keyEquivalent:@""];
  420. [item setTag:MENU_ITEM_TAG_NOTHING];
  421. [menuPorts addItem:item];
  422. // Mark it if it is currently open
  423. if ([serial isOpen]) {
  424. if ([[ports objectAtIndex:i] isEqualToString:[serial portName]]) {
  425. [[menuPorts itemAtIndex:i] setState:NSOnState];
  426. }
  427. }
  428. }
  429. }
  430. - (void)setColorSelected:(NSMenuItem *)sender {
  431. NSColorPanel *cp = [NSColorPanel sharedColorPanel];
  432. [cp setTarget:self];
  433. [cp setAction:@selector(colorSelected:)];
  434. [cp setShowsAlpha:NO];
  435. [cp setContinuous:NO];
  436. [cp setMode:NSRGBModeColorPanel];
  437. // Try to restore last manually selected color
  438. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  439. NSData *lastColorData = [store dataForKey:PREF_COLOR];
  440. NSColor *lastColor = nil;
  441. if (lastColorData != nil) {
  442. lastColor = (NSColor *)[NSUnarchiver unarchiveObjectWithData:lastColorData];
  443. [cp setColor:lastColor];
  444. }
  445. [NSApp activateIgnoringOtherApps:YES];
  446. [application orderFrontColorPanel:cp];
  447. }
  448. - (void)colorSelected:(NSColorPanel *)sender {
  449. [self setLightsColor:[sender color]];
  450. }
  451. - (IBAction)brightnessMoved:(NSSlider *)sender {
  452. [brightnessLabel setTitle:[NSString stringWithFormat:@"Value: %.0f%%", [sender floatValue]]];
  453. // Restore the current configuration for items where it won't happen automatically
  454. for (int i = 0; i < [menuColors numberOfItems]; i++) {
  455. if ([[menuColors itemAtIndex:i] state] == NSOnState) {
  456. [self selectedVisualization:[menuColors itemAtIndex:i]];
  457. }
  458. }
  459. // Store changed value in preferences
  460. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  461. [store setObject:[NSNumber numberWithFloat:[sender floatValue]] forKey:PREF_BRIGHTNESS];
  462. [store synchronize];
  463. }
  464. - (IBAction)turnLEDsOff:(NSMenuItem *)sender {
  465. if ([sender state] == NSOffState) {
  466. lastLEDMode = nil;
  467. // Stop previous timer setting
  468. if (animation != nil) {
  469. [animation invalidate];
  470. animation = nil;
  471. }
  472. // Stop previous audio data retrieval
  473. if (microphone != nil) {
  474. [microphone stopFetchingAudio];
  475. }
  476. // Turn off all other LED menu items
  477. for (int i = 0; i < [menuColors numberOfItems]; i++) {
  478. if ([[menuColors itemAtIndex:i] state] == NSOnState) {
  479. lastLEDMode = [menuColors itemAtIndex:i];
  480. }
  481. [[menuColors itemAtIndex:i] setState:NSOffState];
  482. }
  483. for (int i = 0; i < [menuAnimations numberOfItems]; i++) {
  484. if ([[menuAnimations itemAtIndex:i] state] == NSOnState) {
  485. lastLEDMode = [menuAnimations itemAtIndex:i];
  486. }
  487. [[menuAnimations itemAtIndex:i] setState:NSOffState];
  488. }
  489. for (int i = 0; i < [menuVisualizations numberOfItems]; i++) {
  490. if ([[menuVisualizations itemAtIndex:i] state] == NSOnState) {
  491. lastLEDMode = [menuVisualizations itemAtIndex:i];
  492. }
  493. [[menuVisualizations itemAtIndex:i] setState:NSOffState];
  494. }
  495. for (int i = 0; i < [menuAudio numberOfItems]; i++) {
  496. if ([[menuAudio itemAtIndex:i] state] == NSOnState) {
  497. lastLEDMode = [menuAudio itemAtIndex:i];
  498. }
  499. [[menuAudio itemAtIndex:i] setState:NSOffState];
  500. }
  501. for (int i = 0; i < [menuDisplays numberOfItems]; i++) {
  502. if ([[menuDisplays itemAtIndex:i] state] == NSOnState) {
  503. lastLEDMode = [menuDisplays itemAtIndex:i];
  504. }
  505. [[menuDisplays itemAtIndex:i] setState:NSOffState];
  506. }
  507. // Turn on "off" menu item
  508. [sender setState:NSOnState];
  509. // Store changed value in preferences
  510. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  511. [store setObject:@"" forKey:PREF_LED_MODE];
  512. [store synchronize];
  513. #ifdef DEBUG
  514. NSLog(@"Stored new mode: \"off\"!\n");
  515. #endif
  516. // Send command to turn off LEDs
  517. [self setLightsR:0 G:0 B:0];
  518. } else {
  519. // Try to restore last LED setting
  520. if (lastLEDMode != nil) {
  521. [self selectedVisualization:lastLEDMode];
  522. }
  523. }
  524. }
  525. - (IBAction)toggleLights:(NSMenuItem *)sender {
  526. if ([sender state] == NSOffState) {
  527. // Turn on lights
  528. if ([serial isOpen]) {
  529. [serial sendString:@"UV 1\n"];
  530. }
  531. [sender setState:NSOnState];
  532. } else {
  533. // Turn off lights
  534. if ([serial isOpen]) {
  535. [serial sendString:@"UV 0\n"];
  536. }
  537. [sender setState:NSOffState];
  538. }
  539. // Store changed value in preferences
  540. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  541. [store setBool:([sender state] == NSOnState) forKey:PREF_LIGHTS_STATE];
  542. [store synchronize];
  543. }
  544. - (BOOL)timedVisualization:(NSString *)mode {
  545. // Stop previous timer setting
  546. if (animation != nil) {
  547. [animation invalidate];
  548. animation = nil;
  549. }
  550. // Stop previous audio data retrieval
  551. if (microphone != nil) {
  552. [microphone stopFetchingAudio];
  553. }
  554. // Schedule next invocation for this animation...
  555. if ([mode isEqualToString:TEXT_GPU_USAGE]) {
  556. animation = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(visualizeGPUUsage:) userInfo:mode repeats:YES];
  557. } else if ([mode isEqualToString:TEXT_VRAM_USAGE]) {
  558. animation = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(visualizeVRAMUsage:) userInfo:mode repeats:YES];
  559. } else if ([mode isEqualToString:TEXT_CPU_USAGE]) {
  560. animation = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(visualizeCPUUsage:) userInfo:mode repeats:YES];
  561. } else if ([mode isEqualToString:TEXT_RAM_USAGE]) {
  562. animation = [NSTimer scheduledTimerWithTimeInterval:20.0 target:self selector:@selector(visualizeRAMUsage:) userInfo:mode repeats:YES];
  563. } else if ([mode isEqualToString:TEXT_CPU_TEMPERATURE]) {
  564. animation = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(visualizeCPUTemperature:) userInfo:mode repeats:YES];
  565. } else if ([mode isEqualToString:TEXT_GPU_TEMPERATURE]) {
  566. animation = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(visualizeGPUTemperature:) userInfo:mode repeats:YES];
  567. } else if ([mode isEqualToString:TEXT_RGB_FADE]) {
  568. animation = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(visualizeRGBFade:) userInfo:mode repeats:YES];
  569. } else if ([mode isEqualToString:TEXT_HSV_FADE]) {
  570. animation = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(visualizeHSVFade:) userInfo:mode repeats:YES];
  571. } else if ([mode isEqualToString:TEXT_RANDOM]) {
  572. animation = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(visualizeRandom:) userInfo:mode repeats:YES];
  573. } else {
  574. return NO;
  575. }
  576. #ifdef DEBUG
  577. NSLog(@"Scheduled animation for \"%@\"!\n", mode);
  578. #endif
  579. // ...and also execute it right now
  580. [animation fire];
  581. return YES;
  582. }
  583. - (void)displayVisualization:(NSMenuItem *)sender {
  584. // Stop previous timer setting
  585. if (animation != nil) {
  586. [animation invalidate];
  587. animation = nil;
  588. }
  589. // Stop previous audio data retrieval
  590. if (microphone != nil) {
  591. [microphone stopFetchingAudio];
  592. }
  593. // Schedule next invocation for this animation...
  594. animation = [NSTimer scheduledTimerWithTimeInterval:DISPLAY_DELAY target:self selector:@selector(visualizeDisplay:) userInfo:[NSNumber numberWithInteger:[sender tag]] repeats:YES];
  595. // ...and also execute it right now
  596. [animation fire];
  597. }
  598. - (void)selectedVisualization:(NSMenuItem *)sender {
  599. // Turn off all other LED menu items
  600. if (menuColors != nil) {
  601. for (int i = 0; i < [menuColors numberOfItems]; i++) {
  602. [[menuColors itemAtIndex:i] setState:NSOffState];
  603. }
  604. }
  605. if (menuAnimations != nil) {
  606. for (int i = 0; i < [menuAnimations numberOfItems]; i++) {
  607. [[menuAnimations itemAtIndex:i] setState:NSOffState];
  608. }
  609. }
  610. if (menuVisualizations != nil) {
  611. for (int i = 0; i < [menuVisualizations numberOfItems]; i++) {
  612. [[menuVisualizations itemAtIndex:i] setState:NSOffState];
  613. }
  614. }
  615. if (menuAudio != nil) {
  616. for (int i = 0; i < [menuAudio numberOfItems]; i++) {
  617. [[menuAudio itemAtIndex:i] setState:NSOffState];
  618. }
  619. }
  620. if (menuDisplays != nil) {
  621. for (int i = 0; i < [menuDisplays numberOfItems]; i++) {
  622. [[menuDisplays itemAtIndex:i] setState:NSOffState];
  623. }
  624. }
  625. [buttonOff setState:NSOffState];
  626. [sender setState:NSOnState];
  627. // Check if it is a display
  628. BOOL found = NO;
  629. if ([sender tag] > MENU_ITEM_TAG_NOTHING) {
  630. found = YES;
  631. [self displayVisualization:sender];
  632. }
  633. // Check if it is an audio input device
  634. if ((found == NO) && ([sender tag] == MENU_ITEM_TAG_AUDIO)) {
  635. found = YES;
  636. BOOL foundDev = NO;
  637. NSArray *audioDevices = [EZAudioDevice inputDevices];
  638. for (int i = 0; i < [audioDevices count]; i++) {
  639. EZAudioDevice *dev = [audioDevices objectAtIndex:i];
  640. if ([[dev name] isEqualToString:[sender title]]) {
  641. // Found device
  642. foundDev = YES;
  643. if (microphone != nil) {
  644. [microphone stopFetchingAudio];
  645. } else {
  646. microphone = [EZMicrophone microphoneWithDelegate:self];
  647. }
  648. [microphone setDevice:dev];
  649. [microphone startFetchingAudio];
  650. break;
  651. }
  652. }
  653. if (foundDev == NO) {
  654. NSLog(@"Couldn't find device \"%@\"\n", [sender title]);
  655. [sender setState:NSOffState];
  656. return; // Don't store new mode
  657. }
  658. }
  659. // Check if it is the manual color select item
  660. if ((found == NO) && ([sender.title isEqualToString:TEXT_MANUAL])) {
  661. found = YES;
  662. [self colorSelected:[NSColorPanel sharedColorPanel]];
  663. }
  664. // Check if a static color was selected
  665. if ((found == NO) && (staticColors != nil)) {
  666. for (NSString *key in [staticColors allKeys]) {
  667. if ([sender.title isEqualToString:key]) {
  668. found = YES;
  669. // Stop previous timer setting
  670. if (animation != nil) {
  671. [animation invalidate];
  672. animation = nil;
  673. }
  674. // Stop previous audio data retrieval
  675. if (microphone != nil) {
  676. [microphone stopFetchingAudio];
  677. }
  678. NSColor *color = [staticColors valueForKey:key];
  679. unsigned char red = [color redComponent] * 255;
  680. unsigned char green = [color greenComponent] * 255;
  681. unsigned char blue = [color blueComponent] * 255;
  682. [self setLightsR:red G:green B:blue];
  683. break;
  684. }
  685. }
  686. }
  687. if (found == NO) {
  688. // Check if an animated visualization was selected
  689. if ([self timedVisualization:[sender title]] == NO) {
  690. NSLog(@"Unknown LED Visualization selected!\n");
  691. return;
  692. }
  693. }
  694. // Store changed value in preferences
  695. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  696. if ([sender tag] == MENU_ITEM_TAG_AUDIO) {
  697. // Prepend text for audio device names
  698. NSString *tmp = [NSString stringWithFormat:TEXT_TEMPLATE_AUDIO, [sender title]];
  699. [store setObject:tmp forKey:PREF_LED_MODE];
  700. } else {
  701. [store setObject:[sender title] forKey:PREF_LED_MODE];
  702. }
  703. [store synchronize];
  704. #ifdef DEBUG
  705. NSLog(@"Stored new mode: \"%@\"!\n", [sender title]);
  706. #endif
  707. }
  708. - (void)selectedSerialPort:(NSMenuItem *)source {
  709. // Store selection for next start-up
  710. NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
  711. [store setObject:[source title] forKey:PREF_SERIAL_PORT];
  712. [store synchronize];
  713. // De-select all other ports
  714. for (int i = 0; i < [menuPorts numberOfItems]; i++) {
  715. [[menuPorts itemAtIndex:i] setState:NSOffState];
  716. }
  717. // Select only the current port
  718. [source setState:NSOnState];
  719. // Close previously opened port, if any
  720. if ([serial isOpen]) {
  721. [serial closePort];
  722. }
  723. // Try to open selected port
  724. [serial setPortName:[source title]];
  725. if ([serial openPort] != 0) {
  726. [source setState:NSOffState];
  727. } else {
  728. // Restore the current configuration
  729. for (int i = 0; i < [menuColors numberOfItems]; i++) {
  730. if ([[menuColors itemAtIndex:i] state] == NSOnState) {
  731. [self selectedVisualization:[menuColors itemAtIndex:i]];
  732. }
  733. }
  734. for (int i = 0; i < [menuAnimations numberOfItems]; i++) {
  735. if ([[menuAnimations itemAtIndex:i] state] == NSOnState) {
  736. [self selectedVisualization:[menuAnimations itemAtIndex:i]];
  737. }
  738. }
  739. for (int i = 0; i < [menuVisualizations numberOfItems]; i++) {
  740. if ([[menuVisualizations itemAtIndex:i] state] == NSOnState) {
  741. [self selectedVisualization:[menuVisualizations itemAtIndex:i]];
  742. }
  743. }
  744. for (int i = 0; i < [menuAudio numberOfItems]; i++) {
  745. if ([[menuAudio itemAtIndex:i] state] == NSOnState) {
  746. [self selectedVisualization:[menuAudio itemAtIndex:i]];
  747. }
  748. }
  749. for (int i = 0; i < [menuDisplays numberOfItems]; i++) {
  750. if ([[menuDisplays itemAtIndex:i] state] == NSOnState) {
  751. [self selectedVisualization:[menuDisplays itemAtIndex:i]];
  752. }
  753. }
  754. if ([buttonOff state] == NSOnState) {
  755. [buttonOff setState:NSOffState];
  756. [self turnLEDsOff:buttonOff];
  757. }
  758. if ([buttonLights state] == NSOnState) {
  759. [serial sendString:@"UV 1\n"];
  760. } else {
  761. [serial sendString:@"UV 0\n"];
  762. }
  763. }
  764. }
  765. - (IBAction)showAbout:(id)sender {
  766. [NSApp activateIgnoringOtherApps:YES];
  767. [application orderFrontStandardAboutPanel:self];
  768. }
  769. // ------------------------------------------------------
  770. // ----------------- Microphone Delegate ----------------
  771. // ------------------------------------------------------
  772. - (void)microphone:(EZMicrophone *)microphone hasAudioReceived:(float **)buffer withBufferSize:(UInt32)bufferSize withNumberOfChannels:(UInt32)numberOfChannels {
  773. __weak typeof (self) weakSelf = self;
  774. if (weakSelf.microphone == nil) {
  775. return;
  776. }
  777. // Getting audio data as an array of float buffer arrays that can be fed into the
  778. // EZAudioPlot, EZAudioPlotGL, or whatever visualization you would like to do with
  779. // the microphone data.
  780. dispatch_async(dispatch_get_main_queue(),^{
  781. if (weakSelf.microphone == nil) {
  782. return;
  783. }
  784. // buffer[0] = left channel, buffer[1] = right channel
  785. [AudioVisualizer updateBuffer:buffer[0] withBufferSize:bufferSize];
  786. });
  787. }
  788. - (void)microphone:(EZMicrophone *)microphone changedDevice:(EZAudioDevice *)device {
  789. // This is not always guaranteed to occur on the main thread so make sure you
  790. // wrap it in a GCD block
  791. dispatch_async(dispatch_get_main_queue(), ^{
  792. NSLog(@"Changed audio input device: %@", [device name]);
  793. });
  794. }
  795. // ------------------------------------------------------
  796. // ------------------- Visualizations -------------------
  797. // ------------------------------------------------------
  798. - (void)visualizeDisplay:(NSTimer *)timer {
  799. NSBitmapImageRep *screen = [Screenshot screenshot:[timer userInfo]];
  800. NSInteger spp = [screen samplesPerPixel];
  801. if (((spp != 3) && (spp != 4)) || ([screen isPlanar] == YES) || ([screen numberOfPlanes] != 1)) {
  802. NSLog(@"Unknown image format (%ld, %c, %ld)!\n", (long)spp, ([screen isPlanar] == YES) ? 'p' : 'n', (long)[screen numberOfPlanes]);
  803. return;
  804. }
  805. int redC = 0, greenC = 1, blueC = 2;
  806. if ([screen bitmapFormat] & NSAlphaFirstBitmapFormat) {
  807. redC = 1; greenC = 2; blueC = 3;
  808. }
  809. unsigned char *data = [screen bitmapData];
  810. unsigned long width = [screen pixelsWide];
  811. unsigned long height = [screen pixelsHigh];
  812. unsigned long max = width * height;
  813. unsigned long red = 0, green = 0, blue = 0;
  814. for (unsigned long i = 0; i < max; i += AVERAGE_COLOR_PERFORMANCE_INC) {
  815. unsigned long off = spp * i;
  816. red += data[off + redC];
  817. green += data[off + greenC];
  818. blue += data[off + blueC];
  819. }
  820. max /= AVERAGE_COLOR_PERFORMANCE_INC;
  821. [self setLightsR:(red / max) G:(green / max) B:(blue / max)];
  822. }
  823. - (void)visualizeGPUUsage:(NSTimer *)timer {
  824. NSNumber *usage;
  825. NSNumber *freeVRAM;
  826. NSNumber *usedVRAM;
  827. if ([GPUStats getGPUUsage:&usage freeVRAM:&freeVRAM usedVRAM:&usedVRAM] != 0) {
  828. NSLog(@"Error reading GPU information\n");
  829. } else {
  830. double h = [AppDelegate map:[usage doubleValue] FromMin:0.0 FromMax:100.0 ToMin:GPU_COLOR_MIN ToMax:GPU_COLOR_MAX];
  831. #ifdef DEBUG
  832. NSLog(@"GPU Usage: %.3f%%\n", [usage doubleValue]);
  833. #endif
  834. unsigned char r, g, b;
  835. [AppDelegate convertH:h S:1.0 V:1.0 toR:&r G:&g B:&b];
  836. [self setLightsR:r G:g B:b];
  837. }
  838. }
  839. - (void)visualizeVRAMUsage:(NSTimer *)timer {
  840. NSNumber *usage;
  841. NSNumber *freeVRAM;
  842. NSNumber *usedVRAM;
  843. if ([GPUStats getGPUUsage:&usage freeVRAM:&freeVRAM usedVRAM:&usedVRAM] != 0) {
  844. NSLog(@"Error reading GPU information\n");
  845. } else {
  846. double h = [AppDelegate map:[freeVRAM doubleValue] FromMin:0.0 FromMax:([freeVRAM doubleValue] + [usedVRAM doubleValue]) ToMin:RAM_COLOR_MIN ToMax:RAM_COLOR_MAX];
  847. #ifdef DEBUG
  848. NSLog(@"VRAM %.2fGB Free + %.2fGB Used = %.2fGB mapped to color %.2f!\n", [freeVRAM doubleValue] / (1024.0 * 1024.0 * 1024.0), [usedVRAM doubleValue] / (1024.0 * 1024.0 * 1024.0), ([freeVRAM doubleValue] + [usedVRAM doubleValue]) / (1024.0 * 1024.0 * 1024.0), h);
  849. #endif
  850. unsigned char r, g, b;
  851. [AppDelegate convertH:h S:1.0 V:1.0 toR:&r G:&g B:&b];
  852. [self setLightsR:r G:g B:b];
  853. }
  854. }
  855. - (void)visualizeCPUUsage:(NSTimer *)timer {
  856. JSKMCPUUsageInfo cpuUsageInfo = [JSKSystemMonitor systemMonitor].cpuUsageInfo;
  857. double h = [AppDelegate map:cpuUsageInfo.usage FromMin:0.0 FromMax:100.0 ToMin:CPU_COLOR_MIN ToMax:CPU_COLOR_MAX];
  858. #ifdef DEBUG
  859. NSLog(@"CPU Usage: %.3f%%\n", cpuUsageInfo.usage);
  860. #endif
  861. unsigned char r, g, b;
  862. [AppDelegate convertH:h S:1.0 V:1.0 toR:&r G:&g B:&b];
  863. [self setLightsR:r G:g B:b];
  864. }
  865. - (void)visualizeRAMUsage:(NSTimer *)timer {
  866. JSKMMemoryUsageInfo memoryUsageInfo = [JSKSystemMonitor systemMonitor].memoryUsageInfo;
  867. double h = [AppDelegate map:memoryUsageInfo.freeMemory FromMin:0.0 FromMax:(memoryUsageInfo.usedMemory + memoryUsageInfo.freeMemory) ToMin:RAM_COLOR_MIN ToMax:RAM_COLOR_MAX];
  868. #ifdef DEBUG
  869. NSLog(@"RAM %.2fGB Free + %.2fGB Used = %.2fGB mapped to color %.2f!\n", memoryUsageInfo.freeMemory / (1024.0 * 1024.0 * 1024.0), memoryUsageInfo.usedMemory / (1024.0 * 1024.0 * 1024.0), (memoryUsageInfo.freeMemory + memoryUsageInfo.usedMemory) / (1024.0 * 1024.0 * 1024.0), h);
  870. #endif
  871. unsigned char r, g, b;
  872. [AppDelegate convertH:h S:1.0 V:1.0 toR:&r G:&g B:&b];
  873. [self setLightsR:r G:g B:b];
  874. }
  875. - (void)visualizeGPUTemperature:(NSTimer *)timer {
  876. JSKSMC *smc = [JSKSMC smc];
  877. double temp = [smc temperatureInCelsiusForKey:KEY_GPU_TEMPERATURE];
  878. if (temp > 1000.0) {
  879. temp /= 1000.0;
  880. }
  881. if (temp > GPU_TEMP_MAX) {
  882. temp = GPU_TEMP_MAX;
  883. }
  884. if (temp < GPU_TEMP_MIN) {
  885. temp = GPU_TEMP_MIN;
  886. }
  887. double h = [AppDelegate map:temp FromMin:GPU_TEMP_MIN FromMax:GPU_TEMP_MAX ToMin:GPU_COLOR_MIN ToMax:GPU_COLOR_MAX];
  888. #ifdef DEBUG
  889. NSLog(@"GPU Temp %.2f mapped to color %.2f!\n", temp, h);
  890. #endif
  891. unsigned char r, g, b;
  892. [AppDelegate convertH:h S:1.0 V:1.0 toR:&r G:&g B:&b];
  893. [self setLightsR:r G:g B:b];
  894. }
  895. - (void)visualizeCPUTemperature:(NSTimer *)timer {
  896. JSKSMC *smc = [JSKSMC smc];
  897. double temp = [smc temperatureInCelsiusForKey:KEY_CPU_TEMPERATURE];
  898. if (temp > 1000.0) {
  899. temp /= 1000.0;
  900. }
  901. if (temp > CPU_TEMP_MAX) {
  902. temp = CPU_TEMP_MAX;
  903. }
  904. if (temp < CPU_TEMP_MIN) {
  905. temp = CPU_TEMP_MIN;
  906. }
  907. double h = [AppDelegate map:temp FromMin:CPU_TEMP_MIN FromMax:CPU_TEMP_MAX ToMin:CPU_COLOR_MIN ToMax:CPU_COLOR_MAX];
  908. #ifdef DEBUG
  909. NSLog(@"CPU Temp %.2f mapped to color %.2f!\n", temp, h);
  910. #endif
  911. unsigned char r, g, b;
  912. [AppDelegate convertH:h S:1.0 V:1.0 toR:&r G:&g B:&b];
  913. [self setLightsR:r G:g B:b];
  914. }
  915. - (void)visualizeRGBFade:(NSTimer *)timer {
  916. static unsigned char color[3] = { 255, 0, 0 };
  917. static int dec = 0;
  918. static int val = 0;
  919. // Adapted from:
  920. // https://gist.github.com/jamesotron/766994
  921. if (dec < 3) {
  922. int inc = (dec == 2) ? 0 : (dec + 1);
  923. if (val < 255) {
  924. color[dec] -= 1;
  925. color[inc] += 1;
  926. val++;
  927. } else {
  928. val = 0;
  929. dec++;
  930. }
  931. } else {
  932. dec = 0;
  933. }
  934. [self setLightsR:color[0] G:color[1] B:color[2]];
  935. }
  936. - (void)visualizeHSVFade:(NSTimer *)timer {
  937. static float h = 0.0;
  938. if (h < 359.0) {
  939. h += 0.5;
  940. } else {
  941. h = 0.0;
  942. }
  943. unsigned char r, g, b;
  944. [AppDelegate convertH:h S:1.0 V:1.0 toR:&r G:&g B:&b];
  945. [self setLightsR:r G:g B:b];
  946. }
  947. - (void)visualizeRandom:(NSTimer *)timer {
  948. [self setLightsR:rand() % 256 G:rand() % 256 B:rand() % 256];
  949. }
  950. // -----------------------------------------------------
  951. // --------------------- Utilities ---------------------
  952. // -----------------------------------------------------
  953. + (double)map:(double)val FromMin:(double)fmin FromMax:(double)fmax ToMin:(double)tmin ToMax:(double)tmax {
  954. double norm = (val - fmin) / (fmax - fmin);
  955. return (norm * (tmax - tmin)) + tmin;
  956. }
  957. + (void)convertH:(double)h S:(double)s V:(double)v toR:(unsigned char *)r G:(unsigned char *)g B:(unsigned char *)b {
  958. // Adapted from:
  959. // https://gist.github.com/hdznrrd/656996
  960. if (s == 0.0) {
  961. // Achromatic
  962. *r = *g = *b = (unsigned char)(v * 255);
  963. return;
  964. }
  965. h /= 60; // sector 0 to 5
  966. int i = floor(h);
  967. double f = h - i; // factorial part of h
  968. double p = v * (1 - s);
  969. double q = v * (1 - s * f);
  970. double t = v * (1 - s * (1 - f));
  971. switch (i) {
  972. case 0:
  973. *r = (unsigned char)round(255 * v);
  974. *g = (unsigned char)round(255 * t);
  975. *b = (unsigned char)round(255 * p);
  976. break;
  977. case 1:
  978. *r = (unsigned char)round(255 * q);
  979. *g = (unsigned char)round(255 * v);
  980. *b = (unsigned char)round(255 * p);
  981. break;
  982. case 2:
  983. *r = (unsigned char)round(255 * p);
  984. *g = (unsigned char)round(255 * v);
  985. *b = (unsigned char)round(255 * t);
  986. break;
  987. case 3:
  988. *r = (unsigned char)round(255 * p);
  989. *g = (unsigned char)round(255 * q);
  990. *b = (unsigned char)round(255 * v);
  991. break;
  992. case 4:
  993. *r = (unsigned char)round(255 * t);
  994. *g = (unsigned char)round(255 * p);
  995. *b = (unsigned char)round(255 * v);
  996. break;
  997. default: case 5:
  998. *r = (unsigned char)round(255 * v);
  999. *g = (unsigned char)round(255 * p);
  1000. *b = (unsigned char)round(255 * q);
  1001. break;
  1002. }
  1003. }
  1004. @end