Instrument Neutral Distributed Interface INDI 2.2.5
planewave_mount.cpp
Go to the documentation of this file.
1/*******************************************************************************
2 Copyright(c) 2023-2027 Jasem Mutlaq. All rights reserved.
3
4 Planewave Mount
5 API Communication via PWI4 HTTP Interface
6
7 This library is free software; you can redistribute it and/or
8 modify it under the terms of the GNU Library General Public
9 License version 2 as published by the Free Software Foundation.
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 Library General Public License for more details.
15 .
16 You should have received a copy of the GNU Library General Public License
17 along with this library; see the file COPYING.LIB. If not, write to
18 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19 Boston, MA 02110-1301, USA.
20*******************************************************************************/
21
22#include "planewave_mount.h"
23
24#include "indicom.h"
26#include <libnova/sidereal_time.h>
27#include <libnova/transform.h>
28
29#include <cmath>
30#include <cstring>
31#include <memory>
32#include <sstream>
33#include <iomanip>
34
35std::unique_ptr<PlaneWave> PlaneWave_mount(new PlaneWave());
36
57
58// Must be defined here in the .cpp so that unique_ptr<httplib::Client>
59// is destroyed after the complete type is known.
60PlaneWave::~PlaneWave() = default;
61
66{
67 return "PlaneWave";
68}
69
74{
76
77 // ── Track Modes ─────────────────────────────────────────────────────────
78 AddTrackMode("TRACK_SIDEREAL", "Sidereal", true);
79 AddTrackMode("TRACK_SOLAR", "Solar");
80 AddTrackMode("TRACK_LUNAR", "Lunar");
81 AddTrackMode("TRACK_CUSTOM", "Custom");
82
85
86 tcpConnection->setDefaultHost("192.168.1.1");
87 tcpConnection->setDefaultPort(8220);
88
89 // ── Info tab ─────────────────────────────────────────────────────────────
90
91 FirmwareTP[0].fill("VERSION", "PWI4 Version", "");
92 FirmwareTP.fill(getDeviceName(), "FIRMWARE_INFO", "Firmware",
93 INFO_TAB, IP_RO, 60, IPS_IDLE);
94
95 MountGeometryTP[0].fill("GEOMETRY", "Mount Type", "");
96 MountGeometryTP.fill(getDeviceName(), "MOUNT_GEOMETRY", "Geometry",
97 INFO_TAB, IP_RO, 60, IPS_IDLE);
98
99 // Az / Alt — derived from status on every poll
100 AltAzNP[AZ_VALUE].fill("AZ", "Azimuth (°)", "%.4f", 0.0, 360.0, 0.0, 0.0);
101 AltAzNP[ALT_VALUE].fill("ALT", "Altitude (°)", "%.4f", -90.0, 90.0, 0.0, 0.0);
102 AltAzNP.fill(getDeviceName(), "MOUNT_ALTAZ", "Az/Alt",
104
105 // Axis 0 (AZ / RA) servo telemetry
106 Axis0TelemetryNP[TELEMETRY_RMS_ERROR].fill(
107 "AXIS0_RMS", "RMS Error (\")", "%.3f", 0, 1000, 0, 0);
108 Axis0TelemetryNP[TELEMETRY_DIST_TO_TARGET].fill(
109 "AXIS0_DIST", "Dist to Target (\")", "%.3f", -1e6, 1e6, 0, 0);
110 Axis0TelemetryNP[TELEMETRY_SERVO_ERROR].fill(
111 "AXIS0_SERVO", "Servo Error (\")", "%.3f", -1e6, 1e6, 0, 0);
112 Axis0TelemetryNP[TELEMETRY_MOTOR_CURRENT].fill(
113 "AXIS0_CURRENT", "Motor Current (A)", "%.3f", 0, 100, 0, 0);
114 Axis0TelemetryNP.fill(getDeviceName(), "AXIS0_TELEMETRY", "Axis 0 (AZ/RA) Telemetry",
115 INFO_TAB, IP_RO, 0, IPS_IDLE);
116
117 // Axis 1 (ALT / Dec) servo telemetry
118 Axis1TelemetryNP[TELEMETRY_RMS_ERROR].fill(
119 "AXIS1_RMS", "RMS Error (\")", "%.3f", 0, 1000, 0, 0);
120 Axis1TelemetryNP[TELEMETRY_DIST_TO_TARGET].fill(
121 "AXIS1_DIST", "Dist to Target (\")", "%.3f", -1e6, 1e6, 0, 0);
122 Axis1TelemetryNP[TELEMETRY_SERVO_ERROR].fill(
123 "AXIS1_SERVO", "Servo Error (\")", "%.3f", -1e6, 1e6, 0, 0);
124 Axis1TelemetryNP[TELEMETRY_MOTOR_CURRENT].fill(
125 "AXIS1_CURRENT", "Motor Current (A)", "%.3f", 0, 100, 0, 0);
126 Axis1TelemetryNP.fill(getDeviceName(), "AXIS1_TELEMETRY", "Axis 1 (ALT/Dec) Telemetry",
127 INFO_TAB, IP_RO, 0, IPS_IDLE);
128
129 // Angular separation from current pointing to the Sun (safety indicator)
130 DistanceToSunNP[0].fill("DIST_TO_SUN", "Distance (°)", "%.2f", 0, 180, 0, 0);
131 DistanceToSunNP.fill(getDeviceName(), "DISTANCE_TO_SUN", "Sun Distance",
133
134 // ── Main Control tab ─────────────────────────────────────────────────────
135
136 // Motor enable / disable — axis 0
137 Axis0MotorSP[INDI_ENABLED].fill("AXIS0_ENABLE", "Enable", ISS_OFF);
138 Axis0MotorSP[INDI_DISABLED].fill("AXIS0_DISABLE", "Disable", ISS_OFF);
139 Axis0MotorSP.fill(getDeviceName(), "AXIS0_MOTOR", "Axis 0 (AZ/RA) Motor",
141
142 // Motor enable / disable — axis 1
143 Axis1MotorSP[INDI_ENABLED].fill("AXIS1_ENABLE", "Enable", ISS_OFF);
144 Axis1MotorSP[INDI_DISABLED].fill("AXIS1_DISABLE", "Disable", ISS_OFF);
145 Axis1MotorSP.fill(getDeviceName(), "AXIS1_MOTOR", "Axis 1 (ALT/Dec) Motor",
147
148 // Find Home — relevant for L-series mounts with incremental encoders
149 FindHomeSP[0].fill("FIND_HOME", "Find Home", ISS_OFF);
150 FindHomeSP.fill(getDeviceName(), "MOUNT_HOME", "Homing",
152
153 // ── Pointing Model tab ────────────────────────────────────────────────────
154
155 // Active model filename (read-only, pulled from status)
156 ModelFilenameTP[0].fill("MODEL_FILE", "Active Model", "");
157 ModelFilenameTP.fill(getDeviceName(), "MODEL_FILENAME", "Model File",
158 MODEL_TAB, IP_RO, 60, IPS_IDLE);
159
160 // Model quality statistics (read-only, pulled from status)
161 ModelInfoNP[MODEL_POINTS_TOTAL].fill("MODEL_TOTAL", "Total Points", "%.0f", 0, 10000, 1, 0);
162 ModelInfoNP[MODEL_POINTS_ENABLED].fill("MODEL_ENABLED", "Enabled Points", "%.0f", 0, 10000, 1, 0);
163 ModelInfoNP[MODEL_RMS_ERROR].fill("MODEL_RMS", "RMS Error (\")", "%.3f", 0, 10000, 0, 0);
164 ModelInfoNP.fill(getDeviceName(), "MODEL_INFO", "Model Statistics",
165 MODEL_TAB, IP_RO, 0, IPS_IDLE);
166
167 // One-click model operations
168 ModelOperationSP[MODEL_SAVE_AS_DEFAULT].fill("MODEL_SAVE_DEFAULT", "Save as Default", ISS_OFF);
169 ModelOperationSP[MODEL_CLEAR_POINTS].fill("MODEL_CLEAR", "Clear All Points", ISS_OFF);
170 ModelOperationSP.fill(getDeviceName(), "MODEL_OPERATION", "Model Operations",
171 MODEL_TAB, IP_RW, ISR_ATMOST1, 0, IPS_IDLE);
172
173 // Load model: user types filename → Apply → driver sends /mount/model/load
174 ModelLoadFilenameTP[0].fill("MODEL_LOAD_FILE", "Filename", "DefaultModel.pxp");
175 ModelLoadFilenameTP.fill(getDeviceName(), "MODEL_LOAD", "Load Model",
176 MODEL_TAB, IP_RW, 60, IPS_IDLE);
177
178 // Save model: user types filename → Apply → driver sends /mount/model/save
179 ModelSaveFilenameTP[0].fill("MODEL_SAVE_FILE", "Filename", "MyModel.pxp");
180 ModelSaveFilenameTP.fill(getDeviceName(), "MODEL_SAVE", "Save Model",
181 MODEL_TAB, IP_RW, 60, IPS_IDLE);
182
183 // ── Options tab ───────────────────────────────────────────────────────────
184
185 SlewTimeConstantNP[0].fill("SLEW_TIME_CONSTANT", "Time Constant (s)",
186 "%.2f", 0.1, 5.0, 0.1, 0.5);
187 SlewTimeConstantNP.fill(getDeviceName(), "MOUNT_SLEW_CONSTANT", "Slew Aggressiveness",
189
191 return true;
192}
193
198{
200
201 if (isConnected())
202 {
203 // Info tab
204 defineProperty(FirmwareTP);
205 defineProperty(MountGeometryTP);
206 defineProperty(AltAzNP);
207 defineProperty(Axis0TelemetryNP);
208 defineProperty(Axis1TelemetryNP);
209 defineProperty(DistanceToSunNP);
210
211 // Main Control tab
212 defineProperty(Axis0MotorSP);
213 defineProperty(Axis1MotorSP);
214 defineProperty(FindHomeSP);
215
216 // Pointing Model tab
217 defineProperty(ModelFilenameTP);
218 defineProperty(ModelInfoNP);
219 defineProperty(ModelOperationSP);
220 defineProperty(ModelLoadFilenameTP);
221 defineProperty(ModelSaveFilenameTP);
222
223 // Options tab
224 defineProperty(SlewTimeConstantNP);
225
226 // Parking data
227 if (InitPark())
228 {
231 }
232 else
233 {
234 SetAxis1Park(0);
235 SetAxis2Park(0);
238 }
239 }
240 else
241 {
242 deleteProperty(FirmwareTP);
243 deleteProperty(MountGeometryTP);
244 deleteProperty(AltAzNP);
245 deleteProperty(Axis0TelemetryNP);
246 deleteProperty(Axis1TelemetryNP);
247 deleteProperty(DistanceToSunNP);
248
249 deleteProperty(Axis0MotorSP);
250 deleteProperty(Axis1MotorSP);
251 deleteProperty(FindHomeSP);
252
253 deleteProperty(ModelFilenameTP);
254 deleteProperty(ModelInfoNP);
255 deleteProperty(ModelOperationSP);
256 deleteProperty(ModelLoadFilenameTP);
257 deleteProperty(ModelSaveFilenameTP);
258
259 deleteProperty(SlewTimeConstantNP);
260 }
261
262 return true;
263}
264
269{
270 // Build (or rebuild on reconnect) the persistent client
271 m_HttpClient = std::make_unique<httplib::Client>(tcpConnection->host(),
272 tcpConnection->port());
273 m_HttpClient->set_connection_timeout(5, 0);
274 m_HttpClient->set_read_timeout(10, 0);
275
276 // Fetch initial status
277 if (!getStatus())
278 {
279 LOG_ERROR("Cannot communicate with PWI4. Is PWI4 running and reachable?");
280 return false;
281 }
282
283 // If PWI4 is not connected to the mount hardware, try to connect it
284 bool mountConnected = m_Status["mount.is_connected"].as<bool>();
285 if (!mountConnected)
286 {
287 LOG_INFO("Mount not connected to PWI4. Sending /mount/connect …");
288 if (!dispatch("/mount/connect"))
289 {
290 LOG_ERROR("Failed to connect mount via PWI4.");
291 return false;
292 }
293 mountConnected = m_Status["mount.is_connected"].as<bool>();
294 if (!mountConnected)
295 {
296 LOG_ERROR("Mount still not connected after /mount/connect.");
297 return false;
298 }
299 }
300
301 // ── Populate read-only info properties from the first status fetch ────────
302
303 // PWI4 version
304 std::string version = m_Status["pwi4.version"].as<std::string>();
305 FirmwareTP[0].setText(version.c_str());
306 FirmwareTP.setState(IPS_OK);
307
308 // Mount geometry
309 int geometry = m_Status["mount.geometry"].as<int>();
310 const char *geomStr = "Unknown";
311 switch (geometry)
312 {
313 case 0:
314 geomStr = "Alt-Az";
316 break;
317 case 1:
318 geomStr = "Equatorial Fork";
320 break;
321 case 2:
322 geomStr = "German Equatorial";
324 break;
325 }
326 MountGeometryTP[0].setText(geomStr);
327 MountGeometryTP.setState(IPS_OK);
328
329 // Slew time constant
330 SlewTimeConstantNP[0].setValue(m_Status["mount.slew_time_constant"].as<double>());
331 SlewTimeConstantNP.setState(IPS_OK);
332
333 LOGF_INFO("Connected to PWI4 %s — mount geometry: %s", version.c_str(), geomStr);
334 return true;
335}
336
340bool PlaneWave::getStatus()
341{
342 return dispatch("/status");
343}
344
349{
350 if (!getStatus())
351 return false;
352
353 // ── Coordinates ────────────────────────────────────────────────────────
354 double ra = m_Status["mount.ra_apparent_hours"].as<double>();
355 double de = m_Status["mount.dec_apparent_degs"].as<double>();
356
357 // ── Flags ──────────────────────────────────────────────────────────────
358 bool isSlewing = m_Status["mount.is_slewing"].as<bool>();
359 bool isTracking = m_Status["mount.is_tracking"].as<bool>();
360
361 // ── State machine ──────────────────────────────────────────────────────
362 switch (TrackState)
363 {
364 case SCOPE_PARKING:
365 // Park is complete when the mount has stopped slewing AND is no
366 // longer tracking (it will be in the "stopped" state).
367 if (!isSlewing && !isTracking)
368 SetParked(true);
369 break;
370
371 case SCOPE_SLEWING:
372 // Slewing is complete once mount.is_slewing drops to false;
373 // it then either begins tracking or goes idle.
374 if (!isSlewing)
375 {
376 if (isTracking)
377 {
379 SetTrackEnabled(true);
380 }
381 else
382 {
384 }
385 }
386 break;
387
388 default:
389 // If the mount starts tracking externally (e.g. via PWI4 GUI),
390 // reflect that in the INDI state.
391 if (isTracking && TrackState == SCOPE_IDLE)
393 break;
394 }
395
396 NewRaDec(ra, de);
397
398 // ── Az / Alt ───────────────────────────────────────────────────────────
399 double az = m_Status["mount.azimuth_degs"].as<double>();
400 double alt = m_Status["mount.altitude_degs"].as<double>();
401 AltAzNP[AZ_VALUE].setValue(az);
402 AltAzNP[ALT_VALUE].setValue(alt);
403 AltAzNP.setState(IPS_OK);
404 AltAzNP.apply();
405
406 // ── Pier side (GEM only) ───────────────────────────────────────────────
407 // On a German Equatorial, the HA decides which side the scope is on.
408 // PWI4 does not expose pier side directly; we infer it from axis0 position.
409 int geometry = m_Status["mount.geometry"].as<int>();
410 if (geometry == 2) // GEM
411 {
412 double axis0Pos = m_Status["mount.axis0.position_degs"].as<double>();
413 // Conventional: axis0 > 180° → pointing West → scope on East (pier west)
414 setPierSide((axis0Pos > 180.0) ? PIER_WEST : PIER_EAST);
415 }
416
417 // ── Axis 0 telemetry ───────────────────────────────────────────────────
418 Axis0TelemetryNP[TELEMETRY_RMS_ERROR].setValue(
419 m_Status["mount.axis0.rms_error_arcsec"].as<double>());
420 Axis0TelemetryNP[TELEMETRY_DIST_TO_TARGET].setValue(
421 m_Status["mount.axis0.dist_to_target_arcsec"].as<double>());
422 Axis0TelemetryNP[TELEMETRY_SERVO_ERROR].setValue(
423 m_Status["mount.axis0.servo_error_arcsec"].as<double>());
424 Axis0TelemetryNP[TELEMETRY_MOTOR_CURRENT].setValue(
425 m_Status["mount.axis0.measured_current_amps"].as<double>());
426 Axis0TelemetryNP.setState(IPS_OK);
427 Axis0TelemetryNP.apply();
428
429 // ── Axis 1 telemetry ───────────────────────────────────────────────────
430 Axis1TelemetryNP[TELEMETRY_RMS_ERROR].setValue(
431 m_Status["mount.axis1.rms_error_arcsec"].as<double>());
432 Axis1TelemetryNP[TELEMETRY_DIST_TO_TARGET].setValue(
433 m_Status["mount.axis1.dist_to_target_arcsec"].as<double>());
434 Axis1TelemetryNP[TELEMETRY_SERVO_ERROR].setValue(
435 m_Status["mount.axis1.servo_error_arcsec"].as<double>());
436 Axis1TelemetryNP[TELEMETRY_MOTOR_CURRENT].setValue(
437 m_Status["mount.axis1.measured_current_amps"].as<double>());
438 Axis1TelemetryNP.setState(IPS_OK);
439 Axis1TelemetryNP.apply();
440
441 // ── Motor enabled state ────────────────────────────────────────────────
442 bool axis0Enabled = m_Status["mount.axis0.is_enabled"].as<bool>();
443 bool axis1Enabled = m_Status["mount.axis1.is_enabled"].as<bool>();
444
445 Axis0MotorSP[INDI_ENABLED].setState(axis0Enabled ? ISS_ON : ISS_OFF);
446 Axis0MotorSP[INDI_DISABLED].setState(axis0Enabled ? ISS_OFF : ISS_ON);
447 Axis0MotorSP.setState(IPS_OK);
448 Axis0MotorSP.apply();
449
450 Axis1MotorSP[INDI_ENABLED].setState(axis1Enabled ? ISS_ON : ISS_OFF);
451 Axis1MotorSP[INDI_DISABLED].setState(axis1Enabled ? ISS_OFF : ISS_ON);
452 Axis1MotorSP.setState(IPS_OK);
453 Axis1MotorSP.apply();
454
455 // ── Distance to Sun ────────────────────────────────────────────────────
456 double sunDist = m_Status["mount.distance_to_sun_degs"].as<double>();
457 DistanceToSunNP[0].setValue(sunDist);
458 // Warn when pointing within 30° of the Sun
459 DistanceToSunNP.setState(sunDist < 30.0 ? IPS_ALERT : IPS_OK);
460 DistanceToSunNP.apply();
461
462 // ── Pointing model info ────────────────────────────────────────────────
463 std::string modelFile = m_Status["mount.model.filename"].as<std::string>();
464 if (modelFile != std::string(ModelFilenameTP[0].getText()))
465 {
466 ModelFilenameTP[0].setText(modelFile.c_str());
467 ModelFilenameTP.setState(modelFile.empty() ? IPS_IDLE : IPS_OK);
468 ModelFilenameTP.apply();
469 }
470
471 ModelInfoNP[MODEL_POINTS_TOTAL].setValue(
472 m_Status["mount.model.num_points_total"].as<double>());
473 ModelInfoNP[MODEL_POINTS_ENABLED].setValue(
474 m_Status["mount.model.num_points_enabled"].as<double>());
475 ModelInfoNP[MODEL_RMS_ERROR].setValue(
476 m_Status["mount.model.rms_error_arcsec"].as<double>());
477 ModelInfoNP.setState(IPS_OK);
478 ModelInfoNP.apply();
479
480 // ── Site location readback ─────────────────────────────────────────────
481 // PWI4 is the authority on site location; push its values into INDI so
482 // they are always consistent with what the pointing model uses.
483 double pwi4Lat = m_Status["site.latitude_degs"].as<double>();
484 double pwi4Lon = m_Status["site.longitude_degs"].as<double>();
485 double pwi4Elv = m_Status["site.height_meters"].as<double>();
486 if (std::fabs(pwi4Lat - LocationNP[LOCATION_LATITUDE].getValue()) > 0.0001 ||
487 std::fabs(pwi4Lon - LocationNP[LOCATION_LONGITUDE].getValue()) > 0.0001 ||
488 std::fabs(pwi4Elv - LocationNP[LOCATION_ELEVATION].getValue()) > 1.0)
489 {
490 LocationNP[LOCATION_LATITUDE].setValue(pwi4Lat);
491 LocationNP[LOCATION_LONGITUDE].setValue(pwi4Lon);
492 LocationNP[LOCATION_ELEVATION].setValue(pwi4Elv);
493 LocationNP.apply();
494 }
495
496 return true;
497}
498
502bool PlaneWave::Goto(double ra, double dec)
503{
504 std::ostringstream req;
505 req << std::fixed << std::setprecision(9)
506 << "/mount/goto_ra_dec_j2000?ra_hours=" << ra
507 << "&dec_degs=" << dec;
508
509 if (!dispatch(req.str()))
510 return false;
511
513 return true;
514}
515
519bool PlaneWave::Sync(double ra, double dec)
520{
521 // PWI4 does not have a direct "sync" command. The closest equivalent is
522 // /mount/model/add_point, which maps the current encoder position to the
523 // provided J2000 coordinates and immediately updates the pointing model.
524 std::ostringstream req;
525 req << std::fixed << std::setprecision(9)
526 << "/mount/model/add_point?ra_j2000_hours=" << ra
527 << "&dec_j2000_degs=" << dec;
528
529 if (!dispatch(req.str()))
530 return false;
531
532 LOG_INFO("Sync: added a pointing-model calibration point at the current position.");
533 return true;
534}
535
540{
541 if (!dispatch("/mount/park"))
542 return false;
543
545 return true;
546}
547
552{
553 // Enable axis 0 (AZ / RA)
554 if (!enableAxis(0, true))
555 {
556 LOG_ERROR("Failed to enable axis 0 motor.");
557 return false;
558 }
559 // Enable axis 1 (ALT / Dec)
560 if (!enableAxis(1, true))
561 {
562 LOG_ERROR("Failed to enable axis 1 motor.");
563 return false;
564 }
565
566 SetParked(false);
567 return true;
568}
569
574{
575 if (!dispatch("/mount/set_park_here"))
576 return false;
577
578 LOG_INFO("Park position set to current position.");
579 return true;
580}
581
586{
587 SetAxis1Park(0);
588 SetAxis2Park(0);
589 return true;
590}
591
596{
597 return dispatch("/mount/stop");
598}
599
604{
606 {
607 LOG_ERROR("Please unpark the mount before issuing any motion commands.");
608 return false;
609 }
610
611 double rate = getSlewRateArcsecPerSec();
612 if (dir == DIRECTION_SOUTH)
613 rate = -rate; // South → negative Dec offset
614
615 std::ostringstream req;
616 req << std::fixed << std::setprecision(4);
617
618 if (command == MOTION_START)
619 req << "/mount/offset?dec_set_rate_arcsec_per_sec=" << rate;
620 else
621 req << "/mount/offset?dec_set_rate_arcsec_per_sec=0";
622
623 return dispatch(req.str());
624}
625
630{
632 {
633 LOG_ERROR("Please unpark the mount before issuing any motion commands.");
634 return false;
635 }
636
637 double rate = getSlewRateArcsecPerSec();
638 if (dir == DIRECTION_EAST)
639 rate = -rate; // East → negative RA offset (RA increases westward)
640
641 std::ostringstream req;
642 req << std::fixed << std::setprecision(4);
643
644 if (command == MOTION_START)
645 req << "/mount/offset?ra_set_rate_arcsec_per_sec=" << rate;
646 else
647 req << "/mount/offset?ra_set_rate_arcsec_per_sec=0";
648
649 return dispatch(req.str());
650}
651
656bool PlaneWave::updateLocation(double latitude, double longitude, double elevation)
657{
658 INDI_UNUSED(latitude);
659 INDI_UNUSED(longitude);
660 INDI_UNUSED(elevation);
661
662 // PWI4 manages its own site configuration. The driver keeps INDI's
663 // location in sync by reading back site.* values in ReadScopeStatus().
664 LOG_INFO("Note: site location is managed by PWI4. "
665 "INDI displays the location configured in PWI4.");
666 return true;
667}
668
672bool PlaneWave::updateTime(ln_date *utc, double utc_offset)
673{
674 INDI_UNUSED(utc);
675 INDI_UNUSED(utc_offset);
676 return true;
677}
678
682bool PlaneWave::SetTrackMode(uint8_t mode)
683{
684 // First ensure tracking is on
685 if (!dispatch("/mount/tracking_on"))
686 return false;
687
688 // For custom mode, apply the offsets that simulate non-sidereal rates.
689 // The rates stored in TrackRateNP are in arcsec/sec relative to sidereal.
690 if (mode == TRACK_CUSTOM)
691 {
692 double dRA = TrackRateNP[AXIS_RA].getValue();
693 double dDE = TrackRateNP[AXIS_DE].getValue();
694
695 std::ostringstream req;
696 req << std::fixed << std::setprecision(6)
697 << "/mount/offset?ra_set_rate_arcsec_per_sec=" << dRA
698 << "&dec_set_rate_arcsec_per_sec=" << dDE;
699
700 return dispatch(req.str());
701 }
702
703 // For Sidereal / Solar / Lunar the offset rate is zero; standard tracking
704 // on already handles those. Reset any previous custom offsets.
705 return dispatch("/mount/offset?ra_reset=0&dec_reset=0");
706}
707
711bool PlaneWave::SetTrackRate(double raRate, double deRate)
712{
713 std::ostringstream req;
714 req << std::fixed << std::setprecision(6)
715 << "/mount/offset?ra_set_rate_arcsec_per_sec=" << raRate
716 << "&dec_set_rate_arcsec_per_sec=" << deRate;
717
718 return dispatch(req.str());
719}
720
725{
726 if (enabled)
727 return SetTrackMode(TrackModeSP.findOnSwitchIndex());
728
729 // Disable tracking and clear any active offset rates
730 if (!dispatch("/mount/tracking_off"))
731 return false;
732
733 dispatch("/mount/offset?ra_reset=0&dec_reset=0");
734 return true;
735}
736
741{
743 SlewTimeConstantNP.save(fp);
744 return true;
745}
746
750bool PlaneWave::ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n)
751{
752 if (dev != nullptr && strcmp(dev, getDeviceName()) == 0)
753 {
754 // ── Axis 0 motor control ──────────────────────────────────────────
755 if (Axis0MotorSP.isNameMatch(name))
756 {
757 Axis0MotorSP.update(states, names, n);
758 bool enable = (Axis0MotorSP[INDI_ENABLED].getState() == ISS_ON);
759 if (enableAxis(0, enable))
760 {
761 LOGF_INFO("Axis 0 motor %s.", enable ? "enabled" : "disabled");
762 Axis0MotorSP.setState(IPS_OK);
763 }
764 else
765 {
766 LOG_ERROR("Failed to change axis 0 motor state.");
767 Axis0MotorSP.setState(IPS_ALERT);
768 }
769 Axis0MotorSP.apply();
770 return true;
771 }
772
773 // ── Axis 1 motor control ──────────────────────────────────────────
774 if (Axis1MotorSP.isNameMatch(name))
775 {
776 Axis1MotorSP.update(states, names, n);
777 bool enable = (Axis1MotorSP[INDI_ENABLED].getState() == ISS_ON);
778 if (enableAxis(1, enable))
779 {
780 LOGF_INFO("Axis 1 motor %s.", enable ? "enabled" : "disabled");
781 Axis1MotorSP.setState(IPS_OK);
782 }
783 else
784 {
785 LOG_ERROR("Failed to change axis 1 motor state.");
786 Axis1MotorSP.setState(IPS_ALERT);
787 }
788 Axis1MotorSP.apply();
789 return true;
790 }
791
792 // ── Find Home ──────────────────────────────────────────────────────
793 if (FindHomeSP.isNameMatch(name))
794 {
795 if (dispatch("/mount/find_home"))
796 {
797 LOG_INFO("Home finding sequence started.");
798 FindHomeSP.setState(IPS_BUSY);
799 }
800 else
801 {
802 LOG_ERROR("Failed to start home finding.");
803 FindHomeSP.setState(IPS_ALERT);
804 }
805 // Reset the button to Off (momentary action)
806 FindHomeSP[0].setState(ISS_OFF);
807 FindHomeSP.apply();
808 return true;
809 }
810
811 // ── Pointing model operations ──────────────────────────────────────
812 if (ModelOperationSP.isNameMatch(name))
813 {
814 ModelOperationSP.update(states, names, n);
815 bool ok = false;
816
817 if (ModelOperationSP[MODEL_SAVE_AS_DEFAULT].getState() == ISS_ON)
818 {
819 ok = dispatch("/mount/model/save_as_default");
820 if (ok)
821 LOG_INFO("Pointing model saved as default.");
822 else
823 LOG_ERROR("Failed to save pointing model as default.");
824 }
825 else if (ModelOperationSP[MODEL_CLEAR_POINTS].getState() == ISS_ON)
826 {
827 ok = dispatch("/mount/model/clear_points");
828 if (ok)
829 LOG_INFO("All pointing model calibration points cleared.");
830 else
831 LOG_ERROR("Failed to clear pointing model points.");
832 }
833
834 // Reset buttons (momentary)
835 ModelOperationSP[MODEL_SAVE_AS_DEFAULT].setState(ISS_OFF);
836 ModelOperationSP[MODEL_CLEAR_POINTS].setState(ISS_OFF);
837 ModelOperationSP.setState(ok ? IPS_OK : IPS_ALERT);
838 ModelOperationSP.apply();
839 return true;
840 }
841 }
842
843 return INDI::Telescope::ISNewSwitch(dev, name, states, names, n);
844}
845
849bool PlaneWave::ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n)
850{
851 if (dev != nullptr && strcmp(dev, getDeviceName()) == 0)
852 {
853 // ── Load model by filename ─────────────────────────────────────────
854 if (ModelLoadFilenameTP.isNameMatch(name))
855 {
856 ModelLoadFilenameTP.update(texts, names, n);
857 const char *filename = ModelLoadFilenameTP[0].getText();
858 std::string req = "/mount/model/load?filename=";
859 req += filename;
860
861 if (dispatch(req))
862 {
863 LOGF_INFO("Pointing model '%s' loaded.", filename);
864 ModelLoadFilenameTP.setState(IPS_OK);
865 }
866 else
867 {
868 LOGF_ERROR("Failed to load pointing model '%s'.", filename);
869 ModelLoadFilenameTP.setState(IPS_ALERT);
870 }
871 ModelLoadFilenameTP.apply();
872 return true;
873 }
874
875 // ── Save model with filename ───────────────────────────────────────
876 if (ModelSaveFilenameTP.isNameMatch(name))
877 {
878 ModelSaveFilenameTP.update(texts, names, n);
879 const char *filename = ModelSaveFilenameTP[0].getText();
880 std::string req = "/mount/model/save?filename=";
881 req += filename;
882
883 if (dispatch(req))
884 {
885 LOGF_INFO("Pointing model saved as '%s'.", filename);
886 ModelSaveFilenameTP.setState(IPS_OK);
887 }
888 else
889 {
890 LOGF_ERROR("Failed to save pointing model as '%s'.", filename);
891 ModelSaveFilenameTP.setState(IPS_ALERT);
892 }
893 ModelSaveFilenameTP.apply();
894 return true;
895 }
896 }
897
898 return INDI::Telescope::ISNewText(dev, name, texts, names, n);
899}
900
904bool PlaneWave::ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n)
905{
906 if (dev != nullptr && strcmp(dev, getDeviceName()) == 0)
907 {
908 // ── Slew time constant ─────────────────────────────────────────────
909 if (SlewTimeConstantNP.isNameMatch(name))
910 {
911 SlewTimeConstantNP.update(values, names, n);
912 double tc = SlewTimeConstantNP[0].getValue();
913
914 std::ostringstream req;
915 req << std::fixed << std::setprecision(3)
916 << "/mount/set_slew_time_constant?value=" << tc;
917
918 if (dispatch(req.str()))
919 {
920 LOGF_INFO("Slew time constant set to %.2f s.", tc);
921 SlewTimeConstantNP.setState(IPS_OK);
922 }
923 else
924 {
925 LOG_ERROR("Failed to set slew time constant.");
926 SlewTimeConstantNP.setState(IPS_ALERT);
927 }
928 SlewTimeConstantNP.apply();
929 return true;
930 }
931 }
932
933 return INDI::Telescope::ISNewNumber(dev, name, values, names, n);
934}
935
939bool PlaneWave::enableAxis(int axis, bool enable)
940{
941 std::ostringstream req;
942 req << (enable ? "/mount/enable?axis=" : "/mount/disable?axis=") << axis;
943 return dispatch(req.str());
944}
945
949double PlaneWave::getSlewRateArcsecPerSec() const
950{
951 int idx = SlewRateSP.findOnSwitchIndex();
952 if (idx >= 0 && idx < 4)
953 return SLEW_RATES[idx];
954 return SLEW_RATES[3]; // default to fast if unknown
955}
956
964bool PlaneWave::dispatch(const std::string &request)
965{
966 if (!m_HttpClient)
967 {
968 LOG_ERROR("HTTP client not initialized. Is the mount connected?");
969 return false;
970 }
971
972 auto res = m_HttpClient->Get(request);
973
974 if (!res)
975 {
976 LOGF_ERROR("HTTP GET %s failed: %s",
977 request.c_str(),
978 httplib::to_string(res.error()).c_str());
979 return false;
980 }
981
982 if (res->status != 200)
983 {
984 LOGF_ERROR("HTTP GET %s returned HTTP %d: %s",
985 request.c_str(), res->status,
986 res->body.empty() ? "(no body)" : res->body.c_str());
987 return false;
988 }
989
990 if (res->body.empty())
991 {
992 LOGF_ERROR("HTTP GET %s returned an empty body.", request.c_str());
993 return false;
994 }
995
996 try
997 {
998 // PWI4 returns a flat key=value format. Wrap it in a dummy [status]
999 // section so that inicpp can parse it as a standard INI file.
1000 ini::IniFile inif;
1001 inif.decode("[status]\n" + res->body);
1002
1003 if (inif["status"].size() == 0)
1004 {
1005 LOGF_ERROR("Parsed status for %s is empty.", request.c_str());
1006 return false;
1007 }
1008
1009 m_Status = inif["status"];
1010 return true;
1011 }
1012 catch (const std::exception &e)
1013 {
1014 LOGF_ERROR("Failed to parse PWI4 response for %s: %s",
1015 request.c_str(), e.what());
1016 return false;
1017 }
1018}
bool isConnected() const
INDI::PropertyText getText(const char *name) 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)
void addAuxControls()
Add Debug, Simulation, and Configuration options 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.
virtual bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n) override
Process the client newSwitch command.
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 ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n) override
Process the client newNumber command.
void NewRaDec(double ra, double dec)
The child class calls this function when it has updates.
void setPierSide(TelescopePierSide side)
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...
virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n) override
Process the client newSwitch command.
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 UnPark() override
UnPark — re-enable both motors before clearing the parked state.
virtual bool Abort() override
Abort.
virtual bool updateLocation(double latitude, double longitude, double elevation) override
virtual ~PlaneWave()
virtual bool Sync(double ra, double dec) override
Sync — adds a pointing-model calibration point at the current position.
virtual bool Goto(double ra, double dec) override
Goto — J2000 RA/Dec (INDI convention).
virtual bool SetTrackRate(double raRate, double deRate) override
SetTrackRate — called when the user changes TrackRateNP.
virtual bool Park() override
Park.
virtual bool updateProperties() override
updateProperties
virtual bool SetDefaultPark() override
SetDefaultPark.
virtual bool Handshake() override
Handshake — build the persistent client and verify the mount is live.
virtual bool initProperties() override
initProperties
virtual const char * getDefaultName() override
virtual bool MoveNS(INDI_DIR_NS dir, TelescopeMotionCommand command) override
MoveNS — jog in Dec using a continuous offset rate.
virtual bool SetTrackEnabled(bool enabled) override
SetTrackEnabled.
virtual bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n) override
ISNewText.
virtual bool updateTime(ln_date *utc, double utc_offset) override
updateTime — PWI4 uses the host PC clock; nothing to push.
virtual bool ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n) override
ISNewNumber.
PlaneWave()
Constructor / Destructor.
virtual bool MoveWE(INDI_DIR_WE dir, TelescopeMotionCommand command) override
MoveWE — jog in RA using a continuous offset rate.
virtual bool SetTrackMode(uint8_t mode) override
SetTrackMode.
virtual bool saveConfigItems(FILE *fp) override
saveConfigItems
virtual bool ReadScopeStatus() override
ReadScopeStatus — called every polling interval.
virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n) override
ISNewSwitch.
virtual bool SetCurrentPark() override
SetCurrentPark — tell PWI4 to store the current position as the park point.
void decode(std::istream &is)
Definition inicpp.h:586
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.
const char * OPTIONS_TAB
OPTIONS_TAB Where all the driver's options are located. Those may include auxiliary controls,...
INDI::PropertyNumber TrackRateNP
INDI::PropertySwitch SlewRateSP
INDI::PropertySwitch TrackModeSP
INDI::PropertyNumber LocationNP
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
@ 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
INDI_DIR_NS
@ DIRECTION_SOUTH
Implementations for common driver routines.
#define INDI_UNUSED(x)
Definition indidevapi.h:132
int dispatch(XMLEle *root, char msg[])
Definition indidriver.c:180
*brief user defined string literal for JSON values *sa std::size_t n
#define LOGF_INFO(fmt,...)
Definition indilogger.h:82
#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
IniFileBase< std::less< std::string > > IniFile
Definition inicpp.h:739
json_pointer res
std::unique_ptr< PlaneWave > PlaneWave_mount(new PlaneWave())