/****************************************************************************
remote14.c (KEYPAD VERSION)

USE AT YOUR OWN RISK!

This program is a remote control for Raytheon's Autohelm ST4000 autopilot using the
Seatalk(tm) network protocol.  It also switches the Raytheon instrument lamps on
and off.

The following Seatalk protocol is extracted from Thomas Knauf's web site:
www.thomasknauf.de/seatalk.htm

Message protocol
* Each message contains between 3 and 18 characters:
* COMMAND byte (the only byte with the command-bit set)
  ATTRIBUTE byte, specifying the total length of the message in the least significant nibble:
      Most  significant 4 bits: 0 or part of a data value
      Least significant 4 bits: Number of additional bytes beyond the mandatory data byte
  DATA byte (mandatory, meaning than the smallest message is 3 bytes)
  DATA bytes (optional, up to 15 additional data bytes, meaning that longest messages is 18 bytes)

Serial Data Transmission
11 bits are transmitted for each byte:
  * 1  Start bit (0V)
  * 8  Data Bits (least significant bit transmitted first, bit ON = +12V)
  * 1  Command/Data bit (+12V if command byte, 0V if other)
  * 1  Stop bit (+12V)

Collision Management
Bus should be idle for at least 2mS (+12V for at least 10/4800 seconds).
Listens to it's own transmission and recognizes when its message has
been corrupted by a second talker. In this case it abandons the remaining
bytes in the message, waits for the bus to become free again, and then
retransmits the whole message.

LAMP INTENSITY CODES
------------------------------
30 00 00          Lamp off
30 00 0C          Lamp full on

KEYSTROKE CODES
------------------------------
86 11 01 FE     AUTO
86 11 02 FD     STANDBY
86 11 03 FC     TRACK
86 11 05 FA     -1
86 11 06 F9    -10
86 11 07 F8      +1
86 11 08 F7    +10
86 11 09 F6    Set Response Level 1
86 11 0A F5    Set Response Level 2

                 +5   +5
                  |    |
                  14   4
                ----------
      R1 ----6-| B0    A0 |-17-- out to Seatalk (transistor driver)
      R2 ----7-| B1    A1 |-18-- in from Seatalk (transistor buffer)
      R3 ----8-| B2    A2 |-1--- out to piezo beeper
      R4 ----9-| B3       |
      C1 ---10-| B4       |
      C2 ---11-| B5       |
      C3 ---12-| B6       |
               |          |
  4MHz XTAL-15-|  16F84   |
       XTAL-16-|          |
                ----------
                     5
                     |
                    Gnd


          KEYBOARD ASSIGNMENTS
            C1      C2      C3
        +------------------------+
    R1  |  -1      Track   +1    |
        |                        |
    R2  |  -10     Auto    +10   |
        |                        |
    R3  |  TackP  Standby  TackS |
        |                        |
    R4  |  Lamp      x     Resp  |
        +------------------------+


***************************************************************************/

/* The following include should contain 16F84 or 16F628. */
#include < 16F84.h >

#if __device__==84
#fuses XT, NOPROTECT, PUT, NOWDT
#endif
/* The following has to be 627 for either the 627 or 628. */
#if __device__==627
#fuses XT, NOPROTECT, PUT, NOWDT, BROWNOUT, NOMCLR, NOLVP
#endif
#include < jonsinc.h >

#use fast_io ( A )
#use fast_io ( B )
#use delay ( clock = 4000000 )

#byte PORT_A  = 5
#byte PORT_B  = 6
#bit TX_OUT   = PORT_A.0
#bit RX_IN    = PORT_A.1
#bit BEEP_OUT = PORT_A.2

#define SW_PLUS_ONE    PIN_B0
#define SW_MINUS_ONE   PIN_B1
#define SW_PLUS_TEN    PIN_B2
#define SW_MINUS_TEN   PIN_B3
#define SW_TRACK       PIN_B4
#define SW_AUTO        PIN_B5
#define SW_STANDBY     PIN_B6
#define SW_LAMP_RESP   PIN_B7
#define RESP_AUTO      0x09
#define RESP_TIGHT     0x0A
#define TACK_PORT      0x21
#define TACK_STBD      0x22
#define LAMP_OFF       0x00
#define LAMP_ON        0x0C
#define PLUS_ONE       0x07
#define MINUS_ONE      0x05
#define PLUS_TEN       0x08
#define MINUS_TEN      0x06
#define STANDBY        0x02
#define AUTOM          0x01
#define TRACK          0x03
#define KEY_NONE       0
#define KEY_C1_R1      1
#define KEY_C1_R2      2
#define KEY_C1_R3      3
#define KEY_C1_R4      4
#define KEY_C2_R1      5
#define KEY_C2_R2      6
#define KEY_C2_R3      7
#define KEY_C2_R4      8
#define KEY_C3_R1      9
#define KEY_C3_R2      10
#define KEY_C3_R3      11
#define KEY_C3_R4      12

