diff --git a/C/User Guide (C).txt b/C/User Guide (C).txt deleted file mode 100644 index 7fcc94e..0000000 --- a/C/User Guide (C).txt +++ /dev/null @@ -1,192 +0,0 @@ -X-Plane Connect-C (XPC-C) Readme - -DESCRIPTION - XPC-C is a series of C functions that facilitate communication with X-Plane. - ------------------------------------ -SETUP - Before using XPC Functions you must - 1. Copy the folder "[XPC Directory]/xpcPlugin/XPlaneConnect" to the "[X-Plane Directory]/Resources/plugins" directory. - 2. Put in X-Plane CD 1 or X-Plane USB Key. - 3. Start X-Plane. - 4. #include "xplaneConnect.h" - ------------------------------------ -BASIC FUNCTIONS - 1. openUDP opens a UDP Socket for communication. This is used to send data or receive. - INPUT: - port (unsigned short): Port Number (ex:49067) - xpIP (char *): IP Address of the computer running x-plane - xpPort (unsigned short): Port number that the X-Plane/ xpcPlugin Receives on (send -1 for default (49009), Typically xpcPlugin is 49009) - - OUTPUT: - socket (xpcSocket): The Opened Socket - - USE: - unsigned short portNumber = 49067; - struct xpcSocket theSocket = openUDP(portNumber, “127.0.0.1”, 49009); - - 2. closeUDP closes an opened UDP Socket for communication. This is to be done after the program has finished using that socket. Use opedUDP to open socket. - INPUT: - socket (xpcSocket): The Opened Socket - - USE: - closeUDP(theSocket); - - 3. setCONN sets the return port for requested datarefs. - INPUT: - socket (xpcSocket): Socket to use to send the command - recPort (unsigned Short): Port number for requested dataref values to be sent to - - OUTPUT: - status (short): 0 if successful - - USE: - char IP[16] = "127.0.0.1"; - struct xpcSocket theSocket = openUDP(49067); - setCONN(theSocket,IP,49009,49022); // Sets receive address to 49022; - - 4. pauseSim pauses/resumes the x-plane simulation - INPUT: - socket (xpcSocket): Socket to use to send the command - pause (short): 1=Pause, 0=Resume - - OUTPUT: - status (short): 0 if successful - - USE: - char IP[16] = "127.0.0.1"; - struct xpcSocket theSocket = openUDP(49067); - pauseSim(theSocket, IP, 49009, 1); - - 5. sendDATA set the value of a state in the "DATA Input & Output" Table - INPUT: - socket (xpcSocket): Socket to use to send the command - dataArray (float[][9]): Array of data to be sent. The first element of each row is the item # (corresponding to the number on the X-Plane "DATA Input & Output" Screen). Send -999 to leave the value unchanged. - rows (unsigned short): Number of rows of data being sent - - OUTPUT: - status (short): 0 if successful - - USE: - char IP[16] = "127.0.0.1"; - struct xpcSocket theSocket = openUDP(49067); - float data[] = {{14, 1, -999, -999, -999, -999, -999, -999, -999},{25, 0.8, 0.8, -999, -999, -999, -999, -999, -999}}; // Gear and Throttle - sendDATA(theSocket,IP,49009,data,2); - - 6. sendPOSI set the position of an aircraft - INPUT: - socket (xpcSocket): Socket to use to send the command - ACNum (short): Number of aircraft to be moved, use 0 for main aircraft (ownPlane). - numArgs (short): Number of Arguments to be sent (size of position array) - position (float []): Arguments corresponding to aircrafts position - position[0] = Latitude - position[1] = Longitude - position[2] = Altitude (m MSL) - position[3] = Roll (deg) - position[4] = Pitch (deg) - position[5] = True Heading (deg) - position[6] = Gear (0=up, 1=down) - - OUTPUT: - status (short): 0 if successful - - USE: - char IP[16] = "127.0.0.1"; - struct xpcSocket theSocket = openUDP(49067); - float posit[] = {37.5242422, -122.06899, 2500, 0, 0, 0, 1}; - sendPOSI(theSocket, IP, 49009, 7, posit); - - 7. sendCTRL send control commands to the aircraft - INPUT: - socket (xpcSocket): Socket to use to send the command - numArgs (short): Number of Arguments to be sent (size of control array) - control (float []): Arguments corresponding to aircraft control command - control[0] = Latitudinal Stick [-1,1] - control[1] = Longitudinal Stick [-1,1] - control[2] = Pedal [-1, 1] - control[3] = Throttle [-1, 1] - control[4] = Gear (0=up, 1=down) - control[5] = Flaps [0, 1] - - OUTPUT: - status (short): 0 if successful - - USE: - char IP[16] = "127.0.0.1"; - struct xpcSocket theSocket = openUDP(49067); - float ctrl[] = {0, 0, 0, 0.8, 0, 1}; - sendCTRL(theSocket, IP, 49009, 6, ctrl); - - 8. sendDREF set the value of a specific dataref. Dataref list found at http://www.xsquawkbox.net/xpsdk/docs/DataRefs.html - INPUT: - socket (xpcSocket): Socket to use to send the command - dataRef (char *): Dataref to be set (with or without "sim/" preceeding it) - length (short): length of dataref string - values (float *): Array of values to be sent - length2 (short): Number of values in values array - - OUTPUT: - status (short): 0 if successful - - USE: - char IP[16] = "127.0.0.1"; - struct xpcSocket theSocket = openUDP(49067); - char theDREF[] = "cockpit/switches/gear_handle_status"; - float value = 1; - sendDREF(theSocket, IP, 49009, theDREF, strlen(theDREF), &value, 1); - - 9. requestDREF Request the value of specific dref(s). Dataref list found at http://www.xsquawkbox.net/xpsdk/docs/DataRefs.html - INPUT: - outSocket (xpcSocket): Socket to use to send the command - inSocket (xpcSocket): Socket to use to receive the result - DREFArray (char[][100]): Array of DataRefs to be requested - DREFSizes (int[]): Array of string lengths for each DataRef in DREFArray - listLength (short): Number of DataRefs in DREFArray - result (*float[]): Array of pointers to the values returned - arrayLen (short[]): Array where each element corresponds to the number of elements in the float array. - - OUTPUT: - length (short): Number of Values Returned - - USE: - char IP[16] = "127.0.0.1"; - struct xpcSocket theSocket = openUDP(49067); - char DREFArray[][100] = {"sim/cockpit/switches/gear_handle_status"}; - requestDREF(theSocket, IP, 49009, DREFArray, strlen(DREFArray[0]),1); - - 10. sendTEXT write some text to the screen. - INPUT: - outSocket (xpcSocket): Socket to use to send the command - message (char*): The string to be wrote to the screen - x (int): The x position where the text will be written. Set to -1 to use default position. - y (int): The y position where the text will be written. Set to -1 to use default position. - ------------------------------------ -ADVANCED FUNCTIONS (These are mostly used by the xpcPlugin to read requests) - 1. sendUDP - 2. readUDP - 3. readDATA - 4. parseDATA - 5. readPOSI - 6. parsePOSI - 7. readCTRL - 8. parseCTRL - 9. readRequest - 10. parseRequest - 11. parseDREF - 12. readDREF - ------------------------------------ -PLANNED FUNCTIONS - 1. sendVIEW - 2. parseVIEW - 3. readVIEW - 4. sendWYPT - 5. parseWYPT - 6. readWYPT - 7. selectDATA - ------------------------------------ -CONTACT - Email Christopher Teubert (christopher.a.teubert@nasa.gov) with any questions. diff --git a/C/src/xplaneConnect.c b/C/src/xplaneConnect.c index 7dae28b..ce65c76 100755 --- a/C/src/xplaneConnect.c +++ b/C/src/xplaneConnect.c @@ -1,734 +1,675 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. // -// xPlaneConnect.c Beta +//DISCLAIMERS +// No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, +// EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT +// THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY +// THAT THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, +// WILL CONFORM TO THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN +// ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, +// HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS RESULTING FROM USE OF THE SUBJECT +// SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING +// THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS." +// +// Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST THE UNITED STATES +// GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF +// RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES +// OR LOSSES ARISING FROM SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING +// FROM, RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS THE +// UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, +// TO THE EXTENT PERMITTED BY LAW. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE +// IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT. + +// X-Plane Connect Client // // DESCRIPTION -// XPLANECONNECT (XPC) Facilitates Communication to and from the XPCPlugin -// -// REQUIREMENTS -// 1. X-Plane Version 9.0 or newer (untested on previous versions) -// 2. XPCPlugin.xpl-must be placed in [X-Plane Directory]/Resources/plugins -// 3. OS X 10.8 or newer (untested on previous versions) +// Communicates with the XPC plugin to facilitate controling and gathering data from X-Plane. // // INSTRUCTIONS -// 1. Include the header "xplaneConnect.h" -// EXAMPLE: #include "xplaneConnect.h" -// 2. Open UDP Socket using openUDP -// EXAMPLE: struct xpcSocket theSocket = openUDP(port_number); -// NOTE: Do not send/receive on the same socket -// 3. Use functions described below -// 4. Close UDP Socket using closeUDP -// -// NOTICES: -// Copyright ã 2013-2014 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. -// -// DISCLAIMERS -// No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS." -// -// Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT. -// -// X-Plane API -// Copyright (c) 2008, Sandy Barbour and Ben Supnik All rights reserved. -// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -// * Neither the names of the authors nor that of X-Plane or Laminar Research may be used to endorse or promote products derived from this software without specific prior written permission from the authors or Laminar Research, respectively. -// -// X-Plane API SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// See Readme.md in the root of this repository or the wiki hosted on GitHub at +// https://github.com/nasa/XPlaneConnect/wiki for requirements, installation instructions, +// and detailed documentation. // // CONTACT // For questions email Christopher Teubert (christopher.a.teubert@nasa.gov) // -// TO DO -// 1. Update SelectData -// 2. RequestDREF: look into removing DREFSizes -// -// BEGIN CODE +// CONTRIBUTORS +// CT: Christopher Teubert (christopher.a.teubert@nasa.gov) +// JW: Jason Watkins (jason.w.watkins@nasa.gov) +#include "xplaneConnect.h" +#include +#include #include #include -#include #include #include #include -#include -#include "xplaneConnect.h" -#ifdef _WIN32 /* WIN32 SYSTEM */ - #include - #define strcasecmp _stricmp - #define strncasecmp _strnicmp - #define snprintf sprintf_s - #define socklen_t int +int sendUDP(XPCSocket sock, char buffer[], int len); +int readUDP(XPCSocket sock, char buffer[], int len); +int sendDREFRequest(XPCSocket sock, const char* drefs[], unsigned char count); +int getDREFResponse(XPCSocket sock, float* values[], unsigned char count, int sizes[]); - void usleep(__int64 usec) - { // From http://www.c-plusplus.de/forum/109539-full - HANDLE timer; - LARGE_INTEGER ft; - - ft.QuadPart = -(10*usec); // Convert to 100 nanosecond interval, negative value indicates relative time - - timer = CreateWaitableTimer(NULL, TRUE, NULL); - SetWaitableTimer(timer, &ft, 0, NULL, NULL, 0); - WaitForSingleObject(timer, INFINITE); - CloseHandle(timer); - } -#endif - -short errorReport(char *functionName, char *errorMessage); -short sendRequest(struct xpcSocket recfd, char DREFArray[][100], short DREFSizes[], short listLength); - -short errorReport(char *functionName, char *errorMessage) +void printError(char *functionName, char *format, ...) { - printf("ERROR: %s-%s\n", functionName, errorMessage); - return -1; + va_list args; + va_start(args, format); + + printf("[%s] ERROR: ", functionName); + vprintf(format, args); + printf("\n"); + + va_end(args); } -struct xpcSocket openUDP(unsigned short port_number, const char *xpIP, unsigned short xpPort) +/*****************************************************************************/ +/**** Low Level UDP functions ****/ +/*****************************************************************************/ +XPCSocket openUDP(const char *xpIP) { - struct xpcSocket theSocket; - struct sockaddr_in server; - -#if (__APPLE__ || __linux) - struct timeval tv; - int optval = 1; -#endif - - // Setup Port - server.sin_family = AF_INET; - server.sin_addr.s_addr = INADDR_ANY; - server.sin_port = htons(port_number); - - // Set X-Plane Port and IP - if (strcasecmp(xpIP,"localhost") == 0) // IP - { - strncpy(theSocket.xpIP,"127.0.0.1",9); // Default - } - else - { - memcpy(theSocket.xpIP,xpIP,(size_t) fminl(strlen(xpIP),16)); - } - - if (xpPort <= 0) // Default Port - { - theSocket.xpPort = 49009; // Default - } - else - { - theSocket.xpPort = xpPort; - } - -#ifdef _WIN32 - WSADATA wsa; - if (WSAStartup(MAKEWORD(2,2),&wsa) != 0) - { - perror("ERROR: openUDP- "); - return theSocket; - //ERROR IN Socket Message - } - - if ((theSocket.sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) - { - perror("ERROR: openUDP- "); - return theSocket; - //ERROR IN Socket Message - } - - if (bind(theSocket.sock, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR) - { - perror("ERROR: openUDP- "); - return theSocket; - //ERROR IN Socket Message - } -#elif (__APPLE__ || __linux) - // Create a SOCKET - if ((theSocket.sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) - { - perror((char*) "ERROR: openUDP- "); - return theSocket; - } - - // Options - setsockopt(theSocket.sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); - setsockopt(theSocket.sock, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)); - - //Bind - if ( bind(theSocket.sock, (struct sockaddr *) &server, sizeof(server)) == -1) - { - perror( (char*) "ERROR: openUDP- "); - return theSocket; - } -#endif - - //Set Timout - int usTimeOut = 500; - -#ifdef _WIN32 - DWORD msTimeOutWin = 1; // Minimum socket timeout in Windows is 1ms - setsockopt(theSocket.sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&msTimeOutWin, sizeof(msTimeOutWin)); -#else - tv.tv_sec = 0; /* Sec Timeout */ - tv.tv_usec = usTimeOut; // Microsec Timeout - setsockopt(theSocket.sock, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval)); -#endif - - return theSocket; + return aopenUDP(xpIP, 49009, 0); } -void closeUDP(struct xpcSocket socketNumber) +XPCSocket aopenUDP(const char *xpIP, unsigned short xpPort, unsigned short port) { -#ifdef _WIN32 - closesocket(socketNumber.sock); -#elif (__APPLE__ || __linux) - close(socketNumber.sock); -#endif -} - -short sendUDP(struct xpcSocket recfd, char my_message[], short messageLength) -{ - struct sockaddr_in servaddr; - - my_message[4] = (char) messageLength; - - // Preconditions - if (messageLength <= 0)// Positive Message Length + XPCSocket sock; + + // Setup Port + struct sockaddr_in recvaddr; + recvaddr.sin_family = AF_INET; + recvaddr.sin_addr.s_addr = INADDR_ANY; + recvaddr.sin_port = htons(port); + + // Set X-Plane Port and IP + if (strcmp(xpIP, "localhost") == 0) { - return errorReport("sendUDP", "message length must be positive >0"); + xpIP = "127.0.0.1"; } - - // Code - servaddr.sin_family = AF_INET; - servaddr.sin_port = htons(recfd.xpPort); - servaddr.sin_addr.s_addr = inet_addr(recfd.xpIP); - + strncpy(sock.xpIP, xpIP, 16); + sock.xpPort = xpPort == 0 ? 49009 : xpPort; + #ifdef _WIN32 - const char on = 1; -#else - int on=1; -#endif - - setsockopt(recfd.sock, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)); - - if (sendto(recfd.sock, my_message, (int) messageLength, 0, (const struct sockaddr *) &servaddr, sizeof(servaddr))<0) - { - perror("ERROR: sendUDP-"); - exit(EXIT_FAILURE); - } - - return 0; -} - -short sendDATA(struct xpcSocket recfd, float dataRef[][9], unsigned short rows) -{ - int i; - unsigned short length = rows*9*sizeof(float) + 5; - char message[5000]; - unsigned short step = 9*sizeof(float); - - strncpy(message,"DATA",4); - - for (i=0;i xpc_WYPT_CLR) +#endif + + if ((sock.sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { + printError("OpenUDP", "Socket creation failed"); + exit(EXIT_FAILURE); + } + if (bind(sock.sock, (struct sockaddr*)&recvaddr, sizeof(recvaddr)) == -1) + { + printError("OpenUDP", "Socket bind failed"); + exit(EXIT_FAILURE); + } + + // Set timeout to 100ms +#ifdef _WIN32 + DWORD timeout = 100; +#else + struct timeval timeout; + timeout.tv_sec = 0; + timeout.tv_usec = 100000; +#endif + if (setsockopt(sock.sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)) < 0) + { + printError("OpenUDP", "Failed to set timeout"); + } + return sock; +} + +void closeUDP(XPCSocket sock) +{ +#ifdef _WIN32 + int result = closesocket(sock.sock); +#else + int result = close(sock.sock); +#endif + if (result < 0) + { + printError("closeUDP", "Failed to close socket"); + exit(EXIT_FAILURE); + } +} + +/// Sends the given data to the X-Plane plugin. +/// +/// \param sock The socket to use to send the data. +/// \param buffer A pointer to the data to send. +/// \param len The number of bytes to send. +/// \returns If an error occurs, a negative number. Otehrwise, the number of bytes sent. +int sendUDP(XPCSocket sock, char buffer[], int len) +{ + // Preconditions + if (len <= 0) + { + printError("sendUDP", "Message length must be positive."); return -1; } - //Validate number of points - else if (numPoints > 19) + + // Set up destination address + struct sockaddr_in dst; + dst.sin_family = AF_INET; + dst.sin_port = htons(sock.xpPort); + inet_pton(AF_INET, sock.xpIP, &dst.sin_addr.s_addr); + + int result = sendto(sock.sock, buffer, len, 0, (const struct sockaddr*)&dst, sizeof(dst)); + if (result < 0) { + printError("sendUDP", "Send operation failed."); return -2; } - //Everything checks out; send the message - else + if (result < len) { - buf[5] = op; - buf[6] = numPoints; - size_t len = sizeof(float) * 3 * numPoints; - memcpy(buf + 7, points, len); - sendUDP(sendfd, buf, len + 7); - return 0; - } -} - -//READ -//---------------------------------------- -short readUDP(struct xpcSocket recfd, char *dataRef, struct sockaddr *recvaddr) -{ - socklen_t recvaddrlen = sizeof(*recvaddr); - int status = 0; - -#ifdef _WIN32 - // Windows readUDP needs the select command- minimum timeout is 1ms. - // Without this playback becomes choppy - - // Definitions - FD_SET stReadFDS; - FD_SET stExceptFDS; - struct timeval tv; - struct sockaddr_in testaddr; - int error = 0; - - // Setup for Select - FD_ZERO(&stReadFDS); - FD_SET(recfd.sock, &stReadFDS); - FD_ZERO(&stExceptFDS); - FD_SET(recfd.sock, &stExceptFDS); - tv.tv_sec = 0; /* Sec Timeout */ - tv.tv_usec = 250; // Microsec Timeout - - // Select Command - int tmp = select(-1, &stReadFDS, (FD_SET *)0, &stExceptFDS, &tv); - if (tmp <= 0) // No Data or error - { - return -1; - } - - // If no error: Read Data - recvaddrlen = sizeof(testaddr); - status = (int) recvfrom(recfd.sock,dataRef,5000,0,(SOCKADDR *) &testaddr,&recvaddrlen); - if (status == SOCKET_ERROR) - { - error = WSAGetLastError(); - } -#else - // For apple or linux-just read - will timeout in 0.5 ms - status = (int) recvfrom(recfd.sock,dataRef,5000,0,recvaddr,&recvaddrlen); -#endif - - return status; -} - -short readDATA(struct xpcSocket recfd, float dataRef[][9]) -{ - char buf[5000]; - int buflen = readUDP(recfd,buf, NULL); - - if (buf[0]!= '\0') - { - return parseDATA(buf, buflen, dataRef); - } - return -1; -} - -short readRequest(struct xpcSocket recfd, float *dataRef[], short arraySizes[], struct sockaddr *recvaddr) -{ - char buf[5000]; - readUDP(recfd,buf, recvaddr); - if (buf[0]!= '\0') - { - return parseRequest(buf, dataRef, arraySizes); - } - return -1; -} - -short readDREF(struct xpcSocket recfd, float *resultArray[], short arraySizes[]) -{ - char buf[5000] = {0}; - readUDP(recfd,buf, NULL); - - if (buf[0]!= '\0') - { - return parseRequest(buf, resultArray, arraySizes); - } - return -1; -} - -short readPOSI(struct xpcSocket recfd, float resultArray[], int arraySize, float *gear) -{ - char buf[5000] = {0}; - readUDP(recfd,buf, NULL); - - if (buf[0]!= '\0') // Buffer is not empty - { - return parsePOSI(buf, resultArray, arraySize, gear); - } - return -1; -} - -xpcCtrl readCTRL(struct xpcSocket recfd) -{ - xpcCtrl result; - char buf[5000] = { 0 }; - readUDP(recfd, buf, NULL); - - if (buf[0] != '\0') // Buffer is not empty - { - result = parseCTRL(buf); - } - else - { - result.aircraft = -1; - } - return result; -} - -//PARSE -//--------------------- -short parseDATA(const char my_message[], short messageLength, float dataRef[][9]) -{ - int i, j; - unsigned short totalColumns = ((messageLength-5)/36); - float tmp; - float data[20][9]; - - // Input Validation - - for (i=0;i xpc_WYPT_CLR) - { - result.op = -1; - } - //Validate number of points - else if (data[6] > 19) - { - result.op = -2; - } - //Everything checks out; copy the points into result - else - { - result.op = data[5]; - result.numPoints = data[6]; - char* ptr = data + 7; - for (size_t i = 0; i < result.numPoints; ++i) - { - result.points[i].latitude = *((float*)ptr); - result.points[i].longitude = *((float*)(ptr + 4)); - result.points[i].altitude = *((float*)(ptr + 8)); - ptr += 12; - } + printError("sendUDP", "Unexpected number of bytes sent."); } return result; } + +/// Reads a datagram from the specified socket. +/// +/// \param sock The socket to read from. +/// \param buffer A pointer to the location to store the data. +/// \param len The number of bytes to read. +/// \returns If an error occurs, a negative number. Otehrwise, the number of bytes read. +int readUDP(XPCSocket sock, char buffer[], int len) +{ +#ifdef _WIN32 + // Windows readUDP needs the select command- minimum timeout is 1ms. + // Without this playback becomes choppy + + // Definitions + FD_SET stReadFDS; + FD_SET stExceptFDS; + + // Setup for Select + FD_ZERO(&stReadFDS); + FD_SET(sock.sock, &stReadFDS); + FD_ZERO(&stExceptFDS); + FD_SET(sock.sock, &stExceptFDS); + + struct timeval tv; + tv.tv_sec = 0; + tv.tv_usec = 100000; + + // Select Command + int status = select(-1, &stReadFDS, (FD_SET*)0, &stExceptFDS, &tv); + if (status < 0) + { + printError("readUDP", "Select command error"); + return -1; + } + if (status == 0) + { + // No data + return 0; + } + status = recv(sock.sock, buffer, len, 0); +#else + // For apple or linux-just read - will timeout in 0.5 ms + int status = (int)recv(sock.sock, buffer, len, 0); +#endif + if (status < 0) + { + printError("readUDP", "Error reading socket"); + } + return status; +} +/*****************************************************************************/ +/**** End Low Level UDP functions ****/ +/*****************************************************************************/ + +/*****************************************************************************/ +/**** Configuration functions ****/ +/*****************************************************************************/ +int setCONN(XPCSocket* sock, unsigned short port) +{ + // Set up command + char buffer[32] = "CONN"; + memcpy(&buffer[5], &port, 2); + + // Send command + if (sendUDP(*sock, buffer, 7) < 0) + { + printError("setCONN", "Failed to send command"); + return -1; + } + + // Switch socket + closeUDP(*sock); + *sock = aopenUDP(sock->xpIP, sock->xpPort, port); + + // Read response + int result = readUDP(*sock, buffer, 32); + + if (result <= 0) + { + printError("setCONN", "Failed to read response"); + return -2; + } + if (strncmp(buffer, "CONF", 4) == 0) + { + // Response received succesfully. + return 0; + } + // Response incorrect + return -3; +} + +int pauseSim(XPCSocket sock, char pause) +{ + // Setup command + char buffer[6] = "SIMU"; + buffer[5] = pause == 0 ? 0 : 1; + // Send command + if (sendUDP(sock, buffer, 6) < 0) + { + printError("pauseSim", "Failed to send command"); + return -1; + } + return 0; +} +/*****************************************************************************/ +/**** End Configuration functions ****/ +/*****************************************************************************/ + +/*****************************************************************************/ +/**** X-Plane UDP Data functions ****/ +/*****************************************************************************/ +int sendDATA(XPCSocket sock, float data[][9], int rows) +{ + // Preconditions + // There are only 134 DATA rows in X-Plane. Realistically, clients probably + // shouldn't be trying to set nearly this much data at once anyway. + if (rows > 134) + { + printError("sendDATA", "Too many rows."); + return -1; + } + + // Setup command + // 5 byte header + 134 rows * 9 values * 4 bytes per value => 4829 byte max length. + char buffer[4829] = "DATA"; + int len = 5 + rows * 9 * sizeof(float); + unsigned short step = 9 * sizeof(float); + for (int i=0;i 134) + { + printError("sendDATA", "Too many rows."); + // Read as much as we can anyway + rows = 134; + } + + // Read data + char buffer[4829] = { 0 }; + int result = readUDP(sock, buffer, 5120); + if (result <= 0) + { + printError("readDATA", "Failed to read from socket."); + return -1; + } + // Validate data + int readRows = (result - 5) / 36; + if (readRows > rows) + { + printError("readDATA", "Read more rows than will fit in dataRef."); + // Copy as much data as we can anyway + rows = readRows; + } + + // Parse data + for (int i = 0; i < rows; ++i) + { + data[i][0] = buffer[5 + i * 36]; + memcpy(&data[i][1], &buffer[9 + i * 36], 8 * sizeof(float)); + } + return rows; +} +/*****************************************************************************/ +/**** End X-Plane UDP Data functions ****/ +/*****************************************************************************/ + +/*****************************************************************************/ +/**** DREF functions ****/ +/*****************************************************************************/ +int sendDREF(XPCSocket sock, const char* dref, float value[], int size) +{ + // Setup command + // 5 byte header + max 255 char dref name + max 255 values * 4 bytes per value = 1279 + unsigned char buffer[1279] = "DREF"; + int drefLen = strnlen(dref, 256); + if (drefLen > 255) + { + printError("setDREF", "dref length is too long. Must be less than 256 characters."); + return -1; + } + if (size > 255) + { + printError("setDREF", "size is too big. Must be less than 256."); + return -2; + } + int len = 7 + drefLen + size * sizeof(float); + + // Copy dref to buffer + buffer[5] = (unsigned char)drefLen; + memcpy(buffer + 6, dref, drefLen); + + // Copy values to buffer + buffer[6 + drefLen] = (unsigned char)size; + memcpy(buffer + 7 + drefLen, value, size * sizeof(float)); + + // Send command + if (sendUDP(sock, buffer, len) < 0) + { + printError("setDREF", "Failed to send command"); + return -3; + } + return 0; +} + +int sendDREFRequest(XPCSocket sock, const char* drefs[], unsigned char count) +{ + // Setup command + // 6 byte header + potentially 255 drefs, each 256 chars long. + // Easiest to just round to an even 2^16. + unsigned char buffer[65536] = "GETD"; + buffer[5] = count; + int len = 6; + for (int i = 0; i < count; ++i) + { + size_t drefLen = strnlen(drefs[i], 256); + if (drefLen > 255) + { + printError("getDREFs", "dref %d is too long.", i); + return -1; + } + buffer[len++] = (unsigned char)drefLen; + strncpy(buffer + len, drefs[i], drefLen); + len += drefLen; + } + // Send Command + if (sendUDP(sock, buffer, len) < 0) + { + printError("getDREFs", "Failed to send command"); + return -2; + } + return 0; +} + +int getDREFResponse(XPCSocket sock, float* values[], unsigned char count, int sizes[]) +{ + unsigned char buffer[65536]; + int result = readUDP(sock, buffer, 65536); + + if (result < 0) + { +#ifdef _WIN32 + printError("getDREFs", "Read operation failed. (%d)", WSAGetLastError()); +#else + printError("getDREFs", "Read operation failed."); +#endif + return -1; + } + + if (result < 6) + { + printError("getDREFs", "Response was too short. Expected at least 6 bytes, but only got %d.", result); + return -2; + } + if (buffer[5] != count) + { + printError("getDREFs", "Unexpected response size. Expected %d rows, got %d instead.", count, buffer[5]); + return -3; + } + + int cur = 6; + for (int i = 0; i < count; ++i) + { + int l = buffer[cur++]; + if (l > sizes[i]) + { + printError("getDREFs", "values is too small. Row had %d values, only room for %d.", l, sizes[i]); + // Copy as many values as we can anyway + memcpy(values[i], buffer + cur, sizes[i] * sizeof(float)); + } + else + { + memcpy(values[i], buffer + cur, l * sizeof(float)); + sizes[i] = l; + } + cur += l * sizeof(float); + } + return 0; +} + +int getDREF(XPCSocket sock, const char* dref, float values[], int* size) +{ + return getDREFs(sock, &dref, &values, 1, size); +} + +int getDREFs(XPCSocket sock, const char* drefs[], float* values[], unsigned char count, int sizes[]) +{ + // Send Command + int result = sendDREFRequest(sock, drefs, count); + if (result < 0) + { + // A error ocurred while sending. + // sendDREFRequest will print an error message, so just return. + return -1; + } + + // Read Response + if (getDREFResponse(sock, values, count, sizes) < 0) + { + // A error ocurred while reading the response. + // getDREFResponse will print an error message, so just return. + return -2; + } + return 0; +} +/*****************************************************************************/ +/**** End DREF functions ****/ +/*****************************************************************************/ + +/*****************************************************************************/ +/**** POSI functions ****/ +/*****************************************************************************/ +int sendPOSI(XPCSocket sock, float values[], int size, char ac) +{ + // Validate input + if (ac < 0 || ac > 20) + { + printError("sendPOSI", "aircraft should be a value between 0 and 20."); + return -1; + } + if (size < 1 || size > 7) + { + printError("sendPOSI", "size should be a value between 1 and 7."); + return -2; + } + + // Setup command + // 5 byte header + up to 7 values * 5 bytes each + unsigned char buffer[40] = "POSI"; + buffer[5] = ac; + for (int i = 0; i < 7; i++) + { + float val = -998; + + if (i < size) + { + val = values[i]; + } + *((float*)(buffer + 6 + i * 4)) = val; + } + + // Send Command + if (sendUDP(sock, buffer, 40) < 0) + { + printError("sendPOSI", "Failed to send command"); + return -3; + } + return 0; +} +/*****************************************************************************/ +/**** End POSI functions ****/ +/*****************************************************************************/ + +/*****************************************************************************/ +/**** CTRL functions ****/ +/*****************************************************************************/ +int sendCTRL(XPCSocket sock, float values[], int size, char ac) +{ + // Validate input + if (ac < 0 || ac > 20) + { + printError("sendCTRL", "aircraft should be a value between 0 and 20."); + return -1; + } + if (size < 1 || size > 7) + { + printError("sendCTRL", "size should be a value between 1 and 6."); + return -2; + } + + // Setup Command + // 5 byte header + 5 float values * 4 + 2 byte values + unsigned char buffer[27] = "CTRL"; + int cur = 5; + for (int i = 0; i < 6; i++) + { + float val = -998; + + if (i < size) + { + val = values[i]; + } + if (i == 4) + { + buffer[cur++] = val == -998 ? -1 : (unsigned char)val; + } + else + { + *((float*)(buffer + cur)) = val; + cur += sizeof(float); + } + } + buffer[26] = ac; + + // Send Command + if (sendUDP(sock, buffer, 27) < 0) + { + printError("sendCTRL", "Failed to send command"); + return -3; + } + return 0; +} +/*****************************************************************************/ +/**** End CTRL functions ****/ +/*****************************************************************************/ + +/*****************************************************************************/ +/**** Drawing functions ****/ +/*****************************************************************************/ +int sendTEXT(XPCSocket sock, char* msg, int x, int y) +{ + if (msg == NULL) + { + msg = ""; + } + size_t msgLen = strnlen(msg, 255); + // Input Validation + if (x < -1) + { + printError("sendTEXT", "x should be positive (or -1 for default)."); + // Technically, this should work, and may print something to the screen. + } + if (y < -1) + { + printError("sendTEXT", "y should be positive (or -1 for default)."); + // Negative y will never result in text being displayed. + return -1; + } + if (msgLen > 255) + { + printError("sendTEXT", "msg must be less than 255 bytes."); + return -2; + } + + // Setup command + // 5 byte header + 8 byte position + up to 256 byte message + char buffer[269] = "TEXT"; + size_t len = 14 + msgLen; + memcpy(buffer + 5, &x, sizeof(int)); + memcpy(buffer + 9, &y, sizeof(int)); + buffer[13] = msgLen; + strncpy(buffer + 14, msg, msgLen); + + // Send Command + if (sendUDP(sock, buffer, len) < 0) + { + printError("sendTEXT", "Failed to send command"); + return -3; + } + return 0; +} + +int sendWYPT(XPCSocket sock, WYPT_OP op, float points[], int count) +{ + // Input Validation + if (op < XPC_WYPT_ADD || op > XPC_WYPT_CLR) + { + printError("sendWYPT", "Unrecognized operation."); + return -1; + } + if (count > 255) + { + printError("sendWYPT", "Too many points. Must be less than 256."); + return -2; + } + + // Setup Command + // 7 byte header + 12 bytes * count + char buffer[3067] = "WYPT"; + buffer[5] = (unsigned char)op; + buffer[6] = (unsigned char)count; + size_t ptLen = sizeof(float) * 3 * count; + memcpy(buffer + 7, points, ptLen); + + // Send Command + if (sendUDP(sock, buffer, 40) < 0) + { + printError("sendWYPT", "Failed to send command"); + return -2; + } + return 0; +} +/*****************************************************************************/ +/**** End Drawing functions ****/ +/*****************************************************************************/ diff --git a/C/src/xplaneConnect.h b/C/src/xplaneConnect.h index 86b1615..e8520c3 100644 --- a/C/src/xplaneConnect.h +++ b/C/src/xplaneConnect.h @@ -1,119 +1,217 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. // -// xplaneConnect.h -// -// Created by Chris Teubert on 12/2/13. +//DISCLAIMERS +// No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, +// EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT +// THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY +// THAT THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, +// WILL CONFORM TO THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN +// ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, +// HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS RESULTING FROM USE OF THE SUBJECT +// SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING +// THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS." // +// Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST THE UNITED STATES +// GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF +// RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES +// OR LOSSES ARISING FROM SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING +// FROM, RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS THE +// UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, +// TO THE EXTENT PERMITTED BY LAW. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE +// IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT. +#ifndef xplaneConnect_h +#define xplaneConnect_h #ifdef __cplusplus - extern "C" { +extern "C" { #endif - #ifndef xplaneConnect_h - #define xplaneConnect_h +#include "stdlib.h" +#ifdef _WIN32 /* WIN32 SYSTEM */ +#include +#include +#pragma comment(lib,"ws2_32.lib") //Winsock Library +#elif (__APPLE__ || __linux) +#include +#include +#include +#include +#endif - #ifdef _WIN32 /* WIN32 SYSTEM */ - #include - #include - #pragma comment(lib,"ws2_32.lib") //Winsock Library - #elif (__APPLE__ || __linux) - #include - #include - #include - #include - #endif - - struct xpcSocket { - short open; - unsigned short port; - - // X-Plane IP and Port - char xpIP[16]; - unsigned short xpPort; - - #ifdef _WIN32 /* WIN32 SYSTEM */ - SOCKET sock; - #elif (__APPLE__ || __linux) //OS X/Linux - int sock; - #endif - }; +typedef struct xpcSocket +{ + unsigned short port; - typedef struct - { - float pitch; - float roll; - float yaw; - float throttle; - char gear; - float flaps; - char aircraft; - } xpcCtrl; + // X-Plane IP and Port + char xpIP[16]; + unsigned short xpPort; - typedef struct - { - double latitude; - double longitude; - double altitude; - } Waypoint; +#ifdef _WIN32 + SOCKET sock; +#else + int sock; +#endif +} XPCSocket; - typedef enum - { - xpc_WYPT_ADD = 1, - xpc_WYPT_DEL = 2, - xpc_WYPT_CLR = 3 - } WYPT_OP; +typedef enum +{ + XPC_WYPT_ADD = 1, + XPC_WYPT_DEL = 2, + XPC_WYPT_CLR = 3 +} WYPT_OP; + +// Low Level UDP Functions - typedef struct - { - WYPT_OP op; - Waypoint points[20]; - size_t numPoints; - } xpcWypt; - - // Basic Functions - struct xpcSocket openUDP(unsigned short port, const char *xpIP, unsigned short xpPort); - void closeUDP(struct xpcSocket); - short sendUDP(struct xpcSocket recfd, char my_message[], short messageLength); - short readUDP(struct xpcSocket recfd, char *dataRef, struct sockaddr *recvaddr); - - // Configuration - short setCONN(struct xpcSocket recfd, unsigned short recPort); - short pauseSim(struct xpcSocket recfd, short); - - // UDP DATA - short parseDATA(const char my_message[], short messageLength, float dataRef[][9]); - short readDATA(struct xpcSocket recfd, float dataRef[][9]); - short sendDATA(struct xpcSocket recfd, float dataRef[][9], unsigned short rows); - - // Position - short parsePOSI(const char my_message[], float resultArray[], int arraySize, float *gear); - short readPOSI(struct xpcSocket recfd, float resultArray[], int arraySize, float *gear); - short sendPOSI(struct xpcSocket recfd, short ACNum, short numArgs, float valueArray[]); - - // Controls - xpcCtrl parseCTRL(const char data[]); - xpcCtrl readCTRL(struct xpcSocket recfd); - short sendCTRL(struct xpcSocket recfd, short numArgs, float valueArray[]); - short sendpCTRL(struct xpcSocket recfd, short numArgs, float valueArray[], char acNum); - - // DREF Manipulation - short readDREF(struct xpcSocket recfd, float *resultArray[], short arraySizes[]); - short parseDREF(const char my_message[], char *dataRef, unsigned short *length_of_DREF, float *values, unsigned short *number_of_values); - short sendDREF(struct xpcSocket recfd, const char *dataRef, unsigned short length_of_DREF, float *values, unsigned short number_of_values); - short requestDREF(struct xpcSocket sendfd, struct xpcSocket recfd, char DREFArray[][100], short DREFSizes[], short listLength, float *resultArray[], short arraySizes[]); - int parseGETD(const char my_message[], char *DREFArray[], int DREFSizes[]); - short parseRequest(const char my_message[], float *resultArray[], short arraySizes[]); - short readRequest(struct xpcSocket recfd, float *dataRef[], short arraySizes[], struct sockaddr *recvaddr); +/// Opens a new connection to XPC on an OS chosen port. +/// +/// \param xpIP A string representing the IP address of the host running X-Plane. +/// \returns An XPCSocket struct representing the newly created connection. +XPCSocket openUDP(const char *xpIP); - // Waypoints - xpcWypt parseWYPT(const char data[]); - short sendWYPT(struct xpcSocket sendfd, WYPT_OP op, float points[], int numPoints); +/// Opens a new connection to XPC on the specified port. +/// +/// \param xpIP A string representing the IP address of the host running X-Plane. +/// \param xpPort The port of the X-Plane Connect plugin is listening on. Usually 49009. +/// \param port The local port to use when sending and receiving data from XPC. +/// \returns An XPCSocket struct representing the newly created connection. +XPCSocket aopenUDP(const char *xpIP, unsigned short xpPort, unsigned short port); - // Screen Text - short sendTEXT(struct xpcSocket sendfd, char* msg, int x, int y); +/// Closes the specified connection and releases resources associated with it. +/// +/// \param sock The socket to close. +void closeUDP(XPCSocket sock); +// Configuration + +/// Sets the port on which the socket sends and receives data. +/// +/// \param sock A pointer to the socket to change. +/// \param port The new port to use. +/// \returns 0 if successful, otherwise a negative value. +int setCONN(XPCSocket* sock, unsigned short port); + +/// Pause or unpause the simulation. +/// +/// \param sock The socket to use to send the command. +/// \param pause 0 to unpause the sim; any other value to pause. +/// \returns 0 if successful, otherwise a negative value. +int pauseSim(XPCSocket sock, char pause); - #endif //ifdef _h +// X-Plane UDP DATA + +/// Reads X-Plane data from the specified socket. +/// +/// \details This command is compatible with the X-Plane data API. +/// \param sock The socket to use to send the command. +/// \param data A 2D array of data rows to read into. +/// \param rows The number of rows in dataRef. +/// \returns 0 if successful, otherwise a negative value. +int readDATA(XPCSocket sock, float data[][9], int rows); + +/// Sends X-Plane data on the specified socket. +/// +/// \details This command is compatible with the X-Plane data API. +/// \param sock The socket to use to send the command. +/// \param data A 2D array of data rows to send. +/// \param rows The number of rows in dataRef. +/// \returns 0 if successful, otherwise a negative value. +int sendDATA(XPCSocket sock, float data[][9], int rows); + +// DREF Manipulation + +/// Sets the specified dataref to the specified value. +/// +/// \details dref names and their associated data types can be found on the XPSDK wiki at +/// http://www.xsquawkbox.net/xpsdk/docs/DataRefs.html. The size of values should match +/// the size given on that page. XPC currently sends all values as floats regardless of +/// the type described on the wiki. This doesn't cause any data loss for most datarefs. +/// \param sock The socket to use to send the command. +/// \param dref The name of the dataref to set. +/// \param values An array of values representing the data to set. +/// \param size The number of elements in values. +/// \returns 0 if successful, otherwise a negative value. +int sendDREF(XPCSocket sock, const char* dref, float value[], int size); + +/// Gets the value of the specified dataref. +/// +/// \details dref names and their associated data types can be found on the XPSDK wiki at +/// http://www.xsquawkbox.net/xpsdk/docs/DataRefs.html. The size of values should match +/// the size given on that page. XPC currently sends all values as floats regardless of +/// the type described on the wiki. This doesn't cause any data loss for most datarefs. +/// \param sock The socket to use to send the command. +/// \param dref The name of the dataref to get. +/// \param values The array in which the value of the dataref will be stored. +/// \param size The number of elements in values. The actual number of elements copied in will +/// be set when the function returns. +/// \returns 0 if successful, otherwise a negative value. +int getDREF(XPCSocket sock, const char* dref, float values[], int* size); + +/// Gets the value of the specified dataref. +/// +/// \details dref names and their associated data types can be found on the XPSDK wiki at +/// http://www.xsquawkbox.net/xpsdk/docs/DataRefs.html. The size of values should match +/// the size given on that page. XPC currently sends all values as floats regardless of +/// the type described on the wiki. This doesn't cause any data loss for most datarefs. +/// \param sock The socket to use to send the command. +/// \param drefs The names of the datarefs to get. +/// \param values A 2D array in which the values of the datarefs will be stored. +/// \param count The number of datarefs being requested. +/// \param size The number of elements in each row of values. The size of each row will be set +/// to the actual number of elements copied in for that row. +/// \returns 0 if successful, otherwise a negative value. +int getDREFs(XPCSocket sock, const char* drefs[], float* values[], unsigned char count, int sizes[]); +// Position + +/// Sets the position and orientation of the specified aircraft. +/// +/// \param sock The socket to use to send the command. +/// \param values An array representing position data about the aircraft. The format of values is +/// [Lat, Lon, Alt, Pitch, Roll, Yaw, Gear]. If less than 7 values are specified, +/// the unspecified values will be left unchanged. +/// \param size The number of elements in values. +/// \param ac The aircraft number to set the position of. 0 for the player aircraft. +/// \returns 0 if successful, otherwise a negative value. +int sendPOSI(XPCSocket sock, float values[], int size, char ac); + +// Controls + +/// Sets the control surfaces of the specified aircraft. +/// +/// \param sock The socket to use to send the command. +/// \param values An array representing position data about the aircraft. The format of values is +/// [Elevator, Aileron, Rudder, Throttle, Gear, Flaps]. If less than 6 values are +/// specified, the unspecified values will be left unchanged. +/// \param size The number of elements in values. +/// \param ac The aircraft number to set the control surfaces of. 0 for the player aircraft. +/// \returns 0 if successful, otherwise a negative value. +int sendCTRL(XPCSocket sock, float values[], int size, char ac); + +// Drawing + +/// Sets a string to be printed on the screen in X-Plane. +/// +/// \param sock The socket to use to send the command. +/// \param msg The message to print of the screen. +/// \param x The distance in pixels from the left edge of the screen to print the text. +/// \param y The distance in pixels from the bottom edge of the screen to print the top line of text. +/// \returns 0 if successful, otherwise a negative value. +int sendTEXT(XPCSocket sock, char* msg, int x, int y); + +/// Adds, removes, or clears a set of waypoints. If the command is clear, the points are ignored +/// and all points are removed. +/// +/// \param sock The socket to use to send the command. +/// \param op The operation to perform. 1=add, 2=remove, 3=clear. +/// \param points An array of values representing points. Each triplet in the array will be +/// interpreted as a (Lat, Lon, Alt) point. +/// \param count The number of points. There should be 3 * count elements in points. +/// \returns 0 if successful, otherwise a negative value. +int sendWYPT(XPCSocket sock, WYPT_OP op, float points[], int count); + #ifdef __cplusplus } #endif +#endif diff --git a/C/xpcExample/xpcExample/src/main.cpp b/C/xpcExample/xpcExample/src/main.cpp index f4ba86b..17b2a81 100644 --- a/C/xpcExample/xpcExample/src/main.cpp +++ b/C/xpcExample/xpcExample/src/main.cpp @@ -16,38 +16,17 @@ #define sleep(n) Sleep(n * 1000) #endif -int main() { - int i, j; - struct xpcSocket sendfd, readfd; - float data[4][9] = { 0 }; - char DREF[100] = { 0 }; - char DREFArray[100][100]; - char DREFArray2[100][100]; - short DREFSizes[100]; - float *recDATA[100]; - float POSI[9] = { 0.0 }; - float CTRL[5] = { 0.0 }; - float gear; - char IP[16] = "127.0.0.1"; //IP Address of computer running X-Plane - short PORT = 49009; //xpcPlugin Receiving port (usually 49009) +int main() +{ + printf("XPlaneConnect Example Script\n- Setting up Simulation\n"); - printf("xplaneconnect Example Script\n- Setting up Simulation\n"); - - for (i = 0; i < 100; i++) { - recDATA[i] = (float *)malloc(40 * sizeof(float)); - memset(DREFArray[i], 0, 100); - memset(DREFArray2[i], 0, 100); - } - - // Open Sockets - readfd = openUDP(49055, IP, PORT); //Open socket for receiving - sendfd = openUDP(49077, IP, PORT); //Open socket for sending - - // Set up Connection - setCONN(sendfd, 49055); // Setup so data will be received on port 49055 + // Open Socket + const char* IP = "127.0.0.1"; //IP Address of computer running X-Plane + XPCSocket sock = openUDP(IP); // Set Location/Orientation (sendPOSI) // Set Up Position Array + float POSI[9] = { 0.0 }; POSI[0] = 37.524; // Lat POSI[1] = -122.06899; // Lon POSI[2] = 2500; // Alt @@ -56,22 +35,30 @@ int main() { POSI[5] = 0; // Heading POSI[6] = 1; // Gear - sendPOSI(sendfd, 0, 7, POSI); + // Set position of the player aircraft + sendPOSI(sock, POSI, 7, 0); + POSI[0] = 37.52465; // Move a second aircraft a bit North of us POSI[4] = 20; // Give that aircraft a bit or right roll - sendPOSI(sendfd, 1, 7, POSI); + // Set position of a multiplayer aircraft + sendPOSI(sock, POSI, 7, 1); // Set Rates (sendDATA) - - for (i = 0; i < 4; i++) { // Set array to -999 - for (j = 0; j < 9; j++) data[i][j] = -999; + float data[3][9] = { 0 }; + // Initialize data values to -998 to not overwrite values. + for (int i = 0; i < 3; i++) + { + for (int j = 0; j < 9; j++) + { + data[i][j] = -998; + } } // Set up Data Array (first item in row is item number (example: 20=position) data[0][0] = 18; // Alpha data[0][1] = 0; data[0][3] = 0; - data[1][0] = 3;//21; //Velocity + data[1][0] = 3; //Velocity data[1][1] = 130; data[1][2] = 130; data[1][3] = 130; @@ -82,21 +69,19 @@ int main() { data[2][2] = 0; data[2][3] = 0; - sendDATA(sendfd, data, 3); // Velocity/Alpha/PQR + sendDATA(sock, data, 3); - // Set CTRL + // Set throttle on the player aircraft using sendCTRL + float CTRL[5] = { 0.0 }; CTRL[3] = 0.8; // Throttle - - sendCTRL(sendfd, 4, CTRL); + sendCTRL(sock, CTRL, 5, 0); // pauseSim - pauseSim(sendfd, 1); // Sending 1 to pause - - // Pause for 5 seconds - sleep(5); + pauseSim(sock, 1); // Sending 1 to pause + sleep(5); // Pause for 5 seconds // Unpause - pauseSim(sendfd, 0); // Sending 0 to unpause + pauseSim(sock, 0); // Sending 0 to unpause printf("- Resuming Simulation\n"); // Simulate for 10 seconds @@ -105,28 +90,34 @@ int main() { // SendDREF (Landing Gear) printf("- Stowing Landing Gear\n"); - strcpy(DREF, "sim/cockpit/switches/gear_handle_status"); // Gear handle data reference - DREFSizes[0] = strlen(DREF); - gear = 1; // Stow gear - - sendDREF(sendfd, DREF, DREFSizes[0], &gear, 1); // Set gear to stow + const char* dref = "sim/cockpit/switches/gear_handle_status"; // Gear handle data reference + float gear = 0; // Stow gear + sendDREF(sock, dref, &gear, 1); // Set gear to stow // Simulate for 10 seconds sleep(10); // Check Landing gear, Pause printf("- Confirming Gear Status\n"); - strcpy(DREFArray2[0], "sim/cockpit/switches/gear_handle_status"); - strcpy(DREFArray2[1], "sim/operation/override/override_planepath"); - for (i = 0; i < 2; i++) { - DREFSizes[i] = (int)strlen(DREFArray2[i]); + const char* drefs[2] = + { + "sim/cockpit/switches/gear_handle_status", + "sim/operation/override/override_planepath" + }; + float* results[2]; + int sizes[2] = { 20, 20 }; + for (int i = 0; i < 2; ++i) + { + results[i] = (float*)malloc(20 * sizeof(float)); } - requestDREF(sendfd, readfd, DREFArray2, DREFSizes, 2, recDATA, DREFSizes); // Request 2 values + getDREFs(sock, drefs, results, 2, sizes); - if (*(recDATA[0]) == 0) { + if (results[0][0] == 0) + { printf("\tGear Stowed\n"); } - else { + else + { printf("\tERROR: Gear Stowage unsuccessful\n"); } diff --git a/Docs/Interface Control Document.xlsx b/Docs/Interface Control Document.xlsx index d31f18b..c989b60 100644 Binary files a/Docs/Interface Control Document.xlsx and b/Docs/Interface Control Document.xlsx differ diff --git a/Java/Examples/BasicOperation/src/Main.java b/Java/Examples/BasicOperation/src/Main.java index 76f8805..1ab5bcc 100644 --- a/Java/Examples/BasicOperation/src/Main.java +++ b/Java/Examples/BasicOperation/src/Main.java @@ -82,7 +82,7 @@ public class Main "sim/cockpit/switches/gear_handle_status", "sim/operation/override/override_planepath" }; - float[][] results = xpc.requestDREFs(drefs); + float[][] results = xpc.getDREFs(drefs); if(results[0][0] == 1) { diff --git a/Java/src/XPlaneConnect.java b/Java/src/XPlaneConnect.java index 4215038..245e7c8 100644 --- a/Java/src/XPlaneConnect.java +++ b/Java/src/XPlaneConnect.java @@ -44,8 +44,7 @@ import java.util.Arrays; public class XPlaneConnect implements AutoCloseable { private static int clientNum; - private DatagramSocket outSocket; - private DatagramSocket inSocket; + private DatagramSocket socket; private InetAddress xplaneAddr; private int xplanePort; @@ -54,7 +53,7 @@ public class XPlaneConnect implements AutoCloseable * * @return The incoming port number. */ - public int getRecvPort() { return inSocket.getLocalPort(); } + public int getRecvPort() { return socket.getLocalPort(); } /** * Gets the port on which the client sends data to X-Plane. @@ -116,62 +115,55 @@ public class XPlaneConnect implements AutoCloseable */ public XPlaneConnect(int timeout) throws SocketException { - this.inSocket = new DatagramSocket(49008); - this.outSocket = new DatagramSocket(50000 + ++clientNum); + this.socket = new DatagramSocket(0); this.xplaneAddr = InetAddress.getLoopbackAddress(); this.xplanePort = 49009; - this.inSocket.setSoTimeout(timeout); + this.socket.setSoTimeout(timeout); } /** * Initializes a new instance of the {@code XPlaneConnect} class using the specified ports and X-Plane host. * - * @param port The port on which the X-Plane Connect plugin is sending data. - * @param xplaneHost The network host on which X-Plane is running. - * @param xplanePort The port on which the X-Plane Connect plugin is listening. + * @param xpHost The network host on which X-Plane is running. + * @param xpPort The port on which the X-Plane Connect plugin is listening. + * @param port The local port to use when sending and receiving data from XPC. * @throws java.net.SocketException If this instance is unable to bind to the specified port. * @throws java.net.UnknownHostException If the specified hostname can not be resolved. */ - public XPlaneConnect(int port, String xplaneHost, int xplanePort) + public XPlaneConnect(String xpHost, int xpPort, int port) throws java.net.SocketException, java.net.UnknownHostException { - this(port, xplaneHost, xplanePort, 100); + this(xpHost, xpPort, port, 100); } /** * Initializes a new instance of the {@code XPlaneConnect} class using the specified ports, hostname, and timeout. * - * @param port The port on which the X-Plane Connect plugin is sending data. - * @param xplaneHost The network host on which X-Plane is running. - * @param xplanePort The port on which the X-Plane Connect plugin is listening. + * @param xpHost The network host on which X-Plane is running. + * @param xpPort The port on which the X-Plane Connect plugin is listening. + * @param port The port on which the X-Plane Connect plugin is sending data. * @param timeout The time, in milliseconds, after which read attempts will timeout. * @throws java.net.SocketException If this instance is unable to bind to the specified port. * @throws java.net.UnknownHostException If the specified hostname can not be resolved. */ - public XPlaneConnect(int port, String xplaneHost, int xplanePort, int timeout) + public XPlaneConnect(String xpHost, int xpPort, int port, int timeout) throws java.net.SocketException, java.net.UnknownHostException { - this.inSocket = new DatagramSocket(port); - this.outSocket = new DatagramSocket(50000 + ++clientNum); - this.xplaneAddr = InetAddress.getByName(xplaneHost); - this.xplanePort = xplanePort; - this.inSocket.setSoTimeout(timeout); + this.socket = new DatagramSocket(port); + this.xplaneAddr = InetAddress.getByName(xpHost); + this.xplanePort = xpPort; + this.socket.setSoTimeout(timeout); } /** - * Closes the underlying inSocket. + * Closes the underlying socket. */ public void close() { - if(inSocket != null) + if(socket != null) { - inSocket.close(); - inSocket = null; - } - if(outSocket != null) - { - outSocket.close(); - outSocket = null; + socket.close(); + socket = null; } } @@ -181,14 +173,14 @@ public class XPlaneConnect implements AutoCloseable * @return The data send from X-Plane. * @throws IOException If the read operation fails */ - private byte[] readUDP() throws IOException //TODO: Store data in a class level buffer to account for partial messages + private byte[] readUDP() throws IOException { byte[] buffer = new byte[2048]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); try { - inSocket.receive(packet); - return Arrays.copyOf(buffer, buffer[4]); + socket.receive(packet); + return Arrays.copyOf(buffer, packet.getLength()); } catch (SocketTimeoutException ex) { @@ -197,22 +189,15 @@ public class XPlaneConnect implements AutoCloseable } /** - * Send the given data to the X-Plane plugin. This method automatically sets the length byte before sending, - * overwriting any value previously stored in @{code buffer[4]}. + * Send the given data to the X-Plane plugin. * * @param buffer The data to send. * @throws IOException If the send operation fails. */ private void sendUDP(byte[] buffer) throws IOException { - if(buffer.length < 5 || buffer.length > 255) - { - throw new IllegalArgumentException("buffer must be between 5 and 255 bytes long."); - } - buffer[4] = (byte)buffer.length; - DatagramPacket packet = new DatagramPacket(buffer, buffer.length, xplaneAddr, xplanePort); - outSocket.send(packet); + socket.send(packet); } /** @@ -236,9 +221,9 @@ public class XPlaneConnect implements AutoCloseable * @return A byte array representing data dependent on the dref requested. * @throws IOException If either the request or the response fails. */ - public float[] requestDREF(String dref) throws IOException + public float[] getDREF(String dref) throws IOException { - return requestDREFs(new String[]{dref})[0]; + return getDREFs(new String[] {dref})[0]; } /** @@ -248,7 +233,7 @@ public class XPlaneConnect implements AutoCloseable * @return A multidimensional array representing the data for each requested dref. * @throws IOException If either the request or the response fails. */ - public float[][] requestDREFs(String[] drefs) throws IOException + public float[][] getDREFs(String[] drefs) throws IOException { //Preconditions if(drefs == null || drefs.length == 0) @@ -329,7 +314,7 @@ public class XPlaneConnect implements AutoCloseable /** * Sends a command to X-Plane that sets the given DREF. * - * @param dref The name of the DREF to set. + * @param dref The name of the X-Plane dataref to set. * @param value An array of floating point values whose structure depends on the dref specified. * @throws IOException If the command cannot be sent. */ @@ -375,33 +360,33 @@ public class XPlaneConnect implements AutoCloseable } /** - * Sends command to X-Plane setting control surfaces on the player aircraft. + * Sends command to X-Plane setting control surfaces on the player ac. * - * @param ctrl

An array containing zero to six values representing control surface data as follows:

- *
    - *
  1. Latitudinal Stick [-1,1]
  2. - *
  3. Longitudinal Stick [-1,1]
  4. - *
  5. Rudder Pedals [-1, 1]
  6. - *
  7. Throttle [-1, 1]
  8. - *
  9. Gear (0=up, 1=down)
  10. - *
  11. Flaps [0, 1]
  12. - *
- *

- * If @{code ctrl} is less than 6 elements long, The missing elements will not be changed. To - * change values in the middle of the array without affecting the preceding values, set the - * preceding values to -998. - *

+ * @param values

An array containing zero to six values representing control surface data as follows:

+ *
    + *
  1. Latitudinal Stick [-1,1]
  2. + *
  3. Longitudinal Stick [-1,1]
  4. + *
  5. Rudder Pedals [-1, 1]
  6. + *
  7. Throttle [-1, 1]
  8. + *
  9. Gear (0=up, 1=down)
  10. + *
  11. Flaps [0, 1]
  12. + *
+ *

+ * If @{code ctrl} is less than 6 elements long, The missing elements will not be changed. To + * change values in the middle of the array without affecting the preceding values, set the + * preceding values to -998. + *

* @throws IOException If the command cannot be sent. */ - public void sendCTRL(float[] ctrl) throws IOException + public void sendCTRL(float[] values) throws IOException { - sendCTRL(ctrl, 0); + sendCTRL(values, 0); } /** - * Sends command to X-Plane setting control surfaces on the specified aircraft. + * Sends command to X-Plane setting control surfaces on the specified ac. * - * @param ctrl

An array containing zero to six values representing control surface data as follows:

+ * @param values

An array containing zero to six values representing control surface data as follows:

*
    *
  1. Latitudinal Stick [-1,1]
  2. *
  3. Longitudinal Stick [-1,1]
  4. @@ -415,23 +400,23 @@ public class XPlaneConnect implements AutoCloseable * change values in the middle of the array without affecting the preceding values, set the * preceding values to -998. *

    - * @param aircraft The aircraft to set. 0 for the player's aircraft. + * @param ac The ac to set. 0 for the player's ac. * @throws IOException If the command cannot be sent. */ - public void sendCTRL(float[] ctrl, int aircraft) throws IOException + public void sendCTRL(float[] values, int ac) throws IOException { //Preconditions - if(ctrl == null) + if(values == null) { throw new IllegalArgumentException("ctrl must no be null."); } - if(ctrl.length > 6) + if(values.length > 6) { throw new IllegalArgumentException("ctrl must have 6 or fewer elements."); } - if(aircraft < 0 || aircraft > 9) + if(ac < 0 || ac > 9) { - throw new IllegalArgumentException("aircraft must be non-negative and less than 9."); + throw new IllegalArgumentException("ac must be non-negative and less than 9."); } //Pad command values and convert to bytes @@ -439,16 +424,16 @@ public class XPlaneConnect implements AutoCloseable int cur = 0; ByteBuffer bb = ByteBuffer.allocate(22); bb.order(ByteOrder.LITTLE_ENDIAN); - for(i = 0; i < ctrl.length; ++i) + for(i = 0; i < values.length; ++i) { if(i == 4) { - bb.put(cur, (byte) ctrl[i]); + bb.put(cur, (byte) values[i]); cur += 1; } else { - bb.putFloat(cur, ctrl[i]); + bb.putFloat(cur, values[i]); cur += 4; } } @@ -465,7 +450,7 @@ public class XPlaneConnect implements AutoCloseable cur += 4; } } - bb.put(cur, (byte) aircraft); + bb.put(cur, (byte) ac); //Build and send message ByteArrayOutputStream os = new ByteArrayOutputStream(); @@ -476,11 +461,11 @@ public class XPlaneConnect implements AutoCloseable } /** - * Sets the position of the player aircraft. + * Sets the position of the player ac. * - * @param posi

    An array containing position elements as follows:

    + * @param values

    An array containing position elements as follows:

    *
      - *
    1. Latitiude (deg)
    2. + *
    3. Latitude (deg)
    4. *
    5. Longitude (deg)
    6. *
    7. Altitude (m above MSL)
    8. *
    9. Roll (deg)
    10. @@ -495,17 +480,17 @@ public class XPlaneConnect implements AutoCloseable *

      * @throws IOException If the command can not be sent. */ - public void sendPOSI(float[] posi) throws IOException + public void sendPOSI(float[] values) throws IOException { - sendPOSI(posi, 0); + sendPOSI(values, 0); } /** - * Sets the position of the specified aircraft. + * Sets the position of the specified ac. * - * @param posi

      An array containing position elements as follows:

      + * @param values

      An array containing position elements as follows:

      *
        - *
      1. Latitiude (deg)
      2. + *
      3. Latitude (deg)
      4. *
      5. Longitude (deg)
      6. *
      7. Altitude (m above MSL)
      8. *
      9. Roll (deg)
      10. @@ -518,32 +503,32 @@ public class XPlaneConnect implements AutoCloseable * change values in the middle of the array without affecting the preceding values, set the * preceding values to -998. *

        - * @param aircraft The aircraft to set. 0 for the player aircraft. + * @param ac The ac to set. 0 for the player ac. * @throws IOException If the command can not be sent. */ - public void sendPOSI(float[] posi, int aircraft) throws IOException + public void sendPOSI(float[] values, int ac) throws IOException { //Preconditions - if(posi == null) + if(values == null) { throw new IllegalArgumentException("posi must no be null."); } - if(posi.length > 7) + if(values.length > 7) { throw new IllegalArgumentException("posi must have 7 or fewer elements."); } - if(aircraft < 0 || aircraft > 255) + if(ac < 0 || ac > 255) { - throw new IllegalArgumentException("aircraft must be between 0 and 255."); + throw new IllegalArgumentException("ac must be between 0 and 255."); } //Pad command values and convert to bytes int i; ByteBuffer bb = ByteBuffer.allocate(28); bb.order(ByteOrder.LITTLE_ENDIAN); - for(i = 0; i < posi.length; ++i) + for(i = 0; i < values.length; ++i) { - bb.putFloat(i * 4, posi[i]); + bb.putFloat(i * 4, values[i]); } for(; i < 7; ++i) { @@ -554,11 +539,41 @@ public class XPlaneConnect implements AutoCloseable ByteArrayOutputStream os = new ByteArrayOutputStream(); os.write("POSI".getBytes(StandardCharsets.UTF_8)); os.write(0xFF); //Placeholder for message length - os.write(aircraft); + os.write(ac); os.write(bb.array()); sendUDP(os.toByteArray()); } + /** + * Reads X-Plane data + * + * @return The data read. + * @throws IOException If the read operation fails. + */ + public float[][] readData() throws IOException + { + byte[] buffer = readUDP(); + ByteBuffer bb = ByteBuffer.wrap(buffer); + int cur = 5; + int len = bb.get(cur++); + float[][] result = new float[bb.get(len)][9]; + for(int i = 0; i < len; ++i) + { + for(int j = 0; j < 9; ++j) + { + result[i][j] = bb.getFloat(cur); + cur += 4; + } + } + return result; + } + + /** + * Sends data to X-Plane + * + * @param data The data to send. + * @throws IOException If the command cannot be sent. + */ public void sendDATA(float[][] data) throws IOException { //Preconditions @@ -594,6 +609,36 @@ public class XPlaneConnect implements AutoCloseable sendUDP(os.toByteArray()); } + /** + * Selects what data X-Plane will export over UDP. + * + * @param rows The row numbers to select. + * @throws IOException If the command cannot be sent. + */ + public void selectDATA(int[] rows) throws IOException + { + //Preconditions + if(rows == null || rows.length == 0) + { + throw new IllegalArgumentException("rows must be a non-null, non-empty array."); + } + + //Convert data to bytes + ByteBuffer bb = ByteBuffer.allocate(4 * rows.length); + bb.order(ByteOrder.LITTLE_ENDIAN); + for(int i = 0; i < rows.length; ++i) + { + bb.putInt(i * 4, rows[i]); + } + + //Build and send message + ByteArrayOutputStream os = new ByteArrayOutputStream(); + os.write("DSEL".getBytes(StandardCharsets.UTF_8)); + os.write(0xFF); //Placeholder for message length + os.write(bb.array()); + sendUDP(os.toByteArray()); + } + /** * Sets a message to be displayed on the screen in X-Plane at the default screen location. * @@ -643,6 +688,15 @@ public class XPlaneConnect implements AutoCloseable sendUDP(os.toByteArray()); } + /** + * Adds, removes, or clears a set of waypoints. If the command is clear, the points are ignored + * and all points are removed. + * + * @param op The operation to perform. + * @param points An array of values representing points. Each triplet in the array will be + * interpreted as a (Lat, Lon, Alt) point. + * @throws IOException If the command cannot be sent. + */ public void sendWYPT(WaypointOp op, float[] points) throws IOException { //Preconditions @@ -650,6 +704,10 @@ public class XPlaneConnect implements AutoCloseable { throw new IllegalArgumentException("points.length should be divisible by 3."); } + if(points.length / 3 > 255) + { + throw new IllegalArgumentException("Too many points. Must be less than 256."); + } //Convert points to bytes ByteBuffer bb = ByteBuffer.allocate(4 * points.length); @@ -672,12 +730,12 @@ public class XPlaneConnect implements AutoCloseable /** * Sets the port on which the client will receive data from X-Plane. * - * @param recvPort The new incoming port number. - * @throws IOException If the command cannnot be sent. + * @param port The new incoming port number. + * @throws IOException If the command cannot be sent. */ - public void setCONN(int recvPort) throws IOException + public void setCONN(int port) throws IOException { - if(recvPort < 0 || recvPort >= 0xFFFF) + if(port < 0 || port >= 0xFFFF) { throw new IllegalArgumentException("Invalid port (must be non-negative and less than 65536)."); } @@ -685,13 +743,14 @@ public class XPlaneConnect implements AutoCloseable ByteArrayOutputStream os = new ByteArrayOutputStream(); os.write("CONN".getBytes(StandardCharsets.UTF_8)); os.write(0xFF); //Placeholder for message length - os.write((byte) recvPort); - os.write((byte) (recvPort >> 8)); + os.write((byte) port); + os.write((byte) (port >> 8)); sendUDP(os.toByteArray()); - int soTimeout = inSocket.getSoTimeout(); - inSocket.close(); - inSocket = new DatagramSocket(recvPort); - inSocket.setSoTimeout(soTimeout); + int soTimeout = socket.getSoTimeout(); + socket.close(); + socket = new DatagramSocket(port); + socket.setSoTimeout(soTimeout); + readUDP(); // Try to read response } } diff --git a/MATLAB/+XPlaneConnect/XPlaneConnect.jar b/MATLAB/+XPlaneConnect/XPlaneConnect.jar new file mode 100644 index 0000000..997803d Binary files /dev/null and b/MATLAB/+XPlaneConnect/XPlaneConnect.jar differ diff --git a/MATLAB/+XPlaneConnect/clearUDPBuffer.m b/MATLAB/+XPlaneConnect/clearUDPBuffer.m deleted file mode 100644 index 8237bd5..0000000 --- a/MATLAB/+XPlaneConnect/clearUDPBuffer.m +++ /dev/null @@ -1,33 +0,0 @@ -function socket = clearUDPBuffer(socket,varargin) -% clearUDPBuffer Script that clears an UDP Socket Buffer by closing and -% reopening the socket -% -% Inputs -% Socket: UDP Socket to be cleared -% -% Outputs -% Socket: UDP Socket -% -% Use -% 1. import XPlaneConnect.*; -% 2. Socket = openUDP(49005); -% 3. Socket = clearUDPBuffer(Socket); -% -% Contributors -% [CT] Christopher Teubert (SGT, Inc.) -% christopher.a.teubert@nasa.gov -% -% To Do -% 1. Verify Input -% -% BEGIN CODE - - import XPlaneConnect.* - - %% Close and reopen socket - if ~socket.isClosed() - port = socket.getLocalPort(); %get port of socket - socket.close; %Close Socket - socket = openUDP(port,varargin); %open new socket - end -end \ No newline at end of file diff --git a/MATLAB/+XPlaneConnect/closeUDP.m b/MATLAB/+XPlaneConnect/closeUDP.m index 0575ddb..4941ae1 100644 --- a/MATLAB/+XPlaneConnect/closeUDP.m +++ b/MATLAB/+XPlaneConnect/closeUDP.m @@ -1,28 +1,31 @@ -function [socket] = closeUDP(socket) -% closeUDP Script that closes a UDP Socket +function closeUDP(socket) +% closeUDP Closes the specified connection and releases resources associated with it. % % Inputs -% Socket: UDP Socket to be closed -% -% Outputs -% Socket: Closed Socket +% socket: An XPC client to close % % Use % 1. import XPlaneConnect.*; -% 2. Socket = openUDP(49005); -% 3. Status = closeUDP(Socket); +% 2. socket = openUDP(); +% 3. closeUDP(socket); % % Contributors % [CT] Christopher Teubert (SGT, Inc.) % christopher.a.teubert@nasa.gov -% -% To Do -% 1. Verify Input -% -% BEGIN CODE +% [JW] Jason Watkins +% jason.w.watkins@nasa.gov +%% Close the socket +assert(isequal(class(socket), 'gov.nasa.xpc.XPlaneConnect'),... + '[closeUDP] ERROR: socket was not an XPC client.'); socket.close; -assert(isequal(socket.isClosed(),1),'closeUDP: Error- Could not close socket'); +%% Track open clients +global clients; +for i = 1:length(clients) + if socket == clients(i) + clients = [clients(1:i-1) clients(i+1:length(clients))]; + end +end end \ No newline at end of file diff --git a/MATLAB/+XPlaneConnect/getDREFs.m b/MATLAB/+XPlaneConnect/getDREFs.m new file mode 100644 index 0000000..dc23958 --- /dev/null +++ b/MATLAB/+XPlaneConnect/getDREFs.m @@ -0,0 +1,38 @@ +function result = getDREFs( drefs, socket ) +%requestDREF request the value of a specific DataRef from X-Plane over UDP +% +%Inputs +% drefs: Cell Array of DataRefs to be requested +% socket (optional): The client to use when sending the command. +%Outputs +% result: cell array of resulting data. +% +%Use +% 1. import XPlaneConnect.*; +% 2. socket = opendUDP(); +% 3. drefs = {'sim/cockpit2/controls/yoke_heading_ratio','sim/cockpit2/controls/yoke_roll_ratio'}; +% 4. result = requestDREF(drefs, socket); +% +% Contributors +% [CT] Christopher Teubert (SGT, Inc.) +% christopher.a.teubert@nasa.gov +% [JW] Jason Watkins +% jason.w.watkins@nasa.gov + +import XPlaneConnect.* + +%% Get client +global clients; +if ~exist('socket', 'var') + assert(isequal(length(clients) < 2, 1), '[getDREFs] ERROR: Multiple clients open. You must specify which client to use.'); + if isempty(clients) + socket = openUDP(); + else + socket = clients(1); + end +end + +%% Send command +result = socket.getDREFs(drefs); + +end \ No newline at end of file diff --git a/MATLAB/+XPlaneConnect/openUDP.m b/MATLAB/+XPlaneConnect/openUDP.m index 77aa43f..c38e087 100644 --- a/MATLAB/+XPlaneConnect/openUDP.m +++ b/MATLAB/+XPlaneConnect/openUDP.m @@ -1,41 +1,42 @@ -function [socket] = openUDP(port, varargin) -%openUDP Script that opens an UDP Socket +function [ socket ] = openUDP(varargin) +%openUDP Initializes a new instance of the XPC client and returns it. % %Inputs -% port: UDP Port for socket +% xpHost: The network host on which X-Plane is running. +% xpPort: The port on which the X-Plane Connect plugin is listening. +% port: The local port to use when sending and receiving data from XPC. % timeout (optional): Optional parameter for time to UDP timeout (in ms) %Outputs -% Socket: UDP Socket +% socket: An instance of the XPC client. % % Use % 1. import XPlaneConnect.*; -% 2. Socket = openUDP(49005); %Open socket at port 49005 with timeout=0.1 sec +% 2. socket = openUDP(); % Open a socket using the default settings % or -% 2. Socket = openUDP(49005); %Open socket at port 49005 with timeout=0.2 sec +% 2. Socket = openUDP('127.0.0.1', 49008, 49005); % Open a socket to connect to X-Plane on the local machine and receive data on port 49005 % % Contributors % [CT] Christopher Teubert (SGT, Inc.) % christopher.a.teubert@nasa.gov -% -% To Do -% 1. Verify Input -% -% BEGIN CODE +% [JW] Jason Watkins +% jason.w.watkins@nasa.gov -import java.net.DatagramSocket +%% Handle input +p = inputParser; +addOptional(p,'xpHost','127.0.0.1',@ischar); +addOptional(p,'xpPort',49009,@isnumeric); +addOptional(p,'port',0,@isnumeric); +parse(p,varargin{:}); -%% create socket - socket = DatagramSocket(port); - socket.setSoTimeout(100); - socket.setReceiveBufferSize(2000); - -%% interpret input -if ~isempty(varargin) - if isnumeric(varargin(1)) - socket.setSoTimeout(varargin(1)); - end +%% Create client +if ~exist('gov.nasa.xpc.XPlaneConnect', 'class') + [folder, ~, ~] = fileparts(which('XPlaneConnect.openUDP')); + javaaddpath(fullfile(folder, 'XPlaneConnect.jar')); end +socket = gov.nasa.xpc.XPlaneConnect(p.Results.xpHost, p.Results.xpPort, p.Results.port); -assert(isequal(socket.isClosed(),0),'openUDP: Error- Could not open port'); +%% Track open clients +global clients; +clients = [clients, socket]; -end +end \ No newline at end of file diff --git a/MATLAB/+XPlaneConnect/pauseSim.m b/MATLAB/+XPlaneConnect/pauseSim.m index 4903236..c15f809 100644 --- a/MATLAB/+XPlaneConnect/pauseSim.m +++ b/MATLAB/+XPlaneConnect/pauseSim.m @@ -1,13 +1,9 @@ -function status = pauseSim( pause, varargin ) -%pauseSim pause Simulation +function pauseSim( pause, socket ) +%pauseSim Pauses or unpauses X-Plane. % %Inputs -% Pause: binary value 0=run, 1=pause -% IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine) -% port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin -% -%Outputs -% status: If there was an error. Status<0 means there was an error. +% pause: binary value 0=run, 1=pause +% socket (optional): The client to use when sending the command. % %Use % 1. import XPlaneConnect.*; @@ -16,29 +12,26 @@ function status = pauseSim( pause, varargin ) % Contributors % [CT] Christopher Teubert (SGT, Inc.) % christopher.a.teubert@nasa.gov -% -% To Do -% 1. Verify Input -% -%BEGIN CODE +% [JW] Jason Watkins +% jason.w.watkins@nasa.gov import XPlaneConnect.* -%% Handle Input - % Optional parameters - p = inputParser; - addRequired(p,'pause',@isnumeric); - addOptional(p,'IP','127.0.0.1',@ischar); - addOptional(p,'port',49009,@isnumeric); - parse(p,pause,varargin{:}); +%% Get client +global clients; +if ~exist('socket', 'var') + assert(isequal(length(clients) < 2, 1), '[pauseSim] ERROR: Multiple clients open. You must specify which client to use.'); + if isempty(clients) + socket = openUDP(); + else + socket = clients(1); + end +end - % Check format of input-TODO +%% Validate input +pause = logical(pause); -%% BODY - message = zeros(1,6); - - message(1:4) = 'SIMU'-0; - message(6) = uint8(p.Results.pause); +%% Send command +socket.pauseSim(pause); - status = sendUDP(message, p.Results.IP, p.Results.port); end \ No newline at end of file diff --git a/MATLAB/+XPlaneConnect/readDATA.m b/MATLAB/+XPlaneConnect/readDATA.m index f0492a5..80f888e 100644 --- a/MATLAB/+XPlaneConnect/readDATA.m +++ b/MATLAB/+XPlaneConnect/readDATA.m @@ -1,9 +1,8 @@ -function [ sensor ] = readDATA( socket ) +function [ result ] = readDATA( socket ) % readDATA Reads UDP Socket and interprets data % % Inputs -% location: Either an opened UDP Socket or integer port number -% +% socket (optional): The client to read from. % Outputs % If data is X-Plane data format: % data: Matlab X-Plane DATA Structure @@ -30,62 +29,30 @@ function [ sensor ] = readDATA( socket ) % NOTE: sending in a port number instead of an opened socket clears the UDP buffer. This only works if the data is being sent at a fast rate. Sending in a UDP Socket reads the first packet in the buffer. % % Contributors -% [CT] Christopher Teubert (SGT, Inc.) -% christopher.a.teubert@nasa.gov -% -% To Do -% 1. Verify Input -% -% BEGIN CODE +% Christopher Teubert (SGT, Inc.) +% Jason Watkins - import XPlaneConnect.* +import XPlaneConnect.* - %% Read UDP Socket - [ sensor.raw] = readUDP(socket); - - %% Interpret Input - bits = size(sensor.raw); - if sensor.raw ~= -998 %If the signal exists - header = char(sensor.raw(1:4)'); - if strcmp(header,'DATA') %DATA signal type - Values = floor((bits-5)/36); - sensor.d = []; - sensor.h = zeros(Values(1),1); - for i=1:Values(1) - sensor.h(i) = sensor.raw(6+(i-1)*36); - sensor.d = [sensor.d; typecast(uint8(sensor.raw(10+(i-1)*36:5+i*36))','single')]; - end - elseif strcmp(header,'STRU') %STRU signal type - a = 6; - while a % no data - -%% Handle Input -p = inputParser; -addRequired(p,'DREFArray'); -addOptional(p,'IP','127.0.0.1',@ischar); -addOptional(p,'port',49009,@isnumeric); -parse(p,DREFArray,varargin{:}); - -%% BODY - % Header - message(1:4) = 'GETD'-0; - message(6) = length(p.Results.DREFArray); - - % DREFS - for i=1:length(p.Results.DREFArray) - message(len) = length(p.Results.DREFArray{i}); - message(len+1:len+message(len)) = p.Results.DREFArray{i}; - len = len+1+message(len); - end - - % Send UDP - status = sendUDP(message, p.Results.IP, p.Results.port); - - % Look for response - for i=1:40 - data = readUDP(); - if length(data) > 1 % Received Data - status = 0; - counter = 7; - nArrays = data(6); - result = cell(nArrays,1); - for j=1:nArrays - sizeArray = data(counter); - result{j} = typecast(uint8(data(counter+1:counter+sizeArray*4))','single'); - counter = counter + 1 + sizeArray * 4; - end - break; - else - result = cell(0,1); - end - end -end \ No newline at end of file diff --git a/MATLAB/+XPlaneConnect/selectDATA.m b/MATLAB/+XPlaneConnect/selectDATA.m index 49efca1..dc54fdc 100644 --- a/MATLAB/+XPlaneConnect/selectDATA.m +++ b/MATLAB/+XPlaneConnect/selectDATA.m @@ -1,13 +1,9 @@ -function [ status ] = selectDATA( index, varargin ) +function selectDATA( rows, socket ) % selectDATA Choose specific X-Plane parameters to be send over UDP % % Inputs -% index: An array of the values that to be sent. Corresponds to the numbers on the XPlane Output screen -% IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine) -% port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp -% -% Outputs -% status: If there was an error. Status<0 means there was an error. +% rows: An array of the values that to be sent. Corresponds to the numbers on the XPlane Output screen +% socket (optional): The client to use when sending the command. % % Use % 1. import XPlaneConnect.*; @@ -15,29 +11,24 @@ function [ status ] = selectDATA( index, varargin ) % 3. status = selectDATA( values, '127.0.0.1', 49005 ); % send to localhose port 49005 % % Contributors -% [CT] Christopher Teubert (SGT, Inc.) -% christopher.a.teubert@nasa.gov -% -% To Do -% 1. Verify Input -% -% BEGIN CODE +% Christopher Teubert (SGT, Inc.) +% Jason Watkins import XPlaneConnect.* -%% Handle Input -p = inputParser; -addRequired(p,'index'); -addOptional(p,'IP','127.0.0.1',@ischar); -addOptional(p,'port',49009,@isnumeric); -parse(p,index,varargin{:}); - -%% BODY - dataString = ['DSEL'-0,0]; - for i=1:length(index) - dataString = [dataString, p.Results.index(i), 0, 0, 0]; +%% Get client +global clients; +if ~exist('socket', 'var') + assert(istrue(length(clients) < 2), '[selectDATA] ERROR: Multiple clients open. You must specify which client to use.'); + if isempty(clients) + socket = openUDP(); + else + socket = clients(1); end - status = sendUDP(dataStream, p.Results.IP, p.Results.port); - end +%% Validate input +rows = int32(rows); + +%% Send command +socket.selectDATA(rows); diff --git a/MATLAB/+XPlaneConnect/sendCTRL.m b/MATLAB/+XPlaneConnect/sendCTRL.m index 821efd0..b3d85b3 100644 --- a/MATLAB/+XPlaneConnect/sendCTRL.m +++ b/MATLAB/+XPlaneConnect/sendCTRL.m @@ -1,64 +1,53 @@ -function [ status ] = sendCTRL( ctrl, acft, IP, port ) -% sendCTRL Send X-Plane Aircraft Control Commands over UDP +function sendCTRL( values, ac, socket ) +% sendCTRL Sends command to X-Plane setting control surfaces on the specified aircraft. % % Inputs -% ctrl: control array where the elements are as follows: +% values: control array where the elements are as follows: % 1. Latitudinal Stick [-1,1] % 2. Longitudinal Stick [-1,1] % 3. Pedal [-1, 1] % 4. Throttle [-1, 1] % 5. Gear (0=up, 1=down) % 6. Flaps [0, 1] -% acft (optional): Aircraft # (default is 0; 0 = own aircraft) -% IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine) -% port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp +% ac (optional): The aircraft to set. 0 for the player aircraft. +% socket (optional): The client to use when sending the command. % % Outputs % status: If there was an error. Status<0 means there was an error. % % Use % 1. import XPlaneConnect.*; -% 2. #Send the data array to port 49009 on the computer at IP address 172.0.100.54. -% 3. status = sendCTRL([0, 0, 0, 0.8, 0, 1], 1, '172.0.100.54',49009); +% 2. socket = openUDP(); +% 3. status = sendCTRL([0, 0, 0, 0.8, 0, 1], 0, socket); % Set throttle and flaps on the player aircraft. % -% Note: send the value -998 to not overwrite that parameter. That is, if -998 is sent, the parameter will stay at the current X-Plane value +% Note: send the value -998 to not overwrite that parameter. That is, if +% -998 is sent, the parameter will stay at the current X-Plane value. % % Contributors -% [CT] Christopher Teubert (SGT, Inc.) -% christopher.a.teubert@nasa.gov -% -% To Do -% 1. Verify Input -% -% BEGIN CODE +% Christopher Teubert (SGT, Inc.) +% Jason Watkins import XPlaneConnect.* -%% Handle Input - % Optional parameters - if ~exist('IP','var'), IP = '127.0.0.1'; end - if ~exist('port','var'), port = 49009; end - if ~exist('acft','var'), acft = 0; end - - % Check format of input-TODO - -%%BODY - header = ['CTRL'-0,0]; - dataStream = header; %TODO-ADD ACFT - - % Deal with position update - control = [-998.5, -998.5, -998.5, -998.5, -998.5, -998.5]; - - for i=1:min(length(ctrl),length(control)) - control(i) = ctrl(i); +%% Get client +global clients; +if ~exist('socket', 'var') + assert(isequal(length(clients) < 2, 1), '[sendCTRL] ERROR: Multiple clients open. You must specify which client to use.'); + if isempty(clients) + socket = openUDP(); + else + socket = clients(1); end - dataStream = [dataStream, typecast(single(control(1:4)),'uint8')]; - dataStream = [dataStream, uint8(control(5))]; - dataStream = [dataStream, typecast(single(control(6)),'uint8')]; - dataStream = [dataStream, uint8(acft)]; - - % Send DATA - status = sendUDP(dataStream, IP, port); - end +%% Validate input +values = single(values); +if ~exist('ac', 'var') + ac = 0; +end +ac = logical(ac); + +%% Send command +socket.sendCTRL(values, ac); + +end \ No newline at end of file diff --git a/MATLAB/+XPlaneConnect/sendDATA.m b/MATLAB/+XPlaneConnect/sendDATA.m index f051fbe..8e4c461 100644 --- a/MATLAB/+XPlaneConnect/sendDATA.m +++ b/MATLAB/+XPlaneConnect/sendDATA.m @@ -1,15 +1,11 @@ -function [ status ] = sendDATA(data, varargin) +function sendDATA(data, socket) % sendDATA Send X-Plane formatted DATA over UDP % % Inputs % data: X-Plane formatted data. Is a matlab structure with the following fields: % .h: Header array containing header numbers corresponding to values in the X-Plane UDP Data screen. % .d: 2-D Data array. Each row contains eight values corresponding to the header value (.h(1) corresponds to .d(1,:)) -% IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine) -% port (optional): Port on the receiving machine where the data will be sent . Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp interface. -% -% Outputs -% status: 0: no error, <0: error +% socket (optional): The client to use when sending the command. % % Use % 1. import XPlaneConnect.*; @@ -29,29 +25,23 @@ function [ status ] = sendDATA(data, varargin) import XPlaneConnect.* -%% Handle Input -p = inputParser; -addRequired(p,'data'); -addOptional(p,'IP','127.0.0.1',@ischar); -addOptional(p,'port',49009,@isnumeric); -parse(p,data,varargin{:}); - -%% BODY - - header = ['DATA'-0,0]; - dataStream = header; - - for i=1:length(p.Results.data.h) - dataStream = [dataStream, p.Results.data.h(i), 0, 0, 0, typecast(single(p.Results.data.d(i,1:8)),'uint8')]; %#ok - end - - % Send DATA - if length(dataStream) > 5 - status = sendUDP(dataStream, p.Results.IP, p.Results.port); +%% Get client +global clients; +if ~exist('socket', 'var') + assert(isequal(length(clients) < 2, 1), '[sendDATA] ERROR: Multiple clients open. You must specify which client to use.'); + if isempty(clients) + socket = openUDP(); else - disp('Warning in sendDATA: Sending empty dataStream') - status = -2; + socket = clients(1); end - end +%% Validate input +javaData = []; +for i = 1:length(data.h); + javaData = [javaData; data.h(i) data.d(i, 1:8)]; +end + +%% Send command +socket.sendDATA(javaData); + diff --git a/MATLAB/+XPlaneConnect/sendDREF.m b/MATLAB/+XPlaneConnect/sendDREF.m index 4632d67..cbf2119 100644 --- a/MATLAB/+XPlaneConnect/sendDREF.m +++ b/MATLAB/+XPlaneConnect/sendDREF.m @@ -1,58 +1,38 @@ -function status = sendDREF( dataRef, Value, varargin ) -% sendDREF Send a command to change any DataRef in X-Plane over UDP. This requires the X-Plane Connect Plugin to be running +function sendDREF( dref, value, socket ) +% sendDREF Sends a command to X-Plane that sets the given DREF. % % Inputs -% dataRef: The X-Plane Dataref that will be chaged -% Value: The value that the above dataref is set to -% IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine) -% port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp -% -% Outputs -% status: If there was an error. status<0 means there was an error. +% dref: The name of the X-Plane dataref to set. +% Value: An array of floating point values whose structure depends on the dref specified. +% socket (optional): The client to use when sending the command. % % Use % 1. import XPlaneConnect.* % 2. dataRef = 'sim/aircraft/parts/acf_gear_deploy'; // Landing Gear % 3. Value = 0; -% 4. status = sendDREF(dataRef, Value); +% 4. status = setDREF(dataRef, Value); % % Contributors % [CT] Christopher Teubert (SGT, Inc.) % christopher.a.teubert@nasa.gov -% -% To Do -% 1. Verify Input -% -% BEGIN CODE +% [JW] Jason Watkins +% jason.w.watkins@nasa.gov import XPlaneConnect.* -status = 0; - -%% Handle Input -p = inputParser; -addRequired(p,'dataRef'); -addRequired(p,'Value'); -addOptional(p,'IP','127.0.0.1',@ischar); -addOptional(p,'port',49009,@isnumeric); -parse(p,dataRef, Value ,varargin{:}); +%% Get client +global clients; +if ~exist('socket', 'var') + assert(isequal(length(clients) < 2, 1), '[setDREF] ERROR: Multiple clients open. You must specify which client to use.'); + if isempty(clients) + socket = openUDP(); + else + socket = clients(1); + end +end -%% BODY - dataStream = zeros(1,7+length(p.Results.dataRef)+length(p.Results.Value)*4); - % Build Header - dataStream(1:4) = 'DREF'-0; - - % Add DREF - dataStream(6) = uint8(length(p.Results.dataRef)); - len = 6+length(p.Results.dataRef); - dataStream(7:len)=p.Results.dataRef-0; - - % Add Value - dataStream(len+1) =uint8(length(p.Results.Value)); - dataStream(len+2:end)=typecast(single(p.Results.Value),'uint8'); +%% Validate input +value = single(value); - % Send DREF - if length(dataStream) > 5 - status = sendUDP(dataStream, p.Results.IP, p.Results.port); - end -end \ No newline at end of file +%%Send command +socket.sendDREF(dref, value); \ No newline at end of file diff --git a/MATLAB/+XPlaneConnect/sendPOSI.m b/MATLAB/+XPlaneConnect/sendPOSI.m index 4f85735..bff56fb 100644 --- a/MATLAB/+XPlaneConnect/sendPOSI.m +++ b/MATLAB/+XPlaneConnect/sendPOSI.m @@ -1,5 +1,5 @@ -function [ status ] = sendPOSI( posi, varargin ) -% sendPOSI Send X-Plane Aircraft Position over UDP +function sendPOSI( posi, ac, socket ) +% sendPOSI Sets the position of the specified aircraft. % % Inputs % posi: Position array where the elements are as follows: @@ -10,52 +10,43 @@ function [ status ] = sendPOSI( posi, varargin ) % 5. Pitch (deg) % 6. True Heading (deg) % 7. Gear (0=up, 1=down) -% acft (optional): Aircraft # (default is 0; 0 = own aircraft) -% IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine) -% port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp -% -% Outputs -% status: If there was an error. Status<0 means there was an error. +% acft (optional): The aircraft to set. 0 for the player aircraft. +% socket (optional): The client to use when sending the command. % % Use -% 1. import XPlaneConnect.*; -% 2. #Send the data array to port 49009 on the computer at IP address 172.0.100.54. -% 3. status = sendPOSI([37.5242422, -122.06899, 2500, 0, 0, 0, 1], 1, '172.0.100.54'); +% 1. import XPlaneConnect.*; +% 2. sendPOSI([37.5242422, -122.06899, 2500, 0, 0, 0, 1], 1); % -% Note: send the value -998 to not overwrite that parameter. That is, if -998 is sent, the parameter will stay at the current X-Plane value +% Note: send the value -998 to not overwrite that parameter. That is, if +% -998 is sent, the parameter will stay at the current X-Plane value. % % Contributors % [CT] Christopher Teubert (SGT, Inc.) % christopher.a.teubert@nasa.gov -% -% To Do -% -% BEGIN CODE +% [JW] Jason Watkins +% jason.w.watkins@nasa.gov import XPlaneConnect.* -%% Handle Input -p = inputParser; -addRequired(p,'posi'); -addOptional(p,'acft',0,@isnumeric); -addOptional(p,'IP','127.0.0.1',@ischar); -addOptional(p,'port',49009,@isnumeric); -parse(p,posi,varargin{:}); - -%% BODY - header = ['POSI'-0,0]; - dataStream = [header, p.Results.acft]; - - % Deal with position update - position = [37.4185718,-121.935565,500,0,0,0, 0]; - - for i=1:min(length(position),length(p.Results.posi)) - position(i) = p.Results.posi(i); +%% Get client +global clients; +if ~exist('socket', 'var') + assert(isequal(length(clients) < 2, 1), '[sendPOSI] ERROR: Multiple clients open. You must specify which client to use.'); + if isempty(clients) + socket = openUDP(); + else + socket = clients(1); end - dataStream = [dataStream, typecast(single(position),'uint8')]; - - % Send POSI - status = sendUDP(dataStream, p.Results.IP, p.Results.port); - end +%% Validate input +posi = single(posi); +if ~exist('ac', 'var') + ac = 0; +end +ac = logical(ac); + +%% Send command +socket.sendPOSI(posi, ac); + +end \ No newline at end of file diff --git a/MATLAB/+XPlaneConnect/sendSTRU.m b/MATLAB/+XPlaneConnect/sendSTRU.m deleted file mode 100644 index e00898a..0000000 --- a/MATLAB/+XPlaneConnect/sendSTRU.m +++ /dev/null @@ -1,57 +0,0 @@ -function [ status ] = sendSTRU( STRU, varargin ) -%sendSTRU Send a MATLAB structure over UDP -% -%Inputs -% stru: A MATLAB structure -% IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine) -% port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin -% -%Outputs -% status: If there was an error. Status<0 means there was an error. -% -%Use -% 1. import XPlaneConnect.*; -% 2. data = struct('a',[1:20],'b',1.853,'name','Example Structure'); -% 3. #Send the data structure to port 49005 on the computer at IP address 172.0.100.54 -% 4. status = sendUDP( data, '172.0.100.54', 49005 ); -% -% Contributors -% [CT] Christopher Teubert (SGT, Inc.) -% christopher.a.teubert@nasa.gov -% -% To Do -% -%BEGIN CODE - - import XPlaneConnect.* - - %% Handle Input - p = inputParser; - addRequired(p,'STRU'); - addOptional(p,'IP','127.0.0.1',@ischar); - addOptional(p,'port',49009,@isnumeric); - parse(p,STRU,varargin{:}); - - %% Form Data Array representing the structure - DATA = ['STRU'-0,0]; %array header - fieldName = fieldnames(p.Results.STRU); %all Struct fields - for i=1:length(fieldName) %for each field - field = getfield(p.Results.STRU,fieldName{i}); %get field - if ischar(field) %String - dim1 = 0; %Indicates string - dim2 = length(field); %length - data = field-0; %data - else %Numeric - dim1 = size(field,1); %Array Dim1 - dim2 = size(field,2); %Array Dim2 - data = typecast(single(reshape(field',1,dim1*dim2)),'uint8'); %Data - end - - DATA = [DATA,length(fieldName{i}),fieldName{i}-0,dim1,dim2,data]; %add to array - end - - %% Send Array - status = sendUDP(DATA, p.Results.IP, p.Results.port); - -end - diff --git a/MATLAB/+XPlaneConnect/sendTEXT.m b/MATLAB/+XPlaneConnect/sendTEXT.m index 499c12b..5edfaeb 100644 --- a/MATLAB/+XPlaneConnect/sendTEXT.m +++ b/MATLAB/+XPlaneConnect/sendTEXT.m @@ -1,4 +1,4 @@ -function [ status ] = sendTEXT( msg, varargin ) +function sendTEXT( msg, x, y, socket ) % sendTEXT Sends a string to be displayed in X-Plane. % % Inputs @@ -13,35 +13,35 @@ function [ status ] = sendTEXT( msg, varargin ) % % Use % 1. import XPlaneConnect.*; -% 2. #Set a message to be displayed near the top middle of the screen. +% 2. % Set a message to be displayed near the top middle of the screen. % 3. status = sendTEXT('Some text', 512, 600); % % Contributors -% Jason Watkins -% jason.w.watkins@nasa.gov -% -% To Do -% -% BEGIN CODE +% Jason Watkins (jason.w.watkins@nasa.gov) import XPlaneConnect.* -%% Handle Input -p = inputParser; -addRequired(p,'msg'); -addOptional(p,'x',-1,@isnumeric); -addOptional(p,'y',-1,@isnumeric); -addOptional(p,'IP','127.0.0.1',@ischar); -addOptional(p,'port',49009,@isnumeric); -parse(p,msg,varargin{:}); -%% Body - header = ['TEXT'-0,0]; - dataStream = [header,... - typecast(uint32(p.Results.x), 'uint8'),... - typecast(uint32(p.Results.y), 'uint8'),... - uint8(length(msg)), msg-0]; - - % Send TEXT - status = sendUDP(dataStream, p.Results.IP, p.Results.port); +%% Get client +global clients; +if ~exist('socket', 'var') + assert(isequal(length(clients) < 2, 1), '[sendTEXT] ERROR: Multiple clients open. You must specify which client to use.'); + if isempty(clients) + socket = openUDP(); + else + socket = clients(1); + end end +%% Validate input +if ~exist('x', 'var') + x = -1; +end +if ~exist('y', 'var') + y = -1; +end +x = int32(x); +y = int32(y); + +%% Send command +socket.sendTEXT(msg, x, y); +end \ No newline at end of file diff --git a/MATLAB/+XPlaneConnect/sendUDP.m b/MATLAB/+XPlaneConnect/sendUDP.m deleted file mode 100644 index 6b0b112..0000000 --- a/MATLAB/+XPlaneConnect/sendUDP.m +++ /dev/null @@ -1,49 +0,0 @@ -function [ status ] = sendUDP( data, IP, port ) -%sendUDP Send an one dimensional array of type uint8 data over an UDP connection using a java DatagramSocket -% -%Inputs -% Data: 1-D array of type uint8 data to be sent -% IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine) -% port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin -% -%Outputs -% status: If there was an error. Status<0 means there was an error. -% -%Use -% 1. import XPlaneConnect.*; -% 2. data = uint8([1:20]); -% 3. #Send the data array to port 49005 on the computer at IP address 172.0.100.54. -% 4. status = sendUDP( data, '172.0.100.54', 49005 ); -% -% Contributors -% [CT] Christopher Teubert (SGT, Inc.) -% christopher.a.teubert@nasa.gov -% -% To Do -% 1. Verify Input -% -%BEGIN CODE - - import java.net.DatagramSocket - import java.net.DatagramPacket - import java.net.InetAddress - - data(5) = length(data); - status = 0; - - %% Send array - persistent socket - if isempty(socket) - try - socket = DatagramSocket; - catch err - status = 1; - disp(err) - end - end - - IP = InetAddress.getByName(IP); - packet = DatagramPacket(data, length(data), IP, port); %create packet - socket.send(packet); -end - diff --git a/MATLAB/+XPlaneConnect/sendWYPT.m b/MATLAB/+XPlaneConnect/sendWYPT.m index ed64b04..a366c89 100644 --- a/MATLAB/+XPlaneConnect/sendWYPT.m +++ b/MATLAB/+XPlaneConnect/sendWYPT.m @@ -1,53 +1,50 @@ -function [ status ] = sendWYPT( op, points, varargin ) +function sendWYPT( op, points, socket ) % sendWYPT Adds, removes, or clears a set of waypoints to be rendered in % the simulator. % % Inputs -% msg: The string to be displayed -% x (optional): The distance from the left edge of the screen to display the message. -% y (optional): The distance from the bottom edge of the screen to display the message. -% IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine) -% port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp -% -% Outputs -% status: 0 if successful, otherwise a negative value. +% op: The operation to perform. 1=add, 2=remove, 3=clear. +% points: An array of values representing points. Each triplet in the +% array will be interpreted as a (Lat, Lon, Alt) point. +% socket (optional): The client to use when sending the command. % % Use % 1. import XPlaneConnect.*; -% 2. #Set a message to be displayed near the top middle of the screen. +% 2. %Set a message to be displayed near the top middle of the screen. % 3. status = sendTEXT('Some text', 512, 600); % % Contributors -% Jason Watkins -% jason.w.watkins@nasa.gov +% Jason Watkins (jason.w.watkins@nasa.gov) % % To Do % % BEGIN CODE import XPlaneConnect.* -%% Handle Input -p = inputParser; -addRequired(p,'op'); -addRequired(p,'points'); -addOptional(p,'IP','127.0.0.1',@ischar); -addOptional(p,'port',49009,@isnumeric); -parse(p,op,points,varargin{:}); -%% Validate Input -len = uint32(length(points)); -assert(op > 0 && op < 4); -assert(mod(len, 3) == 0); -assert(len / 3 < 20); - -%% Body -header = ['WYPT'-0,0]; -dataStream = [header,... - uint8(op),... - uint8(len / 3),... - typecast(single(points), 'uint8')]; - -% Send TEXT -status = sendUDP(dataStream, p.Results.IP, p.Results.port); +%% Get client +global clients; +if ~exist('socket', 'var') + assert(isequal(length(clients) < 2, 1), '[sendWYPT] ERROR: Multiple clients open. You must specify which client to use.'); + if isempty(clients) + socket = openUDP(); + else + socket = clients(1); + end end +%% Validate input +len = uint32(length(points)); +assert(op > 0 && op < 4); +wyptOp = gov.nasa.xpc.WaypointOp.Add; +if isequal(op, 2) + wyptOp = gov.nasa.xpc.WaypointOp.Del; +elseif isequal(op, 3) + wyptOp = gov.nasa.xpc.WaypointOp.Clr; +end +assert(mod(len, 3) == 0); + +%% Send command +socket.sendWYPT(wyptOp, points); + +end \ No newline at end of file diff --git a/MATLAB/+XPlaneConnect/setConn.m b/MATLAB/+XPlaneConnect/setConn.m index ad757a4..905c440 100644 --- a/MATLAB/+XPlaneConnect/setConn.m +++ b/MATLAB/+XPlaneConnect/setConn.m @@ -1,50 +1,36 @@ -function status = setConn( recvPort, IP, port ) +function setConn(port, socket) % setConn Send a command to set up the port where you will receive data on % this computer. % % Inputs -% Receiving Port: Port that data will be sent to in the future for this connection -% IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine) -% port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp -% -% Outputs -% status: If there was an error. status<0 means there was an error. +% port: Port that data will be sent to in the future for this connection. +% socket (optional): The client to use when sending the command. % % Use % 1. import XPlaneConnect.* % 2. status = setConn(49011); % % Contributors -% [CT] Christopher Teubert (SGT, Inc.) -% christopher.a.teubert@nasa.gov -% -% To Do -% 1. Verify Input -% -% BEGIN CODE - import XPlaneConnect.* +% Christopher Teubert (SGT, Inc.) +% Jason Watkins - status = 0; - message = zeros(1,7); - -%% Handle Input - % Optional parameters - if ~exist('IP','var'), IP = '127.0.0.1'; end - if ~exist('port','var'), port = 49009; end +import XPlaneConnect.* - % Check format of input-TODO +%% Get client +global clients; +if ~exist('socket', 'var') + assert(isequal(length(clients) < 2, 1), '[setCONN] ERROR: Multiple clients open. You must specify which client to use.'); + if isempty(clients) + socket = openUDP(); + else + socket = clients(1); + end +end -%% BODY - % Header - message(1:4) = 'CONN'-0; - - % RecvPort - message(6:7) = typecast(uint16(recvPort),'uint8'); - - % Send - sendUDP(message,IP,port); - - global udpReadPort; - udpReadPort = recvPort; +%% Validate input +port = int32(port); + +%% Send command +socket.setCONN(port); end \ No newline at end of file diff --git a/MATLAB/Documentation (MATLAB).html b/MATLAB/Documentation (MATLAB).html deleted file mode 100644 index 87ba7c9..0000000 --- a/MATLAB/Documentation (MATLAB).html +++ /dev/null @@ -1,115 +0,0 @@ - - - - - - XPlaneConnect Toolbox - - - - -

        XPC-MATLAB

        -Chris Teubert (Christopher.A.Teubert@nasa.gov)
        - -

        Summary

        -XPC-MATLAB is a series of MATLAB functions that facilitate communication with X-Plane. This toolbox allows for the real-time application of active control to an XPlane simulation, flight visualization, record state during a flight, or interact with a mission using UDP. - -

        Table of Contents

        -
          -
        1. Functions
        2. -
        3. Setup -
        4. Use
        5. -
        6. Example
        7. -
        8. Future Work
        9. -
        10. Notices and Disclaimers
        11. -
        12. Change Log
        13. -
        - -

        Functions

        -

        Basic Package

        - - -
          - - sendDATA: - Send X-Plane Formatted DATA over UDP
          - - sendPOSI: - Send Position and orientation update command to X-Plane over UDP for any aircraft (own or traffic)
          - - sendCTRL: - Send control commands to X-Plane over UDP for any aircraft (own or traffic)
          - - sendDREF: - Set any X-Plane internal variable (dataref) over UDP
          - - selectDATA: - Choose specific X-Plane DATA parameters to be sent by X-Plane over UDP
          - - setConn: - Sets the return port for requested datarefs.
          - - pauseSim: - Pause simulation
          - - openUDP: - Script that opens an UDP Socket
          - - closeUDP: - Script that closes an UDP Socket
        - -

        Advanced/Special-Use Functions

        - -
          - - clearUDPBuffer: - Script that clears an UDP Socket Buffer
          - - readDATA: - Read X-Plane Formatted Data from UDP Socket
          - - readUDP: - Read Array from UDP Socket
          - - sendSTRU: - Send a MATLAB structure over UDP
          - - sendUDP: - Send array over UDP
        - -

        Future

        - -
          - - requestDREF: - Request the value of a specific data ref
          - - drawWaypoint: - NOT FUNCTIONAL
        - -

        Setup

        -Before using XPC Functions you must -1. Install X-Plane (http://www.x-plane.com) -2. Copy the file xpcPlugin.xpl to the "[X-Plane Directory]/Resources/plugins" directory. - a. For Mac xpcPlugin can be found in the "[XPlaneConnect]/xpcPlugin/Mac" directory. - a. For Windows xpcPlugin can be found in the "[XPlaneConnect]/xpcPlugin/Win" directory. -3. Insert X-Plane CD 1 or X-Plane USB Key. -4. Start X-Plane. -5. import XPlaneConnect.* - -

        Examples

        -

        Files

        -TO BE ADDED -

        Description

        - -

        Future Work

        -
          -
        • -
        - -

        Notices and Disclaimers

        -Notices:
        -Copyright ©2013-2014 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved.
        - -
        Disclaimers: - -

        No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS."

        - -

        Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT.

        - -
        X-Plane API
        -Copyright (c) 2008, Sandy Barbour and Ben Supnik All rights reserved.
        -

        Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

        -
          -
        • Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
        • -
        • Neither the names of the authors nor that of X-Plane or Laminar Research may be used to endorse or promote products derived from this software without specific prior written permission from the authors or Laminar Research, respectively.
        • -
        - -

        X-Plane API SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

        - - - diff --git a/MATLAB/pages/clearUDPBuffer.html b/MATLAB/pages/clearUDPBuffer.html deleted file mode 100644 index f09b945..0000000 --- a/MATLAB/pages/clearUDPBuffer.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - XPlaneConnect Toolbox-ClearUDPBuffer - - - - -<-- Back
        -

        clearUDPBuffer

        -Script that clears an UDP Socket Buffer - -

        Inputs

        -
          -
        • Socket: UDP Socket to be cleared
        • -
        - -

        Outputs

        -
          -
        • Socket: UDP Socket
        • -
        - -

        Use

        -1. import XPlaneConnect.*;
        -2. Socket = openUDP(49005);
        -3. Socket = clearUDPBuffer(Socket);
        - -

        Change Log

        -10/02/14: [CT] V0.9: Updated to work with updated xpcPlugin
        -09/12/13: [CT] Add optional arguments
        -09/10/13: [CT] Code created

        -<-- Back
        - - - \ No newline at end of file diff --git a/MATLAB/pages/closeUDP.html b/MATLAB/pages/closeUDP.html deleted file mode 100644 index e2a64c5..0000000 --- a/MATLAB/pages/closeUDP.html +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - XPlaneConnect Toolbox-closeUDP - - - - -<-- Back
        -

        closeUDP

        -Script that closes a UDP Socket - -

        Inputs

        -
          -
        • Socket: UDP Socket to be closed
        • -
        - -

        Outputs

        -
          -
        • Status: Integer indicating the success of socket closing. 1 = Success 0 = Failure
        • -
        - -

        Use

        -1. import XPlaneConnect.*;
        -2. Socket = openUDP(49005);
        -3. Status = closeUDP(Socket);
        - -

        Change Log

        -10/02/14: [CT] V0.9: Updated to work with updated xpcPlugin
        -09/10/13: [CT] Code created

        -<-- Back
        - - - \ No newline at end of file diff --git a/MATLAB/pages/openUDP.html b/MATLAB/pages/openUDP.html deleted file mode 100644 index d13ed2b..0000000 --- a/MATLAB/pages/openUDP.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - XPlaneConnect Toolbox-openUDP - - - - -<-- Back
        -

        openUDP

        -Script that opens a UDP Socket - -

        Inputs

        -
          -
        • port: UDP Port for socket
        • -
        • timeout (optional): Optional parameter for time to UDP timeout (in ms)-Default 0.1 seconds
        • -
        - -

        Outputs

        -
          -
        • Socket: UDP Socket
        • -
        - -

        Use

        -1. import XPlaneConnect.*;
        -2. Socket = openUDP(49005);%Open socket at port 49005 with timeout of 0.1 seconds

        -or

        -2. Socket = openUDP(49005,200);%Open socket at port 49005 with timeout of 0.2 seconds

        - -

        Change Log

        -10/02/14: [CT] V0.9: Updated to work with updated xpcPlugin
        -09/12/13: [CT] Added optional timeout input argument
        -09/10/13: [CT] Code created

        -<-- Back
        - - - \ No newline at end of file diff --git a/MATLAB/pages/pauseSim.html b/MATLAB/pages/pauseSim.html deleted file mode 100644 index bf799c0..0000000 --- a/MATLAB/pages/pauseSim.html +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - XPlaneConnect Toolbox-pauseSim - - - - -<-- Back
        -

        pauseSim

        - -

        Inputs

        -
          -
        • Pause: binary value 0=run, 1=pause
        • -
        • IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine)
        • -
        • port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp
        • -
        - -

        Outputs

        -
          -
        • status: If there was an error. status<0 means there was an error.
        • -
        - -

        Use

        -1. import XPlaneConnect.*;
        -2. status = pauseSim(1);
        - -

        Change Log

        -10/02/14: [CT] V0.9: Updated to work with updated xpcPlugin
        -06/10/13: [CT] Code created

        -<-- Back
        - - - \ No newline at end of file diff --git a/MATLAB/pages/readDATA.html b/MATLAB/pages/readDATA.html deleted file mode 100644 index 12cef1b..0000000 --- a/MATLAB/pages/readDATA.html +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - XPlaneConnect Toolbox-readDATA - - - - -<-- Back
        -

        readDATA

        -Reads UDP Socket and interprets data - -

        Inputs

        -
          -
        • location: Either an opened UDP Socket or integer port number
        • -
        - -

        Outputs

        -If data is X-Plane data format: -
          -
        • data: Matlab X-Plane DATA Structure
            -
          • .h: Header array containing header numbers corresponding to values in the X-Plane UDP Data screen.
          • -
          • .d: 2-D Data array. Each row contains eight values corresponding to the header value (.h(1) corresponds to .d(1,:))
          • -
          • .raw: raw UDP data array received by readUDP
        • -
        -If data is matlab structure: -
          -
        • data: Matlab Structure. Raw udp data saved to data.raw
        • -
        -If data is any other format: -
          -
        • data: Matlab Structure containing one field
            -
          • .raw & .d: raw UDP data array received by readUDP
        • -
        - -

        Use

        -1. import XPlaneConnect.*;
        -2. socket = openUDP(49005);
        -3. data = readDATA(socket);
        -4. status = closeUDP(socket);

        - -or

        - -1. import XPlaneConnect.*;
        -2. data = readDATA(49005); - -

        Note

        -NOTE: sending in a port number instead of an opened socket clears the UDP buffer. This only works if the data is being sent at a fast rate. Sending in a UDP Socket reads the first packet in the buffer.
        - -

        Change Log

        -10/02/14: [CT] V0.9: Updated to work with updated xpcPlugin
        -09/10/13: [CT] Updated to receive UDP socket or port number
        -06/10/13: [CT] Code created

        -<-- Back
        - - - \ No newline at end of file diff --git a/MATLAB/pages/readUDP.html b/MATLAB/pages/readUDP.html deleted file mode 100644 index 8a636f2..0000000 --- a/MATLAB/pages/readUDP.html +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - XPlaneConnect Toolbox-readUDP - - - - -<-- Back
        -

        readUDP

        -Read Array from UDP Socket - -

        Inputs

        -
          -
        • location: Either an opened UDP Socket or integer port number
        • -
        - -

        Outputs

        -
          -
        • data: UDP uint8 Array. Equal to -998 in the case of an error.
        • -
        - -

        Use

        -1. import XPlaneConnect.*;
        -2. socket = openUDP(49005);
        -3. data = readUDP(socket);
        -4. status = closeUDP(socket);

        - -or

        - -1. import XPlaneConnect.*;
        -2. data = readUDP(49005);
        - -

        Note

        -NOTE: sending in a port number instead of an opened socket clears the UDP buffer. This only works if the data is being sent at a fast rate. Sending in a UDP Socket reads the first packet in the buffer. - -

        Change Log

        -10/02/14: [CT] V0.9: Updated to work with updated xpcPlugin
        -09/08/13: [CT] Added option for either UDP Socket or port number input
        -06/10/13: [CT] Code created

        -<-- Back
        \ No newline at end of file diff --git a/MATLAB/pages/requestDREF.html b/MATLAB/pages/requestDREF.html deleted file mode 100644 index ff822de..0000000 --- a/MATLAB/pages/requestDREF.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - XPlaneConnect Toolbox-requestDREF - - - - -<-- Back
        -

        requestDREF

        - -

        Inputs

        -
          -
        • DREFArray: Cell Array of DataRefs to be requested
        • -
        • IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine)
        • -
        • port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin
        • -
        - -

        Outputs

        -
          -
        • status: If there was an error. status<0 means there was an error.
        • -
        - -

        Use

        -1. import XPlaneConnect.*;
        -2. DREFArray = {'sim/cockpit2/controls/yoke_heading_ratio','sim/cockpit2/controls/yoke_roll_ratio'};
        -3. status = requestDREF( DREFArray, '172.0.100.54' );
        - -

        Change Log

        -10/02/14: [CT] V0.9: Updated to work with updated xpcPlugin
        -06/10/13: [CT] Code created

        -<-- Back
        - - - \ No newline at end of file diff --git a/MATLAB/pages/selectDATA.html b/MATLAB/pages/selectDATA.html deleted file mode 100644 index 2a9e3e0..0000000 --- a/MATLAB/pages/selectDATA.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - XPlaneConnect Toolbox-selectDATA - - - - -<-- Back
        -

        selectDATA

        -Choose specific X-Plane parameters to be send over UDP - -

        Inputs

        -
          -
        • index: An array of the values that to be sent. Corresponds to the numbers on the XPlane Output screen (ACTUAL NAME?)
        • -
        • IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine)
        • -
        • port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp
        • -
        - -

        Outputs

        -
          -
        • status: If there was an error. Status<0 means there was an error.
        • -
        - -

        Use

        -1. import XPlaneConnect.*;
        -2. values = [1, 2, 3, 27, 40]; -3. status = selectDATA(values,'127.0.0.1',49005);
        - -

        Change Log

        -10/02/14: [CT] V0.9: Updated to work with updated xpcPlugin
        -04/18/14: [CT] V0.2: Added Versioning
        -06/10/13: [CT] Code created

        -<-- Back
        - - - \ No newline at end of file diff --git a/MATLAB/pages/sendCTRL.html b/MATLAB/pages/sendCTRL.html deleted file mode 100644 index 9bb501a..0000000 --- a/MATLAB/pages/sendCTRL.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - XPlaneConnect Toolbox-sendCTRL - - - - -<-- Back
        -

        sendCTRL

        -Send position and orientation update command to X-Plane over UDP. This requires the X-Plane Connect Plugin to be running - -

        Inputs

        -
          -
        • ctrl: Array of 6 values where: -
            -
          • ctrl(1) Latitudinal Stick [-1,1]
          • -
          • ctrl(2) Longitudinal Stick [-1,1]
          • -
          • ctrl(3) Pedal [-1, 1]
          • -
          • ctrl(4) Throttle [-1, 1]
          • -
          • ctrl(5) Gear (0=up, 1=down)
          • -
          • ctrl(6) Flaps [0, 1]
          • -
          -
        • aircraft number (optional): 0=own aircraft
        • -
        • IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine)
        • -
        • port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp
        • -
        - -

        Outputs

        -
          -
        • status: If there was an error. status<0 means there was an error.
        • -
        - -

        Use

        -1. import XPlaneConnect.*;
        -2. ctrl = [0, 0, 0, 0.8, 0, 0]; -3. status = sendCTRL(ctrl); % Set position of own aircraft
        -4. status2 = sendCTRL(ctrl,1); % Set position of aircraft 1
        - -

        Change Log

        -10/02/14: [CT] V0.9 Updated to use new xpcPlugin
        -09/26/14: [CT] Code created

        -<-- Back
        - - - \ No newline at end of file diff --git a/MATLAB/pages/sendDATA.html b/MATLAB/pages/sendDATA.html deleted file mode 100644 index 02df49d..0000000 --- a/MATLAB/pages/sendDATA.html +++ /dev/null @@ -1,46 +0,0 @@ - - - - - - XPlaneConnect Toolbox-sendDATA - - - - -<-- Back
        -

        sendDATA

        -Send X-Plane formatted DATA over UDP. This function is used to change one of the parameters listed in the x-plane udp data screen (see http://www.nuclearprojects.com/xplane/images/xp_datainout.jpg) - -

        Inputs

        -
          -
        • data: X-Plane formatted data. Is a matlab structure with the following fields: -
            -
          • .h: Header array containing header numbers corresponding to values in the X-Plane UDP Data screen.
          • -
          • .d: 2-D Data array. Each row contains eight values corresponding to the header value (.h(1) corresponds to .d(1,:))
          • -
        • -
        • IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine)
        • -
        • port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp
        • -
        - -

        Outputs

        -
          -
        • status: If there was an error. Status=1 means there was an error.
        • -
        - -

        Use

        -1. import XPlaneConnect.*;
        -2. data = struct('h',14,'d',[1,-998,-998,-998,-998,-998,-998,-998]); %Set Gear
        -3. %Send the data array to port 49005 on the computer at IP address 172.0.100.54.
        -4. status = sendDATA(data, '172.0.100.54', 49005); - -

        note

        -Note: send the value -998 to not overwrite that parameter. That is, if -998 is sent, the parameter will stay at the current X-Plane value
        - -

        Change Log

        -10/01/14: [CT] V0.9: updated to function with new xpcPlugin
        -06/10/13: [CT] First created

        -<-- Back
        - - - \ No newline at end of file diff --git a/MATLAB/pages/sendDREF.html b/MATLAB/pages/sendDREF.html deleted file mode 100644 index c5dd742..0000000 --- a/MATLAB/pages/sendDREF.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - XPlaneConnect Toolbox-sendCTRL - - - - -<-- Back
        -

        sendCTRL

        -Send position and orientation update command to X-Plane over UDP. This requires the X-Plane Connect Plugin to be running - -

        Inputs

        -
          -
            -
          • data(1) Latitudinal Stick [-1,1]
          • -
          • data(2) Longitudinal Stick [-1,1]
          • -
          • data(3) Pedal [-1, 1]
          • -
          • data(4) Throttle [-1, 1]
          • -
          • data(5) Gear (0=up, 1=down)
          • -
          • data(6) Flaps [0, 1]
          • -
          -
        • aircraft number (optional): 0=own aircraft
        • -
        • IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine)
        • -
        • port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp
        • -
        - -

        Outputs

        -
          -
        • status: If there was an error. status<0 means there was an error.
        • -
        - -

        Use

        -1. import XPlaneConnect.*
        -2. dataRef = 'sim/aircraft/parts/acf_gear_deploy'; // Landing Gear
        -3. Value = 0;
        -4. status = sendDREF(dataRef, Value);
        - -

        Change Log

        -10/02/14: [CT] V0.9: Updated to use new xpcPlugin -06/10/13: [CT] Code created

        - -<-- Back
        - - - \ No newline at end of file diff --git a/MATLAB/pages/sendPOSI.html b/MATLAB/pages/sendPOSI.html deleted file mode 100644 index 4642b96..0000000 --- a/MATLAB/pages/sendPOSI.html +++ /dev/null @@ -1,50 +0,0 @@ - - - - - - XPlaneConnect Toolbox-sendDREF - - - - -<-- Back
        -

        sendPosition

        -Send position and orientation update command to X-Plane over UDP. This requires the X-Plane Connect Plugin to be running - -

        Inputs

        -
          -
        • data: Array of 6 values where: -
            -
          • data(1) is the aircraft's Latitude (degrees)
          • -
          • data(2) is the aircraft's Longitude (degrees)
          • -
          • data(3) is the aircraft's altitude (meters above sea level)
          • -
          • data(4) is the aircraft's roll angle (degrees)
          • -
          • data(5) is the aircraft's pitch angle (degrees)
          • -
          • data(6) is the aircraft's heading/yaw angle (degrees)
          • -
          -
        • aircraft number (optional): 0=own aircraft
        • -
        • IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine)
        • -
        • port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp
        • -
        - -

        Outputs

        -
          -
        • status: If there was an error. status<0 means there was an error.
        • -
        - -

        Use

        -1. import XPlaneConnect.*;
        -2. latlon = [37.4185718,-121.935565]; %Lat,lon of NASA Ames Research Center
        -3. alt = 500; %meters above sea level
        -4. orient = [0,20,180]; %Orientation (roll,pitch,yaw/heading). 20 degrees yaw, heading south
        -5. status = sendPOSI([latlon,alt,orient]); % Set position of own aircraft
        -6. status2 = sendPOSI([[latlon(1)+0.005,latlon(2)],alt,orient],1); % Set position of aircraft 1
        - -

        Change Log

        -10/02/14: [CT] V0.9 Updated to use new xpcPlugin
        -06/10/13: [CT] Code created

        -<-- Back
        - - - \ No newline at end of file diff --git a/MATLAB/pages/sendSTRU.html b/MATLAB/pages/sendSTRU.html deleted file mode 100644 index 7ec9b57..0000000 --- a/MATLAB/pages/sendSTRU.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - XPlaneConnect Toolbox-sendSTRU - - - - -<-- Back
        -

        sendSTRU

        -Send a MATLAB structure over UDP - -

        Inputs

        -
          -
        • stru: A MATLAB structure
        • -
        • IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine)
        • -
        • port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin
        • -
        - -

        Outputs

        -
          -
        • status: If there was an error. Status<0 means there was an error.
        • -
        - -

        Use

        -1. import XPlaneConnect.*;
        -2. data = struct('a',[1:20],'b',1.853,'name','Example Structure');
        -3. #Send the data structure to port 49005 on the computer at IP address 172.0.100.54
        -4. status = sendSTRU( data, '172.0.100.54', 49005 );
        - -

        Change Log

        -10/02/14: [CT] V0.9: Updated to work with updated xpcPlugin
        -08/01/13: [CT] Code created

        -<-- Back
        - - - \ No newline at end of file diff --git a/MATLAB/pages/sendUDP.html b/MATLAB/pages/sendUDP.html deleted file mode 100644 index 92e4ae4..0000000 --- a/MATLAB/pages/sendUDP.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - XPlaneConnect Toolbox-sendUDP - - - - -<-- Back
        -

        sendUDP

        -Send an one dimensional array of type uint8 data over an UDP connection - -

        Inputs

        -
          -
        • data: 1-D array of type uint8 data to be sent
        • -
        • IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine)
        • -
        • port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp
        • -
        - -

        Outputs

        -
          -
        • status: If there was an error. Status=1 means there was an error.
        • -
        - -

        Use

        -1. import XPlaneConnect.*;
        -2. data = uint8([1:20]);
        -3. #Send the data array to port 49005 on the computer at IP address 172.0.100.54.
        -4. status = sendUDP( data, '172.0.100.54', 49005 );
        - -

        Change Log

        -10/02/14: [CT] V0.9: Updated to work with updated xpcPlugin
        -06/10/13: [CT] Code created

        -<-- Back
        - - - \ No newline at end of file diff --git a/MATLAB/pages/setConn.html b/MATLAB/pages/setConn.html deleted file mode 100644 index 568f929..0000000 --- a/MATLAB/pages/setConn.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - XPlaneConnect Toolbox-setConn - - - - -<-- Back
        -

        setConn

        -Send a command to set up the port where you will receive data on this computer. - -

        Inputs

        -
          -
        • Receiving Port: Port that data will be sent to in the future for this connection
        • -
        • IP Address (optional): IP Address of the machine that will receive the data as a character array. Default is '127.0.0.1' (local machine)
        • -
        • port (optional): Port on the receiving machine where the data will be sent. Default is 49009 (XPlaneConnect). In general use 49009 to send to the plugin and 49005 to send to the x-plane udp
        • -
        - -

        Outputs

        -
          -
        • status: If there was an error. status<0 means there was an error.
        • -
        - -

        Use

        -1. import XPlaneConnect.*
        -2. status = setConn(49011);
        - -

        Change Log

        -10/02/14: [CT] V0.9: Updated to work with updated xpcPlugin
        -04/21/14: [CT] V0.2: First Version

        -<-- Back
        - - - \ No newline at end of file diff --git a/README.md b/README.md index fbe40ce..0065c56 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,121 @@ -XPlaneConnect -============= +#X-Plane Connect +The X-Plane Connect (XPC) Toolbox is an open source research tool used to +interact with the commercial flight simulator software X-Plane. XPC allows users +to control aircraft and receive state information from aircraft simulated in +X-Plane using functions written in C, C++, Java, or MATLAB in real time over the +network. This research tool has been used to visualize flight paths, test control +algorithms, simulate an active airspace, or generate out-the-window visuals for +in-house flight simulation software. Possible applications include active control +of an XPlane simulation, flight visualization, recording states during a flight, +or interacting with a mission over UDP. -The X-Plane Communications Toolbox (XPC) is an open source research tool used to interact with the commercial flight simulator software X-Plane. XPC allows users to control aircraft and receive state information from aircraft simulated in X-Plane using functions written in C, C++, java, or MATLAB in real time over the network. This research tool has been used to visualize flight paths, test control algorithms, simulate an active airspace, or generate out-the-window visuals for in-house flight simulation software. +###Migrating to 1.0 +For existing users, several important breaking changes have been made in version +1.0. For detailed information, see the 1.0 release changelog. For client-specific +guidlines on migrating to 1.0, refer to the follwing guides: + +####[C](https://github.com/nasa/XPlaneConnect/wiki/Migrating-to-1.0-C) + +####[MATLAB](https://github.com/nasa/XPlaneConnect/wiki/Migrating-to-1.0-MATLAB) + +####[Java](https://github.com/nasa/XPlaneConnect/wiki/Migrating-to-1.0-Java) + +###Architecture +XPC includes an X-Plane plugin (xpcPlugin) and clients written in several +languages that interact with the plugin. + +####Quick Start +To get started using X-Plane Connect, do the following. + +1. Purchase and install X-Plane 9 or 10. +2. Copy the X-Plane Plugin folder (xpcPlugin/XPlaneConnect) to the plugin +directory ([X-Plane Directory]/Resources/plugins/) +3. Write some code using one of the clients to manipulate X-Plane data. + +Each client is located in a top-level directory of the repository named for the +client's language. The client directories generally include a 'src' folder +containing the client source code, and an 'Examples' folder containing sample +code demonstrating how to use the client. + +####Additional Information +For detailed information about XPC and how to use the XPC clients, refer to the +[XPC Wiki](https://github.com/nasa/XPlaneConnect/wiki). + +####Capabilities +The XPC Toolbox allows the user to manipulate the internal state of X-Plane by +reading and setting DataRefs, a complete list of which can be found on the +[X-Plane SDK wiki](http://www.xsquawkbox.net/xpsdk/docs/DataRefs.html). + +In addition, several convenience functions are provided, which allow the user to +efficiently execute common commands. These functions include the ability to set +the position and control surfaces of both player and multiplayer aircraft. In +addition, the pause function allows users to easily pause and un-pause X-Plane's +physics simulation engine. + +###Compatibility +XPC has been tested with the following software versions: +* Windows: Vista, 7, & 8 +* Mac OSX: 10.8-10.10 +* Linux: Tested on Red Hat Enterprise Linux Workstation release 6.6 +* X-Plane: 9 & 10 + +###Contributing +All contributions are welcome! If you are having problems with the plugin, please +open an issue on GitHub or email [Chris Teubert](mailto:christopher.a.teuber@nasa.gov). +If you would like to contribute directly, please feel free to open a pull request +against the "develop" branch. Pull requests will be evaluated and integrated into +the next official release. + +###Notices +Copyright ©2013-2015 United States Government as represented by the Administrator +of the National Aeronautics and Space Administration. All Rights Reserved. + +No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY +KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY +WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR FREEDOM FROM +INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY +WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. +THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT +AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, HARDWARE, +SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS RESULTING FROM USE OF THE SUBJECT +SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND LIABILITIES +REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND +DISTRIBUTES IT "AS IS." + +Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST THE +UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY +PRIOR RECIPIENT. IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS IN ANY +LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH USE, +INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE +OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS THE UNITED +STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR +RECIPIENT, TO THE EXTENT PERMITTED BY LAW. RECIPIENT'S SOLE REMEDY FOR ANY SUCH +MATTER SHALL BE THE IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT. + +####X-Plane API +Copyright (c) 2008, Sandy Barbour and Ben Supnik All rights reserved. +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in the +Software without restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the +Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +* Redistributions of source code must retain the above copyright notice, this +list of conditions and the following disclaimer. +* Neither the names of the authors nor that of X-Plane or Laminar Research may +be used to endorse or promote products derived from this software without +specific prior written permission from the authors or Laminar Research, +respectively. + +X-Plane API SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS +OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN +IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/Readme.txt b/Readme.txt deleted file mode 100644 index f906e0d..0000000 --- a/Readme.txt +++ /dev/null @@ -1,60 +0,0 @@ -X-Plane Connect (XPC) Toolbox - -Description -The X-Plane Connect (XPC) Toolbox facilitates communication with X-Plane. This toolbox allows for the real-time manipulation of X-Plane variables. Possible applications include active control of an XPlane simulation, flight visualization, recording states during a flight, or interacting with a mission over UDP. - -Architecture -XPC includes a plugin (xpcPlugin) which is to be copied into the X-Plane Plugin Directory ([X-Plane Directory]/Resources/Plugin/), and the xpcScripts-A series of functions for communication with X-Plane. - -xpcPlugin (Directory: xpcPlugin/) - -xpcScripts - C: (Directory: C/src/, Example: C/xpcExample/) - MATLAB: (Directory: Matlab/+XPlaneConnect/, Example: MATLAB/xpcExample/) - java: (Directory: java/src/, Example: java/xpcExample/) - python: (future-Not complete yet): (Directory: python/xpc/, Example: python/xpcExample/) - -Instructions: - 1. Purchase/Install X-Plane - 2. Copy the X-Plane Plugin folder (xpcPlugin/XPlaneConnect) to the plugin directory ([X-Plane Directory]/Resources/plugins/) - 3. Write code using the xpcScrips to manipulate X-Plane - -Capabilities: - Set Aircraft Position (own or other aircraft): Use sendPOSI() - Control Aircraft (own or other aircraft): Use sendCTRL() - Set any internal X-Plane dataref: Use sendDREF() - Get the value of any X-Plane dataref: Use requestDREF() - Pause Simulation: Use pauseSim() - -Compatability: - Windows: - Tested on Windows Vista and Windows 7 - Mac OSX - Tested on OS X 10.8-10.10 - X-Plane - Tested with X-Plane 9 & 10 - -Notices: - -Copyright ©2013-2014 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. - -Disclaimers - -No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS." - -Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT. -X-Plane API -Copyright (c) 2008, Sandy Barbour and Ben Supnik All rights reserved. -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Neither the names of the authors nor that of X-Plane or Laminar Research - may be used to endorse or promote products derived from this software - without specific prior written permission from the authors or - Laminar Research, respectively. - -X-Plane API SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -Contributors: - CT: Chris Teubert (christopher.a.teubert@nasa.gov) diff --git a/TestScripts/C Tests.win/CTests.vcxproj b/TestScripts/C Tests.win/CTests.vcxproj index 9ba4d07..c057e7d 100644 --- a/TestScripts/C Tests.win/CTests.vcxproj +++ b/TestScripts/C Tests.win/CTests.vcxproj @@ -22,6 +22,9 @@ + + + {BC701AF4-552C-4C9D-82A1-B352542783A4} CTests diff --git a/TestScripts/C Tests.win/CTests.vcxproj.filters b/TestScripts/C Tests.win/CTests.vcxproj.filters index fae10d4..cd3ca2c 100644 --- a/TestScripts/C Tests.win/CTests.vcxproj.filters +++ b/TestScripts/C Tests.win/CTests.vcxproj.filters @@ -22,4 +22,9 @@ Source Files + + + Header Files + + \ No newline at end of file diff --git a/TestScripts/C Tests/main.c b/TestScripts/C Tests/main.c index 4ee58ba..ffce4ce 100644 --- a/TestScripts/C Tests/main.c +++ b/TestScripts/C Tests/main.c @@ -11,17 +11,17 @@ #include #include #include -#include "xplaneconnect.h" +#include "xplaneConnect.h" + +#define IP "127.0.0.1" int testFailed = 0; int testPassed = 0; -void runTest(short (*f)()) +void runTest(int (*test)(), char* name) { - short result; - - printf("Test %i: ",testPassed+testFailed+1); - result = (*f)(); // Run Test + int result = test(); // Run Test + printf("Test %i: %s - ", testPassed + testFailed + 1, name); if (result == 0) { printf("PASSED\n"); @@ -34,550 +34,895 @@ void runTest(short (*f)()) } } -short openTest() // openUDP Test +int openTest() // openUDP Test { - printf("openUDP - "); - struct xpcSocket sendPort = openUDP( 49062, "127.0.0.1", 49009 ); - return 0; + XPCSocket sock = openUDP("localhost"); + int result = strncmp(sock.xpIP, "127.0.0.1", 16); + closeUDP(sock); + return result; } -short closeTest() // closeUDP test +int closeTest() // closeUDP test { - printf("closeUDP - "); - struct xpcSocket sendPort = openUDP( 49063, "127.0.0.1", 49009 ); + XPCSocket sendPort = aopenUDP(IP, 49009, 49063); closeUDP(sendPort); - sendPort = openUDP(49063, "127.0.0.1", 49009); + sendPort = aopenUDP(IP, 49009, 49063); closeUDP(sendPort); return 0; } -short sendReadTest() // send/read Test +int sendTEXTTest() { - printf("send/readUDP - "); - - // Initialization - int i; // Iterator - char test[] = {0, 1, 2, 3, 5}; - char buf[5] = {0}; - struct xpcSocket sendPort, recvPort; - - // Setup - sendPort = openUDP( 49064, "127.0.0.1", 49063 ); - recvPort = openUDP( 49063, "127.0.0.1", 49009 ); - - // Execution - sendUDP( sendPort, test, sizeof(test) ); - readUDP( recvPort, buf, NULL ); // Test - - // Close - closeUDP(sendPort); - closeUDP(recvPort); - - // Tests - for (i=0; i<4; i++) - { - if (test[i] != buf[i]) // Not received correctly - { - return -1; - } - } - - return 0; -} - -short sendTEXTTest() -{ - printf("sendTEXT - "); - // Setup - struct xpcSocket sendPort = openUDP(49064, "127.0.0.1", 49009); + XPCSocket sendPort = openUDP(IP); int x = 100; int y = 700; - char* msg = "XPlaneConnect test message. Now with 100% fewer new lines!"; + char* msg = "This is an X-Plane Connect test message.\nThis should be a new line.\r\nThat will be parsed as two line breaks."; // Test sendTEXT(sendPort, msg, x, y); // NOTE: Manually verify that msg appears on the screen in X-Plane! + sendTEXT(sendPort, "Another test message", x, y); + // NOTE: Manually verify that msg appears on the screen and that no part of the previous + // message is visible. + + sendTEXT(sendPort, NULL, -1, -1); + // Cleanup closeUDP(sendPort); return 0; } -short requestDREFTest() // Request DREF Test (Required for next tests) +int getDREFTest() // Request DREF Test (Required for next tests) { - printf("requestDREF - "); - // Initialization - int i; // Iterator - char DREFArray[100][100]; - float *recDATA[100]; - short DREFSizes[100]; - struct xpcSocket sendPort, recvPort; - short result = 0; + // Get one DREF of each type (int, float, int[], float[], double, byte[]) + #define GETD_COUNT 6 + char* drefs[GETD_COUNT] = + { + "sim/cockpit/switches/gear_handle_status", //int + "sim/cockpit/autopilot/altitude", //float + "sim/aircraft/prop/acf_prop_type", //int[8] + "sim/cockpit2/switches/panel_brightness_ratio", //float[4] + "sim/aircraft/view/acf_tailnum", //byte[40] + "sim/flightmodel/position/elevation" //double + }; + float* data[GETD_COUNT]; + int sizes[GETD_COUNT]; + XPCSocket sock = openUDP(IP); // Setup - for (i = 0; i < 100; i++) { - recDATA[i] = (float *) malloc(40*sizeof(float)); - memset(DREFArray[i],0,100); - } - sendPort = openUDP( 49064, "127.0.0.1", 49009 ); - recvPort = openUDP( 49008, "127.0.0.1", 49009 ); - strcpy(DREFArray[0],"sim/cockpit/switches/gear_handle_status"); - strcpy(DREFArray[1],"sim/cockpit2/switches/panel_brightness_ratio"); - for (i=0;i<2;i++) { - DREFSizes[i] = (int) strlen(DREFArray[i]); - } + for (int i = 0; i < GETD_COUNT; ++i) + { + data[i] = (float*)malloc(256 * sizeof(float)); + sizes[i] = 256; + } // Execution - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 2, recDATA, DREFSizes); + int result = getDREFs(sock, drefs, data, GETD_COUNT, sizes); // Close - closeUDP(sendPort); - closeUDP(recvPort); + closeUDP(sock); // Tests - if ( result < 0)// Request 2 values + if (result < 0) { return -1; } - if (DREFSizes[0] != 1 || DREFSizes[1] != 4) + // Verify sizes + if (sizes[0] != 1 || sizes[1] != 1 || sizes[2] != 8 + || sizes[3] != 4 || sizes[4] != 40 || sizes[5] != 1) { return -2; } + // Verify integer drefs are integers + if ((float)((int)data[0][0]) != data[0][0]) + { + return -3; + } + for (int i = 0; i < 8; ++i) + { + if ((float)((int)data[2][i]) != data[2][i]) + { + return -3; + } + } + for (int i = 0; i < 40; ++i) + { + if ((float)((char)data[4][i]) != data[4][i]) + { + return -3; + } + } + // Verify tail number has at least one valid character + if (data[4][0] <= 0 || data[4][0] > 127) + { + return -4; + } return 0; } -short sendDREFTest() // sendDREF test +int sendDREFTest() // sendDREF test { - printf("sendDREF - "); - // Initialization - int i; // Iterator - char DREFArray[100][100]; - float *recDATA[100]; - short DREFSizes[100]; - float value = 0.0; - struct xpcSocket sendPort, recvPort; - short result = 0; - - // Setup - for (i = 0; i < 100; i++) { - recDATA[i] = (float *) malloc(40*sizeof(float)); - memset(DREFArray[i],0,100); - } - sendPort = openUDP( 49066, "127.0.0.1", 49009 ); - recvPort = openUDP( 49008, "127.0.0.1", 49009 ); - strcpy(DREFArray[0],"sim/cockpit/switches/gear_handle_status"); - for (i=0;i<1;i++) { - DREFSizes[i] = (int) strlen(DREFArray[i]); - } - + // Set one DREF of each type (int, float, int[], float[], double, byte[]) + // Also set one read-only to make sure it fails + #define DREF_COUNT 6 + char* drefs[DREF_COUNT] = + { + "sim/cockpit/switches/gear_handle_status", //int + "sim/cockpit/autopilot/altitude", //float + "sim/aircraft/prop/acf_prop_type", //int[8] + "sim/cockpit2/switches/panel_brightness_ratio", //float[4] + "sim/aircraft/view/acf_tailnum", //byte[40] + "sim/flightmodel/position/elevation" //double - Read only + }; + float* data[DREF_COUNT]; + int sizes[DREF_COUNT]; + float* values[DREF_COUNT]; + XPCSocket sock = openUDP(IP); + + // Setup + sizes[0] = 1; + values[0] = (float*)malloc(sizes[0] * sizeof(float)); + values[0][0] = 1; + + sizes[1] = 1; + values[1] = (float*)malloc(sizes[1] * sizeof(float)); + values[1][0] = 4000.0F; + + sizes[2] = 8; + values[2] = (float*)malloc(sizes[2] * sizeof(float)); + for (int i = 0; i < 8; ++i) + { + values[2][i] = 0; + } + + sizes[3] = 4; + values[3] = (float*)malloc(sizes[3] * sizeof(float)); + for (int i = 0; i < 4; ++i) + { + values[3][i] = 0.25F; + } + + sizes[4] = 40; + values[4] = (float*)malloc(sizes[4] * sizeof(float)); + memset(values[4], 0, sizes[4] * sizeof(float)); + values[4][0] = 78.0F; //N + values[4][1] = 55.0F; //7 + values[4][2] = 52.0F; //4 + values[4][3] = 56.0F; //8 + values[4][4] = 53.0F; //5 + values[4][5] = 89.0F; //Y + + sizes[5] = 1; + values[5] = (float*)malloc(sizes[5] * sizeof(float)); + values[5][0] = 5000.0F; + // Execution - sendDREF(sendPort, DREFArray[0], DREFSizes[0], &value, 1); - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 1, recDATA, DREFSizes); + for (int i = 0; i < DREF_COUNT; ++i) + { + sendDREF(sock, drefs[i], values[i], sizes[i]); + data[i] = (float*)malloc(256 * sizeof(float)); + sizes[i] = 256; + } + int result = getDREFs(sock, drefs, data, DREF_COUNT, sizes); // Close - closeUDP(sendPort); - closeUDP(recvPort); + closeUDP(sock); // Tests - if (result < 0)// Request 1 value + if (result < 0) { return -1; } - if (DREFSizes[0] != 1) - { - return -2; - } - if (*recDATA[0] != value) - { - return -3; - } + // Verify gear handle was set + if (sizes[0] != 1 || data[0][0] != 1) + { + return -2; + } + // Verify autopilot altitude was set + if (sizes[1] != 1 || data[1][0] != 4000.0F) + { + return -3; + } + // Verify prop type was set + if (sizes[2] != 8) + { + return -4; + } + for (int i = 0; i < 8; ++i) + { + if (data[2][i] != values[2][i]) + { + return -4; + } + } + // Verify panel brightness was set + if (sizes[3] != 4) + { + return -5; + } + for (int i = 0; i < 4; ++i) + { + if (data[3][i] != values[3][i]) + { + return -5; + } + } + // Verify tail number was set + for (int i = 0; i < 6; ++i) + { + if (data[4][i] != values[4][i]) + { + return -6; + } + } + // Verify aircraft elevation was NOT set + if (sizes[5] != 1 || data[5][0] == 5000.0F) + { + return -7; + } return 0; } -short sendDATATest() // sendDATA test +int sendDATATest() // sendDATA test { - printf("sendData - "); - // Initialize int i,j; // Iterator - char DREFArray[100][100]; - float data[4][9] = {0}; - float *recDATA[100]; - short DREFSizes[100]; - struct xpcSocket sendPort, recvPort; - short result = 0; - - // Setup - for (i = 0; i < 100; i++) { - recDATA[i] = (float *) malloc(40*sizeof(float)); - memset(DREFArray[i],0,100); - } - sendPort = openUDP( 49066, "127.0.0.1", 49009 ); - recvPort = openUDP( 49008, "127.0.0.1", 49009 ); - strcpy(DREFArray[0],"sim/aircraft/parts/acf_gear_deploy"); - for (i=0;i<1;i++) { - DREFSizes[i] = (int) strlen(DREFArray[i]); - } - for (i=0;i<4;i++) { // Set array to -999 - for (j=0;j<9;j++) data[i][j] = -999; - } - data[0][0] = 14; // Gear - data[0][1] = 1; - data[0][2] = 0; + char* drefs[100] = + { + "sim/aircraft/parts/acf_gear_deploy" + }; + float* data[100]; // array for result of getDREFs + int sizes[100]; + float DATA[4][9]; // Array for sendDATA + XPCSocket sock = openUDP(IP); + + // Setup + for (int i = 0; i < 100; ++i) + { + data[i] = (float*)malloc(40 * sizeof(float)); + sizes[i] = 40; + } + for (i = 0; i < 4; i++) + { + for (j = 0; j < 9; j++) + { + data[i][j] = -998; + } + } + DATA[0][0] = 14; // Gear + DATA[0][1] = 1; + DATA[0][2] = 0; // Execution - sendDATA(sendPort, data, 1); // Gear - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 1, recDATA, DREFSizes); // Test + sendDATA(sock, DATA, 1); + int result = getDREFs(sock, drefs, data, 1, sizes); // Close - closeUDP(sendPort); - closeUDP(recvPort); + closeUDP(sock); // Tests if ( result < 0 )// Request 1 value { return -1; } - if (DREFSizes[0] != 10) + if (sizes[0] != 10) { return -2; } - if (*recDATA[0] != data[0][1]) + if (*data[0] != data[0][1]) { return -3; } return 0; } -short sendCTRLTest() // sendCTRL test +int psendCTRLTest() // sendCTRL test { - printf("sendCTRL - "); - // Initialize - int i; // Iterator - char DREFArray[100][100]; - float CTRL[6] = { 0.0 }; - float *recDATA[100]; - short DREFSizes[100]; - struct xpcSocket sendPort, recvPort; - short result; + char* drefs[100] = + { + "sim/cockpit2/controls/yoke_pitch_ratio", + "sim/cockpit2/controls/yoke_roll_ratio", + "sim/cockpit2/controls/yoke_heading_ratio", + "sim/flightmodel/engine/ENGN_thro", + "sim/cockpit/switches/gear_handle_status", + "sim/flightmodel/controls/flaprqst" + }; + float* data[100]; + int sizes[100]; + float CTRL[6] = { 0.0F, 0.0F, 0.0F, 0.8F, 1.0F, 0.5F }; + XPCSocket sock = openUDP(IP); // Setup - for (i = 0; i < 100; i++) { - recDATA[i] = (float *)malloc(40 * sizeof(float)); - memset(DREFArray[i], 0, 100); + for (int i = 0; i < 100; i++) + { + data[i] = (float*)malloc(40 * sizeof(float)); + sizes[i] = 40; } - sendPort = openUDP(49066, "127.0.0.1", 49009); - recvPort = openUDP(49008, "127.0.0.1", 49009); - strcpy(DREFArray[0], "sim/cockpit2/controls/yoke_pitch_ratio"); - strcpy(DREFArray[1], "sim/cockpit2/controls/yoke_roll_ratio"); - strcpy(DREFArray[2], "sim/cockpit2/controls/yoke_heading_ratio"); - strcpy(DREFArray[3], "sim/flightmodel/engine/ENGN_thro"); - strcpy(DREFArray[4], "sim/cockpit/switches/gear_handle_status"); - strcpy(DREFArray[5], "sim/flightmodel/controls/flaprqst"); - for (i = 0; i < 100; i++) { - DREFSizes[i] = (int)strlen(DREFArray[i]); - } - CTRL[3] = 0.8; // Throttle - CTRL[4] = 1; // Gear - CTRL[5] = 0.5; // Flaps - // Execute - sendCTRL(sendPort, 6, CTRL); - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 6, recDATA, DREFSizes); // Test + // Execute 1 + // 0 pitch, roll, yaw + sendCTRL(sock, CTRL, 3, 0); + int result = getDREFs(sock, drefs, data, 6, sizes); - // Close - closeUDP(sendPort); - closeUDP(recvPort); + // Close socket + closeUDP(sock); // Tests - if (result < 0)// Request 1 value + if (result < 0) { - return -6; + return -1; } - for (i = 0; i<6; i++) + for (int i = 0; i < 3; i++) { - if (fabs(recDATA[i][0] - CTRL[i])>1e-4) + if (fabs(data[i][0] - CTRL[i]) > 1e-4) { - return -i - 1; + return -i - 11; + } + } + + sock = openUDP(IP); + // Execute 2 + // Set non-zero pitch, roll, & yaw. Also set throttle, gear, and flaps + CTRL[0] = 0.2F; + CTRL[1] = 0.1F; + CTRL[2] = 0.1F; + sendCTRL(sock, CTRL, 6, 0); + result = getDREFs(sock, drefs, data, 6, sizes); + + // Close socket + closeUDP(sock); + + // Tests + if (result < 0) + { + return -2; + } + for (int i = 0; i < 6; i++) + { + if (fabs(data[i][0] - CTRL[i]) > 1e-4) + { + return -i - 21; + } + } + + sock = openUDP(IP); + // Execute 2 + // Set non-zero pitch, roll, & yaw. Also set throttle, gear, and flaps + CTRL[0] = -998.0F; + CTRL[1] = -998.0F; + CTRL[2] = -998.0F; + sendCTRL(sock, CTRL, 6, 0); + result = getDREFs(sock, drefs, data, 6, sizes); + + // Close socket + closeUDP(sock); + + // Tests + if (result < 0) + { + return -3; + } + for (int i = 0; i < 6; i++) + { + if (fabs(data[i][0] - CTRL[i]) > 1e-2) + { + return -i - 31; } } return 0; } -short sendpCTRLTest() +int sendCTRLTest() { - printf("sendNonPlayerCTRL - "); - // Initialize - int i; // Iterator - char DREFArray[100][100]; - float CTRL[6] = { 0.0 }; - float *recDATA[100]; - short DREFSizes[100]; - struct xpcSocket sendPort, recvPort; - short result; + char* drefs[100] = + { + "sim/multiplayer/position/plane1_yolk_pitch", + "sim/multiplayer/position/plane1_yolk_roll", + "sim/multiplayer/position/plane1_yolk_yaw", + "sim/multiplayer/position/plane1_throttle", + "sim/multiplayer/position/plane1_gear_deploy", + "sim/multiplayer/position/plane1_flap_ratio", + }; + float* data[100]; + int sizes[100]; + float CTRL[6] = { 0.0F, 0.0F, 0.0F, 0.8F, 1.0F, 0.5F }; + XPCSocket sock = openUDP(IP); // Setup - for (i = 0; i < 100; i++) + for (int i = 0; i < 100; i++) { - recDATA[i] = (float *)malloc(40 * sizeof(float)); - memset(DREFArray[i], 0, 100); + data[i] = (float*)malloc(40 * sizeof(float)); + sizes[i] = 40; } - sendPort = openUDP(49066, "127.0.0.1", 49009); - recvPort = openUDP(49008, "127.0.0.1", 49009); - strcpy(DREFArray[0], "sim/multiplayer/position/plane1_yolk_pitch"); - strcpy(DREFArray[1], "sim/multiplayer/position/plane1_yolk_roll"); - strcpy(DREFArray[2], "sim/multiplayer/position/plane1_yolk_yaw"); - strcpy(DREFArray[3], "sim/multiplayer/position/plane1_throttle"); - strcpy(DREFArray[4], "sim/multiplayer/position/plane1_gear_deploy"); - strcpy(DREFArray[5], "sim/multiplayer/position/plane1_flap_ratio"); - for (i = 0; i < 100; i++) - { - DREFSizes[i] = (int)strlen(DREFArray[i]); - } - CTRL[3] = 0.8; // Throttle - CTRL[4] = 1; // Gear - CTRL[5] = 0.5; // Flaps - // Execute - sendpCTRL(sendPort, 6, CTRL, 1); - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 9, recDATA, DREFSizes); // Test + // Execute 1 + // 0 pitch, roll, yaw + sendCTRL(sock, CTRL, 3, 1); + int result = getDREFs(sock, drefs, data, 6, sizes); - // Close - closeUDP(sendPort); - closeUDP(recvPort); + // Close socket + closeUDP(sock); // Tests - if (result < 0)// Request 1 value + if (result < 0) { - return -6; + return -1; } - for (i = 0; i<6; i++) + for (int i = 0; i < 3; i++) { - if (fabs(recDATA[i][0] - CTRL[i])>1e-4) + if (fabs(data[i][0] - CTRL[i]) > 1e-4) { - return -i - 1; + return -i - 11; + } + } + + sock = openUDP(IP); + // Execute 2 + // Set non-zero pitch, roll, & yaw. Also set throttle, gear, and flaps + CTRL[0] = 0.2F; + CTRL[1] = 0.1F; + CTRL[2] = 0.1F; + sendCTRL(sock, CTRL, 6, 1); + result = getDREFs(sock, drefs, data, 6, sizes); + + // Close socket + closeUDP(sock); + + // Tests + if (result < 0) + { + return -2; + } + for (int i = 0; i < 6; i++) + { + if (fabs(data[i][0] - CTRL[i]) > 1e-4) + { + return -i - 21; + } + } + + sock = openUDP(IP); + // Execute 2 + // Set non-zero pitch, roll, & yaw. Also set throttle, gear, and flaps + CTRL[0] = -998.0F; + CTRL[1] = -998.0F; + CTRL[2] = -998.0F; + sendCTRL(sock, CTRL, 6, 1); + result = getDREFs(sock, drefs, data, 6, sizes); + + // Close socket + closeUDP(sock); + + // Tests + if (result < 0) + { + return -3; + } + for (int i = 0; i < 6; i++) + { + if (fabs(data[i][0] - CTRL[i]) > 1e-2) + { + return -i - 31; } } return 0; } -short sendPOSITest() // sendPOSI test +int psendPOSITest() // sendPOSI test { - printf("sendPOSI - "); - - // Initialization - int i; // Iterator - char DREFArray[100][100]; - float POSI[8] = {0.0}; - float *recDATA[100]; - short DREFSizes[100]; - struct xpcSocket sendPort, recvPort; - short result; - - // Setup - for (i = 0; i < 100; i++) { - recDATA[i] = (float *) malloc(40*sizeof(float)); - memset(DREFArray[i],0,100); - } - sendPort = openUDP( 49063, "127.0.0.1", 49009 ); - recvPort = openUDP( 49008, "127.0.0.1", 49009 ); - strcpy(DREFArray[0],"sim/flightmodel/position/latitude"); - strcpy(DREFArray[1],"sim/flightmodel/position/longitude"); - strcpy(DREFArray[2],"sim/flightmodel/position/y_agl"); - strcpy(DREFArray[3],"sim/flightmodel/position/phi"); - strcpy(DREFArray[4],"sim/flightmodel/position/theta"); - strcpy(DREFArray[5],"sim/flightmodel/position/psi"); - strcpy(DREFArray[6],"sim/cockpit/switches/gear_handle_status"); - for (i=0;i<7;i++) { - DREFSizes[i] = (int) strlen(DREFArray[i]); - } - POSI[0] = 37.524; // Lat - POSI[1] = -122.06899; // Lon - POSI[2] = 2500; // Alt - POSI[3] = 0; // Pitch - POSI[4] = 0; // Roll - POSI[5] = 0; // Heading - POSI[6] = 1; // Gear - - // Execution - sendPOSI( sendPort, 0, 7, POSI ); - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 7, recDATA, DREFSizes); // Test - - // Close - closeUDP(sendPort); - closeUDP(recvPort); - - // Tests - if ( result < 0 )// Request 1 value - { - return -7; - } - for (i=0;i<7-1;i++) - { - if (i==2) - { - continue; - } - if (fabs(recDATA[i][0]-POSI[i])>1e-4) - { - return -i; - } - } - - - return 0; -} - -short sendWYPTTest() -{ - printf("sendWYPT - "); + // Initialization + int i; // Iterator + char* drefs[100] = + { + "sim/flightmodel/position/latitude", + "sim/flightmodel/position/longitude", + "sim/flightmodel/position/elevation", + "sim/flightmodel/position/theta", + "sim/flightmodel/position/phi", + "sim/flightmodel/position/psi", + "sim/cockpit/switches/gear_handle_status" + }; + float* data[100]; + int sizes[100]; + float POSI[7] = { 37.524F, -122.06899F, 2500, 0, 0, 0, 1 }; + XPCSocket sock = openUDP(IP); // Setup - struct xpcSocket sendPort = openUDP(49064, "127.0.0.1", 49009); + for (i = 0; i < 100; i++) + { + data[i] = (float*)malloc(40 * sizeof(float)); + sizes[i] = 40; + } + + // Execution 1 + pauseSim(sock, 1); + sendPOSI(sock, POSI, 7, 0); + int result = getDREFs(sock, drefs, data, 7, sizes); + pauseSim(sock, 0); + + // Close + closeUDP(sock); + + // Tests + if (result < 0) + { + return -1; + } + for (i = 0; i < 7; ++i) + { + if (fabs(data[i][0] - POSI[i]) > 1e-4) + { + return -i - 11; + } + } + + // Setup 2 + sock = openUDP(IP); + POSI[0] = -998.0F; + POSI[1] = -998.0F; + POSI[2] = -998.0F; + POSI[3] = 5.0F; + POSI[4] = -5.0F; + POSI[5] = 10.0F; + POSI[6] = 0; + + // Execution 2 + pauseSim(sock, 1); + float *loc[3]; + for(int i = 0; i < 3; ++i) + { + loc[i] = (float*)malloc(sizeof(float)); + } + getDREFs(sock, drefs, &loc, 3, sizes); + sendPOSI(sock, POSI, 7, 0); + result = getDREFs(sock, drefs, data, 7, sizes); + pauseSim(sock, 0); + + // Close + closeUDP(sock); + + // Tests + if (result < 0) + { + return -2; + } + // Compare position to make sure they weren't set + for (int i = 0; i < 3; ++i) + { + // Note: Because the sim was paused when both of these were read, we really do expect *exactly* + // the same value even though we are comparing floats. + if (data[i][0] != loc[i][0]) + { + return -i - 21; + } + } + // Compare everything else. + for (i = 3; i < 7; ++i) + { + if (fabs(data[i][0] - POSI[i]) > 1e-4) + { + return -i - 21; + } + } + + // Setup 3 + sock = openUDP(IP); + POSI[0] = 37.524F; + POSI[1] = -122.06899F; + POSI[2] = 20000; + POSI[3] = 15.0F; + POSI[4] = -25.0F; + POSI[5] = -10.0F; + POSI[6] = 1; + + // Execution 2 + pauseSim(sock, 1); + sendPOSI(sock, POSI, 3, 0); + result = getDREFs(sock, drefs, data, 7, sizes); + pauseSim(sock, 0); + + // Close + closeUDP(sock); + + // Tests + if (result < 0) + { + return -3; + } + // Compare position to make sure it was set. + for (int i = 0; i < 3; ++i) + { + if (fabs(data[i][0] - POSI[i]) > 1e-4) + { + return -i - 31; + } + } + // Compare everything else to make sure it *wasn't*. + for (i = 3; i < 7; ++i) + { + if (fabs(data[i][0] - POSI[i]) < 1) + { + return -i - 31; + } + } + + return 0; +} + +int sendPOSITest() // sendPOSI test +{ + // Initialization + int i; // Iterator + char* drefs[100] = + { + // TODO: Can't get global position for multiplayer a/c? + "sim/multiplayer/position/plane1_lat", + "sim/multiplayer/position/plane1_lon", + "sim/multiplayer/position/plane1_el", + "sim/multiplayer/position/plane1_the", + "sim/multiplayer/position/plane1_phi", + "sim/multiplayer/position/plane1_psi", + "sim/multiplayer/position/plane1_gear_deploy" + }; + float* data[100]; + int sizes[100]; + float POSI[7] = { 37.524F, -122.06899F, 2500, 0, 0, 0, 1 }; + XPCSocket sock = openUDP(IP); + + // Setup + for (i = 0; i < 100; i++) + { + data[i] = (float*)malloc(40 * sizeof(float)); + sizes[i] = 40; + } + + // Execution 1 + pauseSim(sock, 1); + sendPOSI(sock, POSI, 7, 1); + int result = getDREFs(sock, drefs, data, 7, sizes); + pauseSim(sock, 0); + + // Close + closeUDP(sock); + + // Tests + if (result < 0) + { + return -1; + } + for (i = 0; i < 7; ++i) + { + if (fabs(data[i][0] - POSI[i]) > 1e-4) + { + return -i - 11; + } + } + + // Setup 2 + sock = openUDP(IP); + POSI[0] = -998.0F; + POSI[1] = -998.0F; + POSI[2] = -998.0F; + POSI[3] = 5.0F; + POSI[4] = -5.0F; + POSI[5] = 10.0F; + POSI[6] = 0; + + // Execution 2 + pauseSim(sock, 1); + float* loc[3]; + for(int i = 0; i < 3; ++i) + { + loc[i] = (float*)malloc(sizeof(float)); + } + getDREFs(sock, drefs, loc, 3, sizes); + sendPOSI(sock, POSI, 7, 1); + result = getDREFs(sock, drefs, data, 7, sizes); + pauseSim(sock, 0); + + // Close + closeUDP(sock); + + // Tests + if (result < 0) + { + return -2; + } + // Compare position to make sure they weren't set + for (int i = 0; i < 3; ++i) + { + // Note: Because the sim was paused when both of these were read, we really do expect *exactly* + // the same value even though we are comparing floats. + if (data[i][0] != loc[i][0]) + { + return -i - 21; + } + } + // Compare everything else. + for (i = 3; i < 7; ++i) + { + if (fabs(data[i][0] - POSI[i]) > 1e-4) + { + return -i - 21; + } + } + + // Setup 3 + sock = openUDP(IP); + POSI[0] = 37.524F; + POSI[1] = -122.06899; + POSI[2] = 20000; + POSI[3] = 15.0F; + POSI[4] = -25.0F; + POSI[5] = -10.0F; + POSI[6] = 1; + + // Execution 2 + pauseSim(sock, 1); + sendPOSI(sock, POSI, 3, 1); + result = getDREFs(sock, drefs, data, 7, sizes); + pauseSim(sock, 0); + + // Close + closeUDP(sock); + + // Tests + if (result < 0) + { + return -3; + } + // Compare position to make sure it was set. + for (int i = 0; i < 3; ++i) + { + if (fabs(data[i][0] - POSI[i]) > 1e-4) + { + return -i - 31; + } + } + // Compare everything else to make sure it *wasn't*. + for (i = 3; i < 7; ++i) + { + if (fabs(data[i][0] - POSI[i]) < 1) + { + return -i - 31; + } + } + + return 0; +} + +int sendWYPTTest() +{ + // Setup + XPCSocket sock = openUDP(IP); float points[] = { - 37.5245, -122.06899, 2500, - 37.455397, -122.050037, 2500, - 37.469567, -122.051411, 2500, - 37.479376, -122.060509, 2300, - 37.482237, -122.076130, 2100, - 37.474881, -122.087288, 1900, - 37.467660, -122.079391, 1700, - 37.466298, -122.090549, 1500, - 37.362562, -122.039223, 1000, - 37.361448, -122.034416, 1000, - 37.361994, -122.026348, 1000, - 37.365541, -122.022572, 1000, - 37.373727, -122.024803, 1000, - 37.403869, -122.041283, 50, - 37.418544, -122.049222, 6 + 37.5245F, -122.06899F, 2500, + 37.455397F, -122.050037F, 2500, + 37.469567F, -122.051411F, 2500, + 37.479376F, -122.060509F, 2300, + 37.482237F, -122.076130F, 2100, + 37.474881F, -122.087288F, 1900, + 37.467660F, -122.079391F, 1700, + 37.466298F, -122.090549F, 1500, + 37.362562F, -122.039223F, 1000, + 37.361448F, -122.034416F, 1000, + 37.361994F, -122.026348F, 1000, + 37.365541F, -122.022572F, 1000, + 37.373727F, -122.024803F, 1000, + 37.403869F, -122.041283F, 50, + 37.418544F, -122.049222F, 6 }; // Test - sendWYPT(sendPort, xpc_WYPT_ADD, points, 15); + sendWYPT(sock, XPC_WYPT_CLR, NULL, 0); + sendWYPT(sock, XPC_WYPT_ADD, points, 15); + // NOTE: Visually ensure waypoints are added in the sim // Cleanup - closeUDP(sendPort); + closeUDP(sock); return 0; } -short pauseTest() // pauseSim test +int pauseTest() // pauseSim test { - printf("pauseSim - "); - // Initialize - int i; // Iterator - char DREFArray[100][100]; - float *recDATA[100]; - short DREFSizes[100],RECSizes[100]; - struct xpcSocket sendPort, recvPort; - short result; + // Note: Always run this test to the end so that the sim ends up unpaused in the + // case where commands are working but reading results isn't. + int result = 0; + char* drefs[100] = + { + "sim/operation/override/override_planepath" + }; + float* data[100]; + int sizes[100]; + XPCSocket sock = openUDP(IP); // Setup - for (i = 0; i < 100; i++) { - recDATA[i] = (float *) malloc(40*sizeof(float)); - memset(DREFArray[i],0,100); - } - - // Setup - sendPort = openUDP( 49064, "127.0.0.1", 49009 ); - recvPort = openUDP( 49008, "127.0.0.1", 49009 ); - strcpy(DREFArray[0],"sim/operation/override/override_planepath"); - for (i=0;i<1;i++) { - DREFSizes[i] = (int) strlen(DREFArray[i]); + for (int i = 0; i < 100; i++) + { + data[i] = (float*)malloc(40 * sizeof(float)); + sizes[i] = 40; } // Execute - pauseSim(sendPort, 1); - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 1, recDATA, RECSizes); // Test - - // Close - closeUDP(sendPort); - closeUDP(recvPort); - + pauseSim(sock, 1); + result = getDREF(sock, drefs[0], data[0], sizes); + // Test - if (result < 0) { - return -1; - } - if (recDATA[0][0] != 1) - { - return -2; - } - - // Reopen - sendPort = openUDP( 49064, "127.0.0.1", 49009 ); - recvPort = openUDP( 49008, "127.0.0.1", 49009 ); - - // Execute 2 - pauseSim(sendPort, 0); - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 1, recDATA, RECSizes); // Test - - // Close 2 - closeUDP(sendPort); - closeUDP(recvPort); - - // Test 2 if (result < 0) - { - return -3; + { + result = -1; } - if (recDATA[0][0] != 0) + if (data[0][0] != 1) { - return -4; + result = -2; } + + if (result == 0) + { + // Execute 2 + pauseSim(sock, 0); + result = getDREF(sock, drefs[0], data[0], sizes); + + // Test 2 + if (result < 0) + { + result = -3; + } + if (data[0][0] != 0) + { + result = -4; + } + } + + // Close + closeUDP(sock); - return 0; + return result; } -short connTest() // setConn test +int connTest() // setConn test { - printf("setConn - "); - // Initialize - int i; // Iterator - char DREFArray[100][100]; - float *recDATA[100]; - short DREFSizes[100]; - struct xpcSocket sendPort, recvPort; - short result = 0; + char* drefs[100] = + { + "sim/cockpit/switches/gear_handle_status" + }; + float* data[100]; + int sizes[100]; + XPCSocket sock = openUDP(IP); #if (__APPLE__ || __linux) usleep(0); #endif // Setup - sendPort = openUDP( 49067, "127.0.0.1", 49009 ); - recvPort = openUDP( 49055, "127.0.0.1", 49009 ); - strcpy(DREFArray[0],"sim/cockpit/switches/gear_handle_status"); - for (i=0;i<1;i++) { - DREFSizes[i] = (int) strlen(DREFArray[i]); - } + for (int i = 0; i < 100; ++i) + { + data[i] = (float*)malloc(40 * sizeof(float)); + sizes[i] = 40; + } // Execution - setCONN(sendPort, 49055); - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 1, recDATA, DREFSizes); // Test + setCONN(&sock, 49055); + int result = getDREF(sock, drefs[0], data[0], sizes); // Close - closeUDP(sendPort); - closeUDP(recvPort); + closeUDP(sock); // Test if ( result < 0 )// No data received { return -1; } - - - // Set up for next test - sendPort = openUDP( 49067, "127.0.0.1", 49009 ); - setCONN(sendPort, 49008); - closeUDP(sendPort); return 0; } @@ -593,19 +938,19 @@ int main(int argc, const char * argv[]) printf("(Linux) \n"); #endif - runTest(openTest); - runTest(closeTest); - runTest(sendReadTest); - runTest(sendTEXTTest); - runTest(requestDREFTest); - runTest(sendDREFTest); - runTest(sendDATATest); - runTest(sendCTRLTest); - runTest(sendpCTRLTest); - runTest(sendPOSITest); - runTest(sendWYPTTest); - runTest(pauseTest); - runTest(connTest); + runTest(openTest, "open"); + runTest(closeTest, "close"); + runTest(pauseTest, "SIMU"); + runTest(getDREFTest, "GETD"); + runTest(sendDREFTest, "DREF"); + runTest(sendDATATest, "DATA"); + runTest(sendCTRLTest, "CTRL"); + runTest(psendCTRLTest, "CTRL (player)"); + runTest(sendPOSITest, "POSI"); + runTest(psendPOSITest, "POSI (player)"); + runTest(sendWYPTTest, "WYPT"); + runTest(sendTEXTTest, "TEXT"); + runTest(connTest, "CONN"); printf( "----------------\nTest Summary\n\tFailed: %i\n\tPassed: %i\n", testFailed, testPassed ); diff --git a/TestScripts/CPP Tests.win/CPPTests.sln b/TestScripts/CPP Tests.win/CPPTests.sln deleted file mode 100644 index ece566f..0000000 --- a/TestScripts/CPP Tests.win/CPPTests.sln +++ /dev/null @@ -1,19 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio 2013 -VisualStudioVersion = 12.0.31101.0 -MinimumVisualStudioVersion = 10.0.40219.1 -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "CPPTests", "CPPTests.vcxproj", "{9BA85F4F-A75A-4C27-BD85-2FEF881BEA13}" -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Win32 = Debug|Win32 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {9BA85F4F-A75A-4C27-BD85-2FEF881BEA13}.Debug|Win32.ActiveCfg = Debug|Win32 - {9BA85F4F-A75A-4C27-BD85-2FEF881BEA13}.Debug|Win32.Build.0 = Debug|Win32 - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection -EndGlobal diff --git a/TestScripts/CPP Tests.win/CPPTests.vcxproj b/TestScripts/CPP Tests.win/CPPTests.vcxproj deleted file mode 100644 index b75ad82..0000000 --- a/TestScripts/CPP Tests.win/CPPTests.vcxproj +++ /dev/null @@ -1,75 +0,0 @@ - - - - - Debug - Win32 - - - Release - Win32 - - - - {9BA85F4F-A75A-4C27-BD85-2FEF881BEA13} - CPPTests - - - - Application - true - v120 - MultiByte - - - Application - false - v120 - true - MultiByte - - - - - - - - - - - - - ../../C/src;$(IncludePath) - - - - Level3 - Disabled - false - - - true - - - - - Level3 - MaxSpeed - true - true - true - - - true - true - true - - - - - - - - - - \ No newline at end of file diff --git a/TestScripts/CPP Tests.win/CPPTests.vcxproj.filters b/TestScripts/CPP Tests.win/CPPTests.vcxproj.filters deleted file mode 100644 index 7558937..0000000 --- a/TestScripts/CPP Tests.win/CPPTests.vcxproj.filters +++ /dev/null @@ -1,25 +0,0 @@ - - - - - {4FC737F1-C7A5-4376-A066-2A32D752A2FF} - cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx - - - {93995380-89BD-4b04-88EB-625FBE52EBFB} - h;hh;hpp;hxx;hm;inl;inc;xsd - - - {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} - rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms - - - - - Source Files - - - Source Files - - - \ No newline at end of file diff --git a/TestScripts/CPP Tests/Cpp_Tests.1 b/TestScripts/CPP Tests/Cpp_Tests.1 deleted file mode 100644 index 6b6d039..0000000 --- a/TestScripts/CPP Tests/Cpp_Tests.1 +++ /dev/null @@ -1,79 +0,0 @@ -.\"Modified from man(1) of FreeBSD, the NetBSD mdoc.template, and mdoc.samples. -.\"See Also: -.\"man mdoc.samples for a complete listing of options -.\"man mdoc for the short list of editing options -.\"/usr/share/misc/mdoc.template -.Dd 11/25/14 \" DATE -.Dt XPC Tests 1 \" Program name and manual section number -.Os Darwin -.Sh NAME \" Section Header - required - don't modify -.Nm XPC Tests, -.\" The following lines are read in generating the apropos(man -k) database. Use only key -.\" words here as the database is built based on the words here and in the .ND line. -.Nm Other_name_for_same_program(), -.Nm Yet another name for the same program. -.\" Use .Nm macro to designate other names for the documented program. -.Nd This line parsed for whatis database. -.Sh SYNOPSIS \" Section Header - required - don't modify -.Nm -.Op Fl abcd \" [-abcd] -.Op Fl a Ar path \" [-a path] -.Op Ar file \" [file] -.Op Ar \" [file ...] -.Ar arg0 \" Underlined argument - use .Ar anywhere to underline -arg2 ... \" Arguments -.Sh DESCRIPTION \" Section Header - required - don't modify -Use the .Nm macro to refer to your program throughout the man page like such: -.Nm -Underlining is accomplished with the .Ar macro like this: -.Ar underlined text . -.Pp \" Inserts a space -A list of items with descriptions: -.Bl -tag -width -indent \" Begins a tagged list -.It item a \" Each item preceded by .It macro -Description of item a -.It item b -Description of item b -.El \" Ends the list -.Pp -A list of flags and their descriptions: -.Bl -tag -width -indent \" Differs from above in tag removed -.It Fl a \"-a flag as a list item -Description of -a flag -.It Fl b -Description of -b flag -.El \" Ends the list -.Pp -.\" .Sh ENVIRONMENT \" May not be needed -.\" .Bl -tag -width "ENV_VAR_1" -indent \" ENV_VAR_1 is width of the string ENV_VAR_1 -.\" .It Ev ENV_VAR_1 -.\" Description of ENV_VAR_1 -.\" .It Ev ENV_VAR_2 -.\" Description of ENV_VAR_2 -.\" .El -.Sh FILES \" File used or created by the topic of the man page -.Bl -tag -width "/Users/joeuser/Library/really_long_file_name" -compact -.It Pa /usr/share/file_name -FILE_1 description -.It Pa /Users/joeuser/Library/really_long_file_name -FILE_2 description -.El \" Ends the list -.\" .Sh DIAGNOSTICS \" May not be needed -.\" .Bl -diag -.\" .It Diagnostic Tag -.\" Diagnostic informtion here. -.\" .It Diagnostic Tag -.\" Diagnostic informtion here. -.\" .El -.Sh SEE ALSO -.\" List links in ascending order by section, alphabetically within a section. -.\" Please do not reference files that do not exist without filing a bug report -.Xr a 1 , -.Xr b 1 , -.Xr c 1 , -.Xr a 2 , -.Xr b 2 , -.Xr a 3 , -.Xr b 3 -.\" .Sh BUGS \" Document known, unremedied bugs -.\" .Sh HISTORY \" Document history if command behaves in a unique manner \ No newline at end of file diff --git a/TestScripts/CPP Tests/main.cpp b/TestScripts/CPP Tests/main.cpp deleted file mode 100755 index 5f8ea20..0000000 --- a/TestScripts/CPP Tests/main.cpp +++ /dev/null @@ -1,490 +0,0 @@ -// -// main.cpp -// XPC Tests -// -// Created by Chris Teubert on 11/25/14. -// Copyright (c) 2014 Chris Teubert. All rights reserved. -// - -#include -#include -#include -#include -#include -#include -#include "xplaneconnect.h" - -int testFailed = 0; -int testPassed = 0; - -void runTest(void (*f)()) -{ - try { - std::cout << "Test " << testPassed+testFailed+1<<": "; - (*f)(); // Run Test - std::cout << "PASSED\n"; - testPassed++; - } - catch (int i) - { - std::cerr << "FAILED\n\tError: " << i << std::endl; - testFailed++; - } - catch (char c) - { - std::cerr << "FAILED\n\tError: " << c << std::endl; - testFailed++; - } - -} - -void openUDPTest() // openUDP Test -{ - std::cout << "openUDP - "; - struct xpcSocket sendPort = openUDP( 49062, "127.0.0.1", 49009 ); -} - -void closeUDPTest() // closeUDP test -{ - std::cout << "closeUDP - "; - struct xpcSocket sendPort = openUDP( 49063, "127.0.0.1", 49009 ); - closeUDP(sendPort); - sendPort = openUDP( 49063, "127.0.0.1", 49009 ); - closeUDP(sendPort); -} - -void sendReadTest() // send/read Test -{ - std::cout << "send/readUDP - "; - - // Initialization - int i; // Iterator - char test[] = {0, 1, 2, 3, 5}; - char buf[5] = {0}; - struct xpcSocket sendPort, recvPort; - - // Setup - sendPort = openUDP( 49064, "127.0.0.1", 49063 ); - recvPort = openUDP( 49063, "127.0.0.1", 49009 ); - - // Execution - sendUDP( sendPort, test, sizeof(test) ); - readUDP( recvPort, buf, NULL ); // Test - - // Close - closeUDP(sendPort); - closeUDP(recvPort); - - // Tests - for (i=0; i<4; i++) - { - if (test[i] != buf[i]) // Not received correctly - { - throw 1; - } - } - -} - -void requestDREFTest() // Request DREF Test (Required for next tests) -{ - std::cout << "requestDREF - "; - - // Initialization - int i; // Iterator - char DREFArray[100][100]; - float *recDATA[100]; - short DREFSizes[100]; - struct xpcSocket sendPort, recvPort; - short result = 0; - - // Setup - for (i = 0; i < 100; i++) { - recDATA[i] = (float *) malloc(40*sizeof(float)); - memset(DREFArray[i],0,100); - } - sendPort = openUDP( 49064, "127.0.0.1", 49009 ); - recvPort = openUDP( 49008, "127.0.0.1", 49009 ); - strcpy(DREFArray[0],"sim/cockpit/switches/gear_handle_status"); - strcpy(DREFArray[1],"sim/cockpit2/switches/panel_brightness_ratio"); - for (i=0;i<2;i++) { - DREFSizes[i] = (int) strlen(DREFArray[i]); - } - - // Execution - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 2, recDATA, DREFSizes); - - // Close - closeUDP(sendPort); - closeUDP(recvPort); - - // Tests - if ( result < 0)// Request 2 values - { - throw 1; - } - if (DREFSizes[0] != 1 || DREFSizes[1] != 4) - { - throw 2; - } -} - -void sendDREFTest() // sendDREF test -{ - std::cout << "sendDREF - "; - - // Initialization - int i; // Iterator - char DREFArray[100][100]; - float *recDATA[100]; - short DREFSizes[100]; - float value = 0.0; - struct xpcSocket sendPort, recvPort; - short result = 0; - - // Setup - for (i = 0; i < 100; i++) { - recDATA[i] = (float *) malloc(40*sizeof(float)); - memset(DREFArray[i],0,100); - } - sendPort = openUDP( 49066, "127.0.0.1", 49009 ); - recvPort = openUDP( 49008, "127.0.0.1", 49009 ); - strcpy(DREFArray[0],"sim/cockpit/switches/gear_handle_status"); - for (i=0;i<1;i++) { - DREFSizes[i] = (int) strlen(DREFArray[i]); - } - - // Execution - sendDREF(sendPort, DREFArray[0], DREFSizes[0], &value, 1); - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 1, recDATA, DREFSizes); - - // Close - closeUDP(sendPort); - closeUDP(recvPort); - - // Tests - if (result < 0)// Request 1 value - { - throw 1; - } - if (DREFSizes[0] != 1) - { - throw 2; - } - if (*recDATA[0] != value) - { - throw 3; - } -} - -void sendDATATest() // sendDATA test -{ - std::cout << "sendData - "; - - // Initialize - int i,j; // Iterator - char DREFArray[100][100]; - float data[4][9] = {0}; - float *recDATA[100]; - short DREFSizes[100]; - struct xpcSocket sendPort, recvPort; - short result = 0; - - // Setup - for (i = 0; i < 100; i++) { - recDATA[i] = (float *) malloc(40*sizeof(float)); - memset(DREFArray[i],0,100); - } - sendPort = openUDP( 49066, "127.0.0.1", 49009 ); - recvPort = openUDP( 49008, "127.0.0.1", 49009 ); - strcpy(DREFArray[0],"sim/aircraft/parts/acf_gear_deploy"); - for (i=0;i<1;i++) { - DREFSizes[i] = (int) strlen(DREFArray[i]); - } - for (i=0;i<4;i++) { // Set array to -999 - for (j=0;j<9;j++) data[i][j] = -999; - } - data[0][0] = 14; // Gear - data[0][1] = 1; - data[0][2] = 0; - - // Execution - sendDATA(sendPort, data, 1); // Gear - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 1, recDATA, DREFSizes); // Test - - // Close - closeUDP(sendPort); - closeUDP(recvPort); - - // Tests - if ( result < 0 )// Request 1 value - { - throw 1; - } - if (DREFSizes[0] != 10) - { - throw 2; - } - if (*recDATA[0] != data[0][1]) - { - throw 3; - } -} - -void sendCTRLTest() // sendCTRL test -{ - std::cout << "sendCTRL - "; - - // Initialize - int i; // Iterator - char DREFArray[100][100]; - float CTRL[6] = {0.0}; - float *recDATA[100]; - short DREFSizes[100]; - struct xpcSocket sendPort, recvPort; - short result; - - // Setup - for (i = 0; i < 100; i++) { - recDATA[i] = (float *) malloc(40*sizeof(float)); - memset(DREFArray[i],0,100); - } - sendPort = openUDP( 49066, "127.0.0.1", 49009 ); - recvPort = openUDP( 49008, "127.0.0.1", 49009 ); - strcpy(DREFArray[0],"sim/cockpit2/controls/yoke_pitch_ratio"); - strcpy(DREFArray[1],"sim/cockpit2/controls/yoke_roll_ratio"); - strcpy(DREFArray[2],"sim/cockpit2/controls/yoke_heading_ratio"); - strcpy(DREFArray[3],"sim/flightmodel/engine/ENGN_thro"); - strcpy(DREFArray[4],"sim/cockpit/switches/gear_handle_status"); - strcpy(DREFArray[5],"sim/flightmodel/controls/flaprqst"); - for (i = 0; i < 100; i++) { - DREFSizes[i] = (int)strlen(DREFArray[i]); - } - CTRL[3] = 0.8; // Throttle - CTRL[4] = 1.0; // Gear - CTRL[5] = 0.5; // Flaps - - // Execute - sendCTRL(sendPort, 6, CTRL); - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 6, recDATA, DREFSizes); // Test - - // Close - closeUDP(sendPort); - closeUDP(recvPort); - - // Tests - if ( result < 0 )// Request 1 value - { - throw -6; - } - for (i=0;i<6;i++) - { - if (std::abs( recDATA[i][0]-CTRL[i])>1e-4) - { - throw -i; - } - } -} - -void sendPOSITest() // sendPOSI test -{ - std::cout << "sendPOSI - "; - - // Initialization - int i; // Iterator - char DREFArray[100][100]; - float POSI[8] = {0.0}; - float *recDATA[100]; - short DREFSizes[100]; - struct xpcSocket sendPort, recvPort; - short result; - - // Setup - for (i = 0; i < 100; i++) { - recDATA[i] = (float *) malloc(40*sizeof(float)); - memset(DREFArray[i],0,100); - } - sendPort = openUDP( 49063, "127.0.0.1", 49009 ); - recvPort = openUDP( 49008, "127.0.0.1", 49009 ); - strcpy(DREFArray[0],"sim/flightmodel/position/latitude"); - strcpy(DREFArray[1],"sim/flightmodel/position/longitude"); - strcpy(DREFArray[2],"sim/flightmodel/position/y_agl"); - strcpy(DREFArray[3],"sim/flightmodel/position/phi"); - strcpy(DREFArray[4],"sim/flightmodel/position/theta"); - strcpy(DREFArray[5],"sim/flightmodel/position/psi"); - strcpy(DREFArray[6],"sim/cockpit/switches/gear_handle_status"); - for (i=0;i<7;i++) { - DREFSizes[i] = (int) strlen(DREFArray[i]); - } - POSI[0] = 37.524; // Lat - POSI[1] = -122.06899; // Lon - POSI[2] = 2500; // Alt - POSI[3] = 0; // Pitch - POSI[4] = 0; // Roll - POSI[5] = 0; // Heading - POSI[6] = 1; // Gear - - // Execution - sendPOSI( sendPort, 0, 7, POSI ); - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 7, recDATA, DREFSizes); // Test - - // Close - closeUDP(sendPort); - closeUDP(recvPort); - - // Tests - if ( result < 0 )// Request 1 value - { - throw -7; - } - for (i=0;i<7-1;i++) - { - if (i==2) - { - continue; - } - if (std::abs(recDATA[i][0]-POSI[i])>1e-4) - { - throw -i; - } - } -} - -void pauseTest() // pauseSim test -{ - std::cout << "pauseSim - "; - - // Initialize - int i; // Iterator - char DREFArray[100][100]; - float *recDATA[100]; - short DREFSizes[100],RECSizes[100]; - struct xpcSocket sendPort, recvPort; - short result; - - // Setup - for (i = 0; i < 100; i++) { - recDATA[i] = (float *) malloc(40*sizeof(float)); - memset(DREFArray[i],0,100); - } - - // Setup - sendPort = openUDP( 49064, "127.0.0.1", 49009 ); - recvPort = openUDP( 49008, "127.0.0.1", 49009 ); - strcpy(DREFArray[0],"sim/operation/override/override_planepath"); - for (i=0;i<1;i++) { - DREFSizes[i] = (int) strlen(DREFArray[i]); - } - - // Execute - pauseSim(sendPort, 1); - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 1, recDATA, RECSizes); // Test - - // Close - closeUDP(sendPort); - closeUDP(recvPort); - - // Test - if (result < 0) { - throw -1; - } - if (recDATA[0][0] != 1) - { - throw -2; - } - - // Reopen - sendPort = openUDP( 49064, "127.0.0.1", 49009 ); - recvPort = openUDP( 49008, "127.0.0.1", 49009 ); - - // Execute 2 - pauseSim(sendPort, 0); - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 1, recDATA, RECSizes); // Test - - // Close 2 - closeUDP(sendPort); - closeUDP(recvPort); - - // Test 2 - if (result < 0) - { - throw -3; - } - if (recDATA[0][0] != 0) - { - throw -4; - } -} - -void connTest() // setConn test -{ - std::cout << "setConn - "; - - // Initialize - int i; // Iterator - char DREFArray[100][100]; - float *recDATA[100]; - short DREFSizes[100]; - struct xpcSocket sendPort, recvPort; - short result = 0; -#if (__APPLE__ || __linux) - usleep(0); -#endif - - // Setup - sendPort = openUDP( 49067, "127.0.0.1", 49009 ); - recvPort = openUDP( 49055, "127.0.0.1", 49009 ); - strcpy(DREFArray[0],"sim/cockpit/switches/gear_handle_status"); - for (i=0;i<1;i++) { - DREFSizes[i] = (int) strlen(DREFArray[i]); - } - - // Execution - setCONN(sendPort, 49055); - result = requestDREF(sendPort, recvPort, DREFArray, DREFSizes, 1, recDATA, DREFSizes); // Test - - // Close - closeUDP(sendPort); - closeUDP(recvPort); - - // Test - if ( result < 0 )// No data received - { - throw 1; - } - - - // Set up for next test - sendPort = openUDP( 49067, "127.0.0.1", 49009 ); - setCONN(sendPort, 49008); - closeUDP(sendPort); -} - -int main(int argc, const char * argv[]) -{ - std::cout << "XPC Tests-cpp "; - -#ifdef _WIN32 - std::cout << "(Windows)\n"; -#elif (__APPLE__) - std::cout << "(Mac) \n"; -#elif (__linux) - std::cout << "(Linux) \n"; -#endif - - runTest(openUDPTest); - runTest(closeUDPTest); - runTest(sendReadTest); - runTest(requestDREFTest); - runTest(sendDREFTest); - runTest(sendDATATest); - runTest(sendCTRLTest); - runTest(sendPOSITest); - runTest(pauseTest); - runTest(connTest); - - std::cout << "----------------\nTest Summary\n\tFailed: " << testFailed << "\n\tPassed: " << testPassed << std::endl; - - return 0; -} - diff --git a/TestScripts/Cpp Tests.xcodeproj/project.pbxproj b/TestScripts/Cpp Tests.xcodeproj/project.pbxproj deleted file mode 100644 index b22b04d..0000000 --- a/TestScripts/Cpp Tests.xcodeproj/project.pbxproj +++ /dev/null @@ -1,240 +0,0 @@ -// !$*UTF8*$! -{ - archiveVersion = 1; - classes = { - }; - objectVersion = 46; - objects = { - -/* Begin PBXBuildFile section */ - BE7C5C021A28F72F00F246B9 /* main.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BE7C5C001A28F72F00F246B9 /* main.cpp */; }; - BEB0F4F81A28F7B0001975A6 /* xplaneConnect.c in Sources */ = {isa = PBXBuildFile; fileRef = BEB0F4F61A28F7B0001975A6 /* xplaneConnect.c */; }; - BEB0F4F91A28F7B0001975A6 /* xplaneConnect.h in Sources */ = {isa = PBXBuildFile; fileRef = BEB0F4F71A28F7B0001975A6 /* xplaneConnect.h */; }; -/* End PBXBuildFile section */ - -/* Begin PBXCopyFilesBuildPhase section */ - BE9C6BA91A253FA100EBE08A /* CopyFiles */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = /usr/share/man/man1/; - dstSubfolderSpec = 0; - files = ( - ); - runOnlyForDeploymentPostprocessing = 1; - }; -/* End PBXCopyFilesBuildPhase section */ - -/* Begin PBXFileReference section */ - BE7C5C001A28F72F00F246B9 /* main.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; name = main.cpp; path = "CPP Tests/main.cpp"; sourceTree = SOURCE_ROOT; }; - BE7C5C011A28F72F00F246B9 /* Cpp_Tests.1 */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.man; name = Cpp_Tests.1; path = "CPP Tests/Cpp_Tests.1"; sourceTree = SOURCE_ROOT; }; - BE9C6BAB1A253FA100EBE08A /* Cpp Tests */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = "Cpp Tests"; sourceTree = BUILT_PRODUCTS_DIR; }; - BEB0F4F61A28F7B0001975A6 /* xplaneConnect.c */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.c; name = xplaneConnect.c; path = ../C/src/xplaneConnect.c; sourceTree = ""; }; - BEB0F4F71A28F7B0001975A6 /* xplaneConnect.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = xplaneConnect.h; path = ../C/src/xplaneConnect.h; sourceTree = ""; }; -/* End PBXFileReference section */ - -/* Begin PBXFrameworksBuildPhase section */ - BE9C6BA81A253FA100EBE08A /* Frameworks */ = { - isa = PBXFrameworksBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXFrameworksBuildPhase section */ - -/* Begin PBXGroup section */ - BE9C6BA21A253FA100EBE08A = { - isa = PBXGroup; - children = ( - BEB0F4F61A28F7B0001975A6 /* xplaneConnect.c */, - BEB0F4F71A28F7B0001975A6 /* xplaneConnect.h */, - BE9C6BAD1A253FA100EBE08A /* Cpp Tests */, - BE9C6BAC1A253FA100EBE08A /* Products */, - ); - sourceTree = ""; - }; - BE9C6BAC1A253FA100EBE08A /* Products */ = { - isa = PBXGroup; - children = ( - BE9C6BAB1A253FA100EBE08A /* Cpp Tests */, - ); - name = Products; - sourceTree = ""; - }; - BE9C6BAD1A253FA100EBE08A /* Cpp Tests */ = { - isa = PBXGroup; - children = ( - BE7C5C001A28F72F00F246B9 /* main.cpp */, - BE7C5C011A28F72F00F246B9 /* Cpp_Tests.1 */, - ); - name = "Cpp Tests"; - path = "XPC Tests"; - sourceTree = ""; - }; -/* End PBXGroup section */ - -/* Begin PBXNativeTarget section */ - BE9C6BAA1A253FA100EBE08A /* Cpp Tests */ = { - isa = PBXNativeTarget; - buildConfigurationList = BE9C6BB41A253FA100EBE08A /* Build configuration list for PBXNativeTarget "Cpp Tests" */; - buildPhases = ( - BE9C6BA71A253FA100EBE08A /* Sources */, - BE9C6BA81A253FA100EBE08A /* Frameworks */, - BE9C6BA91A253FA100EBE08A /* CopyFiles */, - ); - buildRules = ( - ); - dependencies = ( - ); - name = "Cpp Tests"; - productName = "XPC Tests"; - productReference = BE9C6BAB1A253FA100EBE08A /* Cpp Tests */; - productType = "com.apple.product-type.tool"; - }; -/* End PBXNativeTarget section */ - -/* Begin PBXProject section */ - BE9C6BA31A253FA100EBE08A /* Project object */ = { - isa = PBXProject; - attributes = { - LastUpgradeCheck = 0500; - ORGANIZATIONNAME = "Chris Teubert"; - }; - buildConfigurationList = BE9C6BA61A253FA100EBE08A /* Build configuration list for PBXProject "Cpp Tests" */; - compatibilityVersion = "Xcode 3.2"; - developmentRegion = English; - hasScannedForEncodings = 0; - knownRegions = ( - en, - ); - mainGroup = BE9C6BA21A253FA100EBE08A; - productRefGroup = BE9C6BAC1A253FA100EBE08A /* Products */; - projectDirPath = ""; - projectRoot = ""; - targets = ( - BE9C6BAA1A253FA100EBE08A /* Cpp Tests */, - ); - }; -/* End PBXProject section */ - -/* Begin PBXSourcesBuildPhase section */ - BE9C6BA71A253FA100EBE08A /* Sources */ = { - isa = PBXSourcesBuildPhase; - buildActionMask = 2147483647; - files = ( - BEB0F4F81A28F7B0001975A6 /* xplaneConnect.c in Sources */, - BEB0F4F91A28F7B0001975A6 /* xplaneConnect.h in Sources */, - BE7C5C021A28F72F00F246B9 /* main.cpp in Sources */, - ); - runOnlyForDeploymentPostprocessing = 0; - }; -/* End PBXSourcesBuildPhase section */ - -/* Begin XCBuildConfiguration section */ - BE9C6BB21A253FA100EBE08A /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_DYNAMIC_NO_PIC = NO; - GCC_ENABLE_OBJC_EXCEPTIONS = YES; - GCC_OPTIMIZATION_LEVEL = 0; - GCC_PREPROCESSOR_DEFINITIONS = ( - "DEBUG=1", - "$(inherited)", - ); - GCC_SYMBOLS_PRIVATE_EXTERN = NO; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.9; - ONLY_ACTIVE_ARCH = YES; - SDKROOT = macosx; - }; - name = Debug; - }; - BE9C6BB31A253FA100EBE08A /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - ALWAYS_SEARCH_USER_PATHS = NO; - CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; - CLANG_CXX_LIBRARY = "libc++"; - CLANG_ENABLE_OBJC_ARC = YES; - CLANG_WARN_BOOL_CONVERSION = YES; - CLANG_WARN_CONSTANT_CONVERSION = YES; - CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; - CLANG_WARN_EMPTY_BODY = YES; - CLANG_WARN_ENUM_CONVERSION = YES; - CLANG_WARN_INT_CONVERSION = YES; - CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; - CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; - COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - ENABLE_NS_ASSERTIONS = NO; - GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_ENABLE_OBJC_EXCEPTIONS = YES; - GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; - GCC_WARN_UNDECLARED_SELECTOR = YES; - GCC_WARN_UNINITIALIZED_AUTOS = YES; - GCC_WARN_UNUSED_FUNCTION = YES; - GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.9; - SDKROOT = macosx; - }; - name = Release; - }; - BE9C6BB51A253FA100EBE08A /* Debug */ = { - isa = XCBuildConfiguration; - buildSettings = { - PRODUCT_NAME = "Cpp Tests"; - }; - name = Debug; - }; - BE9C6BB61A253FA100EBE08A /* Release */ = { - isa = XCBuildConfiguration; - buildSettings = { - PRODUCT_NAME = "Cpp Tests"; - }; - name = Release; - }; -/* End XCBuildConfiguration section */ - -/* Begin XCConfigurationList section */ - BE9C6BA61A253FA100EBE08A /* Build configuration list for PBXProject "Cpp Tests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - BE9C6BB21A253FA100EBE08A /* Debug */, - BE9C6BB31A253FA100EBE08A /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; - BE9C6BB41A253FA100EBE08A /* Build configuration list for PBXNativeTarget "Cpp Tests" */ = { - isa = XCConfigurationList; - buildConfigurations = ( - BE9C6BB51A253FA100EBE08A /* Debug */, - BE9C6BB61A253FA100EBE08A /* Release */, - ); - defaultConfigurationIsVisible = 0; - defaultConfigurationName = Release; - }; -/* End XCConfigurationList section */ - }; - rootObject = BE9C6BA31A253FA100EBE08A /* Project object */; -} diff --git a/TestScripts/Cpp Tests.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/TestScripts/Cpp Tests.xcodeproj/project.xcworkspace/contents.xcworkspacedata deleted file mode 100644 index f48beca..0000000 --- a/TestScripts/Cpp Tests.xcodeproj/project.xcworkspace/contents.xcworkspacedata +++ /dev/null @@ -1,7 +0,0 @@ - - - - - diff --git a/TestScripts/Java Tests/XPlaneConnectTest.java b/TestScripts/Java Tests/XPlaneConnectTest.java index e76928f..aed0883 100644 --- a/TestScripts/Java Tests/XPlaneConnectTest.java +++ b/TestScripts/Java Tests/XPlaneConnectTest.java @@ -31,7 +31,7 @@ public class XPlaneConnectTest { fail(); } - try(XPlaneConnect xpc = new XPlaneConnect(49007, "127.0.0.1", 49009)) + try(XPlaneConnect xpc = new XPlaneConnect("127.0.0.1", 49009, 49007)) { assertNotNull(xpc); } @@ -39,7 +39,7 @@ public class XPlaneConnectTest { fail(); } - try(XPlaneConnect xpc = new XPlaneConnect(49007, "127.0.0.1", 49009, 200)) + try(XPlaneConnect xpc = new XPlaneConnect("127.0.0.1", 49009, 49007, 200)) { assertNotNull(xpc); } @@ -50,9 +50,9 @@ public class XPlaneConnectTest } @Test - public void testGetRecvPort() throws SocketException + public void testGetRecvPort() throws Exception { - try(XPlaneConnect xpc = new XPlaneConnect()) + try(XPlaneConnect xpc = new XPlaneConnect("127.0.0.1", 49009, 49008)) { assertEquals(49008, xpc.getRecvPort()); } @@ -87,11 +87,11 @@ public class XPlaneConnectTest } @Test - public void constructorTest_SocketAlreadyBound() throws SocketException + public void constructorTest_SocketAlreadyBound() throws Exception { - try(XPlaneConnect xpc = new XPlaneConnect()) + try(XPlaneConnect xpc = new XPlaneConnect("127.0.0.1", 49009, 49008)) { - try(XPlaneConnect xpc2 = new XPlaneConnect()) + try(XPlaneConnect xpc2 = new XPlaneConnect("127.0.0.1", 49009, 49008)) { fail(); } @@ -106,7 +106,7 @@ public class XPlaneConnectTest @Test(expected = UnknownHostException.class) public void constructorTest_InvalidHost() throws UnknownHostException { - try(XPlaneConnect xpc = new XPlaneConnect(49007, "notarealhost", 49009)) + try(XPlaneConnect xpc = new XPlaneConnect("notarealhost", 49009, 49007)) { } @@ -123,7 +123,7 @@ public class XPlaneConnectTest String dref = "sim/cockpit/switches/gear_handle_status"; try(XPlaneConnect xpc = new XPlaneConnect()) { - float[] result = xpc.requestDREF(dref); + float[] result = xpc.getDREF(dref); assertEquals(1, result.length); } } @@ -138,7 +138,7 @@ public class XPlaneConnectTest }; try(XPlaneConnect xpc = new XPlaneConnect()) { - float[][] result = xpc.requestDREFs(drefs); + float[][] result = xpc.getDREFs(drefs); assertEquals(2, result.length); assertEquals(1, result[0].length); assertEquals(4, result[1].length); @@ -150,7 +150,7 @@ public class XPlaneConnectTest { try(XPlaneConnect xpc = new XPlaneConnect()) { - xpc.requestDREFs(null); + xpc.getDREFs(null); fail(); } } @@ -161,7 +161,7 @@ public class XPlaneConnectTest String[] drefs = new String[0]; try(XPlaneConnect xpc = new XPlaneConnect()) { - xpc.requestDREFs(drefs); + xpc.getDREFs(drefs); fail(); } } @@ -172,7 +172,7 @@ public class XPlaneConnectTest String[] drefs = new String[300]; try(XPlaneConnect xpc = new XPlaneConnect()) { - xpc.requestDREFs(drefs); + xpc.getDREFs(drefs); fail(); } } @@ -184,7 +184,7 @@ public class XPlaneConnectTest String[] drefs = new String[]{longDREF}; try(XPlaneConnect xpc = new XPlaneConnect()) { - xpc.requestDREFs(drefs); + xpc.getDREFs(drefs); fail(); } } @@ -195,7 +195,7 @@ public class XPlaneConnectTest String dref = ""; try(XPlaneConnect xpc = new XPlaneConnect()) { - xpc.requestDREF(dref); + xpc.getDREF(dref); fail(); } } @@ -207,12 +207,12 @@ public class XPlaneConnectTest try(XPlaneConnect xpc = new XPlaneConnect()) { xpc.pauseSim(true); - float[] result = xpc.requestDREF(dref); + float[] result = xpc.getDREF(dref); //assertEquals(1, result.length); //TODO: Why is this result 20 elements long in Java? (It's only one in MATLAB) assertEquals(1, result[0], 1e-4); xpc.pauseSim(false); - result = xpc.requestDREF(dref); + result = xpc.getDREF(dref); //assertEquals(1, result.length); assertEquals(0, result[0], 1e-4); } @@ -305,12 +305,12 @@ public class XPlaneConnectTest String dref = "sim/cockpit/switches/gear_handle_status"; try(XPlaneConnect xpc = new XPlaneConnect()) { - float gearHandle = xpc.requestDREF(dref)[0]; + float gearHandle = xpc.getDREF(dref)[0]; float value = gearHandle > 0.5 ? 0 : 1; xpc.sendDREF(dref, value); - float result = xpc.requestDREF(dref)[0]; + float result = xpc.getDREF(dref)[0]; assertEquals(value, result, 1e-4); } } @@ -348,14 +348,17 @@ public class XPlaneConnectTest } } - @Test(expected = IllegalArgumentException.class) + @Test public void testSendDREF_MessageTooLong() throws IOException { + // NOTE: This test originally ensured that the client restricted messages to 255 bytes in length. + // This restriction is no longer necessary, however removing it uncovered a bug that caused + // the plugin to do a bad memcpy and crash. This test is left here to ensure that X-Plane + // does not crash when given erroneously large value arrays. String dref = "sim/cockpit/switches/gear_handle_status"; try(XPlaneConnect xpc = new XPlaneConnect()) { xpc.sendDREF(dref, new float[200]); - fail(); } } @@ -396,7 +399,7 @@ public class XPlaneConnectTest try(XPlaneConnect xpc = new XPlaneConnect()) { xpc.sendCTRL(ctrl); - float[][] result = xpc.requestDREFs(drefs); + float[][] result = xpc.getDREFs(drefs); if(result.length < ctrl.length) { fail(); @@ -425,8 +428,8 @@ public class XPlaneConnectTest try(XPlaneConnect xpc = new XPlaneConnect()) { xpc.sendCTRL(ctrl, 1); - float[][] result1 = xpc.requestDREFs(drefs1); - float[][] result2 = xpc.requestDREFs(drefs2); + float[][] result1 = xpc.getDREFs(drefs1); + float[][] result2 = xpc.getDREFs(drefs2); if(result1.length != 4 || result2.length != 2) { fail(); @@ -480,7 +483,7 @@ public class XPlaneConnectTest xpc.sendPOSI(posi); //TODO: It seems that these calls are a bit too fast. The dref request often gets stale data, causing the test to fail incorrectly. try {Thread.sleep(100);}catch(InterruptedException ex){} - float[][] result = xpc.requestDREFs(drefs); + float[][] result = xpc.getDREFs(drefs); xpc.pauseSim(false); if(result.length < posi.length) { @@ -543,7 +546,7 @@ public class XPlaneConnectTest try(XPlaneConnect xpc = new XPlaneConnect()) { xpc.sendDATA(data); - float[] result = xpc.requestDREF(dref); + float[] result = xpc.getDREF(dref); assertEquals(data[0][1], result[0], 1e-4); } } @@ -575,15 +578,9 @@ public class XPlaneConnectTest String dref = "sim/cockpit/switches/gear_handle_status"; try(XPlaneConnect xpc = new XPlaneConnect()) { - int p = xpc.getRecvPort(); xpc.setCONN(49055); assertEquals(49055, xpc.getRecvPort()); - float[] result = xpc.requestDREF(dref); - assertEquals(1, result.length); - - xpc.setCONN(p); - assertEquals(p, xpc.getRecvPort()); - result = xpc.requestDREF(dref); + float[] result = xpc.getDREF(dref); assertEquals(1, result.length); } } diff --git a/TestScripts/MATLAB Tests/CTRLTest.m b/TestScripts/MATLAB Tests/CTRLTest.m index 6ba5386..7b8a9bc 100644 --- a/TestScripts/MATLAB Tests/CTRLTest.m +++ b/TestScripts/MATLAB Tests/CTRLTest.m @@ -1,6 +1,7 @@ function CTRLTest( ) %CTRLTest Summary of this function goes here % Detailed explanation goes here +%% Test player aircraft addpath('../../MATLAB') import XPlaneConnect.* @@ -14,14 +15,15 @@ THROT = rand(); CTRL = [0.0, 0.0, 1.0, THROT, 0.0, 1.0]; sendCTRL(CTRL); -result = requestDREF(DREFS); +result = getDREFs(DREFS); -assert(isequal(length(result),6),'CTRLTest: requestDREF unsucessful-wrong number of elements returned'); -assert(isequal(length(result{4}),8),'CTRLTest: requestDREF unsucessful- element 1 incorrect size (should be size 8)'); +assert(isequal(length(result),6),'CTRLTest: getDREFs unsucessful-wrong number of elements returned'); +assert(isequal(length(result{4}),8),'CTRLTest: getDREFs unsucessful- element 1 incorrect size (should be size 8)'); for i=1:length(CTRL)-1 assert(abs(result{i}(1)-CTRL(i))<1e-4,['CTRLTest: DATA set unsucessful-',num2str(i)]); end +%% Test NPC aircraft DREFS = {'sim/multiplayer/position/plane1_yolk_pitch',... 'sim/multiplayer/position/plane1_yolk_roll',... 'sim/multiplayer/position/plane1_yolk_yaw',... @@ -32,7 +34,7 @@ THROT = rand(); CTRL = [0.0, 0.0, 1.0, THROT, 0.0, 1.0]; sendCTRL(CTRL, 1); -result = requestDREF(DREFS); +result = getDREFs(DREFS); assert(isequal(length(result),6),'CTRLTest: requestDREF unsucessful-wrong number of elements returned'); assert(isequal(length(result{4}),8),'CTRLTest: requestDREF unsucessful- element 1 incorrect size (should be size 8)'); diff --git a/TestScripts/MATLAB Tests/DATATest.m b/TestScripts/MATLAB Tests/DATATest.m index 4c69a5d..d70e7be 100644 --- a/TestScripts/MATLAB Tests/DATATest.m +++ b/TestScripts/MATLAB Tests/DATATest.m @@ -10,11 +10,10 @@ value = rand(); data = struct('h',25,'d',[value,-998,-998,-998,-998,-998,-998,-998]); sendDATA(data); -result = requestDREF(DREFS); +result = getDREFs(DREFS); -assert(isequal(length(result),1),'DATATest: requestDREF unsucessful-wrong number of elements returned'); -assert(isequal(length(result{1}),8),'DATATest: requestDREF unsucessful- element 1 incorrect size (should be size 8)'); -assert(abs(result{1}(1)-value)<1e-4,'DATATest: DATA set unsucessful'); +assert(isequal(length(result),8),'DATATest: getDREFs unsucessful-wrong number of elements returned'); +assert(abs(result(1)-value)<1e-4,'DATATest: DATA set unsucessful'); end diff --git a/TestScripts/MATLAB Tests/POSITest.m b/TestScripts/MATLAB Tests/POSITest.m index 110d769..16b6c8d 100644 --- a/TestScripts/MATLAB Tests/POSITest.m +++ b/TestScripts/MATLAB Tests/POSITest.m @@ -14,14 +14,14 @@ DREFS = {'sim/flightmodel/position/latitude', ... POSI = [37.524, -122.06899, 2500, 0, 0, 0, 1]; % Gear sendPOSI(POSI); -result = requestDREF(DREFS); +result = getDREFs(DREFS); -assert(isequal(length(result),7),'POSITest: requestDREF unsucessful-wrong number of elements returned'); +assert(isequal(length(result),7),'POSITest: getDREFs unsucessful-wrong number of elements returned'); for i=1:length(POSI) if i==3 continue end - assert(abs(result{i}(1)-POSI(i))<1e-4,['POSITest: DATA set unsucessful-',num2str(i)]); + assert(abs(result(i)-POSI(i))<1e-4,['POSITest: DATA set unsucessful-',num2str(i)]); end end diff --git a/TestScripts/MATLAB Tests/requestDREFTest.m b/TestScripts/MATLAB Tests/getDREFsTest.m similarity index 86% rename from TestScripts/MATLAB Tests/requestDREFTest.m rename to TestScripts/MATLAB Tests/getDREFsTest.m index 36e5f70..43633c3 100644 --- a/TestScripts/MATLAB Tests/requestDREFTest.m +++ b/TestScripts/MATLAB Tests/getDREFsTest.m @@ -1,4 +1,4 @@ -function requestDREFTest( ) +function getDREFsTest( ) %SENDREADTEST Summary of this function goes here % Detailed explanation goes here addpath('../../MATLAB') @@ -7,7 +7,7 @@ import XPlaneConnect.* DREFS = {'sim/cockpit/switches/gear_handle_status',... 'sim/cockpit2/switches/panel_brightness_ratio'}; -result = requestDREF(DREFS); +result = getDREFs(DREFS); assert(isequal(length(result),2)); assert(isequal(length(result{1}),1)); diff --git a/TestScripts/MATLAB Tests/openCloseTest.m b/TestScripts/MATLAB Tests/openCloseTest.m index fc008ac..26af4ce 100644 --- a/TestScripts/MATLAB Tests/openCloseTest.m +++ b/TestScripts/MATLAB Tests/openCloseTest.m @@ -4,13 +4,10 @@ function openCloseTest() addpath('../../MATLAB') import XPlaneConnect.* -socket = openUDP( 49007 ); - -closeUDP( socket ); -assert(isequal(socket.isClosed(),1),'openCloseTest: socket is still open'); - -socket = openUDP( 49007 ); -closeUDP( socket ); +socket = openUDP(); +closeUDP(socket); +socket = openUDP(); +closeUDP(socket); end diff --git a/TestScripts/MATLAB Tests/pauseTest.m b/TestScripts/MATLAB Tests/pauseTest.m index 2e17fe6..7150f9c 100644 --- a/TestScripts/MATLAB Tests/pauseTest.m +++ b/TestScripts/MATLAB Tests/pauseTest.m @@ -9,17 +9,15 @@ DREFS = {'sim/operation/override/override_planepath'}; value = 1; % Pause pauseSim(value); -result = requestDREF(DREFS); +result = getDREFs(DREFS); -assert(isequal(length(result),1),'pauseTest: requestDREF unsucessful-wrong number of elements returned'); -assert(abs(result{1}(1)-value)<1e-4,'pauseTest: Pause Unsuccessful'); +assert(abs(result(1)-value)<1e-4,'pauseTest: Pause Unsuccessful'); value = 0; % Resume pauseSim(value); -result = requestDREF(DREFS); +result = getDREFs(DREFS); -assert(isequal(length(result),1),'pauseTest: requestDREF unsucessful-wrong number of elements returned'); -assert(abs(result{1}(1)-value)<1e-4,'pauseTest: Pause Unsuccessful'); +assert(abs(result(1)-value)<1e-4,'pauseTest: Pause Unsuccessful'); end diff --git a/TestScripts/MATLAB Tests/sendDREFTest.m b/TestScripts/MATLAB Tests/sendDREFTest.m index e688d08..33741c2 100644 --- a/TestScripts/MATLAB Tests/sendDREFTest.m +++ b/TestScripts/MATLAB Tests/sendDREFTest.m @@ -8,12 +8,11 @@ DREFS = {'sim/cockpit/switches/gear_handle_status'}; value = randi([0 10]); sendDREF(DREFS{1},value); -result = requestDREF(DREFS); +result = getDREFs(DREFS); -assert(isequal(length(result),1),'sendDREFTest: requestDREF unsucessful-wrong number of elements returned'); -assert(isequal(length(result{1}),1),'sendDREFTest: requestDREF unsucessful- element 1 incorrect size (should be size 1)'); +assert(isequal(length(result),1),'setDREFTest: requestDREF unsucessful-wrong number of elements returned'); -assert(isequal(result{1},value),'sendDREFTest: DREF set unsucessful'); +assert(isequal(result(1),value),'setDREFTest: DREF set unsucessful'); end diff --git a/TestScripts/MATLAB Tests/sendReadTest.m b/TestScripts/MATLAB Tests/sendReadTest.m deleted file mode 100644 index 62bca30..0000000 --- a/TestScripts/MATLAB Tests/sendReadTest.m +++ /dev/null @@ -1,18 +0,0 @@ -function sendReadTest( ) -%SENDREADTEST Summary of this function goes here -% Detailed explanation goes here -addpath('../../MATLAB') -import XPlaneConnect.* - -recvPortNum = 49074; -recvPort = openUDP(49074); - -sendUDP('test2'-0,'127.0.0.1',49074); -result = readUDP(recvPort); -closeUDP(recvPort); - -assert(~isequal(result,-998), 'no data received'); -assert(all(result(1:4)'=='test'-0)); - -end - diff --git a/TestScripts/MATLAB Tests/setConnTest.m b/TestScripts/MATLAB Tests/setConnTest.m index c06ae9b..2cc063d 100644 --- a/TestScripts/MATLAB Tests/setConnTest.m +++ b/TestScripts/MATLAB Tests/setConnTest.m @@ -8,7 +8,7 @@ import XPlaneConnect.* DREFS = {'sim/cockpit/switches/gear_handle_status'}; setConn(49055); -result = requestDREF(DREFS); +result = getDREFs(DREFS); assert(isequal(length(result),1),'setConnTest: requestDREF unsucessful-wrong number of elements returned'); diff --git a/TestScripts/MATLAB Tests/struTest.m b/TestScripts/MATLAB Tests/struTest.m deleted file mode 100644 index 028e9bd..0000000 --- a/TestScripts/MATLAB Tests/struTest.m +++ /dev/null @@ -1,19 +0,0 @@ -function struTest( ) -%STRUTEST Summary of this function goes here -% Detailed explanation goes here -addpath('../../MATLAB') -import XPlaneConnect.* - -recvNum = 49076; -recvPort = openUDP(recvNum); - -testSTRU = struct('h',15,'d',[12, 34, 55, 99, 1, 0],'test','theTest'); - -sendSTRU(testSTRU,'127.0.0.1',recvNum); -resultSTRU = readDATA(recvPort); -closeUDP(recvPort); -resultSTRU = rmfield(resultSTRU,'raw'); -assert(isequal(testSTRU,resultSTRU),'struTest: Error-structs are not equal'); - -end - diff --git a/TestScripts/MATLAB Tests/tests.m b/TestScripts/MATLAB Tests/tests.m index bfa45d9..6871686 100644 --- a/TestScripts/MATLAB Tests/tests.m +++ b/TestScripts/MATLAB Tests/tests.m @@ -11,16 +11,14 @@ end disp(['XPC Tests-MATLAB (', os, ')']); theTests = {{@openCloseTest, 'Open/Close Test', 0},... - {@sendReadTest,'Send/Read Test', 0},... {@sendTEXTTest,'TEXT Test', 0},... - {@requestDREFTest,'Request DREF Test', 0},... + {@getDREFsTest,'Request DREF Test', 0},... {@sendDREFTest,'Send DREF Test', 0},... {@DATATest,'DATA Test', 0},... {@CTRLTest,'CTRL Test', 0},... {@POSITest,'POSI Test', 0},... {@sendWYPTTest,'WYPT Test', 0},... {@pauseTest,'Pause Test', 0},... - {@struTest,'Struct Test', 0},... {@setConnTest, 'setConn Test', 0}}; for i=1:length(theTests) diff --git a/xpcPlugin/CMakeLists.txt b/xpcPlugin/CMakeLists.txt new file mode 100644 index 0000000..ca964b5 --- /dev/null +++ b/xpcPlugin/CMakeLists.txt @@ -0,0 +1,38 @@ +cmake_minimum_required(VERSION 2.8 FATAL_ERROR) + +project(XPlaneConnect) + +include_directories(${CMAKE_CURRENT_SOURCE_DIR}) +include_directories(SDK/CHeaders/XPLM) +include_directories(../C/src) + +add_definitions(-DXPLM200 -DLIN=1) + +SET(CMAKE_C_COMPILER gcc) +SET(CMAKE_CXX_COMPILER g++) + +add_library(xpc64 SHARED XPCPlugin.cpp + DataManager.cpp + DataMaps.cpp + Drawing.cpp + Log.cpp + Message.cpp + MessageHandlers.cpp + UDPSocket.cpp) +set_target_properties(xpc64 PROPERTIES PREFIX "" SUFFIX ".xpl") +set_target_properties(xpc64 PROPERTIES COMPILE_FLAGS "-m64" LINK_FLAGS "-shared -rdynamic -nodefaultlibs -undefined_warning -m64") + +add_library(xpc32 SHARED XPCPlugin.cpp + DataManager.cpp + DataMaps.cpp + Drawing.cpp + Log.cpp + Message.cpp + MessageHandlers.cpp + UDPSocket.cpp) +set_target_properties(xpc32 PROPERTIES PREFIX "" SUFFIX ".xpl") +set_target_properties(xpc32 PROPERTIES COMPILE_FLAGS "-m32" LINK_FLAGS "-shared -rdynamic -nodefaultlibs -undefined_warning -m32") + +# Switch install targets when uncommenting the 32 bit line above. +install(TARGETS xpc64 DESTINATION XPlaneConnect/64 RENAME lin.xpl) +install(TARGETS xpc32 DESTINATION XPlaneConnect/ RENAME lin.xpl) diff --git a/xpcPlugin/DataManager.cpp b/xpcPlugin/DataManager.cpp new file mode 100644 index 0000000..15335ec --- /dev/null +++ b/xpcPlugin/DataManager.cpp @@ -0,0 +1,818 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. +// +//X-Plane API +//Copyright(c) 2008, Sandy Barbour and Ben Supnik All rights reserved. +//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +//associated documentation files(the "Software"), to deal in the Software without restriction, +//including without limitation the rights to use, copy, modify, merge, publish, distribute, +//sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is +//furnished to do so, subject to the following conditions : +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Neither the names of the authors nor that of X - Plane or Laminar Research +// may be used to endorse or promote products derived from this software +// without specific prior written permission from the authors or +// Laminar Research, respectively. +#include "DataManager.h" +#include "DataMaps.h" +#include "Log.h" + +#include "XPLMDataAccess.h" +#include "XPLMGraphics.h" + +#include +#include +#include + +namespace XPC +{ + using namespace std; + + static map drefs; + static map mdrefs[20]; + static map sdrefs; + + void DataManager::Initialize() + { + drefs.insert(make_pair(DREF_None, XPLMFindDataRef("sim/test/test_float"))); + + drefs.insert(make_pair(DREF_Pause, XPLMFindDataRef("sim/operation/override/override_planepath"))); + drefs.insert(make_pair(DREF_PauseAI, XPLMFindDataRef("sim/operation/override/override_plane_ai_autopilot"))); + + drefs.insert(make_pair(DREF_TotalRuntime, XPLMFindDataRef("sim/time/total_running_time_sec"))); + drefs.insert(make_pair(DREF_TotalFlighttime, XPLMFindDataRef("sim/time/total_flight_time_sec"))); + drefs.insert(make_pair(DREF_TimerElapsedtime, XPLMFindDataRef("sim/time/timer_elapsed_time_sec"))); + + drefs.insert(make_pair(DREF_IndicatedAirspeed, XPLMFindDataRef("sim/flightmodel/position/indicated_airspeed"))); + drefs.insert(make_pair(DREF_TrueAirspeed, XPLMFindDataRef("sim/flightmodel/position/true_airspeed"))); + drefs.insert(make_pair(DREF_GroundSpeed, XPLMFindDataRef("sim/flightmodel/position/groundspeed"))); + + drefs.insert(make_pair(DREF_MachNumber, XPLMFindDataRef("sim/flightmodel/misc/machno"))); + drefs.insert(make_pair(DREF_GForceNormal, XPLMFindDataRef("sim/flightmodel2/misc/gforce_normal"))); + drefs.insert(make_pair(DREF_GForceAxial, XPLMFindDataRef("sim/flightmodel2/misc/gforce_axial"))); + drefs.insert(make_pair(DREF_GForceSide, XPLMFindDataRef("sim/flightmodel2/misc/gforce_side"))); + + drefs.insert(make_pair(DREF_BarometerSealevelInHg, XPLMFindDataRef("sim/weather/barometer_sealevel_inhg"))); + drefs.insert(make_pair(DREF_TemperaturSealevelC, XPLMFindDataRef("sim/weather/temperature_sealevel_c"))); + drefs.insert(make_pair(DREF_WindSpeedKts, XPLMFindDataRef("sim/cockpit2/gauges/indicators/wind_speed_kts"))); + + drefs.insert(make_pair(DREF_YokePitch, XPLMFindDataRef("sim/joystick/yoke_pitch_ratio"))); + drefs.insert(make_pair(DREF_YokeRoll, XPLMFindDataRef("sim/joystick/yoke_roll_ratio"))); + drefs.insert(make_pair(DREF_YokeHeading, XPLMFindDataRef("sim/joystick/yoke_heading_ratio"))); + + drefs.insert(make_pair(DREF_Elevator, XPLMFindDataRef("sim/cockpit2/controls/yoke_pitch_ratio"))); + drefs.insert(make_pair(DREF_Aileron, XPLMFindDataRef("sim/cockpit2/controls/yoke_roll_ratio"))); + drefs.insert(make_pair(DREF_Rudder, XPLMFindDataRef("sim/cockpit2/controls/yoke_heading_ratio"))); + + drefs.insert(make_pair(DREF_FlapSetting, XPLMFindDataRef("sim/flightmodel/controls/flaprqst"))); + drefs.insert(make_pair(DREF_FlapActual, XPLMFindDataRef("sim/flightmodel/controls/flaprat"))); + + drefs.insert(make_pair(DREF_GearDeploy, XPLMFindDataRef("sim/aircraft/parts/acf_gear_deploy"))); + drefs.insert(make_pair(DREF_GearHandle, XPLMFindDataRef("sim/cockpit/switches/gear_handle_status"))); + drefs.insert(make_pair(DREF_BrakeParking, XPLMFindDataRef("sim/flightmodel/controls/parkbrakel"))); + drefs.insert(make_pair(DREF_BrakeLeft, XPLMFindDataRef("sim/cockpit2/controls/left_brake_ratio"))); + drefs.insert(make_pair(DREF_BrakeRight, XPLMFindDataRef("sim/cockpit2/controls/right_brake_ratio"))); + + drefs.insert(make_pair(DREF_M, XPLMFindDataRef("sim/flightmodel/position/M"))); + drefs.insert(make_pair(DREF_L, XPLMFindDataRef("sim/flightmodel/position/L"))); + drefs.insert(make_pair(DREF_N, XPLMFindDataRef("sim/flightmodel/position/N"))); + + drefs.insert(make_pair(DREF_QRad, XPLMFindDataRef("sim/flightmodel/position/Qrad"))); + drefs.insert(make_pair(DREF_PRad, XPLMFindDataRef("sim/flightmodel/position/Prad"))); + drefs.insert(make_pair(DREF_RRad, XPLMFindDataRef("sim/flightmodel/position/Rrad"))); + drefs.insert(make_pair(DREF_Q, XPLMFindDataRef("sim/flightmodel/position/Q"))); + drefs.insert(make_pair(DREF_P, XPLMFindDataRef("sim/flightmodel/position/P"))); + drefs.insert(make_pair(DREF_R, XPLMFindDataRef("sim/flightmodel/position/R"))); + + drefs.insert(make_pair(DREF_Pitch, XPLMFindDataRef("sim/flightmodel/position/theta"))); + drefs.insert(make_pair(DREF_Roll, XPLMFindDataRef("sim/flightmodel/position/phi"))); + drefs.insert(make_pair(DREF_HeadingTrue, XPLMFindDataRef("sim/flightmodel/position/psi"))); + drefs.insert(make_pair(DREF_HeadingMag, XPLMFindDataRef("sim/flightmodel/position/magpsi"))); + drefs.insert(make_pair(DREF_Quaternion, XPLMFindDataRef("sim/flightmodel/position/q"))); + + drefs.insert(make_pair(DREF_AngleOfAttack, XPLMFindDataRef("sim/flightmodel/position/alpha"))); + drefs.insert(make_pair(DREF_Sideslip, XPLMFindDataRef("sim/cockpit2/gauges/indicators/sideslip_degrees"))); + drefs.insert(make_pair(DREF_HPath, XPLMFindDataRef("sim/flightmodel/position/hpath"))); + drefs.insert(make_pair(DREF_VPath, XPLMFindDataRef("sim/flightmodel/position/vpath"))); + + drefs.insert(make_pair(DREF_VPath, XPLMFindDataRef("sim/flightmodel/position/magnetic_variation"))); + + drefs.insert(make_pair(DREF_Latitude, XPLMFindDataRef("sim/flightmodel/position/latitude"))); + drefs.insert(make_pair(DREF_Longitude, XPLMFindDataRef("sim/flightmodel/position/longitude"))); + drefs.insert(make_pair(DREF_AGL, XPLMFindDataRef("sim/flightmodel/position/y_agl"))); + drefs.insert(make_pair(DREF_Elevation, XPLMFindDataRef("sim/flightmodel/position/elevation"))); + + drefs.insert(make_pair(DREF_LocalX, XPLMFindDataRef("sim/flightmodel/position/local_x"))); + drefs.insert(make_pair(DREF_LocalY, XPLMFindDataRef("sim/flightmodel/position/local_y"))); + drefs.insert(make_pair(DREF_LocalZ, XPLMFindDataRef("sim/flightmodel/position/local_z"))); + drefs.insert(make_pair(DREF_LocalVX, XPLMFindDataRef("sim/flightmodel/position/local_vx"))); + drefs.insert(make_pair(DREF_LocalVY, XPLMFindDataRef("sim/flightmodel/position/local_vy"))); + drefs.insert(make_pair(DREF_LocalVZ, XPLMFindDataRef("sim/flightmodel/position/local_vz"))); + + drefs.insert(make_pair(DREF_ThrottleSet, XPLMFindDataRef("sim/flightmodel/engine/ENGN_thro"))); + drefs.insert(make_pair(DREF_ThrottleActual, XPLMFindDataRef("sim/flightmodel2/engines/throttle_used_ratio"))); + + drefs.insert(make_pair(DREF_MP1Lat, XPLMFindDataRef("sim/multiplayer/position/plane1_lat"))); + drefs.insert(make_pair(DREF_MP2Lat, XPLMFindDataRef("sim/multiplayer/position/plane2_lat"))); + drefs.insert(make_pair(DREF_MP3Lat, XPLMFindDataRef("sim/multiplayer/position/plane3_lat"))); + drefs.insert(make_pair(DREF_MP4Lat, XPLMFindDataRef("sim/multiplayer/position/plane4_lat"))); + drefs.insert(make_pair(DREF_MP5Lat, XPLMFindDataRef("sim/multiplayer/position/plane5_lat"))); + drefs.insert(make_pair(DREF_MP6Lat, XPLMFindDataRef("sim/multiplayer/position/plane6_lat"))); + drefs.insert(make_pair(DREF_MP7Lat, XPLMFindDataRef("sim/multiplayer/position/plane7_lat"))); + + drefs.insert(make_pair(DREF_MP1Lon, XPLMFindDataRef("sim/multiplayer/position/plane1_lon"))); + drefs.insert(make_pair(DREF_MP2Lon, XPLMFindDataRef("sim/multiplayer/position/plane2_lon"))); + drefs.insert(make_pair(DREF_MP3Lon, XPLMFindDataRef("sim/multiplayer/position/plane3_lon"))); + drefs.insert(make_pair(DREF_MP4Lon, XPLMFindDataRef("sim/multiplayer/position/plane4_lon"))); + drefs.insert(make_pair(DREF_MP5Lon, XPLMFindDataRef("sim/multiplayer/position/plane5_lon"))); + drefs.insert(make_pair(DREF_MP6Lon, XPLMFindDataRef("sim/multiplayer/position/plane6_lon"))); + drefs.insert(make_pair(DREF_MP7Lon, XPLMFindDataRef("sim/multiplayer/position/plane7_lon"))); + + drefs.insert(make_pair(DREF_MP1Alt, XPLMFindDataRef("sim/multiplayer/position/plane1_el"))); + drefs.insert(make_pair(DREF_MP2Alt, XPLMFindDataRef("sim/multiplayer/position/plane2_el"))); + drefs.insert(make_pair(DREF_MP3Alt, XPLMFindDataRef("sim/multiplayer/position/plane3_el"))); + drefs.insert(make_pair(DREF_MP4Alt, XPLMFindDataRef("sim/multiplayer/position/plane4_el"))); + drefs.insert(make_pair(DREF_MP5Alt, XPLMFindDataRef("sim/multiplayer/position/plane5_el"))); + drefs.insert(make_pair(DREF_MP6Alt, XPLMFindDataRef("sim/multiplayer/position/plane6_el"))); + drefs.insert(make_pair(DREF_MP7Alt, XPLMFindDataRef("sim/multiplayer/position/plane7_el"))); + + char multi[256]; + for (int i = 1; i < 20; i++) + { + sprintf(multi, "sim/multiplayer/position/plane%i_x", i); + mdrefs[i][DREF_LocalX] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_y", i); + mdrefs[i][DREF_LocalY] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_z", i); + mdrefs[i][DREF_LocalZ] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_lat", i); + mdrefs[i][DREF_Latitude] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_lon", i); + mdrefs[i][DREF_Longitude] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_el", i); + mdrefs[i][DREF_Elevation] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_the", i); + mdrefs[i][DREF_Pitch] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_phi", i); + mdrefs[i][DREF_Roll] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_psi", i); + mdrefs[i][DREF_HeadingTrue] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_gear_deploy", i); + mdrefs[i][DREF_GearDeploy] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_flap_ratio", i); + mdrefs[i][DREF_FlapSetting] = XPLMFindDataRef(multi); // Can't set the actual flap setting on npc aircraft + mdrefs[i][DREF_FlapActual] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_flap_ratio2", i); + mdrefs[i][DREF_FlapActual2] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_spoiler_ratio", i); + mdrefs[i][DREF_Spoiler] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_speedbrake_ratio", i); + mdrefs[i][DREF_BrakeSpeed] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_slat_ratio", i); + mdrefs[i][DREF_Slats] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_wing_sweep", i); + mdrefs[i][DREF_Sweep] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_throttle", i); + mdrefs[i][DREF_ThrottleActual] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_yolk_pitch", i); + mdrefs[i][DREF_YokePitch] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_yolk_roll", i); + mdrefs[i][DREF_YokeRoll] = XPLMFindDataRef(multi); + sprintf(multi, "sim/multiplayer/position/plane%i_yolk_yaw", i); + mdrefs[i][DREF_YokeHeading] = XPLMFindDataRef(multi); + } + + // Row 0: Frame Rates + // Row 1: Times + XPData[1][1] = DREF_TotalRuntime; + XPData[1][2] = DREF_TotalFlighttime; + XPData[1][3] = DREF_TimerElapsedtime; + // Row 2: Sim stats + // Row 3: Velocities + XPData[3][0] = DREF_IndicatedAirspeed; + XPData[3][2] = DREF_TrueAirspeed; + XPData[3][4] = DREF_GroundSpeed; + // Row 4: Mach, VVI, G-Loads + XPData[4][0] = DREF_MachNumber; + XPData[4][4] = DREF_GForceNormal; + XPData[4][5] = DREF_GForceAxial; + XPData[4][6] = DREF_GForceSide; + // Row 5: Atmosphere: Weather + XPData[5][0] = DREF_BarometerSealevelInHg; + XPData[5][1] = DREF_TemperaturSealevelC; + XPData[5][3] = DREF_WindSpeedKts; + // Row 6: Atmosphere: Aircraft + // Row 7: System Pressures + // Row 8: Joystick + XPData[8][0] = DREF_YokePitch; + XPData[8][1] = DREF_YokeRoll; + XPData[8][2] = DREF_YokeHeading; + // Row 9: Other Flight Controls + // Row 10: Art stab ail/elv/rud + // Row 11: Control Surfaces + XPData[11][0] = DREF_Elevator; + XPData[11][1] = DREF_Aileron; + XPData[11][2] = DREF_Rudder; + // Row 12: Wing Sweep/Trust Vec + // Row 13: trip/flap/slat/s-brakes + XPData[13][3] = DREF_FlapSetting; + XPData[13][4] = DREF_FlapActual; + // Row 14: Gear, Brakes + XPData[14][0] = DREF_GearDeploy; + XPData[14][1] = DREF_BrakeParking; + XPData[14][2] = DREF_BrakeLeft; + XPData[14][3] = DREF_BrakeRight; + XPData[14][7] = DREF_GearHandle; + // Row 15: MNR (Angular Moments) + XPData[15][0] = DREF_M; + XPData[15][1] = DREF_L; + XPData[15][2] = DREF_N; + // Row 16: PQR (Angular Velocities) + XPData[16][0] = DREF_QRad; + XPData[16][1] = DREF_PRad; + XPData[16][2] = DREF_RRad; + XPData[16][3] = DREF_Q; + XPData[16][4] = DREF_P; + XPData[16][5] = DREF_R; + // Row 17: Orientation: pitch, roll, yaw, heading + XPData[17][0] = DREF_Pitch; + XPData[17][1] = DREF_Roll; + XPData[17][2] = DREF_HeadingTrue; + XPData[17][3] = DREF_HeadingMag; + XPData[17][4] = DREF_Quaternion; + // Row 18: Orientation: alpha beta hpath vpath slip + XPData[18][0] = DREF_AngleOfAttack; + XPData[18][1] = DREF_Sideslip; + XPData[18][2] = DREF_HPath; + XPData[18][3] = DREF_VPath; + XPData[18][4] = DREF_Sideslip; + // Row 19: Mag Compass + XPData[19][0] = DREF_HeadingMag; + XPData[19][1] = DREF_MagneticVariation; + // Row 20: Global Position + XPData[20][0] = DREF_Latitude; + XPData[20][1] = DREF_Longitude; + XPData[20][2] = DREF_Elevation; + XPData[20][3] = DREF_AGL; + // Row 21: Local Position, Velocity + XPData[21][0] = DREF_LocalX; + XPData[21][1] = DREF_LocalY; + XPData[21][2] = DREF_LocalZ; + XPData[21][3] = DREF_LocalVX; + XPData[21][4] = DREF_LocalVY; + XPData[21][5] = DREF_LocalVZ; + // Row 22: All Planes: Lat + XPData[22][0] = DREF_Latitude; + XPData[22][1] = DREF_MP1Lat; + XPData[22][2] = DREF_MP2Lat; + XPData[22][3] = DREF_MP3Lat; + XPData[22][4] = DREF_MP4Lat; + XPData[22][5] = DREF_MP5Lat; + XPData[22][6] = DREF_MP6Lat; + XPData[22][7] = DREF_MP7Lat; + // Row 23: All Planes: Lon + XPData[23][0] = DREF_Longitude; + XPData[23][1] = DREF_MP1Lon; + XPData[23][2] = DREF_MP2Lon; + XPData[23][3] = DREF_MP3Lon; + XPData[23][4] = DREF_MP4Lon; + XPData[23][5] = DREF_MP5Lon; + XPData[23][6] = DREF_MP6Lon; + XPData[23][7] = DREF_MP7Lon; + // Row 22: All Planes: Alt + XPData[24][0] = DREF_AGL; + XPData[24][1] = DREF_MP1Alt; + XPData[24][2] = DREF_MP2Alt; + XPData[24][3] = DREF_MP3Alt; + XPData[24][4] = DREF_MP4Alt; + XPData[24][5] = DREF_MP5Alt; + XPData[24][6] = DREF_MP6Alt; + XPData[24][7] = DREF_MP7Alt; + // Row 25: Throttle Command + XPData[25][0] = DREF_ThrottleSet; + // Row 26: Throttle Actual + XPData[26][0] = DREF_ThrottleActual; + } + + int DataManager::Get(string dref, float values[], int size) + { + XPLMDataRef& xdref = sdrefs[dref]; + if (xdref == NULL) + { + xdref = XPLMFindDataRef(dref.c_str()); + } + if (!xdref) // DREF does not exist + { +#if LOG_VERBOSITY > 0 + Log::FormatLine("[DMAN] ERROR: invalid DREF %s", dref.c_str()); +#endif + return 0; + } + + XPLMDataTypeID dataType = XPLMGetDataRefTypes(xdref); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] Get DREF %s (x:%X) Type: %i", dref.c_str(), xdref, dataType); +#endif + // XPLMDataTypeID is a bit flag, so it may contain more than one of the + // following types. We prefer types as close to float as possible. + if ((dataType & 2) == 2) // Float + { + values[0] = XPLMGetDataf(xdref); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] -- value was %f", values[0]); +#endif + return 1; + } + if ((dataType & 8) == 8) // Float array + { + int drefSize = XPLMGetDatavf(xdref, NULL, 0, 0); + if (drefSize > size) + { +#if LOG_VERBOSITY > 1 + Log::WriteLine("[DMAN] WARN: dref size is larger than available space"); + Log::FormatLine(" Actual dref size: %i, Available size: %i", drefSize, size); +#endif + drefSize = size; + } + XPLMGetDatavf(xdref, values, 0, drefSize); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] -- value count was %i", drefSize); +#endif + return drefSize; + } + if ((dataType & 4) == 4) // Double + { + values[0] = (float)XPLMGetDatad(xdref); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] -- value was %f", values[0]); +#endif + return 1; + } + if ((dataType & 1) == 1) // Integer + { + values[0] = (float)XPLMGetDatai(xdref); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] -- value was %i", (int)values[0]); +#endif + return 1; + } + if ((dataType & 16) == 16) // Integer array + { + int iValues[200]; + int drefSize = XPLMGetDatavi(xdref, NULL, 0, 0); + if (drefSize > size) + { +#if LOG_VERBOSITY > 1 + Log::WriteLine("[DMAN] WARN: dref size is larger than available space"); + Log::FormatLine(" Actual dref size: %i, Available size: %i", drefSize, size); +#endif + drefSize = size; + } + if (drefSize > 200) + { +#if LOG_VERBOSITY > 1 + Log::WriteLine("[DMAN] WARN: dref size is larger than temp buffer"); + Log::FormatLine(" Actual dref size: %i, Temp buffer size: 200", drefSize); +#endif + drefSize = 200; + } + XPLMGetDatavi(xdref, iValues, 0, drefSize); + for (int i = 0; i < drefSize; ++i) + { + values[i] = (float)iValues[i]; + } +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] -- value count was %i", drefSize); +#endif + return drefSize; + } + if ((dataType & 32) == 32) // Byte array + { + char bValues[1024]; + int drefSize = XPLMGetDatab(xdref, NULL, 0, 0); + if (drefSize > size) + { +#if LOG_VERBOSITY > 1 + Log::WriteLine("[DMAN] WARN: dref size is larger than available space"); + Log::FormatLine(" Actual dref size: %i, Available size: %i", drefSize, size); +#endif + drefSize = size; + } + if (drefSize > 1024) + { +#if LOG_VERBOSITY > 1 + Log::WriteLine("[DMAN] WARN: dref size is larger than temp buffer"); + Log::FormatLine(" Actual dref size: %i, Temp buffer size: 1024", drefSize); +#endif + drefSize = 1024; + } + XPLMGetDatab(xdref, bValues, 0, drefSize); + for (int i = 0; i < drefSize; ++i) + { + values[i] = (float)bValues[i]; + } +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] -- value count was %i", drefSize); +#endif + return drefSize; + } + + // No match +#if LOG_VERBOSITY > 0 + Log::WriteLine("[DMAN] ERROR: Unrecognized data type."); +#endif + return 0; + } + + double DataManager::GetDouble(DREF dref, char aircraft) + { + const XPLMDataRef& xdref = aircraft == 0 ? drefs[dref] : mdrefs[aircraft][dref]; + double value = XPLMGetDatad(xdref); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] Get DREF %i (x:%X) result %f for a/c %i", dref, xdref, value, aircraft); +#endif + return value; + } + + float DataManager::GetFloat(DREF dref, char aircraft) + { + const XPLMDataRef& xdref = aircraft == 0 ? drefs[dref] : mdrefs[aircraft][dref]; + float value = XPLMGetDataf(xdref); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] Get DREF %i (x:%X) result %f for a/c %i", dref, xdref, value, aircraft); +#endif + return value; + } + + int DataManager::GetInt(DREF dref, char aircraft) + { + const XPLMDataRef& xdref = aircraft == 0 ? drefs[dref] : mdrefs[aircraft][dref]; + int value = XPLMGetDatai(xdref); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] Get DREF %i (x:%X) result %i for a/c %i", dref, xdref, value, aircraft); +#endif + return value; + } + + int DataManager::GetFloatArray(DREF dref, float values[], int size, char aircraft) + { + const XPLMDataRef& xdref = aircraft == 0 ? drefs[dref] : mdrefs[aircraft][dref]; + int resultSize = XPLMGetDatavf(xdref, values, 0, size); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] Get DREF %i (x:%X) result size %i for a/c %i", dref, xdref, resultSize, aircraft); +#endif + return resultSize; + } + + int DataManager::GetIntArray(DREF dref, int values[], int size, char aircraft) + { + const XPLMDataRef& xdref = aircraft == 0 ? drefs[dref] : mdrefs[aircraft][dref]; + int resultSize = XPLMGetDatavi(xdref, values, 0, size); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] Get DREF %i (x:%X) result size %i for a/c %i", dref, xdref, resultSize, aircraft); +#endif + return resultSize; + } + + void DataManager::Set(DREF dref, double value, char aircraft) + { + const XPLMDataRef& xdref = aircraft == 0 ? drefs[dref] : mdrefs[aircraft][dref]; +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] Setting DREF %i (x:%X) to %f for a/c %i", dref, xdref, value, aircraft); +#endif + XPLMSetDatad(xdref, value); + } + + void DataManager::Set(DREF dref, float value, char aircraft) + { + const XPLMDataRef& xdref = aircraft == 0 ? drefs[dref] : mdrefs[aircraft][dref]; +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] Set DREF %i (x:%X) to %f for a/c %i", dref, xdref, value, aircraft); +#endif + XPLMSetDataf(xdref, value); + } + + void DataManager::Set(DREF dref, int value, char aircraft) + { + const XPLMDataRef& xdref = aircraft == 0 ? drefs[dref] : mdrefs[aircraft][dref]; +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] Set DREF %i (x:%X) to %i for a/c %i", dref, xdref, value, aircraft); +#endif + XPLMSetDatai(xdref, value); + } + + void DataManager::Set(DREF dref, float values[], int size, char aircraft) + { + const XPLMDataRef& xdref = aircraft == 0 ? drefs[dref] : mdrefs[aircraft][dref]; +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] Set DREF %i (x:%X) (%i values) for a/c %i", dref, xdref, size, aircraft); +#endif + int drefSize = XPLMGetDatavf(xdref, NULL, 0, 0); + drefSize = min(drefSize, size); + XPLMSetDatavf(xdref, values, 0, drefSize); + } + + void DataManager::Set(DREF dref, int values[], int size, char aircraft) + { + const XPLMDataRef& xdref = aircraft == 0 ? drefs[dref] : mdrefs[aircraft][dref]; +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] Setting DREF %i (x:%X) (%i values) for a/c %i", dref, xdref, size, aircraft); +#endif + int drefSize = XPLMGetDatavi(xdref, NULL, 0, 0); + drefSize = min(drefSize, size); + XPLMSetDatavi(xdref, values, 0, drefSize); + } + + void DataManager::Set(string dref, float values[], int size) + { + XPLMDataRef& xdref = sdrefs[dref]; + if (xdref == NULL) + { + xdref = XPLMFindDataRef(dref.c_str()); + } + if (!xdref) + { + // DREF does not exist +#if LOG_VERBOSITY > 0 + Log::FormatLine("[DMAN] ERROR: invalid DREF %s", dref.c_str()); +#endif + return; + } + if (isnan(values[0])) + { +#if LOG_VERBOSITY > 0 + Log::WriteLine("[DMAN] ERROR: Value must be a number (NaN received)"); +#endif + return; + } + + XPLMDataTypeID dataType = XPLMGetDataRefTypes(xdref); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] Setting DREF %s (x:%X) Type: %i", dref.c_str(), xdref, dataType); +#endif + if ((dataType & 2) == 2) // Float + { + XPLMSetDataf(xdref, values[0]); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] -- value was %f", values[0]); +#endif + } + else if ((dataType & 8) == 8) // Float Array + { + int drefSize = XPLMGetDatavf(xdref, NULL, 0, 0); +#if LOG_VERBOSITY > 1 + if (size > drefSize) + { + Log::WriteLine("[DMAN] WARN: Provided size is larger than actual dref size"); + Log::FormatLine(" Actual dref size: %i, Provided buffer size: %i", drefSize, size); + } +#endif + drefSize = min(drefSize, size); + XPLMSetDatavf(xdref, values, 0, drefSize); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] -- value count was %i", drefSize); +#endif + } + else if ((dataType & 4) == 4) // Double + { + XPLMSetDatad(xdref, values[0]); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] -- value was %f", values[0]); +#endif + } + else if ((dataType & 1) == 1) // Integer + { + XPLMSetDatai(xdref, (int)values[0]); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] -- value was %i", (int)values[0]); +#endif + } + else if ((dataType & 16) == 16) // Integer Array + { + int iValues[200]; + int drefSize = XPLMGetDatavi(xdref, NULL, 0, 0); +#if LOG_VERBOSITY > 1 + if (size > drefSize) + { + Log::WriteLine("[DMAN] WARN: Provided size is larger than actual dref size"); + Log::FormatLine(" Actual dref size: %i, Provided buffer size: %i", drefSize, size); + } +#endif + drefSize = min(drefSize, size); + if (drefSize > 200) + { +#if LOG_VERBOSITY > 1 + Log::WriteLine("[DMAN] WARN: drefSize larger than temp buffer size."); + Log::FormatLine(" Actual dref size: %i, Temp buffer size: 200", drefSize); +#endif + drefSize = 200; + } + for (int i = 0; i < drefSize; ++i) + { + iValues[i] = (int)values[i]; + } + XPLMSetDatavi(xdref, iValues, 0, drefSize); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] -- value count was %i", drefSize); +#endif + } + else if ((dataType & 32) == 32) // Byte Array + { + char bValues[1024]; + int drefSize = XPLMGetDatab(xdref, NULL, 0, 0); +#if LOG_VERBOSITY > 1 + if (size > drefSize) + { + Log::WriteLine("[DMAN] WARN: Provided size is larger than actual dref size"); + Log::FormatLine(" Actual dref size: %i, Provided buffer size: %i", drefSize, size); + } +#endif + drefSize = min(drefSize, size); + if (drefSize > 1024) + { +#if LOG_VERBOSITY > 1 + Log::WriteLine("[DMAN] WARN: drefSize larger than temp buffer size."); + Log::FormatLine(" Actual dref size: %i, Temp buffer size: 1024", drefSize); +#endif + drefSize = 1024; + } + for (int i = 0; i < drefSize; ++i) + { + bValues[i] = (char)values[i]; + } + XPLMSetDatab(xdref, bValues, 0, drefSize); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[DMAN] -- value count was %i", drefSize); +#endif + } + else + { +#if LOG_VERBOSITY > 0 + Log::WriteLine("[DMAN] ERROR: Unknown type."); +#endif + } + + +#if LOG_VERBOSITY > 1 + if (!XPLMCanWriteDataRef(xdref)) + { + Log::WriteLine("[DMAN] WARN: dref is not writable. The write operation probably failed."); + } +#endif + } + + void DataManager::SetGear(float gear, bool immediate, char aircraft) + { +#if LOG_VERBOSITY > 3 + Log::FormatLine("[DMAN] Setting gear (value:%f, immediate:%i) for aircraft %i", gear, immediate, aircraft); +#endif + if (isnan(gear) || gear < 0 || gear > 1) + { +#if LOG_VERBOSITY > 0 + Log::WriteLine("[GEAR] ERROR: Value must be 0 or 1"); +#endif + return; + } + + if ((gear < -8.5 && gear > -9.5) || (gear < -997.9 && gear > -999.1)) + { + return; + } + + float gearArray[10]; + for (int i = 0; i < 10; i++) + { + gearArray[i] = gear; + } + + if (aircraft == 0) // Own aircraft + { + Set(DREF_GearHandle, (int)gear); + if (immediate) + { + Set(DREF_GearDeploy, gearArray, 10); + } + } + else // Multiplayer aircraft + { + Set(DREF_GearDeploy, gearArray, 10, aircraft); + } + } + + void DataManager::SetPosition(float pos[3], char aircraft) + { +#if LOG_VERBOSITY > 3 + Log::FormatLine("[DMAN] Setting position (%f, %f, %f) for aircraft %i", pos[0], pos[1], pos[2], aircraft); +#endif + if (isnan(pos[0] + pos[1] + pos[2])) + { +#if LOG_VERBOSITY > 0 + Log::WriteLine("[DMAN] ERROR: Position must be a number (NaN received)"); +#endif + return; + } + + if (pos[0] < -997.9 && pos[0] > -999.1) + { + pos[0] = (float)GetDouble(DREF_Latitude, aircraft); + } + if (pos[1] < -997.9 && pos[1] > -999.1) + { + pos[1] = (float)GetDouble(DREF_Longitude, aircraft); + } + if (pos[2] < -997.9 && pos[2] > -999.1) + { + pos[2] = (float)GetDouble(DREF_Elevation, aircraft); + } + + double local[3]; + XPLMWorldToLocal(pos[0], pos[1], pos[2], &local[0], &local[1], &local[2]); + // If the sim is paused, setting global position won't update the + // local position, so set them just in case. + Set(DREF_LocalX, local[0], aircraft); + Set(DREF_LocalY, local[1], aircraft); + Set(DREF_LocalZ, local[2], aircraft); + // If the sim is unpaused, this will override the above settings. + // TODO: Are these setable when paused? Are these necessary? + Set(DREF_Latitude, (double)pos[0], aircraft); + Set(DREF_Longitude, (double)pos[1], aircraft); + Set(DREF_Elevation, (double)pos[2], aircraft); + } + + void DataManager::SetOrientation(float orient[3], char aircraft) + { +#if LOG_VERBOSITY > 3 + Log::FormatLine("[DMAN] Setting orientation (%f, %f, %f) for aircraft %i", + orient[0], orient[1], orient[2], aircraft); +#endif + if (isnan(orient[0] + orient[1] + orient[2])) + { +#if LOG_VERBOSITY > 0 + Log::WriteLine("[DMAN] ERROR: Orientation must be a number (NaN received)"); +#endif + return; + } + + if (orient[0] < -997.9 && orient[0] > -999.1) + { + orient[0] = GetFloat(DREF_Pitch, aircraft); + } + if (orient[1] < -997.9 && orient[1] > -999.1) + { + orient[1] = GetFloat(DREF_Roll, aircraft); + } + if (orient[2] < -997.9 && orient[2] > -999.1) + { + orient[2] = GetFloat(DREF_HeadingTrue, aircraft); + } + + + // If the sim is paused, setting the quaternion won't update these values, + // so we set them here just in case. This also covers multiplayer aircraft, + // which we can't set the quaternion on. + Set(DREF_Pitch, orient[0], aircraft); + Set(DREF_Roll, orient[1], aircraft); + Set(DREF_HeadingTrue, orient[2], aircraft); + if (aircraft == 0) // Player aircraft + { + // Convert to Quaternions + // from: http://www.xsquawkbox.net/xpsdk/mediawiki/MovingThePlane + // http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19770024290.pdf + float q[4]; + float halfRad = 0.00872664625997F; + orient[2] = halfRad * orient[2]; + orient[0] = halfRad * orient[0]; + orient[1] = halfRad * orient[1]; + q[0] = cos(orient[2]) * cos(orient[0]) * cos(orient[1]) + sin(orient[2]) * sin(orient[0]) * sin(orient[1]); + q[1] = cos(orient[2]) * cos(orient[0]) * sin(orient[1]) - sin(orient[2]) * sin(orient[0]) * cos(orient[1]); + q[2] = cos(orient[2]) * sin(orient[0]) * cos(orient[1]) + sin(orient[2]) * cos(orient[0]) * sin(orient[1]); + q[3] = sin(orient[2]) * cos(orient[0]) * cos(orient[1]) - cos(orient[2]) * sin(orient[0]) * sin(orient[1]); + + // If the sim is un-paused, this will overwrite the pitch/roll/yaw + // values set above. + Set(DREF_Quaternion, q, 4); + } + } + + void DataManager::SetFlaps(float value) + { + if (isnan(value)) + { +#if LOG_VERBOSITY > 0 + Log::WriteLine("[DMAN] ERROR: Flap value must be a number (NaN received)"); +#endif + return; + } + if (value < -997.9 && value > -999.1) + { + return; + } + + value = (float)fmaxl(value, 0); + value = (float)fminl(value, 1); + + Set(DREF_FlapSetting, value); + Set(DREF_FlapActual, value); + } +} \ No newline at end of file diff --git a/xpcPlugin/DataManager.h b/xpcPlugin/DataManager.h new file mode 100644 index 0000000..71787dd --- /dev/null +++ b/xpcPlugin/DataManager.h @@ -0,0 +1,411 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. +#ifndef XPC_DATAMANAGER_H +#define XPC_DATAMANAGER_H + +#include + +namespace XPC +{ + /// Represents named datarefs used by X-Plane Connect + enum DREF + { + DREF_None = 0, + + DREF_Pause, + DREF_PauseAI, + + // Times + DREF_TotalRuntime = 100, + DREF_TotalFlighttime, + DREF_TimerElapsedtime, + + // Velocities + DREF_IndicatedAirspeed = 300, + DREF_TrueAirspeed, + DREF_GroundSpeed, + + // Mach, VVI, G-loads + DREF_MachNumber = 400, + DREF_GForceNormal, + DREF_GForceAxial, + DREF_GForceSide, + + // Atmosphere: Weather + DREF_BarometerSealevelInHg = 500, + DREF_TemperaturSealevelC, + DREF_WindSpeedKts, + + // Joystick + DREF_YokePitch = 800, + DREF_YokeRoll, + DREF_YokeHeading, + + // Control Surfaces + DREF_Elevator = 1100, + DREF_Aileron, + DREF_Rudder, + + // Flaps + DREF_FlapSetting = 1300, + DREF_FlapActual, + + // Gear & Brakes + DREF_GearDeploy = 1400, + DREF_GearHandle, + DREF_BrakeParking, + DREF_BrakeLeft, + DREF_BrakeRight, + + // MNR (Angular Moments) + DREF_M = 1500, + DREF_L, + DREF_N, + + //PQR (Angular Velocities) + DREF_QRad = 1600, + DREF_PRad, + DREF_RRad, + DREF_Q, + DREF_P, + DREF_R, + + // Orientation: pitch, roll, yaw, heading + DREF_Pitch = 1700, + DREF_Roll, + DREF_HeadingTrue, + DREF_HeadingMag, + DREF_Quaternion, + + // Orientation: alpha beta hpath vpath slip + DREF_AngleOfAttack = 1800, + DREF_Sideslip, + DREF_HPath, + DREF_VPath, + + DREF_MagneticVariation = 1901, + + // Global Position + DREF_Latitude = 2000, + DREF_Longitude, + DREF_Elevation, + DREF_AGL, + + // Local Postion & Velocity + DREF_LocalX = 2100, + DREF_LocalY, + DREF_LocalZ, + DREF_LocalVX, + DREF_LocalVY, + DREF_LocalVZ, + + DREF_ThrottleSet = 2200, + DREF_ThrottleActual = 2300, + + // Multiplayer Aircraft + DREF_FlapActual2, + DREF_Spoiler, + DREF_BrakeSpeed, + DREF_Sweep, + DREF_Slats, + + // Mulitplayer positon + DREF_MP1Lat, + DREF_MP2Lat, + DREF_MP3Lat, + DREF_MP4Lat, + DREF_MP5Lat, + DREF_MP6Lat, + DREF_MP7Lat, + + DREF_MP1Lon, + DREF_MP2Lon, + DREF_MP3Lon, + DREF_MP4Lon, + DREF_MP5Lon, + DREF_MP6Lon, + DREF_MP7Lon, + + DREF_MP1Alt, + DREF_MP2Alt, + DREF_MP3Alt, + DREF_MP4Alt, + DREF_MP5Alt, + DREF_MP6Alt, + DREF_MP7Alt + }; + + /// Marshals data between the plugin and X-Plane. + /// + /// \author Jason Watkins + /// \version 1.0.1 + /// \since 1.0.0 + /// \date Intial Version: 2015-04-13 + /// \date Last Updated: 2015-04-29 + class DataManager + { + public: + /// Initializes the internal data used by DataManager to translate DREF values + /// into X-Plane internal data. + static void Initialize(); + + /// Gets a dataref based on its name. + /// + /// \param dref The name of the dref to get. + /// \param values An array in which the result of the operation will be stored. + /// \param size The size of the values array. + /// \returns The number of elements placed in the values array. For scalar + /// drefs, this will be one. For array drefs, this will be the + /// lesser of the size and the number of elements in the dref. + /// + /// \remarks The first time this method is called for a given dataref, it must + /// perform a relatively expensive lookup operation to translate the + /// given string into an X-Plane internal pointer. This value is cached, + /// so subsequent calls will incure minimal extra overhead compared to + /// the other methods in this class. + /// + /// \remarks For simplicity, this method is provided with only one output type. + /// For most integer and double drefs, this is unlikely to cause issues. + /// However, for drefs where the entire integer range may be used, or + /// doubles where high precision is required, using this method may result + /// in a loss of precision. In that case, consider using one of the + /// strongly typed methods instead. + static int Get(std::string dref, float values[], int size); + + /// Gets the value of a double dataref. + /// + /// \param dref The dataref to get. + /// \param aircraft The aircraft number for which to get the data. + /// \returns The value of the dref specified if that dref has the type + /// double; otherwise an undefined value. + /// + /// \remarks This method does not verify the type of the dref requested. It is + /// the responsibility of the caller to check the X-Plane documentation + /// and call the appropriate overload of this method. If the wrong + /// overload is called, the value returned is determined by the X-Plane + /// plugin manager, and is considered undefined by the plugin. + /// + /// \remarks Although any combination of dref and aircraft may be passed to this + /// method, most drefs are not valid for multiplayer aircraft. All drefs + /// that are not prefixed with 'MP' are valid for the player aircraft. + /// 'MP' drefs should be called with aircraft 0. + static double GetDouble(DREF dref, char aircraft = 0); + + /// Gets the value of a float dataref. + /// + /// \param dref The dataref to get. + /// \param aircraft The aircraft number for which to get the data. + /// \returns The value of the dref specified if that dref has the type + /// float; otherwise an undefined value. + /// + /// \remarks This method does not verify the type of the dref requested. It is + /// the responsibility of the caller to check the X-Plane documentation + /// and call the appropriate overload of this method. If the wrong + /// overload is called, the value returned is determined by the X-Plane + /// plugin manager, and is considered undefined by the plugin. + /// + /// \remarks Although any combination of dref and aircraft may be passed to this + /// method, most drefs are not valid for multiplayer aircraft. All drefs + /// that are not prefixed with 'MP' are valid for the player aircraft. + /// 'MP' drefs should be called with aircraft 0. + static float GetFloat(DREF dref, char aircraft = 0); + + /// Gets the value of an integer dataref. + /// + /// \param dref The dataref to get. + /// \param aircraft The aircraft number for which to get the data. + /// \returns The value of the dref specified if that dref has the type + /// int; otherwise an undefined value. + /// + /// \remarks This method does not verify the type of the dref requested. It is + /// the responsibility of the caller to check the X-Plane documentation + /// and call the appropriate overload of this method. If the wrong + /// overload is called, the value returned is determined by the X-Plane + /// plugin manager, and is considered undefined by the plugin. + /// + /// \remarks Although any combination of dref and aircraft may be passed to this + /// method, most drefs are not valid for multiplayer aircraft. All drefs + /// that are not prefixed with 'MP' are valid for the player aircraft. + /// 'MP' drefs should be called with aircraft 0. + static int GetInt(DREF dref, char aircraft = 0); + + /// Gets the value of a float array dataref. + /// + /// \param dref The dataref to get. + /// \param values An array in which the result of the operation will be stored. + /// \param size The size of the values array. + /// \param aircraft The aircraft number for which to get the data. + /// \returns The number of elements placed in the values array. This will + /// be the lesser of the size and the number of elements in the dref. + /// + /// \remarks This method does not verify the type of the dref requested. It is + /// the responsibility of the caller to check the X-Plane documentation + /// and call the appropriate overload of this method. If the wrong + /// overload is called, the value returned is determined by the X-Plane + /// plugin manager, and is considered undefined by the plugin. + /// + /// \remarks Although any combination of dref and aircraft may be passed to this + /// method, most drefs are not valid for multiplayer aircraft. All drefs + /// that are not prefixed with 'MP' are valid for the player aircraft. + /// 'MP' drefs should be called with aircraft 0. + static int GetFloatArray(DREF dref, float values[], int size, char aircraft = 0); + + + /// Gets the value of an int array dataref. + /// + /// \param dref The dataref to get. + /// \param values An array in which the result of the operation will be stored. + /// \param size The size of the values array. + /// \param aircraft The aircraft number for which to get the data. + /// \returns The number of elements placed in the values array. This will + /// be the lesser of the size and the number of elements in the dref. + /// + /// \remarks This method does not verify the type of the dref requested. It is + /// the responsibility of the caller to check the X-Plane documentation + /// and call the appropriate overload of this method. If the wrong + /// overload is called, the value returned is determined by the X-Plane + /// plugin manager, and is considered undefined by the plugin. + /// + /// \remarks Although any combination of dref and aircraft may be passed to this + /// method, most drefs are not valid for multiplayer aircraft. All drefs + /// that are not prefixed with 'MP' are valid for the player aircraft. + /// 'MP' drefs should be called with aircraft 0. + static int GetIntArray(DREF dref, int values[], int size, char aircraft = 0); + + /// Sets the value of a dataref + /// + /// \param dref The name of the dref to set. + /// \param values The value to set the dref to. + /// \param size The number of items stored in values. + /// + /// \remarks The first time this method is called for a given dataref, it must + /// perform a relatively expensive lookup operation to translate the + /// given string into an X-Plane internal pointer. This value is cached, + /// so subsequent calls will incure minimal extra overhead compared to + /// the other methods in this class. + /// + /// \remarks For simplicity, this method is provided with only one input type. + /// For most integer and double drefs, this is unlikely to cause issues. + /// However, for drefs where the entire integer range may be used, or + /// doubles where high precision is required, using this method may result + /// in a loss of precision. In that case, consider using one of the + /// strongly typed methods instead. + static void Set(std::string dref, float values[], int size); + + /// Sets the value of a double dataref. + /// + /// \param dref The dataref to set. + /// \param value The value to set the dref to. + /// \param aircraft The aircraft number for which to get the data. + /// + /// \remarks This method does not verify the type of the dref being set. It is + /// the responsibility of the caller to check the X-Plane documentation + /// and call the appropriate overload of this method. If the wrong + /// overload is called, the operation will fail silently. + /// + /// \remarks Although any combination of dref and aircraft may be passed to this + /// method, most drefs are not valid for multiplayer aircraft. All drefs + /// that are not prefixed with 'MP' are valid for the player aircraft. + /// 'MP' drefs should be called with aircraft 0. + static void Set(DREF dref, double value, char aircraft = 0); + + /// Sets the value of a float dataref. + /// + /// \param dref The dataref to set. + /// \param value The value to set the dref to. + /// \param aircraft The aircraft number for which to get the data. + /// + /// \remarks This method does not verify the type of the dref being set. It is + /// the responsibility of the caller to check the X-Plane documentation + /// and call the appropriate overload of this method. If the wrong + /// overload is called, the operation will fail silently. + /// + /// \remarks Although any combination of dref and aircraft may be passed to this + /// method, most drefs are not valid for multiplayer aircraft. All drefs + /// that are not prefixed with 'MP' are valid for the player aircraft. + /// 'MP' drefs should be called with aircraft 0. + static void Set(DREF dref, float value, char aircraft = 0); + + /// Sets the value of an integer dataref. + /// + /// \param dref The dataref to set. + /// \param value The value to set the dref to. + /// \param aircraft The aircraft number for which to get the data. + /// + /// \remarks This method does not verify the type of the dref being set. It is + /// the responsibility of the caller to check the X-Plane documentation + /// and call the appropriate overload of this method. If the wrong + /// overload is called, the operation will fail silently. + /// + /// \remarks Although any combination of dref and aircraft may be passed to this + /// method, most drefs are not valid for multiplayer aircraft. All drefs + /// that are not prefixed with 'MP' are valid for the player aircraft. + /// 'MP' drefs should be called with aircraft 0. + static void Set(DREF dref, int value, char aircraft = 0); + + /// Sets the value of a float array dataref. + /// + /// \param dref The dataref to set. + /// \param values The value to set the dref to. + /// \param size The number of items stored in values. + /// \param aircraft The aircraft number for which to get the data. + /// + /// \remarks This method does not verify the type of the dref being set. It is + /// the responsibility of the caller to check the X-Plane documentation + /// and call the appropriate overload of this method. If the wrong + /// overload is called, the operation will fail silently. + /// + /// \remarks Although any combination of dref and aircraft may be passed to this + /// method, most drefs are not valid for multiplayer aircraft. All drefs + /// that are not prefixed with 'MP' are valid for the player aircraft. + /// 'MP' drefs should be called with aircraft 0. + static void Set(DREF dref, float values[], int size, char aircraft = 0); + + /// Sets the value of an integer array dataref. + /// + /// \param dref The dataref to set. + /// \param values The value to set the dref to. + /// \param size The number of items stored in values. + /// \param aircraft The aircraft number for which to get the data. + /// + /// \remarks This method does not verify the type of the dref being set. It is + /// the responsibility of the caller to check the X-Plane documentation + /// and call the appropriate overload of this method. If the wrong + /// overload is called, the operation will fail silently. + /// + /// \remarks Although any combination of dref and aircraft may be passed to this + /// method, most drefs are not valid for multiplayer aircraft. All drefs + /// that are not prefixed with 'MP' are valid for the player aircraft. + /// 'MP' drefs should be called with aircraft 0. + static void Set(DREF dref, int values[], int size, char aircraft = 0); + + /// Sets the landing gear for the specified airplane. + /// + /// \param gear The value to set the gear to. 0 for gear down, 1 for gear up. + /// \param immediate Whether the gear should be forced to the specified position. + /// If immediate is false, only the gear handle dref will be set. + /// \param aircraft The aircraft to set the landing gear status on. + static void SetGear(float gear, bool immediate, char aircraft = 0); + + /// Sets the position of the specified aircraft on the Earth. + /// + /// \param pos An array containing latitude, longitude and altitude in + /// fractional degrees and meters above sea level. + /// \param aircraft The aircraft to set the position of. + static void SetPosition(float pos[3], char aircraft = 0); + + /// Sets the orientation of the specified aircraft. + /// + /// \param orient An array containing the pitch, roll, and yaw orientations + /// to set, all in fractional degrees. + /// \param aircraft The aircraft to set the orientation of. + static void SetOrientation(float orient[3], char aircraft = 0); + + /// Sets flaps on the the player aircraft. + /// + /// \param value The flaps settings. Should be between 0.0 (no flaps) and 1.0 (full flaps). + static void SetFlaps(float value); + }; +} + +#endif \ No newline at end of file diff --git a/xpcPlugin/DataMaps.cpp b/xpcPlugin/DataMaps.cpp new file mode 100644 index 0000000..977194e --- /dev/null +++ b/xpcPlugin/DataMaps.cpp @@ -0,0 +1,8 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. +#include "DataManager.h" + +namespace XPC +{ + DREF XPData[134][8] = { DREF_None }; +} \ No newline at end of file diff --git a/xpcPlugin/DataMaps.h b/xpcPlugin/DataMaps.h new file mode 100644 index 0000000..ef600b7 --- /dev/null +++ b/xpcPlugin/DataMaps.h @@ -0,0 +1,13 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. +#ifndef XPC_DATAMAPS_H +#define XPC_DATAMAPS_H +#include "DataManager.h" + +namespace XPC +{ + /// Maps X-Plane dataref lines to XPC DREF values. + extern DREF XPData[134][8]; +} + +#endif \ No newline at end of file diff --git a/xpcPlugin/Drawing.cpp b/xpcPlugin/Drawing.cpp new file mode 100644 index 0000000..63caf55 --- /dev/null +++ b/xpcPlugin/Drawing.cpp @@ -0,0 +1,301 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. +// +//X-Plane API +//Copyright(c) 2008, Sandy Barbour and Ben Supnik All rights reserved. +//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +//associated documentation files(the "Software"), to deal in the Software without restriction, +//including without limitation the rights to use, copy, modify, merge, publish, distribute, +//sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is +//furnished to do so, subject to the following conditions : +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Neither the names of the authors nor that of X - Plane or Laminar Research +// may be used to endorse or promote products derived from this software +// without specific prior written permission from the authors or +// Laminar Research, respectively. +#include "Drawing.h" + +#include "XPLMDisplay.h" +#include "XPLMGraphics.h" +#include "XPLMDataAccess.h" + +#include +#include +#include +//OpenGL includes +#if IBM +#include +#endif +#ifdef __APPLE__ +# include +#else +# include +#endif/*__APPLE__*/ + +namespace XPC +{ + //Internal Structures + typedef struct + { + double x; + double y; + double z; + } LocalPoint; + + //Internal Memory + static const size_t MSG_MAX = 1024; + static const size_t MSG_LINE_MAX = MSG_MAX / 16; + static bool msgEnabled = false; + static int msgX = -1; + static int msgY = -1; + static char msgVal[MSG_MAX] = { 0 }; + static size_t newLineCount = 0; + static size_t newLines[MSG_LINE_MAX] = { 0 }; + static float rgb[3] = { 0.25F, 1.0F, 0.25F }; + + static const size_t WAYPOINT_MAX = 128; + static bool routeEnabled = false; + static size_t numWaypoints = 0; + static Waypoint waypoints[WAYPOINT_MAX]; + static LocalPoint localPoints[WAYPOINT_MAX]; + + XPLMDataRef planeXref; + XPLMDataRef planeYref; + XPLMDataRef planeZref; + + //Internal Functions + static int cmp(const void * a, const void * b) + { + std::size_t sa = *(size_t*)a; + std::size_t sb = *(size_t*)b; + if (sa > sb) + { + return 1; + } + if (sb > sa) + { + return -1; + } + return 0; + } + + static void gl_drawCube(float x, float y, float z, float d) + { + //tan(0.25) degrees. Should scale all markers to appear about the same size + const float TAN = 0.00436335F; + float h = d * TAN; + + glBegin(GL_QUAD_STRIP); + //Top + glVertex3f(x - h, y + h, z - h); + glVertex3f(x + h, y + h, z - h); + glVertex3f(x - h, y + h, z + h); + glVertex3f(x + h, y + h, z + h); + //Front + glVertex3f(x - h, y - h, z + h); + glVertex3f(x + h, y - h, z + h); + //Bottom + glVertex3f(x - h, y - h, z - h); + glVertex3f(x + h, y - h, z - h); + //Back + glVertex3f(x - h, y + h, z - h); + glVertex3f(x + h, y + h, z - h); + + glEnd(); + glBegin(GL_QUADS); + //Left + glVertex3f(x - h, y + h, z - h); + glVertex3f(x - h, y + h, z + h); + glVertex3f(x - h, y - h, z + h); + glVertex3f(x - h, y - h, z - h); + //Right + glVertex3f(x + h, y + h, z + h); + glVertex3f(x + h, y + h, z - h); + glVertex3f(x + h, y - h, z - h); + glVertex3f(x + h, y - h, z + h); + + glEnd(); + } + + static int MessageDrawCallback(XPLMDrawingPhase inPhase, int inIsBefore, void * inRefcon) + { + XPLMDrawString(rgb, msgX, msgY, msgVal, NULL, xplmFont_Basic); + int y = msgY - 16; + for (size_t i = 0; i < newLineCount; ++i) + { + XPLMDrawString(rgb, msgX, y, msgVal + newLines[i], NULL, xplmFont_Basic); + y -= 16; + } + return 1; + } + + static int RouteDrawCallback(XPLMDrawingPhase inPhase, int inIsBefore, void * inRefcon) + { + float px = XPLMGetDataf(planeXref); + float py = XPLMGetDataf(planeYref); + float pz = XPLMGetDataf(planeZref); + + //Convert to local + for (size_t i = 0; i < numWaypoints; ++i) + { + Waypoint* g = &waypoints[i]; + LocalPoint* l = &localPoints[i]; + XPLMWorldToLocal(g->latitude, g->longitude, g->altitude, + &l->x, &l->y, &l->z); + } + + + //Draw posts + glColor3f(1.0F, 1.0F, 1.0F); + glBegin(GL_LINES); + for (size_t i = 0; i < numWaypoints; ++i) + { + LocalPoint* l = &localPoints[i]; + glVertex3f((float)l->x, (float)l->y, (float)l->z); + glVertex3f((float)l->x, -1000.0F, (float)l->z); + } + glEnd(); + + //Draw route + glColor3f(1.0F, 0.0F, 0.0F); + glBegin(GL_LINE_STRIP); + for (size_t i = 0; i < numWaypoints; ++i) + { + LocalPoint* l = &localPoints[i]; + glVertex3f((float)l->x, (float)l->y, (float)l->z); + } + glEnd(); + + //Draw markers + glColor3f(1.0F, 1.0F, 1.0F); + for (size_t i = 0; i < numWaypoints; ++i) + { + LocalPoint* l = &localPoints[i]; + float xoff = (float)l->x - px; + float yoff = (float)l->y - py; + float zoff = (float)l->z - pz; + float d = sqrtf(xoff*xoff + yoff*yoff + zoff*zoff); + gl_drawCube((float)l->x, (float)l->y, (float)l->z, d); + } + return 1; + } + + //Public Functions + void Drawing::ClearMessage() + { + XPLMUnregisterDrawCallback(MessageDrawCallback, xplm_Phase_Window, 0, NULL); + msgEnabled = false; + } + + void Drawing::SetMessage(int x, int y, char* msg) + { + //Determine size of message and clear instead if the message string + //is empty. + size_t len = strnlen(msg, MSG_MAX - 1); + if (len == 0) + { + ClearMessage(); + return; + } + + //Set the message, location, and mark new lines. + strncpy(msgVal, msg, len + 1); + newLineCount = 0; + for (size_t i = 0; i < len && newLineCount < MSG_LINE_MAX; ++i) + { + if (msgVal[i] == '\n' || msgVal[i] == '\r') + { + msgVal[i] = 0; + newLines[newLineCount++] = i + 1; + } + } + msgX = x < 0 ? 10 : x; + msgY = y < 0 ? 600 : y; + + //Enable drawing if necessary + if (!msgEnabled) + { + XPLMRegisterDrawCallback(MessageDrawCallback, xplm_Phase_Window, 0, NULL); + msgEnabled = true; + } + } + + void Drawing::ClearWaypoints() + { + numWaypoints = 0; + if (routeEnabled) + { + XPLMUnregisterDrawCallback(RouteDrawCallback, xplm_Phase_Objects, 0, NULL); + } + return; + } + + void Drawing::AddWaypoints(Waypoint points[], size_t numPoints) + { + if (numWaypoints + numPoints > WAYPOINT_MAX) + { + numPoints = WAYPOINT_MAX - numWaypoints; + } + size_t finalNumWaypoints = numPoints + numWaypoints; + for (size_t i = 0; i < numPoints; ++i) + { + waypoints[numWaypoints + i] = points[i]; + } + numWaypoints = finalNumWaypoints; + + if (!routeEnabled) + { + XPLMRegisterDrawCallback(RouteDrawCallback, xplm_Phase_Objects, 0, NULL); + } + if (!planeXref) + { + planeXref = XPLMFindDataRef("sim/flightmodel/position/local_x"); + planeYref = XPLMFindDataRef("sim/flightmodel/position/local_y"); + planeZref = XPLMFindDataRef("sim/flightmodel/position/local_z"); + } + } + + void Drawing::RemoveWaypoints(Waypoint points[], size_t numPoints) + { + //Build a list of indices of waypoints we should delete. + size_t delPoints[WAYPOINT_MAX]; + size_t delPointsCur = 0; + for (size_t i = 0; i < numPoints; ++i) + { + Waypoint p = points[i]; + for (size_t j = 0; j < numWaypoints; ++j) + { + Waypoint q = waypoints[j]; + if (p.latitude == q.latitude && + p.longitude == q.longitude && + p.altitude == q.altitude) + { + delPoints[delPointsCur++] = j; + break; + } + } + } + //Sort the indices so that we only have to iterate them once + qsort(delPoints, delPointsCur, sizeof(size_t), cmp); + + //Copy the new array on top of the old array + size_t copyCur = 0; + size_t count = delPointsCur; + delPointsCur = 0; + for (size_t i = 0; i < numWaypoints; ++i) + { + if (i == delPoints[delPointsCur]) + { + ++delPointsCur; + continue; + } + waypoints[copyCur++] = waypoints[i]; + } + numWaypoints -= count; + if (numWaypoints == 0) + { + ClearWaypoints(); + } + } +} diff --git a/xpcPlugin/Drawing.h b/xpcPlugin/Drawing.h new file mode 100644 index 0000000..0187810 --- /dev/null +++ b/xpcPlugin/Drawing.h @@ -0,0 +1,61 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. +#ifndef XPC_DRAWING_H +#define XPC_DRAWING_H + +#include + +namespace XPC +{ + typedef struct + { + double latitude; + double longitude; + double altitude; + } Waypoint; + + /// Handles tasks that involve drawing to the screen in X-Plane. + /// + /// \author Jason Watkins + /// \version 1.0 + /// \since 1.0 + /// \date Intial Version: 2015-04-10 + /// \date Last Updated: 2015-04-10 + class Drawing + { + public: + /// Clears the current message on the screen if any and unregisters the + /// draw callback for message drawing. + static void ClearMessage(); + + /// Sets the message to be drawn on the screen. + /// + /// \param x The x coordinate of the message relative to the left edge + /// of the screen. + /// \param y The y coordinate of the message relative to the bottom + /// edge of the screen + /// \param msg A C string containing the message to display. The message + /// value is copied into a local buffer. + static void SetMessage(int x, int y, char* msg); + + /// Adds the given waypoints to the list of waypoints to draw. + /// + /// \param points A pointer to an array of waypoints. + /// \param numPoints The number of points in the array. + static void AddWaypoints(Waypoint points[], size_t numPoints); + + /// Removes all waypoints and unregisters the callback for waypoint + /// drawing. + static void ClearWaypoints(); + + /// Removes the given waypoints from the list of waypoints to draw. + /// If all waypoints are removed as a result of this action, unregisters + /// the callback for waypoint drawing. + /// + /// \param points A pointer to an array of waypoints. + /// \param numPoints The number of points in the array. + static void RemoveWaypoints(Waypoint points[], size_t numPoints); + }; +} + +#endif \ No newline at end of file diff --git a/xpcPlugin/Log.cpp b/xpcPlugin/Log.cpp new file mode 100644 index 0000000..c08de8d --- /dev/null +++ b/xpcPlugin/Log.cpp @@ -0,0 +1,97 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. +#include "Log.h" +#include +#include +#include + +// Implementation note: I initial wrote this class using C++ iostreams, but I couldn't find any +// way to implement FormatLine without adding in a call to sprintf. It therefore seems more +// efficient to me to just use C-style IO and call fprintf directly. +namespace XPC +{ + static void WriteTime(FILE* fd) + { + time_t rawtime; + tm* timeinfo; + time(&rawtime); + timeinfo = localtime(&rawtime); + + char buffer[16] = { 0 }; + // Format is equivalent to [%F %T], but neither of those specifiers is + // supported on Windows as of Visual Studio 13 + strftime(buffer, 16, "[%H:%M:%S] ", timeinfo); + + fprintf(fd, buffer); + } + + void Log::Initialize(std::string version) + { + FILE* fd = fopen("XPCLog.txt", "w"); + if (fd != NULL) + { + time_t rawtime; + tm* timeinfo; + time(&rawtime); + timeinfo = localtime(&rawtime); + + char timeStr[16] = { 0 }; + // Format is equivalent to %F, but neither of those specifiers is + // supported on Windows as of Visual Studio 13 + strftime(timeStr, 16, "%Y-%m-%d", timeinfo); + + fprintf(fd, "X-Plane Connect [Version %s]\n", version.c_str()); + fprintf(fd, "Compiled %s %s\n", __DATE__, __TIME__); + fprintf(fd, "Copyright (c) 2013-2015 United States Government as represented by the\n"); + fprintf(fd, "Administrator of the National Aeronautics and Space Administration.\n"); + fprintf(fd, "All Rights Reserved.\n\n"); + + fprintf(fd, "This file contains debugging information about the X-Plane Connect plugin.\n"); + fprintf(fd, "If you have technical issues with the plugin, please report them by opening\n"); + fprintf(fd, "an issue on GitHub (https://github.com/nasa/XPlaneConnect/issues) or by\n"); + fprintf(fd, "emailing Christopher Teubert (christopher.a.teubert@nasa.gov).\n\n"); + + fprintf(fd, "Log file generated on %s.\n", timeStr); + fclose(fd); + } + } + + void Log::WriteLine(const std::string& value) + { + Log::WriteLine(value.c_str()); + } + + void Log::WriteLine(const char* value) + { + FILE* fd = fopen("XPCLog.txt", "a"); + if (!fd) + { + return; + } + + WriteTime(fd); + fprintf(fd, "%s\n", value); + + fclose(fd); + } + + void Log::FormatLine(const char* format, ...) + { + va_list args; + + FILE* fd = fopen("XPCLog.txt", "a"); + if (!fd) + { + return; + } + va_start(args, format); + + WriteTime(fd); + vfprintf(fd, format, args); + fprintf(fd, "\n"); + + fclose(fd); + + va_end(args); + } +} \ No newline at end of file diff --git a/xpcPlugin/Log.h b/xpcPlugin/Log.h new file mode 100644 index 0000000..a7c941e --- /dev/null +++ b/xpcPlugin/Log.h @@ -0,0 +1,59 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. +#ifndef XPC_LOG_H +#define XPC_LOG_H +#include + +// LOG_VERBOSITY determines the level of logging throughout the plugin. +// 0: Minimum logging. Only plugin manager events will be logged. +// 1: Critical errors. When an error that prevents correct operation of the +// plugin, attempt to write useful information to the log. Note that since +// XPC runs inside the X-Plane executable, we try very hard no to crash. +// As a result, these log messages may be the only indication of failure. +// 2: All errors. Any time something unexpected happens, log it. +// 3: Significant actions. Any time something happens outside of normal +// command processing, log it. +// 5: Everything. Log nearly every single action the plugin takes. This may +// have a detrimental impact on X-Plane performance. +#define LOG_VERBOSITY 2 + +namespace XPC +{ + /// Handles logging for the plugin. + /// + /// \details Provides functions to write lines to the XPC log file. + /// \author Jason Watkins + /// \version 1.0 + /// \since 1.0 + /// \date Intial Version: 2015-04-09 + /// \date Last Updated: 2015-04-09 + class Log + { + public: + /// Initializes the logging component by deleting old log files, + /// writing header information to the log file. + static void Initialize(std::string header); + + /// Writes the C string pointed to by format, followed by a line + /// terminator to the XPC log file. If format contains format + /// specifiers, additional arguments following format will be formatted + /// and inserted in the resulting string, replacing their respective + /// specifiers. + /// + /// \param format The format string appropriate for consumption by sprintf. + static void FormatLine(const char* format, ...); + + /// Writes the specified string value, followed by a line terminator + /// to the XPC log file. + /// + /// \param value The value to write. + static void WriteLine(const std::string& value); + + /// Writes the specified C string value, followed by a line terminator + /// to the XPC log file. + /// + /// \param value The value to write. + static void WriteLine(const char* value); + }; +} +#endif diff --git a/xpcPlugin/Message.cpp b/xpcPlugin/Message.cpp new file mode 100644 index 0000000..0fb081a --- /dev/null +++ b/xpcPlugin/Message.cpp @@ -0,0 +1,184 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. +#include "Message.h" +#include "Log.h" + +#include +#include +#include + +namespace XPC +{ + Message::Message() {} + + Message Message::ReadFrom(UDPSocket& sock) + { + Message m; + int len = sock.Read(m.buffer, bufferSize, &m.source); + m.size = len < 0 ? 0 : len; + return m; + } + + unsigned long Message::GetMagicNumber() + { + if (size < 4) + { + return 0; + } + return *((unsigned long*)buffer); + } + + std::string Message::GetHead() + { + if (size < 4) + { + return ""; + } + return std::string((char*)buffer, 4); + } + + const unsigned char* Message::GetBuffer() + { + if (size == 0) + { + return NULL; + } + return buffer; + } + + std::size_t Message::GetSize() + { + return size; + } + + struct sockaddr Message::GetSource() + { + return source; + } + + void Message::PrintToLog() + { +#if LOG_VERBOSITY > 4 + std::stringstream ss; + ss << "[DEBUG]"; + + // Dump raw bytes to string + ss << std::hex << std::setfill('0'); + for (int i = 0; i < size; ++i) + { + ss << ' ' << std::setw(2) << static_cast(buffer[i]); + } + Log::WriteLine(ss.str()); + + ss << std::dec; + ss.str(""); + ss << "[" << GetHead() << "-DEBUG] (" << GetSize() << ")"; + switch (GetMagicNumber()) // Binary version of head + { + case 0x4E4EF443: // CONN + case 0x54505957: // WYPT + case 0x54584554: // TEXT + { + Log::WriteLine(ss.str()); + break; + } + case 0x4C525443: // CTRL + { + // Parse message data + float pitch = *((float*)(buffer + 5)); + float roll = *((float*)(buffer + 9)); + float yaw = *((float*)(buffer + 13)); + float thr = *((float*)(buffer + 17)); + char gear = buffer[21]; + float flaps = *((float*)(buffer + 22)); + unsigned char aircraft = 0; + if (size == 27) + { + aircraft = buffer[26]; + } + ss << " Attitude:(" << pitch << " " << roll << " " << yaw << ")"; + ss << " Thr:" << thr << " Gear:" << (int)gear << " Flaps:" << flaps; + Log::WriteLine(ss.str()); + break; + } + case 0x41544144: // DATA + { + std::size_t numCols = (size - 5) / 36; + float values[32][9]; + for (int i = 0; i < numCols; ++i) + { + values[i][0] = buffer[5 + 36 * i]; + memcpy(values[i] + 1, buffer + 9 + 36 * i, 9 * sizeof(float)); + } + ss << " (" << numCols << " lines)"; + Log::WriteLine(ss.str()); + for (int i = 0; i < numCols; ++i) + { + ss.str(""); + ss << "\t#" << values[i][0]; + for (int j = 1; j < 9; ++j) + { + ss << " " << values[i][j]; + } + Log::WriteLine(ss.str()); + } + break; + } + case 0x46455244: // DREF + { + Log::WriteLine(ss.str()); + std::string dref((char*)buffer + 6, buffer[5]); + Log::FormatLine("-\tDREF (size %i) = %s", dref.length(), dref.c_str()); + ss.str(""); + int values = buffer[6 + buffer[5]]; + ss << "\tValues(size " << values << ") ="; + for (int i = 0; i < values; ++i) + { + ss << " " << *((float*)(buffer + values + 1 + sizeof(float) * i)); + } + Log::WriteLine(ss.str()); + break; + } + case 0x44544547: // GETD + { + Log::WriteLine(ss.str()); + int cur = 6; + for (int i = 0; i < buffer[5]; ++i) + { + std::string dref((char*)buffer + cur + 1, buffer[cur]); + Log::FormatLine("\t#%i/%i (size:%i) %s", i + 1, buffer[5], dref.length(), dref.c_str()); + cur += 1 + buffer[cur]; + } + break; + } + case 0x49534F50: // POSI + { + char aircraft = buffer[5]; + float gear = *((float*)(buffer + 30)); + float pos[3]; + float orient[3]; + memcpy(pos, buffer + 6, 12); + memcpy(orient, buffer + 18, 12); + ss << " AC:" << (int)aircraft; + ss << " Pos:(" << pos[0] << ' ' << pos[1] << ' ' << pos[2] << ") Orient:("; + ss << orient[3] << ' ' << orient[4] << ' ' << orient[5] << ") Gear:"; + ss << gear; + Log::WriteLine(ss.str()); + break; + } + case 0x554D4953: // SIMU + { + ss << ' ' << (int)buffer[5]; + Log::WriteLine(ss.str()); + break; + } + default: + { + ss << " UNKNOWN HEADER "; + Log::WriteLine(ss.str()); + break; + } + } +#endif + } +} \ No newline at end of file diff --git a/xpcPlugin/Message.h b/xpcPlugin/Message.h new file mode 100644 index 0000000..3962dc8 --- /dev/null +++ b/xpcPlugin/Message.h @@ -0,0 +1,57 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. +#ifndef XPC_MESSAGE_H +#define XPC_MESSAGE_H + +#include "UDPSocket.h" + +namespace XPC +{ + /// Represents a message received from an XPC client. + /// + /// \author Jason Watkins + /// \version 1.0 + /// \since 1.0 + /// \date Intial Version: 2015-04-11 + /// \date Last Updated: 2015-04-11 + class Message + { + public: + /// Reads a datagram from the specified socket and interprets it as a + /// message. + /// + /// \param sock The socket to read from. + /// \returns A message parsed from the data read from sock. If no + /// data was read or an error occurs, returns a message + /// with the size set to 0. + static Message ReadFrom(UDPSocket& sock); + + /// Gets the message header in binary form. + unsigned long GetMagicNumber(); + + /// Gets the message header. + std::string GetHead(); + + /// Gets the buffer underlying the message. + const unsigned char* GetBuffer(); + + /// Gets the size of the message in bytes. + std::size_t GetSize(); + + /// Gets the address this message was read from. + struct sockaddr GetSource(); + + /// Prints the contents of the message to the XPC log. + void PrintToLog(); + + private: + Message(); + + static const std::size_t bufferSize = 4096; + unsigned char buffer[bufferSize]; + std::size_t size; + struct sockaddr source; + }; +} + +#endif \ No newline at end of file diff --git a/xpcPlugin/MessageHandlers.cpp b/xpcPlugin/MessageHandlers.cpp new file mode 100644 index 0000000..784ebee --- /dev/null +++ b/xpcPlugin/MessageHandlers.cpp @@ -0,0 +1,622 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. +#include "MessageHandlers.h" +#include "DataManager.h" +#include "DataMaps.h" +#include "Drawing.h" +#include "Log.h" + +#include +#include + +namespace XPC +{ + std::map MessageHandlers::connections; + std::map MessageHandlers::handlers; + + std::string MessageHandlers::connectionKey; + MessageHandlers::ConnectionInfo MessageHandlers::connection; + UDPSocket* MessageHandlers::sock; + + void MessageHandlers::SetSocket(UDPSocket* socket) + { + MessageHandlers::sock = socket; + } + + void MessageHandlers::HandleMessage(Message& msg) + { + if (handlers.size() == 0) + { + // Common messages + handlers.insert(std::make_pair("CONN", MessageHandlers::HandleConn)); + handlers.insert(std::make_pair("CTRL", MessageHandlers::HandleCtrl)); + handlers.insert(std::make_pair("DATA", MessageHandlers::HandleData)); + handlers.insert(std::make_pair("DREF", MessageHandlers::HandleDref)); + handlers.insert(std::make_pair("GETD", MessageHandlers::HandleGetD)); + handlers.insert(std::make_pair("POSI", MessageHandlers::HandlePosi)); + handlers.insert(std::make_pair("SIMU", MessageHandlers::HandleSimu)); + handlers.insert(std::make_pair("TEXT", MessageHandlers::HandleText)); + handlers.insert(std::make_pair("WYPT", MessageHandlers::HandleWypt)); + // Not implemented messages + handlers.insert(std::make_pair("VIEW", MessageHandlers::HandleUnknown)); + // X-Plane data messages + handlers.insert(std::make_pair("DSEL", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("USEL", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("DCOC", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("UCOC", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("MOUS", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("CHAR", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("MENU", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("SOUN", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("FAIL", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("RECO", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("PAPT", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("VEHN", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("VEH1", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("VEHA", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("GSET", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("OBJN", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("OBJL", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("GSET", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("ISET", MessageHandlers::HandleXPlaneData)); + handlers.insert(std::make_pair("BOAT", MessageHandlers::HandleXPlaneData)); + } + + // Make sure we really have a message to handle. + std::string head = msg.GetHead(); + if (head == "") + { + return; // No Message to handle + } + msg.PrintToLog(); + + // Set current connection + sockaddr sourceaddr = msg.GetSource(); + connectionKey = UDPSocket::GetHost(&sourceaddr); +#if LOG_VERBOSITY > 4 + Log::FormatLine("[MSGH] Handling message from %s", connectionKey.c_str()); +#endif + std::map::iterator conn = connections.find(connectionKey); + if (conn == connections.end()) // New connection + { + connection = MessageHandlers::ConnectionInfo(); + // If this is a new connection, that means we just added an elment + // to connections. As long as we never remove elements, the size of + // connections will serve as a unique id. + connection.id = static_cast(connections.size()); + connection.addr = sourceaddr; + connection.getdCount = 0; + connections[connectionKey] = connection; +#if LOG_VERBOSITY > 2 + Log::FormatLine("[MSGH] New connection. ID=%u, Remote=%s", connection.id, connectionKey.c_str()); +#endif + } + else + { + connection = (*conn).second; +#if LOG_VERBOSITY > 3 + Log::FormatLine("[MSGH] Existing connection. ID=%u, Remote=%s", + connection.id, connectionKey.c_str()); +#endif + } + + // Check if there is a handler for this message type. If so, execute + // that handler. Otherwise, execute the unknown message handler. + std::map::iterator iter = handlers.find(head); + if (iter != handlers.end()) + { + MessageHandler handler = (*iter).second; + handler(msg); + } + else + { + MessageHandlers::HandleUnknown(msg); + } + } + + void MessageHandlers::HandleConn(Message& msg) + { + const unsigned char* buffer = msg.GetBuffer(); + + // Store new port + unsigned short port = *((unsigned short*)(buffer + 5)); + sockaddr* sa = &connection.addr; + switch (sa->sa_family) + { + case AF_INET: + { + sockaddr_in* sin = reinterpret_cast(sa); + (*sin).sin_port = htons(port); + break; + } + case AF_INET6: + { + sockaddr_in6* sin = reinterpret_cast(sa); + (*sin).sin6_port = htons(port); + break; + } + default: +#if LOG_VERBOSITY > 0 + Log::WriteLine("[CONN] ERROR: Unknown address type."); + return; +#endif + } + connections.erase(connectionKey); + connectionKey = UDPSocket::GetHost(&connection.addr); + connections[connectionKey] = connection; + + // Create response + unsigned char response[6] = "CONF"; + response[5] = connection.id; + + // Update log +#if LOG_VERBOSITY > 1 + Log::FormatLine("[CONN] ID: %u New destination port: %u", + connection.id, port); +#endif + + // Send response + sock->SendTo(response, 6, &connection.addr); + } + + void MessageHandlers::HandleCtrl(Message& msg) + { + // Update Log +#if LOG_VERBOSITY > 2 + Log::FormatLine("[CTRL] Message Received (Conn %i)", connection.id); +#endif + + const unsigned char* buffer = msg.GetBuffer(); + std::size_t size = msg.GetSize(); + //Legacy packets that don't specify an aircraft number should be 26 bytes long. + //Packets specifying an A/C num should be 27 bytes. + if (size != 26 && size != 27) + { +#if LOG_VERBOSITY > 0 + Log::FormatLine("[CTRL] ERROR: Unexpected message length (%i)", size); +#endif + return; + } + + // Parse message data + float pitch = *((float*)(buffer + 5)); + float roll = *((float*)(buffer + 9)); + float yaw = *((float*)(buffer + 13)); + float thr = *((float*)(buffer + 17)); + char gear = buffer[21]; + float flaps = *((float*)(buffer + 22)); + unsigned char aircraft = 0; + if (size == 27) + { + aircraft = buffer[26]; + } + + float thrArray[8]; + for (int i = 0; i < 8; ++i) + { + thrArray[i] = thr; + } + + DataManager::Set(DREF_YokePitch, pitch, aircraft); + DataManager::Set(DREF_YokeRoll, roll, aircraft); + DataManager::Set(DREF_YokeHeading, yaw, aircraft); + DataManager::Set(DREF_ThrottleSet, thrArray, 8, aircraft); + DataManager::Set(DREF_ThrottleActual, thrArray, 8, aircraft); + if (aircraft == 0) + { + DataManager::Set("sim/flightmodel/engine/ENGN_thro_override", thrArray, 1); + } + if (gear != -1) + { + DataManager::SetGear(gear, false, aircraft); + } + if (flaps < -999.5 || flaps > -997.5) + { + DataManager::Set(DREF_FlapSetting, flaps, aircraft); + } + } + + void MessageHandlers::HandleData(Message& msg) + { + // Parse data + const unsigned char* buffer = msg.GetBuffer(); + std::size_t size = msg.GetSize(); + std::size_t numCols = (size - 5) / 36; + if (numCols > 0) + { +#if LOG_VERBOSITY > 1 + Log::FormatLine("[DATA] Message Received (Conn %i)", connection.id); +#endif + } + else + { +#if LOG_VERBOSITY > 0 + Log::FormatLine("[DATA] WARNING: Empty data packet received (Conn %i)", connection.id); +#endif + return; + } + + if (numCols > 134) // Error. Will overflow values + { +#if LOG_VERBOSITY > 0 + Log::FormatLine("[DATA] ERROR: numCols to large."); +#endif + return; + } + float values[134][9]; + for (int i = 0; i < numCols; ++i) + { + values[i][0] = buffer[5 + 36 * i]; + memcpy(values[i] + 1, buffer + 9 + 36 * i, 9 * sizeof(float)); + } + + // Update log + + float savedAlpha = -998; + float savedHPath = -998; + for (int i = 0; i < numCols; ++i) + { + unsigned char dataRef = (unsigned char)values[i][0]; + if (dataRef >= 134) + { +#if LOG_VERBOSITY > 0 + Log::FormatLine("[DATA] ERROR: DataRef # must be between 0 - 134 (Received: %hi)", (int)dataRef); +#endif + continue; + } + + switch (dataRef) + { + case 3: // Velocity + { + float theta = DataManager::GetFloat(DREF_Pitch); + float alpha = savedAlpha != -998 ? savedAlpha : DataManager::GetFloat(DREF_AngleOfAttack); + float hpath = savedHPath != -998 ? savedHPath : DataManager::GetFloat(DREF_HPath); + if (alpha != alpha || hpath != hpath) + { +#if LOG_VERBOSITY > 0 + Log::WriteLine("[DATA] ERROR: Value must be a number (NaN received)"); +#endif + break; + } + const float deg2rad = 0.0174532925F; + int ind[3] = { 1, 3, 4 }; + for (int j = 0; j < 3; ++j) + { + float v = values[i][ind[j]]; + if (v != -998) + { + DataManager::Set(DREF_LocalVX, v*cos((theta - alpha)*deg2rad)*sin(hpath*deg2rad)); + DataManager::Set(DREF_LocalVY, v*sin((theta - alpha)*deg2rad)); + DataManager::Set(DREF_LocalVZ, -v*cos((theta - alpha)*deg2rad)*cos(hpath*deg2rad)); + } + } + break; + } + case 17: // Orientation + { + float orient[3]; + orient[0] = values[i][1]; + orient[1] = values[i][2]; + orient[2] = values[i][3]; + DataManager::SetOrientation(orient); + break; + } + case 18: // Alpha, hpath etc. + { + if (values[i][1] != values[i][1] || values[i][3] != values[i][3]) + { +#if LOG_VERBOSITY > 0 + Log::WriteLine("[DATA] ERROR: Value must be a number (NaN received)"); +#endif + break; + } + if (values[i][1] != -998) + { + savedAlpha = values[i][1]; + } + if (values[i][3] != -998) + { + savedHPath = values[i][3]; + } + break; + } + case 20: // Position + { + float pos[3]; + pos[0] = values[i][2]; + pos[1] = values[i][3]; + pos[2] = values[i][4]; + DataManager::SetPosition(pos); + break; + } + case 25: // Throttle + { + if (values[i][1] != values[i][1]) + { +#if LOG_VERBOSITY > 0 + Log::WriteLine("[DATA] ERROR: Value must be a number (NaN received)"); +#endif + break; + } + float thr[8]; + for (int j = 0; j < 8; ++j) + { + thr[j] = values[i][1]; + } + DataManager::Set(DREF_ThrottleSet, thr, 8); + break; + } + default: // Non-Special dataRefs + { + float line[8]; + memcpy(line, values[i] + 1, 8 * sizeof(float)); + for (int j = 0; j < 8; ++j) + { +#if LOG_VERBOSITY > 1 + Log::FormatLine("[DATA] Setting Dataref %i.%i to %f", dataRef, j, line[j]); +#endif + + if (dataRef == 14 && j == 0) + { + DataManager::SetGear(line[0], true); + continue; + } + + DREF dref = XPData[dataRef][j]; + if (dref == DREF_None) + { + // TODO: Send single line instead! + HandleXPlaneData(msg); + } + else + { + DataManager::Set(dref, line, 8); + } + } + } + } + } + } + + void MessageHandlers::HandleDref(Message& msg) + { + const unsigned char* buffer = msg.GetBuffer(); + unsigned char len = buffer[5]; + std::string dref = std::string((char*)buffer + 6, len); + + unsigned char valueCount = buffer[6 + len]; + float* values = (float*)(buffer + 7 + len); + +#if LOG_VERBOSITY > 1 + Log::FormatLine("[DREF] Request to set DREF value received (Conn %i): %s", connection.id, dref.c_str()); +#endif + + DataManager::Set(dref, values, valueCount); + } + + void MessageHandlers::HandleGetD(Message& msg) + { + const unsigned char* buffer = msg.GetBuffer(); + unsigned char drefCount = buffer[5]; + if (drefCount == 0) // Use last request + { +#if LOG_VERBOSITY > 0 + Log::FormatLine("[GETD] DATA Requested: Repeat last request from connection %i (%i data refs)", + connection.id, connection.getdCount); +#endif + if (connection.getdCount == 0) // No previous request to use + { +#if LOG_VERBOSITY > 1 + Log::FormatLine("[GETD] ERROR: No previous requests from connection %i.", connection.id); +#endif + return; + } + } + else // New request + { +#if LOG_VERBOSITY > 0 + Log::FormatLine("[GETD] DATA Requested: New Request for connection %i (%i data refs)", + connection.id, drefCount); +#endif + std::size_t ptr = 6; + for (int i = 0; i < drefCount; ++i) + { + unsigned char len = buffer[ptr]; + connection.getdRequest[i] = std::string((char*)buffer + 1 + ptr, len); + ptr += 1 + len; + } + connection.getdCount = drefCount; + connections[connectionKey] = connection; + } + + unsigned char response[4096] = "RESP"; + response[5] = drefCount; + std::size_t cur = 6; + for (int i = 0; i < drefCount; ++i) + { + float values[255]; + int count = DataManager::Get(connection.getdRequest[i], values, 255); + response[cur++] = count; + memcpy(response + cur, values, count * sizeof(float)); + cur += count * sizeof(float); + } + + sock->SendTo(response, cur, &connection.addr); + } + + void MessageHandlers::HandlePosi(Message& msg) + { + // Update log +#if LOG_VERBOSITY > 0 + Log::FormatLine("[POSI] Message Received (Conn %i)", connection.id); +#endif + + const unsigned char* buffer = msg.GetBuffer(); + const std::size_t size = msg.GetSize(); + if (size < 34) + { +#if LOG_VERBOSITY > 1 + Log::FormatLine("[POSI] ERROR: Unexpected size: %i (Expected at least 34)", size); +#endif + return; + } + + char aircraft = buffer[5]; + float gear = *((float*)(buffer + 30)); + float pos[3]; + float orient[3]; + memcpy(pos, buffer + 6, 12); + memcpy(orient, buffer + 18, 12); + + if (aircraft > 0) + { + // Enable AI for the aircraft we are setting + float ai[20]; + std::size_t result = DataManager::GetFloatArray(DREF_PauseAI, ai, 20); + if (result == 20) // Only set values if they were retrieved successfully. + { + ai[aircraft] = 1; + DataManager::Set(DREF_PauseAI, ai, 0, 20); + } + } + + DataManager::SetPosition(pos, aircraft); + DataManager::SetOrientation(orient, aircraft); + if (gear != -1) + { + DataManager::SetGear(gear, true, aircraft); + } + } + + void MessageHandlers::HandleSimu(Message& msg) + { + // Update log +#if LOG_VERBOSITY > 0 + Log::FormatLine("[SIMU] Message Received (Conn %i)", connection.id); +#endif + + const unsigned char* buffer = msg.GetBuffer(); + + // Set DREF + int value[20]; + for (int i = 0; i < 20; ++i) + { + value[i] = buffer[5]; + } + DataManager::Set(DREF_Pause, value, 20); + +#if LOG_VERBOSITY > 2 + if (buffer[5] == 0) + { + Log::FormatLine("[SIMU] Simulation Resumed (Conn %i)", connection.id); + } + else + { + Log::FormatLine("[SIMU] Simulation Paused (Conn %i)", connection.id); + } +#endif + } + + void MessageHandlers::HandleText(Message& msg) + { + // Update Log +#if LOG_VERBOSITY > 0 + Log::FormatLine("[TEXT] Message Received (Conn %i)", connection.id); +#endif + + std::size_t len = msg.GetSize(); + const unsigned char* buffer = msg.GetBuffer(); + + char text[256] = { 0 }; + if (len < 14) + { +#if LOG_VERBOSITY > 1 + Log::WriteLine("[TEXT] ERROR: Length less than 14 bytes"); +#endif + return; + } + size_t msgLen = (unsigned char)buffer[13]; + if (msgLen == 0) + { + Drawing::ClearMessage(); +#if LOG_VERBOSITY > 2 + Log::WriteLine("[TEXT] Text cleared"); +#endif + } + else + { + int x = *((int*)(buffer + 5)); + int y = *((int*)(buffer + 9)); + strncpy(text, (char*)buffer + 14, msgLen); + Drawing::SetMessage(x, y, text); +#if LOG_VERBOSITY > 2 + Log::WriteLine("[TEXT] Text set"); +#endif + } + } + + void MessageHandlers::HandleWypt(Message& msg) + { + // Update Log +#if LOG_VERBOSITY > 0 + Log::FormatLine("[WYPT] Message Received (Conn %i)", connection.id); +#endif + + // Parse data + const unsigned char* buffer = msg.GetBuffer(); + unsigned char op = buffer[5]; + unsigned char count = buffer[6]; + Waypoint points[255]; + const unsigned char* ptr = buffer + 7; + for (size_t i = 0; i < count; ++i) + { + points[i].latitude = *((float*)ptr); + points[i].longitude = *((float*)(ptr + 4)); + points[i].altitude = *((float*)(ptr + 8)); + ptr += 12; + } + + // Perform operation +#if LOG_VERBOSITY > 2 + Log::FormatLine("[WYPT] Performing operation %i", op); +#endif + switch (op) + { + case 1: + Drawing::AddWaypoints(points, count); + break; + case 2: + Drawing::RemoveWaypoints(points, count); + break; + case 3: + Drawing::ClearWaypoints(); + break; + default: +#if LOG_VERBOSITY > 1 + Log::FormatLine("[WYPT] ERROR: %i is not a valid operation.", op); +#endif + break; + } + } + + void MessageHandlers::HandleXPlaneData(Message& msg) + { +#if LOG_VERBOSITY > 1 + Log::WriteLine("[MSGH] Sending raw data to X-Plane"); +#endif + sockaddr_in loopback; + loopback.sin_family = AF_INET; + loopback.sin_addr.s_addr = htonl(INADDR_LOOPBACK); + loopback.sin_port = htons(49000); + sock->SendTo(msg.GetBuffer(), msg.GetSize(), (sockaddr*)&loopback); + } + + void MessageHandlers::HandleUnknown(Message& msg) + { + // UPDATE LOG +#if LOG_VERBOSITY > 0 + Log::FormatLine("[EXEC] ERROR: Unknown packet type %s", msg.GetHead().c_str()); +#endif + } +} diff --git a/xpcPlugin/MessageHandlers.h b/xpcPlugin/MessageHandlers.h new file mode 100644 index 0000000..4881dee --- /dev/null +++ b/xpcPlugin/MessageHandlers.h @@ -0,0 +1,68 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. +#ifndef XPC_MESSAGEHANDLERS_H +#define XPC_MESSAGEHANDLERS_H +#include "Message.h" + +#include +#include + +namespace XPC +{ + /// A function that handles a message. + typedef void(*MessageHandler)(Message&); + + /// Handles incommming messages and manages connections. + /// + /// \author Jason Watkins + /// \version 1.0 + /// \since 1.0 + /// \date Intial Version: 2015-04-12 + /// \date Last Updated: 2015-04-12 + class MessageHandlers + { + public: + /// The first stop for all messages to the plugin after they are read from the + /// socket. + /// + /// \details After a message is read, HandleMessage analyzes the sender's network address + /// to determine whether the sender is a new client. It then either loads + /// connection details for an existing client, or creates a new connection record + /// for new clients. Finally, the message handler checks the message type and + /// dispatches the message to the appropriate handler. + /// \param msg The message to be processed. + static void HandleMessage(Message& msg); + + /// Sets the socke that message handlers use to send responses. + static void SetSocket(UDPSocket* socket); + + private: + static void HandleConn(Message& msg); + static void HandleCtrl(Message& msg); + static void HandleData(Message& msg); + static void HandleDref(Message& msg); + static void HandleGetD(Message& msg); + static void HandlePosi(Message& msg); + static void HandleSimu(Message& msg); + static void HandleText(Message& msg); + static void HandleWypt(Message& msg); + static void HandleXPlaneData(Message& msg); + static void HandleUnknown(Message& msg); + + typedef struct + { + unsigned char id; + sockaddr addr; + unsigned char getdCount; + std::string getdRequest[255]; + } ConnectionInfo; + + static std::map connections; + static std::map handlers; + static std::string connectionKey; // The current connection ip:port string + static ConnectionInfo connection; // The current connection record + static UDPSocket* sock; // Outgoing network socket + }; +} + +#endif \ No newline at end of file diff --git a/xpcPlugin/UDPSocket.cpp b/xpcPlugin/UDPSocket.cpp new file mode 100644 index 0000000..ed4710d --- /dev/null +++ b/xpcPlugin/UDPSocket.cpp @@ -0,0 +1,184 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. +#include "Log.h" +#include "UDPSocket.h" + +#include +#include + +namespace XPC +{ + UDPSocket::UDPSocket(unsigned short recvPort) + { +#if LOG_VERBOSITY > 1 + Log::FormatLine("[SOCK] Opening socket (port:%d)", recvPort); +#endif + // Setup Port + struct sockaddr_in localAddr; + localAddr.sin_family = AF_INET; + localAddr.sin_addr.s_addr = INADDR_ANY; + localAddr.sin_port = htons(recvPort); + + //Create and bind the socket +#ifdef _WIN32 + WSADATA wsa; + int startResult = WSAStartup(MAKEWORD(2, 2), &wsa); + if (startResult != 0) + { +#if LOG_VERBOSITY > 0 + Log::FormatLine("[SOCK] ERROR: WSAStartup failed with error code %i.", startResult); +#endif + this->sock = ~0; + return; + } + if ((this->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == INVALID_SOCKET) + { +#if LOG_VERBOSITY > 0 + int err = WSAGetLastError(); + Log::FormatLine("[SOCK] ERROR: Failed to open socket. (Error code %i)", err); +#endif + return; + } +#elif (__APPLE__ || __linux) + if ((this->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) + { + Log::WriteLine("[SOCK] ERROR: Failed to open socket"); + return; + } + int optval = 1; + setsockopt(this->sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); + setsockopt(this->sock, SOL_SOCKET, SO_REUSEPORT, &optval, sizeof(optval)); +#endif + if (bind(this->sock, (struct sockaddr*)&localAddr, sizeof(localAddr)) != 0) + { +#ifdef _WIN32 +#if LOG_VERBOSITY > 0 + int err = WSAGetLastError(); + Log::FormatLine("[SOCK] ERROR: Failed to bind socket. (Error code %i)", err); +#endif +#endif + return; + } + + //Set Timout + int usTimeOut = 500; + +#ifdef _WIN32 + DWORD msTimeOutWin = 1; // Minimum socket timeout in Windows is 1ms + if(setsockopt(this->sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&msTimeOutWin, sizeof(msTimeOutWin)) != 0) + { +#if LOG_VERBOSITY > 1 + int err = WSAGetLastError(); + Log::FormatLine("[SOCK] ERROR: Failed to set timeout. (Error code %i)", err); +#endif + } +#else + struct timeval tv; + tv.tv_sec = 0; /* Sec Timeout */ + tv.tv_usec = usTimeOut; // Microsec Timeout + setsockopt(this->sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(struct timeval)); +#endif + } + + UDPSocket::~UDPSocket() + { +#if LOG_VERBOSITY > 1 + Log::FormatLine("[SOCK] Closing socket (%d)", this->sock); +#endif +#ifdef _WIN32 + closesocket(this->sock); +#elif (__APPLE__ || __linux) + close(this->sock); +#endif + } + + int UDPSocket::Read(unsigned char* dst, int maxLen, sockaddr* recvAddr) + { + socklen_t recvaddrlen = sizeof(*recvAddr); + int status = 0; + +#ifdef _WIN32 + // Windows readUDP needs the select command- minimum timeout is 1ms. + // Without this playback becomes choppy + + // Definitions + FD_SET stReadFDS; + FD_SET stExceptFDS; + timeval tv; + + // Setup for Select + FD_ZERO(&stReadFDS); + FD_SET(sock, &stReadFDS); + FD_ZERO(&stExceptFDS); + FD_SET(sock, &stExceptFDS); + tv.tv_sec = 0; /* Sec Timeout */ + tv.tv_usec = 250; // Microsec Timeout + + // Select Command + int result = select(-1, &stReadFDS, (FD_SET *)0, &stExceptFDS, &tv); +#if LOG_VERBOSITY > 1 + if (result == SOCKET_ERROR) + { + int err = WSAGetLastError(); + Log::FormatLine("[SOCK] ERROR: Select failed. (Error code %i)", err); + } +#endif + if (result <= 0) // No Data or error + { + return -1; + } + + // If no error: Read Data + status = recvfrom(sock, (char*)dst, maxLen, 0, recvAddr, &recvaddrlen); +#else + // For apple or linux-just read - will timeout in 0.5 ms + status = (int)recvfrom(sock, dst, 5000, 0, recvAddr, &recvaddrlen); +#endif + return status; + } + + void UDPSocket::SendTo(const unsigned char* buffer, std::size_t len, sockaddr* remote) + { + if (sendto(sock, (char*)buffer, (int)len, 0, remote, sizeof(*remote)) < 0) + { +#if LOG_VERBOSITY > 0 + Log::FormatLine("[SOCK] Send failed. (remote: %s)", GetHost(remote).c_str()); +#endif + } + else + { +#if LOG_VERBOSITY > 3 + Log::FormatLine("[SOCK] Datagram sent. (remote: %s)", GetHost(remote).c_str()); +#endif + } + } + + std::string UDPSocket::GetHost(sockaddr* sa) + { + char ip[INET6_ADDRSTRLEN + 6] = { 0 }; + switch (sa->sa_family) + { + case AF_INET: + { + sockaddr_in* sin = reinterpret_cast(sa); + inet_ntop(AF_INET, &sin->sin_addr, ip, INET6_ADDRSTRLEN); + int len = strnlen(ip, INET6_ADDRSTRLEN); + ip[len++] = ':'; + std::sprintf(ip + len, "%u", ntohs((*sin).sin_port)); + break; + } + case AF_INET6: + { + sockaddr_in6* sin = reinterpret_cast(sa); + inet_ntop(AF_INET6, &sin->sin6_addr, ip, INET6_ADDRSTRLEN); + int len = strnlen(ip, INET6_ADDRSTRLEN); + ip[len++] = ':'; + std::sprintf(ip + len, "%u", ntohs((*sin).sin6_port)); + break; + } + default: + return "UNKNOWN"; + } + return std::string(ip); + } +} diff --git a/xpcPlugin/UDPSocket.h b/xpcPlugin/UDPSocket.h new file mode 100644 index 0000000..b6e8e58 --- /dev/null +++ b/xpcPlugin/UDPSocket.h @@ -0,0 +1,74 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. +#ifndef XPC_SOCKET_H +#define XPC_SOCKET_H + +#include +#include +#ifdef _WIN32 +#include +#include +#pragma comment(lib,"ws2_32.lib") //Winsock Library +#elif (__APPLE__ || __linux) +#include +#include +#include +#include +#endif + + +namespace XPC +{ + /// Represents a UDP datagram socket used for reading data from and sending + /// data to XPC clients. + /// + /// \author Jason Watkins + /// \version 1.0 + /// \since 1.0 + /// \date Intial Version: 2015-04-10 + /// \date Last Updated: 2015-04-11 + class UDPSocket + { + public: + /// Initializes a new instance of the XPCSocket class bound to the + /// specified receive port. + /// + /// \param recvPort The port on which this instance will receive data. + UDPSocket(unsigned short recvPort); + + /// Closes the underlying socket for this instance. + ~UDPSocket(); + + /// Reads the specified number of bytes into the data buffer and stores + /// the remote endpoint. + /// + /// \param buffer The array to copy the data into. + /// \param size The number of bytes to read. + /// \param remoteAddr When at least one byte is read, contains the address + /// of the remote host. + /// \returns The number of bytes read, or a negative number if + /// an error occurs. + int Read(unsigned char* buffer, int size, sockaddr* remoteAddr); + + /// Sends data to the specified remote endpoint. + /// + /// \param data The data to be sent. + /// \param len The number of bytes to send. + /// \param remote The destination socket. + void SendTo(const unsigned char* buffer, std::size_t len, sockaddr* remote); + + /// Gets a string containing the IP address and port contained in the given sockaddr. + /// + /// \param addr The socket address to parse. + /// \returns A string representation of the socket address. + static std::string GetHost(sockaddr* addr); + private: +#ifdef _WIN32 + SOCKET sock; +#else + int sock; +#endif + }; +} + +#endif \ No newline at end of file diff --git a/xpcPlugin/XPCPlugin.cpp b/xpcPlugin/XPCPlugin.cpp index bc8dd29..3f00db3 100755 --- a/xpcPlugin/XPCPlugin.cpp +++ b/xpcPlugin/XPCPlugin.cpp @@ -1,158 +1,99 @@ +//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the +//National Aeronautics and Space Administration. All Rights Reserved. // -// XPCPlugin Beta +//DISCLAIMERS +// No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, +// EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT +// THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY +// THAT THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, +// WILL CONFORM TO THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN +// ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, +// HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS RESULTING FROM USE OF THE SUBJECT +// SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING +// THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS." +// +// Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST THE UNITED STATES +// GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF +// RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES +// OR LOSSES ARISING FROM SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING +// FROM, RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS THE +// UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, +// TO THE EXTENT PERMITTED BY LAW. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE +// IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT. +// +//X-Plane API +//Copyright(c) 2008, Sandy Barbour and Ben Supnik All rights reserved. +//Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +//associated documentation files(the "Software"), to deal in the Software without restriction, +//including without limitation the rights to use, copy, modify, merge, publish, distribute, +//sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is +//furnished to do so, subject to the following conditions : +// * Redistributions of source code must retain the above copyright notice, +// this list of conditions and the following disclaimer. +// * Neither the names of the authors nor that of X - Plane or Laminar Research +// may be used to endorse or promote products derived from this software +// without specific prior written permission from the authors or +// Laminar Research, respectively. + + +// X-Plane Connect Plugin // // DESCRIPTION // XPCPlugin Facilitates Communication to and from the XPlane // -// REQUIREMENTS -// 1. X-Plane Version 9.0 or newer (untested on previous versions) -// 2. XPCPlugin.xpl-must be placed in [X-Plane Directory]/Resources/plugins -// 3. OS X 10.8 or newer (untested on previous versions/Windows) -// // INSTRUCTIONS -// 1. Move xpcPlugin.xpl into [X-Plane Directory]/Resources/plugins -// -// COMMAND TYPES -// DATA: Works like UDP Commands -// SIMU: Pauses/Unpauses Simulation -// CONN: Set Returned Port Number -// DREF: Sets value to specific DREF (see http://www.xsquawkbox.net/xpsdk/docs/DataRefs.html) -// GETD: Requests specific DREF -// POSI: Set Position -// CTRL: Set Control Variables -// WYPT: Add/Edit a Waypoint (PLANNED) -// VIEW: Set Simulation View (PLANNED) -// TEXT: Add Text to Screen (PLANNED) -// -// NOTICES: -// Copyright ã 2013-2014 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. -// -// DISCLAIMERS -// No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS RESULTING FROM USE OF THE SUBJECT SOFTWARE. FURTHER, GOVERNMENT AGENCY DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE, IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS." -// -// Waiver and Indemnity: RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS AGAINST THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT. IF RECIPIENT'S USE OF THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, EXPENSES OR LOSSES ARISING FROM SUCH USE, INCLUDING ANY DAMAGES FROM PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE OF THE SUBJECT SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT, TO THE EXTENT PERMITTED BY LAW. RECIPIENT'S SOLE REMEDY FOR ANY SUCH MATTER SHALL BE THE IMMEDIATE, UNILATERAL TERMINATION OF THIS AGREEMENT. -// -// X-Plane API -// Copyright (c) 2008, Sandy Barbour and Ben Supnik All rights reserved. -// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -// * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -// * Neither the names of the authors nor that of X-Plane or Laminar Research may be used to endorse or promote products derived from this software without specific prior written permission from the authors or Laminar Research, respectively. -// -// X-Plane API SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// See Readme.md in the root of this repository or the wiki hosted on GitHub at +// https://github.com/nasa/XPlaneConnect/wiki for requirements, installation instructions, +// and detailed documentation. // // CONTACT // For questions email Christopher Teubert (christopher.a.teubert@nasa.gov) // // CONTRIBUTORS // CT: Christopher Teubert (christopher.a.teubert@nasa.gov) -// -// TO DO -// 1. Handle hitting maxcon -// 2. POSI: Alpha/Beta -// 3. Error Handling -// 4. CTRL: add SpeedBrakes -// 5. SIMU: -1 = switch -// 6. SENDBUF: Add message -// 7. Ability to add text to screen -// 8. Bound checking -// -// BEGIN CODE +// JW: Jason Watkins (jason.w.watkins@nasa.gov) -#define _WINSOCKAPI_ +// XPC Includes +#include "DataManager.h" +#include "Drawing.h" +#include "Log.h" +#include "MessageHandlers.h" +#include "UDPSocket.h" -#include -#include -#include -#include - -//#include "XPLMPlanes.h" +// XPLM Includes #include "XPLMProcessing.h" -#include "XPLMGraphics.h" -#include "xpcDrawing.h" -#include "xpcPluginTools.h" -#ifdef _WIN32 /* WIN32 SYSTEM */ -#include -#elif (__APPLE__) +// System Includes +#include +#ifdef __APPLE__ #include #endif -#define MAXCONN 50 // Maximum number of dedicated connections #define RECVPORT 49009 // Port that the plugin receives commands on -#define SENDPORT 49097 // Port that the plugin sends on #define OPS_PER_CYCLE 20 // Max Number of operations per cycle -static XPLMDataRef XPLMSwitch; // for turning on/off simulation -struct xpcSocket recSocket; -struct xpcSocket sendSocket; +XPC::UDPSocket* sock = NULL; -short number_of_connections = 0; -short current_connection = -1; +double start,lap; +static double timeConvert = 0.0; +int benchmarkingSwitch = 0; // 1 = time for operations, 2 = time for op + cycle; +int cyclesToClear = -1; // Clear message bus every n cycles. -1 == dont clear +int counter = 0; -double start,lap; -static double timeConvert = 0.0; -int benchmarkingSwitch = 0; // 1 = time for operations, 2 = time for op + cycle; -int debugSwitch = 2; -int cyclesToClear = -1; // Clear message bus every n cycles. -1 == dont clear -int counter = 0; - -struct connectionHistory -{ - short connectionID; - - char IP[16]; - unsigned short recPort; - unsigned short fromPort; - short requestLength; - XPLMDataRef XPLMRequestedDRefs[100]; -}; - -connectionHistory connectionList[MAXCONN]; - -PLUGIN_API int XPluginStart(char * outName, char * outSig, char * outDesc); -static float MyFlightLoopCallback(float, float, int inCounter, void * inRefcon); +PLUGIN_API int XPluginStart(char* outName, char* outSig, char* outDesc); PLUGIN_API void XPluginStop(void); PLUGIN_API void XPluginDisable(void); PLUGIN_API int XPluginEnable(void); -PLUGIN_API void XPluginReceiveMessage(XPLMPluginID inFromWho, int inMessage, void * inParam); +PLUGIN_API void XPluginReceiveMessage(XPLMPluginID inFromWho, int inMessage, void* inParam); +static float XPCFlightLoopCallback(float inElapsedSinceLastCall, float inElapsedTimeSinceLastFlightLoop, int inCounter, void* inRefcon); -int handleSIMU(char buf[]); -int handleCONN(char buf[]); -int handlePOSI(char buf[]); -int handleCTRL(char buf[]); -int handleWYPT(char buf[], int len); -int handleGETD(char *buf); -int handleDREF(char *buf); -int handleVIEW(); -int handleDATA(char *buf, int buflen); -int handleTEXT(char *buf, int len); -short handleInput(struct XPCMessage * theMessage); - -char setPOSI(short aircraft, float pos[3]); -char setORIENT(short aircraft, float orient[3]); -char setDREF(XPLMDataRef theDREF, float floatarray[], short arrayStart, short arraySize); -char setGEAR(short aircraft, float gear, char posi); -char setFLAP(float flap); -void sendBUF(char buf[], int buflen); - -PLUGIN_API int XPluginStart( char * outName, - char * outSig, - char * outDesc) +PLUGIN_API int XPluginStart(char* outName, char* outSig, char* outDesc) { - static FILE *logFile; // Log File - strcpy(outName, "xplaneConnect"); - strcpy(outSig, "NASA.xplaneConnect"); - strcpy(outDesc, "X Plane Communications Toolbox"); - - logFile = fopen("xpcLog.txt","w"); - if (logFile != NULL) // If opened correctly - { - fprintf(logFile,"\n"); - fclose(logFile); - } + strcpy(outName, "X-Plane Connect [Version 1.0.1]"); + strcpy(outSig, "NASA.XPlaneConnect"); + strcpy(outDesc, "X Plane Communications Toolbox\nCopyright (c) 2013-2015 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved."); - updateLog("[EXEC] xpcPlugin Start", 22); - #if (__APPLE__) if ( abs(timeConvert) <= 1e-9 ) // is about 0 { @@ -163,91 +104,78 @@ PLUGIN_API int XPluginStart( char * outName, 1000000000.0; } #endif + XPC::Log::Initialize("1.0.1"); + XPC::Log::WriteLine("[EXEC] Plugin Start"); + XPC::DataManager::Initialize(); - // Build the DataRef Array - buildXPLMDataRefs(); - - //On/Off Switch for simulation - XPLMSwitch = XPLMFindDataRef("sim/operation/override/override_planepath"); - - XPLMRegisterFlightLoopCallback( - MyFlightLoopCallback, /* Callback */ - -1, /* Interval (s)*/ - NULL); /* refcon not used. */ + float interval = -1; // Call every frame + void* refcon = NULL; // Don't pass anything to the callback directly + XPLMRegisterFlightLoopCallback(XPCFlightLoopCallback, interval, refcon); return 1; } PLUGIN_API void XPluginStop(void) { - char logmsg[100] = "[EXEC] xpcPlugin Shutdown"; - XPLMUnregisterFlightLoopCallback(MyFlightLoopCallback, NULL); - updateLog(logmsg,strlen(logmsg)); + XPLMUnregisterFlightLoopCallback(XPCFlightLoopCallback, NULL); + XPC::Log::WriteLine("[EXEC] Plugin Shutdown"); } PLUGIN_API void XPluginDisable(void) { - char logmsg[100] = "[EXEC] xpcPlugin Disabled, sockets closed"; - closeUDP(recSocket); - closeUDP(sendSocket); - updateLog(logmsg,strlen(logmsg)); + // Close sockets + delete sock; + sock = NULL; - XPCClearMessage(); + // Stop rendering messages to screen. + XPC::Drawing::ClearMessage(); + + // Stop rendering waypoints to screen. + XPC::Drawing::ClearWaypoints(); + + XPC::Log::WriteLine("[EXEC] Plugin Disabled, sockets closed"); } PLUGIN_API int XPluginEnable(void) { - char logmsg[100] = "[EXEC] xpcPlugin Enabled, sockets opened"; - char IP[16] = "127.0.0.1"; - recSocket = openUDP(RECVPORT, IP, 49009); - sendSocket = openUDP(SENDPORT, IP, 49099); - updateLog(logmsg,strlen(logmsg)); - memset(logmsg,0,strlen(logmsg)); - - if (benchmarkingSwitch>0) + // Open sockets + sock = new XPC::UDPSocket(RECVPORT); + XPC::MessageHandlers::SetSocket(sock); + + XPC::Log::WriteLine("[EXEC] Plugin Enabled, sockets opened"); + if (benchmarkingSwitch > 0) { - sprintf(logmsg,"[EXEC] Benchmarking Enabled (Verbosity: %i)",benchmarkingSwitch); - updateLog(logmsg,strlen(logmsg)); - memset(logmsg,0,strlen(logmsg)); - } - - if (debugSwitch>0) - { - sprintf(logmsg,"[EXEC] Debug Enabled (Verbosity: %i)",debugSwitch); - updateLog(logmsg,strlen(logmsg)); + XPC::Log::FormatLine("[EXEC] Benchmarking Enabled (Verbosity: %i)", benchmarkingSwitch); } +#if LOG_VERBOSITY > 0 + XPC::Log::FormatLine("[EXEC] Debug Logging Enabled (Verbosity: %i)", LOG_VERBOSITY); +#endif return 1; } -PLUGIN_API void XPluginReceiveMessage( XPLMPluginID inFromWho, - int inMessage, - void * inParam) +PLUGIN_API void XPluginReceiveMessage(XPLMPluginID inFromWho, int inMessage, void* inParam) { + // XPC doesn't have anything useful to say to other plugins, so simply ignore + // any messages received. } -float MyFlightLoopCallback( float inElapsedSinceLastCall, - float inElapsedTimeSinceLastFlightLoop, - int inCounter, - void * inRefcon) +float XPCFlightLoopCallback(float inElapsedSinceLastCall, + float inElapsedTimeSinceLastFlightLoop, + int inCounter, + void* inRefcon) { - int i; - short result; - char logmsg[100] = {0}; #if (__APPLE__) double diff_t; #endif - XPCMessage theMessage; - + counter++; if (benchmarkingSwitch > 1) { - sprintf(logmsg,"Cycle time %.6f",inElapsedSinceLastCall); - updateLog(logmsg,strlen(logmsg)); - memset(logmsg,0,strlen(logmsg)); + XPC::Log::FormatLine("Cycle time %.6f", inElapsedSinceLastCall); } - - for (i=0;i 0) { @@ -255,921 +183,29 @@ float MyFlightLoopCallback( float inElapsedSinceLastCall, start = (double)mach_absolute_time( ) * timeConvert; #endif } - readMessage(&recSocket, &theMessage); - result = handleInput(&theMessage); + + XPC::Message msg = XPC::Message::ReadFrom(*sock); + if (msg.GetHead() == "") + { + break; + } + XPC::MessageHandlers::HandleMessage(msg); if (benchmarkingSwitch > 0) { #if (__APPLE__) lap = (double)mach_absolute_time( ) * timeConvert; diff_t = lap-start; - sprintf(logmsg,"Runtime %.6f",diff_t); - updateLog(logmsg,strlen(logmsg)); - memset(logmsg,0,strlen(logmsg)); + XPC::Log::FormatLine("[BENCH] Runtime %.6f",diff_t); #endif } - - if (result<=0) break; // No Signal } - - if (cyclesToClear != -1) + + if (cyclesToClear != -1 && counter%cyclesToClear == 0) { - if (counter%cyclesToClear==0) - { - strcpy(logmsg,"[EXEC] Cleared UDP Buffer"); - updateLog(logmsg,strlen(logmsg)); - char IP[16] = "127.0.0.1"; - closeUDP(recSocket); - recSocket = openUDP(RECVPORT, IP, 49009); - - } + XPC::Log::WriteLine("[EXEC] Cleared UDP Buffer"); + delete sock; + sock = new XPC::UDPSocket(RECVPORT); } return -1; } - -short handleInput(struct XPCMessage * theMessage) -{ - int i; - char logmsg[100] = {0}; - char IP[16] = {0}; - unsigned short port = 0; - - current_connection = -1; - - if (theMessage->msglen > 0) // If message received - { - if (debugSwitch>0) - { -#ifdef _WIN32 -#else - printBufferToLog(*theMessage); -#endif - } - - // Check for existing connection - port = getIP(theMessage->recvaddr,IP); - for (i=0; i 0) - { - current_connection=i; - break; - } - } - - if (current_connection == -1) //SETUP NEW CONNECTION - { - if (number_of_connections>=MAXCONN) // Handle hitting MAXCONN (COME UP WITH A BETTER SOLUTION) - { - updateLog("[EXEC] Hit maximum number of connections-Removing old ones",58); - number_of_connections = 0; - } - - memcpy(connectionList[number_of_connections].IP,IP,16); - connectionList[number_of_connections].recPort = 49008; - connectionList[number_of_connections].fromPort = port; - current_connection = number_of_connections; - number_of_connections ++; - - // Log Connection - sprintf(logmsg,"[EXEC] New Connection [%i]. IP=%s, port=%i",number_of_connections,IP, port); - updateLog(logmsg,strlen(logmsg)); - memset(logmsg,0,strlen(logmsg)); - } - - if (strncmp(theMessage->head,"CONN",4)==0) // Header = CONN (Connection) - { - handleCONN(theMessage->msg); - } - else if (strncmp(theMessage->head,"SIMU",4)==0) // Header = SIMU - { - handleSIMU(theMessage->msg); - } - else if (strncmp(theMessage->head,"POSI",4)==0) // Header = POSI (Position) - { - handlePOSI(theMessage->msg); - } - else if (strncmp(theMessage->head,"CTRL",4)==0) // Header = CTRL (Control) - { - handleCTRL(theMessage->msg); - } - else if (strncmp(theMessage->head,"WYPT",4)==0) // Header = WYPT (Waypoint Draw) - { - handleWYPT(theMessage->msg, theMessage->msglen); - } - else if (strncmp(theMessage->head,"GETD",4)==0) // Header = GETD (Data Request) - { - handleGETD(theMessage->msg); - } - else if (strncmp(theMessage->head,"DREF",4)==0) // Header = DREF (By Data Ref) (this is slower than DATA) - { - handleDREF(theMessage->msg); - } - else if (strncmp(theMessage->head,"VIEW",4)==0) // Header = VIEW (Change View) - { - handleVIEW(); - } - else if (strncmp(theMessage->head,"DATA",4)==0) // Header = DATA (UDP Data) - { - handleDATA(theMessage->msg, theMessage->msglen); - } - else if (strncmp(theMessage->head, "TEXT", 4) == 0) // Header = TEXT (Screen message) - { - handleTEXT(theMessage->msg, theMessage->msglen); - } - else if ((strncmp(theMessage->head,"DSEL",4)==0) || (strncmp(theMessage->head,"USEL",4)==0)) // Header = DSEL/USEL (Select UDP Send) - { - sendBUF(theMessage->msg,theMessage->msglen); // Send to UDP - } - else if ((strncmp(theMessage->head,"DCOC",4)==0) || (strncmp(theMessage->head,"UCOC",4)==0)) - { - sendBUF(theMessage->msg,theMessage->msglen); // Send to UDP - } - else if ((strncmp(theMessage->head,"MOUS",4)==0) || (strncmp(theMessage->head,"CHAR",4)==0)) - { - sendBUF(theMessage->msg,theMessage->msglen); // Send to UDP - } - else if (strncmp(theMessage->head,"MENU",4)==0) - { - sendBUF(theMessage->msg,theMessage->msglen); // Send to UDP - } - else if (strncmp(theMessage->head,"SOUN",4)==0) - { - sendBUF(theMessage->msg,theMessage->msglen); // Send to UDP - } - else if ((strncmp(theMessage->head,"FAIL",4)==0) || (strncmp(theMessage->head,"RECO",4)==0)) - { - sendBUF(theMessage->msg,theMessage->msglen); // Send to UDP - } - else if (strncmp(theMessage->head,"PAPT",4)==0) - { - sendBUF(theMessage->msg,theMessage->msglen); // Send to UDP - } - else if ((strncmp(theMessage->head,"VEHN",4)==0) || (strncmp(theMessage->head,"VEH1",4)==0) || (strncmp(theMessage->head,"VEHA",4)==0)) - { - sendBUF(theMessage->msg,theMessage->msglen); // Send to UDP - } - else if ((strncmp(theMessage->head,"OBJN",4)==0) || (strncmp(theMessage->head,"OBJL",4)==0)) - { - sendBUF(theMessage->msg,theMessage->msglen); // Send to UDP - } - else if ((strncmp(theMessage->head,"GSET",4)==0) || (strncmp(theMessage->head,"ISET",4)==0)) - { - sendBUF(theMessage->msg,theMessage->msglen); // Send to UDP - } - else if (strncmp(theMessage->head, "BOAT", 4) == 0) - { - sendBUF(theMessage->msg, theMessage->msglen); // Send to UDP - } - else - { //unrecognized header - sprintf(logmsg,"[EXEC] ERROR: Command %s not recognized",theMessage->head); - updateLog(logmsg, strlen(logmsg)); - } - current_connection = -1; - } // end if (buflen > 0) - - return theMessage->msglen; -} - -void sendBUF( char buf[], int buflen) -{ - char IP[16] = "127.0.0.1"; - memcpy(sendSocket.xpIP,IP,16); - sendSocket.xpPort = 49000; - sendUDP(sendSocket,buf,buflen); -} - -int handleCONN(char buf[]) -{ - char logmsg[100] = {0}; - char the_message[7]; - char header[5]; - - strncpy(header,"CONF",4); - memcpy(&the_message,&header,4); - the_message[4] = (char) current_connection; - - // COPY PORT - memcpy(&(connectionList[current_connection].recPort),&buf[5],sizeof(connectionList[current_connection].recPort)); - - if (connectionList[current_connection].recPort <= 1) // Is not valid port - { - connectionList[current_connection].recPort = 49008; - return updateLog("[CONN] ERROR: Port Number must be a number (NaN received)",51); - } - - - // UPDATE LOG - sprintf(logmsg,"[CONN] Update Connection %i- Sending to port: %i",current_connection+1,connectionList[current_connection].recPort); - updateLog(logmsg,strlen(logmsg)); - - // SEND CONFIRMATION - // TODO: Ivestigate why sending confirmation causes crashes on Windows 8 - //memcpy(sendSocket.xpIP,connectionList[current_connection].IP, sizeof(connectionList[current_connection].IP)); - //sendSocket.xpPort = connectionList[current_connection].recPort; - //sendUDP(sendSocket, the_message, 5); - - return 0; -} - -int handleSIMU(char buf[]) -{ - int SIMUArray[1] = {buf[5]}; - char logmsg[100] = {0}; - - if (SIMUArray[0] != SIMUArray[0]) // Is NaN - { - return updateLog("[SIMU] ERROR: Value must be a number (NaN received)",51); - } - - XPLMSetDatavi(XPLMSwitch, SIMUArray, 0, 1); - - if (buf[5] == 0) - { - sprintf(logmsg,"[SIMU] Simulation Resumed (Conn %i)", current_connection+1); - updateLog(logmsg,strlen(logmsg)); - } - else - { - sprintf(logmsg,"[SIMU] Simulation Paused (Conn %i)", current_connection+1); - updateLog(logmsg,strlen(logmsg)); - } - - return 0; -} - -int handleTEXT(char *buf, int len) -{ - char msg[256] = { 0 }; - if (len < 14) - { - updateLog("[TEXT] ERROR: Length less than 14 bytes", 39); - return -1; - } - size_t msgLen = (unsigned char)buf[13]; - if (msgLen == 0) - { - XPCClearMessage(); - updateLog("[TEXT] Text cleared", 19); - } - else - { - int x = *((int*)(buf + 5)); - int y = *((int*)(buf + 9)); - strncpy(msg, buf + 14, msgLen); - XPCSetMessage(x, y, msg); - updateLog("[TEXT] Text set", 15); - } - return 0; -} - -char setDREF(XPLMDataRef theDREF, float floatarray[], short arrayStart, short arraySize) -{ - XPLMDataTypeID dataType; - short i=arrayStart; - - if ((floatarray[i]<-997.5 && floatarray[i]>-999.5)) - { - return 0; // Do not change - } - - if (theDREF == XPLMDataRefs[0][0]) - { - return -1; - } - - if (theDREF) // VALID POINTER - { - if (floatarray[i] != floatarray[i]) // Is NaN - { - goto NANMessage; - } - - dataType = XPLMGetDataRefTypes(theDREF); - switch (dataType) - { - {case 1: //Integer - XPLMSetDatai(theDREF,(int) floatarray[i]); - break;} - - {case 4: //Double - XPLMSetDatad(theDREF,(double) floatarray[i]); - break;} - - {case 8: //Float Array - fmini(XPLMGetDatavf(theDREF,NULL,0,8),arraySize); //find size of array - if ( floatarray[0] != floatarray[0] ) // NaN Check - { - goto NANMessage; - } - - XPLMSetDatavf(theDREF,floatarray,arrayStart,arraySize); - break;} - - {case 16: //Integer Array - int intArray[20]; - short length; - length = fmini(XPLMGetDatavi(theDREF,NULL,0,8),arraySize); //find size of array - for (i=arrayStart; i < arrayStart+length; i++) - { - intArray[i] = (int) floatarray[i]; - } - XPLMSetDatavi(theDREF,intArray,0,length); - break;} - - {default: //Float - XPLMSetDataf(theDREF,floatarray[i]); - break;} - } - } - else - return updateLog("[DREF] ERROR: invalid DREF",26); - - return 0; - -NANMessage: - return updateLog("[DREF] ERROR: Value must be a number (NaN received)",51); -} - -char setGEAR(short aircraft, float gear, char posi) -{ - int i; - float gearArray[8]; - - if ((gear < - 8.5f && gear > 9.5f) || (gear < -997.9f && gear > -999.1f)) - { - return -1; // Don't change command - } - - if ( ( gear != gear ) || ( gear < -1.f ) || ( gear > 1.f ) ) // NaN & Positive test - { - return updateLog("[GEAR] ERROR: Value must be 0 or 1",51); - } - - for (i=0;i<8;i++) - { - gearArray[i] = gear; - } - - if (!aircraft) - { // Own Aircraft - setDREF(XPLMDataRefs[14][7], gearArray, 0, 8); - } - else - { // Multiplayer - setDREF(multiplayer[aircraft][6], gearArray, 0, 8); - } - - if (posi) - { - XPLMSetDatavf(XPLMDataRefs[14][0], gearArray, 0, 1); - } - - return 0; -} - -char setPOSI(short aircraft, float pos[3]) -{ - double local[3] = {0}; - int i; - float tPos = pos[0] + pos[1] + pos[2]; - - if (tPos != tPos) // Is NaN - { - return updateLog("[POSI] ERROR: Position must be a number (NaN received)",51); - } - - XPLMWorldToLocal(pos[0],pos[1],pos[2],&local[0],&local[1],&local[2]); - if (aircraft <= 0) - { // Main aircraft - for (i=0; i<3; i++) - { - XPLMSetDatad(XPLMDataRefs[21][i],local[i]); - XPLMSetDatad(XPLMDataRefs[20][i], pos[i]); - } - } - else - { // Multiplayer - for (i=0; i<3; i++) - { - XPLMSetDatad(multiplayer[aircraft][i], local[i]); - } - } - - return 0; -} - -char setORIENT(short aircraft, float orient[3]) -{ - int i; - float q[4] = {0}; - float pi = (float) 0.00872664625997; // 1/2 rad - float tOrient = orient[0] + orient[1] + orient[2]; - - if ( tOrient != tOrient ) // Is NaN - { - return updateLog("[ORIENT] ERROR: Orientation must be a number (NaN received)",53); - } - - if ( aircraft <= 0 ) // Main aircraft - { - XPLMSetDataf(XPLMDataRefs[17][0],orient[0]); - XPLMSetDataf(XPLMDataRefs[17][1],orient[1]); - XPLMSetDataf(XPLMDataRefs[17][2],orient[2]); - - //Convert to Quartonians (from: http://www.xsquawkbox.net/xpsdk/mediawiki/MovingThePlane), http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19770024290.pdf pA2) - orient[2] = pi * orient[2]; // 1/2 raidians - orient[0] = pi * orient[0]; // 1/2 raidians - orient[1] = pi * orient[1]; // 1/2 raidians - q[0] = cos(orient[2]) * cos(orient[0]) * cos(orient[1]) + sin(orient[2]) * sin(orient[0]) * sin(orient[1]); - q[1] = cos(orient[2]) * cos(orient[0]) * sin(orient[1]) - sin(orient[2]) * sin(orient[0]) * cos(orient[1]); - q[2] = cos(orient[2]) * sin(orient[0]) * cos(orient[1]) + sin(orient[2]) * cos(orient[0]) * sin(orient[1]); - q[3] = sin(orient[2]) * cos(orient[0]) * cos(orient[1]) - cos(orient[2]) * sin(orient[0]) * sin(orient[1]); - - XPLMSetDatavf(XPLMDataRefs[17][4],q,0,4); - } - else - { - for (i=0; i<3; i++) - { - XPLMSetDataf(multiplayer[aircraft][i+3],orient[i]); - } - } - - return 0; -} - -char setFLAP(float flap) -{ - float floatArray[1] = {flap}; - setDREF(XPLMDataRefs[13][3],floatArray,0,1); - setDREF(XPLMDataRefs[13][4],floatArray,0,1); - - return 0; -} - -int handlePOSI(char buf[]) -{ - char logmsg[100]; - float position[8] = {0.0}; - float pos[3],orient[3]; - short aircraft = 0; - float gear = -1.0; - int autopilot[20] = {0}; - - // UPDATE LOG - sprintf(logmsg,"[POSI] Message Received (Conn %i)", current_connection+1); - updateLog(logmsg, strlen(logmsg)); - - aircraft = fmini(parsePOSI(buf,position,6, &gear),19); - - //ADD AIRCRAFT HANDLING- (-1 = single aircraft for player) - if (aircraft > 0) // Multiplayer aircraft - { - XPLMGetDatavi(AIswitch, autopilot, 0, 20); - autopilot[aircraft] = 1; - XPLMSetDatavi(AIswitch, autopilot, 0, 20); - } - - // Position - memcpy(pos,position,3*sizeof(float)); - setPOSI(aircraft, pos); - - // Orientation - memcpy(orient,&position[3],3*sizeof(float)); - setORIENT(aircraft, orient); - - //Landing Gear - if (gear != -1) - { - setGEAR(aircraft, gear, 1); - } - - return 0; -} - -int handleCTRL(char buf[]) -{ - char logmsg[100]; - xpcCtrl ctrl; - float thr[8] = { 0 }; - short i; - - // UPDATE LOG - sprintf(logmsg,"[CTRL] Message Received (Conn %i)", current_connection+1); - updateLog(logmsg, strlen(logmsg)); - - ctrl = parseCTRL(buf); - if (ctrl.aircraft < 0) //parseCTRL failed - { - return 1; - } - if (ctrl.aircraft > 19) //Can only handle 19 non-player aircraft right now - { - return 2; - } - if (ctrl.aircraft == 0) //player aircraft - { - // SET CONTROLS - XPLMSetDataf(XPLMDataRefs[11][0], ctrl.pitch); - XPLMSetDataf(XPLMDataRefs[11][1], ctrl.roll); - XPLMSetDataf(XPLMDataRefs[11][2], ctrl.yaw); - - // SET Throttle - for (i = 0; i<8; i++) - { - thr[i] = ctrl.throttle; - } - XPLMSetDatavf(XPLMDataRefs[25][0], thr, 0, 8); - XPLMSetDatavf(XPLMDataRefs[26][0], thr, 0, 8); - setDREF(XPLMFindDataRef("sim/flightmodel/engine/ENGN_thro_override"), thr, 0, 1); - - // SET Gear/Flaps - if (ctrl.gear != -1) - { - setGEAR(0, ctrl.gear, 0); // Gear - } - if (ctrl.flaps < -999.5 || ctrl.flaps > -997.5) // Flaps - { - XPLMSetDataf(XPLMDataRefs[13][3], ctrl.flaps); - } - } - else //non-player aircraft - { - // SET CONTROLS - XPLMSetDataf(multiplayer[ctrl.aircraft][14], ctrl.pitch); - XPLMSetDataf(multiplayer[ctrl.aircraft][15], ctrl.roll); - XPLMSetDataf(multiplayer[ctrl.aircraft][16], ctrl.yaw); - - // SET Throttle - for (i = 0; i<8; i++) - { - thr[i] = ctrl.throttle; - } - XPLMSetDatavf(multiplayer[ctrl.aircraft][13], thr, 0, 8); - - // SET Gear/Flaps - if (ctrl.gear != -1) - { - float gear[10]; - for (int i = 0; i < 10; ++i) - { - gear[i] = ctrl.gear; - } - XPLMSetDatavf(multiplayer[ctrl.aircraft][6], gear, 0, 10); - } - if (ctrl.flaps < -999.5 || ctrl.flaps > -997.5) // Flaps - { - XPLMSetDataf(multiplayer[ctrl.aircraft][7], ctrl.flaps); - XPLMSetDataf(multiplayer[ctrl.aircraft][8], ctrl.flaps); - } - } - return 0; -} - -int handleWYPT(char buf[], int len) -{ - // UPDATE LOG - char logmsg[100]; - sprintf(logmsg,"[WYPT] Message Received (Conn %i)", current_connection+1); - updateLog(logmsg, strlen(logmsg)); - - xpcWypt wypt = parseWYPT(buf); - if (wypt.op < 0) - { - sprintf(logmsg, "[WYPT] Failed to parse command. ERR:%i", wypt.op); - updateLog(logmsg, strlen(logmsg)); - return -1; - } - else - { - sprintf(logmsg, "[WYPT] Performing operation %i", wypt.op); - updateLog(logmsg, strlen(logmsg)); - } - - switch (wypt.op) - { - case xpc_WYPT_ADD: - XPCAddWaypoints(wypt.points, wypt.numPoints); - break; - case xpc_WYPT_DEL: - XPCRemoveWaypoints(wypt.points, wypt.numPoints); - break; - case xpc_WYPT_CLR: - XPCClearWaypoints(); - break; - default: //If parseWYPT is doing its job, we shouldn't ever hit this. - return -2; - } - return 0; -} - -int handleGETD(char buf[]) -{ - int length,i,k; - XPLMDataTypeID dataType; - char logmsg[400] = {0}; - int listLength = buf[5]; - char the_message[5000]; - char header[5] = {0}; - int count = 6; - float values[100] = {-998}; - int intArray[100] = {-998}; - int DREFSizes[100] = {0}; - char *DREFArray[100]; - - strncpy(header,"RESP",4); - memcpy(&the_message,&header,4); - - if (listLength == 0) // USE LAST REQUEST - { - sprintf(logmsg,"[GETD] DATA Requested- repeat last request from connection %i (%i data refs)",current_connection+1,connectionList[current_connection].requestLength); - - if (connectionList[current_connection].requestLength < 0) // No past requests - { - updateLog(logmsg, strlen(logmsg)); - memset(logmsg,0,strlen(logmsg)); - sprintf(logmsg,"[GETD] ERROR- No previous requests from connection %i.",current_connection+1); - return updateLog(logmsg, strlen(logmsg)); - } - } - else if (listLength > 0) // NEW REQUEST - { - connectionList[current_connection].requestLength = (short) listLength; - - for (int i = 0; i < connectionList[current_connection].requestLength; i++) - { - DREFArray[i] = (char *) malloc(100); - memset(DREFArray[i],0,100); - } - - parseGETD(buf,DREFArray,DREFSizes); - sprintf(logmsg,"[GETD] DATA Requested- New Request for connection %i [%i]:",current_connection+1,listLength); - } - else - { - return -1; - } - - // Update Log - updateLog(logmsg,strlen(logmsg)); - memset(logmsg,0,strlen(logmsg)); - - for (i=0;i 0) - { - connectionList[current_connection].XPLMRequestedDRefs[i] = XPLMFindDataRef(DREFArray[i]); - } - - if (connectionList[current_connection].XPLMRequestedDRefs[i]) //Valid Pointer - { - dataType = XPLMGetDataRefTypes(connectionList[current_connection].XPLMRequestedDRefs[i]); - switch (dataType) - { - {case 1: //Integer - length = 1; - values[0] = (float) XPLMGetDatai(connectionList[current_connection].XPLMRequestedDRefs[i]); - break;} - - {case 4: //Double - length = 1; - values[0] = (float) XPLMGetDatad(connectionList[current_connection].XPLMRequestedDRefs[i]); - break;} - - {case 8: //Float Array - length = XPLMGetDatavf(connectionList[current_connection].XPLMRequestedDRefs[i],NULL,0,8); //find size of array - XPLMGetDatavf(connectionList[current_connection].XPLMRequestedDRefs[i],values,0,fminl(length,100)); - break;} - - {case 16: //Integer Array - length = XPLMGetDatavi(connectionList[current_connection].XPLMRequestedDRefs[i],NULL,0,8); //find size of array - XPLMGetDatavi(connectionList[current_connection].XPLMRequestedDRefs[i],intArray,0,fminl(length,100)); - for (k=0; k < length; k++) { - values[k]=(float) intArray[k]; - } - break;} - - {default: //Float - length = 1; - values[0] = XPLMGetDataf(connectionList[current_connection].XPLMRequestedDRefs[i]); - break;} - } - the_message[count] = length; - memcpy(&the_message[count+1],&values,length*sizeof(float)); - count += 1 + length*sizeof(float); - } - else - { - sprintf(logmsg,"%s-ERROR: invalid DREF",DREFArray[i]); - updateLog(logmsg, strlen(logmsg)); - } - } - the_message[5] = (char) connectionList[current_connection].requestLength; - - memcpy(sendSocket.xpIP,connectionList[current_connection].IP, sizeof(connectionList[current_connection].IP)); - sendSocket.xpPort = connectionList[current_connection].recPort; - - if (count > 6) - { - sendUDP(sendSocket, the_message, count); - } - - return 0; -} - -int handleDREF(char buf[]) -{ - char logmsg[400]={0}; - - char DREF[100] = {0}; - unsigned short lenDREF = 0; - unsigned short lenVALUE = 0; - float values[40] = {0.0}; - XPLMDataRef theDREF; - - parseDREF(buf, DREF, &lenDREF,values,&lenVALUE); - - // Input Varification - if (lenDREF <= 0) - { - return 1; - } - - // Handle DREF - sprintf(logmsg,"[DREF] Request to set DREF value received (Conn %i): %s",current_connection+1,DREF); - updateLog(logmsg,strlen(logmsg)); - - theDREF = XPLMFindDataRef(DREF); - setDREF(theDREF, values, 0, lenVALUE); - - return 0; -} - -int handleVIEW() -{ - char logmsg[100]; - - // UPDATE LOG - sprintf(logmsg,"[VIEW] Message Received (Conn %i)- VIEW FEATURE UNDER CONSTRUCTION",current_connection+1); - updateLog(logmsg, strlen(logmsg)); - - return 0; -} - -int handleDATA(char buf[], int buflen) -{ - int i,j,lines; - char logmsg[100] = {0}; - float floatArray[10] = {0}; - float recValues[20][9] = {0}; - const float deg2rad = (float) 0.0174532925; - float savedAlpha=-998; - float savedHPath=-998; - - lines = parseDATA(buf, buflen, recValues); //Parse Data - if (lines > 0) - { - // UPDATE LOG - sprintf(logmsg,"[DATA] Message Received (Conn %i)",current_connection+1); - updateLog(logmsg, strlen(logmsg)); - memset(logmsg,0,strlen(logmsg)); - } - else - { - // UPDATE LOG - sprintf(logmsg,"[DATA] WARNING: Empty data packet received (Conn %i)",current_connection+1); - return updateLog(logmsg, strlen(logmsg)); - } - - for (i = 0; i134 ) - { // DREF Check 1: This ensures that the received dataRef is in the range of 0-134 - sprintf(logmsg,"[DATA] ERROR: DataRef # must be between 0-134 (Rec: %hi)",dataRef); - updateLog(logmsg,strlen(logmsg)); - memset(logmsg,0,strlen(logmsg)); - continue; - } - - switch (dataRef) - { - {case 3: // Velocity - // Velocity has to be broken into individual components in X-Plane World Coordinate System where x=East, y=Up. - //Note: Add Sideslip - - float theta, alpha, hpath,v; - int ind[3] = {1,3,4}; - theta = XPLMGetDataf(XPLMDataRefs[17][0]); //Theta - - if (savedAlpha != -998) - alpha = savedAlpha; - else - alpha = XPLMGetDataf(XPLMDataRefs[18][0]); //Alpha - - if (savedHPath != -998) - hpath = savedHPath; - else - hpath = XPLMGetDataf(XPLMDataRefs[18][2]); //Velocity Heading - - if ( ( hpath != hpath ) && ( alpha != alpha ) && ( theta != theta ) ) // NaN Check - { - updateLog("[DATA] ERROR: Value must be a number (NaN received)",51); - break; - } - - for (j=0;j 0) - { - char theString[100] = {0}; - sprintf(theString,"Setting Dataref %i.%i to %f",dataRef,j,floatArray[j]); - updateLog(theString, strlen(theString)); - } - - if (dataRef==14 && j==0) - { - setGEAR(0, recValues[i][j+1], 1); // Landing Gear - continue; - } - - // Set DATAREF - if (setDREF(XPLMDataRefs[dataRef][j],floatArray,j,8) == -1) - sendBUF(buf,buflen); - } //End for j=1:8 - break;} - } // End switch(dataRef) - }// End for(all lines) - - return 0; -} // End handleDATA diff --git a/xpcPlugin/XPlaneConnect/64/lin.xpl b/xpcPlugin/XPlaneConnect/64/lin.xpl new file mode 100755 index 0000000..82d335a Binary files /dev/null and b/xpcPlugin/XPlaneConnect/64/lin.xpl differ diff --git a/xpcPlugin/XPlaneConnect/64/win.xpl b/xpcPlugin/XPlaneConnect/64/win.xpl index 9f42109..88b4c11 100644 Binary files a/xpcPlugin/XPlaneConnect/64/win.xpl and b/xpcPlugin/XPlaneConnect/64/win.xpl differ diff --git a/xpcPlugin/XPlaneConnect/lin.xpl b/xpcPlugin/XPlaneConnect/lin.xpl new file mode 100755 index 0000000..67f6ccb Binary files /dev/null and b/xpcPlugin/XPlaneConnect/lin.xpl differ diff --git a/xpcPlugin/XPlaneConnect/mac.xpl b/xpcPlugin/XPlaneConnect/mac.xpl index abf3566..0415e6b 100755 Binary files a/xpcPlugin/XPlaneConnect/mac.xpl and b/xpcPlugin/XPlaneConnect/mac.xpl differ diff --git a/xpcPlugin/XPlaneConnect/win.xpl b/xpcPlugin/XPlaneConnect/win.xpl index 0e18c52..30b6838 100644 Binary files a/xpcPlugin/XPlaneConnect/win.xpl and b/xpcPlugin/XPlaneConnect/win.xpl differ diff --git a/xpcPlugin/xpcDrawing.cpp b/xpcPlugin/xpcDrawing.cpp deleted file mode 100644 index d770d27..0000000 --- a/xpcPlugin/xpcDrawing.cpp +++ /dev/null @@ -1,268 +0,0 @@ -#include "xpcDrawing.h" -#include "XPLMDisplay.h" -#include "XPLMGraphics.h" -#include "XPLMDataAccess.h" -#include -#include -#include -//OpenGL includes -#if IBM -#include -#endif -#if __GNUC__ -#include -#else -#include -#endif - -//Internal Structures -typedef struct -{ - double x; - double y; - double z; -} LocalPoint; - -//Internal Memory -static const size_t MSG_MAX = 1024; -static const size_t MSG_LINE_MAX = MSG_MAX / 16; -static bool msgEnabled = false; -static int msgX = -1; -static int msgY = -1; -static char msgVal[MSG_MAX] = { 0 }; -static size_t newLineCount = 0; -static size_t newLines[MSG_LINE_MAX] = { 0 }; -static float rgb[3] = { 0.25F, 1.0F, 0.25F }; - -static const size_t WAYPOINT_MAX = 128; -static bool routeEnabled = false; -static size_t numWaypoints = 0; -static Waypoint waypoints[WAYPOINT_MAX]; -static LocalPoint localPoints[WAYPOINT_MAX]; - -XPLMDataRef planeXref; -XPLMDataRef planeYref; -XPLMDataRef planeZref; - -//Internal Functions -int cmp(const void * a, const void * b) -{ - return (*(size_t*)a - *(size_t*)b); -} - -static void gl_drawCube(float x, float y, float z, float d) -{ - //tan(0.25) degrees. Should scale all markers to appear about the same size - const float TAN = 0.00436335082070156648652885284203; - float h = d * TAN; - - glBegin(GL_QUAD_STRIP); - //Top - glVertex3f(x - h, y + h, z - h); - glVertex3f(x + h, y + h, z - h); - glVertex3f(x - h, y + h, z + h); - glVertex3f(x + h, y + h, z + h); - //Front - glVertex3f(x - h, y - h, z + h); - glVertex3f(x + h, y - h, z + h); - //Bottom - glVertex3f(x - h, y - h, z - h); - glVertex3f(x + h, y - h, z - h); - //Back - glVertex3f(x - h, y + h, z - h); - glVertex3f(x + h, y + h, z - h); - - glEnd(); - glBegin(GL_QUADS); - //Left - glVertex3f(x - h, y + h, z - h); - glVertex3f(x - h, y + h, z + h); - glVertex3f(x - h, y - h, z + h); - glVertex3f(x - h, y - h, z - h); - //Right - glVertex3f(x + h, y + h, z + h); - glVertex3f(x + h, y + h, z - h); - glVertex3f(x + h, y - h, z - h); - glVertex3f(x + h, y - h, z + h); - - glEnd(); -} - -static int MessageDrawCallback(XPLMDrawingPhase inPhase, int inIsBefore, void * inRefcon) -{ - XPLMDrawString(rgb, msgX, msgY, msgVal, NULL, xplmFont_Basic); - int y = msgY - 16; - for (size_t i = 0; i < newLineCount; ++i) - { - XPLMDrawString(rgb, msgX, y, msgVal + newLines[i], NULL, xplmFont_Basic); - y -= 16; - } - return 1; -} - -static int RouteDrawCallback(XPLMDrawingPhase inPhase, int inIsBefore, void * inRefcon) -{ - float px = XPLMGetDataf(planeXref); - float py = XPLMGetDataf(planeYref); - float pz = XPLMGetDataf(planeZref); - - Waypoint* g; - LocalPoint* l; - //Convert to local - for (size_t i = 0; i < numWaypoints; ++i) - { - g = &waypoints[i]; - l = &localPoints[i]; - XPLMWorldToLocal(g->latitude, g->longitude, g->altitude, - &l->x, &l->y, &l->z); - } - - - //Draw posts - glColor3f(1.0F, 1.0F, 1.0F); - glBegin(GL_LINES); - for (size_t i = 0; i < numWaypoints; ++i) - { - l = &localPoints[i]; - glVertex3f((float)l->x, (float)l->y, (float)l->z); - glVertex3f((float)l->x, -1000.0F, (float)l->z); - } - glEnd(); - - //Draw route - glColor3f(1.0F, 0.0F, 0.0F); - glBegin(GL_LINE_STRIP); - for (size_t i = 0; i < numWaypoints; ++i) - { - l = &localPoints[i]; - glVertex3f((float)l->x, (float)l->y, (float)l->z); - } - glEnd(); - - //Draw markers - glColor3f(1.0F, 1.0F, 1.0F); - for (size_t i = 0; i < numWaypoints; ++i) - { - l = &localPoints[i]; - float xoff = (float)l->x - px; - float yoff = (float)l->y - py; - float zoff = (float)l->z - pz; - float d = sqrtf(xoff*xoff + yoff*yoff + zoff*zoff); - gl_drawCube((float)l->x, (float)l->y, (float)l->z, d); - } - return 1; -} - -//Public Functions -void XPCClearMessage() -{ - XPLMUnregisterDrawCallback(MessageDrawCallback, xplm_Phase_Window, 0, NULL); - msgEnabled = false; -} - -void XPCSetMessage(int x, int y, char* msg) -{ - //Determine size of message and clear instead if the message string - //is empty. - size_t len = strnlen(msg, MSG_MAX); - if (len == 0) - { - XPCClearMessage(); - return; - } - - //Set the message, location, and mark new lines. - strncpy(msgVal, msg, len); - newLineCount = 0; - for (size_t i = 0; i < len && newLineCount < MSG_LINE_MAX; ++i) - { - if (msgVal[i] == '\n' || msgVal[i] == '\r') - { - msgVal[i] = 0; - newLines[newLineCount++] = i + 1; - } - } - msgX = x < 0 ? 10 : x; - msgY = y < 0 ? 600 : y; - - //Enable drawing if necessary - if (!msgEnabled) - { - XPLMRegisterDrawCallback(MessageDrawCallback, xplm_Phase_LastCockpit, 0, NULL); - msgEnabled = true; - } -} - -void XPCClearWaypoints() -{ - numWaypoints = 0; - if (routeEnabled) - { - XPLMUnregisterDrawCallback(RouteDrawCallback, xplm_Phase_Objects, 0, NULL); - } - return; -} - -void XPCAddWaypoints(Waypoint points[], size_t numPoints) -{ - if (numWaypoints + numPoints > WAYPOINT_MAX) - { - numPoints = WAYPOINT_MAX - numWaypoints; - } - size_t finalNumWaypoints = numPoints + numWaypoints; - for (size_t i = 0; i < numPoints; ++i) - { - waypoints[numWaypoints + i] = points[i]; - } - numWaypoints = finalNumWaypoints; - - if (!routeEnabled) - { - XPLMRegisterDrawCallback(RouteDrawCallback, xplm_Phase_Objects, 0, NULL); - } - if (!planeXref) - { - planeXref = XPLMFindDataRef("sim/flightmodel/position/local_x"); - planeYref = XPLMFindDataRef("sim/flightmodel/position/local_y"); - planeZref = XPLMFindDataRef("sim/flightmodel/position/local_z"); - } -} - -void XPCRemoveWaypoints(Waypoint points[], size_t numPoints) -{ - //Build a list of indices of waypoints we should delete. - size_t delPoints[WAYPOINT_MAX]; - size_t delPointsCur = 0; - for (size_t i = 0; i < numPoints; ++i) - { - Waypoint p = points[i]; - for (size_t j = 0; j < numWaypoints; ++j) - { - Waypoint q = waypoints[j]; - if (p.latitude == q.latitude && - p.longitude == q.longitude && - p.altitude == q.altitude) - { - delPoints[delPointsCur++] = j; - break; - } - } - } - //Sort the indices so that we only have to iterate them once - qsort(delPoints, delPointsCur, sizeof(size_t), cmp); - - //Copy the new array on top of the old array - size_t copyCur = 0; - size_t count = delPointsCur; - delPointsCur = 0; - for (size_t i = 0; i < numWaypoints; ++i) - { - if (i == delPoints[delPointsCur]) - { - ++delPointsCur; - continue; - } - waypoints[copyCur++] = waypoints[i]; - } - numWaypoints -= count; -} \ No newline at end of file diff --git a/xpcPlugin/xpcDrawing.h b/xpcPlugin/xpcDrawing.h deleted file mode 100644 index 4d79275..0000000 --- a/xpcPlugin/xpcDrawing.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef xpcDrawing_h -#define xpcDrawing_h - -#include -#include "xplaneConnect.h" - -void XPCClearMessage(); - -void XPCSetMessage(int x, int y, char* msg); - -void XPCClearWaypoints(); - -void XPCAddWaypoints(Waypoint points[], size_t numPoints); - -void XPCRemoveWaypoints(Waypoint points[], size_t numPoints); - -#endif diff --git a/xpcPlugin/xpcPlugin.xcodeproj/project.pbxproj b/xpcPlugin/xpcPlugin.xcodeproj/project.pbxproj index 81570d0..4bca25c 100755 --- a/xpcPlugin/xpcPlugin.xcodeproj/project.pbxproj +++ b/xpcPlugin/xpcPlugin.xcodeproj/project.pbxproj @@ -8,10 +8,15 @@ /* Begin PBXBuildFile section */ BE37D960187C8B0F0033B082 /* XPCPlugin.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BE37D95E187C8B0F0033B082 /* XPCPlugin.cpp */; }; - BE5F2FF118FCA1D500AFCD17 /* xpcPluginTools.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BE5F2FF018FCA1D500AFCD17 /* xpcPluginTools.cpp */; }; BE8361EF18C5591C00E9C923 /* mac.xpl in CopyFiles */ = {isa = PBXBuildFile; fileRef = D607B19909A556E400699BC3 /* mac.xpl */; }; + BEABAD371AE041A3007BA7DA /* DataManager.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEABAD2B1AE041A3007BA7DA /* DataManager.cpp */; }; + BEABAD381AE041A3007BA7DA /* DataMaps.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEABAD2D1AE041A3007BA7DA /* DataMaps.cpp */; }; + BEABAD391AE041A3007BA7DA /* Drawing.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEABAD2F1AE041A3007BA7DA /* Drawing.cpp */; }; + BEABAD3A1AE041A3007BA7DA /* Log.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEABAD311AE041A3007BA7DA /* Log.cpp */; }; + BEABAD3B1AE041A3007BA7DA /* Message.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEABAD331AE041A3007BA7DA /* Message.cpp */; }; + BEABAD3C1AE041A3007BA7DA /* MessageHandlers.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEABAD351AE041A3007BA7DA /* MessageHandlers.cpp */; }; + BEABAD3F1AE0498D007BA7DA /* UDPSocket.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEABAD3D1AE0498D007BA7DA /* UDPSocket.cpp */; }; BEDC620418EDF1A7005DB364 /* xplaneConnect.c in Sources */ = {isa = PBXBuildFile; fileRef = BEDC620218EDF1A7005DB364 /* xplaneConnect.c */; }; - BEFBC0CB1AD4A0290025705B /* xpcDrawing.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BEFBC0C91AD4A0290025705B /* xpcDrawing.cpp */; }; D6A7BDAA16A1DEA200D1426A /* OpenGL.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D6A7BDA916A1DEA200D1426A /* OpenGL.framework */; }; D6A7BDC116A1DEC000D1426A /* CoreFoundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D6A7BDC016A1DEC000D1426A /* CoreFoundation.framework */; }; D6A7BDF116A1DED200D1426A /* XPLM.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D6A7BDF016A1DED200D1426A /* XPLM.framework */; }; @@ -33,13 +38,22 @@ /* Begin PBXFileReference section */ BE37D95E187C8B0F0033B082 /* XPCPlugin.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = XPCPlugin.cpp; sourceTree = SOURCE_ROOT; usesTabs = 1; }; - BE3C039719DF043D0063D8DD /* Readme.txt */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text; name = Readme.txt; path = ../Readme.txt; sourceTree = ""; }; - BE5F2FEF18FCA13700AFCD17 /* xpcPluginTools.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = xpcPluginTools.h; sourceTree = ""; }; - BE5F2FF018FCA1D500AFCD17 /* xpcPluginTools.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = xpcPluginTools.cpp; sourceTree = ""; }; + BEABAD2B1AE041A3007BA7DA /* DataManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DataManager.cpp; sourceTree = ""; }; + BEABAD2C1AE041A3007BA7DA /* DataManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DataManager.h; sourceTree = ""; }; + BEABAD2D1AE041A3007BA7DA /* DataMaps.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DataMaps.cpp; sourceTree = ""; }; + BEABAD2E1AE041A3007BA7DA /* DataMaps.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DataMaps.h; sourceTree = ""; }; + BEABAD2F1AE041A3007BA7DA /* Drawing.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Drawing.cpp; sourceTree = ""; }; + BEABAD301AE041A3007BA7DA /* Drawing.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Drawing.h; sourceTree = ""; }; + BEABAD311AE041A3007BA7DA /* Log.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Log.cpp; sourceTree = ""; }; + BEABAD321AE041A3007BA7DA /* Log.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Log.h; sourceTree = ""; }; + BEABAD331AE041A3007BA7DA /* Message.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Message.cpp; sourceTree = ""; }; + BEABAD341AE041A3007BA7DA /* Message.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Message.h; sourceTree = ""; }; + BEABAD351AE041A3007BA7DA /* MessageHandlers.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MessageHandlers.cpp; sourceTree = ""; }; + BEABAD361AE041A3007BA7DA /* MessageHandlers.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MessageHandlers.h; sourceTree = ""; }; + BEABAD3D1AE0498D007BA7DA /* UDPSocket.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = UDPSocket.cpp; sourceTree = ""; }; + BEABAD3E1AE0498D007BA7DA /* UDPSocket.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UDPSocket.h; sourceTree = ""; }; BEDC620218EDF1A7005DB364 /* xplaneConnect.c */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.c; name = xplaneConnect.c; path = ../C/src/xplaneConnect.c; sourceTree = ""; }; BEDC620318EDF1A7005DB364 /* xplaneConnect.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = xplaneConnect.h; path = ../C/src/xplaneConnect.h; sourceTree = ""; }; - BEFBC0C91AD4A0290025705B /* xpcDrawing.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = xpcDrawing.cpp; sourceTree = ""; }; - BEFBC0CA1AD4A0290025705B /* xpcDrawing.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = xpcDrawing.h; sourceTree = ""; }; D607B19909A556E400699BC3 /* mac.xpl */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.dylib"; includeInIndex = 0; path = mac.xpl; sourceTree = BUILT_PRODUCTS_DIR; }; D6A7BDA916A1DEA200D1426A /* OpenGL.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = OpenGL.framework; path = System/Library/Frameworks/OpenGL.framework; sourceTree = SDKROOT; }; D6A7BDC016A1DEC000D1426A /* CoreFoundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreFoundation.framework; path = System/Library/Frameworks/CoreFoundation.framework; sourceTree = SDKROOT; }; @@ -62,26 +76,43 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - AC4E46B809C2E0B3006B7E1B /* C Source */ = { + AC4E46B809C2E0B3006B7E1B /* src */ = { isa = PBXGroup; children = ( BE37D95E187C8B0F0033B082 /* XPCPlugin.cpp */, BEDC620218EDF1A7005DB364 /* xplaneConnect.c */, - BEDC620318EDF1A7005DB364 /* xplaneConnect.h */, - BE5F2FF018FCA1D500AFCD17 /* xpcPluginTools.cpp */, - BE5F2FEF18FCA13700AFCD17 /* xpcPluginTools.h */, - BEFBC0C91AD4A0290025705B /* xpcDrawing.cpp */, - BEFBC0CA1AD4A0290025705B /* xpcDrawing.h */, + BEABAD2B1AE041A3007BA7DA /* DataManager.cpp */, + BEABAD2D1AE041A3007BA7DA /* DataMaps.cpp */, + BEABAD2F1AE041A3007BA7DA /* Drawing.cpp */, + BEABAD311AE041A3007BA7DA /* Log.cpp */, + BEABAD331AE041A3007BA7DA /* Message.cpp */, + BEABAD351AE041A3007BA7DA /* MessageHandlers.cpp */, + BEABAD3D1AE0498D007BA7DA /* UDPSocket.cpp */, ); - name = "C Source"; + name = src; + sourceTree = ""; + }; + BE953E0B1AEB183400CE4A8C /* inc */ = { + isa = PBXGroup; + children = ( + BEDC620318EDF1A7005DB364 /* xplaneConnect.h */, + BEABAD2C1AE041A3007BA7DA /* DataManager.h */, + BEABAD2E1AE041A3007BA7DA /* DataMaps.h */, + BEABAD301AE041A3007BA7DA /* Drawing.h */, + BEABAD321AE041A3007BA7DA /* Log.h */, + BEABAD341AE041A3007BA7DA /* Message.h */, + BEABAD361AE041A3007BA7DA /* MessageHandlers.h */, + BEABAD3E1AE0498D007BA7DA /* UDPSocket.h */, + ); + name = inc; sourceTree = ""; }; D607B15F09A5563000699BC3 = { isa = PBXGroup; children = ( - BE3C039719DF043D0063D8DD /* Readme.txt */, D6A7BDAD16A1DEA700D1426A /* Frameworks */, - AC4E46B809C2E0B3006B7E1B /* C Source */, + AC4E46B809C2E0B3006B7E1B /* src */, + BE953E0B1AEB183400CE4A8C /* inc */, D607B19A09A556E400699BC3 /* Products */, ); sourceTree = ""; @@ -158,10 +189,15 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + BEABAD3A1AE041A3007BA7DA /* Log.cpp in Sources */, + BEABAD3B1AE041A3007BA7DA /* Message.cpp in Sources */, + BEABAD3C1AE041A3007BA7DA /* MessageHandlers.cpp in Sources */, + BEABAD381AE041A3007BA7DA /* DataMaps.cpp in Sources */, BEDC620418EDF1A7005DB364 /* xplaneConnect.c in Sources */, + BEABAD371AE041A3007BA7DA /* DataManager.cpp in Sources */, + BEABAD391AE041A3007BA7DA /* Drawing.cpp in Sources */, BE37D960187C8B0F0033B082 /* XPCPlugin.cpp in Sources */, - BEFBC0CB1AD4A0290025705B /* xpcDrawing.cpp in Sources */, - BE5F2FF118FCA1D500AFCD17 /* xpcPluginTools.cpp in Sources */, + BEABAD3F1AE0498D007BA7DA /* UDPSocket.cpp in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -171,6 +207,9 @@ D607B16309A5563100699BC3 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + ARCHS = "$(ARCHS_STANDARD_32_64_BIT)"; + CLANG_CXX_LANGUAGE_STANDARD = "c++98"; + CLANG_CXX_LIBRARY = "libc++"; CONFIGURATION_BUILD_DIR = ./XPlaneConnect; DYLIB_COMPATIBILITY_VERSION = ""; DYLIB_CURRENT_VERSION = ""; @@ -189,7 +228,7 @@ "$(HEADER_SEARCH_PATHS)", ); MACH_O_TYPE = mh_bundle; - MACOSX_DEPLOYMENT_TARGET = 10.6; + MACOSX_DEPLOYMENT_TARGET = 10.7; ONLY_ACTIVE_ARCH = YES; OTHER_LDFLAGS = ( "$(OTHER_LDFLAGS)", @@ -208,7 +247,7 @@ PRECOMPS_INCLUDE_HEADERS_FROM_BUILT_PRODUCTS_DIR = YES; PRODUCT_NAME = "${TARGET_NAME}"; SCAN_ALL_SOURCE_FILES_FOR_INCLUDES = NO; - SDKROOT = macosx10.8; + SDKROOT = macosx; SYMROOT = build; XPSDK_ROOT = SDK; }; @@ -217,7 +256,10 @@ D607B16409A5563100699BC3 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - CONFIGURATION_BUILD_DIR = ./Mac; + ARCHS = "$(ARCHS_STANDARD_32_64_BIT)"; + CLANG_CXX_LANGUAGE_STANDARD = "c++98"; + CLANG_CXX_LIBRARY = "libc++"; + CONFIGURATION_BUILD_DIR = ./XPlaneConnect; DYLIB_COMPATIBILITY_VERSION = ""; DYLIB_CURRENT_VERSION = ""; EXECUTABLE_EXTENSION = xpl; @@ -235,7 +277,7 @@ "$(HEADER_SEARCH_PATHS)", ); MACH_O_TYPE = mh_bundle; - MACOSX_DEPLOYMENT_TARGET = 10.6; + MACOSX_DEPLOYMENT_TARGET = 10.7; OTHER_LDFLAGS = ( "$(OTHER_LDFLAGS)", "-Wl,-exported_symbol", @@ -253,7 +295,7 @@ PRECOMPS_INCLUDE_HEADERS_FROM_BUILT_PRODUCTS_DIR = YES; PRODUCT_NAME = "${TARGET_NAME}"; SCAN_ALL_SOURCE_FILES_FOR_INCLUDES = NO; - SDKROOT = macosx10.8; + SDKROOT = macosx; SYMROOT = build; XPSDK_ROOT = SDK; }; @@ -291,6 +333,7 @@ ); MACH_O_TYPE = mh_bundle; PRODUCT_NAME = mac; + SDKROOT = macosx; STRIP_INSTALLED_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = XPC; @@ -328,7 +371,9 @@ "$(USER_LIBRARY_DIR)/Developer/Xcode/DerivedData/xplaneConnect-asdjuezcjkhojuewbyxhyhabxfwc/Build/Products/Debug", ); MACH_O_TYPE = mh_bundle; + ONLY_ACTIVE_ARCH = NO; PRODUCT_NAME = mac; + SDKROOT = macosx; STRIP_INSTALLED_PRODUCT = YES; VERSIONING_SYSTEM = "apple-generic"; VERSION_INFO_PREFIX = XPC; diff --git a/xpcPlugin/xpcPlugin/xpcPlugin.sln b/xpcPlugin/xpcPlugin/xpcPlugin.sln index cb04280..e34eb3d 100644 --- a/xpcPlugin/xpcPlugin/xpcPlugin.sln +++ b/xpcPlugin/xpcPlugin/xpcPlugin.sln @@ -9,12 +9,18 @@ Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 + Release|Win32 = Release|Win32 + Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {6AEF5D28-2701-44FF-AE10-1DEF07C5CAEA}.Debug|Win32.ActiveCfg = Debug|Win32 {6AEF5D28-2701-44FF-AE10-1DEF07C5CAEA}.Debug|Win32.Build.0 = Debug|Win32 {6AEF5D28-2701-44FF-AE10-1DEF07C5CAEA}.Debug|x64.ActiveCfg = Debug|x64 {6AEF5D28-2701-44FF-AE10-1DEF07C5CAEA}.Debug|x64.Build.0 = Debug|x64 + {6AEF5D28-2701-44FF-AE10-1DEF07C5CAEA}.Release|Win32.ActiveCfg = Release|Win32 + {6AEF5D28-2701-44FF-AE10-1DEF07C5CAEA}.Release|Win32.Build.0 = Release|Win32 + {6AEF5D28-2701-44FF-AE10-1DEF07C5CAEA}.Release|x64.ActiveCfg = Release|x64 + {6AEF5D28-2701-44FF-AE10-1DEF07C5CAEA}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/xpcPlugin/xpcPlugin/xpcPlugin.vcxproj b/xpcPlugin/xpcPlugin/xpcPlugin.vcxproj index 2b495b4..73e1302 100644 --- a/xpcPlugin/xpcPlugin/xpcPlugin.vcxproj +++ b/xpcPlugin/xpcPlugin/xpcPlugin.vcxproj @@ -9,6 +9,14 @@ Debug x64 + + Release + Win32 + + + Release + x64 + {6AEF5D28-2701-44FF-AE10-1DEF07C5CAEA} @@ -22,27 +30,53 @@ v120 MultiByte + + DynamicLibrary + true + v120 + MultiByte + DynamicLibrary true v120 MultiByte + + DynamicLibrary + true + v120 + MultiByte + + + + + + + true ..\XPlaneConnect\ .xpl - ..\xpcPlugin\SDK\CHeaders\XPLM;..\SDK\CHeaders\XPLM;..\..\C\src;$(IncludePath) + ..\SDK\CHeaders\XPLM;$(IncludePath) + ..\xpcPlugin\SDK\Libraries\Win;$(LibraryPath) + win + + + true + ..\XPlaneConnect\ + .xpl + ..\SDK\CHeaders\XPLM;$(IncludePath) ..\xpcPlugin\SDK\Libraries\Win;$(LibraryPath) win @@ -54,19 +88,28 @@ true ..\XPlaneConnect\64\ + + .xpl + ..\xpcPlugin\SDK\CHeaders\XPLM;..\SDK\CHeaders\XPLM;..\..\C\src;$(IncludePath) + ..\xpcPlugin\SDK\Libraries\Win;$(LibraryPath) + win + true + ..\XPlaneConnect\64\ + NotUsing Level3 Disabled - IBM=1;XPLM200;_DEBUG;_WINDOWS;_USRDLL;XPCPLUGIN_EXPORTS;%(PreprocessorDefinitions) + IBM=1;XPLM200;_DEBUG;_WINDOWS;_USRDLL;XPCPLUGIN_EXPORTS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) OldStyle true false - 4996 + + false - MultiThreaded + MultiThreadedDebug Windows @@ -74,12 +117,39 @@ Opengl32.lib;%(AdditionalDependencies) + + + NotUsing + EnableAllWarnings + Full + IBM=1;XPLM200;%(PreprocessorDefinitions) + OldStyle + true + + + false + + + false + MultiThreaded + Default + true + false + + + Windows + false + Opengl32.lib;%(AdditionalDependencies) + UseLinkTimeCodeGeneration + true + + NotUsing Level3 Disabled - IBM=1;XPLM200;_DEBUG;_WINDOWS;_USRDLL;XPCPLUGIN_EXPORTS;%(PreprocessorDefinitions) + IBM=1;XPLM200;_DEBUG;_WINDOWS;_USRDLL;XPCPLUGIN_EXPORTS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) OldStyle @@ -89,7 +159,7 @@ false 4996 false - MultiThreaded + MultiThreadedDebug Windows @@ -97,16 +167,56 @@ OpenGL32.lib;%(AdditionalDependencies) + + + NotUsing + EnableAllWarnings + Full + IBM=1;XPLM200;%(PreprocessorDefinitions) + + + OldStyle + true + + + false + + + false + MultiThreaded + Default + true + + false + + + Windows + false + OpenGL32.lib;%(AdditionalDependencies) + UseLinkTimeCodeGeneration + + + true + + - - - + + + + + + + - - + + + + + + + - diff --git a/xpcPlugin/xpcPlugin/xpcPlugin.vcxproj.filters b/xpcPlugin/xpcPlugin/xpcPlugin.vcxproj.filters index 0082526..e921a5d 100644 --- a/xpcPlugin/xpcPlugin/xpcPlugin.vcxproj.filters +++ b/xpcPlugin/xpcPlugin/xpcPlugin.vcxproj.filters @@ -15,27 +15,51 @@ - + Header Files - + Header Files - + + Header Files + + + Header Files + + + Header Files + + + Header Files + + Header Files - - Source Files - Source Files - + Source Files - + + Source Files + + + Source Files + + + Source Files + + + Source Files + + + Source Files + + Source Files diff --git a/xpcPlugin/xpcPluginTools.cpp b/xpcPlugin/xpcPluginTools.cpp deleted file mode 100644 index 53228c7..0000000 --- a/xpcPlugin/xpcPluginTools.cpp +++ /dev/null @@ -1,492 +0,0 @@ -// xpcPluginTools functions to support xpcPlugin -// -// FUNCTIONS -// buildXPLMDataRefs -// fmini -// almostequal -// updateLog -// handleDREFSIM -// getIP -// printBuffertoLog -// test -// testi -// -// CONTACT -// For questions email Christopher Teubert (christopher.a.teubert@nasa.gov) -// -// CONTRIBUTORS -// CT: Christopher Teubert (christopher.a.teubert@nasa.gov) -// -// TO DO: -// 1. Support sending -1 length to updateLog for it to calculate intself (look for /0) -// 2. Have printbuffertolog run parse function -// 3. Builddatarefs: Fill out & test options -// -// BEGIN CODE - -#include -#include -#include -#include -#include -#include "xpcPluginTools.h" - -XPLMDataRef XPLMDataRefs[134][8]; -XPLMDataRef multiplayer[20][17]; -XPLMDataRef AIswitch; - -void readMessage(struct xpcSocket * recSocket, struct XPCMessage * pMessage) -{ - pMessage->msglen = readUDP( *recSocket, pMessage->msg, &(pMessage->recvaddr) ); - - if ( pMessage->msglen <= 0 ) // No Message - { - pMessage->msg[0] = 0; - } - else - { - strncpy( pMessage->head, pMessage->msg, 4 ); - } - - return; -} - -void buildXPLMDataRefs() -{ - int i, j; - char multi[50] = {0}; - - for (i=0; i<134; i++) - { - for (j=0; j<8; j++) - { - XPLMDataRefs[i][j] = XPLMFindDataRef("sim/test/test_float"); - } - } - - /* Prefetch the sim variables we will use. */ - //Row 0: Frame Rates - - //Row 1: Times - XPLMDataRefs[1][1] = XPLMFindDataRef("sim/time/total_running_time_sec"); - XPLMDataRefs[1][2] = XPLMFindDataRef("sim/time/total_flight_time_sec"); - XPLMDataRefs[1][3] = XPLMFindDataRef("sim/time/timer_elapsed_time_sec"); - - //cockpit2/clock_time/zulu_time_hours - //cockpit2/clock_time/zulu_time_minutes - //cockpit2/clock_time/zulu_time_seconds - - //cockpit2/clock_time/local_time_hours - - //cockpit2/clock_time/hobbs_time_hours - - //Row 2: Sim Stats - - //Row 3: Velocities - //READ ONLY - XPLMDataRefs[3][0] = XPLMFindDataRef("sim/flightmodel/position/indicated_airspeed"); //Vind knots indicated airspeed TEST - - //Vind knots equivilent airspeed (considering compressible flow) - XPLMDataRefs[3][2] = XPLMFindDataRef("sim/flightmodel/position/true_airspeed"); //Vtrue knots true airspeed - XPLMDataRefs[3][3] = XPLMFindDataRef("sim/flightmodel/position/groundspeed"); //Vtrue Knots true ground speed - - //XPLMDataRefs[3][5] = Vind mph - //XPLMDataRefs[3][6] = Vtrue mphas - //XPLMDataRefs[3][7] = Vtre mphgs - - //Row 4: Mach, VVI, G-loads - XPLMDataRefs[4][0] = XPLMFindDataRef("sim/flightmodel/misc/machno"); // Mach Number - XPLMDataRefs[4][4] = XPLMFindDataRef("sim/flightmodel2/misc/gforce_normal"); - XPLMDataRefs[4][5] = XPLMFindDataRef("sim/flightmodel2/misc/gforce_axial"); - XPLMDataRefs[4][6] = XPLMFindDataRef("sim/flightmodel2/misc/gforce_side"); - - //Row 5: Atmosphere: Weather - XPLMDataRefs[5][0] = XPLMFindDataRef("sim/weather/barometer_sealevel_inhg"); - XPLMDataRefs[5][1] = XPLMFindDataRef("sim/weather/temperature_sealevel_c"); - XPLMDataRefs[5][3] = XPLMFindDataRef("sim/cockpit2/gauges/indicators/wind_speed_kts"); - - //Row 6: Atmosphere: Aircraft - - //Row 7: System Pressures - - //Row 8: Joystick - XPLMDataRefs[8][0] = XPLMFindDataRef("sim/joystick/yoke_pitch_ratio"); - XPLMDataRefs[8][1] = XPLMFindDataRef("sim/joystick/yoke_roll_ratio"); - XPLMDataRefs[8][2] = XPLMFindDataRef("sim/joystick/yoke_heading_ratio"); - - //Row 9: Other Flight Controls - - //Row 10: Art stab ail/elv/rud - - //Row 11: Control Surfaces - XPLMDataRefs[11][0] = XPLMFindDataRef("sim/cockpit2/controls/yoke_pitch_ratio"); //Elevator Position - XPLMDataRefs[11][1] = XPLMFindDataRef("sim/cockpit2/controls/yoke_roll_ratio"); //Aileron Position - XPLMDataRefs[11][2] = XPLMFindDataRef("sim/cockpit2/controls/yoke_heading_ratio"); //Rudder Position - XPLMDataRefs[11][3] = NULL; - XPLMDataRefs[11][4] = NULL; - XPLMDataRefs[11][5] = NULL; - XPLMDataRefs[11][6] = NULL; - XPLMDataRefs[11][7] = NULL; - - //Row 12: Wing Sweep/Trust Vec - - //Row 13: trip/flap/slat/s-brakes - XPLMDataRefs[13][3] = XPLMFindDataRef("sim/flightmodel/controls/flaprqst"); - XPLMDataRefs[13][4] = XPLMFindDataRef("sim/flightmodel/controls/flaprat");// should be equal to flap2rat - - //Row 14: Gear, Brakes - XPLMDataRefs[14][0] = XPLMFindDataRef("sim/aircraft/parts/acf_gear_deploy"); //Landing Gear-SPECIAL (Float[10]) - XPLMDataRefs[14][1] = XPLMFindDataRef("sim/flightmodel/controls/parkbrake"); //Parking Brake - XPLMDataRefs[14][2] = XPLMFindDataRef("sim/cockpit2/controls/left_brake_ratio"); - XPLMDataRefs[14][3] = XPLMFindDataRef("sim/cockpit2/controls/right_brake_ratio"); - - XPLMDataRefs[14][7] = XPLMFindDataRef("sim/cockpit/switches/gear_handle_status"); //Landing Gear Handle - - //Row 15: MNR (Angular Moments) - //READ ONLY - XPLMDataRefs[15][0] = XPLMFindDataRef("sim/flightmodel/position/M"); - XPLMDataRefs[15][1] = XPLMFindDataRef("sim/flightmodel/position/L"); - XPLMDataRefs[15][2] = XPLMFindDataRef("sim/flightmodel/position/N"); - - //Row 16: PQR (Angular Velocities) - XPLMDataRefs[16][0] = XPLMFindDataRef("sim/flightmodel/position/Qrad"); - XPLMDataRefs[16][1] = XPLMFindDataRef("sim/flightmodel/position/Prad"); - XPLMDataRefs[16][2] = XPLMFindDataRef("sim/flightmodel/position/Rrad"); - XPLMDataRefs[16][3] = XPLMFindDataRef("sim/flightmodel/position/Q"); - XPLMDataRefs[16][4] = XPLMFindDataRef("sim/flightmodel/position/P"); - XPLMDataRefs[16][5] = XPLMFindDataRef("sim/flightmodel/position/R"); - - //Row 17: Orientation: pitch, roll, yaw, heading - XPLMDataRefs[17][0] = XPLMFindDataRef("sim/flightmodel/position/theta"); //Pitch - XPLMDataRefs[17][1] = XPLMFindDataRef("sim/flightmodel/position/phi"); //roll - XPLMDataRefs[17][2] = XPLMFindDataRef("sim/flightmodel/position/psi"); //true heading (where nose is pointing) - - //READ ONLY (always) - XPLMDataRefs[17][3] = XPLMFindDataRef("sim/flightmodel/position/magpsi"); //magnetic heading - - //WRITABLE - XPLMDataRefs[17][4] = XPLMFindDataRef("sim/flightmodel/position/q"); //Quartonian - - //Row 18: Orientation: alpha beta hpath vpath slip - XPLMDataRefs[18][0] = XPLMFindDataRef("sim/flightmodel/position/alpha"); //Angle of Attack - XPLMDataRefs[18][1] = XPLMFindDataRef("sim/cockpit2/gauges/indicators/sideslip_degrees"); //fix to beta - XPLMDataRefs[18][2] = XPLMFindDataRef("sim/flightmodel/position/hpath"); //Heading the aircraft flies (velocity vector) TEST - XPLMDataRefs[18][3] = XPLMFindDataRef("sim/flightmodel/position/vpath"); //VPath TEST - XPLMDataRefs[18][7] = XPLMFindDataRef("sim/cockpit2/gauges/indicators/sideslip_degrees"); - - //Row 19: Mag Compass - XPLMDataRefs[19][0] = XPLMFindDataRef("sim/flightmodel/position/magpsi"); - - //READ ONLY - XPLMDataRefs[19][1] = XPLMFindDataRef("sim/flightmodel/position/magnetic_variation"); - - //Row 20: Global Position - //READ ONLY - XPLMDataRefs[20][0] = XPLMFindDataRef("sim/flightmodel/position/latitude"); // Read Only - XPLMDataRefs[20][1] = XPLMFindDataRef("sim/flightmodel/position/longitude"); // Read Only - XPLMDataRefs[20][3] = XPLMFindDataRef("sim/flightmodel/position/y_agl"); // Read Only - - //Row 21: Local Position, Velocity - XPLMDataRefs[21][0] = XPLMFindDataRef("sim/flightmodel/position/local_x"); - XPLMDataRefs[21][1] = XPLMFindDataRef("sim/flightmodel/position/local_y"); - XPLMDataRefs[21][2] = XPLMFindDataRef("sim/flightmodel/position/local_z"); - XPLMDataRefs[21][3] = XPLMFindDataRef("sim/flightmodel/position/local_vx"); - XPLMDataRefs[21][4] = XPLMFindDataRef("sim/flightmodel/position/local_vy"); - XPLMDataRefs[21][5] = XPLMFindDataRef("sim/flightmodel/position/local_vz"); - - //Row 22: All Planes: Lat (READ ONLY) - XPLMDataRefs[22][0] = XPLMDataRefs[20][0]; - XPLMDataRefs[22][1] = XPLMFindDataRef("sim/multiplayer/position/plane1_lat"); - XPLMDataRefs[22][2] = XPLMFindDataRef("sim/multiplayer/position/plane2_lat"); - XPLMDataRefs[22][3] = XPLMFindDataRef("sim/multiplayer/position/plane3_lat"); - XPLMDataRefs[22][4] = XPLMFindDataRef("sim/multiplayer/position/plane4_lat"); - XPLMDataRefs[22][5] = XPLMFindDataRef("sim/multiplayer/position/plane5_lat"); - XPLMDataRefs[22][6] = XPLMFindDataRef("sim/multiplayer/position/plane6_lat"); - XPLMDataRefs[22][7] = XPLMFindDataRef("sim/multiplayer/position/plane7_lat"); - - //Row 23: All Planes: Lon - XPLMDataRefs[23][0] = XPLMDataRefs[20][1]; - XPLMDataRefs[23][1] = XPLMFindDataRef("sim/multiplayer/position/plane1_lon"); - XPLMDataRefs[23][2] = XPLMFindDataRef("sim/multiplayer/position/plane2_lon"); - XPLMDataRefs[23][3] = XPLMFindDataRef("sim/multiplayer/position/plane3_lon"); - XPLMDataRefs[23][4] = XPLMFindDataRef("sim/multiplayer/position/plane4_lon"); - XPLMDataRefs[23][5] = XPLMFindDataRef("sim/multiplayer/position/plane5_lon"); - XPLMDataRefs[23][6] = XPLMFindDataRef("sim/multiplayer/position/plane6_lon"); - XPLMDataRefs[23][7] = XPLMFindDataRef("sim/multiplayer/position/plane7_lon"); - - //Row 24: All Planes: Alt - XPLMDataRefs[24][0] = XPLMDataRefs[20][2]; - XPLMDataRefs[24][1] = XPLMFindDataRef("sim/multiplayer/position/plane1_el"); - XPLMDataRefs[24][2] = XPLMFindDataRef("sim/multiplayer/position/plane2_el"); - XPLMDataRefs[24][3] = XPLMFindDataRef("sim/multiplayer/position/plane3_el"); - XPLMDataRefs[24][4] = XPLMFindDataRef("sim/multiplayer/position/plane4_el"); - XPLMDataRefs[24][5] = XPLMFindDataRef("sim/multiplayer/position/plane5_el"); - XPLMDataRefs[24][6] = XPLMFindDataRef("sim/multiplayer/position/plane6_el"); - XPLMDataRefs[24][7] = XPLMFindDataRef("sim/multiplayer/position/plane7_el"); - - //Row 25: Throttle Command - XPLMDataRefs[25][0] = XPLMFindDataRef("sim/flightmodel/engine/ENGN_thro"); //Throttle (array 8) - - //Row 26: Throttle Actual - XPLMDataRefs[26][0] = XPLMFindDataRef("sim/flightmodel2/engines/throttle_used_ratio"); // Trottle Actual (array 8) (Read Only) - - //Row 27: - - - // Multiplayer - for ( i = 1; i < 20; i++ ) - { - sprintf(multi, "sim/multiplayer/position/plane%i_x", i); // X - multiplayer[i][0] = XPLMFindDataRef(multi); - sprintf(multi, "sim/multiplayer/position/plane%i_y", i); // Y - multiplayer[i][1] = XPLMFindDataRef(multi); - sprintf(multi,"sim/multiplayer/position/plane%i_z", i); // Z - multiplayer[i][2] = XPLMFindDataRef(multi); - sprintf(multi,"sim/multiplayer/position/plane%i_the", i); // Theta (Pitch) - multiplayer[i][3] = XPLMFindDataRef(multi); - sprintf(multi,"sim/multiplayer/position/plane%i_phi", i); // Phi (Roll) - multiplayer[i][4] = XPLMFindDataRef(multi); - sprintf(multi,"sim/multiplayer/position/plane%i_psi", i); // Psi (Heading-True) - multiplayer[i][5] = XPLMFindDataRef(multi); - sprintf(multi, "sim/multiplayer/position/plane%i_gear_deploy", i); // Landing Gear - multiplayer[i][6] = XPLMFindDataRef(multi); - sprintf(multi, "sim/multiplayer/position/plane%i_flap_ratio", i); - multiplayer[i][7] = XPLMFindDataRef(multi); - sprintf(multi, "sim/multiplayer/position/plane%i_flap_ratio2", i); - multiplayer[i][8] = XPLMFindDataRef(multi); - sprintf(multi, "sim/multiplayer/position/plane%i_spoiler_ratio", i); - multiplayer[i][9] = XPLMFindDataRef(multi); - sprintf(multi, "sim/multiplayer/position/plane%i_speedbrake_ratio", i); - multiplayer[i][10] = XPLMFindDataRef(multi); - sprintf(multi, "sim/multiplayer/position/plane%i_slat_ratio", i); - multiplayer[i][11] = XPLMFindDataRef(multi); - sprintf(multi, "sim/multiplayer/position/plane%i_wing_sweep", i); - multiplayer[i][12] = XPLMFindDataRef(multi); - sprintf(multi, "sim/multiplayer/position/plane%i_throttle", i); - multiplayer[i][13] = XPLMFindDataRef(multi); - sprintf(multi, "sim/multiplayer/position/plane%i_yolk_pitch", i); - multiplayer[i][14] = XPLMFindDataRef(multi); - sprintf(multi, "sim/multiplayer/position/plane%i_yolk_roll", i); - multiplayer[i][15] = XPLMFindDataRef(multi); - sprintf(multi, "sim/multiplayer/position/plane%i_yolk_yaw", i); - multiplayer[i][16] = XPLMFindDataRef(multi); - } - AIswitch = XPLMFindDataRef("sim/operation/override/override_plane_ai_autopilot"); -} - -int fmini(int a, int b) -{ - // Returns the minimum value of two integers - return ((((a)-(b))&0x80000000) >> 31)? (a) : (b); -} - -int almostequal(float arg1, float arg2, float tol) -{ - // Compares arg1 and arg 2. If they are within tol returns true - return (abs(arg1-arg2)>8, (int) ((*sendaddr).sin_addr.s_addr&0xFF0000)>>16, (int) ((*sendaddr).sin_addr.s_addr&0xFF000000)>>24); - - return ntohs((*sendaddr).sin_port); -} - -// DEBUGGING TOOLS -// -------------------------------- -int printBufferToLog(struct XPCMessage & msg) -{ - // Prints the entire buffer to the log (for debugging) - char logmsg[350] = "[DEBUG]"; - int i; - - for (i=0;i -#include "xplaneConnect.h" -#include "XPLMDataAccess.h" - - extern XPLMDataRef XPLMDataRefs[134][8]; - extern XPLMDataRef multiplayer[20][17]; - extern XPLMDataRef AIswitch; - - struct XPCMessage - { - short connectionID; - char head[5]; - char msg[5000]; - int msglen; - struct sockaddr recvaddr; - }; - - void readMessage(struct xpcSocket * recSocket, struct XPCMessage * pMessage); - - void buildXPLMDataRefs(void); - - int almostequal(float arg1, float arg2, float tol); - - int test(const char *buffer); - - int test(int buffer); - - int updateLog(const char *buffer, int length); - - unsigned short getIP(struct sockaddr recvaddr, char *IP); - - int printBufferToLog(struct XPCMessage & msg); - - int fmini(int a, int b); - - -#endif