/*******************************************************************************
* PMC825 UDP/IP Socket Interface Test Program                                  *
*                                                                              *
* (C) 2010 Stock Flight Systems. All rights reserved.                          *
*                                                                              *
* Filename: pmc825echo.c                                                       *
*                                                                              *
* Redistribution and use in source and binary forms, with or without           *
* modification, are permitted provided that the following conditions are met:  *
* Redistributions of source code must retain the above copyright notice, this  *
* list of conditions and the following disclaimer.                             *
*                                                                              *
* Redistributions in binary form must reproduce the above copyright notice,    *
* this list of conditions and the following disclaimer in the documentation    *
* and/or other materials provided with the distribution.                       *
*                                                                              *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY EXPRESS    *
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES *
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN   *
* NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY DIRECT, INDIRECT,       *
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT *
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,  *
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF    *
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING         *
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, *
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                           *
*                                                                              *
* This file contains a test program which interfaces to the PMC825 via the     *
* UDP/IP socket interface.                                                     *
*                                                                              *
* Function names                                                               *
* ____________________________________________________________________________ *
*                                                                              *
* int main(void)                                                               *
* void ExceptionHandler(void)                                                  *
*                                                                              *
* MODIFICATIONS:                                                               *
*                                                                              *
* When          Version      What                                  Who         *
* ____________________________________________________________________________ *
*                                                                              *
* 29.07.2010    1.0          Initial Version                       M. Stock    *
*                                                                              *
*******************************************************************************/

/*
 * Includes.
 */

#include "pmc825socket.h"
#include "can_as.h"

/*
 * Local definitions.
 */

#define	LPORT_BASE	34567           /* Local UDP/IP port number base */
#define	RPORT_BASE      34568           /* PMC825 UDP/IP port number base */

//#define PRINT_CAN_MSGS

/*
 * Globals.
 */

PMC825_IF Pmc825;

/*
 * ExceptionHandler() frees all resources then terminates.
 */

void ExceptionHandler(void)
{
Pmc825StopInterface(&Pmc825);
printf("\nProgram terminated, all resources released.\n");
exit(0);
}

/*
 * main() starts here.
 */

