FactMetaData.cc 31.3 KB
Newer Older
1 2 3 4 5 6 7 8 9
/****************************************************************************
 *
 *   (c) 2009-2016 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
 *
 * QGroundControl is licensed according to the terms in the file
 * COPYING.md in the root of the source code directory.
 *
 ****************************************************************************/

Don Gagne's avatar
Don Gagne committed
10 11 12 13 14 15 16

/// @file
///     @brief Object which exposes a FactMetaData
///
///     @author Don Gagne <don@thegagnes.com>

#include "FactMetaData.h"
17
#include "QGroundControlQmlGlobal.h"
18
#include "JsonHelper.h"
Don Gagne's avatar
Don Gagne committed
19

20
#include <QDebug>
21
#include <QtMath>
22 23
#include <QJsonParseError>
#include <QJsonArray>
24

Don Gagne's avatar
Don Gagne committed
25
#include <limits>
26 27
#include <cmath>

28 29 30 31 32 33 34 35 36 37 38
// Conversion Constants
// Time
const qreal FactMetaData::UnitConsts_s::secondsPerHour = 3600.0;

// Velocity
const qreal FactMetaData::UnitConsts_s::knotsToKPH = 1.852; // exact, hence weird base for knotsToMetersPerSecond

// Length
const qreal FactMetaData::UnitConsts_s::milesToMeters = 1609.344;
const qreal FactMetaData::UnitConsts_s::feetToMeters = 0.3048;

39 40
// Built in translations for all Facts
const FactMetaData::BuiltInTranslation_s FactMetaData::_rgBuiltInTranslations[] = {
41 42
    { "centi-degrees",  "deg",  FactMetaData::_centiDegreesToDegrees,   FactMetaData::_degreesToCentiDegrees },
    { "radians",        "deg",  FactMetaData::_radiansToDegrees,        FactMetaData::_degreesToRadians },
43
    { "norm",           "%",    FactMetaData::_normToPercent,           FactMetaData::_percentToNorm },
44
};
Don Gagne's avatar
Don Gagne committed
45

46 47 48 49 50
// Translations driven by app settings
const FactMetaData::AppSettingsTranslation_s FactMetaData::_rgAppSettingsTranslations[] = {
    { "m",      "m",        false,  QGroundControlQmlGlobal::DistanceUnitsMeters,           FactMetaData::_defaultTranslator,                   FactMetaData::_defaultTranslator },
    { "meters", "meters",   false,  QGroundControlQmlGlobal::DistanceUnitsMeters,           FactMetaData::_defaultTranslator,                   FactMetaData::_defaultTranslator },
    { "m/s",    "m/s",      true,   QGroundControlQmlGlobal::SpeedUnitsMetersPerSecond,     FactMetaData::_defaultTranslator,                   FactMetaData::_defaultTranslator },
51
    { "m^2",    "m^2",      false,  QGroundControlQmlGlobal::AreaUnitsSquareMeters,         FactMetaData::_defaultTranslator,                   FactMetaData::_defaultTranslator },
52 53
    { "m",      "ft",       false,  QGroundControlQmlGlobal::DistanceUnitsFeet,             FactMetaData::_metersToFeet,                        FactMetaData::_feetToMeters },
    { "meters", "ft",       false,  QGroundControlQmlGlobal::DistanceUnitsFeet,             FactMetaData::_metersToFeet,                        FactMetaData::_feetToMeters },
54 55 56 57 58
    { "m^2",    "km^2",     false,  QGroundControlQmlGlobal::AreaUnitsSquareKilometers,     FactMetaData::_squareMetersToSquareKilometers,      FactMetaData::_squareKilometersToSquareMeters },
    { "m^2",    "ha",       false,  QGroundControlQmlGlobal::AreaUnitsHectares,             FactMetaData::_squareMetersToHectares,              FactMetaData::_hectaresToSquareMeters },
    { "m^2",    "ft^2",     false,  QGroundControlQmlGlobal::AreaUnitsSquareFeet,           FactMetaData::_squareMetersToSquareFeet,            FactMetaData::_squareFeetToSquareMeters },
    { "m^2",    "ac",       false,  QGroundControlQmlGlobal::AreaUnitsAcres,                FactMetaData::_squareMetersToAcres,                 FactMetaData::_acresToSquareMeters },
    { "m^2",    "mi^2",     false,  QGroundControlQmlGlobal::AreaUnitsSquareMiles,          FactMetaData::_squareMetersToSquareMiles,           FactMetaData::_squareMilesToSquareMeters },
59 60 61 62 63 64
    { "m/s",    "ft/s",     true,   QGroundControlQmlGlobal::SpeedUnitsFeetPerSecond,       FactMetaData::_metersToFeet,                        FactMetaData::_feetToMeters },
    { "m/s",    "mph",      true,   QGroundControlQmlGlobal::SpeedUnitsMilesPerHour,        FactMetaData::_metersPerSecondToMilesPerHour,       FactMetaData::_milesPerHourToMetersPerSecond },
    { "m/s",    "km/h",     true,   QGroundControlQmlGlobal::SpeedUnitsKilometersPerHour,   FactMetaData::_metersPerSecondToKilometersPerHour,  FactMetaData::_kilometersPerHourToMetersPerSecond },
    { "m/s",    "kn",       true,   QGroundControlQmlGlobal::SpeedUnitsKnots,               FactMetaData::_metersPerSecondToKnots,              FactMetaData::_knotsToMetersPerSecond },
};

