GeoFenceController.cc 15.1 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"
DonLakeFlyer's avatar
DonLakeFlyer committed
23
#include "PlanMasterController.h"
Don Gagne's avatar
Don Gagne committed
24 25

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

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

QGC_LOGGING_CATEGORY(GeoFenceControllerLog, "GeoFenceControllerLog")

35 36 37
const char* GeoFenceController::_jsonFileTypeValue =        "GeoFence";
const char* GeoFenceController::_jsonBreachReturnKey =      "breachReturn";
const char* GeoFenceController::_px4ParamCircularFence =    "GF_MAX_HOR_DIST";
38

39
GeoFenceController::GeoFenceController(PlanMasterController* masterController, QObject* parent)
40 41 42 43 44
    : PlanElementController     (masterController, parent)
    , _geoFenceManager          (_managerVehicle->geoFenceManager())
    , _dirty                    (false)
    , _itemsRequested           (false)
    , _px4ParamCircularFenceFact(NULL)
45
{
46 47
    connect(&_polygons, &QmlObjectListModel::countChanged, this, &GeoFenceController::_updateContainsItems);
    connect(&_circles,  &QmlObjectListModel::countChanged, this, &GeoFenceController::_updateContainsItems);
48 49

    managerVehicleChanged(_managerVehicle);
50 51 52 53 54 55 56
}

GeoFenceController::~GeoFenceController()
{

}

57
void GeoFenceController::start(bool flyView)
58
{
59
    qCDebug(GeoFenceControllerLog) << "start flyView" << flyView;
60

61
    PlanElementController::start(flyView);
62 63 64 65 66
    _init();
}

void GeoFenceController::_init(void)
{
67

68 69 70 71
}

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

79
void GeoFenceController::_signalAll(void)
80
{
81
    emit breachReturnPointChanged(breachReturnPoint());
82
    emit dirtyChanged(dirty());
83
    emit supportedChanged(supported());
84 85
}

86
void GeoFenceController::managerVehicleChanged(Vehicle* managerVehicle)
87
{
88 89
    if (_managerVehicle) {
        _geoFenceManager->disconnect(this);
90
        _managerVehicle->disconnect(this);
91
        _managerVehicle->parameterManager()->disconnect(this);
92 93 94
        _managerVehicle = NULL;
        _geoFenceManager = NULL;
    }
95

96 97 98 99 100 101 102
    _managerVehicle = managerVehicle;
    if (!_managerVehicle) {
        qWarning() << "GeoFenceController::managerVehicleChanged managerVehicle=NULL";
        return;
    }

    _geoFenceManager = _managerVehicle->geoFenceManager();
DonLakeFlyer's avatar
DonLakeFlyer committed
103 104 105
    connect(_geoFenceManager, &GeoFenceManager::loadComplete,                   this, &GeoFenceController::_managerLoadComplete);
    connect(_geoFenceManager, &GeoFenceManager::sendComplete,                   this, &GeoFenceController::_managerSendComplete);
    connect(_geoFenceManager, &GeoFenceManager::removeAllComplete,              this, &GeoFenceController::_managerRemoveAllComplete);
106 107
    connect(_geoFenceManager, &GeoFenceManager::inProgressChanged,              this, &GeoFenceController::syncInProgressChanged);

108 109 110 111
    connect(_managerVehicle,  &Vehicle::capabilityBitsChanged,                  this, &GeoFenceController::supportedChanged);

    connect(_managerVehicle->parameterManager(), &ParameterManager::parametersReadyChanged, this, &GeoFenceController::_parametersReady);
    _parametersReady();
112 113

    emit supportedChanged(supported());
Don Gagne's avatar
Don Gagne committed
114
    _signalAll();
115
}
Don Gagne's avatar
Don Gagne committed
116

117
bool GeoFenceController::load(const QJsonObject& json, QString& errorString)
118
{
119 120 121 122
    Q_UNUSED(json);
    Q_UNUSED(errorString);

#if 0
123 124
    QString errorStr;
    QString errorMessage = tr("GeoFence: %1");
125

126 127 128
    if (json.contains(_jsonBreachReturnKey) &&
            !JsonHelper::loadGeoCoordinate(json[_jsonBreachReturnKey], false /* altitudeRequired */, _breachReturnPoint, errorStr)) {
        errorString = errorMessage.arg(errorStr);
129 130 131
        return false;
    }

132 133
    if (!_mapPolygon.loadFromJson(json, true, errorStr)) {
        errorString = errorMessage.arg(errorStr);
134
        return false;
135
    }
136
    _mapPolygon.setDirty(false);
137
    setDirty(false);
138

139
    _signalAll();
140
#endif
141 142

    return true;
143 144
}

