/
phd2.cpp
1598 lines (1340 loc) · 49.6 KB
/
phd2.cpp
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
31
32
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
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
556
557
558
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
586
587
588
589
590
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
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
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
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
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
SPDX-FileCopyrightText: 2016 Jasem Mutlaq <mutlaqja@ikarustech.com>
SPDX-License-Identifier: GPL-2.0-or-later
*/
#include "phd2.h"
#include "Options.h"
#include "kspaths.h"
#include "kstars.h"
#include "ekos/manager.h"
#include "fitsviewer/fitsdata.h"
#include "ekos/guide/guide.h"
#include "fitsviewer/fitsview.h"
#include <cassert>
#include <fitsio.h>
#include <KMessageBox>
#include <QImage>
#include <QJsonDocument>
#include <QNetworkReply>
#include <ekos_guide_debug.h>
#define MAX_SET_CONNECTED_RETRIES 3
namespace Ekos
{
PHD2::PHD2()
{
tcpSocket = new QTcpSocket(this);
//This list of available PHD Events is on https://github.com/OpenPHDGuiding/phd2/wiki/EventMonitoring
events["Version"] = Version;
events["LockPositionSet"] = LockPositionSet;
events["Calibrating"] = Calibrating;
events["CalibrationComplete"] = CalibrationComplete;
events["StarSelected"] = StarSelected;
events["StartGuiding"] = StartGuiding;
events["Paused"] = Paused;
events["StartCalibration"] = StartCalibration;
events["AppState"] = AppState;
events["CalibrationFailed"] = CalibrationFailed;
events["CalibrationDataFlipped"] = CalibrationDataFlipped;
events["LoopingExposures"] = LoopingExposures;
events["LoopingExposuresStopped"] = LoopingExposuresStopped;
events["SettleBegin"] = SettleBegin;
events["Settling"] = Settling;
events["SettleDone"] = SettleDone;
events["StarLost"] = StarLost;
events["GuidingStopped"] = GuidingStopped;
events["Resumed"] = Resumed;
events["GuideStep"] = GuideStep;
events["GuidingDithered"] = GuidingDithered;
events["LockPositionLost"] = LockPositionLost;
events["Alert"] = Alert;
events["GuideParamChange"] = GuideParamChange;
events["ConfigurationChange"] = ConfigurationChange;
//This list of available PHD Methods is on https://github.com/OpenPHDGuiding/phd2/wiki/EventMonitoring
//Only some of the methods are implemented. The ones that say COMMAND_RECEIVED simply return a 0 saying the command was received.
methodResults["capture_single_frame"] = CAPTURE_SINGLE_FRAME;
methodResults["clear_calibration"] = CLEAR_CALIBRATION_COMMAND_RECEIVED;
methodResults["dither"] = DITHER_COMMAND_RECEIVED;
//find_star
//flip_calibration
//get_algo_param_names
//get_algo_param
methodResults["get_app_state"] = APP_STATE_RECEIVED;
//get_calibrated
//get_calibration_data
methodResults["get_connected"] = IS_EQUIPMENT_CONNECTED;
//get_cooler_status
methodResults["get_current_equipment"] = GET_CURRENT_EQUIPMENT;
methodResults["get_dec_guide_mode"] = DEC_GUIDE_MODE;
methodResults["get_exposure"] = EXPOSURE_TIME;
methodResults["get_exposure_durations"] = EXPOSURE_DURATIONS;
methodResults["get_lock_position"] = LOCK_POSITION;
//get_lock_shift_enabled
//get_lock_shift_params
//get_paused
methodResults["get_pixel_scale"] = PIXEL_SCALE;
//get_profile
//get_profiles
//get_search_region
//get_sensor_temperature
methodResults["get_star_image"] = STAR_IMAGE;
//get_use_subframes
methodResults["guide"] = GUIDE_COMMAND_RECEIVED;
//guide_pulse
methodResults["loop"] = LOOP;
//save_image
//set_algo_param
methodResults["set_connected"] = CONNECTION_RESULT;
methodResults["set_dec_guide_mode"] = SET_DEC_GUIDE_MODE_COMMAND_RECEIVED;
methodResults["set_exposure"] = SET_EXPOSURE_COMMAND_RECEIVED;
methodResults["set_lock_position"] = SET_LOCK_POSITION;
//set_lock_shift_enabled
//set_lock_shift_params
methodResults["set_paused"] = SET_PAUSED_COMMAND_RECEIVED;
//set_profile
//shutdown
methodResults["stop_capture"] = STOP_CAPTURE_COMMAND_RECEIVED;
abortTimer = new QTimer(this);
connect(abortTimer, &QTimer::timeout, this, [ = ]
{
if (state == CALIBRATING)
qCDebug(KSTARS_EKOS_GUIDE) << "Abort timeout expired while calibrating, retrying to guide.";
else if (state == LOSTLOCK)
qCDebug(KSTARS_EKOS_GUIDE) << "Abort timeout expired while reacquiring star, retrying to guide.";
else
qCDebug(KSTARS_EKOS_GUIDE) << "Abort timeout expired, stopping.";
abort();
});
ditherTimer = new QTimer(this);
connect(ditherTimer, &QTimer::timeout, this, [ = ]
{
qCDebug(KSTARS_EKOS_GUIDE) << "ditherTimer expired, state" << state << "dithering" << isDitherActive << "settling" << isSettling;
ditherTimer->stop();
isDitherActive = false;
isSettling = false;
if (Options::ditherFailAbortsAutoGuide())
{
abort();
emit newStatus(GUIDE_DITHERING_ERROR);
}
else
{
emit newLog(i18n("PHD2: There was no dithering response from PHD2, but continue guiding."));
emit newStatus(Ekos::GUIDE_DITHERING_SUCCESS);
}
});
stateTimer = new QTimer(this);
connect(stateTimer, &QTimer::timeout, this, [ = ]
{
QTcpSocket::SocketState socketstate = tcpSocket->state();
switch (socketstate)
{
case QTcpSocket::UnconnectedState:
m_PHD2ReconnectCounter++;
if (m_PHD2ReconnectCounter > PHD2_RECONNECT_THRESHOLD)
{
stateTimer->stop();
emit newLog(i18n("Giving up reconnecting."));
}
else
{
emit newLog(i18n("Reconnecting to PHD2 Host: %1, on port %2. . .", Options::pHD2Host(), Options::pHD2Port()));
connect(tcpSocket, &QTcpSocket::readyRead, this, &PHD2::readPHD2, Qt::UniqueConnection);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
connect(tcpSocket, &QTcpSocket::errorOccurred, this, &PHD2::displayError, Qt::UniqueConnection);
#else
connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this,
SLOT(displayError(QAbstractSocket::SocketError)));
#endif
tcpSocket->connectToHost(Options::pHD2Host(), Options::pHD2Port());
}
break;
case QTcpSocket::ConnectedState:
m_PHD2ReconnectCounter = 0;
checkIfEquipmentConnected();
requestAppState();
break;
default:
qCDebug(KSTARS_EKOS_GUIDE) << "PHD2: TCP connection state:" << socketstate;
break;
}
});
}
PHD2::~PHD2()
{
delete abortTimer;
delete ditherTimer;
}
bool PHD2::Connect()
{
switch (connection)
{
case DISCONNECTED:
// Not yet connected, let's connect server
connection = CONNECTING;
emit newLog(i18n("Connecting to PHD2 Host: %1, on port %2. . .", Options::pHD2Host(), Options::pHD2Port()));
connect(tcpSocket, &QTcpSocket::readyRead, this, &PHD2::readPHD2, Qt::UniqueConnection);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
connect(tcpSocket, &QTcpSocket::errorOccurred, this, &PHD2::displayError, Qt::UniqueConnection);
#else
connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this,
SLOT(displayError(QAbstractSocket::SocketError)));
#endif
tcpSocket->connectToHost(Options::pHD2Host(), Options::pHD2Port());
m_PHD2ReconnectCounter = 0;
stateTimer->start(PHD2_RECONNECT_TIMEOUT);
return true;
case EQUIPMENT_DISCONNECTED:
// Equipment disconnected from PHD2, request reconnection
connectEquipment(true);
return true;
case DISCONNECTING:
// Not supposed to interrupt a running disconnection
return false;
default:
return false;
}
}
void PHD2::ResetConnectionState()
{
connection = DISCONNECTED;
// clear the outstanding and queued RPC requests
pendingRpcResultType = NO_RESULT;
rpcRequestQueue.clear();
starImageRequested = false;
isSettling = false;
isDitherActive = false;
ditherTimer->stop();
abortTimer->stop();
tcpSocket->disconnect(this);
emit newStatus(GUIDE_DISCONNECTED);
}
bool PHD2::Disconnect()
{
switch (connection)
{
case EQUIPMENT_CONNECTED:
emit newLog(i18n("Aborting any capture before disconnecting equipment..."));
abort();
connection = DISCONNECTING;
break;
case CONNECTED:
case CONNECTING:
case EQUIPMENT_DISCONNECTED:
stateTimer->stop();
tcpSocket->disconnectFromHost();
ResetConnectionState();
if (tcpSocket->state() != QAbstractSocket::UnconnectedState)
tcpSocket->waitForDisconnected(5000);
emit newLog(i18n("Disconnected from PHD2 Host: %1, on port %2.", Options::pHD2Host(), Options::pHD2Port()));
break;
case DISCONNECTING:
case DISCONNECTED:
break;
}
return true;
}
void PHD2::displayError(QAbstractSocket::SocketError socketError)
{
switch (socketError)
{
case QAbstractSocket::RemoteHostClosedError:
emit newLog(i18n("The host disconnected."));
break;
case QAbstractSocket::HostNotFoundError:
emit newLog(i18n("The host was not found. Please check the host name and port settings in Guide options."));
break;
case QAbstractSocket::ConnectionRefusedError:
emit newLog(i18n("The connection was refused by the peer. Make sure the PHD2 is running, and check that "
"the host name and port settings are correct."));
break;
default:
emit newLog(i18n("The following error occurred: %1.", tcpSocket->errorString()));
}
ResetConnectionState();
emit newStatus(GUIDE_DISCONNECTED);
}
void PHD2::readPHD2()
{
while (!tcpSocket->atEnd() && tcpSocket->canReadLine())
{
QByteArray line = tcpSocket->readLine();
if (line.isEmpty())
continue;
QJsonParseError qjsonError;
QJsonDocument jdoc = QJsonDocument::fromJson(line, &qjsonError);
if (qjsonError.error != QJsonParseError::NoError)
{
emit newLog(i18n("PHD2: invalid response received: %1", QString(line)));
emit newLog(i18n("PHD2: JSON error: %1", qjsonError.errorString()));
continue;
}
QJsonObject jsonObj = jdoc.object();
if (jsonObj.contains("Event"))
processPHD2Event(jsonObj, line);
else if (jsonObj.contains("error"))
processPHD2Error(jsonObj, line);
else if (jsonObj.contains("result"))
processPHD2Result(jsonObj, line);
}
}
void PHD2::processPHD2Event(const QJsonObject &jsonEvent, const QByteArray &line)
{
if (Options::verboseLogging())
qCDebug(KSTARS_EKOS_GUIDE) << "PHD2: event:" << line;
QString eventName = jsonEvent["Event"].toString();
if (!events.contains(eventName))
{
emit newLog(i18n("Unknown PHD2 event: %1", eventName));
return;
}
event = events.value(eventName);
switch (event)
{
case Version:
emit newLog(i18n("PHD2: Version %1", jsonEvent["PHDVersion"].toString()));
break;
case CalibrationComplete:
emit newLog(i18n("PHD2: Calibration Complete."));
emit newStatus(Ekos::GUIDE_CALIBRATION_SUCCESS);
break;
case StartGuiding:
updateGuideParameters();
requestCurrentEquipmentUpdate();
// Do not report guiding as started because it will start scheduled capture before guiding is settled
// just print the log message and GUIDE_STARTED status will be set in SettleDone
// phd2 will always send SettleDone event
emit newLog(i18n("PHD2: Waiting for guiding to settle."));
break;
case Paused:
handlePHD2AppState(PAUSED);
break;
case StartCalibration:
handlePHD2AppState(CALIBRATING);
break;
case AppState:
// AppState is the last of the initial messages received when we first connect to PHD2
processPHD2State(jsonEvent["State"].toString());
// if the equipment is not already connected, then try to connect it.
if (connection == CONNECTING)
{
emit newLog("PHD2: Connecting equipment and external guider...");
connectEquipment(true);
}
break;
case CalibrationFailed:
emit newLog(i18n("PHD2: Calibration Failed (%1).", jsonEvent["Reason"].toString()));
handlePHD2AppState(STOPPED);
break;
case CalibrationDataFlipped:
emit newLog(i18n("Calibration Data Flipped."));
break;
case LoopingExposures:
handlePHD2AppState(LOOPING);
break;
case LoopingExposuresStopped:
handlePHD2AppState(STOPPED);
break;
case Calibrating:
case Settling:
case SettleBegin:
//This can happen for guiding or for dithering. A Settle done event will arrive when it finishes.
break;
case SettleDone:
{
// guiding stopped during dithering
if (state == PHD2::STOPPED)
return;
bool error = false;
if (jsonEvent["Status"].toInt() != 0)
{
error = true;
emit newLog(i18n("PHD2: Settling failed (%1).", jsonEvent["Error"].toString()));
}
bool wasDithering = isDitherActive;
isDitherActive = false;
isSettling = false;
if (wasDithering)
{
ditherTimer->stop();
if (error && Options::ditherFailAbortsAutoGuide())
{
abort();
emit newStatus(GUIDE_DITHERING_ERROR);
}
else
{
if (error)
emit newLog(i18n("PHD2: There was a dithering error, but continue guiding."));
emit newStatus(Ekos::GUIDE_DITHERING_SUCCESS);
}
}
else
{
if (error)
{
emit newLog(i18n("PHD2: Settling failed, aborted."));
emit newStatus(GUIDE_ABORTED);
}
else
{
// settle completed after "guide" command
emit newLog(i18n("PHD2: Settling complete, Guiding Started."));
emit newStatus(GUIDE_GUIDING);
}
}
}
break;
case StarSelected:
handlePHD2AppState(SELECTED);
break;
case StarLost:
// If we lost the guide star, let the state and abort timers update our state
handlePHD2AppState(LOSTLOCK);
break;
case GuidingStopped:
handlePHD2AppState(STOPPED);
break;
case Resumed:
handlePHD2AppState(GUIDING);
break;
case GuideStep:
{
// If we lost the guide star, let the state timer update our state
// Sometimes PHD2 is actually not guiding at that time, so we'll either resume or abort
if (state == LOSTLOCK)
emit newLog(i18n("PHD2: Star found, guiding is resuming..."));
if (isDitherActive)
return;
double diff_ra_pixels, diff_de_pixels, diff_ra_arcsecs, diff_de_arcsecs, pulse_ra, pulse_dec, snr;
QString RADirection, DECDirection;
diff_ra_pixels = jsonEvent["RADistanceRaw"].toDouble();
diff_de_pixels = jsonEvent["DECDistanceRaw"].toDouble();
pulse_ra = jsonEvent["RADuration"].toDouble();
pulse_dec = jsonEvent["DECDuration"].toDouble();
RADirection = jsonEvent["RADirection"].toString();
DECDirection = jsonEvent["DECDirection"].toString();
snr = jsonEvent["SNR"].toDouble();
if (RADirection == "East")
pulse_ra = -pulse_ra; //West Direction is Positive, East is Negative
if (DECDirection == "South")
pulse_dec = -pulse_dec; //South Direction is Negative, North is Positive
//If the pixelScale is properly set from PHD2, the second block of code is not needed, but if not, we will attempt to calculate the ra and dec error without it.
if (pixelScale != 0)
{
diff_ra_arcsecs = diff_ra_pixels * pixelScale;
diff_de_arcsecs = diff_de_pixels * pixelScale;
}
else
{
diff_ra_arcsecs = 206.26480624709 * diff_ra_pixels * ccdPixelSizeX / mountFocalLength;
diff_de_arcsecs = 206.26480624709 * diff_de_pixels * ccdPixelSizeY / mountFocalLength;
}
if (std::isfinite(snr))
emit newSNR(snr);
if (std::isfinite(diff_ra_arcsecs) && std::isfinite(diff_de_arcsecs))
{
errorLog.append(QPointF(diff_ra_arcsecs, diff_de_arcsecs));
if(errorLog.size() > 50)
errorLog.remove(0);
emit newAxisDelta(diff_ra_arcsecs, diff_de_arcsecs);
emit newAxisPulse(pulse_ra, pulse_dec);
// Does PHD2 real a sky background or num-stars measure?
emit guideStats(diff_ra_arcsecs, diff_de_arcsecs, pulse_ra, pulse_dec,
std::isfinite(snr) ? snr : 0, 0, 0);
double total_sqr_RA_error = 0.0;
double total_sqr_DE_error = 0.0;
for (auto &point : errorLog)
{
total_sqr_RA_error += point.x() * point.x();
total_sqr_DE_error += point.y() * point.y();
}
emit newAxisSigma(sqrt(total_sqr_RA_error / errorLog.size()), sqrt(total_sqr_DE_error / errorLog.size()));
}
//Note that if it is receiving full size remote images, it should not get the guide star image.
//But if it is not getting the full size images, or if the current camera is not in Ekos, it should get the guide star image
//If we are getting the full size image, we will want to know the lock position for the image that loads in the viewer.
if ( Options::guideSubframe() || currentCameraIsNotInEkos )
requestStarImage(32); //This requests a star image for the guide view. 32 x 32 pixels
else
requestLockPosition();
}
break;
case GuidingDithered:
break;
case LockPositionSet:
handlePHD2AppState(SELECTED);
break;
case LockPositionLost:
handlePHD2AppState(LOSTLOCK);
break;
case Alert:
emit newLog(i18n("PHD2 %1: %2", jsonEvent["Type"].toString(), jsonEvent["Msg"].toString()));
break;
case GuideParamChange:
case ConfigurationChange:
//Don't do anything for now, might change this later.
//Some Possible Parameter Names:
//Backlash comp enabled, Backlash comp amount,
//For Each Axis: MinMove, Max Duration,
//PPEC aggressiveness, PPEC prediction weight,
//Resist switch minimum motion, Resist switch aggression,
//Low-pass minimum move, Low-pass slope weight,
//Low-pass2 minimum move, Low-pass2 aggressiveness,
//Hysteresis hysteresis, Hysteresis aggression
break;
}
}
void PHD2::processPHD2State(const QString &phd2State)
{
if (phd2State == "Stopped")
handlePHD2AppState(STOPPED);
else if (phd2State == "Selected")
handlePHD2AppState(SELECTED);
else if (phd2State == "Calibrating")
handlePHD2AppState(CALIBRATING);
else if (phd2State == "Guiding")
handlePHD2AppState(GUIDING);
else if (phd2State == "LostLock")
handlePHD2AppState(LOSTLOCK);
else if (phd2State == "Paused")
handlePHD2AppState(PAUSED);
else if (phd2State == "Looping")
handlePHD2AppState(LOOPING);
else emit newLog(QString("PHD2: Unsupported app state ") + phd2State + ".");
}
void PHD2::handlePHD2AppState(PHD2State newstate)
{
// do not handle the same state twice
if (state == newstate)
return;
switch (newstate)
{
case STOPPED:
switch (state)
{
case CALIBRATING:
//emit newLog(i18n("PHD2: Calibration Failed (%1).", jsonEvent["Reason"].toString()));
emit newStatus(Ekos::GUIDE_CALIBRATION_ERROR);
break;
case LOOPING:
emit newLog(i18n("PHD2: Looping Exposures Stopped."));
emit newStatus(Ekos::GUIDE_IDLE);
break;
case GUIDING:
case LOSTLOCK:
emit newLog(i18n("PHD2: Guiding Stopped."));
emit newStatus(Ekos::GUIDE_ABORTED);
break;
default:
if (connection == DISCONNECTING)
{
emit newLog("PHD2: Disconnecting equipment and external guider...");
connectEquipment(false);
}
break;
}
break;
case SELECTED:
switch (state)
{
case STOPPED:
case CALIBRATING:
case GUIDING:
emit newLog(i18n("PHD2: Lock Position Set."));
if (isSettling)
{
newstate = CALIBRATING;
emit newStatus(Ekos::GUIDE_CALIBRATING);
}
break;
case DITHERING:
// do nothing, this is the initial step in PHD2 for dithering
break;
default:
emit newLog(i18n("PHD2: Star Selected."));
emit newStatus(GUIDE_STAR_SELECT);
}
break;
case GUIDING:
switch (state)
{
case PAUSED:
case DITHERING:
emit newLog(i18n("PHD2: Dithering successful."));
abortTimer->stop();
emit newStatus(Ekos::GUIDE_DITHERING_SUCCESS);
break;
default:
emit newLog(i18n("PHD2: Guiding started."));
abortTimer->stop();
emit newStatus(Ekos::GUIDE_GUIDING);
break;
}
break;
case LOSTLOCK:
switch (state)
{
case CALIBRATING:
emit newLog(i18n("PHD2: Lock Position Lost, continuing calibration."));
// Don't be paranoid, accept star-lost events during calibration and trust PHD2 to complete
//newstate = STOPPED;
//emit newStatus(Ekos::GUIDE_CALIBRATION_ERROR);
break;
case GUIDING:
emit newLog(i18n("PHD2: Star Lost. Trying to reacquire for %1s.", Options::guideLostStarTimeout()));
abortTimer->start(static_cast<int>(Options::guideLostStarTimeout()) * 1000);
qCDebug(KSTARS_EKOS_GUIDE) << "PHD2: Lost star timeout started (" << Options::guideLostStarTimeout() << " sec)";
emit newStatus(Ekos::GUIDE_REACQUIRE);
break;
default:
emit newLog(i18n("PHD2: Lock Position Lost."));
break;
}
break;
case PAUSED:
emit newLog(i18n("PHD2: Guiding paused."));
emit newStatus(GUIDE_SUSPENDED);
break;
case CALIBRATING:
emit newLog(i18n("PHD2: Calibrating, timing out in %1s.", Options::guideCalibrationTimeout()));
abortTimer->start(static_cast<int>(Options::guideCalibrationTimeout()) * 1000);
emit newStatus(GUIDE_CALIBRATING);
break;
case LOOPING:
switch (state)
{
case CALIBRATING:
emit newLog(i18n("PHD2: Calibration turned to looping, failed."));
emit newStatus(GUIDE_CALIBRATION_ERROR);
break;
default:
emit newLog(i18n("PHD2: Looping Exposures."));
emit newStatus(GUIDE_LOOPING);
break;
}
break;
case DITHERING:
emit newLog(i18n("PHD2: Dithering started."));
emit newStatus(GUIDE_DITHERING);
break;
}
state = newstate;
}
void PHD2::processPHD2Result(const QJsonObject &jsonObj, const QByteArray &line)
{
PHD2ResultType resultType = takeRequestFromList(jsonObj);
if (resultType == STAR_IMAGE)
qCDebug(KSTARS_EKOS_GUIDE) << "PHD2: received star image response, id" <<
jsonObj["id"].toInt(); // don't spam the log with image data
else
qCDebug(KSTARS_EKOS_GUIDE) << "PHD2: response:" << line;
switch (resultType)
{
case NO_RESULT:
//Ekos didn't ask for this result?
break;
case CAPTURE_SINGLE_FRAME: //capture_single_frame
break;
case CLEAR_CALIBRATION_COMMAND_RECEIVED: //clear_calibration
emit newLog(i18n("PHD2: Calibration is cleared"));
break;
case DITHER_COMMAND_RECEIVED: //dither
handlePHD2AppState(DITHERING);
break;
//find_star
//flip_calibration
//get_algo_param_names
//get_algo_param
case APP_STATE_RECEIVED: //get_app_state
{
QString state = jsonObj["State"].toString();
if (state.isEmpty())
state = jsonObj["result"].toString();
if (state.isEmpty())
qCDebug(KSTARS_EKOS_GUIDE) << "PHD2: received unsupported app state";
else
processPHD2State(state);
}
break;
//get_calibrated
//get_calibration_data
case IS_EQUIPMENT_CONNECTED: //get_connected
{
bool isConnected = jsonObj["result"].toBool();
switch (connection)
{
case CONNECTING:
// We just plugged in server, request equipment connection if needed
if (isConnected)
{
connection = CONNECTED;
setEquipmentConnected();
}
else connectEquipment(true);
break;
case CONNECTED:
// We were waiting for equipment to be connected after plugging in server
if (isConnected)
setEquipmentConnected();
break;
case DISCONNECTING:
// We were waiting for equipment to be disconnected before unplugging from server
if (!isConnected)
{
connection = EQUIPMENT_DISCONNECTED;
Disconnect();
}
else connectEquipment(false);
break;
case EQUIPMENT_CONNECTED:
// Equipment was disconnected from PHD2 side, so notify clients and wait.
if (!isConnected)
{
// TODO: setEquipmentDisconnected()
connection = EQUIPMENT_DISCONNECTED;
emit newStatus(Ekos::GUIDE_DISCONNECTED);
}
break;
case DISCONNECTED:
case EQUIPMENT_DISCONNECTED:
// Equipment was connected from PHD2 side, so notify clients and wait.
if (isConnected)
setEquipmentConnected();
break;
}
}
break;
//get_cooler_status
case GET_CURRENT_EQUIPMENT: //get_current_equipment
{
QJsonObject equipObject = jsonObj["result"].toObject();
currentCamera = equipObject["camera"].toObject()["name"].toString();
currentMount = equipObject["mount"].toObject()["name"].toString();
currentAuxMount = equipObject["aux_mount"].toObject()["name"].toString();
emit guideEquipmentUpdated();
break;
}
case DEC_GUIDE_MODE: //get_dec_guide_mode
{
QString mode = jsonObj["result"].toString();
Ekos::Manager::Instance()->guideModule()->updateDirectionsFromPHD2(mode);
emit newLog(i18n("PHD2: DEC Guide Mode is Set to: %1", mode));
}
break;
case EXPOSURE_TIME: //get_exposure
{
int exposurems = jsonObj["result"].toInt();
double exposureTime = exposurems / 1000.0;
Ekos::Manager::Instance()->guideModule()->setExposure(exposureTime);
emit newLog(i18n("PHD2: Exposure Time set to: ") + QString::number(exposureTime, 'f', 2));
break;
}
case EXPOSURE_DURATIONS: //get_exposure_durations
{
QVariantList exposureListArray = jsonObj["result"].toArray().toVariantList();
logValidExposureTimes = i18n("PHD2: Valid Exposure Times: Auto, ");
QList<double> values;
for(int i = 1; i < exposureListArray.size();
i ++) //For some reason PHD2 has a negative exposure time of 1 at the start of the array?
values << exposureListArray.at(i).toDouble() / 1000.0; //PHD2 reports in ms.
logValidExposureTimes += Ekos::Manager::Instance()->guideModule()->setRecommendedExposureValues(values);
emit newLog(logValidExposureTimes);
break;
}
case LOCK_POSITION: //get_lock_position
{
if(jsonObj["result"].toArray().count() == 2)
{
double x = jsonObj["result"].toArray().at(0).toDouble();
double y = jsonObj["result"].toArray().at(1).toDouble();
QVector3D newStarCenter(x, y, 0);
emit newStarPosition(newStarCenter, true);
//This is needed so that PHD2 sends the new star pixmap when
//remote images are enabled.
emit newStarPixmap(m_GuideFrame->getTrackingBoxPixmap());
}
break;
}
//get_lock_shift_enabled
//get_lock_shift_params
//get_paused
case PIXEL_SCALE: //get_pixel_scale
pixelScale = jsonObj["result"].toDouble();
if (pixelScale == 0)
emit newLog(i18n("PHD2: Please set CCD and telescope parameters in PHD2, Pixel Scale is invalid."));
else
emit newLog(i18n("PHD2: Pixel Scale is %1 arcsec per pixel", QString::number(pixelScale, 'f', 2)));
break;
//get_profile
//get_profiles
//get_search_region
//get_sensor_temperature
case STAR_IMAGE: //get_star_image
{
starImageRequested = false;
QJsonObject jsonResult = jsonObj["result"].toObject();
processStarImage(jsonResult);
break;
}
//get_use_subframes
case GUIDE_COMMAND_RECEIVED: //guide
if (0 != jsonObj["result"].toInt(0))
{
emit newLog("PHD2: Guide command was rejected.");
handlePHD2AppState(STOPPED);
}
break;
//guide_pulse
case LOOP: //loop
handlePHD2AppState(jsonObj["result"].toBool() ? LOOPING : STOPPED);
break;
//save_image
//set_algo_param
case CONNECTION_RESULT: //set_connected
checkIfEquipmentConnected();
break;
case SET_DEC_GUIDE_MODE_COMMAND_RECEIVED: //set_dec_guide_mode
checkDEGuideMode();
break;
case SET_EXPOSURE_COMMAND_RECEIVED: //set_exposure
requestExposureTime(); //This will check what it was set to and print a message as to what it is.
break;
case SET_LOCK_POSITION: //set_lock_position
handlePHD2AppState(SELECTED);
break;
//set_lock_shift_enabled
//set_lock_shift_params
case SET_PAUSED_COMMAND_RECEIVED: //set_paused
handlePHD2AppState(PAUSED);
break;
//set_profile
//shutdown
case STOP_CAPTURE_COMMAND_RECEIVED: //stop_capture
handlePHD2AppState(STOPPED);
//emit newStatus(GUIDE_ABORTED);
break;
}
// send the next pending call
sendNextRpcCall();
}
void PHD2::processPHD2Error(const QJsonObject &jsonError, const QByteArray &line)
{
qCDebug(KSTARS_EKOS_GUIDE) << "PHD2: error:" << line;
QJsonObject jsonErrorObject = jsonError["error"].toObject();
PHD2ResultType resultType = takeRequestFromList(jsonError);
// This means the user mistakenly entered an invalid exposure time.
switch (resultType)
{
case SET_EXPOSURE_COMMAND_RECEIVED:
emit newLog(logValidExposureTimes); //This will let the user know the valid exposure durations
QTimer::singleShot(300, [ = ] {requestExposureTime();}); //This will reset the Exposure time in Ekos to PHD2's current exposure time after a third of a second.
break;
case CONNECTION_RESULT:
connection = EQUIPMENT_DISCONNECTED;
emit newStatus(Ekos::GUIDE_DISCONNECTED);
break;
case DITHER_COMMAND_RECEIVED:
ditherTimer->stop();
isSettling = false;
isDitherActive = false;
emit newStatus(GUIDE_DITHERING_ERROR);
if (Options::ditherFailAbortsAutoGuide())
{
abort();
emit newLog("PHD2: failing after dithering aborts.");
emit newStatus(GUIDE_ABORTED);
}
else
{
// !FIXME-ag why is this trying to resume (un-pause)?
resume();
}
break;
case GUIDE_COMMAND_RECEIVED:
isSettling = false;