capture.cpp 136 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/*  Ekos
    Copyright (C) 2012 Jasem Mutlaq <mutlaqja@ikarustech.com>

    This application is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.
 */

#include <QFileDialog>
#include <QDirIterator>
#include <QStandardPaths>

#include <KMessageBox>
#include <KDirWatch>
#include <KLocalizedString>
#include <KNotifications/KNotification>

#include <basedevice.h>
#include <lilxml.h>

#include "Options.h"

24 25
#include "oal/log.h"

26
#include "kstars.h"
27
#include "skymap.h"
28 29 30 31
#include "kstarsdata.h"

#include "capture.h"
#include "sequencejob.h"
32
#include "dslrinfodialog.h"
33 34 35 36 37 38 39 40

#include "indi/driverinfo.h"
#include "indi/indifilter.h"
#include "indi/clientmanager.h"

#include "fitsviewer/fitsviewer.h"
#include "fitsviewer/fitsview.h"

41 42
#include "ekos/auxiliary/darklibrary.h"
#include "ekos/ekosmanager.h"
43 44 45
#include "captureadaptor.h"
#include "ui_calibrationoptions.h"

46
#include "auxiliary/QProgressIndicator.h"
47 48 49 50

#define INVALID_TEMPERATURE 10000
#define INVALID_HA          10000
#define MF_TIMER_TIMEOUT    90000
51
#define GD_TIMER_TIMEOUT    60000
52 53 54
#define MF_RA_DIFF_LIMIT    4
#define MAX_CAPTURE_RETRIES 3

55 56 57 58
// Current Sequence File Format:
#define SQ_FORMAT_VERSION   1.7
// We accept file formats with version back to:
#define SQ_COMPAT_VERSION   1.6
59