65 66 67 68 69 70 71 72 73 74
const char* FactMetaData::_decimalPlacesJsonKey =       "decimalPlaces";
const char* FactMetaData::_nameJsonKey =                "name";
const char* FactMetaData::_typeJsonKey =                "type";
const char* FactMetaData::_shortDescriptionJsonKey =    "shortDescription";
const char* FactMetaData::_longDescriptionJsonKey =     "longDescription";
const char* FactMetaData::_unitsJsonKey =               "units";
const char* FactMetaData::_defaultValueJsonKey =        "defaultValue";
const char* FactMetaData::_minJsonKey =                 "min";
const char* FactMetaData::_maxJsonKey =                 "max";

75 76 77
FactMetaData::FactMetaData(QObject* parent)
    : QObject(parent)
    , _type(valueTypeInt32)
78
    , _decimalPlaces(unknownDecimalPlaces)
79
    , _rawDefaultValue(0)
80
    , _defaultValueAvailable(false)
81
    , _group("*Default Group")
82
    , _rawMax(_maxForType())
83
    , _maxIsDefaultForType(true)
84
    , _rawMin(_minForType())
85
    , _minIsDefaultForType(true)
86 87
    , _rawTranslator(_defaultTranslator)
    , _cookedTranslator(_defaultTranslator)
88
    , _rebootRequired(false)
Don Gagne's avatar
Don Gagne committed
89
    , _increment(std::numeric_limits<double>::quiet_NaN())
Don Gagne's avatar
Don Gagne committed
90 91 92 93
{

}

94 95 96
FactMetaData::FactMetaData(ValueType_t type, QObject* parent)
    : QObject(parent)
    , _type(type)
97
    , _decimalPlaces(unknownDecimalPlaces)
98
    , _rawDefaultValue(0)
99
    , _defaultValueAvailable(false)
100
    , _group("*Default Group")
101
    , _rawMax(_maxForType())
102
    , _maxIsDefaultForType(true)
103
    , _rawMin(_minForType())
104
    , _minIsDefaultForType(true)
105 106
    , _rawTranslator(_defaultTranslator)
    , _cookedTranslator(_defaultTranslator)
107
    , _rebootRequired(false)
Don Gagne's avatar
Don Gagne committed
108
    , _increment(std::numeric_limits<double>::quiet_NaN())
109 110 111 112
{

}

Don Gagne's avatar
Don Gagne committed
113 114 115 116 117 118 119 120
FactMetaData::FactMetaData(const FactMetaData& other, QObject* parent)
    : QObject(parent)
{
    *this = other;
}

const FactMetaData& FactMetaData::operator=(const FactMetaData& other)
{
121
    _decimalPlaces          = other._decimalPlaces;
122
    _rawDefaultValue        = other._rawDefaultValue;
Don Gagne's avatar
Don Gagne committed
123
    _defaultValueAvailable  = other._defaultValueAvailable;
124 125
    _bitmaskStrings         = other._bitmaskStrings;
    _bitmaskValues          = other._bitmaskValues;
126 127 128 129
    _enumStrings            = other._enumStrings;
    _enumValues             = other._enumValues;
    _group                  = other._group;
    _longDescription        = other._longDescription;
130
    _rawMax                 = other._rawMax;
Don Gagne's avatar
Don Gagne committed
131
    _maxIsDefaultForType    = other._maxIsDefaultForType;
132
    _rawMin                 = other._rawMin;
133 134 135 136
    _minIsDefaultForType    = other._minIsDefaultForType;
    _name                   = other._name;
    _shortDescription       = other._shortDescription;
    _type                   = other._type;
137 138
    _rawUnits               = other._rawUnits;
    _cookedUnits            = other._cookedUnits;
139 140
    _rawTranslator          = other._rawTranslator;
    _cookedTranslator       = other._cookedTranslator;
141
    _rebootRequired         = other._rebootRequired;
Don Gagne's avatar
Don Gagne committed
142
    _increment              = other._increment;
143

Don Gagne's avatar
Don Gagne committed
144 145 146
    return *this;
}

147
QVariant FactMetaData::rawDefaultValue(void) const
148 149
{
    if (_defaultValueAvailable) {
150
        return _rawDefaultValue;
151 152 153 154 155 156
    } else {
        qWarning() << "Attempt to access unavailable default value";
        return QVariant(0);
    }
}

