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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076
  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. inline uint8_t LED_scan()
  514. {
  515. // I2C Busy
  516. // S & I2C_S_BUSY
  517. //I2C_S_BUSY
  518. return 0;
  519. }
  520. // Called by parent Scan Module whenver the available current has changed
  521. // current - mA
  522. void LED_currentChange( unsigned int current )
  523. {
  524. // TODO dim LEDs in low power mode instead of shutting off
  525. if ( current < 150 )
  526. {
  527. // Enabled Software shutdown of ISSI chip
  528. LED_writeReg( 0x0A, 0x00, 0x0B );
  529. }
  530. else
  531. {
  532. // Disable Software shutdown of ISSI chip
  533. LED_writeReg( 0x0A, 0x01, 0x0B );
  534. }
  535. }
  536. // ----- Capabilities -----
  537. // Basic LED Control Capability
  538. typedef enum LedControlMode {
  539. // Single LED Modes
  540. LedControlMode_brightness_decrease,
  541. LedControlMode_brightness_increase,
  542. LedControlMode_brightness_set,
  543. // Set all LEDs (index argument not required)
  544. LedControlMode_brightness_decrease_all,
  545. LedControlMode_brightness_increase_all,
  546. LedControlMode_brightness_set_all,
  547. } LedControlMode;
  548. typedef struct LedControl {
  549. LedControlMode mode; // XXX Make sure to adjust the .kll capability if this variable is larger than 8 bits
  550. uint8_t amount;
  551. uint16_t index;
  552. } LedControl;
  553. void LED_control( LedControl *control )
  554. {
  555. // Only send if we've completed all other transactions
  556. /*
  557. if ( I2C_TxBuffer.sequencePos > 0 )
  558. return;
  559. */
  560. // Configure based upon the given mode
  561. // TODO Perhaps do gamma adjustment?
  562. switch ( control->mode )
  563. {
  564. case LedControlMode_brightness_decrease:
  565. // Don't worry about rolling over, the cycle is quick
  566. LED_pageBuffer.buffer[ control->index ] -= control->amount;
  567. break;
  568. case LedControlMode_brightness_increase:
  569. // Don't worry about rolling over, the cycle is quick
  570. LED_pageBuffer.buffer[ control->index ] += control->amount;
  571. break;
  572. case LedControlMode_brightness_set:
  573. LED_pageBuffer.buffer[ control->index ] = control->amount;
  574. break;
  575. case LedControlMode_brightness_decrease_all:
  576. for ( uint8_t channel = 0; channel < LED_TotalChannels; channel++ )
  577. {
  578. // Don't worry about rolling over, the cycle is quick
  579. LED_pageBuffer.buffer[ channel ] -= control->amount;
  580. }
  581. break;
  582. case LedControlMode_brightness_increase_all:
  583. for ( uint8_t channel = 0; channel < LED_TotalChannels; channel++ )
  584. {
  585. // Don't worry about rolling over, the cycle is quick
  586. LED_pageBuffer.buffer[ channel ] += control->amount;
  587. }
  588. break;
  589. case LedControlMode_brightness_set_all:
  590. for ( uint8_t channel = 0; channel < LED_TotalChannels; channel++ )
  591. {
  592. LED_pageBuffer.buffer[ channel ] = control->amount;
  593. }
  594. break;
  595. }
  596. // Sync LED buffer with ISSI chip buffer
  597. // TODO Support multiple frames
  598. LED_pageBuffer.i2c_addr = 0xE8; // Chip 1
  599. LED_pageBuffer.reg_addr = 0x24; // Brightness section
  600. LED_sendPage( (uint8_t*)&LED_pageBuffer, sizeof( LED_Buffer ), 0 );
  601. }
  602. uint8_t LED_control_timer = 0;
  603. void LED_control_capability( uint8_t state, uint8_t stateType, uint8_t *args )
  604. {
  605. // Display capability name
  606. if ( stateType == 0xFF && state == 0xFF )
  607. {
  608. print("LED_control_capability(mode,amount,index)");
  609. return;
  610. }
  611. // Only use capability on press
  612. // TODO Analog
  613. if ( stateType == 0x00 && state == 0x03 ) // Not on release
  614. return;
  615. // XXX
  616. // ISSI Chip locks up if we spam updates too quickly (might be an I2C bug on this side too -HaaTa)
  617. // Make sure we only send an update every 30 milliseconds at most
  618. // It may be possible to optimize speed even further, but will likely require serious time with a logic analyzer
  619. uint8_t currentTime = (uint8_t)systick_millis_count;
  620. int8_t compare = (int8_t)(currentTime - LED_control_timer) & 0x7F;
  621. if ( compare < 30 )
  622. {
  623. return;
  624. }
  625. LED_control_timer = currentTime;
  626. // Set the input structure
  627. LedControl *control = (LedControl*)args;
  628. // Interconnect broadcasting
  629. #if defined(ConnectEnabled_define)
  630. uint8_t send_packet = 0;
  631. uint8_t ignore_node = 0;
  632. // By default send to the *next* node, which will determine where to go next
  633. extern uint8_t Connect_id; // connect_scan.c
  634. uint8_t addr = Connect_id + 1;
  635. switch ( control->mode )
  636. {
  637. // Calculate the led address to send
  638. // If greater than the Total hannels
  639. // Set address - Total channels
  640. // Otherwise, ignore
  641. case LedControlMode_brightness_decrease:
  642. case LedControlMode_brightness_increase:
  643. case LedControlMode_brightness_set:
  644. // Ignore if led is on this node
  645. if ( control->index < LED_TotalChannels )
  646. break;
  647. // Calculate new led index
  648. control->index -= LED_TotalChannels;
  649. ignore_node = 1;
  650. send_packet = 1;
  651. break;
  652. // Broadcast to all nodes
  653. // XXX Do not set broadcasting address
  654. // Will send command twice
  655. case LedControlMode_brightness_decrease_all:
  656. case LedControlMode_brightness_increase_all:
  657. case LedControlMode_brightness_set_all:
  658. send_packet = 1;
  659. break;
  660. }
  661. // Only send interconnect remote capability packet if necessary
  662. if ( send_packet )
  663. {
  664. // generatedKeymap.h
  665. extern const Capability CapabilitiesList[];
  666. // Broadcast layerStackExact remote capability (0xFF is the broadcast id)
  667. Connect_send_RemoteCapability(
  668. addr,
  669. LED_control_capability_index,
  670. state,
  671. stateType,
  672. CapabilitiesList[ LED_control_capability_index ].argCount,
  673. args
  674. );
  675. }
  676. // If there is nothing to do on this node, ignore
  677. if ( ignore_node )
  678. return;
  679. #endif
  680. // Modify led state of this node
  681. LED_control( control );
  682. }
  683. // ----- CLI Command Functions -----
  684. // TODO Currently not working correctly
  685. void cliFunc_i2cSend( char* args )
  686. {
  687. char* curArgs;
  688. char* arg1Ptr;
  689. char* arg2Ptr = args;
  690. // Buffer used after interpretting the args, will be sent to I2C functions
  691. // NOTE: Limited to 8 bytes currently (can be increased if necessary
  692. #define i2cSend_BuffLenMax 8
  693. uint8_t buffer[ i2cSend_BuffLenMax ];
  694. uint8_t bufferLen = 0;
  695. // No \r\n by default after the command is entered
  696. print( NL );
  697. info_msg("Sending: ");
  698. // Parse args until a \0 is found
  699. while ( bufferLen < i2cSend_BuffLenMax )
  700. {
  701. curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
  702. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  703. // Stop processing args if no more are found
  704. if ( *arg1Ptr == '\0' )
  705. break;
  706. // If | is found, end sequence and start new one
  707. if ( *arg1Ptr == '|' )
  708. {
  709. print("| ");
  710. I2C_Send( buffer, bufferLen, 0 );
  711. bufferLen = 0;
  712. continue;
  713. }
  714. // Interpret the argument
  715. buffer[ bufferLen++ ] = (uint8_t)numToInt( arg1Ptr );
  716. // Print out the arg
  717. dPrint( arg1Ptr );
  718. print(" ");
  719. }
  720. print( NL );
  721. I2C_Send( buffer, bufferLen, 0 );
  722. }
  723. void cliFunc_i2cRecv( char* args )
  724. {
  725. char* curArgs;
  726. char* arg1Ptr;
  727. char* arg2Ptr = args;
  728. // Buffer used after interpretting the args, will be sent to I2C functions
  729. // NOTE: Limited to 8 bytes currently (can be increased if necessary
  730. #define i2cSend_BuffLenMax 8
  731. uint8_t buffer[ i2cSend_BuffLenMax ];
  732. uint8_t bufferLen = 0;
  733. // No \r\n by default after the command is entered
  734. print( NL );
  735. info_msg("Sending: ");
  736. // Parse args until a \0 is found
  737. while ( bufferLen < i2cSend_BuffLenMax )
  738. {
  739. curArgs = arg2Ptr; // Use the previous 2nd arg pointer to separate the next arg from the list
  740. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  741. // Stop processing args if no more are found
  742. if ( *arg1Ptr == '\0' )
  743. break;
  744. // If | is found, end sequence and start new one
  745. if ( *arg1Ptr == '|' )
  746. {
  747. print("| ");
  748. I2C_Send( buffer, bufferLen, 0 );
  749. bufferLen = 0;
  750. continue;
  751. }
  752. // Interpret the argument
  753. buffer[ bufferLen++ ] = (uint8_t)numToInt( arg1Ptr );
  754. // Print out the arg
  755. dPrint( arg1Ptr );
  756. print(" ");
  757. }
  758. print( NL );
  759. I2C_Send( buffer, bufferLen, 1 ); // Only 1 byte is ever read at a time with the ISSI chip
  760. }
  761. // TODO Currently not working correctly
  762. void cliFunc_ledRPage( char* args )
  763. {
  764. // Parse number from argument
  765. // NOTE: Only first argument is used
  766. char* arg1Ptr;
  767. char* arg2Ptr;
  768. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  769. // Default to 0 if no argument is given
  770. uint8_t page = 0;
  771. if ( arg1Ptr[0] != '\0' )
  772. {
  773. page = (uint8_t)numToInt( arg1Ptr );
  774. }
  775. // No \r\n by default after the command is entered
  776. print( NL );
  777. LED_readPage( 0x1, page );
  778. //LED_readPage( 0xB4, page );
  779. }
  780. void cliFunc_ledWPage( char* args )
  781. {
  782. char* curArgs;
  783. char* arg1Ptr;
  784. char* arg2Ptr = args;
  785. // First process page and starting address
  786. curArgs = arg2Ptr;
  787. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  788. // Stop processing args if no more are found
  789. if ( *arg1Ptr == '\0' )
  790. return;
  791. uint8_t page[] = { 0xE8, 0xFD, numToInt( arg1Ptr ) };
  792. curArgs = arg2Ptr;
  793. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  794. // Stop processing args if no more are found
  795. if ( *arg1Ptr == '\0' )
  796. return;
  797. uint8_t data[] = { 0xE8, numToInt( arg1Ptr ), 0 };
  798. // Set the register page
  799. while ( I2C_Send( page, sizeof( page ), 0 ) == 0 )
  800. delay(1);
  801. // Process all args
  802. for ( ;; )
  803. {
  804. curArgs = arg2Ptr;
  805. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  806. // Stop processing args if no more are found
  807. if ( *arg1Ptr == '\0' )
  808. break;
  809. data[2] = numToInt( arg1Ptr );
  810. // Write register location and data to I2C
  811. while ( I2C_Send( data, sizeof( data ), 0 ) == 0 )
  812. delay(1);
  813. // Increment address
  814. data[1]++;
  815. }
  816. }
  817. void cliFunc_ledStart( char* args )
  818. {
  819. print( NL ); // No \r\n by default after the command is entered
  820. LED_zeroPages( 0x0B, 1, 0x00, 0x0C ); // Control Registers
  821. //LED_zeroPages( 0x00, 8, 0x00, 0xB4 ); // LED Registers
  822. LED_writeReg( 0x0A, 0x01, 0x0B );
  823. LED_sendPage( (uint8_t*)LED_ledEnableMask1, sizeof( LED_ledEnableMask1 ), 0 );
  824. }
  825. void cliFunc_ledTest( char* args )
  826. {
  827. print( NL ); // No \r\n by default after the command is entered
  828. LED_sendPage( (uint8_t*)LED_defaultBrightness1, sizeof( LED_defaultBrightness1 ), 0 );
  829. }
  830. void cliFunc_ledZero( char* args )
  831. {
  832. print( NL ); // No \r\n by default after the command is entered
  833. LED_zeroPages( 0x00, 8, 0x24, 0xB4 ); // Only PWMs
  834. }
  835. void cliFunc_ledCtrl( char* args )
  836. {
  837. char* curArgs;
  838. char* arg1Ptr;
  839. char* arg2Ptr = args;
  840. LedControl control;
  841. // First process mode
  842. curArgs = arg2Ptr;
  843. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  844. // Stop processing args if no more are found
  845. if ( *arg1Ptr == '\0' )
  846. return;
  847. control.mode = numToInt( arg1Ptr );
  848. // Next process amount
  849. curArgs = arg2Ptr;
  850. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  851. // Stop processing args if no more are found
  852. if ( *arg1Ptr == '\0' )
  853. return;
  854. control.amount = numToInt( arg1Ptr );
  855. // Finally process led index, if it exists
  856. // Default to 0
  857. curArgs = arg2Ptr;
  858. CLI_argumentIsolation( curArgs, &arg1Ptr, &arg2Ptr );
  859. control.index = *arg1Ptr == '\0' ? 0 : numToInt( arg1Ptr );
  860. // Process request
  861. LED_control( &control );
  862. }