60 61 62 63 64 65 66 67 68 69
namespace Ekos
{

Capture::Capture()
{
    setupUi(this);

    new CaptureAdaptor(this);
    QDBusConnection::sessionBus().registerObject("/KStars/Ekos/Capture",  this);

70
    dirPath     = QUrl::fromLocalFile(QDir::homePath());
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91

    state = CAPTURE_IDLE;
    focusState = FOCUS_IDLE;
    guideState = GUIDE_IDLE;
    alignState = ALIGN_IDLE;

    currentCCD = NULL;
    currentTelescope = NULL;
    currentFilter = NULL;
    dustCap = NULL;
    lightBox= NULL;
    dome    = NULL;

    filterSlot = NULL;
    filterName = NULL;
    activeJob  = NULL;

    targetChip = NULL;
    guideChip  = NULL;

    targetADU  = 0;
92
    targetADUTolerance = 1000;
93 94 95 96 97 98 99 100 101 102 103 104 105 106
    flatFieldDuration = DURATION_MANUAL;
    flatFieldSource   = SOURCE_MANUAL;
    calibrationStage         = CAL_NONE;
    preMountPark           = false;
    preDomePark            = false;

    deviationDetected = false;
    spikeDetected     = false;
    isBusy            = false;

    ignoreJobProgress=true;

    dustCapLightEnabled = lightBoxLightEnabled = false;

107
    //isAutoGuiding   = false;
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
    isAutoFocus     = false;
    autoFocusStatus = false;
    resumeAlignmentAfterFlip= false;

    mDirty          = false;
    jobUnderEdit    = false;
    currentFilterPosition   = -1;

    //calibrationState  = CALIBRATE_NONE;
    meridianFlipStage = MF_NONE;
    resumeGuidingAfterFlip = false;

    //ADURaw1 = ADURaw2 = ExpRaw1 = ExpRaw2 = -1;
    //ADUSlope = 0;

    pi = new QProgressIndicator(this);

    progressLayout->addWidget(pi, 0, 4, 1, 1);

    seqFileCount    = 0;
    //seqWatcher		= new KDirWatch();
    seqTimer = new QTimer(this);
    connect(seqTimer, SIGNAL(timeout()), this, SLOT(captureImage()));

    connect(startB, SIGNAL(clicked()), this, SLOT(toggleSequence()));
    connect(pauseB, SIGNAL(clicked()), this, SLOT(pause()));

135
    startB->setIcon(QIcon::fromTheme("media-playback-start", QIcon(":/icons/breeze/default/media-playback-start.svg") ));
Robert Lancaster's avatar
Robert Lancaster committed
136
    startB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
137
    pauseB->setIcon(QIcon::fromTheme("media-playback-pause", QIcon(":/icons/breeze/default/media-playback-pause.svg") ));
Robert Lancaster's avatar
Robert Lancaster committed
138
    pauseB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
139

140 141
    filterOffsetB->setIcon(QIcon::fromTheme("view-filter", QIcon(":/icons/breeze/default/view-filter.svg") ));
    connect(filterOffsetB, SIGNAL(clicked()), this, SLOT(showFilterOffsetDialog()));
Robert Lancaster's avatar
Robert Lancaster committed
142
    filterOffsetB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
143

144 145 146 147 148
    connect(binXIN, SIGNAL(valueChanged(int)), binYIN, SLOT(setValue(int)));

    connect(CCDCaptureCombo, SIGNAL(activated(QString)), this, SLOT(setDefaultCCD(QString)));
    connect(CCDCaptureCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(checkCCD(int)));

149 150
    connect(liveVideoB, SIGNAL(clicked(bool)), this, SLOT(toggleVideoStream(bool)));

151 152
    guideDeviationTimer.setInterval(GD_TIMER_TIMEOUT);
    connect(&guideDeviationTimer, SIGNAL(timeout()), this, SLOT(checkGuideDeviationTimeout()));
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176

    connect(FilterCaptureCombo, SIGNAL(activated(int)), this, SLOT(checkFilter(int)));

    connect(previewB, SIGNAL(clicked()), this, SLOT(captureOne()));

    //connect( seqWatcher, SIGNAL(dirty(QString)), this, SLOT(checkSeqFile(QString)));

    connect(addToQueueB, SIGNAL(clicked()), this, SLOT(addJob()));
    connect(removeFromQueueB, SIGNAL(clicked()), this, SLOT(removeJob()));
    connect(queueUpB, SIGNAL(clicked()), this, SLOT(moveJobUp()));
    connect(queueDownB, SIGNAL(clicked()), this, SLOT(moveJobDown()));
    connect(selectFITSDirB, SIGNAL(clicked()), this, SLOT(saveFITSDirectory()));
    connect(queueSaveB, SIGNAL(clicked()), this, SLOT(saveSequenceQueue()));
    connect(queueSaveAsB, SIGNAL(clicked()), this, SLOT(saveSequenceQueueAs()));
    connect(queueLoadB, SIGNAL(clicked()), this, SLOT(loadSequenceQueue()));
    connect(resetB, SIGNAL(clicked()), this, SLOT(resetJobs()));
    connect(queueTable, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(editJob(QModelIndex)));
    connect(queueTable, SIGNAL(itemSelectionChanged()), this, SLOT(resetJobEdit()));
    connect(setTemperatureB, SIGNAL(clicked()), this, SLOT(setTemperature()));
    connect(temperatureIN, SIGNAL(editingFinished()), setTemperatureB, SLOT(setFocus()));
    connect(frameTypeCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(checkFrameType(int)));
    connect(resetFrameB, SIGNAL(clicked()), this, SLOT(resetFrame()));
    connect(calibrationB, SIGNAL(clicked()), this, SLOT(openCalibrationDialog()));

177
    addToQueueB->setIcon(QIcon::fromTheme("list-add", QIcon(":/icons/breeze/default/list-add.svg") ));
Robert Lancaster's avatar
Robert Lancaster committed
178
    addToQueueB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
179
    removeFromQueueB->setIcon(QIcon::fromTheme("list-remove", QIcon(":/icons/breeze/default/list-remove.svg") ));
Robert Lancaster's avatar
Robert Lancaster committed
180
    removeFromQueueB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
181
    queueUpB->setIcon(QIcon::fromTheme("go-up", QIcon(":/icons/breeze/default/go-up.svg") ));
Robert Lancaster's avatar
Robert Lancaster committed
182
    queueUpB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
183
    queueDownB->setIcon(QIcon::fromTheme("go-down", QIcon(":/icons/breeze/default/go-down.svg") ));
Robert Lancaster's avatar
Robert Lancaster committed
184
    queueDownB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
185
    selectFITSDirB->setIcon(QIcon::fromTheme("document-open-folder", QIcon(":/icons/breeze/default/document-open-folder.svg") ));
Robert Lancaster's avatar
Robert Lancaster committed
186
    selectFITSDirB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
187
    queueLoadB->setIcon(QIcon::fromTheme("document-open", QIcon(":/icons/breeze/default/document-open.svg") ));
Robert Lancaster's avatar
Robert Lancaster committed
188
    queueLoadB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
189
    queueSaveB->setIcon(QIcon::fromTheme("document-save", QIcon(":/icons/breeze/default/document-save.svg") ));
Robert Lancaster's avatar
Robert Lancaster committed
190
    queueSaveB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
191
    queueSaveAsB->setIcon(QIcon::fromTheme("document-save-as", QIcon(":/icons/breeze/default/document-save-as.svg") ));
Robert Lancaster's avatar
Robert Lancaster committed
192
    queueSaveAsB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
193
    resetB->setIcon(QIcon::fromTheme("system-reboot", QIcon(":/icons/breeze/default/system-reboot.svg") ));
Robert Lancaster's avatar
Robert Lancaster committed
194
    resetB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
195
    resetFrameB->setIcon(QIcon::fromTheme("view-refresh", QIcon(":/icons/breeze/default/view-refresh.svg") ));
Robert Lancaster's avatar
Robert Lancaster committed
196
    resetFrameB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
197
    calibrationB->setIcon(QIcon::fromTheme("run-build", QIcon(":/icons/breeze/default/run-build.svg") ));
Robert Lancaster's avatar
Robert Lancaster committed
198
    calibrationB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
199 200 201 202 203 204 205 206 207 208 209

    addToQueueB->setToolTip(i18n("Add job to sequence queue"));
    removeFromQueueB->setToolTip(i18n("Remove job from sequence queue"));

    fitsDir->setText(Options::fitsDir());

    seqExpose = 0;
    seqTotalCount = 0;
    seqCurrentCount = 0;
    seqDelay = 0;
    fileHFR=0;
210
    useGuideHead = false;
211 212 213 214 215 216 217
    firstAutoFocus = true;

    foreach(QString filter, FITSViewer::filterTypes)
        filterCombo->addItem(filter);

    guideDeviationCheck->setChecked(Options::enforceGuideDeviation());
    guideDeviation->setValue(Options::guideDeviation());
218
    autofocusCheck->setChecked(Options::enforceAutofocus());
219 220
    meridianCheck->setChecked(Options::autoMeridianFlip());
    meridianHours->setValue(Options::autoMeridianHours());
221
    useFITSViewerInCapture->setChecked(Options::useFITSViewerInCapture());
222 223 224 225 226 227 228

    connect(autofocusCheck, SIGNAL(toggled(bool)), this, SLOT(setDirty()));
    connect(HFRPixels, SIGNAL(valueChanged(double)), this, SLOT(setDirty()));
    connect(guideDeviationCheck, SIGNAL(toggled(bool)), this, SLOT(setDirty()));
    connect(guideDeviation, SIGNAL(valueChanged(double)), this, SLOT(setDirty()));
    connect(meridianCheck, SIGNAL(toggled(bool)), this, SLOT(setDirty()));
    connect(meridianHours, SIGNAL(valueChanged(double)), this, SLOT(setDirty()));
229 230
    connect(uploadModeCombo, SIGNAL(activated(int)), this, SLOT(setDirty()));
    connect(remoteDirIN, SIGNAL(editingFinished()), this, SLOT(setDirty()));
231

232 233 234 235
    observerName = Options::defaultObserver();
    observerB->setIcon(QIcon::fromTheme("im-user", QIcon(":/icons/breeze/default/im-user.svg") ));
    observerB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
    connect(observerB, SIGNAL(clicked()), this, SLOT(showObserverDialog()));
236

237
    // Post capture script
238
    connect(&postCaptureScript, SIGNAL(finished(int)), this, SLOT(postScriptFinished(int)));
239 240

    // Remote directory
241 242 243 244
    connect(uploadModeCombo, static_cast<void (QComboBox::*)(int)>(&QComboBox::activated), this, [&](int index)
    {
        remoteDirIN->setEnabled(index != 0);
    });
245 246 247

    // Load FIlter Offets
    loadFilterOffsets();
248 249 250 251 252 253 254 255 256 257 258 259
}

Capture::~Capture()
{
    qDeleteAll(jobs);
}

void Capture::setDefaultCCD(QString ccd)
{
    Options::setDefaultCaptureCCD(ccd);
}

260
void Capture::addCCD(ISD::GDInterface * newCCD)
261
{
262
    ISD::CCD * ccd = static_cast<ISD::CCD *> (newCCD);
263 264

    if (CCDs.contains(ccd))
265
        return;
266 267 268 269 270 271 272 273 274

    CCDs.append(ccd);

    CCDCaptureCombo->addItem(ccd->getDeviceName());

    if (Filters.count() > 0)
        syncFilterInfo();
}

275
void Capture::addGuideHead(ISD::GDInterface * newCCD)
276 277 278 279 280 281 282 283 284 285
{
    QString guiderName = newCCD->getDeviceName() + QString(" Guider");

    if (CCDCaptureCombo->findText(guiderName) == -1)
    {
        CCDCaptureCombo->addItem(guiderName);
        CCDs.append(static_cast<ISD::CCD *> (newCCD));
    }
}

286
void Capture::addFilter(ISD::GDInterface * newFilter)
287
{
288
    foreach(ISD::GDInterface * filter, Filters)
289 290 291 292 293 294 295 296 297
    {
        if (!strcmp(filter->getDeviceName(), newFilter->getDeviceName()))
            return;
    }

    FilterCaptureCombo->addItem(newFilter->getDeviceName());

    Filters.append(static_cast<ISD::Filter *>(newFilter));

298 299
    filterOffsetB->setEnabled(true);

300 301 302 303 304 305 306 307 308 309 310 311 312 313
    checkFilter(0);

    FilterCaptureCombo->setCurrentIndex(0);

}

void Capture::pause()
{
    pauseFunction=NULL;
    state = CAPTURE_PAUSED;
    emit newStatus(Ekos::CAPTURE_PAUSED);
    appendLogText(i18n("Sequence shall be paused after current exposure is complete."));
    pauseB->setEnabled(false);

314
    startB->setIcon(QIcon::fromTheme("media-playback-start", QIcon(":/icons/breeze/default/media-playback-start.svg") ));
315 316 317 318 319 320 321
    startB->setToolTip(i18n("Resume Sequence"));
}

void Capture::toggleSequence()
{
    if (state == CAPTURE_PAUSED)
    {
322
        startB->setIcon(QIcon::fromTheme("media-playback-stop", QIcon(":/icons/breeze/default/media-playback-stop.svg") ));
323 324 325 326 327 328 329 330 331 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
        startB->setToolTip(i18n("Stop Sequence"));
        pauseB->setEnabled(true);

        state = CAPTURE_CAPTURING;
        emit newStatus(Ekos::CAPTURE_CAPTURING);

        appendLogText(i18n("Sequence resumed."));

        // Call from where ever we have left of when we paused
        if (pauseFunction)
            (this->*pauseFunction)();
    }
    else if (state == CAPTURE_IDLE || state == CAPTURE_COMPLETE)
    {
        start();
    }
    else
    {
        abort();
    }
}

void Capture::start()
{
    if (darkSubCheck->isChecked())
    {
        KMessageBox::error(this, i18n("Auto dark subtract is not supported in batch mode."));
        return;
    }

    Options::setGuideDeviation(guideDeviation->value());
    Options::setEnforceGuideDeviation(guideDeviationCheck->isChecked());
    Options::setEnforceAutofocus(autofocusCheck->isChecked());
    Options::setAutoMeridianFlip(meridianCheck->isChecked());
357
    Options::setAutoMeridianHours(meridianHours->value());
358
    Options::setUseFITSViewerInCapture(useFITSViewerInCapture->isChecked());
359 360 361 362

    if (queueTable->rowCount() ==0)
        addJob();

363
    SequenceJob * first_job = NULL;
364

365
    foreach(SequenceJob * job, jobs)
366 367 368 369 370 371 372 373 374 375
    {
        if (job->getStatus() == SequenceJob::JOB_IDLE || job->getStatus() == SequenceJob::JOB_ABORTED)
        {
            first_job = job;
            break;
        }
    }

    if (first_job == NULL)
    {
376
        foreach(SequenceJob * job, jobs)
377 378 379 380 381 382 383 384 385 386 387 388 389
        {
            if (job->getStatus() != SequenceJob::JOB_DONE)
            {
                appendLogText(i18n("No pending jobs found. Please add a job to the sequence queue."));
                return;
            }
        }

        if (KMessageBox::warningContinueCancel(NULL, i18n("All jobs are complete. Do you want to reset the status of all jobs and restart capturing?"),
                                               i18n("Reset job status"), KStandardGuiItem::cont(), KStandardGuiItem::cancel(),
                                               "reset_job_complete_status_warning") !=KMessageBox::Continue)
            return;

390
        foreach(SequenceJob * job, jobs)
391 392 393 394 395 396 397 398
            job->resetStatus();

        first_job = jobs.first();
    }

    deviationDetected = false;
    spikeDetected     = false;

399
    lastFilterOffset  = 0;
400 401 402 403 404
    // lastFilterOffset should be set to the offset of the current used filter so that any subsequent filter change
    // is made against this startup value
    if (currentFilterPosition > 0)
    {
        QString currentFilterName = FilterPosCombo->itemText(currentFilterPosition-1);
405
        foreach(FocusOffset * offset, filterFocusOffsets)
406 407 408 409 410 411 412 413
        {
            if (offset->filter == currentFilterName)
            {
                lastFilterOffset = offset->offset;
                break;
            }
        }
    }
414

415
    ditherCounter     = Options::ditherFrames();
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
    initialHA = getCurrentHA();
    meridianFlipStage = MF_NONE;

    // Check if we need to update the sequence directory numbers before starting
    /*for (int i=0; i < jobs.count(); i++)
    {
        QString firstDir = jobs.at(i)->getFITSDir();
        int sequenceID=1;

        for (int j=i+1; j < jobs.count(); j++)
        {
            if (firstDir == jobs.at(j)->getFITSDir())
            {
                jobs.at(i)->setFITSDir(QString("%1/Sequence_1").arg(firstDir));
                jobs.at(j)->setFITSDir(QString("%1/Sequence_%2").arg(jobs.at(j)->getFITSDir()).arg(++sequenceID));
            }
        }
    }*/

    state = CAPTURE_PROGRESS;
    emit newStatus(Ekos::CAPTURE_PROGRESS);

438
    startB->setIcon(QIcon::fromTheme("media-playback-stop", QIcon(":/icons/breeze/default/media-playback-stop.svg") ));
439 440 441
    startB->setToolTip(i18n("Stop Sequence"));
    pauseB->setEnabled(true);

442
    setBusy(true);
443 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

    prepareJob(first_job);

}

void Capture::stop(bool abort)
{

    retries              = 0;
    seqTotalCount        = 0;
    seqCurrentCount      = 0;
    //ADURaw1 = ADURaw2 = ExpRaw1 = ExpRaw2 = -1;
    //ADUSlope = 0;
    ADURaw.clear();
    ExpRaw.clear();

    calibrationStage = CAL_NONE;

    if (activeJob)
    {
        if (activeJob->getStatus() == SequenceJob::JOB_BUSY)
        {
            KNotification::event( QLatin1String( "CaptureFailed"), i18n("CCD capture failed with errors") );
            activeJob->abort();
            emit newStatus(Ekos::CAPTURE_ABORTED);
        }

Jasem Mutlaq's avatar
Jasem Mutlaq committed
470 471 472 473 474 475 476 477 478 479 480 481
        if (activeJob->isPreview() == false)
        {
            activeJob->disconnect(this);
            activeJob->reset();
        }
        else // Delete preview job
        {
            jobs.removeOne(activeJob);
            delete (activeJob);
            activeJob = nullptr;
        }

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
    }

    state = CAPTURE_IDLE;

    // Turn off any calibration light, IF they were turned on by Capture module
    if  (dustCap && dustCapLightEnabled)
    {
        dustCapLightEnabled = false;
        dustCap->SetLightEnabled(false);
    }
    if (lightBox && lightBoxLightEnabled)
    {
        lightBoxLightEnabled = false;
        lightBox->SetLightEnabled(false);
    }

    secondsLabel->clear();
499 500 501
    disconnect(currentCCD, SIGNAL(BLOBUpdated(IBLOB *)), this, SLOT(newFITS(IBLOB *)));
    disconnect(currentCCD, SIGNAL(newImage(QImage *,ISD::CCDChip *)), this, SLOT(sendNewImage(QImage *,ISD::CCDChip *)));
    disconnect(currentCCD, SIGNAL(newExposureValue(ISD::CCDChip *,double, IPState)), this, SLOT(setExposureProgress(ISD::CCDChip *,double,IPState)));
502 503 504 505 506 507 508 509 510 511 512 513 514 515

    currentCCD->setFITSDir("");

    imgProgress->reset();
    imgProgress->setEnabled(false);

    fullImgCountOUT->setText(QString());
    currentImgCountOUT->setText(QString());
    exposeOUT->setText(QString());

    setBusy(false);

    if (abort)
    {
516
        startB->setIcon(QIcon::fromTheme("media-playback-start", QIcon(":/icons/breeze/default/media-playback-start.svg") ));
517 518 519 520
        startB->setToolTip(i18n("Start Sequence"));
        pauseB->setEnabled(false);
    }

521
    //foreach (QAbstractButton *button, queueEditButtonGroup->buttons())
522
    //button->setEnabled(true);
523 524 525 526 527

    seqTimer->stop();

}

528
void Capture::sendNewImage(QImage * image, ISD::CCDChip * myChip)
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
{
    if (activeJob && myChip != guideChip)
        emit newImage(image, activeJob);
}

bool Capture::setCCD(QString device)
{
    for (int i=0; i < CCDCaptureCombo->count(); i++)
        if (device == CCDCaptureCombo->itemText(i))
        {
            CCDCaptureCombo->setCurrentIndex(i);
            return true;
        }

    return false;
}

void Capture::checkCCD(int ccdNum)
{
    if (ccdNum == -1)
    {
        ccdNum = CCDCaptureCombo->currentIndex();

        if (ccdNum == -1)
            return;
    }

556
    foreach(ISD::CCD * ccd, CCDs)
557
    {
558
        disconnect(ccd, SIGNAL(numberUpdated(INumberVectorProperty *)), this, SLOT(processCCDNumber(INumberVectorProperty *)));
559 560
        disconnect(ccd, SIGNAL(newTemperatureValue(double)), this, SLOT(updateCCDTemperature(double)));
        disconnect(ccd, SIGNAL(newRemoteFile(QString)), this, SLOT(setNewRemoteFile(QString)));
561
        disconnect(ccd, SIGNAL(videoStreamToggled(bool)), this, SLOT(setVideoStreamEnabled(bool)));
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
    }

    if (ccdNum <= CCDs.count())
    {
        // Check whether main camera or guide head only
        currentCCD = CCDs.at(ccdNum);

        if (CCDCaptureCombo->itemText(ccdNum).right(6) == QString("Guider"))
        {
            useGuideHead = true;
            targetChip = currentCCD->getChip(ISD::CCDChip::GUIDE_CCD);
        }
        else
        {
            currentCCD = CCDs.at(ccdNum);
            targetChip = currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);
            useGuideHead = false;
        }

        if (currentCCD->hasCooler())
        {
            temperatureCheck->setEnabled(true);
            temperatureIN->setEnabled(true);

            if (currentCCD->getBaseDevice()->getPropertyPermission("CCD_TEMPERATURE") != IP_RO)
            {
                double min,max,step;
                setTemperatureB->setEnabled(true);
                temperatureIN->setReadOnly(false);
591
                temperatureCheck->setEnabled(true);
592 593 594 595 596 597 598 599 600
                currentCCD->getMinMaxStep("CCD_TEMPERATURE", "CCD_TEMPERATURE_VALUE", &min, &max, &step);
                temperatureIN->setMinimum(min);
                temperatureIN->setMaximum(max);
                temperatureIN->setSingleStep(1);
            }
            else
            {
                setTemperatureB->setEnabled(false);
                temperatureIN->setReadOnly(true);
601
                temperatureCheck->setEnabled(false);
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
            }

            double temperature=0;
            if (currentCCD->getTemperature(&temperature))
            {
                temperatureOUT->setText(QString::number(temperature, 'f', 2));
                if (temperatureIN->cleanText().isEmpty())
                    temperatureIN->setValue(temperature);
            }
        }
        else
        {
            temperatureCheck->setEnabled(false);
            temperatureIN->setEnabled(false);
            temperatureIN->clear();
617
            temperatureOUT->clear();
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638
            setTemperatureB->setEnabled(false);
        }

        updateFrameProperties();

        QStringList frameTypes = targetChip->getFrameTypes();

        frameTypeCombo->clear();

        if (frameTypes.isEmpty())
            frameTypeCombo->setEnabled(false);
        else
        {
            frameTypeCombo->setEnabled(true);
            frameTypeCombo->addItems(frameTypes);
            frameTypeCombo->setCurrentIndex(targetChip->getFrameType());
        }

        QStringList isoList = targetChip->getISOList();
        ISOCombo->clear();

639
        transferFormatCombo->disconnect();
640 641
        transferFormatCombo->clear();

642 643 644
        if (isoList.isEmpty())
        {
            ISOCombo->setEnabled(false);
645
            ISOLabel->setEnabled(false);
646 647
            // Only one trasnfer format
            transferFormatCombo->addItem(i18n("FITS"));
648 649 650 651
        }
        else
        {
            ISOCombo->setEnabled(true);
652
            ISOLabel->setEnabled(true);
653 654
            ISOCombo->addItems(isoList);
            ISOCombo->setCurrentIndex(targetChip->getISOIndex());
Jasem Mutlaq's avatar
Jasem Mutlaq committed
655

656 657 658
            // DSLRs have two transfer formats
            transferFormatCombo->addItem(i18n("FITS"));
            transferFormatCombo->addItem(i18n("Native"));
659 660 661 662
            transferFormatCombo->setCurrentIndex(currentCCD->getTargetTransferFormat());
            // Keep track of TARGET transfer format when changing CCDs (FITS or NATIVE). Actual format is not changed until capture
            connect(transferFormatCombo, static_cast<void (QComboBox::*) (int)>(&QComboBox::activated), this, [&](int index)
            {
663
                currentCCD->setTargetTransferFormat(static_cast<ISD::CCD::TransferFormat>(index));
664
            });
665 666 667 668 669

            double pixelX=0, pixelY=0;
            bool rc = targetChip->getPixelSize(pixelX, pixelY);
            if (rc == false || pixelX == 0 || pixelY == 0)
            {
670 671 672
                DSLRInfo infoDialog(this, currentCCD);
                infoDialog.exec();
                //appendLogText(i18n("DSLR CCD Information is incomplete. Please update CCD Information in Image Info section in the INDI Control Panel."));
673
            }
674 675
        }

676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
        gainLabel->setEnabled(currentCCD->hasGain());
        gainIN->setEnabled(currentCCD->hasGain());
        if (gainIN->isEnabled())
        {
            double gain=0, min=0,max=0,step=1;
            currentCCD->getGainMinMaxStep(&min, &max, &step);
            if (currentCCD->getGain(&gain))
            {
                gainIN->setMinimum(min);
                gainIN->setMaximum(max);
                if (step > 0)
                    gainIN->setSingleStep(step);
                gainIN->setValue(gain);
            }
        }
        else
            gainIN->clear();

694
        liveVideoB->setEnabled(currentCCD->hasVideoStream());
695
        setVideoStreamEnabled(currentCCD->isStreamingEnabled());
696

697
        connect(currentCCD, SIGNAL(numberUpdated(INumberVectorProperty *)), this, SLOT(processCCDNumber(INumberVectorProperty *)), Qt::UniqueConnection);
698 699
        connect(currentCCD, SIGNAL(newTemperatureValue(double)), this, SLOT(updateCCDTemperature(double)), Qt::UniqueConnection);
        connect(currentCCD, SIGNAL(newRemoteFile(QString)), this, SLOT(setNewRemoteFile(QString)));
700
        connect(currentCCD, SIGNAL(videoStreamToggled(bool)), this, SLOT(setVideoStreamEnabled(bool)));
701 702 703
    }
}