157
void FactMetaData::setRawDefaultValue(const QVariant& rawDefaultValue)
158
{
159 160
    if (_rawMin <= rawDefaultValue && rawDefaultValue <= _rawMax) {
        _rawDefaultValue = rawDefaultValue;
161 162 163 164 165 166
        _defaultValueAvailable = true;
    } else {
        qWarning() << "Attempt to set default value which is outside min/max range";
    }
}

167
void FactMetaData::setRawMin(const QVariant& rawMin)
168
{
Don Gagne's avatar
Don Gagne committed
169
    if (rawMin >= _minForType()) {
170
        _rawMin = rawMin;
Don Gagne's avatar
Don Gagne committed
171
        _minIsDefaultForType = false;
172
    } else {
173
        qWarning() << "Attempt to set min below allowable value for fact: " << name()
174
                   << ", value attempted: " << rawMin
175
                   << ", type: " << type() << ", min for type: " << _minForType();
176
        _rawMin = _minForType();
177 178 179
    }
}

180
void FactMetaData::setRawMax(const QVariant& rawMax)
181
{
182
    if (rawMax > _maxForType()) {
183
        qWarning() << "Attempt to set max above allowable value";
184
        _rawMax = _maxForType();
185
    } else {
186
        _rawMax = rawMax;
Don Gagne's avatar
Don Gagne committed
187
        _maxIsDefaultForType = false;
188 189 190
    }
}

191
QVariant FactMetaData::_minForType(void) const
Don Gagne's avatar
Don Gagne committed
192
{
193
    switch (_type) {
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
    case valueTypeUint8:
        return QVariant(std::numeric_limits<unsigned char>::min());
    case valueTypeInt8:
        return QVariant(std::numeric_limits<signed char>::min());
    case valueTypeUint16:
        return QVariant(std::numeric_limits<unsigned short int>::min());
    case valueTypeInt16:
        return QVariant(std::numeric_limits<short int>::min());
    case valueTypeUint32:
        return QVariant(std::numeric_limits<unsigned int>::min());
    case valueTypeInt32:
        return QVariant(std::numeric_limits<int>::min());
    case valueTypeFloat:
        return QVariant(-std::numeric_limits<float>::max());
    case valueTypeDouble:
        return QVariant(-std::numeric_limits<double>::max());
210
    }
Don Gagne's avatar
Don Gagne committed
211 212 213
    
    // Make windows compiler happy, even switch is full cased
    return QVariant();
Don Gagne's avatar
Don Gagne committed
214
}
Don Gagne's avatar
Don Gagne committed
215

216
QVariant FactMetaData::_maxForType(void) const
Don Gagne's avatar
Don Gagne committed
217
{
218
    switch (_type) {
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
    case valueTypeUint8:
        return QVariant(std::numeric_limits<unsigned char>::max());
    case valueTypeInt8:
        return QVariant(std::numeric_limits<signed char>::max());
    case valueTypeUint16:
        return QVariant(std::numeric_limits<unsigned short int>::max());
    case valueTypeInt16:
        return QVariant(std::numeric_limits<short int>::max());
    case valueTypeUint32:
        return QVariant(std::numeric_limits<unsigned int>::max());
    case valueTypeInt32:
        return QVariant(std::numeric_limits<int>::max());
    case valueTypeFloat:
        return QVariant(std::numeric_limits<float>::max());
    case valueTypeDouble:
        return QVariant(std::numeric_limits<double>::max());
235
    }
Don Gagne's avatar
Don Gagne committed
236 237 238
    
    // Make windows compiler happy, even switch is full cased
    return QVariant();
Don Gagne's avatar
Don Gagne committed
239
}
Don Gagne's avatar
Don Gagne committed
240

