focus.cpp 67.8 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
24
25
26
27
28
29
30
/*  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 "focus.h"
#include "Options.h"

#include <KMessageBox>
#include <KLocalizedString>
#include <KPlotting/KPlotWidget>
#include <KPlotting/KPlotObject>
#include <KPlotting/KPlotAxis>

#include <KNotifications/KNotification>

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

#include "auxiliary/kspaths.h"

#include "fitsviewer/fitsviewer.h"
#include "fitsviewer/fitstab.h"
#include "fitsviewer/fitsview.h"
31
32
#include "ekos/ekosmanager.h"
#include "ekos/auxiliary/darklibrary.h"
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63

#include "kstars.h"
#include "focusadaptor.h"

#include <basedevice.h>

#define MAXIMUM_ABS_ITERATIONS      30
#define MAXIMUM_RESET_ITERATIONS    2
#define DEFAULT_SUBFRAME_DIM        128
#define AUTO_STAR_TIMEOUT           45000
#define MINIMUM_PULSE_TIMER         32
#define MAX_RECAPTURE_RETRIES       3

namespace Ekos
{

Focus::Focus()
{
    setupUi(this);

    new FocusAdaptor(this);
    QDBusConnection::sessionBus().registerObject("/KStars/Ekos/Focus",  this);

    currentFocuser = NULL;
    currentCCD     = NULL;
    currentFilter  = NULL;
    filterName     = NULL;
    filterSlot     = NULL;

    canAbsMove        = false;
    canRelMove        = false;
Jasem Mutlaq's avatar
Jasem Mutlaq committed
64
    canTimerMove      = false;
65
66
67
68
    inAutoFocus       = false;
    inFocusLoop       = false;
    captureInProgress = false;
    inSequenceFocus   = false;
69
    starSelected      = false;
70
71
    //frameModified     = false;
    subFramed         = false;
72
    resetFocus        = false;    
73
74
75
76
77
78
79
80
    filterPositionPending= false;

    rememberUploadMode = ISD::CCD::UPLOAD_CLIENT;
    HFRInc =0;
    noStarCount=0;
    reverseDir = false;
    initialFocuserAbsPosition = -1;

81
82
    focusAlgorithm = ALGORITHM_GRADIENT;

83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
    state = Ekos::FOCUS_IDLE;

    pulseDuration = 1000;

    resetFocusIteration=0;
    //fy=fw=fh=0;
    //orig_x = orig_y = orig_w = orig_h =-1;
    lockedFilterIndex=-1;
    maxHFR=1;
    minimumRequiredHFR = -1;
    currentFilterIndex=-1;
    minPos=1e6;
    maxPos=0;
    frameNum=0;

    connect(startFocusB, SIGNAL(clicked()), this, SLOT(start()));
    connect(stopFocusB, SIGNAL(clicked()), this, SLOT(checkStopFocus()));

Jasem Mutlaq's avatar
Jasem Mutlaq committed
101
102
    connect(focusOutB, SIGNAL(clicked()), this, SLOT(focusOut()));
    connect(focusInB, SIGNAL(clicked()), this, SLOT(focusIn()));
103

104
    connect(captureB, SIGNAL(clicked()), this, SLOT(capture()));    
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122

    connect(startLoopB, SIGNAL(clicked()), this, SLOT(startFraming()));

    connect(kcfg_subFrame, SIGNAL(toggled(bool)), this, SLOT(toggleSubframe(bool)));

    connect(resetFrameB, SIGNAL(clicked()), this, SLOT(resetFrame()));

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

    connect(focuserCombo, SIGNAL(activated(int)), this, SLOT(checkFocuser(int)));
    connect(FilterCaptureCombo, SIGNAL(activated(int)), this, SLOT(checkFilter(int)));
    connect(FilterPosCombo, SIGNAL(activated(int)), this, SLOT(updateFilterPos(int)));
    connect(lockFilterCheck, SIGNAL(toggled(bool)), this, SLOT(filterLockToggled(bool)));
    connect(setAbsTicksB, SIGNAL(clicked()), this, SLOT(setAbsoluteFocusTicks()));
    connect(binningCombo, SIGNAL(activated(int)), this, SLOT(setActiveBinning(int)));
    connect(focusBoxSize, SIGNAL(valueChanged(int)), this, SLOT(updateBoxSize(int)));

123
124
125
    // Reset star center on auto star check toggle
    connect(autoStarCheck, &QCheckBox::toggled, this, [&](){starCenter = QVector3D();});

126
127
128
129
130
131
132
133
134
135
    focusAlgorithm = static_cast<StarAlgorithm>(Options::focusAlgorithm());
    focusAlgorithmCombo->setCurrentIndex(focusAlgorithm);

    connect(focusAlgorithmCombo, static_cast<void (QComboBox::*) (int)>(&QComboBox::activated), this, [&](int index)
    {
        focusAlgorithm=static_cast<StarAlgorithm>(index);
        thresholdSpin->setEnabled(focusAlgorithm == ALGORITHM_THRESHOLD);
        Options::setFocusAlgorithm(index);
    });

136
137
138
139
140
141
142
    activeBin=Options::focusXBin();
    binningCombo->setCurrentIndex(activeBin-1);

    connect(clearDataB, SIGNAL(clicked()) , this, SLOT(clearDataPoints()));

    lastFocusDirection = FOCUS_NONE;

Jasem Mutlaq's avatar
Jasem Mutlaq committed
143
    focusType = FOCUS_MANUAL;
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221

    profilePlot->setBackground(QBrush(Qt::black));
    profilePlot->xAxis->setBasePen(QPen(Qt::white, 1));
    profilePlot->yAxis->setBasePen(QPen(Qt::white, 1));
    profilePlot->xAxis->grid()->setPen(QPen(QColor(140, 140, 140), 1, Qt::DotLine));
    profilePlot->yAxis->grid()->setPen(QPen(QColor(140, 140, 140), 1, Qt::DotLine));
    profilePlot->xAxis->grid()->setSubGridPen(QPen(QColor(80, 80, 80), 1, Qt::DotLine));
    profilePlot->yAxis->grid()->setSubGridPen(QPen(QColor(80, 80, 80), 1, Qt::DotLine));
    profilePlot->xAxis->grid()->setZeroLinePen(Qt::NoPen);
    profilePlot->yAxis->grid()->setZeroLinePen(Qt::NoPen);
    profilePlot->xAxis->setBasePen(QPen(Qt::white, 1));
    profilePlot->yAxis->setBasePen(QPen(Qt::white, 1));
    profilePlot->xAxis->setTickPen(QPen(Qt::white, 1));
    profilePlot->yAxis->setTickPen(QPen(Qt::white, 1));
    profilePlot->xAxis->setSubTickPen(QPen(Qt::white, 1));
    profilePlot->yAxis->setSubTickPen(QPen(Qt::white, 1));
    profilePlot->xAxis->setTickLabelColor(Qt::white);
    profilePlot->yAxis->setTickLabelColor(Qt::white);
    profilePlot->xAxis->setLabelColor(Qt::white);
    profilePlot->yAxis->setLabelColor(Qt::white);

    firstGaus   = NULL;

    currentGaus = profilePlot->addGraph();
    currentGaus->setLineStyle(QCPGraph::lsLine);
    currentGaus->setPen(QPen(Qt::red, 2));

    lastGaus = profilePlot->addGraph();
    lastGaus->setLineStyle(QCPGraph::lsLine);
    QPen pen(Qt::darkGreen);
    pen.setStyle(Qt::DashLine);
    pen.setWidth(2);
    lastGaus->setPen(pen);

    HFRPlot->setBackground(QBrush(Qt::black));

    HFRPlot->xAxis->setBasePen(QPen(Qt::white, 1));
    HFRPlot->yAxis->setBasePen(QPen(Qt::white, 1));

    HFRPlot->xAxis->setTickPen(QPen(Qt::white, 1));
    HFRPlot->yAxis->setTickPen(QPen(Qt::white, 1));

    HFRPlot->xAxis->setSubTickPen(QPen(Qt::white, 1));
    HFRPlot->yAxis->setSubTickPen(QPen(Qt::white, 1));

    HFRPlot->xAxis->setTickLabelColor(Qt::white);
    HFRPlot->yAxis->setTickLabelColor(Qt::white);

    HFRPlot->xAxis->setLabelColor(Qt::white);
    HFRPlot->yAxis->setLabelColor(Qt::white);

    HFRPlot->xAxis->grid()->setPen(QPen(QColor(140, 140, 140), 1, Qt::DotLine));
    HFRPlot->yAxis->grid()->setPen(QPen(QColor(140, 140, 140), 1, Qt::DotLine));
    HFRPlot->xAxis->grid()->setSubGridPen(QPen(QColor(80, 80, 80), 1, Qt::DotLine));
    HFRPlot->yAxis->grid()->setSubGridPen(QPen(QColor(80, 80, 80), 1, Qt::DotLine));
    HFRPlot->xAxis->grid()->setZeroLinePen(Qt::NoPen);
    HFRPlot->yAxis->grid()->setZeroLinePen(Qt::NoPen);

    HFRPlot->yAxis->setLabel(i18n("HFR"));

    v_graph = HFRPlot->addGraph();
    v_graph->setLineStyle(QCPGraph::lsNone);
    v_graph->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::white, Qt::red, 3));

    resetButtons();

    appendLogText(i18n("Idle."));

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

    filterCombo->setCurrentIndex(Options::focusEffect());
    defaultScale = static_cast<FITSScale>(Options::focusEffect());
    connect(filterCombo, SIGNAL(activated(int)), this, SLOT(filterChangeWarning(int)));

    exposureIN->setValue(Options::focusExposure());
    toleranceIN->setValue(Options::focusTolerance());
    stepIN->setValue(Options::focusTicks());
222
    autoStarCheck->setChecked(Options::focusAutoStarEnabled());
223
224
225
226
227
228
229
    focusBoxSize->setValue(Options::focusBoxSize());
    maxTravelIN->setValue(Options::focusMaxTravel());
    kcfg_subFrame->setChecked(Options::focusSubFrame());
    suspendGuideCheck->setChecked(Options::suspendGuiding());
    lockFilterCheck->setChecked(Options::lockFocusFilter());
    darkFrameCheck->setChecked(Options::useFocusDarkFrame());
    thresholdSpin->setValue(Options::focusThreshold());
230
    //focusFramesSpin->setValue(Options::focusFrames());
231
232

    connect(thresholdSpin, SIGNAL(valueChanged(double)), this, SLOT(setThreshold(double)));
233
    //connect(focusFramesSpin, SIGNAL(valueChanged(int)), this, SLOT(setFrames(int)));
234
235
236
237
238
239
240
241

    focusView = new FITSView(focusingWidget);
    focusView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    focusView->setBaseSize(focusingWidget->size());
    QVBoxLayout *vlayout = new QVBoxLayout();
    vlayout->addWidget(focusView);
    focusingWidget->setLayout(vlayout);
    connect(focusView, SIGNAL(trackingStarSelected(int,int)), this, SLOT(focusStarSelected(int,int)), Qt::UniqueConnection);
242
243

    focusView->setStarsEnabled(true);
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
}

Focus::~Focus()
{
    //qDeleteAll(HFRAbsolutePoints);
   // HFRAbsolutePoints.clear();
}

void Focus::resetFrame()
{
    if (currentCCD)
    {
        ISD::CCDChip *targetChip = currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);

        if (targetChip)
        {
            //fx=fy=fw=fh=0;
            targetChip->resetFrame();

            int x,y,w,h;
            targetChip->getFrame(&x,&y,&w, &h);

            QVariantMap settings;
            settings["x"] = x;
            settings["y"] = y;
            settings["w"] = w;
            settings["h"] = h;
            settings["binx"] = 1;
            settings["biny"] = 1;
            frameSettings[targetChip] = settings;
            //targetChip->setFocusFrame(0,0,0,0);

276
277
            starSelected = false;
            starCenter = QVector3D();            
278
279
            subFramed = false;

280
            focusView->setTrackingBox(QRect());
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
        }
    }
}

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

    return false;
}

void Focus::setDefaultCCD(QString ccd)
{
    Options::setDefaultFocusCCD(ccd);
}

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

        if (ccdNum == -1)
            return;
    }

    if (ccdNum >=0 && ccdNum <= CCDs.count())
    {
        currentCCD = CCDs.at(ccdNum);

        ISD::CCDChip *targetChip = currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);
        if (targetChip)
        {
319
320
            targetChip->setImageView(focusView, FITS_FOCUS);

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
351
352
353
354
355
356
357
358
359
360
361
362
363
            binningCombo->setEnabled(targetChip->canBin());
            kcfg_subFrame->setEnabled(targetChip->canSubframe());
            if (targetChip->canBin())
            {
                int subBinX=1,subBinY=1;
                binningCombo->clear();
                targetChip->getMaxBin(&subBinX, &subBinY);
                for (int i=1; i <= subBinX; i++)
                    binningCombo->addItem(QString("%1x%2").arg(i).arg(i));

                binningCombo->setCurrentIndex(activeBin-1);

            }

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

            if (isoList.isEmpty())
            {
                ISOCombo->setEnabled(false);
                ISOLabel->setEnabled(false);
            }
            else
            {
                ISOCombo->setEnabled(true);
                ISOLabel->setEnabled(true);
                ISOCombo->addItems(isoList);
                ISOCombo->setCurrentIndex(targetChip->getISOIndex());
            }

        }
    }

    syncCCDInfo();
}

void Focus::syncCCDInfo()
{
    if (currentCCD == NULL)
        return;

    ISD::CCDChip *targetChip = currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);

Jasem Mutlaq's avatar
Jasem Mutlaq committed
364
365
    kcfg_subFrame->setEnabled(targetChip->canSubframe());

366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
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
545
546
547
548
549
550
551
552
553
554
555
    if (frameSettings.contains(targetChip) == false)
    {
        int x,y,w,h;
        if (targetChip->getFrame(&x, &y, &w, &h))
        {
            int binx=1,biny=1;
            targetChip->getBinning(&binx, &biny);
            if (w > 0 && h > 0)
            {
                QVariantMap settings;

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

                frameSettings[targetChip] = settings;
            }
        }
    }
}

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

    FilterCaptureLabel->setEnabled(true);
    FilterCaptureCombo->setEnabled(true);
    FilterPosLabel->setEnabled(true);
    FilterPosCombo->setEnabled(true);
    lockFilterCheck->setEnabled(true);

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

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

    checkFilter(0);

    FilterCaptureCombo->setCurrentIndex(0);

}

bool Focus::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 Focus::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);

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

    currentFilterIndex = filterSlot->np[0].value - 1;

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

    }

    if (lockFilterCheck->isChecked() == false)
        FilterPosCombo->setCurrentIndex( currentFilterIndex);
    else
    {
        if (lockedFilterIndex < 0)
        {
            //lockedFilterIndex = currentFilterIndex;
            lockedFilterIndex = Options::lockFocusFilterIndex();
            emit filterLockUpdated(currentFilter, lockedFilterIndex);
        }
        FilterPosCombo->setCurrentIndex(lockedFilterIndex);
    }

    // If we are waiting to change the filter wheel, let's check if the condition is now met.
    if (filterPositionPending)
    {
        if (lockedFilterIndex == currentFilterIndex)
        {
            filterPositionPending = false;
            capture();
        }
    }

}

void Focus::filterLockToggled(bool enable)
{
    if (enable)
    {
        lockedFilterIndex = FilterPosCombo->currentIndex();
        if (lockedFilterIndex >= 0)
            Options::setLockFocusFilterIndex(lockedFilterIndex);
        emit filterLockUpdated(currentFilter, lockedFilterIndex);
    }
    else if (filterSlot != NULL)
    {
        FilterPosCombo->setCurrentIndex(filterSlot->np[0].value-1);
        emit filterLockUpdated(NULL, 0);
    }
}

void Focus::updateFilterPos(int index)
{
    if (lockFilterCheck->isChecked() == true)
    {
        lockedFilterIndex = index;
        Options::setLockFocusFilterIndex(lockedFilterIndex);
        emit filterLockUpdated(currentFilter, lockedFilterIndex);
    }
}

void Focus::addFocuser(ISD::GDInterface *newFocuser)
{
    focuserCombo->addItem(newFocuser->getDeviceName());

    Focusers.append(static_cast<ISD::Focuser*>(newFocuser));

    currentFocuser = static_cast<ISD::Focuser *> (newFocuser);

    checkFocuser();
}

bool Focus::setFocuser(QString device)
{
    for (int i=0; i < focuserCombo->count(); i++)
        if (device == focuserCombo->itemText(i))
        {
            checkFocuser(i);
            return true;
        }

    return false;
}

void Focus::checkFocuser(int FocuserNum)
{
    if (FocuserNum == -1)
        FocuserNum = focuserCombo->currentIndex();

556
557
558
    if (FocuserNum == -1)
        return;

559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
    if (FocuserNum <= Focusers.count())
        currentFocuser = Focusers.at(FocuserNum);

    if (currentFocuser->canAbsMove())
    {
        canAbsMove = true;
        getAbsFocusPosition();

        absTicksSpin->setEnabled(true);
        setAbsTicksB->setEnabled(true);
    }
    else
    {
        canAbsMove = false;
        absTicksSpin->setEnabled(false);
        setAbsTicksB->setEnabled(false);
    }

    if (currentFocuser->canRelMove())
    {
        // We pretend this is an absolute focuser
        canRelMove = true;
        currentPosition = 50000;
        absMotionMax  = 100000;
        absMotionMin  = 0;
    }

Jasem Mutlaq's avatar
Jasem Mutlaq committed
586
587
588
589
    canTimerMove = currentFocuser->canTimerMove();

    focusType = (canRelMove || canAbsMove || canTimerMove) ? FOCUS_AUTO : FOCUS_MANUAL;

590
    connect(currentFocuser, SIGNAL(numberUpdated(INumberVectorProperty*)), this, SLOT(processFocusNumber(INumberVectorProperty*)), Qt::UniqueConnection);    
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668

    resetButtons();

    //if (!inAutoFocus && !inFocusLoop && !captureInProgress && !inSequenceFocus)
      //  emit autoFocusFinished(true, -1);
}

void Focus::addCCD(ISD::GDInterface *newCCD)
{
    if (CCDs.contains(static_cast<ISD::CCD *>(newCCD)))
         return;

    CCDs.append(static_cast<ISD::CCD *>(newCCD));

    CCDCaptureCombo->addItem(newCCD->getDeviceName());
}

void Focus::getAbsFocusPosition()
{
    INumberVectorProperty *absMove = NULL;
    if (canAbsMove)
    {
        absMove = currentFocuser->getBaseDevice()->getNumber("ABS_FOCUS_POSITION");

        if (absMove)
        {
           currentPosition = absMove->np[0].value;
           absMotionMax  = absMove->np[0].max;
           absMotionMin  = absMove->np[0].min;

           absTicksSpin->setMinimum(absMove->np[0].min);
           absTicksSpin->setMaximum(absMove->np[0].max);
           absTicksSpin->setSingleStep(absMove->np[0].step);

           absTicksSpin->setValue(currentPosition);
        }
    }

}

void Focus::start()
{
    if (currentCCD == NULL)
    {
        appendLogText(i18n("No CCD connected."));
        return;
    }

    lastFocusDirection = FOCUS_NONE;

    lastHFR = 0;

    if (canAbsMove)
    {
        absIterations = 0;
        getAbsFocusPosition();
        pulseDuration = stepIN->value();
    }
    else if (canRelMove)
    {
        appendLogText(i18n("Setting dummy central position to 50000"));
        absIterations = 0;
        pulseDuration = stepIN->value();
        currentPosition = 50000;
        absMotionMax  = 100000;
        absMotionMin  = 0;
    }
    else
    {
      pulseDuration=stepIN->value();

      if (pulseDuration <= MINIMUM_PULSE_TIMER)
      {
          appendLogText(i18n("Starting pulse step is too low. Increase the step size to %1 or higher...", MINIMUM_PULSE_TIMER*5));
          return;
      }
    }

669
    inAutoFocus = true;    
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
    frameNum=0;

    resetButtons();

    reverseDir = false;

    /*if (fw > 0 && fh > 0)
        starSelected= true;
    else
        starSelected= false;*/

    clearDataPoints();

    if (firstGaus)
    {
        profilePlot->removeGraph(firstGaus);
        firstGaus = NULL;
    }

    Options::setFocusTicks(stepIN->value());
    Options::setFocusTolerance(toleranceIN->value());
    Options::setFocusExposure(exposureIN->value());
    Options::setFocusXBin(activeBin);
    Options::setFocusMaxTravel(maxTravelIN->value());