704 705 706 707 708 709 710 711 712 713 714 715
void Capture::setGuideChip(ISD::CCDChip * chip)
{
    guideChip = chip;
    // We should suspend guide in two scenarios:
    // 1. If guide chip is within the primary CCD, then we cannot download any data from guide chip while primary CCD is downloading.
    // 2. If we have two CCDs running from ONE driver (Multiple-Devices-Per-Driver mpdp is true). Same issue as above, only one download
    // at a time.
    // After primary CCD download is complete, we resume guiding.
    suspendGuideOnDownload = (currentCCD->getChip(ISD::CCDChip::GUIDE_CCD) == guideChip) ||
                             (guideChip->getCCD() == currentCCD && currentCCD->getDriverInfo()->getAuxInfo().value("mdpd", false).toBool());
}

716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
void Capture::resetFrameToZero()
{
    frameXIN->setMinimum(0);
    frameXIN->setMaximum(0);
    frameXIN->setValue(0);

    frameYIN->setMinimum(0);
    frameYIN->setMaximum(0);
    frameYIN->setValue(0);

    frameWIN->setMinimum(0);
    frameWIN->setMaximum(0);
    frameWIN->setValue(0);

    frameHIN->setMinimum(0);
    frameHIN->setMaximum(0);
    frameHIN->setValue(0);
}

