Applied-motion SV7-Q-EE Manuel d'utilisateur Page 17

  • Télécharger
  • Ajouter à mon manuel
  • Imprimer
  • Page
    / 19
  • Table des matières
  • MARQUE LIVRES
  • Noté. / 5. Basé sur avis des utilisateurs
Vue de la page 16
6/26/2010
9200032a3eSCLCommunicationReferenceManual Page17
Pollingiseasiertocodebutlessefficientbecauseyo umusteithersitinaloopwaitingforanexpected
responseorrunatimertoperiodicallycheckfordatacomingin.Sincethechoicedependsonyour
programmingstyleandtherequirementsofyourapplication,wepresentbothtechniques.
Pollingforanincomingpacket
ThesameUdpClientobjectthatyouusetosendpacketscanbeusedtoretrieveincomingresponsesfromthe
drive.TheAvailableproperty willbegreaterthanzeroifapackethasbeenreceived.Toretrieveapacket,
assigntheReceivepropertytoaBytearray.YoumustcreateanIPEndPoint objectinordertousetheReceive
property.
private void UDPpoll()
{
// you can call this from a timer event or a loop
if (udpClient.Available > 0) // is there a packet ready?
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
try
{
// Get the received packet. Receive method blocks
// until a message returns on this socket from a remote host,
// so always check .Available to see if a packet is ready.
Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
// strip opcode
Byte[] SCLstring = new byte[receiveBytes.Length - 2];
for (int i = 0; i < SCLstring.Length; i++)
SCLstring[i] = receiveBytes[i + 2];
string returnData = Encoding.ASCII.GetString(SCLstring);
AddToHistory(returnData);
}
catch (Exception ex)
{
// put your error handler here
Console.WriteLine(ex.ToString());
}
}
}
Creatingareceiveeventusingacallbackfunction
First,createafunctiontohandleincomingpackets.Thisfunctionmustcontaintwolocalobjects:aUdpClient
andanIPEndPoint.ThecallbackfunctionwillbepassedanIAsyncResultobjectthatcontainsareferenceto
theUDPconnection.ThelocalIPEn dPointobjectispassedtotheUDPClient’sEndReceivepropertytoretrieve
thepacket.
public void ReceiveCallback(IAsyncResult ar)
{
int opcode;
UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;
Byte[] receiveBytes = u.EndReceive(ar, ref e);
// get opcode
opcode = 256 * receiveBytes[0] + receiveBytes[1];
if (opcode == 7) // SCL response
{
string receiveString = Encoding.ASCII.GetString(receiveBytes);
Vue de la page 16
1 2 ... 12 13 14 15 16 17 18 19

Commentaires sur ces manuels

Pas de commentaire