Instrument Neutral Distributed Interface INDI 2.2.5
alpaca_dome.cpp
Go to the documentation of this file.
1/*******************************************************************************
2 Copyright(c) 2026 Philippe Bazart, Jérémie Klein. All rights reserved.
3 With partial reuse of code by Jasem Mutlaq, originally written for the
4 Alpaca CCD INDI driver.
5
6 ASCOM Alpaca Dome INDI Driver
7
8 This program is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 2 of the License, or (at your option)
11 any later version.
12
13 This program is distributed in the hope that it will be useful, but WITHOUT
14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
16 more details.
17
18 You should have received a copy of the GNU Library General Public License
19 along with this library; see the file COPYING.LIB. If not, write to
20 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 Boston, MA 02110-1301, USA.
22
23 The full GNU General Public License is included in this distribution in the
24 file called LICENSE.
25*******************************************************************************/
26
27#include "alpaca_dome.h"
28
29#include <httplib.h>
30#include <string.h>
31#include <chrono>
32#include <thread>
33
34#ifdef _USE_SYSTEM_JSONLIB
35#include <nlohmann/json.hpp>
36#else
37#include <indijson.hpp>
38#endif
39
40// We declare an auto pointer to AlpacaDome
41std::unique_ptr<AlpacaDome> alpaca_dome(new AlpacaDome());
42
49
51
53{
54 if (!isConnected())
55 return;
56
57 updateStatus();
59}
60
62
63void AlpacaDome::ISGetProperties(const char *dev)
64{
66
67 // Always define these properties
71}
72
74
75bool AlpacaDome::ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
76{
77 if (dev != nullptr && isDeviceNameMatch(dev))
78 {
79 if (OperationSP.isNameMatch(name))
80 {
81 const char *requestedOperation = IUFindOnSwitchName(states, names, n);
82 if (OperationSP[OPERATION_FIND_HOME].isNameMatch(requestedOperation))
83 {
84 IPState rc = FindHome();
85 if (rc != IPS_ALERT)
86 {
87 OperationSP.reset();
90 }
91 OperationSP.setState(rc);
92 }
93 else if (OperationSP[OPERATION_CALIBRATE].isNameMatch(requestedOperation))
94 {
95 IPState rc = Calibrate();
96 if (rc != IPS_ALERT)
97 {
98 OperationSP.reset();
101 }
102 OperationSP.setState(rc);
103 }
104
105 OperationSP.apply();
106 return true;
107 }
108 }
109
110 return INDI::Dome::ISNewSwitch(dev, name, states, names, n);
111}
112
114
115bool AlpacaDome::ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n)
116{
117 if (dev != nullptr && isDeviceNameMatch(dev))
118 {
119 if (ConnectionSettingsNP.isNameMatch(name))
120 {
121 ConnectionSettingsNP.update(values, names, n);
123 ConnectionSettingsNP.apply();
124 // Save configuration after update
125 saveConfig();
126 LOG_INFO("Connection settings updated.");
127 return true;
128 }
129 else if (DeviceNumberNP.isNameMatch(name))
130 {
131 DeviceNumberNP.update(values, names, n);
132 DeviceNumberNP.setState(IPS_OK);
133 DeviceNumberNP.apply();
134 // Save configuration after update
135 saveConfig();
136 LOG_INFO("Alpaca device number updated.");
137 return true;
138 }
139 }
140
141 return INDI::Dome::ISNewNumber(dev, name, values, names, n);
142}
143
145
146bool AlpacaDome::ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n)
147{
148 if (dev != nullptr && isDeviceNameMatch(dev) && ServerAddressTP.isNameMatch(name))
149 {
150 ServerAddressTP.update(texts, names, n);
151 ServerAddressTP.setState(IPS_OK);
152 ServerAddressTP.apply();
153 // Save configuration after update
154 saveConfig();
155 return true;
156 }
157
158 return INDI::Dome::ISNewText(dev, name, texts, names, n);
159}
160
162
164{
165 return "Alpaca Dome";
166}
167
169
171{
173
174 // Try to load server address from saved config (mirrors TCP plugin pattern).
175 // m_ConfigHost/m_ConfigPort are empty if no config was previously saved.
176 char configHost[MAXINDINAME] = {0};
177 char configPort[MAXINDINAME] = {0};
178 if (IUGetConfigText(getDeviceName(), "SERVER_ADDRESS", "HOST", configHost, MAXINDINAME) == 0)
179 m_ConfigHost = configHost;
180 if (IUGetConfigText(getDeviceName(), "SERVER_ADDRESS", "PORT", configPort, MAXINDINAME) == 0)
181 m_ConfigPort = configPort;
182
183 // Setup server address properties
184 ServerAddressTP[HOST].fill("HOST", "Host", m_ConfigHost.c_str());
185 ServerAddressTP[PORT].fill("PORT", "Port", m_ConfigPort.c_str());
186 ServerAddressTP.fill(getDeviceName(), "SERVER_ADDRESS", "Server", CONNECTION_TAB, IP_RW, 60, IPS_IDLE);
187 ServerAddressTP.load();
188
189 // Setup device number property
190 DeviceNumberNP[0].fill("DEVICE_NUMBER", "Device Number", "%.0f", 0, 10, 1, 0);
191 DeviceNumberNP.fill(getDeviceName(), "DEVICE_NUMBER", "Alpaca Device", CONNECTION_TAB, IP_RW, 60, IPS_IDLE);
192 DeviceNumberNP.load();
193
194 // Setup connection settings properties
195 ConnectionSettingsNP[TIMEOUT].fill("TIMEOUT", "Connection timeout (ms)", "%.0f", 1, 10000, 100, 5000);
196 ConnectionSettingsNP[RW_TIMEOUT].fill("RW_TIMEOUT", "Read/Write timeout (ms)", "%.0f", 1, 5000, 100, 1000);
197 ConnectionSettingsNP.fill(getDeviceName(), "CONNECTION_SETTINGS", "Connection", CONNECTION_TAB, IP_RW, 60, IPS_IDLE);
199
200 // Device and driver Info property
201 InfoTP[INFO_DEVICE_NAME].fill("INFO_DEVICE_NAME", "Name", "");
202 InfoTP[INFO_DESCRIPTION].fill("INFO_DESCRIPTION", "Description", "");
203 InfoTP[INFO_DRIVER_INFO].fill("INFO_DRIVER_INFO", "Driver", "");
204 InfoTP[INFO_DRIVER_VERSION].fill("INFO_DRIVER_VERSION", "Driver Version", "");
205 InfoTP[INFO_INTERFACE_VERSION].fill("INFO_INTERFACE_VERSION", "ASCOM Dome Interface Version", "");
206 InfoTP.fill(getDeviceName(), "DEVICE_INFO", "Alpaca Device Info", INFO_TAB, IP_RO, 60, IPS_IDLE);
207
208 // Configuring operations about positionning and home definition
209 OperationSP[OPERATION_FIND_HOME].fill("OPERATION_FIND_HOME", "Find Home", ISS_OFF);
210 OperationSP[OPERATION_CALIBRATE].fill("OPERATION_CALIBRATE", "Calibrate", ISS_OFF);
211 OperationSP.fill(getDeviceName(), "OPERATION", "Operation", MAIN_CONTROL_TAB, IP_RW, ISR_ATMOST1, 0, IPS_IDLE);
212
215
216 // Default server address.
217 setDefaultServerAddress("alpaca.local", "7843");
218
219 return true;
220}
221
223
225{
227
228 if (isConnected())
229 {
230 // State properties
231 if (CanFindHome() || CanCalibrate())
232 {
234 }
235
236 // Device Info properties
238 InfoTP[INFO_DEVICE_NAME].setText(m_DeviceName.c_str());
239 InfoTP[INFO_DESCRIPTION].setText(m_Description.c_str());
240 InfoTP[INFO_DRIVER_INFO].setText(m_DriverInfo.c_str());
241 InfoTP[INFO_DRIVER_VERSION].setText(m_DriverVersion.c_str());
242 InfoTP[INFO_INTERFACE_VERSION].setText(std::to_string(m_InterfaceVersion).c_str());
243 InfoTP.setState(IPS_OK);
244 InfoTP.apply();
245
246 LOG_INFO("Alpaca dome is ready for operation.");
247 }
248 else
249 {
252
253 LOG_INFO("Alpaca dome is disconnected.");
254 }
255
256 return true;
257}
258
260
262{
264
265 ServerAddressTP.save(fp);
266 DeviceNumberNP.save(fp);
267 ConnectionSettingsNP.save(fp);
268
269 return true;
270}
271
273
275{
276 if (ServerAddressTP[HOST].isEmpty() || ServerAddressTP[PORT].isEmpty())
277 {
278 LOG_ERROR("Server address or port is not set.");
279 return false;
280 }
281
282 // Initialize HTTP client
283 int connectionTimeout = static_cast<int>(ConnectionSettingsNP[TIMEOUT].getValue());
284 int timeout = static_cast<int>(ConnectionSettingsNP[RW_TIMEOUT].getValue());
285 httpClient = std::make_unique<httplib::Client>(ServerAddressTP[HOST].getText(), std::stoi(ServerAddressTP[PORT].getText()));
286 httpClient->set_connection_timeout(std::chrono::milliseconds(connectionTimeout));
287 httpClient->set_read_timeout(std::chrono::milliseconds(timeout));
288 httpClient->set_write_timeout(std::chrono::milliseconds(timeout));
289
290 // Test connection by getting camera status
291 bool connected = false;
292 if (!alpacaGetBool("/connected", connected))
293 {
294 LOG_ERROR("Failed to connect to Alpaca dome. Please check server address and port.");
295 return false;
296 }
297
298 // Connect to the device if not already connected
299 if (!connected)
300 {
301 if (!alpacaConnect())
302 return false;
303 }
304
305 LOG_INFO("Successfully connected to Alpaca dome.");
306
307 // Get device info
308 alpacaGetString("/name", m_DeviceName);
309 alpacaGetString("/description", m_Description);
310 alpacaGetString("/driverinfo", m_DriverInfo);
311 alpacaGetString("/driverversion", m_DriverVersion);
312 alpacaGetInt("/interfaceversion", m_InterfaceVersion);
313
314 // Update dome capabilities
315 alpacaGetBool("/canfindhome", m_CanFindHome);
316 alpacaGetBool("/canpark", m_CanPark);
317 alpacaGetBool("/cansetaltitude", m_CanSetAltitude);
318 alpacaGetBool("/cansetazimuth", m_CanSetAzimuth);
319 alpacaGetBool("/cansetpark", m_CanSetPark);
320 alpacaGetBool("/cansetshutter", m_CanSetShutter);
321 alpacaGetBool("/canslave", m_CanSlave);
322 alpacaGetBool("/cansyncazimuth", m_CanSyncAzimuth);
323 uint32_t cap = INDI::Dome::DOME_CAN_ABORT;
324 if (m_CanPark)
326 if (m_CanSetShutter)
328 if (m_CanSetAzimuth)
330 if (m_CanSyncAzimuth)
333
334 // Setting parked flag once on connection
335 if (m_CanPark)
336 {
337 bool slewing, parked;
338 if (alpacaGetBool("/slewing", slewing, false) && alpacaGetBool("/atpark", parked, true))
339 SetParked(!slewing && parked);
340 }
341
343 return true;
344}
345
347
349{
350 if (isConnected())
351 {
352 if (!alpacaDisconnect())
353 {
354 LOG_ERROR("Failed to set disconnected state on Alpaca dome.");
355 return false;
356 }
357 }
358
359 // Reset HTTP client object and close any existing connections
360 httpClient.reset();
361
362 LOG_INFO("Disconnected from Alpaca dome.");
363 return true;
364}
365
367
368bool AlpacaDome::SetSpeed(double rpm)
369{
370 INDI_UNUSED(rpm);
371 return false;
372}
373
375
377{
378 if (CanSetAzimuth() == false)
379 {
380 LOG_ERROR( "Dome does not support azimuth slewing.");
381 return IPS_ALERT;
382 }
383
384 double targetAz = range360(DomeAbsPosNP[0].getValue() + azDiff);
385 return MoveAbs(targetAz);
386}
387
389
391{
392 if (CanSetAzimuth() == false)
393 {
394 LOG_ERROR( "Dome does not support azimuth slewing.");
395 return IPS_ALERT;
396 }
397
398 if (!alpacaDomeSlewToAzimuth(range360(az)))
399 return IPS_ALERT;
400 return IPS_BUSY;
401}
402
404
406{
407 if (CanSetAzimuth() == false)
408 {
409 LOG_ERROR( "Dome does not support azimuth slewing.");
410 return IPS_ALERT;
411 }
412
413 double targetAz = DomeAbsPosNP[0].getValue();
414
415 if (operation == MOTION_START)
416 {
417 targetAz = DomeAbsPosNP[0].getValue();
418 if (dir == DOME_CW)
419 targetAz += 5;
420 else
421 targetAz -= 5;
422 targetAz = range360(targetAz);
423 }
424
425 if (MoveAbs(targetAz) == IPS_ALERT)
426 return IPS_ALERT;
427
428 return ((operation == MOTION_START) ? IPS_BUSY : IPS_OK);
429}
430
432
433bool AlpacaDome::Sync(double az)
434{
435 if (CanSync() == false)
436 {
437 LOG_ERROR( "Dome does not support syncing.");
438 return false;
439 }
440
441 double targetAz = range360(az);
442 bool success = alpacaDomeSyncToAzimuth(targetAz);
443 if (success)
444 {
445 DomeSyncNP.setState(IPS_OK);
446 LOGF_INFO( "Dome successfully synchronized to azimuth angle %.2f.", targetAz);
447 }
448 else
449 {
450 DomeSyncNP.setState(IPS_ALERT);
451 LOGF_ERROR( "Error: cannot synchronize dome to azimuth angle %.2f.", targetAz);
452 }
453
454 DomeSyncNP.apply();
455 return success;
456}
457
459
461{
462 if (alpacaDomeAbortSlew())
463 {
464 if (OperationSP.getState() == IPS_BUSY)
465 {
466 if (OperationSP[OPERATION_FIND_HOME].getState() == ISS_ON)
467 {
468 LOG_WARN("Finding home operation is aborted.");
469 }
470 else if (OperationSP[OPERATION_CALIBRATE].getState() == ISS_ON)
471 {
472 LOG_WARN("Calibrating operation is aborted.");
473 }
474 OperationSP.reset();
475 OperationSP.setState(IPS_ALERT);
476 OperationSP.apply();
477 }
478 else if (getShutterState() == SHUTTER_MOVING)
479 {
480 LOG_WARN("Shutter motion aborted!");
481 DomeShutterSP.setState(IPS_ALERT);
482 DomeShutterSP.apply();
483 }
484 else
485 {
486 LOG_WARN("Dome motion aborted.");
487 }
488
489 return true;
490 }
491
492 return false;
493}
494
496
498{
499 if (alpacaDomePark())
500 {
501 LOG_INFO("Parking dome...");
503 return IPS_BUSY;
504 }
505
506 LOG_ERROR("Failed to park dome");
507 return IPS_ALERT;
508}
509
511
513{
514 LOG_INFO("Unparking dome...");
515 IPState result = MoveAbs(DomeAbsPosNP[0].getValue());
516 if (result != IPS_ALERT)
518
519 return result;
520}
521
523
525{
526 if (operation == SHUTTER_OPEN)
527 {
528 LOG_INFO("Opening dome...");
529 if (alpacaDomeOpenShutter())
530 {
531 LOG_INFO("Dome is opening...");
533 return IPS_BUSY;
534 }
535
536 return IPS_ALERT;
537 }
538 else if (operation == SHUTTER_CLOSE)
539 {
540 if (isLocked())
541 {
542 LOG_WARN("Cannot close dome when mount is locking. See: Telescope parking policy, in options tab");
543 return IPS_ALERT;
544 }
545
546 LOG_INFO("Closing dome...");
547 if (alpacaDomeCloseShutter())
548 {
549 LOG_INFO("Dome is closing...");
551 return IPS_BUSY;
552 }
553
554 return IPS_ALERT;
555 }
556
557 return IPS_OK;
558}
559
561
563{
564 if (CanSetPark() == false)
565 {
566 LOG_ERROR( "Dome does not support setting park position.");
567 return false;
568 }
569
570 if (alpacaDomeSetPark())
571 {
572 LOG_INFO( "Dome park position successfully set to current azimuth");
573 return true;
574 }
575
576 LOG_ERROR( "Error: cannot set park position to current azimuth");
577 return false;
578}
579
581
583{
584 return SetCurrentPark();
585}
586
588
590{
591 if (CanFindHome() == false)
592 {
593 LOG_ERROR( "Dome does not support homing.");
594 return IPS_ALERT;
595 }
596
597 if (alpacaDomeFindHome())
598 {
599 LOG_INFO( "Dome is moving to home position...");
601 return IPS_BUSY;
602 }
603
604 LOG_ERROR( "Error: cannot move the dome to the home position");
605 return IPS_ALERT;
606}
607
609
611{
612 LOG_ERROR( "Calibration is not supported by standard basic Alpaca dome.");
613 return IPS_ALERT;
614}
615
617
618std::string AlpacaDome::getAlpacaURL(const std::string& endpoint)
619{
620 return "/api/v1/dome/" + std::to_string(static_cast<int>(DeviceNumberNP[0].getValue())) + endpoint;
621}
622
624
626{
627 // Convert JSON to form data for Alpaca compatibility
628 std::string form_data;
629 for (auto & [key, value] : request.items())
630 {
631 if (!form_data.empty()) form_data += "&";
632
633 if (value.is_string())
634 {
635 form_data += key + "=" + value.get<std::string>();
636 }
637 else if (value.is_number_integer())
638 {
639 form_data += key + "=" + std::to_string(value.get<int>());
640 }
641 else if (value.is_number_float())
642 {
643 form_data += key + "=" + std::to_string(value.get<double>());
644 }
645 else if (value.is_boolean())
646 {
647 form_data += key + "=" + (value.get<bool>() ? "true" : "false");
648 }
649 }
650
651 // Add ClientID and ClientTransactionID to form data
652 if (!form_data.empty()) form_data += "&";
653 form_data += "ClientID=" + std::to_string(getpid());
654 form_data += "&ClientTransactionID=" + std::to_string(getTransactionId());
655
656 return form_data;
657}
658
660
661void AlpacaDome::setDefaultServerAddress(const char *host, const char *port, bool force)
662{
663 // Only apply defaults if no value was loaded from saved config (mirrors TCP plugin pattern).
664 // m_ConfigHost/m_ConfigPort are empty when no config file entry exists for this device,
665 // meaning this is either a first run or the user has never saved settings.
666 if (host != nullptr)
667 {
668 if (force || m_ConfigHost.empty())
669 ServerAddressTP[HOST].setText(host);
670 }
671
672 if (port != nullptr)
673 {
674 if (force || m_ConfigPort.empty())
675 ServerAddressTP[PORT].setText(port);
676 }
677}
678
680
682{
683 return ++m_ClientTransactionID;
684}
685
687
688void AlpacaDome::updateStatus()
689{
690 if (!isConnected())
691 {
694 return;
695 }
696
697 // Request dome current state.
698 AlapacaDomeState value;
699 if (alpacaGetDeviceState(value))
700 {
701 // Shutter state update
702 if (HasShutter())
703 updateShutterStatus(value);
704
705 // Dome state update
706 updateDomeStatus(value);
707 }
708}
709
711
712void AlpacaDome::updateDomeStatus(AlapacaDomeState &state)
713{
714 if (getDomeState() == DOME_MOVING && !state.slewing)
715 {
716 bool isHoming = (OperationSP.getState() == IPS_BUSY && OperationSP[OPERATION_FIND_HOME].getState() == ISS_ON);
717 bool isCalibrating = (OperationSP.getState() == IPS_BUSY && OperationSP[OPERATION_CALIBRATE].getState() == ISS_ON);
718
719 if (isHoming && state.atHome)
720 {
721 LOG_INFO("Dome has found home position.");
722 OperationSP.reset();
723 OperationSP.setState(IPS_OK);
724 OperationSP.apply();
726 }
727 else if (isCalibrating)
728 {
729 LOG_INFO("Dome calibration complete.");
730 OperationSP.reset();
731 OperationSP.setState(IPS_OK);
732 OperationSP.apply();
734 }
735 else
736 {
737 LOGF_INFO("Dome reached requested azimuth: %.3f Degrees", state.azimuth);
739 }
740 }
741 else if (getDomeState() == DOME_PARKING && !state.slewing && state.atPark)
742 {
743 SetParked(true);
744 }
745 else if (getDomeState() == DOME_UNPARKING && !state.slewing)
746 {
747 SetParked(false);
748 }
749 else if (getDomeState() == DOME_MOVING && state.slewing && DomeAbsPosNP.getState() != IPS_BUSY)
750 {
751 DomeAbsPosNP.setState(IPS_BUSY);
752 }
753 DomeAbsPosNP[0].setValue(state.azimuth);
754 DomeAbsPosNP.apply();
755}
756
758
759void AlpacaDome::updateShutterStatus(AlapacaDomeState &state)
760{
761 // Alpaca shutter states
762 // 0 = Open
763 // 1 = Closed
764 // 2 = Opening
765 // 3 = Closing
766 // 4 = Error
767 ShutterState previousState = getShutterState();
768 switch(state.shutterStatus)
769 {
770 case 0: // Open
771 if (previousState != SHUTTER_OPENED)
772 {
773 LOG_INFO("Shutter is fully open.");
775 }
776 break;
777
778 case 1: // Closed
779 if (previousState != SHUTTER_CLOSED)
780 {
781 LOG_INFO("Shutter is fully closed.");
783 }
784 break;
785
786 case 2: // Opening
787 if (previousState != SHUTTER_MOVING)
788 {
789 LOG_INFO("Shutter is opening...");
791 }
792 break;
793
794 case 3: // Closing
795 if (previousState != SHUTTER_MOVING)
796 {
797 LOG_INFO("Shutter is closing...");
799 }
800 break;
801
802 case 4: // Error
803 if (previousState != SHUTTER_ERROR)
804 {
805 LOG_ERROR("Shutter is in error state.");
807 }
808 break;
809
810 default:
811 if (previousState != SHUTTER_UNKNOWN)
813 break;
814 }
815}
816
818
819bool AlpacaDome::sendAlpacaGET(const std::string &endpoint, nlohmann::json &response)
820{
821 if (!httpClient)
822 {
823 LOG_ERROR("HTTP client not initialized.");
824 return false;
825 }
826
827 std::string url = getAlpacaURL(endpoint);
828 url += "?ClientID=" + std::to_string(getpid()) + "&ClientTransactionID=" + std::to_string(getTransactionId());
829
830 auto result = httpClient->Get(url.c_str());
831
832 if (!result)
833 {
834 LOGF_ERROR("HTTP GET failed for %s: %s", endpoint.c_str(),
835 httplib::to_string(result.error()).c_str());
836 return false;
837 }
838
839 if (result->status != 200)
840 {
841 LOGF_ERROR("HTTP GET %s returned status %d", endpoint.c_str(), result->status);
842 return false;
843 }
844
845 try
846 {
847 response = nlohmann::json::parse(result->body);
848
849 // Check for Alpaca errors
850 if (response.contains("ErrorNumber") && response["ErrorNumber"].get<int>() != 0)
851 {
852 LOGF_ERROR("Alpaca error in %s: %d - %s", endpoint.c_str(),
853 response["ErrorNumber"].get<int>(),
854 response["ErrorMessage"].get<std::string>().c_str());
855 return false;
856 }
857
858 return true;
859 }
860 catch (const nlohmann::json::exception& e)
861 {
862 LOGF_ERROR("JSON parse error for %s: %s", endpoint.c_str(), e.what());
863 return false;
864 }
865}
866
868
869bool AlpacaDome::sendAlpacaPUT(const std::string &endpoint, const nlohmann::json &request, nlohmann::json &response)
870{
871 if (!httpClient)
872 {
873 LOG_ERROR("HTTP client not initialized.");
874 return false;
875 }
876
877 std::string url = getAlpacaURL(endpoint);
878 std::string form_data = buildAlpacaFormData(request);
879
880 auto result = httpClient->Put(url, form_data, "application/x-www-form-urlencoded");
881
882 if (!result)
883 {
884 LOGF_ERROR("HTTP PUT failed for %s: %s", endpoint.c_str(),
885 httplib::to_string(result.error()).c_str());
886 return false;
887 }
888
889 if (result->status != 200)
890 {
891 LOGF_ERROR("HTTP PUT %s returned status %d", endpoint.c_str(), result->status);
892 return false;
893 }
894
895 try
896 {
897 response = nlohmann::json::parse(result->body);
898
899 // Check for Alpaca errors
900 if (response.contains("ErrorNumber") && response["ErrorNumber"].get<int>() != 0)
901 {
902
903 // JM 2025.08.29: For some reason, I always get error 1025 when setting temperature
904 // even though value is in range. Ignore this error for now.
905 // if (response["ErrorNumber"].get<int>() == 1025)
906 // return true;
907
908 LOGF_ERROR("Alpaca error in %s: %d - %s", endpoint.c_str(),
909 response["ErrorNumber"].get<int>(),
910 response["ErrorMessage"].get<std::string>().c_str());
911 return false;
912 }
913
914 return true;
915
916 }
917 catch (const nlohmann::json::exception& e)
918 {
919 LOGF_ERROR("JSON parse error for %s: %s", endpoint.c_str(), e.what());
920 return false;
921 }
922}
923
925
926bool AlpacaDome::alpacaConnect()
927{
928 nlohmann::json response;
929
930 // IDome Version 3 and later
931 if (m_InterfaceVersion >= 3)
932 {
933 if (!sendAlpacaPUT("/connect", {}, response))
934 return false;
935
936 bool connecting = true;
937 int retryDelay = 100;
938
939 // Need waiting for connection to be fully established (by checking /connecting)
940 while (connecting && retryDelay < 4000)
941 {
942 if (!alpacaGetBool("/connecting", connecting))
943 return false;
944 if (connecting)
945 {
946 std::this_thread::sleep_for(std::chrono::milliseconds(retryDelay));
947 retryDelay *= 2;
948 }
949 }
950 }
951 else
952 {
953 if (!sendAlpacaPUT("/connected", {{"Connected", true}}, response))
954 return false;
955
956 bool connected = false;
957 int retryDelay = 100;
958
959 // Need waiting for connection to be fully established (by checking /connecting)
960 while (!connected && retryDelay < 4000)
961 {
962 if (!alpacaGetBool("/connected", connected))
963 return false;
964 if (!connected)
965 {
966 std::this_thread::sleep_for(std::chrono::milliseconds(retryDelay));
967 retryDelay *= 2;
968 }
969 }
970 }
971
972 return true;
973}
974
976
977bool AlpacaDome::alpacaDisconnect()
978{
979 nlohmann::json response;
980
981 // IDome Version 3 and later
982 if (m_InterfaceVersion >= 3)
983 {
984 if (!sendAlpacaPUT("/disconnect", {}, response))
985 return false;
986 }
987 else
988 {
989 if (!sendAlpacaPUT("/connected", {{"Connected", false}}, response))
990 return false;
991 }
992
993 return true;
994}
995
997
998bool AlpacaDome::alpacaGetBool(const std::string &endpoint, bool& value, bool defaultValue)
999{
1000 nlohmann::json response;
1001 if (!sendAlpacaGET(endpoint, response))
1002 return false;
1003 if (response.contains("Value") && response["Value"].is_boolean())
1004 value = response["Value"].get<bool>();
1005 else
1006 value = defaultValue;
1007 return true;
1008}
1009
1011
1012bool AlpacaDome::alpacaGetInt(const std::string &endpoint, int &value, int defaultValue)
1013{
1014 nlohmann::json response;
1015 if (!sendAlpacaGET(endpoint, response))
1016 return false;
1017 if (response.contains("Value") && response["Value"].is_number_integer())
1018 value = response["Value"].get<int>();
1019 else
1020 value = defaultValue;
1021 return true;
1022}
1023
1025
1026bool AlpacaDome::alpacaGetDouble(const std::string &endpoint, double &value, double defaultValue)
1027{
1028 nlohmann::json response;
1029 if (!sendAlpacaGET(endpoint, response))
1030 return false;
1031 if (response.contains("Value") && response["Value"].is_number_float())
1032 value = response["Value"].get<double>();
1033 else
1034 value = defaultValue;
1035 return true;
1036}
1037
1039
1040bool AlpacaDome::alpacaGetString(const std::string &endpoint, std::string &value, const std::string& defaultValue)
1041{
1042 nlohmann::json response;
1043 if (!sendAlpacaGET(endpoint, response))
1044 return false;
1045 if (response.contains("Value") && response["Value"].is_string())
1046 value = response["Value"].get<std::string>();
1047 else
1048 value = defaultValue;
1049 return true;
1050}
1051
1053
1054bool AlpacaDome::alpacaGetDeviceState(AlapacaDomeState &value, double defaultAz, double defaultAlt)
1055{
1056 value.atPark = value.atHome = value.slewing = false;
1057 value.azimuth = defaultAz;
1058 value.altitude = defaultAlt;
1059 value.shutterStatus = -1;
1060
1061 // IDome Version 3 and later
1062 if (m_InterfaceVersion >= 3)
1063 {
1064 nlohmann::json response;
1065
1066 if (!sendAlpacaGET("/devicestate", response))
1067 return false;
1068
1069 if (!response.contains("Value") || !response["Value"].is_array())
1070 {
1071 LOG_ERROR("Error: an array of objects is expected in Value attribute of response");
1072 return false;
1073 }
1074
1075 for (auto &item : response["Value"])
1076 {
1077 if (!item.contains("Name") || !item["Name"].is_string())
1078 {
1079 LOG_ERROR("Error: missing string element Name in Value array item, as returned by /devicestate API method");
1080 continue;
1081 }
1082 if (!item.contains("Value"))
1083 {
1084 LOG_ERROR("Error: missing element Value in Value array item, as returned by /devicestate API method");
1085 continue;
1086 }
1087
1088 const std::string &key = item["Name"].get<std::string>();
1089 if (key == "Altitude")
1090 value.altitude = item["Value"].get<double>();
1091 else if (key == "AtHome")
1092 value.atHome = item["Value"].get<bool>();
1093 else if (key == "AtPark")
1094 value.atPark = item["Value"].get<bool>();
1095 else if (key == "Azimuth")
1096 value.azimuth = item["Value"].get<double>();
1097 else if (key == "ShutterStatus")
1098 value.shutterStatus = item["Value"].get<int>();
1099 else if (key == "Slewing")
1100 value.slewing = item["Value"].get<bool>();
1101 }
1102 }
1103 else
1104 {
1105 if (CanSetAzimuth() || CanAbsMove() || CanRelMove())
1106 alpacaGetBool("/slewing", value.slewing, false);
1107 if (CanFindHome())
1108 alpacaGetBool("/athome", value.atHome, false);
1109 if (CanSetPark())
1110 alpacaGetBool("/atpark", value.atPark, false);
1111 if (CanSetAzimuth())
1112 alpacaGetDouble("/azimuth", value.azimuth, defaultAz);
1113 if (CanSetAltitude())
1114 alpacaGetDouble("/altitude", value.altitude, defaultAlt);
1115 if (HasShutter())
1116 alpacaGetInt("/shutterstatus", value.shutterStatus, -1);
1117 }
1118
1119 return true;
1120}
1121
1123
1124bool AlpacaDome::alpacaDomeAbortSlew()
1125{
1126 nlohmann::json response;
1127 return sendAlpacaPUT("/abortslew", {}, response);
1128}
1129
1131
1132bool AlpacaDome::alpacaDomeCloseShutter()
1133{
1134 nlohmann::json response;
1135 return sendAlpacaPUT("/closeshutter", {}, response);
1136}
1137
1139
1140bool AlpacaDome::alpacaDomeFindHome()
1141{
1142 nlohmann::json response;
1143 return sendAlpacaPUT("/findhome", {}, response);
1144}
1145
1147
1148bool AlpacaDome::alpacaDomeOpenShutter()
1149{
1150 nlohmann::json response;
1151 return sendAlpacaPUT("/openshutter", {}, response);
1152}
1153
1155
1156bool AlpacaDome::alpacaDomePark()
1157{
1158 nlohmann::json response;
1159 return sendAlpacaPUT("/park", {}, response);
1160}
1161
1163
1164bool AlpacaDome::alpacaDomeSetPark()
1165{
1166 nlohmann::json response;
1167 return sendAlpacaPUT("/setpark", {}, response);
1168}
1169
1171
1172bool AlpacaDome::alpacaDomeSlewToAltitude(double alt)
1173{
1174 nlohmann::json response;
1175 nlohmann::json request = {{"Altitude", alt}};
1176 return sendAlpacaPUT("/slewtoaltitude", request, response);
1177}
1178
1180
1181bool AlpacaDome::alpacaDomeSlewToAzimuth(double az)
1182{
1183 nlohmann::json response;
1184 nlohmann::json request = {{"Azimuth", az}};
1185 return sendAlpacaPUT("/slewtoazimuth", request, response);
1186}
1187
1189
1190bool AlpacaDome::alpacaDomeSyncToAzimuth(double az)
1191{
1192 nlohmann::json response;
1193 nlohmann::json request = {{"Azimuth", az}};
1194 return sendAlpacaPUT("/synctoazimuth", request, response);
1195}
std::unique_ptr< AlpacaDome > alpaca_dome(new AlpacaDome())
INDI::PropertySwitch OperationSP
bool CanFindHome()
Definition alpaca_dome.h:90
virtual bool saveConfigItems(FILE *fp) override
Save all dome parameters in the configuration file. This overridden method adds the HTTP connection i...
virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n) override
Process the client newSwitch command.
virtual bool Abort() override
Abort all dome motion (spinning and shutter).
virtual IPState FindHome()
Request the dome for moving and finding its Home position. The method is asynchronous and the dome sh...
bool CanSetPark()
virtual bool SetCurrentPark() override
Set parking position of the dome with the current position.
virtual IPState Park() override
Park the dome.
virtual bool SetSpeed(double rpm) override
Set Dome speed. This does not initiate motion, it sets the speed for the next motion command....
virtual bool ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n) override
Process the client newNumber command.
virtual IPState MoveAbs(double az) override
Move the Dome to an absolute azimuth.
virtual bool Disconnect() override
Disconnect from the remote dome device.
virtual IPState MoveRel(double azDiff) override
Move the Dome to an relative position.
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...
@ INFO_INTERFACE_VERSION
@ INFO_DRIVER_VERSION
virtual uint32_t getTransactionId()
INDI::PropertyText ServerAddressTP
Additional properties.
bool CanCalibrate()
Definition alpaca_dome.h:98
virtual IPState Move(DomeDirection dir, DomeMotionCommand operation) override
Move the Dome in a particular direction.
INDI::PropertyNumber DeviceNumberNP
virtual IPState ControlShutter(ShutterOperation operation) override
Open or Close the shutter.
virtual bool updateProperties() override
Called whenever there is a change in the CONNECTION status of the driver. This will enable the driver...
INDI::PropertyText InfoTP
bool CanSetAzimuth()
bool CanSetAltitude()
virtual bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n) override
Process the client newSwitch command.
virtual std::string buildAlpacaFormData(const nlohmann::json &request)
INDI::PropertyNumber ConnectionSettingsNP
virtual bool initProperties() override
Initialize properties state and value for Alpaca dome device.
@ OPERATION_CALIBRATE
@ OPERATION_FIND_HOME
virtual const char * getDefaultName() override
virtual void setDefaultServerAddress(const char *host, const char *port, bool force=false)
virtual void TimerHit() override
Callback function to be called once SetTimer duration elapses.
virtual IPState Calibrate()
Request the dome for moving in order to calibrate itself. The calibration is an asynchronous process ...
virtual bool Sync(double az) override
Set the dome current azimuth with the supplied azimuth position.
virtual bool Connect() override
Connect to the remote dome device. For Alpaca drivers, this method tries to connect to the device usi...
virtual IPState UnPark() override
UnPark the dome. The action of the Unpark command is dome specific, but it may include opening the sh...
virtual bool SetDefaultPark() override
Set parking position of the dome with the current position.
virtual std::string getAlpacaURL(const std::string &endpoint)
bool isConnected() const
INDI::PropertyText getText(const char *name) const
bool isDeviceNameMatch(const char *otherName) const
Check that the device name matches the argument.
virtual bool saveConfig(bool silent=false, const char *property=nullptr)
Save the current properties in a configuration file.
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.
void addAuxControls()
Add Debug, Simulation, and Configuration options to the driver.
int SetTimer(uint32_t ms)
Set a timer to call the function TimerHit after ms milliseconds.
@ CONNECTION_NONE
Definition indidome.h:171
void SetParked(bool isparked)
SetParked Change the mount parking status. The data park file (stored in ~/.indi/ParkData....
void SetDomeCapability(uint32_t cap)
SetDomeCapability set the dome capabilities. All capabilities must be initialized.
void setDomeConnection(const uint8_t &value)
setDomeConnection Set Dome connection mode. Child class should call this in the constructor before Do...
@ DOME_UNPARKING
Definition indidome.h:135
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...
Definition indidome.cpp:273
bool CanRelMove()
Definition indidome.h:234
ShutterOperation
Shutter operation command.
Definition indidome.h:114
@ SHUTTER_CLOSE
Definition indidome.h:116
DomeMotionCommand
Definition indidome.h:97
@ MOTION_START
Definition indidome.h:98
virtual bool initProperties() override
Initialize properties initial state and value. The child class must implement this function.
Definition indidome.cpp:108
bool CanSync()
Definition indidome.h:250
bool HasShutter()
Definition indidome.h:258
@ SHUTTER_ERROR
Definition indidome.h:151
@ SHUTTER_MOVING
Definition indidome.h:149
@ SHUTTER_UNKNOWN
Definition indidome.h:150
@ SHUTTER_OPENED
Definition indidome.h:147
@ SHUTTER_CLOSED
Definition indidome.h:148
bool isLocked()
isLocked, is the dome currently locked?
@ DOME_CAN_PARK
Definition indidome.h:159
@ DOME_CAN_ABS_MOVE
Definition indidome.h:157
@ DOME_HAS_SHUTTER
Definition indidome.h:161
@ DOME_CAN_REL_MOVE
Definition indidome.h:158
@ DOME_CAN_ABORT
Definition indidome.h:156
@ DOME_CAN_SYNC
Definition indidome.h:160
virtual bool updateProperties() override
updateProperties is called whenever there is a change in the CONNECTION status of the driver....
Definition indidome.cpp:287
INDI::PropertyNumber DomeAbsPosNP
Definition indidome.h:558
virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n) override
Process the client newSwitch command.
Definition indidome.cpp:508
virtual bool saveConfigItems(FILE *fp) override
saveConfigItems Saves the Device Port and Dome Presets in the configuration file
bool CanAbsMove()
Definition indidome.h:226
virtual bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n) override
Process the client newSwitch command.
Definition indidome.cpp:824
void setShutterState(const ShutterState &value)
void setDomeState(const DomeState &value)
void SetParkDataType(DomeParkData type)
setParkDataType Sets the type of parking data stored in the park data file and presented to the user.
INDI::PropertySwitch DomeShutterSP
Definition indidome.h:568
ShutterState getShutterState() const
Definition indidome.h:291
virtual bool ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n) override
Process the client newNumber command.
Definition indidome.cpp:399
DomeState getDomeState() const
Definition indidome.h:285
INDI::PropertyNumber DomeSyncNP
Definition indidome.h:566
friend class ::nlohmann::detail::exception
const char * CONNECTION_TAB
CONNECTION_TAB Where all device connection settings (serial, usb, ethernet) are defined and controlle...
const char * MAIN_CONTROL_TAB
MAIN_CONTROL_TAB Where all the primary controls for the device are located.
const char * INFO_TAB
INFO_TAB Where all the properties for general information are located.
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_ATMOST1
Definition indiapi.h:172
#define MAXINDINAME
Definition indiapi.h:189
double range360(double r)
range360 Limits an angle to be between 0-360 degrees.
Definition indicom.c:1321
const char * IUFindOnSwitchName(ISState *states, char *names[], int n)
Returns the name of the first ON switch it finds in the supplied arguments.
Definition indidevapi.c:355
#define INDI_UNUSED(x)
Definition indidevapi.h:132
int IUGetConfigText(const char *dev, const char *property, const char *member, char *value, int len)
IUGetConfigText Opens configuration file and reads single text property.
Definition indidriver.c:908
*brief user defined string literal for JSON values *sa std::size_t n
#define LOGF_INFO(fmt,...)
Definition indilogger.h:82
#define LOG_WARN(txt)
Definition indilogger.h:73
#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
std::string to_string(Error error)
Definition httplib.h:9275
basic_json<> json
default specialization