' {$STAMP BS2}
' {$PBASIC 2.5}

'THIS IS THE MAIN TRIAL OF THE PROGRAM

' -----[ I/O Definitions ]-------------------------------------------------

  'RFID PINS
Enable          PIN     0                       ' low = reader on
RXrf              PIN     1                       ' serial from reader
Spkr            PIN     2                       ' speaker output
Latch           PIN     3                       ' lock/latch control

  'DATA LOGGER PINS
TX              PIN     8               ' Transmit Data   --> 27937.4 (RXD)
RTS             PIN     9               ' Request To Send --> 27937.6 (CTS)
RX              PIN     10              ' Receive Data    <-- 27937.5 (TXD)
CTS             PIN     11              ' Clear To Send   <-- 27937.2 (RTS)

' -----[ Constants ]-------------------------------------------------------

  'RFID RELATED
#SELECT $STAMP
  #CASE BS2, BS2E, BS2PE
    T1200       CON     813
    T2400       CON     396
    T4800       CON     188
    T9600       CON     84
    T19K2       CON     32
    TMidi       CON     12
    T38K4       CON     6
#ENDSELECT

SevenBit        CON     $2000
Inverted        CON     $4000
Open            CON     $8000
Baud            CON     T2400

#SELECT $STAMP
  #CASE BS2, BS2E
    TmAdj       CON     $100                    ' x 1.0 (time adjust)
    FrAdj       CON     $100                    ' x 1.0 (freq adjust)
#ENDSELECT

LastTag         CON     3
#DEFINE __No_SPRAM = ($STAMP < BS2P)            ' does module have SPRAM?

  'DATA LOGGER
BaudDL            CON     84              ' Serial Baud Rate 9600 bps (BS2)
enter       CON     0

' -----[ Variables ]-------------------------------------------------------
  'RFID RELATED
#IF __No_SPRAM #THEN
  buf           VAR     Byte(10)                ' RFID bytes buffer
#ELSE
  chkChar       VAR     Byte                    ' character to test
#ENDIF

tagNum          VAR     Nib                     ' from EEPROM table
idx             VAR     Byte                    ' tag byte index
char            VAR     Byte                    ' character from table

  'DATA LOGGER
timeout         VAR     Bit             ' Timeout Inidicator
'this is where the buffer was
index           VAR     Byte            ' Index Variable
ioByte          VAR     Byte            ' Input/Output Storage

' -----[ EEPROM Data ]-----------------------------------------------------

Tag1            DATA    "25005FED2D"            ' valid tags
Tag2            DATA    "210083A266"                                     'here is where you register the user information

Name0           DATA    "Unauthorized", CR, 0
Name1           DATA    "Tag 1 (White Card)Ivan", CR, 0
Name2           DATA    "Tag 2 (Small Round)Sugu", CR, 0
Name3           DATA    "Unauthorized", CR, 0

' -----[ Initialization RFID READER ]--------------------------------------------------

Reset:
  HIGH Enable                                   ' turn of RFID reader
  LOW Latch                                     ' lock the door!
  DEBUG CR, "Turn the RFID reader", CR

' -----[ Initialization DATA LOGGER ]--------------------------------------------------

DEBUG CLS, "our own test", CR, CR
PAUSE 2000                              ' Allow Time To Settle

HIGH TX                                 ' Initialize Transmit Line
LOW RTS                                 ' Take Vinculum Out Of Reset

PAUSE 2000                              ' Allow Time To Settle

GOSUB Purge                             ' Purge Buffer
DEBUG "Synchronizing...", CR
index = 0

' For Synchronization send E until echoed back
DO WHILE (index < 1)
  PAUSE 500
  SEROUT  TX\CTS, BaudDL, ["E", CR]       ' Transmit "E CR"
  GOSUB Get_Serial_Bytes                ' Get Returned Data
LOOP
GOSUB Purge                             ' Purge Buffer

' Send e to complete synchronization
PAUSE 500
SEROUT  TX\CTS, BaudDL, ["e", CR]         ' Transmit "e CR"
GOSUB Get_Serial_Bytes

' Send CR to see if drive is present
PAUSE 500
GOSUB Purge                             ' Purge Buffer
DEBUG "Checking for USB Flash drive...", CR
SEROUT TX\CTS, BaudDL, [CR]               ' Send Carriage Return
GOSUB Get_Serial_Bytes                  ' Wait for D:\>

IF (buf(0) = "N") THEN
  DEBUG "No drive present!"
  STOP
ELSE
  DEBUG "Drive D: Ready...", CR
ENDIF
GOSUB Purge                             ' Purge Buffer

' -----[ Program Code ]----------------------------------------------------

