Kiibohd Controller
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

led_scan.c 26KB

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