-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwema.py
2317 lines (1772 loc) · 117 KB
/
wema.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
"""
WER 20210624
First attempt at having a parallel dedicated agent for weather and enclosure.
This code should be as simple and reliable as possible, no hanging variables,
etc.
This would be a good place to log the weather data and any enclosure history,
once this code is stable enough to run as a service.
"""
import os
import signal
import json
import shelve
import time
import socket
from pathlib import Path
import math
import requests
import traceback
import ephem
import ptr_config
from api_calls import API_calls
import wema_events
from devices.observing_conditions import ObservingConditions
from devices.enclosure import Enclosure
from global_yard import g_dev
import logging
from wema_utility import plog
from pyowm import OWM
from pyowm.utils import config
from pyowm.utils import timestamps
from pyowm.utils.config import get_default_config
from pyowm.commons.databoxes import SubscriptionType
#from requests.adapters import HTTPAdapter, Retry
from dotenv import load_dotenv
load_dotenv(".env")
from wema_config import get_enc_status_custom
from wema_config import get_ocn_status_custom
from astropy.coordinates import EarthLocation, AltAz, SkyCoord
from astropy.time import Time
import astropy.units as u
from func_timeout import func_timeout, FunctionTimedOut
#import http.client
#http.client.HTTPConnection.debuglevel = 1
#logging.getLogger("urllib3").setLevel(logging.DEBUG)
close_headers = {
"Connection": "close" # Forces the server to close the connection after the response
}
import pytz
import datetime
import requests
# Default headers to force closing connections
close_headers = {"Connection": "close"}
def global_request(method, url, **kwargs):
""" Wrapper around requests to enforce default options and ensure response is closed """
kwargs.setdefault("allow_redirects", False)
kwargs.setdefault("headers", close_headers)
kwargs.setdefault("stream", False)
kwargs.setdefault("timeout", 5) # Optional: Set a global timeout
# Send the request
response = requests.request(method, url, **kwargs)
# Read the response content (to ensure the connection can be closed)
content = response.content # Ensure the body is downloaded before closing
status_code = response.status_code
headers = response.headers
# Close the response immediately
response.close()
# Return relevant response data (since original response object is closed)
return {
"status_code": status_code,
"content": content,
"headers": headers
}
# FIXME: This needs attention once we figure out the restart_obs script.
def terminate_restart_observer(site_path, no_restart=False):
"""Terminates obs-platform code if running and restarts obs."""
if no_restart is False:
return
camShelf = shelve.open(site_path + "ptr_night_shelf/" + "pid_obs")
pid = camShelf["pid_obs"] # a 9 character string
camShelf.close()
try:
print("Terminating: ", pid)
os.kill(pid, signal.SIGTERM)
except:
print("No observer process was found, starting a new one.")
# The above routine does not return but does start a process.
parentPath = Path.cwd()
os.system("cmd /c " + str(parentPath) + "\restart_obs.bat")
return
def send_status(obsy, column, status_to_send):
"""Sends a status update to AWS."""
uri_status = f"https://status.photonranch.org/status/{obsy}/status/"
# NB None of the strings can be empty. Otherwise this put faults.
payload = {"statusType": str(column), "status": status_to_send}\
data = json.dumps(payload)
try:
response = requests.post(uri_status, data=data, timeout=20, allow_redirects=False, headers=close_headers)
if response.ok:
# pass
print("~")
except:
print(
'self.api.authenticated_request("PUT", uri, status): Failed! ',
response.status_code,
)
class WxEncAgent:
"""A class for weather enclosure functionality."""
"""
Re-working ARO Weather 20231226 WER. Currently the Wema-attached external
SkyAlert is failing so we are picking up Weather from the ARO-0m30 Skyalert
provided by a reflection from AWS -- and we have an inside skyalert which
measures the underside roof temp during the day! Unfortunately the AWS
style reflection gets stale so I am putting in a redis based way to pass
the ARO-0m30 weather information over to the Wema. No Weather decisions
are made at ARO-0m30 except to convert to metric and compute the 15 minute
wind-gust value.
In the event the redis data is stale -- we may use the AWS supplied data if
we can figure out how to verify it is not stale.
NOTE ARO-0m30 passes its weather line through skyalert\weatherdata_nw.txt
Status as sent to GUI does go through AWS however.
The whole Weather Hold system has been bypassed and semi-replaced with the OWM
rework. I plan to revisit this once I am satsified it serves a useful purpose.
for ARO late afternoon winds are common but they tend to abate. Some wind-
shake during eve skyflats causes no harm so we can be more tolerant.
"""
def __init__(self, name, config):
self.api = API_calls()
self.command_interval = 30
self.status_interval = 30
self.config = config
g_dev["wema"] = self
# Initialise location
self.latitude=self.config["latitude"]
self.longitude=self.config["longitude"]
self.height=0
self.observer_location = EarthLocation(lat=self.latitude*u.deg, lon=self.longitude*u.deg, height=self.height*u.m)
self.ocn_status=None
self.enc_status=None
self.current_owm_humidity=-1
# Initialise this variable
self.open_and_enabled_to_observe=False
self.debug_flag = self.config['debug_mode']
self.admin_only_flag = self.config['admin_owner_commands_only']
if self.debug_flag:
self.debug_lapse_time = time.time() + self.config['debug_duration_sec']
g_dev['debug'] = True
else:
self.debug_lapse_time = 0.0
g_dev['debug'] = False
self.hostname = socket.gethostname()
if self.hostname in self.config["wema_hostname"]:
self.is_wema = True
else:
# This host is a client. What does this mean?? This IS wema code.
self.is_wema = False # This is a client.
self.wema_path = config["wema_path"]
g_dev["wema_write_share_path"] = self.wema_path
#self.site_path = self.wema_path # No longer used
# THIS IS JUST THE FIRST OF SOME DOMES
# NEED TO MAKE THIS A CONFIG ITEM
self.dome_offset = self.config['enclosure']['enclosure1']['dome_offset_in_degrees'] ### THIS IS PURELY FOR LCS
self.last_request = None
self.stopped = False
self.site_message = "-"
#self.site_mode = config['site_enclosures_default_mode']
self.device_types = config["wema_types"]
self.astro_events = wema_events.Events(self.config)
self.astro_events.compute_day_directory()
self.astro_events.calculate_events()
self.astro_events.display_events()
self.dome_check_timer=time.time()
self.dome_check_timer_period=5
self.wema_pid = os.getpid()
print("Fresh WEMA_PID: ", self.wema_pid)
self.update_config()
self.create_devices(config)
self.time_last_status = time.time() - 60 #forces early status on startup.
self.loud_status = False
self.blocks = None
self.projects = None
self.events_new = None
immed_time = time.time()
self.obs_time = immed_time
self.wema_start_time = immed_time
self.cool_down_latch = False
obs_win_begin, sunZ88Op, sunZ88Cl, ephem_now = self.astro_events.getSunEvents()
self.nightly_weather_report_complete = False
self.weather_report_run_timer=time.time()-3600
self.local_pytz_timezone=pytz.timezone(self.config['TZ_database_name'])
self.owm_active=config['OWM_active']
self.local_weather_active=config['local_weather_active']
self.enclosure_status_check_period=config['enclosure_status_check_period']
self.weather_status_check_period = config['weather_status_check_period']
self.safety_status_check_period = config['safety_status_check_period']
self.scan_requests_check_period = 4
self.wema_settings_upload_period = 10
self.error_fault_clear_timer=time.time()
# Timers rather than time.sleeps
self.enclosure_status_check_timer=time.time() - 2*self.enclosure_status_check_period
self.weather_status_check_timer = time.time() - 2*self.weather_status_check_period
self.safety_check_timer=time.time() - 2*self.safety_status_check_period
self.scan_requests_timer=time.time() -2 * self.scan_requests_check_period
self.wema_settings_upload_timer=time.time() -2 * self.wema_settings_upload_period
# This is a flag that enables or disables observing for all OBS in the WEMA.
self.observing_mode = 'active'
self.rain_limit_quiet=False
self.cloud_limit_quiet=False
self.humidity_limit_quiet=False
self.windspeed_limit_quiet=False
self.lightning_limit_quiet=False
self.temp_minus_dew_quiet=False
self.skytemp_limit_quiet=False
self.hightemp_limit_quiet=False
self.lowtemp_limit_quiet=False
if self.config['observing_conditions']['observing_conditions1']['driver'] == None:
self.ocn_exists=False
else:
self.ocn_exists=True
# This variable prevents the roof being called to open every loop...
self.enclosure_next_open_time = time.time()
# This keeps a track of how many times the roof has been open this evening
# Which is really a measure of how many times the enclosure has
# attempted to observe but been shut on....
# If it is too many, then it shuts down for the whole evening.
self.opens_this_evening = 0
self.local_weather_ok = None
self.weather_text_report = []
self.times_to_open = []
self.times_to_close = []
self.hourly_report_holder=[]
self.weather_report_open_at_start = False
self.nightly_reset_complete = False
self.keep_open_all_night = False
self.keep_closed_all_night = False
self.open_at_specific_utc = False
self.specific_utc_when_to_open = -1.0
self.manual_weather_hold_set = False
self.manual_weather_hold_duration = -1.0
self.wema_has_roof_control=config['wema_has_control_of_roof']
# Obs under WEMA guidance
self.obs_ids=self.config['obsp_ids']
self.morning_flats_finished=False
# This prevents commands from previous nights/runs suddenly running
# when wema.py is booted (has happened a bit!)
url_job = "https://jobs.photonranch.org/jobs/getnewjobs"
body = {"site": self.config['wema_name']}
try:
requests.request("POST", url_job, data=json.dumps(body), timeout=30, allow_redirects=False, headers=close_headers, stream=False).json()
except:
plog ("Connection glitch in getnewjobs")
plog(traceback.format_exc())
if not os.path.exists(self.wema_path):
os.makedirs(self.wema_path)
if not os.path.exists(self.wema_path + "ptr_night_shelf"):
os.makedirs(self.wema_path + "ptr_night_shelf")
self.wema_settings_shelf_filename = self.wema_path + "ptr_night_shelf/" + str(self.config['wema_name'])+"_wema_stored_settings"
#######################
# THIS AREA JUST GETS DELETED ONCE WE HAVE AN ONLINE ADJUSTABLE WEMA SETTINGS
# UNTIL THEN IT WILL LOAD THE VALUES FROM THE CONFIG
#######################
plog ("Loading limits from config: TO BE DEPRECATED ONCE WE HAVE AN ONLINE LIMIT SYSTEM")
try:
wema_settings_shelf = shelve.open(self.wema_settings_shelf_filename)
self.rain_limit_setting = self.config['rain_limit']
self.humidity_limit_setting = self.config['humidity_limit']
self.windspeed_limit_setting = self.config['windspeed_limit']
self.lightning_limit_setting = self.config['lightning_limit']
self.temp_minus_dew_setting = self.config['temperature_minus_dewpoint_limit']
self.sky_temp_limit_setting = self.config['sky_temperature_limit']
self.cloud_cover_limit_setting = self.config['cloud_cover_limit']
self.lowest_temperature_setting = self.config['lowest_ambient_temperature']
self.highest_temperature_setting = self.config['highest_ambient_temperature']
self.warning_rain_limit_setting = self.config['warning_rain_limit']
self.warning_humidity_limit_setting = self.config['warning_humidity_limit']
self.warning_windspeed_limit_setting = self.config['warning_windspeed_limit']
self.warning_lightning_limit_setting = self.config['warning_lightning_limit']
self.warning_temp_minus_dew_setting = self.config['warning_temperature_minus_dewpoint_limit']
self.warning_sky_temp_limit_setting = self.config['warning_sky_temperature_limit']
self.warning_cloud_cover_limit_setting = self.config['warning_cloud_cover_limit']
self.warning_lowest_temperature_setting = self.config['warning_lowest_ambient_temperature']
self.warning_highest_temperature_setting = self.config['warning_highest_ambient_temperature']
self.rain_limit_on = self.config['rain_limit_on']
self.humidity_limit_on = self.config['humidity_limit_on']
self.windspeed_limit_on = self.config['windspeed_limit_on']
self.lightning_limit_on = self.config['lightning_limit_on']
self.temp_minus_dew_on = self.config['temperature_minus_dewpoint_limit_on']
self.sky_temperature_limit_on = self.config['sky_temperature_limit_on']
self.cloud_cover_limit_on = self.config['cloud_cover_limit_on']
self.lowest_temperature_on = self.config['lowest_ambient_temperature_on']
self.highest_temperature_on = self.config['highest_ambient_temperature_on']
wema_settings_shelf['rain_limit_on'] = self.rain_limit_on
wema_settings_shelf['warning_rain_limit_setting'] = self.warning_rain_limit_setting
wema_settings_shelf['rain_limit_setting'] = self.rain_limit_setting
wema_settings_shelf['cloud_cover_limit_on'] = self.cloud_cover_limit_on
wema_settings_shelf['warning_cloud_cover_limit_setting'] = self.warning_cloud_cover_limit_setting
wema_settings_shelf['cloud_cover_limit_setting'] = self.cloud_cover_limit_setting
wema_settings_shelf['humidity_limit_on'] = self.humidity_limit_on
wema_settings_shelf['warning_humidity_limit_setting'] = self.warning_humidity_limit_setting
wema_settings_shelf['humidity_limit_setting'] = self.humidity_limit_setting
wema_settings_shelf['windspeed_limit_on'] = self.windspeed_limit_on
wema_settings_shelf['warning_windspeed_limit_setting'] = self.warning_windspeed_limit_setting
wema_settings_shelf['windspeed_limit_setting'] = self.windspeed_limit_setting
wema_settings_shelf['lightning_limit_on'] = self.lightning_limit_on
wema_settings_shelf['warning_lightning_limit_setting'] = self.warning_lightning_limit_setting
wema_settings_shelf['lightning_limit_setting'] = self.lightning_limit_setting
wema_settings_shelf['temp_minus_dew_on'] = self.temp_minus_dew_on
wema_settings_shelf['warning_temp_minus_dew_setting'] = self.warning_temp_minus_dew_setting
wema_settings_shelf['temp_minus_dew_setting'] = self.temp_minus_dew_setting
wema_settings_shelf['sky_temperature_limit_on'] = self.sky_temperature_limit_on
wema_settings_shelf['warning_sky_temp_limit_setting'] = self.warning_sky_temp_limit_setting
wema_settings_shelf['sky_temp_limit_setting'] = self.sky_temp_limit_setting
wema_settings_shelf['lowest_ambient_temperature'] = self.lowest_temperature_setting
wema_settings_shelf['highest_ambient_temperature'] = self.highest_temperature_setting
wema_settings_shelf['lowest_ambient_temperature_on'] = self.lowest_temperature_on
wema_settings_shelf['highest_ambient_temperature_on']= self.highest_temperature_on
wema_settings_shelf['hightemperature_limit_warning_level'] = self.warning_highest_temperature_setting
#status['wema_settings']['hightemperature_limit_danger_level'] = self.highest_temperature_setting
# status['wema_settings']['lowtemperature_limit_on'] = self.lowest_temperature_on
# status['wema_settings']['lowtemperature_limit_quiet'] = self.lowtemp_limit_quiet
wema_settings_shelf['lowtemperature_limit_warning_level'] = self.warning_lowest_temperature_setting
#pid = camShelf["pid_obs"] # a 9 character string
wema_settings_shelf.close()
except:
plog ("Startup shelf load failed.")
plog(traceback.format_exc())
plog ("passed startup shelf load")
#######################
# ^^^^^^^^^^^^^^ THIS AREA JUST GETS DELETED ONCE WE HAVE AN ONLINE ADJUSTABLE WEMA SETTINGS
# UNTIL THEN IT WILL LOAD THE VALUES FROM THE CONFIG
#######################
if os.path.exists(self.wema_settings_shelf_filename + '.dat'):
wema_settings_shelf = shelve.open(self.wema_settings_shelf_filename)
#print ("woo")
#print (wema_settings_shelf['local_weather_active'])
g_dev['enc'].mode =wema_settings_shelf['mode']
self.observing_mode=wema_settings_shelf['observing_mode']
self.local_weather_active=wema_settings_shelf['local_weather_active']
self.owm_active=wema_settings_shelf['owm_active']
self.keep_open_all_night=wema_settings_shelf['keep_open_all_night']
self.keep_closed_all_night=wema_settings_shelf['keep_closed_all_night']
if self.ocn_exists:
try:
self.rain_limit_on=wema_settings_shelf['rain_limit_on']
self.warning_rain_limit_setting=wema_settings_shelf['warning_rain_limit_setting']
self.rain_limit_setting=wema_settings_shelf['rain_limit_setting']
self.cloud_cover_limit_on=wema_settings_shelf['cloud_cover_limit_on']
self.warning_cloud_cover_limit_setting=wema_settings_shelf['warning_cloud_cover_limit_setting']
self.cloud_cover_limit_setting=wema_settings_shelf['cloud_cover_limit_setting']
self.humidity_limit_on=wema_settings_shelf['humidity_limit_on']
self.warning_humidity_limit_setting=wema_settings_shelf['warning_humidity_limit_setting']
self.humidity_limit_setting=wema_settings_shelf['humidity_limit_setting']
self.windspeed_limit_on=wema_settings_shelf['windspeed_limit_on']
self.warning_windspeed_limit_setting=wema_settings_shelf['warning_windspeed_limit_setting']
self.windspeed_limit_setting=wema_settings_shelf['windspeed_limit_setting']
self.lightning_limit_on=wema_settings_shelf['lightning_limit_on']
self.warning_lightning_limit_setting=wema_settings_shelf['warning_lightning_limit_setting']
self.lightning_limit_setting=wema_settings_shelf['lightning_limit_setting']
self.temp_minus_dew_on=wema_settings_shelf['temp_minus_dew_on']
self.warning_temp_minus_dew_setting=wema_settings_shelf['warning_temp_minus_dew_setting']
self.temp_minus_dew_setting=wema_settings_shelf['temp_minus_dew_setting']
self.sky_temperature_limit_on=wema_settings_shelf['sky_temperature_limit_on']
self.warning_sky_temp_limit_setting=wema_settings_shelf['warning_sky_temp_limit_setting']
self.sky_temp_limit_setting=wema_settings_shelf['sky_temp_limit_setting']
self.lowest_temperature_setting = wema_settings_shelf['lowest_ambient_temperature']
self.highest_temperature_setting = wema_settings_shelf['highest_ambient_temperature']
self.lowest_temperature_on = wema_settings_shelf['lowest_ambient_temperature_on']
self.highest_temperature_on = wema_settings_shelf['highest_ambient_temperature_on']
self.warning_highest_temperature_setting=wema_settings_shelf['highest_ambient_temperature_on']
#status['wema_settings']['hightemperature_limit_danger_level'] = self.highest_temperature_setting
# status['wema_settings']['lowtemperature_limit_on'] = self.lowest_temperature_on
# status['wema_settings']['lowtemperature_limit_quiet'] = self.lowtemp_limit_quiet
self.warning_lowest_temperature_setting=wema_settings_shelf['lowest_ambient_temperature_on']
except:
plog ("Probably has not formed a shelf yet, forming a shelf from the config.")
plog(traceback.format_exc())
self.rain_limit_setting = self.config['rain_limit']
self.humidity_limit_setting = self.config['humidity_limit']
self.windspeed_limit_setting = self.config['windspeed_limit']
self.lightning_limit_setting = self.config['lightning_limit']
self.temp_minus_dew_setting = self.config['temperature_minus_dewpoint_limit']
self.sky_temp_limit_setting = self.config['sky_temperature_limit']
self.cloud_cover_limit_setting = self.config['cloud_cover_limit']
self.lowest_temperature_setting = self.config['lowest_ambient_temperature']
self.highest_temperature_setting = self.config['highest_ambient_temperature']
self.warning_rain_limit_setting = self.config['warning_rain_limit']
self.warning_humidity_limit_setting = self.config['warning_humidity_limit']
self.warning_windspeed_limit_setting = self.config['warning_windspeed_limit']
self.warning_lightning_limit_setting = self.config['warning_lightning_limit']
self.warning_temp_minus_dew_setting = self.config['warning_temperature_minus_dewpoint_limit']
self.warning_sky_temp_limit_setting = self.config['warning_sky_temperature_limit']
self.warning_cloud_cover_limit_setting = self.config['warning_cloud_cover_limit']
self.warning_lowest_temperature_setting = self.config['warning_lowest_ambient_temperature']
self.warning_highest_temperature_setting = self.config['warning_highest_ambient_temperature']
self.rain_limit_on = self.config['rain_limit_on']
self.humidity_limit_on = self.config['humidity_limit_on']
self.windspeed_limit_on = self.config['windspeed_limit_on']
self.lightning_limit_on = self.config['lightning_limit_on']
self.temp_minus_dew_on = self.config['temperature_minus_dewpoint_limit_on']
self.sky_temperature_limit_on = self.config['sky_temperature_limit_on']
self.cloud_cover_limit_on = self.config['cloud_cover_limit_on']
self.lowest_temperature_on = self.config['lowest_ambient_temperature_on']
self.highest_temperature_on = self.config['highest_ambient_temperature_on']
# self.rain_limit_on=True
# self.warning_rain_limit_setting=1
# self.rain_limit_setting=3
# self.cloud_cover_limit_on=True
# self.warning_cloud_cover_limit_setting=25
# self.cloud_cover_limit_setting=50
# self.humidity_limit_on=True
# self.warning_humidity_limit_setting=75
# self.humidity_limit_setting=88
# self.windspeed_limit_on=True
# self.warning_windspeed_limit_setting=10
# self.windspeed_limit_setting=15
# self.lightning_limit_on=False
# self.warning_lightning_limit_setting=10
# self.lightning_limit_setting=15
# self.temp_minus_dew_on=False
# self.warning_temp_minus_dew_setting=2
# self.temp_minus_dew_setting=3
# self.sky_temperature_limit_on=False
# self.warning_sky_temp_limit_setting=-17
# self.sky_temp_limit_setting=-1
wema_settings_shelf['rain_limit_on'] = self.rain_limit_on
wema_settings_shelf['warning_rain_limit_setting'] = self.warning_rain_limit_setting
wema_settings_shelf['rain_limit_setting'] = self.rain_limit_setting
wema_settings_shelf['cloud_cover_limit_on'] = self.cloud_cover_limit_on
wema_settings_shelf['warning_cloud_cover_limit_setting'] = self.warning_cloud_cover_limit_setting
wema_settings_shelf['cloud_cover_limit_setting'] = self.cloud_cover_limit_setting
wema_settings_shelf['humidity_limit_on'] = self.humidity_limit_on
wema_settings_shelf['warning_humidity_limit_setting'] = self.warning_humidity_limit_setting
wema_settings_shelf['humidity_limit_setting'] = self.humidity_limit_setting
wema_settings_shelf['windspeed_limit_on'] = self.windspeed_limit_on
wema_settings_shelf['warning_windspeed_limit_setting'] = self.warning_windspeed_limit_setting
wema_settings_shelf['windspeed_limit_setting'] = self.windspeed_limit_setting
wema_settings_shelf['lightning_limit_on'] = self.lightning_limit_on
wema_settings_shelf['warning_lightning_limit_setting'] = self.warning_lightning_limit_setting
wema_settings_shelf['lightning_limit_setting'] = self.lightning_limit_setting
wema_settings_shelf['temp_minus_dew_on'] = self.temp_minus_dew_on
wema_settings_shelf['warning_temp_minus_dew_setting'] = self.warning_temp_minus_dew_setting
wema_settings_shelf['temp_minus_dew_setting'] = self.temp_minus_dew_setting
wema_settings_shelf['sky_temperature_limit_on'] = self.sky_temperature_limit_on
wema_settings_shelf['warning_sky_temp_limit_setting'] = self.warning_sky_temp_limit_setting
wema_settings_shelf['sky_temp_limit_setting'] = self.sky_temp_limit_setting
wema_settings_shelf['lowest_ambient_temperature'] = self.lowest_temperature_setting
wema_settings_shelf['highest_ambient_temperature'] = self.highest_temperature_setting
wema_settings_shelf['lowest_ambient_temperature_on'] = self.lowest_temperature_on
wema_settings_shelf['highest_ambient_temperature_on']= self.highest_temperature_on
wema_settings_shelf['hightemperature_limit_warning_level'] = self.warning_highest_temperature_setting
#status['wema_settings']['hightemperature_limit_danger_level'] = self.highest_temperature_setting
# status['wema_settings']['lowtemperature_limit_on'] = self.lowest_temperature_on
# status['wema_settings']['lowtemperature_limit_quiet'] = self.lowtemp_limit_quiet
wema_settings_shelf['lowtemperature_limit_warning_level'] = self.warning_lowest_temperature_setting
#pid = camShelf["pid_obs"] # a 9 character string
wema_settings_shelf.close()
self.update_status()
plog ("booted up and got status from ocn device")
# The LCS dome loses it's position if the wema code gets restarted.
# If the WEMA code is restarted while the shutter is open, it needs to rehome
# to figure out where it is.
if 'MaxDome' in g_dev['enc'].config['enclosure']['enclosure1']['driver']:
home_on_boot=True
enc_status=g_dev['enc'].get_status()
if enc_status is not None:
#breakpoint()
if enc_status['shutter_status'] in ['Open', 'Sim Open']:
if home_on_boot:
try:
g_dev['enc'].enclosure.FindHome()
while not g_dev['enc'].enclosure.AtHome:
plog ("Waiting for Home")
time.sleep(5)
g_dev['enc'].enclosure.SyncToAzimuth(self.config['enclosure']['enclosure1']['dome_home_azimuth']) # If shutter home at 194, then park at 100.
plog ("Successfully found Home. Ready to observe")
except:
plog(traceback.format_exc())
plog ("DOME COMMAND GLITCHED OUT.")
def create_devices(self, config: dict):
self.all_devices = {}
for (
dev_type
) in self.device_types: # This has been set up for wema to be ocn and enc.
self.all_devices[dev_type] = {}
devices_of_type = config.get(dev_type, {})
device_names = devices_of_type.keys()
if dev_type == "camera":
pass
for name in device_names:
driver = devices_of_type[name]["driver"]
if dev_type == "observing_conditions" and not self.config['observing_conditions']['observing_conditions1']['ocn_is_custom']:
device = ObservingConditions(
driver, name, self.config, self.astro_events
)
self.ocn_status_custom=False
elif dev_type == "observing_conditions" and self.config['observing_conditions']['observing_conditions1']['ocn_is_custom']:
device=None
self.ocn_status_custom=True
elif dev_type == "enclosure" and not self.config['enclosure']['enclosure1']['encl_is_custom']:
device = Enclosure(driver, name, self.config, self.astro_events)
self.enc_status_custom=False
elif dev_type == "enclosure" and self.config['enclosure']['enclosure1']['encl_is_custom']:
device=None
self.enc_status_custom=True
else:
print(f"Unknown device: {name}")
self.all_devices[dev_type][name] = device
print("Finished creating devices.")
def update_config(self):
"""Sends the config to AWS."""
uri = f"{self.config['wema_name']}/config/"
self.config["events"] = g_dev["events"]
response = self.api.authenticated_request("PUT", uri, self.config)
if response:
print("\n\nConfig uploaded successfully.")
def scan_requests(self):
"""
This can pick up owner/admin Shutdown and Automatic request but it
would need to be a custom api endpoint.
Not too many useful commands: Shutdown, Automatic, Immediate close,
BadWxSimulate event (ie a 15 min shutdown)
For a wema this can be used to capture commands to the wema once the
AWS side knows how to redirect from any mount/telescope to the common
Wema.
This should be changed to look into the site command queue to pick up
any commands directed at the Wx station, or if the agent is going to
always exist lets develop a seperate command queue for it.
NB NB NB should this be on some sort of timeout so that if AWS
connection goes away the code can deal with that case?
"""
url_job = "https://jobs.photonranch.org/jobs/getnewjobs"
body = {"site": self.config['wema_name']}
cmd = {}
# Get a list of new jobs to complete (this request
# marks the commands as "RECEIVED")
#plog ("scanning requests")
try:
unread_commands = requests.request(
"POST", url_job, data=json.dumps(body), timeout=20, allow_redirects=False, headers=close_headers, stream=False
).json()
except:
plog(traceback.format_exc())
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 'action' in cmd:
plog(cmd)
if cmd['action']=='open':
plog ("open enclosure command received")
self.open_enclosure({}, {}) #WER added missing dicts 10142023 WER
self.enclosure_status_check_timer=time.time() - 2*self.enclosure_status_check_period
self.update_status()
if cmd['action']=='close':
plog ("command enclosure command received")
self.park_enclosure_and_close()
self.enclosure_status_check_timer=time.time() - 2*self.enclosure_status_check_period
self.update_status()
if cmd['action']=='simulate_weather_hold':
plog("simulate weather hold button doesn't do anything yet")
if cmd['action']=='open_no_earlier_than_owm_plan':
plog("open no earlier than owm button doesn't do anything yet")
# Change in Enclosure mode
if cmd['action']=='set_enclosure_mode':
plog ("set enclosure mode command received")
g_dev['enc'].mode = cmd['required_params']['enclosure_mode']
self.enclosure_status_check_timer =time.time() - 2* self.enclosure_status_check_period
self.update_status()
if cmd['action']=='set_observing_mode':
plog ("set observing mode command received")
self.observing_mode=cmd['required_params']['observing_mode']
self.enclosure_status_check_timer =time.time() - 2* self.enclosure_status_check_period
self.update_status()
if cmd['action']=='configure_active_weather_report':
plog ("configure weather settings command received")
if cmd['required_params']["weather_type"] == 'local':
if cmd['required_params']["weather_type_value"] == 'on':
self.local_weather_active=True
if cmd['required_params']["weather_type_value"] == 'off':
self.local_weather_active=False
if cmd['required_params']["weather_type"] == 'owm':
if cmd['required_params']["weather_type_value"] == 'on':
self.owm_active=True
if cmd['required_params']["weather_type_value"] == 'off':
self.owm_active=False
self.wema_settings_upload_timer=time.time() -2 * self.wema_settings_upload_period
self.update_status()
if cmd['action']=='force_roof_state':
if cmd['required_params']["force_roof_state"] == 'open':
plog ("keep roof open all night command received")
self.keep_open_all_night = True
self.keep_closed_all_night = False
if cmd['required_params']["force_roof_state"] == 'closed':
plog ("keep roof closed all night command received")
self.keep_closed_all_night= True
self.keep_open_all_night = False
if cmd['required_params']["force_roof_state"] == 'auto':
plog ("Remove roof force command received")
self.keep_closed_all_night= False
self.keep_open_all_night = False
self.wema_settings_upload_timer=time.time() -2 * self.wema_settings_upload_period
self.update_status()
if cmd['action']=='set_weather_values':
tempval=cmd['required_params']['weather_values']
self.rain_limit_on='on' in tempval['rain']['status']
self.warning_rain_limit_setting=tempval['rain']['warning_level']
self.rain_limit_setting=tempval['rain']['danger_level']
self.cloud_cover_limit_on='on' in tempval['clouds']['status']
self.warning_cloud_cover_limit_setting=tempval['clouds']['warning_level']
self.cloud_cover_limit_setting=tempval['clouds']['danger_level']
self.humidity_limit_on='on' in tempval['humidity']['status']
self.warning_humidity_limit_setting=tempval['humidity']['warning_level']
self.humidity_limit_setting=tempval['humidity']['danger_level']
self.windspeed_limit_on='on' in tempval['windspeed']['status']
self.warning_windspeed_limit_setting=tempval['windspeed']['warning_level']
self.windspeed_limit_setting=tempval['windspeed']['danger_level']
self.lightning_limit_on='on' in tempval['lightning']['status']
self.warning_lightning_limit_setting=tempval['lightning']['warning_level']
self.lightning_limit_setting=tempval['lightning']['danger_level']
self.temp_minus_dew_on='on' in tempval['tempDew']['status']
self.warning_temp_minus_dew_setting=tempval['tempDew']['warning_level']
self.temp_minus_dew_setting=tempval['tempDew']['danger_level']
self.sky_temperature_limit_on='on' in tempval['skyTempLimit']['status']
self.warning_sky_temp_limit_setting=tempval['skyTempLimit']['warning_level']
self.sky_temp_limit_setting=tempval['skyTempLimit']['danger_level']
self.wema_settings_upload_timer=time.time() -2 * self.wema_settings_upload_period
self.update_status()
else:
plog ("orphanned command?")
plog(cmd)
# Open and store the settings in the wema settings shelf
wema_settings_shelf = shelve.open(self.wema_settings_shelf_filename)
wema_settings_shelf['mode']=g_dev['enc'].mode
wema_settings_shelf['observing_mode']=self.observing_mode
wema_settings_shelf['local_weather_active']=self.local_weather_active
wema_settings_shelf['owm_active']=self.owm_active
wema_settings_shelf['keep_open_all_night']=self.keep_open_all_night
wema_settings_shelf['keep_closed_all_night']=self.keep_closed_all_night
if self.ocn_exists:
wema_settings_shelf['rain_limit_on']=self.rain_limit_on
wema_settings_shelf['warning_rain_limit_setting']=self.warning_rain_limit_setting
wema_settings_shelf['rain_limit_setting']=self.rain_limit_setting
wema_settings_shelf['cloud_cover_limit_on']=self.cloud_cover_limit_on
wema_settings_shelf['warning_cloud_cover_limit_setting']=self.warning_cloud_cover_limit_setting
wema_settings_shelf['cloud_cover_limit_setting']=self.cloud_cover_limit_setting
wema_settings_shelf['humidity_limit_on']=self.humidity_limit_on
wema_settings_shelf['warning_humidity_limit_setting']=self.warning_humidity_limit_setting
wema_settings_shelf['humidity_limit_setting']=self.humidity_limit_setting
wema_settings_shelf['windspeed_limit_on']=self.windspeed_limit_on
wema_settings_shelf['warning_windspeed_limit_setting']=self.warning_windspeed_limit_setting
wema_settings_shelf['windspeed_limit_setting']=self.windspeed_limit_setting
wema_settings_shelf['lightning_limit_on']=self.lightning_limit_on
wema_settings_shelf['warning_lightning_limit_setting']=self.warning_lightning_limit_setting
wema_settings_shelf['lightning_limit_setting']=self.lightning_limit_setting
wema_settings_shelf['temp_minus_dew_on']=self.temp_minus_dew_on
wema_settings_shelf['warning_temp_minus_dew_setting']=self.warning_temp_minus_dew_setting
wema_settings_shelf['temp_minus_dew_setting']=self.temp_minus_dew_setting
wema_settings_shelf['sky_temperature_limit_on']=self.sky_temperature_limit_on
wema_settings_shelf['warning_sky_temp_limit_setting']=self.warning_sky_temp_limit_setting
wema_settings_shelf['sky_temp_limit_setting']=self.sky_temp_limit_setting
wema_settings_shelf['lowest_ambient_temperature'] = self.lowest_temperature_setting
wema_settings_shelf['highest_ambient_temperature'] = self.highest_temperature_setting
wema_settings_shelf['lowest_temperature_on'] = self.lowest_temperature_on
wema_settings_shelf['highest_temperature_on']= self.highest_temperature_on
wema_settings_shelf['hightemperature_limit_warning_level'] = self.warning_highest_temperature_setting
#status['wema_settings']['hightemperature_limit_danger_level'] = self.highest_temperature_setting
# status['wema_settings']['lowtemperature_limit_on'] = self.lowest_temperature_on
# status['wema_settings']['lowtemperature_limit_quiet'] = self.lowtemp_limit_quiet
wema_settings_shelf['lowtemperature_limit_warning_level'] = self.warning_lowest_temperature_setting
# status['wema_settings']['lowtemperature_limit_danger_level'] = self.lowest_temperature_setting
#pid = camShelf["pid_obs"] # a 9 character string
wema_settings_shelf.close()
except:
if 'Internal server error' in str(unread_commands):
plog("AWS server glitch reading unread_commands")
else:
plog(traceback.format_exc())
plog("unread commands")
plog(unread_commands)
plog("MF trying to find whats happening with this relatively rare bug!")
return
def update_status(self):
"""
Collect status from weather and enclosure devices and sends an
update to AWS. Each device class is responsible for implementing the
method 'get_status()', which returns a dictionary.
"""
enc_status = None
ocn_status = None
wema = self.config['wema_name']
sync_obs= self.config['obsp_ids'][0]
# For those domes not synced by ascom, check in with telescope
# pointing and rotate dome accordingly
# This needs a config item at some stage
# Only bother checking if the shutter is open
enc_status=g_dev['enc'].get_status()
if enc_status is not None:
#breakpoint()
if enc_status['shutter_status'] in ['Open', 'Sim Open']:
if 'MaxDome' in g_dev['enc'].config['enclosure']['enclosure1']['driver']:
if time.time() > (self.dome_check_timer + self.dome_check_timer_period):
print (time.time() - self.dome_check_timer)
self.dome_check_timer=time.time()
dome_at_scope=False
while not dome_at_scope:
#breakpoint()
try:
while g_dev['enc'].enclosure.Slewing:
plog("Waiting for dome to stop slewing")
#self.send_enclosure_status(self.enc_status, self.ocn_status)
time.sleep(0.25)
except:
plog(traceback.format_exc())
plog ("DOME COMMAND GLITCHED OUT.")
# Call out to aws to get current main scope pointing and ra and dec
uri_status = f"https://status.photonranch.org/status/{sync_obs}/device"
try:
#print ("Grabbing obs status")
main_obs_status=requests.get(uri_status, timeout=20, allow_redirects=False, headers=close_headers, stream=False)
#try:
#main_obs_status = func_timeout(10, requests.get, args=(uri_status,), kwargs={"timeout": 20, "allow_redirects": False, "headers": close_headers, "stream": False})
#except:
#print ("Got obs status")
obs_mount_name=list(main_obs_status.json()['status']['mount'].keys())[0]
obs_mount_status=main_obs_status.json()['status']['mount'][obs_mount_name]
# Where is scope currently pointing?
obs_mount_ra=obs_mount_status['right_ascension']['val']
obs_mount_dec=obs_mount_status['declination']['val']
# Figure out the implied azimuth for that ra and dec at this location
observation_time=Time.now()
sky_coord=SkyCoord(ra=obs_mount_ra*15*u.deg, dec=obs_mount_dec*u.deg)
# Convert to AltAz frame
altaz_frame = AltAz(obstime=observation_time, location=self.observer_location)
altaz_coords = sky_coord.transform_to(altaz_frame)
obs_current_altitude = altaz_coords.alt.deg
obs_current_azimuth = altaz_coords.az.deg
slave_directly_to_telescope_pointing=False
if slave_directly_to_telescope_pointing:
obs_mount_ra=obs_mount_status['right_ascension']['val']
obs_mount_dec=obs_mount_status['declination']['val']
# Figure out the implied azimuth for that ra and dec at this location
observation_time=Time.now()
sky_coord=SkyCoord(ra=obs_mount_ra*15*u.deg, dec=obs_mount_dec*u.deg)
# Convert to AltAz frame
altaz_frame = AltAz(obstime=observation_time, location=self.observer_location)
altaz_coords = sky_coord.transform_to(altaz_frame)
# Extract altitude and azimuth
#obs_altitude = altaz_coords.alt.deg
obs_target_azimuth = altaz_coords.az.deg
else:
obs_target_azimuth=obs_mount_dec=obs_mount_status['target_az']['val']
if obs_target_azimuth == -500:
#plog ("Target Azimuth for Scope not an actual skytarget, so not moving dome")