241
bool FactMetaData::convertAndValidateRaw(const QVariant& rawValue, bool convertOnly, QVariant& typedValue, QString& errorString)
Don Gagne's avatar
Don Gagne committed
242
{
243
    bool convertOk = false;
Don Gagne's avatar
Don Gagne committed
244 245 246 247
    
    errorString.clear();
    
    switch (type()) {
248 249 250 251 252 253 254
    case FactMetaData::valueTypeInt8:
    case FactMetaData::valueTypeInt16:
    case FactMetaData::valueTypeInt32:
        typedValue = QVariant(rawValue.toInt(&convertOk));
        if (!convertOnly && convertOk) {
            if (rawMin() > typedValue || typedValue > rawMax()) {
                errorString = QString("Value must be within %1 and %2").arg(cookedMin().toInt()).arg(cookedMax().toInt());
Don Gagne's avatar
Don Gagne committed
255
            }
256 257 258 259 260 261 262 263 264 265
        }
        break;

    case FactMetaData::valueTypeUint8:
    case FactMetaData::valueTypeUint16:
    case FactMetaData::valueTypeUint32:
        typedValue = QVariant(rawValue.toUInt(&convertOk));
        if (!convertOnly && convertOk) {
            if (rawMin() > typedValue || typedValue > rawMax()) {
                errorString = QString("Value must be within %1 and %2").arg(cookedMin().toUInt()).arg(cookedMax().toUInt());
Don Gagne's avatar
Don Gagne committed
266
            }
267 268 269 270 271 272 273 274
        }
        break;

    case FactMetaData::valueTypeFloat:
        typedValue = QVariant(rawValue.toFloat(&convertOk));
        if (!convertOnly && convertOk) {
            if (rawMin() > typedValue || typedValue > rawMax()) {
                errorString = QString("Value must be within %1 and %2").arg(cookedMin().toFloat()).arg(cookedMax().toFloat());
Don Gagne's avatar
Don Gagne committed
275
            }
276 277 278 279 280 281 282 283
        }
        break;

    case FactMetaData::valueTypeDouble:
        typedValue = QVariant(rawValue.toDouble(&convertOk));
        if (!convertOnly && convertOk) {
            if (rawMin() > typedValue || typedValue > rawMax()) {
                errorString = QString("Value must be within %1 and %2").arg(cookedMin().toDouble()).arg(cookedMax().toDouble());
Don Gagne's avatar
Don Gagne committed
284
            }
285 286
        }
        break;
Don Gagne's avatar
Don Gagne committed
287 288 289
    }
    
    if (!convertOk) {
290
        errorString += "Invalid number";
Don Gagne's avatar
Don Gagne committed
291 292 293 294
    }
    
    return convertOk && errorString.isEmpty();
}
295

296 297 298 299 300 301 302
bool FactMetaData::convertAndValidateCooked(const QVariant& cookedValue, bool convertOnly, QVariant& typedValue, QString& errorString)
{
    bool convertOk = false;

    errorString.clear();

    switch (type()) {
303 304 305 306 307 308 309
    case FactMetaData::valueTypeInt8:
    case FactMetaData::valueTypeInt16:
    case FactMetaData::valueTypeInt32:
        typedValue = QVariant(cookedValue.toInt(&convertOk));
        if (!convertOnly && convertOk) {
            if (cookedMin() > typedValue || typedValue > cookedMax()) {
                errorString = QString("Value must be within %1 and %2").arg(cookedMin().toInt()).arg(cookedMax().toInt());
310
            }
311 312 313 314 315 316 317 318 319 320
        }
        break;

    case FactMetaData::valueTypeUint8:
    case FactMetaData::valueTypeUint16:
    case FactMetaData::valueTypeUint32:
        typedValue = QVariant(cookedValue.toUInt(&convertOk));
        if (!convertOnly && convertOk) {
            if (cookedMin() > typedValue || typedValue > cookedMax()) {
                errorString = QString("Value must be within %1 and %2").arg(cookedMin().toUInt()).arg(cookedMax().toUInt());
321
            }
322 323 324 325 326 327 328 329
        }
        break;

    case FactMetaData::valueTypeFloat:
        typedValue = QVariant(cookedValue.toFloat(&convertOk));
        if (!convertOnly && convertOk) {
            if (cookedMin() > typedValue || typedValue > cookedMax()) {
                errorString = QString("Value must be within %1 and %2").arg(cookedMin().toFloat()).arg(cookedMax().toFloat());
330
            }
331 332 333 334 335 336 337 338
        }
        break;

    case FactMetaData::valueTypeDouble:
        typedValue = QVariant(cookedValue.toDouble(&convertOk));
        if (!convertOnly && convertOk) {
            if (cookedMin() > typedValue || typedValue > cookedMax()) {
                errorString = QString("Value must be within %1 and %2").arg(cookedMin().toDouble()).arg(cookedMax().toDouble());
339
            }
340 341
        }
        break;
342 343 344 345 346 347 348 349 350
    }

    if (!convertOk) {
        errorString += "Invalid number";
    }

    return convertOk && errorString.isEmpty();
}

351 352 353 354 355 356 357 358 359
void FactMetaData::setBitmaskInfo(const QStringList& strings, const QVariantList& values)
{
    if (strings.count() != values.count()) {
        qWarning() << "Count mismatch strings:values" << strings.count() << values.count();
        return;
    }

    _bitmaskStrings = strings;
    _bitmaskValues = values;
360
    setBuiltInTranslator();
361 362 363 364 365 366 367 368
}

void FactMetaData::addBitmaskInfo(const QString& name, const QVariant& value)
{
    _bitmaskStrings << name;
    _bitmaskValues << value;
}

369 370 371 372 373 374 375 376 377
void FactMetaData::setEnumInfo(const QStringList& strings, const QVariantList& values)
{
    if (strings.count() != values.count()) {
        qWarning() << "Count mismatch strings:values" << strings.count() << values.count();
        return;
    }

    _enumStrings = strings;
    _enumValues = values;
378
    setBuiltInTranslator();
379 380
}

381 382 383 384 385 386
void FactMetaData::addEnumInfo(const QString& name, const QVariant& value)
{
    _enumStrings << name;
    _enumValues << value;
}

