The xplane_io (X-Plane I/O) program is used to establish network communications, via UDP, with the X-Plane flight simulator running on a computer. The code consists of class libraries that abstract the lower-level UDP packet encoding and decoding details, according to the UDP protocol specifications in X-Plane version 9. Any X-Plane DATA packets can be sent and received, and any X-Plane DataRefs can be set by sending DREF packets to X-Plane.

Dependencies:   EthernetNetIf mbed ConfigFile

XPlaneUdp/XPlaneUdpEncoder.cpp

Committer:
bapowell
Date:
2011-12-21
Revision:
0:a5d13af495af

File content as of revision 0:a5d13af495af:

#include <stdio.h>
#include <string.h>
#include "XPlaneUdp.h"
#include "XPlaneUdpEncoder.h"
#include "XPlaneUdpDATA.h"

void XPlaneUdpEncoder::setDebug(bool debug) {
    _debug = debug;
}

int XPlaneUdpEncoder::encodeFromDATAMap(char * udpBuffer, int maxBufferLen, XPlaneUdpDATAMap & DATAMap, bool changedDataOnly) {
    if (maxBufferLen < 5  ||  DATAMap.size() == 0) {
        return 0;
    }

    strcpy(udpBuffer, "DATA");
    int bufOffset = 5;

    for (XPlaneUdpDATAMap::iterator it = DATAMap.begin(); it != DATAMap.end(); it++) {
        if ((bufOffset + XPLANE_DATA_MSG_LENGTH) > maxBufferLen) {
            break;
        }
        else {
            XPlaneUdpDATA * DATAmsg = it->second;
            if ((!changedDataOnly) || DATAmsg->isDataChanged()) {
                DATAmsg->populateDATAMessage(udpBuffer + bufOffset);
                bufOffset += XPLANE_DATA_MSG_LENGTH;
            }
        }
    }

    if (_debug) printf("encodeFromDATAMap(): Encoded %d bytes into UDP buffer \n", bufOffset);

    return bufOffset;
}


int XPlaneUdpEncoder::encodeDataRef(char * udpBuffer, int maxBufferLen, XPlaneUdpDREF & dref) {
    if (maxBufferLen < DATAREF_PACKET_SIZE) {
        return 0;
    }

    memset(udpBuffer, '\0' , DATAREF_PACKET_SIZE);      // zero out the buffer
    
    strcpy(udpBuffer, "DREF");
    int bufOffset = 5;

    dref.populateDREFMessage(udpBuffer + bufOffset);

    if (_debug) {
        printf("encodeDataRef(): Encoded DREF packet into UDP buffer: ");
        dref.toString(stdout);
        printf("\n");
    }

    return DATAREF_PACKET_SIZE;
}