145
void  GeoFenceController::save(QJsonObject& json)
146
{
147 148
    Q_UNUSED(json);
#if 0
149
    json[JsonHelper::jsonVersionKey] = 1;
150

151
    if (_breachReturnPoint.isValid()) {
152 153
        QJsonValue jsonBreachReturn;
        JsonHelper::saveGeoCoordinate(_breachReturnPoint, false /* writeAltitude */, jsonBreachReturn);
154
        json[_jsonBreachReturnKey] = jsonBreachReturn;
155 156
    }

157
    _mapPolygon.saveToJson(json);
158
#endif
159 160
}

161
void GeoFenceController::removeAll(void)
162
{    
163
    setBreachReturnPoint(QGeoCoordinate());
164 165
    _polygons.clearAndDeleteContents();
    _circles.clearAndDeleteContents();
166 167
}

DonLakeFlyer's avatar
DonLakeFlyer committed
168 169 170 171 172 173 174 175 176 177 178
void GeoFenceController::removeAllFromVehicle(void)
{
    if (_masterController->offline()) {
        qCWarning(GeoFenceControllerLog) << "GeoFenceController::removeAllFromVehicle called while offline";
    } else if (syncInProgress()) {
        qCWarning(GeoFenceControllerLog) << "GeoFenceController::removeAllFromVehicle called while syncInProgress";
    } else {
        _geoFenceManager->removeAll();
    }
}

179 180
void GeoFenceController::loadFromVehicle(void)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
181 182 183 184
    if (_masterController->offline()) {
        qCWarning(GeoFenceControllerLog) << "GeoFenceController::loadFromVehicle called while offline";
    } else if (syncInProgress()) {
        qCWarning(GeoFenceControllerLog) << "GeoFenceController::loadFromVehicle called while syncInProgress";
185
    } else {
DonLakeFlyer's avatar
DonLakeFlyer committed
186 187
        _itemsRequested = true;
        _geoFenceManager->loadFromVehicle();
188 189 190 191 192
    }
}

void GeoFenceController::sendToVehicle(void)
{
DonLakeFlyer's avatar
DonLakeFlyer committed
193 194 195 196 197
    if (_masterController->offline()) {
        qCWarning(GeoFenceControllerLog) << "GeoFenceController::sendToVehicle called while offline";
    } else if (syncInProgress()) {
        qCWarning(GeoFenceControllerLog) << "GeoFenceController::sendToVehicle called while syncInProgress";
    } else {
DonLakeFlyer's avatar
DonLakeFlyer committed
198
        qCDebug(GeoFenceControllerLog) << "GeoFenceController::sendToVehicle";
199
        _geoFenceManager->sendToVehicle(_breachReturnPoint, _polygons, _circles);
DonLakeFlyer's avatar
DonLakeFlyer committed
200 201
        setDirty(false);
    }
202 203 204 205
}

bool GeoFenceController::syncInProgress(void) const
{
206
    return _geoFenceManager->inProgress();
207 208 209 210
}

bool GeoFenceController::dirty(void) const
{
211
    return _dirty;
212 213 214 215 216 217 218 219
}


void GeoFenceController::setDirty(bool dirty)
{
    if (dirty != _dirty) {
        _dirty = dirty;
        if (!dirty) {
220 221 222 223 224 225 226 227
            for (int i=0; i<_polygons.count(); i++) {
                QGCFencePolygon* polygon = _polygons.value<QGCFencePolygon*>(i);
                polygon->setDirty(false);
            }
            for (int i=0; i<_circles.count(); i++) {
                QGCFenceCircle* circle = _circles.value<QGCFenceCircle*>(i);
                circle->setDirty(false);
            }
228 229 230 231 232 233 234 235 236 237 238
        }
        emit dirtyChanged(dirty);
    }
}

void GeoFenceController::_polygonDirtyChanged(bool dirty)
{
    if (dirty) {
        setDirty(true);
    }
}
239 240 241 242 243 244

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

245 246
void GeoFenceController::_setFenceFromManager(const QList<QGCFencePolygon>& polygons,
                                              const QList<QGCFenceCircle>&  circles)
247
{
248 249 250 251 252
    _polygons.clearAndDeleteContents();
    _circles.clearAndDeleteContents();

    for (int i=0; i<polygons.count(); i++) {
        _polygons.append(new QGCFencePolygon(polygons[i], this));
253
    }
254 255 256 257 258 259

    for (int i=0; i<circles.count(); i++) {
        _circles.append(new QGCFenceCircle(circles[i], this));
    }

    setDirty(false);
260 261 262 263 264 265
}