694
    Options::setFocusBoxSize(focusBoxSize->value());
695
    Options::setFocusSubFrame(kcfg_subFrame->isChecked());
696
    Options::setFocusAutoStarEnabled(autoStarCheck->isChecked());
697
698
699
700
701
702
    Options::setSuspendGuiding(suspendGuideCheck->isChecked());
    Options::setLockFocusFilter(lockFilterCheck->isChecked());
    Options::setUseFocusDarkFrame(darkFrameCheck->isChecked());

    if (Options::focusLogging())
        qDebug() << "Focus: Starting focus with box size: " << focusBoxSize->value() << " Step Size: " <<  stepIN->value() << " Threshold: " << thresholdSpin->value() << " Tolerance: "  << toleranceIN->value()
703
                 << " Frames: " << 1 /*focusFramesSpin->value()*/ << " Maximum Travel: " << maxTravelIN->value();
704

705
    if (autoStarCheck->isChecked())
706
707
708
709
710
        appendLogText(i18n("Autofocus in progress..."));
    else
        appendLogText(i18n("Please wait until image capture is complete..."));

    if (suspendGuideCheck->isChecked())
Jasem Mutlaq's avatar
Jasem Mutlaq committed
711
         emit suspendGuiding();
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742

    //emit statusUpdated(true);
    state = Ekos::FOCUS_PROGRESS;
    emit newStatus(state);

    // Denoise with median filter
    //defaultScale = FITS_MEDIAN;

    capture();
}