void SendKeystrokeMsg ( char cData );
void SendLampMsg ( char cX );
char SendByte ( char cError, char cCommand, char cData );
char SendBit ( cBit );
void CheckBus ( void );
void Beep ( char cCnt );
char GetKey ( void );

static char cLampState;
static char cResponseState;

void main ( void )
        {
        char cX, cKey;

        TX_OUT = LOW;                       // allow output to float
        BEEP_OUT = LOW;
        set_tris_a ( 0b11111010 );          // A0, A2 are outputs, A1 is input
        set_tris_b ( 0b10001111 );          // Columns are outputs, rows are inputs
        setup_counters ( RTCC_INTERNAL, WDT_18MS );   // 256 * 4uS = 1.024mS timer wrap
        port_b_pullups ( TRUE );
        cLampState = LAMP_OFF;
        cResponseState = RESP_AUTO;

        for ( cX = 0; cX < 10; cX++ )
            {
            Beep ( 1 );
            }

        while ( TRUE )      // do forever
            {
            cKey = GetKey();
            if ( cKey != KEY_NONE )
                {
                switch ( cKey )
                    {
                    case KEY_C1_R1:
                        {
                        SendKeystrokeMsg ( MINUS_ONE );
                        break;
                        }
                    case KEY_C1_R2:
                        {
                        SendKeystrokeMsg ( MINUS_TEN );
                        break;
                        }
                    case KEY_C1_R3:
                        {
                        SendKeystrokeMsg ( TACK_PORT );
                        break;
                        }
                    case KEY_C1_R4:
                        {
                        if ( cLampState == LAMP_OFF )
                            {
                            cLampState = LAMP_ON;
                            }
                        else
                            {
                            cLampState = LAMP_OFF;
                            }
                        SendLampMsg ( cLampState );      // send DISP keystroke
                        break;
                        }
                    case KEY_C2_R1:
                        {
                        SendKeystrokeMsg ( TRACK );
                        break;
                        }
                    case KEY_C2_R2:
                        {
                        SendKeystrokeMsg ( AUTOM );
                        break;
                        }
                    case KEY_C2_R3:
                        {
                        SendKeystrokeMsg ( STANDBY );
                        break;
                        }
                    case KEY_C2_R4:
                        {
                        break;
                        }
                    case KEY_C3_R1:
                        {
                        SendKeystrokeMsg ( PLUS_ONE );
                        break;
                        }
                    case KEY_C3_R2:
                        {
                        SendKeystrokeMsg ( PLUS_TEN );
                        break;
                        }
                    case KEY_C3_R3:
                        {
                        SendKeystrokeMsg ( TACK_STBD );
                        break;
                        }
                    case KEY_C3_R4:
                        {
                        if ( cResponseState == RESP_AUTO )
                            {
                            cResponseState = RESP_TIGHT;
                            }
                        else
                            {
                            cResponseState = RESP_AUTO;
                            }
                        SendKeystrokeMsg ( cResponseState );
                        break;
                        }
                    }
                delay_ms ( 25 );
                }
            }
        }

void SendKeystrokeMsg ( char cData )
    {
    char cError;

    do {
        CheckBus();                                //wait for bus to be idle
        cError = SendByte ( NO, YES, 0x86 );       // command: keystroke
        cError = SendByte ( cError, NO, 0x11 );    // data: remote control, 1 extra byte (4 total)
        cError = SendByte ( cError, NO, cData );   // data: PlusOne key
        cError = SendByte ( cError, NO,~cData );   // data: inverted data
        } while ( cError == YES );                 // repeat if message was corrupted
    }

void SendLampMsg ( char cX )
    {
    char cError;
    do {
        CheckBus();                                //wait for bus to be idle
        cError = SendByte ( NO, YES, 0x30 );       // command: lamp
        cError = SendByte ( cError, NO, 0x00 );    // data: 00
        cError = SendByte ( cError, NO, cLampState );   // data: lamp state
        } while ( cError == YES );                 // repeat if message was corrupted
    }

