capture.cpp 140 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
// Current Sequence File Format:
56
#define SQ_FORMAT_VERSION 1.7
57
// We accept file formats with version back to:
58
#define SQ_COMPAT_VERSION 1.6
59

60 61 62 63 64 65 66
namespace Ekos
{
Capture::Capture()
{
    setupUi(this);

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

69
    dirPath = QUrl::fromLocalFile(QDir::homePath());
70

71
    state      = CAPTURE_IDLE;
72 73 74 75
    focusState = FOCUS_IDLE;
    guideState = GUIDE_IDLE;
    alignState = ALIGN_IDLE;

76
    currentCCD       = nullptr;
Csaba Kertesz's avatar
Csaba Kertesz committed
77
    currentTelescope = nullptr;
78 79 80 81
    currentFilter    = nullptr;
    dustCap          = nullptr;
    lightBox         = nullptr;
    dome             = nullptr;
82

Csaba Kertesz's avatar
Csaba Kertesz committed
83 84
    filterSlot = nullptr;
    filterName = nullptr;
85
    activeJob  = nullptr;
86

Csaba Kertesz's avatar
Csaba Kertesz committed
87
    targetChip = nullptr;
88
    guideChip  = nullptr;
89

90
    targetADU          = 0;
91
    targetADUTolerance = 1000;
92 93 94 95 96
    flatFieldDuration  = DURATION_MANUAL;
    flatFieldSource    = SOURCE_MANUAL;
    calibrationStage   = CAL_NONE;
    preMountPark       = false;
    preDomePark        = false;
97 98 99 100 101

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

102
    ignoreJobProgress = true;
103 104 105

    dustCapLightEnabled = lightBoxLightEnabled = false;

106
    //isAutoGuiding   = false;
107 108 109
    isAutoFocus              = false;
    autoFocusStatus          = false;
    resumeAlignmentAfterFlip = false;
110

111 112 113
    mDirty                = false;
    jobUnderEdit          = false;
    currentFilterPosition = -1;
114 115

    //calibrationState  = CALIBRATE_NONE;
116
    meridianFlipStage      = MF_NONE;
117 118 119 120 121 122 123 124 125
    resumeGuidingAfterFlip = false;

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

    pi = new QProgressIndicator(this);

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

126
    seqFileCount = 0;
127 128 129 130 131 132 133
    //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()));

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

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

143 144 145 146 147
    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)));

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

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

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

176
    addToQueueB->setIcon(QIcon::fromTheme("list-add", QIcon(":/icons/breeze/default/list-add.svg")));
Robert Lancaster's avatar
Robert Lancaster committed
177
    addToQueueB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
178
    removeFromQueueB->setIcon(QIcon::fromTheme("list-remove", QIcon(":/icons/breeze/default/list-remove.svg")));
Robert Lancaster's avatar
Robert Lancaster committed
179
    removeFromQueueB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
180
    queueUpB->setIcon(QIcon::fromTheme("go-up", QIcon(":/icons/breeze/default/go-up.svg")));
Robert Lancaster's avatar
Robert Lancaster committed
181
    queueUpB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
182
    queueDownB->setIcon(QIcon::fromTheme("go-down", QIcon(":/icons/breeze/default/go-down.svg")));
Robert Lancaster's avatar
Robert Lancaster committed
183
    queueDownB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
184 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
    rotatorB->setIcon(QIcon::fromTheme("kstars_solarsystem", QIcon(":/icons/breeze/default/kstars_solarsystem.svg")));
    rotatorB->setAttribute(Qt::WA_LayoutUsesWidgetRect);
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());

207 208
    seqExpose       = 0;
    seqTotalCount   = 0;
209
    seqCurrentCount = 0;
210 211 212 213
    seqDelay        = 0;
    fileHFR         = 0;
    useGuideHead    = false;
    firstAutoFocus  = true;
214

215
    foreach (QString filter, FITSViewer::filterTypes)
216 217 218 219
        filterCombo->addItem(filter);

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

    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()));
231 232
    connect(uploadModeCombo, SIGNAL(activated(int)), this, SLOT(setDirty()));
    connect(remoteDirIN, SIGNAL(editingFinished()), this, SLOT(setDirty()));
