Instrument Neutral Distributed Interface INDI 2.2.5
ccd_simulator.cpp
Go to the documentation of this file.
1/*******************************************************************************
2 Copyright(c) 2017 Jasem Mutlaq. All rights reserved.
3 Copyright(c) 2010 Gerry Rozema. All rights reserved.
4 This library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public
6 License version 2 as published by the Free Software Foundation.
7 .
8 This library is distributed in the hope that it will be useful,
9 but WITHOUT ANY WARRANTY; without even the implied warranty of
10 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 Library General Public License for more details.
12 .
13 You should have received a copy of the GNU Library General Public License
14 along with this library; see the file COPYING.LIB. If not, write to
15 the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
16 Boston, MA 02110-1301, USA.
17*******************************************************************************/
18
19#include "ccd_simulator.h"
20#include "indicom.h"
22
23#include <libnova/julian_day.h>
24#include <libastro.h>
25
26#ifdef HAVE_XISF
27#include <libxisf.h>
28#endif
29
30#include <cmath>
31#include <cstdio>
32#include <cstring>
33#include <strings.h>
34#include <unistd.h>
35#include <sys/types.h>
36#include <dirent.h>
37#include <sys/stat.h>
38#include <algorithm>
39#include <chrono>
40#include <random>
41#include <thread>
42
43static pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
44static pthread_mutex_t condMutex = PTHREAD_MUTEX_INITIALIZER;
45
46static std::unique_ptr<CCDSim> ccdsim(new CCDSim());
47
49{
50 currentRA = RA;
51 currentDE = Dec;
52
53 terminateThread = false;
54
55 time(&RunStart);
56
57 // Filter stuff
58 FilterSlotNP[0].setMin(1);
59 FilterSlotNP[0].setMax(8);
60}
61
63{
65 SimulatorSettingsNP[SIM_YRES].getValue(),
66 16,
68 SimulatorSettingsNP[SIM_YSIZE].getValue());
69
73 m_Bias = OffsetNP[0].getValue();
76 // An oag is offset this much from center of scope position (arcminutes);
83 // This is the rotation of the simulated camera respective to North.
84 // Because the simulated star field is calculated with their RA/DEC-coordinates
85 // (see DrawCcdFrame()) the origin angle of star field points north. So this value
86 // simulates a certain camera offset and is a constant. On an ALTAZ mount cameraRotation()
87 // adds the parallactic angle to it, which simulates the field rotation.
89
90 uint32_t nbuf = PrimaryCCD.getXRes() * PrimaryCCD.getYRes() * PrimaryCCD.getBPP() / 8;
91 PrimaryCCD.setFrameBufferSize(nbuf);
92
93 if (!m_PlanetMode)
94 Streamer->setPixelFormat(INDI_MONO, 16);
95 Streamer->setSize(PrimaryCCD.getXRes(), PrimaryCCD.getYRes());
96
97 return true;
98}
99
101{
102 streamPredicate = 0;
103 terminateThread = false;
104 pthread_create(&primary_thread, nullptr, &streamVideoHelper, this);
106 return true;
107}
108
110{
111 pthread_mutex_lock(&condMutex);
112 streamPredicate = 1;
113 terminateThread = true;
114 pthread_cond_signal(&cv);
115 pthread_mutex_unlock(&condMutex);
116
117 return true;
118}
119
121{
122 return "CCD Simulator";
123}
124
126{
128
129 m_Clock.initProperties(getDeviceName(), SITE_TAB);
130
131 // Constrain temperature range to match TEC physics: -15°C to ambient (25°C)
132 TemperatureNP[0].setMin(-15);
133 TemperatureNP[0].setMax(25);
134 TemperatureNP[0].setValue(0);
135
136 CaptureFormat format = {"INDI_MONO", "Mono", 16, true};
137 addCaptureFormat(format);
138
139 // Planet mode uses RGB capture format
140 CaptureFormat rgbFormat = {"INDI_RGB", "RGB", 16, false};
141 addCaptureFormat(rgbFormat);
142
143 SimulatorSettingsNP[SIM_XRES].fill("SIM_XRES", "X resolution", "%4.0f", 512, 8192, 512, 1280);
144 SimulatorSettingsNP[SIM_YRES].fill("SIM_YRES", "Y resolution", "%4.0f", 512, 8192, 512, 1024);
145 SimulatorSettingsNP[SIM_XSIZE].fill("SIM_XSIZE", "X Pixel Size", "%4.2f", 1, 30, 5, 5.2);
146 SimulatorSettingsNP[SIM_YSIZE].fill("SIM_YSIZE", "Y Pixel Size", "%4.2f", 1, 30, 5, 5.2);
147 SimulatorSettingsNP[SIM_MAXVAL].fill("SIM_MAXVAL", "Maximum ADU", "%4.0f", 255, 65000, 1000, 65000);
148 SimulatorSettingsNP[SIM_SATURATION].fill("SIM_SATURATION", "Saturation Mag", "%4.1f", 0, 20, 1, 1.0);
149 SimulatorSettingsNP[SIM_LIMITINGMAG].fill("SIM_LIMITINGMAG", "Limiting Mag", "%4.1f", 0, 20, 1, 17.0);
150 SimulatorSettingsNP[SIM_NOISE].fill("SIM_NOISE", "Noise", "%4.0f", 0, 6000, 500, 10);
151 SimulatorSettingsNP[SIM_SKYGLOW].fill("SIM_SKYGLOW", "Sky Glow (magnitudes)", "%4.1f", 0, 6000, 500, 19.5);
152 SimulatorSettingsNP[SIM_OAGOFFSET].fill("SIM_OAGOFFSET", "Oag Offset (arcminutes)", "%4.1f", 0, 6000, 500, 0);
153 SimulatorSettingsNP[SIM_POLAR].fill("SIM_POLAR", "PAE (arcminutes)", "%4.1f", -600, 600, 100, 0);
154 SimulatorSettingsNP[SIM_POLARDRIFT].fill("SIM_POLARDRIFT", "PAE Drift (minutes)", "%4.1f", 0, 60, 5, 0);
155 SimulatorSettingsNP[SIM_PE_PERIOD].fill("SIM_PEPERIOD", "PE Period (seconds)", "%4.1f", 0, 60, 5, 0);
156 SimulatorSettingsNP[SIM_PE_MAX].fill("SIM_PEMAX", "PE Max (arcsec)", "%4.1f", 0, 6000, 500, 0);
157 SimulatorSettingsNP[SIM_TIME_FACTOR].fill("SIM_TIME_FACTOR", "Time Factor (x)", "%.2f", 0.01, 100, 10, 1);
158 SimulatorSettingsNP[SIM_ROTATION].fill("SIM_ROTATION", "Rotation Offset", "%.2f", -180, 180, 10, 0);
159
160 SimulatorSettingsNP.fill(getDeviceName(), "SIMULATOR_SETTINGS",
161 "Settings", SIMULATOR_TAB, IP_RW, 60, IPS_IDLE);
162 // load() is important to fill all editfields with saved values also, so ISNewNumber() of one field
163 // doesn't update the other fields of the group with the "old" contents.
164 SimulatorSettingsNP.load();
165
166 // Sim Tests
167 SimTestsSP[SIM_TESTS_BAYER].fill("BAYER", "Bayer", ISS_OFF);
168 SimTestsSP[SIM_TESTS_CRASH].fill("CRASH", "Crash", ISS_OFF);
169 SimTestsSP[SIM_TESTS_TIMEOUT].fill("TIMEOUT", "Timeout", ISS_OFF);
170 SimTestsSP.fill(getDeviceName(), "SIM_TESTS", "Sim Tests", SIMULATOR_TAB, IP_RW,
171 ISR_NOFMANY, 60, IPS_IDLE);
172
173 // Simulate focusing
174 FocusSimulationNP[SIM_FOCUS_POSITION].fill("SIM_FOCUS_POSITION", "Focus", "%.f", 0.0, 100000.0, 1.0, 36700.0);
175 FocusSimulationNP[SIM_FOCUS_MAX].fill("SIM_FOCUS_MAX", "Max. Position", "%.f", 0.0, 100000.0, 1.0, 100000.0);
176 FocusSimulationNP[SIM_SEEING].fill("SIM_SEEING", "Seeing (arcsec)", "%4.2f", 0, 60, 0, 3.5);
177 FocusSimulationNP.fill(getDeviceName(), "SIM_FOCUSING", "Focus Simulation",
179
180 // Simulate sensor tilt (extra defocus in arcsec at sensor edge)
181 TiltSimulationNP[SIM_TILT_LR].fill("SIM_TILT_LR", "Left-Right (arcsec)", "%4.2f", 0, 20, 0.5, 0);
182 TiltSimulationNP[SIM_TILT_TB].fill("SIM_TILT_TB", "Top-Bottom (arcsec)", "%4.2f", 0, 20, 0.5, 0);
183 TiltSimulationNP.fill(getDeviceName(), "SIM_TILT", "Tilt Simulation",
185
186 // Simulate fixed sensor defects. Hot pixels gain (rate x exposure) ADU in every frame type,
187 // cold pixels read half the CCD_OFFSET bias. The layout is the same in every session.
188 DefectSimulationNP[SIM_HOT_PIXELS].fill("SIM_HOT_PIXELS", "Hot pixels", "%.f", 0, 100000, 100, 0);
189 DefectSimulationNP[SIM_COLD_PIXELS].fill("SIM_COLD_PIXELS", "Cold pixels", "%.f", 0, 100000, 100, 0);
190 DefectSimulationNP[SIM_HOT_RATE].fill("SIM_HOT_RATE", "Hot rate (ADU/s)", "%.f", 0, 65000, 100, 1000);
191 DefectSimulationNP.fill(getDeviceName(), "SIM_DEFECTS", "Sensor Defects",
193
194 // Periodic Error
195 EqPENP[AXIS_RA].fill("RA_PE", "RA (hh:mm:ss)", "%010.6m", 0, 24, 0, 0);
196 EqPENP[AXIS_DE].fill("DEC_PE", "DEC (dd:mm:ss)", "%010.6m", -90, 90, 0, 0);
197 EqPENP.fill(getDeviceName(), "EQUATORIAL_PE", "EQ PE", SIMULATOR_TAB, IP_RW, 60,
198 IPS_IDLE);
199
200 // Field rotation of an ALTAZ mount
201 FieldRotationNP[0].fill("SIM_PARALLACTIC_ANGLE", "Parallactic Angle", "%.3f", -180, 180, 0, 0);
202 FieldRotationNP.fill(getDeviceName(), "SIM_FIELD_ROTATION", "Field Rotation", SIMULATOR_TAB, IP_RO, 60,
203 IPS_IDLE);
204
205 // Pointing offset, added to the mount coordinates before rendering
206 PointingOffsetNP[SIM_OFFSET_RA].fill("SIM_OFFSET_RA", "RA Offset (deg)", "%.4f", -180, 180, 0, 0);
207 PointingOffsetNP[SIM_OFFSET_DE].fill("SIM_OFFSET_DE", "DE Offset (deg)", "%.4f", -90, 90, 0, 0);
208 PointingOffsetNP.fill(getDeviceName(), "SIM_POINTING_OFFSET", "Pointing Offset", SIMULATOR_TAB, IP_RW, 60,
209 IPS_IDLE);
210 PointingOffsetNP.load();
211
212 // FWHM
213 auto focuser = ActiveDeviceTP[ACTIVE_FOCUSER].getText() ? ActiveDeviceTP[ACTIVE_FOCUSER].getText() : "";
214 IUFillNumber(&FWHMN[0], "SIM_FWHM", "FWHM (arcseconds)", "%4.2f", 0, 60, 0, 7.5);
215 IUFillNumberVector(&FWHMNP, FWHMN, 1, focuser, "FWHM", "FWHM", OPTIONS_TAB, IP_RO, 60, IPS_IDLE);
216
217 // Cooler
218 CoolerSP[INDI_ENABLED].fill("COOLER_ON", "ON", ISS_OFF);
219 CoolerSP[INDI_DISABLED].fill("COOLER_OFF", "OFF", ISS_ON);
220 CoolerSP.fill(getDeviceName(), "CCD_COOLER", "Cooler", MAIN_CONTROL_TAB, IP_WO,
222
223 // Gain
224 GainNP[0].fill("GAIN", "value", "%.f", 0, 300, 10, 90);
225 GainNP.fill(getDeviceName(), "CCD_GAIN", "Gain", MAIN_CONTROL_TAB, IP_RW, 60, IPS_IDLE);
226
227 // Offset
228 OffsetNP[0].fill("OFFSET", "value", "%.f", 0, 6000, 500, 0);
229 OffsetNP.fill(getDeviceName(), "CCD_OFFSET", "Offset", MAIN_CONTROL_TAB, IP_RW, 60, IPS_IDLE);
230
231 // Directory to read images from. This is useful to test real images captured by camera
232 // For each capture, one file is read (sorted by name) and is sent to client.
233 DirectoryTP[0].fill("LOCATION", "Location", getenv("HOME"));
234 DirectoryTP.fill(getDeviceName(), "CCD_DIRECTORY_LOCATION", "Directory", SIMULATOR_TAB, IP_RW, 60, IPS_IDLE);
235 DirectoryTP.load();
236
237 // Toggle Directory Reading. If enabled. The simulator will just read images from the directory and not generate them.
238 DirectorySP[INDI_ENABLED].fill("INDI_ENABLED", "Enabled", ISS_OFF);
239 DirectorySP[INDI_DISABLED].fill("INDI_DISABLED", "Disabled", ISS_ON);
240 DirectorySP.fill(getDeviceName(), "CCD_DIRECTORY_TOGGLE", "Use Dir.", SIMULATOR_TAB, IP_RW, ISR_1OFMANY, 60, IPS_IDLE);
241
242 // Resolution
243 for (uint8_t i = 0; i < Resolutions.size(); i++)
244 {
245 std::ostringstream ss;
246 if (Resolutions[i].first > 0)
247 ss << Resolutions[i].first << " x " << Resolutions[i].second;
248 else
249 ss << "Custom";
250 ResolutionSP[i].fill(ss.str().c_str(), ss.str().c_str(), i == 0 ? ISS_ON : ISS_OFF);
251 }
252 ResolutionSP.fill(getDeviceName(), "CCD_RESOLUTION", "Resolution", SIMULATOR_TAB, IP_RW, ISR_1OFMANY, 60, IPS_IDLE);
253
254 auto mount = ActiveDeviceTP[ACTIVE_TELESCOPE].getText() ? ActiveDeviceTP[ACTIVE_TELESCOPE].getText() : "";
255
256#ifdef USE_EQUATORIAL_PE
257 IDSnoopDevice(mount, "EQUATORIAL_PE");
258#else
259 IDSnoopDevice(mount, "EQUATORIAL_EOD_COORD");
260#endif
261 IDSnoopDevice(mount, "TELESCOPE_MOUNT_TYPE");
262
263 IDSnoopDevice(focuser, "FWHM");
264
265 uint32_t cap = 0;
266
267 cap |= CCD_CAN_ABORT;
268 cap |= CCD_CAN_BIN;
269 cap |= CCD_CAN_SUBFRAME;
270 cap |= CCD_HAS_COOLER;
271 cap |= CCD_HAS_GUIDE_HEAD;
272 cap |= CCD_HAS_SHUTTER;
273 cap |= CCD_HAS_ST4_PORT;
274 cap |= CCD_HAS_STREAMING;
275 cap |= CCD_HAS_DSP;
276
277 SetCCDCapability(cap);
278
279 // This should be called after the initial SetCCDCapability (above)
280 // as it modifies the capabilities.
282
284
285 FilterSlotNP[0].setMin(1);
286 FilterSlotNP[0].setMax(8);
287
288 // ===================== Planet Simulation =====================
289
290 // Planet mode toggle
291 PlanetModeSP[PLANET_ENABLED].fill("PLANET_ENABLED", "Enabled", ISS_OFF);
292 PlanetModeSP[PLANET_DISABLED].fill("PLANET_DISABLED", "Disabled", ISS_ON);
293 PlanetModeSP.fill(getDeviceName(), "PLANET_MODE", "Planet Mode", PLANET_TAB, IP_RW, ISR_1OFMANY, 60, IPS_IDLE);
294
295 // Planet selection
296 PlanetSelectSP[PLANET_MERCURY].fill("PLANET_MERCURY", "Mercury", ISS_OFF);
297 PlanetSelectSP[PLANET_VENUS].fill("PLANET_VENUS", "Venus", ISS_OFF);
298 PlanetSelectSP[PLANET_MARS].fill("PLANET_MARS", "Mars", ISS_OFF);
299 PlanetSelectSP[PLANET_JUPITER].fill("PLANET_JUPITER", "Jupiter", ISS_ON);
300 PlanetSelectSP[PLANET_SATURN].fill("PLANET_SATURN", "Saturn", ISS_OFF);
301 PlanetSelectSP[PLANET_URANUS].fill("PLANET_URANUS", "Uranus", ISS_OFF);
302 PlanetSelectSP[PLANET_NEPTUNE].fill("PLANET_NEPTUNE", "Neptune", ISS_OFF);
303 PlanetSelectSP[PLANET_MOON].fill("PLANET_MOON", "Moon", ISS_OFF);
304 PlanetSelectSP[PLANET_SUN].fill("PLANET_SUN", "Sun", ISS_OFF);
305 PlanetSelectSP.fill(getDeviceName(), "PLANET_SELECT", "Planet", PLANET_TAB, IP_RW, ISR_1OFMANY, 60, IPS_IDLE);
306
307 // Planet settings: refresh interval (minutes) and size override (arcsec)
308 PlanetSettingsNP[PLANET_REFRESH].fill("PLANET_REFRESH", "Refresh (min)", "%4.0f", 1, 1440, 10, 60);
309 PlanetSettingsNP[PLANET_SIZE].fill("PLANET_SIZE", "Size (arcsec, 0=auto)", "%4.1f", 0, 3600, 10, 0);
310 PlanetSettingsNP.fill(getDeviceName(), "PLANET_SETTINGS", "Planet Settings", PLANET_TAB, IP_RW, 60, IPS_IDLE);
311 PlanetSettingsNP.load();
312
313 // Planet drift: tracking error (positive RA drift moves the planet east, positive DE drift north),
314 // seeing jitter added to every frame, and transparency to simulate clouds
315 PlanetDriftNP[PLANET_DRIFT_RA].fill("PLANET_DRIFT_RA", "RA Drift (arcsec/min)", "%.1f", -600, 600, 10, 0);
316 PlanetDriftNP[PLANET_DRIFT_DE].fill("PLANET_DRIFT_DE", "DE Drift (arcsec/min)", "%.1f", -600, 600, 10, 0);
317 PlanetDriftNP[PLANET_JITTER].fill("PLANET_JITTER", "Jitter (arcsec RMS)", "%.1f", 0, 60, 0.5, 0);
318 PlanetDriftNP[PLANET_TRANSPARENCY].fill("PLANET_TRANSPARENCY", "Transparency (%)", "%.f", 0, 100, 10, 100);
319 PlanetDriftNP.fill(getDeviceName(), "PLANET_DRIFT", "Planet Drift", PLANET_TAB, IP_RW, 60, IPS_IDLE);
320 PlanetDriftNP.load();
321
322 PlanetRecenterSP[0].fill("PLANET_RECENTER", "Recenter", ISS_OFF);
323 PlanetRecenterSP.fill(getDeviceName(), "PLANET_RECENTER", "Recenter", PLANET_TAB, IP_RW, ISR_ATMOST1, 60, IPS_IDLE);
324
325 // xplanet executable and config paths
326 PlanetPathsTP[PLANET_XPLANET_PATH].fill("XPLANET_PATH", "xplanet binary", "xplanet");
327 PlanetPathsTP[PLANET_XPLANET_CONFIG].fill("XPLANET_CONFIG", "Config file", "/usr/share/xplanet/config/default");
328 PlanetPathsTP.fill(getDeviceName(), "PLANET_PATHS", "xplanet Paths", PLANET_TAB, IP_RW, 60, IPS_IDLE);
329 PlanetPathsTP.load();
330
332
334
335 return true;
336}
337
339{
340 if (onOff)
341 {
343 BayerTP[CFA_OFFSET_X].setText("0");
344 BayerTP[CFA_OFFSET_Y].setText("0");
345 BayerTP[CFA_TYPE].setText("RGGB");
346 }
347 else
348 {
350 }
351}
352
374
376{
378
379 m_Clock.updateProperties(this, isConnected());
380
381 if (isConnected())
382 {
383 if (HasCooler())
385
388
392
394
395 if (HasGuideHead())
396 {
397 SetGuiderParams(500, 290, 16, 9.8, 12.6);
398 GuideCCD.setFrameBufferSize(GuideCCD.getXRes() * GuideCCD.getYRes() * 2);
399 }
400
401 // Define the Filter Slot and name properties
403 }
404 else
405 {
406 if (HasCooler())
408
414
416 }
417
418 return true;
419}
420
422{
424 if (std::abs(temperature - TemperatureNP[0].getValue()) < 0.1)
425 {
426 TemperatureNP[0].setValue(temperature);
427 return 1;
428 }
429
430 auto isCooling = temperature < TemperatureNP[0].getValue();
431 CoolerSP[INDI_ENABLED].setState(isCooling ? ISS_ON : ISS_OFF);
432 CoolerSP[INDI_DISABLED].setState(isCooling ? ISS_OFF : ISS_ON);
433 CoolerSP.setState(isCooling ? IPS_BUSY : IPS_IDLE);
434 CoolerSP.apply();
435 return 0;
436}
437
438bool CCDSim::StartExposure(float duration)
439{
440 // for the simulator, we can just draw the frame now
441 // and it will get returned at the right time
442 // by the timer routines
443 AbortPrimaryFrame = false;
444 ExposureRequest = duration;
445
446 PrimaryCCD.setExposureDuration(duration);
447 gettimeofday(&ExpStart, nullptr);
448
449 // Planet mode: draw the cached xplanet sprite at the current planet position
450 if (m_PlanetMode && PrimaryCCD.getFrameType() == INDI::CCDChip::LIGHT_FRAME)
451 {
452 // Full resolution 3-channel 16-bit planar RGB (NAXIS=3 already set by SetCaptureFormat)
453 uint32_t rgbBufSize = PrimaryCCD.getXRes() * PrimaryCCD.getYRes() * 3 * 2;
454 if (PrimaryCCD.getFrameBufferSize() != static_cast<int>(rgbBufSize))
455 PrimaryCCD.setFrameBufferSize(rgbBufSize);
456
457 std::lock_guard<std::mutex> lock(m_PlanetMutex);
458 uint16_t *buffer = reinterpret_cast<uint16_t *>(PrimaryCCD.getFrameBuffer());
459 if (renderPlanet())
460 {
461 double centerX, centerY;
462 planetPosition(centerX, centerY);
463 drawPlanetRGB16(buffer, centerX, centerY);
464 }
465 else
466 {
467 // Fallback to blank frame on failure
468 memset(buffer, 0, PrimaryCCD.getFrameBufferSize());
469 }
470 }
471 // When the directory is enabled, load every frame type (LIGHT, DARK, BIAS, FLAT)
472 // from the watched folder instead of generating a synthetic frame.
473 else if (DirectorySP[INDI_ENABLED].getState() == ISS_ON)
474 {
475 if (loadNextImage() == false)
476 return false;
477 }
478 else
479 {
480 // Reset to mono (NAXIS=2) if coming from planet mode
481 if (PrimaryCCD.getNAxis() == 3)
482 {
483 PrimaryCCD.setNAxis(2);
484 uint32_t nbuf = PrimaryCCD.getXRes() * PrimaryCCD.getYRes() * PrimaryCCD.getBPP() / 8;
485 PrimaryCCD.setFrameBufferSize(nbuf);
486 // Re-enable Bayer if previously enabled (not applicable during planet mode)
488 }
490 }
491
492 // Now compress the actual wait time
493 ExposureRequest = duration * m_TimeFactor;
494 InExposure = true;
495
496 return true;
497}
498
500{
502 AbortGuideFrame = false;
503 GuideCCD.setExposureDuration(n);
505 gettimeofday(&GuideExpStart, nullptr);
506 InGuideExposure = true;
507 return true;
508}
509
511{
512 if (!InExposure)
513 return true;
514
515 AbortPrimaryFrame = true;
516
517 return true;
518}
519
521{
522 //IDLog("Enter AbortGuideExposure\n");
523 if (!InGuideExposure)
524 return true; // no need to abort if we aren't doing one
525 AbortGuideFrame = true;
526 return true;
527}
528
530{
531 uint32_t nextTimer = getCurrentPollingPeriod();
532
533 // No need to reset timer if we are not connected anymore
534 if (!isConnected())
535 return;
536
538 {
540 {
541 InExposure = false;
542 AbortPrimaryFrame = false;
543 }
544 else
545 {
546 float timeleft;
548
549 //IDLog("CCD Exposure left: %g - Request: %g\n", timeleft, ExposureRequest);
550 if (timeleft < 0)
551 timeleft = 0;
552
553 PrimaryCCD.setExposureLeft(timeleft);
554
555 if (timeleft < 1.0)
556 {
557 if (timeleft <= 0.001)
558 {
559 InExposure = false;
560 // Skip binning for planet mode (RGB data) and directory mode; only bin for generated star fields
561 if (!m_PlanetMode && DirectorySP[INDI_DISABLED].getState() == ISS_ON)
562 PrimaryCCD.binFrame();
564 }
565 else
566 {
567 // set a shorter timer
568 nextTimer = timeleft * 1000;
569 }
570 }
571 }
572 }
573
574 if (InGuideExposure)
575 {
577 if (timeleft < 0)
578 timeleft = 0;
579
580 GuideCCD.setExposureLeft(timeleft);
581
582 if (timeleft < 1.0)
583 {
584 if (timeleft <= 0.001)
585 {
586 InGuideExposure = false;
587 if (!AbortGuideFrame)
588 {
589 GuideCCD.binFrame();
591 if (InGuideExposure)
592 {
593 // the call to complete triggered another exposure
595 if (timeleft < 1.0)
596 {
597 nextTimer = timeleft * 1000;
598 }
599 }
600 }
601 else
602 {
603 //IDLog("Not sending guide frame cuz of abort\n");
604 }
605 AbortGuideFrame = false;
606 }
607 else
608 {
609 nextTimer = timeleft * 1000; // set a shorter timer
610 }
611 }
612 }
613
614 // Simulate realistic TEC cooler with ambient temperature of 25°C.
615 // Minimum achievable temperature: 40°C below ambient (-15°C).
616 // Warming up beyond ambient is not possible (TEC cannot heat).
617 constexpr double AMBIENT_TEMPERATURE = 25.0;
618 constexpr double MIN_TEC_TEMPERATURE = -15.0; // 40°C below ambient
619
620 const double currentTemp = TemperatureNP[0].getValue();
621 // Clamp target to achievable range
622 const double targetTemp = std::clamp(TemperatureRequest, MIN_TEC_TEMPERATURE, AMBIENT_TEMPERATURE);
623
624 // The base class declares the target as reached (IPS_OK) as soon as the temperature is within
625 // RAMP_THRESHOLD of the requested target. That is adequate for real hardware which keeps
626 // settling onto its setpoint, so keep simulating while the sensor has not settled onto the
627 // requested setpoint yet, even if the state is no longer BUSY. Otherwise the reported
628 // temperature would freeze at the threshold boundary (e.g. stop at -2.5°C for a -2°C request
629 // with a 0.5°C threshold) and never reach the actual setpoint.
630 if (TemperatureNP.getState() == IPS_BUSY || std::abs(targetTemp - currentTemp) > 0.01)
631 {
632 double newTemp = currentTemp;
633
634 if (targetTemp < newTemp)
635 {
636 // Cooling: approach target at -0.5°C per TimerHit cycle
637 newTemp = std::max(targetTemp, newTemp - 0.5);
638 }
639 else if (targetTemp > newTemp)
640 {
641 // Warming: approach target naturally (ambient), slowing as we get closer
642 // Simulate exponential decay toward ambient
643 double deltaT = AMBIENT_TEMPERATURE - newTemp;
644 // When below ambient, warm up by ~20% of remaining gap per cycle
645 // (roughly 0.4°C at 10°C delta, slowing to ~0.02°C near ambient)
646 double warmingStep = deltaT * 0.2;
647 if (warmingStep < 0.02)
648 warmingStep = 0.02;
649 if (warmingStep > 0.5)
650 warmingStep = 0.5;
651 newTemp = std::min(targetTemp, newTemp + warmingStep);
652 }
653
654 TemperatureNP[0].setValue(newTemp);
655
656 if (std::abs(newTemp - m_LastTemperature) > 0.1)
657 {
658 m_LastTemperature = newTemp;
659 TemperatureNP.apply();
660 }
661
662 // Cooler is effectively off when at or near ambient
663 if (newTemp >= AMBIENT_TEMPERATURE - 0.1 && CoolerSP.getState() != IPS_IDLE)
664 {
665 CoolerSP[INDI_ENABLED].setState(ISS_OFF);
666 CoolerSP[INDI_DISABLED].setState(ISS_ON);
667 CoolerSP.setState(IPS_IDLE);
668 CoolerSP.apply();
669 }
670 }
671
672
673 SetTimer(nextTimer);
674}
675
677{
678 float exposure_time;
679
680 uint16_t * ptr = reinterpret_cast<uint16_t *>(targetChip->getFrameBuffer());
681
682 if (targetChip->getXRes() == 500)
683 exposure_time = GuideExposureRequest * 4;
684 else if (Streamer->isStreaming())
685 exposure_time = (ExposureRequest < 1) ? (ExposureRequest * 100) : ExposureRequest * 2;
686 else
687 exposure_time = ExposureRequest;
688
689 exposure_time *= (1 + sqrt(GainNP[0].getValue()));
690
691 auto targetFocalLength = ScopeInfoNP[FOCAL_LENGTH].getValue() > 0 ? ScopeInfoNP[FOCAL_LENGTH].getValue() :
693
694 if (ShowStarField)
695 {
696 float PEOffset = periodicErrorOffset();
697 double theta = cameraRotation();
698 LOGF_DEBUG("Rotator Angle: %f, Camera Rotation: %f", RotatorAngle, theta);
699
701
702 // Field center: RA in degrees (with PE), Dec with OAG offset and polar drift
703 double ra_deg = currentRA * 15.0 + PEOffset;
704 double cameradec = currentDE + m_OAGOffset / 60.0;
705 double decr = cameradec * 0.0174532925;
706 double decDrift = (m_PolarDrift * m_PolarError * cos(decr)) / 3.81;
707 double dec_deg = cameradec + decDrift / 3600.0;
708
709 INDI::CCDChip::CCD_FRAME ftype = targetChip->getFrameType();
710 bool const isLight = (ftype == INDI::CCDChip::LIGHT_FRAME);
711 bool const isFlat = (ftype == INDI::CCDChip::FLAT_FRAME);
712
713 RenderConfig cfg;
714 cfg.maxVal = m_MaxVal;
717 cfg.seeing = m_Seeing;
718 cfg.tiltLR = TiltSimulationNP[SIM_TILT_LR].getValue();
719 cfg.tiltTB = TiltSimulationNP[SIM_TILT_TB].getValue();
720 // Sky glow: 30% boost for realistic light-frame backgrounds; flat frames use diffuser daylight level
721 cfg.skyGlow = isLight ? m_SkyGlow * 1.3f : m_SkyGlow / 10.0f;
722 m_Renderer.setConfig(cfg);
723
724 std::unique_lock<std::mutex> guard(ccdBufferLock);
725
726 if (isLight || isFlat)
727 {
728 int drawn = m_Renderer.renderFrame(targetChip, ra_deg, dec_deg,
729 targetFocalLength, theta, exposure_time, isLight);
730 if (isLight && drawn < 0)
731 LOG_ERROR("Error launching gsc, is it installed with appropriate environment variables set?");
732 else if (isLight && drawn == 0)
733 LOG_WARN("No stars found in field -- check gsc catalog coverage for this region.");
734 }
735 else
736 {
737 memset(targetChip->getFrameBuffer(), 0, targetChip->getFrameBufferSize());
738 }
739
740 m_Renderer.applyReadoutNoise(targetChip, m_Bias, m_MaxNoise);
741
742 // Defects belong to the primary sensor only; the guide head is a separate sensor.
743 if (targetChip == &PrimaryCCD)
744 {
746 m_Renderer.applyDefects(targetChip, m_Defects, exposure_time, m_Bias);
747 }
748 }
749 else
750 {
751 testvalue++;
752 if (testvalue > 255)
753 testvalue = 0;
754 uint16_t val = testvalue;
755
756 int nbuf = targetChip->getSubW() * targetChip->getSubH();
757
758 for (int x = 0; x < nbuf; x++)
759 {
760 *ptr = val++;
761 ptr++;
762 }
763 }
764 return 0;
765}
766
768{
769 int const xres = PrimaryCCD.getXRes();
770 int const yres = PrimaryCCD.getYRes();
771 int const hot = static_cast<int>(DefectSimulationNP[SIM_HOT_PIXELS].getValue());
772 int const cold = static_cast<int>(DefectSimulationNP[SIM_COLD_PIXELS].getValue());
773 double const rate = DefectSimulationNP[SIM_HOT_RATE].getValue();
774
775 if (xres == m_DefectsXRes && yres == m_DefectsYRes && hot == m_DefectsHot && cold == m_DefectsCold &&
776 rate == m_DefectsRate)
777 return;
778
779 m_Defects = SkyRenderer::generateDefects(xres, yres, hot, cold, static_cast<float>(rate));
780 m_DefectsXRes = xres;
781 m_DefectsYRes = yres;
782 m_DefectsHot = hot;
783 m_DefectsCold = cold;
784 m_DefectsRate = rate;
785 if (hot > 0 || cold > 0)
786 LOGF_DEBUG("Simulating %d hot and %d cold pixels on a %dx%d sensor.", hot, cold, xres, yres);
787}
788
790{
791 if (m_PEPeriod <= 0)
792 return 0;
793
794 time_t now;
795 time(&now);
796 double timesince = difftime(now, RunStart);
797 double PESpot = timesince / m_PEPeriod * 2.0 * 3.14159;
798 return m_PEMax * std::sin(PESpot) / 3600.0f;
799}
800
802{
804 double theta = m_RotationOffset;
805 if (!std::isnan(RotatorAngle))
806 theta += RotatorAngle;
807 // The camera of an ALTAZ mount stays fixed to the horizon, so the sky turns by the parallactic angle.
808 // An ALTAZ mount has no meridian flip, and its pier side is not maintained.
809 if (m_AltAzMount)
810 theta += parallacticAngle();
811 else if (pierSide == 1)
812 theta -= 180;
813 return range360(theta);
814}
815
817{
818 double ra = RA, de = Dec;
819#ifdef USE_EQUATORIAL_PE
820 if (usePE)
821 {
822 ra = raPE;
823 de = decPE;
824 }
825#endif
826 if (std::isnan(ra) || std::isnan(de) || std::isnan(Latitude) || std::isnan(Longitude))
827 return 0;
828
829 // Meeus, Astronomical Algorithms, eq. 14.1: the position angle of the zenith, east of north
830 const double ha = (m_Clock.localSiderealTime(Longitude) - ra) * 15.0 * (M_PI / 180.0);
831 const double dec = de * (M_PI / 180.0);
832 const double lat = Latitude * (M_PI / 180.0);
833 const double q = std::atan2(std::sin(ha), std::tan(lat) * std::cos(dec) - std::sin(dec) * std::cos(ha))
834 * (180.0 / M_PI);
835
836 FieldRotationNP[0].setValue(q);
837 FieldRotationNP.setState(IPS_OK);
838 FieldRotationNP.apply();
839 return q;
840}
841
843{
844 double ra = RA, de = Dec;
845#ifdef USE_EQUATORIAL_PE
846 if (usePE)
847 {
848 ra = raPE;
849 de = decPE;
850 }
851 else
852 {
853 static bool s_warnedNoSnoop = false;
854 if (!s_warnedNoSnoop)
855 {
856 LOG_WARN("EQUATORIAL_PE not yet snooped -- rendering at raw EQUATORIAL_EOD_COORD (mount errors not active)");
857 s_warnedNoSnoop = true;
858 }
859 }
860#endif
861
862 if (std::isnan(ra))
863 {
864 ra = 0;
865 de = 0;
866 }
867
868 // Offset the JNow pointing, so solving the image gives exactly the mount coordinates plus the offset
870
871 INDI::IEquatorialCoordinates epochPos { ra, de }, J2000Pos { 0, 0 };
872 INDI::ObservedToJ2000(&epochPos, m_Clock.julianDate(), &J2000Pos);
873 currentRA = J2000Pos.rightascension + guideWEOffset;
874 currentDE = J2000Pos.declination + guideNSOffset;
875}
876
877void CCDSim::applyPointingOffset(double &ra, double &de)
878{
879 ra = range24(ra + PointingOffsetNP[SIM_OFFSET_RA].getValue() / 15.0);
880 de += PointingOffsetNP[SIM_OFFSET_DE].getValue();
881
882 // Past a pole, continue down the other side of it
883 if (de > 90 || de < -90)
884 {
885 de = (de > 0 ? 180 : -180) - de;
886 ra = range24(ra + 12);
887 }
888}
889
890float CCDSim::CalcTimeLeft(timeval start, float req)
891{
892 struct timeval now
893 {
894 0, 0
895 };
896 gettimeofday(&now, nullptr);
897 double const timesince = (now.tv_sec * 1000.0 + now.tv_usec / 1000.0)
898 - (start.tv_sec * 1000.0 + start.tv_usec / 1000.0);
899 return static_cast<float>(req - timesince / 1000.0);
900}
901
903{
904 guideNSOffset += v / 1000.0 * GuideRate / 3600;
905 return IPS_OK;
906}
907
909{
910 guideNSOffset += v / -1000.0 * GuideRate / 3600;
911 return IPS_OK;
912}
913
915{
916 float c = v / 1000.0 * GuideRate;
917 c = c / 3600.0 / 15.0;
918 c = c / (cos(currentDE * 0.0174532925));
919
920 guideWEOffset += c;
921
922 return IPS_OK;
923}
924
926{
927 float c = v / -1000.0 * GuideRate;
928 c = c / 3600.0 / 15.0;
929 c = c / (cos(currentDE * 0.0174532925));
930
931 guideWEOffset += c;
932
933 return IPS_OK;
934}
935
936bool CCDSim::ISNewText(const char * dev, const char * name, char * texts[], char * names[], int n)
937{
938 if (dev != nullptr && strcmp(dev, getDeviceName()) == 0)
939 {
940 // This is for our device
941 // Now lets see if it's something we process here
942 if (INDI::FilterInterface::processText(dev, name, texts, names, n))
943 return true;
944
945 if (m_Clock.processText(name, texts, names, n))
946 return true;
947
948 if (DirectoryTP.isNameMatch(name))
949 {
950 DirectoryTP.update(texts, names, n);
951 if (DirectorySP[INDI_ENABLED].getState() == ISS_OFF || (DirectorySP[INDI_ENABLED].getState() == ISS_ON && watchDirectory()))
952 DirectoryTP.setState(IPS_OK);
953 else
954 DirectoryTP.setState(IPS_ALERT);
955 DirectoryTP.apply();
957 return true;
958 }
959
960 if (PlanetPathsTP.isNameMatch(name))
961 {
962 PlanetPathsTP.update(texts, names, n);
965 // Invalidate cache to force re-render with new paths
967 PlanetPathsTP.setState(IPS_OK);
968 PlanetPathsTP.apply();
970 return true;
971 }
972 }
973
974 return INDI::CCD::ISNewText(dev, name, texts, names, n);
975}
976
977bool CCDSim::ISNewNumber(const char * dev, const char * name, double values[], char * names[], int n)
978{
979 if (dev != nullptr && strcmp(dev, getDeviceName()) == 0)
980 {
981 if (INDI::FilterInterface::processNumber(dev, name, values, names, n))
982 return true;
983
984 if (GainNP.isNameMatch(name))
985 {
986 GainNP.update(values, names, n);
987 GainNP.setState(IPS_OK);
988 GainNP.apply();
989 return true;
990 }
991 if (OffsetNP.isNameMatch(name))
992 {
993 OffsetNP.update(values, names, n);
994 OffsetNP.setState(IPS_OK);
995 OffsetNP.apply();
996 m_Bias = OffsetNP[0].getValue();
997 return true;
998 }
999 else if (SimulatorSettingsNP.isNameMatch(name))
1000 {
1001 SimulatorSettingsNP.update(values, names, n);
1002 SimulatorSettingsNP.setState(IPS_OK);
1003
1004 // Reset our parameters now
1006 // Invalidate planet cache since FOV/pixel scale may have changed
1008 SimulatorSettingsNP.apply();
1009 saveConfig(true, SimulatorSettingsNP.getName());
1010 return true;
1011 }
1012 // Record PE EQ to simulate different position in the sky than actual mount coordinate
1013 // This can be useful to simulate Periodic Error or cone error or any arbitrary error.
1014 else if (EqPENP.isNameMatch(name))
1015 {
1016 EqPENP.update(values, names, n);
1017 EqPENP.setState(IPS_OK);
1018
1019 RA = EqPENP[AXIS_RA].getValue();
1020 Dec = EqPENP[AXIS_DE].getValue();
1021
1022 // updatePointing() renders from raPE/decPE once usePE is set
1023 raPE = RA;
1024 decPE = Dec;
1025 usePE = true;
1026
1027 EqPENP.apply();
1028 return true;
1029 }
1030 else if (PointingOffsetNP.isNameMatch(name))
1031 {
1032 PointingOffsetNP.update(values, names, n);
1033 PointingOffsetNP.setState(IPS_OK);
1034 PointingOffsetNP.apply();
1036 return true;
1037 }
1038 else if (FocusSimulationNP.isNameMatch(name))
1039 {
1040 // update focus simulation parameters
1041 FocusSimulationNP.update(values, names, n);
1042 FocusSimulationNP.setState(IPS_OK);
1043 FocusSimulationNP.apply();
1044 }
1045 else if (TiltSimulationNP.isNameMatch(name))
1046 {
1047 TiltSimulationNP.update(values, names, n);
1048 TiltSimulationNP.setState(IPS_OK);
1049 TiltSimulationNP.apply();
1050 }
1051 else if (DefectSimulationNP.isNameMatch(name))
1052 {
1053 DefectSimulationNP.update(values, names, n);
1054 DefectSimulationNP.setState(IPS_OK);
1055 DefectSimulationNP.apply();
1056 return true;
1057 }
1058 else if (PlanetDriftNP.isNameMatch(name))
1059 {
1060 PlanetDriftNP.update(values, names, n);
1061 PlanetDriftNP.setState(IPS_OK);
1062 PlanetDriftNP.apply();
1064 return true;
1065 }
1066 else if (PlanetSettingsNP.isNameMatch(name))
1067 {
1068 PlanetSettingsNP.update(values, names, n);
1071 // Invalidate cache so new settings take effect next exposure
1073 PlanetSettingsNP.setState(IPS_OK);
1074 PlanetSettingsNP.apply();
1075 saveConfig(true, PlanetSettingsNP.getName());
1076 return true;
1077 }
1078 }
1079
1080 return INDI::CCD::ISNewNumber(dev, name, values, names, n);
1081}
1082
1083bool CCDSim::ISNewSwitch(const char * dev, const char * name, ISState * states, char * names[], int n)
1084{
1085 if (dev != nullptr && strcmp(dev, getDeviceName()) == 0)
1086 {
1087 // Sim Tests
1088 if (SimTestsSP.isNameMatch(name))
1089 {
1090 SimTestsSP.update(states, names, n);
1091
1092 // Bayer
1093 if (SimTestsSP[SIM_TESTS_BAYER].getState() == ISS_ON)
1094 {
1095 m_SimulateBayer = true;
1097 }
1098 else
1099 {
1100 m_SimulateBayer = false;
1102 }
1104
1105 // Crash
1106 if (SimTestsSP[SIM_TESTS_CRASH].getState() == ISS_ON)
1107 {
1108 abort();
1109 }
1110
1111 // Timeout
1112 if (SimTestsSP[SIM_TESTS_TIMEOUT].getState() == ISS_ON)
1113 {
1114 m_SimulateTimeout = true;
1116 }
1117 else
1118 {
1119 m_SimulateTimeout = false;
1121 }
1122
1123 SimTestsSP.setState(IPS_OK);
1124 SimTestsSP.apply();
1125 return true;
1126 }
1127 else if (CoolerSP.isNameMatch(name))
1128 {
1129 CoolerSP.update(states, names, n);
1130
1131 if (CoolerSP[INDI_ENABLED].getState() == ISS_ON)
1132 CoolerSP.setState(IPS_BUSY);
1133 else
1134 {
1135 CoolerSP.setState(IPS_IDLE);
1136 // When cooler is turned off, warm up to ambient (25°C)
1137 constexpr double AMBIENT_TEMPERATURE = 25.0;
1138 TemperatureRequest = AMBIENT_TEMPERATURE;
1139 m_TargetTemperature = AMBIENT_TEMPERATURE;
1140 TemperatureNP.setState(IPS_BUSY);
1146 m_TemperatureRampTimer.start();
1147 }
1148
1149 CoolerSP.apply();
1150
1151 return true;
1152 }
1153 else if (DirectorySP.isNameMatch(name))
1154 {
1155 DirectorySP.update(states, names, n);
1156 m_AllFiles.clear();
1157 m_RemainingFiles.clear();
1158 if (DirectorySP[INDI_ENABLED].getState() == ISS_ON)
1159 {
1160 if (watchDirectory() == false)
1161 {
1162 DirectorySP[INDI_ENABLED].setState(ISS_OFF);
1163 DirectorySP[INDI_DISABLED].setState(ISS_ON);
1164 DirectorySP.setState(IPS_ALERT);
1165 }
1166 }
1167 else
1168 {
1169 m_RemainingFiles.clear();
1170 DirectorySP.setState(IPS_OK);
1172 LOG_INFO("Directory-based images are disabled.");
1173 }
1174 DirectorySP.apply(nullptr);
1175 return true;
1176 }
1177 else if (ResolutionSP.isNameMatch(name))
1178 {
1179 ResolutionSP.update(states, names, n);
1180 ResolutionSP.setState(IPS_OK);
1181 ResolutionSP.apply();
1182
1183 int index = ResolutionSP.findOnSwitchIndex();
1184 if (index >= 0 && index < static_cast<int>(Resolutions.size() - 1))
1185 {
1186 SimulatorSettingsNP[SIM_XRES].setValue(Resolutions[index].first);
1187 SimulatorSettingsNP[SIM_YRES].setValue(Resolutions[index].second);
1189 SimulatorSettingsNP[SIM_YRES].getValue(),
1190 16,
1191 SimulatorSettingsNP[SIM_XSIZE].getValue(),
1192 SimulatorSettingsNP[SIM_YSIZE].getValue());
1194 uint32_t nbuf = PrimaryCCD.getXRes() * PrimaryCCD.getYRes() * PrimaryCCD.getBPP() / 8;
1195 PrimaryCCD.setFrameBufferSize(nbuf);
1196
1197 SimulatorSettingsNP.apply();
1198
1199 // Invalidate planet cache since resolution changed
1201 if (m_PlanetMode)
1202 {
1203 SetCaptureFormat(1); // Re-apply RGB format with new buffer size
1204 }
1205 }
1206 return true;
1207 }
1208 // Planet mode toggle
1209 else if (PlanetModeSP.isNameMatch(name))
1210 {
1211 PlanetModeSP.update(states, names, n);
1213 if (m_PlanetMode)
1214 {
1215 // Switch to RGB capture format
1216 int rgbIndex = -1;
1217 for (size_t i = 0; i < m_CaptureFormats.size(); i++)
1218 {
1219 if (m_CaptureFormats[i].name == "INDI_RGB")
1220 {
1221 rgbIndex = static_cast<int>(i);
1222 break;
1223 }
1224 }
1225 if (rgbIndex >= 0 && CaptureFormatSP[rgbIndex].getState() != ISS_ON)
1226 {
1227 CaptureFormatSP.reset();
1228 CaptureFormatSP[rgbIndex].setState(ISS_ON);
1229 CaptureFormatSP.apply();
1230 SetCaptureFormat(rgbIndex);
1231 }
1232 // Disable directory mode when planet mode is active
1233 DirectorySP[INDI_ENABLED].setState(ISS_OFF);
1234 DirectorySP[INDI_DISABLED].setState(ISS_ON);
1235 DirectorySP.apply();
1236 m_AllFiles.clear();
1237 m_RemainingFiles.clear();
1238 // Invalidate cached planet so it re-renders on next exposure
1241 LOGF_INFO("Planet simulation enabled for %s", m_SelectedPlanet.c_str());
1242 }
1243 else
1244 {
1245 // Switch back to Mono capture format
1246 int monoIndex = -1;
1247 for (size_t i = 0; i < m_CaptureFormats.size(); i++)
1248 {
1249 if (m_CaptureFormats[i].name == "INDI_MONO")
1250 {
1251 monoIndex = static_cast<int>(i);
1252 break;
1253 }
1254 }
1255 if (monoIndex >= 0 && CaptureFormatSP[monoIndex].getState() != ISS_ON)
1256 {
1257 CaptureFormatSP.reset();
1258 CaptureFormatSP[monoIndex].setState(ISS_ON);
1259 CaptureFormatSP.apply();
1260 SetCaptureFormat(monoIndex);
1261 }
1262 // Restore star field settings: pixel format, buffer, Bayer, streamer
1265 LOG_INFO("Planet simulation disabled. Returning to star field mode.");
1266 }
1267 PlanetModeSP.setState(IPS_OK);
1268 PlanetModeSP.apply(nullptr);
1269 return true;
1270 }
1271 else if (PlanetRecenterSP.isNameMatch(name))
1272 {
1274 PlanetRecenterSP.reset();
1275 PlanetRecenterSP.setState(IPS_OK);
1276 PlanetRecenterSP.apply();
1277 LOG_INFO("Planet recentered.");
1278 return true;
1279 }
1280 // Planet selection
1281 else if (PlanetSelectSP.isNameMatch(name))
1282 {
1283 PlanetSelectSP.update(states, names, n);
1284 int index = PlanetSelectSP.findOnSwitchIndex();
1285 static const char* planetNames[] =
1286 {
1287 "mercury", "venus", "mars", "jupiter", "saturn",
1288 "uranus", "neptune", "moon", "sun"
1289 };
1290 if (index >= 0 && index < 9)
1291 {
1292 m_SelectedPlanet = planetNames[index];
1293 // Invalidate cache to re-render with new planet
1295 LOGF_INFO("Selected planet: %s", m_SelectedPlanet.c_str());
1296 }
1297 PlanetSelectSP.setState(IPS_OK);
1298 PlanetSelectSP.apply(nullptr);
1299 return true;
1300 }
1301 }
1302
1303 // Nobody has claimed this, so, ignore it
1304 return INDI::CCD::ISNewSwitch(dev, name, states, names, n);
1305}
1306
1308{
1309 DIR* dirp = opendir(DirectoryTP[0].getText());
1310 if (dirp == nullptr)
1311 {
1312 LOGF_ERROR("Cannot monitor invalid directory %s", DirectoryTP[0].getText());
1313 return false;
1314 }
1315
1316 struct dirent * dp;
1317 std::string d_dir = std::string(DirectoryTP[0].getText());
1318 auto directory = DirectoryTP[0].getText();
1319 if (directory[std::string(directory).length() - 1] != '/')
1320 d_dir += "/";
1321
1322 // Accept FITS (.fit/.fits) and, when built with LibXISF support, XISF (.xisf) files.
1323 static const std::vector<std::string> supportedExtensions =
1324 {
1325 ".fits", ".fit",
1326#ifdef HAVE_XISF
1327 ".xisf",
1328#endif
1329 };
1330
1331 auto hasSupportedExtension = [](const std::string &name)
1332 {
1333 for (const auto &extension : supportedExtensions)
1334 {
1335 if (name.size() < extension.size())
1336 continue;
1337 if (strcasecmp(name.c_str() + name.size() - extension.size(), extension.c_str()) == 0)
1338 return true;
1339 }
1340 return false;
1341 };
1342
1343 while ((dp = readdir(dirp)) != NULL)
1344 {
1345 if (hasSupportedExtension(dp->d_name))
1346 m_AllFiles.push_back(d_dir + dp->d_name);
1347 }
1348 closedir(dirp);
1349
1350 if (m_AllFiles.empty())
1351 {
1352 LOGF_ERROR("No supported image files (.fit, .fits%s) found in directory %s",
1353#ifdef HAVE_XISF
1354 ", .xisf"
1355#else
1356 ""
1357#endif
1358 , directory);
1359 return false;
1360 }
1361 else
1362 {
1363 std::sort(m_AllFiles.begin(), m_AllFiles.end());
1365 LOGF_INFO("Directory-based images are enabled. Subsequent exposures will be loaded from directory %s",
1366 directory);
1367 }
1368
1369 return true;
1370}
1371
1373{
1374#ifdef USE_EQUATORIAL_PE
1376#endif
1377 IDSnoopDevice(ActiveDeviceTP[ACTIVE_TELESCOPE].getText(), "EQUATORIAL_EOD_COORD");
1378 IDSnoopDevice(ActiveDeviceTP[ACTIVE_TELESCOPE].getText(), "TELESCOPE_MOUNT_TYPE");
1380 m_AltAzMount = false;
1381
1382 snprintf(FWHMNP.device, MAXINDIDEVICE, "%s", ActiveDeviceTP[ACTIVE_FOCUSER].getText());
1383}
1384
1386{
1387 if (IUSnoopNumber(root, &FWHMNP) == 0)
1388 {
1389 // we calculate the FWHM and do not snoop it from the focus simulator
1390 // m_Seeing = FWHMNP.np[0].value;
1391 return true;
1392 }
1393
1394 XMLEle * ep = nullptr;
1395 const char * propName = findXMLAttValu(root, "name");
1396
1397 if (!strcmp(propName, "ABS_FOCUS_POSITION"))
1398 {
1399 for (ep = nextXMLEle(root, 1); ep != nullptr; ep = nextXMLEle(root, 0))
1400 {
1401 const char * name = findXMLAttValu(ep, "name");
1402
1403 if (!strcmp(name, "FOCUS_ABSOLUTE_POSITION"))
1404 {
1405 FocuserPos = atol(pcdataXMLEle(ep));
1406 LOGF_DEBUG("Snooped FocuserPosition %g", FocuserPos);
1407 // calculate FWHM
1408 double focus = FocusSimulationNP[SIM_FOCUS_POSITION].getValue();
1409 double max = FocusSimulationNP[SIM_FOCUS_MAX].getValue();
1410 double optimalFWHM = FocusSimulationNP[SIM_SEEING].getValue();
1411
1412 // limit to +/- 10
1413 double ticks = 20 * (FocuserPos - focus) / max;
1414
1415 m_Seeing = 0.5625 * ticks * ticks + optimalFWHM;
1416 return true;
1417 }
1418 }
1419 }
1420 else if (!strcmp(propName, "ABS_ROTATOR_ANGLE"))
1421 {
1422 for (ep = nextXMLEle(root, 1); ep != nullptr; ep = nextXMLEle(root, 0))
1423 {
1424 const char * name = findXMLAttValu(ep, "name");
1425
1426 if (!strcmp(name, "ANGLE"))
1427 {
1428 RotatorAngle = atof(pcdataXMLEle(ep));
1429 LOGF_DEBUG("Snooped RotatorAngle %f", RotatorAngle);
1430 return true;
1431 }
1432 }
1433 }
1434 else if (!strcmp(propName, "TELESCOPE_MOUNT_TYPE"))
1435 {
1436 for (ep = nextXMLEle(root, 1); ep != nullptr; ep = nextXMLEle(root, 0))
1437 {
1438 if (!strcmp(findXMLAttValu(ep, "name"), "ALTAZ"))
1439 {
1440 const bool altAz = !strcmp(pcdataXMLEle(ep), "On");
1441 if (altAz != m_AltAzMount)
1442 {
1443 LOGF_INFO("Mount is %s, field rotation is %s.", altAz ? "Alt-Az" : "equatorial",
1444 altAz ? "simulated" : "off");
1445 if (!altAz)
1446 {
1447 FieldRotationNP.setState(IPS_IDLE);
1448 FieldRotationNP.apply();
1449 }
1450 }
1451 m_AltAzMount = altAz;
1452 return true;
1453 }
1454 }
1455 }
1456 // A goto puts the planet back in the frame center once the slew ends
1457 if (!strcmp(propName, "EQUATORIAL_EOD_COORD"))
1458 {
1459 const bool slewing = !strcmp(findXMLAttValu(root, "state"), "Busy");
1460 if (m_MountSlewing && !slewing)
1462 m_MountSlewing = slewing;
1463 }
1464
1465 // We try to snoop EQUATORIAL_PE first (true pointing with mount errors injected);
1466 // if not found we fall through to the regular EQUATORIAL_EOD_COORD snoop below.
1467#ifdef USE_EQUATORIAL_PE
1468 if (!strcmp(propName, "EQUATORIAL_PE"))
1469 {
1470 int rc_ra = -1, rc_de = -1;
1471 double newra = 0, newdec = 0;
1472
1473 for (ep = nextXMLEle(root, 1); ep != nullptr; ep = nextXMLEle(root, 0))
1474 {
1475 const char * elemName = findXMLAttValu(ep, "name");
1476
1477 if (!strcmp(elemName, "RA_PE"))
1478 rc_ra = f_scansexa(pcdataXMLEle(ep), &newra);
1479 else if (!strcmp(elemName, "DEC_PE"))
1480 rc_de = f_scansexa(pcdataXMLEle(ep), &newdec);
1481 }
1482
1483 if (rc_ra == 0 && rc_de == 0)
1484 {
1485 raPE = newra;
1486 decPE = newdec;
1487
1488 // Only activate PE rendering once the telescope reports a valid (Ok) state.
1489 // The initial defNumberVector arrives with state Idle and values 0/0.
1490 const char * state = findXMLAttValu(root, "state");
1491 if (!usePE && strcmp(state, "Ok") == 0)
1492 {
1493 LOGF_INFO("EQUATORIAL_PE snoop active: JNow RA %.4f Dec %.4f", newra, newdec);
1494 usePE = true;
1495 }
1496
1497 EqPENP[AXIS_RA].setValue(newra);
1498 EqPENP[AXIS_DE].setValue(newdec);
1499 EqPENP.apply();
1500
1501 LOGF_DEBUG("Snooped EQUATORIAL_PE JNow RA %g Dec %g", newra, newdec);
1502 return true;
1503 }
1504 }
1505#endif
1506
1507 return INDI::CCD::ISSnoopDevice(root);
1508}
1509
1511{
1512 // Save CCD Config
1514
1515 // Save Filter Wheel Config
1517
1518 // Save CCD Simulator Config
1519 SimulatorSettingsNP.save(fp);
1520
1521 // Gain
1522 GainNP.save(fp);
1523 OffsetNP.save(fp);
1524
1525 // Directory
1526 DirectoryTP.save(fp);
1527
1528 // Resolution
1529 ResolutionSP.save(fp);
1530
1531 // Focus simulation
1532 FocusSimulationNP.save(fp);
1533
1534 // Tilt simulation
1535 TiltSimulationNP.save(fp);
1536
1537 // Sensor defects
1538 DefectSimulationNP.save(fp);
1539
1540 PointingOffsetNP.save(fp);
1541
1542 // Planet simulation
1543 PlanetSettingsNP.save(fp);
1544 PlanetDriftNP.save(fp);
1545 PlanetPathsTP.save(fp);
1546
1547 return true;
1548}
1549
1551{
1552 // Sleep randomly between 1500 and 2000ms to simulate filter selection
1553 std::random_device rd;
1554 std::mt19937 gen(rd());
1555 std::uniform_int_distribution<> dist(1500, 2000);
1556 std::this_thread::sleep_for(std::chrono::milliseconds(dist(gen)));
1557
1558 CurrentFilter = f;
1560 return true;
1561}
1562
1564{
1565 return CurrentFilter;
1566}
1567
1569{
1570 ExposureRequest = Streamer->getTargetExposure();
1571
1572 // Planet mode: stream raw 8-bit RGB like a planetary camera, so frames can be subframed,
1573 // recorded and measured by the stream manager
1574 if (m_PlanetMode)
1575 {
1576 Streamer->setPixelFormat(INDI_RGB, 8);
1577 Streamer->setSize(PrimaryCCD.getSubW(), PrimaryCCD.getSubH());
1578 }
1579 else
1580 {
1581 Streamer->setPixelFormat(INDI_MONO, 16);
1582 Streamer->setSize(PrimaryCCD.getXRes(), PrimaryCCD.getYRes());
1583 }
1584
1585 pthread_mutex_lock(&condMutex);
1586 streamPredicate = 1;
1587 pthread_mutex_unlock(&condMutex);
1588 pthread_cond_signal(&cv);
1589
1590 return true;
1591}
1592
1594{
1595 pthread_mutex_lock(&condMutex);
1596 streamPredicate = 0;
1597 pthread_mutex_unlock(&condMutex);
1598 pthread_cond_signal(&cv);
1599
1600 return true;
1601}
1602
1603bool CCDSim::UpdateCCDFrame(int x, int y, int w, int h)
1604{
1605 long bin_width = w / PrimaryCCD.getBinX();
1606 long bin_height = h / PrimaryCCD.getBinY();
1607
1608 bin_width = bin_width - (bin_width % 2);
1609 bin_height = bin_height - (bin_height % 2);
1610
1611 Streamer->setSize(bin_width, bin_height);
1612
1613 return INDI::CCD::UpdateCCDFrame(x, y, w, h);
1614}
1615
1616bool CCDSim::UpdateCCDBin(int hor, int ver)
1617{
1618 // Binning is not supported in planet mode (RGB data)
1619 if (m_PlanetMode && (hor != 1 || ver != 1))
1620 {
1621 LOG_ERROR("Binning is not supported in planet mode.");
1622 return false;
1623 }
1624
1625 if (PrimaryCCD.getSubW() % hor != 0 || PrimaryCCD.getSubH() % ver != 0)
1626 {
1627 LOGF_ERROR("%dx%d binning is not supported.", hor, ver);
1628 return false;
1629 }
1630
1631 uint32_t bin_width = PrimaryCCD.getSubW() / hor;
1632 uint32_t bin_height = PrimaryCCD.getSubH() / ver;
1633 Streamer->setSize(bin_width, bin_height);
1634
1635 return INDI::CCD::UpdateCCDBin(hor, ver);
1636}
1637
1638bool CCDSim::UpdateGuiderBin(int hor, int ver)
1639{
1640 if (GuideCCD.getSubW() % hor != 0 || GuideCCD.getSubH() % ver != 0)
1641 {
1642 LOGF_ERROR("%dx%d binning is not supported.", hor, ver);
1643 return false;
1644 }
1645
1646 return INDI::CCD::UpdateGuiderBin(hor, ver);
1647}
1648
1649void * CCDSim::streamVideoHelper(void * context)
1650{
1651 return static_cast<CCDSim *>(context)->streamVideo();
1652}
1653
1655{
1656 auto start = std::chrono::high_resolution_clock::now();
1657
1658 while (true)
1659 {
1660 pthread_mutex_lock(&condMutex);
1661
1662 while (streamPredicate == 0)
1663 {
1664 pthread_cond_wait(&cv, &condMutex);
1665 ExposureRequest = Streamer->getTargetExposure();
1666 }
1667
1668 if (terminateThread)
1669 break;
1670
1671 // release condMutex
1672 pthread_mutex_unlock(&condMutex);
1673
1674
1675 // Planet mode: draw the planet at its current position into an RGB frame
1676 if (m_PlanetMode)
1677 {
1678 {
1679 std::lock_guard<std::mutex> lock(m_PlanetMutex);
1680 m_PlanetStreamFrame.resize(PrimaryCCD.getSubW() * PrimaryCCD.getSubH() * 3);
1681 if (renderPlanet())
1682 {
1683 double centerX, centerY;
1684 planetPosition(centerX, centerY);
1685 drawPlanetRGB8(m_PlanetStreamFrame.data(), centerX, centerY);
1686 }
1687 else
1688 std::fill(m_PlanetStreamFrame.begin(), m_PlanetStreamFrame.end(), 0);
1689 }
1690
1691 auto finish = std::chrono::high_resolution_clock::now();
1692 std::chrono::duration<double> elapsed = finish - start;
1693 if (elapsed.count() < ExposureRequest)
1694 usleep(fabs(ExposureRequest - elapsed.count()) * 1e6);
1695 Streamer->newFrame(m_PlanetStreamFrame.data(), m_PlanetStreamFrame.size());
1696 }
1697 else
1698 {
1700 // Software binning for mono star field mode only
1701 if (DirectorySP[INDI_DISABLED].getState() == ISS_ON)
1702 PrimaryCCD.binFrame();
1703
1704 auto finish = std::chrono::high_resolution_clock::now();
1705 std::chrono::duration<double> elapsed = finish - start;
1706 if (elapsed.count() < ExposureRequest)
1707 usleep(fabs(ExposureRequest - elapsed.count()) * 1e6);
1708
1709 uint32_t size = PrimaryCCD.getFrameBufferSize();
1710 Streamer->newFrame(PrimaryCCD.getFrameBuffer(), size);
1711 }
1712
1713 start = std::chrono::high_resolution_clock::now();
1714 }
1715
1716 pthread_mutex_unlock(&condMutex);
1717 return nullptr;
1718}
1719
1721{
1722 // Compute pixel scale: arcsec per pixel = 206.265 * pixel_size_um / focal_length_mm
1723 float pixelSizeX = SimulatorSettingsNP[SIM_XSIZE].getValue();
1724 float pixelSizeY = SimulatorSettingsNP[SIM_YSIZE].getValue();
1725 float focalLength = ScopeInfoNP[FOCAL_LENGTH].getValue() > 0 ?
1727 if (!(focalLength > 0))
1728 focalLength = 1000.0f; // default fallback
1729 float arcsecPerPixelX = 206.265f * pixelSizeX / focalLength;
1730 float arcsecPerPixelY = 206.265f * pixelSizeY / focalLength;
1731
1732 // Re-render when the sprite is stale or its parameters changed. After a failed render, wait for
1733 // the next refresh or a settings change instead of spawning xplanet on every frame.
1734 time_t now;
1735 time(&now);
1736 const bool stale = difftime(now, m_LastPlanetRenderTime) / 60.0 >= m_PlanetRefreshMinutes;
1737 const bool paramsChanged = m_CachedPlanet != m_SelectedPlanet ||
1738 m_CachedFocalLength != focalLength ||
1739 m_CachedPixelSizeX != pixelSizeX;
1740 if (!stale && !paramsChanged)
1741 return !m_PlanetSprite.empty();
1742
1745 m_CachedFocalLength = focalLength;
1746 m_CachedPixelSizeX = pixelSizeX;
1747 m_PlanetSprite.clear();
1749
1750 // Determine planet angular diameter
1751 float planetDiameterArcsec = 0;
1752 if (m_PlanetSizeOverride > 0)
1753 {
1754 planetDiameterArcsec = m_PlanetSizeOverride;
1755 }
1756 else
1757 {
1759 if (it != PlanetAngularDiameter.end())
1760 planetDiameterArcsec = it->second;
1761 else
1762 planetDiameterArcsec = 42.0f; // fallback
1763 }
1764
1765 // How many sensor pixels the planet spans (use average of X and Y pixel scales)
1766 float planetPixelsX = planetDiameterArcsec / arcsecPerPixelX;
1767 float planetPixelsY = planetDiameterArcsec / arcsecPerPixelY;
1768 float avgPlanetPixels = (planetPixelsX + planetPixelsY) / 2.0f;
1769
1770 // Render xplanet at high resolution (1024x1024) with visible black margin.
1771 // Use -range (camera distance in degrees) - NOT -radius which is angular FOV
1772 // and causes planet to fill entire frame under orthographic projection.
1773 // Range of 0.05° gives ~40% black border for Jupiter (~0.0117° angular diam).
1774 const int renderSize = 1024;
1775 const float planetRange = 0.05f; // degrees
1776
1777 // Compute planet disk pixel radius from angular size and range
1778 float planetDiamDeg = planetDiameterArcsec / 3600.0f;
1779 float planetFracOfFrame = planetDiamDeg / planetRange;
1780 float srcPlanetRadius = planetFracOfFrame * renderSize / 2.0f;
1781 if (srcPlanetRadius < 10.0f) srcPlanetRadius = 10.0f;
1782
1783 // Build xplanet command. We output PNG, then convert it to PPM for parsing.
1784 std::string searchDir;
1785 size_t configPos = m_XPlanetConfig.rfind("/config/");
1786 if (configPos != std::string::npos)
1787 searchDir = m_XPlanetConfig.substr(0, configPos);
1788
1789 const char *pngPath = "/tmp/indi_planet.png";
1790 char cmd[2048];
1791 const bool useCustomConfig = (m_XPlanetConfig != "/usr/share/xplanet/config/default");
1792
1793 if (!searchDir.empty() && useCustomConfig)
1794 {
1795 snprintf(cmd, sizeof(cmd),
1796 "%s -body %s -geometry %dx%d -range %.4f "
1797 "-num_times 1 -projection orthographic "
1798 "-config %s -searchdir %s "
1799 "-output %s 2>/dev/null",
1800 m_XPlanetBinary.c_str(), m_SelectedPlanet.c_str(),
1801 renderSize, renderSize, static_cast<double>(planetRange),
1802 m_XPlanetConfig.c_str(), searchDir.c_str(), pngPath);
1803 }
1804 else if (!searchDir.empty())
1805 {
1806 snprintf(cmd, sizeof(cmd),
1807 "%s -body %s -geometry %dx%d -range %.4f "
1808 "-num_times 1 -projection orthographic "
1809 "-searchdir %s "
1810 "-output %s 2>/dev/null",
1811 m_XPlanetBinary.c_str(), m_SelectedPlanet.c_str(),
1812 renderSize, renderSize, static_cast<double>(planetRange),
1813 searchDir.c_str(), pngPath);
1814 }
1815 else
1816 {
1817 snprintf(cmd, sizeof(cmd),
1818 "%s -body %s -geometry %dx%d -range %.4f "
1819 "-num_times 1 -projection orthographic "
1820 "-output %s 2>/dev/null",
1821 m_XPlanetBinary.c_str(), m_SelectedPlanet.c_str(),
1822 renderSize, renderSize, static_cast<double>(planetRange), pngPath);
1823 }
1824
1825 LOGF_DEBUG("Running: %s", cmd);
1826 int ret = system(cmd);
1827 if (ret != 0)
1828 {
1829 LOGF_ERROR("xplanet failed with exit code %d. Is xplanet installed?", ret);
1830 return false;
1831 }
1832
1833 ret = system("convert /tmp/indi_planet.png /tmp/indi_planet.ppm 2>/dev/null");
1834 if (ret != 0)
1835 {
1836 LOG_ERROR("Failed to convert PNG to PPM. Is ImageMagick installed?");
1837 return false;
1838 }
1839
1840 // Parse the PPM file
1841 FILE *fp = fopen("/tmp/indi_planet.ppm", "rb");
1842 if (!fp)
1843 {
1844 LOG_ERROR("Failed to open /tmp/indi_planet.ppm");
1845 return false;
1846 }
1847
1848 char magic[3];
1849 if (fscanf(fp, "%2s\n", magic) != 1 || strcmp(magic, "P6") != 0)
1850 {
1851 LOG_ERROR("PPM file is not P6 format (binary RGB)");
1852 fclose(fp);
1853 return false;
1854 }
1855
1856 int ppmWidth, ppmHeight, maxVal;
1857 // Skip comments
1858 int c = fgetc(fp);
1859 while (c == '#')
1860 {
1861 while (fgetc(fp) != '\n');
1862 c = fgetc(fp);
1863 }
1864 ungetc(c, fp);
1865 if (fscanf(fp, "%d %d\n%d\n", &ppmWidth, &ppmHeight, &maxVal) != 3)
1866 {
1867 LOG_ERROR("Failed to parse PPM header");
1868 fclose(fp);
1869 return false;
1870 }
1871
1872 std::vector<uint8_t> rgbData(ppmWidth * ppmHeight * 3);
1873 size_t bytesRead = fread(rgbData.data(), 1, rgbData.size(), fp);
1874 fclose(fp);
1875
1876 if (bytesRead != rgbData.size())
1877 {
1878 LOGF_ERROR("PPM read error: expected %zu bytes, got %zu", rgbData.size(), bytesRead);
1879 return false;
1880 }
1881
1882 // Scale the planet disk to its size on the sensor. Pixels outside the disk stay black.
1883 float dstPlanetRadius = avgPlanetPixels / 2.0f;
1884 if (dstPlanetRadius < 1.0f)
1885 dstPlanetRadius = 1.0f;
1886 float scale = srcPlanetRadius / dstPlanetRadius;
1887
1888 const uint32_t spriteSize = static_cast<uint32_t>(std::ceil(dstPlanetRadius * 2)) + 2;
1889 const float spriteCenter = spriteSize / 2.0f;
1890 std::vector<uint8_t> sprite(spriteSize * spriteSize * 3, 0);
1891
1892 for (uint32_t y = 0; y < spriteSize; y++)
1893 {
1894 for (uint32_t x = 0; x < spriteSize; x++)
1895 {
1896 float dx = (x - spriteCenter) * scale;
1897 float dy = (y - spriteCenter) * scale;
1898 if (sqrtf(dx * dx + dy * dy) > srcPlanetRadius)
1899 continue;
1900
1901 int ix = static_cast<int>(dx + ppmWidth / 2.0f);
1902 int iy = static_cast<int>(dy + ppmHeight / 2.0f);
1903 if (ix < 0 || ix >= ppmWidth || iy < 0 || iy >= ppmHeight)
1904 continue;
1905
1906 memcpy(&sprite[(y * spriteSize + x) * 3], &rgbData[(iy * ppmWidth + ix) * 3], 3);
1907 }
1908 }
1909
1910 m_PlanetSprite = std::move(sprite);
1911 m_PlanetSpriteSize = spriteSize;
1912
1913 LOGF_INFO("Rendered planet %s: diameter=%.1f arcsec, pixels=%.1f, scale=%.1f arcsec/px",
1914 m_SelectedPlanet.c_str(), planetDiameterArcsec, planetPixelsX, arcsecPerPixelX);
1915
1916 return true;
1917}
1918
1920{
1921 std::lock_guard<std::mutex> lock(m_PlanetMutex);
1922 m_PlanetPositionValid = false;
1923}
1924
1925void CCDSim::planetPosition(double &x, double &y)
1926{
1928 const double pointingRA = currentRA * 15.0 + periodicErrorOffset();
1929 const double pointingDE = currentDE;
1930
1932 {
1933 m_PlanetRA = pointingRA;
1934 m_PlanetDE = pointingDE;
1935 m_PlanetDriftStart = std::chrono::steady_clock::now();
1936 m_PlanetPositionValid = true;
1937 }
1938
1939 // Standard coordinates of the planet relative to the pointing, as in SkyRenderer::renderFrame
1940 const double rar = pointingRA * (M_PI / 180.0);
1941 const double decr = pointingDE * (M_PI / 180.0);
1942 const double srar = m_PlanetRA * (M_PI / 180.0);
1943 const double sdecr = m_PlanetDE * (M_PI / 180.0);
1944 const double denom = cos(decr) * cos(sdecr) * cos(srar - rar) + sin(decr) * sin(sdecr);
1945 double sx = cos(sdecr) * sin(srar - rar) / denom;
1946 double sy = (sin(decr) * cos(sdecr) * cos(srar - rar) - cos(decr) * sin(sdecr)) / denom;
1947
1948 // Tracking drift since the last recenter, plus per-frame seeing jitter (arcsec -> radians)
1949 const double minutes = std::chrono::duration<double>(std::chrono::steady_clock::now() - m_PlanetDriftStart).count() / 60.0;
1950 const double arcsecToRad = M_PI / (180.0 * 3600.0);
1951 sx += PlanetDriftNP[PLANET_DRIFT_RA].getValue() * minutes * arcsecToRad;
1952 sy -= PlanetDriftNP[PLANET_DRIFT_DE].getValue() * minutes * arcsecToRad;
1953 const double jitter = PlanetDriftNP[PLANET_JITTER].getValue();
1954 if (jitter > 0)
1955 {
1956 std::normal_distribution<double> seeing(0, jitter * arcsecToRad);
1957 sx += seeing(m_PlanetRandom);
1958 sy += seeing(m_PlanetRandom);
1959 }
1960
1961 // Plate matrix, as in SkyRenderer::renderFrame
1962 double focalLength = ScopeInfoNP[FOCAL_LENGTH].getValue() > 0 ? ScopeInfoNP[FOCAL_LENGTH].getValue() : snoopedFocalLength;
1963 if (!(focalLength > 0))
1964 focalLength = 1000.0;
1965 const double theta = cameraRotation() * (M_PI / 180.0);
1966 const double pprx = focalLength / PrimaryCCD.getPixelSizeX() * 1000.0;
1967 const double ppry = focalLength / PrimaryCCD.getPixelSizeY() * 1000.0;
1968 const double pa = pprx * std::cos(theta);
1969 const double pb = ppry * std::sin(theta);
1970 const double pd = -pprx * std::sin(theta);
1971 const double pe = ppry * std::cos(theta);
1972
1973 x = PrimaryCCD.getXRes() / 2.0 - (pa * sx + pb * sy);
1974 y = PrimaryCCD.getYRes() / 2.0 + (pd * sx + pe * sy);
1975}
1976
1977void CCDSim::drawPlanetRGB8(uint8_t *buffer, double centerX, double centerY)
1978{
1979 const int subX = PrimaryCCD.getSubX(), subY = PrimaryCCD.getSubY();
1980 const int subW = PrimaryCCD.getSubW(), subH = PrimaryCCD.getSubH();
1981 memset(buffer, 0, static_cast<size_t>(subW) * subH * 3);
1982
1983 // Sprite origin in subframe pixels
1984 const int size = m_PlanetSpriteSize;
1985 const int originX = static_cast<int>(std::lround(centerX - size / 2.0)) - subX;
1986 const int originY = static_cast<int>(std::lround(centerY - size / 2.0)) - subY;
1987 const int x0 = std::max(0, originX), x1 = std::min(subW, originX + size);
1988 const int y0 = std::max(0, originY), y1 = std::min(subH, originY + size);
1989 const uint32_t transparency = static_cast<uint32_t>(PlanetDriftNP[PLANET_TRANSPARENCY].getValue());
1990
1991 for (int y = y0; y < y1; y++)
1992 {
1993 const uint8_t *src = &m_PlanetSprite[((y - originY) * size + (x0 - originX)) * 3];
1994 uint8_t *dst = buffer + (static_cast<size_t>(y) * subW + x0) * 3;
1995 for (int i = 0; i < (x1 - x0) * 3; i++)
1996 dst[i] = src[i] * transparency / 100;
1997 }
1998}
1999
2000void CCDSim::drawPlanetRGB16(uint16_t *buffer, double centerX, double centerY)
2001{
2002 const int subX = PrimaryCCD.getSubX(), subY = PrimaryCCD.getSubY();
2003 const int subW = PrimaryCCD.getSubW(), subH = PrimaryCCD.getSubH();
2004 const size_t planeSize = static_cast<size_t>(subW) * subH;
2005 memset(buffer, 0, planeSize * 3 * sizeof(uint16_t));
2006
2007 const int size = m_PlanetSpriteSize;
2008 const int originX = static_cast<int>(std::lround(centerX - size / 2.0)) - subX;
2009 const int originY = static_cast<int>(std::lround(centerY - size / 2.0)) - subY;
2010 const int x0 = std::max(0, originX), x1 = std::min(subW, originX + size);
2011 const int y0 = std::max(0, originY), y1 = std::min(subH, originY + size);
2012 const uint32_t transparency = static_cast<uint32_t>(PlanetDriftNP[PLANET_TRANSPARENCY].getValue());
2013
2014 // Linear 8->16-bit scaling (x256) keeps the planet's perceptual brightness, so auto-stretch
2015 // works naturally without crushing mid-tones. FITS NAXIS=3 is planar: R plane | G plane | B plane.
2016 for (int y = y0; y < y1; y++)
2017 {
2018 for (int x = x0; x < x1; x++)
2019 {
2020 const uint8_t *src = &m_PlanetSprite[((y - originY) * size + (x - originX)) * 3];
2021 const size_t px = static_cast<size_t>(y) * subW + x;
2022 for (int c = 0; c < 3; c++)
2023 {
2024 uint32_t value = src[c] * 256u * transparency / 100;
2025 buffer[c * planeSize + px] = static_cast<uint16_t>(std::min<uint32_t>(value, m_MaxVal));
2026 }
2027 }
2028 }
2029}
2030
2031void CCDSim::addFITSKeywords(INDI::CCDChip *targetChip, std::vector<INDI::FITSRecord> &fitsKeyword)
2032{
2033 INDI::CCD::addFITSKeywords(targetChip, fitsKeyword);
2034
2035 fitsKeyword.push_back({"GAIN", GainNP[0].getValue(), 3, "Gain"});
2036
2037 if (m_PlanetMode)
2038 {
2039 fitsKeyword.emplace_back("OBJECT", m_SelectedPlanet.c_str(), "Target planet");
2040 fitsKeyword.emplace_back("XPLANET", static_cast<int64_t>(1), "Generated by xplanet");
2041 fitsKeyword.emplace_back("COLORSPC", "RGB", "Color space");
2042 }
2043}
2044
2046{
2047 if (m_RemainingFiles.empty())
2049 const std::string filename = m_RemainingFiles[0];
2050 m_RemainingFiles.pop_front();
2051
2052#ifdef HAVE_XISF
2053 if (filename.size() >= 5 && strcasecmp(filename.c_str() + filename.size() - 5, ".xisf") == 0)
2054 return loadNextXISFImage(filename);
2055#endif
2056
2057 return loadNextFITSImage(filename);
2058}
2059
2060bool CCDSim::loadNextFITSImage(const std::string &filename)
2061{
2062 char comment[512] = {0}, bayer_pattern[16] = {0};
2063 int status = 0, anynull = 0;
2064 double pixel_size = 5.2;
2065 int ndim {2}, bitpix {8};
2066 long naxes[3];
2067 fitsfile *fptr = nullptr;
2068
2069 if (fits_open_diskfile(&fptr, filename.c_str(), READONLY, &status))
2070 {
2071 char error_status[512] = {0};
2072 fits_get_errstatus(status, error_status);
2073 LOGF_WARN("Error opening file %s due to error %s", filename.c_str(), error_status);
2074 return false;
2075 }
2076
2077 if (fits_get_img_param(fptr, 3, &bitpix, &ndim, naxes, &status))
2078 {
2079 char error_status[512] = {0};
2080 fits_get_errstatus(status, error_status);
2081 LOGF_WARN("Error reading image parameters from %s due to error %s", filename.c_str(), error_status);
2082 fits_close_file(fptr, &status);
2083 return false;
2084 }
2085
2086 if (ndim < 3)
2087 naxes[2] = 1;
2088 else
2089 PrimaryCCD.setNAxis(3);
2090 int samples_per_channel = naxes[0] * naxes[1];
2091 int channels = naxes[2];
2092 int elements = samples_per_channel * channels;
2093 int size = elements * bitpix / 8;
2094 PrimaryCCD.setFrameBufferSize(size);
2095
2096 if (fits_read_img(fptr, bitpix == 8 ? TBYTE : TUSHORT, 1, elements, 0, PrimaryCCD.getFrameBuffer(), &anynull, &status))
2097 {
2098 char error_status[512] = {0};
2099 fits_get_errstatus(status, error_status);
2100 LOGF_WARN("Error reading pixel data from %s due to error %s", filename.c_str(), error_status);
2101 fits_close_file(fptr, &status);
2102 return false;
2103 }
2104
2105 // Pixel size is informational only. Different capture applications use different keywords
2106 // for it (e.g. INDI writes PIXSIZE1 while others like N.I.N.A/SharpCap write XPIXSZ), and some
2107 // omit it entirely, so fall back gracefully instead of rejecting the whole image over it.
2108 status = 0;
2109 if (fits_read_key_dbl(fptr, "PIXSIZE1", &pixel_size, comment, &status))
2110 {
2111 status = 0;
2112 if (fits_read_key_dbl(fptr, "XPIXSZ", &pixel_size, comment, &status))
2113 {
2114 LOGF_DEBUG("No PIXSIZE1 or XPIXSZ keyword found in %s, defaulting pixel size to %.2f microns",
2115 filename.c_str(), pixel_size);
2116 }
2117 }
2118
2119 status = 0;
2120 if (fits_read_key_str(fptr, "BAYERPAT", bayer_pattern, comment, &status))
2121 {
2122 char error_status[512] = {0};
2123 fits_get_errstatus(status, error_status);
2124 LOGF_DEBUG("No BAYERPAT keyword found in %s (%s)", filename.c_str(), error_status);
2125 }
2126 SetCCDParams(naxes[0], naxes[1], bitpix, pixel_size, pixel_size);
2127
2128 // Check if MONO or Bayer
2129 if (channels == 1 && strlen(bayer_pattern) == 4)
2130 {
2132 BayerTP[CFA_OFFSET_X].setText("0");
2133 BayerTP[CFA_OFFSET_Y].setText("0");
2134 BayerTP[CFA_TYPE].setText(bayer_pattern);
2135 }
2136 else
2137 {
2139 }
2140
2141 status = 0;
2142 fits_close_file(fptr, &status);
2143 return true;
2144}
2145
2146#ifdef HAVE_XISF
2147bool CCDSim::loadNextXISFImage(const std::string &filename)
2148{
2149 try
2150 {
2151 LibXISF::XISFReader reader;
2152 reader.open(filename);
2153
2154 if (reader.imagesCount() < 1)
2155 {
2156 LOGF_WARN("No images found in XISF file %s", filename.c_str());
2157 return false;
2158 }
2159
2160 // Work on a local copy so we can normalize pixel storage before copying it out.
2161 LibXISF::Image image = reader.getImage(0);
2162
2163 const auto sampleFormat = image.sampleFormat();
2164 const bool isFloat = (sampleFormat == LibXISF::Image::Float32 || sampleFormat == LibXISF::Image::Float64);
2165 int bitpix = 0;
2166 switch (sampleFormat)
2167 {
2168 case LibXISF::Image::UInt8:
2169 bitpix = 8;
2170 break;
2171 case LibXISF::Image::UInt16:
2172 bitpix = 16;
2173 break;
2174 case LibXISF::Image::Float32:
2175 case LibXISF::Image::Float64:
2176 // Processed/master XISF files (e.g. exported from PixInsight) are commonly stored as
2177 // normalized [0,1] floating point samples per the XISF spec. Scale them to 16-bit so
2178 // they can flow through the same integer pipeline as camera-native captures.
2179 bitpix = 16;
2180 break;
2181 default:
2182 LOGF_WARN("Unsupported XISF sample format '%s' in %s. Only 8/16-bit integer and 32/64-bit "
2183 "normalized float samples are supported.",
2184 LibXISF::Image::sampleFormatString(sampleFormat).c_str(), filename.c_str());
2185 return false;
2186 }
2187
2188 int channels = static_cast<int>(image.channelCount());
2189 PrimaryCCD.setNAxis(channels >= 3 ? 3 : 2);
2190
2191 // The CCD frame buffer expects channel-planar data (as FITS image cubes store it),
2192 // matching how this driver (and INDI in general) writes XISF images.
2193 if (image.pixelStorage() != LibXISF::Image::Planar)
2194 image.convertPixelStorageTo(LibXISF::Image::Planar);
2195
2196 const size_t elementCount = image.width() * image.height() * channels;
2197 if (isFloat)
2198 {
2199 PrimaryCCD.setFrameBufferSize(elementCount * 2);
2200 auto * dest = reinterpret_cast<uint16_t *>(PrimaryCCD.getFrameBuffer());
2201 auto scaleClamp = [](double value) -> uint16_t
2202 {
2203 if (value <= 0.0)
2204 return 0;
2205 if (value >= 1.0)
2206 return 65535;
2207 return static_cast<uint16_t>(std::lround(value * 65535.0));
2208 };
2209
2210 if (sampleFormat == LibXISF::Image::Float32)
2211 {
2212 const float * src = image.imageData<float>();
2213 for (size_t i = 0; i < elementCount; i++)
2214 dest[i] = scaleClamp(src[i]);
2215 }
2216 else
2217 {
2218 const double * src = image.imageData<double>();
2219 for (size_t i = 0; i < elementCount; i++)
2220 dest[i] = scaleClamp(src[i]);
2221 }
2222 }
2223 else
2224 {
2225 PrimaryCCD.setFrameBufferSize(image.imageDataSize());
2226 memcpy(PrimaryCCD.getFrameBuffer(), image.imageData(), image.imageDataSize());
2227 }
2228
2229 // Pixel size is informational only; fall back to a default if not present, same as the FITS path.
2230 double pixel_size = 5.2;
2231 bool foundPixelSize = false;
2232 for (const auto &keyword : image.fitsKeywords())
2233 {
2234 if (keyword.name == "PIXSIZE1" || keyword.name == "XPIXSZ")
2235 {
2236 pixel_size = std::stod(keyword.value);
2237 foundPixelSize = true;
2238 break;
2239 }
2240 }
2241 if (!foundPixelSize)
2242 LOGF_DEBUG("No PIXSIZE1 or XPIXSZ keyword found in %s, defaulting pixel size to %.2f microns",
2243 filename.c_str(), pixel_size);
2244
2245 SetCCDParams(image.width(), image.height(), bitpix, pixel_size, pixel_size);
2246
2247 // Check if MONO or Bayer
2248 const auto cfa = image.colorFilterArray();
2249 if (channels == 1 && cfa.pattern.size() == 4)
2250 {
2252 BayerTP[CFA_OFFSET_X].setText("0");
2253 BayerTP[CFA_OFFSET_Y].setText("0");
2254 BayerTP[CFA_TYPE].setText(cfa.pattern.c_str());
2255 }
2256 else
2257 {
2259 }
2260 }
2261 catch (LibXISF::Error &error)
2262 {
2263 LOGF_WARN("Error reading XISF file %s due to error: %s", filename.c_str(), error.what());
2264 return false;
2265 }
2266
2267 return true;
2268}
2269#endif
2270
2271bool CCDSim::SetCaptureFormat(uint8_t index)
2272{
2273 // Get the selected format
2274 if (index >= m_CaptureFormats.size())
2275 return false;
2276
2277 const auto &format = m_CaptureFormats[index];
2278 bool isRGB = (format.name == "INDI_RGB");
2279
2280 // Set NAXIS and buffer size for RGB vs Mono
2281 // The base CCD class handles CaptureFormatSP state, we just need to configure the chip
2282 uint32_t nbuf;
2283 if (isRGB)
2284 {
2285 PrimaryCCD.setNAxis(3);
2286 nbuf = PrimaryCCD.getXRes() * PrimaryCCD.getYRes() * 3 * (PrimaryCCD.getBPP() / 8);
2288 }
2289 else
2290 {
2291 PrimaryCCD.setNAxis(2);
2292 nbuf = PrimaryCCD.getXRes() * PrimaryCCD.getYRes() * (PrimaryCCD.getBPP() / 8);
2294 }
2295 PrimaryCCD.setFrameBufferSize(nbuf);
2296 Streamer->setPixelFormat(isRGB ? INDI_RGB : INDI_MONO, 16);
2297 m_IsRGBFormat = isRGB;
2298 return true;
2299}
double temperature
The CCDSim class provides an advanced simulator for a CCD that includes a dedicated on-board guide ch...
virtual bool UpdateCCDFrame(int x, int y, int w, int h) override
CCD calls this function when CCD Frame dimension needs to be updated in the hardware....
bool m_IsRGBFormat
@ SIM_TESTS_TIMEOUT
@ SIM_TESTS_BAYER
@ SIM_TESTS_CRASH
INDI::PropertyNumber TiltSimulationNP
float periodicErrorOffset()
float m_CachedPixelSizeX
bool m_SimulateBayer
double m_LastTemperature
void recenterPlanet()
bool initProperties() override
Initialize properties initial state and value. The child class must implement this function.
INDI::PropertySwitch PlanetRecenterSP
float guideWEOffset
double cameraRotation()
INDI::PropertyNumber PlanetDriftNP
void setBayerEnabled(bool onOff)
INDI::PropertyNumber FocusSimulationNP
bool StartExposure(float duration) override
Start exposing primary CCD chip.
bool loadNextFITSImage(const std::string &filename)
void applyPointingOffset(double &ra, double &de)
virtual IPState GuideSouth(uint32_t) override
Guide southward for ms milliseconds.
INDI::PropertyText PlanetPathsTP
INDI::PropertyText DirectoryTP
int m_DefectsXRes
INDI::PropertyNumber GainNP
bool m_PlanetPositionValid
std::chrono::steady_clock::time_point m_PlanetDriftStart
@ PLANET_DRIFT_RA
@ PLANET_DRIFT_DE
@ PLANET_TRANSPARENCY
bool ShowStarField
static const constexpr char * SIMULATOR_TAB
std::string m_XPlanetConfig
bool watchDirectory()
float GuideRate
Guide rate is 7 arcseconds per second.
bool AbortGuideFrame
double parallacticAngle()
float m_RotationOffset
bool Disconnect() override
Disconnect from device.
float m_SkyGlow
INDI::PropertyNumber EqPENP
void ISGetProperties(const char *dev) override
define the driver's properties to the client. Usually, only a minimum set of properties are defined t...
virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n) override
Process the client newSwitch command.
void * streamVideo()
@ PLANET_DISABLED
float guideNSOffset
bool StartGuideExposure(float) override
Start exposing guide CCD chip.
virtual bool SetCaptureFormat(uint8_t index) override
SetCaptureFormat Set Active Capture format.
INDI::PropertySwitch SimTestsSP
std::vector< uint8_t > m_PlanetSprite
float m_PolarDrift
pthread_t primary_thread
std::string m_XPlanetBinary
float m_PEMax
void drawPlanetRGB16(uint16_t *buffer, double centerX, double centerY)
bool m_MountSlewing
void TimerHit() override
Callback function to be called once SetTimer duration elapses.
double m_PlanetDE
virtual int SetTemperature(double temperature) override
Set CCD temperature.
static const std::map< std::string, float > PlanetAngularDiameter
const char * getDefaultName() override
std::deque< std::string > m_AllFiles
int m_DefectsHot
INDI::PropertySwitch CoolerSP
virtual bool StartStreaming() override
StartStreaming Start live video streaming.
INDI::PropertyNumber SimulatorSettingsNP
static void * streamVideoHelper(void *context)
void drawPlanetRGB8(uint8_t *buffer, double centerX, double centerY)
@ SIM_FOCUS_POSITION
@ PLANET_XPLANET_PATH
@ PLANET_XPLANET_CONFIG
virtual bool ISSnoopDevice(XMLEle *root) override
Process a snoop event from INDI server. This function is called when a snooped property is updated in...
float m_PolarError
bool setupParameters()
std::atomic< time_t > m_LastPlanetRenderTime
float m_PlanetRefreshMinutes
SkyRenderer m_Renderer
virtual IPState GuideEast(uint32_t) override
Guide easward for ms milliseconds.
bool m_PlanetMode
void updateDefects()
void updatePointing()
time_t RunStart
void planetPosition(double &x, double &y)
float m_PlanetSizeOverride
double raPE
virtual IPState GuideWest(uint32_t) override
Guide westward for ms milliseconds.
float m_OAGOffset
bool renderPlanet()
std::mt19937 m_PlanetRandom
@ SIM_SATURATION
@ SIM_LIMITINGMAG
@ SIM_TIME_FACTOR
@ SIM_PE_PERIOD
@ SIM_OAGOFFSET
@ SIM_POLARDRIFT
int QueryFilter() override
Return current filter position.
double m_PlanetRA
INumber FWHMN[1]
virtual bool StopStreaming() override
StopStreaming Stop live video streaming.
float m_PEPeriod
PEPeriod in minutes.
std::vector< uint8_t > m_PlanetStreamFrame
bool SelectFilter(int) override
Select a new filter position.
bool Connect() override
Connect to the device. INDI::DefaultDevice implementation connects to appropriate connection interfac...
double currentDE
std::vector< SensorDefect > m_Defects
INDI::PropertyNumber FieldRotationNP
INDI::PropertyNumber OffsetNP
bool loadNextImage()
int m_DefectsCold
bool AbortPrimaryFrame
virtual bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n) override
Process the client newSwitch command.
virtual bool UpdateCCDBin(int hor, int ver) override
CCD calls this function when CCD Binning needs to be updated in the hardware. Derived classes should ...
int testvalue
float m_LimitingMag
static const std::vector< std::pair< uint32_t, uint32_t > > Resolutions
INDI::PropertySwitch ResolutionSP
INumberVectorProperty FWHMNP
std::string m_SelectedPlanet
double m_DefectsRate
virtual IPState GuideNorth(uint32_t) override
Guide northward for ms milliseconds.
bool AbortExposure() override
Abort ongoing exposure.
INDI::PropertyNumber PlanetSettingsNP
bool m_AltAzMount
INDI::PropertySwitch PlanetSelectSP
bool m_SimulateTimeout
INDI::PropertyNumber DefectSimulationNP
float m_CachedFocalLength
std::mutex m_PlanetMutex
float m_TimeFactor
float m_SaturationMag
INDI::PropertyNumber PointingOffsetNP
int streamPredicate
double decPE
@ SIM_COLD_PIXELS
std::string m_CachedPlanet
double TemperatureRequest
uint32_t m_PlanetSpriteSize
bool updateProperties() override
updateProperties is called whenever there is a change in the CONNECTION status of the driver....
INDI::PropertySwitch DirectorySP
SimulatorClock m_Clock
virtual void activeDevicesUpdated() override
activeDevicesUpdated Inform children that ActiveDevices property was updated so they can snoop on the...
double currentRA
float ExposureRequest
int m_MaxNoise
std::deque< std::string > m_RemainingFiles
virtual bool ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n) override
Process the client newNumber command.
INDI::PropertySwitch PlanetModeSP
bool terminateThread
int m_DefectsYRes
float CalcTimeLeft(timeval start, float req)
virtual bool saveConfigItems(FILE *fp) override
saveConfigItems Save configuration items in XML file.
virtual bool UpdateGuiderBin(int hor, int ver) override
CCD calls this function when Guide head binning is updated by the client. Derived classes should impl...
float m_Seeing
float GuideExposureRequest
virtual void addFITSKeywords(INDI::CCDChip *targetChip, std::vector< INDI::FITSRecord > &fitsKeyword) override
Generate FITS keywords that will be added to FIST/XISF file.
bool AbortGuideExposure() override
Abort ongoing exposure.
int DrawCcdFrame(INDI::CCDChip *targetChip)
static const constexpr char * PLANET_TAB
bool isConnected() const
INDI::PropertyText getText(const char *name) const
The CCDChip class provides functionality of a CCD Chip within a CCD.
Definition indiccdchip.h:39
int getSubH() const
getSubH Get the height of the frame
CCD_FRAME getFrameType() const
isInterlaced
int getXRes() const
getXRes Get the horizontal resolution in pixels of the CCD Chip.
Definition indiccdchip.h:81
uint8_t * getFrameBuffer()
getFrameBuffer Get raw frame buffer of the CCD chip.
int getSubW() const
getSubW Get the width of the frame
int getFrameBufferSize() const
getFrameBufferSize Get allocated frame buffer size to hold the CCD image frame.
bool InGuideExposure
Definition indiccd.h:567
double m_InitialRampTemperature
Definition indiccd.h:609
double Longitude
Definition indiccd.h:597
CCDChip PrimaryCCD
Definition indiccd.h:624
uint32_t GetCCDCapability() const
GetCCDCapability returns the CCD capabilities.
Definition indiccd.h:161
bool HasGuideHead()
Definition indiccd.h:199
std::unique_ptr< StreamManager > Streamer
Definition indiccd.h:622
bool HasCooler()
Definition indiccd.h:223
bool InExposure
Definition indiccd.h:566
double m_TemperatureStabilizationValue
Definition indiccd.h:606
@ CFA_OFFSET_Y
Definition indiccd.h:691
@ CFA_OFFSET_X
Definition indiccd.h:690
INDI::Timer m_TemperatureCheckTimer
Definition indiccd.h:603
INDI::PropertyText ActiveDeviceTP
ActiveDeviceTP defines 4 devices the camera driver can listen to (snoop) for properties of interest s...
Definition indiccd.h:659
virtual bool UpdateCCDFrame(int x, int y, int w, int h)
CCD calls this function when CCD Frame dimension needs to be updated in the hardware....
Definition indiccd.cpp:1989
virtual void addFITSKeywords(CCDChip *targetChip, std::vector< FITSRecord > &fitsKeywords)
Generate FITS keywords that will be added to FIST/XISF file.
Definition indiccd.cpp:2056
virtual bool ISNewSwitch(const char *dev, const char *name, ISState *states, char *names[], int n) override
Process the client newSwitch command.
Definition indiccd.cpp:1555
virtual bool ExposureComplete(CCDChip *targetChip)
Uploads target Chip exposed buffer as FITS to the client. Derived classes should class this function ...
Definition indiccd.cpp:2357
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 indiccd.cpp:525
INDI::PropertyNumber TemperatureNP
TemperatureNP Camera Temperature in Celcius.
Definition indiccd.h:672
std::mutex ccdBufferLock
Definition indiccd.h:615
@ ACTIVE_TELESCOPE
Definition indiccd.h:662
@ ACTIVE_FOCUSER
Definition indiccd.h:664
INDI::PropertyNumber ScopeInfoNP
Definition indiccd.h:723
virtual bool UpdateCCDBin(int hor, int ver)
CCD calls this function when CCD Binning needs to be updated in the hardware. Derived classes should ...
Definition indiccd.cpp:2008
@ FOCAL_LENGTH
Definition indiccd.h:726
long FocuserPos
Definition indiccd.h:591
@ CCD_CAN_SUBFRAME
Definition indiccd.h:116
@ CCD_HAS_DSP
Definition indiccd.h:124
@ CCD_CAN_ABORT
Definition indiccd.h:117
@ CCD_HAS_GUIDE_HEAD
Definition indiccd.h:118
@ CCD_HAS_SHUTTER
Definition indiccd.h:120
@ CCD_HAS_BAYER
Definition indiccd.h:122
@ CCD_CAN_BIN
Definition indiccd.h:115
@ CCD_HAS_STREAMING
Definition indiccd.h:123
@ CCD_HAS_ST4_PORT
Definition indiccd.h:119
@ CCD_HAS_COOLER
Definition indiccd.h:121
virtual bool initProperties() override
Initialize properties initial state and value. The child class must implement this function.
Definition indiccd.cpp:157
virtual bool ISNewText(const char *dev, const char *name, char *texts[], char *names[], int n) override
Process the client newSwitch command.
Definition indiccd.cpp:910
int pierSide
Definition indiccd.h:554
INDI::PropertyText BayerTP
BayerTP Bayer pattern offset and type.
Definition indiccd.h:687
virtual bool updateProperties() override
updateProperties is called whenever there is a change in the CONNECTION status of the driver....
Definition indiccd.cpp:540
virtual void addCaptureFormat(const CaptureFormat &format)
addCaptureFormat Add a supported camera native capture format (e.g. Mono, Bayer8.....
Definition indiccd.cpp:3263
double RotatorAngle
Definition indiccd.h:585
virtual void SetGuiderParams(int x, int y, int bpp, float xf, float yf)
Setup CCD parameters for guide head CCD. Child classes call this function to update CCD parameters.
Definition indiccd.cpp:2900
INDI::ElapsedTimer m_TemperatureElapsedTimer
Definition indiccd.h:604
virtual bool UpdateGuiderBin(int hor, int ver)
CCD calls this function when Guide head binning is updated by the client. Derived classes should impl...
Definition indiccd.cpp:2026
virtual bool saveConfigItems(FILE *fp) override
saveConfigItems Save configuration items in XML file.
Definition indiccd.cpp:2913
virtual bool ISSnoopDevice(XMLEle *root) override
Process a snoop event from INDI server. This function is called when a snooped property is updated in...
Definition indiccd.cpp:729
INDI::PropertySwitch CaptureFormatSP
Specifies Camera NATIVE capture format (e.g. Mono, RGB, RAW8..etc).
Definition indiccd.h:702
void SetCCDCapability(uint32_t cap)
SetCCDCapability Set the CCD capabilities. All fields must be initialized.
Definition indiccd.cpp:140
virtual bool ISNewNumber(const char *dev, const char *name, double values[], char *names[], int n) override
Process the client newNumber command.
Definition indiccd.cpp:1143
double Latitude
Definition indiccd.h:596
CCDChip GuideCCD
Definition indiccd.h:625
double RA
Definition indiccd.h:551
INDI::ElapsedTimer m_TemperatureRampTimer
Definition indiccd.h:612
virtual void SetCCDParams(int x, int y, int bpp, float xf, float yf)
Setup CCD parameters for primary CCD. Child classes call this function to update CCD parameters.
Definition indiccd.cpp:2887
double snoopedFocalLength
Definition indiccd.h:565
std::vector< CaptureFormat > m_CaptureFormats
Definition indiccd.h:620
double m_TargetTemperature
Definition indiccd.h:602
INDI::ElapsedTimer m_TemperatureStabilizationTimer
Definition indiccd.h:607
double Dec
Definition indiccd.h:551
virtual bool saveConfig(bool silent=false, const char *property=nullptr)
Save the current properties in a configuration file.
void setDriverInterface(uint32_t value)
setInterface Set driver interface. By default the driver interface is set to GENERAL_DEVICE....
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.
uint32_t getDriverInterface() const
int SetTimer(uint32_t ms)
Set a timer to call the function TimerHit after ms milliseconds.
void addDebugControl()
Add Debug control to the driver.
FilterInterface(DefaultDevice *defaultDevice)
FilterInterface Initiailize Filter Interface.
bool processText(const char *dev, const char *name, char *texts[], char *names[], int n)
Process text properties.
INDI::PropertyNumber FilterSlotNP
bool updateProperties()
updateProperties Defines or Delete properties based on default device connection status
bool processNumber(const char *dev, const char *name, double values[], char *names[], int n)
Process number properties.
void SelectFilterDone(int newpos)
The child class calls this function when the hardware successfully finished selecting a new filter wh...
void initProperties(const char *groupName)
Initialize filter wheel properties. It is recommended to call this function within initProperties() o...
bool saveConfigItems(FILE *fp)
saveConfigItems save Filter Names in config file
static std::vector< SensorDefect > generateDefects(int xres, int yres, int hotCount, int coldCount, float hotRate, uint32_t seed=1)
const char * FILTER_TAB
FILTER_TAB Where all the properties for filter wheels are located.
const char * MAIN_CONTROL_TAB
MAIN_CONTROL_TAB Where all the primary controls for the device are located.
const char * SITE_TAB
SITE_TAB Where all site information setting are located.
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
double max(void)
double ra
double dec
ISState
Switch state.
Definition indiapi.h:148
@ ISS_OFF
Definition indiapi.h:149
@ ISS_ON
Definition indiapi.h:150
#define MAXINDIDEVICE
Definition indiapi.h:191
@ IP_RW
Definition indiapi.h:184
@ IP_RO
Definition indiapi.h:182
@ IP_WO
Definition indiapi.h:183
IPState
Property state.
Definition indiapi.h:158
@ IPS_BUSY
Definition indiapi.h:161
@ IPS_ALERT
Definition indiapi.h:162
@ IPS_IDLE
Definition indiapi.h:159
@ IPS_OK
Definition indiapi.h:160
@ ISR_1OFMANY
Definition indiapi.h:171
@ ISR_NOFMANY
Definition indiapi.h:173
@ ISR_ATMOST1
Definition indiapi.h:172
@ AXIS_DE
@ AXIS_RA
@ INDI_MONO
@ INDI_RGB
int f_scansexa(const char *str0, double *dp)
convert sexagesimal string str AxBxC to double. x can be anything non-numeric. Any missing A,...
Definition indicom.c:194
double range24(double r)
range24 Limits a number to be between 0-24 range.
Definition indicom.c:1311
double range360(double r)
range360 Limits an angle to be between 0-360 degrees.
Definition indicom.c:1321
Implementations for common driver routines.
void IUFillNumberVector(INumberVectorProperty *nvp, INumber *np, int nnp, const char *dev, const char *name, const char *label, const char *group, IPerm p, double timeout, IPState s)
Assign attributes for a number vector property. The vector's auxiliary elements will be set to NULL.
Definition indidevapi.c:490
int IUSnoopNumber(XMLEle *root, INumberVectorProperty *nvp)
Update a snooped number vector property from the given XML root element.
Definition indidevapi.c:555
void IUFillNumber(INumber *np, const char *name, const char *label, const char *format, double min, double max, double step, double value)
Assign attributes for a number property. The number's auxiliary elements will be set to NULL.
Definition indidevapi.c:398
void IDSnoopDevice(const char *snooped_device, const char *snooped_property)
Function a Driver calls to snoop on another Device. Snooped messages will then arrive via ISSnoopDevi...
Definition indidriver.c:143
*brief user defined string literal for JSON values *sa std::size_t n
#define LOGF_INFO(fmt,...)
Definition indilogger.h:82
#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
const char * findXMLAttValu(XMLEle *ep, const char *name)
Find an XML element's attribute value.
Definition lilxml.cpp:644
XMLEle * nextXMLEle(XMLEle *ep, int init)
Iterate an XML element for a list of nesetd XML elements.
Definition lilxml.cpp:555
char * pcdataXMLEle(XMLEle *ep)
Return the pcdata of an XML element.
Definition lilxml.cpp:606
struct xml_ele_ XMLEle
Definition lilxml.h:81
Namespace to encapsulate INDI client, drivers, and mediator classes.
void ObservedToJ2000(IEquatorialCoordinates *observed, double jd, IEquatorialCoordinates *J2000pos)
ObservedToJ2000 converts an observed position to a J2000 catalogue position removes aberration,...
Definition libastro.cpp:51
@ error
throw a parse_error exception in case of a tag
uint8_t cmd[4]
Definition pwc-ioctl.h:2
float limitingMag
float saturationMag