Sei sulla pagina 1di 9

using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

//agregar
using System.Diagnostics;
using System.Runtime.InteropServices;
using MecaniqueUK;

// agregar
using System.IO;
using System.Net;
using System.Net.Sockets;

namespace Aplicacion_USB_HID
{

public partial class Form2 : Form
{
Int32 port = 13000;//iniia codigo del servidor
IPAddress localAddr = IPAddress.Parse("192.168.0.105");


Byte[] bytes = new Byte[256];
// String data = null;
//String perver;//variavle del dato que se enviara por el usb al ser
recivido por el servidor
static string datousb;

bool Binicio = false;//codigo servidor

static UInt32 controlador;
//Buffer carc;
int[] cadena = new int[32];

public Form2()
{
InitializeComponent();

}

public void inicio()
{


try
{
var server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
EscuchandoCliente(server);

}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
// server.Stop();
}// fin de try

} //fin de inicio


public async void EscuchandoCliente(TcpListener server)
{

// Enter the listening loop.
while (true)
{


var cliente = await server.AcceptTcpClientAsync();
MENSAJE_USB.Items.Add("Conectado");
procesar(cliente);

}

} //fin de escuchar cliente


public static async void procesar(TcpClient cliente)
{

var stream = cliente.GetStream();
var buffer = new byte[256];
var amountRead = await stream.ReadAsync(buffer, 0, 256);
var message = Encoding.ASCII.GetString(buffer, 0, amountRead);
listBox1.Items.Add("client sent: " + message);

// String data = null;

//data = data.ToUpper();

byte[] msg = System.Text.Encoding.ASCII.GetBytes(message);

// Send back a response.
stream.Write(msg, 0, msg.Length);
listBox1.Items.Add(Encoding.ASCII.GetString(buffer, 0, amountRead));
datousb = Encoding.ASCII.GetString(buffer, 0, amountRead);
//escribirmicro(0);
string dato = datousb;

byte[] BufferOUT = new byte[EasyHID.BUFFER_OUT_SIZE];
// BufferOUT[4] = 'r';
//for (int i = 1; (i < dato.Length) && (i < 32); i++)
//{
BufferOUT[1] = (byte)Convert.ToChar(datousb);
EasyHID.Write(controlador, BufferOUT);
System.Threading.Thread.Sleep(50);

// BufferOUT[i] = (byte)dato[i - 1];
//}
//EasyHID.Write(controlador, BufferOUT);
//System.Threading.Thread.Sleep(50);


//perver = Encoding.ASCII.GetString(buffer, 0, amountRead);





} //fin del hilo
//fin de la form1


private void Boton_Conectar_pic_Click(object sender, EventArgs e)
{
try
{
//MessageBox.Show("Aki si entra :D");
EasyHID.Connect(Handle);
//MessageBox.Show("Aki si entra :D");


if (EasyHID.IsAvailable(EasyHID.VENDOR_ID, EasyHID.PRODUCT_ID) ==
true)
{

habilitar();
MENSAJE_USB.Items.Clear();
MENSAJE_USB.Items.Add("Dispositivo USB Conectado!");
CONECTAR_PIC.Text = "DISPOSITIVO CONECTADO";
CONECTAR_PIC.BackColor = Color.LightSeaGreen;
CONECTAR_PIC.ForeColor = Color.Black;

// EasyHID.SetReadNotify(handle, true);
//controlador = handle;
MENSAJE_USB.Items.Add("Puede usar el Dispositivo.");


}
else
{
MENSAJE_USB.Items.Clear();
MENSAJE_USB.Items.Add("Dispositivo no encontrado,");
MENSAJE_USB.Items.Add("controlador conectado...");
CONECTAR_PIC.Text = "CONTROLADOR CONECTADO";
CONECTAR_PIC.BackColor = Color.GreenYellow;
CONECTAR_PIC.ForeColor = Color.Black;
}
}
catch { MENSAJE_USB.Items.Add("imposible conectar" + e); }



}//fin del boton

private void habilitar()
{
/*
OUT_DIGITAL_1.Enabled = true;
OUT_DIGITAL_2.Enabled = true;
OUT_DIGITAL_3.Enabled = true;
OUT_DIGITAL_4.Enabled = true;
OUT_DIGITAL_5.Enabled = true;
OUT_DIGITAL_6.Enabled = true;
OUT_DIGITAL_7.Enabled = true;
OUT_DIGITAL_8.Enabled = true;
*/
//MENSAJE_USB.Enabled = true;
}
private void deshabilitar()
{
/*
OUT_DIGITAL_1.Enabled = false;
OUT_DIGITAL_2.Enabled = false;
OUT_DIGITAL_3.Enabled = false;
OUT_DIGITAL_4.Enabled = false;
OUT_DIGITAL_5.Enabled = false;
OUT_DIGITAL_6.Enabled = false;
OUT_DIGITAL_7.Enabled = false;
OUT_DIGITAL_8.Enabled = false;
*/
//MENSAJE_USB.Enabled = false;
}

private void MENSAJE_USB_TextChanged(object sender, EventArgs e)
{


}

protected override void WndProc(ref Message message)
{
if (message.Msg == EasyHID.WM_HID_EVENT)
{
switch (message.WParam.ToInt32())
{
case EasyHID.NOTIFY_PLUGGED:
Dispositivo_Conectado((UInt32)message.LParam.ToInt32());
break;
case EasyHID.NOTIFY_UNPLUGGED:
Dispositivo_desconectado((UInt32)message.LParam.ToInt32());
break;
case EasyHID.NOTIFY_READ:

Leer_pic((UInt32)message.LParam.ToInt32());

break;
}
}
base.WndProc(ref message);

if (Binicio == false)
{


inicio();
Binicio = true;
}



base.WndProc(ref message);
}
private void Dispositivo_Conectado(UInt32 handle)
{
if (EasyHID.GetVendorID(handle) == EasyHID.VENDOR_ID &&
EasyHID.GetProductID(handle) == EasyHID.PRODUCT_ID)
{
EasyHID.SetReadNotify(handle, true);
controlador = handle;
MENSAJE_USB.Items.Add("Puede usar el Dispositivo.");
}
}
private void Leer_pic(UInt32 In_handle)
{
byte [] BufferINP = new byte [EasyHID.BUFFER_IN_SIZE];



if ((EasyHID.Read(In_handle, out BufferINP)) == true)
{

string cadena="";
char car;


for (int x = 1; x < BufferINP.Length; x++)
{


car = Convert.ToChar(BufferINP[x]);
cadena = cadena + car;
}

// From string to byte RAUL RAUL RAUL RAUL !!!!!!!!
// byte[] buffer = BufferINP;

// From byte array to string
// (BufferINP, 0, BufferINP.Length);
// s = Encoding.ASCII.GetString(BufferINP, 0, BufferINP.Length);
// s = en GetString(BufferINP, 0, BufferINP.Length);


// System.Threading.Thread.Sleep(1);


// s =
Convert.ToString(Convert.ToChar(BufferINP,0,BufferINP.Length));
// s= D
MENSAJE_USB.Items.Add(cadena.ToString());

}
}

private void Dispositivo_desconectado(UInt32 handle)
{
if (EasyHID.GetVendorID(handle) == EasyHID.VENDOR_ID &&
EasyHID.GetProductID(handle) == EasyHID.PRODUCT_ID)
{
MENSAJE_USB.Items.Clear();
MENSAJE_USB.Items.Add("Dispositivo USB, desconectado.");
CONECTAR_PIC.BackColor = Color.Red;
CONECTAR_PIC.ForeColor = Color.White;
CONECTAR_PIC.Text = "CONECTAR DISPOSITIVO";
deshabilitar();
EasyHID.Disconnect();
}
}



private void Leer_Mensaje_Pic_Click(object sender, EventArgs e)
{
string dato = datousb;

byte [] BufferOUT = new byte [EasyHID.BUFFER_OUT_SIZE];
// BufferOUT[4] = 'r';
for(int i=1;(i<dato.Length) &&(i<32);i++){


BufferOUT[i] = (byte)dato[i-1];

//ufferOUT[i]= Convert.ToByte(Convert.ToChar(dato[i]));


}
//BufferOUT.All= Co.("raul");
//BufferOUT[]= conv ("hola");
//BufferOUT[1] = (string)"hola"; // 65--> A
EasyHID.Write(controlador, BufferOUT);
System.Threading.Thread.Sleep(50);



//BufferOUT[1] = (byte)'o'; // 65--> A
//EasyHID.Write(controlador, BufferOUT);
//System.Threading.Thread.Sleep(50);

//BufferOUT[1] = (byte)'l'; // 65--> A
//EasyHID.Write(controlador, BufferOUT);
//System.Threading.Thread.Sleep(50);

//BufferOUT[1] = (byte)'a'; // 65--> A
//EasyHID.Write(controlador, BufferOUT);
//System.Threading.Thread.Sleep(50);

//BufferOUT[1] = (byte)' '; // 65--> A
//EasyHID.Write(controlador, BufferOUT);
//System.Threading.Thread.Sleep(50);

//BufferOUT[1] = (byte)'R'; // 65--> A
//EasyHID.Write(controlador, BufferOUT);
//System.Threading.Thread.Sleep(50);

//BufferOUT[1] = (byte)'a'; // 65--> A
//EasyHID.Write(controlador, BufferOUT);

//System.Threading.Thread.Sleep(50);


//BufferOUT[1] = (byte)'a'; // 65--> A
//EasyHID.Write(controlador, BufferOUT);
//System.Threading.Thread.Sleep(50);

//BufferOUT[1] = (byte)'u'; // 65--> A
//EasyHID.Write(controlador, BufferOUT);

//System.Threading.Thread.Sleep(50);


//BufferOUT[1] = (byte)'l'; // 65--> A
//EasyHID.Write(controlador, BufferOUT);
} //fin de la funcion



private void USB_HID_FormClosed(object sender, FormClosedEventArgs e)
{
EasyHID.Disconnect();
}







} //fin de la forma

