GeoFenceController.cc 13.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/****************************************************************************
 *
 *   (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.
 *
 ****************************************************************************/


/// @file
///     @author Don Gagne <don@thegagnes.com>

#include "GeoFenceController.h"
#include "Vehicle.h"
#include "FirmwarePlugin.h"
#include "MAVLinkProtocol.h"
#include "QGCApplication.h"
19 20
#include "ParameterManager.h"
#include "JsonHelper.h"
21
#include "QGCQGeoCoordinate.h"
22
#include "AppSettings.h"
Don Gagne's avatar
Don Gagne committed
23 24

#ifndef __mobile__
25
#include "MainWindow.h"
26
#include "QGCQFileDialog.h"
Don Gagne's avatar
Don Gagne committed
27
#endif
28 29

#include <QJsonDocument>
30
#include <QJsonArray>
31 32 33

QGC_LOGGING_CATEGORY(GeoFenceControllerLog, "GeoFenceControllerLog")

34 35
const char* GeoFenceController::_jsonFileTypeValue =    "GeoFence";
const char* GeoFenceController::_jsonBreachReturnKey =  "breachReturn";
36

37 38 39
GeoFenceController::GeoFenceController(QObject* parent)
    : PlanElementController(parent)
    , _dirty(false)
40
    , _mapPolygon(this)
41
{
42 43
    connect(_mapPolygon.qmlPathModel(), &QmlObjectListModel::countChanged, this, &GeoFenceController::_updateContainsItems);
    connect(_mapPolygon.qmlPathModel(), &QmlObjectListModel::dirtyChanged, this, &GeoFenceController::_polygonDirtyChanged);
44 45 46 47 48 49 50 51 52 53 54 55
}

GeoFenceController::~GeoFenceController()
{

}

void GeoFenceController::start(bool editMode)
{
    qCDebug(GeoFenceControllerLog) << "start editMode" << editMode;

    PlanElementController::start(editMode);
56 57 58 59 60 61
    _init();
}

void GeoFenceController::startStaticActiveVehicle(Vehicle* vehicle)
{
    qCDebug(GeoFenceControllerLog) << "startStaticActiveVehicle";
62

63 64 65 66 67 68
    PlanElementController::startStaticActiveVehicle(vehicle);
    _init();
}

void GeoFenceController::_init(void)
{
69

70 71 72 73
}

void GeoFenceController::setBreachReturnPoint(const QGeoCoordinate& breachReturnPoint)
{
74 75 76
    if (_breachReturnPoint != breachReturnPoint) {
        _breachReturnPoint = breachReturnPoint;
        setDirty(true);
77 78 79 80
        emit breachReturnPointChanged(breachReturnPoint);
    }
}

81
void GeoFenceController::_signalAll(void)
82
{
83 84 85
    emit circleEnabledChanged(circleEnabled());
    emit polygonEnabledChanged(polygonEnabled());
    emit breachReturnEnabledChanged(breachReturnEnabled());
86
    emit breachReturnPointChanged(breachReturnPoint());
87 88 89
    emit circleRadiusChanged(circleRadius());
    emit paramsChanged(params());
    emit paramLabelsChanged(paramLabels());
90
    emit editorQmlChanged(editorQml());
91
    emit dirtyChanged(dirty());
92 93
}

94
void GeoFenceController::_activeVehicleBeingRemoved(void)
95
{
96
    _activeVehicle->geoFenceManager()->disconnect(this);
97 98 99 100
}

