]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/ISSILed/led_scan.c
8a92b768c67122b4b3e69b5dd037cb550a1f48d7
[kiibohd-controller.git] / Scan / ISSILed / led_scan.c
1 /* Copyright (C) 2014-2015 by Jacob Alexander
2  *
3  * This file is free software: you can redistribute it and/or modify
4  * it under the terms of the GNU General Public License as published by
5  * the Free Software Foundation, either version 3 of the License, or
6  * (at your option) any later version.
7  *
8  * This file is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License
14  * along with this file.  If not, see <http://www.gnu.org/licenses/>.
15  */
16
17 // ----- Includes -----
18
19 // Compiler Includes
20 #include <Lib/ScanLib.h>
21
22 // Project Includes
23 #include <cli.h>
24 #include <kll_defs.h>
25 #include <led.h>
26 #include <print.h>
27
28 // Interconnect module if compiled in
29 #if defined(ConnectEnabled_define)
30 #include <connect_scan.h>
31 #endif
32
33 // Local Includes
34 #include "led_scan.h"
35
36
37
38 // ----- Defines -----
39
40 #define I2C_TxBufferLength 300
41 #define I2C_RxBufferLength 8
42
43 #define LED_BufferLength 144
44
45 // TODO Needs to be defined per keyboard
46 #define LED_TotalChannels 144
47
48
49
50 // ----- Structs -----
51
52 typedef struct I2C_Buffer {
53         uint16_t  head;
54         uint16_t  tail;
55         uint8_t   sequencePos;
56         uint16_t  size;
57         uint8_t  *buffer;
58 } I2C_Buffer;
59
60 typedef struct LED_Buffer {
61         uint8_t i2c_addr;
62         uint8_t reg_addr;
63         uint8_t buffer[LED_BufferLength];
64 } LED_Buffer;
65
66
67
68 // ----- Function Declarations -----
69
70 // CLI Functions
71 void cliFunc_i2cRecv ( char* args );
72 void cliFunc_i2cSend ( char* args );
73 void cliFunc_ledCtrl ( char* args );
74 void cliFunc_ledRPage( char* args );
75 void cliFunc_ledStart( char* args );
76 void cliFunc_ledTest ( char* args );
77 void cliFunc_ledWPage( char* args );
78 void cliFunc_ledZero ( char* args );
79
80 uint8_t I2C_TxBufferPop();
81 void I2C_BufferPush( uint8_t byte, I2C_Buffer *buffer );
82 uint16_t I2C_BufferLen( I2C_Buffer *buffer );
83 uint8_t I2C_Send( uint8_t *data, uint8_t sendLen, uint8_t recvLen );
84
85
86
87 // ----- Variables -----
88
89 // Scan Module command dictionary
90 CLIDict_Entry( i2cRecv,     "Send I2C sequence of bytes and expect a reply of 1 byte on the last sequence." NL "\t\tUse |'s to split sequences with a stop." );
91 CLIDict_Entry( i2cSend,     "Send I2C sequence of bytes. Use |'s to split sequences with a stop." );
92 CLIDict_Entry( ledCtrl,     "Basic LED control. Args: <mode> <amount> [<index>]" );
93 CLIDict_Entry( ledRPage,    "Read the given register page." );
94 CLIDict_Entry( ledStart,    "Disable software shutdown." );
95 CLIDict_Entry( ledTest,     "Test out the led pages." );
96 CLIDict_Entry( ledWPage,    "Write to given register page starting at address. i.e. 0x2 0x24 0xF0 0x12" );
97 CLIDict_Entry( ledZero,     "Zero out LED register pages (non-configuration)." );
98
99 CLIDict_Def( ledCLIDict, "ISSI LED Module Commands" ) = {
100         CLIDict_Item( i2cRecv ),
101         CLIDict_Item( i2cSend ),
102         CLIDict_Item( ledCtrl ),
103         CLIDict_Item( ledRPage ),
104         CLIDict_Item( ledStart ),
105         CLIDict_Item( ledTest ),
106         CLIDict_Item( ledWPage ),
107         CLIDict_Item( ledZero ),
108         { 0, 0, 0 } // Null entry for dictionary end
109 };
110
111
112
113 // Before sending the sequence, I2C_TxBuffer_CurLen is assigned and as each byte is sent, it is decremented
114 // Once I2C_TxBuffer_CurLen reaches zero, a STOP on the I2C bus is sent
115 volatile uint8_t I2C_TxBufferPtr[ I2C_TxBufferLength ];
116 volatile uint8_t I2C_RxBufferPtr[ I2C_TxBufferLength ];
117
118 volatile I2C_Buffer I2C_TxBuffer = { 0, 0, 0, I2C_TxBufferLength, (uint8_t*)I2C_TxBufferPtr };
119 volatile I2C_Buffer I2C_RxBuffer = { 0, 0, 0, I2C_RxBufferLength, (uint8_t*)I2C_RxBufferPtr };
120
121 LED_Buffer LED_pageBuffer;
122
123 // A bit mask determining which LEDs are enabled in the ISSI chip
124 const uint8_t LED_ledEnableMask1[] = {
125         0xE8, // I2C address
126         0x00, // Starting register address
127         ISSILedMask1_define
128 };
129
130 // Default LED brightness
131 const uint8_t LED_defaultBrightness1[] = {
132         0xE8, // I2C address
133         0x24, // Starting register address
134         ISSILedBrightness1_define
135 };
136
137
138
139 // ----- Interrupt Functions -----
140
141 void i2c0_isr()
142 {
143         cli(); // Disable Interrupts
144
145         uint8_t status = I2C0_S; // Read I2C Bus status
146
147         // Master Mode Transmit
148         if ( I2C0_C1 & I2C_C1_TX )
149         {
150                 // Check current use of the I2C bus
151                 // Currently sending data
152                 if ( I2C_TxBuffer.sequencePos > 0 )
153                 {
154                         // Make sure slave sent an ACK
155                         if ( status & I2C_S_RXAK )
156                         {
157                                 // NACK Detected, disable interrupt
158                                 erro_print("I2C NAK detected...");
159                                 I2C0_C1 = I2C_C1_IICEN;
160
161                                 // Abort Tx Buffer
162                                 I2C_TxBuffer.head = 0;
163                                 I2C_TxBuffer.tail = 0;
164                                 I2C_TxBuffer.sequencePos = 0;
165                         }
166                         else
167                         {
168                                 // Transmit byte
169                                 I2C0_D = I2C_TxBufferPop();
170                         }
171                 }
172                 // Receiving data
173                 else if ( I2C_RxBuffer.sequencePos > 0 )
174                 {
175                         // Master Receive, addr sent
176                         if ( status & I2C_S_ARBL )
177                         {
178                                 // Arbitration Lost
179                                 erro_print("Arbitration lost...");
180                                 // TODO Abort Rx
181
182                                 I2C0_C1 = I2C_C1_IICEN;
183                                 I2C0_S = I2C_S_ARBL | I2C_S_IICIF; // Clear ARBL flag and interrupt
184                         }
185                         if ( status & I2C_S_RXAK )
186                         {
187                                 // Slave Address NACK Detected, disable interrupt
188                                 erro_print("Slave Address I2C NAK detected...");
189                                 // TODO Abort Rx
190
191                                 I2C0_C1 = I2C_C1_IICEN;
192                         }
193                         else
194                         {
195                                 dbug_msg("Attempting to read byte - ");
196                                 printHex( I2C_RxBuffer.sequencePos );
197                                 print( NL );
198                                 I2C0_C1 = I2C_RxBuffer.sequencePos == 1
199                                         ? I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TXAK // Single byte read
200                                         : I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST; // Multi-byte read
201                         }
202                 }
203                 else
204                 {
205                         /*
206                         dbug_msg("STOP - ");
207                         printHex( I2C_BufferLen( (I2C_Buffer*)&I2C_TxBuffer ) );
208                         print(NL);
209                         */
210
211                         // Delay around STOP to make sure it actually happens...
212                         delayMicroseconds( 1 );
213                         I2C0_C1 = I2C_C1_IICEN; // Send STOP
214                         delayMicroseconds( 7 );
215
216                         // If there is another sequence, start sending
217                         if ( I2C_BufferLen( (I2C_Buffer*)&I2C_TxBuffer ) < I2C_TxBuffer.size )
218                         {
219                                 // Clear status flags
220                                 I2C0_S = I2C_S_IICIF | I2C_S_ARBL;
221
222                                 // Wait...till the master dies
223                                 while ( I2C0_S & I2C_S_BUSY );
224
225                                 // Enable I2C interrupt
226                                 I2C0_C1 = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TX;
227
228                                 // Transmit byte
229                                 I2C0_D = I2C_TxBufferPop();
230                         }
231                 }
232         }
233         // Master Mode Receive
234         else
235         {
236                 // XXX Do we need to handle 2nd last byte?
237                 //I2C0_C1 = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TXAK; // No STOP, Rx, NAK on recv
238
239                 // Last byte
240                 if ( I2C_TxBuffer.sequencePos <= 1 )
241                 {
242                         // Change to Tx mode
243                         I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
244
245                         // Grab last byte
246                         I2C_BufferPush( I2C0_D, (I2C_Buffer*)&I2C_RxBuffer );
247
248                         delayMicroseconds( 1 ); // Should be enough time before issuing the stop
249                         I2C0_C1 = I2C_C1_IICEN; // Send STOP
250                 }
251                 else
252                 {
253                         // Retrieve data
254                         I2C_BufferPush( I2C0_D, (I2C_Buffer*)&I2C_RxBuffer );
255                 }
256         }
257
258         I2C0_S = I2C_S_IICIF; // Clear interrupt
259
260         sei(); // Re-enable Interrupts
261 }
262
263
264
265 // ----- Functions -----
266
267 inline void I2C_setup()
268 {
269         // Enable I2C internal clock
270         SIM_SCGC4 |= SIM_SCGC4_I2C0; // Bus 0
271
272         // External pull-up resistor
273         PORTB_PCR0 = PORT_PCR_ODE | PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(2);
274         PORTB_PCR1 = PORT_PCR_ODE | PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(2);
275
276         // SCL Frequency Divider
277         // 400kHz -> 120 (0x85) @ 48 MHz F_BUS
278         I2C0_F = 0x85;
279         I2C0_FLT = 4;
280         I2C0_C1 = I2C_C1_IICEN;
281         I2C0_C2 = I2C_C2_HDRS; // High drive select
282
283         // Enable I2C Interrupt
284         NVIC_ENABLE_IRQ( IRQ_I2C0 );
285 }
286
287 void LED_zeroPages( uint8_t startPage, uint8_t numPages, uint8_t startReg, uint8_t endReg )
288 {
289         // Page Setup
290         uint8_t pageSetup[] = { 0xE8, 0xFD, 0x00 };
291
292         // Max length of a page + chip id + reg start
293         uint8_t fullPage[ 0xB4 + 2 ] = { 0 }; // Max size of page
294         fullPage[0] = 0xE8;     // Set chip id
295         fullPage[1] = startReg; // Set start reg
296
297         // Iterate through given pages, zero'ing out the given register regions
298         for ( uint8_t page = startPage; page < startPage + numPages; page++ )
299         {
300                 // Set page
301                 pageSetup[2] = page;
302
303                 // Setup page
304                 while ( I2C_Send( pageSetup, sizeof( pageSetup ), 0 ) == 0 )
305                         delay(1);
306
307                 // Zero out page
308                 while ( I2C_Send( fullPage, endReg - startReg + 2, 0 ) == 0 )
309                         delay(1);
310         }
311 }
312
313 void LED_sendPage( uint8_t *buffer, uint8_t len, uint8_t page )
314 {
315         // Page Setup
316         uint8_t pageSetup[] = { 0xE8, 0xFD, page };
317
318         // Setup page
319         while ( I2C_Send( pageSetup, sizeof( pageSetup ), 0 ) == 0 )
320                 delay(1);
321
322         // Write page to I2C Tx Buffer
323         while ( I2C_Send( buffer, len, 0 ) == 0 )
324                 delay(1);
325
326 }
327
328 void LED_writeReg( uint8_t reg, uint8_t val, uint8_t page )
329 {
330         // Page Setup
331         uint8_t pageSetup[] = { 0xE8, 0xFD, page };
332
333         // Reg Write Setup
334         uint8_t writeData[] = { 0xE8, reg, val };
335
336         // Setup page
337         while ( I2C_Send( pageSetup, sizeof( pageSetup ), 0 ) == 0 )
338                 delay(1);
339
340         while ( I2C_Send( writeData, sizeof( writeData ), 0 ) == 0 )
341                 delay(1);
342 }
343
344 void LED_readPage( uint8_t len, uint8_t page )
345 {
346         // Software shutdown must be enabled to read registers
347         LED_writeReg( 0x0A, 0x00, 0x0B );
348
349         // Page Setup
350         uint8_t pageSetup[] = { 0xE8, 0xFD, page };
351
352         // Setup page
353         while ( I2C_Send( pageSetup, sizeof( pageSetup ), 0 ) == 0 )
354                 delay(1);
355
356         // Register Setup
357         uint8_t regSetup[] = { 0xE8, 0x00 };
358
359         // Read each register in the page
360         for ( uint8_t reg = 0; reg < len; reg++ )
361         {
362                 // Update register to read
363                 regSetup[1] = reg;
364
365                 // Configure register
366                 while ( I2C_Send( regSetup, sizeof( regSetup ), 0 ) == 0 )
367                         delay(1);
368
369                 // Register Read Command
370                 uint8_t regReadCmd[] = { 0xE9 };
371
372                 // Request single register byte
373                 while ( I2C_Send( regReadCmd, sizeof( regReadCmd ), 1 ) == 0 )
374                         delay(1);
375                 dbug_print("NEXT");
376         }
377
378         // Disable software shutdown
379         LED_writeReg( 0x0A, 0x01, 0x0B );
380 }
381
382 // Setup
383 inline void LED_setup()
384 {
385         // Register Scan CLI dictionary
386         CLI_registerDictionary( ledCLIDict, ledCLIDictName );
387
388         // Initialize I2C
389         I2C_setup();
390
391         // Zero out Frame Registers
392         // This needs to be done before disabling the hardware shutdown (or the leds will do undefined things)
393         LED_zeroPages( 0x0B, 1, 0x00, 0x0C ); // Control Registers
394
395         // Disable Hardware shutdown of ISSI chip (pull high)
396         GPIOB_PDDR |= (1<<16);
397         PORTB_PCR16 = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1);
398         GPIOB_PSOR |= (1<<16);
399
400         // Clear LED Pages
401         LED_zeroPages( 0x00, 8, 0x00, 0xB4 ); // LED Registers
402
403         // Enable LEDs based upon mask
404         LED_sendPage( (uint8_t*)LED_ledEnableMask1, sizeof( LED_ledEnableMask1 ), 0 );
405
406         // Set default brightness
407         LED_sendPage( (uint8_t*)LED_defaultBrightness1, sizeof( LED_defaultBrightness1 ), 0 );
408
409         // Disable Software shutdown of ISSI chip
410         LED_writeReg( 0x0A, 0x01, 0x0B );
411 }
412
413
414 inline uint8_t I2C_BufferCopy( uint8_t *data, uint8_t sendLen, uint8_t recvLen, I2C_Buffer *buffer )
415 {
416         uint8_t reTurn = 0;
417
418         // If sendLen is greater than buffer fail right away
419         if ( sendLen > buffer->size )
420                 return 0;
421
422         // Calculate new tail to determine if buffer has enough space
423         // The first element specifies the expected number of bytes from the slave (+1)
424         // The second element in the new buffer is the length of the buffer sequence (+1)
425         uint16_t newTail = buffer->tail + sendLen + 2;
426         if ( newTail >= buffer->size )
427                 newTail -= buffer->size;
428
429         if ( I2C_BufferLen( buffer ) < sendLen + 2 )
430                 return 0;
431
432 /*
433         print("|");
434         printHex( sendLen + 2 );
435         print("|");
436         printHex( *tail );
437         print("@");
438         printHex( newTail );
439         print("@");
440 */
441
442         // If buffer is clean, return 1, otherwise 2
443         reTurn = buffer->head == buffer->tail ? 1 : 2;
444
445         // Add to buffer, already know there is enough room (simplifies adding logic)
446         uint8_t bufferHeaderPos = 0;
447         for ( uint16_t c = 0; c < sendLen; c++ )
448         {
449                 // Add data to buffer
450                 switch ( bufferHeaderPos )
451                 {
452                 case 0:
453                         buffer->buffer[ buffer->tail ] = recvLen;
454                         bufferHeaderPos++;
455                         c--;
456                         break;
457
458                 case 1:
459                         buffer->buffer[ buffer->tail ] = sendLen;
460                         bufferHeaderPos++;
461                         c--;
462                         break;
463
464                 default:
465                         buffer->buffer[ buffer->tail ] = data[ c ];
466                         break;
467                 }
468
469                 // Check for wrap-around case
470                 if ( buffer->tail + 1 >= buffer->size )
471                 {
472                         buffer->tail = 0;
473                 }
474                 // Normal case
475                 else
476                 {
477                         buffer->tail++;
478                 }
479         }
480
481         return reTurn;
482 }
483
484
485 inline uint16_t I2C_BufferLen( I2C_Buffer *buffer )
486 {
487         // Tail >= Head
488         if ( buffer->tail >= buffer->head )
489                 return buffer->head + buffer->size - buffer->tail;
490
491         // Head > Tail
492         return buffer->head - buffer->tail;
493 }
494
495
496 void I2C_BufferPush( uint8_t byte, I2C_Buffer *buffer )
497 {
498         dbug_msg("DATA: ");
499         printHex( byte );
500
501         // Make sure buffer isn't full
502         if ( buffer->tail + 1 == buffer->head || ( buffer->head > buffer->tail && buffer->tail + 1 - buffer->size == buffer->head ) )
503         {
504                 warn_msg("I2C_BufferPush failed, buffer full: ");
505                 printHex( byte );
506                 print( NL );
507                 return;
508         }
509
510         // Check for wrap-around case
511         if ( buffer->tail + 1 >= buffer->size )
512         {
513                 buffer->tail = 0;
514         }
515         // Normal case
516         else
517         {
518                 buffer->tail++;
519         }
520
521         // Add byte to buffer
522         buffer->buffer[ buffer->tail ] = byte;
523 }
524
525
526 uint8_t I2C_TxBufferPop()
527 {
528         // Return 0xFF if no buffer left (do not rely on this)
529         if ( I2C_BufferLen( (I2C_Buffer*)&I2C_TxBuffer ) >= I2C_TxBuffer.size )
530         {
531                 erro_msg("No buffer to pop an entry from... ");
532                 printHex( I2C_TxBuffer.head );
533                 print(" ");
534                 printHex( I2C_TxBuffer.tail );
535                 print(" ");
536                 printHex( I2C_TxBuffer.sequencePos );
537                 print(NL);
538                 return 0xFF;
539         }
540
541         // If there is currently no sequence being sent, the first entry in the RingBuffer is the length
542         if ( I2C_TxBuffer.sequencePos == 0 )
543         {
544                 I2C_TxBuffer.sequencePos = 0xFF; // So this doesn't become an infinite loop
545                 I2C_RxBuffer.sequencePos = I2C_TxBufferPop();
546                 I2C_TxBuffer.sequencePos = I2C_TxBufferPop();
547         }
548
549         uint8_t data = I2C_TxBuffer.buffer[ I2C_TxBuffer.head ];
550
551         // Prune head
552         I2C_TxBuffer.head++;
553
554         // Wrap-around case
555         if ( I2C_TxBuffer.head >= I2C_TxBuffer.size )
556                 I2C_TxBuffer.head = 0;
557
558         // Decrement buffer sequence (until next stop will be sent)
559         I2C_TxBuffer.sequencePos--;
560
561         /*
562         dbug_msg("Popping: ");
563         printHex( data );
564         print(" ");
565         printHex( I2C_TxBuffer.head );
566         print(" ");
567         printHex( I2C_TxBuffer.tail );
568         print(" ");
569         printHex( I2C_TxBuffer.sequencePos );
570         print(NL);
571         */
572         return data;
573 }
574
575
576 uint8_t I2C_Send( uint8_t *data, uint8_t sendLen, uint8_t recvLen )
577 {
578         // Check head and tail pointers
579         // If full, return 0
580         // If empty, start up I2C Master Tx
581         // If buffer is non-empty and non-full, just append to the buffer
582         switch ( I2C_BufferCopy( data, sendLen, recvLen, (I2C_Buffer*)&I2C_TxBuffer ) )
583         {
584         // Not enough buffer space...
585         case 0:
586                 /*
587                 erro_msg("Not enough Tx buffer space... ");
588                 printHex( I2C_TxBuffer.head );
589                 print(":");
590                 printHex( I2C_TxBuffer.tail );
591                 print("+");
592                 printHex( sendLen );
593                 print("|");
594                 printHex( I2C_TxBuffer.size );
595                 print( NL );
596                 */
597                 return 0;
598
599         // Empty buffer, initialize I2C
600         case 1:
601                 // Clear status flags
602                 I2C0_S = I2C_S_IICIF | I2C_S_ARBL;
603
604                 // Check to see if we already have control of the bus
605                 if ( I2C0_C1 & I2C_C1_MST )
606                 {
607                         // Already the master (ah yeah), send a repeated start
608                         I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_RSTA | I2C_C1_TX;
609                 }
610                 // Otherwise, seize control
611                 else
612                 {
613                         // Wait...till the master dies
614                         while ( I2C0_S & I2C_S_BUSY );
615
616                         // Now we're the master (ah yisss), get ready to send stuffs
617                         I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
618                 }
619
620                 // Enable I2C interrupt
621                 I2C0_C1 = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TX;
622
623                 // Depending on what type of transfer, the first byte is configured for R or W
624                 I2C0_D = I2C_TxBufferPop();
625
626                 return 1;
627         }
628
629         // Dirty buffer, I2C already initialized
630         return 2;
631 }
632
633
634
635 // LED State processing loop
636 inline uint8_t LED_scan()
637 {
638
639         // I2C Busy
640         // S & I2C_S_BUSY
641         //I2C_S_BUSY
642
643         return 0;
644 }
645
646
647
648 // ----- Capabilities -----
649
650 // Basic LED Control Capability
651 typedef enum LedControlMode {
652         // Single LED Modes
653         LedControlMode_brightness_decrease,
654         LedControlMode_brightness_increase,
655         LedControlMode_brightness_set,
656         // Set all LEDs (index argument not required)
657         LedControlMode_brightness_decrease_all,
658         LedControlMode_brightness_increase_all,
659         LedControlMode_brightness_set_all,
660 } LedControlMode;
661
662 typedef struct LedControl {
663         LedControlMode mode;   // XXX Make sure to adjust the .kll capability if this variable is larger than 8 bits
664         uint8_t        amount;
665         uint16_t       index;
666 } LedControl;
667
668 void LED_control( LedControl *control )
669 {
670         // Only send if we've completed all other transactions
671         /*
672         if ( I2C_TxBuffer.sequencePos > 0 )
673                 return;
674         */
675
676         // Configure based upon the given mode
677         // TODO Perhaps do gamma adjustment?
678         switch ( control->mode )
679         {
680         case LedControlMode_brightness_decrease:
681                 // Don't worry about rolling over, the cycle is quick
682                 LED_pageBuffer.buffer[ control->index ] -= control->amount;
683                 break;
684
685         case LedControlMode_brightness_increase:
686                 // Don't worry about rolling over, the cycle is quick
687                 LED_pageBuffer.buffer[ control->index ] += control->amount;
688                 break;
689
690         case LedControlMode_brightness_set:
691                 LED_pageBuffer.buffer[ control->index ] = control->amount;
692                 break;
693
694         case LedControlMode_brightness_decrease_all:
695                 for ( uint8_t channel = 0; channel < LED_TotalChannels; channel++ )
696                 {
697                         // Don't worry about rolling over, the cycle is quick
698                         LED_pageBuffer.buffer[ channel ] -= control->amount;
699                 }
700                 break;
701
702         case LedControlMode_brightness_increase_all:
703                 for ( uint8_t channel = 0; channel < LED_TotalChannels; channel++ )
704                 {
705                         // Don't worry about rolling over, the cycle is quick
706                         LED_pageBuffer.buffer[ channel ] += control->amount;
707                 }
708                 break;
709
710         case LedControlMode_brightness_set_all:
711                 for ( uint8_t channel = 0; channel < LED_TotalChannels; channel++ )
712                 {
713                         LED_pageBuffer.buffer[ channel ] = control->amount;
714                 }
715                 break;
716         }
717
718         // Sync LED buffer with ISSI chip buffer
719         // TODO Support multiple frames
720         LED_pageBuffer.i2c_addr = 0xE8; // Chip 1
721         LED_pageBuffer.reg_addr = 0x24; // Brightness section
722         LED_sendPage( (uint8_t*)&LED_pageBuffer, sizeof( LED_Buffer ), 0 );
723 }
724
725 uint8_t LED_control_timer = 0;
726 void LED_control_capability( uint8_t state, uint8_t stateType, uint8_t *args )
727 {
728         // Display capability name
729         if ( stateType == 0xFF && state == 0xFF )
730         {
731                 print("LED_control_capability(mode,amount,index)");
732                 return;
733         }
734
735         // Only use capability on press
736         // TODO Analog
737         if ( stateType == 0x00 && state == 0x03 ) // Not on release
738                 return;
739
740         // XXX
741         // ISSI Chip locks up if we spam updates too quickly (might be an I2C bug on this side too -HaaTa)
742         // Make sure we only send an update every 30 milliseconds at most
743         // It may be possible to optimize speed even further, but will likely require serious time with a logic analyzer
744
745         uint8_t currentTime = (uint8_t)systick_millis_count;
746         int8_t compare = (int8_t)(currentTime - LED_control_timer) & 0x7F;
747         if ( compare < 30 )
748         {
749                 return;
750         }
751         LED_control_timer = currentTime;
752
753         // Set the input structure
754         LedControl *control = (LedControl*)args;
755
756         // Interconnect broadcasting
757 #if defined(ConnectEnabled_define)
758         uint8_t send_packet = 0;
759         uint8_t ignore_node = 0;
760
761         // By default send to the *next* node, which will determine where to go next
762         extern uint8_t Connect_id; // connect_scan.c
763         uint8_t addr = Connect_id + 1;
764
765         switch ( control->mode )
766         {
767         // Calculate the led address to send
768         // If greater than the Total hannels
769         // Set address - Total channels
770         // Otherwise, ignore
771         case LedControlMode_brightness_decrease:
772         case LedControlMode_brightness_increase:
773         case LedControlMode_brightness_set:
774                 // Ignore if led is on this node
775                 if ( control->index < LED_TotalChannels )
776                         break;
777
778                 // Calculate new led index
779                 control->index -= LED_TotalChannels;
780
781                 ignore_node = 1;
782                 send_packet = 1;
783                 break;
784
785         // Broadcast to all nodes
786         // XXX Do not set broadcasting address
787         //     Will send command twice
788         case LedControlMode_brightness_decrease_all:
789         case LedControlMode_brightness_increase_all:
790         case LedControlMode_brightness_set_all:
791                 send_packet = 1;
792                 break;
793         }
794
795         // Only send interconnect remote capability packet if necessary
796         if ( send_packet )
797         {
798                 // generatedKeymap.h
799                 extern const Capability CapabilitiesList[];
800
801                 // Broadcast layerStackExact remote capability (0xFF is the broadcast id)
802                 Connect_send_RemoteCapability(
803                         addr,
804                         LED_control_capability_index,
805                         state,
806                         stateType,
807                         CapabilitiesList[ LED_control_capability_index ].argCount,
808                         args
809                 );
810         }
811
812         // If there is nothing to do on this node, ignore
813         if ( ignore_node )
814                 return;
815 #endif
816
817         // Modify led state of this node
818         LED_control( control );
819 }
820
821
822
823 // ----- CLI Command Functions -----
824
825 // TODO Currently not working correctly
826 void cliFunc_i2cSend( char* args )
827 {
828         char* curArgs;
829         char* arg1Ptr;
830         char* arg2Ptr = args;
831
832         // Buffer used after interpretting the args, will be sent to I2C functions
833         // NOTE: Limited to 8 bytes currently (can be increased if necessary
834         #define i2cSend_BuffLenMax 8
835         uint8_t buffer[ i2cSend_BuffLenMax ];
836         uint8_t bufferLen = 0;
837
838         // No \r\n by default after the command is entered
839         print( NL );
840         info_msg("Sending: ");
841
842         // Parse args until a \0 is found
843         while ( bufferLen < i2cSend_BuffLenMax )
844         {
845                 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
846                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
847
848                 // Stop processing args if no more are found
849                 if ( *arg1Ptr == '\0' )
850                         break;
851
852                 // If | is found, end sequence and start new one
853                 if ( *arg1Ptr == '|' )
854                 {
855                         print("| ");
856                         I2C_Send( buffer, bufferLen, 0 );
857                         bufferLen = 0;
858                         continue;
859                 }
860
861                 // Interpret the argument
862                 buffer[ bufferLen++ ] = (uint8_t)numToInt( arg1Ptr );
863
864                 // Print out the arg
865                 dPrint( arg1Ptr );
866                 print(" ");
867         }
868
869         print( NL );
870
871         I2C_Send( buffer, bufferLen, 0 );
872 }
873
874 void cliFunc_i2cRecv( char* args )
875 {
876         char* curArgs;
877         char* arg1Ptr;
878         char* arg2Ptr = args;
879
880         // Buffer used after interpretting the args, will be sent to I2C functions
881         // NOTE: Limited to 8 bytes currently (can be increased if necessary
882         #define i2cSend_BuffLenMax 8
883         uint8_t buffer[ i2cSend_BuffLenMax ];
884         uint8_t bufferLen = 0;
885
886         // No \r\n by default after the command is entered
887         print( NL );
888         info_msg("Sending: ");
889
890         // Parse args until a \0 is found
891         while ( bufferLen < i2cSend_BuffLenMax )
892         {
893                 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
894                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
895
896                 // Stop processing args if no more are found
897                 if ( *arg1Ptr == '\0' )
898                         break;
899
900                 // If | is found, end sequence and start new one
901                 if ( *arg1Ptr == '|' )
902                 {
903                         print("| ");
904                         I2C_Send( buffer, bufferLen, 0 );
905                         bufferLen = 0;
906                         continue;
907                 }
908
909                 // Interpret the argument
910                 buffer[ bufferLen++ ] = (uint8_t)numToInt( arg1Ptr );
911
912                 // Print out the arg
913                 dPrint( arg1Ptr );
914                 print(" ");
915         }
916
917         print( NL );
918
919         I2C_Send( buffer, bufferLen, 1 ); // Only 1 byte is ever read at a time with the ISSI chip
920 }
921
922 // TODO Currently not working correctly
923 void cliFunc_ledRPage( char* args )
924 {
925         // Parse number from argument
926         //  NOTE: Only first argument is used
927         char* arg1Ptr;
928         char* arg2Ptr;
929         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
930
931         // Default to 0 if no argument is given
932         uint8_t page = 0;
933
934         if ( arg1Ptr[0] != '\0' )
935         {
936                 page = (uint8_t)numToInt( arg1Ptr );
937         }
938
939         // No \r\n by default after the command is entered
940         print( NL );
941
942         LED_readPage( 0x1, page );
943         //LED_readPage( 0xB4, page );
944 }
945
946 void cliFunc_ledWPage( char* args )
947 {
948         char* curArgs;
949         char* arg1Ptr;
950         char* arg2Ptr = args;
951
952         // First process page and starting address
953         curArgs = arg2Ptr;
954         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
955
956         // Stop processing args if no more are found
957         if ( *arg1Ptr == '\0' )
958                 return;
959         uint8_t page[] = { 0xE8, 0xFD, numToInt( arg1Ptr ) };
960
961         curArgs = arg2Ptr;
962         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
963
964         // Stop processing args if no more are found
965         if ( *arg1Ptr == '\0' )
966                 return;
967         uint8_t data[] = { 0xE8, numToInt( arg1Ptr ), 0 };
968
969         // Set the register page
970         while ( I2C_Send( page, sizeof( page ), 0 ) == 0 )
971                 delay(1);
972
973         // Process all args
974         for ( ;; )
975         {
976                 curArgs = arg2Ptr;
977                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
978
979                 // Stop processing args if no more are found
980                 if ( *arg1Ptr == '\0' )
981                         break;
982
983                 data[2] = numToInt( arg1Ptr );
984
985                 // Write register location and data to I2C
986                 while ( I2C_Send( data, sizeof( data ), 0 ) == 0 )
987                         delay(1);
988
989                 // Increment address
990                 data[1]++;
991         }
992 }
993
994 void cliFunc_ledStart( char* args )
995 {
996         print( NL ); // No \r\n by default after the command is entered
997         LED_zeroPages( 0x0B, 1, 0x00, 0x0C ); // Control Registers
998         //LED_zeroPages( 0x00, 8, 0x00, 0xB4 ); // LED Registers
999         LED_writeReg( 0x0A, 0x01, 0x0B );
1000         LED_sendPage( (uint8_t*)LED_ledEnableMask1, sizeof( LED_ledEnableMask1 ), 0 );
1001
1002 }
1003
1004 void cliFunc_ledTest( char* args )
1005 {
1006         print( NL ); // No \r\n by default after the command is entered
1007         LED_sendPage( (uint8_t*)LED_defaultBrightness1, sizeof( LED_defaultBrightness1 ), 0 );
1008 }
1009
1010 void cliFunc_ledZero( char* args )
1011 {
1012         print( NL ); // No \r\n by default after the command is entered
1013         LED_zeroPages( 0x00, 8, 0x24, 0xB4 ); // Only PWMs
1014 }
1015
1016 void cliFunc_ledCtrl( char* args )
1017 {
1018         char* curArgs;
1019         char* arg1Ptr;
1020         char* arg2Ptr = args;
1021         LedControl control;
1022
1023         // First process mode
1024         curArgs = arg2Ptr;
1025         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1026
1027         // Stop processing args if no more are found
1028         if ( *arg1Ptr == '\0' )
1029                 return;
1030         control.mode = numToInt( arg1Ptr );
1031
1032
1033         // Next process amount
1034         curArgs = arg2Ptr;
1035         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1036
1037         // Stop processing args if no more are found
1038         if ( *arg1Ptr == '\0' )
1039                 return;
1040         control.amount = numToInt( arg1Ptr );
1041
1042
1043         // Finally process led index, if it exists
1044         // Default to 0
1045         curArgs = arg2Ptr;
1046         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1047         control.index = *arg1Ptr == '\0' ? 0 : numToInt( arg1Ptr );
1048
1049         // Process request
1050         LED_control( &control );
1051 }
1052