char SendByte ( char cError, char cCommand, char cData )
    {
    char cX;

    if ( cError != YES )
        {
        cError = SendBit ( HIGH );           // start bit (0V)
        for ( cX = 0; cX < 8; cX++ )
            {
            cError = SendBit ( ~cData & 0x01 );  // LSB data bit
            cData >>= 1;                 // shift right
            }
        cError = SendBit ( cCommand ? LOW : HIGH );    // set if command byte, clear if data byte
        cError = SendBit ( LOW );           // stop bit (+12V)
        }
    return ( cError );
    }

char SendBit ( cBit )
    {
    char cX, cY;
    // this code adjusted to give 208uS bit times (4800 baud)
    TX_OUT = cBit;                  // send bit to output
    for ( cX = 0; cX < 5; cX++ )
        {
        delay_us ( 15 );
        if ( RX_IN == !cBit )       // check if output bit is corrupted by another talker
            {
            return ( HIGH );        // return collision error
            }
        }
    return ( LOW );                 // return no error
    }

void CheckBus ( void )
    {
    char cX;

    for ( cX = 0; cX < 255; cX++ )  // assumes output is floating to +12V for ~5mS
        {
        if ( RX_IN == HIGH )        // check if output bit is corrupted by another talker
            {
            cX = 0;                 // reset count to zero
            }
        delay_us ( 7 );
        }
    }

void Beep ( char cCnt )
    {
    char cX, cY;

    for ( cY = 0; cY < cCnt; cY++ )
        {
        for ( cX = 0; cX < 30; cX++ )
            {
            BEEP_OUT = HIGH;
            delay_us ( 1000 );
            BEEP_OUT = LOW;
            delay_us ( 1000 );
            }
        delay_ms ( 30 );
        }
    }

char GetKey ( void )
    {
    char cKey;

    cKey = KEY_NONE;                            // default is invalidated key
    PORT_B = 0b10001111;                        // make all three columns low
    delay_ms ( 5 );                             // wait for row lines to settle
    if ( ( PORT_B & 0x0F ) != 0x0F )            // if any row line is low
        {
        Beep ( 1 );
        delay_ms ( 5 );                         // debounce
        PORT_B = 0b11101111;                    // make C1 low
        if ( ( PORT_B & 0x0F ) == 0b00001110 )  // check rows
            {
            cKey = KEY_C1_R1;
            }
        if ( ( PORT_B & 0x0F ) == 0b00001101 )
            {
            cKey = KEY_C1_R2;
            }
        if ( ( PORT_B & 0x0F ) == 0b00001011 )
            {
            cKey = KEY_C1_R3;
            }
        if ( ( PORT_B & 0x0F ) == 0b00000111 )
            {
            cKey = KEY_C1_R4;
            }
        PORT_B = 0b11011111;                    /* make C2 low */
        if ( ( PORT_B & 0x0F ) == 0b00001110 )  /* check rows */
            {
            cKey = KEY_C2_R1;
            }
        if ( ( PORT_B & 0x0F ) == 0b00001101 )
            {
            cKey = KEY_C2_R2;
            }
        if ( ( PORT_B & 0x0F ) == 0b00001011 )
            {
            cKey = KEY_C2_R3;
            }
        if ( ( PORT_B & 0x0F ) == 0b00000111 )
            {
            cKey = KEY_C2_R4;
            }
        PORT_B = 0b10111111;                    /* make C3 low */
        if ( ( PORT_B & 0x0F ) == 0b00001110 )  /* check rows */
            {
            cKey = KEY_C3_R1;
            }
        if ( ( PORT_B & 0x0F ) == 0b00001101 )
            {
            cKey = KEY_C3_R2;
            }
        if ( ( PORT_B & 0x0F ) == 0b00001011 )
            {
            cKey = KEY_C3_R3;
            }
        if ( ( PORT_B & 0x0F ) == 0b00000111 )
            {
            cKey = KEY_C3_R4;
            }
        delay_ms ( 5 );
        PORT_B = 0b10001111;                   // make all three columns low
        while ( ( PORT_B & 0x0F ) != 0x0F )    // wait until all rows are high (no keys pressed )
            {
            delay_ms ( 5 );
            }
        }
    PORT_B = 0b11111111;                   // make all three columns high
    return ( cKey );
    }