387 388 389 390 391
void FactMetaData::setTranslators(Translator rawTranslator, Translator cookedTranslator)
{
    _rawTranslator = rawTranslator;
    _cookedTranslator = cookedTranslator;
}
392

393
void FactMetaData::setBuiltInTranslator(void)
394 395 396 397 398
{
    if (_enumStrings.count()) {
        // No translation if enum
        setTranslators(_defaultTranslator, _defaultTranslator);
        _cookedUnits = _rawUnits;
399
        return;
400
    } else {
401 402
        for (size_t i=0; i<sizeof(_rgBuiltInTranslations)/sizeof(_rgBuiltInTranslations[0]); i++) {
            const BuiltInTranslation_s* pBuiltInTranslation = &_rgBuiltInTranslations[i];
403 404 405 406

            if (pBuiltInTranslation->rawUnits == _rawUnits.toLower()) {
                _cookedUnits = pBuiltInTranslation->cookedUnits;
                setTranslators(pBuiltInTranslation->rawTranslator, pBuiltInTranslation->cookedTranslator);
407
                return;
408 409 410
            }
        }
    }
411 412 413

    // Translator not yet set, try app settings translators
    _setAppSettingsTranslators();
414 415 416 417
}

QVariant FactMetaData::_degreesToRadians(const QVariant& degrees)
{
418
    return QVariant(qDegreesToRadians(degrees.toDouble()));
419 420 421 422
}

QVariant FactMetaData::_radiansToDegrees(const QVariant& radians)
{
423
    return QVariant(qRadiansToDegrees(radians.toDouble()));
424 425 426 427
}

QVariant FactMetaData::_centiDegreesToDegrees(const QVariant& centiDegrees)
{
428
    return QVariant(centiDegrees.toReal() / 100.0);
429 430 431 432
}

QVariant FactMetaData::_degreesToCentiDegrees(const QVariant& degrees)
{
433
    return QVariant(qRound(degrees.toReal() * 100.0));
434 435
}

436 437
QVariant FactMetaData::_metersToFeet(const QVariant& meters)
{
438
    return QVariant(meters.toDouble() * 1.0/constants.feetToMeters);
439 440 441 442
}

QVariant FactMetaData::_feetToMeters(const QVariant& feet)
{
443
    return QVariant(feet.toDouble() * constants.feetToMeters);
444 445
}

446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
QVariant FactMetaData::_squareMetersToSquareKilometers(const QVariant& squareMeters)
{
    return QVariant(squareMeters.toDouble() * 0.000001);
}

QVariant FactMetaData::_squareKilometersToSquareMeters(const QVariant& squareKilometers)
{
    return QVariant(squareKilometers.toDouble() * 1000000.0);
}

QVariant FactMetaData::_squareMetersToHectares(const QVariant& squareMeters)
{
    return QVariant(squareMeters.toDouble() * 0.0001);
}

QVariant FactMetaData::_hectaresToSquareMeters(const QVariant& hectares)
{
    return QVariant(hectares.toDouble() * 1000.0);
}

QVariant FactMetaData::_squareMetersToSquareFeet(const QVariant& squareMeters)
{
    return QVariant(squareMeters.toDouble() * 10.7639);
}

QVariant FactMetaData::_squareFeetToSquareMeters(const QVariant& squareFeet)
{
    return QVariant(squareFeet.toDouble() * 0.0929);
}

QVariant FactMetaData::_squareMetersToAcres(const QVariant& squareMeters)
{
    return QVariant(squareMeters.toDouble() * 0.000247105);
}

QVariant FactMetaData::_acresToSquareMeters(const QVariant& acres)
{
    return QVariant(acres.toDouble() * 4046.86);
}

QVariant FactMetaData::_squareMetersToSquareMiles(const QVariant& squareMeters)
{
    return QVariant(squareMeters.toDouble() * 3.86102e-7);
}

QVariant FactMetaData::_squareMilesToSquareMeters(const QVariant& squareMiles)
{
    return QVariant(squareMiles.toDouble() * 258999039.98855);
}

496 497
QVariant FactMetaData::_metersPerSecondToMilesPerHour(const QVariant& metersPerSecond)
{
498
    return QVariant((metersPerSecond.toDouble() * 1.0/constants.milesToMeters) * constants.secondsPerHour);
499 500 501 502
}

QVariant FactMetaData::_milesPerHourToMetersPerSecond(const QVariant& milesPerHour)
{
503
    return QVariant((milesPerHour.toDouble() * constants.milesToMeters) / constants.secondsPerHour);
504 505 506 507
}

QVariant FactMetaData::_metersPerSecondToKilometersPerHour(const QVariant& metersPerSecond)
{
508
    return QVariant((metersPerSecond.toDouble() / 1000.0) * constants.secondsPerHour);
509 510 511 512
}

QVariant FactMetaData::_kilometersPerHourToMetersPerSecond(const QVariant& kilometersPerHour)
{
513
    return QVariant((kilometersPerHour.toDouble() * 1000.0) / constants.secondsPerHour);
514 515 516 517
}

