-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobs.py
4563 lines (4080 loc) · 222 KB
/
obs.py
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
# -*- coding: utf-8 -*-
"""
obs.py obs.py obs.py obs.py obs.py obs.py obs.py obs.py obs.py obs.py
Observatory is the central organising part of a given observatory system.
It deals with connecting all the devices together and deals with decisions that
involve multiple devices and fundamental operations of the OBS.
It also organises the various queues that process, send, slice and dice data.
"""
# The ingester should only be imported after environment variables are loaded in.
from dotenv import load_dotenv
load_dotenv(".env")
import ocs_ingester.exceptions
from ocs_ingester.ingester import upload_file_and_ingest_to_archive
from requests.adapters import HTTPAdapter, Retry
import ephem
import datetime
import json
import os
import queue
import shelve
import threading
from multiprocessing.pool import ThreadPool
import time
import sys
import copy
import math
import shutil
import glob
import subprocess
import pickle
from astropy.io import fits
from astropy.utils.data import check_download_cache
from astropy.coordinates import SkyCoord, get_sun, AltAz
from astropy.time import Time
from astropy import units as u
import bottleneck as bn
import numpy as np
import requests
import urllib.request
import traceback
import psutil
from global_yard import g_dev
import ptr_config
from devices.camera import Camera
from devices.filter_wheel import FilterWheel
from devices.focuser import Focuser
from devices.mount import Mount
from devices.rotator import Rotator
#from devices.selector import Selector
#from devices.screen import Screen
from devices.sequencer import Sequencer
from ptr_events import Events
from ptr_utility import plog
from astropy.utils.exceptions import AstropyUserWarning
import warnings
warnings.simplefilter("ignore", category=AstropyUserWarning)
reqs = requests.Session()
retries = Retry(total=3, backoff_factor=0.1,
status_forcelist=[500, 502, 503, 504])
reqs.mount("http://", HTTPAdapter(max_retries=retries))
def test_connect(host="http://google.com"):
# This just tests the net connection
# for certain safety checks
# If it cannot connect to the internet for an extended period of time.
# It will park
try:
urllib.request.urlopen(host) # Python 3.x
return True
except:
return False
def ra_dec_fix_hd(ra, dec):
# Get RA and Dec into the proper domain
# RA in hours, Dec in degrees
if dec > 90:
dec = 180 - dec
ra -= 12
if dec < -90:
dec = -180 - dec
ra += 12
while ra >= 24:
ra -= 24
while ra < 0:
ra += 24
return ra, dec
def findProcessIdByName(processName):
"""
Get a list of all the PIDs of a all the running process whose name contains
the given string processName
"""
listOfProcessObjects = []
# Iterate over the all the running process
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=["pid", "name", "create_time"])
# Check if process name contains the given name string.
if processName.lower() in pinfo["name"].lower():
listOfProcessObjects.append(pinfo)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return listOfProcessObjects
def authenticated_request(method: str, uri: str, payload: dict = None) -> str:
# Populate the request parameters. Include data only if it was sent.
base_url = "https://api.photonranch.org/api"
request_kwargs = {
"method": method,
"timeout": 10,
"url": f"{base_url}/{uri}",
}
if payload is not None:
request_kwargs["data"] = json.dumps(payload)
response = requests.request(**request_kwargs)
return response.json()
def send_status(obsy, column, status_to_send):
"""Sends an update to the status endpoint."""
uri_status = f"https://status.photonranch.org/status/{obsy}/status/"
payload = {"statusType": str(column), "status": status_to_send}
# if column == 'weather':
# print("Did not send spurious weathr report.")
# return
try:
data = json.dumps(payload)
#print(data)
except Exception as e:
plog("Failed to create status payload. Usually not fatal: ", e)
try:
reqs.post(uri_status, data=data, timeout=20)
except Exception as e:
plog("Failed to send_status. Usually not fatal: ", e)
class Observatory:
"""
Observatory is the central organising part of a given observatory system.
It deals with connecting all the devices together and deals with decisions that
involve multiple devices and fundamental operations of the OBS.
It also organises the various queues that process, send, slice and dice data.
"""
def __init__(self, name, ptr_config):
self.name = name
self.obs_id = name
g_dev["name"] = name
self.config = ptr_config
self.wema_name = self.config["wema_name"]
self.wema_config = self.get_wema_config() # fetch the wema config from AWS
# Used to tell whether the obs is currently rebooting theskyx
self.rebooting_theskyx = False
# Creation of directory structures if they do not exist already
self.obsid_path = str(
ptr_config["archive_path"] + "/" + self.name + "/"
).replace("//", "/")
g_dev["obsid_path"] = self.obsid_path
if not os.path.exists(self.obsid_path):
os.makedirs(self.obsid_path, mode=0o777)
self.local_calibration_path = (
ptr_config["local_calibration_path"] + self.config["obs_id"] + "/"
)
if not os.path.exists(ptr_config["local_calibration_path"]):
os.makedirs(ptr_config["local_calibration_path"], mode=0o777)
if not os.path.exists(self.local_calibration_path):
os.makedirs(self.local_calibration_path, mode=0o777)
if self.config["save_to_alt_path"] == "yes":
self.alt_path = ptr_config["alt_path"] + \
self.config["obs_id"] + "/"
if not os.path.exists(ptr_config["alt_path"]):
os.makedirs(ptr_config["alt_path"], mode=0o777)
if not os.path.exists(self.alt_path):
os.makedirs(self.alt_path, mode=0o777)
if not os.path.exists(self.obsid_path + "ptr_night_shelf"):
os.makedirs(self.obsid_path + "ptr_night_shelf", mode=0o777)
if not os.path.exists(self.obsid_path + "archive"):
os.makedirs(self.obsid_path + "archive", mode=0o777)
if not os.path.exists(self.obsid_path + "tokens"):
os.makedirs(self.obsid_path + "tokens", mode=0o777)
if not os.path.exists(self.obsid_path + "astropycache"):
os.makedirs(self.obsid_path + "astropycache", mode=0o777)
# Local Calibration Paths
main_camera_device_name = self.config["device_roles"]["main_cam"]
camera_name_for_directories = self.config["camera"][main_camera_device_name]["name"]
# Base path and camera name
base_path = self.local_calibration_path
def create_directories(base_path, camera_name, subdirectories):
"""
Create directories if they do not already exist.
"""
for subdir in subdirectories:
path = os.path.join(base_path, "archive", camera_name, subdir)
if not os.path.exists(path):
os.makedirs(path, mode=0o777)
# Subdirectories to create
subdirectories = [
"calibmasters",
"localcalibrations",
"localcalibrations/darks",
"localcalibrations/darks/narrowbanddarks",
"localcalibrations/darks/broadbanddarks",
"localcalibrations/darks/fortymicroseconddarks",
"localcalibrations/darks/fourhundredmicroseconddarks",
"localcalibrations/darks/pointzerozerofourfivedarks",
"localcalibrations/darks/onepointfivepercentdarks",
"localcalibrations/darks/fivepercentdarks",
"localcalibrations/darks/tenpercentdarks",
"localcalibrations/darks/quartersecdarks",
"localcalibrations/darks/halfsecdarks",
"localcalibrations/darks/sevenfivepercentdarks",
"localcalibrations/darks/onesecdarks",
"localcalibrations/darks/oneandahalfsecdarks",
"localcalibrations/darks/twosecdarks",
"localcalibrations/darks/threepointfivesecdarks",
"localcalibrations/darks/fivesecdarks",
"localcalibrations/darks/sevenpointfivesecdarks",
"localcalibrations/darks/tensecdarks",
"localcalibrations/darks/fifteensecdarks",
"localcalibrations/darks/twentysecdarks",
"localcalibrations/darks/thirtysecdarks",
"localcalibrations/biases",
"localcalibrations/flats",
]
# Create the directories
create_directories(base_path, camera_name_for_directories, subdirectories)
# Set calib masters folder
self.calib_masters_folder = os.path.join(base_path, "archive", camera_name_for_directories, "calibmasters") + "/"
self.local_dark_folder = (
self.local_calibration_path
+ "archive/"
+ camera_name_for_directories
+ "/localcalibrations/darks"
+ "/"
)
self.local_bias_folder = (
self.local_calibration_path
+ "archive/"
+ camera_name_for_directories
+ "/localcalibrations/biases"
+ "/"
)
self.local_flat_folder = (
self.local_calibration_path
+ "archive/"
+ camera_name_for_directories
+ "/localcalibrations/flats"
+ "/"
)
# Directories for broken and orphaned upload files
self.orphan_path = (
self.config["archive_path"] + "/" + self.name + "/" + "orphans/"
)
if not os.path.exists(self.orphan_path):
os.makedirs(self.orphan_path, mode=0o777)
self.broken_path = (
self.config["archive_path"] + "/" + self.name + "/" + "broken/"
)
if not os.path.exists(self.broken_path):
os.makedirs(self.broken_path, mode=0o777)
# Clear out smartstacks directory
try:
shutil.rmtree(self.local_calibration_path + "smartstacks")
except:
pass
if not os.path.exists(self.local_calibration_path + "smartstacks"):
os.makedirs(self.local_calibration_path + "smartstacks", mode=0o777)
# Copy in the latest fz_archive subprocess file to the smartstacks folder
shutil.copy(
"subprocesses/fz_archive_file.py",
self.local_calibration_path + "smartstacks/fz_archive_file.py",
)
shutil.copy(
"subprocesses/local_reduce_file_subprocess.py",
self.local_calibration_path + "smartstacks/local_reduce_file_subprocess.py",
)
# # Clear out substacks directory #This is redundant
# try:
# shutil.rmtree(self.local_calibration_path + "substacks")
# except:
# pass
# if not os.path.exists(self.local_calibration_path + "substacks"):
# os.makedirs(self.local_calibration_path + "substacks")
# # Orphan and Broken paths
# self.orphan_path = (
# self.config["archive_path"] + "/" + self.name + "/" + "orphans/"
# )
# if not os.path.exists(self.orphan_path):
# os.makedirs(self.orphan_path)
# self.broken_path = (
# self.config["archive_path"] + "/" + self.name + "/" + "broken/"
# )
# if not os.path.exists(self.broken_path):
# os.makedirs(self.broken_path)
# Software Kills.
# There are some software that really benefits from being restarted from
# scratch on Windows, so on bootup of obs.py, the system closes them down
# Reconnecting the devices reboots the softwares later on.
processes = [
"Gemini Software.exe",
"OptecGHCommander.exe",
"AltAzDSConfig.exe",
"ASCOM.AltAzDS.exe",
"AstroPhysicsV2 Driver.exe",
"AstroPhysicsCommandCenter.exe",
"TheSkyX.exe",
"TheSky64.exe",
"PWI4.exe",
"PWI3.exe",
"FitsLiberator.exe"
]
if name != "tbo2": # saves a few seconds for the simulator site.
for process in processes:
try:
os.system(f'taskkill /IM "{process}" /F')
except Exception:
pass
listOfProcessIds = findProcessIdByName("maxim_dl")
for pid in listOfProcessIds:
pid_num = pid["pid"]
plog("Terminating existing Maxim process: ", pid_num)
p2k = psutil.Process(pid_num)
p2k.terminate()
# Initialisation of variables best explained elsewhere
self.status_interval = 0
self.status_count = 0
self.status_upload_time = 0.5
self.time_last_status = time.time() - 3000
self.pulse_timer=time.time()
self.check_lightning = self.config.get("has_lightning_detector", False)
# Timers to only update status at regular specified intervals.
self.observing_status_timer = datetime.datetime.now() - datetime.timedelta(days=1)
self.observing_check_period = self.config["observing_check_period"]
self.enclosure_status_timer = datetime.datetime.now() - datetime.timedelta(days=1)
self.enclosure_check_period = self.config["enclosure_check_period"]
self.obs_settings_upload_timer = time.time() - 20
self.obs_settings_upload_period = 60
self.last_time_report_to_console = time.time() - 180 #NB changed fro
self.last_solve_time = datetime.datetime.now() - datetime.timedelta(days=1)
self.images_since_last_solve = 10000
self.project_call_timer = time.time()
self.get_new_job_timer = time.time()
self.scan_request_timer = time.time()
# ANd one for scan requests
self.cmd_queue = queue.Queue(maxsize=0)
self.currently_scan_requesting = True
self.scan_request_queue = queue.Queue(maxsize=0)
self.scan_request_thread = threading.Thread(
target=self.scan_request_thread)
self.scan_request_thread.daemon = True
self.scan_request_thread.start()
# And one for updating calendar blocks
self.currently_updating_calendar_blocks = False
self.calendar_block_queue = queue.Queue(maxsize=0)
self.calendar_block_thread = threading.Thread(
target=self.calendar_block_thread)
self.calendar_block_thread.daemon = True
self.calendar_block_thread.start()
self.too_hot_temperature = self.config[
"temperature_at_which_obs_too_hot_for_camera_cooling"
]
self.warm_report_timer = time.time() - 600
# Keep track of how long it has been since the last activity of slew or exposure
# This is useful for various functions... e.g. if telescope idle for an hour, park.
self.time_of_last_exposure = time.time()
self.time_of_last_slew = time.time()
self.time_of_last_pulse = time.time()
# Keep track of how long it has been since the last live connection to the internet
self.time_of_last_live_net_connection = time.time()
# Initialising various flags best explained elsewhere
self.env_exists = os.path.exists(
os.getcwd() + "\.env"
) # Boolean, check if .env present
self.stop_processing_command_requests = False
self.platesolve_is_processing = False
self.stop_all_activity = False # This is used to stop the camera or sequencer
self.exposure_halted_indicator = False
self.camera_sufficiently_cooled_for_calibrations = True
self.last_slew_was_pointing_slew = False
self.open_and_enabled_to_observe = False
self.net_connection_dead = False
# Set default obs safety settings at bootup
self.scope_in_manual_mode = self.config["scope_in_manual_mode"]
self.moon_checks_on = self.config["moon_checks_on"]
self.sun_checks_on = self.config["sun_checks_on"]
self.altitude_checks_on = self.config["altitude_checks_on"]
self.daytime_exposure_time_safety_on = self.config["daytime_exposure_time_safety_on"]
self.mount_reference_model_off = self.config["mount_reference_model_off"]
self.admin_owner_commands_only = self.config.get("owner_only_commands", False)
self.assume_roof_open = self.config.get("simulate_open_roof", False)
self.auto_centering_off = self.config.get("auto_centering_off", False)
# Instantiate the helper class for astronomical events
# Soon the primary event / time values can come from AWS. NB NB I send them there! Why do we want to put that code in AWS???
self.astro_events = Events(self.config, self.wema_config)
self.astro_events.calculate_events()
self.astro_events.display_events()
# If the camera is detected as substantially (20 degrees) warmer than the setpoint
# during safety checks, it will keep it warmer for about 20 minutes to make sure
# the camera isn't overheating, then return it to its usual temperature.
self.camera_overheat_safety_warm_on = False
# self.camera_overheat_safety_warm_on = self.config['warm_camera_during_daytime_if_too_hot']
self.camera_overheat_safety_timer = time.time()
# Some things you don't want to check until the camera has been cooling for a while.
self.camera_time_initialised = time.time()
# You want to make sure that the camera has been cooling for a while at the setpoint
# Before taking calibrations to ensure the sensor is evenly cooled
self.last_time_camera_was_warm = time.time() - 60
# If there is a pointing correction needed, then it is REQUESTED
# by the platesolve thread and then the code will interject
# a pointing correction at an appropriate stage.
# But if the telescope moves in the meantime, this is cancelled.
# A telescope move itself should already correct for this pointing in the process of moving.
# This is sort of a more elaborate and time-efficient version of the previous "re-seek"
self.pointing_correction_requested_by_platesolve_thread = False
self.pointing_recentering_requested_by_platesolve_thread = False
self.pointing_correction_request_time = time.time()
self.pointing_correction_request_ra = 0.0
self.pointing_correction_request_dec = 0.0
self.pointing_correction_request_ra_err = 0.0
self.pointing_correction_request_dec_err = 0.0
self.last_platesolved_ra = np.nan
self.last_platesolved_dec = np.nan
self.last_platesolved_ra_err = np.nan
self.last_platesolved_dec_err = np.nan
self.platesolve_errors_in_a_row = 0
self.sync_after_platesolving = False
self.worst_potential_pointing_in_arcseconds = 30000
# Rotator vs mount vs camera sync stuff
self.rotator_has_been_checked_since_last_slew = False
g_dev["obs"] = self
g_dev["obsid"] = ptr_config["obs_id"]
self.currently_updating_status = False
# Use the configuration to instantiate objects for all devices.
# Also configure device roles in here.
self.create_devices()
self.last_update_complete = time.time() - 5
self.mountless_operation = False
if self.devices["mount"] == None:
plog("Engaging mountless operations. Telescope set in manual mode")
self.mountless_operation = True
self.scope_in_manual_mode = True
self.ptrarchive_queue = queue.PriorityQueue(maxsize=0)
self.ptrarchive_queue_thread = threading.Thread(
target=self.send_to_ptrarchive, args=()
)
self.ptrarchive_queue_thread.daemon = True
self.ptrarchive_queue_thread.start()
self.fast_queue = queue.Queue(maxsize=0)
self.fast_queue_thread = threading.Thread(
target=self.fast_to_ui, args=())
self.fast_queue_thread.daemon = True
self.fast_queue_thread.start()
self.file_wait_and_act_queue = queue.Queue(maxsize=0)
self.file_wait_and_act_queue_thread = threading.Thread(
target=self.file_wait_and_act, args=()
)
self.file_wait_and_act_queue_thread.daemon = True
self.file_wait_and_act_queue_thread.start()
self.mediumui_queue = queue.PriorityQueue(maxsize=0)
self.mediumui_thread = threading.Thread(
target=self.medium_to_ui, args=())
self.mediumui_thread.daemon = True
self.mediumui_thread.start()
self.calibrationui_queue = queue.PriorityQueue(maxsize=0)
self.calibrationui_thread = threading.Thread(
target=self.calibration_to_ui, args=()
)
self.calibrationui_thread.daemon = True
self.calibrationui_thread.start()
self.slow_camera_queue = queue.PriorityQueue(maxsize=0)
self.slow_camera_queue_thread = threading.Thread(
target=self.slow_camera_process, args=()
)
self.slow_camera_queue_thread.daemon = True
self.slow_camera_queue_thread.start()
self.send_status_queue = queue.Queue(maxsize=0)
self.send_status_queue_thread = threading.Thread(
target=self.send_status_process, args=()
)
self.send_status_queue_thread.daemon = True
self.send_status_queue_thread.start()
self.platesolve_queue = queue.Queue(maxsize=0)
self.platesolve_queue_thread = threading.Thread(
target=self.platesolve_process, args=()
)
self.platesolve_queue_thread.daemon = True
self.platesolve_queue_thread.start()
self.laterdelete_queue = queue.Queue(maxsize=0)
self.laterdelete_queue_thread = threading.Thread(
target=self.laterdelete_process, args=()
)
self.laterdelete_queue_thread.daemon = True
self.laterdelete_queue_thread.start()
self.sendtouser_queue = queue.Queue(maxsize=0)
self.sendtouser_queue_thread = threading.Thread(
target=self.sendtouser_process, args=()
)
self.sendtouser_queue_thread.daemon = True
self.sendtouser_queue_thread.start()
self.queue_reporting_period = 60
self.queue_reporting_timer = time.time() - (2 * self.queue_reporting_period)
# send up obs status immediately
self.obs_settings_upload_timer = (
time.time() - 2 * self.obs_settings_upload_period
)
# A dictionary that holds focus results for the SEP queue.
self.fwhmresult = {}
self.fwhmresult["error"] = True
self.fwhmresult["FWHM"] = np.nan
self.fwhmresult["mean_focus"] = np.nan
self.fwhmresult["No_of_sources"] = np.nan
# On initialisation, there should be no commands heading towards the site
# So this command reads the commands waiting and just ... ignores them
# essentially wiping the command queue coming from AWS.
# This prevents commands from previous nights/runs suddenly running
# when obs.py is booted (has happened a bit in the past!)
try:
reqs.request(
"POST",
"https://jobs.photonranch.org/jobs/getnewjobs",
data=json.dumps({"site": self.name}),
timeout=30,
).json()
except:
plog ("getnewjobs connection glitch on startup")
# On startup, collect orphaned fits files that may have been dropped from the queue
# when the site crashed or was rebooted.
if self.config["ingest_raws_directly_to_archive"]:
self.devices["sequencer"].collect_and_queue_neglected_fits()
# Inform UI of reboot
self.send_to_user(
"Observatory code has been rebooted. Manually queued commands have been flushed."
)
# Upload the config to the UI
self.update_config()
# Report previously calculated Camera Gains as part of bootup
textfilename = (
self.obsid_path
+ "ptr_night_shelf/"
+ "cameragain"
+ self.devices["main_cam"].alias
+ str(self.name)
+ ".txt"
)
if os.path.exists(textfilename):
try:
with open(textfilename, "r") as f:
lines = f.readlines()
for line in lines:
plog(line.replace("\n", ""))
except:
plog("something wrong with opening camera gain text file")
pass
# Report filter throughputs as part of bootup
filter_throughput_shelf = shelve.open(
self.obsid_path
+ "ptr_night_shelf/"
+ "filterthroughput"
+ self.devices["main_cam"].alias
+ str(self.name)
)
if len(filter_throughput_shelf) == 0:
plog("Looks like there is no filter throughput shelf.")
else:
#First lts sort this shelf for lowest to highest throughput.
#breakpoint()
#filter_throughput_shelf = dict(sorted(filter_throughput_shelf.items(), key=lambda item: item[1], reverse=False)
plog("Stored filter throughputs")
for filtertempgain in list(filter_throughput_shelf.keys()):
plog(
str(filtertempgain)
+ " "
+ str(filter_throughput_shelf[filtertempgain])
)
filter_throughput_shelf.close()
# Boot up filter offsets
filteroffset_shelf = shelve.open(
self.obsid_path
+ "ptr_night_shelf/"
+ "filteroffsets_"
+ self.devices["main_cam"].alias
+ str(self.name)
)
plog("Filter Offsets")
for filtername in filteroffset_shelf:
plog(str(filtername) + " " + str(filteroffset_shelf[filtername]))
self.devices["main_fw"].filter_offsets[filtername.lower()] = filteroffset_shelf[
filtername
]
filteroffset_shelf.close()
# On bootup, detect the roof status and set the obs to observe or not.
try:
self.enc_status = self.get_enclosure_status_from_aws()
# If the roof is open, then it is open and enabled to observe
if not self.enc_status == None:
if "Open" in self.enc_status["shutter_status"]:
if (
not "NoObs" in self.enc_status["shutter_status"]
and not self.net_connection_dead
) or self.assume_roof_open:
self.open_and_enabled_to_observe = True
else:
self.open_and_enabled_to_observe = False
except:
plog("FAIL ON OPENING ROOF CHECK")
self.open_and_enabled_to_observe = False
# AND one for safety checks
# Only poll the broad safety checks (altitude and inactivity) every 5 minutes
self.safety_check_period = self.config["safety_check_period"]
self.time_since_safety_checks = time.time() - (2 * self.safety_check_period)
self.safety_and_monitoring_checks_loop_thread = threading.Thread(
target=self.safety_and_monitoring_checks_loop
)
self.safety_and_monitoring_checks_loop_thread.daemon = True
self.safety_and_monitoring_checks_loop_thread.start()
self.drift_tracker_timer = time.time()
self.drift_tracker_counter = 0
self.currently_scan_requesting = False
# Sometimes we update the status in a thread. This variable prevents multiple status updates occuring simultaneously
self.currently_updating_status = False
# Create this actual thread
self.update_status_queue = queue.Queue(maxsize=0)
self.update_status_thread = threading.Thread(
target=self.update_status_thread)
self.update_status_thread.daemon = True
self.update_status_thread.start()
# Initialisation complete!
def create_devices(self):
"""Create and store device objects by type, including role assignments.
This function creates several ways to access devices:
1. By type and name: self.all_devices['camera']['QHY600m'] = camera object
2. By name only: self.device_by_name['QHY600m'] = camera object
3. By role: self.devices['main_cam'] = camera object
"""
print("\n--- Initializing Devices ---")
self.all_device_types = self.config["device_types"]
self.all_devices = {} # Store devices by type then name. So all_devices['camera']['QHY600m'] = camera object
self.device_by_name = {} # Store devices by name only. So device_by_name['QHY600m'] = camera object
# Make a dict for accessing devices by role
# This must match the config! But it's duplicated here so human programmers can easily see what the supported roles are.
self.devices = {
"mount": None,
"main_focuser": None,
"main_fw": None,
"main_rotator": None,
"main_cam": None,
"guide_cam": None,
"widefield_cam": None,
"allsky_cam": None
}
# Validate to make sure that the roles in the config match the roles defined here
if set(self.devices.keys()) != set(self.config["device_roles"].keys()):
plog("ERROR: Device roles in Observatory class do not match device roles in config.")
plog(f"Config roles: {set(self.config['device_roles'].keys())}")
plog(f"Roles in obs.py Observatory.create_devices: {set(self.devices.keys())}")
plog("Please update config.device_roles so that they match the roles in Observatory.devices.")
plog('Fatal error, exiting...')
sys.exit()
# Make a dict we can use to lookup the roles for a device
# Use like: device_roles['QHY600m'] = ['main_cam'] (or whatever roles are assigned to that device)
# Support multiple roles per device, though this isn't used currently (2025/11/01).
device_roles = dict()
for role, device_name in self.config.get("device_roles", {}).items():
if device_name not in device_roles:
device_roles[device_name] = []
device_roles[device_name].append(role)
# Now we can create the device objects. Group by type, with type order defined by config.device_types
for dev_type in self.all_device_types:
# Get all the names of devices of this type
self.all_devices[dev_type] = {}
devices_of_type = self.config.get(dev_type, {})
device_names = devices_of_type.keys()
# For each of this device type, create the device object and save it in the appropriate lookup dicts
for device_name in device_names:
plog(f"Initializing {dev_type} device: {device_name}")
driver = devices_of_type[device_name].get("driver")
settings = devices_of_type[device_name].get("settings", {})
# Instantiate the device object based on its type
if dev_type == "mount":
if "PWI4" in driver:
subprocess.Popen('"C:\Program Files (x86)\PlaneWave Instruments\PlaneWave Interface 4\PWI4.exe"', shell=True)
time.sleep(10)
urllib.request.urlopen("http://localhost:8220/mount/connect")
time.sleep(5)
device = Mount(driver, device_name, self.config, self, tel=True)
elif dev_type == "rotator":
device = Rotator(driver, device_name, self.config, self)
elif dev_type == "focuser":
device = Focuser(driver, device_name, self.config, self)
elif dev_type == "filter_wheel":
device = FilterWheel(driver, device_name, self.config, self)
elif dev_type == "camera":
device = Camera(driver, device_name, self.config, self)
elif dev_type == "sequencer":
device = Sequencer(self)
self.devices["sequencer"] = device # seq doesn't have a role, but add it to self.devices for easy access
else:
continue
# Store the device for name-based lookup
self.all_devices[dev_type][device_name] = device
self.device_by_name[device_name] = device
# Store the device for role-based lookup
if device_name in device_roles:
for role in device_roles[device_name]:
self.devices[role] = device
# Assign roles
for role, device_name in self.config.get("device_roles", {}).items():
if device_name and device_name not in self.device_by_name.keys():
print("\n")
print(f"\tWARNING: the device role <{role}> should be assigned to device {device_name}, but that device was never initialized.")
print(f"This will result in errors if the observatory tries to access <{role}>. Please check the device roles in the config.")
print(f"This error is probably because the device name in config.device_roles doesn't match any device in the config.")
print(f"It might also be because the role is for a type of device that is not included in config.device_types.")
print("\n")
print("--- Finished Initializing Devices ---\n")
def get_wema_config(self):
""" Fetch the WEMA config from AWS """
wema_config = None
url = f"https://api.photonranch.org/api/{self.wema_name}/config/"
try:
response = requests.get(url, timeout=20)
wema_config = response.json()['configuration']
wema_last_recorded_day_dir = wema_config['events'].get('day_directory', '<missing>')
plog(f"Retrieved wema config, lastest version is from day_directory {wema_last_recorded_day_dir}")
except Exception as e:
plog("WARNING: failed to get wema config!", e)
return wema_config
def update_config(self):
"""Sends the config to AWS."""
uri = f"{self.config['obs_id']}/config/"
self.config["events"] = g_dev["events"]
# Insert camera size into config
for name, camera in self.all_devices["camera"].items():
self.config["camera"][name]["camera_size_x"] = camera.imagesize_x
self.config["camera"][name]["camera_size_y"] = camera.imagesize_y
retryapi = True
while retryapi:
try:
response = authenticated_request("PUT", uri, self.config)
retryapi = False
except:
plog("connection glitch in update config. Waiting 5 seconds.")
time.sleep(5)
if "message" in response:
if response["message"] == "Missing Authentication Token":
plog(
"Missing Authentication Token. Config unable to be uploaded. Please fix this now."
)
sys.exit()
else:
plog(
"There may be a problem in the config upload? Here is the response."
)
plog(response)
elif "ResponseMetadata" in response:
if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
plog("Config uploaded successfully.")
else:
plog("Response to obsid config upload unclear. Here is the response")
plog(response)
else:
plog("Response to obsid config upload unclear. Here is the response")
plog(response)
def cancel_all_activity(self):
self.stop_all_activity = True
self.stop_all_activity_timer = time.time()
plog("Stop_all_activity is now set True.")
self.send_to_user(
"Cancel/Stop received. Exposure stopped, camera may begin readout, then will discard image."
)
self.send_to_user(
"Pending reductions and transfers to the PTR Archive are not affected."
)
plog("Emptying Command Queue")
with self.cmd_queue.mutex:
self.cmd_queue.queue.clear()
plog("Stopping Exposure")
try:
self.devices["main_cam"]._stop_expose()
self.devices["main_cam"].running_an_exposure_set = False
except Exception as e:
plog("Camera is not busy.", e)
plog(traceback.format_exc())
self.devices["main_cam"].running_an_exposure_set = False
self.exposure_halted_indicator = True
self.exposure_halted_indicator_timer = time.time()
def scan_requests(self, cancel_check=False):
"""Gets commands from AWS, and post a STOP/Cancel flag.
We limit the polling to once every 4 seconds because AWS does not
appear to respond any faster. When we poll, we parse
the action keyword for 'stop' or 'cancel' and post the
existence of the timestamp of that command to the
respective device attribute <self>.cancel_at. Then we
enqueue the incoming command as well.
NB at this time we are preserving one command queue
for all devices at a site. This may need to change when we
have parallel mountings or independently controlled cameras.
"""
self.scan_request_timer = time.time()
url_job = "https://jobs.photonranch.org/jobs/getnewjobs"
body = {"site": self.name}
cmd = {}
# Get a list of new jobs to complete (this request
# marks the commands as "RECEIVED")
try:
unread_commands = reqs.request(
"POST", url_job, data=json.dumps(body), timeout=20
).json()
except:
plog("problem gathering scan requests. Likely just a connection glitch.")
unread_commands = []
# Make sure the list is sorted in the order the jobs were issued
# Note: the ulid for a job is a unique lexicographically-sortable id.
if len(unread_commands) > 0:
try:
unread_commands.sort(key=lambda x: x["timestamp_ms"])
# Process each job one at a time
for cmd in unread_commands:
if (
self.admin_owner_commands_only
and (
("admin" in cmd["user_roles"])
or ("owner" in cmd["user_roles"])
)
) or (not self.admin_owner_commands_only):
# Check for a stop or cancel command
if (
cmd["action"] in ["cancel_all_commands", "stop"]
or cmd["action"].lower() in ["stop", "cancel"]
or (
cmd["action"] == "run"
and cmd["required_params"]["script"] == "stopScript"
)
):
# A stop script command flags to the running scripts that it is time to stop
# activity and return. This period runs for about 30 seconds.
self.send_to_user(
"A Cancel/Stop has been called. Cancelling out of running scripts over 30 seconds."
)
self.devices["sequencer"].stop_script_called = True
self.devices["sequencer"].stop_script_called_time = time.time()
# Cancel out of all running exposures.
self.cancel_all_activity()
# Anything that is not a stop or cancel command
else:
action = cmd.get('action')
script = cmd["required_params"].get("script")
if cmd["deviceType"] == "obs":
plog("OBS COMMAND: received a system wide command")
if cmd["action"] == "configure_pointing_reference_off":
self.mount_reference_model_off = True
plog("mount_reference_model_off")
self.send_to_user(
"mount_reference_model_off."
)
elif cmd["action"] == "configure_pointing_reference_on":
self.mount_reference_model_off = False
plog("mount_reference_model_on")
self.send_to_user(
"mount_reference_model_on."
)
elif cmd["action"] == "configure_telescope_mode":
if cmd["required_params"]["mode"] == "manual":