capture.cpp 131 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
#define SQ_FORMAT_VERSION   1.6
56

57 58 59 60 61 62 63 64 65 66
namespace Ekos
{

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

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

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

    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;
89
    targetADUTolerance = 1000;
90 91 92 93 94 95 96 97 98 99 100 101 102 103
    flatFieldDuration = DURATION_MANUAL;
    flatFieldSource   = SOURCE_MANUAL;
    calibrationStage         = CAL_NONE;
    preMountPark           = false;
    preDomePark            = false;

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

    ignoreJobProgress=true;

    dustCapLightEnabled = lightBoxLightEnabled = false;

104
    //isAutoGuiding   = false;
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    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()));

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

137 138
    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
139
    filterOffsetB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
140

141 142 143 144 145
    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)));

146 147
    connect(liveVideoB, SIGNAL(clicked(bool)), this, SLOT(toggleVideoStream(bool)));

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

    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()));

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

    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;
207
    useGuideHead = false;
208 209 210 211 212 213 214
    firstAutoFocus = true;

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

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

    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()));
226 227
    connect(uploadModeCombo, SIGNAL(activated(int)), this, SLOT(setDirty()));
    connect(remoteDirIN, SIGNAL(editingFinished()), this, SLOT(setDirty()));
228

229 230 231 232
    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()));
233

234
    // Post capture script
235
    connect(&postCaptureScript, SIGNAL(finished(int)), this, SLOT(postScriptFinished(int)));
236 237 238

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

    // Load FIlter Offets
    loadFilterOffsets();
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
}

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

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

void Capture::addCCD(ISD::GDInterface *newCCD)
{
    ISD::CCD *ccd = static_cast<ISD::CCD *> (newCCD);

    if (CCDs.contains(ccd))
            return;

    CCDs.append(ccd);

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

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

void Capture::addGuideHead(ISD::GDInterface *newCCD)
{
    QString guiderName = newCCD->getDeviceName() + QString(" Guider");

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

void Capture::addFilter(ISD::GDInterface *newFilter)
{
    foreach(ISD::GDInterface *filter, Filters)
    {
        if (!strcmp(filter->getDeviceName(), newFilter->getDeviceName()))
            return;
    }

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

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

292 293
    filterOffsetB->setEnabled(true);

294 295 296 297 298 299 300 301 302 303 304 305 306 307
    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);

308
    startB->setIcon(QIcon::fromTheme("media-playback-start", QIcon(":/icons/breeze/default/media-playback-start.svg") ));
309 310 311 312 313 314 315
    startB->setToolTip(i18n("Resume Sequence"));
}

void Capture::toggleSequence()
{
    if (state == CAPTURE_PAUSED)
    {
316
        startB->setIcon(QIcon::fromTheme("media-playback-stop", QIcon(":/icons/breeze/default/media-playback-stop.svg") ));
317 318 319 320 321 322 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
        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());
351
    Options::setAutoMeridianHours(meridianHours->value());    
352
    Options::setUseFITSViewerInCapture(useFITSViewerInCapture->isChecked());
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

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

    SequenceJob *first_job = NULL;

    foreach(SequenceJob *job, jobs)
    {
        if (job->getStatus() == SequenceJob::JOB_IDLE || job->getStatus() == SequenceJob::JOB_ABORTED)
        {
            first_job = job;
            break;
        }
    }

    if (first_job == NULL)
    {
        foreach(SequenceJob *job, jobs)
        {
            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;

        foreach(SequenceJob *job, jobs)
            job->resetStatus();

        first_job = jobs.first();
    }

    deviationDetected = false;
    spikeDetected     = false;

393
    lastFilterOffset  = 0;
394 395 396 397 398 399 400 401 402 403 404 405 406 407
    // 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);
        foreach(FocusOffset *offset, filterFocusOffsets)
        {
            if (offset->filter == currentFilterName)
            {
                lastFilterOffset = offset->offset;
                break;
            }
        }
    }
408

409
    ditherCounter     = Options::ditherFrames();
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
    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);

432
    startB->setIcon(QIcon::fromTheme("media-playback-stop", QIcon(":/icons/breeze/default/media-playback-stop.svg") ));
433 434 435
    startB->setToolTip(i18n("Stop Sequence"));
    pauseB->setEnabled(true);

436
    setBusy(true);
437 438 439 440 441 442 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 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484

    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);
        }

        activeJob->disconnect(this);
        activeJob->reset();
    }

    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();
    disconnect(currentCCD, SIGNAL(BLOBUpdated(IBLOB*)), this, SLOT(newFITS(IBLOB*)));
    disconnect(currentCCD, SIGNAL(newImage(QImage*,ISD::CCDChip*)), this, SLOT(sendNewImage(QImage*,ISD::CCDChip*)));
