// BotControlDlg.cpp : implementation file
//

/* (C) 2005 Daniel Alvarez (dani001@gmail.com). All rights reserved.
 *
 * Permission is granted to use, distribute and modify this code provided that:
 *   · this copyright notice remain unchanged,
 *   · you submit all changes to the copyright holder and properly mark the
 *     changes so they can be told from the original code,
 *   · credits are given to the copyright holder in the documentation of any
 *     software using this code with the following line:
 *       "Portions copyright 2005 Daniel Alvarez (dani001@gmail.com)"
 *
 * The author welcomes any suggestions on the code or reportings of actual
 * use of the code. Please send your comments to dani001@gmail.com.
 *
 * The author makes NO WARRANTY or representation, either express or implied,
 * with respect to this code, its quality, accuracy, merchantability, or
 * fitness for a particular purpose.  This software is provided "AS IS", and
 * you, its user, assume the entire risk as to its quality and accuracy.
 *
 * Last modified: July 16th, 2001
 */


#include "stdafx.h"
#include "BotControl.h"
#include "BotControlDlg.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif



extern CBotControlApp theApp;

CString Puertos[10];
int iNumPuertos=0;
int m_GiNumCom=0;

static BOOL CALLBACK callback(LPVOID lpCallbackValue,LISTPORTS_PORTINFO* lpPortInfo)
{
 
  Puertos[iNumPuertos] = lpPortInfo->lpPortName+3;
  iNumPuertos++;
  return TRUE;
}



UINT LeerSensores(LPVOID pParam) {

	
	CBotControlDlg *pDlg=(CBotControlDlg *)pParam;
	pDlg->m_bHiloEjecucion=TRUE;

	int valor;

	while( pDlg->m_bHiloEjecucion == TRUE ) {

	 WaitForSingleObject( theApp.hIOMutex, INFINITE );
	 if( pDlg->m_pSerie->SGLoad(PORTB, &valor) != 1 ) 
	 {

		 ReleaseMutex(theApp.hIOMutex);	
		 AfxMessageBox("Error al leer los sensores.");
		 return 0;
	 }

	 ReleaseMutex(theApp.hIOMutex);

	 if( valor & 0x80 )
		 pDlg->m_ctlCheckSensor4.SetCheck(FALSE);
	 else
		 pDlg->m_ctlCheckSensor4.SetCheck(TRUE);
	 if( valor & 0x40 )
		 pDlg->m_ctlCheckSensor3.SetCheck(FALSE);
	 else
		 pDlg->m_ctlCheckSensor3.SetCheck(TRUE);
	 if( valor & 0x20 )
		 pDlg->m_ctlCheckSensor2.SetCheck(FALSE);
	 else
		 pDlg->m_ctlCheckSensor2.SetCheck(TRUE);
	 if( valor & 0x01 )
		 pDlg->m_ctlCheckSensor1.SetCheck(FALSE);
	 else
		 pDlg->m_ctlCheckSensor1.SetCheck(TRUE);
	 
Sleep(80);

	}

   

	return 0;

}

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();

// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
		// No message handlers
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CBotControlDlg dialog

CBotControlDlg::CBotControlDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CBotControlDlg::IDD, pParent)
{
	//{{AFX_DATA_INIT(CBotControlDlg)
	m_iComPort = -1;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CBotControlDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CBotControlDlg)
	DDX_Control(pDX, IDC_TEXTO, m_ctlStaticTexto);
	DDX_Control(pDX, IDC_BUTTON_CONECTAR, m_ctlButtonConectar);
	DDX_Control(pDX, IDC_SENSOR4, m_ctlCheckSensor4);
	DDX_Control(pDX, IDC_SENSOR3, m_ctlCheckSensor3);
	DDX_Control(pDX, IDC_SENSOR2, m_ctlCheckSensor2);
	DDX_Control(pDX, IDC_SENSOR1, m_ctlCheckSensor1);
	DDX_Control(pDX, IDC_COMBO1, m_ctlComboCom);
	DDX_Control(pDX, IDC_ATRAS, m_ctlButtonAtras);
	DDX_Control(pDX, IDC_DERECHA, m_ctlButtonDerecha);
	DDX_Control(pDX, IDC_IZQUIERDA, m_ctlButtonIzquierda);
	DDX_Control(pDX, IDC_ALANTE, m_ctlButtonAlante);
	DDX_CBIndex(pDX, IDC_COMBO1, m_iComPort);
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CBotControlDlg, CDialog)
	//{{AFX_MSG_MAP(CBotControlDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_CBN_SELCHANGE(IDC_COMBO1, OnSelchangeCombo1)
	ON_BN_CLICKED(IDC_BUTTON_CONECTAR, OnConnect)
	ON_BN_CLICKED(IDC_ALANTE, OnAlante)
	ON_BN_CLICKED(IDC_DERECHA, OnDerecha)
	ON_BN_CLICKED(IDC_ATRAS, OnAtras)
	ON_BN_CLICKED(IDC_IZQUIERDA, OnIzquierda)
	ON_WM_LBUTTONUP()
   ON_WM_LBUTTONDOWN()
   ON_COMMAND(ID_MEN_SALIR, OnMenSalir)
   ON_COMMAND(ID_MEN_ABOUT, OnMenAbout)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()


void CBotControlDlg::OnLButtonDown(UINT nFlags, CPoint point) 
{
   PostMessage(WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(point.x, point.y));	
   CDialog::OnLButtonDown(nFlags, point);
}


/////////////////////////////////////////////////////////////////////////////
// CBotControlDlg message handlers