//**********************************************************************************
*******************************************



class EasyHID
{
// HID specific...
public const UInt32 VENDOR_ID = 0x1234; //1234 HEX
public const UInt32 PRODUCT_ID = 0x0001; //0001 HEX
public const int BUFFER_IN_SIZE = 32;
public const int BUFFER_OUT_SIZE = 32;

// HID events...
private const int WM_APP = 0x8000;
public const int WM_HID_EVENT = WM_APP + 200;
public const int NOTIFY_PLUGGED = 0x0001;
public const int NOTIFY_UNPLUGGED = 0x0002;
public const int NOTIFY_CHANGED = 0x0003;
public const int NOTIFY_READ = 0x0004;

// HID interface...
[DllImport("mcHID.dll")]
public static extern bool Connect(IntPtr pHostWin);
[DllImport("mcHID.dll")]
public static extern bool Disconnect();
[DllImport("mcHID.dll")]
public static extern UInt32 GetItem(UInt32 pIndex);
[DllImport("mcHID.dll")]
public static extern UInt32 GetItemCount();
[DllImport("mcHID.dll")]
public static extern bool Read(UInt32 pHandle, IntPtr pData);
[DllImport("mcHID.dll")]
private static extern bool Write(UInt32 pHandle, IntPtr pData);
[DllImport("mcHID.dll")]
private static extern bool ReadEx(UInt32 pVendorId, UInt32 pProductId,
IntPtr pData);
[DllImport("mcHID.dll")]
private static extern bool WriteEx(UInt32 pVendorId, UInt32 pProductId,
IntPtr pData);
[DllImport("mcHID.dll")]
public static extern UInt32 GetHandle(UInt32 pVendorID, UInt32 pProductId);
[DllImport("mcHID.dll")]
public static extern UInt32 GetVendorID(UInt32 pHandle);
[DllImport("mcHID.dll")]
public static extern UInt32 GetProductID(UInt32 pHandle);
[DllImport("mcHID.dll")]
public static extern UInt32 GetVersionID(UInt32 pHandle);
[DllImport("mcHID.dll")]
public static extern UInt32 GetInputReportLength(UInt32 pHandle);
[DllImport("mcHID.dll")]
public static extern UInt32 GetOutputReportLength(UInt32 pHandle);
[DllImport("mcHID.dll")]
public static extern void SetReadNotify(UInt32 pHandle, bool pValue);
[DllImport("mcHID.dll")]
public static extern bool IsReadNotifyEnabled(UInt32 pHandle);
[DllImport("mcHID.dll")]
public static extern bool IsAvailable(UInt32 pVendorId, UInt32 pProductId);

// Managed version of the read/write functions.
public static bool Read(UInt32 pHandle, out byte[] pData)
{
IntPtr unmanagedBuffer = Marshal.AllocHGlobal(BUFFER_IN_SIZE);
bool result = Read(pHandle, unmanagedBuffer);

try { pData = new byte[BUFFER_IN_SIZE]; Marshal.Copy(unmanagedBuffer,
pData, 0, BUFFER_IN_SIZE); }
finally { Marshal.FreeHGlobal(unmanagedBuffer); }

return result;
}

public static bool Write(UInt32 pHandle, byte[] pData)
{
IntPtr unmanagedBuffer = Marshal.AllocHGlobal(BUFFER_OUT_SIZE);
bool result;

try { Marshal.Copy(pData, 0, unmanagedBuffer, BUFFER_OUT_SIZE); result =
Write(pHandle, unmanagedBuffer); }
finally { Marshal.FreeHGlobal(unmanagedBuffer); }

return result;
}

} //fin clase





} //fin del spacename

Potrebbero piacerti anche