-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathskysolve.py
More file actions
executable file
·1481 lines (1199 loc) · 46.5 KB
/
skysolve.py
File metadata and controls
executable file
·1481 lines (1199 loc) · 46.5 KB
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
from subprocess import call
from zipfile import ZipFile
from attr import get_run_validators
from flask import Flask, render_template, request, Response, send_file, send_from_directory
import time
from flask.wrappers import Request
import pprint
import copy
from camera_pi import skyCamera
from datetime import datetime, timedelta
import threading
import numpy as np
from PIL import Image, ImageDraw, ImageFont
import subprocess
import os
import math
import json
from shutil import copyfile
from enum import Enum, auto
import io
import getpass
import copy
import sys
from tetra3 import Tetra3
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
import glob
import matplotlib.pyplot as plt
from scipy import stats
import logging
debugLastState = 'startup'
solveReadyForImage = False
solveImage = None
GUIReadyForImage = False
GUIImage = None
print("argssss", sys.argv, len(sys.argv))
print('user', getpass.getuser())
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7, GPIO.IN, pull_up_down=GPIO.PUD_UP)
initGPIO7 = GPIO.input(7)
print("gpio", initGPIO7)
try:
os.system('systemctl restart encodertoSkySafari.service ')
except BaseException as e:
print("did not start encoder", e )
usedIndexes = {}
# Create instance and load default_database (built with max_fov=12 and the rest as default)
t3 = None
if t3 == None:
t3 = Tetra3('default_database')
class Mode(Enum):
PAUSED = auto()
ALIGN = auto()
SOLVING = auto()
PLAYBACK = auto()
SOLVETHIS = auto()
# playback and sovlve history images without user clicking on each.
AUTOPLAYBACK = auto()
class LimitedLengthList(list):
def __init__(self, seq=(), length=math.inf):
self.length = length
if len(seq) > length:
raise ValueError("Argument seq has too many items")
super(LimitedLengthList, self).__init__(seq)
def append(self, item):
if len(self) < self.length:
super(LimitedLengthList, self).append(item)
else:
super(LimitedLengthList, self).__init__(
super(LimitedLengthList, self)[self.length/2:])
super(LimitedLengthList, self).append(item)
app = 30
solving = False
maxTime = 50
searchEnable = False
searchRadius = 90
solveLog = LimitedLengthList(length=1000)
ra = 0
dec = 0
solveStatus = ''
computedPPa = ''
focusStd = ''
state = Mode.ALIGN
testNdx = 0
lastDisplayedFile = ''
testFiles = []
root_path = os.getcwd()
if len(sys.argv) == 2:
root_path = sys.argv[1]
solve_path = os.path.join(root_path, 'static')
history_path = os.path.join(solve_path, 'history')
doDebug = True
logging.basicConfig(filename=os.path.join(solve_path,'skysolve.log'),\
format='%(levelname)s %(asctime)s %(message)s',filemode='w',level=logging.WARNING)
if not os.path.exists(history_path):
os.mkdir(history_path)
demo_path = os.path.join(solve_path, 'demo')
test_path = '/home/pi/pyPlateSolve/data'
solveThisImage = ''
solveCurrent = False
triggerSolutionDisplay = False
saveObs = False
obsList = []
ndx = 0
lastObs = ""
cameraNotPresent = True
"""
skyConfig = {'camera': {'shutter': 1, 'ISO':800, 'frame': '800x600','format': 'jpeg'},
'solver':{'currentProfile': 'default', 'startupSolving': False},
'observing':{'saveImages': False, 'showSolution': False, 'savePosition': True , 'obsDelta': .1},
'solverProfiles' :{\
'default': {'name': 'default', 'maxTime': 20, 'solveSigma':5, 'solveDepth':20, 'UselastDelta':False, 'FieldWidthMode':'FieldWidthModeField',
'FieldWidthModeaPP': 'checked', 'FieldWidthModeField':"", 'FieldWidthModeOther':'', 'aPPLoValue': 27, 'aPPHiValue': 30,
'fieldLoValue': 14, 'fieldHiValue': 0, 'searchRadius': 10, 'solveVerbose':False , "showStars": True ,"plots":True},
'25FL' : {'name': '25FL', 'maxTime': 20, 'solveSigma':9, 'solveDepth':20, 'UselastDelta':False, 'FieldWidthMode':'FieldWidthModeField',
'FieldWidthModeaPP': 'checked', 'FieldWidthModeField':"", 'FieldWidthModeOther':'', 'aPPLoValue': 27, 'aPPHiValue': 0,
'fieldLoValue': 14, 'fieldHiValue': 0, 'searchRadius': 10, 'solveVerbose':False , "showStars": False ,"plots":False},
'50FL': {'name':'50FL','maxTime': 20, 'solveSigma':9, 'solveDepth':20, 'UselastDelta':False, 'FieldWidthMode':'FieldWidthModeField',
'FieldWidthModeaPP': 'checked', 'FieldWidthModeField':"", 'FieldWidthModeOther':'', 'aPPLoValue': 40, 'aPPHiValue': 0,
'fieldLoValue': 22, 'fieldHiValue': 0, 'searchRadius': 10, 'solveVerbose':False , "showStars": False ,"plots":False}}}
"""
import builtins
class ListStream:
def write(self, s):
global doDebug
if doDebug:
logging.warning(s)
def flush(self):
pass
def saveConfig():
with open('skyConfig.json', 'w') as f:
json.dump(skyConfig, f, indent=4)
# saveConfig()
print('cwd', os.getcwd())
with open(os.path.join(root_path, 'skyConfig.json')) as f:
skyConfig = json.load(f)
print(json.dumps(skyConfig['solverProfiles']['25FL'], indent=4))
print(json.dumps(skyConfig['observing'], indent=4))
print(json.dumps(skyConfig['camera'], indent=4) )
imageName = 'cap.'+skyConfig['camera']['format']
#print (skyConfig)
skyCam = None
skyStatusText = ''
verboseSolveText = ''
def delayedStatus(delay, status):
global skyStatusText
time.sleep(delay)
skyStatusText = status
def setupCamera():
global skyCam, cameraNotPresent, state, skyStatusText
if not skyCam:
print('creating cam')
try:
skyCam = skyCamera(delayedStatus, shutter=int(
1000000 * float(skyConfig['camera']['shutter'])),
format=skyConfig['camera']['format'],
resolution=skyConfig['camera']['frame'])
cameraNotPresent = False
if skyConfig['solver']['startupSolveing']:
print("startup in solving")
state = Mode.SOLVING
startFrame = skyCam.get_frame()
if startFrame is None:
print("camera did not seem to start")
print("camera started and frame received",
cameraNotPresent )
except Exception as e:
print(e)
cameraNotPresent = True
skyStatusText = 'camera not connected or enabled. Demo mode and replay mode will still work however.'
def frameGrabberThread():
global solveReadyForImage, GUIReadyForImage, solveImage, GUIImage
while(True):
frame = skyCam.get_frame()
if solveReadyForImage:
print('getting solve image')
solveImage = copy.deepcopy(frame)
solveReadyForImage = False
if GUIReadyForImage:
print('getting gui image')
GUIImage = copy.deepcopy(frame)
GUIReadyForImage = False
setupCamera()
frameGrabberT = threading.Thread(target=frameGrabberThread)
frameGrabberT.start()
framecnt = 0
lastsolveTime = datetime.now()
justStarted = True
camera_Died = False
solveCompleted = False
lastpictureTime = -1
framecnt = 0
def delayedStatus(delay,status):
global skyStatusText
time.sleep(delay)
skyStatusText = status
def solveWatchDog():
global lastsolveTime, state, skyStatusText, justStarted, framecnt, camera_Died,\
doDebug, debugLastState,lastpictureTime
lastmode = -1
if doDebug:
logging.warning("watch dog started %s", doDebug)
logging.warning("state %s",state)
while (True):
time.sleep(5)
if doDebug:
if lastmode != state:
if doDebug:
logging.warning("watchdog last state %s",state)
logging.warning("debug last state, %s",debugLastState)
lastmode = state
if state is Mode.SOLVING:
now = datetime.now()
duration = now - lastpictureTime
if duration > 20 and doDebug:
logging.warning("watchdog says not solving within " + str(duration) + "seconds.")
if camera_Died:
state = Mode.PAUSED
skyStatusText = "camera seens to have stopped. Restarting"
os.system('./restartsky.sh')
time.sleep(10)
break
def shutThread():
time.sleep(3)
call("sudo nohup shutdown -h now", shell=True)
#thread to watch for the switch to change positions for 10 seconds then shutdown
def switchWatcher():
#check for shutdown switch throw
initGPIO7 = GPIO.input(7)
while True:
time.sleep(2)
pin7 = GPIO.input(7)
if pin7 != initGPIO7:
print("pin7 changed states")
time.sleep(3)
if GPIO.input(7) == pin7:
print("shutting down")
skyStatusText = "shutting down."
th = threading.Thread(target=shutThread)
state = Mode.PAUSED
th.start()
break
switcherWatcherThread = threading.Thread(target=switchWatcher)
switcherWatcherThread.start()
#
# this is responsible for getting images from the camera even in align mod
def solveThread():
global skyStatusText, focusStd, solveCurrent, state, skyCam, testNdx, camera_Died,\
solveLog, solveCompleted, debugLastState, lastpictureTime,\
solveReadyForImage,solveImage,solveThisImage
# save the image to be solved in the file system and on the stack for the gen() routine to give to the client browser
def saveImage(frame):
global doDebug
with open(os.path.join(solve_path, imageName), "wb") as f:
try:
f.write(frame)
return True
except Exception as e:
if doDebug:
logging.error(str(e))
print(e)
solveLog.append(str(e) + '\n')
return False
def makeDeadImage(text):
img = Image.new('RGB', (600, 200), color=(0, 0, 0))
d = ImageDraw.Draw(img)
myFont = ImageFont.truetype('FreeMono.ttf', 40)
d.text((10, 10), text, fill=(100, 0, 0), font=myFont)
arr = io.BytesIO()
img.save(arr, format='JPEG')
return arr.getvalue()
cameraTry = 0
print('solvethread', state)
lastpictureTime = datetime.now()
while True:
lastsolveTime = datetime.now()
if state is Mode.PAUSED or state is Mode.PLAYBACK:
continue
# solve this one selected image then switch state to playback
if state is Mode.SOLVETHIS:
print('solving skyStatus', skyStatusText, solveThisImage)
copyfile(solveThisImage, os.path.join(solve_path, imageName))
skyStatusText = 'Solving'
print("solving", solveThisImage)
if skyConfig['solverProfiles'][skyConfig['solver']['currentProfile']]['solver_type'] == 'solverTetra3':
verboseSolveText = ""
s = tetraSolve(os.path.join(solve_path, imageName))
if s['RA'] != None:
ra = s['RA']
dec = s['Dec']
fov = s['FOV']
dur = (s['T_solve']+s['T_extract'])/1000
result = "RA:%6.3lf Dec:%6.3lf FOV:%6.3lf %6.3lf secs" % (
ra/15, dec, fov, dur)
skyStatusText = result
else:
skyStatusText = str(s)
else:
if not solve(os.path.join(solve_path, imageName)) and skyConfig['solverProfiles'][skyConfig['solver']['currentProfile']]['searchRadius'] > 0:
skyStatusText = 'Failed. Retrying with no position hint.'
if doDebug:
logging.warning("did not solve first try")
# try again but this time since the previous failed it will not use a starting guess possition
solve(os.path.join(solve_path, imageName))
state = Mode.PLAYBACK
solveCompleted = True
continue
else: # live solving loop path
#print("getting image in solve" )
if cameraNotPresent:
continue
try:
debugLastState = "waiting for image"
if doDebug:
logging.warning("waiting for image frame")
solveReadyForImage = True
print("solvesetting ready")
while solveReadyForImage:
print('solve waiting for image')
time.sleep(1)
print('got image')
frame = solveImage
except Exception as e:
cameraTry += 1
if doDebug:
logging.error("no image after timeout retry count %s",cameraTry)
if cameraTry > 10:
debugLastState = "no image after timeout"
saveImage(makeDeadImage("no camera. Restarting"))
print("camera failed" )
camera_Died = True
continue
continue
if doDebug:
logging.warning("got frame %s",framecnt)
if frame is None:
print('frame is none')
cameraTry += 1
if cameraTry > 10:
if doDebug:
logging.error("empty frame after 10 retries")
debugLastState = "frame was none after 10 retries"
saveImage(makeDeadImage("camera died. Restarting"))
print("camera died\nRestarting" )
camera_Died = True
continue
lastpictureTime = datetime.now()
cameraTry = 0
# if solving history one after the other in auto playback
if (state is Mode.AUTOPLAYBACK):
if testNdx == len(testFiles):
state = Mode.PLAYBACK
skyStatusText = "Complete."
continue
fn = testFiles[testNdx]
solveThisImage = fn
skyStatusText = "%d %s" % (testNdx, fn)
solveLog.append(skyStatusText + '\n')
testNdx += 1
#print ("image", testNdx, fn)
with open(fn, 'rb') as infile:
frame = infile.read()
saveImage(frame)
#debug to fake camera image with a real star image
#copyfile("static/history/11_01_22_23_47_15.jpeg", os.path.join(solve_path, imageName))
if state is Mode.SOLVING or state is Mode.AUTOPLAYBACK :
if skyConfig['solverProfiles'][skyConfig['solver']['currentProfile']]['solver_type'] == 'solverTetra3':
s = tetraSolve(os.path.join(solve_path, imageName))
# print(str(s))
if s['RA'] != None:
ra = s['RA']
dec = s['Dec']
fov = s['FOV']
dur = (s['T_solve']+s['T_extract'])/1000
result = "RA:%6.3lf Dec:%6.3lf FOV:%6.3lf %6.3lf secs" % (
ra/15, dec, fov, dur)
skyStatusText = result
else:
skyStatusText = str(s)
else:
if state is Mode.SOLVING:
skyStatusText = ""
f = solve(os.path.join(solve_path, imageName))
if f == False:
state = Mode.PLAYBACK
solveCompleted = True
continue
# else measaure contrast for focus bar
try:
img = Image.open(os.path.join(solve_path, imageName)).convert("L")
imgarr = np.array(img)
avg = imgarr.mean()
imax = imgarr.max()
if avg == 0:
avg = 1
contrast = (imax - avg)/avg
focusStd = f"{contrast:.2f}"
except Exception as e:
print(e)
solveT = None
# print("config",skyConfig['solver'])
if skyConfig['solver']['startupSolveing']:
print("should startup solver now")
solveT = threading.Thread(target=solveThread)
solveT.start()
#solveWatchDogTh = threading.Thread(target = solveWatchDog)
#solveWatchDogTh.start()
def solve(fn, parms=[]):
global doDebug, debugLastState
print("solving" )
if doDebug:
logging.warning("solving function")
debugLastState = 'solving'
global app, solving, maxTime, searchRaius, solveLog, ra, dec, searchEnable, solveStatus,\
triggerSolutionDisplay, skyStatusText, lastObs, verboseSolveText
startTime = datetime.now()
solving = True
solved = ''
profile = skyConfig['solverProfiles'][skyConfig['solver']
['currentProfile']]
fieldwidthParm = ''
#print('fieldwidthMode', profile['FieldWidthMode'])
if profile['FieldWidthMode'] == 'FieldWidthModeaPP':
low = profile['aPPLoValue']
high = profile['aPPHiValue']
if high == '':
field = ['--scale-units', 'arcsecperpix', '--scale-low', low]
else:
field = ['--scale-units', 'arcsecperpix',
'--scale-low', low, '--scale-high', high]
elif profile['FieldWidthMode'] == 'FieldWidthModeField':
low = profile['fieldLoValue']
high = profile['fieldHiValue'].replace(' ', '')
#print("highval", high)
if high == '':
field = ['--scale-units', 'degwidth', '--scale-low', low]
else:
field = ['--scale-units', 'degwidth',
'--scale-low', low, '--scale-high', high]
else:
field = []
if profile['additionalParms'] != '':
parmlist = profile['additionalParms'].split()
parms = parms + parmlist
parms = parms + field
parms = parms + ['--cpulimit', str(profile['maxTime'])]
if profile['searchRadius'] > 0 and ra != 0:
parms = parms + ['--ra', str(ra), '--dec', str(dec),
'--radius', str(profile['searchRadius'])]
#print('show stars', profile['showStars'])
if not profile['showStars']:
parms = parms + ['-p']
parms = parms + ["--uniformize", "0", "--no-remove-lines", "--new-fits", "none", "--pnm", "none", "--rdls",
"none"]
cmd = ["solve-field", fn, "--depth", str(profile['solveDepth']), "--sigma", str(profile['solveSigma']),
'--overwrite'] + parms
#print("\n\nsolving ", cmd)
if skyConfig['observing']['verbose']:
solveLog.append(' '.join(cmd) + '\n')
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
solveLog.clear()
ppa = ''
starNames = {}
duration = None
radec = ''
ra = 0
dec = 0
solveLog.append("solving:\n")
skyStatusText = skyStatusText + " solving"
lastmessage = ''
while not p.poll():
stdoutdata = p.stdout.readline().decode(encoding='UTF-8')
if stdoutdata:
if stdoutdata == lastmessage:
continue
lastmessage = stdoutdata
if 'simplexy: found' in stdoutdata:
skyStatusText = stdoutdata
print("stdoutdata", stdoutdata)
elif stdoutdata.startswith('Field center: (RA,Dec) = ('):
solved = stdoutdata
fields = solved.split()[-3:-1]
#print ('f',fields)
ra = fields[0][1:-1]
dec = fields[1][0:-1]
ra = float(fields[0][1:-1])
dec = float(fields[1][0:-1])
radec = "%s %6.6lf %6.6lf \n" % (
time.strftime('%H:%M:%S'), ra, dec)
file1 = open(os.path.join(
solve_path, "radec.txt"), "w") # write mode
file1.write(radec)
file1.close()
if doDebug:
logging.warning('here is RAdec')
logging.warning(radec)
stopTime = datetime.now()
duration = stopTime - startTime
#print ('duration', duration)
skyStatusText = skyStatusText + " solved "+str(duration)+'secs'
if stdoutdata and skyConfig['observing']['verbose']:
solveLog.append(stdoutdata)
print("stdout", str(stdoutdata))
skyStatusText = skyStatusText + '.'
if stdoutdata.startswith("Field 1: solved with"):
ndx = stdoutdata.split("index-")[-1].strip()
print("index", ndx, stdoutdata )
usedIndexes[ndx] = usedIndexes.get(ndx, 0)+1
pp = pprint.pformat(usedIndexes)
print("Used indexes", pp )
solveLog.append('used indexes ' + pp + '\n')
elif stdoutdata.startswith('Field size'):
print("Field size", stdoutdata )
solveLog.append(stdoutdata)
solveStatus += (". " + stdoutdata.split(":")[1].rstrip())
elif stdoutdata.find('pixel scale') > 0:
computedPPa = stdoutdata.split("scale ")[1].rstrip()
elif 'The star' in stdoutdata:
stdoutdata = stdoutdata.replace(')', '')
con = stdoutdata[-4:-1]
if con not in starNames:
starNames[con] = 1
else:
break
solveStatus += ". scale " + ppa
# create solved plot
if solved and (state is Mode.PLAYBACK or skyConfig['observing']['verbose']):
# Write-Overwrites
file1 = open(os.path.join(solve_path, "radec.txt"), "w") # write mode
file1.write(radec)
file1.close()
cmdPlot = ['/usr/bin/plot-constellations', '-v', '-w', os.path.join(solve_path, 'cap.wcs'),
'-B', '-C', '-N', '-o', os.path.join(solve_path, 'cap-ngc.png')]
p2 = subprocess.Popen(cmdPlot, stdout=subprocess.PIPE)
ndx = 0
stars = []
while not p2.poll():
if ndx > 1000:
break
ndx += 1
stdoutdata = p2.stdout.readline().decode(encoding='UTF-8')
if stdoutdata:
stars.append(stdoutdata)
print(stdoutdata)
if 'The star' in stdoutdata:
stdoutdata = stdoutdata.replace(')', '')
con = stdoutdata[-4:-1]
if con not in starNames:
starNames[con] = 1
foundStars = ', '.join(stars).replace("\n", "")
foundStars = foundStars.replace("The star", "")
#solveLog.append(foundStars + "\n")
constellations = ', '.join(starNames.keys())
# copy the index over the ngc file so stars will display with the index triangle
if profile['showStars']:
os.remove(os.path.join(solve_path, 'cap-objs.png'))
copyfile(os.path.join(solve_path, 'cap-indx.png'),
os.path.join(solve_path, 'cap-objs.png'))
if skyConfig['observing']['savePosition'] and state is Mode.SOLVING:
obsfile = open(os.path.join(solve_path, "obs.log"), "a+")
obsfile.write(radec.rstrip() + " " + constellations + '\n')
obsfile.close()
#print ("wrote obs log")
if skyConfig['observing']['saveImages']:
saveimage = False
if skyConfig['observing']['obsDelta'] > 0:
#print ("checking delta")
if lastObs:
old = lastObs.split(" ")
ra1 = math.radians(float(old[1]))
dec1 = math.radians(float(old[2]))
ra2 = math.radians(float(ra))
dec2 = math.radians(float(dec))
delta = math.degrees(math.acos(math.sin(
dec1) * math.sin(dec2) + math.cos(dec1) * math.cos(dec2)*math.cos(ra1 - ra2)))
#print("image delta", delta)
if delta > skyConfig['observing']['obsDelta']:
saveimage = True
else:
saveimage = True
if state is Mode.SOLVING and saveimage:
lastObs = radec
fn = datetime.now().strftime("%m_%d_%y_%H_%M_%S.") + \
skyConfig['camera']['format']
copyfile(os.path.join(solve_path, imageName),
os.path.join(solve_path, 'history', fn))
if skyConfig['observing']['showSolution']:
triggerSolutionDisplay = True
stopTime = datetime.now()
duration = stopTime - startTime
skyStatusText = "solved "+str(duration) + ' secs'
verboseSolveText = foundStars
if doDebug:
logging.warning(skyStatusText)
logging.warning(verboseSolveText)
logging.warning(radec)
if not solved:
skyStatusText = skyStatusText + " Failed"
ra = 0
solveLog.append("Failed\n")
solving = False
solvestatestr = 'solved'
if not solved:
solvestatestr = 'failed'
if doDebug:
logging.warning("solve finished with solve state %s", solvestatestr)
return solved
def tetraSolve(imageName):
global skyStatusText, solveLog, t3
solveLog.append("solving " + imageName + '\n')
img = Image.open(os.path.join(solve_path, imageName))
#print('solving', imageName)
profile = skyConfig['solverProfiles'][skyConfig['solver']
['currentProfile']]
solved = t3.solve_from_image(
img, fov_estimate=float(profile['fieldLoValue']))
# print(str(solved),profile['fieldLoValue'],flush=True)
if solved['RA'] == None:
return solved
radec = "%s %6.6lf %6.6lf \n" % (time.strftime(
'%H:%M:%S'), solved['RA'], solved['Dec'])
solveLog.append(str(solved) + '\n')
file1 = open(os.path.join(solve_path, "radec.txt"), "w") # write mode
file1.write(radec)
file1.close()
skyStatusText = str(solved['RA'])
return solved
app = Flask(__name__)
doDebug = False
skyStatusText = 'Initilizing Camera'
@app.route("/StarHistory", methods=['GET','POST'])
def showStarHistoryPage():
return render_template('starHistory.html')
@app.route("/", methods=['GET', 'POST'])
def index():
global skyCam, cameraNotPresent, skyStatusText, solveT, verboseSolveText
verboseSolveText = ""
shutterValues = ['.001', '.002', '.005', '.01', '.02', '.05', '.1', '.15', '.2',
'.5', '.7', '.9', '1', '2.', '3', '4', '5', '10']
skyFrameValues = ['400x300', '640x480', '800x600', '1024x768',
'1280x960', '1920x1440', '2000x1000', '2000x1500']
isoValues = ['100', '200', '400', '800']
formatValues = ['jpeg', 'png']
solveParams = {'PPA': 27, 'FieldWidth': 14, 'Timeout': 34,
'Sigma': 9, 'Depth': 20, 'SearchRadius': 10}
if cameraNotPresent:
skyStatusText = 'camera not connected or enabled. Demo mode and replay mode will still work however.'
print('camera was not found')
#print('current profile', skyConfig['solver'])
if not solveT: # start up solver if not already running.
solveT = threading.Thread(target=solveThread)
solveT.start()
return render_template('template.html', shutterData=shutterValues, skyFrameData=skyFrameValues, skyFormatData=formatValues,
skyIsoData=isoValues, profiles=skyConfig['solverProfiles'], startup=skyConfig['solver']['startupSolveing'], solveP=skyConfig['solver']['currentProfile'], obsParms=skyConfig['observing'], cameraParms=skyConfig['camera'])
#
@app.route("/solveLog")
def streamSolveLog():
global solveLog
def generate():
global solveLog
while True:
#print (len(solveLog))
if len(solveLog) > 0:
str = solveLog.pop(0)
#print ("log", str)
yield str
return app.response_class(generate(), mimetype="text/plain")
@app.route('/pause', methods=['POST'])
def pause():
global skyStatusText, skyCam, state
if skyCam:
skyCam.pause()
state = Mode.PAUSED
skyStatusText = 'Paused'
return Response(skyStatusText)
@app.route('/Align', methods=['POST'])
def Align():
global skyStatusText, skyCam, state
if skyCam:
skyCam.resume()
state = Mode.ALIGN
skyStatusText = 'Align Mode'
return Response(skyStatusText)
@app.route('/saveCurrent', methods=['POST'])
def saveCurrent():
global skyStatusText, imageName
print("save current image" )
fn = datetime.now().strftime("%m_%d_%y_%H_%M_%S.") + \
skyConfig['camera']['format']
copyfile(os.path.join(solve_path, imageName),
os.path.join(solve_path, 'history', fn))
skyStatusText = 'saved'
return Response(skyStatusText)
@app.route('/Solve', methods=['POST'])
def Solving():
global skyStatusText, state, skyCam
if skyCam:
skyCam.resume()
if state is Mode.PLAYBACK:
state = Mode.AUTOPLAYBACK
skyStatusText = "Auto playback"
elif state is Mode.AUTOPLAYBACK:
state = Mode.PLAYBACK
skyStatusText = "Manual playback"
else:
state = Mode.SOLVING
skyStatusText = 'Solving Mode'
return Response(skyStatusText)
@app.route('/setISO', methods=['POST'])
def setISOx():
print("setISO FORM", request.form.values)
global solveLog, skyStatusText, isoglobal
value = request.form.get('setISO')
solveLog.append("ISO changing will take 10 seconds to stabilize gain.\n")
delayedStatus(2, "changing to ISO " + value)
isoglobal = value
skyCam.setISO(int(value))
skyConfig['camera']['ISO'] = value
saveConfig()
return Response(status=204)
@app.route('/setISO/<value>', methods=['POST', 'GET'])
def setISO(value):
print("setting iso", value)
global solveLog, skyStatusText, isoglobal
solveLog.append("ISO changing will take 10 seconds to stabilize gain.\n")
delayedStatus(2, "changing to ISO " + value)
isoglobal = value
skyCam.setISO(int(value))
skyConfig['camera']['ISO'] = value
saveConfig()
return Response(status=204)
@app.route('/setFrame/<value>', methods=['POST'])
def setFrame(value):
skyCam.setResolution(value)
skyConfig['camera']['frame'] = value
saveConfig()
return Response(status=204)
@app.route('/setFormat/<value>', methods=['POST'])
def setFormat(value):
global skyStatusText, imageName
skyStatusText = "changing Image Format to " + value
imageName = 'cap.'+value
skyCam.setFormat(value)
skyConfig['camera']['format'] = value
saveConfig()
return Response(status=204)
@app.route('/setShutter', methods=['POST'])
def setShutterx():
global skyStatusText
value = request.form.get('setShutter')
print("shutter value", value)
skyCam.setShutter(int(1000000 * float(value)))
skyConfig['camera']['shutter'] = value
delayedStatus(2, "Setting shutter to "+str(value) +
" may take about 10 seconds.")
saveConfig()
return Response(status=204)
@app.route('/setShutter/<value>', methods=['POST'])
def setShutter(value):
global skyStatusText
print("shutter value", value)
skyCam.setShutter(int(1000000 * float(value)))
skyConfig['camera']['shutter'] = value
delayedStatus(2, "Setting shutter to "+str(value) +
" may take about 10 seconds.")
saveConfig()
return Response(status=204)
@app.route('/showSolution/<value>', methods=['POSt'])
def setShowSolutions(value):
global skyConfig
print('show solutions', value)
if (value == '1'):
skyConfig['observing']['showSolution'] = value == '1'
saveConfig()
return Response(status=204)
@app.route('/saveImages/<value>', methods=['POST'])
def saveSolvedImage(value):
global skyConfig
print('save images ', value)
skyConfig['observing']['saveImages'] = value == '1'
saveConfig()
print("config", skyConfig)
return Response(status=204)
@app.route('/verbose/<value>', methods=['POST'])
def verbose(value):
global skyConfig
print("verbose", value)
skyConfig['observing']['verbose'] = (value == 'true')
saveConfig()
print("config verbose", skyConfig['observing']['verbose'])
return Response(status=204)
@app.route('/clearObsLog', methods=['POST'])
def clearObsLog():
global ndx, obsList
ndx = 0
obsList.clear()
with open(os.path.join(solve_path, 'obs.log'), 'w') as infile:
pass # this will write an empty file erasing the previous contents
return Response("observing log cleared")
setTimeDate = True
@app.route('/lastVerboseSolve', methods=['post'])
def verboseSolveUpdate():
global verboseSolveText
return Response(verboseSolveText)
@app.route('/skyStatus', methods=['post'])
def skyStatus():
global skyStatusText, setTimeDate
if setTimeDate:
setTimeDate = False
t = float(request.form['time'])/1000
time.clock_settime(time.CLOCK_REALTIME, t)
resp = copy.deepcopy(skyStatusText)
skyStatusText = ''
return Response(resp)
@app.route('/Focus', methods=['post'])
def Focus():
global focusStd
return Response(focusStd)
lastmode = state
def gen():
global skyStatusText, solveT, testNdx, triggerSolutionDisplay,\
doDebug, state, solveCurrent, framecnt, lastDisplayedFile,lastmode,\
GUIReadyForImage, GUIImage
# Video streaming generator function.
lastImageTime = datetime.now()
yield (b'\r\n--framex\r\n' b'Content-Type: image/jpeg\r\n\r\n')
while True:
frame = None
if state is Mode.PAUSED:
time.sleep(1)
continue