Merge branch 'master' into develop

# Conflicts:
#	xpcPlugin/XPlaneConnect/mac.xpl
#	xpcPlugin/xpcPlugin.xcodeproj/project.pbxproj
This commit is contained in:
Chris Teubert
2016-02-29 12:48:30 -08:00
parent 8d5af7e47e
commit cfdd183214
100 changed files with 4224 additions and 1912 deletions

View File

@@ -13,7 +13,6 @@ SET(CMAKE_CXX_COMPILER g++)
add_library(xpc64 SHARED XPCPlugin.cpp
DataManager.cpp
DataMaps.cpp
Drawing.cpp
Log.cpp
Message.cpp
@@ -24,7 +23,6 @@ set_target_properties(xpc64 PROPERTIES COMPILE_FLAGS "-m64" LINK_FLAGS "-shared
add_library(xpc32 SHARED XPCPlugin.cpp
DataManager.cpp
DataMaps.cpp
Drawing.cpp
Log.cpp
Message.cpp

View File

@@ -1,25 +1,26 @@
//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the
//National Aeronautics and Space Administration. All Rights Reserved.
// 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.
// 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 "Log.h"
#include "XPLMDataAccess.h"
#include "XPLMGraphics.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <map>
@@ -28,14 +29,17 @@ namespace XPC
{
using namespace std;
const size_t PLANE_COUNT = 20;
static map<DREF, XPLMDataRef> drefs;
static map<DREF, XPLMDataRef> mdrefs[20];
static map<DREF, XPLMDataRef> mdrefs[PLANE_COUNT];
static map<string, XPLMDataRef> sdrefs;
DREF XPData[134][8] = { DREF_None };
void DataManager::Initialize()
{
Log::WriteLine(LOG_TRACE, "DMAN", "Initializing drefs");
drefs.insert(make_pair(DREF_None, XPLMFindDataRef("sim/test/test_float")));
drefs.insert(make_pair(DREF_Pause, XPLMFindDataRef("sim/operation/override/override_planepath")));
@@ -142,7 +146,7 @@ namespace XPC
drefs.insert(make_pair(DREF_MP7Alt, XPLMFindDataRef("sim/multiplayer/position/plane7_el")));
char multi[256];
for (int i = 1; i < 20; i++)
for (int i = 1; i < PLANE_COUNT; i++)
{
sprintf(multi, "sim/multiplayer/position/plane%i_x", i);
mdrefs[i][DREF_LocalX] = XPLMFindDataRef(multi);
@@ -165,8 +169,8 @@ namespace XPC
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);
mdrefs[i][DREF_FlapSetting] = mdrefs[i][DREF_FlapActual]; // Can't set the actual flap setting on npc aircraft
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);
@@ -179,6 +183,7 @@ namespace XPC
mdrefs[i][DREF_Sweep] = XPLMFindDataRef(multi);
sprintf(multi, "sim/multiplayer/position/plane%i_throttle", i);
mdrefs[i][DREF_ThrottleActual] = XPLMFindDataRef(multi);
mdrefs[i][DREF_ThrottleSet] = mdrefs[i][DREF_ThrottleActual]; // No throttle set for multiplayer planes.
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);
@@ -299,8 +304,9 @@ namespace XPC
XPData[26][0] = DREF_ThrottleActual;
}
int DataManager::Get(string dref, float values[], int size)
int DataManager::Get(const string& dref, float values[], int size)
{
Log::WriteLine(LOG_TRACE, "DMAN", "Entered Get(string, float*, int)");
XPLMDataRef& xdref = sdrefs[dref];
if (xdref == NULL)
{
@@ -308,24 +314,18 @@ namespace XPC
}
if (!xdref) // DREF does not exist
{
#if LOG_VERBOSITY > 0
Log::FormatLine("[DMAN] ERROR: invalid DREF %s", dref.c_str());
#endif
Log::FormatLine(LOG_ERROR, "DMAN", "ERROR: invalid DREF %s", dref.c_str());
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
Log::FormatLine(LOG_INFO, "DMAN", "Get DREF %s (x:%X) Type: %i", dref.c_str(), xdref, dataType);
// 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
Log::FormatLine(LOG_INFO, "DMAN", " -- value was %f", values[0]);
return 1;
}
if ((dataType & 8) == 8) // Float array
@@ -333,99 +333,80 @@ namespace XPC
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
Log::WriteLine(LOG_WARN, "DMAN", "Warning: dref size is larger than available space");
Log::FormatLine(LOG_DEBUG, "DMAN", "Actual dref size : %i, Available size : %i", drefSize, size);
drefSize = size;
}
XPLMGetDatavf(xdref, values, 0, drefSize);
#if LOG_VERBOSITY > 4
Log::FormatLine("[DMAN] -- value count was %i", drefSize);
#endif
Log::FormatLine(LOG_INFO, "DMAN", " -- value count was %i", drefSize);
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
Log::FormatLine(LOG_INFO, "DMAN", " -- value was %f", values[0]);
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
int iValue = XPLMGetDatai(xdref);
values[0] = (float)iValue;
Log::FormatLine(LOG_INFO, "DMAN", " -- Real value was %i, cast to %f", iValue, values[0]);
return 1;
}
if ((dataType & 16) == 16) // Integer array
{
int iValues[200];
const std::size_t TMP_SIZE = 200;
int iValues[TMP_SIZE];
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
Log::WriteLine(LOG_WARN, "DMAN", "Warning: dref size is larger than available space");
Log::FormatLine(LOG_DEBUG, "DMAN", "Actual dref size : %i, Available size : %i", drefSize, size);
drefSize = size;
}
if (drefSize > 200)
if (drefSize > TMP_SIZE)
{
#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;
Log::WriteLine(LOG_WARN, "DMAN", "Warning: dref size is larger than temp buffer");
Log::FormatLine(LOG_DEBUG, "DMAN", "Actual dref size : %i, Temp buffer size: %u", drefSize, TMP_SIZE);
drefSize = TMP_SIZE;
}
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
Log::FormatLine(LOG_INFO, "DMAN", " -- value count was %i", drefSize);
return drefSize;
}
if ((dataType & 32) == 32) // Byte array
{
char bValues[1024];
const std::size_t TMP_SIZE = 1024;
char bValues[TMP_SIZE];
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
Log::WriteLine(LOG_WARN, "DMAN", "Warning: dref size is larger than available space");
Log::FormatLine(LOG_DEBUG, "DMAN", "Actual dref size : %i, Available size : %i", drefSize, size);
drefSize = size;
}
if (drefSize > 1024)
if (drefSize > TMP_SIZE)
{
#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;
Log::WriteLine(LOG_WARN, "DMAN", "Warning: dref size is larger than temp buffer");
Log::FormatLine(LOG_DEBUG, "DMAN", "Actual dref size : %i, Temp buffer size: %u", drefSize, TMP_SIZE);
drefSize = TMP_SIZE;
}
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
Log::FormatLine(LOG_INFO, "DMAN", " -- value count was %i", drefSize);
return drefSize;
}
// No match
#if LOG_VERBOSITY > 0
Log::WriteLine("[DMAN] ERROR: Unrecognized data type.");
#endif
Log::WriteLine(LOG_ERROR, "DMAN", "ERROR: Unrecognized data type.");
return 0;
}
@@ -433,9 +414,8 @@ namespace XPC
{
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
Log::FormatLine(LOG_INFO, "DMAN", "Get DREF %i (x:%X) result %f for a/c %i",
dref, xdref, value, aircraft);
return value;
}
@@ -443,9 +423,8 @@ namespace XPC
{
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
Log::FormatLine(LOG_INFO, "DMAN", "Get DREF %i (x:%X) result %f for a/c %i",
dref, xdref, value, aircraft);
return value;
}
@@ -453,9 +432,8 @@ namespace XPC
{
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
Log::FormatLine(LOG_INFO, "DMAN", "Get DREF %i (x:%X) result %i for a/c %i",
dref, xdref, value, aircraft);
return value;
}
@@ -463,9 +441,8 @@ namespace XPC
{
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
Log::FormatLine(LOG_INFO, "DMAN", "Get DREF %i (x:%X) result size %i for a/c %i",
dref, xdref, resultSize, aircraft);
return resultSize;
}
@@ -473,62 +450,66 @@ namespace XPC
{
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
Log::FormatLine(LOG_INFO, "DMAN", "Get DREF %i (x:%X) result size %i for a/c %i",
dref, xdref, resultSize, aircraft);
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
Log::FormatLine(LOG_INFO, "DMAN", "Setting DREF %i (x:%X) to %f for a/c %i",
dref, xdref, value, aircraft);
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
Log::FormatLine(LOG_INFO, "DMAN", "Setting DREF %i (x:%X) to %f for a/c %i",
dref, xdref, value, aircraft);
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
Log::FormatLine(LOG_INFO, "DMAN", "Setting DREF %i (x:%X) to %i for a/c %i",
dref, xdref, value, aircraft);
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
Log::FormatLine(LOG_INFO, "DMAN", "Setting DREF %i (x:%X) (%i values) for a/c %i",
dref, xdref, size, aircraft);
int drefSize = XPLMGetDatavf(xdref, NULL, 0, 0);
if (drefSize < size)
{
Log::FormatLine(LOG_WARN, "DMAN", "Warning: Too many values when setting DREF %i. Expected %i, got %i",
dref, drefSize, size);
}
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
Log::FormatLine(LOG_INFO, "DMAN", "Setting DREF %i (x:%X) (%i values) for a/c %i",
dref, xdref, size, aircraft);
int drefSize = XPLMGetDatavi(xdref, NULL, 0, 0);
if (drefSize < size)
{
Log::FormatLine(LOG_WARN, "DMAN", "Warning: Too many values when setting DREF %i. Expected %i, got %i",
dref, drefSize, size);
}
drefSize = min(drefSize, size);
XPLMSetDatavi(xdref, values, 0, drefSize);
}
void DataManager::Set(string dref, float values[], int size)
void DataManager::Set(const string& dref, float values[], int size)
{
XPLMDataRef& xdref = sdrefs[dref];
if (xdref == NULL)
@@ -538,149 +519,121 @@ namespace XPC
if (!xdref)
{
// DREF does not exist
#if LOG_VERBOSITY > 0
Log::FormatLine("[DMAN] ERROR: invalid DREF %s", dref.c_str());
#endif
Log::FormatLine(LOG_ERROR, "DMAN", "ERROR: invalid DREF %s", dref.c_str());
return;
}
if (isnan(values[0]))
{
#if LOG_VERBOSITY > 0
Log::WriteLine("[DMAN] ERROR: Value must be a number (NaN received)");
#endif
Log::WriteLine(LOG_ERROR, "DMAN", "ERROR: Value must be a number (NaN received)");
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
Log::FormatLine(LOG_INFO, "DMAN", "Setting DREF %s (x:%X) Type: %i", dref.c_str(), xdref, dataType);
if ((dataType & 2) == 2) // Float
{
XPLMSetDataf(xdref, values[0]);
#if LOG_VERBOSITY > 4
Log::FormatLine("[DMAN] -- value was %f", values[0]);
#endif
Log::FormatLine(LOG_INFO, "DMAN", " -- value was %f", values[0]);
}
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);
Log::WriteLine(LOG_WARN, "DMAN", "Warning: dref size is larger than actual dref size");
Log::FormatLine(LOG_DEBUG, "DMAN", "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
Log::FormatLine(LOG_INFO, "DMAN", " -- value count was %i", drefSize);
}
else if ((dataType & 4) == 4) // Double
{
XPLMSetDatad(xdref, values[0]);
#if LOG_VERBOSITY > 4
Log::FormatLine("[DMAN] -- value was %f", values[0]);
#endif
Log::FormatLine(LOG_INFO, "DMAN", " -- value was %f", values[0]);
}
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
Log::FormatLine(LOG_INFO, "DMAN", " -- value was %i", (int)values[0]);
}
else if ((dataType & 16) == 16) // Integer Array
{
int iValues[200];
const std::size_t TMP_SIZE = 200;
int iValues[TMP_SIZE];
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);
Log::WriteLine(LOG_WARN, "DMAN", "Warning: dref size is larger than actual dref size");
Log::FormatLine(LOG_DEBUG, "DMAN", "Actual dref size : %i, Provided buffer size : %i",
drefSize, size);
}
#endif
drefSize = min(drefSize, size);
if (drefSize > 200)
if (drefSize > TMP_SIZE)
{
#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;
Log::WriteLine(LOG_WARN, "DMAN", "Warning: dref size is larger temp buffer size");
Log::FormatLine(LOG_DEBUG, "DMAN", "Actual dref size : %i, Temp buffer size: %i",
drefSize, TMP_SIZE);
drefSize = TMP_SIZE;
}
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
Log::FormatLine(LOG_INFO, "DMAN", " -- value count was %i", drefSize);
}
else if ((dataType & 32) == 32) // Byte Array
{
char bValues[1024];
const std::size_t TMP_SIZE = 1024;
char bValues[TMP_SIZE];
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);
Log::WriteLine(LOG_WARN, "DMAN", "Warning: dref size is larger than actual dref size");
Log::FormatLine(LOG_DEBUG, "DMAN", "Actual dref size : %i, Provided buffer size : %i",
drefSize, size);
}
#endif
drefSize = min(drefSize, size);
if (drefSize > 1024)
if (drefSize > TMP_SIZE)
{
#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;
Log::WriteLine(LOG_WARN, "DMAN", "Warning: dref size is larger temp buffer size");
Log::FormatLine(LOG_DEBUG, "DMAN", "Actual dref size : %i, Temp buffer size: %i",
drefSize, TMP_SIZE);
drefSize = TMP_SIZE;
}
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
Log::FormatLine(LOG_INFO, "DMAN", " -- value count was %i", drefSize);
}
else
{
#if LOG_VERBOSITY > 0
Log::WriteLine("[DMAN] ERROR: Unknown type.");
#endif
Log::WriteLine(LOG_ERROR, "DMAN", "ERROR: Unknown type.");
}
#if LOG_VERBOSITY > 1
if (!XPLMCanWriteDataRef(xdref))
{
Log::WriteLine("[DMAN] WARN: dref is not writable. The write operation probably failed.");
Log::WriteLine(LOG_WARN, "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)
Log::FormatLine(LOG_INFO, "DMAN", "Setting gear (value:%f, immediate:%i) for aircraft %i",
gear, immediate, aircraft);
if ((gear < -8.5 && gear > -9.5) || IsDefault(gear))
{
#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))
if (isnan(gear) || gear < 0 || gear > 1)
{
Log::WriteLine(LOG_ERROR, "DMAN", "ERROR: Gear value must be 0 or 1");
return;
}
@@ -706,26 +659,23 @@ namespace XPC
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
Log::FormatLine(LOG_INFO, "DMAN", "Setting position (%f, %f, %f) for aircraft %i",
pos[0], pos[1], pos[2], aircraft);
if (isnan(pos[0] + pos[1] + pos[2]))
{
#if LOG_VERBOSITY > 0
Log::WriteLine("[DMAN] ERROR: Position must be a number (NaN received)");
#endif
Log::WriteLine(LOG_ERROR, "DMAN", "ERROR: Position must be a number (NaN received)");
return;
}
if (pos[0] < -997.9 && pos[0] > -999.1)
if (IsDefault(pos[0]))
{
pos[0] = (float)GetDouble(DREF_Latitude, aircraft);
}
if (pos[1] < -997.9 && pos[1] > -999.1)
if (IsDefault(pos[1]))
{
pos[1] = (float)GetDouble(DREF_Longitude, aircraft);
}
if (pos[2] < -997.9 && pos[2] > -999.1)
if (IsDefault(pos[2]))
{
pos[2] = (float)GetDouble(DREF_Elevation, aircraft);
}
@@ -738,7 +688,6 @@ namespace XPC
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);
@@ -746,27 +695,23 @@ namespace XPC
void DataManager::SetOrientation(float orient[3], char aircraft)
{
#if LOG_VERBOSITY > 3
Log::FormatLine("[DMAN] Setting orientation (%f, %f, %f) for aircraft %i",
Log::FormatLine(LOG_INFO, "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
Log::WriteLine(LOG_ERROR, "DMAN", "ERROR: Orientation must be a number (NaN received)");
return;
}
if (orient[0] < -997.9 && orient[0] > -999.1)
if (IsDefault(orient[0]))
{
orient[0] = GetFloat(DREF_Pitch, aircraft);
}
if (orient[1] < -997.9 && orient[1] > -999.1)
if (IsDefault(orient[1]))
{
orient[1] = GetFloat(DREF_Roll, aircraft);
}
if (orient[2] < -997.9 && orient[2] > -999.1)
if (IsDefault(orient[2]))
{
orient[2] = GetFloat(DREF_HeadingTrue, aircraft);
}
@@ -782,16 +727,16 @@ namespace XPC
{
// Convert to Quaternions
// from: http://www.xsquawkbox.net/xpsdk/mediawiki/MovingThePlane
// http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19770024290.pdf
// 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]);
float theta = halfRad * orient[0];
float phi = halfRad * orient[1];
float psi = halfRad * orient[2];
q[0] = cos(phi) * cos(theta) * cos(psi) + sin(phi) * sin(theta) * sin(psi);
q[1] = sin(phi) * cos(theta) * cos(psi) - cos(phi) * sin(theta) * sin(psi);
q[2] = cos(phi) * sin(theta) * cos(psi) + sin(phi) * cos(theta) * sin(psi);
q[3] = cos(phi) * cos(theta) * sin(psi) - sin(phi) * sin(theta) * cos(psi);
// If the sim is un-paused, this will overwrite the pitch/roll/yaw
// values set above.
@@ -801,14 +746,14 @@ namespace XPC
void DataManager::SetFlaps(float value)
{
Log::FormatLine(LOG_INFO, "DMAN", "Setting flaps (value:%f)", value);
if (isnan(value))
{
#if LOG_VERBOSITY > 0
Log::WriteLine("[DMAN] ERROR: Flap value must be a number (NaN received)");
#endif
Log::WriteLine(LOG_ERROR, "DMAN", "ERROR: Flap value must be a number (NaN received)");
return;
}
if (value < -997.9 && value > -999.1)
if (IsDefault(value))
{
return;
}
@@ -819,4 +764,14 @@ namespace XPC
Set(DREF_FlapSetting, value);
Set(DREF_FlapActual, value);
}
float DataManager::GetDefaultValue()
{
return -998.0F;
}
bool DataManager::IsDefault(float value)
{
return value < -997.9 && value > -999.1;
}
}

View File

@@ -1,7 +1,7 @@
//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
// Copyright (c) 2013-2015 United States Government as represented by the Administrator of the
// National Aeronautics and Space Administration. All Rights Reserved.
#ifndef XPCPLUGIN_DATAMANAGER_H_
#define XPCPLUGIN_DATAMANAGER_H_
#include <string>
@@ -62,7 +62,7 @@ namespace XPC
DREF_L,
DREF_N,
//PQR (Angular Velocities)
// PQR (Angular Velocities)
DREF_QRad = 1600,
DREF_PRad,
DREF_RRad,
@@ -139,13 +139,13 @@ namespace XPC
/// Maps X-Plane dataref lines to XPC DREF values.
extern DREF XPData[134][8];
/// Marshals data between the plugin and X-Plane.
/// Contains methods to martial data between the plugin and X-Plane.
///
/// \author Jason Watkins
/// \version 1.0.1
/// \version 1.1
/// \since 1.0.0
/// \date Intial Version: 2015-04-13
/// \date Last Updated: 2015-04-29
/// \date Last Updated: 2015-05-14
class DataManager
{
public:
@@ -165,7 +165,7 @@ namespace XPC
/// \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
/// so subsequent calls will incur minimal extra overhead compared to
/// the other methods in this class.
///
/// \remarks For simplicity, this method is provided with only one output type.
@@ -174,7 +174,7 @@ namespace XPC
/// 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);
static int Get(const std::string& dref, float values[], int size);
/// Gets the value of a double dataref.
///
@@ -294,7 +294,7 @@ namespace XPC
/// 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);
static void Set(const std::string& dref, float values[], int size);
/// Sets the value of a double dataref.
///
@@ -409,6 +409,15 @@ namespace XPC
///
/// \param value The flaps settings. Should be between 0.0 (no flaps) and 1.0 (full flaps).
static void SetFlaps(float value);
/// Gets a default value that indicates that a dataref should not be changed.
static float GetDefaultValue();
/// Checks whether the given value should be treated as a default value.
///
/// \param value The value to check.
/// \returns true if value is a default value; otherwise false.
static bool IsDefault(float value);
};
}
#endif

View File

@@ -1,19 +1,19 @@
//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the
//National Aeronautics and Space Administration. All Rights Reserved.
// 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.
// 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"
@@ -23,7 +23,7 @@
#include <cmath>
#include <string>
#include <cstring>
//OpenGL includes
// OpenGL includes
#if IBM
#include <windows.h>
#endif
@@ -31,11 +31,11 @@
# include <OpenGL/gl.h>
#else
# include <GL/gl.h>
#endif/*__APPLE__*/
#endif
namespace XPC
{
//Internal Structures
// Internal Structures
typedef struct
{
double x;
@@ -43,7 +43,7 @@ namespace XPC
double z;
} LocalPoint;
//Internal Memory
// Internal Memory
static const size_t MSG_MAX = 1024;
static const size_t MSG_LINE_MAX = MSG_MAX / 16;
static bool msgEnabled = false;
@@ -64,7 +64,9 @@ namespace XPC
XPLMDataRef planeYref;
XPLMDataRef planeZref;
//Internal Functions
// Internal Functions
/// Comparse two size_t integers. Used by qsort in RemoveWaypoints.
static int cmp(const void * a, const void * b)
{
std::size_t sa = *(size_t*)a;
@@ -80,36 +82,42 @@ namespace XPC
return 0;
}
/// Draws a cube centered at the specified OpenGL world coordinates.
///
/// \param x The X coordinate.
/// \param y The Y coordinate.
/// \param z The Z coordinate.
/// \param d The distance from the player airplane to the center of the cube.
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
// 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
// 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
// Front
glVertex3f(x - h, y - h, z + h);
glVertex3f(x + h, y - h, z + h);
//Bottom
// Bottom
glVertex3f(x - h, y - h, z - h);
glVertex3f(x + h, y - h, z - h);
//Back
// Back
glVertex3f(x - h, y + h, z - h);
glVertex3f(x + h, y + h, z - h);
glEnd();
glBegin(GL_QUADS);
//Left
// 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
// Right
glVertex3f(x + h, y + h, z + h);
glVertex3f(x + h, y + h, z - h);
glVertex3f(x + h, y - h, z - h);
@@ -118,25 +126,28 @@ namespace XPC
glEnd();
}
/// Draws the string set by the TEXT command.
static int MessageDrawCallback(XPLMDrawingPhase inPhase, int inIsBefore, void * inRefcon)
{
const int LINE_HEIGHT = 16;
XPLMDrawString(rgb, msgX, msgY, msgVal, NULL, xplmFont_Basic);
int y = msgY - 16;
int y = msgY - LINE_HEIGHT;
for (size_t i = 0; i < newLineCount; ++i)
{
XPLMDrawString(rgb, msgX, y, msgVal + newLines[i], NULL, xplmFont_Basic);
y -= 16;
y -= LINE_HEIGHT;
}
return 1;
}
/// Draws waypoints.
static int RouteDrawCallback(XPLMDrawingPhase inPhase, int inIsBefore, void * inRefcon)
{
float px = XPLMGetDataf(planeXref);
float py = XPLMGetDataf(planeYref);
float pz = XPLMGetDataf(planeZref);
//Convert to local
// Convert to local
for (size_t i = 0; i < numWaypoints; ++i)
{
Waypoint* g = &waypoints[i];
@@ -146,7 +157,7 @@ namespace XPC
}
//Draw posts
// Draw posts
glColor3f(1.0F, 1.0F, 1.0F);
glBegin(GL_LINES);
for (size_t i = 0; i < numWaypoints; ++i)
@@ -157,7 +168,7 @@ namespace XPC
}
glEnd();
//Draw route
// Draw route
glColor3f(1.0F, 0.0F, 0.0F);
glBegin(GL_LINE_STRIP);
for (size_t i = 0; i < numWaypoints; ++i)
@@ -167,7 +178,7 @@ namespace XPC
}
glEnd();
//Draw markers
// Draw markers
glColor3f(1.0F, 1.0F, 1.0F);
for (size_t i = 0; i < numWaypoints; ++i)
{
@@ -181,7 +192,7 @@ namespace XPC
return 1;
}
//Public Functions
// Public Functions
void Drawing::ClearMessage()
{
XPLMUnregisterDrawCallback(MessageDrawCallback, xplm_Phase_Window, 0, NULL);
@@ -190,8 +201,7 @@ namespace XPC
void Drawing::SetMessage(int x, int y, char* msg)
{
//Determine size of message and clear instead if the message string
//is empty.
// Determine the size of the message and clear it if it is empty.
size_t len = strnlen(msg, MSG_MAX - 1);
if (len == 0)
{
@@ -199,7 +209,7 @@ namespace XPC
return;
}
//Set the message, location, and mark new lines.
// 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)
@@ -213,7 +223,7 @@ namespace XPC
msgX = x < 0 ? 10 : x;
msgY = y < 0 ? 600 : y;
//Enable drawing if necessary
// Enable drawing if necessary
if (!msgEnabled)
{
XPLMRegisterDrawCallback(MessageDrawCallback, xplm_Phase_Window, 0, NULL);
@@ -258,7 +268,7 @@ namespace XPC
void Drawing::RemoveWaypoints(Waypoint points[], size_t numPoints)
{
//Build a list of indices of waypoints we should delete.
// 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)
@@ -276,10 +286,10 @@ namespace XPC
}
}
}
//Sort the indices so that we only have to iterate them once
// 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
// Copy the new array on top of the old array
size_t copyCur = 0;
size_t count = delPointsCur;
delPointsCur = 0;

View File

@@ -1,7 +1,7 @@
//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
// Copyright (c) 2013-2015 United States Government as represented by the Administrator of the
// National Aeronautics and Space Administration. All Rights Reserved.
#ifndef XPCPLUGIN_DRAWING_H_
#define XPCPLUGIN_DRAWING_H_
#include <cstdlib>

View File

@@ -1,17 +1,20 @@
//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the
//National Aeronautics and Space Administration. All Rights Reserved.
// 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 "XPLMUtilities.h"
#include <chrono>
#include <cstdarg>
#include <cstdio>
#include <ctime>
#ifndef LIN
#include <chrono>
#endif
#include <iomanip>
#include <sstream>
// Implementation note: I initial wrote this class using C++ iostreams, but I couldn't find any
// Implementation note: I initially 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 std::fprintf directly.
namespace XPC
@@ -19,6 +22,20 @@ namespace XPC
static std::FILE* fd;
static void WriteTime(FILE* fd)
{
#ifdef LIN
// Can't provide high resolution logging on Linux because C++11 doesn't work with X-Plane.
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);
#else
using namespace std::chrono;
system_clock::time_point now = system_clock::now();
@@ -28,17 +45,59 @@ namespace XPC
std::tm * tm = std::localtime(&now_tt);
std::stringstream ss;
ss << std::setfill('0') << "["
ss << std::setfill('0')
<< std::setw(2) << tm->tm_hour << ":"
<< std::setw(2) << tm->tm_min << ":"
<< std::setw(2) << tm->tm_sec << "."
<< std::setw(3) << ms.count() << "]";
<< std::setw(3) << ms.count() << "|";
std::fprintf(fd, ss.str().c_str());
#endif
}
void Log::Initialize(std::string version)
static void WriteLevel(FILE* fd, int level)
{
const char* str;
switch (level)
{
case LOG_OFF:
str = " OFF|";
break;
case LOG_FATAL:
str = "FATAL|";
break;
case LOG_ERROR:
str = "ERROR|";
break;
case LOG_WARN:
str = " WARN|";
break;
case LOG_INFO:
str = " INFO|";
break;
case LOG_DEBUG:
str = "DEBUG|";
break;
case LOG_TRACE:
str = "TRACE|";
break;
default:
str = " UNK|";
break;
}
std::fprintf(fd, str);
}
void Log::Initialize(const std::string& version)
{
if (LOG_LEVEL == LOG_OFF)
{
return;
}
// Note: Mode "w" deletes an existing file with the same name. This means that we only
// ever get the log from the last run. This matches the way that X-Plane treats its
// log.
fd = std::fopen("XPCLog.txt", "w");
if (fd != NULL)
{
@@ -81,35 +140,33 @@ namespace XPC
}
}
void Log::WriteLine(const std::string& value)
void Log::WriteLine(int level, const std::string& tag, const std::string& value)
{
Log::WriteLine(value.c_str());
}
void Log::WriteLine(const char* value)
{
if (!fd)
if (level > LOG_LEVEL || !fd)
{
return;
}
WriteTime(fd);
std::fprintf(fd, "%s\n", value);
WriteLevel(fd, level);
std::fprintf(fd, "%s|%s\n", tag.c_str(), value.c_str());
std::fflush(fd);
}
void Log::FormatLine(const char* format, ...)
void Log::FormatLine(int level, const std::string& tag, std::string format, ...)
{
va_list args;
if (!fd)
if (level > LOG_LEVEL || !fd)
{
return;
}
va_start(args, format);
WriteTime(fd);
std::vfprintf(fd, format, args);
WriteLevel(fd, level);
std::fprintf(fd, "%s|", tag.c_str());
std::vfprintf(fd, format.c_str(), args);
std::fprintf(fd, "\n");
std::fflush(fd);

View File

@@ -1,21 +1,28 @@
//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
// Copyright (c) 2013-2015 United States Government as represented by the Administrator of the
// National Aeronautics and Space Administration. All Rights Reserved.
#ifndef XPCPLUGIN_LOG_H_
#define XPCPLUGIN_LOG_H_
#include <string>
// 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
// OFF: No logging at all will be performed.
// FATAL: Critical errors that would normally result in termination of the program. Because XPC
// operates in the X-Plane process, we try to never actually crash. As a result, we this
// level of logging may be the only indication of a problem.
// ERROR: All errors not covered by FATAL
// WARN: Potentially, but not definitely, incorrect behavior
// INFO: Information about normal actions taken by the plugin.
// DEBUG: More verbose information usefull for debugging.
// TRACE: Log all the things!
#define LOG_OFF 0
#define LOG_FATAL 1
#define LOG_ERROR 2
#define LOG_WARN 3
#define LOG_INFO 4
#define LOG_DEBUG 5
#define LOG_TRACE 6
#define LOG_LEVEL LOG_TRACE
namespace XPC
{
@@ -23,40 +30,37 @@ namespace XPC
///
/// \details Provides functions to write lines to the XPC log file.
/// \author Jason Watkins
/// \version 1.0
/// \version 1.1
/// \since 1.0
/// \date Intial Version: 2015-04-09
/// \date Last Updated: 2015-04-09
/// \date Last Updated: 2015-05-11
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);
static void Initialize(const std::string& header);
/// Closes the log file.
static void Close();
/// Writes the C string pointed to by format, followed by a line
/// Writes the 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, ...);
///
/// \remarks Note that Visual C++ silently fails va_start when the last non-varargs
/// argument is a reference, so we need a value-type format here.
static void FormatLine(int level, const std::string& tag, const std::string 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);
static void WriteLine(int level, const std::string& tag, const std::string& value);
};
}
#endif

View File

@@ -1,8 +1,10 @@
//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the
//National Aeronautics and Space Administration. All Rights Reserved.
// 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 <cstring>
#include <iomanip>
#include <sstream>
#include <string>
@@ -11,79 +13,62 @@ namespace XPC
{
Message::Message() {}
Message Message::ReadFrom(UDPSocket& sock)
Message Message::ReadFrom(const UDPSocket& sock)
{
Message m;
int len = sock.Read(m.buffer, bufferSize, &m.source);
m.size = len < 0 ? 0 : len;
if (len > 0)
{
Log::FormatLine(LOG_TRACE, "MESG", "Read message with length %i", len);
}
return m;
}
unsigned long Message::GetMagicNumber()
std::string Message::GetHead() const
{
if (size < 4)
{
return 0;
}
return *((unsigned long*)buffer);
std::string val = size < 4 ? "" : std::string((char*)buffer, 4);
return val;
}
std::string Message::GetHead()
const unsigned char* Message::GetBuffer() const
{
if (size < 4)
{
return "";
}
return std::string((char*)buffer, 4);
const unsigned char* val = size == 0 ? NULL : buffer;
return val;
}
const unsigned char* Message::GetBuffer()
{
if (size == 0)
{
return NULL;
}
return buffer;
}
std::size_t Message::GetSize()
std::size_t Message::GetSize() const
{
return size;
}
struct sockaddr Message::GetSource()
struct sockaddr Message::GetSource() const
{
return source;
}
void Message::PrintToLog()
void Message::PrintToLog() const
{
#if LOG_VERBOSITY > 4
std::stringstream ss;
ss << "[DEBUG]";
using namespace std;
stringstream ss;
// Dump raw bytes to string
ss << std::hex << std::setfill('0');
ss << std::hex << setfill('0');
for (int i = 0; i < size; ++i)
{
ss << ' ' << std::setw(2) << static_cast<unsigned>(buffer[i]);
ss << ' ' << setw(2) << static_cast<unsigned>(buffer[i]);
}
Log::WriteLine(ss.str());
Log::WriteLine(LOG_TRACE, "DBUG", ss.str());
ss << std::dec;
std::string head = GetHead();
ss.str("");
ss << "[" << GetHead() << "-DEBUG] (" << GetSize() << ")";
switch (GetMagicNumber()) // Binary version of head
ss << "Head: " << head << std::dec << " Size: " << GetSize();
if (head == "CONN" || head == "WYPT" || head == "TEXT")
{
Log::WriteLine(LOG_DEBUG, "DBUG", ss.str());
}
else if (head == "CTRL")
{
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));
@@ -96,89 +81,91 @@ namespace XPC
{
aircraft = buffer[26];
}
ss << " Attitude:(" << pitch << " " << roll << " " << yaw << ")";
ss << " Thr:" << thr << " Gear:" << (int)gear << " Flaps:" << flaps;
Log::WriteLine(ss.str());
break;
}
case 0x41544144: // DATA
ss << " Attitude:(" << pitch << " " << roll << " " << yaw << ")";
ss << " Thr:" << thr << " Gear:" << (int)gear << " Flaps:" << flaps;
Log::WriteLine(LOG_DEBUG, "DBUG", ss.str());
}
else if (head == "DATA")
{
std::size_t numCols = (size - 5) / 36;
size_t numCols = (size - 5) / 36;
float values[32][9];
for (int i = 0; i < numCols; ++i)
{
values[i][0] = buffer[5 + 36 * i];
std::memcpy(values[i] + 1, buffer + 9 + 36 * i, 9 * sizeof(float));
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 << " (" << numCols << " lines)";
Log::WriteLine(LOG_DEBUG, "DBUG", ss.str());
for (int i = 0; i < numCols; ++i)
{
ss.str("");
ss << " #" << 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());
}
Log::WriteLine(LOG_DEBUG, "DBUG", ss.str());
}
}
else if (head == "DREF")
{
Log::WriteLine(LOG_DEBUG, "DBUG", ss.str());
string dref((char*)buffer + 6, buffer[5]);
Log::FormatLine(LOG_DEBUG, "DBUG", " DREF (size %i) = %s", dref.length(), dref.c_str());
ss.str("");
int values = buffer[6 + buffer[5]];
ss << "\tValues(size " << values << ") =";
ss << " Values(size " << values << ") =";
for (int i = 0; i < values; ++i)
{
ss << " " << *((float*)(buffer + values + 1 + sizeof(float) * i));
}
Log::WriteLine(ss.str());
break;
}
Log::WriteLine(LOG_DEBUG, "DBUG", ss.str());
}
case 0x44544547: // GETD
{
Log::WriteLine(ss.str());
else if (head == "GETC" || head == "GETP")
{
ss << " Aircraft:" << (int)buffer[5];
Log::WriteLine(LOG_DEBUG, "DBUG", ss.str());
}
else if (head == "GETD")
{
Log::WriteLine(LOG_DEBUG, "DBUG", 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());
string dref((char*)buffer + cur + 1, buffer[cur]);
Log::FormatLine(LOG_DEBUG, "DBUG", " #%i/%i (size:%i) %s",
i + 1, buffer[5], dref.length(), dref.c_str());
cur += 1 + buffer[cur];
}
break;
}
case 0x49534F50: // POSI
else if (head == "POSI")
{
char aircraft = buffer[5];
float gear = *((float*)(buffer + 30));
float pos[3];
float orient[3];
std::memcpy(pos, buffer + 6, 12);
std::memcpy(orient, buffer + 18, 12);
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;
ss << gear;
Log::WriteLine(LOG_DEBUG, "DBUG", ss.str());
}
case 0x554D4953: // SIMU
else if (head == "SIMU")
{
ss << ' ' << (int)buffer[5];
Log::WriteLine(ss.str());
break;
}
default:
{
ss << " UNKNOWN HEADER ";
Log::WriteLine(ss.str());
break;
}
ss << ' ' << (int)buffer[5];
Log::WriteLine(LOG_DEBUG, "DBUG", ss.str());
}
#endif
else if (head == "VIEW")
{
ss << "Type:" << *((unsigned long*)(buffer + 5));
Log::WriteLine(LOG_DEBUG, "DBUG", ss.str());
}
else
{
ss << " UNKNOWN HEADER ";
Log::WriteLine(LOG_DEBUG, "DBUG", ss.str());
}
}
}