QVariant FactMetaData::_metersPerSecondToKnots(const QVariant& metersPerSecond)
{
518
    return QVariant(metersPerSecond.toDouble() * constants.secondsPerHour / (1000.0 * constants.knotsToKPH));
519 520 521 522
}

QVariant FactMetaData::_knotsToMetersPerSecond(const QVariant& knots)
{
523
    return QVariant(knots.toDouble() * (1000.0 * constants.knotsToKPH / constants.secondsPerHour));
524 525
}

526 527 528 529 530 531 532 533 534 535
QVariant FactMetaData::_percentToNorm(const QVariant& percent)
{
    return QVariant(percent.toDouble() / 100.0);
}

QVariant FactMetaData::_normToPercent(const QVariant& normalized)
{
    return QVariant(normalized.toDouble() * 100.0);
}

536 537 538 539 540
void FactMetaData::setRawUnits(const QString& rawUnits)
{
    _rawUnits = rawUnits;
    _cookedUnits = rawUnits;

541
    setBuiltInTranslator();
542
}
Don Gagne's avatar
Don Gagne committed
543 544 545 546 547 548 549 550 551

FactMetaData::ValueType_t FactMetaData::stringToType(const QString& typeString, bool& unknownType)
{
    QStringList         knownTypeStrings;
    QList<ValueType_t>  knownTypes;

    unknownType = false;

    knownTypeStrings << QStringLiteral("Uint8")
552 553 554 555 556 557 558
                     << QStringLiteral("Int8")
                     << QStringLiteral("Uint16")
                     << QStringLiteral("Int16")
                     << QStringLiteral("Uint32")
                     << QStringLiteral("Int32")
                     << QStringLiteral("Float")
                     << QStringLiteral("Double");
Don Gagne's avatar
Don Gagne committed
559 560

    knownTypes << valueTypeUint8
561 562 563 564 565 566 567
               << valueTypeInt8
               << valueTypeUint16
               << valueTypeInt16
               << valueTypeUint32
               << valueTypeInt32
               << valueTypeFloat
               << valueTypeDouble;
Don Gagne's avatar
Don Gagne committed
568 569 570 571 572 573 574 575 576 577 578

    for (int i=0; i<knownTypeStrings.count(); i++) {
        if (knownTypeStrings[i].compare(typeString, Qt::CaseInsensitive) == 0) {
            return knownTypes[i];
        }
    }

    unknownType = true;

    return valueTypeDouble;
}
579 580 581 582

size_t FactMetaData::typeToSize(ValueType_t type)
{
    switch (type) {
583 584 585
    case valueTypeUint8:
    case valueTypeInt8:
        return 1;
586

587 588 589
    case valueTypeUint16:
    case valueTypeInt16:
        return 2;
590

591 592 593 594
    case valueTypeUint32:
    case valueTypeInt32:
    case valueTypeFloat:
        return 4;
595

596 597
    case valueTypeDouble:
        return 8;
598

599 600 601
    default:
        qWarning() << "Unsupported fact value type" << type;
        return 4;
602 603
    }
}
604

605 606 607

/// Set translators according to app settings
void FactMetaData::_setAppSettingsTranslators(void)
608
{
609 610
    // We can only translate between real numbers
    if (!_enumStrings.count() && (type() == valueTypeDouble || type() == valueTypeFloat)) {
611 612 613 614 615 616 617 618 619 620 621 622 623
        for (size_t i=0; i<sizeof(_rgAppSettingsTranslations)/sizeof(_rgAppSettingsTranslations[0]); i++) {
            const AppSettingsTranslation_s* pAppSettingsTranslation = &_rgAppSettingsTranslations[i];

            if (pAppSettingsTranslation->rawUnits == _rawUnits.toLower() &&
                    ((pAppSettingsTranslation->speed && pAppSettingsTranslation->speedOrDistanceUnits == QGroundControlQmlGlobal::speedUnits()->rawValue().toUInt()) ||
                     (!pAppSettingsTranslation->speed && pAppSettingsTranslation->speedOrDistanceUnits == QGroundControlQmlGlobal::distanceUnits()->rawValue().toUInt()))) {
                _cookedUnits = pAppSettingsTranslation->cookedUnits;
                setTranslators(pAppSettingsTranslation->rawTranslator, pAppSettingsTranslation->cookedTranslator);
                return;
            }
        }
    }
}
624 625 626 627 628 629 630

const FactMetaData::AppSettingsTranslation_s* FactMetaData::_findAppSettingsDistanceUnitsTranslation(const QString& rawUnits)
{
    for (size_t i=0; i<sizeof(_rgAppSettingsTranslations)/sizeof(_rgAppSettingsTranslations[0]); i++) {
        const AppSettingsTranslation_s* pAppSettingsTranslation = &_rgAppSettingsTranslations[i];

        if (pAppSettingsTranslation->rawUnits == rawUnits &&
631
                (!pAppSettingsTranslation->speed && pAppSettingsTranslation->speedOrDistanceUnits == QGroundControlQmlGlobal::distanceUnits()->rawValue().toUInt())) {
632 633 634 635 636 637 638
            return pAppSettingsTranslation;
        }
    }

    return NULL;
}