233

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

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

    // Remote directory
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
{
    QString guiderName = newCCD->getDeviceName() + QString(" Guider");

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

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

    FilterCaptureCombo->setCurrentIndex(0);
}

void Capture::pause()
{
Csaba Kertesz's avatar
Csaba Kertesz committed
307
    pauseFunction = nullptr;
308
    state         = CAPTURE_PAUSED;
309 310 311 312
    emit newStatus(Ekos::CAPTURE_PAUSED);
    appendLogText(i18n("Sequence shall be paused after current exposure is complete."));
    pauseB->setEnabled(false);

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

void Capture::toggleSequence()
{
    if (state == CAPTURE_PAUSED)
    {
321 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
    if (queueTable->rowCount() == 0)
361 362
        addJob();

363
    SequenceJob *first_job = nullptr;
364

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

Csaba Kertesz's avatar
Csaba Kertesz committed
374
    if (first_job == nullptr)
375
    {
376
        foreach (SequenceJob *job, jobs)
377 378 379 380 381 382 383 384
        {
            if (job->getStatus() != SequenceJob::JOB_DONE)
            {
                appendLogText(i18n("No pending jobs found. Please add a job to the sequence queue."));
                return;
            }
        }

385 386 387 388 389
        if (KMessageBox::warningContinueCancel(
                nullptr,
                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)
390 391
            return;

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

        first_job = jobs.first();
    }

    deviationDetected = false;
    spikeDetected     = false;

401
    lastFilterOffset = 0;
402 403 404 405
    // 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)
    {
406 407
        QString currentFilterName = FilterPosCombo->itemText(currentFilterPosition - 1);
        foreach (FocusOffset *offset, filterFocusOffsets)
408 409 410 411 412 413 414 415
        {
            if (offset->filter == currentFilterName)
            {
                lastFilterOffset = offset->offset;
                break;
            }
        }
    }
416

417
    ditherCounter     = Options::ditherFrames();
418
    initialHA         = getCurrentHA();
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
    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);

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

444
    setBusy(true);
445 446 447 448 449 450

    prepareJob(first_job);
}

void Capture::stop(bool abort)
{
451 452 453
    retries         = 0;
    seqTotalCount   = 0;
    seqCurrentCount = 0;
454 455 456 457 458 459 460 461 462
    //ADURaw1 = ADURaw2 = ExpRaw1 = ExpRaw2 = -1;
    //ADUSlope = 0;
    ADURaw.clear();
    ExpRaw.clear();

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

468
        // In case
Jasem Mutlaq's avatar
Jasem Mutlaq committed
469 470 471 472 473
        if (activeJob->isPreview() == false)
        {
            activeJob->disconnect(this);
            activeJob->reset();
        }
474 475 476 477 478 479 480
        else if (calibrationStage == CAL_CALIBRATION)
        {
            activeJob->disconnect(this);
            activeJob->reset();
            activeJob->setPreview(false);
            currentCCD->setUploadMode(rememberUploadMode);
        }
Jasem Mutlaq's avatar
Jasem Mutlaq committed
481 482 483 484 485 486
        else // Delete preview job
        {
            jobs.removeOne(activeJob);
            delete (activeJob);
            activeJob = nullptr;
        }
487 488
    }

489
    calibrationStage = CAL_NONE;
490
    state            = CAPTURE_IDLE;
491 492

    // Turn off any calibration light, IF they were turned on by Capture module
493
    if (dustCap && dustCapLightEnabled)
494 495 496 497 498 499 500 501 502 503 504
    {
        dustCapLightEnabled = false;
        dustCap->SetLightEnabled(false);
    }
    if (lightBox && lightBoxLightEnabled)
    {
        lightBoxLightEnabled = false;
        lightBox->SetLightEnabled(false);
    }

    secondsLabel->clear();
505
    disconnect(currentCCD, SIGNAL(BLOBUpdated(IBLOB *)), this, SLOT(newFITS(IBLOB *)));
506 507 508 509
    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)));
510 511 512 513 514 515 516 517 518 519 520 521 522 523

    currentCCD->setFITSDir("");

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

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

    setBusy(false);

    if (abort)
    {
524 525
        startB->setIcon(
            QIcon::fromTheme("media-playback-start", QIcon(":/icons/breeze/default/media-playback-start.svg")));
526 527 528 529
        startB->setToolTip(i18n("Start Sequence"));
        pauseB->setEnabled(false);
    }