void Focus::checkStopFocus()
{
    if (inSequenceFocus == true)
    {
        inSequenceFocus = false;
        setAutoFocusResult(false);
    }

    if (captureInProgress && inAutoFocus == false && inFocusLoop == false)
    {
        captureB->setEnabled(true);
        stopFocusB->setEnabled(false);

        appendLogText(i18n("Capture aborted."));
    }

    abort();
}

void Focus::abort()
Jasem Mutlaq's avatar
Jasem Mutlaq committed
743
744
745
746
747
{
    stop(true);
}

void Focus::stop(bool aborted)
748
749
750
751
752
753
754
755
{
    if (Options::focusLogging())
        qDebug() << "Focus: Stopppig Focus";

    ISD::CCDChip *targetChip = currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);

    inAutoFocus = false;
    inFocusLoop = false;
756
    starSelected= false;
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
    minimumRequiredHFR    = -1;
    noStarCount = 0;
    frameNum=0;
    //maxHFR=1;

    disconnect(currentCCD, SIGNAL(BLOBUpdated(IBLOB*)), this, SLOT(newFITS(IBLOB*)));

    if (rememberUploadMode != currentCCD->getUploadMode())
        currentCCD->setUploadMode(rememberUploadMode);

    targetChip->abortExposure();

    //resetFrame();

    resetButtons();

    absIterations = 0;
    HFRInc=0;
    reverseDir = false;

    //emit statusUpdated(false);
Jasem Mutlaq's avatar
Jasem Mutlaq committed
778
779
780
781
782
    if (aborted)
    {
        state = Ekos::FOCUS_ABORTED;
        emit newStatus(state);
    }
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
}