void GeoFenceController::_activeVehicleSet(void)
{
101
    GeoFenceManager* geoFenceManager = _activeVehicle->geoFenceManager();
102 103 104 105 106 107 108 109 110
    connect(geoFenceManager, &GeoFenceManager::polygonEnabledChanged,       this, &GeoFenceController::_setDirty);
    connect(geoFenceManager, &GeoFenceManager::circleEnabledChanged,        this, &GeoFenceController::circleEnabledChanged);
    connect(geoFenceManager, &GeoFenceManager::polygonEnabledChanged,       this, &GeoFenceController::polygonEnabledChanged);
    connect(geoFenceManager, &GeoFenceManager::breachReturnEnabledChanged,  this, &GeoFenceController::breachReturnEnabledChanged);
    connect(geoFenceManager, &GeoFenceManager::circleRadiusChanged,         this, &GeoFenceController::circleRadiusChanged);
    connect(geoFenceManager, &GeoFenceManager::paramsChanged,               this, &GeoFenceController::paramsChanged);
    connect(geoFenceManager, &GeoFenceManager::paramLabelsChanged,          this, &GeoFenceController::paramLabelsChanged);
    connect(geoFenceManager, &GeoFenceManager::loadComplete,                this, &GeoFenceController::_loadComplete);
    connect(geoFenceManager, &GeoFenceManager::inProgressChanged,           this, &GeoFenceController::syncInProgressChanged);
111

112 113 114
    if (!geoFenceManager->inProgress()) {
        _loadComplete(geoFenceManager->breachReturnPoint(), geoFenceManager->polygon());
    }
115

Don Gagne's avatar
Don Gagne committed
116
    _signalAll();
117
}
Don Gagne's avatar
Don Gagne committed
118

119 120 121 122
bool GeoFenceController::_loadJsonFile(QJsonDocument& jsonDoc, QString& errorString)
{
    QJsonObject json = jsonDoc.object();

Don Gagne's avatar
Don Gagne committed
123 124 125 126 127 128 129
    int fileVersion;
    if (!JsonHelper::validateQGCJsonFile(json,
                                         _jsonFileTypeValue,    // expected file type
                                         1,                     // minimum supported version
                                         1,                     // maximum supported version
                                         fileVersion,
                                         errorString)) {
130 131 132
        return false;
    }

133
    if (!_activeVehicle->parameterManager()->loadFromJson(json, false /* required */, errorString)) {
134 135 136
        return false;
    }

137
    if (breachReturnEnabled()) {
138
        if (json.contains(_jsonBreachReturnKey)
139
                && !JsonHelper::loadGeoCoordinate(json[_jsonBreachReturnKey], false /* altitudeRequired */, _breachReturnPoint, errorString)) {
140 141 142 143 144 145
            return false;
        }
    } else {
        _breachReturnPoint = QGeoCoordinate();
    }

146
    if (polygonEnabled()) {
147
        if (!_mapPolygon.loadFromJson(json, true, errorString)) {
148 149
            return false;
        }
150
    }
151
    _mapPolygon.setDirty(false);
152 153

    return true;
154 155
}

156 157 158
#if 0
// NYI
bool GeoFenceController::_loadTextFile(QTextStream& stream, QmlObjectListModel* visualItems, QString& errorString)
159
{
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    bool addPlannedHomePosition = false;

    QString firstLine = stream.readLine();
    const QStringList& version = firstLine.split(" ");

    bool versionOk = false;
    if (version.size() == 3 && version[0] == "QGC" && version[1] == "WPL") {
        if (version[2] == "110") {
            // ArduPilot file, planned home position is already in position 0
            versionOk = true;
        } else if (version[2] == "120") {
            // Old QGC file, no planned home position
            versionOk = true;
            addPlannedHomePosition = true;
        }
    }

    if (versionOk) {
        while (!stream.atEnd()) {
            SimpleMissionItem* item = new SimpleMissionItem(_activeVehicle, this);

            if (item->load(stream)) {
                visualItems->append(item);
            } else {
                errorString = QStringLiteral("The mission file is corrupted.");
                return false;
            }
        }
    } else {
189
        errorString = QStringLiteral("The mission file is not compatible with this version of %1.").arg(qgcApp()->applicationName()));
190 191
        return false;
    }
192

193 194 195 196 197 198 199 200 201 202 203 204 205
    if (addPlannedHomePosition || visualItems->count() == 0) {
        _addPlannedHomePosition(visualItems, true /* addToCenter */);

        // Update sequence numbers in DO_JUMP commands to take into account added home position in index 0
        for (int i=1; i<visualItems->count(); i++) {
            SimpleMissionItem* item = qobject_cast<SimpleMissionItem*>(visualItems->get(i));
            if (item && item->command() == MavlinkQmlSingleton::MAV_CMD_DO_JUMP) {
                item->missionItem().setParam1((int)item->missionItem().param1() + 1);
            }
        }
    }

    return true;