530
    //foreach (QAbstractButton *button, queueEditButtonGroup->buttons())
531
    //button->setEnabled(true);
532 533 534 535

    seqTimer->stop();
}

536
void Capture::sendNewImage(QImage *image, ISD::CCDChip *myChip)
537 538 539 540 541 542 543
{
    if (activeJob && myChip != guideChip)
        emit newImage(image, activeJob);
}

bool Capture::setCCD(QString device)
{
544
    for (int i = 0; i < CCDCaptureCombo->count(); i++)
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
        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;
    }

564
    foreach (ISD::CCD *ccd, CCDs)
565
    {
566 567
        disconnect(ccd, SIGNAL(numberUpdated(INumberVectorProperty *)), this,
                   SLOT(processCCDNumber(INumberVectorProperty *)));
568 569
        disconnect(ccd, SIGNAL(newTemperatureValue(double)), this, SLOT(updateCCDTemperature(double)));
        disconnect(ccd, SIGNAL(newRemoteFile(QString)), this, SLOT(setNewRemoteFile(QString)));
570
        disconnect(ccd, SIGNAL(videoStreamToggled(bool)), this, SLOT(setVideoStreamEnabled(bool)));
571 572 573 574 575 576 577 578 579 580
    }

    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;
581
            targetChip   = currentCCD->getChip(ISD::CCDChip::GUIDE_CCD);
582 583 584
        }
        else
        {
585 586
            currentCCD   = CCDs.at(ccdNum);
            targetChip   = currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);
587 588 589 590 591 592 593 594 595 596
            useGuideHead = false;
        }

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

            if (currentCCD->getBaseDevice()->getPropertyPermission("CCD_TEMPERATURE") != IP_RO)
            {
597
                double min, max, step;
598 599
                setTemperatureB->setEnabled(true);
                temperatureIN->setReadOnly(false);
600
                temperatureCheck->setEnabled(true);
601 602 603 604 605 606 607 608 609
                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);
610
                temperatureCheck->setEnabled(false);
611 612
            }

613
            double temperature = 0;
614 615 616 617 618 619 620 621 622 623 624 625
            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();
626
            temperatureOUT->clear();
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
            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();

648
        transferFormatCombo->disconnect();
649 650
        transferFormatCombo->clear();

651 652 653
        if (isoList.isEmpty())
        {
            ISOCombo->setEnabled(false);
654
            ISOLabel->setEnabled(false);
655 656
            // Only one trasnfer format
            transferFormatCombo->addItem(i18n("FITS"));
657 658 659 660
        }
        else
        {
            ISOCombo->setEnabled(true);
661
            ISOLabel->setEnabled(true);
662 663
            ISOCombo->addItems(isoList);
            ISOCombo->setCurrentIndex(targetChip->getISOIndex());
Jasem Mutlaq's avatar
Jasem Mutlaq committed
664

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

674
            double pixelX = 0, pixelY = 0;
675 676 677
            bool rc = targetChip->getPixelSize(pixelX, pixelY);
            if (rc == false || pixelX == 0 || pixelY == 0)
            {
678 679 680
                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."));
681
            }
682 683
        }

684 685 686 687
        gainLabel->setEnabled(currentCCD->hasGain());
        gainIN->setEnabled(currentCCD->hasGain());
        if (gainIN->isEnabled())
        {
688
            double gain = 0, min = 0, max = 0, step = 1;
689 690 691 692 693 694 695 696 697 698 699 700 701
            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();

702
        liveVideoB->setEnabled(currentCCD->hasVideoStream());
703
        setVideoStreamEnabled(currentCCD->isStreamingEnabled());
704

705 706 707 708
        connect(currentCCD, SIGNAL(numberUpdated(INumberVectorProperty *)), this,
                SLOT(processCCDNumber(INumberVectorProperty *)), Qt::UniqueConnection);
        connect(currentCCD, SIGNAL(newTemperatureValue(double)), this, SLOT(updateCCDTemperature(double)),
                Qt::UniqueConnection);
709
        connect(currentCCD, SIGNAL(newRemoteFile(QString)), this, SLOT(setNewRemoteFile(QString)));
710
        connect(currentCCD, SIGNAL(videoStreamToggled(bool)), this, SLOT(setVideoStreamEnabled(bool)));
711 712 713
    }
}