void Focus::capture()
{
    if (currentCCD == NULL)
    {
        appendLogText(i18n("No CCD connected."));
        return;
    }

    ISD::CCDChip *targetChip = currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);

    double seqExpose = exposureIN->value();

    if (currentCCD->isConnected() == false)
    {
        appendLogText(i18n("Error: Lost connection to CCD."));
        return;
    }

    if (currentFilter != NULL && lockFilterCheck->isChecked())
    {
        if (currentFilter->isConnected() == false)
        {
            appendLogText(i18n("Error: Lost connection to filter wheel."));
            return;
        }

        if (lockedFilterIndex != currentFilterIndex)
        {
            int lockedFilterPosition = lockedFilterIndex + 1;
            filterPositionPending = true;
            appendLogText(i18n("Changing filter to %1", FilterPosCombo->currentText()));
            currentFilter->runCommand(INDI_SET_FILTER, &lockedFilterPosition);
            return;
        }
    }

    if (currentCCD->getUploadMode() == ISD::CCD::UPLOAD_LOCAL)
    {
        rememberUploadMode = ISD::CCD::UPLOAD_LOCAL;
        currentCCD->setUploadMode(ISD::CCD::UPLOAD_CLIENT);
    }

    targetChip->setBinning(activeBin, activeBin);

    targetChip->setCaptureMode(FITS_FOCUS);

    // Always disable filtering if using a dark frame and then re-apply after subtraction. TODO: Implement this in capture and guide and align
    if (darkFrameCheck->isChecked())
        targetChip->setCaptureFilter(FITS_NONE);
    else
        targetChip->setCaptureFilter(defaultScale);

    if (ISOCombo->isEnabled() && ISOCombo->currentIndex() != -1 && targetChip->getISOIndex() != ISOCombo->currentIndex())
        targetChip->setISOIndex(ISOCombo->currentIndex());

    connect(currentCCD, SIGNAL(BLOBUpdated(IBLOB*)), this, SLOT(newFITS(IBLOB*)));

    targetChip->setFrameType(FRAME_LIGHT);

    if (frameSettings.contains(targetChip))
    {
        QVariantMap settings = frameSettings[targetChip];
        targetChip->setFrame(settings["x"].toInt(), settings["y"].toInt(), settings["w"].toInt(), settings["h"].toInt());
        settings["binx"] = activeBin;
        settings["biny"] = activeBin;
        frameSettings[targetChip] = settings;
    }

    captureInProgress = true;

855
856
    focusView->setBaseSize(focusingWidget->size());

857
858
859
860
861
862
863
864
865
866
867
868
869
870
    targetChip->capture(seqExpose);

    if (inFocusLoop == false)
    {
        appendLogText(i18n("Capturing image..."));

        if (inAutoFocus == false)
        {
            captureB->setEnabled(false);
            stopFocusB->setEnabled(true);
        }
    }
}

Jasem Mutlaq's avatar
Jasem Mutlaq committed
871
void Focus::focusIn(int ms)
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
{
  if (currentFocuser == NULL)
       return;

  if (currentFocuser->isConnected() == false)
  {
            appendLogText(i18n("Error: Lost connection to Focuser."));
            return;
  }

    if (ms == -1)
        ms = stepIN->value();

    if (Options::focusLogging())
        qDebug() << "Focus: Focus in (" << ms << ")" ;

    lastFocusDirection = FOCUS_IN;

     currentFocuser->focusIn();

     if (canAbsMove)
     {
         currentFocuser->moveAbs(currentPosition-ms);
         appendLogText(i18n("Focusing inward..."));
     }
     else if (canRelMove)
     {
         currentFocuser->moveRel(ms);
         appendLogText(i18n("Focusing inward..."));
     }
     else
     {
       currentFocuser->moveByTimer(ms);
       appendLogText(i18n("Focusing inward by %1 ms...", ms));
     }



}

Jasem Mutlaq's avatar
Jasem Mutlaq committed
912
void Focus::focusOut(int ms)
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
{
    if (currentFocuser == NULL)
         return;

    if (currentFocuser->isConnected() == false)
    {
       appendLogText(i18n("Error: Lost connection to Focuser."));
       return;
    }

    lastFocusDirection = FOCUS_OUT;

    if (ms == -1)
        ms = stepIN->value();

    if (Options::focusLogging())
        qDebug() << "Focus: Focus out (" << ms << ")" ;

     currentFocuser->focusOut();

    if (canAbsMove)
    {
           currentFocuser->moveAbs(currentPosition+ms);
           appendLogText(i18n("Focusing outward..."));
    }
    else if (canRelMove)
    {
            currentFocuser->moveRel(ms);
            appendLogText(i18n("Focusing outward..."));
    }
    else
    {
            currentFocuser->moveByTimer(ms);
            appendLogText(i18n("Focusing outward by %1 ms...", ms));
    }
}

void Focus::newFITS(IBLOB *bp)
{
    if (bp == NULL)
    {
        capture();
        return;
    }

    // Ignore guide head if there is any.
    if (!strcmp(bp->name, "CCD2"))
        return;

    ISD::CCDChip *targetChip = currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);
    disconnect(currentCCD, SIGNAL(BLOBUpdated(IBLOB*)), this, SLOT(newFITS(IBLOB*)));

    if (darkFrameCheck->isChecked())
966
    {        
967
968
969
970
971
972
973
974
975
976
        FITSData *darkData       = NULL;
        QVariantMap settings = frameSettings[targetChip];
        uint16_t offsetX = settings["x"].toInt() / settings["binx"].toInt();
        uint16_t offsetY = settings["y"].toInt() / settings["biny"].toInt();

        darkData = DarkLibrary::Instance()->getDarkFrame(targetChip, exposureIN->value());

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

977
978
        targetChip->setCaptureFilter(defaultScale);

979
        if (darkData)
980
            DarkLibrary::Instance()->subtract(darkData, focusView, defaultScale, offsetX, offsetY);
981
        else
982
983
984
985
        {
            bool rc = DarkLibrary::Instance()->captureAndSubtract(targetChip, focusView, exposureIN->value(), offsetX, offsetY);
            darkFrameCheck->setChecked(rc);
        }
986
987
988
989
990
991
992
993
994
995
996
997

        return;
    }

    setCaptureComplete();
}

void Focus::setCaptureComplete()
{
    DarkLibrary::Instance()->disconnect(this);

    ISD::CCDChip *targetChip = currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);
998
999
    int subBinX=1, subBinY=1;
    targetChip->getBinning(&subBinX, &subBinY);
1000
1001

    // Always reset capture mode to NORMAL
1002
1003
    // JM 2016-09-28: Disable setting back to FITS_NORMAL as it might be causing issues. Each module should set capture module separately.
    //targetChip->setCaptureMode(FITS_NORMAL);
1004

1005
    syncTrackingBoxPosition();
1006

1007
    //connect(targetImage, SIGNAL(trackingStarSelected(int,int)), this, SLOT(focusStarSelected(int, int)), Qt::UniqueConnection);
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020

    if (inFocusLoop == false)
        appendLogText(i18n("Image received."));

    if (captureInProgress && inFocusLoop == false && inAutoFocus==false)
    {
        captureB->setEnabled(true);
        stopFocusB->setEnabled(false);
        currentCCD->setUploadMode(rememberUploadMode);
    }

    captureInProgress = false;

1021
    FITSData *image_data = focusView->getImageData();
1022

1023
    starPixmap = focusView->getTrackingBoxPixmap();
1024
1025
1026
    emit newStarPixmap(starPixmap);

    // If we're not framing, let's try to detect stars
1027
    if (inFocusLoop == false || (inFocusLoop && focusView->isTrackingBoxEnabled()))