206
}
207
#endif
208 209 210

void GeoFenceController::loadFromFile(const QString& filename)
{
211 212 213 214 215 216 217 218 219
    QString errorString;

    if (filename.isEmpty()) {
        return;
    }

    QFile file(filename);

    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
Don Gagne's avatar
Don Gagne committed
220
        errorString = file.errorString() + QStringLiteral(" ") + filename;
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
    } else {
        QJsonDocument   jsonDoc;
        QByteArray      bytes = file.readAll();

        if (JsonHelper::isJsonFile(bytes, jsonDoc)) {
            _loadJsonFile(jsonDoc, errorString);
        } else {
            // FIXME: No MP file format support
            qgcApp()->showMessage("GeoFence file is in incorrect format.");
            return;
        }
    }

    if (!errorString.isEmpty()) {
        qgcApp()->showMessage(errorString);
    }

238 239
    _signalAll();
    setDirty(true);
240 241 242 243
}

void GeoFenceController::saveToFile(const QString& filename)
{
244 245 246 247 248 249
    if (filename.isEmpty()) {
        return;
    }

    QString fenceFilename = filename;
    if (!QFileInfo(filename).fileName().contains(".")) {
250
        fenceFilename += QString(".%1").arg(AppSettings::fenceFileExtension);
251 252 253 254 255 256 257 258 259 260
    }

    QFile file(fenceFilename);

    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qgcApp()->showMessage(file.errorString());
    } else {
        QJsonObject fenceFileObject;    // top level json object

        fenceFileObject[JsonHelper::jsonFileTypeKey] =      _jsonFileTypeValue;
Don Gagne's avatar
Don Gagne committed
261
        fenceFileObject[JsonHelper::jsonVersionKey] =       1;
262 263 264
        fenceFileObject[JsonHelper::jsonGroundStationKey] = JsonHelper::jsonGroundStationValue;

        QStringList         paramNames;
265
        ParameterManager*   paramMgr = _activeVehicle->parameterManager();
266 267 268 269 270 271 272
        GeoFenceManager*    fenceMgr = _activeVehicle->geoFenceManager();
        QVariantList        params = fenceMgr->params();

        for (int i=0; i< params.count(); i++) {
            paramNames.append(params[i].value<Fact*>()->name());
        }
        if (paramNames.count() > 0) {
273
            paramMgr->saveToJson(_activeVehicle->defaultComponentId(), paramNames, fenceFileObject);
274 275
        }

276
        if (breachReturnEnabled()) {
277
            QJsonValue jsonBreachReturn;
278
            JsonHelper::saveGeoCoordinate(_breachReturnPoint, false /* writeAltitude */, jsonBreachReturn);
279 280 281
            fenceFileObject[_jsonBreachReturnKey] = jsonBreachReturn;
        }

282
        if (polygonEnabled()) {
283
            _mapPolygon.saveToJson(fenceFileObject);
284
        }
285 286 287 288 289 290 291 292

        QJsonDocument saveDoc(fenceFileObject);
        file.write(saveDoc.toJson());
    }

    setDirty(false);
}

293 294
void GeoFenceController::removeAll(void)
{
295
    setBreachReturnPoint(QGeoCoordinate());
296
    _mapPolygon.clear();
297 298 299 300
}

void GeoFenceController::loadFromVehicle(void)
{
301
    if (_activeVehicle->parameterManager()->parametersReady() && !syncInProgress()) {
302
        _activeVehicle->geoFenceManager()->loadFromVehicle();
303
    } else {
304
        qCWarning(GeoFenceControllerLog) << "GeoFenceController::loadFromVehicle call at wrong time" << _activeVehicle->parameterManager()->parametersReady() << syncInProgress();
305 306 307 308 309
    }
}