Main:
  LOW Enable                                    ' activate the reader
  #IF __No_SPRAM #THEN
    SERIN RXrf, T2400, [WAIT($0A), STR buf\10]    ' wait for hdr + ID
  #ELSE
    SERIN RXrf, T2400, [WAIT($0A), SPSTR 10]
  #ENDIF
  HIGH Enable                                   ' deactivate reader

Check_List:
  FOR tagNum = 1 TO LastTag                     ' scan through known tags
    FOR idx = 0 TO 9                            ' scan bytes in tag
      READ (tagNum - 1 * 10 + idx), char        ' get tag data from table
      #IF __No_SPRAM #THEN
        IF (char <> buf(idx)) THEN Bad_Char     ' compare tag to table
      #ELSE
        GET idx, chkChar                        ' read char from SPRAM
        IF (char <> chkChar) THEN Bad_Char      ' compare to table
      #ENDIF
    NEXT
    GOTO Tag_Found                              ' all bytes match!

Bad_Char:                                       ' try next tag
  NEXT

Bad_Tag:
  tagNum = 0
  GOSUB Show_Name                               ' print message
  FREQOUT Spkr, 1000 */ TmAdj, 115 */ FrAdj     ' groan
  PAUSE 1000
  GOTO Main

Tag_Found:
  GOSUB Show_Name                               ' print name
  HIGH Latch                                    ' remove latch
  FREQOUT Spkr, 2000 */ TmAdj, 880 */ FrAdj     ' beep
  LOW Latch                                     ' restore latch
  GOTO Main

  END

' -----[ Subroutines ]-----------------------------------------------------

' Prints name associated with RFID tag

Show_Name:
  DEBUG DEC tagNum, ": "
  LOOKUP tagNum,
         [Name0, Name1, Name2, Name3], idx      ' point to first character
  ' Open SEEDFILE.TXT for output (write)
  PAUSE 1
  SEROUT TX\CTS, BaudDL, ["OPW newfile.txt", CR]
  GOSUB Get_Serial_Bytes
  DEBUG CR, "opening File"

  PAUSE 1
  SEROUT TX\CTS, BaudDL, ["WRF ", $00, $00, $00, $05, $00, $00, $00, $05, CR, DEC enter, LF,CR]
  GOSUB Get_Serial_Bytes

  DO
    READ idx, char                              ' read character from name
    IF (char = 0) THEN EXIT                     ' if 0, we're done
    DEBUG char                                  ' otherwise print it

      ' Write random seed value to SEEDFILE.TXT
    PAUSE 1
    SEROUT TX\CTS, BaudDL, ["WRF ", $00, $00, $00, $05, $00, $00, $00, $05, CR,CR, STR char, CR,CR]
SEROUT TX\CTS, BaudDL, ["WRF ", $00, $00, $00, $01, $0D, char, CR]
    GOSUB Get_Serial_Bytes
    idx = idx + 1                               ' point to next character
  LOOP

SEROUT TX\CTS, BaudDL, ["WRF ", $00, $00, $00, $01, $0D, CR, CR]
    GOSUB Get_Serial_Bytes

    DEBUG CR, "writing succesfull "

  ' Close SEEDFILE.TXT
  PAUSE 1
  SEROUT TX\CTS, BaudDL, ["CLF newfile.txt", CR]
  GOSUB Get_Serial_Bytes
  GOSUB Purge                           ' Purge Buffer
  DEBUG CR, "file closed"

    RETURN

' -----[ Subroutines DATA LOGGER]-----------------------------------------------------

Get_Serial_Bytes:
  timeout = 1                           ' Set Timeout Indicator Flag
  index = 0                             ' Initialize Index
  DO WHILE (timeout > 0)                ' While Timeout Has Not Occurred
    ioByte = 0                          ' Clear Temporary Storage
    SERIN RX\RTS, BaudDL, 100, No_Data, [ioByte]
    buf(index) = ioByte              ' Save Byte Received To Array
    index = index + 1                   ' Increment Index
    IF (index > 9) THEN                ' Check For Overflow                      'changed from 14 to 9
      index = 9                        ' Prevent Overflow                        'similar change
    ENDIF
  LOOP
RETURN

Purge:
  timeout = 1                           ' Set Timeout Indicator Flag
  DO WHILE (timeout > 0)                ' While Timeout Has Not Occurred
    PAUSE 50
    SERIN RX\RTS, BaudDL, 500, No_Data, [ioByte]
  LOOP
  RETURN

No_Data:
  timeout = 0                           ' Timeout, Clear Flag
RETURN

No_Data2:
  DEBUG CR, "Error reading the seed file -- Halting execution!", CR
  PAUSE 1000
  GOSUB Purge                           ' Purge Buffer
  STOP
RETURN