// AuvMonDlg.cpp : implementation file
//

#include "stdafx.h"
#include "AuvMon.h"
#include "AuvMonDlg.h"
#include "smac.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

#define RED_BUTTON RGB(255,65,65)
#define GRN_BUTTON RGB(20,255,20)
#define YLW_BUTTON RGB(244,244,0)
#define BLK_TEXT   RGB(0,0,0)
#define USBL_BUFFER_SIZE 256

// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support

// Implementation
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()


// CAuvMonDlg dialog



CAuvMonDlg::CAuvMonDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CAuvMonDlg::IDD, pParent)
{
	statList = 0;
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CAuvMonDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAuvMonDlg, CDialog)
	ON_WM_TIMER()
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	//}}AFX_MSG_MAP
	ON_LBN_SELCHANGE(IDC_RECLIST, OnLbnSelchangeList1)
	ON_BN_CLICKED(IDC_USBLCON, OnBnClickedUsblcon)
	ON_BN_CLICKED(IDC_AUVCON, OnBnClickedAuvcon)
	ON_BN_CLICKED(IDC_BUTTON1, OnBnClickedButton1)
	ON_BN_CLICKED(IDOK, OnBnClickedOk)
	ON_EN_CHANGE(IDC_XMITPERIOD, OnEnChangeXmitperiod)
	ON_BN_CLICKED(IDC_REQSTAT, OnBnClickedReqstat)
	ON_BN_CLICKED(IDC_ABORTMSSN, OnBnClickedAbortmssn)
	ON_BN_CLICKED(IDC_STARTSRVY, OnBnClickedStartsrvy)
	ON_NOTIFY(LVN_ITEMCHANGED, IDC_STATLIST, OnLvnItemchangedStatlist)
	ON_BN_CLICKED(IDC_PAN2, &CAuvMonDlg::OnBnClickedPan2)
	ON_EN_CHANGE(IDC_PANCOM, &CAuvMonDlg::OnEnChangePancom)
	ON_BN_CLICKED(IDC_PAN, &CAuvMonDlg::OnBnClickedPan)
	ON_EN_CHANGE(IDC_USBLCOM, &CAuvMonDlg::OnEnChangeUsblcom)
	ON_EN_CHANGE(IDC_AUVCOM, &CAuvMonDlg::OnEnChangeAuvcom)
	ON_EN_CHANGE(IDC_BEHAVE, &CAuvMonDlg::OnEnChangeBehave)
	ON_EN_CHANGE(IDC_PANADDRS, &CAuvMonDlg::OnEnChangePanaddrs)
END_MESSAGE_MAP()


// CAuvMonDlg message handlers