void GeoFenceController::_setReturnPointFromManager(QGeoCoordinate breachReturnPoint)
{
    _breachReturnPoint = breachReturnPoint;
    emit breachReturnPointChanged(_breachReturnPoint);
266 267
}

268
void GeoFenceController::_managerLoadComplete(void)
269
{
DonLakeFlyer's avatar
DonLakeFlyer committed
270 271
    // Fly view always reloads on _loadComplete
    // Plan view only reloads on _loadComplete if specifically requested
272
    if (_flyView || _itemsRequested) {
273 274
        _setReturnPointFromManager(_geoFenceManager->breachReturnPoint());
        _setFenceFromManager(_geoFenceManager->polygons(), _geoFenceManager->circles());
DonLakeFlyer's avatar
DonLakeFlyer committed
275 276 277 278 279 280 281
        setDirty(false);
        _signalAll();
        emit loadComplete();
    }
    _itemsRequested = false;
}

282
void GeoFenceController::_managerSendComplete(bool error)
DonLakeFlyer's avatar
DonLakeFlyer committed
283 284
{
    // Fly view always reloads on manager sendComplete
285
    if (!error && _flyView) {
DonLakeFlyer's avatar
DonLakeFlyer committed
286 287 288 289
        showPlanFromManagerVehicle();
    }
}

290
void GeoFenceController::_managerRemoveAllComplete(bool error)
DonLakeFlyer's avatar
DonLakeFlyer committed
291
{
292 293 294 295
    if (!error) {
        // Remove all from vehicle so we always update
        showPlanFromManagerVehicle();
    }
296
}
297

298 299
bool GeoFenceController::containsItems(void) const
{
300
    return _polygons.count() > 0 || _circles.count() > 0;
301 302 303 304 305 306 307
}

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

DonLakeFlyer's avatar
DonLakeFlyer committed
308
bool GeoFenceController::showPlanFromManagerVehicle(void)
309
{
310
    qCDebug(GeoFenceControllerLog) << "showPlanFromManagerVehicle _flyView" << _flyView;
DonLakeFlyer's avatar
DonLakeFlyer committed
311 312
    if (_masterController->offline()) {
        qCWarning(GeoFenceControllerLog) << "GeoFenceController::showPlanFromManagerVehicle called while offline";
Patrick José Pereira's avatar
Patrick José Pereira committed
313
        return true;    // stops further propagation of showPlanFromManagerVehicle due to error
DonLakeFlyer's avatar
DonLakeFlyer committed
314 315 316
    } else {
        _itemsRequested = true;
        if (!_managerVehicle->initialPlanRequestComplete()) {
DonLakeFlyer's avatar
DonLakeFlyer committed
317
            // The vehicle hasn't completed initial load, we can just wait for loadComplete to be signalled automatically
DonLakeFlyer's avatar
DonLakeFlyer committed
318 319 320 321 322 323 324 325 326 327
            qCDebug(GeoFenceControllerLog) << "showPlanFromManagerVehicle: !initialPlanRequestComplete, wait for signal";
            return true;
        } else if (syncInProgress()) {
            // If the sync is already in progress, _loadComplete will be called automatically when it is done. So no need to do anything.
            qCDebug(GeoFenceControllerLog) << "showPlanFromManagerVehicle: syncInProgress wait for signal";
            return true;
        } else {
            // Fake a _loadComplete with the current items
            qCDebug(GeoFenceControllerLog) << "showPlanFromManagerVehicle: sync complete simulate signal";
            _itemsRequested = true;
328
            _managerLoadComplete();
DonLakeFlyer's avatar
DonLakeFlyer committed
329 330 331
            return false;
        }
    }
332
}
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421

void GeoFenceController::addInclusionPolygon(QGeoCoordinate topLeft, QGeoCoordinate bottomRight)
{
    QGeoCoordinate topRight(topLeft.latitude(), bottomRight.longitude());
    QGeoCoordinate bottomLeft(bottomRight.latitude(), topLeft.longitude());

    double halfWidthMeters = topLeft.distanceTo(topRight) / 2.0;
    double halfHeightMeters = topLeft.distanceTo(bottomLeft) / 2.0;

    QGeoCoordinate centerLeftEdge = topLeft.atDistanceAndAzimuth(halfHeightMeters, 180);
    QGeoCoordinate centerTopEdge = topLeft.atDistanceAndAzimuth(halfWidthMeters, 90);
    QGeoCoordinate center(centerLeftEdge.latitude(), centerTopEdge.longitude());

    // Initial polygon is inset to take 3/4s of viewport with max width/height of 3000 meters
    halfWidthMeters =   qMin(halfWidthMeters * 0.75, 1500.0);
    halfHeightMeters =  qMin(halfHeightMeters * 0.75, 1500.0);

    // Initial polygon has max width and height of 3000 meters
    topLeft =           center.atDistanceAndAzimuth(halfWidthMeters, -90).atDistanceAndAzimuth(halfHeightMeters, 0);
    topRight =          center.atDistanceAndAzimuth(halfWidthMeters, 90).atDistanceAndAzimuth(halfHeightMeters, 0);
    bottomLeft =        center.atDistanceAndAzimuth(halfWidthMeters, -90).atDistanceAndAzimuth(halfHeightMeters, 180);
    bottomRight =       center.atDistanceAndAzimuth(halfWidthMeters, 90).atDistanceAndAzimuth(halfHeightMeters, 180);

    QGCFencePolygon* polygon = new QGCFencePolygon(true /* inclusion */, this);
    polygon->appendVertex(topLeft);
    polygon->appendVertex(topRight);
    polygon->appendVertex(bottomRight);
    polygon->appendVertex(bottomLeft);
    _polygons.append(polygon);

    clearAllInteractive();
    polygon->setInteractive(true);
}

