Simple RGB LED controller for Mac OS X
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AppDelegate.m 42KB

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