1 /* Copyright (C) 2014-2015 by Jacob Alexander
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.
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.
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/>.
17 // ----- Includes -----
20 #include <Lib/ScanLib.h>
30 #include "connect_scan.h"
34 // ----- Defines -----
36 #define UART_Num_Interfaces 2
39 #define UART_Buffer_Size UARTConnectBufSize_define
45 // Macro for adding to each uart Tx ring buffer
46 #define uart_addTxBuffer( uartNum ) \
48 /* Delay UART copy until there's some space left */ \
49 while ( uart_tx_buf[ uartNum ].items + count > UART_Buffer_Size ) \
51 warn_msg("Too much data to send on UART0, waiting..."); \
54 /* Append data to ring buffer */ \
55 for ( uint8_t c = 0; c < count; c++ ) \
57 if ( Connect_debug ) \
59 printHex( buffer[ c ] ); \
60 print( " +" #uartNum NL ); \
62 uart_tx_buf[ uartNum ].buffer[ uart_tx_buf[ uartNum ].tail++ ] = buffer[ c ]; \
63 uart_tx_buf[ uartNum ].items++; \
64 if ( uart_tx_buf[ uartNum ].tail >= UART_Buffer_Size ) \
65 uart_tx_buf[ uartNum ].tail = 0; \
66 if ( uart_tx_buf[ uartNum ].head == uart_tx_buf[ uartNum ].tail ) \
67 uart_tx_buf[ uartNum ].head++; \
68 if ( uart_tx_buf[ uartNum ].head >= UART_Buffer_Size ) \
69 uart_tx_buf[ uartNum ].head = 0; \
73 // Macro for popping from Tx ring buffer
74 #define uart_fillTxFifo( uartNum ) \
76 uint8_t fifoSize = ( ( UART##uartNum##_PFIFO & UART_PFIFO_TXFIFOSIZE ) >> 2 ); \
77 if ( fifoSize == 0 ) \
79 if ( Connect_debug ) \
81 print( "TxFIFO " #uartNum " - " ); \
82 printHex( fifoSize ); \
84 printHex( UART##uartNum##_TCFIFO ); \
86 printHex( uart_tx_buf[ uartNum ].items ); \
89 /* XXX Doesn't work well */ \
90 /* while ( UART##uartNum##_TCFIFO < fifoSize ) */ \
91 /* More reliable, albeit slower */ \
92 fifoSize -= UART##uartNum##_TCFIFO; \
93 while ( fifoSize-- != 0 ) \
95 if ( uart_tx_buf[ uartNum ].items == 0 ) \
97 UART##uartNum##_D = uart_tx_buf[ uartNum ].buffer[ uart_tx_buf[ uartNum ].head++ ]; \
98 uart_tx_buf[ uartNum ].items--; \
99 if ( uart_tx_buf[ uartNum ].head >= UART_Buffer_Size ) \
100 uart_tx_buf[ uartNum ].head = 0; \
104 // Macros for locking/unlock Tx buffers
105 #define uart_lockTx( uartNum ) \
107 /* First, secure place in line for the resource */ \
108 while ( uart_tx_status[ uartNum ].lock ); \
109 uart_tx_status[ uartNum ].lock = 1; \
110 /* Next, wait unit the UART is ready */ \
111 while ( uart_tx_status[ uartNum ].status != UARTStatus_Ready ); \
112 uart_tx_status[ uartNum ].status = UARTStatus_Wait; \
115 #define uart_lockBothTx( uartNum1, uartNum2 ) \
117 /* First, secure place in line for the resource */ \
118 while ( uart_tx_status[ uartNum1 ].lock || uart_tx_status[ uartNum2 ].lock ); \
119 uart_tx_status[ uartNum1 ].lock = 1; \
120 uart_tx_status[ uartNum2 ].lock = 1; \
121 /* Next, wait unit the UARTs are ready */ \
122 while ( uart_tx_status[ uartNum1 ].status != UARTStatus_Ready || uart_tx_status[ uartNum2 ].status != UARTStatus_Ready ); \
123 uart_tx_status[ uartNum1 ].status = UARTStatus_Wait; \
124 uart_tx_status[ uartNum2 ].status = UARTStatus_Wait; \
127 #define uart_unlockTx( uartNum ) \
129 /* Ready the UART */ \
130 uart_tx_status[ uartNum ].status = UARTStatus_Ready; \
131 /* Unlock the resource */ \
132 uart_tx_status[ uartNum ].lock = 0; \
137 // ----- Function Declarations -----
140 void cliFunc_connectCmd ( char *args );
141 void cliFunc_connectDbg ( char *args );
142 void cliFunc_connectIdl ( char *args );
143 void cliFunc_connectLst ( char *args );
144 void cliFunc_connectMst ( char *args );
145 void cliFunc_connectRst ( char *args );
146 void cliFunc_connectSts ( char *args );
150 // ----- Structs -----
152 typedef struct UARTRingBuf {
156 uint8_t buffer[UART_Buffer_Size];
159 typedef struct UARTDMABuf {
160 uint8_t buffer[UART_Buffer_Size];
164 typedef struct UARTStatusRx {
167 uint16_t bytes_waiting;
170 typedef struct UARTStatusTx {
177 // ----- Variables -----
179 // Connect Module command dictionary
180 CLIDict_Entry( connectCmd, "Sends a command via UART Connect, first arg is which uart, next arg is the command, rest are the arguments." );
181 CLIDict_Entry( connectDbg, "Toggle UARTConnect debug mode." );
182 CLIDict_Entry( connectIdl, "Sends N number of Idle commands, 2 is the default value, and should be sufficient in most cases." );
183 CLIDict_Entry( connectLst, "Lists available UARTConnect commands and index id" );
184 CLIDict_Entry( connectMst, "Sets the device as master. Use argument of s to set as slave." );
185 CLIDict_Entry( connectRst, "Resets both Rx and Tx connect buffers and state variables." );
186 CLIDict_Entry( connectSts, "UARTConnect status." );
187 CLIDict_Def( uartConnectCLIDict, "UARTConnect Module Commands" ) = {
188 CLIDict_Item( connectCmd ),
189 CLIDict_Item( connectDbg ),
190 CLIDict_Item( connectIdl ),
191 CLIDict_Item( connectLst ),
192 CLIDict_Item( connectMst ),
193 CLIDict_Item( connectRst ),
194 CLIDict_Item( connectSts ),
195 { 0, 0, 0 } // Null entry for dictionary end
199 // -- Connect Device Id Variables --
200 uint8_t Connect_id = 255; // Invalid, unset
201 uint8_t Connect_master = 0;
202 uint8_t Connect_maxId = 0;
205 // -- Control Variables --
206 uint32_t Connect_lastCheck = 0; // Cable Check scheduler
207 uint8_t Connect_debug = 0; // Set 1 for debug
208 uint8_t Connect_override = 0; // Prevents master from automatically being set
210 volatile uint8_t uarts_configured = 0;
213 // -- Rx Variables --
215 volatile UARTDMABuf uart_rx_buf[UART_Num_Interfaces];
216 volatile UARTStatusRx uart_rx_status[UART_Num_Interfaces];
219 // -- Tx Variables --
221 UARTRingBuf uart_tx_buf [UART_Num_Interfaces];
222 UARTStatusTx uart_tx_status[UART_Num_Interfaces];
225 // -- Ring Buffer Convenience Functions --
227 void Connect_addBytes( uint8_t *buffer, uint8_t count, uint8_t uart )
229 // Too big to fit into buffer
230 if ( count > UART_Buffer_Size )
232 erro_msg("Too big of a command to fit into the buffer...");
239 uart_addTxBuffer( UART_Master );
240 uart_addTxBuffer( UART_Slave );
242 erro_msg("Invalid UART to send from...");
248 // -- Connect send functions --
250 // patternLen defines how many bytes should the incrementing pattern have
251 void Connect_send_CableCheck( uint8_t patternLen )
253 // Wait until the Tx buffers are ready, then lock them
254 uart_lockBothTx( UART_Master, UART_Slave );
257 uint8_t header[] = { 0x16, 0x01, CableCheck, patternLen };
260 Connect_addBytes( header, sizeof( header ), UART_Master );
261 Connect_addBytes( header, sizeof( header ), UART_Slave );
263 // Send 0xD2 (11010010) for each argument
264 uint8_t value = 0xD2;
265 for ( uint8_t c = 0; c < patternLen; c++ )
267 Connect_addBytes( &value, 1, UART_Master );
268 Connect_addBytes( &value, 1, UART_Slave );
271 // Release Tx buffers
272 uart_unlockTx( UART_Master );
273 uart_unlockTx( UART_Slave );
276 void Connect_send_IdRequest()
278 // Lock master bound Tx
279 uart_lockTx( UART_Master );
282 uint8_t header[] = { 0x16, 0x01, IdRequest };
285 Connect_addBytes( header, sizeof( header ), UART_Master );
288 uart_unlockTx( UART_Master );
291 // id is the value the next slave should enumerate as
292 void Connect_send_IdEnumeration( uint8_t id )
294 // Lock slave bound Tx
295 uart_lockTx( UART_Slave );
298 uint8_t header[] = { 0x16, 0x01, IdEnumeration, id };
301 Connect_addBytes( header, sizeof( header ), UART_Slave );
304 uart_unlockTx( UART_Slave );
307 // id is the currently assigned id to the slave
308 void Connect_send_IdReport( uint8_t id )
310 // Lock master bound Tx
311 uart_lockTx( UART_Master );
314 uint8_t header[] = { 0x16, 0x01, IdReport, id };
317 Connect_addBytes( header, sizeof( header ), UART_Master );
320 uart_unlockTx( UART_Master );
323 // id is the currently assigned id to the slave
324 // scanCodeStateList is an array of [scancode, state]'s (8 bit values)
325 // numScanCodes is the number of scan codes to parse from array
326 void Connect_send_ScanCode( uint8_t id, TriggerGuide *scanCodeStateList, uint8_t numScanCodes )
328 // Lock master bound Tx
329 uart_lockTx( UART_Master );
332 uint8_t header[] = { 0x16, 0x01, ScanCode, id, numScanCodes };
335 Connect_addBytes( header, sizeof( header ), UART_Master );
337 // Send each of the scan codes
338 Connect_addBytes( (uint8_t*)scanCodeStateList, numScanCodes * TriggerGuideSize, UART_Master );
341 uart_unlockTx( UART_Master );
344 // id is the currently assigned id to the slave
345 // paramList is an array of [param, value]'s (8 bit values)
346 // numParams is the number of params to parse from the array
347 void Connect_send_Animation( uint8_t id, uint8_t *paramList, uint8_t numParams )
349 // Lock slave bound Tx
350 uart_lockTx( UART_Slave );
353 uint8_t header[] = { 0x16, 0x01, Animation, id, numParams };
356 Connect_addBytes( header, sizeof( header ), UART_Slave );
358 // Send each of the scan codes
359 Connect_addBytes( paramList, numParams, UART_Slave );
362 uart_unlockTx( UART_Slave );
365 // Send a remote capability command using capability index
366 // This may not be what's expected (especially if the firmware is not the same on each node)
367 // To broadcast to all slave nodes, set id to 255 instead of a specific id
368 void Connect_send_RemoteCapability( uint8_t id, uint8_t capabilityIndex, uint8_t state, uint8_t stateType, uint8_t numArgs, uint8_t *args )
371 uint8_t header[] = { 0x16, 0x01, RemoteCapability, id, capabilityIndex, state, stateType, numArgs };
374 if ( id == Connect_id )
377 // Send towards slave node
378 if ( id > Connect_id )
380 // Lock slave bound Tx
381 uart_lockTx( UART_Slave );
384 Connect_addBytes( header, sizeof( header ), UART_Slave );
387 Connect_addBytes( args, numArgs, UART_Slave );
390 uart_unlockTx( UART_Slave );
393 // Send towards master node
394 if ( id < Connect_id || id == 255 )
396 // Lock slave bound Tx
397 uart_lockTx( UART_Master );
400 Connect_addBytes( header, sizeof( header ), UART_Master );
403 Connect_addBytes( args, numArgs, UART_Master );
406 uart_unlockTx( UART_Master );
410 void Connect_send_Idle( uint8_t num )
412 // Wait until the Tx buffers are ready, then lock them
413 uart_lockBothTx( UART_Slave, UART_Master );
415 // Send n number of idles to reset link status (if in a bad state)
416 uint8_t value = 0x16;
417 for ( uint8_t c = 0; c < num; c++ )
419 Connect_addBytes( &value, 1, UART_Master );
420 Connect_addBytes( &value, 1, UART_Slave );
423 // Release Tx buffers
424 uart_unlockTx( UART_Master );
425 uart_unlockTx( UART_Slave );
429 // -- Connect receive functions --
431 // - Cable Check variables -
432 uint32_t Connect_cableFaultsMaster = 0;
433 uint32_t Connect_cableFaultsSlave = 0;
434 uint32_t Connect_cableChecksMaster = 0;
435 uint32_t Connect_cableChecksSlave = 0;
436 uint8_t Connect_cableOkMaster = 0;
437 uint8_t Connect_cableOkSlave = 0;
439 uint8_t Connect_receive_CableCheck( uint8_t byte, uint16_t *pending_bytes, uint8_t uart_num )
441 // Check if this is the first byte
442 if ( *pending_bytes == 0xFFFF )
444 *pending_bytes = byte;
448 dbug_msg("PENDING SET -> ");
451 printHex( *pending_bytes );
460 // The argument bytes are always 0xD2 (11010010)
463 warn_print("Cable Fault!");
465 // Check which side of the chain
466 if ( uart_num == UART_Slave )
468 Connect_cableFaultsSlave++;
469 Connect_cableOkSlave = 0;
474 Connect_cableFaultsMaster++;
475 Connect_cableOkMaster = 0;
481 // Signal that the command should wait for a SYN again
486 // Check which side of the chain
487 if ( uart_num == UART_Slave )
489 Connect_cableChecksSlave++;
493 Connect_cableChecksMaster++;
498 // If cable check was successful, set cable ok
499 if ( *pending_bytes == 0 )
501 if ( uart_num == UART_Slave )
503 Connect_cableOkSlave = 1;
507 Connect_cableOkMaster = 1;
513 dbug_msg("CABLECHECK RECEIVE - ");
516 printHex( *pending_bytes );
520 // Check whether the cable check has finished
521 return *pending_bytes == 0 ? 1 : 0;
524 uint8_t Connect_receive_IdRequest( uint8_t byte, uint16_t *pending_bytes, uint8_t uart_num )
526 dbug_print("IdRequest");
527 // Check the directionality
528 if ( uart_num == UART_Master )
530 erro_print("Invalid IdRequest direction...");
533 // Check if master, begin IdEnumeration
534 if ( Connect_master )
536 // The first device is always id 1
537 // Id 0 is reserved for the master
538 Connect_send_IdEnumeration( 1 );
540 // Propagate IdRequest
543 Connect_send_IdRequest();
549 uint8_t Connect_receive_IdEnumeration( uint8_t id, uint16_t *pending_bytes, uint8_t uart_num )
551 dbug_print("IdEnumeration");
552 // Check the directionality
553 if ( uart_num == UART_Slave )
555 erro_print("Invalid IdEnumeration direction...");
561 // Send reponse back to master
562 Connect_send_IdReport( id );
564 // Propogate next Id if the connection is ok
565 if ( Connect_cableOkSlave )
567 Connect_send_IdEnumeration( id + 1 );
573 uint8_t Connect_receive_IdReport( uint8_t id, uint16_t *pending_bytes, uint8_t uart_num )
575 dbug_print("IdReport");
576 // Check the directionality
577 if ( uart_num == UART_Master )
579 erro_print("Invalid IdRequest direction...");
582 // Track Id response if master
583 if ( Connect_master )
585 info_msg("Id Reported: ");
589 // Check if this is the highest ID
590 if ( id > Connect_maxId )
594 // Propagate id if yet another slave
597 Connect_send_IdReport( id );
603 // - Scan Code Variables -
604 TriggerGuide Connect_receive_ScanCodeBuffer;
605 uint8_t Connect_receive_ScanCodeBufferPos;
606 uint8_t Connect_receive_ScanCodeDeviceId;
608 uint8_t Connect_receive_ScanCode( uint8_t byte, uint16_t *pending_bytes, uint8_t uart_num )
610 // Check the directionality
611 if ( uart_num == UART_Master )
613 erro_print("Invalid ScanCode direction...");
616 // Master node, trigger scan codes
617 if ( Connect_master ) switch ( (*pending_bytes)-- )
619 // Byte count always starts at 0xFFFF
620 case 0xFFFF: // Device Id
621 Connect_receive_ScanCodeDeviceId = byte;
624 case 0xFFFE: // Number of TriggerGuides in bytes (byte * 3)
625 *pending_bytes = byte * sizeof( TriggerGuide );
626 Connect_receive_ScanCodeBufferPos = 0;
630 // Set the specific TriggerGuide entry
631 ((uint8_t*)&Connect_receive_ScanCodeBuffer)[ Connect_receive_ScanCodeBufferPos++ ] = byte;
633 // Reset the BufferPos if higher than sizeof TriggerGuide
634 // And send the TriggerGuide to the Macro Module
635 if ( Connect_receive_ScanCodeBufferPos >= sizeof( TriggerGuide ) )
637 Connect_receive_ScanCodeBufferPos = 0;
639 // Adjust ScanCode offset
640 if ( Connect_receive_ScanCodeDeviceId > 0 )
642 // Check if this node is too large
643 if ( Connect_receive_ScanCodeDeviceId >= InterconnectNodeMax )
645 warn_msg("Not enough interconnect layout nodes configured: ");
646 printHex( Connect_receive_ScanCodeDeviceId );
651 // This variable is in generatedKeymaps.h
652 extern uint8_t InterconnectOffsetList[];
653 Connect_receive_ScanCodeBuffer.scanCode = Connect_receive_ScanCodeBuffer.scanCode + InterconnectOffsetList[ Connect_receive_ScanCodeDeviceId - 1 ];
656 // ScanCode receive debug
660 printHex( Connect_receive_ScanCodeBuffer.type );
662 printHex( Connect_receive_ScanCodeBuffer.state );
664 printHex( Connect_receive_ScanCodeBuffer.scanCode );
668 // Send ScanCode to macro module
669 Macro_interconnectAdd( &Connect_receive_ScanCodeBuffer );
674 // Propagate ScanCode packet
675 // XXX It would be safer to buffer the scancodes first, before transmitting the packet -Jacob
676 // The current method is the more efficient/aggressive, but could cause issues if there were errors during transmission
677 else switch ( (*pending_bytes)-- )
679 // Byte count always starts at 0xFFFF
680 case 0xFFFF: // Device Id
682 Connect_receive_ScanCodeDeviceId = byte;
684 // Lock the master Tx buffer
685 uart_lockTx( UART_Master );
687 // Send header + Id byte
688 uint8_t header[] = { 0x16, 0x01, ScanCode, byte };
689 Connect_addBytes( header, sizeof( header ), UART_Master );
692 case 0xFFFE: // Number of TriggerGuides in bytes
693 *pending_bytes = byte * sizeof( TriggerGuide );
694 Connect_receive_ScanCodeBufferPos = 0;
697 Connect_addBytes( &byte, 1, UART_Master );
702 Connect_addBytes( &byte, 1, UART_Master );
704 // Unlock Tx Buffer after sending last byte
705 if ( *pending_bytes == 0 )
706 uart_unlockTx( UART_Master );
710 // Check whether the scan codes have finished sending
711 return *pending_bytes == 0 ? 1 : 0;
714 uint8_t Connect_receive_Animation( uint8_t byte, uint16_t *pending_bytes, uint8_t uart_num )
716 dbug_print("Animation");
720 // - Remote Capability Variables -
721 #define Connect_receive_RemoteCapabilityMaxArgs 5 // XXX Calculate the max using kll
722 RemoteCapabilityCommand Connect_receive_RemoteCapabilityBuffer;
723 uint8_t Connect_receive_RemoteCapabilityArgs[Connect_receive_RemoteCapabilityMaxArgs];
725 uint8_t Connect_receive_RemoteCapability( uint8_t byte, uint16_t *pending_bytes, uint8_t uart_num )
727 // Check which byte in the packet we are at
728 switch ( (*pending_bytes)-- )
730 // Byte count always starts at 0xFFFF
731 case 0xFFFF: // Device Id
732 Connect_receive_RemoteCapabilityBuffer.id = byte;
735 case 0xFFFE: // Capability Index
736 Connect_receive_RemoteCapabilityBuffer.capabilityIndex = byte;
739 case 0xFFFD: // State
740 Connect_receive_RemoteCapabilityBuffer.state = byte;
743 case 0xFFFC: // StateType
744 Connect_receive_RemoteCapabilityBuffer.stateType = byte;
747 case 0xFFFB: // Number of args
748 Connect_receive_RemoteCapabilityBuffer.numArgs = byte;
749 *pending_bytes = byte;
752 default: // Args (# defined by previous byte)
753 Connect_receive_RemoteCapabilityArgs[
754 Connect_receive_RemoteCapabilityBuffer.numArgs - *pending_bytes + 1
757 // If entire packet has been fully received
758 if ( *pending_bytes == 0 )
760 // Determine if this is the node to run the capability on
761 // Conditions: Matches or broadcast (0xFF)
762 if ( Connect_receive_RemoteCapabilityBuffer.id == 0xFF
763 || Connect_receive_RemoteCapabilityBuffer.id == Connect_id )
765 extern const Capability CapabilitiesList[]; // See generatedKeymap.h
766 void (*capability)(uint8_t, uint8_t, uint8_t*) = (void(*)(uint8_t, uint8_t, uint8_t*))(
767 CapabilitiesList[ Connect_receive_RemoteCapabilityBuffer.capabilityIndex ].func
770 Connect_receive_RemoteCapabilityBuffer.state,
771 Connect_receive_RemoteCapabilityBuffer.stateType,
772 &Connect_receive_RemoteCapabilityArgs[2]
776 // If this is not the correct node, keep sending it in the same direction (doesn't matter if more nodes exist)
777 // or if this is a broadcast
778 if ( Connect_receive_RemoteCapabilityBuffer.id == 0xFF
779 || Connect_receive_RemoteCapabilityBuffer.id != Connect_id )
781 // Prepare outgoing packet
782 Connect_receive_RemoteCapabilityBuffer.command = RemoteCapability;
784 // Send to the other UART (not the one receiving the packet from
785 uint8_t uart_direction = uart_num == UART_Master ? UART_Slave : UART_Master;
788 switch ( uart_direction )
790 case UART_Master: uart_lockTx( UART_Master ); break;
791 case UART_Slave: uart_lockTx( UART_Slave ); break;
795 uint8_t header[] = { 0x16, 0x01 };
796 Connect_addBytes( header, sizeof( header ), uart_direction );
798 // Send Remote Capability and arguments
799 Connect_addBytes( (uint8_t*)&Connect_receive_RemoteCapabilityBuffer, sizeof( RemoteCapabilityCommand ), uart_direction );
800 Connect_addBytes( Connect_receive_RemoteCapabilityArgs, Connect_receive_RemoteCapabilityBuffer.numArgs, uart_direction );
803 switch ( uart_direction )
805 case UART_Master: uart_unlockTx( UART_Master ); break;
806 case UART_Slave: uart_unlockTx( UART_Slave ); break;
813 // Check whether the scan codes have finished sending
814 return *pending_bytes == 0 ? 1 : 0;
819 // NOTE: If finer baud adjustment is needed see UARTx_C4 -> BRFA in the datasheet
820 uint16_t Connect_baud = UARTConnectBaud_define; // Max setting of 8191
821 uint16_t Connect_baudFine = UARTConnectBaudFine_define;
823 // Connect receive function lookup
824 void *Connect_receiveFunctions[] = {
825 Connect_receive_CableCheck,
826 Connect_receive_IdRequest,
827 Connect_receive_IdEnumeration,
828 Connect_receive_IdReport,
829 Connect_receive_ScanCode,
830 Connect_receive_Animation,
831 Connect_receive_RemoteCapability,
836 // ----- Functions -----
838 // Resets the state of the UART buffers and state variables
842 memset( (void*)uart_rx_status, 0, sizeof( UARTStatusRx ) * UART_Num_Interfaces );
845 memset( (void*)uart_tx_buf, 0, sizeof( UARTRingBuf ) * UART_Num_Interfaces );
846 memset( (void*)uart_tx_status, 0, sizeof( UARTStatusTx ) * UART_Num_Interfaces );
848 // Set Rx/Tx buffers as ready
849 for ( uint8_t inter = 0; inter < UART_Num_Interfaces; inter++ )
851 uart_tx_status[ inter ].status = UARTStatus_Ready;
852 uart_rx_buf[ inter ].last_read = UART_Buffer_Size;
857 // Setup connection to other side
858 // - Only supports a single slave and master
859 // - If USB has been initiallized at this point, this side is the master
860 // - If both sides assert master, flash error leds
861 void Connect_setup( uint8_t master )
863 // Indication that UARTs are not ready
864 uarts_configured = 0;
866 // Register Connect CLI dictionary
867 CLI_registerDictionary( uartConnectCLIDict, uartConnectCLIDictName );
870 Connect_master = master;
871 if ( Connect_master )
872 Connect_id = 0; // 0x00 is always the master Id
876 // Setup the the UART interface for keyboard data input
877 SIM_SCGC4 |= SIM_SCGC4_UART0; // Disable clock gating
878 SIM_SCGC4 |= SIM_SCGC4_UART1; // Disable clock gating
880 // Pin Setup for UART0 / UART1
881 PORTA_PCR1 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_PFE | PORT_PCR_MUX(2); // RX Pin
882 PORTA_PCR2 = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(2); // TX Pin
883 PORTE_PCR0 = PORT_PCR_PE | PORT_PCR_PS | PORT_PCR_PFE | PORT_PCR_MUX(3); // RX Pin
884 PORTE_PCR1 = PORT_PCR_DSE | PORT_PCR_SRE | PORT_PCR_MUX(3); // TX Pin
887 UART0_BDH = (uint8_t)(Connect_baud >> 8);
888 UART0_BDL = (uint8_t)Connect_baud;
889 UART0_C4 = Connect_baudFine;
890 UART1_BDH = (uint8_t)(Connect_baud >> 8);
891 UART1_BDL = (uint8_t)Connect_baud;
892 UART1_C4 = Connect_baudFine;
894 // 8 bit, Even Parity, Idle Character bit after stop
895 // NOTE: For 8 bit with Parity you must enable 9 bit transmission (pg. 1065)
896 // You only need to use UART0_D for 8 bit reading/writing though
897 // UART_C1_M UART_C1_PE UART_C1_PT UART_C1_ILT
898 UART0_C1 = UART_C1_M | UART_C1_PE | UART_C1_ILT;
899 UART1_C1 = UART_C1_M | UART_C1_PE | UART_C1_ILT;
901 // Only using Tx Fifos
902 UART0_PFIFO = UART_PFIFO_TXFE;
903 UART1_PFIFO = UART_PFIFO_TXFE;
906 SIM_SCGC6 |= SIM_SCGC6_DMAMUX;
907 SIM_SCGC7 |= SIM_SCGC7_DMA;
909 // Start with channels disabled first
913 // Configure DMA channels
914 //DMA_DSR_BCR0 |= DMA_DSR_BCR_DONE_MASK; // TODO What's this?
918 // Default control register
922 DMA_DCHPRI0 = 0; // Ch 0, priority 0
923 DMA_DCHPRI1 = 1; // ch 1, priority 1
925 // Clear error interrupts
929 DMA_TCD0_SADDR = (uint32_t*)&UART0_D;
930 DMA_TCD1_SADDR = (uint32_t*)&UART1_D;
934 // No modulo, 8-bit transfer size
935 DMA_TCD0_ATTR = DMA_TCD_ATTR_SMOD(0) | DMA_TCD_ATTR_SSIZE(0) | DMA_TCD_ATTR_DMOD(0) | DMA_TCD_ATTR_DSIZE(0);
936 DMA_TCD1_ATTR = DMA_TCD_ATTR_SMOD(0) | DMA_TCD_ATTR_SSIZE(0) | DMA_TCD_ATTR_DMOD(0) | DMA_TCD_ATTR_DSIZE(0);
938 // One byte transferred at a time
939 DMA_TCD0_NBYTES_MLNO = 1;
940 DMA_TCD1_NBYTES_MLNO = 1;
942 // Source address does not change
946 // Destination buffer
947 DMA_TCD0_DADDR = (uint32_t*)uart_rx_buf[0].buffer;
948 DMA_TCD1_DADDR = (uint32_t*)uart_rx_buf[1].buffer;
950 // Incoming byte, increment by 1 in the rx buffer
954 // Single major loop, must be the same value
955 DMA_TCD0_CITER_ELINKNO = UART_Buffer_Size;
956 DMA_TCD1_CITER_ELINKNO = UART_Buffer_Size;
957 DMA_TCD0_BITER_ELINKNO = UART_Buffer_Size;
958 DMA_TCD1_BITER_ELINKNO = UART_Buffer_Size;
960 // Reset buffer when full
961 DMA_TCD0_DLASTSGA = -( UART_Buffer_Size );
962 DMA_TCD1_DLASTSGA = -( UART_Buffer_Size );
964 // Enable DMA channels
965 DMA_ERQ |= DMA_ERQ_ERQ0 | DMA_ERQ_ERQ1;
967 // Setup DMA channel routing
968 DMAMUX0_CHCFG0 = DMAMUX_ENABLE | DMAMUX_SOURCE_UART0_RX;
969 DMAMUX0_CHCFG1 = DMAMUX_ENABLE | DMAMUX_SOURCE_UART1_RX;
971 // Enable DMA requests (requires Rx interrupts)
972 UART0_C5 = UART_C5_RDMAS;
973 UART1_C5 = UART_C5_RDMAS;
975 // TX Enabled, RX Enabled, RX Interrupt Enabled
976 UART0_C2 = UART_C2_TE | UART_C2_RE | UART_C2_RIE;
977 UART1_C2 = UART_C2_TE | UART_C2_RE | UART_C2_RIE;
979 // Add interrupts to the vector table
980 NVIC_ENABLE_IRQ( IRQ_UART0_STATUS );
981 NVIC_ENABLE_IRQ( IRQ_UART1_STATUS );
983 // UARTs are now ready to go
984 uarts_configured = 1;
986 // Reset the state of the UART variables
991 #define DMA_BUF_POS( x, pos ) \
993 pos = DMA_TCD##x##_CITER_ELINKNO; \
995 void Connect_rx_process( uint8_t uartNum )
997 // Determine current position to read until
1001 DMA_BUF_POS( 0, bufpos );
1002 DMA_BUF_POS( 1, bufpos );
1005 // Process each of the new bytes
1006 // Even if we receive more bytes during processing, wait until the next check so we don't starve other tasks
1007 while ( bufpos != uart_rx_buf[ uartNum ].last_read )
1009 // If the last_read byte is at the buffer edge, roll back to beginning
1010 if ( uart_rx_buf[ uartNum ].last_read == 0 )
1012 uart_rx_buf[ uartNum ].last_read = UART_Buffer_Size;
1014 // Check to see if we're at the boundary
1015 if ( bufpos == UART_Buffer_Size )
1019 // Read the byte out of Rx DMA buffer
1020 uint8_t byte = uart_rx_buf[ uartNum ].buffer[ UART_Buffer_Size - uart_rx_buf[ uartNum ].last_read-- ];
1022 if ( Connect_debug )
1028 // Process UART byte
1029 switch ( uart_rx_status[ uartNum ].status )
1031 // Every packet must start with a SYN / 0x16
1032 case UARTStatus_Wait:
1033 if ( Connect_debug )
1037 uart_rx_status[ uartNum ].status = byte == 0x16 ? UARTStatus_SYN : UARTStatus_Wait;
1040 // After a SYN, there must be a SOH / 0x01
1041 case UARTStatus_SYN:
1042 if ( Connect_debug )
1046 uart_rx_status[ uartNum ].status = byte == 0x01 ? UARTStatus_SOH : UARTStatus_Wait;
1049 // After a SOH the packet structure may diverge a bit
1050 // This is the packet type field (refer to the Command enum)
1051 // For very small packets (e.g. IdRequest) this is all that's required to take action
1052 case UARTStatus_SOH:
1054 if ( Connect_debug )
1059 // Check if this is actually a reserved CMD 0x16 (Error condition)
1060 if ( byte == Command_SYN )
1062 uart_rx_status[ uartNum ].status = UARTStatus_SYN;
1066 // Otherwise process the command
1067 if ( byte < Command_TOP )
1069 uart_rx_status[ uartNum ].status = UARTStatus_Command;
1070 uart_rx_status[ uartNum ].command = byte;
1071 uart_rx_status[ uartNum ].bytes_waiting = 0xFFFF;
1073 // Invalid packet type, ignore
1076 uart_rx_status[ uartNum ].status = UARTStatus_Wait;
1079 // Check if this is a very short packet
1080 switch ( uart_rx_status[ uartNum ].command )
1083 Connect_receive_IdRequest( 0, (uint16_t*)&uart_rx_status[ uartNum ].bytes_waiting, uartNum );
1084 uart_rx_status[ uartNum ].status = UARTStatus_Wait;
1088 if ( Connect_debug )
1091 printHex( uart_rx_status[ uartNum ].command );
1098 // After the packet type has been deciphered do Command specific processing
1099 // Until the Command has received all the bytes it requires the UART buffer stays in this state
1100 case UARTStatus_Command:
1102 if ( Connect_debug )
1106 /* Call specific UARTConnect command receive function */
1107 uint8_t (*rcvFunc)(uint8_t, uint16_t(*), uint8_t) = (uint8_t(*)(uint8_t, uint16_t(*), uint8_t))(Connect_receiveFunctions[ uart_rx_status[ uartNum ].command ]);
1108 if ( rcvFunc( byte, (uint16_t*)&uart_rx_status[ uartNum ].bytes_waiting, uartNum ) )
1109 uart_rx_status[ uartNum ].status = UARTStatus_Wait;
1113 // Unknown status, should never get here
1115 erro_msg("Invalid UARTStatus...");
1116 uart_rx_status[ uartNum ].status = UARTStatus_Wait;
1120 if ( Connect_debug )
1128 // Scan for updates in the master/slave
1129 // - Interrupts will deal with most input functions
1130 // - Used to send queries
1131 // - SyncEvent is sent immediately once the current command is sent
1132 // - SyncEvent is also blocking until sent
1135 // Check if initially configured as a slave and usb comes up
1136 // Then reconfigure as a master
1137 if ( !Connect_master && Output_Available && !Connect_override )
1139 Connect_setup( Output_Available );
1142 // Limit how often we do cable checks
1143 uint32_t time_compare = 0x7FF; // Must be all 1's, 0x3FF is valid, 0x4FF is not
1144 uint32_t current_time = systick_millis_count;
1145 if ( Connect_lastCheck != current_time
1146 && ( current_time & time_compare ) == time_compare
1149 // Make sure we don't double check if the clock speed is too high
1150 Connect_lastCheck = current_time;
1152 // Send a cable check command of 2 bytes
1153 Connect_send_CableCheck( UARTConnectCableCheckLength_define );
1155 // If this is a slave, and we don't have an id yeth
1156 // Don't bother sending if there are cable issues
1157 if ( !Connect_master && Connect_id == 0xFF && Connect_cableOkMaster )
1159 Connect_send_IdRequest();
1163 // Only process commands if uarts have been configured
1164 if ( uarts_configured )
1166 // Check if Tx Buffers are empty and the Tx Ring buffers have data to send
1167 // This happens if there was previously nothing to send
1168 if ( uart_tx_buf[ 0 ].items > 0 && UART0_TCFIFO == 0 )
1169 uart_fillTxFifo( 0 );
1170 if ( uart_tx_buf[ 1 ].items > 0 && UART1_TCFIFO == 0 )
1171 uart_fillTxFifo( 1 );
1173 // Process Rx Buffers
1174 Connect_rx_process( 0 );
1175 Connect_rx_process( 1 );
1181 // ----- CLI Command Functions -----
1183 void cliFunc_connectCmd( char* args )
1185 // Parse number from argument
1186 // NOTE: Only first argument is used
1189 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1193 switch ( numToInt( &arg1Ptr[0] ) )
1196 Connect_send_CableCheck( UARTConnectCableCheckLength_define );
1200 Connect_send_IdRequest();
1204 Connect_send_IdEnumeration( 5 );
1208 Connect_send_IdReport( 8 );
1213 TriggerGuide scanCodes[] = { { 0x00, 0x01, 0x05 }, { 0x00, 0x03, 0x16 } };
1214 Connect_send_ScanCode( 10, scanCodes, 2 );
1220 case RemoteCapability:
1237 void cliFunc_connectDbg( char* args )
1240 info_msg("Connect Debug Mode Toggle");
1241 Connect_debug = !Connect_debug;
1244 void cliFunc_connectIdl( char* args )
1246 // Parse number from argument
1247 // NOTE: Only first argument is used
1250 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1253 info_msg("Sending Sync Idles...");
1255 uint8_t count = numToInt( &arg1Ptr[0] );
1256 // Default to 2 idles
1260 Connect_send_Idle( count );
1263 void cliFunc_connectLst( char* args )
1265 const char *Command_strs[] = {
1278 info_msg("List of UARTConnect commands");
1279 for ( uint8_t cmd = 0; cmd < Command_TOP; cmd++ )
1284 dPrint( (char*)Command_strs[ cmd ] );
1288 void cliFunc_connectMst( char* args )
1290 // Parse number from argument
1291 // NOTE: Only first argument is used
1294 CLI_argumentIsolation( args, &arg1Ptr, &arg2Ptr );
1299 Connect_override = 1;
1301 switch ( arg1Ptr[0] )
1306 Connect_override = 0;
1309 info_msg("Setting device as slave.");
1317 info_msg("Setting device as master.");
1324 void cliFunc_connectRst( char* args )
1327 info_msg("Resetting UARTConnect state...");
1334 void cliFunc_connectSts( char* args )
1337 info_msg("UARTConnect Status");
1338 print( NL "Device Type:\t" );
1339 print( Connect_master ? "Master" : "Slave" );
1340 print( NL "Device Id:\t" );
1341 printHex( Connect_id );
1342 print( NL "Max Id:\t" );
1343 printHex( Connect_maxId );
1344 print( NL "Master <=" NL "\tStatus:\t");
1345 printHex( Connect_cableOkMaster );
1346 print( NL "\tFaults:\t");
1347 printHex32( Connect_cableFaultsMaster );
1349 printHex32( Connect_cableChecksMaster );
1350 print( NL "\tRx:\t");
1351 printHex( uart_rx_status[UART_Master].status );
1352 print( NL "\tTx:\t");
1353 printHex( uart_tx_status[UART_Master].status );
1354 print( NL "Slave <=" NL "\tStatus:\t");
1355 printHex( Connect_cableOkSlave );
1356 print( NL "\tFaults:\t");
1357 printHex32( Connect_cableFaultsSlave );
1359 printHex32( Connect_cableChecksSlave );
1360 print( NL "\tRx:\t");
1361 printHex( uart_rx_status[UART_Slave].status );
1362 print( NL "\tTx:\t");
1363 printHex( uart_tx_status[UART_Slave].status );