639 640 641 642 643 644
const FactMetaData::AppSettingsTranslation_s* FactMetaData::_findAppSettingsAreaUnitsTranslation(const QString& rawUnits)
{
    for (size_t i=0; i<sizeof(_rgAppSettingsTranslations)/sizeof(_rgAppSettingsTranslations[0]); i++) {
        const AppSettingsTranslation_s* pAppSettingsTranslation = &_rgAppSettingsTranslations[i];

        if (pAppSettingsTranslation->rawUnits == rawUnits &&
645
                (!pAppSettingsTranslation->speed && pAppSettingsTranslation->speedOrDistanceUnits == QGroundControlQmlGlobal::areaUnits()->rawValue().toUInt())
646 647 648 649 650 651 652 653
                ) {
            return pAppSettingsTranslation;
        }
    }

    return NULL;
}

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
QVariant FactMetaData::metersToAppSettingsDistanceUnits(const QVariant& meters)
{
    const AppSettingsTranslation_s* pAppSettingsTranslation = _findAppSettingsDistanceUnitsTranslation("m");
    if (pAppSettingsTranslation) {
        return pAppSettingsTranslation->rawTranslator(meters);
    } else {
        return meters;
    }
}

QVariant FactMetaData::appSettingsDistanceUnitsToMeters(const QVariant& distance)
{
    const AppSettingsTranslation_s* pAppSettingsTranslation = _findAppSettingsDistanceUnitsTranslation("m");
    if (pAppSettingsTranslation) {
        return pAppSettingsTranslation->cookedTranslator(distance);
    } else {
        return distance;
    }
}

QString FactMetaData::appSettingsDistanceUnitsString(void)
{
    const AppSettingsTranslation_s* pAppSettingsTranslation = _findAppSettingsDistanceUnitsTranslation("m");
    if (pAppSettingsTranslation) {
        return pAppSettingsTranslation->cookedUnits;
    } else {
        return QStringLiteral("m");
    }
}
683

684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
QVariant FactMetaData::squareMetersToAppSettingsAreaUnits(const QVariant& squareMeters)
{
    const AppSettingsTranslation_s* pAppSettingsTranslation = _findAppSettingsAreaUnitsTranslation("m^2");
    if (pAppSettingsTranslation) {
        return pAppSettingsTranslation->rawTranslator(squareMeters);
    } else {
        return squareMeters;
    }
}

QVariant FactMetaData::appSettingsAreaUnitsToSquareMeters(const QVariant& area)
{
    const AppSettingsTranslation_s* pAppSettingsTranslation = _findAppSettingsAreaUnitsTranslation("m^2");
    if (pAppSettingsTranslation) {
        return pAppSettingsTranslation->cookedTranslator(area);
    } else {
        return area;
    }
}

QString FactMetaData::appSettingsAreaUnitsString(void)
{
    const AppSettingsTranslation_s* pAppSettingsTranslation = _findAppSettingsAreaUnitsTranslation("m^2");
    if (pAppSettingsTranslation) {
        return pAppSettingsTranslation->cookedUnits;
    } else {
        return QStringLiteral("m^2");
    }
}

714 715 716 717 718 719
int FactMetaData::decimalPlaces(void) const
{
    int actualDecimalPlaces = defaultDecimalPlaces;
    int incrementDecimalPlaces = unknownDecimalPlaces;

    // First determine decimal places from increment
720
    double increment = _rawTranslator(this->increment()).toDouble();
721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
    if (!qIsNaN(increment)) {
        double integralPart;

        // Get the fractional part only
        increment = fabs(modf(increment, &integralPart));
        if (increment == 0.0) {
            // No fractional part, so no decimal places
            incrementDecimalPlaces = 0;
        } else {
            incrementDecimalPlaces = -ceil(log10(increment));
        }
    }

    // Correct decimal places is the larger of the two, increment or meta data value
    if (incrementDecimalPlaces != unknownDecimalPlaces && _decimalPlaces == unknownDecimalPlaces) {
        actualDecimalPlaces = incrementDecimalPlaces;
    } else {
738 739
        // Adjust decimal places for cooked translation
        int settingsDecimalPlaces = _decimalPlaces == unknownDecimalPlaces ? defaultDecimalPlaces : _decimalPlaces;
740 741 742 743 744 745 746 747
        double ctest = _rawTranslator(1.0).toDouble();

        settingsDecimalPlaces += -log10(ctest);

        settingsDecimalPlaces = qMin(25, settingsDecimalPlaces);
        settingsDecimalPlaces = qMax(0, settingsDecimalPlaces);

        actualDecimalPlaces = qMax(settingsDecimalPlaces, incrementDecimalPlaces);
748 749 750 751
    }

    return actualDecimalPlaces;
}
752