735
void Capture::updateFrameProperties(int reset)
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759
{
    int x,y,w,h;
    int binx=1,biny=1;
    double min,max,step;
    int xstep=0, ystep=0;

    QString frameProp = useGuideHead ? QString("GUIDER_FRAME") : QString("CCD_FRAME");
    QString exposureProp = useGuideHead ? QString("GUIDER_EXPOSURE") : QString("CCD_EXPOSURE");
    QString exposureElem = useGuideHead ? QString("GUIDER_EXPOSURE_VALUE") : QString("CCD_EXPOSURE_VALUE");
    targetChip = useGuideHead ? currentCCD->getChip(ISD::CCDChip::GUIDE_CCD) : currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);

    frameWIN->setEnabled(targetChip->canSubframe());
    frameHIN->setEnabled(targetChip->canSubframe());
    frameXIN->setEnabled(targetChip->canSubframe());
    frameYIN->setEnabled(targetChip->canSubframe());

    binXIN->setEnabled(targetChip->canBin());
    binYIN->setEnabled(targetChip->canBin());

    if (currentCCD->getMinMaxStep(exposureProp, exposureElem, &min, &max, &step))
    {
        exposureIN->setMinimum(min);
        exposureIN->setMaximum(max);
        exposureIN->setSingleStep(step);
760 761 762 763 764

        if (min < 0.001)
            exposureIN->setDecimals(6);
        else
            exposureIN->setDecimals(3);
765 766 767 768
    }

    if (currentCCD->getMinMaxStep(frameProp, "WIDTH", &min, &max, &step))
    {
769 770 771
        if (min >= max)
        {
            resetFrameToZero();
772
            return;
773
        }
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791

        if (step == 0)
            xstep = (int) max * 0.05;
        else
            xstep = step;

        if (min >= 0 && max > 0)
        {
            frameWIN->setMinimum(min);
            frameWIN->setMaximum(max);
            frameWIN->setSingleStep(xstep);
        }
    }
    else
        return;

    if (currentCCD->getMinMaxStep(frameProp, "HEIGHT", &min, &max, &step))
    {
792 793 794
        if (min >= max)
        {
            resetFrameToZero();
795
            return;
796
        }
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814

        if (step == 0)
            ystep = (int) max * 0.05;
        else
            ystep = step;

        if (min >= 0 && max > 0)
        {
            frameHIN->setMinimum(min);
            frameHIN->setMaximum(max);
            frameHIN->setSingleStep(ystep);
        }
    }
    else
        return;

    if (currentCCD->getMinMaxStep(frameProp, "X", &min, &max, &step))
    {
815 816 817
        if (min >= max)
        {
            resetFrameToZero();
818
            return;
819
        }
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835

        if (step == 0)
            step = xstep;

        if (min >= 0 && max > 0)
        {
            frameXIN->setMinimum(min);
            frameXIN->setMaximum(max);
            frameXIN->setSingleStep(step);
        }
    }
    else
        return;

    if (currentCCD->getMinMaxStep(frameProp, "Y", &min, &max, &step))
    {
836 837 838
        if (min >= max)
        {
            resetFrameToZero();
839
            return;
840
        }
841 842 843 844 845 846 847 848 849 850 851 852 853 854

        if (step == 0)
            step = ystep;

        if (min >= 0 && max > 0)
        {
            frameYIN->setMinimum(min);
            frameYIN->setMaximum(max);
            frameYIN->setSingleStep(step);
        }
    }
    else
        return;

