-- Title: tstRF12com.jal  to be included by tstRF12main.jal
-- Author H.v.Broekhuyzen (henk@henkzelf.nl)
-- Compiler: >=2.4m
--
-- This file is part of jallib  (http://jallib.googlecode.com)
-- Released under the BSD license (http://www.opensource.org/licenses/bsd-license.php)
--
-- Description: This files forms, together with tstRF12main.jal, tstRFsub.jal
--              and T0comInIsr.jal the test- and experiment- framework for
--              the files: spi_rf12b.jal and spi_sw_master.jal
--
-- Function: command interpreter included by tstRF12main.jal
--

--*********************************************************************

case CommandIn of
"b" : block ; bandwith in Receiver Control Command  (init sets 4)
            ; 1= 400, 2=340, 3=270,4=200, 5=134, 6=67 kHz
        SPI_RF12B_set_Bandwidth(ComValIn)
        ReportCommandRecognised()
      end block
"c" : block ;  RF12B clock output in state <ComValIn & 0x0007
        ReportCommandRecognised()
        ComValIn = ComValIn & 0x0007
        ComValIn = ComValIn << 5
        ComValIn = ComValIn | 0xC000
        while ComFlag == 0 loop  ; While loop to observe SPI-signals on scoop
          SPI_RF12B_writeCommand(ComValIn)
        end loop
      end block
"d" : block ;   ;  dataRate Command
        SPI_RF12B_set_Datarate(ComValIn)
        ReportCommandRecognised()
      end block
"e" : block ;  Master echo-test (until next (non-parameter) command).
            ; Send a packet and receive a packet. Command E on other node
            ; It should have raised al bytes in the packet by 1
            ; Flash LED2 in case of error or trouble, and LED3 if OK
        var sbyte result = -1 ; of function SPI_RF12B_receive_packet()
        var byte ValFirstByte = 0x30
        var byte i
        var word NrOfTests = 0
        var word NROfErrors = 0
        var word t1_transmit
        var word t2_response
        var word t3_turnaround
        const word t_set = 0x7FFF
        
        ReportCommandRecognised()
        delay_1ms(1000) ; allow other PIC a headstart if powered-up at the
                       ; same time (auto-start of command e and E in other PIC)
        while ComFlag == 0 loop
          print_crlf(Serial_HW_data)
          ------------------ Prepare packet -----------------------------------
          if  ValFirstByte > 90 then
              ValFirstByte = 0x30  ;limit inprintable range
          end if
          i = 0
          while i < MaxPayloadSize loop
             RF12BpacketToTransmit[i] = i + ValFirstByte
             i = i +1
          end loop
          ------------- Transmit packet and measure that time------------------
          TMR_nr1 = t_set; Interrupt routine counts this down with 5 kHx
          TMR_nr2 = t_set; Interrupt routine counts this down with 5 kHx
          SPI_RF12B_transmit_packet(LengthToSend)
          t1_transmit = t_set - TMR_nr1
           -- receive packet (or timeout) -------------------------------------
          LED2 = 0
          LED3 = 0
          TMR_nr1 = TimeOutTicks; Interrupt routine countss this down with 5 kHx
          result = -1
          while (result == -1) & (ComFlag == 0) & (TMR_nr1 > 0)loop
            LED4 = 1
            result = SPI_RF12B_receive_packet(1000)
                              ; 1000 = 110ms using SPI_sw_master(), Xtal=20MHz
            LED4 = 0
          end loop ; will run max 50 ms because of TMR_nr1
          if TMR_nr1 == 0 then
            SPI_RF12B_toOff()
            result = -4
          end if
          t2_response   = TimeOutTicks - TMR_nr1
          t3_turnAround = t_set - TMR_nr2
          ------ The echo is now received ---------------------
            ------- check received packet or signal ----------------------
            --     (if there is payload, all byte should be all raised by one)
          if Echotest_Normal == 0 & result == 0 then  ; if E echoed only ACK
            LED3 = 1   ; OK
            ValFirstByte = ValFirstByte + 1
          elsif result != LengthToSend then
            LED2 = 1
            NROfErrors = NROfErrors + 1
          elsif LengthToSend <= 0  then  ;we did sent a signal
            LED3 = 1   ; OK
          else   ; if payload was sent (no signal) and Ecotest_Normal == 1
            ValFirstByte = ValFirstByte + 1
            i = 0
            while i < LengthToSend loop
             if RF12BpacketReceived[i] != (i + ValFirstByte) then
                i = LengthToSend  ; stop while loop because of error
              end if
              i = i + 1
            end loop
            if i > LengthToSend  then  ;if last loop stopped because an error
              LED2 = 1
              NROfErrors = NROfErrors + 1
            else
              LED3 = 1  ; OK
            end if
          end if
          if (PrintInEchotestMasK & 0xF0) != 0 then ; if anything to print
            print_crlf(Serial_HW_data)
            serial_hw_write("e")
            serial_hw_write(":")
            serial_hw_write(" ")
          end if
          if (PrintInEchotestMask & 0x10) != 0 then
            format_sbyte_dec(Serial_HW_data, result, 4, 0)
            serial_hw_write(" ")
          end if
          if (PrintInEchotestMask & 0x20) != 0 then
            serial_hw_write("t")
            serial_hw_write("1")
            serial_hw_write("=")
            format_word_dec(Serial_HW_data, t1_transmit <<1 , 4, 1)
            serial_hw_write(" ")
            serial_hw_write("m")
            serial_hw_write("s")
            serial_hw_write(" ")
          end if
          if (PrintInEchotestMask & 0x40) != 0  then
            serial_hw_write("t")
            serial_hw_write("2")
            serial_hw_write("=")
            format_word_dec(Serial_HW_data, t2_response <<1 , 6, 1)
            serial_hw_write(" ")
            serial_hw_write("m")
            serial_hw_write("s")
            serial_hw_write(" ")
          end if
          if (PrintInEchotestMask & 0x40) != 0  then
            serial_hw_write("t")
            serial_hw_write("3")
            serial_hw_write("=")
            format_word_dec(Serial_HW_data, t3_turnAround <<1 , 6, 1)
            serial_hw_write(" ")
            serial_hw_write("m")
            serial_hw_write("s")
            serial_hw_write(" ")
          end if
          ---- One test is complete, now wait
          if Loop_delay > 0 then
            delay_1ms(Loop_delay)
          end if
          ValFirstByte = ValFirstByte + 1 ;message to send will get new content
          ; ValFirstByte = 0x30 ;message to send will Not get new content
          NrOfTests = NrOfTests + 1
          -- check if a command has arrived that should not stop the loop
          CheckForParameterCommand()
        end loop
        LED2 = 0
        LED3 = 0
        print_crlf(Serial_HW_data)
        format_word_dec(Serial_HW_data, NrOfErrors ,6, 0)
        const byte strErrors[] = " Errors in "
        print_string(Serial_HW_data, strErrors)
        format_word_dec(Serial_HW_data, NrOfTests ,6, 0)
      end block
"E" : block ;  Echo = Receive a packet,  raise all bytes by 1 and send it
            ;  back, print it,Repeat this until next (non-parameter) command.
        var byte index   ; in RF12BpacketReceived
        var sbyte result ; of function SPI_RF12B_receive_packet()
        ReportCommandRecognised()
        while ComFlag == 0 loop
          ------- Receive a packet, NO timeout LED4 = 1 while waiting
          result = -1
          while (result == -1) & (ComFlag == 0) loop
            LED4 = 1
            result = SPI_RF12B_receive_packet(1000)
            LED4 = 0
          end loop ;
          if Reply_delay > 0 then
            delay_1ms(Reply_delay) ; wait some time to allowe other PIC to
                             ; switch from transmit to receive (if necessary)
          end if
          if (PrintInEchotestMask & 0x03) != 0 then ; if anything to print
            print_crlf(Serial_HW_data)
            serial_hw_write("E")
            serial_hw_write(":")
          end if
          if (PrintInEchotestMask & 0x01) != 0 then
            format_sbyte_dec(Serial_HW_data, result, 5, 0)
            serial_hw_write(" ")
          end if
          if result > 0 then
            index = 0
            while index < result loop
              if (PrintInEchotestMask & 0x02) != 0 then
                serial_hw_write(RF12BpacketReceived[index])
              end if
              RF12BpacketToTransmit[index] = RF12BpacketReceived[index] + 1
              index = index + 1
            end loop
          end if
          if (result >= 0) | (result < -4) then
            LED3 = 1     ; flash OK
            if Echotest_Normal == 1 then
               SPI_RF12B_transmit_packet(result)
            else   ; if only ACK signal has to be echoed
               SPI_RF12B_transmit_packet(0)
            end if
            LED3 = 0
          else
            LED2 = 1     ; flash Error
            SPI_RF12B_transmit_packet(result + 5) ; error (2 or 3) +5 because:
                                      ; command e can also cause error 2 and 3
            LED2 = 0
          end if
          -- check if a command has arrived that should not stop the loop
          CheckForParameterCommand()
        end loop
        SPI_RF12B_toOff() ; for if new command arrived while trying to receive
        print_crlf(Serial_HW_data)
      end block
"F" : block ;  FIFO clear
        SPI_RF12B_ResetFifo()
        ReportCommandRecognised()
      end block
"f" : block ;  Frequency Setting Command
        SPI_RF12B_set_Frequency(ComValIn)
        ReportCommandRecognised()
      end block
"H" : block ;  halt (dummy command)
        ComFlag = 0
      end block
"h" : block ;  halt (dummy command)
        ReportCommandRecognised()
      end block
"i" : block ;  Initialise RF12B
        ReportCommandRecognised()
        SPI_RF12B_writeCommand(0x8080) ; Config setting default
        SPI_RF12B_Init()
      end block
"l" : block ;  Set length to send by command e
        Command_l()
        ReportCommandRecognised()
      end block
"m" : block ;  Mode: 0 = OFF ,  > 0 = transmit, < 0 = Receive
        ReportCommandRecognised()
        if ComValIn == 0 then
          SPI_RF12B_toOff()
        elsif ComValIn > 0 then
          SPI_RF12B_toTransmit()
        else
          SPI_RF12B_toReceive()
        end if
        SPI_RF12B_Init()
      end block
"p" : block ;  Set PrintInEchotestMask
        PrintInEchotestMask = ComValIn
        ReportCommandRecognised()
      end block
"r" : block ;  Report byte in FIFO
        ReportCommandRecognised()
        format_byte_hex(Serial_HW_data,SPI_RF12B_ByteFromFiFo())
      end block
"R" : block ;  Switch to receive mode and report received bytes until 0
            ; (until new (non-parameter) command). Slave for command "T"
        var word statusRF12B
        var byte inb
        var word messageNr = 0
        ReportCommandRecognised()
        while ComFlag == 0 loop
          SPI_RF12B_toReceive()
          SPI_RF12B_ResetFifo()  ; to be sure
          inb = 1 ;
          while (ComFlag == 0) & (inb != 0) loop
            statusRF12B = SPI_RF12B_readStatus()
            LED4 = 1
            if (statusRF12B & 0x8080) == 0x8080 then ;if FFIT(not RGIT) and DQD
              LED3 = 1
              inb = SPI_RF12B_ByteFromFiFo();
              if inb != 0 then
                ;serial_hw_write(inb)
                serial_hw_write(" ")
                format_byte_hex(Serial_HW_data,inb)
              else
                SPI_RF12B_toOff()
                LED4 = 0
                SPI_RF12B_ResetFifo()
                ; SPI_RF12B_print_status_history()
              end if
            end if
          end loop
          LED3 = 0
          const byte strEnd[] = " End message: "
          print_string(Serial_HW_data, strEnd)
          format_word_dec(Serial_HW_data, messageNr, 6,0)
          print_crlf(Serial_HW_data)
          messageNr = messageNr + 1
          -- check if a command has arrived that should not stop the loop
          CheckForParameterCommand()
        end loop
      end block
"s" : block ;  report Status log (last one is now)
        ReportCommandRecognised()
        SPI_RF12B_readStatus()
        SPI_RF12B_print_status_history()
      end block
"t" : block ;  timeout (in ms) for response (used in command e)
        Command_t()
        ReportCommandRecognised()
      end block
"T" : block ;  Transmit until new command  (developed before command e and E)
        var byte x
        var word statusRF12B
        ReportCommandRecognised()
        SPI_RF12B_toTransmit()
        while ComFlag == 0 loop
          LED3 = 1
          statusRF12B = SPI_RF12B_readStatus()
          SPI_RF12B_transmit(0xAA)
          SPI_RF12B_transmit(0xAA)
          SPI_RF12B_transmit(0xAA)
          SPI_RF12B_transmit(0x2D)
          SPI_RF12B_transmit(0xD4)
          SPI_RF12B_transmit(0x0D)
          SPI_RF12B_transmit(0x0A)
          x = 0
          while x < 64 loop
            SPI_RF12B_transmit("0" + x)
            x = x + 1
          end loop
          SPI_RF12B_transmit(0)
          LED3 = 0
          if  Loop_delay > 0 then
            delay_1ms(Loop_delay)
          end if
          -- check if a command has arrived that should not stop the loop
          CheckForParameterCommand()
        end loop
      end block
"W" : block ;  waittime (in ms)for command E (delay in send-back)
        Reply_delay = ComValIn
        ReportCommandRecognised()
      end block
"w" : block ;  waittime for command e and T (delay in loop)
        Loop_delay = ComValIn
        ReportCommandRecognised()
      end block
otherwise block
            serial_hw_write("?")
            ComFlag = 0
          end block
end case