BOOL CAuvMonDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	WSADATA wsaData;
	int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);

	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here
	_timerId = SetTimer(1, 500, NULL);
	SetDlgItemText(IDC_XMITPERIOD, "5");
	OnEnChangeXmitperiod();

	statList = (CListCtrl*)GetDlgItem(IDC_STATLIST);
	statList->InsertColumn(0, "Status Message", LVCFMT_LEFT, 400);

	recList = (CListCtrl*)GetDlgItem(IDC_RECLIST);
	recList->InsertColumn(0, "Transmitted Nav Records", LVCFMT_LEFT, 400);

	WriteStat("AuvMon Started...ready");

	_lastXmitTime = 0;

	_usblBtn.SubclassDlgItem(IDC_USBLCON, this);
	_usblBtn.SetColor(BLK_TEXT, RED_BUTTON);
	_usblConnected = FALSE;


	_auvBtn.SubclassDlgItem(IDC_AUVCON, this);
	_auvBtn.SetColor(BLK_TEXT, RED_BUTTON);
	_auvConnected = FALSE;
	_panConnected = FALSE;

	_xmitBtn.SubclassDlgItem(IDC_BUTTON1, this);
	_xmitBtn.SetColor(BLK_TEXT, RED_BUTTON);
	_xmit = FALSE;

	_panBtn.SubclassDlgItem(IDC_PAN, this);
	_panBtn.SetColor(BLK_TEXT, RED_BUTTON);
	_panConnected = FALSE;

	_panAddrsBtn.SubclassDlgItem(IDC_PAN2, this);
	_panAddrsBtn.SetColor(BLK_TEXT, RED_BUTTON);
	_panAddrsSet = FALSE;
	_panEnabled = FALSE;

	SetDlgItemText(IDC_AUVCOM, "15");
	SetDlgItemText(IDC_GPSCOM, "7");
	SetDlgItemText(IDC_USBLCOM, "20");
	SetDlgItemText(IDC_PANCOM, "12");

	//SetDlgItemText(IDC_XMITREC, "N/A");
	//SetDlgItemText(IDC_XMITACK, "N/A");
	SetDlgItemText(IDC_LAT,   "---");
	SetDlgItemText(IDC_LONG,  "---");
	SetDlgItemText(IDC_HEAD,  "---");
	SetDlgItemText(IDC_DEPTH, "---");
	SetDlgItemText(IDC_ALT,   "---");
	SetDlgItemText(IDC_VOLT,  "---");
	SetDlgItemText(IDC_BEHAVE, "N/A");

	_nmeaSocket = NULL;

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CAuvMonDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

void CAuvMonDlg::Update()
{
	char buf[32];

	sprintf(buf, "%.6f", _auvLat);
	SetDlgItemText(IDC_LAT,   buf);
	sprintf(buf, "%.6f", _auvLong);
	SetDlgItemText(IDC_LONG,  buf);
	sprintf(buf, "%.6f", _auvHead);
	SetDlgItemText(IDC_HEAD,  buf);
	sprintf(buf, "%.2f", _auvDepth);
	SetDlgItemText(IDC_DEPTH, buf);
	sprintf(buf, "%.2f", _auvAlt);
	SetDlgItemText(IDC_ALT,   buf);
	sprintf(buf, "%.2f", _auvVolt);
	SetDlgItemText(IDC_VOLT,  buf);
	sprintf(buf, "%.2f", _auvHumid);
	SetDlgItemText(IDC_HUMIDITY,  buf);
	SetDlgItemText(IDC_BEHAVE, _auvBehavior);
	SetDlgItemText(IDC_ABORT, _auvAbort);

	OnPaint();
}

void CAuvMonDlg::OnTimer(UINT nIDEvent)
{
	static int __cntr = 0;

	// Check for a message from the AUV
	if (_auvConnected && GetAuvData())
	{
		Update();
	}

	if (_panConnected && GetAuvPanData())
	{
		Update();
	}

	// Check for data from WinFrog
	if (_usblConnected)
	{
		GetUsblData();
	}

	if (__cntr++ == 30) {
///		__cntr = 0;
//		if (_panConnected) {
//			_panPort.SendData("ADM1009\xd\xa", 9);
//			Sleep(2000);
//		}
	}

}