485
    disconnect(currentCCD, SIGNAL(newExposureValue(ISD::CCDChip*,double, IPState)), this, SLOT(setExposureProgress(ISD::CCDChip*,double,IPState)));
486 487 488 489 490 491 492 493 494 495 496 497 498 499

    currentCCD->setFITSDir("");

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

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

    setBusy(false);

    if (abort)
    {
500
        startB->setIcon(QIcon::fromTheme("media-playback-start", QIcon(":/icons/breeze/default/media-playback-start.svg") ));
501 502 503 504
        startB->setToolTip(i18n("Start Sequence"));
        pauseB->setEnabled(false);
    }

505 506
    //foreach (QAbstractButton *button, queueEditButtonGroup->buttons())
        //button->setEnabled(true);
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544

    seqTimer->stop();

}

void Capture::sendNewImage(QImage *image, ISD::CCDChip *myChip)
{
    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;
    }

    foreach(ISD::CCD *ccd, CCDs)
    {
        disconnect(ccd, SIGNAL(numberUpdated(INumberVectorProperty*)), this, SLOT(processCCDNumber(INumberVectorProperty*)));
        disconnect(ccd, SIGNAL(newTemperatureValue(double)), this, SLOT(updateCCDTemperature(double)));
        disconnect(ccd, SIGNAL(newRemoteFile(QString)), this, SLOT(setNewRemoteFile(QString)));
545
        disconnect(ccd, SIGNAL(videoStreamToggled(bool)), this, SLOT(setVideoStreamEnabled(bool)));
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
    }

    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);
575
                temperatureCheck->setEnabled(true);
576 577 578 579 580 581 582 583 584
                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);
585
                temperatureCheck->setEnabled(false);
586 587 588 589 590 591 592 593 594 595 596 597 598 599 600
            }

            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();
601
            temperatureOUT->clear();
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
            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();

623
        transferFormatCombo->disconnect();
624 625
        transferFormatCombo->clear();

626 627 628
        if (isoList.isEmpty())
        {
            ISOCombo->setEnabled(false);
629
            ISOLabel->setEnabled(false);
630 631
            // Only one trasnfer format
            transferFormatCombo->addItem(i18n("FITS"));
632 633 634 635
        }
        else
        {
            ISOCombo->setEnabled(true);
636
            ISOLabel->setEnabled(true);
637 638
            ISOCombo->addItems(isoList);
            ISOCombo->setCurrentIndex(targetChip->getISOIndex());
Jasem Mutlaq's avatar
Jasem Mutlaq committed
639

640 641 642
            // DSLRs have two transfer formats
            transferFormatCombo->addItem(i18n("FITS"));
            transferFormatCombo->addItem(i18n("Native"));
643 644 645 646
            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)
            {
647
                currentCCD->setTargetTransferFormat(static_cast<ISD::CCD::TransferFormat>(index));
648
            });
649 650 651 652 653

            double pixelX=0, pixelY=0;
            bool rc = targetChip->getPixelSize(pixelX, pixelY);
            if (rc == false || pixelX == 0 || pixelY == 0)
            {
654 655 656
                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."));
657
            }
658 659
        }

660
        liveVideoB->setEnabled(currentCCD->hasVideoStream());
661
        setVideoStreamEnabled(currentCCD->isStreamingEnabled());
662

663 664 665
        connect(currentCCD, SIGNAL(numberUpdated(INumberVectorProperty*)), this, SLOT(processCCDNumber(INumberVectorProperty*)), Qt::UniqueConnection);
        connect(currentCCD, SIGNAL(newTemperatureValue(double)), this, SLOT(updateCCDTemperature(double)), Qt::UniqueConnection);
        connect(currentCCD, SIGNAL(newRemoteFile(QString)), this, SLOT(setNewRemoteFile(QString)));
666
        connect(currentCCD, SIGNAL(videoStreamToggled(bool)), this, SLOT(setVideoStreamEnabled(bool)));
667 668 669
    }
}

670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688
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);
}

