Debian Codegraph @

gphoto_ccd.cpp

raw
1 /*
2 Driver type: GPhoto Camera INDI Driver
3
4 Copyright (C) 2009 Geoffrey Hausheer
5 Copyright (C) 2013 Jasem Mutlaq (mutlaqja AT ikarustech DOT com)
6
7 This library is free software; you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as published
9 by the Free Software Foundation; either version 2.1 of the License, or
10 (at your option) any later version.
11
12 This library is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
14 or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
15 License for more details.
16
17 You should have received a copy of the GNU Lesser General Public License
18 along with this library; if not, write to the Free Software Foundation,
19 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
21 */
22
23 #include "gphoto_ccd.h"
24
25 #include "config.h"
26 #include "gphoto_driver.h"
27 #include "gphoto_readimage.h"
28
29 #include <algorithm>
30 #include <stream/streammanager.h>
31
32 #include <deque>
33 #include <memory>
34 #include <math.h>
35 #include <unistd.h>
36 #include <sys/mman.h>
37 #include <fcntl.h>
38 #include <sys/stat.h>
39
40 #define FOCUS_TAB "Focus"
41 #define MAX_DEVICES 5 /* Max device cameraCount */
42 #define FOCUS_TIMER 50
43 #define MAX_RETRIES 3
44
45 extern char * __progname;
46
47
48 typedef struct
49 {
50 const char * exec;
51 const char * driver;
52 const char * model;
53 } CamDriverInfo;
54
55 static CamDriverInfo camInfos[] = { { "indi_gphoto_ccd", "GPhoto CCD", "GPhoto" },
56 { "indi_canon_ccd", "Canon DSLR", "Canon" },
57 { "indi_nikon_ccd", "Nikon DSLR", "Nikon" },
58 { "indi_pentax_ccd", "Pentax DSLR", "Pentax" },
59 { "indi_sony_ccd", "Sony DSLR", "Sony" },
60 { "indi_fuji_ccd", "Fuji DSLR", "Fuji" },
61 { nullptr, nullptr, nullptr }
62 };
63
64 static class Loader
65 {
66 public:
67 std::deque<std::unique_ptr<GPhotoCCD>> cameras;
68 GPContext *context;
69
70 public:
71 Loader()
72 : context(gp_context_new())
73 {
74 // Let's just create one camera for now
75 if (!strcmp(__progname, "indi_gphoto_ccd"))
76 {
77 cameras.push_back(std::unique_ptr<GPhotoCCD>(new GPhotoCCD()));
78 return;
79 }
80
81 CameraList * list;
82 /* Detect all the cameras that can be autodetected... */
83 int ret = gp_list_new(&list);
84 if (ret < GP_OK)
85 {
86 // Use Legacy Mode
87 IDLog("Failed to initialize list in libgphoto2\n");
88 return;
89 }
90
91 const char * model, *port;
92 gp_list_reset(list);
93 int availableCameras = gp_camera_autodetect(list, context);
94 /* Now open all cameras we autodected for usage */
95 IDLog("Number of cameras detected: %d.\n", availableCameras);
96
97 if (availableCameras == 0)
98 {
99 IDLog("Failed to detect any cameras. Check power and make sure camera is not mounted by other programs "
100 "and try again.\n");
101 // Use Legacy Mode
102 #if 0
103 IDLog("No cameras detected. Using legacy mode...");
104 cameras.push_back(std::unique_ptr<GPhotoCCD>(new GPhotoCCD()));
105 #endif
106 return;
107 }
108
109 int cameraIndex = 0;
110
111 std::vector<std::string> cameraNames;
112
113 while (availableCameras > 0)
114 {
115 gp_list_get_name(list, cameraIndex, &model);
116 gp_list_get_value(list, cameraIndex, &port);
117
118 IDLog("Detected camera model %s on port %s\n", model, port);
119
120 cameraIndex++;
121 availableCameras--;
122
123 // If we're NOT using the Generic INDI GPhoto drievr
124 // then let's search for multiple cameras
125 if (strcmp(__progname, "indi_gphoto_ccd"))
126 {
127 char prefix[MAXINDINAME];
128 char name[MAXINDINAME];
129 bool modelFound = false;
130
131 for (int j = 0; camInfos[j].exec != nullptr; j++)
132 {
133 if (strstr(model, camInfos[j].model))
134 {
135 strncpy(prefix, camInfos[j].driver, MAXINDINAME);
136
137 // If if the model was already registered for a prior camera in case we are using
138 // two identical models
139 if (std::find(cameraNames.begin(), cameraNames.end(), camInfos[j].model) == cameraNames.end())
140 snprintf(name, MAXINDIDEVICE, "%s %s", prefix, model + strlen(camInfos[j].model) + 1);
141 else
142 snprintf(name, MAXINDIDEVICE, "%s %s %d", prefix, model + strlen(camInfos[j].model) + 1,
143 static_cast<int>(std::count(cameraNames.begin(), cameraNames.end(), camInfos[j].model)) + 1);
144
145 std::unique_ptr<GPhotoCCD> camera(new GPhotoCCD(model, port));
146 camera->setDeviceName(name);
147 cameras.push_back(std::move(camera));
148
149 modelFound = true;
150 // Store camera model in list to check for duplicates
151 cameraNames.push_back(camInfos[j].model);
152 break;
153 }
154 }
155
156 if (modelFound == false)
157 {
158 IDLog("Failed to find model %s in supported cameras.\n", model);
159 // If we are no cameras left
160 // Let us use the generic model name
161 // This is a libgphoto2 bug for some cameras which model does not correspond
162 // to the actual make of the camera but rather a generic class designation is given (e.g. PTP USB Camera)
163 if (availableCameras == 0)
164 {
165 IDLog("Falling back to generic name.\n");
166 for (int j = 0; camInfos[j].exec != nullptr; j++)
167 {
168 if (!strcmp(camInfos[j].exec, me))
169 {
170 snprintf(name, MAXINDIDEVICE, "%s", camInfos[j].model);
171 std::unique_ptr<GPhotoCCD> camera(new GPhotoCCD(model, port));
172 camera->setDeviceName(name);
173 cameras.push_back(std::move(camera));
174 }
175 }
176 }
177 }
178 }
179 else
180 {
181 cameras.push_back(std::unique_ptr<GPhotoCCD>(new GPhotoCCD(model, port)));
182 }
183 }
184 }
185
186 ~Loader()
187 {
188 // TODO free GPContext
189 }
190 } loader;
191
192 //==========================================================================
193 GPhotoCCD::GPhotoCCD() : FI(this)
194 {
195 memset(model, 0, MAXINDINAME);
196 memset(port, 0, MAXINDINAME);
197
198 gphotodrv = nullptr;
199 frameInitialized = false;
200 on_off[0] = strdup("On");
201 on_off[1] = strdup("Off");
202
203 setVersion(INDI_GPHOTO_VERSION_MAJOR, INDI_GPHOTO_VERSION_MINOR);
204 }
205
206 GPhotoCCD::GPhotoCCD(const char * model, const char * port) : FI(this)
207 {
208 strncpy(this->port, port, MAXINDINAME);
209 strncpy(this->model, model, MAXINDINAME);
210
211 gphotodrv = nullptr;
212 frameInitialized = false;
213 on_off[0] = strdup("On");
214 on_off[1] = strdup("Off");
215
216 setVersion(INDI_GPHOTO_VERSION_MAJOR, INDI_GPHOTO_VERSION_MINOR);
217 }
218
219 //==========================================================================
220 GPhotoCCD::~GPhotoCCD()
221 {
222 free(on_off[0]);
223 free(on_off[1]);
224 expTID = 0;
225 }
226
227 const char * GPhotoCCD::getDefaultName()
228 {
229 return "GPhoto CCD";
230 }
231
232 bool GPhotoCCD::initProperties()
233 {
234 // For now let's set name to default name. In the future, we need to to support multiple devices per one driver
235 if (*getDeviceName() == '\0')
236 strncpy(name, getDefaultName(), MAXINDINAME);
237 else
238 strncpy(name, getDeviceName(), MAXINDINAME);
239 setDeviceName(this->name);
240
241 // Init parent properties first
242 INDI::CCD::initProperties();
243
244 FI::initProperties(FOCUS_TAB);
245
246 IUFillText(&mPortT[0], "PORT", "Port", "");
247 IUFillTextVector(&PortTP, mPortT, NARRAY(mPortT), getDeviceName(), "DEVICE_PORT", "Shutter Release",
248 MAIN_CONTROL_TAB, IP_RW, 0, IPS_IDLE);
249
250 IUFillNumber(&mMirrorLockN[0], "MIRROR_LOCK_SECONDS", "Seconds", "%1.0f", 0, 10, 1, 0);
251 IUFillNumberVector(&mMirrorLockNP, mMirrorLockN, 1, getDeviceName(), "MIRROR_LOCK", "Mirror Lock", MAIN_CONTROL_TAB,
252 IP_RW, 60, IPS_IDLE);
253
254 //We don't know how many items will be in the switch yet
255 IUFillSwitchVector(&mIsoSP, nullptr, 0, getDeviceName(), "CCD_ISO", "ISO", IMAGE_SETTINGS_TAB, IP_RW, ISR_1OFMANY, 60,
256 IPS_IDLE);
257 IUFillSwitchVector(&mExposurePresetSP, nullptr, 0, getDeviceName(), "CCD_EXPOSURE_PRESETS", "Presets",
258 MAIN_CONTROL_TAB, IP_RW, ISR_1OFMANY, 60, IPS_IDLE);
259
260 IUFillSwitch(&autoFocusS[0], "Set", "", ISS_OFF);
261 IUFillSwitchVector(&autoFocusSP, autoFocusS, 1, getDeviceName(), "Auto Focus", "", FOCUS_TAB, IP_RW, ISR_1OFMANY, 0,
262 IPS_IDLE);
263
264 IUFillSwitch(&livePreviewS[0], "Enable", "", ISS_OFF);
265 IUFillSwitch(&livePreviewS[1], "Disable", "", ISS_ON);
266 IUFillSwitchVector(&livePreviewSP, livePreviewS, 2, getDeviceName(), "AUX_VIDEO_STREAM", "Preview",
267 MAIN_CONTROL_TAB, IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
268
269 // Nikon should use SD card by default
270 const bool isNikon = strstr(getDeviceName(), "Nikon");
271 IUFillSwitch(&captureTargetS[CAPTURE_INTERNAL_RAM], "RAM", "RAM", isNikon ? ISS_OFF : ISS_ON);
272 IUFillSwitch(&captureTargetS[CAPTURE_SD_CARD], "SD Card", "SD Card", isNikon ? ISS_ON : ISS_OFF);
273 IUFillSwitchVector(&captureTargetSP, captureTargetS, 2, getDeviceName(), "CCD_CAPTURE_TARGET", "Capture Target",
274 IMAGE_SETTINGS_TAB, IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
275
276 IUFillSwitch(&SDCardImageS[SD_CARD_SAVE_IMAGE], "Save", "", ISS_ON);
277 IUFillSwitch(&SDCardImageS[SD_CARD_DELETE_IMAGE], "Delete", "", ISS_OFF);
278 IUFillSwitch(&SDCardImageS[SD_CARD_IGNORE_IMAGE], "Ignore", "", ISS_OFF);
279 IUFillSwitchVector(&SDCardImageSP, SDCardImageS, 3, getDeviceName(), "CCD_SD_CARD_ACTION", "SD Image",
280 IMAGE_SETTINGS_TAB, IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
281
282 // Nikon should have force bulb off by default.
283 IUFillSwitch(&forceBULBS[FORCE_BULB_ON], "On", "On", isNikon ? ISS_OFF : ISS_ON);
284 IUFillSwitch(&forceBULBS[FORCE_BULB_OFF], "Off", "Off", isNikon ? ISS_ON : ISS_OFF);
285 IUFillSwitchVector(&forceBULBSP, forceBULBS, 2, getDeviceName(), "CCD_FORCE_BLOB", "Force BULB",
286 OPTIONS_TAB, IP_RW, ISR_1OFMANY, 0, IPS_IDLE);
287
288 // Upload File
289 IUFillText(&UploadFileT[0], "PATH", "Path", nullptr);
290 IUFillTextVector(&UploadFileTP, UploadFileT, 1, getDeviceName(), "CCD_UPLOAD_FILE", "Upload File", OPTIONS_TAB, IP_RW, 0,
291 IPS_IDLE);
292
293 PrimaryCCD.setMinMaxStep("CCD_EXPOSURE", "CCD_EXPOSURE_VALUE", 0.001, 3600, 1, false);
294
295 // Most cameras have this by default, so let's set it as default.
296 IUSaveText(&BayerT[2], "RGGB");
297
298 #ifdef HAVE_WEBSOCKET
299 SetCCDCapability(CCD_CAN_SUBFRAME | CCD_CAN_BIN | CCD_CAN_ABORT | CCD_HAS_BAYER | CCD_HAS_STREAMING | CCD_HAS_WEB_SOCKET);
300 #else
301 SetCCDCapability(CCD_CAN_SUBFRAME | CCD_CAN_BIN | CCD_CAN_ABORT | CCD_HAS_BAYER | CCD_HAS_STREAMING);
302 #endif
303
304 Streamer->setStreamingExposureEnabled(false);
305
306 #if 0
307 FI::SetCapability(FOCUSER_HAS_VARIABLE_SPEED);
308 FocusSpeedN[0].min = 0;
309 FocusSpeedN[0].max = 3;
310 FocusSpeedN[0].step = 1;
311 FocusSpeedN[0].value = 3;
312 #endif
313
314 FI::SetCapability(FOCUSER_CAN_REL_MOVE);
315
316 /* JM 2014-05-20 Make PrimaryCCD.ImagePixelSizeNP writable since we can't know for now the pixel size and bit depth from gphoto */
317 PrimaryCCD.getCCDInfo()->p = IP_RW;
318
319 setDriverInterface(getDriverInterface() | FOCUSER_INTERFACE);
320
321 gphoto_set_debug(getDeviceName());
322 gphoto_read_set_debug(getDeviceName());
323
324 // Add Debug, Simulator, and Configuration controls
325 addAuxControls();
326
327 return true;
328 }
329
330 void GPhotoCCD::ISGetProperties(const char * dev)
331 {
332 INDI::CCD::ISGetProperties(dev);
333
334 char configPort[MAXINDINAME] = {0};
335 if (IUGetConfigText(getDeviceName(), PortTP.name, mPortT[0].name, configPort, MAXINDINAME) == 0 && configPort[0])
336 IUSaveText(&mPortT[0], configPort);
337 defineProperty(&PortTP);
338
339 if (isConnected())
340 return;
341
342 // Read Image Info if we have not connected yet.
343 double pixel = 0, pixel_x = 0, pixel_y = 0;
344 IUGetConfigNumber(getDeviceName(), "CCD_INFO", "CCD_PIXEL_SIZE", &pixel);
345 IUGetConfigNumber(getDeviceName(), "CCD_INFO", "CCD_PIXEL_SIZE_X", &pixel_x);
346 IUGetConfigNumber(getDeviceName(), "CCD_INFO", "CCD_PIXEL_SIZE_Y", &pixel_y);
347
348 INumberVectorProperty *nvp = PrimaryCCD.getCCDInfo();
349
350 if (!nvp)
351 return;
352
353 // Load the necessary pixel size information
354 // The maximum resolution and bits per pixel depend on the capture itself.
355 // while the pixel size data remains constant.
356 if (pixel > 0)
357 nvp->np[INDI::CCDChip::CCD_PIXEL_SIZE].value = pixel;
358 if (pixel_x > 0)
359 nvp->np[INDI::CCDChip::CCD_PIXEL_SIZE_X].value = pixel_x;
360 if (pixel_y > 0)
361 nvp->np[INDI::CCDChip::CCD_PIXEL_SIZE_Y].value = pixel_y;
362
363 }
364
365 bool GPhotoCCD::updateProperties()
366 {
367 INDI::CCD::updateProperties();
368
369 if (isConnected())
370 {
371 if (mExposurePresetSP.nsp > 0)
372 defineProperty(&mExposurePresetSP);
373 if (mIsoSP.nsp > 0)
374 defineProperty(&mIsoSP);
375
376 defineProperty(&livePreviewSP);
377 defineProperty(&autoFocusSP);
378
379 if (m_CanFocus)
380 FI::updateProperties();
381
382 if (captureTargetSP.s == IPS_OK)
383 {
384 defineProperty(&captureTargetSP);
385 }
386
387 defineProperty(&SDCardImageSP);
388
389 imageBP = getBLOB("CCD1");
390 imageB = imageBP->bp;
391
392 // Dummy values until first capture is done
393 //SetCCDParams(1280, 1024, 8, 5.4, 5.4);
394
395 if (isSimulation() == false)
396 {
397 ShowExtendedOptions();
398
399 if (strstr(gphoto_get_manufacturer(gphotodrv), "Canon"))
400 defineProperty(&mMirrorLockNP);
401 }
402
403 if (isSimulation())
404 isTemperatureSupported = false;
405 else
406 isTemperatureSupported = gphoto_supports_temperature(gphotodrv);
407
408 if (isTemperatureSupported)
409 {
410 TemperatureNP.p = IP_RO;
411 defineProperty(&TemperatureNP);
412 }
413
414 defineProperty(&forceBULBSP);
415
416 //timerID = SetTimer(getCurrentPollingPeriod());
417 }
418 else
419 {
420 if (mExposurePresetSP.nsp > 0)
421 deleteProperty(mExposurePresetSP.name);
422 if (mIsoSP.nsp > 0)
423 deleteProperty(mIsoSP.name);
424
425 deleteProperty(mMirrorLockNP.name);
426 deleteProperty(livePreviewSP.name);
427 deleteProperty(autoFocusSP.name);
428
429 if (m_CanFocus)
430 FI::updateProperties();
431
432 if (captureTargetSP.s != IPS_IDLE)
433 {
434 deleteProperty(captureTargetSP.name);
435 }
436
437 if (isTemperatureSupported)
438 deleteProperty(TemperatureNP.name);
439
440 deleteProperty(SDCardImageSP.name);
441
442 deleteProperty(forceBULBSP.name);
443
444 HideExtendedOptions();
445 }
446
447 return true;
448 }
449
450 bool GPhotoCCD::ISNewText(const char * dev, const char * name, char * texts[], char * names[], int n)
451 {
452 if (dev != nullptr && strcmp(dev, getDeviceName()) == 0)
453 {
454 if (strcmp(name, PortTP.name) == 0)
455 {
456 const char *previousPort = mPortT[0].text;
457 PortTP.s = IPS_OK;
458 IUUpdateText(&PortTP, texts, names, n);
459 IDSetText(&PortTP, nullptr);
460
461 // Port changes requires a driver restart.
462 if (!previousPort || strcmp(previousPort, PortTP.tp[0].text))
463 {
464 saveConfig(true, PortTP.name);
465 LOG_INFO("Please restart the driver for this change to have effect.");
466 }
467 return true;
468 }
469 else if (strcmp(name, UploadFileTP.name) == 0)
470 {
471 struct stat buffer;
472 if (stat (texts[0], &buffer) == 0)
473 {
474 IUUpdateText(&UploadFileTP, texts, names, n);
475 UploadFileTP.s = IPS_OK;
476 }
477 else
478 {
479 LOGF_ERROR("File %s does not exist. Check path again.", texts[0]);
480 UploadFileTP.s = IPS_ALERT;
481 }
482
483 IDSetText(&UploadFileTP, nullptr);
484 return true;
485 }
486 else if (CamOptions.find(name) != CamOptions.end())
487 {
488 cam_opt * opt = CamOptions[name];
489 if (opt->widget->type != GP_WIDGET_TEXT)
490 {
491 LOGF_ERROR("ERROR: Property '%s'is not a string", name);
492 return false;
493 }
494 if (opt->widget->readonly)
495 {
496 LOGF_WARN("WARNING: Property %s is read-only", name);
497 IDSetText(&opt->prop.text, nullptr);
498 return false;
499 }
500
501 if (IUUpdateText(&opt->prop.text, texts, names, n) < 0)
502 return false;
503 gphoto_set_widget_text(gphotodrv, opt->widget, texts[0]);
504 opt->prop.num.s = IPS_OK;
505 IDSetText(&opt->prop.text, nullptr);
506 return true;
507 }
508 }
509
510 return INDI::CCD::ISNewText(dev, name, texts, names, n);
511 }
512
513 bool GPhotoCCD::ISNewSwitch(const char * dev, const char * name, ISState * states, char * names[], int n)
514 {
515 if (dev != nullptr && strcmp(dev, getDeviceName()) == 0)
516 {
517 if (!strcmp(name, mIsoSP.name))
518 {
519 if (IUUpdateSwitch(&mIsoSP, states, names, n) < 0)
520 return false;
521
522 for (int i = 0; i < mIsoSP.nsp; i++)
523 {
524 if (mIsoS[i].s == ISS_ON)
525 {
526 if (isSimulation() == false)
527 gphoto_set_iso(gphotodrv, i);
528 mIsoSP.s = IPS_OK;
529 IDSetSwitch(&mIsoSP, nullptr);
530 break;
531 }
532 }
533 }
534
535 ///////////////////////////////////////////////////////////////////////////////////////////////
536 // Force BULB
537 // This force driver to _always_ capture in bulb mode and never use predefined exposures unless the exposures are less
538 // than a second.
539 ///////////////////////////////////////////////////////////////////////////////////////////////
540 if (!strcmp(name, forceBULBSP.name))
541 {
542 if (IUUpdateSwitch(&forceBULBSP, states, names, n) < 0)
543 return false;
544
545 forceBULBSP.s = IPS_OK;
546 if (forceBULBS[FORCE_BULB_ON].s == ISS_ON)
547 {
548 if (isSimulation() == false)
549 gphoto_force_bulb(gphotodrv, true);
550 LOG_INFO("Force BULB is enabled. All expsures shall be captured in BULB mode except for subsecond captures.");
551 }
552 else
553 {
554 if (isSimulation() == false)
555 gphoto_force_bulb(gphotodrv, false);
556 LOG_INFO("Force BULB is disabled. Exposures shall utilize camera predefined exposures time first before attempting BULB.");
557 }
558
559 IDSetSwitch(&forceBULBSP, nullptr);
560 return true;
561 }
562
563 if (!strcmp(name, mExposurePresetSP.name))
564 {
565 if (IUUpdateSwitch(&mExposurePresetSP, states, names, n) < 0)
566 return false;
567
568 mExposurePresetSP.s = IPS_OK;
569 IDSetSwitch(&mExposurePresetSP, nullptr);
570
571 ISwitch * currentSwitch = IUFindOnSwitch(&mExposurePresetSP);
572 if (strcmp(currentSwitch->label, "bulb"))
573 {
574 LOGF_INFO("Preset %s seconds selected.", currentSwitch->label);
575
576 float duration;
577 int num, denom;
578 if (sscanf(currentSwitch->label, "%d/%d", &num, &denom) == 2)
579 {
580 duration = (static_cast<double>(num)) / (static_cast<double>(denom));
581 StartExposure(duration);
582 }
583 else if ((duration = strtod(currentSwitch->label, nullptr)))
584 {
585 // Fuji returns long exposure values ( > 60s) with m postfix
586 if (currentSwitch->label[strlen(currentSwitch->label) - 1] == 'm')
587 {
588 duration *= 60;
589 }
590 StartExposure(duration);
591 }
592 }
593
594 return true;
595 }
596
597 // Autofocus
598 if (!strcmp(name, autoFocusSP.name))
599 {
600 IUResetSwitch(&autoFocusSP);
601 char errMsg[MAXRBUF];
602 if (gphoto_auto_focus(gphotodrv, errMsg) == GP_OK)
603 autoFocusSP.s = IPS_OK;
604 else
605 {
606 autoFocusSP.s = IPS_ALERT;
607 LOGF_ERROR("%s", errMsg);
608 }
609
610 IDSetSwitch(&autoFocusSP, nullptr);
611 return true;
612 }
613
614 // Live preview
615 #if 0
616 if (!strcmp(name, livePreviewSP.name))
617 {
618 IUUpdateSwitch(&livePreviewSP, states, names, n);
619
620 if (Streamer->isBusy())
621 {
622 livePreviewS[0].s = ISS_OFF;
623 livePreviewS[1].s = ISS_ON;
624 livePreviewSP.s = IPS_ALERT;
625 LOG_WARN("Cannot start live preview while video streaming is active.");
626 IDSetSwitch(&livePreviewSP, nullptr);
627 return true;
628 }
629
630 if (livePreviewS[0].s == ISS_ON)
631 {
632 livePreviewSP.s = IPS_BUSY;
633 SetTimer(STREAMPOLLMS);
634 }
635 else
636 {
637 stopLivePreview();
638 livePreviewSP.s = IPS_IDLE;
639 }
640 IDSetSwitch(&livePreviewSP, nullptr);
641 return true;
642 }
643 #endif
644
645 // Capture target
646 if (!strcmp(captureTargetSP.name, name))
647 {
648 const char * onSwitch = IUFindOnSwitchName(states, names, n);
649 int captureTarget =
650 (!strcmp(onSwitch, captureTargetS[CAPTURE_INTERNAL_RAM].name) ? CAPTURE_INTERNAL_RAM : CAPTURE_SD_CARD);
651 int ret = gphoto_set_capture_target(gphotodrv, captureTarget);
652 if (ret == GP_OK)
653 {
654 captureTargetSP.s = IPS_OK;
655 IUUpdateSwitch(&captureTargetSP, states, names, n);
656 LOGF_INFO("Capture target set to %s",
657 (captureTarget == CAPTURE_INTERNAL_RAM) ? "Internal RAM" : "SD Card");
658 }
659 else
660 {
661 captureTargetSP.s = IPS_ALERT;
662 LOGF_INFO("Failed to set capture target set to %s",
663 (captureTarget == CAPTURE_INTERNAL_RAM) ? "Internal RAM" : "SD Card");
664 }
665
666 IDSetSwitch(&captureTargetSP, nullptr);
667 return true;
668 }
669
670 if (!strcmp(SDCardImageSP.name, name))
671 {
672 IUUpdateSwitch(&SDCardImageSP, states, names, n);
673 SDCardImageSP.s = IPS_OK;
674 const auto index = IUFindOnSwitchIndex(&SDCardImageSP);
675 switch (index)
676 {
677 case SD_CARD_SAVE_IMAGE:
678 LOG_INFO("Images downloaded from camera will saved in the camera internal storage.");
679 break;
680 case SD_CARD_DELETE_IMAGE:
681 LOG_INFO("Images downloaded from camera will not be stored on the camera internal storage.");
682 break;
683 case SD_CARD_IGNORE_IMAGE:
684 LOG_INFO("Images should only remain in the camera internal storage and will not be downloaded at all.");
685
686 // Upload mode should always be local, no images uploaded.
687 if (UploadS[UPLOAD_LOCAL].s != ISS_ON)
688 {
689 IUResetSwitch(&UploadSP);
690 UploadS[UPLOAD_LOCAL].s = ISS_ON;
691 UploadSP.s = IPS_OK;
692 IDSetSwitch(&UploadSP, nullptr);
693 }
694
695 // Capture target should always be SD card.
696 if (captureTargetS[CAPTURE_SD_CARD].s != ISS_ON)
697 {
698 IUResetSwitch(&captureTargetSP);
699 captureTargetSP.s = IPS_OK;
700 captureTargetS[CAPTURE_SD_CARD].s = ISS_ON;
701 gphoto_set_capture_target(gphotodrv, CAPTURE_SD_CARD);
702 IDSetSwitch(&captureTargetSP, nullptr);
703 }
704 break;
705 }
706
707 gphoto_handle_sdcard_image(gphotodrv, static_cast<CameraImageHandling>(index));
708 IDSetSwitch(&SDCardImageSP, nullptr);
709 return true;
710 }
711
712 if (strstr(name, "FOCUS"))
713 {
714 return FI::processSwitch(dev, name, states, names, n);
715 }
716
717 if (CamOptions.find(name) != CamOptions.end())
718 {
719 cam_opt * opt = CamOptions[name];
720 if (opt->widget->type != GP_WIDGET_RADIO && opt->widget->type != GP_WIDGET_MENU &&
721 opt->widget->type != GP_WIDGET_TOGGLE)
722 {
723 LOGF_ERROR("ERROR: Property '%s'is not a switch (%d)", name, opt->widget->type);
724 return false;
725 }
726
727 if (opt->widget->readonly)
728 {
729 LOGF_WARN("WARNING: Property %s is read-only", name);
730 IDSetSwitch(&opt->prop.sw, nullptr);
731 return false;
732 }
733
734 if (IUUpdateSwitch(&opt->prop.sw, states, names, n) < 0)
735 return false;
736
737 if (opt->widget->type == GP_WIDGET_TOGGLE)
738 {
739 gphoto_set_widget_num(gphotodrv, opt->widget, opt->item.sw[ON_S].s == ISS_ON);
740 }
741 else
742 {
743 for (int i = 0; i < opt->prop.sw.nsp; i++)
744 {
745 if (opt->item.sw[i].s == ISS_ON)
746 {
747 gphoto_set_widget_num(gphotodrv, opt->widget, i);
748 break;
749 }
750 }
751 }
752
753 opt->prop.sw.s = IPS_OK;
754 IDSetSwitch(&opt->prop.sw, nullptr);
755 return true;
756 }
757 }
758
759 return INDI::CCD::ISNewSwitch(dev, name, states, names, n);
760 }
761
762 bool GPhotoCCD::ISNewNumber(const char * dev, const char * name, double values[], char * names[], int n)
763 {
764 if (dev != nullptr && strcmp(dev, getDeviceName()) == 0)
765 {
766 if (strstr(name, "FOCUS_"))
767 return FI::processNumber(dev, name, values, names, n);
768
769 if (!strcmp(name, mMirrorLockNP.name))
770 {
771 IUUpdateNumber(&mMirrorLockNP, values, names, n);
772 mMirrorLockNP.s = IPS_OK;
773 IDSetNumber(&mMirrorLockNP, nullptr);
774 return true;
775 }
776
777 if (CamOptions.find(name) != CamOptions.end())
778 {
779 cam_opt * opt = CamOptions[name];
780 if (opt->widget->type != GP_WIDGET_RANGE)
781 {
782 LOGF_ERROR("ERROR: Property '%s'is not a string", name);
783 return false;
784 }
785 if (opt->widget->readonly)
786 {
787 LOGF_WARN("WARNING: Property %s is read-only", name);
788 return false;
789 }
790 if (IUUpdateNumber(&opt->prop.num, values, names, n) < 0)
791 return false;
792 gphoto_set_widget_num(gphotodrv, opt->widget, values[0]);
793 opt->prop.num.s = IPS_OK;
794 IDSetNumber(&opt->prop.num, nullptr);
795 return true;
796 }
797 }
798
799 return INDI::CCD::ISNewNumber(dev, name, values, names, n);
800 }
801
802 bool GPhotoCCD::Connect()
803 {
804 int setidx;
805 char ** options;
806 int max_opts;
807 const char * shutter_release_port = nullptr;
808 LOGF_DEBUG("Mirror lock value: %f", mMirrorLockN[0].value);
809
810 if (PortTP.tp[0].text && strlen(PortTP.tp[0].text))
811 {
812 shutter_release_port = PortTP.tp[0].text;
813 }
814
815 if (isSimulation() == false)
816 {
817 // Regular detect
818 if (port[0] == '\0')
819 gphotodrv = gphoto_open(camera, loader.context, nullptr, nullptr, shutter_release_port);
820 else
821 gphotodrv = gphoto_open(camera, loader.context, model, port, shutter_release_port);
822 if (gphotodrv == nullptr)
823 {
824 LOG_ERROR("Can not open camera: Power OK? If camera is auto-mounted as external disk "
825 "storage, please unmount it and disable auto-mount.");
826 return false;
827 }
828 }
829
830 if (isSimulation())
831 {
832 PrimaryCCD.setMinMaxStep("CCD_EXPOSURE", "CCD_EXPOSURE_VALUE", 0.001, 3600, 1, true);
833 }
834 else
835 {
836 double min_exposure = 0.001, max_exposure = 3600;
837
838 gphoto_get_minmax_exposure(gphotodrv, &min_exposure, &max_exposure);
839 PrimaryCCD.setMinMaxStep("CCD_EXPOSURE", "CCD_EXPOSURE_VALUE", min_exposure, max_exposure, 1, true);
840 }
841
842 const char * fmts[] = { "Custom" };
843 //setidx = 0;
844 max_opts = 1;
845 options = const_cast<char **>(fmts);
846
847 if (!isSimulation())
848 {
849 //setidx = gphoto_get_format_current(gphotodrv);
850 options = gphoto_get_formats(gphotodrv, &max_opts);
851 }
852
853 if (max_opts > 0)
854 {
855 for (int i = 0; i < max_opts; i++)
856 {
857 std::string label = options[i];
858 if (label.find('+') != std::string::npos ||
859 label.find("sRAW") != std::string::npos ||
860 label.find("mRAW") != std::string::npos)
861 {
862 continue;
863 }
864
865 uint8_t index = CaptureFormatSP.size();
866 auto isRAW = strcasestr(label.c_str(), "RAW") != nullptr;
867 char name[MAXINDINAME] = {0};
868 snprintf(name, MAXINDINAME, "FORMAT_%d", index + 1);
869 CaptureFormat format = {name, label, 8, isRAW};
870 addCaptureFormat(format);
871
872 m_CaptureFormatMap[index] = i;
873 }
874 }
875
876 if (mIsoS)
877 free(mIsoS);
878
879 const char * isos[] = { "100", "200", "400", "800" };
880 setidx = 0;
881 max_opts = 4;
882 options = const_cast<char **>(isos);
883
884 if (!isSimulation())
885 {
886 setidx = gphoto_get_iso_current(gphotodrv);
887 options = gphoto_get_iso(gphotodrv, &max_opts);
888 }
889
890 mIsoS = create_switch("ISO", options, max_opts, setidx);
891 mIsoSP.sp = mIsoS;
892 mIsoSP.nsp = max_opts;
893
894 if (mExposurePresetS)
895 {
896 free(mExposurePresetS);
897 mExposurePresetS = nullptr;
898 }
899
900 const char * exposureList[] =
901 {
902 "1/2000",
903 "1/1000",
904 "1/500",
905 "1/200",
906 "1/100",
907 "1/50",
908 "1/8",
909 "1/4",
910 "1/2",
911 "1",
912 "2",
913 "5",
914 "bulb"
915 };
916 setidx = 0;
917 max_opts = NARRAY(exposureList);
918 options = const_cast<char **>(exposureList);
919
920 if (!isSimulation())
921 {
922 setidx = 0;
923 max_opts = 0;
924 options = gphoto_get_exposure_presets(gphotodrv, &max_opts);
925 }
926
927 if (max_opts > 0)
928 {
929 mExposurePresetS = create_switch("EXPOSURE_PRESET", options, max_opts, setidx);
930 mExposurePresetSP.sp = mExposurePresetS;
931 mExposurePresetSP.nsp = max_opts;
932 }
933
934 // Get Capture target
935 int captureTarget = -1;
936
937 if (!isSimulation() && gphoto_get_capture_target(gphotodrv, &captureTarget) == GP_OK)
938 {
939 IUResetSwitch(&captureTargetSP);
940 captureTargetS[CAPTURE_INTERNAL_RAM].s = (captureTarget == 0) ? ISS_ON : ISS_OFF;
941 captureTargetS[CAPTURE_SD_CARD].s = (captureTarget == 1) ? ISS_ON : ISS_OFF;
942 captureTargetSP.s = IPS_OK;
943 }
944
945 if (isSimulation())
946 m_CanFocus = false;
947 else
948 m_CanFocus = gphoto_can_focus(gphotodrv);
949
950 LOGF_INFO("%s is online.", getDeviceName());
951
952 if (!isSimulation() && gphoto_get_manufacturer(gphotodrv) && gphoto_get_model(gphotodrv))
953 {
954 LOGF_INFO("Detected %s Model %s.", gphoto_get_manufacturer(gphotodrv),
955 gphoto_get_model(gphotodrv));
956 }
957
958 frameInitialized = false;
959
960 return true;
961 }
962
963 bool GPhotoCCD::Disconnect()
964 {
965 if (isSimulation())
966 return true;
967 gphoto_close(gphotodrv);
968 gphotodrv = nullptr;
969 frameInitialized = false;
970 LOGF_INFO("%s is offline.", getDeviceName());
971 return true;
972 }
973
974 bool GPhotoCCD::StartExposure(float duration)
975 {
976 if (PrimaryCCD.getPixelSizeX() == 0.0)
977 {
978 LOG_INFO("Please update the CCD Information in the Image Info section before "
979 "proceeding. The camera resolution shall be updated after the first exposure "
980 "is complete.");
981 return false;
982 }
983
984 if (InExposure)
985 {
986 LOG_ERROR("GPhoto driver is already exposing.");
987 return false;
988 }
989
990 /* start new exposure with last ExpValues settings.
991 * ExpGo goes busy. set timer to read when done
992 */
993
994 if (isSimulation() == false)
995 gphoto_set_format(gphotodrv, m_CaptureFormatMap[CaptureFormatSP.findOnSwitchIndex()]);
996
997 // Microseconds
998 uint32_t exp_us = static_cast<uint32_t>(ceil(duration * 1e6));
999
1000 PrimaryCCD.setExposureDuration(duration);
1001
1002 if (mMirrorLockN[0].value > 0)
1003 LOGF_INFO("Starting %g seconds exposure (+%g seconds mirror lock).", duration, mMirrorLockN[0].value);
1004 else
1005 LOGF_INFO("Starting %g seconds exposure.", duration);
1006
1007 if (isSimulation() == false && gphoto_start_exposure(gphotodrv, exp_us, mMirrorLockN[0].value) < 0)
1008 {
1009 LOG_ERROR("Error starting exposure");
1010 return false;
1011 }
1012
1013 ExposureRequest = duration;
1014 gettimeofday(&ExpStart, nullptr);
1015 InExposure = true;
1016
1017 SetTimer(getCurrentPollingPeriod());
1018
1019 return true;
1020 }
1021
1022 bool GPhotoCCD::AbortExposure()
1023 {
1024 if (!isSimulation())
1025 gphoto_abort_exposure(gphotodrv);
1026 InExposure = false;
1027 return true;
1028 }
1029
1030 bool GPhotoCCD::UpdateCCDFrame(int x, int y, int w, int h)
1031 {
1032 if (EncodeFormatSP[FORMAT_FITS].getState() != ISS_ON)
1033 {
1034 LOG_ERROR("Subframing is only supported in FITS encode mode.");
1035 return false;
1036 }
1037
1038 PrimaryCCD.setFrame(x, y, w, h);
1039 return true;
1040 }
1041
1042 // binning
1043 bool GPhotoCCD::UpdateCCDBin(int hor, int ver)
1044 {
1045
1046 if(hor == 1 && ver == 1)
1047 {
1048 binning = false;
1049 }
1050 else
1051 {
1052 // only for fits output
1053 if (EncodeFormatSP[FORMAT_FITS].getState() != ISS_ON)
1054 {
1055 LOG_ERROR("Binning is only supported in FITS transport mode.");
1056 return false;
1057 }
1058
1059 binning = true;
1060
1061 }
1062
1063 return INDI::CCD::UpdateCCDBin(hor, ver);
1064 }
1065
1066
1067 double GPhotoCCD::CalcTimeLeft()
1068 {
1069 struct timeval now, diff;
1070 gettimeofday(&now, nullptr);
1071
1072 timersub(&now, &ExpStart, &diff);
1073 double timesince = diff.tv_sec + diff.tv_usec / 1000000.0;
1074 return (ExposureRequest - timesince);
1075 }
1076
1077 void GPhotoCCD::TimerHit()
1078 {
1079 if (isConnected() == false)
1080 return;
1081
1082 if (InExposure)
1083 {
1084 int timerID = -1;
1085 double timeleft = CalcTimeLeft();
1086
1087 if (timeleft < 0)
1088 timeleft = 0;
1089
1090 PrimaryCCD.setExposureLeft(timeleft);
1091
1092 if (timeleft < 1.0)
1093 {
1094 if (timeleft > 0.25)
1095 timerID = SetTimer(timeleft * 900);
1096 else
1097 {
1098 PrimaryCCD.setExposureLeft(0);
1099 InExposure = false;
1100 // grab and save image
1101 bool rc = grabImage();
1102 if (rc == false)
1103 {
1104 PrimaryCCD.setExposureFailed();
1105 }
1106 }
1107
1108 if (isTemperatureSupported)
1109 {
1110 double cameraTemperature = static_cast<double>(gphoto_get_last_sensor_temperature(gphotodrv));
1111 if (fabs(cameraTemperature - TemperatureN[0].value) > 0.01)
1112 {
1113 // Check if we are getting bogus temperature values and set property to alert
1114 // unless it is already set
1115 if (cameraTemperature < MINUMUM_CAMERA_TEMPERATURE)
1116 {
1117 if (TemperatureNP.s != IPS_ALERT)
1118 {
1119 TemperatureNP.s = IPS_ALERT;
1120 IDSetNumber(&TemperatureNP, nullptr);
1121 }
1122 }
1123 else
1124 {
1125 TemperatureNP.s = IPS_OK;
1126 TemperatureN[0].value = cameraTemperature;
1127 IDSetNumber(&TemperatureNP, nullptr);
1128 }
1129 }
1130 }
1131 }
1132
1133 if (InExposure && timerID == -1)
1134 SetTimer(getCurrentPollingPeriod());
1135 }
1136 }
1137
1138 void GPhotoCCD::UpdateExtendedOptions(void * p)
1139 {
1140 GPhotoCCD * cam = static_cast<GPhotoCCD *>(p);
1141 cam->UpdateExtendedOptions();
1142 }
1143
1144 void GPhotoCCD::UpdateExtendedOptions(bool force)
1145 {
1146 if (!expTID)
1147 {
1148 for (auto &option : CamOptions)
1149 {
1150 cam_opt * opt = option.second;
1151
1152 if (force || gphoto_widget_changed(opt->widget))
1153 {
1154 gphoto_read_widget(opt->widget);
1155 UpdateWidget(opt);
1156 }
1157 }
1158 }
1159
1160 optTID = IEAddTimer(1000, GPhotoCCD::UpdateExtendedOptions, this);
1161 }
1162
1163 bool GPhotoCCD::grabImage()
1164 {
1165 uint8_t * memptr = PrimaryCCD.getFrameBuffer();
1166 size_t memsize = 0;
1167 int naxis = 2, w = 0, h = 0, bpp = 8;
1168
1169 if (SDCardImageS[SD_CARD_IGNORE_IMAGE].s == ISS_ON)
1170 {
1171 PrimaryCCD.setFrameBufferSize(0);
1172 ExposureComplete(&PrimaryCCD);
1173 gphoto_read_exposure_fd(gphotodrv, -1);
1174 }
1175 else if (EncodeFormatSP[FORMAT_FITS].getState() == ISS_ON)
1176 {
1177 char filename[MAXRBUF] = "/tmp/indi_XXXXXX";
1178 const char *extension = "unknown";
1179 if (isSimulation())
1180 {
1181 if (UploadFileT[0].text == nullptr || !UploadFileT[0].text[0])
1182 {
1183 LOG_WARN("You must specify simulation file path under Options.");
1184 return false;
1185 }
1186
1187 strncpy(filename, UploadFileT[0].text, MAXRBUF);
1188 const char *found = strchr(filename, '.');
1189 if (found == nullptr)
1190 {
1191 LOGF_ERROR("Upload filename %s is invalid.", UploadFileT[0].text);
1192 return false;
1193 }
1194 extension = found + 1;
1195 }
1196 else
1197 {
1198 int fd = mkstemp(filename);
1199 int ret = gphoto_read_exposure_fd(gphotodrv, fd);
1200 if (ret != GP_OK || fd == -1)
1201 {
1202 if (fd == -1)
1203 LOGF_ERROR("Exposure failed to save image. Cannot create temp file %s", tmpfile);
1204 else
1205 {
1206 LOGF_ERROR("Exposure failed to save image... %s", gp_result_as_string(ret));
1207 // As suggested on INDI forums, this result could be misleading.
1208 if (ret == GP_ERROR_DIRECTORY_NOT_FOUND)
1209 LOG_INFO("Make sure BULB switch is ON in the camera. Try setting AF switch to OFF.");
1210 }
1211 unlink(filename);
1212 return false;
1213 }
1214
1215 extension = gphoto_get_file_extension(gphotodrv);
1216 }
1217
1218 if (!strcmp(extension, "unknown"))
1219 {
1220 LOG_ERROR("Exposure failed.");
1221 return false;
1222 }
1223
1224 // We're done exposing
1225 if (ExposureRequest > 3)
1226 LOG_INFO("Exposure done, downloading image...");
1227
1228 if (strcasecmp(extension, "jpg") == 0 || strcasecmp(extension, "jpeg") == 0)
1229 {
1230 if (read_jpeg(filename, &memptr, &memsize, &naxis, &w, &h))
1231 {
1232 LOG_ERROR("Exposure failed to parse jpeg.");
1233 if (!isSimulation())
1234 unlink(filename);
1235 return false;
1236 }
1237
1238 LOGF_DEBUG("read_jpeg: memsize (%d) naxis (%d) w (%d) h (%d) bpp (%d)", memsize, naxis, w, h, bpp);
1239
1240 SetCCDCapability(GetCCDCapability() & ~CCD_HAS_BAYER);
1241 }
1242 else
1243 {
1244 char bayer_pattern[8] = {};
1245
1246 if (read_libraw(filename, &memptr, &memsize, &naxis, &w, &h, &bpp, bayer_pattern))
1247 {
1248 LOG_ERROR("Exposure failed to parse raw image.");
1249 if (!isSimulation())
1250 unlink(filename);
1251 return false;
1252 }
1253
1254 LOGF_DEBUG("read_libraw: memsize (%d) naxis (%d) w (%d) h (%d) bpp (%d) bayer pattern (%s)",
1255 memsize, naxis, w, h, bpp, bayer_pattern);
1256
1257 if (!isSimulation())
1258 unlink(filename);
1259
1260 IUSaveText(&BayerT[2], bayer_pattern);
1261 IDSetText(&BayerTP, nullptr);
1262 SetCCDCapability(GetCCDCapability() | CCD_HAS_BAYER);
1263 }
1264
1265 PrimaryCCD.setImageExtension("fits");
1266
1267 uint16_t subW = PrimaryCCD.getSubW();
1268 uint16_t subH = PrimaryCCD.getSubH();
1269
1270 // If subframing is requested
1271 // If either axis is less than the image resolution
1272 // then we subframe, given the OTHER axis is within range as well.
1273 if ( (subW > 0 && subH > 0) && ((subW < w && subH <= h) || (subH < h && subW <= w)))
1274 {
1275
1276 uint16_t subX = PrimaryCCD.getSubX();
1277 uint16_t subY = PrimaryCCD.getSubY();
1278
1279 // Align all boundaries to be even
1280 // This should fix issues with subframed bayered images.
1281 // subX -= subX % 2;
1282 // subY -= subY % 2;
1283 // subW -= subW % 2;
1284 // subH -= subH % 2;
1285
1286 int subFrameSize = subW * subH * bpp / 8 * ((naxis == 3) ? 3 : 1);
1287 int oneFrameSize = subW * subH * bpp / 8;
1288
1289 int lineW = subW * bpp / 8;
1290
1291 LOGF_DEBUG("Subframing... subFrameSize: %d - oneFrameSize: %d - subX: %d - subY: %d - subW: %d - subH: %d",
1292 subFrameSize, oneFrameSize,
1293 subX, subY, subW, subH);
1294
1295 if (naxis == 2)
1296 {
1297 // JM 2020-08-29: Using memmove since regions are overlaping
1298 // as proposed by Camiel Severijns on INDI forums.
1299 for (int i = subY; i < subY + subH; i++)
1300 memmove(memptr + (i - subY) * lineW, memptr + (i * w + subX) * bpp / 8, lineW);
1301 }
1302 else
1303 {
1304 uint8_t * subR = memptr;
1305 uint8_t * subG = memptr + oneFrameSize;
1306 uint8_t * subB = memptr + oneFrameSize * 2;
1307
1308 uint8_t * startR = memptr;
1309 uint8_t * startG = memptr + (w * h * bpp / 8);
1310 uint8_t * startB = memptr + (w * h * bpp / 8 * 2);
1311
1312 for (int i = subY; i < subY + subH; i++)
1313 {
1314 memcpy(subR + (i - subY) * lineW, startR + (i * w + subX) * bpp / 8, lineW);
1315 memcpy(subG + (i - subY) * lineW, startG + (i * w + subX) * bpp / 8, lineW);
1316 memcpy(subB + (i - subY) * lineW, startB + (i * w + subX) * bpp / 8, lineW);
1317 }
1318 }
1319
1320 PrimaryCCD.setFrameBuffer(memptr);
1321 PrimaryCCD.setFrameBufferSize(memsize, false);
1322 PrimaryCCD.setResolution(w, h);
1323 PrimaryCCD.setFrame(subX, subY, subW, subH);
1324 PrimaryCCD.setNAxis(naxis);
1325 PrimaryCCD.setBPP(bpp);
1326
1327 // binning if needed
1328 if(binning)
1329 {
1330
1331 // binBayerFrame implemented since 1.9.4
1332 #if INDI_VERSION_MAJOR >= 1 && INDI_VERSION_MINOR >= 9 && INDI_VERSION_RELEASE >=4
1333 PrimaryCCD.binBayerFrame();
1334 #else
1335 PrimaryCCD.binFrame();
1336 #endif
1337 }
1338
1339 ExposureComplete(&PrimaryCCD);
1340
1341 // Restore old pointer and release memory
1342 //PrimaryCCD.setFrameBuffer(memptr);
1343 //PrimaryCCD.setFrameBufferSize(memsize, false);
1344 //delete [] (subframeBuf);
1345 }
1346 else
1347 {
1348 if (PrimaryCCD.getSubW() != 0 && (w > PrimaryCCD.getSubW() || h > PrimaryCCD.getSubH()))
1349 LOGF_WARN("Camera image size (%dx%d) is less than requested size (%d,%d). Purge configuration and update frame size to match camera size.",
1350 w, h, PrimaryCCD.getSubW(), PrimaryCCD.getSubH());
1351
1352 PrimaryCCD.setFrameBuffer(memptr);
1353 PrimaryCCD.setFrameBufferSize(memsize, false);
1354 PrimaryCCD.setResolution(w, h);
1355 PrimaryCCD.setFrame(0, 0, w, h);
1356 PrimaryCCD.setNAxis(naxis);
1357 PrimaryCCD.setBPP(bpp);
1358
1359 // binning if needed
1360 if(binning)
1361 {
1362 // binBayerFrame implemented since 1.9.4
1363 #if INDI_VERSION_MAJOR >= 1 && INDI_VERSION_MINOR >= 9 && INDI_VERSION_RELEASE >=4
1364 PrimaryCCD.binBayerFrame();
1365 #else
1366 PrimaryCCD.binFrame();
1367 #endif
1368 }
1369
1370 ExposureComplete(&PrimaryCCD);
1371 }
1372 }
1373
1374 // Read Native image AS IS
1375 else
1376 {
1377 if (isSimulation())
1378 {
1379 int fd = open(UploadFileT[0].text, O_RDONLY);
1380 struct stat sb;
1381
1382 // Get file size
1383 if (fstat(fd, &sb) == -1)
1384 {
1385 LOGF_ERROR("Error opening file %s: %s", UploadFileT[0].text, strerror(errno));
1386 close(fd);
1387 return false;
1388 }
1389
1390 // Copy file to memory using mmap
1391 memsize = sb.st_size;
1392 void *mmap_mem = mmap(nullptr, memsize, PROT_READ, MAP_PRIVATE, fd, 0);
1393 if (mmap_mem == nullptr)
1394 {
1395 LOGF_ERROR("Error reading file %s: %s", UploadFileT[0].text, strerror(errno));
1396 close(fd);
1397 return false;
1398 }
1399
1400 // Guard CCD Buffer content until we finish copying mmap buffer to it
1401 std::unique_lock<std::mutex> guard(ccdBufferLock);
1402 // If CCD Buffer size is different, allocate memory to file size
1403 if (PrimaryCCD.getFrameBufferSize() != static_cast<int>(memsize))
1404 {
1405 PrimaryCCD.setFrameBufferSize(memsize);
1406 memptr = PrimaryCCD.getFrameBuffer();
1407 }
1408
1409 // Copy mmap buffer to ccd buffer
1410 memcpy(memptr, mmap_mem, memsize);
1411
1412 // Release mmap memory
1413 munmap(mmap_mem, memsize);
1414 // Close file
1415 close(fd);
1416 // Set extension (eg. cr2..etc)
1417 PrimaryCCD.setImageExtension(strchr(UploadFileT[0].text, '.') + 1);
1418 // We are ready to unlock
1419 guard.unlock();
1420
1421 }
1422 else
1423 {
1424 int rc = gphoto_read_exposure(gphotodrv);
1425 if (rc != 0)
1426 {
1427 LOG_ERROR("Failed to expose.");
1428 if (strstr(gphoto_get_manufacturer(gphotodrv), "Canon") && mMirrorLockN[0].value == 0.0)
1429 DEBUG(INDI::Logger::DBG_WARNING,
1430 "If your camera mirror lock is enabled, you must set a value for the mirror locking duration.");
1431 return false;
1432 }
1433
1434 // We're done exposing
1435 if (ExposureRequest > 3)
1436 LOG_DEBUG("Exposure done, downloading image...");
1437 const char * gphotoFileData = nullptr;
1438 unsigned long gphotoFileSize = 0;
1439 gphoto_get_buffer(gphotodrv, &gphotoFileData, &gphotoFileSize);
1440 memsize = gphotoFileSize;
1441 // We copy the obtained memory pointer to avoid freeing some gphoto memory
1442 memptr = static_cast<uint8_t *>(IDSharedBlobRealloc(memptr, gphotoFileSize));
1443 if (memptr == nullptr)
1444 memptr = static_cast<uint8_t *>(IDSharedBlobAlloc(gphotoFileSize));
1445 if (memptr == nullptr)
1446 {
1447 LOG_ERROR("Failed to allocate memory to load file from camera.");
1448 PrimaryCCD.setExposureFailed();
1449 return false;
1450 }
1451 memcpy(memptr, gphotoFileData, gphotoFileSize);
1452
1453 gphoto_get_dimensions(gphotodrv, &w, &h);
1454
1455 PrimaryCCD.setImageExtension(gphoto_get_file_extension(gphotodrv));
1456 if (w > 0 && h > 0)
1457 PrimaryCCD.setFrame(0, 0, w, h);
1458 PrimaryCCD.setFrameBuffer(memptr);
1459 PrimaryCCD.setFrameBufferSize(memsize, false);
1460 if (w > 0 && h > 0)
1461 PrimaryCCD.setResolution(w, h);
1462 PrimaryCCD.setNAxis(naxis);
1463 PrimaryCCD.setBPP(bpp);
1464
1465 }
1466
1467 ExposureComplete(&PrimaryCCD);
1468 }
1469
1470 return true;
1471 }
1472
1473 ISwitch * GPhotoCCD::create_switch(const char * basestr, char ** options, int max_opts, int setidx)
1474 {
1475 int i;
1476 ISwitch * sw = static_cast<ISwitch *>(calloc(sizeof(ISwitch), max_opts));
1477 ISwitch * one_sw = sw;
1478
1479 char sw_name[MAXINDINAME];
1480 char sw_label[MAXINDILABEL];
1481 ISState sw_state;
1482
1483 for (i = 0; i < max_opts; i++)
1484 {
1485 snprintf(sw_name, MAXINDINAME, "%s%d", basestr, i);
1486 strncpy(sw_label, options[i], MAXINDILABEL);
1487 sw_state = (i == setidx) ? ISS_ON : ISS_OFF;
1488
1489 IUFillSwitch(one_sw++, sw_name, sw_label, sw_state);
1490 }
1491 return sw;
1492 }
1493
1494 void GPhotoCCD::UpdateWidget(cam_opt * opt)
1495 {
1496 switch (opt->widget->type)
1497 {
1498 case GP_WIDGET_RADIO:
1499 case GP_WIDGET_MENU:
1500 for (int i = 0; i < opt->widget->choice_cnt; i++)
1501 opt->item.sw[i].s = opt->widget->value.index == i ? ISS_ON : ISS_OFF;
1502 IDSetSwitch(&opt->prop.sw, nullptr);
1503 break;
1504 case GP_WIDGET_TEXT:
1505 free(opt->item.text.text);
1506 opt->item.text.text = strdup(opt->widget->value.text);
1507 IDSetText(&opt->prop.text, nullptr);
1508 break;
1509 case GP_WIDGET_TOGGLE:
1510 if (opt->widget->value.toggle)
1511 {
1512 opt->item.sw[0].s = ISS_ON;
1513 opt->item.sw[1].s = ISS_OFF;
1514 }
1515 else
1516 {
1517 opt->item.sw[0].s = ISS_OFF;
1518 opt->item.sw[1].s = ISS_ON;
1519 }
1520 IDSetSwitch(&opt->prop.sw, nullptr);
1521 break;
1522 case GP_WIDGET_RANGE:
1523 opt->item.num.value = opt->widget->value.num;
1524 IDSetNumber(&opt->prop.num, nullptr);
1525 break;
1526 case GP_WIDGET_DATE:
1527 free(opt->item.text.text);
1528 opt->item.text.text = static_cast<char *>(malloc(MAXINDILABEL));
1529 strftime(opt->item.text.text, MAXINDILABEL, "%FT%TZ", gmtime(reinterpret_cast<time_t *>(&opt->widget->value.date)));
1530 IDSetText(&opt->prop.text, nullptr);
1531 break;
1532 default:
1533 delete opt;
1534 return;
1535 }
1536 }
1537
1538 void GPhotoCCD::AddWidget(gphoto_widget * widget)
1539 {
1540 IPerm perm;
1541
1542 if (!widget)
1543 return;
1544
1545 perm = widget->readonly ? IP_RO : IP_RW;
1546
1547 cam_opt * opt = new cam_opt();
1548 opt->widget = widget;
1549
1550 switch (widget->type)
1551 {
1552 case GP_WIDGET_RADIO:
1553 case GP_WIDGET_MENU:
1554 opt->item.sw = create_switch(widget->name, widget->choices, widget->choice_cnt, widget->value.index);
1555 IUFillSwitchVector(&opt->prop.sw, opt->item.sw, widget->choice_cnt, getDeviceName(), widget->name,
1556 widget->name, widget->parent, perm, ISR_1OFMANY, 60, IPS_IDLE);
1557 defineProperty(&opt->prop.sw);
1558 break;
1559 case GP_WIDGET_TEXT:
1560 IUFillText(&opt->item.text, widget->name, widget->name, widget->value.text);
1561 IUFillTextVector(&opt->prop.text, &opt->item.text, 1, getDeviceName(), widget->name, widget->name,
1562 widget->parent, perm, 60, IPS_IDLE);
1563 defineProperty(&opt->prop.text);
1564 break;
1565 case GP_WIDGET_TOGGLE:
1566 opt->item.sw = create_switch(widget->name, static_cast<char **>(on_off), 2, widget->value.toggle ? 0 : 1);
1567 IUFillSwitchVector(&opt->prop.sw, opt->item.sw, 2, getDeviceName(), widget->name, widget->name,
1568 widget->parent, perm, ISR_1OFMANY, 60, IPS_IDLE);
1569 defineProperty(&opt->prop.sw);
1570 break;
1571 case GP_WIDGET_RANGE:
1572 IUFillNumber(&opt->item.num, widget->name, widget->name, "%5.2f", widget->min, widget->max, widget->step,
1573 widget->value.num);
1574 IUFillNumberVector(&opt->prop.num, &opt->item.num, 1, getDeviceName(), widget->name, widget->name,
1575 widget->parent, perm, 60, IPS_IDLE);
1576 defineProperty(&opt->prop.num);
1577 break;
1578 case GP_WIDGET_DATE:
1579 {
1580 //tm = gmtime((time_t *)&widget->value.date);
1581 //IUFillText(&opt->item.text, widget->name, widget->name, asctime(tm));
1582 char ts[MAXINDITSTAMP] = {0};
1583 strftime(ts, MAXINDILABEL, "%FT%TZ", gmtime(reinterpret_cast<time_t *>(&opt->widget->value.date)));
1584 IUFillText(&opt->item.text, widget->name, widget->name, ts);
1585 IUFillTextVector(&opt->prop.text, &opt->item.text, 1, getDeviceName(), widget->name, widget->name,
1586 widget->parent, perm, 60, IPS_IDLE);
1587 defineProperty(&opt->prop.text);
1588 }
1589 break;
1590 default:
1591 delete opt;
1592 return;
1593 }
1594
1595 CamOptions[widget->name] = opt;
1596 }
1597
1598 void GPhotoCCD::ShowExtendedOptions(void)
1599 {
1600 gphoto_widget_list * iter;
1601
1602 iter = gphoto_find_all_widgets(gphotodrv);
1603 while (iter)
1604 {
1605 gphoto_widget * widget = gphoto_get_widget_info(gphotodrv, &iter);
1606 AddWidget(widget);
1607 }
1608
1609 gphoto_show_options(gphotodrv);
1610
1611 optTID = IEAddTimer(1000, GPhotoCCD::UpdateExtendedOptions, this);
1612 }
1613
1614 void GPhotoCCD::HideExtendedOptions(void)
1615 {
1616 if (optTID)
1617 {
1618 IERmTimer(optTID);
1619 optTID = 0;
1620 }
1621
1622 std::vector<std::string> extendedPropertyNames;
1623
1624 while (CamOptions.begin() != CamOptions.end())
1625 {
1626 cam_opt * opt = (*CamOptions.begin()).second;
1627
1628 switch (opt->widget->type)
1629 {
1630 case GP_WIDGET_RADIO:
1631 case GP_WIDGET_MENU:
1632 case GP_WIDGET_TOGGLE:
1633 free(opt->item.sw);
1634 break;
1635 case GP_WIDGET_TEXT:
1636 case GP_WIDGET_DATE:
1637 free(opt->item.text.text);
1638 break;
1639 default:
1640 break;
1641 }
1642
1643 extendedPropertyNames.push_back((*CamOptions.begin()).first);
1644 delete opt;
1645 CamOptions.erase(CamOptions.begin());
1646 }
1647
1648 for (const auto &oneName : extendedPropertyNames)
1649 deleteProperty(oneName.c_str());
1650 }
1651
1652 #if 0
1653 IPState GPhotoCCD::MoveFocuser(FocusDirection dir, int speed, uint16_t duration)
1654 {
1655 if (isSimulation() || speed == 0)
1656 return IPS_OK;
1657
1658 // Set speed accordng to duration
1659 if (duration >= 1000)
1660 speed = 3;
1661 else if (duration >= 250)
1662 speed = 2;
1663 else
1664 speed = 1;
1665
1666 if (dir == FOCUS_INWARD)
1667 focusSpeed = speed * -1;
1668 else
1669 focusSpeed = speed;
1670
1671 LOGF_DEBUG("Setting focuser speed to %d", focusSpeed);
1672
1673 FocusTimerNP.s = IPS_BUSY;
1674 IDSetNumber(&FocusTimerNP, nullptr);
1675
1676 /*while (duration-->0)
1677 {
1678 if ( gphoto_manual_focus(gphotodrv, focusSpeed, errMsg) != GP_OK)
1679 {
1680 LOGF_ERROR("Focusing failed: %s", errMsg);
1681 return IPS_ALERT;
1682 }
1683 }*/
1684
1685 // If we have a view finder, let's turn it on
1686 if (Streamer->isBusy() == false)
1687 gphoto_set_view_finder(gphotodrv, true);
1688
1689 //SetTimer(FOCUS_TIMER);
1690
1691 char errMsg[MAXRBUF];
1692 if (gphoto_manual_focus(gphotodrv, focusSpeed, errMsg) != GP_OK)
1693 {
1694 LOGF_ERROR("Focusing failed: %s", errMsg);
1695 return IPS_ALERT;
1696 }
1697 else if (Streamer->isBusy() == false)
1698 gphoto_set_view_finder(gphotodrv, false);
1699
1700 FocusTimerN[0].value = 0;
1701 return IPS_OK;
1702 }
1703
1704 bool GPhotoCCD::SetFocuserSpeed(int speed)
1705 {
1706 if (speed >= FocusSpeedN[0].min && speed <= FocusSpeedN[0].max)
1707 return true;
1708
1709 return false;
1710 }
1711 #endif
1712
1713 IPState GPhotoCCD::MoveRelFocuser(FocusDirection dir, uint32_t ticks)
1714 {
1715 INDI_UNUSED(dir);
1716
1717 // Reduce by a factor of 10
1718 double adaptiveTicks = ticks / 10.0;
1719
1720 double largeStep = adaptiveTicks / (FOCUS_HIGH_MED_RATIO * FOCUS_MED_LOW_RATIO);
1721 double medStep = (largeStep - rint(largeStep)) * FOCUS_HIGH_MED_RATIO;
1722 double lowStep = (medStep - rint(medStep)) * FOCUS_MED_LOW_RATIO;
1723
1724 m_TargetLargeStep = rint(fabs(largeStep));
1725 m_TargetMedStep = rint(fabs(medStep));
1726 m_TargetLowStep = rint(fabs(lowStep));
1727
1728 if (m_FocusTimerID > 0)
1729 RemoveTimer(m_FocusTimerID);
1730
1731 m_FocusTimerID = IEAddTimer(FOCUS_TIMER, &GPhotoCCD::UpdateFocusMotionHelper, this);
1732
1733 return IPS_BUSY;
1734 }
1735
1736 void GPhotoCCD::UpdateFocusMotionHelper(void *context)
1737 {
1738 static_cast<GPhotoCCD*>(context)->UpdateFocusMotionCallback();
1739 }
1740
1741 void GPhotoCCD::UpdateFocusMotionCallback()
1742 {
1743 char errmsg[MAXRBUF] = {0};
1744 int focusSpeed = -1;
1745
1746 if (m_TargetLargeStep > 0)
1747 {
1748 m_TargetLargeStep--;
1749 focusSpeed = IUFindOnSwitchIndex(&FocusMotionSP) == FOCUS_INWARD ? -3 : 3;
1750 }
1751 else if (m_TargetMedStep > 0)
1752 {
1753 m_TargetMedStep--;
1754 focusSpeed = IUFindOnSwitchIndex(&FocusMotionSP) == FOCUS_INWARD ? -2 : 2;
1755 }
1756 else if (m_TargetLowStep > 0)
1757 {
1758 m_TargetLowStep--;
1759 focusSpeed = IUFindOnSwitchIndex(&FocusMotionSP) == FOCUS_INWARD ? -1 : 1;
1760 }
1761
1762 if (gphoto_manual_focus(gphotodrv, focusSpeed, errmsg) != GP_OK)
1763 {
1764 LOGF_ERROR("Focusing failed: %s", errmsg);
1765 FocusRelPosNP.s = IPS_ALERT;
1766 IDSetNumber(&FocusRelPosNP, nullptr);
1767 return;
1768 }
1769
1770 if (m_TargetLargeStep == 0 && m_TargetMedStep == 0 && m_TargetLowStep == 0)
1771 {
1772 FocusRelPosNP.s = IPS_OK;
1773 IDSetNumber(&FocusRelPosNP, nullptr);
1774 }
1775 else
1776 m_FocusTimerID = IEAddTimer(FOCUS_TIMER, &GPhotoCCD::UpdateFocusMotionHelper, this);
1777 }
1778
1779 bool GPhotoCCD::StartStreaming()
1780 {
1781 if (livePreviewSP.s == IPS_BUSY)
1782 {
1783 LOG_ERROR("Cannot start live video streaming while live preview is on.");
1784 return false;
1785 }
1786
1787 if (gphoto_start_preview(gphotodrv) == GP_OK)
1788 {
1789 Streamer->setPixelFormat(INDI_RGB);
1790 std::unique_lock<std::mutex> guard(liveStreamMutex);
1791 m_RunLiveStream = true;
1792 guard.unlock();
1793 liveViewThread = std::thread(&GPhotoCCD::streamLiveView, this);
1794 return true;
1795 }
1796
1797 return false;
1798
1799 }
1800
1801 bool GPhotoCCD::StopStreaming()
1802 {
1803 std::unique_lock<std::mutex> guard(liveStreamMutex);
1804 m_RunLiveStream = false;
1805 guard.unlock();
1806 liveViewThread.join();
1807 return (gphoto_stop_preview(gphotodrv) == GP_OK);
1808 }
1809
1810 void GPhotoCCD::streamLiveView()
1811 {
1812 //char errMsg[MAXRBUF];
1813 const char * previewData = nullptr;
1814 unsigned long int previewSize = 0;
1815 CameraFile * previewFile = nullptr;
1816
1817 int rc = gp_file_new(&previewFile);
1818 if (rc != GP_OK)
1819 {
1820 LOGF_ERROR("Error creating gphoto file: %s", gp_result_as_string(rc));
1821 return;
1822 }
1823
1824 char errMsg[MAXRBUF] = {0};
1825 while (true)
1826 {
1827 std::unique_lock<std::mutex> guard(liveStreamMutex);
1828 if (m_RunLiveStream == false)
1829 break;
1830 guard.unlock();
1831
1832 rc = gphoto_capture_preview(gphotodrv, previewFile, errMsg);
1833 if (rc != GP_OK)
1834 {
1835 //LOGF_DEBUG("%s", errMsg);
1836 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1837 continue;
1838 }
1839
1840 if (rc >= GP_OK)
1841 {
1842 rc = gp_file_get_data_and_size(previewFile, &previewData, &previewSize);
1843 if (rc != GP_OK)
1844 {
1845 LOGF_ERROR("Error getting preview image data and size: %s", gp_result_as_string(rc));
1846 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1847 continue;
1848 }
1849 }
1850
1851 uint8_t * inBuffer = reinterpret_cast<uint8_t *>(const_cast<char *>(previewData));
1852
1853 // if (streamSubframeS[1].s == ISS_ON)
1854 // {
1855 // if (liveVideoWidth <= 0)
1856 // {
1857 // read_jpeg_size(inBuffer, previewSize, &liveVideoWidth, &liveVideoHeight);
1858 // Streamer->setSize(liveVideoWidth, liveVideoHeight);
1859 // }
1860
1861 // std::unique_lock<std::mutex> ccdguard(ccdBufferLock);
1862 // Streamer->newFrame(inBuffer, previewSize);
1863 // ccdguard.unlock();
1864 // continue;
1865 // }
1866
1867 uint8_t * ccdBuffer = PrimaryCCD.getFrameBuffer();
1868 size_t size = 0;
1869 int w = 0, h = 0, naxis = 0;
1870
1871 // Read jpeg from memory
1872 std::unique_lock<std::mutex> ccdguard(ccdBufferLock);
1873 rc = read_jpeg_mem(inBuffer, previewSize, &ccdBuffer, &size, &naxis, &w, &h);
1874
1875 if (rc != 0)
1876 {
1877 LOG_ERROR("Error getting live video frame.");
1878 std::this_thread::sleep_for(std::chrono::milliseconds(100));
1879 continue;
1880 }
1881
1882 if (liveVideoWidth <= 0)
1883 {
1884 liveVideoWidth = w;
1885 liveVideoHeight = h;
1886 Streamer->setSize(liveVideoWidth, liveVideoHeight);
1887 }
1888
1889 PrimaryCCD.setFrameBuffer(ccdBuffer);
1890
1891 // We are done with writing to CCD buffer
1892 ccdguard.unlock();
1893
1894 if (naxis != PrimaryCCD.getNAxis())
1895 {
1896 if (naxis == 1)
1897 Streamer->setPixelFormat(INDI_MONO);
1898
1899 PrimaryCCD.setNAxis(naxis);
1900 }
1901
1902 if (PrimaryCCD.getSubW() != w || PrimaryCCD.getSubH() != h)
1903 {
1904 Streamer->setSize(w, h);
1905 PrimaryCCD.setBin(1, 1);
1906 PrimaryCCD.setFrame(0, 0, w, h);
1907 }
1908
1909 if (PrimaryCCD.getFrameBufferSize() != static_cast<int>(size))
1910 PrimaryCCD.setFrameBufferSize(size, false);
1911
1912 Streamer->newFrame(ccdBuffer, size);
1913 }
1914
1915 gp_file_unref(previewFile);
1916 }
1917
1918 #if 0
1919 bool GPhotoCCD::startLivePreview()
1920 {
1921 if (isSimulation())
1922 return false;
1923
1924 int rc = GP_OK;
1925 char errMsg[MAXRBUF];
1926 const char * previewData = nullptr;
1927 unsigned long int previewSize = 0;
1928
1929 CameraFile * previewFile = nullptr;
1930
1931 rc = gp_file_new(&previewFile);
1932 if (rc != GP_OK)
1933 {
1934 LOGF_ERROR("Error creating gphoto file: %s", gp_result_as_string(rc));
1935 return false;
1936 }
1937
1938 for (int i = 0; i < MAX_RETRIES; i++)
1939 {
1940 rc = gphoto_capture_preview(gphotodrv, previewFile, errMsg);
1941 if (rc == true)
1942 break;
1943 }
1944
1945 if (rc != GP_OK)
1946 {
1947 LOGF_ERROR("%s", errMsg);
1948 return false;
1949 }
1950
1951 if (rc >= GP_OK)
1952 {
1953 rc = gp_file_get_data_and_size(previewFile, &previewData, &previewSize);
1954 if (rc != GP_OK)
1955 {
1956 LOGF_ERROR("Error getting preview image data and size: %s", gp_result_as_string(rc));
1957 return false;
1958 }
1959 }
1960
1961 //LOGF_DEBUG("Preview capture size %d bytes.", previewSize);
1962
1963 char * previewBlob = (char *)previewData;
1964
1965 imageB->blob = previewBlob;
1966 imageB->bloblen = previewSize;
1967 imageB->size = previewSize;
1968 strncpy(imageB->format, "stream_jpeg", MAXINDIBLOBFMT);
1969
1970 IDSetBLOB(imageBP, nullptr);
1971
1972 if (previewFile)
1973 {
1974 gp_file_unref(previewFile);
1975 previewFile = nullptr;
1976 }
1977
1978 return true;
1979 }
1980 #endif
1981
1982 //bool GPhotoCCD::stopLiveVideo()
1983 //{
1984 // if (isSimulation())
1985 // return false;
1986
1987 // return (gphoto_stop_preview(gphotodrv) == GP_OK);
1988 //}
1989
1990 bool GPhotoCCD::saveConfigItems(FILE * fp)
1991 {
1992 // First save Device Port
1993 if (PortTP.tp[0].text)
1994 IUSaveConfigText(fp, &PortTP);
1995
1996 // Second save the CCD Info property
1997 IUSaveConfigNumber(fp, PrimaryCCD.getCCDInfo());
1998
1999 // Save regular CCD properties
2000 INDI::CCD::saveConfigItems(fp);
2001
2002 // Mirror Locking
2003 IUSaveConfigNumber(fp, &mMirrorLockNP);
2004
2005 // Capture Target
2006 if (captureTargetSP.s == IPS_OK)
2007 {
2008 IUSaveConfigSwitch(fp, &captureTargetSP);
2009 }
2010
2011 // SD Card delete?
2012 if (captureTargetSP.s == IPS_OK || strstr(getDeviceName(), "Fuji"))
2013 {
2014 IUSaveConfigSwitch(fp, &SDCardImageSP);
2015 }
2016
2017 // ISO Settings
2018 if (mIsoSP.nsp > 0)
2019 IUSaveConfigSwitch(fp, &mIsoSP);
2020
2021 // Force BULB Mode
2022 IUSaveConfigSwitch(fp, &forceBULBSP);
2023
2024 return true;
2025 }
2026
2027 void GPhotoCCD::addFITSKeywords(INDI::CCDChip * targetChip)
2028 {
2029 auto fptr = *targetChip->fitsFilePointer();
2030
2031 INDI::CCD::addFITSKeywords(targetChip);
2032
2033 int status = 0;
2034
2035 if (mIsoSP.nsp > 0)
2036 {
2037 ISwitch * onISO = IUFindOnSwitch(&mIsoSP);
2038 if (onISO)
2039 {
2040 int isoSpeed = atoi(onISO->label);
2041 if (isoSpeed > 0)
2042 fits_update_key_s(fptr, TUINT, "ISOSPEED", &isoSpeed, "ISO Speed", &status);
2043 }
2044 }
2045
2046 if (isTemperatureSupported)
2047 {
2048 fits_update_key_s(fptr, TDOUBLE, "CCD-TEMP", &(TemperatureN[0].value), "CCD Temperature (Celsius)", &status);
2049 }
2050 }
2051
2052 bool GPhotoCCD::UpdateCCDUploadMode(CCD_UPLOAD_MODE mode)
2053 {
2054 if (!isSimulation())
2055 gphoto_set_upload_settings(gphotodrv, mode);
2056
2057 // Reject changes to upload mode while we are ignoring the image download.
2058 if (SDCardImageS[SD_CARD_IGNORE_IMAGE].s == ISS_ON && mode != UPLOAD_LOCAL)
2059 return false;
2060
2061 return true;
2062 }
2063
2064 void GPhotoCCD::simulationTriggered(bool enabled)
2065 {
2066 if (enabled)
2067 defineProperty(&UploadFileTP);
2068 else
2069 deleteProperty(UploadFileTP.name);
2070 }
2071
2072 bool GPhotoCCD::SetCaptureFormat(uint8_t index)
2073 {
2074 INDI_UNUSED(index);
2075 // We need to get frame W and H if format changes
2076 frameInitialized = false;
2077 return true;
2078 }