int CAuvMonDlg::GetUsblData()
{
	static int oldlatdd = 0, oldlongdd = 0;
	static float oldlatmm = 0.0, oldlongmm = 0.0;
	static int nbytes = 0;
	// If there's data waiting from WinFrog, then read and parse for transmit

	if (_usblPort.ReadDataWaiting() > 0)
//	if (_usblPort.ReadDataWaiting() > 20)
	{
	  char usbldata[USBL_BUFFER_SIZE];
	  unsigned long usbl_size;
	  char *ptr;
	  int bytesRead;

	  memset((void *)usbldata, 0, USBL_BUFFER_SIZE);
	  ptr = usbldata;

	  do {
		  bytesRead = _usblPort.ReadDataBlocking((void *)ptr, 1);
		  if (!bytesRead) return 1;
		  if ((ptr - usbldata + 1) > (USBL_BUFFER_SIZE - 1)) return 1;
	  } while (*(ptr++) != 0x0a);

	  //usbl_size = _usblPort.ReadData(((char *)usbldata)+nbytes, USBL_BUFFER_SIZE-1);

	  char msgType[10];
	  char n = ' ', w = ' ';
	  int hh = 0, mm = 0, latdd = 0, longdd = 0;
	  float ss = 0, latmm = 0, longmm = 0, slant = 0, dum = 0.;
	  int oldData;

	  // For testing, create dummy string according to WinFrog spec
	  //
	  // sprintf(usbldata, "$PUSBA,111213.145,3345.7500,N,12123.7500,E,1.1,2.2,3.3,,4.4,5.55,7.8,a.a,ddmm.mmm,a,dddmm.mmmm,a*hh\xd\xa");

	  int ntokens = sscanf(usbldata, "%6s,%2d%2d%f,%2d%f,%c,%3d%f,%c,%f,%f,%f,%f,%f,%f",
		msgType,&_usblhh,&_usblmm,&_usblss,
		&latdd,&latmm,&n,&longdd,&longmm,&w,&dum,&dum,&dum,&dum,&dum,&_usblSlant);
//      int ntokens = sscanf(wf, "%6s,%2d%2d%f,%2d%f,%c,%3d%f,%c",
//		msgType, &_usblhh, &_usblmm, &_usblss, &latdd,&latmm,&n,&longdd, &longmm, &w);

	  if (ntokens != 16) {
		WriteStat("received too few tokens in USBL string");
	  }

	  if (ntokens == 16) {
	    _usblLat = latdd + (latmm/60.f);
		if (n == 'S') _usblLat = 0.f - _usblLat;
		_usblLong = longdd + (longmm/60.f);
		if (w == 'W') _usblLong = 0.f - _usblLong;

		if ((latdd==oldlatdd) && (latmm==oldlatmm) && (longdd==oldlongdd) && (longmm==oldlongmm)) {
			oldData = 1;
		} else {
			oldData = 0;
		}
		  

		// Placing the call to SendNavPacket here ensures that only fresh
		// USBL data is sent to the AUV.
		// Are we due to xmit a Nav packet?
		time_t now;
		time(&now);

		if (_xmit && ((now - _lastXmitTime) >= _period))
		{
			if (!oldData) {
				SendNavPacket(now);
				_lastXmitTime = now;
				oldlatdd = latdd; oldlatmm = latmm; oldlongdd = longdd; oldlongmm = longmm;
			} else {
				//WriteStat("USBL data is stale");
			}
		}
	  }
	  return 0;
	}


	// This should rarely, if ever, occur
	else if (_usblPort.ReadDataWaiting() > 0)
	{
		char usbldata[USBL_BUFFER_SIZE];
		unsigned long usbl_size;

		usbl_size = _usblPort.ReadData((void*)usbldata, USBL_BUFFER_SIZE);

		WriteStat("Data on usbl port of insufficient length");
	}

	return 1;
}