View File

@@ -1,7 +1,7 @@
//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
// Copyright (c) 2013-2015 United States Government as represented by the Administrator of the
// National Aeronautics and Space Administration. All Rights Reserved.
#ifndef XPCPLUGIN_MESSAGE_H_
#define XPCPLUGIN_MESSAGE_H_
#include "UDPSocket.h"
@@ -10,10 +10,10 @@ namespace XPC
/// Represents a message received from an XPC client.
///
/// \author Jason Watkins
/// \version 1.0
/// \version 1.1
/// \since 1.0
/// \date Intial Version: 2015-04-11
/// \date Last Updated: 2015-04-11
/// \date Last Updated: 2015-05-11
class Message
{
public:
@@ -24,25 +24,25 @@ namespace XPC
/// \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);
static Message ReadFrom(const UDPSocket& sock);
/// Gets the message header in binary form.
unsigned long GetMagicNumber();
unsigned long GetMagicNumber() const;
/// Gets the message header.
std::string GetHead();
std::string GetHead() const;
/// Gets the buffer underlying the message.
const unsigned char* GetBuffer();
const unsigned char* GetBuffer() const;
/// Gets the size of the message in bytes.
std::size_t GetSize();
std::size_t GetSize() const;
/// Gets the address this message was read from.
struct sockaddr GetSource();
struct sockaddr GetSource() const;
/// Prints the contents of the message to the XPC log.
void PrintToLog();
void PrintToLog() const;
private:
Message();

View File

@@ -1,10 +1,26 @@
//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the
//National Aeronautics and Space Administration. All Rights Reserved.
// 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 "MessageHandlers.h"
#include "DataManager.h"
#include "Drawing.h"
#include "Log.h"
#include "XPLMUtilities.h"
#include <cmath>
#include <cstring>
@@ -19,6 +35,7 @@ namespace XPC
void MessageHandlers::SetSocket(UDPSocket* socket)
{
Log::WriteLine(LOG_TRACE, "MSGH", "Setting socket");
MessageHandlers::sock = socket;
}
@@ -26,6 +43,7 @@ namespace XPC
{
if (handlers.size() == 0)
{
Log::WriteLine(LOG_TRACE, "MSGH", "Initializing handlers");
// Common messages
handlers.insert(std::make_pair("CONN", MessageHandlers::HandleConn));
handlers.insert(std::make_pair("CTRL", MessageHandlers::HandleCtrl));
@@ -36,8 +54,9 @@ namespace XPC
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));
handlers.insert(std::make_pair("VIEW", MessageHandlers::HandleView));
handlers.insert(std::make_pair("GETC", MessageHandlers::HandleGetC));
handlers.insert(std::make_pair("GETP", MessageHandlers::HandleGetP));
// X-Plane data messages
handlers.insert(std::make_pair("DSEL", MessageHandlers::HandleXPlaneData));
handlers.insert(std::make_pair("USEL", MessageHandlers::HandleXPlaneData));
@@ -65,16 +84,14 @@ namespace XPC
std::string head = msg.GetHead();
if (head == "")
{
Log::WriteLine(LOG_WARN, "MSGH", "Warning: HandleMessage called with empty message.");
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
Log::FormatLine(LOG_INFO, "MSGH", "Handling message from %s", connectionKey.c_str());
std::map<std::string, ConnectionInfo>::iterator conn = connections.find(connectionKey);
if (conn == connections.end()) // New connection
{
@@ -86,19 +103,17 @@ namespace XPC
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
Log::FormatLine(LOG_DEBUG, "MSGH", "New connection. ID=%u, Remote=%s",
connection.id, connectionKey.c_str());
}
else
{
connection = (*conn).second;
#if LOG_VERBOSITY > 3
Log::FormatLine("[MSGH] Existing connection. ID=%u, Remote=%s",
Log::FormatLine(LOG_DEBUG, "MSGH", "Existing connection. ID=%u, Remote=%s",
connection.id, connectionKey.c_str());
#endif
}
msg.PrintToLog();
// Check if there is a handler for this message type. If so, execute
// that handler. Otherwise, execute the unknown message handler.
std::map<std::string, MessageHandler>::iterator iter = handlers.find(head);
@@ -113,7 +128,7 @@ namespace XPC
}
}
void MessageHandlers::HandleConn(Message& msg)
void MessageHandlers::HandleConn(const Message& msg)
{
const unsigned char* buffer = msg.GetBuffer();
@@ -122,23 +137,21 @@ namespace XPC
sockaddr* sa = &connection.addr;
switch (sa->sa_family)
{
case AF_INET:
case AF_INET: // IPV4 address
{
sockaddr_in* sin = reinterpret_cast<sockaddr_in*>(sa);
(*sin).sin_port = htons(port);
break;
}
case AF_INET6:
case AF_INET6: // IPV6 addres
{
sockaddr_in6* sin = reinterpret_cast<sockaddr_in6*>(sa);
(*sin).sin6_port = htons(port);
break;
}
default:
#if LOG_VERBOSITY > 0
Log::WriteLine("[CONN] ERROR: Unknown address type.");
Log::WriteLine(LOG_ERROR, "CONN", "ERROR: Unknown address type.");
return;
#endif
}
connections.erase(connectionKey);
connectionKey = UDPSocket::GetHost(&connection.addr);
@@ -149,31 +162,26 @@ namespace XPC
response[5] = connection.id;
// Update log
#if LOG_VERBOSITY > 1
Log::FormatLine("[CONN] ID: %u New destination port: %u",
Log::FormatLine(LOG_TRACE, "CONN", "ID: %u New destination port: %u",
connection.id, port);
#endif
// Send response
sock->SendTo(response, 6, &connection.addr);
}
void MessageHandlers::HandleCtrl(Message& msg)
void MessageHandlers::HandleCtrl(const Message& msg)
{
// Update Log
#if LOG_VERBOSITY > 2
Log::FormatLine("[CTRL] Message Received (Conn %i)", connection.id);
#endif
Log::FormatLine(LOG_TRACE, "CTRL", "Message Received (Conn %i)", connection.id);
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.
// Legacy packets that don't specify an aircraft number should be 26 bytes long.
// Packets specifying an A/C num should be 27 bytes. Packets specifying a speedbrake
// should be 31 bytes.
if (size != 26 && size != 27 && size != 31)
{
#if LOG_VERBOSITY > 0
Log::FormatLine("[CTRL] ERROR: Unexpected message length (%i)", size);
#endif
Log::FormatLine(LOG_ERROR, "CTRL", "ERROR: Unexpected message length (%i)", size);
return;
}
@@ -181,63 +189,63 @@ namespace XPC
float pitch = *((float*)(buffer + 5));
float roll = *((float*)(buffer + 9));
float yaw = *((float*)(buffer + 13));
float thr = *((float*)(buffer + 17));
float throttle = *((float*)(buffer + 17));
char gear = buffer[21];
float flaps = *((float*)(buffer + 22));
unsigned char aircraft = 0;
unsigned char aircraftNumber = 0;
if (size >= 27)
{
aircraft = buffer[26];
aircraftNumber = buffer[26];
}
float spdbrk = -998;
float spdbrk = DataManager::GetDefaultValue();
if (size >= 31)
{
spdbrk = *((float*)(buffer + 27));
}
if (pitch < -999.5 || pitch > -997.5)
if (!DataManager::IsDefault(pitch))
{
DataManager::Set(DREF_YokePitch, pitch, aircraft);
DataManager::Set(DREF_YokePitch, pitch, aircraftNumber);
}
if (roll < -999.5 || roll > -997.5)
if (!DataManager::IsDefault(roll))
{
DataManager::Set(DREF_YokeRoll, roll, aircraft);
DataManager::Set(DREF_YokeRoll, roll, aircraftNumber);
}
if (yaw < -999.5 || yaw > -997.5)
if (!DataManager::IsDefault(yaw))
{
DataManager::Set(DREF_YokeHeading, yaw, aircraft);
DataManager::Set(DREF_YokeHeading, yaw, aircraftNumber);
}
if (thr < -999.5 || thr > -997.5)
if (!DataManager::IsDefault(throttle))
{
float thrArray[8];
float throttleArray[8];
for (int i = 0; i < 8; ++i)
{
thrArray[i] = thr;
throttleArray[i] = throttle;
}
DataManager::Set(DREF_ThrottleSet, thrArray, 8, aircraft);
DataManager::Set(DREF_ThrottleActual, thrArray, 8, aircraft);
if (aircraft == 0)
DataManager::Set(DREF_ThrottleSet, throttleArray, 8, aircraftNumber);
DataManager::Set(DREF_ThrottleActual, throttleArray, 8, aircraftNumber);
if (aircraftNumber == 0)
{
DataManager::Set("sim/flightmodel/engine/ENGN_thro_override", thrArray, 1);
DataManager::Set("sim/flightmodel/engine/ENGN_thro_override", throttleArray, 1);
}
}
if (gear != -1)
{
DataManager::SetGear(gear, false, aircraft);
DataManager::SetGear(gear, false, aircraftNumber);
}
if (flaps < -999.5 || flaps > -997.5)
if (!DataManager::IsDefault(flaps))
{
DataManager::Set(DREF_FlapSetting, flaps, aircraft);
DataManager::Set(DREF_FlapSetting, flaps, aircraftNumber);
}
if (spdbrk < -999.5 || spdbrk > -997.5)
if (!DataManager::IsDefault(spdbrk))
{
DataManager::Set(DREF_SpeedBrakeSet, spdbrk, aircraft);
DataManager::Set(DREF_SpeedBrakeSet, spdbrk, aircraftNumber);
}
}
void MessageHandlers::HandleData(Message& msg)
void MessageHandlers::HandleData(const Message& msg)
{
// Parse data
const unsigned char* buffer = msg.GetBuffer();
@@ -245,59 +253,51 @@ namespace XPC
std::size_t numCols = (size - 5) / 36;
if (numCols > 0)
{
#if LOG_VERBOSITY > 1
Log::FormatLine("[DATA] Message Received (Conn %i)", connection.id);
#endif
Log::FormatLine(LOG_TRACE, "DATA", "Message Received (Conn %i)", connection.id);
}
else
{
#if LOG_VERBOSITY > 0
Log::FormatLine("[DATA] WARNING: Empty data packet received (Conn %i)", connection.id);
#endif
Log::FormatLine(LOG_WARN, "DATA", "WARNING: Empty data packet received (Conn %i)", connection.id);
return;
}
if (numCols > 134) // Error. Will overflow values
{
#if LOG_VERBOSITY > 0
Log::FormatLine("[DATA] ERROR: numCols to large.");
#endif
Log::FormatLine(LOG_ERROR, "DATA", "ERROR: numCols to large.");
return;
}
float values[134][9];
for (int i = 0; i < numCols; ++i)
{
// 5 byte header + (9 * 4 = 36) bytes per row
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;
float savedAlpha = DataManager::GetDefaultValue();
float savedHPath = DataManager::GetDefaultValue();
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
Log::FormatLine(LOG_ERROR, "DATA", "ERROR: DataRef # must be between 0 - 134 (Received: %hi)", (int)dataRef);
continue;
}
switch (dataRef)
{
// TODO(jason-watkins): This currently overwrites the velocity several times. Should look into making this case smarter somehow.
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);
float alpha = DataManager::IsDefault(savedAlpha) ? savedAlpha : DataManager::GetFloat(DREF_AngleOfAttack);
float hpath = DataManager::IsDefault(savedHPath) ? 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
Log::WriteLine(LOG_ERROR, "DATA", "ERROR: Value must be a number (NaN received)");
break;
}
const float deg2rad = 0.0174532925F;
@@ -305,7 +305,7 @@ namespace XPC
for (int j = 0; j < 3; ++j)
{
float v = values[i][ind[j]];
if (v != -998)
if (!DataManager::IsDefault(v))
{
DataManager::Set(DREF_LocalVX, v*cos((theta - alpha)*deg2rad)*sin(hpath*deg2rad));
DataManager::Set(DREF_LocalVY, v*sin((theta - alpha)*deg2rad));
@@ -316,27 +316,25 @@ namespace XPC
}
case 17: // Orientation
{
float orient[3];
orient[0] = values[i][1];
orient[1] = values[i][2];
orient[2] = values[i][3];
DataManager::SetOrientation(orient);
float orientation[3];
orientation[0] = values[i][1];
orientation[1] = values[i][2];
orientation[2] = values[i][3];
DataManager::SetOrientation(orientation);
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
Log::WriteLine(LOG_ERROR, "DATA", "ERROR: Value must be a number (NaN received)");
break;
}
if (values[i][1] != -998)
if (!DataManager::IsDefault(values[i][1]))
{
savedAlpha = values[i][1];
}
if (values[i][3] != -998)
if (DataManager::IsDefault(values[i][3]))
{
savedHPath = values[i][3];
}
@@ -355,17 +353,15 @@ namespace XPC
{
if (values[i][1] != values[i][1])
{
#if LOG_VERBOSITY > 0
Log::WriteLine("[DATA] ERROR: Value must be a number (NaN received)");
#endif
Log::WriteLine(LOG_ERROR, "DATA", "ERROR: Value must be a number (NaN received)");
break;
}
float thr[8];
float throttle[8];
for (int j = 0; j < 8; ++j)
{
thr[j] = values[i][1];
throttle[j] = values[i][1];
}
DataManager::Set(DREF_ThrottleSet, thr, 8);
DataManager::Set(DREF_ThrottleSet, throttle, 8);
break;
}
default: // Non-Special dataRefs
@@ -374,10 +370,8 @@ namespace XPC
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
Log::FormatLine(LOG_ERROR, "DATA", "Setting Dataref %i.%i to %f", dataRef, j, line[j]);
// TODO(jason-watkins): Why is this a special case?
if (dataRef == 14 && j == 0)
{
DataManager::SetGear(line[0], true);
@@ -387,7 +381,7 @@ namespace XPC
DREF dref = XPData[dataRef][j];
if (dref == DREF_None)
{
// TODO: Send single line instead!
// TODO(jason): Send single line instead!
HandleXPlaneData(msg);
}
else
@@ -400,46 +394,96 @@ namespace XPC
}
}
void MessageHandlers::HandleDref(Message& msg)
void MessageHandlers::HandleDref(const Message& msg)
{
Log::FormatLine(LOG_TRACE, "DREF", "Request to set DREF value received (Conn %i)", connection.id);
const unsigned char* buffer = msg.GetBuffer();
unsigned char len = buffer[5];
std::string dref = std::string((char*)buffer + 6, len);
std::size_t size = msg.GetSize();
std::size_t pos = 5;
while (pos < size)
{
unsigned char len = buffer[pos++];
if (pos + len > size)
{
break;
}
std::string dref = std::string((char*)buffer + pos, len);
pos += len;
unsigned char valueCount = buffer[6 + len];
float* values = (float*)(buffer + 7 + len);
unsigned char valueCount = buffer[pos++];
if (pos + 4 * valueCount > size)
{
break;
}
float* values = (float*)(buffer + pos);
pos += 4 * valueCount;
#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);
DataManager::Set(dref, values, valueCount);
Log::FormatLine(LOG_DEBUG, "DREF", "Set %d values for %s", valueCount, dref.c_str());
}
if (pos != size)
{
Log::WriteLine(LOG_ERROR, "DREF", "ERROR: Command did not terminate at the expected position.");
}
}
void MessageHandlers::HandleGetD(Message& msg)
void MessageHandlers::HandleGetC(const Message& msg)
{
const unsigned char* buffer = msg.GetBuffer();
std::size_t size = msg.GetSize();
if (size != 6)
{
Log::FormatLine(LOG_ERROR, "GCTL", "Unexpected message length: %u", size);
return;
}
unsigned char aircraft = buffer[5];
// TODO(jason-watkins): Get proper printf specifier for unsigned char
Log::FormatLine(LOG_TRACE, "GCTL", "Getting control information for aircraft %u", aircraft);
float throttle[8];
unsigned char response[31] = "CTRL";
*((float*)(response + 5)) = DataManager::GetFloat(DREF_Elevator, aircraft);
*((float*)(response + 9)) = DataManager::GetFloat(DREF_Aileron, aircraft);
*((float*)(response + 13)) = DataManager::GetFloat(DREF_Rudder, aircraft);
DataManager::GetFloatArray(DREF_ThrottleSet, throttle, 8, aircraft);
*((float*)(response + 17)) = throttle[0];
if (aircraft == 0)
{
response[21] = (char)DataManager::GetInt(DREF_GearHandle, aircraft);
}
else
{
float mpGear[10];
DataManager::GetFloatArray(DREF_GearDeploy, mpGear, 10, aircraft);
response[21] = mpGear[0] > 0.5 ? 1 : 0;
}
*((float*)(response + 22)) = DataManager::GetFloat(DREF_FlapSetting, aircraft);
response[26] = aircraft;
*((float*)(response + 27)) = DataManager::GetFloat(DREF_SpeedBrakeSet, aircraft);
sock->SendTo(response, 31, &connection.addr);
}
void MessageHandlers::HandleGetD(const 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)",
Log::FormatLine(LOG_TRACE, "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
Log::FormatLine(LOG_ERROR, "GETD", "ERROR: No previous requests from connection %i.",
connection.id);
return;
}
}
else // New request
{
#if LOG_VERBOSITY > 0
Log::FormatLine("[GETD] DATA Requested: New Request for connection %i (%i data refs)",
Log::FormatLine(LOG_TRACE, "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)
{
@@ -466,64 +510,84 @@ namespace XPC
sock->SendTo(response, cur, &connection.addr);
}
void MessageHandlers::HandlePosi(Message& msg)
void MessageHandlers::HandleGetP(const Message& msg)
{
const unsigned char* buffer = msg.GetBuffer();
std::size_t size = msg.GetSize();
if (size != 6)
{
Log::FormatLine(LOG_ERROR, "GPOS", "Unexpected message length: %u", size);
return;
}
unsigned char aircraft = buffer[5];
Log::FormatLine(LOG_TRACE, "GPOS", "Getting position information for aircraft %u", aircraft);
unsigned char response[34] = "POSI";
response[5] = (char)DataManager::GetInt(DREF_GearHandle, aircraft);
*((float*)(response + 6)) = (float)DataManager::GetDouble(DREF_Latitude, aircraft);
*((float*)(response + 10)) = (float)DataManager::GetDouble(DREF_Longitude, aircraft);
*((float*)(response + 14)) = (float)DataManager::GetDouble(DREF_Elevation, aircraft);
*((float*)(response + 18)) = DataManager::GetFloat(DREF_Pitch, aircraft);
*((float*)(response + 22)) = DataManager::GetFloat(DREF_Roll, aircraft);
*((float*)(response + 26)) = DataManager::GetFloat(DREF_HeadingTrue, aircraft);
float gear[10];
DataManager::GetFloatArray(DREF_GearDeploy, gear, 10, aircraft);
*((float*)(response + 30)) = gear[0];
sock->SendTo(response, 34, &connection.addr);
}
void MessageHandlers::HandlePosi(const Message& msg)
{
// Update log
#if LOG_VERBOSITY > 0
Log::FormatLine("[POSI] Message Received (Conn %i)", connection.id);
#endif
Log::FormatLine(LOG_TRACE, "POSI", "Message Received (Conn %i)", connection.id);
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
Log::FormatLine(LOG_ERROR, "POSI", "ERROR: Unexpected size: %i (Expected at least 34)", size);
return;
}
char aircraft = buffer[5];
char aircraftNumber = 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)
if (aircraftNumber > 0)
{
// Enable AI for the aircraft we are setting
// Enable AI for the aircraftNumber 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;
ai[aircraftNumber] = 1;
DataManager::Set(DREF_PauseAI, ai, 0, 20);
}
}
DataManager::SetPosition(pos, aircraft);
DataManager::SetOrientation(orient, aircraft);
DataManager::SetPosition(pos, aircraftNumber);
DataManager::SetOrientation(orient, aircraftNumber);
if (gear != -1)
{
DataManager::SetGear(gear, true, aircraft);
DataManager::SetGear(gear, true, aircraftNumber);
}
}
void MessageHandlers::HandleSimu(Message& msg)
void MessageHandlers::HandleSimu(const Message& msg)
{
// Update log
#if LOG_VERBOSITY > 1
Log::FormatLine("[SIMU] Message Received (Conn %i)", connection.id);
#endif
Log::FormatLine(LOG_TRACE, "SIMU", "Message Received (Conn %i)", connection.id);
char v = msg.GetBuffer()[5];
if (v < 0 || v > 2)
{
#if LOG_VERBOSITY > 0
Log::FormatLine("[SIMU] ERROR: Invalid argument: %i", v);
Log::FormatLine(LOG_ERROR, "SIMU", "ERROR: Invalid argument: %i", v);
return;
#endif
}
int value[20];
@@ -546,28 +610,24 @@ namespace XPC
// Set DREF
DataManager::Set(DREF_Pause, value, 20);
#if LOG_VERBOSITY > 2
switch (v)
{
case 0:
Log::WriteLine("[SIMU] Simulation Resumed");
Log::WriteLine(LOG_INFO, "SIMU", "Simulation resumed");
break;
case 1:
Log::WriteLine("[SIMU] Simulation Paused");
Log::WriteLine(LOG_INFO, "SIMU", "Simulation paused");
break;
case 2:
Log::WriteLine("[SIMU] Simulation switched.");
Log::FormatLine(LOG_INFO, "SIMU", "Simulation switched to %i", value[0]);
break;
}
#endif
}
void MessageHandlers::HandleText(Message& msg)
void MessageHandlers::HandleText(const Message& msg)
{
// Update Log
#if LOG_VERBOSITY > 0
Log::FormatLine("[TEXT] Message Received (Conn %i)", connection.id);
#endif
Log::FormatLine(LOG_TRACE, "TEXT", "Message Received (Conn %i)", connection.id);
std::size_t len = msg.GetSize();
const unsigned char* buffer = msg.GetBuffer();
@@ -575,18 +635,14 @@ namespace XPC
char text[256] = { 0 };
if (len < 14)
{
#if LOG_VERBOSITY > 1
Log::WriteLine("[TEXT] ERROR: Length less than 14 bytes");
#endif
Log::WriteLine(LOG_ERROR, "TEXT", "ERROR: Length less than 14 bytes");
return;
}
size_t msgLen = (unsigned char)buffer[13];
if (msgLen == 0)
{
Drawing::ClearMessage();
#if LOG_VERBOSITY > 2
Log::WriteLine("[TEXT] Text cleared");
#endif
Log::WriteLine(LOG_INFO, "TEXT", "[TEXT] Text cleared");
}
else
{
@@ -594,18 +650,30 @@ namespace XPC
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
Log::WriteLine(LOG_INFO, "TEXT", "[TEXT] Text set");
}
}
void MessageHandlers::HandleWypt(Message& msg)
void MessageHandlers::HandleView(const Message& msg)
{
// Update Log
#if LOG_VERBOSITY > 0
Log::FormatLine("[WYPT] Message Received (Conn %i)", connection.id);
#endif
Log::FormatLine(LOG_TRACE, "VIEW", "Message Received(Conn %i)", connection.id);
const std::size_t size = msg.GetSize();
if (size != 9)
{
Log::FormatLine(LOG_ERROR, "VIEW", "Error: Unexpected length. Message was %d bytes, expected 9.", size);
return;
}
const unsigned char* buffer = msg.GetBuffer();
int type = *((int*)(buffer + 5));
XPLMCommandKeyStroke(type);
}
void MessageHandlers::HandleWypt(const Message& msg)
{
// Update Log
Log::FormatLine(LOG_TRACE, "WYPT", "Message Received (Conn %i)", connection.id);
// Parse data
const unsigned char* buffer = msg.GetBuffer();
@@ -622,9 +690,7 @@ namespace XPC
}
// Perform operation
#if LOG_VERBOSITY > 2
Log::FormatLine("[WYPT] Performing operation %i", op);
#endif
Log::FormatLine(LOG_INFO, "WYPT", "Performing operation %i", op);
switch (op)
{
case 1:
@@ -637,18 +703,14 @@ namespace XPC
Drawing::ClearWaypoints();
break;
default:
#if LOG_VERBOSITY > 1
Log::FormatLine("[WYPT] ERROR: %i is not a valid operation.", op);
#endif
Log::FormatLine(LOG_ERROR, "WYPT", "ERROR: %i is not a valid operation.", op);
break;
}
}
void MessageHandlers::HandleXPlaneData(Message& msg)
void MessageHandlers::HandleXPlaneData(const Message& msg)
{
#if LOG_VERBOSITY > 1
Log::WriteLine("[MSGH] Sending raw data to X-Plane");
#endif
Log::WriteLine(LOG_TRACE, "MSGH", "Sending raw data to X - Plane");
sockaddr_in loopback;
loopback.sin_family = AF_INET;
loopback.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
@@ -656,11 +718,8 @@ namespace XPC
sock->SendTo(msg.GetBuffer(), msg.GetSize(), (sockaddr*)&loopback);
}
void MessageHandlers::HandleUnknown(Message& msg)
void MessageHandlers::HandleUnknown(const Message& msg)
{
// UPDATE LOG
#if LOG_VERBOSITY > 0
Log::FormatLine("[EXEC] ERROR: Unknown packet type %s", msg.GetHead().c_str());
#endif
Log::FormatLine(LOG_ERROR, "MSGH", "ERROR: Unknown packet type %s", msg.GetHead().c_str());
}
}