1028
1029
1030
    {
        if (image_data->areStarsSearched() == false)
        {
1031
1032
1033
            //if (starSelected == false && autoStarCheck->isChecked() && subFramed == false)
            //if (autoStarCheck->isChecked() && subFramed == false)
                //focusView->findStars(ALGORITHM_CENTROID);
1034

1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
            if (subFramed && focusView->isTrackingBoxEnabled())
            {
                focusView->findStars(focusAlgorithm);
                focusView->updateFrame();
                currentHFR= image_data->getHFR(HFR_MAX);
            }
            else if (autoStarCheck->isChecked())
            {
                focusView->findStars(ALGORITHM_CENTROID);
                focusView->updateFrame();
                currentHFR= image_data->getHFR(HFR_MAX);
            }
1047
1048
1049
1050
1051
1052
1053
        }

        if (Options::focusLogging())
            qDebug() << "Focus newFITS #" << frameNum+1 << ": Current HFR " << currentHFR;

        HFRFrames[frameNum++] = currentHFR;

1054
        if (frameNum >= 1 /*focusFramesSpin->value()*/)
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
        {
            currentHFR=0;
            for (int i=0; i < frameNum; i++)
                currentHFR+= HFRFrames[i];

            currentHFR /= frameNum;
            frameNum =0;
        }
        else
        {
            capture();
            return;
        }

        emit newHFR(currentHFR);

        QString HFRText = QString("%1").arg(currentHFR, 0,'g', 3);

1073
        if (/*focusType == FOCUS_MANUAL && */ lastHFR == -1)
1074
1075
1076
1077
1078
1079
1080
1081
                appendLogText(i18n("FITS received. No stars detected."));

        HFROut->setText(HFRText);

        if (currentHFR > 0)
        {
            // Center tracking box around selected star
            //if (starSelected && inAutoFocus)
1082
            if (starCenter.isNull() == false && (inAutoFocus || minimumRequiredHFR >= 0))
1083
1084
1085
1086
1087
            {
                Edge *maxStarHFR = image_data->getMaxHFRStar();

                if (maxStarHFR)
                {
1088
                    starSelected=true;
1089
1090
                    starCenter.setX(qMax(0, static_cast<int>(maxStarHFR->x)));
                    starCenter.setY(qMax(0, static_cast<int>(maxStarHFR->y)));
1091
1092

                    syncTrackingBoxPosition();
1093
1094
1095
1096
                }
            }

            if (currentHFR > maxHFR)
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1097
                maxHFR = currentHFR;            
1098

Jasem Mutlaq's avatar
Jasem Mutlaq committed
1099
1100
1101
1102
1103
1104
1105
            if (inFocusLoop || (inAutoFocus && canAbsMove == false && canRelMove == false))
            {
                if (hfr_position.empty())
                    hfr_position.append(1);
                else
                    hfr_position.append(hfr_position.last()+1);
                hfr_value.append(currentHFR);
1106
1107

                drawHFRPlot();
Jasem Mutlaq's avatar
Jasem Mutlaq committed
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
        }
    }

    // If just framing, let's capture again
    if (inFocusLoop)
    {
        capture();
        return;
    }

    //if (starSelected == false)
    if (starCenter.isNull())
    {
        int x=0, y=0, w=0,h=0;

        if (frameSettings.contains(targetChip))
        {
            QVariantMap settings = frameSettings[targetChip];
            x = settings["x"].toInt();
            y = settings["y"].toInt();
            w = settings["w"].toInt();
            h = settings["h"].toInt();
        }
        else
            targetChip->getFrame(&x, &y, &w, &h);

Jasem Mutlaq's avatar
Jasem Mutlaq committed
1135
        if (autoStarCheck->isChecked())
1136
1137
1138
1139
        {
            Edge *maxStar = image_data->getMaxHFRStar();
            if (maxStar == NULL)
            {
1140
                appendLogText(i18n("Failed to automatically select a star. Please select a star manually."));                                
1141
1142
1143
1144
1145

                //if (fw == 0 || fh == 0)
                    //targetChip->getFrame(&fx, &fy, &fw, &fh);

                //targetImage->setTrackingBox(QRect((fw-focusBoxSize->value())/2, (fh-focusBoxSize->value())/2, focusBoxSize->value(), focusBoxSize->value()));
1146
1147
                focusView->setTrackingBox(QRect(w-focusBoxSize->value()/(subBinX*2), h-focusBoxSize->value()/(subBinY*2), focusBoxSize->value()/subBinX, focusBoxSize->value()/subBinY));
                focusView->setTrackingBoxEnabled(true);
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158

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

                QTimer::singleShot(AUTO_STAR_TIMEOUT, this, SLOT(checkAutoStarTimeout()));

                return;
            }

            if (subFramed == false && kcfg_subFrame->isEnabled() && kcfg_subFrame->isChecked())
            {
1159
1160
1161
1162
1163
                int offset = (static_cast<double>(focusBoxSize->value()) / subBinX) * 1.5;
                int subX=(maxStar->x - offset) * subBinX;
                int subY=(maxStar->y - offset) * subBinY;
                int subW=offset*2*subBinX;
                int subH=offset*2*subBinY;
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
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201

                int minX, maxX, minY, maxY, minW, maxW, minH, maxH;
                targetChip->getFrameMinMax(&minX, &maxX, &minY, &maxY, &minW, &maxW, &minH, &maxH);

                if (subX< minX)
                    subX=minX;
                if (subY< minY)
                    subY= minY;
                if ((subW+subX)> maxW)
                    subW=maxW-subX;
                if ((subH+subY)> maxH)
                    subH=maxH-subY;

                //targetChip->setFocusFrame(subX, subY, subW, subH);

                //fx += subX;
                //fy += subY;
                //fw = subW;
                //fh = subH;
                //frameModified = true;

                //x += subX;
                //y += subY;
                //w = subW;
                //h = subH;

                QVariantMap settings = frameSettings[targetChip];
                settings["x"] = subX;
                settings["y"] = subY;
                settings["w"] = subW;
                settings["h"] = subH;
                settings["binx"] = subBinX;
                settings["biny"] = subBinY;

                frameSettings[targetChip] = settings;

                starCenter.setX(subW/(2*subBinX));
                starCenter.setY(subH/(2*subBinY));
1202
                starCenter.setZ(subBinX);
1203
1204

                subFramed = true;
1205

1206
1207
                focusView->setFirstLoad(true);

1208
                capture();
1209
1210
1211
1212
1213
            }
            else
            {
                starCenter.setX(maxStar->x);
                starCenter.setY(maxStar->y);
1214
                starCenter.setZ(subBinX);
1215
1216
1217

                if (inAutoFocus)
                    capture();
1218
1219
            }

1220
1221
            syncTrackingBoxPosition();
            defaultScale = static_cast<FITSScale>(filterCombo->currentIndex());            
1222
1223
            return;
        }
1224
        else
1225
1226
1227
        {
            appendLogText(i18n("Capture complete. Select a star to focus."));

1228
            starSelected = false;
1229
1230
1231
1232
1233
1234
            //if (fw == 0 || fh == 0)
                //targetChip->getFrame(&fx, &fy, &fw, &fh);

            int subBinX=1,subBinY=1;
            targetChip->getBinning(&subBinX, &subBinY);

1235
1236
            focusView->setTrackingBox(QRect((w-focusBoxSize->value())/(subBinX*2), (h-focusBoxSize->value())/(2*subBinY), focusBoxSize->value()/subBinX, focusBoxSize->value()/subBinY));
            focusView->setTrackingBoxEnabled(true);
1237
1238
1239

            state = Ekos::FOCUS_WAITING;
            emit newStatus(state);
1240
            //connect(targetImage, SIGNAL(trackingStarSelected(int,int)), this, SLOT(focusStarSelected(int, int)), Qt::UniqueConnection);
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
            return;
        }
    }

    if (minimumRequiredHFR >= 0)
    {
        if (currentHFR == -1)
        {
            if (noStarCount++ < MAX_RECAPTURE_RETRIES)
            {
                appendLogText(i18n("No stars detected, capturing again..."));
                // On Last Attempt reset focus frame to capture full frame and recapture star if possible
                if (noStarCount == MAX_RECAPTURE_RETRIES)
                    resetFrame();
                capture();
                return;
            }
            else
            {
                noStarCount = 0;
                setAutoFocusResult(false);
            }
        }
        else if (currentHFR > minimumRequiredHFR)
        {
1266
           inSequenceFocus = true;           
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
           start();
        }
        else
        {
            setAutoFocusResult(true);
        }

        minimumRequiredHFR = -1;

        return;
    }

    drawProfilePlot();

    if (Options::focusLogging())
    {
        QDir dir;
        QString path = KSPaths::writableLocation(QStandardPaths::GenericDataLocation) + "autofocus/" + QDateTime::currentDateTime().toString("yyyy-MM-dd");
        dir.mkpath(path);
        QString name = "autofocus_frame_" + QDateTime::currentDateTime().toString("HH:mm:ss") + ".fits";
        QString filename = path + QStringLiteral("/") + name;
1288
        focusView->getImageData()->saveFITS(filename);
1289
1290
    }

1291
1292
1293
    if (inAutoFocus==false)
        return;

1294
1295
1296
1297
1298
1299
    if (state != Ekos::FOCUS_PROGRESS)
    {
        state = Ekos::FOCUS_PROGRESS;
        emit newStatus(state);
    }

1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
    if (canAbsMove || canRelMove)
        autoFocusAbs();
    else
        autoFocusRel();
}

