]> git.donarmstrong.com Git - kiibohd-controller.git/blob - Scan/ISSILed/led_scan.c
Move matrix information to a cli command
[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 unsigned int LED_currentEvent = 0;
643 inline uint8_t LED_scan()
644 {
645         // Check for current change event
646         if ( LED_currentEvent )
647         {
648                 // TODO dim LEDs in low power mode instead of shutting off
649                 if ( LED_currentEvent < 150 )
650                 {
651                         // Enable Software shutdown of ISSI chip
652                         LED_writeReg( 0x0A, 0x00, 0x0B );
653                 }
654                 else
655                 {
656                         // Disable Software shutdown of ISSI chip
657                         LED_writeReg( 0x0A, 0x01, 0x0B );
658                 }
659
660                 LED_currentEvent = 0;
661         }
662
663         return 0;
664 }
665
666
667 // Called by parent Scan Module whenver the available current has changed
668 // current - mA
669 void LED_currentChange( unsigned int current )
670 {
671         // Delay action till next LED scan loop (as this callback sometimes occurs during interrupt requests)
672         LED_currentEvent = current;
673 }
674
675
676
677 // ----- Capabilities -----
678
679 // Basic LED Control Capability
680 typedef enum LedControlMode {
681         // Single LED Modes
682         LedControlMode_brightness_decrease,
683         LedControlMode_brightness_increase,
684         LedControlMode_brightness_set,
685         // Set all LEDs (index argument not required)
686         LedControlMode_brightness_decrease_all,
687         LedControlMode_brightness_increase_all,
688         LedControlMode_brightness_set_all,
689 } LedControlMode;
690
691 typedef struct LedControl {
692         LedControlMode mode;   // XXX Make sure to adjust the .kll capability if this variable is larger than 8 bits
693         uint8_t        amount;
694         uint16_t       index;
695 } LedControl;
696
697 void LED_control( LedControl *control )
698 {
699         // Only send if we've completed all other transactions
700         /*
701         if ( I2C_TxBuffer.sequencePos > 0 )
702                 return;
703         */
704
705         // Configure based upon the given mode
706         // TODO Perhaps do gamma adjustment?
707         switch ( control->mode )
708         {
709         case LedControlMode_brightness_decrease:
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_increase:
715                 // Don't worry about rolling over, the cycle is quick
716                 LED_pageBuffer.buffer[ control->index ] += control->amount;
717                 break;
718
719         case LedControlMode_brightness_set:
720                 LED_pageBuffer.buffer[ control->index ] = control->amount;
721                 break;
722
723         case LedControlMode_brightness_decrease_all:
724                 for ( uint8_t channel = 0; channel < LED_TotalChannels; channel++ )
725                 {
726                         // Don't worry about rolling over, the cycle is quick
727                         LED_pageBuffer.buffer[ channel ] -= control->amount;
728                 }
729                 break;
730
731         case LedControlMode_brightness_increase_all:
732                 for ( uint8_t channel = 0; channel < LED_TotalChannels; channel++ )
733                 {
734                         // Don't worry about rolling over, the cycle is quick
735                         LED_pageBuffer.buffer[ channel ] += control->amount;
736                 }
737                 break;
738
739         case LedControlMode_brightness_set_all:
740                 for ( uint8_t channel = 0; channel < LED_TotalChannels; channel++ )
741                 {
742                         LED_pageBuffer.buffer[ channel ] = control->amount;
743                 }
744                 break;
745         }
746
747         // Sync LED buffer with ISSI chip buffer
748         // TODO Support multiple frames
749         LED_pageBuffer.i2c_addr = 0xE8; // Chip 1
750         LED_pageBuffer.reg_addr = 0x24; // Brightness section
751         LED_sendPage( (uint8_t*)&LED_pageBuffer, sizeof( LED_Buffer ), 0 );
752 }
753
754 uint8_t LED_control_timer = 0;
755 void LED_control_capability( uint8_t state, uint8_t stateType, uint8_t *args )
756 {
757         // Display capability name
758         if ( stateType == 0xFF && state == 0xFF )
759         {
760                 print("LED_control_capability(mode,amount,index)");
761                 return;
762         }
763
764         // Only use capability on press
765         // TODO Analog
766         if ( stateType == 0x00 && state == 0x03 ) // Not on release
767                 return;
768
769         // XXX
770         // ISSI Chip locks up if we spam updates too quickly (might be an I2C bug on this side too -HaaTa)
771         // Make sure we only send an update every 30 milliseconds at most
772         // It may be possible to optimize speed even further, but will likely require serious time with a logic analyzer
773
774         uint8_t currentTime = (uint8_t)systick_millis_count;
775         int8_t compare = (int8_t)(currentTime - LED_control_timer) & 0x7F;
776         if ( compare < 30 )
777         {
778                 return;
779         }
780         LED_control_timer = currentTime;
781
782         // Set the input structure
783         LedControl *control = (LedControl*)args;
784
785         // Interconnect broadcasting
786 #if defined(ConnectEnabled_define)
787         uint8_t send_packet = 0;
788         uint8_t ignore_node = 0;
789
790         // By default send to the *next* node, which will determine where to go next
791         extern uint8_t Connect_id; // connect_scan.c
792         uint8_t addr = Connect_id + 1;
793
794         switch ( control->mode )
795         {
796         // Calculate the led address to send
797         // If greater than the Total hannels
798         // Set address - Total channels
799         // Otherwise, ignore
800         case LedControlMode_brightness_decrease:
801         case LedControlMode_brightness_increase:
802         case LedControlMode_brightness_set:
803                 // Ignore if led is on this node
804                 if ( control->index < LED_TotalChannels )
805                         break;
806
807                 // Calculate new led index
808                 control->index -= LED_TotalChannels;
809
810                 ignore_node = 1;
811                 send_packet = 1;
812                 break;
813
814         // Broadcast to all nodes
815         // XXX Do not set broadcasting address
816         //     Will send command twice
817         case LedControlMode_brightness_decrease_all:
818         case LedControlMode_brightness_increase_all:
819         case LedControlMode_brightness_set_all:
820                 send_packet = 1;
821                 break;
822         }
823
824         // Only send interconnect remote capability packet if necessary
825         if ( send_packet )
826         {
827                 // generatedKeymap.h
828                 extern const Capability CapabilitiesList[];
829
830                 // Broadcast layerStackExact remote capability (0xFF is the broadcast id)
831                 Connect_send_RemoteCapability(
832                         addr,
833                         LED_control_capability_index,
834                         state,
835                         stateType,
836                         CapabilitiesList[ LED_control_capability_index ].argCount,
837                         args
838                 );
839         }
840
841         // If there is nothing to do on this node, ignore
842         if ( ignore_node )
843                 return;
844 #endif
845
846         // Modify led state of this node
847         LED_control( control );
848 }
849
850
851
852 // ----- CLI Command Functions -----
853
854 // TODO Currently not working correctly
855 void cliFunc_i2cSend( char* args )
856 {
857         char* curArgs;
858         char* arg1Ptr;
859         char* arg2Ptr = args;
860
861         // Buffer used after interpretting the args, will be sent to I2C functions
862         // NOTE: Limited to 8 bytes currently (can be increased if necessary
863         #define i2cSend_BuffLenMax 8
864         uint8_t buffer[ i2cSend_BuffLenMax ];
865         uint8_t bufferLen = 0;
866
867         // No \r\n by default after the command is entered
868         print( NL );
869         info_msg("Sending: ");
870
871         // Parse args until a \0 is found
872         while ( bufferLen < i2cSend_BuffLenMax )
873         {
874                 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
875                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
876
877                 // Stop processing args if no more are found
878                 if ( *arg1Ptr == '\0' )
879                         break;
880
881                 // If | is found, end sequence and start new one
882                 if ( *arg1Ptr == '|' )
883                 {
884                         print("| ");
885                         I2C_Send( buffer, bufferLen, 0 );
886                         bufferLen = 0;
887                         continue;
888                 }
889
890                 // Interpret the argument
891                 buffer[ bufferLen++ ] = (uint8_t)numToInt( arg1Ptr );
892
893                 // Print out the arg
894                 dPrint( arg1Ptr );
895                 print(" ");
896         }
897
898         print( NL );
899
900         I2C_Send( buffer, bufferLen, 0 );
901 }
902
903 void cliFunc_i2cRecv( char* args )
904 {
905         char* curArgs;
906         char* arg1Ptr;
907         char* arg2Ptr = args;
908
909         // Buffer used after interpretting the args, will be sent to I2C functions
910         // NOTE: Limited to 8 bytes currently (can be increased if necessary
911         #define i2cSend_BuffLenMax 8
912         uint8_t buffer[ i2cSend_BuffLenMax ];
913         uint8_t bufferLen = 0;
914
915         // No \r\n by default after the command is entered
916         print( NL );
917         info_msg("Sending: ");
918
919         // Parse args until a \0 is found
920         while ( bufferLen < i2cSend_BuffLenMax )
921         {
922                 curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
923                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
924
925                 // Stop processing args if no more are found
926                 if ( *arg1Ptr == '\0' )
927                         break;
928
929                 // If | is found, end sequence and start new one
930                 if ( *arg1Ptr == '|' )
931                 {
932                         print("| ");
933                         I2C_Send( buffer, bufferLen, 0 );
934                         bufferLen = 0;
935                         continue;
936                 }
937
938                 // Interpret the argument
939                 buffer[ bufferLen++ ] = (uint8_t)numToInt( arg1Ptr );
940
941                 // Print out the arg
942                 dPrint( arg1Ptr );
943                 print(" ");
944         }
945
946         print( NL );
947
948         I2C_Send( buffer, bufferLen, 1 ); // Only 1 byte is ever read at a time with the ISSI chip
949 }
950
951 // TODO Currently not working correctly
952 void cliFunc_ledRPage( char* args )
953 {
954         // Parse number from argument
955         //  NOTE: Only first argument is used
956         char* arg1Ptr;
957         char* arg2Ptr;
958         CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
959
960         // Default to 0 if no argument is given
961         uint8_t page = 0;
962
963         if ( arg1Ptr[0] != '\0' )
964         {
965                 page = (uint8_t)numToInt( arg1Ptr );
966         }
967
968         // No \r\n by default after the command is entered
969         print( NL );
970
971         LED_readPage( 0x1, page );
972         //LED_readPage( 0xB4, page );
973 }
974
975 void cliFunc_ledWPage( char* args )
976 {
977         char* curArgs;
978         char* arg1Ptr;
979         char* arg2Ptr = args;
980
981         // First process page and starting address
982         curArgs = arg2Ptr;
983         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
984
985         // Stop processing args if no more are found
986         if ( *arg1Ptr == '\0' )
987                 return;
988         uint8_t page[] = { 0xE8, 0xFD, numToInt( arg1Ptr ) };
989
990         curArgs = arg2Ptr;
991         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
992
993         // Stop processing args if no more are found
994         if ( *arg1Ptr == '\0' )
995                 return;
996         uint8_t data[] = { 0xE8, numToInt( arg1Ptr ), 0 };
997
998         // Set the register page
999         while ( I2C_Send( page, sizeof( page ), 0 ) == 0 )
1000                 delay(1);
1001
1002         // Process all args
1003         for ( ;; )
1004         {
1005                 curArgs = arg2Ptr;
1006                 CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1007
1008                 // Stop processing args if no more are found
1009                 if ( *arg1Ptr == '\0' )
1010                         break;
1011
1012                 data[2] = numToInt( arg1Ptr );
1013
1014                 // Write register location and data to I2C
1015                 while ( I2C_Send( data, sizeof( data ), 0 ) == 0 )
1016                         delay(1);
1017
1018                 // Increment address
1019                 data[1]++;
1020         }
1021 }
1022
1023 void cliFunc_ledStart( char* args )
1024 {
1025         print( NL ); // No \r\n by default after the command is entered
1026         LED_zeroPages( 0x0B, 1, 0x00, 0x0C ); // Control Registers
1027         //LED_zeroPages( 0x00, 8, 0x00, 0xB4 ); // LED Registers
1028         LED_writeReg( 0x0A, 0x01, 0x0B );
1029         LED_sendPage( (uint8_t*)LED_ledEnableMask1, sizeof( LED_ledEnableMask1 ), 0 );
1030
1031 }
1032
1033 void cliFunc_ledTest( char* args )
1034 {
1035         print( NL ); // No \r\n by default after the command is entered
1036         LED_sendPage( (uint8_t*)LED_defaultBrightness1, sizeof( LED_defaultBrightness1 ), 0 );
1037 }
1038
1039 void cliFunc_ledZero( char* args )
1040 {
1041         print( NL ); // No \r\n by default after the command is entered
1042         LED_zeroPages( 0x00, 8, 0x24, 0xB4 ); // Only PWMs
1043 }
1044
1045 void cliFunc_ledCtrl( char* args )
1046 {
1047         char* curArgs;
1048         char* arg1Ptr;
1049         char* arg2Ptr = args;
1050         LedControl control;
1051
1052         // First process mode
1053         curArgs = arg2Ptr;
1054         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1055
1056         // Stop processing args if no more are found
1057         if ( *arg1Ptr == '\0' )
1058                 return;
1059         control.mode = numToInt( arg1Ptr );
1060
1061
1062         // Next process amount
1063         curArgs = arg2Ptr;
1064         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1065
1066         // Stop processing args if no more are found
1067         if ( *arg1Ptr == '\0' )
1068                 return;
1069         control.amount = numToInt( arg1Ptr );
1070
1071
1072         // Finally process led index, if it exists
1073         // Default to 0
1074         curArgs = arg2Ptr;
1075         CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
1076         control.index = *arg1Ptr == '\0' ? 0 : numToInt( arg1Ptr );
1077
1078         // Process request
1079         LED_control( &control );
1080 }
1081