689
void Capture::updateFrameProperties(int reset)
690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
{
    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);
    }

    if (currentCCD->getMinMaxStep(frameProp, "WIDTH", &min, &max, &step))
    {
718 719 720
        if (min >= max)
        {
            resetFrameToZero();
721
            return;
722
        }
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740

        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))
    {
741 742 743
        if (min >= max)
        {
            resetFrameToZero();
744
            return;
745
        }
746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763

        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))
    {
764 765 766
        if (min >= max)
        {
            resetFrameToZero();
767
            return;
768
        }
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784

        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))
    {
785 786 787
        if (min >= max)
        {
            resetFrameToZero();
788
            return;
789
        }
790 791 792 793 794 795 796 797 798 799 800 801 802 803

        if (step == 0)
            step = ystep;

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

804
    if (reset == 1 || frameSettings.contains(targetChip) == false)
805 806 807 808 809 810 811 812 813 814 815 816
    {
        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;
    }
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
    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;
    }
840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877

    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);
    }
}

void Capture::processCCDNumber(INumberVectorProperty *nvp)
{
878 879 880 881
    if (currentCCD == NULL)
        return;

    if ((!strcmp(nvp->name, "CCD_FRAME") && useGuideHead == false) || (!strcmp(nvp->name, "GUIDER_FRAME") && useGuideHead))
882
        updateFrameProperties();
883 884
    else if ((!strcmp(nvp->name, "CCD_INFO") && useGuideHead == false) || (!strcmp(nvp->name, "GUIDER_INFO") && useGuideHead))
        updateFrameProperties(2);
885 886 887 888 889 890
}

void Capture::resetFrame()
{
    targetChip = useGuideHead ? currentCCD->getChip(ISD::CCDChip::GUIDE_CCD) : currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);
    targetChip->resetFrame();
