]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/ISSILed/led_scan.c
Adding dynamic USB power support
[kiibohd-controller.git] / Scan / ISSILed / led_scan.c
1 /* Copyright (C) 2014-2016 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         // Do not disable software shutdown of ISSI chip unless current is high enough
410         // Require at least 150 mA
411         // May be enabled/disabled at a later time
412         if ( Output_current_available() >= 150 )
413         {
414                 // Disable Software shutdown of ISSI chip
415                 LED_writeReg( 0x0A, 0x01, 0x0B );
416         }
417 }
418
419
420 inline uint8_t I2C_BufferCopy( uint8_t *data, uint8_t sendLen, uint8_t recvLen, I2C_Buffer *buffer )
421 {
422         uint8_t reTurn = 0;
423
424         // If sendLen is greater than buffer fail right away
425         if ( sendLen > buffer->size )
426                 return 0;
427
428         // Calculate new tail to determine if buffer has enough space
429         // The first element specifies the expected number of bytes from the slave (+1)
430         // The second element in the new buffer is the length of the buffer sequence (+1)
431         uint16_t newTail = buffer->tail + sendLen + 2;
432         if ( newTail >= buffer->size )
433                 newTail -= buffer->size;
434
435         if ( I2C_BufferLen( buffer ) < sendLen + 2 )
436                 return 0;
437
438 /*
439         print("|");
440         printHex( sendLen + 2 );
441         print("|");
442         printHex( *tail );
443         print("@");
444         printHex( newTail );
445         print("@");
446 */
447
448         // If buffer is clean, return 1, otherwise 2
449         reTurn = buffer->head == buffer->tail ? 1 : 2;
450
451         // Add to buffer, already know there is enough room (simplifies adding logic)
452         uint8_t bufferHeaderPos = 0;
453         for ( uint16_t c = 0; c < sendLen; c++ )
454         {
455                 // Add data to buffer
456                 switch ( bufferHeaderPos )
457                 {
458                 case 0:
459                         buffer->buffer[ buffer->tail ] = recvLen;
460                         bufferHeaderPos++;
461                         c--;
462                         break;
463
464                 case 1:
465                         buffer->buffer[ buffer->tail ] = sendLen;
466                         bufferHeaderPos++;
467                         c--;
468                         break;
469
470                 default:
471                         buffer->buffer[ buffer->tail ] = data[ c ];
472                         break;
473                 }
474
475                 // Check for wrap-around case
476                 if ( buffer->tail + 1 >= buffer->size )
477                 {
478                         buffer->tail = 0;
479                 }
480                 // Normal case
481                 else
482                 {
483                         buffer->tail++;
484                 }
485         }
486
487         return reTurn;
488 }
489
490
491 inline uint16_t I2C_BufferLen( I2C_Buffer *buffer )
492 {
493         // Tail >= Head
494         if ( buffer->tail >= buffer->head )
495                 return buffer->head + buffer->size - buffer->tail;
496
497         // Head > Tail
498         return buffer->head - buffer->tail;
499 }
500
501
502 void I2C_BufferPush( uint8_t byte, I2C_Buffer *buffer )
503 {
504         dbug_msg("DATA: ");
505         printHex( byte );
506
507         // Make sure buffer isn't full
508         if ( buffer->tail + 1 == buffer->head || ( buffer->head > buffer->tail && buffer->tail + 1 - buffer->size == buffer->head ) )
509         {
510                 warn_msg("I2C_BufferPush failed, buffer full: ");
511                 printHex( byte );
512                 print( NL );
513                 return;
514         }
515
516         // Check for wrap-around case
517         if ( buffer->tail + 1 >= buffer->size )
518         {
519                 buffer->tail = 0;
520         }
521         // Normal case
522         else
523         {
524                 buffer->tail++;
525         }
526
527         // Add byte to buffer
528         buffer->buffer[ buffer->tail ] = byte;
529 }
530
531
532 uint8_t I2C_TxBufferPop()
533 {
534         // Return 0xFF if no buffer left (do not rely on this)
535         if ( I2C_BufferLen( (I2C_Buffer*)&I2C_TxBuffer ) >= I2C_TxBuffer.size )
536         {
537                 erro_msg("No buffer to pop an entry from... ");
538                 printHex( I2C_TxBuffer.head );
539                 print(" ");
540                 printHex( I2C_TxBuffer.tail );
541                 print(" ");
542                 printHex( I2C_TxBuffer.sequencePos );
543                 print(NL);
544                 return 0xFF;
545         }
546
547         // If there is currently no sequence being sent, the first entry in the RingBuffer is the length
548         if ( I2C_TxBuffer.sequencePos == 0 )
549         {
550                 I2C_TxBuffer.sequencePos = 0xFF; // So this doesn't become an infinite loop
551                 I2C_RxBuffer.sequencePos = I2C_TxBufferPop();
552                 I2C_TxBuffer.sequencePos = I2C_TxBufferPop();
553         }
554
555         uint8_t data = I2C_TxBuffer.buffer[ I2C_TxBuffer.head ];
556
557         // Prune head
558         I2C_TxBuffer.head++;
559
560         // Wrap-around case
561         if ( I2C_TxBuffer.head >= I2C_TxBuffer.size )
562                 I2C_TxBuffer.head = 0;
563
564         // Decrement buffer sequence (until next stop will be sent)
565         I2C_TxBuffer.sequencePos--;
566
567         /*
568         dbug_msg("Popping: ");
569         printHex( data );
570         print(" ");
571         printHex( I2C_TxBuffer.head );
572         print(" ");
573         printHex( I2C_TxBuffer.tail );
574         print(" ");
575         printHex( I2C_TxBuffer.sequencePos );
576         print(NL);
577         */
578         return data;
579 }
580
581
582 uint8_t I2C_Send( uint8_t *data, uint8_t sendLen, uint8_t recvLen )
583 {
584         // Check head and tail pointers
585         // If full, return 0
586         // If empty, start up I2C Master Tx
587         // If buffer is non-empty and non-full, just append to the buffer
588         switch ( I2C_BufferCopy( data, sendLen, recvLen, (I2C_Buffer*)&I2C_TxBuffer ) )
589         {
590         // Not enough buffer space...
591         case 0:
592                 /*
593                 erro_msg("Not enough Tx buffer space... ");
594                 printHex( I2C_TxBuffer.head );
595                 print(":");
596                 printHex( I2C_TxBuffer.tail );
597                 print("+");
598                 printHex( sendLen );
599                 print("|");
600                 printHex( I2C_TxBuffer.size );
601                 print( NL );
602                 */
603                 return 0;
604
605         // Empty buffer, initialize I2C
606         case 1:
607                 // Clear status flags
608                 I2C0_S = I2C_S_IICIF | I2C_S_ARBL;
609
610                 // Check to see if we already have control of the bus
611                 if ( I2C0_C1 & I2C_C1_MST )
612                 {
613                         // Already the master (ah yeah), send a repeated start
614                         I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_RSTA | I2C_C1_TX;
615                 }
616                 // Otherwise, seize control
617                 else
618                 {
619                         // Wait...till the master dies
620                         while ( I2C0_S & I2C_S_BUSY );
621
622                         // Now we're the master (ah yisss), get ready to send stuffs
623                         I2C0_C1 = I2C_C1_IICEN | I2C_C1_MST | I2C_C1_TX;
624                 }
625
626                 // Enable I2C interrupt
627                 I2C0_C1 = I2C_C1_IICEN | I2C_C1_IICIE | I2C_C1_MST | I2C_C1_TX;
628
629                 // Depending on what type of transfer, the first byte is configured for R or W
630                 I2C0_D = I2C_TxBufferPop();
631
632                 return 1;
633         }
634
635         // Dirty buffer, I2C already initialized
636         return 2;
637 }
638
639
640
641 // LED State processing loop
642 inline uint8_t LED_scan()
643 {
644
645         // I2C Busy
646         // S & I2C_S_BUSY
647         //I2C_S_BUSY
648
649         return 0;
650 }
651
652
653 // Called by parent Scan Module whenver the available current has changed
654 // current - mA
655 void LED_currentChange( unsigned int current )
656 {
657         // TODO dim LEDs in low power mode instead of shutting off
658         if ( current < 150 )
659         {
660                 // Enabled Software shutdown of ISSI chip
661                 LED_writeReg( 0x0A, 0x00, 0x0B );
662         }
663         else
664         {
665                 // Disable Software shutdown of ISSI chip
666                 LED_writeReg( 0x0A, 0x01, 0x0B );
667         }
668 }
669
670
671
672 // ----- Capabilities -----
673
674 // Basic LED Control Capability
675 typedef enum LedControlMode {
676         // Single LED Modes
677         LedControlMode_brightness_decrease,
678         LedControlMode_brightness_increase,
679         LedControlMode_brightness_set,
680         // Set all LEDs (index argument not required)
681         LedControlMode_brightness_decrease_all,
682         LedControlMode_brightness_increase_all,
683         LedControlMode_brightness_set_all,
684 } LedControlMode;
685
686 typedef struct LedControl {
687         LedControlMode mode;   // XXX Make sure to adjust the .kll capability if this variable is larger than 8 bits
688         uint8_t        amount;
689         uint16_t       index;
690 } LedControl;
691
692 void LED_control( LedControl *control )
693 {
694         // Only send if we've completed all other transactions
695         /*
696         if ( I2C_TxBuffer.sequencePos > 0 )
697                 return;
698         */
699
700         // Configure based upon the given mode
701         // TODO Perhaps do gamma adjustment?
702         switch ( control->mode )
703         {
704         case LedControlMode_brightness_decrease:
705                 // Don't worry about rolling over, the cycle is quick
706                 LED_pageBuffer.buffer[ control->index ] -= control->amount;
707                 break;
708
709         case LedControlMode_brightness_increase:
710                 // Don't worry about rolling over, the cycle is quick
711                 LED_pageBuffer.buffer[ control->index ] += control->amount;
712                 break;
713
714         case LedControlMode_brightness_set:
715                 LED_pageBuffer.buffer[ control->index ] = control->amount;
716                 break;
717
718         case LedControlMode_brightness_decrease_all:
719                 for ( uint8_t channel = 0; channel < LED_TotalChannels; channel++ )
720                 {
721                         // Don't worry about rolling over, the cycle is quick
722                         LED_pageBuffer.buffer[ channel ] -= control->amount;
723                 }
724                 break;
725
726         case LedControlMode_brightness_increase_all:
727                 for ( uint8_t channel = 0; channel < LED_TotalChannels; channel++ )
728                 {
729                         // Don't worry about rolling over, the cycle is quick
730                         LED_pageBuffer.buffer[ channel ] += control->amount;
731                 }
732                 break;
733
734         case LedControlMode_brightness_set_all:
735                 for ( uint8_t channel = 0; channel < LED_TotalChannels; channel++ )
736                 {
737                         LED_pageBuffer.buffer[ channel ] = control->amount;
738                 }
739                 break;
740         }
741
742         // Sync LED buffer with ISSI chip buffer
743         // TODO Support multiple frames
744         LED_pageBuffer.i2c_addr = 0xE8; // Chip 1
745         LED_pageBuffer.reg_addr = 0x24; // Brightness section
746         LED_sendPage( (uint8_t*)&LED_pageBuffer, sizeof( LED_Buffer ), 0 );
747 }
748
749 uint8_t LED_control_timer = 0;
750 void LED_control_capability( uint8_t state, uint8_t stateType, uint8_t *args )
751 {
752         // Display capability name
753         if ( stateType == 0xFF && state == 0xFF )
754         {
755                 print("LED_control_capability(mode,amount,index)");
756                 return;
757         }
758
759         // Only use capability on press
760         // TODO Analog
761         if ( stateType == 0x00 && state == 0x03 ) // Not on release
762                 return;
763
764         // XXX
765         // ISSI Chip locks up if we spam updates too quickly (might be an I2C bug on this side too -HaaTa)
766         // Make sure we only send an update every 30 milliseconds at most
767         // It may be possible to optimize speed even further, but will likely require serious time with a logic analyzer
768
769         uint8_t currentTime = (uint8_t)systick_millis_count;
770         int8_t compare = (int8_t)(currentTime - LED_control_timer) & 0x7F;
771         if ( compare < 30 )
772         {
773                 return;
774         }
775         LED_control_timer = currentTime;
776
777         // Set the input structure
778         LedControl *control = (LedControl*)args;
779
780         // Interconnect broadcasting
781 #if defined(ConnectEnabled_define)
782         uint8_t send_packet = 0;
783         uint8_t ignore_node = 0;
784
785         // By default send to the *next* node, which will determine where to go next
786         extern uint8_t Connect_id; // connect_scan.c
787         uint8_t addr = Connect_id + 1;
788
789         switch ( control->mode )
790         {
791         // Calculate the led address to send
792         // If greater than the Total hannels
793         // Set address - Total channels
794         // Otherwise, ignore
795         case LedControlMode_brightness_decrease:
796         case LedControlMode_brightness_increase:
797         case LedControlMode_brightness_set:
798                 // Ignore if led is on this node
799                 if ( control->index < LED_TotalChannels )
800                         break;
801
802                 // Calculate new led index
803                 control->index -= LED_TotalChannels;
804
805                 ignore_node = 1;
806                 send_packet = 1;
807                 break;
808
809         // Broadcast to all nodes
810         // XXX Do not set broadcasting address
811         //     Will send command twice
812         case LedControlMode_brightness_decrease_all:
813         case LedControlMode_brightness_increase_all:
814         case LedControlMode_brightness_set_all:
815                 send_packet = 1;
816                 break;
817         }
818
819         // Only send interconnect remote capability packet if necessary
820         if ( send_packet )
821         {
822                 // generatedKeymap.h
823                 extern const Capability CapabilitiesList[];
824
825                 // Broadcast layerStackExact remote capability (0xFF is the broadcast id)
826                 Connect_send_RemoteCapability(
827                         addr,
828                         LED_control_capability_index,
829                         state,
830                         stateType,
831                         CapabilitiesList[ LED_control_capability_index ].argCount,
832                         args
833                 );
834         }
835
836         // If there is nothing to do on this node, ignore
837         if ( ignore_node )
838                 return;
839 #endif
840
841         // Modify led state of this node
842         LED_control( control );
843 }
844
845
846
847 // ----- CLI Command Functions -----
848
849 // TODO Currently not working correctly
850 void cliFunc_i2cSend( char* args )
851 {
852         char* curArgs;
853         char* arg1Ptr;
854         char* arg2Ptr = args;
855
856         // Buffer used after interpretting the args, will be sent to I2C functions
857         // NOTE: Limited to 8 bytes currently (can be increased if necessary
858         #define i2cSend_BuffLenMax 8
859         uint8_t buffer[ i2cSend_BuffLenMax ];
860         uint8_t bufferLen = 0;
861
862         // No \r\n by default after the command is entered
863         print( NL );
864         info_msg("Sending: ");
865
866         // Parse args until a \0 is found
867         while ( bufferLen < i2cSend_BuffLenMax )
868         {
869                 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
870                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
871
872                 // Stop processing args if no more are found
873                 if ( *arg1Ptr == '\0' )
874                         break;
875
876                 // If | is found, end sequence and start new one
877                 if ( *arg1Ptr == '|' )
878                 {
879                         print("| ");
880                         I2C_Send( buffer, bufferLen, 0 );
881                         bufferLen = 0;
882                         continue;
883                 }
884
885                 // Interpret the argument
886                 buffer[ bufferLen++ ] = (uint8_t)numToInt( arg1Ptr );
887
888                 // Print out the arg
889                 dPrint( arg1Ptr );
890                 print(" ");
891         }
892
893         print( NL );
894
895         I2C_Send( buffer, bufferLen, 0 );
896 }
897
898 void cliFunc_i2cRecv( char* args )
899 {
900         char* curArgs;
901         char* arg1Ptr;
902         char* arg2Ptr = args;
903
904         // Buffer used after interpretting the args, will be sent to I2C functions
905         // NOTE: Limited to 8 bytes currently (can be increased if necessary
906         #define i2cSend_BuffLenMax 8
907         uint8_t buffer[ i2cSend_BuffLenMax ];
908         uint8_t bufferLen = 0;
909
910         // No \r\n by default after the command is entered
911         print( NL );
912         info_msg("Sending: ");
913
914         // Parse args until a \0 is found
915         while ( bufferLen < i2cSend_BuffLenMax )
916         {
917                 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
918                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
919
920                 // Stop processing args if no more are found
921                 if ( *arg1Ptr == '\0' )
922                         break;
923
924                 // If | is found, end sequence and start new one
925                 if ( *arg1Ptr == '|' )
926                 {
927                         print("| ");
928                         I2C_Send( buffer, bufferLen, 0 );
929                         bufferLen = 0;
930                         continue;
931                 }
932
933                 // Interpret the argument
934                 buffer[ bufferLen++ ] = (uint8_t)numToInt( arg1Ptr );
935
936                 // Print out the arg
937                 dPrint( arg1Ptr );
938                 print(" ");
939         }
940
941         print( NL );
942
943         I2C_Send( buffer, bufferLen, 1 ); // Only 1 byte is ever read at a time with the ISSI chip
944 }
945
946 // TODO Currently not working correctly
947 void cliFunc_ledRPage( char* args )
948 {
949         // Parse number from argument
950         //  NOTE: Only first argument is used
951         char* arg1Ptr;
952         char* arg2Ptr;
953         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
954
955         // Default to 0 if no argument is given
956         uint8_t page = 0;
957
958         if ( arg1Ptr[0] != '\0' )
959         {
960                 page = (uint8_t)numToInt( arg1Ptr );
961         }
962
963         // No \r\n by default after the command is entered
964         print( NL );
965
966         LED_readPage( 0x1, page );
967         //LED_readPage( 0xB4, page );
968 }
969
970 void cliFunc_ledWPage( char* args )
971 {
972         char* curArgs;
973         char* arg1Ptr;
974         char* arg2Ptr = args;
975
976         // First process page and starting address
977         curArgs = arg2Ptr;
978         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
979
980         // Stop processing args if no more are found
981         if ( *arg1Ptr == '\0' )
982                 return;
983         uint8_t page[] = { 0xE8, 0xFD, numToInt( arg1Ptr ) };
984
985         curArgs = arg2Ptr;
986         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
987
988         // Stop processing args if no more are found
989         if ( *arg1Ptr == '\0' )
990                 return;
991         uint8_t data[] = { 0xE8, numToInt( arg1Ptr ), 0 };
992
993         // Set the register page
994         while ( I2C_Send( page, sizeof( page ), 0 ) == 0 )
995                 delay(1);
996
997         // Process all args
998         for ( ;; )
999         {
1000                 curArgs = arg2Ptr;
1001                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1002
1003                 // Stop processing args if no more are found
1004                 if ( *arg1Ptr == '\0' )
1005                         break;
1006
1007                 data[2] = numToInt( arg1Ptr );
1008
1009                 // Write register location and data to I2C
1010                 while ( I2C_Send( data, sizeof( data ), 0 ) == 0 )
1011                         delay(1);
1012
1013                 // Increment address
1014                 data[1]++;
1015         }
1016 }
1017
1018 void cliFunc_ledStart( char* args )
1019 {
1020         print( NL ); // No \r\n by default after the command is entered
1021         LED_zeroPages( 0x0B, 1, 0x00, 0x0C ); // Control Registers
1022         //LED_zeroPages( 0x00, 8, 0x00, 0xB4 ); // LED Registers
1023         LED_writeReg( 0x0A, 0x01, 0x0B );
1024         LED_sendPage( (uint8_t*)LED_ledEnableMask1, sizeof( LED_ledEnableMask1 ), 0 );
1025
1026 }
1027
1028 void cliFunc_ledTest( char* args )
1029 {
1030         print( NL ); // No \r\n by default after the command is entered
1031         LED_sendPage( (uint8_t*)LED_defaultBrightness1, sizeof( LED_defaultBrightness1 ), 0 );
1032 }
1033
1034 void cliFunc_ledZero( char* args )
1035 {
1036         print( NL ); // No \r\n by default after the command is entered
1037         LED_zeroPages( 0x00, 8, 0x24, 0xB4 ); // Only PWMs
1038 }
1039
1040 void cliFunc_ledCtrl( char* args )
1041 {
1042         char* curArgs;
1043         char* arg1Ptr;
1044         char* arg2Ptr = args;
1045         LedControl control;
1046
1047         // First process mode
1048         curArgs = arg2Ptr;
1049         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1050
1051         // Stop processing args if no more are found
1052         if ( *arg1Ptr == '\0' )
1053                 return;
1054         control.mode = numToInt( arg1Ptr );
1055
1056
1057         // Next process amount
1058         curArgs = arg2Ptr;
1059         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1060
1061         // Stop processing args if no more are found
1062         if ( *arg1Ptr == '\0' )
1063                 return;
1064         control.amount = numToInt( arg1Ptr );
1065
1066
1067         // Finally process led index, if it exists
1068         // Default to 0
1069         curArgs = arg2Ptr;
1070         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1071         control.index = *arg1Ptr == '\0' ? 0 : numToInt( arg1Ptr );
1072
1073         // Process request
1074         LED_control( &control );
1075 }
1076