View File

@@ -1,7 +1,7 @@
//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
// Copyright (c) 2013-2015 United States Government as represented by the Administrator of the
// National Aeronautics and Space Administration. All Rights Reserved.
#ifndef XPCPLUGIN_MESSAGEHANDLERS_H_
#define XPCPLUGIN_MESSAGEHANDLERS_H_
#include "Message.h"
#include <string>
@@ -10,15 +10,15 @@
namespace XPC
{
/// A function that handles a message.
typedef void(*MessageHandler)(Message&);
typedef void(*MessageHandler)(const Message&);
/// Handles incommming messages and manages connections.
/// Handles incoming messages and manages connections.
///
/// \author Jason Watkins
/// \version 1.0
/// \version 1.1
/// \since 1.0
/// \date Intial Version: 2015-04-12
/// \date Last Updated: 2015-04-12
/// \date Last Updated: 2015-05-11
class MessageHandlers
{
public:
@@ -33,21 +33,27 @@ namespace XPC
/// \param msg The message to be processed.
static void HandleMessage(Message& msg);
/// Sets the socke that message handlers use to send responses.
/// Sets the socket 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);
// One handler per message type. Message types are descripbed on the
// wiki at https://github.com/nasa/XPlaneConnect/wiki/Network-Information
static void HandleConn(const Message& msg);
static void HandleCtrl(const Message& msg);
static void HandleData(const Message& msg);
static void HandleDref(const Message& msg);
static void HandleGetC(const Message& msg);
static void HandleGetD(const Message& msg);
static void HandleGetP(const Message& msg);
static void HandlePosi(const Message& msg);
static void HandleSimu(const Message& msg);
static void HandleText(const Message& msg);
static void HandleWypt(const Message& msg);
static void HandleView(const Message& msg);
static void HandleXPlaneData(const Message& msg);
static void HandleUnknown(const Message& msg);
typedef struct
{

View File

@@ -1,5 +1,5 @@
//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the
//National Aeronautics and Space Administration. All Rights Reserved.
// 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"
@@ -8,41 +8,37 @@
namespace XPC
{
const static std::string tag = "SOCK";
UDPSocket::UDPSocket(unsigned short recvPort)
{
#if LOG_VERBOSITY > 1
Log::FormatLine("[SOCK] Opening socket (port:%d)", recvPort);
#endif
Log::FormatLine(LOG_TRACE, tag, "Opening socket (port:%d)", recvPort);
// 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
// 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
Log::FormatLine(LOG_FATAL, tag, "ERROR: WSAStartup failed with error code %i.", startResult);
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
Log::FormatLine(LOG_FATAL, tag, "ERROR: Failed to open socket. (Error code %i)", err);
return;
}
#elif (__APPLE__ || __linux)
if ((this->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
{
Log::WriteLine("[SOCK] ERROR: Failed to open socket");
Log::WriteLine(LOG_FATAL, tag, "ERROR: Failed to open socket");
return;
}
int optval = 1;
@@ -52,39 +48,35 @@ namespace XPC
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
Log::FormatLine(LOG_FATAL, tag, "ERROR: Failed to bind socket. (Error code %i)", err);
#else
Log::WriteLine(LOG_FATAL, tag, "ERROR: Failed to bind socket.");
#endif
return;
}
//Set Timout
// 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
Log::FormatLine(LOG_ERROR, tag, "ERROR: Failed to set timeout. (Error code %i)", err);
}
#else
struct timeval tv;
tv.tv_sec = 0; /* Sec Timeout */
tv.tv_usec = usTimeOut; // Microsec Timeout
tv.tv_sec = 0;
tv.tv_usec = usTimeOut;
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
Log::FormatLine(LOG_TRACE, tag, "Closing socket (%d)", this->sock);
#ifdef _WIN32
closesocket(this->sock);
#elif (__APPLE__ || __linux)
@@ -92,7 +84,7 @@ namespace XPC
#endif
}
int UDPSocket::Read(unsigned char* dst, int maxLen, sockaddr* recvAddr)
int UDPSocket::Read(unsigned char* dst, int maxLen, sockaddr* recvAddr) const
{
socklen_t recvaddrlen = sizeof(*recvAddr);
int status = 0;
@@ -111,18 +103,16 @@ namespace XPC
FD_SET(sock, &stReadFDS);
FD_ZERO(&stExceptFDS);
FD_SET(sock, &stExceptFDS);
tv.tv_sec = 0; /* Sec Timeout */
tv.tv_usec = 250; // Microsec Timeout
tv.tv_sec = 0;
tv.tv_usec = 250;
// 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);
Log::FormatLine(LOG_ERROR, tag, "ERROR: Select failed. (Error code %i)", err);
}
#endif
if (result <= 0) // No Data or error
{
return -1;
@@ -137,22 +127,18 @@ namespace XPC
return status;
}
void UDPSocket::SendTo(const unsigned char* buffer, std::size_t len, sockaddr* remote)
void UDPSocket::SendTo(const unsigned char* buffer, std::size_t len, sockaddr* remote) const
{
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
Log::FormatLine(LOG_ERROR, tag, "Send failed. (remote: %s)", GetHost(remote).c_str());
}
else
{
#if LOG_VERBOSITY > 3
Log::FormatLine("[SOCK] Datagram sent. (remote: %s)", GetHost(remote).c_str());
#endif
Log::FormatLine(LOG_INFO, tag, "Send succeeded. (remote: %s)", GetHost(remote).c_str());
}
}
std::string UDPSocket::GetHost(sockaddr* sa)
{
char ip[INET6_ADDRSTRLEN + 6] = { 0 };

View File

@@ -1,14 +1,14 @@
//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
// Copyright (c) 2013-2015 United States Government as represented by the Administrator of the
// National Aeronautics and Space Administration. All Rights Reserved.
#ifndef XPCPLUGIN_SOCKET_H_
#define XPCPLUGIN_SOCKET_H_
#include <cstdlib>
#include <string>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib,"ws2_32.lib") //Winsock Library
#pragma comment(lib, "ws2_32.lib") // Winsock Library
#elif (__APPLE__ || __linux)
#include <sys/socket.h>
#include <netinet/in.h>
@@ -23,10 +23,10 @@ namespace XPC
/// data to XPC clients.
///
/// \author Jason Watkins
/// \version 1.0
/// \version 1.1
/// \since 1.0
/// \date Intial Version: 2015-04-10
/// \date Last Updated: 2015-04-11
/// \date Last Updated: 2015-05-11
class UDPSocket
{
public:
@@ -34,7 +34,7 @@ namespace XPC
/// specified receive port.
///
/// \param recvPort The port on which this instance will receive data.
UDPSocket(unsigned short recvPort);
explicit UDPSocket(unsigned short recvPort);
/// Closes the underlying socket for this instance.
~UDPSocket();
@@ -45,17 +45,17 @@ namespace XPC
/// \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.
/// 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);
/// an error occurs.
int Read(unsigned char* buffer, int size, sockaddr* remoteAddr) const;
/// 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);
void SendTo(const unsigned char* buffer, std::size_t len, sockaddr* remote) const;
/// Gets a string containing the IP address and port contained in the given sockaddr.
///

View File

@@ -1,58 +1,58 @@
//Copyright (c) 2013-2015 United States Government as represented by the Administrator of the
//National Aeronautics and Space Administration. All Rights Reserved.
// Copyright (c) 2013-2015 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."
// 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.
// 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
// 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
// X-Plane Connect Plugin
//
// DESCRIPTION
// XPCPlugin Facilitates Communication to and from the XPlane
// DESCRIPTION
// XPCPlugin Facilitates Communication to and from the XPlane
//
// INSTRUCTIONS
// 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.
// INSTRUCTIONS
// 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)
// CONTACT
// For questions email Christopher Teubert (christopher.a.teubert@nasa.gov)
//
// CONTRIBUTORS
// CT: Christopher Teubert (christopher.a.teubert@nasa.gov)
// JW: Jason Watkins (jason.w.watkins@nasa.gov)
// CONTRIBUTORS
// CT: Christopher Teubert (christopher.a.teubert@nasa.gov)
// JW: Jason Watkins (jason.w.watkins@nasa.gov)
// XPC Includes
#include "DataManager.h"
@@ -75,7 +75,8 @@
XPC::UDPSocket* sock = NULL;
double start,lap;
double start;
double 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
@@ -90,40 +91,37 @@ static float XPCFlightLoopCallback(float inElapsedSinceLastCall, float inElapsed
PLUGIN_API int XPluginStart(char* outName, char* outSig, char* outDesc)
{
strcpy(outName, "X-Plane Connect [Version 1.0.1]");
strcpy(outName, "X-Plane Connect [Version 1.2.0]");
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.");
#if (__APPLE__)
if ( abs(timeConvert) <= 1e-9 ) // is about 0
{
mach_timebase_info_data_t timeBase;
(void)mach_timebase_info( &timeBase );
(void)mach_timebase_info(&timeBase);
timeConvert = (double)timeBase.numer /
(double)timeBase.denom /
1000000000.0;
}
#endif
XPC::Log::Initialize("1.0.1");
XPC::Log::WriteLine("[EXEC] Plugin Start");
XPC::Log::Initialize("1.1.1");
XPC::Log::WriteLine(LOG_INFO, "EXEC", "Plugin Start");
XPC::DataManager::Initialize();
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)
{
XPLMUnregisterFlightLoopCallback(XPCFlightLoopCallback, NULL);
XPC::Log::WriteLine("[EXEC] Plugin Shutdown");
XPC::Log::WriteLine(LOG_INFO, "EXEC", "Plugin Shutdown");
XPC::Log::Close();
}
PLUGIN_API void XPluginDisable(void)
{
XPLMUnregisterFlightLoopCallback(XPCFlightLoopCallback, NULL);
// Close sockets
delete sock;
sock = NULL;
@@ -134,7 +132,7 @@ PLUGIN_API void XPluginDisable(void)
// Stop rendering waypoints to screen.
XPC::Drawing::ClearWaypoints();
XPC::Log::WriteLine("[EXEC] Plugin Disabled, sockets closed");
XPC::Log::WriteLine(LOG_INFO, "EXEC", "Plugin Disabled, sockets closed");
}
PLUGIN_API int XPluginEnable(void)
@@ -143,15 +141,17 @@ PLUGIN_API int XPluginEnable(void)
sock = new XPC::UDPSocket(RECVPORT);
XPC::MessageHandlers::SetSocket(sock);
XPC::Log::WriteLine("[EXEC] Plugin Enabled, sockets opened");
XPC::Log::WriteLine(LOG_INFO, "EXEC", "Plugin Enabled, sockets opened");
if (benchmarkingSwitch > 0)
{
XPC::Log::FormatLine("[EXEC] Benchmarking Enabled (Verbosity: %i)", benchmarkingSwitch);
XPC::Log::FormatLine(LOG_INFO, "EXEC", "Benchmarking Enabled (Verbosity: %i)", benchmarkingSwitch);
}
#if LOG_VERBOSITY > 0
XPC::Log::FormatLine("[EXEC] Debug Logging Enabled (Verbosity: %i)", LOG_VERBOSITY);
#endif
XPC::Log::FormatLine(LOG_INFO, "EXEC", "Debug Logging Enabled (Verbosity: %i)", LOG_LEVEL);
float interval = -1; // Call every frame
void* refcon = NULL; // Don't pass anything to the callback directly
XPLMRegisterFlightLoopCallback(XPCFlightLoopCallback, interval, refcon);
return 1;
}
@@ -173,7 +173,7 @@ float XPCFlightLoopCallback(float inElapsedSinceLastCall,
counter++;
if (benchmarkingSwitch > 1)
{
XPC::Log::FormatLine("Cycle time %.6f", inElapsedSinceLastCall);
XPC::Log::FormatLine(LOG_DEBUG, "EXEC", "Cycle time %.6f", inElapsedSinceLastCall);
}
for (int i = 0; i < OPS_PER_CYCLE; i++)
@@ -196,15 +196,15 @@ float XPCFlightLoopCallback(float inElapsedSinceLastCall,
{
#if (__APPLE__)
lap = (double)mach_absolute_time( ) * timeConvert;
diff_t = lap-start;
XPC::Log::FormatLine("[BENCH] Runtime %.6f",diff_t);
diff_t = lap - start;
XPC::Log::FormatLine(LOG_INFO, "EXEC", "Runtime %.6f", diff_t);
#endif
}
}
if (cyclesToClear != -1 && counter%cyclesToClear == 0)
{
XPC::Log::WriteLine("[EXEC] Cleared UDP Buffer");
XPC::Log::WriteLine(LOG_DEBUG, "EXEC", "Cleared UDP Buffer");
delete sock;
sock = new XPC::UDPSocket(RECVPORT);
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -10,7 +10,6 @@
BE37D960187C8B0F0033B082 /* XPCPlugin.cpp in Sources */ = {isa = PBXBuildFile; fileRef = BE37D95E187C8B0F0033B082 /* XPCPlugin.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 */; };
@@ -40,8 +39,6 @@
BE37D95E187C8B0F0033B082 /* XPCPlugin.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = XPCPlugin.cpp; sourceTree = SOURCE_ROOT; usesTabs = 1; };
BEABAD2B1AE041A3007BA7DA /* DataManager.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DataManager.cpp; sourceTree = "<group>"; };
BEABAD2C1AE041A3007BA7DA /* DataManager.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DataManager.h; sourceTree = "<group>"; };
BEABAD2D1AE041A3007BA7DA /* DataMaps.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = DataMaps.cpp; sourceTree = "<group>"; };
BEABAD2E1AE041A3007BA7DA /* DataMaps.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DataMaps.h; sourceTree = "<group>"; };
BEABAD2F1AE041A3007BA7DA /* Drawing.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Drawing.cpp; sourceTree = "<group>"; };
BEABAD301AE041A3007BA7DA /* Drawing.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Drawing.h; sourceTree = "<group>"; };
BEABAD311AE041A3007BA7DA /* Log.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Log.cpp; sourceTree = "<group>"; };
@@ -82,7 +79,6 @@
BE37D95E187C8B0F0033B082 /* XPCPlugin.cpp */,
BEDC620218EDF1A7005DB364 /* xplaneConnect.c */,
BEABAD2B1AE041A3007BA7DA /* DataManager.cpp */,
BEABAD2D1AE041A3007BA7DA /* DataMaps.cpp */,
BEABAD2F1AE041A3007BA7DA /* Drawing.cpp */,
BEABAD311AE041A3007BA7DA /* Log.cpp */,
BEABAD331AE041A3007BA7DA /* Message.cpp */,
@@ -97,7 +93,6 @@
children = (
BEDC620318EDF1A7005DB364 /* xplaneConnect.h */,
BEABAD2C1AE041A3007BA7DA /* DataManager.h */,
BEABAD2E1AE041A3007BA7DA /* DataMaps.h */,
BEABAD301AE041A3007BA7DA /* Drawing.h */,
BEABAD321AE041A3007BA7DA /* Log.h */,
BEABAD341AE041A3007BA7DA /* Message.h */,
@@ -192,7 +187,6 @@
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 */,
@@ -259,7 +253,7 @@
ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
CLANG_CXX_LANGUAGE_STANDARD = "c++98";
CLANG_CXX_LIBRARY = "libc++";
CONFIGURATION_BUILD_DIR = ./Mac;
CONFIGURATION_BUILD_DIR = ./XPlaneConnect;
DYLIB_COMPATIBILITY_VERSION = "";
DYLIB_CURRENT_VERSION = "";
EXECUTABLE_EXTENSION = xpl;
@@ -371,7 +365,11 @@
"$(USER_LIBRARY_DIR)/Developer/Xcode/DerivedData/xplaneConnect-asdjuezcjkhojuewbyxhyhabxfwc/Build/Products/Debug",
);
MACH_O_TYPE = mh_bundle;
<<<<<<< HEAD
ONLY_ACTIVE_ARCH = YES;
=======
ONLY_ACTIVE_ARCH = NO;
>>>>>>> master
PRODUCT_NAME = mac;
SDKROOT = macosx;
STRIP_INSTALLED_PRODUCT = YES;