void Focus::clearDataPoints()
{
    maxHFR=1;
    hfr_position.clear();
    hfr_value.clear();

    drawHFRPlot();
}

void Focus::drawHFRPlot()
{
    v_graph->setData(hfr_position, hfr_value);

Jasem Mutlaq's avatar
Jasem Mutlaq committed
1319
    if (inFocusLoop == false && (canAbsMove || canRelMove))
1320
1321
1322
1323
1324
1325
1326
1327
1328
    {
        //HFRPlot->xAxis->setLabel(i18n("Position"));
        HFRPlot->xAxis->setRange(minPos-pulseDuration, maxPos+pulseDuration);
        HFRPlot->yAxis->setRange(currentHFR/1.5, maxHFR);
    }
    else
    {
        //HFRPlot->xAxis->setLabel(i18n("Iteration"));
        HFRPlot->xAxis->setRange(1, hfr_value.count()+1);
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1329
        HFRPlot->yAxis->setRange(currentHFR/1.5, maxHFR*1.25);
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
    }

    HFRPlot->replot();

}

void Focus::drawProfilePlot()
{
    QVector<double> currentIndexes;
    QVector<double> currentFrequencies;

    // HFR = 50% * 1.36 = 68% aka one standard deviation
    double stdDev = currentHFR * 1.36;
    float start= -stdDev*4;
    float end  = stdDev*4;
    float step = stdDev*4 / 20.0;
    for (float x=start; x < end; x+= step)
    {
        currentIndexes.append(x);
        currentFrequencies.append((1/(stdDev*sqrt(2*M_PI))) * exp(-1 * ( x*x ) / (2 * (stdDev * stdDev))));
    }

    currentGaus->setData(currentIndexes, currentFrequencies);

    if (lastGausIndexes.count() > 0)
        lastGaus->setData(lastGausIndexes, lastGausFrequencies);

    if (focusType == FOCUS_AUTO && firstGaus == NULL)
    {
        firstGaus = profilePlot->addGraph();
        QPen pen;
        pen.setStyle(Qt::DashDotLine);
        pen.setWidth(2);
        pen.setColor(Qt::darkMagenta);
        firstGaus->setPen(pen);

        firstGaus->setData(currentIndexes, currentFrequencies);
    }
1368
    else if (firstGaus)
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
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
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
    {
        profilePlot->removeGraph(firstGaus);
        firstGaus=NULL;
    }

    profilePlot->rescaleAxes();
    profilePlot->replot();

    lastGausIndexes      = currentIndexes;
    lastGausFrequencies  = currentFrequencies;

    profilePixmap = profilePlot->grab();
    emit newProfilePixmap(profilePixmap);
}

