Instrument Neutral Distributed Interface INDI 2.2.5
indi_alpaca_telescope.cpp
Go to the documentation of this file.
1/*
2 INDI alpaca Driver
3
4 Copyright (C) 2026 Gord Tulloch
5
6 This library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
10
11 This library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public
17 License along with this library; if not, write to the Free Software
18 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19*/
20
23#include <memory>
24#include <cstring>
25#include <cmath>
26#include <indicom.h>
27#include <libnova/julian_day.h>
28
29// We declare an auto pointer to alpacaTelescopeDriver instance
30std::unique_ptr<alpacaTelescopeDriver> alpaca(new alpacaTelescopeDriver());
31
32#define RA_AXIS 0
33#define DEC_AXIS 1
34
36{
37 DBG_SCOPE = static_cast<uint32_t>(INDI::Logger::getInstance().addDebugLevel("Scope Verbose", "SCOPE"));
38
39 setVersion(1, 0);
46 4
47 );
49 m_ClientID = getpid();
50 LOG_DEBUG("Initializing from alpacaTelescope device...");
51}
52
54{
55 return "Alpaca Telescope";
56}
57
59{
61
62 // Use built-in TCP connection with default alpaca.local:32323
63 tcpConnection->setDefaultHost("alpaca.local");
64 tcpConnection->setDefaultPort(32323);
65
66 // Device info
67 DeviceInfoTP[DESCRIPTION].fill("DESCRIPTION", "Description", "");
68 DeviceInfoTP[DRIVER_INFO].fill("DRIVER_INFO", "Driver Info", "");
69 DeviceInfoTP[DRIVER_VERSION].fill("DRIVER_VERSION", "Driver Version", "");
70 DeviceInfoTP[INTERFACE_VERSION].fill("INTERFACE_VERSION", "Interface Version", "");
71 DeviceInfoTP.fill(getDeviceName(), "DEVICE_INFO", "Device Info", OPTIONS_TAB, IP_RO, 60, IPS_IDLE);
72
74
75 // RA is a rotating frame, while HA or Alt/Az is not
77
78 /* Add debug controls so we may debug driver if necessary */
80
81 return true;
82}
83
85{
87
88 if (isConnected())
89 {
90 defineProperty(DeviceInfoTP);
91
92 if (InitPark())
93 {
94 // Load park data if available
95 m_currentRA = ParkPositionNP[AXIS_RA].getValue();
96 m_currentDEC = ParkPositionNP[AXIS_DE].getValue();
99 }
100 else
101 {
102 SetAxis1Park(-6.);
103 SetAxis2Park(0.);
106 }
107 }
108 else
109 {
110 deleteProperty(DeviceInfoTP);
111 }
112
113 return true;
114}
115
117{
118 std::string host = tcpConnection->host();
119 int port = tcpConnection->port();
120
121 LOGF_INFO("Connecting to alpaca server at %s:%d", host.c_str(), port);
122
123 httpClient = std::make_unique<httplib::Client>(host.c_str(), port);
124 httpClient->set_connection_timeout(10);
125 httpClient->set_read_timeout(30); // Increased timeout for commands that may take time to respond
126
127 nlohmann::json response;
128 if (!sendAlpacaGET("/connected", response))
129 {
130 LOG_ERROR("Failed to connect to alpaca");
131 httpClient.reset();
132 return false;
133 }
134
135 LOGF_INFO("alpaca reachable, connected=%s",
136 response.value("Value", false) ? "true" : "false");
137
138 nlohmann::json request;
139 request["Connected"] = true;
140 if (!sendAlpacaPUT("/connected", request, response))
141 {
142 LOG_ERROR("Failed to set connected state");
143 httpClient.reset();
144 return false;
145 }
146
147 // Query device capabilities, location, time, and initial status now that the
148 // HTTP client is ready (Handshake() also defines TrackModeSP via AddTrackMode(),
149 // which must happen before updateProperties() is called)
150 Handshake();
151
152 // Start the timer
154
155 LOG_INFO("Successfully connected to alpaca");
156 return true;
157}
158
160{
161 if (httpClient)
162 {
163 nlohmann::json request, response;
164 request["Connected"] = false;
165 sendAlpacaPUT("/connected", request, response);
166 httpClient.reset();
167 }
168 LOG_INFO("Disconnected from alpaca");
169 return true;
170}
171
173{
174 nlohmann::json response;
175
176 if (sendAlpacaGET("/description", response) && response.contains("Value"))
177 DeviceInfoTP[DESCRIPTION].setText(response["Value"].get<std::string>().c_str());
178
179 if (sendAlpacaGET("/driverinfo", response) && response.contains("Value"))
180 DeviceInfoTP[DRIVER_INFO].setText(response["Value"].get<std::string>().c_str());
181
182 if (sendAlpacaGET("/driverversion", response) && response.contains("Value"))
183 DeviceInfoTP[DRIVER_VERSION].setText(response["Value"].get<std::string>().c_str());
184
185 if (sendAlpacaGET("/interfaceversion", response) && response.contains("Value"))
186 DeviceInfoTP[INTERFACE_VERSION].setText(std::to_string(response["Value"].get<int>()).c_str());
187
188 DeviceInfoTP.apply();
189
190 // Query alignment mode to determine mount behavior
191 // 0 = algPolar (equatorial), 1 = algAltAz, 2 = algGermanPolar
192 if (sendAlpacaGET("/alignmentmode", response) && response.contains("Value"))
193 {
194 int alignmentMode = response["Value"].get<int>();
195 if (alignmentMode == 1)
196 {
197 LOG_INFO("Telescope alignment mode: Alt-Az (no meridian flips)");
199 }
200 else if (alignmentMode == 0)
201 {
202 LOG_INFO("Telescope alignment mode: Equatorial (Fork mount - no meridian flips)");
204 }
205 else if (alignmentMode == 2)
206 {
207 LOG_INFO("Telescope alignment mode: German Equatorial");
209 }
210 }
211
212 bool canPark = false;
213 if (sendAlpacaGET("/canpark", response) && response.contains("Value"))
214 canPark = response["Value"].get<bool>();
215
216 if (canPark)
217 {
219
220 // Initialize park position if not already set
221 // Default to zenith (RA=0, Dec=observer latitude)
222 if (!InitPark())
223 {
224 // Set default park position to zenith
225 SetAxis1Park(0);
226 SetAxis2Park(90);
227 LOG_INFO("Park position initialized to zenith");
228 }
229
230 // Get current park state
231 if (sendAlpacaGET("/atpark", response) && response.contains("Value"))
232 {
233 isParked = response["Value"].get<bool>();
234 SetParked(isParked);
235 }
236 }
237
238 // Get site location from device
239 double latitude = 0.0, longitude = 0.0;
240 bool locationValid = false;
241
242 if (sendAlpacaGET("/sitelatitude", response) && response.contains("Value"))
243 {
244 latitude = response["Value"].get<double>();
245 locationValid = true;
246 LOGF_INFO("Site latitude from device: %.6f°", latitude);
247 }
248 else
249 {
250 LOG_WARN("Failed to get site latitude from device");
251 }
252
253 if (sendAlpacaGET("/sitelongitude", response) && response.contains("Value"))
254 {
255 longitude = response["Value"].get<double>();
256 LOGF_INFO("Site longitude from device: %.6f°", longitude);
257 }
258 else
259 {
260 LOG_WARN("Failed to get site longitude from device");
261 locationValid = false;
262 }
263
264 // Site elevation is optional - default to 0 if the device doesn't report it
265 double elevation = 0.0;
266 if (sendAlpacaGET("/siteelevation", response) && response.contains("Value"))
267 {
268 elevation = response["Value"].get<double>();
269 LOGF_INFO("Site elevation from device: %.1fm", elevation);
270 }
271 else
272 {
273 LOG_WARN("Failed to get site elevation from device");
274 }
275
276 // Update INDI location property if we got valid data
277 if (locationValid)
278 {
279 // INDI uses: LOCATION_LATITUDE = latitude (positive north), LOCATION_LONGITUDE = longitude (positive east)
280 // Alpaca uses same convention
281 LocationNP[LOCATION_LATITUDE].setValue(latitude);
282 LocationNP[LOCATION_LONGITUDE].setValue(longitude);
283 LocationNP[LOCATION_ELEVATION].setValue(elevation);
284 LocationNP.setState(IPS_OK);
285 LocationNP.apply();
286
287 // Calculate and cache sin/cos for coordinate transformations
288 double latRad = latitude * M_PI / 180.0;
289 m_sinLat = sin(latRad);
290 m_cosLat = cos(latRad);
291
292 LOGF_INFO("Site location set: Lat=%.6f° Long=%.6f°", latitude, longitude);
293 }
294
295 // Get UTC date/time from device
296 if (sendAlpacaGET("/utcdate", response) && response.contains("Value"))
297 {
298 std::string utcDate = response["Value"].get<std::string>();
299 TimeTP[UTC].setText(utcDate.c_str());
300 TimeTP[OFFSET].setText("0");
301 TimeTP.setState(IPS_OK);
302 TimeTP.apply();
303 LOGF_INFO("Device UTC date/time: %s", utcDate.c_str());
304 }
305 else
306 {
307 LOG_WARN("Failed to get UTC date/time from device, using system time");
309 }
310
311 // Query tracking capability
312 if (sendAlpacaGET("/cansettracking", response) && response.contains("Value"))
313 {
314 if (response["Value"].get<bool>())
315 {
317 LOG_INFO("Telescope supports tracking control - TELESCOPE_TRACK_STATE enabled");
318 }
319 else
320 {
321 LOG_INFO("Telescope does not support tracking control");
322 }
323 }
324 else
325 {
326 LOG_WARN("Failed to query tracking capability from device");
327 }
328
329 // Query whether the mount supports the non-blocking slewtotargetasync/slewtoaltazasync
330 // commands. If not, fall back to the blocking slewtotarget/slewtoaltaz commands.
331 if (sendAlpacaGET("/canslewasync", response) && response.contains("Value"))
332 m_CanSlewAsync = response["Value"].get<bool>();
333 else
334 m_CanSlewAsync = false;
335 LOGF_INFO("Telescope supports async slew: %s", m_CanSlewAsync ? "Yes" : "No");
336
337 // Query the list of supported tracking rates (Alpaca DriveRate enum: 0=Sidereal,
338 // 1=Lunar, 2=Solar, 3=King) and build the TrackModeSP property accordingly.
339 m_TrackModeAlpacaRates.clear();
340 TrackModeSP.resize(0);
341 if (sendAlpacaGET("/trackingrates", response) && response.contains("Value") && response["Value"].is_array())
342 {
343 static const struct { int rate; const char *name; const char *label; } alpacaRates[] =
344 {
345 {0, "TRACK_SIDEREAL", "Sidereal"},
346 {1, "TRACK_LUNAR", "Lunar"},
347 {2, "TRACK_SOLAR", "Solar"},
348 {3, "TRACK_KING", "King"},
349 };
350
351 for (const auto &entry : alpacaRates)
352 {
353 for (const auto &value : response["Value"])
354 {
355 if (value.get<int>() == entry.rate)
356 {
357 AddTrackMode(entry.name, entry.label, entry.rate == 0);
358 m_TrackModeAlpacaRates.push_back(entry.rate);
359 break;
360 }
361 }
362 }
363 }
364
365 if (!m_TrackModeAlpacaRates.empty())
366 {
368 LOGF_INFO("Telescope supports %zu tracking rate(s)", m_TrackModeAlpacaRates.size());
369
370 // Sync the current tracking rate
371 if (sendAlpacaGET("/trackingrate", response) && response.contains("Value"))
372 {
373 int currentRate = response["Value"].get<int>();
374 for (size_t i = 0; i < m_TrackModeAlpacaRates.size(); i++)
375 {
376 if (m_TrackModeAlpacaRates[i] == currentRate)
377 {
378 TrackModeSP.reset();
379 TrackModeSP[i].setState(ISS_ON);
380 break;
381 }
382 }
383 }
384 }
385 else
386 {
387 LOG_WARN("Failed to query supported tracking rates from device");
388 }
389
390 // Query support for custom (offset) tracking rates
391 m_CanSetRaRate = sendAlpacaGET("/cansetrightascensionrate", response) && response.contains("Value")
392 && response["Value"].get<bool>();
393 m_CanSetDecRate = sendAlpacaGET("/cansetdeclinationrate", response) && response.contains("Value")
394 && response["Value"].get<bool>();
395
396 if (m_CanSetRaRate && m_CanSetDecRate)
397 {
399 LOG_INFO("Telescope supports custom tracking rates - TELESCOPE_TRACK_RATE enabled");
400 }
401 else
402 {
403 LOG_INFO("Telescope does not support custom tracking rates");
404 }
405
406 // Get initial coordinates
408
409 LOG_INFO("alpaca connected successfully");
410 return true;
411}
412
414{
415 nlohmann::json response;
416
417 // Get RA/Dec
418 double newRA = m_currentRA, newDec = m_currentDEC;
419
420 // Get current coordinates from Alpaca API
421 bool raUpdated = false, decUpdated = false;
422 if (sendAlpacaGET("/rightascension", response) && response.contains("Value"))
423 {
424 newRA = response["Value"].get<double>();
425 raUpdated = true;
426 }
427 else
428 {
429 LOG_WARN("Failed to get RA from Alpaca API");
430 }
431
432 if (sendAlpacaGET("/declination", response) && response.contains("Value"))
433 {
434 newDec = response["Value"].get<double>();
435 decUpdated = true;
436 }
437 else
438 {
439 LOG_WARN("Failed to get Dec from Alpaca API");
440 }
441
442 // Update current coordinates
443 if (raUpdated && decUpdated)
444 {
445 m_currentRA = newRA;
446 m_currentDEC = newDec;
447
448 // Always call NewRaDec to update client display
449 // This is critical during slewing to show real-time position updates
450 NewRaDec(m_currentRA, m_currentDEC);
451 }
452 else
453 {
454 LOG_WARN("NewRaDec NOT called - coordinate update failed");
455 }
456
457 // Get slewing state
458 if (sendAlpacaGET("/slewing", response) && response.contains("Value"))
459 isSlewing = response["Value"].get<bool>();
460
461 // Get tracking state
462 if (sendAlpacaGET("/tracking", response) && response.contains("Value"))
463 isTracking = response["Value"].get<bool>();
464
465 // Keep TrackModeSP in sync with the device's current tracking rate
466 if (HasTrackMode() && sendAlpacaGET("/trackingrate", response) && response.contains("Value"))
467 {
468 int currentRate = response["Value"].get<int>();
469 int currentIndex = TrackModeSP.findOnSwitchIndex();
470 for (size_t i = 0; i < m_TrackModeAlpacaRates.size(); i++)
471 {
472 if (m_TrackModeAlpacaRates[i] == currentRate && static_cast<int>(i) != currentIndex)
473 {
474 TrackModeSP.reset();
475 TrackModeSP[i].setState(ISS_ON);
476 TrackModeSP.setState(IPS_OK);
477 TrackModeSP.apply();
478 break;
479 }
480 }
481 }
482
483 // Get park state
484 if (sendAlpacaGET("/atpark", response) && response.contains("Value"))
485 {
486 bool parked = response["Value"].get<bool>();
487 if (parked != isParked)
488 {
489 isParked = parked;
490 SetParked(isParked);
491 }
492 }
493
494 // Update telescope state
496 {
497 // If we're parking and slewing stopped, we've reached park position
498 if (!isSlewing)
499 {
501 LOG_INFO("Parking complete - telescope at park position");
502 }
503 // else keep SCOPE_PARKING state while slewing to park position
504 }
505 else if (isSlewing)
507 else if (isTracking)
509 else if (isParked)
511 else
513
514 return true;
515}
516
518{
519 // Check if telescope is parked - must unpark before slewing
520 if (isParked)
521 {
522 LOG_ERROR("Cannot GoTo while parked. Please unpark the telescope first.");
523 return false;
524 }
525
526 LOGF_INFO("GoTo command: RA=%f Dec=%f", ra, dec);
527
528 // Use ASCOM Alpaca pattern: set target coordinates first, then slew
529 // Step 1: Set target RA
530 nlohmann::json response;
531 nlohmann::json raRequest;
532 raRequest["TargetRightAscension"] = ra;
533 if (!sendAlpacaPUT("/targetrightascension", raRequest, response))
534 {
535 LOG_ERROR("Failed to set target RA");
536 return false;
537 }
538
539 // Step 2: Set target Dec
540 nlohmann::json decRequest;
541 decRequest["TargetDeclination"] = dec;
542 if (!sendAlpacaPUT("/targetdeclination", decRequest, response))
543 {
544 LOG_ERROR("Failed to set target Dec");
545 return false;
546 }
547
548 // Step 3: Start slew to target. Prefer the non-blocking /slewtotargetasync if the
549 // device supports it, since /slewtotarget blocks the HTTP request (and therefore
550 // this driver) until the slew completes.
551 nlohmann::json emptyRequest;
552 const char *slewEndpoint = m_CanSlewAsync ? "/slewtotargetasync" : "/slewtotarget";
553 if (!sendAlpacaPUT(slewEndpoint, emptyRequest, response))
554 {
555 LOG_ERROR("Failed to send GoTo command");
556 return false;
557 }
558
560 LOGF_INFO("GoTo command sent (%s) - slewing to target", m_CanSlewAsync ? "async" : "sync");
561 return true;
562}
563
565{
566 nlohmann::json request, response;
567 request["RightAscension"] = ra;
568 request["Declination"] = dec;
569
570 if (!sendAlpacaPUT("/synctocoordinates", request, response))
571 {
572 LOG_ERROR("Failed to sync");
573 return false;
574 }
575
576 LOG_INFO("Sync successful");
577 return true;
578}
579
581{
582 nlohmann::json request, response;
583
584 // Check if we're parking - parking cannot be aborted via AbortSlew
586 {
587 LOG_WARN("Cannot abort parking operation - park must complete");
588 return false;
589 }
590
591 if (!sendAlpacaPUT("/abortslew", request, response))
592 {
593 LOG_ERROR("Failed to abort");
594 return false;
595 }
596
598 LOG_INFO("Slew aborted");
599 return true;
600}
601
603{
604 nlohmann::json request, response;
605
606 // Abort any ongoing slew first
607 if (isSlewing)
608 {
609 LOG_INFO("Aborting slew before park");
610 nlohmann::json abortReq, abortResp;
611 sendAlpacaPUT("/abortslew", abortReq, abortResp);
612 }
613
614 LOG_INFO("Sending park command to Alpaca device");
615
616 // Use Alpaca park command
617 if (!sendAlpacaPUT("/park", request, response))
618 {
619 LOG_ERROR("Failed to send park command to Alpaca device");
620 return false;
621 }
622
623 // Mark as parked - set state to PARKED not PARKING since command is sent
624 isParked = true;
625 SetParked(true);
627 LOG_INFO("Park command sent - telescope parked");
628
629 return true;
630}
631
633{
634 nlohmann::json request, response;
635
636 LOG_INFO("Sending unpark command to Alpaca device");
637
638 // Use Alpaca unpark command
639 if (!sendAlpacaPUT("/unpark", request, response))
640 {
641 LOG_ERROR("Failed to send unpark command to Alpaca device");
642 return false;
643 }
644
645 // Immediately mark as unparked so INDI allows motion commands
646 // ReadScopeStatus will sync with actual device state
647 isParked = false;
648 SetParked(false);
650 LOG_INFO("Unpark command sent - telescope unparked");
651
652 return true;
653}
654
656{
657 // Save current RA/Dec position as park position
658 // This allows user to park at current position via "Park Options -> Set Current"
659
660 // Get current coordinates
661 nlohmann::json response;
662 double ra = 0, dec = 0;
663
664 if (sendAlpacaGET("/rightascension", response) && response.contains("Value"))
665 {
666 ra = response["Value"].get<double>();
667 }
668 else
669 {
670 LOG_ERROR("Failed to get current RA for SetCurrentPark");
671 return false;
672 }
673
674 if (sendAlpacaGET("/declination", response) && response.contains("Value"))
675 {
676 dec = response["Value"].get<double>();
677 }
678 else
679 {
680 LOG_ERROR("Failed to get current Dec for SetCurrentPark");
681 return false;
682 }
683
684 // Save current position as park position
685 SetAxis1Park(ra); // RA in hours
686 SetAxis2Park(dec); // Dec in degrees
687
688 LOGF_INFO("Park position set to current coordinates: RA=%.6f hours, Dec=%.6f degrees", ra, dec);
689
690 return true;
691}
692
694{
695 nlohmann::json request, response;
696 request["Tracking"] = enabled;
697
698 if (!sendAlpacaPUT("/tracking", request, response))
699 {
700 LOGF_ERROR("Failed to %s tracking", enabled ? "enable" : "disable");
701 return false;
702 }
703
704 isTracking = enabled;
705 LOGF_INFO("Tracking %s", enabled ? "enabled" : "disabled");
706 return true;
707}
708
710{
711 if (mode >= m_TrackModeAlpacaRates.size())
712 {
713 LOG_ERROR("Invalid track mode index");
714 return false;
715 }
716
717 nlohmann::json request, response;
718 request["TrackingRate"] = m_TrackModeAlpacaRates[mode];
719
720 if (!sendAlpacaPUT("/trackingrate", request, response))
721 {
722 LOG_ERROR("Failed to set track mode");
723 return false;
724 }
725
726 LOGF_INFO("Track mode set to %s", TrackModeSP[mode].getLabel());
727 return true;
728}
729
730bool alpacaTelescopeDriver::SetTrackRate(double raRate, double deRate)
731{
732 if (!m_CanSetRaRate || !m_CanSetDecRate)
733 {
734 LOG_WARN("Custom tracking rates are not supported by this telescope");
735 return false;
736 }
737
738 nlohmann::json request, response;
739
740 // Alpaca's RightAscensionRate is expressed in seconds of RA per sidereal second,
741 // while INDI's raRate is in arcseconds/second. 1 second of RA = 15 arcseconds, and
742 // the sidereal/solar second difference (~0.27%) is negligible for this offset.
743 request["RightAscensionRate"] = raRate / 15.0;
744 if (!sendAlpacaPUT("/rightascensionrate", request, response))
745 {
746 LOG_ERROR("Failed to set RA tracking rate");
747 return false;
748 }
749
750 request.clear();
751 request["DeclinationRate"] = deRate;
752 if (!sendAlpacaPUT("/declinationrate", request, response))
753 {
754 LOG_ERROR("Failed to set DEC tracking rate");
755 return false;
756 }
757
758 LOGF_INFO("Custom tracking rate set: RA=%.6f arcsec/s, DEC=%.6f arcsec/s", raRate, deRate);
759 return true;
760}
761
763{
764 nlohmann::json request, response;
765
766 // Secondary axis (Dec/Altitude): 1
767 // Positive rate = North/Up, Negative rate = South/Down
768 request["Axis"] = 1;
769
770 if (command == MOTION_START)
771 {
772 // Use moderate rate for manual movement (0.5 deg/sec)
773 // TODO: Query /axisrates to get valid rates and use client-selected slew rate
774 double rate = (dir == DIRECTION_NORTH) ? 0.5 : -0.5;
775 request["Rate"] = rate;
776 LOGF_INFO("Moving %s at rate %.2f deg/sec", (dir == DIRECTION_NORTH) ? "North" : "South", rate);
777 }
778 else
779 {
780 request["Rate"] = 0.0;
781 LOG_INFO("Stopping NS motion");
782 }
783
784 if (!sendAlpacaPUT("/moveaxis", request, response))
785 {
786 LOG_ERROR("Failed to move NS");
787 return false;
788 }
789
790 // Log response for debugging
791 if (response.contains("ErrorNumber"))
792 {
793 int errNum = response["ErrorNumber"].get<int>();
794 if (errNum != 0)
795 {
796 LOGF_WARN("MoveAxis NS returned error %d: %s", errNum,
797 response.value("ErrorMessage", "Unknown error").c_str());
798 }
799 }
800
801 return true;
802}
803
805{
806 nlohmann::json request, response;
807
808 // Primary axis (RA/Azimuth): 0
809 // Positive rate = East/Right, Negative rate = West/Left
810 request["Axis"] = 0;
811
812 if (command == MOTION_START)
813 {
814 // Use moderate rate for manual movement (0.5 deg/sec)
815 // TODO: Query /axisrates to get valid rates and use client-selected slew rate
816 double rate = (dir == DIRECTION_EAST) ? 0.5 : -0.5;
817 request["Rate"] = rate;
818 LOGF_INFO("Moving %s at rate %.2f deg/sec", (dir == DIRECTION_EAST) ? "East" : "West", rate);
819 }
820 else
821 {
822 request["Rate"] = 0.0;
823 LOG_INFO("Stopping WE motion");
824 }
825
826 if (!sendAlpacaPUT("/moveaxis", request, response))
827 {
828 LOG_ERROR("Failed to move WE");
829 return false;
830 }
831
832 // Log response for debugging
833 if (response.contains("ErrorNumber"))
834 {
835 int errNum = response["ErrorNumber"].get<int>();
836 if (errNum != 0)
837 {
838 LOGF_WARN("MoveAxis WE returned error %d: %s", errNum,
839 response.value("ErrorMessage", "Unknown error").c_str());
840 }
841 }
842
843 return true;
844}
845
847{
849 return true;
850}
851
852bool alpacaTelescopeDriver::updateLocation(double latitude, double longitude, double elevation)
853{
854 // Update location on the Alpaca device
855 nlohmann::json request, response;
856
857 // Set latitude
858 request["SiteLatitude"] = latitude;
859 if (!sendAlpacaPUT("/sitelatitude", request, response))
860 {
861 LOG_ERROR("Failed to set site latitude on device");
862 return false;
863 }
864
865 // Set longitude
866 request.clear();
867 request["SiteLongitude"] = longitude;
868 if (!sendAlpacaPUT("/sitelongitude", request, response))
869 {
870 LOG_ERROR("Failed to set site longitude on device");
871 return false;
872 }
873
874 // Set elevation (not all Alpaca devices support this, so just warn on failure)
875 request.clear();
876 request["SiteElevation"] = elevation;
877 if (!sendAlpacaPUT("/siteelevation", request, response))
878 LOG_WARN("Failed to set site elevation on device");
879
880 // Calculate and cache sin/cos for coordinate transformations
881 double latRad = latitude * M_PI / 180.0;
882 m_sinLat = sin(latRad);
883 m_cosLat = cos(latRad);
884
885 LOGF_INFO("Site location updated: Lat=%.6f° Long=%.6f°", latitude, longitude);
886
887 // Call base class to update INDI properties
888 return INDI::Telescope::updateLocation(latitude, longitude, elevation);
889}
890
891bool alpacaTelescopeDriver::updateTime(ln_date *utc, double utc_offset)
892{
893 INDI_UNUSED(utc_offset);
894
895 // Alpaca utcdate is always UTC, expressed as an ISO 8601 string
896 char isoDate[32];
897 snprintf(isoDate, sizeof(isoDate), "%04d-%02d-%02dT%02d:%02d:%06.3fZ",
898 utc->years, utc->months, utc->days, utc->hours, utc->minutes, utc->seconds);
899
900 nlohmann::json request, response;
901 request["UTCDate"] = isoDate;
902 if (!sendAlpacaPUT("/utcdate", request, response))
903 {
904 LOG_ERROR("Failed to set UTC date/time on device");
905 return false;
906 }
907
908 return true;
909}
910
911// Alpaca helper methods
912std::string alpacaTelescopeDriver::getAlpacaURL(const std::string& endpoint)
913{
914 return "/api/v1/telescope/" + std::to_string(m_DeviceNumber) + endpoint;
915}
916
917bool alpacaTelescopeDriver::sendAlpacaGET(const std::string& endpoint, nlohmann::json& response)
918{
919 if (!httpClient)
920 {
921 LOG_ERROR("HTTP client not initialized");
922 return false;
923 }
924
925 std::string url = getAlpacaURL(endpoint);
926 url += "?ClientID=" + std::to_string(m_ClientID) +
927 "&ClientTransactionID=" + std::to_string(getTransactionId());
928
929 auto result = httpClient->Get(url.c_str());
930
931 if (!result)
932 {
933 LOGF_ERROR("GET %s failed: %s", endpoint.c_str(),
934 httplib::to_string(result.error()).c_str());
935 return false;
936 }
937
938 if (result->status != 200)
939 {
940 LOGF_ERROR("GET %s HTTP %d", endpoint.c_str(), result->status);
941 return false;
942 }
943
944 try
945 {
946 response = nlohmann::json::parse(result->body);
947
948 if (response.contains("ErrorNumber") && response["ErrorNumber"].get<int>() != 0)
949 {
950 LOGF_ERROR("Alpaca error %s: %d - %s", endpoint.c_str(),
951 response["ErrorNumber"].get<int>(),
952 response.value("ErrorMessage", "").c_str());
953 return false;
954 }
955
956 return true;
957 }
958 catch (const nlohmann::json::exception& e)
959 {
960 LOGF_ERROR("JSON parse error %s: %s", endpoint.c_str(), e.what());
961 return false;
962 }
963}
964
965bool alpacaTelescopeDriver::sendAlpacaPUT(const std::string& endpoint, const nlohmann::json& request,
966 nlohmann::json& response)
967{
968 if (!httpClient)
969 {
970 LOG_ERROR("HTTP client not initialized");
971 return false;
972 }
973
974 std::string url = getAlpacaURL(endpoint);
975
976 // Build form data - Alpaca expects form-encoded parameters
977 httplib::Params params;
978
979 for (auto& [key, value] : request.items())
980 {
981 if (value.is_string())
982 params.emplace(key, value.get<std::string>());
983 else if (value.is_boolean())
984 params.emplace(key, value.get<bool>() ? "true" : "false");
985 else if (value.is_number_integer())
986 params.emplace(key, std::to_string(value.get<int>()));
987 else if (value.is_number())
988 params.emplace(key, std::to_string(value.get<double>()));
989 }
990
991 params.emplace("ClientID", std::to_string(m_ClientID));
992 params.emplace("ClientTransactionID", std::to_string(getTransactionId()));
993
994 auto result = httpClient->Put(url.c_str(), params);
995
996 if (!result)
997 {
998 // Some Alpaca devices (like Seestar) close connection immediately after
999 // receiving /slewtotarget command. Log as debug instead of error.
1000 if (endpoint == "/slewtotarget")
1001 {
1002 LOGF_DEBUG("PUT %s: connection closed (expected for some devices)", endpoint.c_str());
1003 }
1004 else
1005 {
1006 LOGF_ERROR("PUT %s failed: %s", endpoint.c_str(),
1007 httplib::to_string(result.error()).c_str());
1008 }
1009 return false;
1010 }
1011
1012 if (result->status != 200)
1013 {
1014 LOGF_ERROR("PUT %s HTTP %d", endpoint.c_str(), result->status);
1015 return false;
1016 }
1017
1018 try
1019 {
1020 response = nlohmann::json::parse(result->body);
1021
1022 if (response.contains("ErrorNumber") && response["ErrorNumber"].get<int>() != 0)
1023 {
1024 int errorNum = response["ErrorNumber"].get<int>();
1025 std::string errorMsg = response.value("ErrorMessage", "");
1026 LOGF_ERROR("Alpaca error %s: %d - %s", endpoint.c_str(), errorNum, errorMsg.c_str());
1027 return false;
1028 }
1029
1030 return true;
1031 }
1032 catch (const nlohmann::json::exception& e)
1033 {
1034 LOGF_ERROR("JSON parse error %s: %s", endpoint.c_str(), e.what());
1035 return false;
1036 }
1037}
1038
1039void ISGetProperties(const char *dev)
1040{
1041 alpaca->ISGetProperties(dev);
1042}
1043
1044void ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
1045{
1046 alpaca->ISNewSwitch(dev, name, states, names, n);
1047}
1048
1049void ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n)
1050{
1051 alpaca->ISNewText(dev, name, texts, names, n);
1052}
1053
1054void ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n)
1055{
1056 alpaca->ISNewNumber(dev, name, values, names, n);
1057}
1058
1059void ISNewBLOB(const char *dev, const char *name, int sizes[], int blobsizes[], char *blobs[], char *formats[],
1060 char *names[], int n)
1061{
1062 alpaca->ISNewBLOB(dev, name, sizes, blobsizes, blobs, formats, names, n);
1063}
1064
1066{
1067 alpaca->ISSnoopDevice(root);
1068}
bool isConnected() const
void setVersion(uint16_t vMajor, uint16_t vMinor)
Set driver version information to be defined in DRIVER_INFO property as vMajor.vMinor.
virtual bool deleteProperty(const char *propertyName)
Delete a property and unregister it. It will also be deleted from all clients.
void defineProperty(INumberVectorProperty *property)
uint32_t getCurrentPollingPeriod() const
getCurrentPollingPeriod Return the current polling period.
int SetTimer(uint32_t ms)
Set a timer to call the function TimerHit after ms milliseconds.
void addDebugControl()
Add Debug control to the driver.
static Logger & getInstance()
Method to get a reference to the object (i.e., Singleton) It is a static method.
int addDebugLevel(const char *debugLevelName, const char *LoggingLevelName)
Adds a new debugging level to the driver.
TelescopeStatus TrackState
void SetAxis1Park(double value)
SetRAPark Set current RA/AZ parking position. The data park file (stored in ~/.indi/ParkData....
void SetAxis1ParkDefault(double steps)
SetRAPark Set default RA/AZ parking position.
void SetTelescopeCapability(uint32_t cap, uint8_t slewRateCount)
SetTelescopeCapability sets the Telescope capabilities. All capabilities must be initialized.
virtual bool initProperties() override
Called to initialize basic properties required all the time.
void setTelescopeConnection(const uint8_t &value)
setTelescopeConnection Set telescope connection mode. Child class should call this in the constructor...
virtual int AddTrackMode(const char *name, const char *label, bool isDefault=false)
AddTrackMode.
virtual bool updateProperties() override
Called when connected state changes, to add/remove properties.
virtual void SetParked(bool isparked)
SetParked Change the mount parking status. The data park file (stored in ~/.indi/ParkData....
Connection::TCP * tcpConnection
virtual bool updateLocation(double latitude, double longitude, double elevation)
Update telescope location settings.
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.
bool InitPark()
InitPark Loads parking data (stored in ~/.indi/ParkData.xml) that contains parking status and parking...
virtual bool saveConfigItems(FILE *fp) override
saveConfigItems Save specific properties in the provide config file handler. Child class usually over...
void SetAxis2Park(double steps)
SetDEPark Set current DEC/ALT parking position. The data park file (stored in ~/.indi/ParkData....
void setMountType(TelescopeMountType type)
setMountType Report the mount type in TELESCOPE_MOUNT_TYPE. Drivers call it when the type is fixed by...
void SetParkDataType(TelescopeParkData type)
setParkDataType Sets the type of parking data stored in the park data file and presented to the user.
void SetAxis2ParkDefault(double steps)
SetDEParkDefault Set default DEC/ALT parking position.
virtual bool Goto(double ra, double dec) override
Move the scope to the supplied RA and DEC coordinates.
virtual bool Disconnect() override
Disconnect from device.
virtual bool SetTrackEnabled(bool enabled) override
SetTrackEnabled Engages or disengages mount tracking. If there are no tracking modes available,...
virtual bool ReadScopeStatus() override
Read telescope status.
virtual bool updateLocation(double latitude, double longitude, double elevation) override
Update telescope location settings.
virtual bool Abort() override
Abort any telescope motion including tracking if possible.
virtual const char * getDefaultName() override
virtual bool Connect() override
Connect to the device. INDI::DefaultDevice implementation connects to appropriate connection interfac...
virtual bool UnPark() override
Unpark the telescope if already parked.
virtual bool MoveWE(INDI_DIR_WE dir, TelescopeMotionCommand command) override
Move the telescope in the direction dir.
virtual bool initProperties() override
Called to initialize basic properties required all the time.
virtual bool saveConfigItems(FILE *fp) override
saveConfigItems Save specific properties in the provide config file handler. Child class usually over...
virtual bool Sync(double ra, double dec) override
Set the telescope current RA and DEC coordinates to the supplied RA and DEC coordinates.
virtual bool Handshake() override
perform handshake with device to check communication
virtual bool SetCurrentPark() override
SetCurrentPark Set current coordinates/encoders value as the desired parking position.
virtual bool SetTrackMode(uint8_t mode) override
SetTrackMode Set active tracking mode. Do not change track state.
virtual bool updateTime(ln_date *utc, double utc_offset) override
Update telescope time, date, and UTC offset.
virtual bool updateProperties() override
Called when connected state changes, to add/remove properties.
virtual bool MoveNS(INDI_DIR_NS dir, TelescopeMotionCommand command) override
Start or Stop the telescope motion in the direction dir.
virtual bool Park() override
Park the telescope to its home position.
virtual bool SetTrackRate(double raRate, double deRate) override
SetTrackRate Set custom tracking rates.
friend class ::nlohmann::detail::exception
const char * OPTIONS_TAB
OPTIONS_TAB Where all the driver's options are located. Those may include auxiliary controls,...
#define M_PI
Definition dsp.h:52
INDI::PropertySwitch TrackModeSP
INDI::PropertyText TimeTP
INDI::PropertyNumber LocationNP
INDI::PropertyNumber ParkPositionNP
double ra
double dec
std::unique_ptr< alpacaTelescopeDriver > alpaca(new alpacaTelescopeDriver())
void ISNewBLOB(const char *dev, const char *name, int sizes[], int blobsizes[], char *blobs[], char *formats[], char *names[], int n)
Update data of an existing blob vector property.
void ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
Update the value of an existing switch vector property.
void ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n)
Update the value of an existing text vector property.
void ISGetProperties(const char *dev)
Get Device Properties.
void ISSnoopDevice(XMLEle *root)
Function defined by Drivers that is called when another Driver it is snooping (by having previously c...
void ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n)
ISState
Switch state.
Definition indiapi.h:148
@ ISS_ON
Definition indiapi.h:150
@ IP_RO
Definition indiapi.h:182
@ IPS_IDLE
Definition indiapi.h:159
@ IPS_OK
Definition indiapi.h:160
@ AXIS_DE
@ AXIS_RA
INDI_DIR_WE
@ DIRECTION_EAST
INDI_DIR_NS
@ DIRECTION_NORTH
Implementations for common driver routines.
#define INDI_UNUSED(x)
Definition indidevapi.h:132
*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 getDeviceName
struct xml_ele_ XMLEle
Definition lilxml.h:81
std::string to_string(Error error)
Definition httplib.h:9275
std::multimap< std::string, std::string > Params
Definition httplib.h:609
basic_json<> json
default specialization