891
    updateFrameProperties(1);
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 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 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 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
}

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

    ISD::CCDChip *tChip = NULL;
    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)
    {
        ITextVectorProperty *activeDevices = currentCCD->getBaseDevice()->getText("ACTIVE_DEVICES");
        if (activeDevices)
        {
            IText *activeFilter = IUFindText(activeDevices, "ACTIVE_FILTER");
            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;
}

void Capture::newFITS(IBLOB *bp)
{
    ISD::CCDChip *tChip = NULL;

    // 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;

        disconnect(currentCCD, SIGNAL(BLOBUpdated(IBLOB*)), this, SLOT(newFITS(IBLOB*)));
        disconnect(currentCCD, SIGNAL(newImage(QImage*, ISD::CCDChip*)), this, SLOT(sendNewImage(QImage*, ISD::CCDChip*)));

        if (useGuideHead == false && darkSubCheck->isChecked() && activeJob->isPreview())
        {
1073
            FITSView *currentImage   = targetChip->getImageView(FITS_NORMAL);
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
            FITSData *darkData       = NULL;
            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()
{
1098
    disconnect(currentCCD, SIGNAL(newExposureValue(ISD::CCDChip*,double,IPState)), this, SLOT(setExposureProgress(ISD::CCDChip*,double,IPState)));
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
    DarkLibrary::Instance()->disconnect(this);
    secondsLabel->setText(i18n("Complete."));

    // If it was initially set as preview job
    if (seqTotalCount <= 0)
    {
       jobs.removeOne(activeJob);
       delete(activeJob);
       // Reset active job pointer
       activeJob = NULL;
       abort();
       return true;
    }

    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;

            if (calibrationStage == CAL_CALIBRATION_COMPLETE)
                calibrationStage = CAL_CAPTURING;
    }

    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)
    {
       processJobCompletion();
       return true;
    }

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

1152
    if (activeJob->getPostCaptureScript().isEmpty() == false)
1153
    {
1154 1155
        postCaptureScript.start(activeJob->getPostCaptureScript());
        appendLogText(i18n("Executing post capture script %1", activeJob->getPostCaptureScript()));
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
    }
    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)
        if (guideState == GUIDE_SUSPENDED && currentCCD->getChip(ISD::CCDChip::GUIDE_CCD) == guideChip)
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1189
            emit resumeGuiding();
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
    }

}

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)
    {
        SequenceJob *next_job = NULL;

        foreach(SequenceJob *job, jobs)
        {
            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)
            if (guideState == GUIDE_SUSPENDED && currentCCD->getChip(ISD::CCDChip::GUIDE_CCD) == guideChip)
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1225
                emit resumeGuiding();
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247

            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
        if (guideState == GUIDE_SUSPENDED && currentCCD->getChip(ISD::CCDChip::GUIDE_CCD) == guideChip)
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1248
            emit resumeGuiding();
1249

1250
        if (guideState == GUIDE_GUIDING && Options::ditherEnabled() && activeJob->getFrameType() == FRAME_LIGHT && --ditherCounter == 0)
1251
        {
1252
            ditherCounter = Options::ditherFrames();
1253

1254 1255 1256 1257
            secondsLabel->setText(i18n("Dithering..."));

            state = CAPTURE_DITHERING;
            emit newStatus(Ekos::CAPTURE_DITHERING);
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
        }
        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()
{
1276 1277
    Options::setUseFITSViewerInCapture(useFITSViewerInCapture->isChecked());

1278 1279
    //if (currentCCD->getUploadMode() == ISD::CCD::UPLOAD_LOCAL)
    if (uploadModeCombo->currentIndex() != 0)
1280
    {
1281
        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."));
1282 1283 1284
        return;
    }

1285
    if (transferFormatCombo->currentIndex() == ISD::CCD::FORMAT_NATIVE && darkSubCheck->isChecked())
1286
    {
Yuri Chornoivan's avatar
Yuri Chornoivan committed
1287
        appendLogText(i18n("Cannot perform auto dark subtraction of native DSLR formats."));
1288 1289 1290
        return;
    }

1291 1292 1293 1294 1295 1296 1297
    addJob(true);

    prepareJob(jobs.last());
}

void Capture::captureImage()
{
1298 1299 1300 1301
    if (activeJob == NULL)
        return;

    seqTimer->stop();    
1302 1303
    SequenceJob::CAPTUREResult rc=SequenceJob::CAPTURE_OK;

1304 1305 1306 1307 1308 1309 1310
    if (currentCCD->isConnected() == false)
    {
        appendLogText(i18n("Error: Lost connection to CCD."));
        abort();
        return;
    }

1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
    if (focusState >= FOCUS_PROGRESS)
    {
        appendLogText(i18n("Cannot capture while focus module is busy."));
        abort();
        return;
    }

    if (filterSlot != NULL)
    {
        currentFilterPosition = (int) filterSlot->np[0].value;
        activeJob->setCurrentFilter(currentFilterPosition);
    }

    if (currentCCD->hasCooler())
    {
        double temperature=0;
        currentCCD->getTemperature(&temperature);
        activeJob->setCurrentTemperature(temperature);
    }

    connect(currentCCD, SIGNAL(BLOBUpdated(IBLOB*)), this, SLOT(newFITS(IBLOB*)), Qt::UniqueConnection);
    connect(currentCCD, SIGNAL(newImage(QImage*, ISD::CCDChip*)), this, SLOT(sendNewImage(QImage*, ISD::CCDChip*)), Qt::UniqueConnection);

    if (activeJob->getFrameType() == FRAME_FLAT)
    {
        // If we have to calibrate ADU levels, first capture must be preview and not in batch mode
        if (activeJob->isPreview() == false && activeJob->getFlatFieldDuration() == DURATION_ADU && calibrationStage == CAL_PRECAPTURE_COMPLETE)
        {
1339 1340 1341 1342 1343 1344 1345
            if (currentCCD->getTransferFormat() == ISD::CCD::FORMAT_NATIVE)
            {
                appendLogText(i18n("Cannot calculate ADU levels in non-FITS images."));
                abort();
                return;
            }

1346 1347 1348 1349 1350 1351
            calibrationStage = CAL_CALIBRATION;
            activeJob->setPreview(true);
        }
    }

    if (currentCCD->getUploadMode() != ISD::CCD::UPLOAD_LOCAL)
1352
    {
1353
        checkSeqBoundary(activeJob->getFITSDir());
1354 1355
        currentCCD->setNextSequenceID(nextSequenceID);
    }
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374

    state = CAPTURE_CAPTURING;

    if (activeJob->isPreview() == false)
        emit newStatus(Ekos::CAPTURE_CAPTURING);

    if (frameSettings.contains(activeJob->getActiveChip()))
    {
        QVariantMap settings;
        settings["x"]      = activeJob->getSubX();
        settings["y"]      = activeJob->getSubY();
        settings["w"]      = activeJob->getSubW();
        settings["h"]      = activeJob->getSubH();
        settings["binx"]   = activeJob->getXBin();
        settings["biny"]   = activeJob->getYBin();

        frameSettings[activeJob->getActiveChip()] = settings;
    }

1375
    // If using DSLR, make sure it is set to correct transfer format
1376
    currentCCD->setTransformFormat(activeJob->getTransforFormat());
1377

1378 1379 1380 1381 1382
    rc = activeJob->capture(darkSubCheck->isChecked() ? true : false);

    switch (rc)
    {
    case SequenceJob::CAPTURE_OK:
1383
        connect(currentCCD, SIGNAL(newExposureValue(ISD::CCDChip*,double,IPState)), this, SLOT(setExposureProgress(ISD::CCDChip*,double,IPState)), Qt::UniqueConnection);
1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476
        appendLogText(i18n("Capturing image..."));
        break;

    case SequenceJob::CAPTURE_FRAME_ERROR:
        appendLogText(i18n("Failed to set sub frame."));
        abort();
        break;

    case SequenceJob::CAPTURE_BIN_ERROR:
        appendLogText(i18n("Failed to set binning."));
        abort();
        break;

    case SequenceJob::CAPTURE_FILTER_BUSY:
        // Try again in 1 second if filter is busy
        QTimer::singleShot(1000, this, SLOT(captureImage()));
        break;

    case SequenceJob::CAPTURE_FOCUS_ERROR:
        appendLogText(i18n("Cannot capture while focus module is busy."));
        abort();
        break;

    }
}

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

    appendLogText(i18n("Dither complete."));

    if (isAutoFocus && autoFocusStatus == false)
    {
        secondsLabel->setText(i18n("Focusing..."));
        emit checkFocus(HFRPixels->value());
        state = CAPTURE_FOCUSING;
        emit newStatus(Ekos::CAPTURE_FOCUSING);
        return true;
    }

    startNextExposure();

    return true;
}