855
    if (reset == 1 || frameSettings.contains(targetChip) == false)
856 857 858 859 860 861 862 863 864 865 866 867
    {
        QVariantMap settings;

        settings["x"] = 0;
        settings["y"] = 0;
        settings["w"] = frameWIN->maximum();
        settings["h"] = frameHIN->maximum();
        settings["binx"] = 1;
        settings["biny"] = 1;

        frameSettings[targetChip] = settings;
    }
868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
    else if (reset == 2 && frameSettings.contains(targetChip))
    {
        QVariantMap settings = frameSettings[targetChip];
        int x,y,w,h;

        x = settings["x"].toInt();
        y = settings["y"].toInt();
        w = settings["w"].toInt();
        h = settings["h"].toInt();

        // Bound them
        x = qBound(frameXIN->minimum(), x, frameXIN->maximum()-1);
        y = qBound(frameYIN->minimum(), y, frameYIN->maximum()-1);
        w = qBound(frameWIN->minimum(), w, frameWIN->maximum());
        h = qBound(frameHIN->minimum(), h, frameHIN->maximum());

        settings["x"] = x;
        settings["y"] = y;
        settings["w"] = w;
        settings["h"] = h;

        frameSettings[targetChip] = settings;
    }
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926

    if (frameSettings.contains(targetChip))
    {
        QVariantMap settings = frameSettings[targetChip];

        if (targetChip->canBin())
        {
            targetChip->getMaxBin(&binx, &biny);
            binXIN->setMaximum(binx);
            binYIN->setMaximum(biny);

            binXIN->setValue(settings["binx"].toInt());
            binYIN->setValue(settings["biny"].toInt());
        }
        else
        {
            binXIN->setValue(1);
            binYIN->setValue(1);
        }

        x = settings["x"].toInt();
        y = settings["y"].toInt();
        w = settings["w"].toInt();
        h = settings["h"].toInt();

        if (x >= 0)
            frameXIN->setValue(x);
        if (y >= 0)
            frameYIN->setValue(y);
        if (w > 0)
            frameWIN->setValue(w);
        if (h > 0)
            frameHIN->setValue(h);
    }
}