// Assemble and transmit Nav packet to AUV via acoustic modem link
void CAuvMonDlg::SendNavPacket(long ts)
{
	// Assemble packet for AUV
	SMAC_RECORD_HEADER sh;
	SMAC_SAN_RECORD    san;
	char packet[100];
	unsigned long packet_size;

	san.wfLat = _usblLat;
	san.wfLong = _usblLong;
//	san.wfSlant = _usblSlant;
//	san.wfTime = _usblhh*3600.f + _usblmm*60.f + _usblss;

	smac::encodePacket(&sh, &san, packet, &packet_size);

	// Send packet to AUV
	if (_auvConnected) {
		_auvPort.SendData(packet, packet_size);
//		_auvPort.SendData("Done", 5);
	}

	if (_panEnabled) {
		char buffer[256];
		if (_panConnected) {
			int i, nbytes;
			memset(buffer, 0, 256);
			nbytes = sprintf(buffer, "SMS:%04d;W0;P0,A0,C0,R0,B0|", _addrs);
			//nbytes = sprintf(buffer, "SMS:%04d|", _addrs);
			for (i = 0; i < packet_size; i++) {
				sprintf(buffer + i * 2 + nbytes, "%1x%1x", (unsigned char)(packet[i] & 0x0F),
					(unsigned char)((packet[i] & 0xF0) >> 4));
			}
			buffer[i * 2 + nbytes] = '\xa';
//			buffer[i * 2 + nbytes] = '\xd';
//			buffer[i * 2 + nbytes + 1] = '\xa';
		}
	_panPort.SendData(buffer, strlen(buffer));
	}
	
	// Write this record info to record list
	char msg[256];
	sprintf(msg, "%02d:%02d:%.3f   LT:%.5f   LG:%.5f   SL:%.2f", _usblhh, _usblmm, 
		_usblss, _usblLat, _usblLong, _usblSlant);
	WriteRecList(msg);
}

// Read data from AUV via acoustic modem link
int CAuvMonDlg::GetAuvData()
{
	char packet[180];
	unsigned long packet_size;

	if (_auvPort.ReadDataWaiting() >= (sizeof(SMAC_RECORD_HEADER) + sizeof(SMAC_STAT_RECORD)+4)) Sleep(2000); else return 0;

	// Read status packet from modem
	if (_auvPort.ReadDataWaiting() >= (sizeof(SMAC_RECORD_HEADER) + sizeof(SMAC_STAT_RECORD))
		&& ((packet_size) = _auvPort.ReadData((void*)packet, 180)) > 0)
	{
		SMAC_RECORD_HEADER hdr;
		SMAC_STAT_RECORD stat;
		int decodeOK = 0;

		char bcMsg[100];
		sprintf(bcMsg, "got %d bytes from modem", packet_size);
		WriteStat(bcMsg);

		//smac::decodeHeader(packet, packet_size, &hdr);
		hdr.record_type = smac::RecordType::STAT;
		switch (hdr.record_type) {
		case smac::RecordType::STAT:
			decodeOK = smac::decodeStatRecord(packet, packet_size, &stat);
			if (0 == decodeOK)
			{
				UpdateAuvData(stat);
				return 1;
			}
			else if (1 == decodeOK)
				WriteStat("Checksum failed in Auv Status data packet");

			else if (2 == decodeOK)
				WriteStat("Checksum failed in Auv Status header");

			break;

		default:
			WriteStat("Unknown message received from AUV");

			break;
		}
	}

	return 0; // No data
}