int main (int argc, char *argv[])
{
#ifndef WIN32
struct timespec t2,t1 = {0,1000000*20};	/* 20ms frame time */
#endif
unsigned int *test, ts, tsl, tsh, host_ip, pmc825_ip, lport, rport;
unsigned char hip[32], pip[32], ch[8];
float tsf;
int loops, ret, i, chan, ip[4];
CAN_MSG tx_buf, rx_buf;
CTRL_MSG tx_ctrl, rx_ctrl;

/*
 * First of all, get IP addresses and CAN channel number.
 */

if (argc != 4)
  {
  printf("usage: %s host_ip pmc825_ip can_channel\n", argv[0]);
  exit(1);
  }

strcpy(hip, argv[1]);
strcpy(pip, argv[2]);
strcpy(ch, argv[3]);

sscanf(hip, "%d.%d.%d.%d", &ip[0], &ip[1], &ip[2], &ip[3]);
host_ip = (ip[0] << 24) | (ip[1] << 16) | (ip[2] << 8) | ip[3];

sscanf(pip, "%d.%d.%d.%d", &ip[0], &ip[1], &ip[2], &ip[3]);
pmc825_ip = (ip[0] << 24) | (ip[1] << 16) | (ip[2] << 8) | ip[3];

sscanf(ch, "%d", &chan);

lport = LPORT_BASE + chan * 2;
rport = RPORT_BASE + chan * 2;

/*
 * Set up the exception handler. We want to make sure that we perform
 * cleanup in case we are terminated by some unexpected event.
 */

#ifndef WIN32
signal(SIGQUIT, (void *) ExceptionHandler);
signal(SIGINT,  (void *) ExceptionHandler);
signal(SIGTERM, (void *) ExceptionHandler);
signal(SIGKILL, (void *) ExceptionHandler);
signal(SIGPIPE, (void *) ExceptionHandler);
#endif

/*
 * Initialize the interface for the PMC825.
 */

ret = Pmc825StartInterface(&Pmc825, pmc825_ip, host_ip, rport, lport, chan);

if (ret == PMC825_MEM_ALLOC_ERR)
  {
  printf("Memory allocation error, exiting ...\n");
  Pmc825StopInterface(&Pmc825);
  exit(0);
  }
else if (ret == PMC825_SOCKET_ERR)
  {
  printf("Socket error, exiting ...\n");
  Pmc825StopInterface(&Pmc825);
  exit(0);
  }

/*
 * Set CAN baud rate.
 */

tx_ctrl.opcode = CAN_CTRL;
tx_ctrl.svc_rsp_code = INIT_CAN_CHIP;
tx_ctrl.arg[0] = CAN_1M;
tx_ctrl.arg[1] = 0;
tx_ctrl.arg[2] = 0;
tx_ctrl.arg[3] = 0;
tx_ctrl.arg[4] = 0;

ret = Pmc825CtrlWrite(&Pmc825, &tx_ctrl);

if (ret != PMC825_OK)
  {
  printf("INIT_CAN_CHIP failed, exiting ...\n");
  Pmc825StopInterface(&Pmc825);
  exit(0);
  }

/*
 * Setup the CANaerospace transmit message.
 */

tx_buf.identifier = 2001;
tx_buf.byte_count = 8;
tx_buf.frame_type = DATA;

for (i = 0; i < 8; i++)
  tx_buf.data[i] = 0;

tx_buf.can_status = 0;
tx_buf.error_counter = 0;
tx_buf.time_stamp_lo = 0;
tx_buf.time_stamp_hi = 0;

/*
 * Now go into an endless loop echoeing CAN messages on the PMC825.
 */

printf("Start echoeing CAN messages on channel %d:\n", chan);

for (;;)
  {
  /*
   * Get all received CAN messages and print them.
   */

  ret = Pmc825RawCanRead(&Pmc825, &rx_buf);

  while (ret != PMC825_NO_MSG)
    {
    /*
     * Echo the received CAN message with Std-ID 2000.
     */

    if (rx_buf.identifier == 2000)
      {
      if (rx_buf.data[7] == 0x01)
        {
        for (loops = 0; loops < 8; loops++)
          tx_buf.data[loops] = 0xff;
        }
      else
        {
        for (loops = 0; loops < 8; loops++)
          tx_buf.data[loops] = 0x00;
        }

      Pmc825RawCanWrite(&Pmc825, (CAN_MSG *) &tx_buf, 1);
      }

#ifdef PRINT_CAN_MSGS
    /*
     * Artificially reduce the time stamp resolution from 31,25ns to 1us
     * for display purposes.
     */

    tsl = rx_buf.time_stamp_lo;
    tsh = rx_buf.time_stamp_hi;
    tsl = (tsl >> 5) & 0x07ffffff;
    tsh = (tsh << 27) & 0xf8000000;
    ts = tsl | tsh;
    tsf = ((float) ts)/1e6;

    if ((rx_buf.identifier & EXT_ID) == EXT_ID)
      {
      rx_buf.identifier &= ~EXT_ID;
      printf("%1.4f  EXT-CAN-ID $%08X: ", tsf, rx_buf.identifier);
      }
    else
      printf("%1.4f  STD-CAN-ID $%03X: ", tsf, rx_buf.identifier);

    for (loops = 0; loops < rx_buf.byte_count; loops++)
      printf("$%02X ", rx_buf.data[loops] & 0xff);
    printf("\n");
#endif
    ret = Pmc825RawCanRead(&Pmc825, (CAN_MSG *) &rx_buf);
    }

  /*
   * 20ms time frame.
   */

#ifndef WIN32
 // nanosleep(&t1,&t2);
#else
  Sleep (20);
#endif
  }
exit(0);
}

/*
 * End of file.
 */