714
void Capture::setGuideChip(ISD::CCDChip *chip)
715 716 717 718 719 720 721
{
    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.
722 723 724
    suspendGuideOnDownload =
        (currentCCD->getChip(ISD::CCDChip::GUIDE_CCD) == guideChip) ||
        (guideChip->getCCD() == currentCCD && currentCCD->getDriverInfo()->getAuxInfo().value("mdpd", false).toBool());
725 726
}

727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
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);
}

746
void Capture::updateFrameProperties(int reset)
747
{
748 749 750 751
    int x, y, w, h;
    int binx = 1, biny = 1;
    double min, max, step;
    int xstep = 0, ystep = 0;
752

753
    QString frameProp    = useGuideHead ? QString("GUIDER_FRAME") : QString("CCD_FRAME");
754 755
    QString exposureProp = useGuideHead ? QString("GUIDER_EXPOSURE") : QString("CCD_EXPOSURE");
    QString exposureElem = useGuideHead ? QString("GUIDER_EXPOSURE_VALUE") : QString("CCD_EXPOSURE_VALUE");
756 757
    targetChip =
        useGuideHead ? currentCCD->getChip(ISD::CCDChip::GUIDE_CCD) : currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);
758 759 760 761 762 763 764 765 766 767 768 769 770 771

    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);
772 773 774 775 776

        if (min < 0.001)
            exposureIN->setDecimals(6);
        else
            exposureIN->setDecimals(3);
777 778 779 780
    }

    if (currentCCD->getMinMaxStep(frameProp, "WIDTH", &min, &max, &step))
    {
781 782 783
        if (min >= max)
        {
            resetFrameToZero();
784
            return;
785
        }
786 787

        if (step == 0)
788
            xstep = (int)max * 0.05;
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
        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))
    {
804 805 806
        if (min >= max)
        {
            resetFrameToZero();
807
            return;
808
        }
809 810

        if (step == 0)
811
            ystep = (int)max * 0.05;
812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
        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))
    {
827 828 829
        if (min >= max)
        {
            resetFrameToZero();
830
            return;
831
        }
832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847

        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))
    {
848 849 850
        if (min >= max)
        {
            resetFrameToZero();
851
            return;
852
        }
853 854 855 856 857 858 859 860 861 862 863 864 865 866

        if (step == 0)
            step = ystep;

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

867
    if (reset == 1 || frameSettings.contains(targetChip) == false)
868 869 870
    {
        QVariantMap settings;

871 872 873 874
        settings["x"]    = 0;
        settings["y"]    = 0;
        settings["w"]    = frameWIN->maximum();
        settings["h"]    = frameHIN->maximum();
875 876 877 878 879
        settings["binx"] = 1;
        settings["biny"] = 1;

        frameSettings[targetChip] = settings;
    }
880 881 882
    else if (reset == 2 && frameSettings.contains(targetChip))
    {
        QVariantMap settings = frameSettings[targetChip];
883
        int x, y, w, h;
884 885 886 887 888 889 890

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

        // Bound them
891 892
        x = qBound(frameXIN->minimum(), x, frameXIN->maximum() - 1);
        y = qBound(frameYIN->minimum(), y, frameYIN->maximum() - 1);
893 894 895 896 897 898 899 900 901 902
        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;
    }
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

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

939
void Capture::processCCDNumber(INumberVectorProperty *nvp)
940
{
Csaba Kertesz's avatar
Csaba Kertesz committed
941
    if (currentCCD == nullptr)
942 943
        return;

944 945
    if ((!strcmp(nvp->name, "CCD_FRAME") && useGuideHead == false) ||
        (!strcmp(nvp->name, "GUIDER_FRAME") && useGuideHead))
946
        updateFrameProperties();
947 948
    else if ((!strcmp(nvp->name, "CCD_INFO") && useGuideHead == false) ||
             (!strcmp(nvp->name, "GUIDER_INFO") && useGuideHead))
949
        updateFrameProperties(2);
950 951 952 953
}

void Capture::resetFrame()
{
954 955
    targetChip =
        useGuideHead ? currentCCD->getChip(ISD::CCDChip::GUIDE_CCD) : currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);
956
    targetChip->resetFrame();
957
    updateFrameProperties(1);
958 959
}

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