// Read data from AUV via acoustic modem link
int CAuvMonDlg::GetAuvPanData()
{
	char packet[100];
	unsigned long packet_size;
	char buffer[4096];

	//do the same checks for data on the Ranger 2 modem
	if (_panPort.ReadDataWaiting() >= 2*(sizeof(SMAC_RECORD_HEADER) + sizeof(SMAC_STAT_RECORD))) {
		SMAC_RECORD_HEADER hdr;
		SMAC_STAT_RECORD stat;
		int decodeOK = 0;
		char *ptr;
		unsigned char msn, lsn;

		ptr = buffer; memset(buffer, 0x0, 4096);
//		char *fakeString = " SMS:1902|100000004200000074C4A975E81000001000000000000000E0C0000000000000000000000000000000000000000000000000091400000000300000000000000080220000";
//		memcpy(buffer, fakeString, strlen(fakeString));
//		buffer[strlen(fakeString)] = 0x0d; buffer[strlen(fakeString) + 1] = 0x0a;


		//read in entire line of data from SMS - only printables allowed, cr lf denotes end of data
		Sleep(2000); //add a delay here, so that really long SMS packets, like the ones generated by Ranger 2
					 //have time to be fully received before processing
		do {
			if (ptr > buffer + 4095) {
				WriteStat("buffer overflow reading PAN data");
				return 0;
			}
			_panPort.ReadData(ptr, 1);
		} while (*ptr++ != 0x0a);

		for (int i = 0; i < 4096; i++) {
			if (buffer[i] == 0x0d || buffer[i] == 0x0a) buffer[i] = 0x0;
		}

		ptr = strchr(buffer, '|');
		if (ptr == NULL) return 0; //return if we don't find the beginning of an SMS packet
		if (strlen(ptr) > 2 * 100) return 0; //if length of data won't fit into packet, something wierd is going on. Flush 
		packet_size = 0;
		ptr++; //increment ptr to point at beginning of SMS packet
		unsigned int val1, val2;
		for (int i = 0; i < strlen(ptr); i+=2) {
			sscanf(ptr + i, "%1x%1x", &val1, &val2);
			packet[packet_size++] = val1 | (val2 << 4);
		}

		hdr.record_type = smac::RecordType::STAT;
		switch (hdr.record_type) {
		case smac::RecordType::STAT:
			decodeOK = smac::decodeStatRecord(packet, packet_size, &stat);
			if (0 == decodeOK)
			{
				UpdateAuvData(stat);
				return 1;
			}
			else if (1 == decodeOK)
				WriteStat("Checksum failed in Auv Status data packet");

			else if (2 == decodeOK)
				WriteStat("Checksum failed in Auv Status header");

			break;

		default:
			WriteStat("Unknown message received from AUV");

			break;
		}

	}

	return 0; // No data
}