927
void Capture::processCCDNumber(INumberVectorProperty * nvp)
928
{
929 930 931 932
    if (currentCCD == NULL)
        return;

    if ((!strcmp(nvp->name, "CCD_FRAME") && useGuideHead == false) || (!strcmp(nvp->name, "GUIDER_FRAME") && useGuideHead))
933
        updateFrameProperties();
934 935
    else if ((!strcmp(nvp->name, "CCD_INFO") && useGuideHead == false) || (!strcmp(nvp->name, "GUIDER_INFO") && useGuideHead))
        updateFrameProperties(2);
936 937 938 939 940 941
}

void Capture::resetFrame()
{
    targetChip = useGuideHead ? currentCCD->getChip(ISD::CCDChip::GUIDE_CCD) : currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);
    targetChip->resetFrame();
942
    updateFrameProperties(1);
943 944
}

945
void Capture::syncFrameType(ISD::GDInterface * ccd)
946 947 948 949
{
    if (strcmp(ccd->getDeviceName(), CCDCaptureCombo->currentText().toLatin1()))
        return;

950
    ISD::CCDChip * tChip = NULL;
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
    tChip = (static_cast<ISD::CCD *> (ccd) )->getChip(ISD::CCDChip::PRIMARY_CCD);

    QStringList frameTypes = tChip->getFrameTypes();

    frameTypeCombo->clear();

    if (frameTypes.isEmpty())
        frameTypeCombo->setEnabled(false);
    else
    {
        frameTypeCombo->setEnabled(true);
        frameTypeCombo->addItems(frameTypes);
        frameTypeCombo->setCurrentIndex(tChip->getFrameType());
    }


}

bool Capture::setFilter(QString device, int filterSlot)
{
    bool deviceFound=false;

    for (int i=0; i < FilterCaptureCombo->count(); i++)
        if (device == FilterCaptureCombo->itemText(i))
        {
            checkFilter(i);
            deviceFound = true;
            break;
        }

    if (deviceFound == false)
        return false;

    if (filterSlot < FilterCaptureCombo->count())
        FilterCaptureCombo->setCurrentIndex(filterSlot);

    return true;
}