965
    ISD::CCDChip *tChip = (static_cast<ISD::CCD *>(ccd))->getChip(ISD::CCDChip::PRIMARY_CCD);
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982

    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)
{
983
    bool deviceFound = false;
984

985
    for (int i = 0; i < FilterCaptureCombo->count(); i++)
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
        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();

Csaba Kertesz's avatar
Csaba Kertesz committed
1020
    filterName = currentFilter->getBaseDevice()->getText("FILTER_NAME");
1021 1022
    filterSlot = currentFilter->getBaseDevice()->getNumber("FILTER_SLOT");

Csaba Kertesz's avatar
Csaba Kertesz committed
1023
    if (filterSlot == nullptr)
1024
    {
1025 1026
        KMessageBox::error(0, i18n("Unable to find FILTER_SLOT property in driver %1",
                                   currentFilter->getBaseDevice()->getDeviceName()));
1027 1028 1029
        return;
    }

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

Csaba Kertesz's avatar
Csaba Kertesz committed
1034
        if (filterName != nullptr && (i < filterName->ntp))
1035 1036 1037 1038
            item = filterName->tp[i].text;
        else if (i < filterAlias.count() && filterAlias[i].isEmpty() == false)
            item = filterAlias.at(i);
        else
1039
            item = QString("Filter_%1").arg(i + 1);
1040 1041 1042 1043

        FilterPosCombo->addItem(item);
    }

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

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

1048 1049
    if (activeJob &&
        (activeJob->getStatus() == SequenceJob::JOB_ABORTED || activeJob->getStatus() == SequenceJob::JOB_IDLE))
1050 1051 1052 1053 1054 1055 1056
        activeJob->setCurrentFilter(currentFilterPosition);
}

void Capture::syncFilterInfo()
{
    if (currentCCD && currentFilter)
    {
1057
        ITextVectorProperty *activeDevices = currentCCD->getBaseDevice()->getText("ACTIVE_DEVICES");
1058 1059
        if (activeDevices)
        {
1060
            IText *activeFilter = IUFindText(activeDevices, "ACTIVE_FILTER");
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091
            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;
}

1092
void Capture::newFITS(IBLOB *bp)
1093
{
1094
    ISD::CCDChip *tChip = nullptr;
1095 1096

    // If there is no active job, ignore
Csaba Kertesz's avatar
Csaba Kertesz committed
1097
    if (activeJob == nullptr || meridianFlipStage >= MF_ALIGNING)
1098 1099 1100 1101
        return;

    if (currentCCD->getUploadMode() != ISD::CCD::UPLOAD_LOCAL)
    {
Csaba Kertesz's avatar
Csaba Kertesz committed
1102
        if (bp == nullptr)
1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
        {
            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()))
1126
        if (QString(bp->bvp->device) != currentCCD->getDeviceName() || state == CAPTURE_IDLE)
1127 1128
            return;

1129
        disconnect(currentCCD, SIGNAL(BLOBUpdated(IBLOB *)), this, SLOT(newFITS(IBLOB *)));
1130 1131
        disconnect(currentCCD, SIGNAL(newImage(QImage *, ISD::CCDChip *)), this,
                   SLOT(sendNewImage(QImage *, ISD::CCDChip *)));
1132 1133 1134

        if (useGuideHead == false && darkSubCheck->isChecked() && activeJob->isPreview())
        {
1135 1136 1137 1138
            FITSView *currentImage = targetChip->getImageView(FITS_NORMAL);
            FITSData *darkData     = nullptr;
            uint16_t offsetX       = activeJob->getSubX() / activeJob->getXBin();
            uint16_t offsetY       = activeJob->getSubY() / activeJob->getYBin();
1139 1140 1141 1142 1143 1144 1145

            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)
1146 1147
                DarkLibrary::Instance()->subtract(darkData, currentImage, activeJob->getCaptureFilter(), offsetX,
                                                  offsetY);
1148
            else
1149