void CAuvMonDlg::UpdateAuvData(SMAC_STAT_RECORD stat)
{
	_auvLat = stat.auvLat;
	_auvLong = stat.auvLong;
	_auvHead = stat.auvHeading;
	_auvDepth = stat.auvDepth;
	_auvAlt = stat.auvAlt;
	_auvVolt = 0.0; // stat.auvVolt;
	_auvHumid = stat.auvHumid;

	_auvBehavior.Format("%d", stat.auvBehavior);

	/*
	if (stat.auvBehavior < smac::BhavrType::INVALID_BHAVR)
	  _auvBehavior.Format("%s", smac::_behaviorNames[stat.auvBehavior]);
	else
	  _auvBehavior.Format("%s", "UNKNOWN");
    */
//	if (stat.auvAbort)
//	  _auvAbort = "Yes";
//	else
	  _auvAbort = "No";

	char gllString[100];
	double lat_deg, lat_min, lon_deg, lon_min;
	lat_min = 60.0*modf(_auvLat, &lat_deg); lon_min = 60*modf(_auvLong, &lon_deg);
	time_t secs;

	time(&secs);
	secs %= 86400;

	sprintf(gllString, "$GPGLL,%02d%08.5f,%c,%03d%08.5f,%c,%02d%02d%02d,A\r\n\0",
		(int)(abs(lat_deg)), abs(lat_min), (lat_deg>0) ? 'N' : 'S',
		(int)(abs(lon_deg)), abs(lon_min), (lon_deg > 0) ? 'E' : 'W',
		(int)(secs / 3600), (int)((secs % 3600) / 60), secs % 60);
	if (_nmeaSocket) _nmeaSocket->sending(gllString, strlen(gllString));
	WriteStat(gllString);
	return;
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CAuvMonDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this function to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CAuvMonDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

void CAuvMonDlg::OnLbnSelchangeList1()
{
	// TODO: Add your control notification handler code here
}

void CAuvMonDlg::OnEnChangeEdit7()
{
	// TODO:  If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.

	// TODO:  Add your control notification handler code here
}


void CAuvMonDlg::OnBnClickedUsblcon()
{
	// TODO: Add your control notification handler code here
	// Attempt to establish comms with USBL
	//
	CString s;
	GetDlgItemText(IDC_USBLCOM, s);
//	if (_usblPort.Open(atoi(s.GetString()), 9600))
	if (_usblPort.Open(atoi(s.GetString()), 9600) || 1)
	{
	  // Port opened, set-up USBL to send data
	  WriteStat("WinFrog responding...Connected");
	  _usblConnected = TRUE;
	  _usblBtn.SetColor(BLK_TEXT, GRN_BUTTON);
	}
}

void CAuvMonDlg::OnBnClickedAuvcon()
{
	// TODO: Add your control notification handler code here
	// Attempt to establish comms with AUV via acoustic modem
	//
	CString s;
	GetDlgItemText(IDC_AUVCOM, s);
	if (_auvPort.Open(atoi(s.GetString()), 9600))
	{
	  // Port opened, set-up USBL to send data
	  WriteStat("AUV responding...Connected");
	  _auvConnected = TRUE;
	  _auvBtn.SetColor(BLK_TEXT, GRN_BUTTON);
	}

	//set up a network connection to winfrog running on rcnav
	_nmeaSocket = new SimpleSocket();
	_nmeaSocket->createConnectedStreamClient(2050, "134.89.22.33");
	if (!_nmeaSocket->ready()) {
		WriteStat("socket to winfrog not connected");
	}
	else {
		WriteStat("socket to winfrog connected");
	}

	//set up serial port connection to PAN 
}


// Start transmitting Nav packets
void CAuvMonDlg::OnBnClickedButton1()
{
	// TODO: Add your control notification handler code here
	if (!_xmit)
	{
	  char p[10];
	  GetDlgItemText(IDC_XMITPERIOD, p, 10);
	  _period = (atoi(p));
	  
	  if (_usblConnected && (_auvConnected || (_panConnected && _panAddrsSet)))
	  {
	    WriteStat("Start transmitting Nav packets");
	    _xmit = TRUE;
	    _xmitBtn.SetColor(BLK_TEXT, GRN_BUTTON);
	    SetDlgItemText(IDC_BUTTON1, "Stop Packet Xmit");
	    return;
	  }
	  else
	  {
	    WriteStat("WinFrog-USBL|AUV not connected");
		return;
	  }
	}

	else
	{
	  WriteStat("Stop transmitting Nav packets");
	  _lastXmitTime = 0;
	  _xmit = FALSE;
	  _xmitBtn.SetColor(BLK_TEXT, RED_BUTTON);
	  SetDlgItemText(IDC_BUTTON1, "Start Packet Xmit");
	  return;
	}
}

// Write the string to the status list after pre-pending the date/time
void CAuvMonDlg::WriteStat(const char *msg)
{
	if (statList)
	{
		char line[256];
		time_t now;
		struct tm *tms;

		// Get current date/time
		time(&now);
		tms = localtime(&now);
		// Format string
		sprintf(line, "[%03d %02d:%02d:%02d] %s", tms->tm_yday, tms->tm_hour, tms->tm_min,
		tms->tm_sec, msg);
		// Insert the string at the top of the list
		statList->InsertItem(0, line);
	}
}

// Write the string to the record list
void CAuvMonDlg::WriteRecList(const char *msg)
{
	if (recList)
	{
		recList->InsertItem(0, msg);
	}
}

void CAuvMonDlg::OnBnClickedOk()
{
	// TODO: Add your control notification handler code here
	KillTimer(_timerId);
	OnOK();
}

void CAuvMonDlg::OnEnChangeXmitperiod()
{
	// TODO:  If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.

	// TODO:  Add your control notification handler code here
}

void CAuvMonDlg::OnBnClickedReqstat()
{
	// TODO: Add your control notification handler code here
	// Create and send a status request command over the modem to the AUV
	//
	if (!_auvConnected && !(_panConnected && _panAddrsSet))
	{
	  WriteStat("Not connected to AUV");
	  return;
	}

    WriteStat("Requesting status from AUV");

	SMAC_RECORD_HEADER sh;
	SMAC_CMD_RECORD sc;
	char packet[100];
	unsigned long packet_size;

	sh.parameter = smac::REQ_STAT;
	smac::encodePacket(&sh, &sc, packet, &packet_size);
//	char cmdstr[30];
//	sprintf(cmdstr, "+++\xd\xa\x0"); _auvPort.SendData(cmdstr, strlen(cmdstr)); Sleep(1000);
//	sprintf(cmdstr, "ats14=%d\xd\xa", 2); _auvPort.SendData(cmdstr, strlen(cmdstr)); Sleep(500);
//	sprintf(cmdstr, "ato\xd\xa\x0"); _auvPort.SendData(cmdstr, strlen(cmdstr)); Sleep(500);

	if (_panEnabled) {
		char buffer[256];
		if (_panConnected) {
			int i, nbytes;
			memset(buffer, 0, 256);
			nbytes = sprintf(buffer, "SMS:%04d;W0;P0,A0,C0,R0,B0|", _addrs);
//			nbytes = sprintf(buffer, "SMS:%04d|", _addrs);
			for (i = 0; i < packet_size; i++) {
				sprintf(buffer + i * 2 + nbytes, "%1x%1x", (unsigned char)(packet[i] & 0x0F),
					(unsigned char)((packet[i] & 0xF0) >> 4));
		}
			buffer[i * 2 + nbytes] = '\xa';
//			buffer[i * 2 + nbytes] = '\xd';
//			buffer[i * 2 + nbytes + 1] = '\xa';
			_panPort.SendData(buffer, strlen(buffer));
		}

	} else {
		if (_auvConnected) _auvPort.SendData((char *)packet, packet_size);	
	}

	
}

void CAuvMonDlg::OnBnClickedAbortmssn()
{
	// TODO: Add your control notification handler code here
	if (!_auvConnected && !(_panConnected && _panAddrsSet))
	{
	  WriteStat("Not connected to AUV");
	  return;
	}

	int ans = MessageBox("Abort mission and return to surface?",
		"Abort Mission", MB_YESNO);

	if (ans == IDYES)
	{
	  WriteStat("Sending \"Abort\" message to AUV");
	  if (_xmit) OnBnClickedButton1(); // Turn off nav packet transmit

	  SMAC_RECORD_HEADER hdr;
	  SMAC_CMD_RECORD sc;
  	  char packet[100];
	  unsigned long packet_size;

	  hdr.parameter = smac::ABORT_MISSION;
	  smac::encodePacket(&hdr, &sc, packet, &packet_size);
	  if (_auvConnected && !_panConnected) _auvPort.SendData(packet, packet_size);

	  if (_panEnabled) {
		  char buffer[256];
		  if (_panConnected) {
			  int i, nbytes;
			  memset(buffer, 0, 256);
			  nbytes = sprintf(buffer, "SMS:%04d;W0;P0,A0,C0,R0,B0|", _addrs);
//			  nbytes = sprintf(buffer, "SMS:%04d|", _addrs);
			  for (i = 0; i < packet_size; i++) {
				  sprintf(buffer + i * 2 + nbytes, "%1x%1x", (unsigned char)(packet[i] & 0x0F),
					  (unsigned char)((packet[i] & 0xF0) >> 4));
			  }
			  buffer[i * 2 + nbytes] = '\xa';
//			  buffer[i * 2 + nbytes] = '\xd';
//			  buffer[i * 2 + nbytes + 1] = '\xa';
		  }
		  _panPort.SendData(buffer, strlen(buffer));
	  }

	}
}

void CAuvMonDlg::OnBnClickedStartsrvy()
{
	// TODO: Add your control notification handler code here
	if (!_auvConnected && !(_panConnected && _panAddrsSet))
	{
	  WriteStat("Not connected to AUV");
	  return;
	}

	int ans = MessageBox("Start mapping survey now?",
		"Start Survey", MB_YESNO);

	if (ans == IDYES)
	{
	  WriteStat("Sending \"Start Survey\" message to AUV");
	  if (_xmit) OnBnClickedButton1(); // Turn off nav packet transmit

	  SMAC_RECORD_HEADER hdr;
	  SMAC_CMD_RECORD sc;
  	  char packet[100];
	  unsigned long packet_size;

	  hdr.parameter = smac::CmdType::START_SURVEY;
	  smac::encodePacket(&hdr, &sc, packet, &packet_size);
	  if (_auvConnected && !_panConnected) _auvPort.SendData(packet, packet_size);

	  if (_panEnabled) {
		  char buffer[256];
		  if (_panConnected) {
			  int i, nbytes;
			  memset(buffer, 0, 256);
			  nbytes = sprintf(buffer, "SMS:%04d;W0;P0,A0,C0,R0,B0|", _addrs);
//			  nbytes = sprintf(buffer, "SMS:%04d|", _addrs);
			  for (i = 0; i < packet_size; i++) {
				  sprintf(buffer + i * 2 + nbytes, "%1x%1x", (unsigned char)(packet[i] & 0x0F),
					  (unsigned char)((packet[i] & 0xF0) >> 4));
			  }
			  buffer[i * 2 + nbytes] = '\xa';
//			  buffer[i * 2 + nbytes] = '\xd';
//			  buffer[i * 2 + nbytes + 1] = '\xa';
		  }
		  _panPort.SendData(buffer, strlen(buffer));
	  }

	}
}

void CAuvMonDlg::OnLvnItemchangedStatlist(NMHDR *pNMHDR, LRESULT *pResult)
{
	LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR);
	// TODO: Add your control notification handler code here
	*pResult = 0;
}