void Focus::autoFocusAbs()
{
    static int lastHFRPos=0, minHFRPos=0, initSlopePos=0, focusOutLimit=0, focusInLimit=0;
    static double minHFR=0, initSlopeHFR=0;
    double targetPosition=0, delta=0;

    QString deltaTxt = QString("%1").arg(fabs(currentHFR-minHFR)*100.0, 0,'g', 3);
    QString HFRText = QString("%1").arg(currentHFR, 0,'g', 3);

    if (Options::focusLogging())
    {
        qDebug() << "Focus: ########################################";
        qDebug() << "Focus: ========================================";
        qDebug() << "Focus: Current HFR: " << currentHFR << " Current Position: " << currentPosition;
        qDebug() << "Focus: Last minHFR: " << minHFR << " Last MinHFR Pos: " << minHFRPos;
        qDebug() << "Focus: Delta: " << deltaTxt << "%";
        qDebug() << "Focus: ========================================";
    }

    if (minHFR)
         appendLogText(i18n("FITS received. HFR %1 @ %2. Delta (%3%)", HFRText, currentPosition, deltaTxt));
    else
        appendLogText(i18n("FITS received. HFR %1 @ %2.", HFRText, currentPosition));

    if (++absIterations > MAXIMUM_ABS_ITERATIONS)
    {
        appendLogText(i18n("Autofocus failed to reach proper focus. Try increasing tolerance value."));
        abort();
        setAutoFocusResult(false);
        return;
    }

    // No stars detected, try to capture again
    if (currentHFR == -1)
    {
        if (noStarCount < MAX_RECAPTURE_RETRIES)
        {
            appendLogText(i18n("No stars detected, capturing again..."));
            capture();
            noStarCount++;
            return;
        }
        else if (noStarCount == MAX_RECAPTURE_RETRIES)
        {
            currentHFR = 20;
            noStarCount++;
        }
        else
        {
            appendLogText(i18n("Failed to detect any stars. Reset frame and try again."));
            abort();
            setAutoFocusResult(false);
            return;
        }
    }
    else
        noStarCount = 0;

    /*if (currentHFR > maxHFR || HFRAbsolutePoints.empty())
    {
        maxHFR = currentHFR;

        if (HFRAbsolutePoints.empty())
        {
            maxPos=1;
            minPos=1e6;
        }
    }*/

    if (hfr_position.empty())
    {
        maxPos=1;
        minPos=1e6;
    }

    if (currentPosition > maxPos)
        maxPos = currentPosition;
    if (currentPosition < minPos)
        minPos = currentPosition;

    //HFRPoint *p = new HFRPoint();

    //p->HFR = currentHFR;
    //p->pos = currentPosition;

    hfr_position.append(currentPosition);
    hfr_value.append(currentHFR);

    //HFRAbsolutePoints.append(p);

    drawHFRPlot();

    switch (lastFocusDirection)
    {
        case FOCUS_NONE:
            lastHFR = currentHFR;
            initialFocuserAbsPosition = currentPosition;
            minHFR=currentHFR;
            minHFRPos=currentPosition;
            HFRDec=0;
            HFRInc=0;
            focusOutLimit=0;
            focusInLimit=0;
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1487
            focusOut(pulseDuration);
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
            break;

        case FOCUS_IN:
        case FOCUS_OUT:
        if (reverseDir && focusInLimit && focusOutLimit && fabs(currentHFR - minHFR) < (toleranceIN->value()/100.0) && HFRInc == 0 )
            {
                if (absIterations <= 2)
                {
                    appendLogText(i18n("Change in HFR is too small. Try increasing the step size or decreasing the tolerance."));
                    abort();
                    setAutoFocusResult(false);
                }
                else if (noStarCount > 0)
                {
                    appendLogText(i18n("Failed to detect focus star in frame. Capture and select a focus star."));
                    abort();
                    setAutoFocusResult(false);
                }
                else
                {
                    appendLogText(i18n("Autofocus complete."));
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1509
                    stop();
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1510
                    emit resumeGuiding();
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
                    setAutoFocusResult(true);
                }
                break;
            }
            else if (currentHFR < lastHFR)
            {
                double slope=0;

                // Let's try to calculate slope of the V curve.
                if (initSlopeHFR == 0 && HFRInc == 0 && HFRDec >= 1)
                {
                    initSlopeHFR = lastHFR;
                    initSlopePos = lastHFRPos;

                    if (Options::focusLogging())
                        qDebug() << "Focus: Setting initial slop to " << initSlopePos << " @ HFR " << initSlopeHFR;
                }

                // Let's now limit the travel distance of the focuser
                if (lastFocusDirection == FOCUS_OUT && lastHFRPos < focusInLimit && fabs(currentHFR - lastHFR) > 0.1)
                {
                    focusInLimit = lastHFRPos;
                    if (Options::focusLogging())
                        qDebug() << "Focus: New FocusInLimit " << focusInLimit;
                }
                else if (lastFocusDirection == FOCUS_IN && lastHFRPos > focusOutLimit && fabs(currentHFR - lastHFR) > 0.1)
                {
                    focusOutLimit = lastHFRPos;
                    if (Options::focusLogging())
                        qDebug() << "Focus: New FocusOutLimit " << focusOutLimit;
                }

                // If we have slope, get next target position
                if (initSlopeHFR && absMotionMax > 50)
                {
                    double factor=0.5;
                    slope = (currentHFR - initSlopeHFR) / (currentPosition - initSlopePos);
                    if (fabs(currentHFR-minHFR)*100.0 < 0.5)
                        factor = 1 - fabs(currentHFR-minHFR)*10;
                    targetPosition = currentPosition + (currentHFR*factor - currentHFR)/slope;
                    if (targetPosition < 0)
                    {
                        factor = 1;
                        while (targetPosition < 0 && factor > 0)
                        {
                           factor -= 0.005;
                            targetPosition = currentPosition + (currentHFR*factor - currentHFR)/slope;
                        }
                    }
                    if (Options::focusLogging())
                        qDebug() << "Focus: Using slope to calculate target pulse...";
                }
                // Otherwise proceed iteratively
                else
                {
                     if (lastFocusDirection == FOCUS_IN)
                         targetPosition = currentPosition - pulseDuration;
                     else
                         targetPosition = currentPosition + pulseDuration;

                     if (Options::focusLogging())
                        qDebug() << "Focus: Proceeding iteratively to next target pulse ...";
                }

                if (Options::focusLogging())
                    qDebug() << "Focus: V-Curve Slope " << slope << " current Position " << currentPosition << " targetPosition " << targetPosition;

                lastHFR = currentHFR;

                // Let's keep track of the minimum HFR
                if (lastHFR < minHFR)
                {
                    minHFR = lastHFR;
                    minHFRPos = currentPosition;
                    if (Options::focusLogging())
                    {
                        qDebug() << "Focus: new minHFR " << minHFR << " @ positioin " << minHFRPos;
                        qDebug() << "Focus: ########################################";
                    }

                }

                lastHFRPos = currentPosition;

                // HFR is decreasing, we are on the right direction
                HFRDec++;
                HFRInc=0;
            }
            else

            {
                // HFR increased, let's deal with it.
                HFRInc++;
                HFRDec=0;

                // Reality Check: If it's first time, let's capture again and see if it changes.
                /*if (HFRInc <= 1 && reverseDir == false)
                {
                    capture();
                    return;
                }
                // Looks like we're going away from optimal HFR
                else
                {*/
                    reverseDir = true;
                    lastHFR = currentHFR;
                    lastHFRPos = currentPosition;
                    initSlopeHFR=0;
                    HFRInc=0;

                    if (Options::focusLogging())
                        qDebug() << "Focus: We are going away from optimal HFR ";

                    // Let's set new limits
                    if (lastFocusDirection == FOCUS_IN)
                    {
                        focusInLimit = currentPosition;
                        if (Options::focusLogging())
                            qDebug() << "Focus: Setting focus IN limit to " << focusInLimit;
                    }
                    else
                    {
                        focusOutLimit = currentPosition;
                        if (Options::focusLogging())
                            qDebug() << "Focus: Setting focus OUT limit to " << focusOutLimit;
                    }

                    // Decrease pulse
                    pulseDuration = pulseDuration * 0.75;

                    // Let's get close to the minimum HFR position so far detected
                    if (lastFocusDirection == FOCUS_OUT)
                          targetPosition = minHFRPos-pulseDuration/2;
                     else
                          targetPosition = minHFRPos+pulseDuration/2;

                    if (Options::focusLogging())
                        qDebug() << "Focus: new targetPosition " << targetPosition;

               // }
            }

        // Limit target Pulse to algorithm limits
        if (focusInLimit != 0 && lastFocusDirection == FOCUS_IN && targetPosition < focusInLimit)
        {
            targetPosition = focusInLimit;
            if (Options::focusLogging())
                qDebug() << "Focus: Limiting target pulse to focus in limit " << targetPosition;
        }
        else if (focusOutLimit != 0 && lastFocusDirection == FOCUS_OUT && targetPosition > focusOutLimit)
        {
            targetPosition = focusOutLimit;
            if (Options::focusLogging())
                qDebug() << "Focus: Limiting target pulse to focus out limit " << targetPosition;
        }

        // Limit target pulse to focuser limits
        if (targetPosition < absMotionMin)
            targetPosition = absMotionMin;
        else if (targetPosition > absMotionMax)
            targetPosition = absMotionMax;

        // Ops, we can't go any further, we're done.
        if (targetPosition == currentPosition)
        {
            appendLogText(i18n("Autofocus complete."));
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1677
            stop();
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1678
            emit resumeGuiding();
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
            setAutoFocusResult(true);
            return;
        }

        // Ops, deadlock
        if (focusOutLimit && focusOutLimit == focusInLimit)
        {
            appendLogText(i18n("Deadlock reached. Please try again with different settings."));
            abort();
            setAutoFocusResult(false);
            return;
        }

        if (fabs(targetPosition - initialFocuserAbsPosition) > maxTravelIN->value())
        {
            if (Options::focusLogging())
                qDebug() << "Focus: targetPosition (" << targetPosition << ") - initHFRAbsPos (" << initialFocuserAbsPosition << ") exceeds maxTravel distance of " << maxTravelIN->value();

            appendLogText("Maximum travel limit reached. Autofocus aborted.");
            abort();
            setAutoFocusResult(false);
            break;

        }

        // Get delta for next move
        delta = (targetPosition - currentPosition);

        if (Options::focusLogging())
        {
            qDebug() << "Focus: delta (targetPosition - currentPosition) " << delta;
            qDebug() << "Focus: Focusing " << ((delta < 0) ? "IN"  : "OUT");
            qDebug() << "Focus: ########################################";
        }

        // Now cross your fingers and wait
       if (delta > 0)
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1716
            focusOut(delta);
1717
        else
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1718
          focusIn(fabs(delta));
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
        break;

    }

}