void Capture::checkFilter(int filterNum)
{

    if (filterNum == -1)
    {
        filterNum = FilterCaptureCombo->currentIndex();
        if (filterNum == -1)
            return;
    }


    QStringList filterAlias = Options::filterAlias();

    if (filterNum <= Filters.count())
        currentFilter = Filters.at(filterNum);

    syncFilterInfo();

    FilterPosCombo->clear();

    filterName   = currentFilter->getBaseDevice()->getText("FILTER_NAME");
    filterSlot = currentFilter->getBaseDevice()->getNumber("FILTER_SLOT");

    if (filterSlot == NULL)
    {
        KMessageBox::error(0, i18n("Unable to find FILTER_SLOT property in driver %1", currentFilter->getBaseDevice()->getDeviceName()));
        return;
    }

    for (int i=0; i < filterSlot->np[0].max; i++)
    {
        QString item;

        if (filterName != NULL && (i < filterName->ntp))
            item = filterName->tp[i].text;
        else if (i < filterAlias.count() && filterAlias[i].isEmpty() == false)
            item = filterAlias.at(i);
        else
            item = QString("Filter_%1").arg(i+1);

        FilterPosCombo->addItem(item);

    }

    FilterPosCombo->setCurrentIndex( (int) filterSlot->np[0].value-1);

    currentFilterPosition = (int) filterSlot->np[0].value;

    if (activeJob && (activeJob->getStatus() == SequenceJob::JOB_ABORTED || activeJob->getStatus() == SequenceJob::JOB_IDLE))
        activeJob->setCurrentFilter(currentFilterPosition);

}

void Capture::syncFilterInfo()
{
    if (currentCCD && currentFilter)
    {
1047
        ITextVectorProperty * activeDevices = currentCCD->getBaseDevice()->getText("ACTIVE_DEVICES");
1048 1049
        if (activeDevices)
        {
1050
            IText * activeFilter = IUFindText(activeDevices, "ACTIVE_FILTER");
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
            if (activeFilter && strcmp(activeFilter->text, currentFilter->getDeviceName()))
            {
                IUSaveText(activeFilter, currentFilter->getDeviceName());
                currentCCD->getDriverInfo()->getClientManager()->sendNewText(activeDevices);
            }
        }
    }
}

bool Capture::startNextExposure()
{
    if (state == CAPTURE_PAUSED)
    {
        pauseFunction = &Capture::startNextExposure;
        appendLogText(i18n("Sequence paused."));
        secondsLabel->setText(i18n("Paused..."));
        return false;
    }

    if (seqDelay > 0)
    {
        secondsLabel->setText(i18n("Waiting..."));
        state = CAPTURE_WAITING;
        emit newStatus(Ekos::CAPTURE_WAITING);
    }

    seqTimer->start(seqDelay);

    return true;
}

1082
void Capture::newFITS(IBLOB * bp)
1083
{
1084
    ISD::CCDChip * tChip = NULL;
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118

    // If there is no active job, ignore
    if (activeJob == NULL || meridianFlipStage >= MF_ALIGNING)
        return;

    if (currentCCD->getUploadMode() != ISD::CCD::UPLOAD_LOCAL)
    {
        if (bp == NULL)
        {
            abort();
            return;
        }

        if (!strcmp(bp->name, "CCD2"))
            tChip = currentCCD->getChip(ISD::CCDChip::GUIDE_CCD);
        else
            tChip = currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);

        if (tChip != targetChip)
            return;

        if (targetChip->getCaptureMode() == FITS_FOCUS || targetChip->getCaptureMode() == FITS_GUIDE)
            return;

        // If this is a preview job, make sure to enable preview button after
        // we receive the FITS
        if (activeJob->isPreview() && previewB->isEnabled() == false)
            previewB->setEnabled(true);

        // If the FITS is not for our device, simply ignore
        //if (QString(bp->bvp->device)  != currentCCD->getDeviceName() || (startB->isEnabled() && previewB->isEnabled()))
        if (QString(bp->bvp->device)  != currentCCD->getDeviceName() || state == CAPTURE_IDLE)
            return;

1119 1120
        disconnect(currentCCD, SIGNAL(BLOBUpdated(IBLOB *)), this, SLOT(newFITS(IBLOB *)));
        disconnect(currentCCD, SIGNAL(newImage(QImage *, ISD::CCDChip *)), this, SLOT(sendNewImage(QImage *, ISD::CCDChip *)));
1121 1122 1123

        if (useGuideHead == false && darkSubCheck->isChecked() && activeJob->isPreview())
        {
1124 1125
            FITSView * currentImage   = targetChip->getImageView(FITS_NORMAL);
            FITSData * darkData       = NULL;
1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
            uint16_t offsetX = activeJob->getSubX() / activeJob->getXBin();
            uint16_t offsetY = activeJob->getSubY() / activeJob->getYBin();

            darkData = DarkLibrary::Instance()->getDarkFrame(targetChip, activeJob->getExposure());

            connect(DarkLibrary::Instance(), SIGNAL(darkFrameCompleted(bool)), this, SLOT(setCaptureComplete()));
            connect(DarkLibrary::Instance(), SIGNAL(newLog(QString)), this, SLOT(appendLogText(QString)));

            if (darkData)
                DarkLibrary::Instance()->subtract(darkData, currentImage, activeJob->getCaptureFilter(), offsetX, offsetY);
            else
                DarkLibrary::Instance()->captureAndSubtract(targetChip, currentImage, activeJob->getExposure(), offsetX, offsetY);

            return;
        }
    }

    setCaptureComplete();

}