void CAuvMonDlg::OnBnClickedPan2()
{
	CString s;
	GetDlgItemText(IDC_PANADDRS, s);

	_addrs = atoi(s);
	_panAddrsSet = TRUE;
	WriteStat("PAN Addrs...Connected");
	_panEnabled = !_panEnabled;
	if (_panEnabled) {
		WriteStat("PAN Updates Enabled");
		_panAddrsBtn.SetColor(BLK_TEXT, GRN_BUTTON);
	}
	else {
		WriteStat("PAN Updates Disabled");
		_panAddrsBtn.SetColor(BLK_TEXT, RED_BUTTON);
	}

//	if (_panConnected) {
//		_panPort.SendData("ADM1009\xd\xa", 9);
//		Sleep(3000);
//	}
}


void CAuvMonDlg::OnEnChangePancom()
{
	// TODO:  If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.

	// TODO:  Add your control notification handler code here
}


void CAuvMonDlg::OnBnClickedPan()
{
	CString s;
	GetDlgItemText(IDC_PANCOM, s);

	if (_panPort.Open(atoi(s), 9600))
		{
			// Port opened
			WriteStat("PAN responding...Connected");
			_panConnected = TRUE;
			_panBtn.SetColor(BLK_TEXT, GRN_BUTTON);
		}

	//set up a network connection to winfrog running on rcnav
	_nmeaSocket = new SimpleSocket();
	_nmeaSocket->createConnectedStreamClient(2051, "134.89.22.33");
	if (!_nmeaSocket->ready()) {
		WriteStat("socket to winfrog not connected");
	}
	else {
		WriteStat("socket to winfrog connected");
	}
	// TODO: Add your control notification handler code here
}


void CAuvMonDlg::OnEnChangeUsblcom()
{
	// TODO:  If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.

	// TODO:  Add your control notification handler code here
}


void CAuvMonDlg::OnEnChangeAuvcom()
{
	// TODO:  If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.

	// TODO:  Add your control notification handler code here
}


void CAuvMonDlg::OnEnChangeBehave()
{
	// TODO:  If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.

	// TODO:  Add your control notification handler code here
}


void CAuvMonDlg::OnEnChangePanaddrs()
{
	// TODO:  If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.

	// TODO:  Add your control notification handler code here
}