BOOL CBotControlDlg::OnInitDialog()
{
	CDialog::OnInitDialog();

	// 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
	this->m_ctlCheckSensor1.SetCheck(FALSE);
	this->m_ctlCheckSensor2.SetCheck(FALSE);
	this->m_ctlCheckSensor3.SetCheck(FALSE);
	this->m_ctlCheckSensor4.SetCheck(FALSE);
	
	this->m_ctlCheckSensor1.SetLedSize(400);
	this->m_ctlCheckSensor2.SetLedSize(400);
	this->m_ctlCheckSensor3.SetLedSize(400);
	this->m_ctlCheckSensor4.SetLedSize(400);

	this->m_ctlCheckSensor1.SetLedColor(RGB(255, 255, 255), RGB(0, 0, 0));
	this->m_ctlCheckSensor2.SetLedColor(RGB(255,255, 255), RGB(0, 0, 0));
	this->m_ctlCheckSensor3.SetLedColor(RGB(255, 255, 255), RGB(0, 0, 0));
	this->m_ctlCheckSensor4.SetLedColor(RGB(255,255, 255), RGB(0, 0, 0));

   
   
   this->m_ctlButtonAlante.setDirection(ALANTE);
	this->m_ctlButtonAlante.SetDirection(CTriangleButton::POINT_UP);
   
   this->m_ctlButtonAtras.setDirection(ATRAS);
	this->m_ctlButtonAtras.SetDirection(CTriangleButton::POINT_DOWN);

   this->m_ctlButtonIzquierda.setDirection(IZQUIERDA);
   this->m_ctlButtonIzquierda.SetDirection(CTriangleButton::POINT_LEFT);

   this->m_ctlButtonDerecha.setDirection(DERECHA);
   this->m_ctlButtonDerecha.SetDirection(CTriangleButton::POINT_RIGHT);



	this->m_bPortOpen=FALSE;
	this->m_bHiloEjecucion =FALSE;


	ListPorts(callback,NULL);
	

   theApp.m_pSerie = new CSGTramas();
   theApp.hIOMutex = CreateMutex (NULL, FALSE, NULL);
   this->m_pSerie = theApp.m_pSerie;

	for(int i=0;i<iNumPuertos;i++) {
		this->m_ctlComboCom.AddString(Puertos[i]);
		if( i==0 ) {
			CString  aux;
			this->m_ctlComboCom.SetCurSel(i);
			this->m_ctlComboCom.GetLBText(0,aux);
			m_GiNumCom = _ttoi(aux);
		}
	}

   AfxGetMainWnd()->SetWindowText(_T("BotControl"));
	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CBotControlDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// 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 CBotControlDlg::OnPaint() 
{
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		SendMessage(WM_ICONERASEBKGND, (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 to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CBotControlDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}

void CBotControlDlg::OnOK() 
{
}




void CBotControlDlg::OnMenSalir() {
   
   this->OnCancel();


}

void CBotControlDlg::OnMenAbout() 
{
   CAboutDlg dlg;
   dlg.DoModal();
}


void CBotControlDlg::OnCancel() {
   
   if(this->m_bPortOpen == TRUE)
      this->m_pSerie->Close();

	CDialog::OnCancel();

}



void CBotControlDlg::OnSelchangeCombo1() 
{

	this->UpdateData(TRUE);
	CString aux;
	this->m_ctlComboCom.GetLBText(this->m_iComPort,aux);
	m_GiNumCom = _ttoi(aux);
	
}

void CBotControlDlg::OnConnect() 
{

   m_GiNumCom=1;

	this->UpdateData(TRUE);
	if(this->m_bPortOpen == FALSE) {

		if( this->m_pSerie->Open(m_GiNumCom,9600) == FALSE ) {

				AfxMessageBox("Error al abrir el puerto serie.");
				return;
		}
		

		
		if( this->m_pSerie->SGPing() != 1 ) {

			this->m_pSerie->Close();
			AfxMessageBox("No se obtiene respuesta del microcontrolador.");
			return;
		}

   
		CString txt; txt.Format("Conectado a COM%d   9600bps",m_GiNumCom);
		this->m_ctlStaticTexto.SetWindowText(txt);
	
		this->m_bPortOpen=TRUE;
		this->m_ctlButtonConectar.SetWindowText("Desconectar");

		//Configuramos el TRISB para funcionar con skybot v1.2
		this->m_pSerie->SGStore(TRISB, 0xe1);

		// Lanzamos el hilo de captura
		AfxBeginThread(LeerSensores, this);

	}
	
	else {


		this->m_bHiloEjecucion = FALSE;
		this->m_pSerie->Close();
		this->m_bPortOpen=FALSE;
		this->m_ctlButtonConectar.SetWindowText("Conectar");
		this->m_ctlStaticTexto.SetWindowText("");
		

	}

	this->UpdateData(TRUE);
	this->UpdateData(FALSE);
	
}

void CBotControlDlg::OnAlante() 
{

   
	if( this->m_bPortOpen == FALSE ) {
		AfxMessageBox("El puerto no está abierto");
		return;
	}

	
}

void CBotControlDlg::OnDerecha() 
{

	if( this->m_bPortOpen == FALSE ) {
		AfxMessageBox("El puerto no está abierto");
		return;
	}

	
}

void CBotControlDlg::OnAtras() 
{

	if( this->m_bPortOpen == FALSE ) {
		AfxMessageBox("El puerto no está abierto");
		return;
	}

	
}

void CBotControlDlg::OnIzquierda() 
{

	if( this->m_bPortOpen == FALSE ) {
		AfxMessageBox("El puerto no está abierto");
		return;
	}

	
}

