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.

connect_scan.c 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170
  1. /* Copyright (C) 2014-2015 by Jacob Alexander
  2. *
  3. * This file is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This file is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this file. If not, see <http://www.gnu.org/licenses/>.
  15. */
  16. // ----- 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. #include <macro.h>
  25. // Local Includes
  26. #include "connect_scan.h"
  27. // ----- Macros -----
  28. #define UART_Master 1
  29. #define UART_Slave 0
  30. #define uart_lock_m( uartNum ) uart##uartNum##_lock
  31. #define uart_buffer_items_m( uartNum ) uart##uartNum##_buffer_items
  32. #define uart_buffer_m( uartNum ) uart##uartNum##_buffer
  33. #define uart_buffer_head_m( uartNum ) uart##uartNum##_buffer_head
  34. #define uart_buffer_tail_m( uartNum ) uart##uartNum##_buffer_tail
  35. #define uart_tx_status_m( uartNum ) uart##uartNum##_tx_status
  36. // Macro for adding to each uart Tx ring buffer
  37. #define uart_addTxBuffer( uartNum ) \
  38. case uartNum: \
  39. /* Delay UART copy until there's some space left */ \
  40. while ( uart_buffer_items_m( uartNum ) + count > uart_buffer_size ) \
  41. { \
  42. warn_msg("Too much data to send on UART0, waiting..."); \
  43. delay( 1 ); \
  44. } \
  45. /* Append data to ring buffer */ \
  46. for ( uint8_t c = 0; c < count; c++ ) \
  47. { \
  48. if ( Connect_debug ) \
  49. { \
  50. printHex( buffer[ c ] ); \
  51. print( " +" #uartNum NL ); \
  52. } \
  53. uart_buffer_m( uartNum )[ uart_buffer_tail_m( uartNum )++ ] = buffer[ c ]; \
  54. uart_buffer_items_m( uartNum )++; \
  55. if ( uart_buffer_tail_m( uartNum ) >= uart_buffer_size ) \
  56. uart_buffer_tail_m( uartNum ) = 0; \
  57. if ( uart_buffer_head_m( uartNum ) == uart_buffer_tail_m( uartNum ) ) \
  58. uart_buffer_head_m( uartNum )++; \
  59. if ( uart_buffer_head_m( uartNum ) >= uart_buffer_size ) \
  60. uart_buffer_head_m( uartNum ) = 0; \
  61. } \
  62. break
  63. // Macro for popping from Tx ring buffer
  64. #define uart_fillTxFifo( uartNum ) \
  65. { \
  66. uint8_t fifoSize = ( ( UART##uartNum##_PFIFO & UART_PFIFO_TXFIFOSIZE ) >> 2 ); \
  67. if ( fifoSize == 0 ) \
  68. fifoSize = 1; \
  69. if ( Connect_debug ) \
  70. { \
  71. print( "TxFIFO " #uartNum " - " ); \
  72. printHex( fifoSize ); \
  73. print("/"); \
  74. printHex( UART##uartNum##_TCFIFO ); \
  75. print("/"); \
  76. printHex( uart##uartNum##_buffer_items ); \
  77. print( NL ); \
  78. } \
  79. /* XXX Doesn't work well */ \
  80. /* while ( UART##uartNum##_TCFIFO < fifoSize ) */ \
  81. /* More reliable, albeit slower */ \
  82. fifoSize -= UART##uartNum##_TCFIFO; \
  83. while ( fifoSize-- != 0 ) \
  84. { \
  85. if ( uart##uartNum##_buffer_items == 0 ) \
  86. break; \
  87. UART##uartNum##_D = uart##uartNum##_buffer[ uart##uartNum##_buffer_head++ ]; \
  88. uart##uartNum##_buffer_items--; \
  89. if ( uart##uartNum##_buffer_head >= uart_buffer_size ) \
  90. uart##uartNum##_buffer_head = 0; \
  91. } \
  92. }
  93. // Macro for processing UART Rx
  94. #define uart_processRx( uartNum ) \
  95. { \
  96. if ( !( UART##uartNum##_S1 & UART_S1_RDRF ) ) \
  97. return; \
  98. uint8_t available = UART##uartNum##_RCFIFO; \
  99. if ( available == 0 ) \
  100. { \
  101. available = UART##uartNum##_D; \
  102. UART##uartNum##_CFIFO = UART_CFIFO_RXFLUSH; \
  103. return; \
  104. } \
  105. /* Process each byte in the UART buffer */ \
  106. while ( available-- > 0 ) \
  107. { \
  108. /* First check if there was noise or Parity issues with current byte */ \
  109. uint8_t err_status = UART##uartNum##_ED; \
  110. /* Read byte from Rx FIFO */ \
  111. uint8_t byteRead = UART##uartNum##_D; \
  112. if ( Connect_debug ) \
  113. { \
  114. printHex( byteRead ); \
  115. print("("); \
  116. printInt8( available ); \
  117. print(") <-"); \
  118. } \
  119. /* Check error status */ \
  120. if ( err_status & 0x80 ) \
  121. { \
  122. print(" NOISY "); \
  123. } \
  124. if ( err_status & 0x40 ) \
  125. { \
  126. print(" PARITY ERR "); \
  127. } \
  128. /* Ignore current byte if there was an error */ \
  129. if ( err_status ) \
  130. { \
  131. uart##uartNum##_rx_status = UARTStatus_Wait; \
  132. if ( Connect_debug ) \
  133. { \
  134. print( NL ); \
  135. } \
  136. continue; \
  137. } \
  138. switch ( uart##uartNum##_rx_status ) \
  139. { \
  140. case UARTStatus_Wait: \
  141. if ( Connect_debug ) \
  142. { \
  143. print(" Wait "); \
  144. } \
  145. uart##uartNum##_rx_status = byteRead == 0x16 ? UARTStatus_SYN : UARTStatus_Wait; \
  146. break; \
  147. case UARTStatus_SYN: \
  148. if ( Connect_debug ) \
  149. { \
  150. print(" SYN "); \
  151. } \
  152. uart##uartNum##_rx_status = byteRead == 0x01 ? UARTStatus_SOH : UARTStatus_Wait; \
  153. break; \
  154. case UARTStatus_SOH: \
  155. { \
  156. if ( Connect_debug ) \
  157. { \
  158. print(" SOH "); \
  159. } \
  160. /* Check if this is actually a reserved CMD 0x16 */ \
  161. if ( byteRead == Command_SYN ) \
  162. { \
  163. uart##uartNum##_rx_status = UARTStatus_SYN; \
  164. break; \
  165. } \
  166. /* Otherwise process the command */ \
  167. uint8_t byte = byteRead; \
  168. if ( byte < Command_TOP ) \
  169. { \
  170. uart##uartNum##_rx_status = UARTStatus_Command; \
  171. uart##uartNum##_rx_command = byte; \
  172. uart##uartNum##_rx_bytes_waiting = 0xFFFF; \
  173. } \
  174. else \
  175. { \
  176. uart##uartNum##_rx_status = UARTStatus_Wait; \
  177. } \
  178. switch ( uart##uartNum##_rx_command ) \
  179. { \
  180. case IdRequest: \
  181. Connect_receive_IdRequest( 0, (uint16_t*)&uart##uartNum##_rx_bytes_waiting, uartNum ); \
  182. uart##uartNum##_rx_status = UARTStatus_Wait; \
  183. break; \
  184. default: \
  185. if ( Connect_debug ) \
  186. { \
  187. print(" ### "); \
  188. printHex( uart##uartNum##_rx_command ); \
  189. } \
  190. break; \
  191. } \
  192. break; \
  193. } \
  194. case UARTStatus_Command: \
  195. { \
  196. if ( Connect_debug ) \
  197. { \
  198. print(" CMD "); \
  199. } \
  200. /* Call specific UARTConnect command receive function */ \
  201. uint8_t (*rcvFunc)(uint8_t, uint16_t(*), uint8_t) = (uint8_t(*)(uint8_t, uint16_t(*), uint8_t))(Connect_receiveFunctions[ uart##uartNum##_rx_command ]); \
  202. if ( rcvFunc( byteRead, (uint16_t*)&uart##uartNum##_rx_bytes_waiting, uartNum ) ) \
  203. uart##uartNum##_rx_status = UARTStatus_Wait; \
  204. break; \
  205. } \
  206. default: \
  207. erro_msg("Invalid UARTStatus..."); \
  208. uart##uartNum##_rx_status = UARTStatus_Wait; \
  209. available++; \
  210. continue; \
  211. } \
  212. if ( Connect_debug ) \
  213. { \
  214. print( NL ); \
  215. } \
  216. } \
  217. }
  218. // Macros for locking/unlock Tx buffers
  219. #define uart_lockTx( uartNum ) \
  220. { \
  221. /* First, secure place in line for the resource */ \
  222. while ( uart_lock_m( uartNum ) ); \
  223. uart_lock_m( uartNum ) = 1; \
  224. /* Next, wait unit the UART is ready */ \
  225. while ( uart_tx_status_m( uartNum ) != UARTStatus_Ready ); \
  226. uart_tx_status_m( uartNum ) = UARTStatus_Wait; \
  227. }
  228. #define uart_lockBothTx( uartNum1, uartNum2 ) \
  229. { \
  230. /* First, secure place in line for the resource */ \
  231. while ( uart_lock_m( uartNum1 ) || uart_lock_m( uartNum2 ) ); \
  232. uart_lock_m( uartNum1 ) = 1; \
  233. uart_lock_m( uartNum2 ) = 1; \
  234. /* Next, wait unit the UARTs are ready */ \
  235. while ( uart_tx_status_m( uartNum1 ) != UARTStatus_Ready || uart_tx_status_m( uartNum2 ) != UARTStatus_Ready ); \
  236. uart_tx_status_m( uartNum1 ) = UARTStatus_Wait; \
  237. uart_tx_status_m( uartNum2 ) = UARTStatus_Wait; \
  238. }
  239. #define uart_unlockTx( uartNum ) \
  240. { \
  241. /* Ready the UART */ \
  242. uart_tx_status_m( uartNum ) = UARTStatus_Ready; \
  243. /* Unlock the resource */ \
  244. uart_lock_m( uartNum ) = 0; \
  245. }
  246. // ----- Function Declarations -----
  247. // CLI Functions
  248. void cliFunc_connectCmd ( char *args );
  249. void cliFunc_connectDbg ( char *args );
  250. void cliFunc_connectIdl ( char *args );
  251. void cliFunc_connectLst ( char *args );
  252. void cliFunc_connectMst ( char *args );
  253. void cliFunc_connectRst ( char *args );
  254. void cliFunc_connectSts ( char *args );
  255. // ----- Variables -----
  256. // Connect Module command dictionary
  257. CLIDict_Entry( connectCmd, "Sends a command via UART Connect, first arg is which uart, next arg is the command, rest are the arguments." );
  258. CLIDict_Entry( connectDbg, "Toggle UARTConnect debug mode." );
  259. CLIDict_Entry( connectIdl, "Sends N number of Idle commands, 2 is the default value, and should be sufficient in most cases." );
  260. CLIDict_Entry( connectLst, "Lists available UARTConnect commands and index id" );
  261. CLIDict_Entry( connectMst, "Sets the device as master. Use argument of s to set as slave." );
  262. CLIDict_Entry( connectRst, "Resets both Rx and Tx connect buffers and state variables." );
  263. CLIDict_Entry( connectSts, "UARTConnect status." );
  264. CLIDict_Def( uartConnectCLIDict, "UARTConnect Module Commands" ) = {
  265. CLIDict_Item( connectCmd ),
  266. CLIDict_Item( connectDbg ),
  267. CLIDict_Item( connectIdl ),
  268. CLIDict_Item( connectLst ),
  269. CLIDict_Item( connectMst ),
  270. CLIDict_Item( connectRst ),
  271. CLIDict_Item( connectSts ),
  272. { 0, 0, 0 } // Null entry for dictionary end
  273. };
  274. // -- Connect Device Id Variables --
  275. uint8_t Connect_id = 255; // Invalid, unset
  276. uint8_t Connect_master = 0;
  277. uint8_t Connect_maxId = 0;
  278. // -- Control Variables --
  279. uint32_t Connect_lastCheck = 0; // Cable Check scheduler
  280. uint8_t Connect_debug = 0; // Set 1 for debug
  281. uint8_t Connect_override = 0; // Prevents master from automatically being set
  282. // -- Rx Status Variables --
  283. volatile UARTStatus uart0_rx_status;
  284. volatile UARTStatus uart1_rx_status;
  285. volatile uint16_t uart0_rx_bytes_waiting;
  286. volatile uint16_t uart1_rx_bytes_waiting;
  287. volatile Command uart0_rx_command;
  288. volatile Command uart1_rx_command;
  289. volatile uint8_t uart0_lock;
  290. volatile uint8_t uart1_lock;
  291. // -- Tx Status Variables --
  292. volatile UARTStatus uart0_tx_status;
  293. volatile UARTStatus uart1_tx_status;
  294. // -- Ring Buffer Variables --
  295. #define uart_buffer_size UARTConnectBufSize_define
  296. volatile uint8_t uart0_buffer_head;
  297. volatile uint8_t uart0_buffer_tail;
  298. volatile uint8_t uart0_buffer_items;
  299. volatile uint8_t uart0_buffer[uart_buffer_size];
  300. volatile uint8_t uart1_buffer_head;
  301. volatile uint8_t uart1_buffer_tail;
  302. volatile uint8_t uart1_buffer_items;
  303. volatile uint8_t uart1_buffer[uart_buffer_size];
  304. volatile uint8_t uarts_configured = 0;
  305. // -- Ring Buffer Convenience Functions --
  306. void Connect_addBytes( uint8_t *buffer, uint8_t count, uint8_t uart )
  307. {
  308. // Too big to fit into buffer
  309. if ( count > uart_buffer_size )
  310. {
  311. erro_msg("Too big of a command to fit into the buffer...");
  312. return;
  313. }
  314. // Choose the uart
  315. switch ( uart )
  316. {
  317. uart_addTxBuffer( UART_Master );
  318. uart_addTxBuffer( UART_Slave );
  319. default:
  320. erro_msg("Invalid UART to send from...");
  321. break;
  322. }
  323. }
  324. // -- Connect send functions --
  325. // patternLen defines how many bytes should the incrementing pattern have
  326. void Connect_send_CableCheck( uint8_t patternLen )
  327. {
  328. // Wait until the Tx buffers are ready, then lock them
  329. uart_lockBothTx( UART_Master, UART_Slave );
  330. // Prepare header
  331. uint8_t header[] = { 0x16, 0x01, CableCheck, patternLen };
  332. // Send header
  333. Connect_addBytes( header, sizeof( header ), UART_Master );
  334. Connect_addBytes( header, sizeof( header ), UART_Slave );
  335. // Send 0xD2 (11010010) for each argument
  336. uint8_t value = 0xD2;
  337. for ( uint8_t c = 0; c < patternLen; c++ )
  338. {
  339. Connect_addBytes( &value, 1, UART_Master );
  340. Connect_addBytes( &value, 1, UART_Slave );
  341. }
  342. // Release Tx buffers
  343. uart_unlockTx( UART_Master );
  344. uart_unlockTx( UART_Slave );
  345. }
  346. void Connect_send_IdRequest()
  347. {
  348. // Lock master bound Tx
  349. uart_lockTx( UART_Master );
  350. // Prepare header
  351. uint8_t header[] = { 0x16, 0x01, IdRequest };
  352. // Send header
  353. Connect_addBytes( header, sizeof( header ), UART_Master );
  354. // Unlock Tx
  355. uart_unlockTx( UART_Master );
  356. }
  357. // id is the value the next slave should enumerate as
  358. void Connect_send_IdEnumeration( uint8_t id )
  359. {
  360. // Lock slave bound Tx
  361. uart_lockTx( UART_Slave );
  362. // Prepare header
  363. uint8_t header[] = { 0x16, 0x01, IdEnumeration, id };
  364. // Send header
  365. Connect_addBytes( header, sizeof( header ), UART_Slave );
  366. // Unlock Tx
  367. uart_unlockTx( UART_Slave );
  368. }
  369. // id is the currently assigned id to the slave
  370. void Connect_send_IdReport( uint8_t id )
  371. {
  372. // Lock master bound Tx
  373. uart_lockTx( UART_Master );
  374. // Prepare header
  375. uint8_t header[] = { 0x16, 0x01, IdReport, id };
  376. // Send header
  377. Connect_addBytes( header, sizeof( header ), UART_Master );
  378. // Unlock Tx
  379. uart_unlockTx( UART_Master );
  380. }
  381. // id is the currently assigned id to the slave
  382. // scanCodeStateList is an array of [scancode, state]'s (8 bit values)
  383. // numScanCodes is the number of scan codes to parse from array
  384. void Connect_send_ScanCode( uint8_t id, TriggerGuide *scanCodeStateList, uint8_t numScanCodes )
  385. {
  386. // Lock master bound Tx
  387. uart_lockTx( UART_Master );
  388. // Prepare header
  389. uint8_t header[] = { 0x16, 0x01, ScanCode, id, numScanCodes };
  390. // Send header
  391. Connect_addBytes( header, sizeof( header ), UART_Master );
  392. // Send each of the scan codes
  393. Connect_addBytes( (uint8_t*)scanCodeStateList, numScanCodes * TriggerGuideSize, UART_Master );
  394. // Unlock Tx
  395. uart_unlockTx( UART_Master );
  396. }
  397. // id is the currently assigned id to the slave
  398. // paramList is an array of [param, value]'s (8 bit values)
  399. // numParams is the number of params to parse from the array
  400. void Connect_send_Animation( uint8_t id, uint8_t *paramList, uint8_t numParams )
  401. {
  402. // Lock slave bound Tx
  403. uart_lockTx( UART_Slave );
  404. // Prepare header
  405. uint8_t header[] = { 0x16, 0x01, Animation, id, numParams };
  406. // Send header
  407. Connect_addBytes( header, sizeof( header ), UART_Slave );
  408. // Send each of the scan codes
  409. Connect_addBytes( paramList, numParams, UART_Slave );
  410. // Unlock Tx
  411. uart_unlockTx( UART_Slave );
  412. }
  413. void Connect_send_Idle( uint8_t num )
  414. {
  415. // Wait until the Tx buffers are ready, then lock them
  416. uart_lockBothTx( UART_Slave, UART_Master );
  417. // Send n number of idles to reset link status (if in a bad state)
  418. uint8_t value = 0x16;
  419. for ( uint8_t c = 0; c < num; c++ )
  420. {
  421. Connect_addBytes( &value, 1, UART_Master );
  422. Connect_addBytes( &value, 1, UART_Slave );
  423. }
  424. // Release Tx buffers
  425. uart_unlockTx( UART_Master );
  426. uart_unlockTx( UART_Slave );
  427. }
  428. // -- Connect receive functions --
  429. // - Cable Check variables -
  430. uint32_t Connect_cableFaultsMaster = 0;
  431. uint32_t Connect_cableFaultsSlave = 0;
  432. uint32_t Connect_cableChecksMaster = 0;
  433. uint32_t Connect_cableChecksSlave = 0;
  434. uint8_t Connect_cableOkMaster = 0;
  435. uint8_t Connect_cableOkSlave = 0;
  436. uint8_t Connect_receive_CableCheck( uint8_t byte, uint16_t *pending_bytes, uint8_t uart_num )
  437. {
  438. // Check if this is the first byte
  439. if ( *pending_bytes == 0xFFFF )
  440. {
  441. *pending_bytes = byte;
  442. if ( Connect_debug )
  443. {
  444. dbug_msg("PENDING SET -> ");
  445. printHex( byte );
  446. print(" ");
  447. printHex( *pending_bytes );
  448. print( NL );
  449. }
  450. }
  451. // Verify byte
  452. else
  453. {
  454. (*pending_bytes)--;
  455. // The argument bytes are always 0xD2 (11010010)
  456. if ( byte != 0xD2 )
  457. {
  458. warn_print("Cable Fault!");
  459. // Check which side of the chain
  460. if ( uart_num == UART_Slave )
  461. {
  462. Connect_cableFaultsSlave++;
  463. Connect_cableOkSlave = 0;
  464. print(" Slave ");
  465. }
  466. else
  467. {
  468. Connect_cableFaultsMaster++;
  469. Connect_cableOkMaster = 0;
  470. print(" Master ");
  471. }
  472. printHex( byte );
  473. print( NL );
  474. // Signal that the command should wait for a SYN again
  475. return 1;
  476. }
  477. else
  478. {
  479. // Check which side of the chain
  480. if ( uart_num == UART_Slave )
  481. {
  482. Connect_cableChecksSlave++;
  483. }
  484. else
  485. {
  486. Connect_cableChecksMaster++;
  487. }
  488. }
  489. }
  490. // If cable check was successful, set cable ok
  491. if ( *pending_bytes == 0 )
  492. {
  493. if ( uart_num == UART_Slave )
  494. {
  495. Connect_cableOkSlave = 1;
  496. }
  497. else
  498. {
  499. Connect_cableOkMaster = 1;
  500. }
  501. }
  502. if ( Connect_debug )
  503. {
  504. dbug_msg("CABLECHECK RECEIVE - ");
  505. printHex( byte );
  506. print(" ");
  507. printHex( *pending_bytes );
  508. print( NL );
  509. }
  510. // Check whether the cable check has finished
  511. return *pending_bytes == 0 ? 1 : 0;
  512. }
  513. uint8_t Connect_receive_IdRequest( uint8_t byte, uint16_t *pending_bytes, uint8_t uart_num )
  514. {
  515. dbug_print("IdRequest");
  516. // Check the directionality
  517. if ( uart_num == UART_Master )
  518. {
  519. erro_print("Invalid IdRequest direction...");
  520. }
  521. // Check if master, begin IdEnumeration
  522. if ( Connect_master )
  523. {
  524. // The first device is always id 1
  525. // Id 0 is reserved for the master
  526. Connect_send_IdEnumeration( 1 );
  527. }
  528. // Propagate IdRequest
  529. else
  530. {
  531. Connect_send_IdRequest();
  532. }
  533. return 1;
  534. }
  535. uint8_t Connect_receive_IdEnumeration( uint8_t id, uint16_t *pending_bytes, uint8_t uart_num )
  536. {
  537. dbug_print("IdEnumeration");
  538. // Check the directionality
  539. if ( uart_num == UART_Slave )
  540. {
  541. erro_print("Invalid IdEnumeration direction...");
  542. }
  543. // Set the device id
  544. Connect_id = id;
  545. // Send reponse back to master
  546. Connect_send_IdReport( id );
  547. // Propogate next Id if the connection is ok
  548. if ( Connect_cableOkSlave )
  549. {
  550. Connect_send_IdEnumeration( id + 1 );
  551. }
  552. return 1;
  553. }
  554. uint8_t Connect_receive_IdReport( uint8_t id, uint16_t *pending_bytes, uint8_t uart_num )
  555. {
  556. dbug_print("IdReport");
  557. // Check the directionality
  558. if ( uart_num == UART_Master )
  559. {
  560. erro_print("Invalid IdRequest direction...");
  561. }
  562. // Track Id response if master
  563. if ( Connect_master )
  564. {
  565. info_msg("Id Reported: ");
  566. printHex( id );
  567. print( NL );
  568. // Check if this is the highest ID
  569. if ( id > Connect_maxId )
  570. Connect_maxId = id;
  571. return 1;
  572. }
  573. // Propagate id if yet another slave
  574. else
  575. {
  576. Connect_send_IdReport( id );
  577. }
  578. return 1;
  579. }
  580. // - Scan Code Variables -
  581. TriggerGuide Connect_receive_ScanCodeBuffer;
  582. uint8_t Connect_receive_ScanCodeBufferPos;
  583. uint8_t Connect_receive_ScanCodeDeviceId;
  584. uint8_t Connect_receive_ScanCode( uint8_t byte, uint16_t *pending_bytes, uint8_t uart_num )
  585. {
  586. // Check the directionality
  587. if ( uart_num == UART_Master )
  588. {
  589. erro_print("Invalid ScanCode direction...");
  590. }
  591. // Master node, trigger scan codes
  592. if ( Connect_master ) switch ( (*pending_bytes)-- )
  593. {
  594. // Byte count always starts at 0xFFFF
  595. case 0xFFFF: // Device Id
  596. Connect_receive_ScanCodeDeviceId = byte;
  597. break;
  598. case 0xFFFE: // Number of TriggerGuides in bytes (byte * 3)
  599. *pending_bytes = byte * sizeof( TriggerGuide );
  600. Connect_receive_ScanCodeBufferPos = 0;
  601. break;
  602. default:
  603. // Set the specific TriggerGuide entry
  604. ((uint8_t*)&Connect_receive_ScanCodeBuffer)[ Connect_receive_ScanCodeBufferPos++ ] = byte;
  605. // Reset the BufferPos if higher than sizeof TriggerGuide
  606. // And send the TriggerGuide to the Macro Module
  607. if ( Connect_receive_ScanCodeBufferPos >= sizeof( TriggerGuide ) )
  608. {
  609. Connect_receive_ScanCodeBufferPos = 0;
  610. // Adjust ScanCode offset
  611. if ( Connect_receive_ScanCodeDeviceId > 0 )
  612. {
  613. // Check if this node is too large
  614. if ( Connect_receive_ScanCodeDeviceId >= InterconnectNodeMax )
  615. {
  616. warn_msg("Not enough interconnect layout nodes configured: ");
  617. printHex( Connect_receive_ScanCodeDeviceId );
  618. print( NL );
  619. break;
  620. }
  621. // This variable is in generatedKeymaps.h
  622. extern uint8_t InterconnectOffsetList[];
  623. Connect_receive_ScanCodeBuffer.scanCode = Connect_receive_ScanCodeBuffer.scanCode + InterconnectOffsetList[ Connect_receive_ScanCodeDeviceId - 1 ];
  624. }
  625. // ScanCode receive debug
  626. if ( Connect_debug )
  627. {
  628. dbug_msg("");
  629. printHex( Connect_receive_ScanCodeBuffer.type );
  630. print(" ");
  631. printHex( Connect_receive_ScanCodeBuffer.state );
  632. print(" ");
  633. printHex( Connect_receive_ScanCodeBuffer.scanCode );
  634. print( NL );
  635. }
  636. // Send ScanCode to macro module
  637. Macro_interconnectAdd( &Connect_receive_ScanCodeBuffer );
  638. }
  639. break;
  640. }
  641. // Propagate ScanCode packet
  642. else switch ( (*pending_bytes)-- )
  643. {
  644. // Byte count always starts at 0xFFFF
  645. case 0xFFFF: // Device Id
  646. {
  647. Connect_receive_ScanCodeDeviceId = byte;
  648. // Lock the master Tx buffer
  649. uart_lockTx( UART_Master );
  650. // Send header + Id byte
  651. uint8_t header[] = { 0x16, 0x01, ScanCode, byte };
  652. Connect_addBytes( header, sizeof( header ), UART_Master );
  653. break;
  654. }
  655. case 0xFFFE: // Number of TriggerGuides in bytes
  656. *pending_bytes = byte * sizeof( TriggerGuide );
  657. Connect_receive_ScanCodeBufferPos = 0;
  658. // Pass through byte
  659. Connect_addBytes( &byte, 1, UART_Master );
  660. break;
  661. default:
  662. // Pass through byte
  663. Connect_addBytes( &byte, 1, UART_Master );
  664. // Unlock Tx Buffer after sending last byte
  665. if ( *pending_bytes == 0 )
  666. uart_unlockTx( UART_Master );
  667. break;
  668. }
  669. // Check whether the scan codes have finished sending
  670. return *pending_bytes == 0 ? 1 : 0;
  671. }
  672. uint8_t Connect_receive_Animation( uint8_t byte, uint16_t *pending_bytes, uint8_t uart_num )
  673. {
  674. dbug_print("Animation");
  675. return 1;
  676. }
  677. // Baud Rate
  678. // NOTE: If finer baud adjustment is needed see UARTx_C4 -> BRFA in the datasheet
  679. uint16_t Connect_baud = UARTConnectBaud_define; // Max setting of 8191
  680. uint16_t Connect_baudFine = UARTConnectBaudFine_define;
  681. // Connect receive function lookup
  682. void *Connect_receiveFunctions[] = {
  683. Connect_receive_CableCheck,
  684. Connect_receive_IdRequest,
  685. Connect_receive_IdEnumeration,
  686. Connect_receive_IdReport,
  687. Connect_receive_ScanCode,
  688. Connect_receive_Animation,
  689. };
  690. // ----- Interrupt Functions -----
  691. // Master / UART0 ISR
  692. void uart0_status_isr()
  693. {
  694. // Process Rx buffer
  695. uart_processRx( 0 );
  696. }
  697. // Slave / UART1 ISR
  698. void uart1_status_isr()
  699. {
  700. // Process Rx buffer
  701. uart_processRx( 1 );
  702. }
  703. // ----- Functions -----
  704. // Resets the state of the UART buffers and state variables
  705. void Connect_reset()
  706. {
  707. // Rx Status Variables
  708. uart0_rx_status = UARTStatus_Wait;
  709. uart1_rx_status = UARTStatus_Wait;
  710. uart0_rx_bytes_waiting = 0;
  711. uart1_rx_bytes_waiting = 0;
  712. uart0_lock = 0;
  713. uart1_lock = 0;
  714. // Tx Status Variables
  715. uart0_tx_status = UARTStatus_Ready;
  716. uart1_tx_status = UARTStatus_Ready;
  717. // Ring Buffer Variables
  718. uart0_buffer_head = 0;
  719. uart0_buffer_tail = 0;
  720. uart0_buffer_items = 0;
  721. uart1_buffer_head = 0;
  722. uart1_buffer_tail = 0;
  723. uart1_buffer_items = 0;
  724. }
  725. // Setup connection to other side
  726. // - Only supports a single slave and master
  727. // - If USB has been initiallized at this point, this side is the master
  728. // - If both sides assert master, flash error leds
  729. void Connect_setup( uint8_t master )
  730. {
  731. // Indication that UARTs are not ready
  732. uarts_configured = 0;
  733. // Register Connect CLI dictionary
  734. CLI_registerDictionary( uartConnectCLIDict, uartConnectCLIDictName );
  735. // Check if master
  736. Connect_master = master;
  737. if ( Connect_master )
  738. Connect_id = 0; // 0x00 is always the master Id
  739. // Master / UART0 setup
  740. // Slave / UART1 setup
  741. // Setup the the UART interface for keyboard data input
  742. SIM_SCGC4 |= SIM_SCGC4_UART0; // Disable clock gating
  743. SIM_SCGC4 |= SIM_SCGC4_UART1; // Disable clock gating
  744. // Pin Setup for UART0 / UART1
  745. PORTA_PCR1 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_PFE | PORT_PCR_MUX(2); // RX Pin
  746. PORTA_PCR2 = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(2); // TX Pin
  747. PORTE_PCR0 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_PFE | PORT_PCR_MUX(3); // RX Pin
  748. PORTE_PCR1 = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(3); // TX Pin
  749. // Baud Rate setting
  750. UART0_BDH = (uint8_t)(Connect_baud >> 8);
  751. UART0_BDL = (uint8_t)Connect_baud;
  752. UART0_C4 = Connect_baudFine;
  753. UART1_BDH = (uint8_t)(Connect_baud >> 8);
  754. UART1_BDL = (uint8_t)Connect_baud;
  755. UART1_C4 = Connect_baudFine;
  756. // 8 bit, Even Parity, Idle Character bit after stop
  757. // NOTE: For 8 bit with Parity you must enable 9 bit transmission (pg. 1065)
  758. // You only need to use UART0_D for 8 bit reading/writing though
  759. // UART_C1_M UART_C1_PE UART_C1_PT UART_C1_ILT
  760. UART0_C1 = UART_C1_M | UART_C1_PE | UART_C1_ILT;
  761. UART1_C1 = UART_C1_M | UART_C1_PE | UART_C1_ILT;
  762. // Number of bytes in FIFO before TX Interrupt
  763. UART0_TWFIFO = 1;
  764. UART1_TWFIFO = 1;
  765. // Number of bytes in FIFO before RX Interrupt
  766. UART0_RWFIFO = 1;
  767. UART1_RWFIFO = 1;
  768. // Enable TX and RX FIFOs
  769. UART0_PFIFO = UART_PFIFO_TXFE | UART_PFIFO_RXFE;
  770. UART1_PFIFO = UART_PFIFO_TXFE | UART_PFIFO_RXFE;
  771. // Reciever Inversion Disabled, LSBF
  772. // UART_S2_RXINV UART_S2_MSBF
  773. UART0_S2 |= 0x00;
  774. UART1_S2 |= 0x00;
  775. // Transmit Inversion Disabled
  776. // UART_C3_TXINV
  777. UART0_C3 |= 0x00;
  778. UART1_C3 |= 0x00;
  779. // TX Enabled, RX Enabled, RX Interrupt Enabled
  780. // UART_C2_TE UART_C2_RE UART_C2_RIE
  781. UART0_C2 = UART_C2_TE | UART_C2_RE | UART_C2_RIE;
  782. UART1_C2 = UART_C2_TE | UART_C2_RE | UART_C2_RIE;
  783. // Add interrupts to the vector table
  784. NVIC_ENABLE_IRQ( IRQ_UART0_STATUS );
  785. NVIC_ENABLE_IRQ( IRQ_UART1_STATUS );
  786. // UARTs are now ready to go
  787. uarts_configured = 1;
  788. // Reset the state of the UART variables
  789. Connect_reset();
  790. }
  791. // Scan for updates in the master/slave
  792. // - Interrupts will deal with most input functions
  793. // - Used to send queries
  794. // - SyncEvent is sent immediately once the current command is sent
  795. // - SyncEvent is also blocking until sent
  796. void Connect_scan()
  797. {
  798. // Check if initially configured as a slave and usb comes up
  799. // Then reconfigure as a master
  800. if ( !Connect_master && Output_Available && !Connect_override )
  801. {
  802. Connect_setup( Output_Available );
  803. }
  804. // Limit how often we do cable checks
  805. uint32_t time_compare = 0x7FF; // Must be all 1's, 0x3FF is valid, 0x4FF is not
  806. uint32_t current_time = systick_millis_count;
  807. if ( Connect_lastCheck != current_time
  808. && ( current_time & time_compare ) == time_compare
  809. )
  810. {
  811. // Make sure we don't double check if the clock speed is too high
  812. Connect_lastCheck = current_time;
  813. // Send a cable check command of 2 bytes
  814. Connect_send_CableCheck( UARTConnectCableCheckLength_define );
  815. // If this is a slave, and we don't have an id yeth
  816. // Don't bother sending if there are cable issues
  817. if ( !Connect_master && Connect_id == 0xFF && Connect_cableOkMaster )
  818. {
  819. Connect_send_IdRequest();
  820. }
  821. }
  822. // Only process commands if uarts have been configured
  823. if ( uarts_configured )
  824. {
  825. // Check if Tx Buffers are empty and the Tx Ring buffers have data to send
  826. // This happens if there was previously nothing to send
  827. if ( uart0_buffer_items > 0 && UART0_TCFIFO == 0 )
  828. uart_fillTxFifo( 0 );
  829. if ( uart1_buffer_items > 0 && UART1_TCFIFO == 0 )
  830. uart_fillTxFifo( 1 );
  831. }
  832. }
  833. // ----- CLI Command Functions -----
  834. void cliFunc_connectCmd( char* args )
  835. {
  836. // Parse number from argument
  837. // NOTE: Only first argument is used
  838. char* arg1Ptr;
  839. char* arg2Ptr;
  840. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  841. print( NL );
  842. switch ( numToInt( &arg1Ptr[0] ) )
  843. {
  844. case CableCheck:
  845. Connect_send_CableCheck( UARTConnectCableCheckLength_define );
  846. break;
  847. case IdRequest:
  848. Connect_send_IdRequest();
  849. break;
  850. case IdEnumeration:
  851. Connect_send_IdEnumeration( 5 );
  852. break;
  853. case IdReport:
  854. Connect_send_IdReport( 8 );
  855. break;
  856. case ScanCode:
  857. {
  858. TriggerGuide scanCodes[] = { { 0x00, 0x01, 0x05 }, { 0x00, 0x03, 0x16 } };
  859. Connect_send_ScanCode( 10, scanCodes, 2 );
  860. break;
  861. }
  862. case Animation:
  863. break;
  864. case RemoteCapability:
  865. // TODO
  866. break;
  867. case RemoteOutput:
  868. // TODO
  869. break;
  870. case RemoteInput:
  871. // TODO
  872. break;
  873. default:
  874. break;
  875. }
  876. }
  877. void cliFunc_connectDbg( char* args )
  878. {
  879. print( NL );
  880. info_msg("Connect Debug Mode Toggle");
  881. Connect_debug = !Connect_debug;
  882. }
  883. void cliFunc_connectIdl( char* args )
  884. {
  885. // Parse number from argument
  886. // NOTE: Only first argument is used
  887. char* arg1Ptr;
  888. char* arg2Ptr;
  889. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  890. print( NL );
  891. info_msg("Sending Sync Idles...");
  892. uint8_t count = numToInt( &arg1Ptr[0] );
  893. // Default to 2 idles
  894. if ( count == 0 )
  895. count = 2;
  896. Connect_send_Idle( count );
  897. }
  898. void cliFunc_connectLst( char* args )
  899. {
  900. const char *Command_strs[] = {
  901. "CableCheck",
  902. "IdRequest",
  903. "IdEnumeration",
  904. "IdReport",
  905. "ScanCode",
  906. "Animation",
  907. "RemoteCapability",
  908. "RemoteOutput",
  909. "RemoteInput",
  910. };
  911. print( NL );
  912. info_msg("List of UARTConnect commands");
  913. for ( uint8_t cmd = 0; cmd < Command_TOP; cmd++ )
  914. {
  915. print( NL );
  916. printInt8( cmd );
  917. print(" - ");
  918. dPrint( (char*)Command_strs[ cmd ] );
  919. }
  920. }
  921. void cliFunc_connectMst( char* args )
  922. {
  923. // Parse number from argument
  924. // NOTE: Only first argument is used
  925. char* arg1Ptr;
  926. char* arg2Ptr;
  927. CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
  928. print( NL );
  929. // Set override
  930. Connect_override = 1;
  931. switch ( arg1Ptr[0] )
  932. {
  933. // Disable override
  934. case 'd':
  935. case 'D':
  936. Connect_override = 0;
  937. case 's':
  938. case 'S':
  939. info_msg("Setting device as slave.");
  940. Connect_master = 0;
  941. Connect_id = 0xFF;
  942. break;
  943. case 'm':
  944. case 'M':
  945. default:
  946. info_msg("Setting device as master.");
  947. Connect_master = 1;
  948. Connect_id = 0;
  949. break;
  950. }
  951. }
  952. void cliFunc_connectRst( char* args )
  953. {
  954. print( NL );
  955. info_msg("Resetting UARTConnect state...");
  956. Connect_reset();
  957. // Reset node id
  958. Connect_id = 0xFF;
  959. }
  960. void cliFunc_connectSts( char* args )
  961. {
  962. print( NL );
  963. info_msg("UARTConnect Status");
  964. print( NL "Device Type:\t" );
  965. print( Connect_master ? "Master" : "Slave" );
  966. print( NL "Device Id:\t" );
  967. printHex( Connect_id );
  968. print( NL "Max Id:\t" );
  969. printHex( Connect_maxId );
  970. print( NL "Master <=" NL "\tStatus:\t");
  971. printHex( Connect_cableOkMaster );
  972. print( NL "\tFaults:\t");
  973. printHex32( Connect_cableFaultsMaster );
  974. print("/");
  975. printHex32( Connect_cableChecksMaster );
  976. print( NL "\tRx:\t");
  977. printHex( uart1_rx_status );
  978. print( NL "\tTx:\t");
  979. printHex( uart1_tx_status );
  980. print( NL "Slave <=" NL "\tStatus:\t");
  981. printHex( Connect_cableOkSlave );
  982. print( NL "\tFaults:\t");
  983. printHex32( Connect_cableFaultsSlave );
  984. print("/");
  985. printHex32( Connect_cableChecksSlave );
  986. print( NL "\tRx:\t");
  987. printHex( uart0_rx_status );
  988. print( NL "\tTx:\t");
  989. printHex( uart0_tx_status );
  990. }