bool Capture::setCaptureComplete()
{
1149
    disconnect(currentCCD, SIGNAL(newExposureValue(ISD::CCDChip *,double,IPState)), this, SLOT(setExposureProgress(ISD::CCDChip *,double,IPState)));
1150 1151 1152 1153 1154 1155
    DarkLibrary::Instance()->disconnect(this);
    secondsLabel->setText(i18n("Complete."));

    // If it was initially set as preview job
    if (seqTotalCount <= 0)
    {
1156 1157 1158 1159 1160 1161
        jobs.removeOne(activeJob);
        delete(activeJob);
        // Reset active job pointer
        activeJob = NULL;
        abort();
        return true;
1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176
    }

    if (state == CAPTURE_PAUSED)
    {
        pauseFunction = &Capture::setCaptureComplete;
        appendLogText(i18n("Sequence paused."));
        secondsLabel->setText(i18n("Paused..."));
        return false;
    }

    if (activeJob->getFrameType() != FRAME_LIGHT)
    {
        if (processPostCaptureCalibrationStage() == false)
            return true;

1177 1178
        if (calibrationStage == CAL_CALIBRATION_COMPLETE)
            calibrationStage = CAL_CAPTURING;
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
    }

    seqCurrentCount++;
    activeJob->setCompleted(seqCurrentCount);
    imgProgress->setValue(seqCurrentCount);

    appendLogText(i18n("Received image %1 out of %2.", seqCurrentCount, seqTotalCount));

    state = CAPTURE_IMAGE_RECEIVED;
    emit newStatus(Ekos::CAPTURE_IMAGE_RECEIVED);

    currentImgCountOUT->setText( QString::number(seqCurrentCount));

    // if we're done
    if (seqCurrentCount >= seqTotalCount)
    {
1195 1196
        processJobCompletion();
        return true;
1197 1198 1199 1200 1201 1202
    }

    // Check if meridian condition is met
    if (checkMeridianFlip())
        return true;

1203
    if (activeJob->getPostCaptureScript().isEmpty() == false)
1204
    {
1205 1206
        postCaptureScript.start(activeJob->getPostCaptureScript());
        appendLogText(i18n("Executing post capture script %1", activeJob->getPostCaptureScript()));
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
    }
    else
        resumeSequence();

    return true;
}

void Capture::processJobCompletion()
{
    activeJob->done();

    stop();

    // Check if meridian condition is met
    if (checkMeridianFlip())
        return;

    // Check if there are more pending jobs and execute them
    if (resumeSequence())
        return;
    // Otherwise, we're done. We park if required and resume guiding if no parking is done and autoguiding was engaged before.
    else
    {
        KNotification::event( QLatin1String( "CaptureSuccessful"), i18n("CCD capture sequence completed"));

        abort();

        state = CAPTURE_COMPLETE;
        emit newStatus(Ekos::CAPTURE_COMPLETE);

        //Resume guiding if it was suspended before
        //if (isAutoGuiding && currentCCD->getChip(ISD::CCDChip::GUIDE_CCD) == guideChip)
1239
        if (guideState == GUIDE_SUSPENDED && suspendGuideOnDownload)
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1240
            emit resumeGuiding();
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256
    }
}

bool Capture::resumeSequence()
{
    if (state == CAPTURE_PAUSED)
    {
        pauseFunction = &Capture::resumeSequence;
        appendLogText(i18n("Sequence paused."));
        secondsLabel->setText(i18n("Paused..."));
        return false;
    }

    // If seqTotalCount is zero, we have to find if there are more pending jobs in the queue
    if (seqTotalCount == 0)
    {
1257
        SequenceJob * next_job = NULL;
1258

1259
        foreach(SequenceJob * job, jobs)
1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
        {
            if (job->getStatus() == SequenceJob::JOB_IDLE || job->getStatus() == SequenceJob::JOB_ABORTED)
            {
                next_job = job;
                break;
            }
        }

        if (next_job)
        {
            prepareJob(next_job);

            //Resume guiding if it was suspended before
            //if (isAutoGuiding && currentCCD->getChip(ISD::CCDChip::GUIDE_CCD) == guideChip)
1274
            if (guideState == GUIDE_SUSPENDED && suspendGuideOnDownload)
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1275
                emit resumeGuiding();
1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296

            return true;
        }
        else
            return false;
    }
    // Otherwise, let's prepare for next exposure after making sure in-sequence focus and dithering are complete if applicable.
    else
    {
        isAutoFocus = (autofocusCheck->isEnabled() && autofocusCheck->isChecked() && HFRPixels->value() > 0);
        if (isAutoFocus)
            autoFocusStatus = false;

        // Reset HFR pixels to zero after merdian flip
        if (isAutoFocus && meridianFlipStage != MF_NONE)
        {
            firstAutoFocus=true;
            HFRPixels->setValue(fileHFR);
        }

        // If we suspended guiding due to primary chip download, resume guide chip guiding now
1297
        if (guideState == GUIDE_SUSPENDED && suspendGuideOnDownload)
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1298
            emit resumeGuiding();
1299

1300
        if (guideState == GUIDE_GUIDING && Options::ditherEnabled() && activeJob->getFrameType() == FRAME_LIGHT && --ditherCounter == 0)
1301
        {
1302
            ditherCounter = Options::ditherFrames();
1303

1304 1305 1306 1307
            secondsLabel->setText(i18n("Dithering..."));

            state = CAPTURE_DITHERING;
            emit newStatus(Ekos::CAPTURE_DITHERING);
1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325
        }
        else if (isAutoFocus && activeJob->getFrameType() == FRAME_LIGHT)
        {
            secondsLabel->setText(i18n("Focusing..."));
            emit checkFocus(HFRPixels->value());

            state = CAPTURE_FOCUSING;
            emit newStatus(Ekos::CAPTURE_FOCUSING);
        }
        else
            startNextExposure();
    }

    return true;
}

void Capture::captureOne()
{
1326 1327
    Options::setUseFITSViewerInCapture(useFITSViewerInCapture->isChecked());

1328 1329
    //if (currentCCD->getUploadMode() == ISD::CCD::UPLOAD_LOCAL)
    if (uploadModeCombo->currentIndex() != 0)
1330
    {
1331
        appendLogText(i18n("Cannot take preview image while CCD upload mode is set to local or both. Please change upload mode to client and try again."));
1332 1333 1334
        return;
    }

1335
    if (transferFormatCombo->currentIndex() == ISD::CCD::FORMAT_NATIVE && darkSubCheck->isChecked())
1336
    {
Yuri Chornoivan's avatar
Yuri Chornoivan committed
1337
        appendLogText(i18n("Cannot perform auto dark subtraction of native DSLR formats."));
1338 1339 1340
        return;
    }

1341 1342 1343 1344 1345 1346 1347
    addJob(true);

    prepareJob(jobs.last());
}

void Capture::captureImage()
{
1348 1349 1350
    if (activeJob == NULL)
        return;

1351
    seqTimer->stop();
1352 1353
    SequenceJob::CAPTUREResult rc=SequenceJob::CAPTURE_OK;

1354 1355 1356 1357 1358 1359 1360
    if (currentCCD->isConnected() == false)
    {
        appendLogText(i18n("Error: Lost connection to CCD."));
        abort();
        return;
    }

1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
    if (focusState >= FOCUS_PROGRESS)
    {
        appendLogText(i18n("Cannot capture while focus module is busy."));
        abort();
        return;
    }

    if (filterSlot != NULL)
    {
        currentFilterPosition = (int) filterSlot->np[