Instrument Neutral Distributed Interface INDI 2.2.5
lx200ap_v2.cpp
Go to the documentation of this file.
1/*
2 Astro-Physics INDI driver
3
4 Copyright (C) 2014 Jasem Mutlaq, Mike Fulbright
5 Copyright (C) 2020 indilib.org, by Markus Wildi
6 Copyright (C) 2022 Hy Murveit
7
8 Based on INDI Astrophysics Driver by Markus Wildi
9
10 This library is free software; you can redistribute it and/or
11 modify it under the terms of the GNU Lesser General Public
12 License as published by the Free Software Foundation; either
13 version 2.1 of the License, or (at your option) any later version.
14
15 This library is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 Lesser General Public License for more details.
19
20 You should have received a copy of the GNU Lesser General Public
21 License along with this library; if not, write to the Free Software
22 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23*/
24/*
252020-08-07, ToDo --wildi
26AP commands not yet implemented for revision >= G
27
28Sets the centering rate for the N-S-E-W buttons to xxx Rcxxx#
29Default command for an equatorial fork mount, which eliminates the meridian flip :FM#
30Default command for A German equatorial mount that includes the meridian flip :EM#
31Horizon check during slewing functions :ho# and :hq#
32*/
33
34
35/***********************************************************************
36 * This file was copied an modified from lx200ap.cpp in Jan 2022.
37 *
38 * This is an update of the Wildi and Fulbright A-P drivers.
39 * It is currently being tested.
40 * You should not use this unless part of the test group.
41***********************************************************************/
42
43#include "lx200ap_v2.h"
44
45#include "indicom.h"
46#include "lx200driver.h"
47#include "lx200apdriver.h"
49
50#include <libnova/transform.h>
51
52#include <cmath>
53#include <cstring>
54#include <unistd.h>
55#include <termios.h>
56#include <regex>
57
58// PEC Recording values
64
65// maximum guide pulse request to send to controller
66#define MAX_LX200AP_PULSE_LEN 999u
67
68// The workaround for long pulses doesn't work!
69// #define DONT_SIMULATE_LONG_PULSES true
70// This didn't work. The driver simply doesn't send pulse
71// commands longer than 999ms since CP3 controllers don't support that.
72
84
86{
87 return "AstroPhysics V2";
88}
89
91{
92 Connection::Interface *activeConnection = getActiveConnection();
93 if (!activeConnection->name().compare("CONNECTION_TCP"))
94 {
95 // When using a tcp connection, the GTOCP4 adds trailing LF to response.
96 // this small hack will get rid of them as they are not expected in the driver. and generated
97 // lot of communication errors.
99 }
100
101 // If ApInitialize fails, probably have to turn some buttons red. Verify!
102 return LX200Generic::Connect() && ApInitialize();
103}
104
106{
108
110
111 IUFillNumber(&HourangleCoordsN[0], "HA", "HA H:M:S", "%10.6m", -24., 24., 0., 0.);
112 IUFillNumber(&HourangleCoordsN[1], "DEC", "Dec D:M:S", "%10.6m", -90.0, 90.0, 0., 0.);
113 IUFillNumberVector(&HourangleCoordsNP, HourangleCoordsN, 2, getDeviceName(), "HOURANGLE_COORD", "Hourangle Coords",
115
116 IUFillNumber(&HorizontalCoordsN[0], "AZ", "Az D:M:S", "%10.6m", 0., 360., 0., 0.);
117 IUFillNumber(&HorizontalCoordsN[1], "ALT", "Alt D:M:S", "%10.6m", -90., 90., 0., 0.);
119 "Horizontal Coords", MAIN_CONTROL_TAB, IP_RW, 120, IPS_IDLE);
120
121 // Max rate is 999.99999X for the GTOCP4.
122 // Using :RR998.9999# just to be safe. 15.041067*998.99999 = 15026.02578
123 TrackRateNP[AXIS_RA].setMin(-15026.0258);
124 TrackRateNP[AXIS_RA].setMax(15026.0258);
125 TrackRateNP[AXIS_DE].setMin(-998.9999);
126 TrackRateNP[AXIS_DE].setMax(998.9999);
127
128 // Rates populated in a different routine since they can change after connect:
129 initRateLabels();
130
131 // Home button for clutch aware mounts with encoders.
132 IUFillSwitch(&HomeAndReSyncS[0], "GO", "Home and ReSync", ISS_OFF);
134 "HomeAndReSync", MAIN_CONTROL_TAB, IP_RW, ISR_ATMOST1, 60, IPS_IDLE);
135
136 // Manual-set-mount-to-parked button for recovering from issues.
137 IUFillSwitch(&ManualSetParkedS[0], "MANUAL SET PARKED", "Manual Set Parked", ISS_OFF);
139 "ManualSetParked", MAIN_CONTROL_TAB, IP_RW, ISR_ATMOST1, 60, IPS_IDLE);
140
141 IUFillSwitch(&SwapS[0], "NS", "North/South", ISS_OFF);
142 IUFillSwitch(&SwapS[1], "EW", "East/West", ISS_OFF);
143 IUFillSwitchVector(&SwapSP, SwapS, 2, getDeviceName(), "SWAP", "Swap buttons", MOTION_TAB, IP_RW, ISR_1OFMANY, 0,
144 IPS_IDLE);
145
146 // guide speed
147 IUFillSwitch(&APGuideSpeedS[0], "0.25", "0.25x", ISS_OFF);
148 IUFillSwitch(&APGuideSpeedS[1], "0.5", "0.50x", ISS_OFF);
149 IUFillSwitch(&APGuideSpeedS[2], "1.0", "1.0x", ISS_ON);
151 0, IPS_IDLE);
152
153 // Unpark from?
154 // Order should be the same as the ParkPosition enum.
155 IUFillSwitch(&UnparkFromS[0], "Last", "Last Parked--recommended!", ISS_ON);
156 IUFillSwitch(&UnparkFromS[1], "Park1", "Park1", ISS_OFF);
157 IUFillSwitch(&UnparkFromS[2], "Park2", "Park2", ISS_OFF);
158 IUFillSwitch(&UnparkFromS[3], "Park3", "Park3", ISS_OFF);
159 IUFillSwitch(&UnparkFromS[4], "Park4", "Park4", ISS_OFF);
160 IUFillSwitchVector(&UnparkFromSP, UnparkFromS, 5, getDeviceName(), "UNPARK_FROM", "Unpark From?", MAIN_CONTROL_TAB, IP_RW,
162
163 // park presets
164 // Order should be the same as the ParkPosition enum.
165 IUFillSwitch(&ParkToS[0], "Custom", "Custom--not implemented", ISS_OFF);
166 IUFillSwitch(&ParkToS[1], "Park1", "Park1", ISS_OFF);
167 IUFillSwitch(&ParkToS[2], "Park2", "Park2", ISS_OFF);
168 IUFillSwitch(&ParkToS[3], "Park3", "Park3", ISS_ON);
169 IUFillSwitch(&ParkToS[4], "Park4", "Park4", ISS_OFF);
170 IUFillSwitch(&ParkToS[5], "Current", "Current Position--not implemented", ISS_OFF);
172 IPS_IDLE);
173
174 IUFillText(&VersionT[0], "Version", "Version", "");
175 IUFillTextVector(&VersionTP, VersionT, 1, getDeviceName(), "Firmware", "Firmware", SITE_TAB, IP_RO, 0, IPS_IDLE);
176
177 // UTC offset
178 IUFillNumber(&APUTCOffsetN[0], "APUTC_OFFSET", "AP UTC offset", "%8.5f", 0.0, 24.0, 0.0, 0.);
179 IUFillNumberVector(&APUTCOffsetNP, APUTCOffsetN, 1, getDeviceName(), "APUTC_OFFSET", "AP UTC offset", SITE_TAB,
180 IP_RW, 60, IPS_OK);
181 // sidereal time, ToDO move define where it belongs to
182 IUFillNumber(&APSiderealTimeN[0], "AP_SIDEREAL_TIME", "AP sidereal time", "%10.6m", 0.0, 24.0, 0.0, 0.0);
183 IUFillNumberVector(&APSiderealTimeNP, APSiderealTimeN, 1, getDeviceName(), "AP_SIDEREAL_TIME", "ap sidereal time", SITE_TAB,
184 IP_RO, 60, IPS_OK);
185
186 // Worm position
187 IUFillNumber(&APWormPositionN[0], "APWormPosition", "AP Worm Position", "%3.0f", 0, 1000, 1, 0);
188 IUFillNumberVector(&APWormPositionNP, APWormPositionN, 1, getDeviceName(), "APWormPosition", "AP Worm Position",
190
191 // PEC State
192 IUFillText(&APPECStateT[0], "APPECState", "AP PEC State", "");
193 IUFillTextVector(&APPECStateTP, APPECStateT, 1, getDeviceName(), "APPECState", "AP PEC State",
195
196 IUFillText(&APMountStatusT[0], "APMountStatus", "AP Mount Status", "");
197 IUFillTextVector(&APMountStatusTP, APMountStatusT, 1, getDeviceName(), "APMountStatus", "AP Mount Status",
199
200 // PEC Record button.
201 IUFillSwitch(&APPECRecordS[AP_PEC_RECORD_OFF], "APPECRecordOFF", "Off", ISS_ON);
202 IUFillSwitch(&APPECRecordS[AP_PEC_RECORD_ON], "APPECRecordON", "Record", ISS_OFF);
203 IUFillSwitchVector(&APPECRecordSP, APPECRecordS, 2, getDeviceName(), "APPECRecord", "Record PEC", MOTION_TAB,
205
206 tcpConnection->setConnectionType(Connection::TCP::TYPE_UDP);
207
208 // Without below, it will not write the ParkData.xml file.
209 // However, ParkData.xml is not used.
210 // SetParkDataType(PARK_AZ_ALT);
211
212 return true;
213}
214
215void LX200AstroPhysicsV2::initRateLabels()
216{
217 if (rateTable == AP_RATE_TABLE_DEFAULT) // Legacy, pre P02-01
218 {
219 // Motion speed of axis when pressing NSWE buttons
220 SlewRateSP[0].fill("1", "Guide", ISS_OFF);
221 SlewRateSP[1].fill("12", "12x", ISS_OFF);
222 SlewRateSP[2].fill("64", "64x", ISS_ON);
223 SlewRateSP[3].fill("600", "600x", ISS_OFF);
224 SlewRateSP[4].fill("1200", "1200x", ISS_OFF);
225 SlewRateSP.fill(getDeviceName(), "TELESCOPE_SLEW_RATE", "Slew Rate", MOTION_TAB, IP_RW,
227
228 // Slew speed when performing regular GOTO
229 IUFillSwitch(&APSlewSpeedS[0], "600", "600x", ISS_ON);
230 IUFillSwitch(&APSlewSpeedS[1], "900", "900x", ISS_OFF);
231 IUFillSwitch(&APSlewSpeedS[2], "1200", "1200x", ISS_OFF);
233 0, IPS_IDLE);
234 }
235 else
236 {
237 // This is the rate table straight out of the CPx source. First two numbers
238 // are the highest two center/button rates, and the next three numbers are the
239 // three 'goto' rates. There are 4 sets of rates for 4 different types of mounts.
240 std::string standard_rates[4][5] =
241 {
242 { "600", "1200", "600", "900", "1200" },
243 { "500", "900", "400", "650", "900" },
244 { "400", "600", "300", "450", "600" },
245 { "600", "1200", "600", "1000", "1800" }
246 };
247
248 // The 8 means there are 8 slew/center rates.
251 int i = rateTable;
252 SlewRateSP[0].fill("0.25", "0.25x", ISS_OFF);
253 SlewRateSP[1].fill("0.5", "0.5x", ISS_OFF);
254 SlewRateSP[2].fill("1.0", "1.0x", ISS_OFF);
255 SlewRateSP[3].fill("12", "12x", ISS_OFF);
256 SlewRateSP[4].fill("64", "64x", ISS_ON);
257 SlewRateSP[5].fill("200", "200x", ISS_OFF);
258 SlewRateSP[6].fill(standard_rates[i][0].c_str(), standard_rates[i][0].append("x").c_str(), ISS_OFF);
259 SlewRateSP[7].fill(standard_rates[i][1].c_str(), standard_rates[i][1].append("x").c_str(), ISS_OFF);
260
261 // Slew speed when performing regular GOTO
262 IUFillSwitch(&APSlewSpeedS[0], standard_rates[i][2].c_str(), standard_rates[i][2].append("x").c_str(), ISS_ON);
263 IUFillSwitch(&APSlewSpeedS[1], standard_rates[i][3].c_str(), standard_rates[i][3].append("x").c_str(), ISS_OFF);
264 IUFillSwitch(&APSlewSpeedS[2], standard_rates[i][4].c_str(), standard_rates[i][4].append("x").c_str(), ISS_OFF);
265 }
266}
267
290
333
334bool LX200AstroPhysicsV2::getWormPosition()
335{
336 int position;
337 if (isSimulation())
338 position = 0;
339 else
340 {
341 int res = getAPWormPosition(PortFD, &position);
342 if (res != TTY_OK)
343 {
346 IDSetNumber(&APWormPositionNP, nullptr);
347 return false;
348 }
349 }
350 APWormPositionNP.np[0].value = position;
352 IDSetNumber(&APWormPositionNP, nullptr);
353 return true;
354}
355
356void LX200AstroPhysicsV2::processMountStatus(const char *statusString)
357{
358 const char *mountStatusString = apMountStatus(statusString);
359 IUSaveText(&APMountStatusT[0], mountStatusString);
360 IDSetText(&APMountStatusTP, nullptr);
362}
363
364bool LX200AstroPhysicsV2::getPECState(const char *statusString)
365{
366 int pecState;
367 if (isSimulation())
368 pecState = AP_PEC_OFF;
369 else
370 {
371 if (strlen(statusString) < 10)
372 return false;
373 const char pecChar = statusString[9];
374 switch (pecChar)
375 {
376 case 'O':
377 pecState = AP_PEC_OFF;
378 break;
379 case 'P':
380 pecState = AP_PEC_ON;
381 break;
382 case 'R':
383 pecState = AP_PEC_RECORD;
384 break;
385 case 'E':
386 pecState = AP_PEC_ENCODER;
387 break;
388 default:
389 IUSaveText(&APPECStateT[0], "");
390 IDSetText(&APPECStateTP, nullptr);
392 return false;
393 }
394 }
395 // Set the text status display based on the info from the mount.
396 // Also set the PEC buttons: playback on/off & recording on/off.
397 switch (pecState)
398 {
399 case AP_PEC_OFF:
400 IUSaveText(&APPECStateT[0], "Off");
401
405 IDSetSwitch(&APPECRecordSP, nullptr);
406
408
409 break;
410 case AP_PEC_ON:
411 IUSaveText(&APPECStateT[0], "On");
412
416 IDSetSwitch(&APPECRecordSP, nullptr);
417
419
420 break;
421 case AP_PEC_RECORD:
422 IUSaveText(&APPECStateT[0], "Recording");
423
427 IDSetSwitch(&APPECRecordSP, nullptr);
428
430
431 break;
432 case AP_PEC_ENCODER:
433 IUSaveText(&APPECStateT[0], "Encoder");
434
438 IDSetSwitch(&APPECRecordSP, nullptr);
439
441
442 break;
443 }
444 IDSetText(&APPECStateTP, nullptr);
446
447 return true;
448}
449
450// The version string should be formatted as VCP4-$MAJOR-$MINOR.
451// Could be VCP5 or VCP6 as well. For instance: VCP4-P02-12
452void LX200AstroPhysicsV2::setMajorMinorVersions(char *version)
453{
454 majorVersion = 0;
455 minorVersion = 0;
456
457 const std::string v = version;
458 std::regex rgx(".*-(\\w+)-(\\w+)");
459 std::smatch match;
460
461 if (std::regex_search(v.begin(), v.end(), match, rgx))
462 {
463 std::string major = match.str(1);
464 std::string minor = match.str(2);
465
466 std::string majorStripped = std::regex_replace(major, std::regex(R"([\D])"), "");
467 std::string minorStripped = std::regex_replace(minor, std::regex(R"([\D])"), "");
468
469 if (majorStripped.size() > 0)
470 majorVersion = stoi(majorStripped);
471 if (minorStripped.size() > 0)
472 minorVersion = stoi(minorStripped);
473 }
474}
475
476bool LX200AstroPhysicsV2::getFirmwareVersion()
477{
478 bool success;
479 char versionString[128];
480 majorVersion = 0;
481 minorVersion = 0;
482
483 success = false;
484
485 if (isSimulation())
486 strncpy(versionString, "VCP4-P01-01", 128);
487 else
488 getAPVersionNumber(PortFD, versionString);
489
490 VersionTP.s = IPS_OK;
491 IUSaveText(&VersionT[0], versionString);
492 IDSetText(&VersionTP, nullptr);
493
494 if (strstr(versionString, "VCP4"))
495 {
496 firmwareVersion = MCV_V;
497 servoType = GTOCP4;
498 success = true;
499 setMajorMinorVersions(versionString);
500 }
501 else if (strstr(versionString, "VCP5"))
502 {
503 firmwareVersion = MCV_V;
504 servoType = GTOCP5;
505 setMajorMinorVersions(versionString);
506 success = true;
507 }
508 else if (strstr(versionString, "VCP6"))
509 {
510 // GTOCP6 uses the same command set as the GTOCP5.
511 firmwareVersion = MCV_V;
512 servoType = GTOCP6;
513 setMajorMinorVersions(versionString);
514 success = true;
515 }
516 else if (strlen(versionString) == 1 || strlen(versionString) == 2)
517 {
518 // Check earlier versions
519 // FIXME could probably use better range checking in case we get a letter like 'Z' that doesn't map to anything!
520 int typeIndex = VersionT[0].text[0] - 'D';
521 if (typeIndex >= 0)
522 {
523 firmwareVersion = static_cast<ControllerVersion>(typeIndex);
524 LOGF_DEBUG("Firmware version index: %d", typeIndex);
525 if (firmwareVersion < MCV_G)
526 servoType = GTOCP2;
527 else
528 servoType = GTOCP3;
529
530 success = true;
531 }
532 else
533 {
534 LOGF_WARN("unknown AP controller version %s", VersionT[0].text);
535 }
536 }
537
538 if (success)
539 {
540 LOGF_INFO("Servo Box Controller: GTOCP%d.", servoType);
541 LOGF_INFO("Firmware Version: '%s'", versionString);
542 if (majorVersion && minorVersion)
543 LOGF_INFO("Firmware Major Version: %d Minor Version %d", majorVersion, minorVersion);
544 }
545
546 return success;
547}
548
549/**************************************************************************************
550**
551***************************************************************************************/
552bool LX200AstroPhysicsV2::ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n)
553{
554 if (strcmp(getDeviceName(), dev))
555 return false;
556
557 if (!strcmp(name, APUTCOffsetNP.name))
558 {
559 if (IUUpdateNumber(&APUTCOffsetNP, values, names, n) < 0)
560 return false;
561
562 float mdelay;
563 int err;
564
565 mdelay = APUTCOffsetN[0].value;
566
567 if (!isSimulation() && (err = setAPUTCOffset(PortFD, mdelay) < 0))
568 {
569 LOGF_ERROR("Error setting UTC offset (%d).", err);
570 return false;
571 }
572
574 IDSetNumber(&APUTCOffsetNP, nullptr);
575
576 return true;
577 }
578 if (!strcmp(name, HourangleCoordsNP.name))
579 {
580
581 if (IUUpdateNumber(&HourangleCoordsNP, values, names, n) < 0)
582 return false;
583
584 double lng = LocationNP[LOCATION_LONGITUDE].getValue();
585 double lst = get_local_sidereal_time(lng);
586 double ra = lst - HourangleCoordsN[0].value;
587 double dec = HourangleCoordsN[1].value;
588 bool success = false;
589 if (CoordSP.isSwitchOn("TRACK") || CoordSP.isSwitchOn("SLEW"))
590 {
591 success = Goto(ra, dec);
592 }
593 else
594 {
595 success = APSync(ra, dec, true);
596 }
597 if (success)
598 {
600 }
601 else
602 {
604 }
606 return true;
607 }
608
609 return LX200Generic::ISNewNumber(dev, name, values, names, n);
610}
611
612bool LX200AstroPhysicsV2::ApInitialize()
613{
614 if ((firmwareVersion == MCV_UNKNOWN) || (firmwareVersion < MCV_T))
615 {
616 // Can't use this driver
617 LOG_ERROR("This driver requires at least version T firmware");
618 return false;
619 }
620
622 char status_string[256];
623 if (getApStatusString(PortFD, status_string) == TTY_OK)
624 {
625 rateTable = apRateTable(status_string);
626 if ((rateTable >= 0) && (rateTable <= 3))
627 LOGF_INFO("Using Rate Table: %d", rateTable);
628 else
630 }
631 initRateLabels();
632
634
635 // Set location up every time we connect.
636 double longitude = -1000, latitude = -1000;
637 // Get value from config file if it exists.
638 IUGetConfigNumber(getDeviceName(), "GEOGRAPHIC_COORD", "LONG", &longitude);
639 IUGetConfigNumber(getDeviceName(), "GEOGRAPHIC_COORD", "LAT", &latitude);
640 if (longitude != -1000 && latitude != -1000)
641 updateAPLocation(latitude, longitude, 0);
642
643 bool isAPParked = false;
644 if (!IsMountParked(&isAPParked))
645 return false;
646 if (isAPParked)
647 {
648 if (!loadConfig(true, UnparkFromSP.name))
649 LOG_DEBUG("could not load config data for UnparkFromSP.name");
650 if (!loadConfig(true, ParkToSP.name))
651 LOG_DEBUG("could not load config data for ParkTo.name");
653 LOG_INFO("Driver's config 'Unpark From ?' is set to Last Parked");
654 // forcing mount being parked from INDI's perspective
655 LOG_INFO("ApInitialize, parked.");
656 SetParked(true);
657 }
658 else
659 {
660 LOG_INFO("ApInitialize, not parked.");
661 SetParked(false);
662 }
663
664 if (isSimulation())
665 {
666 SlewRateSP.setState(IPS_OK);
667 SlewRateSP.apply();
668
670 IDSetSwitch(&APSlewSpeedSP, nullptr);
671
672 IUSaveText(&VersionT[0], "1.0");
673 VersionTP.s = IPS_OK;
674 IDSetText(&VersionTP, nullptr);
675
676 return true;
677
678 }
679 // Make sure that the mount is setup according to the properties
680 int switch_nr = TrackModeSP.findOnSwitchIndex();
681
682 int err = 0;
683 if ( (err = selectAPTrackingMode(PortFD, switch_nr)) < 0)
684 {
685 LOGF_ERROR("ApInitialize: Error setting tracking mode (%d).", err);
686 return false;
687 }
688
689 // On most mounts SlewRateS defines the MoveTo AND Slew (GOTO) speeds
690 // lx200ap is different - some of the MoveTo speeds are not VALID
691 // Slew speeds so we have to keep two lists.
692 //
693 // SlewRateS is used as the MoveTo speed
694 switch_nr = SlewRateSP.findOnSwitchIndex();
695 if ((err = selectAPV2CenterRate(PortFD, switch_nr, rateTable)) < 0)
696 {
697 LOGF_ERROR("ApInitialize: Error setting move rate (%d).", err);
698 return false;
699 }
700
701 SlewRateSP.setState(IPS_OK);
702 SlewRateSP.apply();
703
704 // APSlewSpeedsS defines the Slew (GOTO) speeds valid on the AP mounts
706 if ( (err = selectAPSlewRate(PortFD, switch_nr)) < 0)
707 {
708 LOGF_ERROR("ApInitialize: Error setting slew to rate (%d).", err);
709 return false;
710 }
712 IDSetSwitch(&APSlewSpeedSP, nullptr);
713
716
717 // make a IDSet in order the dome controller is aware of the initial values
720
722
723 char versionString[64];
724 getAPVersionNumber(PortFD, versionString);
725 VersionTP.s = IPS_OK;
726 IUSaveText(&VersionT[0], versionString);
727 IDSetText(&VersionTP, nullptr);
728
729 return true;
730}
731
732bool LX200AstroPhysicsV2::ISNewSwitch(const char *dev, const char *name, ISState * states, char *names[], int n)
733{
734 int err = 0;
735 if (strcmp(getDeviceName(), dev))
736 return false;
737
738 // =======================================
739 // Swap Buttons
740 // =======================================
741 if (!strcmp(name, SwapSP.name))
742 {
743 int currentSwap;
744
746 IUUpdateSwitch(&SwapSP, states, names, n);
747 currentSwap = IUFindOnSwitchIndex(&SwapSP);
748
749 if ((!isSimulation() && (err = swapAPButtons(PortFD, currentSwap)) < 0))
750 {
751 LOGF_ERROR("Error swapping buttons (%d).", err);
752 return false;
753 }
754
755 SwapS[0].s = ISS_OFF;
756 SwapS[1].s = ISS_OFF;
757 SwapSP.s = IPS_OK;
758 IDSetSwitch(&SwapSP, nullptr);
759 return true;
760 }
761
762 // ===========================================================
763 // GOTO ("slew") Speed.
764 // ===========================================================
765 if (!strcmp(name, APSlewSpeedSP.name))
766 {
767 IUUpdateSwitch(&APSlewSpeedSP, states, names, n);
768 int slewRate = IUFindOnSwitchIndex(&APSlewSpeedSP);
769
770 if (!isSimulation() && (err = selectAPSlewRate(PortFD, slewRate) < 0))
771 {
772 LOGF_ERROR("Error setting move to rate (%d).", err);
773 return false;
774 }
775
777 IDSetSwitch(&APSlewSpeedSP, nullptr);
778 return true;
779 }
780
781 // ===========================================================
782 // Guide Speed.
783 // ===========================================================
784 if (!strcmp(name, APGuideSpeedSP.name))
785 {
786 IUUpdateSwitch(&APGuideSpeedSP, states, names, n);
787 int guideRate = IUFindOnSwitchIndex(&APGuideSpeedSP);
788
789 if (!isSimulation() && (err = selectAPGuideRate(PortFD, guideRate) < 0))
790 {
791 LOGF_ERROR("Error setting guiding to rate (%d).", err);
792 return false;
793 }
794
796 IDSetSwitch(&APGuideSpeedSP, nullptr);
797 return true;
798 }
799
800 // =======================================
801 // Choose the PEC playback mode
802 // =======================================
803 if (PECStateSP.isNameMatch(name))
804 {
805 PECStateSP.reset();
806 PECStateSP.update(states, names, n);
807 PECStateSP.findOnSwitchIndex();
808
809 int pecstate = PECStateSP.findOnSwitchIndex();
810
811 if (!isSimulation() && (err = selectAPPECState(PortFD, pecstate) < 0))
812 {
813 LOGF_ERROR("Error setting PEC state (%d).", err);
814 return false;
815 }
816
817 PECStateSP.setState(IPS_OK);
818 PECStateSP.apply();
819
820 return true;
821 }
822
823 if (strcmp(name, APPECRecordSP.name) == 0)
824 {
826 IUUpdateSwitch(&APPECRecordSP, states, names, n);
828
829 int recordState = IUFindOnSwitchIndex(&APPECRecordSP);
830
831 // Can't turn recording off.
832 if (recordState == AP_PEC_RECORD_ON)
833 {
835 if (!isSimulation() && (err != 0))
836 {
837 LOGF_ERROR("Error setting PEC state RECORD (%d).", err);
838 return false;
839 }
840 LOG_INFO("Recording PEC");
842 PECStateSP.apply();
843 }
844 return true;
845 }
846
847 // ===========================================================
848 // Unpark from positions
849 // ===========================================================
850 if (!strcmp(name, UnparkFromSP.name))
851 {
852 IUUpdateSwitch(&UnparkFromSP, states, names, n);
853 ParkPosition unparkPos = static_cast<ParkPosition>(IUFindOnSwitchIndex(&UnparkFromSP));
854
856 if( unparkPos != PARK_LAST)
857 {
858 double unparkAlt, unparkAz;
859 if (!calcParkPosition(unparkPos, &unparkAlt, &unparkAz))
860 {
861 LOG_WARN("Error calculating unpark position!");
863 }
864 else
865 {
866 // 2020-06-01, wildi, UnPark() relies on it
867 saveConfig(true);
868 }
869 }
870 IDSetSwitch(&UnparkFromSP, nullptr);
871 return true;
872 }
873
874 // ===========================================================
875 // Switch Park(ed), Unpark(ed)
876 // ===========================================================
877
878 if (ParkSP.isNameMatch(name))
879 {
880 }
881
882 // ===========================================================
883 // Park To positions
884 // ===========================================================
885 if (!strcmp(name, ParkToSP.name))
886 {
887 IUUpdateSwitch(&ParkToSP, states, names, n);
888 ParkPosition parkPos = static_cast<ParkPosition>(IUFindOnSwitchIndex(&ParkToSP));
889 if (parkPos != PARK_CUSTOM && parkPos != PARK_CURRENT)
890 {
891 double parkAz, parkAlt;
892 if (calcParkPosition(parkPos, &parkAlt, &parkAz))
893 {
894 LOGF_INFO("Set predefined park position %d to az=%f alt=%f", parkPos, parkAz, parkAlt);
895 }
896 else
897 {
898 LOGF_ERROR("Unable to set predefined park position %d!!", parkPos);
899 }
900 }
901 else
902 {
903 LOG_WARN("ISNewSwitch: park custom/current not supported");
906 IDSetSwitch(&ParkToSP, nullptr);
907 return false;
908 }
910 ParkToS[(int)parkPos].s = ISS_ON;
911 ParkToSP.s = IPS_OK;
912 IDSetSwitch(&ParkToSP, nullptr);
913 return true;
914 }
915
916 if (strcmp(name, ManualSetParkedSP.name) == 0)
917 {
918 // Force the mount to be parked where it is and disconnect.
920 bool alreadyConnected = isConnected();
921 if (!alreadyConnected)
922 {
924 Connection::Interface *activeConnection = getActiveConnection();
925 if (!activeConnection->name().compare("CONNECTION_TCP"))
926 {
927 // When using a tcp connection, the GTOCP4 adds trailing LF to response.
928 // this small hack will get rid of them as they are not expected in the driver. and generated
929 // lot of communication errors.
931 }
933 {
934 LOG_ERROR("Connect failed for Manual Park");
935 return true;
936 }
937 }
938
939 if (parkInternal())
940 saveConfig(true);
941 else
942 LOG_ERROR("ParkInternal failed for Manual Park");
943
944 if (!alreadyConnected)
945 {
946 if (!Disconnect())
947 LOG_ERROR("Disconnect failed for Manual Park");
948 }
950 return true;
951 }
952
953 // ===========================================================
954 // Home and ReSync mount
955 // ===========================================================
956 if (strcmp(name, HomeAndReSyncSP.name) == 0)
957 {
960 IDSetSwitch(&HomeAndReSyncSP, nullptr);
961 return true;
962 }
963
964 return LX200Generic::ISNewSwitch(dev, name, states, names, n);
965}
966
968{
969 switch(state)
970 {
972 static char idleStr[] = "Idle";
973 return idleStr;
975 static char slewStr[] = "Slewing";
976 return slewStr;
978 static char trackStr[] = "Tracking";
979 return trackStr;
981 static char parkingStr[] = "Parking";
982 return parkingStr;
984 static char parkStr[] = "Parked";
985 return parkStr;
986 }
987 static char emptyStr[] = "???";
988 return emptyStr;
989}
990
992{
993 if (!isAPReady())
994 {
995 LOGF_DEBUG("APStatus: Not ready--Checked %s Initialized %s Time updated %s Location Updated %s",
996 apInitializationChecked ? "Y" : "N", apIsInitialized ? "Y" : "N",
997 apTimeInitialized ? "Y" : "N", apLocationInitialized ? "Y" : "N");
998
999 // hope this return doesn't delay the time & location. If it does return true?
1000 return false;
1001 }
1002 double lng = LocationNP[LOCATION_LONGITUDE].getValue();
1003 double lst = get_local_sidereal_time(lng);
1004 double val = lst;
1005 if ((!isSimulation()) && (getSDTime(PortFD, &val) < 0))
1006 {
1007 LOG_ERROR("Reading sidereal time failed");
1008 return false;
1009 }
1010 std::string sTimeStr;
1011 if (val >= 0 && val <= 24.0)
1012 sTimeStr = std::to_string(val);
1013 else
1014 {
1015 val = 0;
1016 sTimeStr = "????";
1017 }
1018
1019 APSiderealTimeNP.np[0].value = lst;
1021 IDSetNumber(&APSiderealTimeNP, nullptr);
1022
1023 if (isSimulation())
1024 {
1025 mountSim();
1026 return true;
1027 }
1029 {
1030 EqNP.setState(IPS_ALERT);
1031 LOG_ERROR("Error reading RA/DEC.");
1032 EqNP.apply();
1033 return false;
1034 }
1035
1036 char apStatusString[256];
1037 if (getApStatusString(PortFD, apStatusString) != TTY_OK)
1038 {
1039 LOG_ERROR("Reading AP status failed");
1040 return false;
1041 }
1042
1043 getWormPosition();
1044 getPECState(apStatusString);
1045 processMountStatus(apStatusString);
1046
1047 const bool apParked = apStatusParked(apStatusString);
1048 if (!apParked)
1049 {
1050 double ha = get_local_hour_angle(lst, currentRA);
1051
1052 // No need to spam log until we have some actual changes.
1053 if (std::fabs(HourangleCoordsN[0].value - ha) > 0.00001 ||
1054 std::fabs(HourangleCoordsN[1].value - currentDEC) > 0.00001)
1055 {
1056 // in case of simulation, the coordinates are set on parking
1057 HourangleCoordsN[0].value = ha;
1058 HourangleCoordsN[1].value = currentDEC;
1060 IDSetNumber(&HourangleCoordsNP, nullptr );
1061 }
1062 }
1063 LOGF_DEBUG("APStatus: %s %s stime: %s RA/DEC: %.3f %.3f",
1064 trackStateString(TrackState), apParked ? "Parked" : "Unparked", sTimeStr.c_str(), currentRA, currentDEC);
1065
1067 {
1068 const double dx = fabs(lastRA - currentRA);
1069 const double dy = fabs(lastDE - currentDEC);
1070
1071 LOGF_DEBUG("Slewing... currentRA: %.3f dx: %g currentDE: %.3f dy: %g", currentRA, dx, currentDEC, dy);
1072
1073 // Note, RA won't hit 0 if it's not tracking, because the RA changes when still.
1074 // Dec might, though.
1075 // 0 might work now that I "fixed" slewing...perhaps not when tracking is off.
1076 if (dx < 1e-3 && dy < 1e-3)
1077 {
1079 LOG_INFO("Slew is complete. Tracking...");
1080 }
1081
1082 // Keep try of last values to determine if the mount settled.
1083 lastRA = currentRA;
1084 lastDE = currentDEC;
1085 }
1086 else if (TrackState == SCOPE_PARKING)
1087 {
1088 bool slewcomplete = false;
1089 double PARKTHRES = 0.1; // max difference from parked position to consider mount PARKED
1090
1091 if (!apStatusSlewing(apStatusString))
1092 slewcomplete = true;
1093
1094 // old way
1095 if (getLX200Az(PortFD, &currentAz) < 0 || getLX200Alt(PortFD, &currentAlt) < 0)
1096 {
1097 EqNP.setState(IPS_ALERT);
1098 LOG_ERROR("Error reading Az/Alt.");
1099 EqNP.apply();
1100 return false;
1101 }
1102
1103 const double dx = fabs(lastAZ - currentAz);
1104 const double dy = fabs(lastAL - currentAlt);
1105 LOGF_DEBUG("Parking... currentAz: %g dx: %g currentAlt: %g dy: %g", currentAz, dx, currentAlt, dy);
1106
1107 // if for some reason we check slew status BEFORE park motion starts make sure we dont consider park
1108 // action complete too early by checking how far from park position we are!
1109
1110 if (slewcomplete && (dx > PARKTHRES || dy > PARKTHRES))
1111 {
1112 LOG_WARN("Parking... slew status indicates mount stopped by dx/dy too far from mount - continuing!");
1113 slewcomplete = false;
1114 }
1115
1116 // Not sure why it hedged previously. Require slewcomplete for now. Verify!
1117 // if (slewcomplete || (dx <= PARKTHRES && dy <= PARKTHRES))
1118 if (slewcomplete)
1119 {
1120 LOG_DEBUG("Parking slew is complete. Asking astrophysics mount to park...");
1121 if (!parkInternal())
1122 {
1123 return false;
1124 }
1125 saveConfig(true);
1126 }
1127
1128 lastAZ = currentAz;
1129 lastAL = currentAlt;
1130 }
1131
1133
1134 syncSideOfPier();
1135
1136 return true;
1137}
1138
1139bool LX200AstroPhysicsV2::parkInternal()
1140{
1141 if (APParkMount(PortFD) < 0)
1142 {
1143 LOG_ERROR("Parking Failed.");
1144 return false;
1145 }
1146
1147 SetTrackEnabled(false);
1148 SetParked(true);
1149 return true;
1150}
1151
1152bool LX200AstroPhysicsV2::IsMountParked(bool * isAPParked)
1153{
1154 if (isSimulation())
1155 {
1156 // 2030-05-30, if Unparked is selected, this condition is not met
1157 *isAPParked = (ParkSP[PARK].getState() == ISS_ON);
1158 return true;
1159 }
1160
1161 char parkStatus;
1162 char slewStatus;
1163 if (check_lx200ap_status(PortFD, &parkStatus, &slewStatus) == 0)
1164 {
1165 LOGF_DEBUG("parkStatus: %c", parkStatus);
1166
1167 *isAPParked = (parkStatus == 'P');
1168 return true;
1169 }
1170 return false;
1171}
1172
1173bool LX200AstroPhysicsV2::Goto(double r, double d)
1174{
1175 if (!isAPReady())
1176 return false;
1177
1178 const struct timespec timeout = {0, 100000000L};
1179
1180 targetRA = r;
1181 targetDEC = d;
1182
1183 char RAStr[64], DecStr[64];
1184 fs_sexa(RAStr, targetRA, 2, 3600);
1185 fs_sexa(DecStr, targetDEC, 2, 3600);
1186
1187 // If moving, let's stop it first.
1188 if (EqNP.getState() == IPS_BUSY)
1189 {
1190 if (!isSimulation() && abortSlew(PortFD) < 0)
1191 {
1192 AbortSP.setState(IPS_ALERT);
1193 LOG_ERROR("Abort slew failed.");
1194 AbortSP.apply();
1195 return false;
1196 }
1197
1198 AbortSP.setState(IPS_OK);
1199 EqNP.setState(IPS_IDLE);
1200 LOG_ERROR("Slew aborted.");
1201 AbortSP.apply();
1202 EqNP.apply();
1203
1204 if (MovementNSSP.getState() == IPS_BUSY || MovementWESP.getState() == IPS_BUSY)
1205 {
1206 MovementNSSP.setState(IPS_IDLE);
1207 MovementWESP.setState(IPS_IDLE);
1208 EqNP.setState(IPS_IDLE);
1209 MovementNSSP.reset();
1210 MovementWESP.reset();
1211 MovementNSSP.apply();
1212 MovementWESP.apply();
1213 }
1214
1215 // sleep for 100 mseconds
1216 nanosleep(&timeout, nullptr);
1217 }
1218
1219 if (!isSimulation())
1220 {
1222 {
1223 EqNP.setState(IPS_ALERT);
1224 LOG_ERROR("Error setting RA/DEC.");
1225 EqNP.apply();
1226 return false;
1227 }
1228
1229 int err = 0;
1230
1231 /* Slew reads the '0', that is not the end of the slew */
1232 if ((err = Slew(PortFD)))
1233 {
1234 EqNP.setState(IPS_ALERT);
1235 LOGF_ERROR("Error Slewing to JNow RA %s - DEC %s\n", RAStr, DecStr);
1236 EqNP.apply();
1237 slewError(err);
1238 return false;
1239 }
1240 lastRA = targetRA;
1241 lastDE = targetDEC;
1242 }
1243
1245 //EqNP.s = IPS_BUSY;
1246
1247 LOGF_INFO("Slewing to RA: %s - DEC: %s", RAStr, DecStr);
1248 return true;
1249}
1250
1251// AP mounts handle guide commands differently enough from the "generic" LX200 we need to override some
1252// functions related to the GuiderInterface
1253
1255{
1256 if (!isAPReady())
1257 return IPS_ALERT;
1258
1259 // If we're using pulse command, then MovementXXX should NOT be active at all.
1260 if (usePulseCommand && (MovementNSSP.getState() == IPS_BUSY || MovementWESP.getState() == IPS_BUSY))
1261 {
1262 LOG_ERROR("Cannot pulse guide while manually in motion. Stop first.");
1263 return IPS_ALERT;
1264 }
1265
1266 if (GuideNSTID)
1267 {
1269 GuideNSTID = 0;
1270 }
1271
1272 ms = std::clamp(ms, 1u, MAX_LX200AP_PULSE_LEN);
1273
1274 if (usePulseCommand)
1275 {
1277 GuideNSTID = IEAddTimer(static_cast<int>(ms), pulseGuideTimeoutHelperNS, this);
1278 }
1279
1280 return IPS_BUSY;
1281}
1282
1284{
1285 if (!isAPReady())
1286 return IPS_ALERT;
1287
1288 // If we're using pulse command, then MovementXXX should NOT be active at all.
1289 if (usePulseCommand && (MovementNSSP.getState() == IPS_BUSY || MovementWESP.getState() == IPS_BUSY))
1290 {
1291 LOG_ERROR("Cannot pulse guide while manually in motion. Stop first.");
1292 return IPS_ALERT;
1293 }
1294
1295 if (GuideNSTID)
1296 {
1298 GuideNSTID = 0;
1299 }
1300
1301 // Clamp to within 1 to 9999
1302 ms = std::clamp(ms, 1u, MAX_LX200AP_PULSE_LEN);
1303
1304 if (usePulseCommand)
1305 {
1307 GuideNSTID = IEAddTimer(static_cast<int>(ms), pulseGuideTimeoutHelperNS, this);
1308 }
1309
1310 return IPS_BUSY;
1311}
1312
1314{
1315 if (!isAPReady())
1316 return IPS_ALERT;
1317
1318 // If we're using pulse command, then MovementXXX should NOT be active at all.
1319 if (usePulseCommand && (MovementNSSP.getState() == IPS_BUSY || MovementWESP.getState() == IPS_BUSY))
1320 {
1321 LOG_ERROR("Cannot pulse guide while manually in motion. Stop first.");
1322 return IPS_ALERT;
1323 }
1324
1325 if (GuideWETID)
1326 {
1328 GuideWETID = 0;
1329 }
1330
1331 // Clamp to within 1 to 9999
1332 ms = std::clamp(ms, 1u, MAX_LX200AP_PULSE_LEN);
1333
1334 if (usePulseCommand)
1335 {
1337 GuideWETID = IEAddTimer(static_cast<int>(ms), pulseGuideTimeoutHelperWE, this);
1338 }
1339
1340 return IPS_BUSY;
1341}
1342
1344{
1345 if (!isAPReady())
1346 return IPS_ALERT;
1347
1348 // If we're using pulse command, then MovementXXX should NOT be active at all.
1349 if (usePulseCommand && (MovementNSSP.getState() == IPS_BUSY || MovementWESP.getState() == IPS_BUSY))
1350 {
1351 LOG_ERROR("Cannot pulse guide while manually in motion. Stop first.");
1352 return IPS_ALERT;
1353 }
1354
1355 if (GuideWETID)
1356 {
1358 GuideWETID = 0;
1359 }
1360
1361 // Clamp to within 1 to 9999
1362 ms = std::clamp(ms, 1u, MAX_LX200AP_PULSE_LEN);
1363
1364 if (usePulseCommand)
1365 {
1367 GuideWETID = IEAddTimer(static_cast<int>(ms), pulseGuideTimeoutHelperWE, this);
1368 }
1369
1370 return IPS_BUSY;
1371}
1372
1377
1382
1387
1392
1394{
1395 LOGF_DEBUG("AstroPhysicsGuideTimeoutWE() pulse guide simul = %d", simul);
1396
1397 if (simul == true)
1398 {
1399 ISState states[] = { ISS_OFF, ISS_OFF };
1400 const char *names[] = { MovementWESP[DIRECTION_WEST].getName(), MovementWESP[DIRECTION_EAST].getName()};
1401 ISNewSwitch(MovementWESP.getDeviceName(), MovementWESP.getName(), states, const_cast<char **>(names), 2);
1402 }
1403
1404 GuideWENP[DIRECTION_WEST].setValue(0);
1405 GuideWENP[DIRECTION_EAST].setValue(0);
1406 GuideWENP.setState(IPS_IDLE);
1407 GuideWETID = 0;
1408 GuideWENP.apply();
1409}
1410
1412{
1413 LOGF_DEBUG("AstroPhysicsGuideTimeoutNS() pulse guide simul = %d", simul);
1414
1415 if (simul == true)
1416 {
1417 ISState states[] = { ISS_OFF, ISS_OFF };
1418 const char *names[] = { MovementNSSP[DIRECTION_NORTH].getName(), MovementNSSP[DIRECTION_SOUTH].getName()};
1419 ISNewSwitch(MovementNSSP.getDeviceName(), MovementNSSP.getName(), states, const_cast<char **>(names), 2);
1420 }
1421
1422 GuideNSNP[0].setValue(0);
1423 GuideNSNP[1].setValue(0);
1424 GuideNSNP.setState(IPS_IDLE);
1425 GuideNSTID = 0;
1426 GuideNSNP.apply();
1427}
1428
1429int LX200AstroPhysicsV2::SendPulseCmd(int8_t direction, uint32_t duration_msec)
1430{
1431 return APSendPulseCmd(PortFD, direction, duration_msec);
1432}
1433
1435{
1436 if (isSimulation())
1437 {
1438 LOG_INFO("Simulated Astrophysics is online. Retrieving basic data...");
1439 getFirmwareVersion();
1440 return true;
1441 }
1442
1443 int err = 0;
1444
1445 if ((err = setAPClearBuffer(PortFD)) < 0)
1446 {
1447 LOGF_ERROR("Error clearing the buffer (%d): %s", err, strerror(err));
1448 return false;
1449 }
1450 if (!getActiveConnection()->name().compare("CONNECTION_TCP"))
1451 {
1452 LOG_INFO("Setting generic udp format (1)");
1454 }
1455 if (setAPBackLashCompensation(PortFD, 0, 0, 0) < 0)
1456 {
1457 // It seems we need to send it twice before it works!
1458 if ((err = setAPBackLashCompensation(PortFD, 0, 0, 0)) < 0)
1459 {
1460 LOGF_ERROR("Error setting backlash compensation (%d): %s.", err, strerror(err));
1461 }
1462 }
1463
1464 // get firmware version
1465 bool rc = false;
1466
1467 rc = getFirmwareVersion();
1468
1469 if (!rc || (firmwareVersion == MCV_UNKNOWN) || (firmwareVersion < MCV_T))
1470 {
1471 // Can't use this driver at < version T. No way to test.
1472 LOG_ERROR("Firmware detection failed or is unknown. This driver requires at least version T firmware");
1473 return false;
1474 }
1475
1476 // Do not track until mount is umparked
1478 {
1479 LOGF_ERROR("Handshake: Error setting tracking mode to zero (%d).", err);
1480 return false;
1481 }
1482 else
1483 {
1484 LOG_INFO("Stopped tracking");
1485 }
1486
1487 // Check to see if the mount is initialized during handshake.
1488 // If it isn't, we'll later need to set things up, and make sure
1489 // that location and time were sent to it.
1490 apIsInitialized = false;
1491 apInitializationChecked = false;
1492 apLocationInitialized = false;
1493 apTimeInitialized = false;
1494
1495 // Let it fail twice before failing
1496 if ((isAPInitialized(PortFD, &apIsInitialized) != TTY_OK) ||
1497 (isAPInitialized(PortFD, &apIsInitialized) != TTY_OK))
1498 {
1499 return false;
1500 }
1501 apInitializationChecked = true;
1502
1503 // Detect and set format. It should be LONG.
1504 return (checkLX200EquatorialFormat(PortFD) == 0);
1505}
1506
1507bool LX200AstroPhysicsV2::isAPReady()
1508{
1509 if (!apInitializationChecked)
1510 return false;
1511
1512 // AP has passed the initialization check.
1513 if (apIsInitialized)
1514 return true;
1515
1516 // Below is implementing the LastParked Scheme.
1517 // I don't require that PARK_LAST is the unparkFrom scheme.
1518 // If the mount is uninitialized, then trust the mount's PARK_LAST data.
1519 if (apLocationInitialized && apTimeInitialized)
1520 {
1521 bool commWorked = true;
1522 char statusString[256];
1523 if (getApStatusString(PortFD, statusString) != TTY_OK)
1524 {
1525 // Try again
1526 commWorked = getApStatusString(PortFD, statusString) == TTY_OK;
1527 }
1528 if (commWorked)
1529 {
1530 bool isAPParked = apStatusParked(statusString);
1531
1532 // A-P came up uninitialized, but we can now fix.
1533 if (APUnParkMount(PortFD) != TTY_OK)
1534 // Try again if we had a comm failure.
1535 commWorked = APUnParkMount(PortFD) == TTY_OK;
1536
1537 if (commWorked)
1538 {
1539 // The mount should now be "calibrated" and have a correct RA/DEC,
1540 // based on its LastParked position.
1541 bool mountOk = false;
1542 if (isAPInitialized(PortFD, &mountOk) != TTY_OK)
1543 {
1544 // try one more time
1545 commWorked = isAPInitialized(PortFD, &mountOk) == TTY_OK;
1546 }
1547 if (commWorked && mountOk)
1548 {
1549 apIsInitialized = true;
1550
1551 // Put it back into the state we found it.
1552 if (isAPParked)
1553 parkInternal();
1554 else
1555 SetParked(false);
1556 return true;
1557 }
1558 }
1559 }
1560 // If we arrive here, we tried but were unable to initialized the mount.
1561 // If unparkFrom is set to one of the park positions, and we're parked,
1562 // then don't fail, as we will recover on the unpark.
1563 ISState lastParkState;
1564 IUGetConfigSwitch(getDeviceName(), "UNPARK_FROM", "Last", &lastParkState);
1565 if (commWorked && apStatusParked(statusString) && (lastParkState != ISS_ON))
1566 {
1567 apIsInitialized = true;
1568 return true;
1569 }
1570 else
1571 {
1572 LOG_ERROR("Could not initialize mount.");
1573 Disconnect(); // Not sure about this....
1574 return false;
1575 }
1576 }
1577 // Not initialized, but not ready to give up either.
1578 return false;
1579}
1580
1582{
1583 apIsInitialized = false;
1584 apLocationInitialized = false;
1585 apTimeInitialized = false;
1586 apInitializationChecked = false;
1587
1588 return LX200Generic::Disconnect();
1589}
1590
1591bool LX200AstroPhysicsV2::APSync(double ra, double dec, bool recalibrate)
1592{
1593 char syncString[256] = ""; // simulation needs UTF-8
1594
1595 if (!isSimulation())
1596 {
1597 if (setAPObjectRA(PortFD, ra) < 0 || setAPObjectDEC(PortFD, dec) < 0)
1598 {
1600 LOG_ERROR("Error setting RA/DEC. Unable to Sync.");
1601 EqNP.apply();
1602 return false;
1603 }
1604 bool syncOK = true;
1605
1606 if (recalibrate)
1607 {
1608 if (APSyncCMR(PortFD, syncString) < 0)
1609 syncOK = false;
1610 }
1611 else
1612 {
1613 if (APSyncCM(PortFD, syncString) < 0)
1614 syncOK = false;
1615 }
1616
1617 if (!syncOK)
1618 {
1619 EqNP.setState(IPS_ALERT);
1620 LOG_ERROR("Synchronization failed");
1621 EqNP.apply();
1622 return false;
1623 }
1624
1625 }
1626
1627 currentRA = ra;
1628 currentDEC = dec;
1629 LOGF_DEBUG("%s Synchronization successful %s", (recalibrate ? "CMR" : "CM"), syncString);
1630
1631 EqNP.setState(IPS_OK);
1632
1634
1635 return true;
1636}
1637
1639{
1640 // The default sync is a "CMR" / "Recalibrate" sync.
1641 return APSync(ra, dec, true);
1642}
1643
1644bool LX200AstroPhysicsV2::updateTime(ln_date * utc, double utc_offset)
1645{
1646 // 2020-06-02, wildi, ToDo, time obtained from KStars differs up to a couple
1647 // of 5 seconds from system time.
1648 struct ln_zonedate ltm;
1649
1650 ln_date_to_zonedate(utc, &ltm, utc_offset * 3600.0);
1651 JD = ln_get_julian_day(utc);
1652 LOGF_DEBUG("New JD is %f, local time: %d, %d, %d, utc offset: %f", JD, ltm.hours, ltm.minutes, (int)ltm.seconds,
1653 utc_offset);
1654
1655 // Set Local Time
1656 if (isSimulation() == false && setLocalTime(PortFD, ltm.hours, ltm.minutes, (int)ltm.seconds) < 0)
1657 {
1658 LOG_ERROR("Error setting local time.");
1659 return false;
1660 }
1661 LOGF_DEBUG("Set Local Time %02d:%02d:%02d is successful.", ltm.hours, ltm.minutes,
1662 (int)ltm.seconds);
1663
1664 if (isSimulation() == false && setCalenderDate(PortFD, ltm.days, ltm.months, ltm.years) < 0)
1665 {
1666 LOG_ERROR("Error setting local date.");
1667 return false;
1668 }
1669 LOGF_DEBUG("Set Local Date %02d/%02d/%02d is successful.", ltm.days, ltm.months, ltm.years);
1670
1671 // 2020-05-30, wildi, after a very long journey
1672 // AP: TZ (0,12): West, East (-12.,-0), (>12,24)
1673 // Peru, Lima:
1674 //(TX=':Gg#'), RX='+77*01:42#
1675 //(TX=':SG05:00:00#'), RX='1'
1676 // Linux/Windows TZ values: West: -12,0, East 0,12
1677 // AP GTOCPX accepts a converted float including 24.
1678 double ap_utc_offset = - utc_offset;
1679 if (!isSimulation() && setAPUTCOffset(PortFD, ap_utc_offset) < 0)
1680 {
1681 LOG_ERROR("Error setting UTC Offset.");
1682 return false;
1683 }
1684 APUTCOffsetN[0].value = ap_utc_offset ;
1686 IDSetNumber(&APUTCOffsetNP, nullptr);
1687
1688 LOGF_DEBUG("Set UTC Offset %g as AP UTC Offset %g is successful.", utc_offset, ap_utc_offset);
1689 apTimeInitialized = true;
1690 return true;
1691}
1692
1693bool LX200AstroPhysicsV2::updateAPLocation(double latitude, double longitude, double elevation)
1694{
1695 INDI_UNUSED(elevation);
1696 LOG_DEBUG("LX200AstroPhysicsV2::updateLocation entry");
1697
1698 if ((latitude == 0.) && (longitude == 0.))
1699 {
1700 LOG_DEBUG("updateLocation: latitude, longitude both zero");
1701 return false;
1702 }
1703
1704 // Why is it 360-longitude? Verify!
1705 double apLongitude = 360 - longitude ;
1706 while (apLongitude < 0)
1707 apLongitude += 360;
1708 while (apLongitude > 360)
1709 apLongitude -= 360;
1710
1711 LOGF_DEBUG("Setting site longitude coordinates, %f %f", longitude, apLongitude);
1712
1713 if (!isSimulation() && setAPSiteLongitude(PortFD, apLongitude) < 0)
1714 {
1715 LOG_ERROR("Error setting site longitude coordinates");
1716 return false;
1717 }
1718
1719 if (!isSimulation() && setAPSiteLatitude(PortFD, latitude) < 0)
1720 {
1721 LOG_ERROR("Error setting site latitude coordinates");
1722 return false;
1723 }
1724
1725 char l[32], L[32];
1726 fs_sexa(l, latitude, 3, 3600);
1727 fs_sexa(L, longitude, 4, 3600);
1728
1729 LOGF_DEBUG("Site location updated to Lat %.32s - Long %.32s, deg: %f, %f", l, L, latitude, longitude);
1730 apLocationInitialized = true;
1731 return true;
1732}
1733
1734bool LX200AstroPhysicsV2::updateLocation(double latitude, double longitude, double elevation)
1735{
1736 if ((latitude == 0.) && (longitude == 0.))
1737 {
1738 LOG_DEBUG("updateLocation: latitude, longitude both zero");
1739 return false;
1740 }
1741 if (!isConnected())
1742 return true;
1743 return updateAPLocation(latitude, longitude, elevation);
1744}
1745
1747{
1749
1750 // we use routines from legacy AP driver routines and newer experimental driver routines
1752
1753}
1754
1755// For most mounts the SetSlewRate() method sets both the MoveTo and Slew (GOTO) speeds.
1756// For AP mounts these two speeds are handled separately - so SetSlewRate() actually sets the MoveTo speed for AP mounts - confusing!
1757// ApSetSlew
1759{
1760 if (!isSimulation() && selectAPV2CenterRate(PortFD, index, rateTable) < 0)
1761 {
1762 LOG_ERROR("Error setting slew mode.");
1763 return false;
1764 }
1765
1766 return true;
1767}
1768
1770{
1771 ParkPosition parkPos = static_cast<ParkPosition>(IUFindOnSwitchIndex(&ParkToSP));
1772 double parkAz {90}, parkAlt {0};
1773 if (parkPos == PARK_CURRENT)
1774 {
1775 LOG_DEBUG("PARK_CURRENT not implemented");
1776 }
1777 else if (calcParkPosition(parkPos, &parkAlt, &parkAz))
1778 {
1779 LOGF_DEBUG("Set park position %d to az=%f alt=%f", parkPos, parkAz, parkAlt);
1780 }
1781 else
1782 {
1783 LOGF_ERROR("Unable to set park position %d!!", parkPos);
1784 }
1785
1786 char AzStr[16] = {0}, AltStr[16] = {0};
1787 fs_sexa(AzStr, parkAz, 2, 3600);
1788 fs_sexa(AltStr, parkAlt, 2, 3600);
1789 LOGF_INFO("Parking to Az (%s) Alt (%s)...", AzStr, AltStr);
1790
1791 INDI::IEquatorialCoordinates equatorialCoords {0, 0};
1792 INDI::IHorizontalCoordinates horizontalCoords {parkAz, parkAlt};
1793 INDI::HorizontalToEquatorial(&horizontalCoords, &m_Location, ln_get_julian_from_sys(), &equatorialCoords);
1794 double lst = get_local_sidereal_time(m_Location.longitude);
1795 double ha = get_local_hour_angle(lst, equatorialCoords.rightascension);
1796
1798 HourangleCoordsN[0].value = ha;
1799 HourangleCoordsN[1].value = equatorialCoords.declination;
1800 IDSetNumber(&HourangleCoordsNP, nullptr);
1801
1802 if (isSimulation())
1803 {
1804 Goto(equatorialCoords.rightascension, equatorialCoords.declination);
1805 }
1806 else
1807 {
1808 if (setAPObjectAZ(PortFD, parkAz) < 0 || setAPObjectAlt(PortFD, parkAlt) < 0)
1809 {
1810 LOG_ERROR("Error setting Az/Alt.");
1811 return false;
1812 }
1813
1814 int err = 0;
1815
1816 /* Slew reads the '0', that is not the end of the slew */
1817 if ((err = Slew(PortFD)))
1818 {
1819 LOGF_ERROR("Error Slewing to Az %s - Alt %s", AzStr, AltStr);
1820 slewError(err);
1821 return false;
1822 }
1823 lastAZ = parkAz;
1824 lastAL = parkAlt;
1825 }
1826
1827 EqNP.setState(IPS_BUSY);
1829 LOG_INFO("Parking is in progress...");
1830
1831 return true;
1832}
1833
1834bool LX200AstroPhysicsV2::calcParkPosition(ParkPosition pos, double * parkAlt, double * parkAz)
1835{
1836 switch (pos)
1837 {
1838 // last unparked and park custom share enum 0
1839 case PARK_CUSTOM:
1840 LOG_ERROR("Called calcParkPosition with PARK_CUSTOM or PARK_LAST!");
1841 return false;
1842 break;
1843
1844 case PARK_CURRENT:
1845 LOG_ERROR("Called calcParkPosition with PARK_CURRENT!");
1846 return false;
1847 break;
1848
1849 // Park 1
1850 // Northern Hemisphere should be pointing at ALT=0 AZ=0 with scope on WEST side of pier
1851 // Southern Hemisphere should be pointing at ALT=0 AZ=180 with scope on WEST side of pier
1852 case PARK_PARK1:
1853 LOG_INFO("Computing PARK1 position...");
1854 *parkAlt = 0;
1855 *parkAz = LocationNP[LOCATION_LATITUDE].getValue() > 0 ? 359.1 : 180.1;
1856 break;
1857
1858 // Park 2
1859 // Northern Hemisphere should be pointing at ALT=0 AZ=90 with scope pointing EAST
1860 // Southern Hemisphere should be pointing at ALT=0 AZ=90 with scope pointing EAST
1861 case PARK_PARK2:
1862 LOG_INFO("Computing PARK2 position...");
1863 *parkAlt = 0;
1864 *parkAz = 90;
1865 break;
1866
1867 // Park 3
1868 // Northern Hemisphere should be pointing at ALT=LAT AZ=0 with scope pointing NORTH with CW down
1869 // Southern Hemisphere should be pointing at ALT=LAT AZ=180 with scope pointing SOUTH with CW down
1870 // wildi: the hour angle is undefined if AZ = 0,180 and ALT=LAT is chosen, adding .1 to Az sets PARK3
1871 // as close as possible to to HA = -6 hours (CW down), valid for both hemispheres.
1872 case PARK_PARK3:
1873 *parkAlt = fabs(LocationNP[LOCATION_LATITUDE].getValue());
1874 *parkAz = LocationNP[LOCATION_LATITUDE].getValue() > 0 ? 0.1 : 179.9;
1875 LOG_INFO("Computing PARK3 position");
1876 break;
1877
1878 // Park 4
1879 // Northern Hemisphere should be pointing at ALT=0 AZ=180 with scope on EAST side of pier
1880 // Southern Hemisphere should be pointing at ALT=0 AZ=0 with scope on EAST side of pier
1881 case PARK_PARK4:
1882 LOG_INFO("Computing PARK4 position...");
1883 *parkAlt = 0;
1884 *parkAz = LocationNP[LOCATION_LATITUDE].getValue() > 0 ? 180.1 : 359.1;
1885 break;
1886
1887 default:
1888 LOG_ERROR("Unknown park position!");
1889 return false;
1890 break;
1891 }
1892
1893 LOGF_DEBUG("calcParkPosition: parkPos=%d parkAlt=%f parkAz=%f", pos, *parkAlt, *parkAz);
1894
1895 return true;
1896
1897}
1898
1900{
1901 bool unpark_from_last_config = (PARK_LAST == IUFindOnSwitchIndex(&UnparkFromSP));
1902 double unparkAlt = 0, unparkAz = 0;
1903
1904 if (!unpark_from_last_config)
1905 {
1906 ParkPosition unparkfromPos = static_cast<ParkPosition>(IUFindOnSwitchIndex(&UnparkFromSP));
1907 LOGF_DEBUG("UnPark: park position = %d from current driver", unparkfromPos);
1908 if (!calcParkPosition(unparkfromPos, &unparkAlt, &unparkAz))
1909 {
1910 LOG_ERROR("UnPark: Error calculating unpark position!");
1912 IDSetSwitch(&UnparkFromSP, nullptr);
1913 return false;
1914 }
1915 LOGF_DEBUG("UnPark: parkPos=%d parkAlt=%f parkAz=%f", unparkfromPos, unparkAlt, unparkAz);
1916 }
1917
1918 bool isAPParked = true;
1919 if(!isSimulation())
1920 {
1921 if (!IsMountParked(&isAPParked))
1922 {
1923 LOG_WARN("UnPark:could not determine AP park status");
1925 IDSetSwitch(&UnparkFromSP, nullptr);
1926 return false;
1927 }
1928
1929 if(!isAPParked)
1930 {
1931 LOG_WARN("UnPark: AP mount status: unparked, park first");
1933 IDSetSwitch(&UnparkFromSP, nullptr);
1934 return false;
1935 }
1936
1937 if (APUnParkMount(PortFD) < 0)
1938 {
1939 ParkSP.reset();
1940 ParkSP[PARK].setState(ISS_ON);
1941 ParkSP.setState(IPS_ALERT);
1942 ParkSP.apply();
1943 LOG_ERROR("UnParking AP mount failed.");
1944 return false;
1945 }
1946
1947 SetParked(false);
1948 // Stop :Q#
1949 if ( abortSlew(PortFD) < 0)
1950 {
1951 ParkSP.reset();
1952 ParkSP[PARK].setState(ISS_ON);
1953 ParkSP.setState(IPS_ALERT);
1954 ParkSP.apply();
1955 LOG_WARN("Abort motion Failed");
1956 return false;
1957 }
1958 SetTrackEnabled(true);
1960 }
1961 else
1962 {
1963 SetParked(false);
1964 SetTrackEnabled(false);
1966 }
1967
1968 if (!unpark_from_last_config)
1969 {
1970 INDI::IEquatorialCoordinates equatorialCoords {0, 0};
1971 INDI::IHorizontalCoordinates horizontalCoords {unparkAz, unparkAlt};
1972 INDI::HorizontalToEquatorial(&horizontalCoords, &m_Location, ln_get_julian_from_sys(), &equatorialCoords);
1973
1974 char AzStr[16], AltStr[16];
1975 fs_sexa(AzStr, unparkAz, 2, 3600);
1976 fs_sexa(AltStr, unparkAlt, 2, 3600);
1977 char RaStr[16], DecStr[16];
1978 fs_sexa(RaStr, equatorialCoords.rightascension, 2, 3600);
1979 fs_sexa(DecStr, equatorialCoords.declination, 2, 3600);
1980
1981 double lst = get_local_sidereal_time(m_Location.longitude);
1982 double ha = get_local_hour_angle(lst, equatorialCoords.rightascension);
1983 char HaStr[16];
1984 fs_sexa(HaStr, ha, 2, 3600);
1985 LOGF_INFO("UnPark: Current parking position Az (%s) Alt (%s), HA (%s) RA (%s) Dec (%s)", AzStr, AltStr, HaStr,
1986 RaStr, DecStr);
1987
1989 HourangleCoordsN[0].value = ha;
1990 HourangleCoordsN[1].value = equatorialCoords.declination;
1991 IDSetNumber(&HourangleCoordsNP, nullptr);
1992
1993
1994 // If we are not using PARK_LAST, then we're unparking from a pre-defined position, and this is the
1995 // only time we should use the full :CM "Fully Calibrate" sync command.
1996 bool success = APSync(equatorialCoords.rightascension, equatorialCoords.declination, false);
1997 if(!success)
1998 {
1999 LOG_WARN("Could not sync mount");
2000 return false;
2001 }
2002 else
2003 {
2004 LOGF_INFO("UnPark: Sync'd (:CM) to RA/DEC: %f %f", equatorialCoords.rightascension, equatorialCoords.declination);
2005 }
2006 }
2007
2008 if (MovementNSSP.getState() == IPS_BUSY || MovementWESP.getState() == IPS_BUSY)
2009 {
2010 MovementNSSP.setState(IPS_IDLE);
2011 MovementWESP.setState(IPS_IDLE);
2012 EqNP.setState(IPS_IDLE);
2013 MovementNSSP.reset();
2014 MovementWESP.reset();
2015 MovementNSSP.apply();
2016 MovementWESP.apply();
2017 }
2018
2019 UnparkFromSP.s = IPS_OK;
2020 IDSetSwitch(&UnparkFromSP, nullptr);
2021 // SlewRateS is used as the MoveTo speed
2022 int err;
2023 int switch_nr = SlewRateSP.findOnSwitchIndex();
2024 if (!isSimulation() && (err = selectAPV2CenterRate(PortFD, switch_nr, rateTable)) < 0)
2025 {
2026 LOGF_ERROR("Error setting center (MoveTo) rate (%d).", err);
2027 return false;
2028 }
2029
2030 SlewRateSP.setState(IPS_OK);
2031 SlewRateSP.apply();
2032
2033 // APSlewSpeedsS defines the Slew (GOTO) speeds valid on the AP mounts
2034 switch_nr = IUFindOnSwitchIndex(&APSlewSpeedSP);
2035 if (!isSimulation() && (err = selectAPSlewRate(PortFD, switch_nr)) < 0)
2036 {
2037 LOGF_ERROR("Error setting slew to rate (%d).", err);
2038 return false;
2039 }
2040
2042 IDSetSwitch(&APSlewSpeedSP, nullptr);
2043
2044 LOG_DEBUG("UnPark: Mount unparked successfully");
2045
2046 return true;
2047}
2048
2050{
2051 return true;
2052}
2053
2055{
2056 return true;
2057}
2058
2059void LX200AstroPhysicsV2::syncSideOfPier()
2060{
2061 const char *cmd = "#:pS#";
2062 // Response
2063 char response[16] = { 0 };
2064 int rc = 0, nbytes_read = 0, nbytes_written = 0;
2065
2066 LOGF_DEBUG("CMD: <%s>", cmd);
2067
2068 tcflush(PortFD, TCIOFLUSH);
2069
2070 if ((rc = tty_write(PortFD, cmd, strlen(cmd), &nbytes_written)) != TTY_OK)
2071 {
2072 char errmsg[256];
2073 tty_error_msg(rc, errmsg, 256);
2074 LOGF_ERROR("Error writing to device %s (%d)", errmsg, rc);
2075 return;
2076 }
2077
2078 // Read Side
2079 if ((rc = tty_read_section(PortFD, response, '#', 3, &nbytes_read)) != TTY_OK)
2080 {
2081 char errmsg[256];
2082 tty_error_msg(rc, errmsg, 256);
2083 LOGF_ERROR("Error reading from device %s (%d)", errmsg, rc);
2084 return;
2085 }
2086
2087 response[nbytes_read - 1] = '\0';
2088
2089 tcflush(PortFD, TCIOFLUSH);
2090
2091 LOGF_DEBUG("RES: <%s>", response);
2092
2093 if (!strcmp(response, "East"))
2095 else if (!strcmp(response, "West"))
2097 else
2098 LOGF_ERROR("Invalid pier side response from device-> %s", response);
2099}
2100
2102{
2104
2109 TrackStateSP.save(fp);
2110
2111 return true;
2112}
2113
2115{
2116 int err = 0;
2117
2118 LOGF_DEBUG("LX200AstroPhysicsV2::SetTrackMode(%d)", mode);
2119
2120 if (mode == TRACK_CUSTOM)
2121 {
2123 {
2124 LOGF_ERROR("Error setting tracking mode (%d).", err);
2125 return false;
2126 }
2127
2128 return SetTrackRate(TrackRateNP[AXIS_RA].getValue(), TrackRateNP[AXIS_DE].getValue());
2129 }
2130
2131 if (!isSimulation() && (err = selectAPTrackingMode(PortFD, mode)) < 0)
2132 {
2133 LOGF_ERROR("Error setting tracking mode (%d).", err);
2134 return false;
2135 }
2136
2137 return true;
2138}
2139
2141{
2142 bool rc;
2143
2144 LOGF_DEBUG("LX200AstroPhysicsV2::SetTrackEnabled(%d)", enabled);
2145
2146 rc = SetTrackMode(enabled ? TrackModeSP.findOnSwitchIndex() : AP_TRACKING_OFF);
2147
2148 LOGF_DEBUG("LX200AstroPhysicsV2::SetTrackMode() returned %d", rc);
2149
2150 return rc;
2151}
2152
2153bool LX200AstroPhysicsV2::SetTrackRate(double raRate, double deRate)
2154{
2155 // Convert to arcsecs/s to AP sidereal multiplier
2156 /*
2157 :RR0.0000# = normal sidereal tracking in RA - similar to :RT2#
2158 :RR+1.0000# = 1 + normal sidereal = 2X sidereal
2159 :RR+9.0000# = 9 + normal sidereal = 10X sidereal
2160 :RR-1.0000# = normal sidereal - 1 = 0 or Stop - similar to :RT9#
2161 :RR-11.0000# = normal sidereal - 11 = -10X sidereal (East at 10X)
2162
2163 :RD0.0000# = normal zero rate for Dec.
2164 :RD5.0000# = 5 + normal zero rate = 5X sidereal clockwise from above - equivalent to South
2165 :RD-5.0000# = normal zero rate - 5 = 5X sidereal counter-clockwise from above - equivalent to North
2166 */
2167
2168 double APRARate = (raRate - TRACKRATE_SIDEREAL) / TRACKRATE_SIDEREAL;
2169 double APDERate = deRate / TRACKRATE_SIDEREAL;
2170
2171 if (!isSimulation())
2172 {
2173 if (setAPRATrackRate(PortFD, APRARate) < 0 || setAPDETrackRate(PortFD, APDERate) < 0)
2174 return false;
2175 }
2176
2177 return true;
2178}
2179
2181{
2182 if (isSimulation())
2183 {
2184 *offset = 3;
2185 return true;
2186 }
2187
2188 return (getAPUTCOffset(PortFD, offset) == 0);
2189}
2190
2192{
2193 // If we are not guiding and we need to restore slew rate, then let's restore it.
2194 if (command == MOTION_START && GuideNSTID == 0 && rememberSlewRate >= 0)
2195 {
2196 ISState states[] = { ISS_OFF, ISS_OFF, ISS_OFF, ISS_OFF };
2197 states[rememberSlewRate] = ISS_ON;
2198 const char *names[] = { SlewRateSP[0].getName(), SlewRateSP[1].getName(),
2199 SlewRateSP[2].getName(), SlewRateSP[3].getName()
2200 };
2201 ISNewSwitch(SlewRateSP.getDeviceName(), SlewRateSP.getName(), states, const_cast<char **>(names), 4);
2202 rememberSlewRate = -1;
2203 }
2204
2205 bool rc = LX200Generic::MoveNS(dir, command);
2206 return rc;
2207}
2208
2210{
2211 // If we are not guiding and we need to restore slew rate, then let's restore it.
2212 if (command == MOTION_START && GuideWETID == 0 && rememberSlewRate >= 0)
2213 {
2214 ISState states[] = { ISS_OFF, ISS_OFF, ISS_OFF, ISS_OFF };
2215 states[rememberSlewRate] = ISS_ON;
2216 const char *names[] = { SlewRateSP[0].getName(), SlewRateSP[1].getName(),
2217 SlewRateSP[2].getName(), SlewRateSP[3].getName()
2218 };
2219 ISNewSwitch(SlewRateSP.getDeviceName(), SlewRateSP.getName(), states, const_cast<char **>(names), 4);
2220 rememberSlewRate = -1;
2221 }
2222
2223 bool rc = LX200Generic::MoveWE(dir, command);
2224 return rc;
2225}
2226
2228{
2229 if (!isAPReady())
2230 return false;
2231
2232 // restore guide rate
2234
2235 bool rc = LX200Generic::MoveNS(dir, command);
2236 return rc;
2237}
2238
2240{
2241 if (!isAPReady())
2242 return false;
2243
2244 // restore guide rate
2246
2247 bool rc = LX200Generic::MoveWE(dir, command);
2248 return rc;
2249}
2250
The Interface class is the base class for all INDI connection plugins.
virtual std::string name()=0
bool isConnected() const
virtual bool saveConfig(bool silent=false, const char *property=nullptr)
Save the current properties in a configuration file.
virtual bool Disconnect()
Disconnect from device.
void setVersion(uint16_t vMajor, uint16_t vMinor)
Set driver version information to be defined in DRIVER_INFO property as vMajor.vMinor.
virtual bool loadConfig(bool silent=false, const char *property=nullptr)
Load the last saved configuration file.
virtual bool deleteProperty(const char *propertyName)
Delete a property and unregister it. It will also be deleted from all clients.
void defineProperty(INumberVectorProperty *property)
bool isSimulation() const
Connection::Interface * getActiveConnection()
virtual bool Connect()
Connect to the device. INDI::DefaultDevice implementation connects to appropriate connection interfac...
INDI::PropertyNumber GuideNSNP
INDI::PropertyNumber GuideWENP
void setState(IPState state)
void apply(const char *format,...) const ATTRIBUTE_FORMAT_PRINTF(2
void fill(const char *device, const char *name, const char *label, const char *group, IPerm permission, ISRule rule, double timeout, IPState state)
TelescopeStatus TrackState
void SetTelescopeCapability(uint32_t cap, uint8_t slewRateCount)
SetTelescopeCapability sets the Telescope capabilities. All capabilities must be initialized.
virtual void SetParked(bool isparked)
SetParked Change the mount parking status. The data park file (stored in ~/.indi/ParkData....
Connection::TCP * tcpConnection
void setPECState(TelescopePECState state)
IGeographicCoordinates m_Location
uint32_t GetTelescopeCapability() const
GetTelescopeCapability returns the capability of the Telescope.
void NewRaDec(double ra, double dec)
The child class calls this function when it has updates.
void setPierSide(TelescopePierSide side)
TelescopePECState getPECState()
virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n) override
Process the client newSwitch command.
virtual bool initProperties() override
Called to initialize basic properties required all the time.
ITextVectorProperty APMountStatusTP
Definition lx200ap_v2.h:162
virtual bool SetCurrentPark() override
SetCurrentPark Set current coordinates/encoders value as the desired parking position.
ISwitchVectorProperty APSlewSpeedSP
Definition lx200ap_v2.h:123
virtual IPState GuideNorth(uint32_t ms) override
Guide north for ms milliseconds. North is defined as DEC+.
INumber HorizontalCoordsN[2]
Definition lx200ap_v2.h:119
virtual bool MoveWE(INDI_DIR_WE dir, TelescopeMotionCommand command) override
Move the telescope in the direction dir.
ISwitch UnparkFromS[5]
Definition lx200ap_v2.h:135
virtual bool Handshake() override
perform handshake with device to check communication
virtual IPState GuideWest(uint32_t ms) override
Guide west for ms milliseconds. West is defined as RA-.
INumberVectorProperty HourangleCoordsNP
Definition lx200ap_v2.h:115
ISwitchVectorProperty ParkToSP
Definition lx200ap_v2.h:139
ISwitch APSlewSpeedS[3]
Definition lx200ap_v2.h:122
void AstroPhysicsGuideTimeoutNS(bool simul)
ITextVectorProperty APPECStateTP
Definition lx200ap_v2.h:159
ITextVectorProperty VersionTP
Definition lx200ap_v2.h:145
ISwitch APPECRecordS[2]
Definition lx200ap_v2.h:165
INumberVectorProperty HorizontalCoordsNP
Definition lx200ap_v2.h:120
virtual bool GuideNS(INDI_DIR_NS dir, TelescopeMotionCommand command)
ISwitch HomeAndReSyncS[1]
Definition lx200ap_v2.h:151
virtual bool Park() override
Park the telescope to its home position.
virtual bool SetTrackMode(uint8_t mode) override
SetTrackMode Set active tracking mode. Do not change track state.
virtual bool updateProperties() override
Called when connected state changes, to add/remove properties.
virtual bool SetTrackEnabled(bool enabled) override
SetTrackEnabled Engages or disengages mount tracking. If there are no tracking modes available,...
virtual void debugTriggered(bool enable) override
Inform driver that the debug option was triggered. This function is called after setDebug is triggere...
virtual bool UnPark() override
Unpark the telescope if already parked.
virtual bool updateLocation(double latitude, double longitude, double elevation) override
Update telescope location settings.
static void pulseGuideTimeoutHelperWE(void *p)
INumberVectorProperty APSiderealTimeNP
Definition lx200ap_v2.h:117
virtual bool getUTFOffset(double *offset) override
INumberVectorProperty APUTCOffsetNP
Definition lx200ap_v2.h:141
INumber APSiderealTimeN[1]
Definition lx200ap_v2.h:116
INumber APUTCOffsetN[1]
Definition lx200ap_v2.h:142
virtual bool Sync(double ra, double dec) override
Set the telescope current RA and DEC coordinates to the supplied RA and DEC coordinates.
static void pulseGuideTimeoutHelperNS(void *p)
ISwitch APGuideSpeedS[3]
Definition lx200ap_v2.h:132
virtual int SendPulseCmd(int8_t direction, uint32_t duration_msec) override
virtual bool Goto(double, double) override
Move the scope to the supplied RA and DEC coordinates.
ISwitchVectorProperty SwapSP
Definition lx200ap_v2.h:126
virtual bool ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n) override
Process the client newNumber command.
virtual IPState GuideEast(uint32_t ms) override
Guide east for ms milliseconds. East is defined as RA+.
ISwitchVectorProperty APGuideSpeedSP
Definition lx200ap_v2.h:133
IText APMountStatusT[1]
Definition lx200ap_v2.h:161
virtual bool SetDefaultPark() override
SetDefaultPark Set default coordinates/encoders value as the desired parking position.
virtual bool SetTrackRate(double raRate, double deRate) override
SetTrackRate Set custom tracking rates.
static void simulGuideTimeoutHelperNS(void *p)
ISwitchVectorProperty ManualSetParkedSP
Definition lx200ap_v2.h:147
virtual bool saveConfigItems(FILE *fp) override
saveConfigItems Save specific properties in the provide config file handler. Child class usually over...
virtual IPState GuideSouth(uint32_t ms) override
Guide south for ms milliseconds. South is defined as DEC-.
APRateTableState rateTable
Definition lx200ap_v2.h:153
ISwitchVectorProperty APPECRecordSP
Definition lx200ap_v2.h:164
ISwitchVectorProperty UnparkFromSP
Definition lx200ap_v2.h:136
virtual bool ReadScopeStatus() override
Read telescope status.
ISwitchVectorProperty HomeAndReSyncSP
Definition lx200ap_v2.h:150
virtual bool Disconnect() override
Disconnect from device.
void AstroPhysicsGuideTimeoutWE(bool simul)
virtual void ISGetProperties(const char *dev) override
define the driver's properties to the client. Usually, only a minimum set of properties are defined t...
virtual bool SetSlewRate(int index) override
SetSlewRate Set desired slew rate index.
INumber HourangleCoordsN[2]
Definition lx200ap_v2.h:114
INumberVectorProperty APWormPositionNP
Definition lx200ap_v2.h:156
virtual bool Connect() override
Connect to the device. INDI::DefaultDevice implementation connects to appropriate connection interfac...
virtual bool GuideWE(INDI_DIR_WE dir, TelescopeMotionCommand command)
virtual bool updateTime(ln_date *utc, double utc_offset) override
Update telescope time, date, and UTC offset.
static void simulGuideTimeoutHelperWE(void *p)
virtual bool MoveNS(INDI_DIR_NS dir, TelescopeMotionCommand command) override
Start or Stop the telescope motion in the direction dir.
ISwitch ManualSetParkedS[1]
Definition lx200ap_v2.h:148
INumber APWormPositionN[1]
Definition lx200ap_v2.h:155
virtual const char * getDefaultName() override
virtual bool initProperties() override
Called to initialize basic properties required all the time.
virtual void slewError(int slewCode)
virtual bool ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n) override
Process the client newNumber command.
virtual bool MoveNS(INDI_DIR_NS dir, TelescopeMotionCommand command) override
Start or Stop the telescope motion in the direction dir.
virtual bool updateProperties() override
Called when connected state changes, to add/remove properties.
virtual bool saveConfigItems(FILE *fp) override
saveConfigItems Save specific properties in the provide config file handler. Child class usually over...
virtual bool MoveWE(INDI_DIR_WE dir, TelescopeMotionCommand command) override
Move the telescope in the direction dir.
virtual void ISGetProperties(const char *dev) override
define the driver's properties to the client. Usually, only a minimum set of properties are defined t...
virtual void debugTriggered(bool enable) override
Inform driver that the debug option was triggered. This function is called after setDebug is triggere...
virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n) override
Process the client newSwitch command.
void setLX200Capability(uint32_t cap)
const char * GUIDE_TAB
GUIDE_TAB Where all the properties for guiding are located.
const char * MAIN_CONTROL_TAB
MAIN_CONTROL_TAB Where all the primary controls for the device are located.
const char * MOTION_TAB
MOTION_TAB Where all the motion control properties of the device are located.
const char * SITE_TAB
SITE_TAB Where all site information setting are located.
void IERmTimer(int timerid)
Remove the timer with the given timerid, as returned from IEAddTimer() or IEAddPeriodicTimer().
Definition eventloop.c:606
int IEAddTimer(int millisecs, IE_TCF *fp, void *p)
Register a new single-shot timer function, fp, to be called with ud as argument after ms.
Definition eventloop.c:586
INDI::PropertySwitch ParkSP
INDI::PropertySwitch AbortSP
INDI::PropertyNumber TrackRateNP
INDI::PropertySwitch MovementNSSP
INDI::PropertyNumber EqNP
INDI::PropertySwitch TrackStateSP
INDI::PropertySwitch PECStateSP
INDI::PropertySwitch SlewRateSP
INDI::PropertySwitch TrackModeSP
INDI::PropertySwitch MovementWESP
INDI::PropertySwitch CoordSP
INDI::PropertyNumber LocationNP
#define setLocalTime(fd, x, y, z)
double ra
double dec
ISState
Switch state.
Definition indiapi.h:148
@ ISS_OFF
Definition indiapi.h:149
@ ISS_ON
Definition indiapi.h:150
@ IP_RW
Definition indiapi.h:184
@ IP_RO
Definition indiapi.h:182
IPState
Property state.
Definition indiapi.h:158
@ IPS_BUSY
Definition indiapi.h:161
@ IPS_ALERT
Definition indiapi.h:162
@ IPS_IDLE
Definition indiapi.h:159
@ IPS_OK
Definition indiapi.h:160
@ ISR_1OFMANY
Definition indiapi.h:171
@ ISR_ATMOST1
Definition indiapi.h:172
@ AXIS_DE
@ AXIS_RA
INDI_DIR_WE
@ DIRECTION_EAST
@ DIRECTION_WEST
INDI_DIR_NS
@ DIRECTION_SOUTH
@ DIRECTION_NORTH
void tty_set_generic_udp_format(int enabled)
Definition indicom.c:364
int tty_read_section(int fd, char *buf, char stop_char, int timeout, int *nbytes_read)
read buffer from terminal with a delimiter
Definition indicom.c:653
int tty_write(int fd, const char *buf, int nbytes, int *nbytes_written)
Writes a buffer to fd.
Definition indicom.c:418
void tty_error_msg(int err_code, char *err_msg, int err_msg_len)
Retrieve the tty error message.
Definition indicom.c:1243
int fs_sexa(char *out, double a, int w, int fracbase)
Converts a sexagesimal number to a string. sprint the variable a in sexagesimal format into out[].
Definition indicom.c:130
void tty_clr_trailing_read_lf(int enabled)
Definition indicom.c:369
double get_local_hour_angle(double sideral_time, double ra)
get_local_hour_angle Returns local hour angle of an object
Definition indicom.c:1379
Implementations for common driver routines.
@ TTY_OK
Definition indicom.h:54
double get_local_sidereal_time(double longitude)
get_local_sidereal_time Returns local sidereal time given longitude and system clock.
void IUSaveConfigSwitch(FILE *fp, const ISwitchVectorProperty *svp)
Add a switch vector property value to the configuration file.
Definition indidevapi.c:33
void IUFillNumberVector(INumberVectorProperty *nvp, INumber *np, int nnp, const char *dev, const char *name, const char *label, const char *group, IPerm p, double timeout, IPState s)
Assign attributes for a number vector property. The vector's auxiliary elements will be set to NULL.
Definition indidevapi.c:490
int IUFindOnSwitchIndex(const ISwitchVectorProperty *svp)
Returns the index of first ON switch it finds in the vector switch property.
Definition indidevapi.c:337
void IUResetSwitch(ISwitchVectorProperty *svp)
Reset all switches in a switch vector property to OFF.
Definition indidevapi.c:366
void IUFillTextVector(ITextVectorProperty *tvp, IText *tp, int ntp, const char *dev, const char *name, const char *label, const char *group, IPerm p, double timeout, IPState s)
Assign attributes for a text vector property. The vector's auxiliary elements will be set to NULL.
Definition indidevapi.c:509
void IUSaveText(IText *tp, const char *newtext)
Function to reliably save new text in a IText.
Definition indidevapi.c:44
void IUFillSwitch(ISwitch *sp, const char *name, const char *label, ISState s)
Assign attributes for a switch property. The switch's auxiliary elements will be set to NULL.
Definition indidevapi.c:376
void IUFillText(IText *tp, const char *name, const char *label, const char *initialText)
Assign attributes for a text property. The text's auxiliary elements will be set to NULL.
Definition indidevapi.c:416
void IUFillNumber(INumber *np, const char *name, const char *label, const char *format, double min, double max, double step, double value)
Assign attributes for a number property. The number's auxiliary elements will be set to NULL.
Definition indidevapi.c:398
void IUFillSwitchVector(ISwitchVectorProperty *svp, ISwitch *sp, int nsp, const char *dev, const char *name, const char *label, const char *group, IPerm p, ISRule r, double timeout, IPState s)
Assign attributes for a switch vector property. The vector's auxiliary elements will be set to NULL.
Definition indidevapi.c:453
#define INDI_UNUSED(x)
Definition indidevapi.h:132
int IUUpdateSwitch(ISwitchVectorProperty *svp, ISState *states, char *names[], int n)
Update all switches in a switch vector property.
void IDSetNumber(const INumberVectorProperty *nvp, const char *fmt,...)
void IDSetSwitch(const ISwitchVectorProperty *svp, const char *fmt,...)
int IUGetConfigNumber(const char *dev, const char *property, const char *member, double *value)
IUGetConfigNumber Opens configuration file and reads single number property.
Definition indidriver.c:846
int IUUpdateNumber(INumberVectorProperty *nvp, double values[], char *names[], int n)
Update all numbers in a number vector property.
void IDSetText(const ITextVectorProperty *tvp, const char *fmt,...)
int IUGetConfigSwitch(const char *dev, const char *property, const char *member, ISState *value)
IUGetConfigSwitch Opens configuration file and reads single switch property.
Definition indidriver.c:657
*brief user defined string literal for JSON values *sa std::size_t n
#define LOGF_INFO(fmt,...)
Definition indilogger.h:82
#define LOG_DEBUG(txt)
Definition indilogger.h:75
#define LOGF_WARN(fmt,...)
Definition indilogger.h:81
#define LOG_WARN(txt)
Definition indilogger.h:73
#define LOGF_DEBUG(fmt,...)
Definition indilogger.h:83
#define LOG_ERROR(txt)
Shorter logging macros. In order to use these macros, the function (or method) "getDeviceName()" must...
Definition indilogger.h:72
#define LOGF_ERROR(fmt,...)
Definition indilogger.h:80
#define LOG_INFO(txt)
Definition indilogger.h:74
#define TRACKRATE_SIDEREAL
Definition indimacros.h:39
#define getDeviceName
APPECRecordingState
@ AP_PEC_RECORD_ON
@ AP_PEC_RECORD_OFF
char * trackStateString(INDI::Telescope::TelescopeStatus state)
#define MAX_LX200AP_PULSE_LEN
bool apStatusParked(const char *statusString)
int setAPUTCOffset(int fd, double hours)
int setAPSiteLatitude(int fd, double Lat)
int getAPWormPosition(int fd, int *position)
void set_lx200ap_name(const char *deviceName, unsigned int debug_level)
int setAPRATrackRate(int fd, double rate)
int apHomeAndSync(int fd)
int setAPObjectRA(int fd, double ra)
int APSyncCMR(int fd, char *matchedObject)
int setAPObjectAlt(int fd, double alt)
int swapAPButtons(int fd, int currentSwap)
int setAPObjectDEC(int fd, double dec)
int isAPInitialized(int fd, bool *isInitialized)
int APSendPulseCmd(int fd, int direction, int duration_msec)
int APParkMount(int fd)
int selectAPSlewRate(int fd, int slewIndex)
const char * apMountStatus(const char *statusString)
int getApStatusString(int fd, char *statusString)
int check_lx200ap_status(int fd, char *parkStatus, char *slewStatus)
int APUnParkMount(int fd)
bool apCanHome(int fd)
int selectAPPECState(int fd, int pecstate)
int selectAPGuideRate(int fd, int guideRate)
APRateTableState apRateTable(const char *statusString)
int setAPObjectAZ(int fd, double az)
int APSyncCM(int fd, char *matchedObject)
int getAPUTCOffset(int fd, double *value)
int setAPDETrackRate(int fd, double rate)
bool apStatusSlewing(const char *statusString)
int setAPSiteLongitude(int fd, double Long)
int selectAPV2CenterRate(int fd, int centerIndex, APRateTableState rateTable)
int selectAPTrackingMode(int fd, int trackMode)
#define setAPBackLashCompensation(fd, x, y, z)
@ AP_RATE_TABLE_DEFAULT
#define getAPVersionNumber(fd, x)
#define setAPClearBuffer(fd)
#define AP_PEC_OFF
#define AP_PEC_ON
#define AP_PEC_ENCODER
#define AP_TRACKING_OFF
#define AP_PEC_RECORD
#define AP_TRACKING_SIDEREAL
int checkLX200EquatorialFormat(int fd)
int abortSlew(int fd)
int setCalenderDate(int fd, int dd, int mm, int yy, bool addSpace)
int Slew(int fd)
#define getLX200DEC(fd, x)
@ LX200_24
Definition lx200driver.h:64
#define getLX200RA(fd, x)
#define getLX200Alt(fd, x)
@ LX200_WEST
Definition lx200driver.h:42
@ LX200_SOUTH
Definition lx200driver.h:44
@ LX200_NORTH
Definition lx200driver.h:41
@ LX200_EAST
Definition lx200driver.h:43
#define getLX200Az(fd, x)
#define getSDTime(fd, x)
void HorizontalToEquatorial(IHorizontalCoordinates *object, IGeographicCoordinates *observer, double JD, IEquatorialCoordinates *position)
HorizontalToEquatorial Calculate Equatorial EOD Coordinates from horizontal coordinates.
Definition libastro.cpp:161
uint8_t cmd[4]
Definition pwc-ioctl.h:2
double value
Definition indiapi.h:288