/*******************************************************************************/
/* Update the prefix for the sequence of images to be captured                 */
/*******************************************************************************/
void Capture::updateSequencePrefix( const QString &newPrefix, const QString &dir)
{
    seqPrefix = newPrefix;

    // If it doesn't exist, create it
    QDir().mkpath(dir);

    nextSequenceID = 1;
}

/*******************************************************************************/
/* Determine the next file number sequence. That is, if we have file1.png      */
/* and file2.png, then the next sequence should be file3.png		       */
/*******************************************************************************/
void Capture::checkSeqBoundary(const QString &path)
{
    int newFileIndex=-1;
    QString tempName;
    seqFileCount=0;

    // No updates during meridian flip
    if (meridianFlipStage >= MF_ALIGNING)
        return;

    QDirIterator it(path, QDir::Files);

    while (it.hasNext())
    {
        tempName = it.next();
        QFileInfo info(tempName);
        tempName = info.baseName();

        // find the prefix first
        if (tempName.startsWith(seqPrefix) == false)
            continue;

        seqFileCount++;

1477 1478 1479 1480
        int lastUnderScoreIndex = tempName.lastIndexOf("_");
        if (lastUnderScoreIndex > 0)
        {
            bool indexOK = false;
1481

1482 1483 1484 1485
            newFileIndex = tempName.mid(lastUnderScoreIndex+1).toInt(&indexOK);
            if (indexOK && newFileIndex >= nextSequenceID)
                nextSequenceID = newFileIndex + 1;
        }
1486

1487
    }    
1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
}

void Capture::appendLogText(const QString &text)
{
    logText.insert(0, i18nc("log entry; %1 is the date, %2 is the text", "%1 %2", QDateTime::currentDateTime().toString("yyyy-MM-ddThh:mm:ss"), text));

    if (Options::captureLogging())
        qDebug() << "Capture: " << text;

    emit newLog();
}

void Capture::clearLog()
{
    logText.clear();
    emit newLog();
}

1506
void Capture::setExposureProgress(ISD::CCDChip * tChip, double value, IPState state)
1507 1508 1509 1510 1511 1512 1513
{
    if (targetChip != tChip || targetChip->getCaptureMode() != FITS_NORMAL || meridianFlipStage >= MF_ALIGNING)
        return;

    exposeOUT->setText(QString::number(value, 'd', 2));

    if (activeJob)
1514
    {
1515 1516
        activeJob->setExposeLeft(value);

1517 1518 1519
        emit newExposureProgress(activeJob);
    }

1520 1521 1522 1523 1524 1525
    if (activeJob && state == IPS_ALERT)
    {
        int retries = activeJob->getCaptureRetires()+1;

        activeJob->setCaptureRetires(retries);