void Focus::autoFocusRel()
{
    static int noStarCount=0;
    static double minHFR=1e6;
    QString deltaTxt = QString("%1").arg(fabs(currentHFR-minHFR)*100.0, 0,'g', 2);
    QString minHFRText = QString("%1").arg(minHFR, 0, 'g', 3);
    QString HFRText = QString("%1").arg(currentHFR, 0,'g', 3);

    appendLogText(i18n("FITS received. HFR %1. Delta (%2%) Min HFR (%3)", HFRText, deltaTxt, minHFRText));

    if (pulseDuration <= MINIMUM_PULSE_TIMER)
    {
        appendLogText(i18n("Autofocus failed to reach proper focus. Try adjusting the tolerance value."));
        abort();
        setAutoFocusResult(false);
        return;
    }

    // No stars detected, try to capture again
    if (currentHFR == -1)
    {
        if (noStarCount++ < MAX_RECAPTURE_RETRIES)
        {
            appendLogText(i18n("No stars detected, capturing again..."));
            capture();
            return;
        }
        else
            currentHFR = 20;
    }
    else
        noStarCount = 0;

    switch (lastFocusDirection)
    {
        case FOCUS_NONE:
            lastHFR = currentHFR;
            minHFR=1e6;
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1763
            focusIn(pulseDuration);
1764
1765
1766
1767
1768
1769
1770
            break;

        case FOCUS_IN:
            //if (fabs(currentHFR - lastHFR) < (toleranceIN->value()/100.0) && HFRInc == 0)
            if (fabs(currentHFR - minHFR) < (toleranceIN->value()/100.0) && HFRInc == 0)
            {
                appendLogText(i18n("Autofocus complete."));
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1771
                stop();
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1772
                emit resumeGuiding();
1773
1774
1775
1776
1777
1778
1779
1780
1781
                setAutoFocusResult(true);
                break;
            }
            else if (currentHFR < lastHFR)
            {
                if (currentHFR < minHFR)
                    minHFR = currentHFR;

                lastHFR = currentHFR;
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1782
                focusIn(pulseDuration);
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
                HFRInc=0;
            }
            else
            {
                HFRInc++;

                /*if (HFRInc <= 1)
                {
                    capture();
                    return;
                }
                else
                {*/

                    lastHFR = currentHFR;

                    HFRInc=0;

                    pulseDuration *= 0.75;
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1802
                    focusOut(pulseDuration);
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
                //}
            }

            break;

    case FOCUS_OUT:
        if (fabs(currentHFR - minHFR) < (toleranceIN->value()/100.0) && HFRInc == 0)
        //if (fabs(currentHFR - lastHFR) < (toleranceIN->value()/100.0) && HFRInc == 0)
        {
            appendLogText(i18n("Autofocus complete."));
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1813
            stop();
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1814
            emit resumeGuiding();
1815
1816
1817
1818
1819
1820
1821
1822
1823
            setAutoFocusResult(true);
            break;
        }
        else if (currentHFR < lastHFR)
        {
            if (currentHFR < minHFR)
                minHFR = currentHFR;

            lastHFR = currentHFR;
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1824
            focusOut(pulseDuration);
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
            HFRInc=0;
        }
        else
        {
            HFRInc++;

            /*if (HFRInc <= 1)
                capture();
            else
            {*/

                lastHFR = currentHFR;

                HFRInc=0;

                pulseDuration *= 0.75;
Jasem Mutlaq's avatar
Jasem Mutlaq committed
1841
                focusIn(pulseDuration);
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
            //}
        }

        break;

    }

}

void Focus::processFocusNumber(INumberVectorProperty *nvp)
{

    if (canAbsMove == false && currentFocuser->canAbsMove())
    {
        canAbsMove = true;
        getAbsFocusPosition();

        absTicksSpin->setEnabled(true);
        setAbsTicksB->setEnabled(true);
    }

    if (canRelMove == false && currentFocuser->canRelMove())
        canRelMove = true;

    if (!strcmp(nvp->name, "ABS_FOCUS_POSITION"))
    {
       INumber *pos = IUFindNumber(nvp, "FOCUS_ABSOLUTE_POSITION");
       if (pos)
       {
           currentPosition = pos->value;
           absTicksSpin->setValue(currentPosition);
       }

       if (resetFocus && nvp->s == IPS_OK)
       {
           resetFocus = false;
           appendLogText(i18n("Restarting autofocus process..."));
           start();
       }

       if (canAbsMove && inAutoFocus)
       {
           if (nvp->s == IPS_OK && captureInProgress == false)
               capture();
           else if (nvp->s == IPS_ALERT)
           {
               appendLogText(i18n("Focuser error, check INDI panel."));
               abort();
               setAutoFocusResult(false);
           }

       }

       return;
    }

    if (canAbsMove)
        return;

    if (!strcmp(nvp->name, "REL_FOCUS_POSITION"))
    {
        INumber *pos = IUFindNumber(nvp, "FOCUS_RELATIVE_POSITION");
        if (pos && nvp->s == IPS_OK)
            currentPosition += pos->value * (lastFocusDirection == FOCUS_IN ? -1 : 1);

        if (resetFocus && nvp->s == IPS_OK)
        {
            resetFocus = false;
            appendLogText(i18n("Restarting autofocus process..."));
            start();
        }

        if (canRelMove && inAutoFocus)
        {
            if (nvp->s == IPS_OK && captureInProgress == false)
                capture();
            else if (nvp->s == IPS_ALERT)
            {
                appendLogText(i18n("Focuser error, check INDI panel."));
                abort();
                setAutoFocusResult(false);
            }
        }

        return;
    }

    if (canRelMove)
        return;

    if (!strcmp(nvp->name, "FOCUS_TIMER"))
    {
        if (resetFocus && nvp->s == IPS_OK)
        {
            resetFocus = false;
            appendLogText(i18n("Restarting autofocus process..."));
            start();
        }

        if (canAbsMove == false && canRelMove == false && inAutoFocus)
        {
            if (nvp->s == IPS_OK && captureInProgress == false)
                capture();
            else if (nvp->s == IPS_ALERT)
            {
                appendLogText(i18n("Focuser error, check INDI panel."));
                abort();
                setAutoFocusResult(false);
            }

        }

        return;
    }

}

void Focus::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::focusLogging())
        qDebug() << "Focus: " << text;

    emit newLog();
}

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

void Focus::startFraming()
{
    if (currentCCD == NULL)
    {
        appendLogText(i18n("No CCD connected."));
        return;
    }

    inFocusLoop = true;
    frameNum=0;

Jasem Mutlaq's avatar
Jasem Mutlaq committed
1987
1988
    clearDataPoints();

1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
    //emit statusUpdated(true);
    state = Ekos::FOCUS_FRAMING;
    emit newStatus(state);

    resetButtons();

    appendLogText(i18n("Starting continuous exposure..."));

    capture();
}

void Focus::resetButtons()
{
    if (inFocusLoop)
    {
        startFocusB->setEnabled(false);
        startLoopB->setEnabled(false);
        stopFocusB->setEnabled(true);

        captureB->setEnabled(false);

        return;
    }

    if (inAutoFocus)
    {
        stopFocusB->setEnabled(true);

        startFocusB->setEnabled(false);
        startLoopB->setEnabled(false);
        captureB->setEnabled(false);
        focusOutB->setEnabled(false);
        focusInB->setEnabled(false);
Jasem Mutlaq's avatar
Jasem Mutlaq committed
2022
        setAbsTicksB->setEnabled(false);
2023
2024
2025
2026

        return;
    }

Jasem Mutlaq's avatar
Jasem Mutlaq committed
2027
    if (currentFocuser)
2028
    {
Jasem Mutlaq's avatar
Jasem Mutlaq committed
2029
2030
2031
2032
2033
        focusOutB->setEnabled(true);
        focusInB->setEnabled(true);

        startFocusB->setEnabled(focusType == FOCUS_AUTO);
        setAbsTicksB->setEnabled(canAbsMove || canRelMove);
2034
2035

    }
Jasem Mutlaq's avatar
Jasem Mutlaq committed
2036
2037
2038

    stopFocusB->setEnabled(false);
    startLoopB->setEnabled(true);
2039
2040
2041
2042
2043
2044

    captureB->setEnabled(true);
}

void Focus::updateBoxSize(int value)
{
Jasem Mutlaq's avatar
Jasem Mutlaq committed
2045
2046
2047
    if (currentCCD == NULL)
        return;

2048
2049
2050
2051
    ISD::CCDChip *targetChip = currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);
    if (targetChip == NULL)
        return;

2052
    QRect trackBox = focusView->getTrackingBox();
2053
2054
2055
2056
2057
    trackBox.setX(trackBox.x()+(trackBox.width()-value)/2);
    trackBox.setY(trackBox.y()+(trackBox.height()-value)/2);
    trackBox.setWidth(value);
    trackBox.setHeight(value);

2058
    focusView->setTrackingBox(trackBox);
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
}

void Focus::focusStarSelected(int x, int y)
{
    if (state == Ekos::FOCUS_PROGRESS)
        return;

    ISD::CCDChip *targetChip = currentCCD->getChip(ISD::CCDChip::PRIMARY_CCD);

    int subBinX, subBinY;
    targetChip->getBinning(&subBinX, &subBinY);

    // If binning was changed outside of the focus module, recapture
    if (subBinX != activeBin)
    {
        capture();
        return;
    }

2078
    int offset = (static_cast<double>(focusBoxSize->value())/subBinX) * 1.5;
2079
2080
2081

    QRect starRect;

2082
2083
    bool squareMovedOutside=false;

2084
2085
2086
2087