void GeoFenceController::addInclusionCircle(QGeoCoordinate topLeft, QGeoCoordinate bottomRight)
{
    QGeoCoordinate topRight(topLeft.latitude(), bottomRight.longitude());
    QGeoCoordinate bottomLeft(bottomRight.latitude(), topLeft.longitude());

    // Initial radius is inset to take 3/4s of viewport and max of 1500 meters
    double halfWidthMeters = topLeft.distanceTo(topRight) / 2.0;
    double halfHeightMeters = topLeft.distanceTo(bottomLeft) / 2.0;
    double radius = qMin(qMin(halfWidthMeters, halfHeightMeters) * 0.75, 1500.0);

    QGeoCoordinate centerLeftEdge = topLeft.atDistanceAndAzimuth(halfHeightMeters, 180);
    QGeoCoordinate centerTopEdge = topLeft.atDistanceAndAzimuth(halfWidthMeters, 90);
    QGeoCoordinate center(centerLeftEdge.latitude(), centerTopEdge.longitude());

    QGCFenceCircle* circle = new QGCFenceCircle(center, radius, true /* inclusion */, this);
    _circles.append(circle);

    clearAllInteractive();
    circle->setInteractive(true);
}

void GeoFenceController::deletePolygon(int index)
{
    if (index < 0 || index > _polygons.count() - 1) {
        return;
    }

    QGCFencePolygon* polygon = qobject_cast<QGCFencePolygon*>(_polygons.removeAt(index));
    polygon->deleteLater();
}

void GeoFenceController::deleteCircle(int index)
{
    if (index < 0 || index > _circles.count() - 1) {
        return;
    }

    QGCFenceCircle* circle = qobject_cast<QGCFenceCircle*>(_circles.removeAt(index));
    circle->deleteLater();
}

void GeoFenceController::clearAllInteractive(void)
{
    for (int i=0; i<_polygons.count(); i++) {
        _polygons.value<QGCFencePolygon*>(i)->setInteractive(false);
    }
    for (int i=0; i<_circles.count(); i++) {
        _circles.value<QGCFenceCircle*>(i)->setInteractive(false);
    }
}

bool GeoFenceController::supported(void) const
{
    return (_managerVehicle->capabilityBits() & MAV_PROTOCOL_CAPABILITY_MISSION_FENCE) && (_managerVehicle->maxProtoVersion() >= 200);
}
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448

// Hack for PX4
double GeoFenceController::paramCircularFence(void)
{
    if (_managerVehicle->isOfflineEditingVehicle() || !_managerVehicle->parameterManager()->parameterExists(FactSystem::defaultComponentId, _px4ParamCircularFence)) {
        return 0;
    }

    return _managerVehicle->parameterManager()->getParameter(FactSystem::defaultComponentId, _px4ParamCircularFence)->rawValue().toDouble();
}

void GeoFenceController::_parametersReady(void)
{
    if (_px4ParamCircularFenceFact) {
        _px4ParamCircularFenceFact->disconnect(this);
        _px4ParamCircularFenceFact = NULL;
    }

    if (_managerVehicle->isOfflineEditingVehicle() || !_managerVehicle->parameterManager()->parameterExists(FactSystem::defaultComponentId, _px4ParamCircularFence)) {
        emit paramCircularFenceChanged();
        return;
    }

    _px4ParamCircularFenceFact = _managerVehicle->parameterManager()->getParameter(FactSystem::defaultComponentId, _px4ParamCircularFence);
    connect(_px4ParamCircularFenceFact, &Fact::rawValueChanged, this, &GeoFenceController::paramCircularFenceChanged);
    emit paramCircularFenceChanged();
}