753
FactMetaData* FactMetaData::createFromJsonObject(const QJsonObject& json, QObject* metaDataParent)
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857
{
    QString         errorString;

    // Make sure we have the required keys
    QStringList requiredKeys;
    requiredKeys << _nameJsonKey << _typeJsonKey;
    if (!JsonHelper::validateRequiredKeys(json, requiredKeys, errorString)) {
        qWarning() << errorString;
        return new FactMetaData(valueTypeUint32, metaDataParent);
    }

    // Validate key types
    QStringList             keys;
    QList<QJsonValue::Type> types;
    keys << _nameJsonKey << _decimalPlacesJsonKey << _typeJsonKey << _shortDescriptionJsonKey << _longDescriptionJsonKey << _unitsJsonKey << _defaultValueJsonKey << _minJsonKey << _maxJsonKey;
    types << QJsonValue::String << QJsonValue::Double << QJsonValue::String << QJsonValue::String << QJsonValue::String << QJsonValue::String << QJsonValue::Double << QJsonValue::Double << QJsonValue::Double;
    if (!JsonHelper::validateKeyTypes(json, keys, types, errorString)) {
        qWarning() << errorString;
        return new FactMetaData(valueTypeUint32, metaDataParent);
    }

    bool unknownType;
    FactMetaData::ValueType_t type = FactMetaData::stringToType(json[_typeJsonKey].toString(), unknownType);
    if (unknownType) {
        qWarning() << "Unknown type" << json[_typeJsonKey].toString();
        return new FactMetaData(valueTypeUint32, metaDataParent);
    }

    FactMetaData*   metaData = new FactMetaData(type, metaDataParent);

    metaData->_name = json[_nameJsonKey].toString();

    QStringList enumValues, enumStrings;
    if (JsonHelper::parseEnum(json, enumStrings, enumValues, errorString)) {
        for (int i=0; i<enumValues.count(); i++) {
            QVariant    enumVariant;
            QString     errorString;

            if (metaData->convertAndValidateRaw(enumValues[i], false /* validate */, enumVariant, errorString)) {
                metaData->addEnumInfo(enumStrings[i], enumVariant);
            } else {
                qWarning() << "Invalid enum value, name:" << metaData->name()
                           << " type:" << metaData->type()
                           << " value:" << enumValues[i]
                           << " error:" << errorString;
            }
        }
    } else {
        qWarning() << errorString;
    }

    metaData->setDecimalPlaces(json[_decimalPlacesJsonKey].toInt(0));
    metaData->setShortDescription(json[_shortDescriptionJsonKey].toString());
    metaData->setLongDescription(json[_longDescriptionJsonKey].toString());

    if (json.contains(_unitsJsonKey)) {
        metaData->setRawUnits(json[_unitsJsonKey].toString());
    }
    if (json.contains(_defaultValueJsonKey)) {
        metaData->setRawDefaultValue(json[_defaultValueJsonKey].toDouble());
    }
    if (json.contains(_minJsonKey)) {
        metaData->setRawMin(json[_minJsonKey].toDouble());
    }
    if (json.contains(_maxJsonKey)) {
        metaData->setRawMax(json[_maxJsonKey].toDouble());
    }

    return metaData;
}

QMap<QString, FactMetaData*> FactMetaData::createMapFromJsonFile(const QString& jsonFilename, QObject* metaDataParent)
{
    QMap<QString, FactMetaData*> metaDataMap;

    QFile jsonFile(jsonFilename);
    if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Unable to open file" << jsonFilename << jsonFile.errorString();
        return metaDataMap;
    }

    QByteArray bytes = jsonFile.readAll();
    jsonFile.close();
    QJsonParseError jsonParseError;
    QJsonDocument doc = QJsonDocument::fromJson(bytes, &jsonParseError);
    if (jsonParseError.error != QJsonParseError::NoError) {
        qWarning() <<  "Unable to parse json document" << jsonFilename << jsonParseError.errorString();
        return metaDataMap;
    }

    if (!doc.isArray()) {
        qWarning() << "json document is not array";
        return metaDataMap;
    }

    QJsonArray jsonArray = doc.array();
    for (int i=0; i<jsonArray.count(); i++) {
        QJsonValueRef jsonValue = jsonArray[i];

        if (!jsonValue.isObject()) {
            qWarning() << QStringLiteral("JsonValue at index %1 not an object").arg(i);
            continue;
        }
        QJsonObject jsonObject = jsonValue.toObject();
858
        FactMetaData* metaData = createFromJsonObject(jsonObject, metaDataParent);
859 860 861 862 863 864 865 866 867 868

        if (metaDataMap.contains(metaData->name())) {
            qWarning() << QStringLiteral("Duplicate fact name:") << metaData->name();
        } else {
            metaDataMap[metaData->name()] = metaData;
        }
    }

    return metaDataMap;
}