/*@!Encoding:1252*/ includes { #include "Common.cin" #include "TcpUdpCommon.cin" } variables { UdpSocket gSocket; byte gRxBuffer[8192]; } word UdpOpenSocket() { dword i = 0; CHAR errorText[200]; if (EthGetAdapterStatus() != 2) // Not connected { writeLineEx(0, 3, "<%NODE_NAME%> Error: Adapter status not ok: %d!", EthGetAdapterStatus()); return INVALID_IP; } // Try to open socket do { gSocket = UdpSocket::Open(0, 0); // Open socket on any IP and Port if (gSocket.GetLastSocketError() != 0) { gSocket.GetLastSocketErrorAsString(errorText, elcount(errorText)); writeLineEx(0, 1, "<%NODE_NAME%> Error: could not open Udp socket: %s (%d)!", errorText, gSocket.GetLastSocketError()); } } while (gSocket.GetLastSocketError() != 0 && i++ < 9); if (gSocket.GetLastSocketError() != 0) { writeLineEx(0, 1, "<%NODE_NAME%> Error: could not open Udp socket!"); return gSocket.GetLastSocketError(); } else { writeLineEx(0, 1, "<%NODE_NAME%> Udp socket opened."); } return 0; } word UdpConnectTo(char Remote_IP[], word remotePort) { dword remoteIp; // Convert IP string to Number remoteIp = IpGetAddressAsNumber(Remote_IP); if (remoteIp == INVALID_IP) { writeLineEx(0, 1, "<%NODE_NAME%> Error: invalid server Ip address!"); return 1; } return UdpConnectTo(remoteIp, remotePort); } word UdpConnectTo(dword remoteIp, word remotePort) { long fehler; // Try to open a socket fehler = UdpOpenSocket(); if (fehler != 0) { gSocketState = ERROR; return fehler; } gRemoteIP = remoteIp; gRemotePort = remotePort; gSocketState = OK; return 0; } void UdpRecv() { int result; if (gSocketState != OK) { writeLineEx(0, 2, "UdpRecv: Socket status is not OK!"); return; } result = gSocket.ReceiveFrom(gRxBuffer, elcount(gRxBuffer)); if (result != 0) // Calling OnUdpReceive otherwise { gIpLastErr = gSocket.GetLastSocketError(); if (gIpLastErr != WSA_IO_PENDING) // Calling OnUdpReceive otherwise { gSocket.GetLastSocketErrorAsString(gIpLastErrStr, elcount(gIpLastErrStr)); writeLineEx(0, 2, "<%NODE_NAME%> UdpRecv Error (%d): %s", gIpLastErr, gIpLastErrStr); gSocket.Close(); gSocketState = CLOSED; } } return; } void UdpSnd(byte buffer[], word length) { //char str[20*3]; switch (gSocketState) { case CLOSED: UdpConnectTo(gRemoteIP, gRemotePort); if (gSocketState != OK) { writeLineEx(0, 2, "UdpSnd: Reconnecting failed!"); return; } case OK: break; default: writeLineEx(0, 2, "UdpSnd: Socket status is not OK!"); return; } //bin_to_strhex(buffer, str); //writeLineEx(0, 1, "<%NODE_NAME%> UdpSnd: %s (Länge: %d)", str, length); if (gSocket.SendTo(gRemoteIP, gRemotePort, buffer, length) != 0) { gIpLastErr = gSocket.GetLastSocketError(); if (gIpLastErr != WSA_IO_PENDING) { gSocket.GetLastSocketErrorAsString(gIpLastErrStr, elcount(gIpLastErrStr)); writeLineEx(0, 2, "<%NODE_NAME%> UdpSnd error (%d): %s", gIpLastErr, gIpLastErrStr); gSocket.Close(); gSocketState = CLOSED; } } }