void GeoFenceController::sendToVehicle(void)
{
310
    if (_activeVehicle->parameterManager()->parametersReady() && !syncInProgress()) {
311 312
        _activeVehicle->geoFenceManager()->sendToVehicle(_breachReturnPoint, _mapPolygon.pathModel());
        _mapPolygon.setDirty(false);
Don Gagne's avatar
Don Gagne committed
313
        setDirty(false);
314
    } else {
315
        qCWarning(GeoFenceControllerLog) << "GeoFenceController::loadFromVehicle call at wrong time" << _activeVehicle->parameterManager()->parametersReady() << syncInProgress();
316 317 318 319 320
    }
}

bool GeoFenceController::syncInProgress(void) const
{
321
    return _activeVehicle->geoFenceManager()->inProgress();
322 323 324 325
}

bool GeoFenceController::dirty(void) const
{
326
    return _dirty;
327 328 329 330 331 332 333 334
}


void GeoFenceController::setDirty(bool dirty)
{
    if (dirty != _dirty) {
        _dirty = dirty;
        if (!dirty) {
335
            _mapPolygon.setDirty(dirty);
336 337 338 339 340 341 342 343 344 345 346
        }
        emit dirtyChanged(dirty);
    }
}

void GeoFenceController::_polygonDirtyChanged(bool dirty)
{
    if (dirty) {
        setDirty(true);
    }
}
347

348
bool GeoFenceController::circleEnabled(void) const
349
{
350
    return _activeVehicle->geoFenceManager()->circleEnabled();
351 352
}

353
bool GeoFenceController::polygonEnabled(void) const
354
{
355
    return _activeVehicle->geoFenceManager()->polygonEnabled();
356 357
}

358
bool GeoFenceController::breachReturnEnabled(void) const
359
{
360
    return _activeVehicle->geoFenceManager()->breachReturnEnabled();
361 362 363 364 365 366 367
}

void GeoFenceController::_setDirty(void)
{
    setDirty(true);
}

368
void GeoFenceController::_setPolygonFromManager(const QList<QGeoCoordinate>& polygon)
369
{
370 371 372 373 374
    _mapPolygon.clear();
    for (int i=0; i<polygon.count(); i++) {
        _mapPolygon.appendVertex(polygon[i]);
    }
    _mapPolygon.setDirty(false);
375 376 377 378 379 380
}

void GeoFenceController::_setReturnPointFromManager(QGeoCoordinate breachReturnPoint)
{
    _breachReturnPoint = breachReturnPoint;
    emit breachReturnPointChanged(_breachReturnPoint);
381 382 383 384
}

float GeoFenceController::circleRadius(void) const
{
385
    return _activeVehicle->geoFenceManager()->circleRadius();
386 387 388 389
}

QVariantList GeoFenceController::params(void) const
{
390
    return _activeVehicle->geoFenceManager()->params();
391 392 393 394
}

QStringList GeoFenceController::paramLabels(void) const
{
395
    return _activeVehicle->geoFenceManager()->paramLabels();
396
}
397 398 399

QString GeoFenceController::editorQml(void) const
{
400
    return _activeVehicle->geoFenceManager()->editorQml();
401
}
402 403 404 405 406 407

void GeoFenceController::_loadComplete(const QGeoCoordinate& breachReturn, const QList<QGeoCoordinate>& polygon)
{
    _setReturnPointFromManager(breachReturn);
    _setPolygonFromManager(polygon);
    setDirty(false);
Don Gagne's avatar
Don Gagne committed
408
    emit loadComplete();
409
}
410 411 412

QString GeoFenceController::fileExtension(void) const
{
413
    return AppSettings::fenceFileExtension;
414
}
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441

bool GeoFenceController::containsItems(void) const
{
    return _mapPolygon.count() > 2;
}

void GeoFenceController::_updateContainsItems(void)
{
    emit containsItemsChanged(containsItems());
}

void GeoFenceController::removeAllFromVehicle(void)
{
    _activeVehicle->geoFenceManager()->removeAll();
}

void GeoFenceController::addFence(void)
{
    // GeoFenceMapVisuals control is resposible for this
    emit addFencePolygon();
}

void GeoFenceController::removeFence(void)
{
    _mapPolygon.clear();
}