//Copyright (C) 2000 - 2003 Thomas Schank 
// 
//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either version 2
//of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA. 

#ifndef _LINK_H
#define _LINK_H

#include <string>
#include "datatypes.h"
#include "win32serial.h"
#include "posixserial.h"
#include "packet.h"

#define DATA_SIZE 270

// [0] -> DLE
// [1] -> PID
// [2] -> SIZE
// [3] -> data1 .....
// [n-4] -> data n
// [n-3] -> checksum
// [n-2] -> DLE
// [n-1] -> ETX
//
//**************************************************************


namespace gpspoint2 {
using namespace std;
using namespace gpspoint2;

/// this class handles the basic package exchange routines with a garmin device
/**
 * It can send and receives garmin packages. Packages are veryfied
 * with a checksum and in case of an errer 3 retries are performed.
 */
class Link : Serial
{
   public:
      Link(void);

   protected:
      /// set device e.g. /dev/ttyS1
      void setDevice(string s) { Serial::setDevice(s); }
      /// set Bauds for device 
      void setSpeed(string s) { Serial::setSpeed(s); }
      /// open the device 
      int openPort(void) { return Serial::openPort();}
      /// close the device
      void closePort(void){ Serial::closePort();}

      /// get an garmin packet 
      /** 
       *  if the class fails to get a valid Packet -1 will be returned,
       *  if it succeeds a value equal or bigger than  1 will be returned
       */
      int getPacket(Packet &);

      /// send a garmin packet
        /** 
       *  if the class fails to get a valid Packet -1 will be returned,
       *  if it succeeds a value equal or bigger than  1 will be returned
       */
    	int sendPacket(Packet);

   private:
      void clear(void);
      Packet gld;
      const g_char DLE, ETX, ACK, NAK;
      g_byte  data[DATA_SIZE];
      g_byte calculateChecksum(void);
      bool validateChecksum(void);
      void setChecksum(void);
      int getRawPacket(void);
      int sendRawPacket(void);
      void sendACK(g_byte pid);
      void sendNAK(g_byte pid);
};

}
#endif 
