-
Notifications
You must be signed in to change notification settings - Fork 184
/
Copy pathcapture_ZWO.cpp
1913 lines (1693 loc) · 66.3 KB
/
capture_ZWO.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include "include/ASICamera2.h"
#include <math.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <string>
#include <tr1/memory>
#include <stdlib.h>
#include <signal.h>
#include <fstream>
#include <stdarg.h>
#include <chrono>
#include "include/allsky_common.h"
// CG holds all configuration variables.
// There are only a few cases where it's not passed to a function.
// When it's passed, functions call it "cg", so use upper case for global version.
config CG;
#define CAMERA_TYPE "ZWO"
#define IS_ZWO
#include "ASI_functions.cpp"
// Forward definitions
char *getRetCode(ASI_ERROR_CODE);
void closeUp(int);
bool checkMaxErrors(int *, int);
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
// These are global so they can be used by other routines.
// Variables for command-line settings are first and are "long" so we can use validateLong().
timeval exposureStartDateTime; // date/time an image started
cv::Mat pRgb;
std::vector<int> compressionParameters;
bool bMain = true;
bool bDisplay = false;
std::string dayOrNight;
bool bSaveRun = false;
bool bSavingImg = false;
pthread_mutex_t mtxSaveImg;
pthread_cond_t condStartSave;
ASI_CONTROL_CAPS ControlCaps;
int numTotalErrors = 0; // Total number of errors, fyi
int numConsecutiveErrors = 0; // Number of consecutive errors
int maxErrors = 5; // Max number of errors in a row before we exit
bool gotSignal = false; // Did we get a signal?
int iNumOfCtrl = NOT_SET; // Number of camera control capabilities
pthread_t threadDisplay = 0;
pthread_t hthdSave = 0;
int numExposures = 0; // how many valid pictures have we taken so far?
int currentBpp = NOT_SET; // bytes per pixel: 1, 2, or 3
bool capturingVideo = false; // are we capturing video?
// Make sure we don't try to update a non-updateable control, and check for errors.
ASI_ERROR_CODE setControl(int camNum, ASI_CONTROL_TYPE control, long value, ASI_BOOL makeAuto)
{
ASI_ERROR_CODE ret = ASI_SUCCESS;
// The array of controls might contain 3 items, control IDs 1, 5, and 9.
// The 2nd argument to ASIGetControlCaps() is the INDEX into the controll array,
// NOT the control ID (e.g., 1, 5, or 9).
// Hence if we're looking for control ID 5 we can't do
// ASIGetControlCaps(camNum, 5, &ControlCaps) since there are only 3 elements in the array.
for (int i = 0; i < iNumOfCtrl && i <= control; i++) // controls are sorted 1 to n
{
ret = ASIGetControlCaps(camNum, i, &ControlCaps);
if (ret != ASI_SUCCESS)
{
Log(-1, "*** %s: WARNING: ASIGetControlCaps() for control %d failed: %s, camNum=%d, iNumOfCtrl=%d, control=%d\n",
CG.ME, i, getRetCode(ret), camNum, iNumOfCtrl, (int) control);
return(ret);
}
if (ControlCaps.ControlType == control)
{
if (ControlCaps.IsWritable)
{
if (value > ControlCaps.MaxValue)
{
Log(-1, "*** %s: WARNING: Value of %ld greater than max value allowed (%ld) for control '%s' (#%d).\n",
CG.ME, value, ControlCaps.MaxValue, ControlCaps.Name, ControlCaps.ControlType);
value = ControlCaps.MaxValue;
} else if (value < ControlCaps.MinValue)
{
Log(1, "*** %s: WARNING: Value of %ld less than min value allowed (%ld) for control '%s' (#%d).\n",
CG.ME, value, ControlCaps.MinValue, ControlCaps.Name, ControlCaps.ControlType);
value = ControlCaps.MinValue;
}
if (makeAuto == ASI_TRUE && ControlCaps.IsAutoSupported == ASI_FALSE)
{
Log(-1, "*** %s: WARNING: control '%s' (#%d) doesn't support auto mode.\n",
CG.ME, ControlCaps.Name, ControlCaps.ControlType);
makeAuto = ASI_FALSE;
}
ret = ASISetControlValue(camNum, control, value, makeAuto);
if (ret != ASI_SUCCESS)
{
Log(-1, "*** %s: WARNING: ASISetControlValue() for control %d, value=%ld, camNum=%d, makeAuto=%d failed: %s\n",
CG.ME, control, value, camNum, makeAuto, getRetCode(ret));
return(ret);
}
} else {
Log(0, "*** %s: ERROR: ControlCap: '%s' (#%d) not writable; not setting to %ld.\n",
CG.ME, ControlCaps.Name, ControlCaps.ControlType, value);
ret = ASI_ERROR_INVALID_MODE; // this seemed like the closest error
}
return ret;
}
}
Log(-2, "NOTICE: Camera does not support ControlCap # %d; not setting to %ld.\n", control, value);
return ASI_ERROR_INVALID_CONTROL_TYPE;
}
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
void *Display(void *params)
{
cv::Mat *pImg = (cv::Mat *)params;
int w = pImg->cols;
int h = pImg->rows;
cv::namedWindow("Preview", cv::WINDOW_AUTOSIZE);
cv::Mat Img2 = *pImg, *pImg2 = &Img2;
while (bDisplay)
{
// default preview size usually fills whole screen, so shrink.
cv::resize(*pImg, *pImg2, cv::Size((int)w/2, (int)h/2));
cv::imshow("Preview", *pImg2);
cv::waitKey(500);
}
cv::destroyWindow("Preview");
Log(4, "Display thread over\n");
return (void *)0;
}
void *SaveImgThd(void *para)
{
while (bSaveRun)
{
pthread_mutex_lock(&mtxSaveImg);
pthread_cond_wait(&condStartSave, &mtxSaveImg);
if (gotSignal)
{
// we got a signal to exit, so don't save the (probably incomplete) image
pthread_mutex_unlock(&mtxSaveImg);
break;
}
// I don't know how to cast "st" to 0, so call now() and ignore it.
auto st = std::chrono::high_resolution_clock::now();
auto et = st;
bool result = false;
if (pRgb.data)
{
bSavingImg = true;
char cmd[1100+strlen(CG.allskyHome)];
Log(4, " > Saving %s image '%s'\n",
CG.takeDarkFrames ? "dark" : dayOrNight.c_str(), CG.finalFileName);
snprintf(cmd, sizeof(cmd), "%s/scripts/saveImage.sh %s '%s'",
CG.allskyHome, dayOrNight.c_str(), CG.fullFilename);
add_variables_to_command(CG, cmd, exposureStartDateTime);
strcat(cmd, " &");
try
{
st = std::chrono::high_resolution_clock::now();
result = imwrite(CG.fullFilename, pRgb, compressionParameters);
et = std::chrono::high_resolution_clock::now();
}
catch (const cv::Exception& ex)
{
Log(0, "*** %s: ERROR: Exception saving image: %s\n", CG.ME, ex.what());
}
if (result)
{
system(cmd);
static int totalSaves = 0;
static double totalTime_ms = 0;
totalSaves++;
long long diff_us = std::chrono::duration_cast<std::chrono::microseconds>(et - st).count();
double diff_ms = diff_us / US_IN_MS;
totalTime_ms += diff_ms;
Log(4, " > Image took %'.1f ms to save (average %'.1f ms).\n",
diff_ms, totalTime_ms / totalSaves);
}
else
{
Log(0, "*** %s: ERROR: Unable to save image '%s'.\n", CG.ME, CG.fullFilename);
}
bSavingImg = false;
} else {
// This can happen if the program is closed before the first picture.
Log(0, "----- SaveImgThd(): pRgb.data is null\n");
}
pthread_mutex_unlock(&mtxSaveImg);
}
return (void *)0;
}
// As of July 2021, ZWO's SDK (version 1.9) has a bug where autoexposure daylight shots'
// exposures jump all over the place. One is way too dark and the next way too light, etc.
// As a workaround, our histogram code replaces ZWO's code auto-exposure mechanism.
// We look at the mean brightness of an X by X rectangle in image, and adjust exposure based on that.
// FIXME prevent this from misbehaving when unreasonable settings are given,
// eg. box size 0x0, box size WxW, box crosses image edge, ... basically
// anything that would read/write out-of-bounds
double computeHistogram(unsigned char *imageBuffer, config cg, bool useHistogramBox)
{
unsigned char *buf = imageBuffer;
const int histogramEntries = 256;
int histogram[histogramEntries];
// Clear the histogram array.
for (int i = 0; i < histogramEntries; i++) {
histogram[i] = 0;
}
// Different image types have a different number of bytes per pixel.
cg.width *= currentBpp;
int roiX1, roiX2, roiY1, roiY2;
if (useHistogramBox)
{
roiX1 = (cg.width * cg.HB.histogramBoxPercentFromLeft) - (cg.HB.currentHistogramBoxSizeX * currentBpp / 2);
roiX2 = roiX1 + (currentBpp * cg.HB.currentHistogramBoxSizeX);
roiY1 = (cg.height * cg.HB.histogramBoxPercentFromTop) - (cg.HB.currentHistogramBoxSizeY / 2);
roiY2 = roiY1 + cg.HB.currentHistogramBoxSizeY;
// Start off and end on a logical pixel boundries.
roiX1 = (roiX1 / currentBpp) * currentBpp;
roiX2 = (roiX2 / currentBpp) * currentBpp;
} else {
roiX1 = 0;
roiX2 = cg.width;
roiY1 = 0;
roiY2 = cg.height;
}
// For RGB24, data for each pixel is stored in 3 consecutive bytes: blue, green, red.
// For all image types, each row in the image contains one row of pixels.
// currentBpp doesn't apply to rows, just columns.
switch (cg.imageType) {
case IMG_RGB24:
case IMG_RAW8:
case IMG_Y8:
for (int y = roiY1; y < roiY2; y++) {
for (int x = roiX1; x < roiX2; x += currentBpp) {
int i = (cg.width * y) + x;
int avg = buf[i];
if (cg.imageType == IMG_RGB24) {
// For RGB24 this averages the blue, green, and red pixels.
// avg already contains the first color from above, so just add the other 2:
avg += buf[i+1] + buf[i+2];
avg /= currentBpp;
}
histogram[avg]++;
}
}
break;
case IMG_RAW16:
for (int y = roiY1; y < roiY2; y++) {
for (int x = roiX1; x < roiX2; x+=currentBpp) {
int i = (cg.width * y) + x;
int pixelValue;
// Use the least significant byte.
// This assumes the image data is laid out in big endian format.
pixelValue = buf[i+1];
histogram[pixelValue]++;
}
}
break;
case ASI_IMG_END:
break;
}
// Now calculate the mean.
int a = 0, b = 0;
for (int i = 0; i < histogramEntries; i++) {
a += (i+1) * histogram[i];
b += histogram[i];
}
if (b == 0)
{
// This is one heck of a dark picture!
return(0);
}
// Need to normalize from 0.0 to 1.0.
return ((a/b - 1) / (double)histogramEntries);
}
// This is based on code from PHD2.
// Camera has internal frame buffers we need to clear.
// The camera and/or driver will buffer frames and return the oldest one which
// could be very old. Read out all the buffered frames so the frame we get is current.
ASI_ERROR_CODE flushBufferedImages(config *cg, unsigned char *buf, long size)
{
enum { NUM_IMAGE_BUFFERS = 2 };
ASI_ERROR_CODE status;
status = setControl(cg->cameraNumber, ASI_EXPOSURE, cg->cameraMinExposure_us, ASI_FALSE);
if (status != ASI_SUCCESS)
{
Log(0, "*** %s: ERROR: flushBufferedImages() setControl() returned %s\n", cg->ME, getRetCode(status));
return(status);
}
for (int i = 0; i < NUM_IMAGE_BUFFERS; i++)
{
status = ASIGetVideoData(cg->cameraNumber, buf, size, 500 + (2 * cg->cameraMinExposure_us));
if (status == ASI_SUCCESS)
{
Log(3, " > [Cleared buffer frame]: %s\n", getRetCode(status));
}
else if (status == ASI_ERROR_TIMEOUT)
{
// No more frames left in buffer.
return(status);
}
else
{
Log(1, "%s: WARNING: flushBufferedImages() got %s\n", cg->ME, getRetCode(status));
}
}
return(status);
}
// In version 0.8 we introduced a different way to take exposures. Instead of turning video mode on at
// the beginning of the program and off at the end (which kept the camera running all the time, heating it up),
// version 0.8 turned video mode on, then took a picture, then turned it off. This helps cool the camera,
// but some users (seems hit or miss) get ASI_ERROR_TIMEOUTs when taking exposures with the new method.
// So, we added the ability for them to use the 0.7 video-always-on method, or the 0.8 "new exposure" method.
// In the 2024 version we added "snapshot" mode to overcome the ASI_ERROR_TIMEOUTs.
// Next exposure suggested by the camera.
long suggestedNextExposure_us = 0;
// "auto" flag returned by ASIGetControlValue(), when we don't care what it is.
ASI_BOOL bAuto = ASI_FALSE;
ASI_BOOL wasAutoExposure = ASI_FALSE;
long bufferSize = NOT_SET;
ASI_ERROR_CODE takeOneExposure(config *cg, unsigned char *imageBuffer)
{
if (imageBuffer == NULL) {
return (ASI_ERROR_CODE) -1;
}
ASI_ERROR_CODE status, ret;
// ZWO recommends timeout = (exposure*2) + 500 ms
// After some discussion, we're doing +5000ms to account for delays induced by
// USB contention, such as that caused by heavy USB disk IO
long timeout = ((cg->currentExposure_us * 2) / US_IN_MS) + 5000; // timeout is in ms
// Sanity check.
if (cg->HB.useHistogram && cg->currentAutoExposure)
Log(0, " > %s: ERROR: HB.useHistogram AND currentAutoExposure are both set\n", cg->ME);
if (cg->ZWOexposureType != ZWOsnap)
flushBufferedImages(cg, imageBuffer, bufferSize);
setControl(cg->cameraNumber, ASI_EXPOSURE, cg->currentExposure_us, cg->currentAutoExposure ? ASI_TRUE : ASI_FALSE);
if (cg->ZWOexposureType == ZWOvideoOff && ! capturingVideo)
{
status = ASIStartVideoCapture(cg->cameraNumber);
if (status != ASI_SUCCESS) {
Log(0, " > %s: ERROR: ASIStartVideoCapture() failed: %s.\n", cg->ME, getRetCode(status));
Log(1, " > Total errors=%'d\n", numTotalErrors+1);
return(status);
}
capturingVideo = true;
}
// Make sure the actual time to take the picture is "close" to the requested time.
auto tStart = std::chrono::high_resolution_clock::now();
int exitCode;
if (cg->ZWOexposureType == ZWOsnap)
{
status = ASIStartExposure(cg->cameraNumber, ASI_FALSE);
if (status != ASI_SUCCESS)
{
Log(0, " > %s: ERROR: ASIStartExposure() failed: %s.\n", cg->ME, getRetCode(status));
Log(1, " > Total errors=%'d\n", numTotalErrors+1);
if (! checkMaxErrors(&exitCode, maxErrors))
closeUp(exitCode);
return(status);
}
// Do an initial sleep of the exposure time + 500 ms for overhead,
// then go into a check_status / sleep loop where
// we sleep for 5% of the exposure time.
// The total sleep time will be longer than exposure time due to overhead starting the exposure.
long initial_sleep_us = cg->currentExposure_us + 500 * US_IN_MS;
long sleep_us = std::max(cg->currentExposure_us * 0.05, 1.0);
Log(4, " > Doing initial usleep(%'ld) for exposure time %'ld.\n", initial_sleep_us, cg->currentExposure_us);
usleep(initial_sleep_us);
// We should be fairly close to the end of the exposure so now go
// into a loop until the exposure is done.
ASI_EXPOSURE_STATUS s = ASI_EXP_WORKING;
int num_sleeps = 0;
while (s == ASI_EXP_WORKING)
{
status = ASIGetExpStatus(cg->cameraNumber, &s);
if (status != ASI_SUCCESS)
{
Log(0, " > %s: ERROR: ASIGetExpStatus() failed after %d sleeps: %s.\n",
cg->ME, num_sleeps, getRetCode(status));
Log(1, " > Total errors=%'d\n", numTotalErrors+1);
if (! checkMaxErrors(&exitCode, maxErrors))
closeUp(exitCode);
return(status);
}
usleep(sleep_us);
num_sleeps++;
}
Log(4, " > Did usleep(%'ld) %d times in loop for total usleep() of %'ldus\n",
sleep_us, num_sleeps, initial_sleep_us + (sleep_us * num_sleeps));
// Exposure done, if it worked get the image
if (s != ASI_EXP_SUCCESS)
{
// This error DOES happen sometimes.
// Unfortunately "s" is either success or failure - not much help.
Log(1, " > ERROR: Exposure failed after %d sleeps, s=%d.\n", num_sleeps, s);
Log(1, " > Total errors=%'d\n", numTotalErrors+1);
if (! checkMaxErrors(&exitCode, maxErrors))
closeUp(exitCode);
return(ASI_ERROR_END);
}
status = ASIGetDataAfterExp(cg->cameraNumber, imageBuffer, bufferSize);
if (status != ASI_SUCCESS)
{
// For whatever reason this does fail sometimes, so to avoid having
// every failure appear in the WebUI message center, log with level 1.
Log(1, " > ERROR: ASIGetDataAfterExp() failed after %d sleeps: %s.\n",
num_sleeps, getRetCode(status));
Log(1, " > Total errors=%'d\n", numTotalErrors+1);
if (! checkMaxErrors(&exitCode, maxErrors))
closeUp(exitCode);
return(status);
}
} else { // some video mode
status = ASIGetVideoData(cg->cameraNumber, imageBuffer, bufferSize, timeout);
if (status != ASI_SUCCESS)
{
Log(0, " > %s: ERROR: Failed getting image: %s.\n",
cg->ME, getRetCode(status));
Log(1, " > Total errors=%'d\n", numTotalErrors+1);
// Check if we reached the maximum number of consective errors
if (! checkMaxErrors(&exitCode, maxErrors))
closeUp(exitCode);
return(status);
}
if (cg->ZWOexposureType == ZWOvideoOff)
{
ret = ASIStopVideoCapture(cg->cameraNumber);
if (ret != ASI_SUCCESS)
{
Log(1, " > WARNING: ASIStopVideoCapture() failed: %s\n", getRetCode(ret));
// continue
}
capturingVideo = false;
}
}
// We successfully got the image so reset the global error counter;
numConsecutiveErrors = 0;
// The timeToTakeImage_us should never be less than what was requested.
// and shouldn't be less then the time taken plus overhead of setting up the shot.
auto tElapsed = std::chrono::high_resolution_clock::now() - tStart;
long timeToTakeImage_us = std::chrono::duration_cast<std::chrono::microseconds>(tElapsed).count();
long diff_us = timeToTakeImage_us - cg->currentExposure_us;
long threshold_us = 0;
bool tooShort = false;
if (diff_us < 0)
{
// This "should" never happen but actually does sometimes.
tooShort = true;
}
else if (cg->currentExposure_us > (5 * US_IN_SEC))
{
// There is too much variance in the overhead of taking pictures to
// accurately determine the actual time to take an image at short exposures,
// so only check for long ones.
// Testing shows there's about this much us overhead (at least for video mode),
// so subtract it to get our best estimate of the "actual" time.
const int OVERHEAD_us = (int) (340 * US_IN_MS);
// Don't subtract if it would have made timeToTakeImage_us negative.
if (timeToTakeImage_us > OVERHEAD_us)
diff_us -= OVERHEAD_us;
float t;
// These seem like good numbers.
// snapshot mode seems more consistent so use a lower threshold.
if (cg->ZWOexposureType == ZWOsnap)
t = 0.2;
else
t = 0.5;
threshold_us = cg->currentExposure_us * t;
if (abs(diff_us) > threshold_us)
tooShort = true;
}
if (tooShort)
{
Log(1, " *** WARNING: Time to take exposure (%s) ",
length_in_units(timeToTakeImage_us, true));
Log(1, "differs from requested exposure time (%s) by %s, threshold=%s\n",
length_in_units(cg->currentExposure_us, true),
length_in_units(diff_us, true),
length_in_units(threshold_us, true));
}
else
{
Log(4, " > Time to take exposure=%'ld us, diff_us=%'ld", timeToTakeImage_us, diff_us);
if (threshold_us > 0)
Log(4, ", threshold_us=%'ld", threshold_us);
Log(4, "\n");
}
// Get some metadata on the image.
long l;
ret = ASIGetControlValue(cg->cameraNumber, ASI_GAIN, &l, &bAuto);
if (ret != ASI_SUCCESS)
{
Log(1, " > %s: WARNING: ASIGetControlValue(ASI_GAIN) failed: %s\n", cg->ME, getRetCode(ret));
}
else
{
cg->lastGain = (double) l;
}
char tempBuf[500] = { 0 };
char *tb = tempBuf;
cg->lastMean = computeHistogram(imageBuffer, *cg, true);
sprintf(tb, " @ mean %.3f, %sgain %ld",
cg->lastMean, cg->currentAutoGain ? "(auto) " : "", (long) cg->lastGain);
cg->lastExposure_us = cg->currentExposure_us;
// Per ZWO, when in manual-exposure mode, the returned exposure length
// should always be equal to the requested length;
// they said, "there's no need to call ASIGetControlValue()".
// When in auto-exposure mode the returned exposure length is what the driver thinks the
// next exposure should be, and will eventually converge on the correct exposure.
Log(2, " > GOT IMAGE%s.", tb);
ret = ASIGetControlValue(cg->cameraNumber, ASI_EXPOSURE, &suggestedNextExposure_us, &wasAutoExposure);
if (ret != ASI_SUCCESS)
{
Log(1, " > WARNING: ASIGetControlValue(ASI_EXPOSURE) failed: %s\n",
cg->ME, getRetCode(ret));
}
else if (cg->ZWOexposureType != ZWOsnap)
{
Log(3, cg->HB.useHistogram ? " Ignoring suggested next exposure of %s." : " Suggested next exposure: %s.",
length_in_units(suggestedNextExposure_us, true));
}
Log(2, "\n");
long temp;
ret = ASIGetControlValue(cg->cameraNumber, ASI_TEMPERATURE, &temp, &bAuto);
if (ret != ASI_SUCCESS)
{
Log(1, " > %s: WARNING: ASIGetControlValue(ASI_TEMPERATURE) failed: %s\n",
cg->ME, getRetCode(ret));
}
else
{
cg->lastSensorTemp = (long) ((double)temp / cg->divideTemperatureBy);
}
if (cg->isColorCamera)
{
ret = ASIGetControlValue(cg->cameraNumber, ASI_WB_R, &l, &bAuto);
if (ret != ASI_SUCCESS)
{
Log(1, " > %s: WARNING: ASIGetControlValue(ASI_WB_R) failed: %s\n",
cg->ME, getRetCode(ret));
}
else
{
cg->lastWBR = (double) l;
}
ret = ASIGetControlValue(cg->cameraNumber, ASI_WB_B, &l, &bAuto);
if (ret != ASI_SUCCESS)
{
Log(1, " > %s: WARNING: ASIGetControlValue(ASI_WB_B) failed: %s\n",
cg->ME, getRetCode(ret));
}
else
{
cg->lastWBB = (double) l;
}
}
if (cg->asiAutoBandwidth)
{
ret = ASIGetControlValue(cg->cameraNumber, ASI_BANDWIDTHOVERLOAD, &cg->lastAsiBandwidth, &wasAutoExposure);
if (ret != ASI_SUCCESS)
{
Log(1, " > %s: WARNING: ASIGetControlValue(ASI_BANDWIDTHOVERLOAD) failed: %s\n", cg->ME, getRetCode(ret));
}
}
return ASI_SUCCESS;
}
bool adjustGain = false; // Should we adjust the gain? Set by user on command line.
bool currentAdjustGain = false; // Adjusting it right now?
int totalAdjustGain = 0; // The total amount to adjust gain.
int perImageAdjustGain = 0; // Amount of gain to adjust each image
int gainTransitionImages = 0;
int numGainChanges = 0; // This is reset at every day/night and night/day transition.
// Reset the gain transition variables for the first transition image.
// This is called when the program first starts and at the beginning of every day/night transition.
// "dayOrNight" is the new value, e.g., if we just transitioned from day to night, it's "NIGHT".
bool resetGainTransitionVariables(config cg)
{
if (adjustGain == false)
{
// determineGainChange() will never be called so no need to set any variables.
return(false);
}
if (numExposures == 0)
{
// we don't adjust when the program first starts since there's nothing to transition from
return(false);
}
// Determine the amount to adjust gain per image.
// Do this once per day/night or night/day transition (i.e., numGainChanges == 0).
// First determine how long an exposure and delay is, in seconds.
// The transition period is in seconds, the max exposures and delays are in milliseconds,
// so convert to seconds to compare to transition period.
float totalTimeInSec;
totalTimeInSec = ((float) cg.currentMaxAutoExposure_us / US_IN_SEC) +
((float) cg.currentDelay_ms / MS_IN_SEC);
/* xxxx remove after we know new gain algorithm works
if (dayOrNight == "DAY")
{
totalTimeInSec = (cg.dayExposure_us / US_IN_SEC) + (cg.dayDelay_ms / MS_IN_SEC);
}
else // NIGHT
{
// At nightime if the exposure is less than the max, we wait until max has expired,
// so use it instead of the exposure time.
totalTimeInSec = (cg.nightMaxAutoExposure_us / US_IN_SEC) + (cg.nightDelay_ms / MS_IN_SEC);
}
*/
gainTransitionImages = ceil(cg.gainTransitionTime / totalTimeInSec);
Log(4, " gainTransitionImages=%d, gainTransitionTime=%d, totalTimeInSec=%f\n",
gainTransitionImages, cg.gainTransitionTime, totalTimeInSec);
if (gainTransitionImages == 0)
{
Log(-1, "*** INFORMATION: Not adjusting gain - your 'Gain Transition Time' (%d seconds) is less than the time to take one image plus its delay (%.1f seconds).\n", cg.gainTransitionTime, totalTimeInSec);
return(false);
}
totalAdjustGain = cg.nightGain - cg.dayGain;
perImageAdjustGain = ceil((float) totalAdjustGain / gainTransitionImages); // spread evenly
if (perImageAdjustGain == 0)
perImageAdjustGain = totalAdjustGain;
else
{
// Since we can't adust gain by fractions,
// see if there's any "left over" after gainTransitionImages.
// For example, if totalAdjustGain is 7 and we're adjusting by 3 each of 2 times,
// we need an extra transition to get the remaining 1 ((7 - (3 * 2)) == 1).
if (gainTransitionImages * perImageAdjustGain < totalAdjustGain)
gainTransitionImages++; // this one will get the remaining amount
}
Log(4, " totalAdjustGain=%d, gainTransitionImages=%d, perImageAdjustGain=%d\n",
totalAdjustGain, gainTransitionImages, perImageAdjustGain);
return(true);
}
// Determine the change in gain needed for smooth transitions between night and day.
// Gain during the day is usually 0 and at night is usually > 0.
// If auto-exposure is on for both, the first several night frames may be too bright at night
// because of the sudden (often large) increase in gain, or too dark at the night-to-day
// transition.
// Try to mitigate that by changing the gain over several images at each transition.
int determineGainChange(config cg)
{
if (numGainChanges > gainTransitionImages || totalAdjustGain == 0)
{
// no more changes needed in this transition
Log(4, " No more gain changes needed.\n");
currentAdjustGain = false;
return(0);
}
numGainChanges++;
int amt; // amount to adjust gain on next picture
if (dayOrNight == "DAY")
{
// When DAY begins the last image was at nightGain but the first day
// image (ignoring transition) is dayGain so we want to go down
// from nightGain to dayGain.
// Increase the first image's gain by perImageAdjustGain - totalAdjustGain (which
// will be a big positive number), then increase the next image less,
// and so on until we get to dayGain.
// This assumes night gain is > day gain.
//x Log(4, ">> DAY: amt=%d, perImageAdjustGain=%d, numGainChanges=%d\n", amt, perImageAdjustGain, numGainChanges);
amt = totalAdjustGain - (perImageAdjustGain * numGainChanges);
if (amt < 0)
{
amt = 0;
totalAdjustGain = 0; // we're done making changes
}
}
else // NIGHT
{
// When NIGHT begins the last image was at dayGain but the first night
// image (ignoring transition) is nightGain so we want to go up
// from dayGain to nightGain.
// Decrease the first image's gain by perImageAdjustGain - totalAdjustGain (which
// will be a big negative number), then decrease the next image less,
// and so on until we get to nightGain.
amt = (perImageAdjustGain * numGainChanges) - totalAdjustGain;
if (amt > 0)
{
amt = 0;
totalAdjustGain = 0; // we're done making changes
}
}
Log(4, "Adjusting %s gain on next image by %d to %d (currentGain=%d); will be gain change # %d of %d.\n",
dayOrNight.c_str(), amt, amt+(int)cg.currentGain,
(int) cg.currentGain, numGainChanges, gainTransitionImages);
return(amt);
}
// Check if the maximum number of consecutive errors has been reached
bool checkMaxErrors(int *e, int maxErrors)
{
// Once takeOneExposure() fails with a timeout, it seems to always fail,
// even with extremely large timeout values, so apparently ASI_ERROR_TIMEOUT doesn't
// necessarily mean it's timing out. Exit forcing us to be restarted.
numTotalErrors++;
numConsecutiveErrors++; sleep(2);
if (numConsecutiveErrors >= maxErrors)
{
*e = EXIT_RESET_USB; // exit code. Need to reset USB bus
Log(0, "*** %s: ERROR: Maximum number of consecutive errors of %d reached; capture program exited.\n",
CG.ME, maxErrors);
Log(1, " > Total errors=%'d\n", numTotalErrors+1);
return(false); // gets us out of inner and outer loop
}
return(true);
}
//-------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
CG.ME = basename(argv[0]);
CG.allskyHome = getenv("ALLSKY_HOME");
if (CG.allskyHome == NULL)
{
Log(0, "*** %s: ERROR: ALLSKY_HOME not set!\n", CG.ME);
exit(EXIT_ERROR_STOP);
}
if (! getCommandLineArguments(&CG, argc, argv, false))
{
// getCommandLineArguments outputs an error message.
exit(EXIT_ERROR_STOP);
}
pthread_mutex_init(&mtxSaveImg, 0);
pthread_cond_init(&condStartSave, 0);
char bufTime[128] = { 0 };
char bufTemp[1024] = { 0 };
char const *bayer[] = { "RG", "BG", "GR", "GB" };
bool justTransitioned = false;
ASI_ERROR_CODE asiRetCode; // used for return code from ASI functions.
// Some settings have both day and night versions, some have only one version that applies to both,
// and some have either a day OR night version but not both.
// For settings with both versions we keep a "current" variable (e.g., "currentBin") that's either the day
// or night version so the code doesn't always have to check if it's day or night.
// The settings have either "day" or "night" in the name.
// In theory, almost every setting could have both day and night versions (e.g., width & height),
// but the chances of someone wanting different versions.
int maxHistogramAttempts = 15; // max number of times we'll try for a better histogram mean
// If we just transitioned from night to day, it's possible currentExposure_us will
// be MUCH greater than the daytime max (and will possibly be at the nighttime's max exposure).
// So, decrease currentExposure_us by a certain amount of the difference between the two so
// it takes several frames to reach the daytime max (which is now in currentMaxAutoExposure_us).
// If we don't do this, we'll be stuck in a loop taking an exposure
// that's over the max forever.
// Note that it's likely getting lighter outside with every exposure
// so the mean will eventually get into the valid range.
const int percentChange = 10.0; // percent of ORIGINAL difference
//---------------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------------
setlinebuf(stdout); // Line buffer output so entries appear in the log immediately.
CG.ct = ctZWO;
processConnectedCameras(); // exits on error. Sets CG.cameraNumber.
asiRetCode = ASIOpenCamera(CG.cameraNumber);
if (asiRetCode != ASI_SUCCESS)
{
Log(0, "*** %s: ERROR: opening camera, check that you have root permissions! (%s)\n",
CG.ME, getRetCode(asiRetCode));
closeUp(EXIT_NO_CAMERA);
}
ASI_CAMERA_INFO ASICameraInfo;
asiRetCode = ASIGetCameraProperty(&ASICameraInfo, CG.cameraNumber);
if (asiRetCode != ASI_SUCCESS)
{
Log(0, "*** %s: ERROR: ASIGetCamerProperty() returned: %s\n", CG.ME, getRetCode(asiRetCode));
exit(EXIT_ERROR_STOP);
}
asiRetCode = ASIGetNumOfControls(CG.cameraNumber, &iNumOfCtrl);
if (asiRetCode != ASI_SUCCESS)
{
Log(0, "*** %s: ERROR: ASIGetNumOfControls() returned: %s\n", CG.ME, getRetCode(asiRetCode));
exit(EXIT_ERROR_STOP);
}
CG.ASIversion = ASIGetSDKVersion();
// Set defaults that depend on the camera type.
if (! setDefaults(&CG, ASICameraInfo))
closeUp(EXIT_ERROR_STOP);
if (CG.configFile[0] != '\0' && ! getConfigFileArguments(&CG))
{
// getConfigFileArguments() outputs error messages
exit(EXIT_ERROR_STOP);
}
if (! CG.saveCC && ! CG.help)
{
displayHeader(CG);
}
doLocale(&CG);
if (CG.help)
{
displayHelp(CG);
closeUp(EXIT_OK);
}
// Do argument error checking if we're not going to exit soon.
if (! CG.saveCC && ! validateSettings(&CG, ASICameraInfo))
closeUp(EXIT_ERROR_STOP);
if (! checkForValidExtension(&CG)) {
// checkForValidExtension() displayed the error message.
closeUp(EXIT_ERROR_STOP);
}
int iMaxWidth, iMaxHeight;
double pixelSize;
iMaxWidth = ASICameraInfo.MaxWidth;
iMaxHeight = ASICameraInfo.MaxHeight;
pixelSize = ASICameraInfo.PixelSize;
if (CG.width == 0 || CG.height == 0)
{
CG.width = iMaxWidth;
CG.height = iMaxHeight;
}
else
{
validateLong(&CG.width, 0, iMaxWidth, "Width", true);
validateLong(&CG.height, 0, iMaxHeight, "Height", true);
}
long originalWidth = CG.width;
long originalHeight = CG.height;
// Limit these to a reasonable value based on the size of the sensor.
validateLong(&CG.overlay.iTextLineHeight, 0, (long)(iMaxHeight / 2), "Line Height", true);
validateLong(&CG.overlay.iTextX, 0, (long)iMaxWidth - 10, "Text X", true);
validateLong(&CG.overlay.iTextY, 0, (long)iMaxHeight - 10, "Text Y", true);
validateFloat(&CG.overlay.fontsize, 0.1, iMaxHeight / 2, "Font Size", true);
validateLong(&CG.overlay.linewidth, 0, (long)(iMaxWidth / 2), "Font Weight", true);
if (CG.saveCC)
{
saveCameraInfo(ASICameraInfo, CG.CC_saveFile, iMaxWidth, iMaxHeight, pixelSize, bayer[ASICameraInfo.BayerPattern]);
closeUp(EXIT_OK);
}
outputCameraInfo(ASICameraInfo, CG, iMaxWidth, iMaxHeight, pixelSize, bayer[ASICameraInfo.BayerPattern]);
// checkExposureValues() must come after outputCameraInfo().
(void) checkExposureValues(&CG);
// The histogram box needs to fit on the image.
// If we're binning we'll decrease the size of the box accordingly.
bool ok = true;
if (CG.HB.sArgs[0] != '\0')
{
if (sscanf(CG.HB.sArgs, "%d %d %f %f", &CG.HB.histogramBoxSizeX, &CG.HB.histogramBoxSizeY, &CG.HB.histogramBoxPercentFromLeft, &CG.HB.histogramBoxPercentFromTop) != 4)
{
Log(0, "*** %s: ERROR: Not enough histogram box parameters should be 4: '%s'\n", CG.ME, CG.HB.sArgs);
ok = false;
} else {
if (CG.HB.histogramBoxSizeX < 1 || CG.HB.histogramBoxSizeY < 1)
{
Log(0, "*** %s: ERROR: Histogram box size must be > 0; you entered X=%d, Y=%d\n",
CG.ME, CG.HB.histogramBoxSizeX, CG.HB.histogramBoxSizeY);
ok = false;
}
if (CG.HB.histogramBoxPercentFromLeft < 0.0 || CG.HB.histogramBoxPercentFromTop < 0.0)
{
Log(0, "*** %s: ERROR: Histogram box percents must be > 0; you entered X=%.0f%%, Y=%.0f%%\n",
CG.ME, (CG.HB.histogramBoxPercentFromLeft*100.0), (CG.HB.histogramBoxPercentFromTop*100.0));
ok = false;
}
else
{
// scale user-input 0-100 to 0.0-1.0
CG.HB.histogramBoxPercentFromLeft /= 100;
CG.HB.histogramBoxPercentFromTop /= 100;
// Now check if the box fits the image.
CG.HB.centerX = CG.width * CG.HB.histogramBoxPercentFromLeft;
CG.HB.centerY = CG.height * CG.HB.histogramBoxPercentFromTop;
CG.HB.leftOfBox = CG.HB.centerX - (CG.HB.histogramBoxSizeX / 2);
CG.HB.rightOfBox = CG.HB.centerX + (CG.HB.histogramBoxSizeX / 2);
CG.HB.topOfBox = CG.HB.centerY - (CG.HB.histogramBoxSizeY / 2);
CG.HB.bottomOfBox = CG.HB.centerY + (CG.HB.histogramBoxSizeY / 2);
if (CG.HB.leftOfBox < 0 || CG.HB.rightOfBox >= CG.width ||
CG.HB.topOfBox < 0 || CG.HB.bottomOfBox >= CG.height)
{
Log(0, "*** %s: ERROR: Histogram box location must fit on image; upper left of box is %dx%d, lower right %dx%d%s\n",
CG.ME, CG.HB.leftOfBox, CG.HB.topOfBox, CG.HB.rightOfBox, CG.HB.bottomOfBox);
ok = false;
} // else everything is hunky dory
}
}
} else {
Log(0, "*** %s: ERROR: No values specified for histogram box.\n", CG.ME);
ok = false;
}
if (! ok)