-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwema.py
More file actions
3695 lines (2805 loc) · 190 KB
/
wema.py
File metadata and controls
3695 lines (2805 loc) · 190 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
"""
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
import csv
#from requests.auth import HTTPBasicAuth
from astropy.coordinates import EarthLocation, AltAz, SkyCoord, get_body
from astropy.time import Time
import astropy.units as u
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import copy
# from sentinelsat import SentinelAPI, read_geojson, geojson_to_wkt
# from datetime import date
# # Australian weather service
# from weather_au import api
#from func_timeout import func_timeout, FunctionTimedOut
import numpy as np
#import http.client
#http.client.HTTPConnection.debuglevel = 1
#logging.getLogger("urllib3").setLevel(logging.DEBUG)
#from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import pandas as pd
# import sys
# from scipy.fft import fft, ifft, fftfreq
# import numpy as np
# from scipy.signal import correlate
import seaborn as sns
#from sklearn.model_selection import train_test_split#,cross_val_predict, KFold
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import mean_squared_error, r2_score
#from sklearn.preprocessing import PolynomialFeatures
#import rasterio
close_headers = {
"Connection": "close" # Forces the server to close the connection after the response
}
import pytz
import datetime
from datetime import timezone
def fit_cloud_prediction_model(df, directory):
#directory = directory + '/weatherfits'
if not os.path.exists(directory):
os.makedirs(directory)
# daytime model
if not os.path.exists(directory + '/nighttime'):
os.makedirs(directory+ '/nighttime')
if not os.path.exists(directory + '/daytime'):
os.makedirs(directory+ '/daytime')
file_date_string = str(datetime.datetime.now()).replace(' ', '_').split('.')[0].replace(':', '-')
daytime_model=None
nighttime_model=None
# Manually add polynomial terms for specific features
df['sky-ambient^2'] = df['sky-ambient'] ** 2
features = ['sky_temp_C', 'sky-ambient', 'sky-ambient^2']#'phase_of_day', 'sky-ambient^2', 'sin_hour', 'cos_hour'] 'dew_point_depression',
for part_of_day in ['daytime','nighttime']:
region_df=copy.deepcopy(df)
if part_of_day == 'daytime':
region_df = region_df[(region_df['sun_altitude'] > 0) ].copy()
number_of_daytime_weather_observations=len(region_df)
else:
region_df = region_df[(region_df['sun_altitude'] < 0) ].copy()
number_of_nighttime_weather_observations=len(region_df)
# Trim the extreme values off... realistically MOST of the time it can be clear or cloudy
# and we even aren't too particularly interested in the extremes... more the range
# But only if there is enough observations within that range.
filtered_df = region_df[(region_df['avg_forecast_cloudcover'] >= 5) & (region_df['avg_forecast_cloudcover'] <= 95)].copy()
if len(filtered_df) >= 50:
region_df = filtered_df.copy() # apply the filter
# Only consider those values where all the forecasts tend to agree on it.
region_df['clouds_row_stdev'] = region_df[
['OWM_clouds', 'openmeteo_clouds',
'OWMClouds_inanhour', 'openmeteoclouds_inanhour',
'tomorrowio_nowclouds', 'tomorrowio_nexthourclouds',
'pirate_clouds_now', 'pirate_clouds_inanhour',
'metocean_clouds_now', 'metocean_clouds_inanhour',
'worldweather_clouds_now', 'worldweather_clouds_inanhour']
].std(axis=1).copy()
# Split the weather stuff into cloud ranges to apply threshholds
# Create masks for each range
try:
low_clouds = region_df['avg_forecast_cloudcover'].between(0, 20)
mid_clouds = region_df['avg_forecast_cloudcover'].between(20, 80)
high_clouds = region_df['avg_forecast_cloudcover'].between(80, 100)
# Compute thresholds
low_cloud_thresh = np.quantile(np.asarray(region_df.loc[low_clouds, 'clouds_row_stdev']), 0.2)
mid_cloud_thresh = np.quantile(np.asarray(region_df.loc[mid_clouds, 'clouds_row_stdev']), 0.2)
high_cloud_thresh = np.quantile(np.asarray(region_df.loc[high_clouds, 'clouds_row_stdev']), 0.2)
region_df = region_df[
(low_clouds & (region_df['clouds_row_stdev'] <= low_cloud_thresh)) |
(mid_clouds & (region_df['clouds_row_stdev'] <= mid_cloud_thresh)) |
(high_clouds & (region_df['clouds_row_stdev'] <= high_cloud_thresh))
].copy()
except:
plog ("failed at splitting dataset by cloud levels... usually we don't have good coverage yet.")
# 1) grab x and y
x = region_df['avg_forecast_cloudcover'].to_numpy()
y = region_df['sky_temp_C'].to_numpy()
# initial mask: everyone in
mask = np.ones_like(y, dtype=bool)
n_sigma = 2.0 # how many σ out to reject
max_iters = 5 # maximum number of cycles
for i in range(max_iters):
# 1) fit to the current inliers
slope, intercept = np.polyfit(x[mask], y[mask], 1)
# 2) compute residuals of all points to that fit
resid = y - (slope*x + intercept)
# 3) measure the scatter on the CURRENT inliers
sigma = np.std(resid[mask])
# 4) build a new mask
new_mask = np.abs(resid) <= n_sigma * sigma
# 5) if nothing changed, stop early
if new_mask.sum() == mask.sum():
break
mask = new_mask
# prepare your fit‐line for plotting
x_line = np.linspace(x.min(), x.max(), 200)
y_line = slope*x_line + intercept
plt.figure(figsize=(6,4))
plt.scatter(x[mask], y[mask], alpha=0.7, label='Inliers')
plt.scatter(x[~mask], y[~mask], color='red', alpha=0.7, label='Outliers')
plt.plot(x_line, y_line, color='black', linewidth=2, label=f'{n_sigma}σ fit')
plt.legend()
# plt.title('Sky Temperature vs Forecast Cloud Cover with Regression Line')
# plt.xlabel('Average Forecast Cloud Cover (%)')
# plt.ylabel('Sky Temperature (°C)')
# plt.savefig(directory + '/' + part_of_day + '/skytempvsclouds_' + str(file_date_string) + '.png', dpi=300, bbox_inches='tight')
# … set labels, title, save …
# plt.figure(figsize=(6, 4))
# sns.regplot(x='avg_forecast_cloudcover', y='sky_temp_C', data=region_df)
plt.title('Sky Temperature vs Forecast Cloud Cover with Regression Line')
plt.xlabel('Average Forecast Cloud Cover (%)')
plt.ylabel('Sky Temperature (°C)')
plt.savefig(directory + '/' + part_of_day + '/skytempvsclouds_' + str(file_date_string) + '.png', dpi=300, bbox_inches='tight')
# 1) grab x and y
x = region_df['avg_forecast_cloudcover'].to_numpy()
y = region_df['sky-ambient'].to_numpy()
# initial mask: everyone in
mask = np.ones_like(y, dtype=bool)
n_sigma = 2.0 # how many σ out to reject
max_iters = 5 # maximum number of cycles
for i in range(max_iters):
# 1) fit to the current inliers
slope, intercept = np.polyfit(x[mask], y[mask], 1)
# 2) compute residuals of all points to that fit
resid = y - (slope*x + intercept)
# 3) measure the scatter on the CURRENT inliers
sigma = np.std(resid[mask])
# 4) build a new mask
new_mask = np.abs(resid) <= n_sigma * sigma
# 5) if nothing changed, stop early
if new_mask.sum() == mask.sum():
break
mask = new_mask
# prepare your fit‐line for plotting
x_line = np.linspace(x.min(), x.max(), 200)
y_line = slope*x_line + intercept
plt.figure(figsize=(6,4))
plt.scatter(x[mask], y[mask], alpha=0.7, label='Inliers')
plt.scatter(x[~mask], y[~mask], color='red', alpha=0.7, label='Outliers')
plt.plot(x_line, y_line, color='black', linewidth=2, label=f'{n_sigma}σ fit')
plt.legend()
#sns.regplot(x='avg_forecast_cloudcover', y='sky-ambient', data=region_df)
plt.xlabel('Average Forecast Cloud Cover (%)')
plt.ylabel('Sky Temperature - Ambient Temperature (°C)')
plt.title('Sky - Ambient Temperature vs Forecast Cloud Cover')
plt.savefig(directory + '/' + part_of_day + '/skyminusambientvsclouds_' + str(file_date_string) + '.png', dpi=300, bbox_inches='tight')
# 1) grab x and y
x = region_df['avg_forecast_cloudcover'].to_numpy()
y = region_df['sky-ambient^2'].to_numpy()
# initial mask: everyone in
mask = np.ones_like(y, dtype=bool)
n_sigma = 2.0 # how many σ out to reject
max_iters = 5 # maximum number of cycles
for i in range(max_iters):
# 1) fit to the current inliers
slope, intercept = np.polyfit(x[mask], y[mask], 1)
# 2) compute residuals of all points to that fit
resid = y - (slope*x + intercept)
# 3) measure the scatter on the CURRENT inliers
sigma = np.std(resid[mask])
# 4) build a new mask
new_mask = np.abs(resid) <= n_sigma * sigma
# 5) if nothing changed, stop early
if new_mask.sum() == mask.sum():
break
mask = new_mask
# prepare your fit‐line for plotting
x_line = np.linspace(x.min(), x.max(), 200)
y_line = slope*x_line + intercept
plt.figure(figsize=(6,4))
plt.scatter(x[mask], y[mask], alpha=0.7, label='Inliers')
plt.scatter(x[~mask], y[~mask], color='red', alpha=0.7, label='Outliers')
plt.plot(x_line, y_line, color='black', linewidth=2, label=f'{n_sigma}σ fit')
plt.legend()
# plt.figure(figsize=(6, 4))
# sns.regplot(x='avg_forecast_cloudcover', y='sky-ambient^2', data=region_df)
plt.xlabel('Average Forecast Cloud Cover (%)')
plt.ylabel('Sky-Ambient^2 Temperature (°C)')
plt.title('Sky-Ambient^2 Temperature vs Forecast Cloud Cover')
plt.savefig(directory + '/' + part_of_day + '/skyminusambientsquaredvsclouds_' + str(file_date_string) + '.png', dpi=300, bbox_inches='tight')
# Now remove ALL these outliers from the actual model fit
def sigma_clip_mask(x, y, n_sigma=2.0, max_iters=5):
"""
Iterative σ–clipping mask: returns a boolean array (True=inlier).
"""
mask = np.ones_like(y, dtype=bool)
for _ in range(max_iters):
# fit only to current inliers
m, b = np.polyfit(x[mask], y[mask], 1)
resid = y - (m*x + b)
sigma = np.std(resid[mask])
new_mask = np.abs(resid) <= n_sigma*sigma
if new_mask.sum() == mask.sum():
break
mask = new_mask
return mask
# --- prepare x once ---
x = region_df['avg_forecast_cloudcover'].to_numpy()
# --- get masks for each y-series ---
m1 = sigma_clip_mask(x, region_df['sky_temp_C'].to_numpy())
m2 = sigma_clip_mask(x, region_df['sky-ambient'].to_numpy())
m3 = sigma_clip_mask(x, region_df['sky-ambient^2'].to_numpy())
# --- combine: only keep rows that are inliers in *all* three ---
keep = m1 & m2 & m3
# --- filter your original DataFrame ---
region_df = region_df.loc[keep].copy()
X = region_df[features].copy()
y = region_df['avg_forecast_cloudcover'].copy()
try:
### ✅ First Pass: Fit Model and Remove Outliers
gb_model = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, random_state=42)
gb_model.fit(X, y)
y_pred = gb_model.predict(X)
# Outlier rejection - First Pass
residuals = y - y_pred
mask = np.abs(residuals) <= 30 # Remove large outliers (> 30 units)
X = X[mask].copy()
y = y[mask].copy()
plog(f"First pass removed {len(residuals) - len(y)} outliers.")
### ✅ Second Pass: Refit Model and Remove Outliers Again
gb_model.fit(X, y)
y_pred = gb_model.predict(X)
residuals = y - y_pred
mask = np.abs(residuals) <= 30 # Remove outliers a second time
X = X[mask].copy()
y = y[mask].copy()
plog(f"Second pass removed {len(residuals) - len(y)} outliers.")
### ✅ Final Fit: Fit Model on Cleaned Data
gb_model.fit(X, y)
y_pred = gb_model.predict(X)
### ✅ Plot predicted vs actual values
plt.figure(figsize=(8, 6))
plt.scatter(y, y_pred, alpha=0.7, color='black', marker='o')
plt.plot([y.min(), y.max()], [y.min(), y.max()], '--', color='red')
plt.xlabel('Actual average weather report clouds')
plt.ylabel('Predicted average weather report clouds')
plt.title('Predicted vs Actual Clouds')
plt.savefig(directory + '/' + part_of_day + '/ActualVSPredicted_' + str(file_date_string) + '.png', dpi=300, bbox_inches='tight')
### ✅ Heatmap of correlation between factors
plt.figure(figsize=(8, 6))
sns.heatmap(pd.DataFrame(X).join(pd.Series(y, name='avg_forecast_cloudcover')).corr(), annot=True, cmap='coolwarm', fmt='.2f', linewidths=0.5)
plt.title('Correlation Heatmap')
plt.savefig(directory + '/' + part_of_day + '/Correlation_' + str(file_date_string) + '.png', dpi=300, bbox_inches='tight')
### ✅ Evaluate performance
mse = mean_squared_error(y, y_pred)
rmse = np.sqrt(mse)
r2 = r2_score(y, y_pred)
### ✅ plog performance metrics
plog (part_of_day)
plog(f"Mean Squared Error: {mse:.2f}")
plog(f"Root Mean Squared Error: {rmse:.2f}")
plog(f"R² Score: {r2:.2f}")
if part_of_day=='daytime':
daytime_model=copy.deepcopy(gb_model)
else:
nighttime_model=copy.deepcopy(gb_model)
### ✅ Save updated dataframe with predictions
region_df.loc[X.index, 'predicted_clouds'] = y_pred
region_df.to_csv(directory + '/' + part_of_day + '/WeatherData_' + str(file_date_string) + '.csv', index=False)
except:
plog("failed to do model?")
plog(traceback.format_exc())
return daytime_model, nighttime_model, number_of_daytime_weather_observations,number_of_nighttime_weather_observations
def correct_dome_azimuth(telescope_az, telescope_alt, side_of_pier, dome_radius, telescope_offset):#, dome_slit_offset=0):
"""
Corrects the dome azimuth based on telescope pointing and side of the pier.
Parameters:
telescope_az (float): Telescope azimuth in degrees (0-360).
telescope_alt (float): Telescope altitude in degrees (0-90).
side_of_pier (str): 'E' for East, 'W' for West.
dome_radius (float): Radius of the dome in meters.
telescope_offset (float): Lateral offset of the telescope from the dome center in meters.
dome_slit_offset (float, optional): Empirical offset to keep the telescope centered in the dome slit (default 0).
Returns:
float: Corrected dome azimuth in degrees (0-360).
"""
# Convert to radians for calculations
#az_rad = np.radians(telescope_az)
alt_rad = np.radians(telescope_alt)
# Compute the small offset angle due to the telescope offset inside the dome
if dome_radius > 0:
offset_angle = np.degrees(np.arctan2(telescope_offset * np.cos(alt_rad), dome_radius))
else:
offset_angle = 0 # Avoid division by zero
# Adjust azimuth based on the side of the pier
if side_of_pier.upper() == 'E':
dome_az = (telescope_az + offset_angle) % 360
elif side_of_pier.upper() == 'W':
dome_az = (telescope_az - offset_angle) % 360
else:
raise ValueError("side_of_pier must be 'E' or 'W'")
# # Apply an empirical dome slit offset
# dome_az = (dome_az + dome_slit_offset) % 360
return dome_az
# 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:
plog("Terminating: ", pid)
os.kill(pid, signal.SIGTERM)
except:
plog("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, status_type, 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 POST faults.
payload = {"statusType": str(status_type), "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:
plog(f"~ sent latest {status_type} status") # clearer success log including the type that was sent
else:
plog(f"Failed! Status code: {response.status_code}, Response: {response.text}")
except Exception as e:
plog(f"Request exception: {str(e)}")
class WxEncAgent:
"""A class for weather enclosure functionality."""
"""
Re-working ARO Weather 20231226 WER. Currently the Wema-attached external
n 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.name=name
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.opens_during_nighttime=self.config['opens_during_nighttime']
self.opens_during_daytime=self.config['opens_during_daytime']
# Load up the secrets and passwords
with open('secrets.txt', "r") as file:
secrets=json.load(file)
self.number_of_nighttime_weather_observations = 0 # Just initialising
self.smtp_server=secrets["smtp_server"]
self.smtp_port=secrets["smtp_port"]
self.sender_email=secrets["sender_email"]
self.email_password=secrets["email_password"]
self.owm_api_key=secrets["OWM_Key"]
self.tomorrowio_APIkey=secrets['tomorrowio_Key']
self.weather_to_emails=secrets["weather_to_emails"]
self.pirateapi_key=secrets["pirateapi_Key"]
self.metocean_apikey=secrets["metocean_key"]
self.worldweather_key=secrets["worldweather_key"]
self.daytime_cloud_model=None
self.nighttime_cloud_model=None
self.ocn_status=None
self.enc_status=None
self.current_owm_humidity=-1
self.current_owm_ambient_temperature=0
self.current_owm_dewpoint=0
self.cloud_tracker=[]
self.median_cloud_estimate=0
# 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
try:
self.dome_offset = self.config['enclosure']['enclosure1']['dome_offset_in_degrees'] ### THIS IS PURELY FOR LCS
except:
plog ("Couldn't load dome offset. mayhaps not a dome")
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()
plog("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.local_cloud_limit_quiet=False
self.forecast_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.sky_minus_ambient_limit_quiet=False
self.sky_temperature_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
self.owm_cloud_cover=None
self.open_meteo_cloud_cover=None
self.open_meteo_cloud_cover_next_hour=None
self.medianforecast_current_cloud_cover=None
self.tomorrowio_cloud_now=None
self.tomorrowio_cloud_inanhour=None
# 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_minus_ambient_limit_setting = self.config['sky_minus_ambient_limit']
self.sky_temperature_limit_setting = self.config['sky_temperature_limit']
self.local_cloud_cover_limit_setting = self.config['local_cloud_cover_limit']
self.forecast_cloud_cover_limit_setting = self.config['forecast_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_minus_ambient_limit_setting = self.config['warning_sky_minus_ambient_limit']
self.warning_sky_temperature_limit_setting = self.config['warning_sky_temperature_limit']
self.warning_local_cloud_cover_limit_setting = self.config['warning_local_cloud_cover_limit']
self.warning_forecast_cloud_cover_limit_setting = self.config['warning_forecast_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_minus_ambient_limit_on = self.config['sky_minus_ambient_limit_on']
self.sky_temperature_limit_on = self.config['sky_temperature_limit_on']
self.local_cloud_cover_limit_on = self.config['local_cloud_cover_limit_on']
self.forecast_cloud_cover_limit_on = self.config['forecast_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['local_cloud_cover_limit_on'] = self.local_cloud_cover_limit_on
wema_settings_shelf['forecast_cloud_cover_limit_on'] = self.forecast_cloud_cover_limit_on
wema_settings_shelf['warning_local_cloud_cover_limit_setting'] = self.warning_local_cloud_cover_limit_setting
wema_settings_shelf['warning_forecast_cloud_cover_limit_setting'] = self.warning_forecast_cloud_cover_limit_setting
wema_settings_shelf['local_cloud_cover_limit_setting'] = self.local_cloud_cover_limit_setting
wema_settings_shelf['forecast_cloud_cover_limit_setting'] = self.forecast_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_minus_ambient_limit_on'] = self.sky_minus_ambient_limit_on
wema_settings_shelf['warning_sky_minus_ambient_limit_setting'] = self.warning_sky_minus_ambient_limit_setting
wema_settings_shelf['sky_minus_ambient_limit_setting'] = self.sky_minus_ambient_limit_setting
wema_settings_shelf['sky_temperature_limit_on'] = self.sky_temperature_limit_on
wema_settings_shelf['warning_sky_temperature_limit_setting'] = self.warning_sky_temperature_limit_setting
wema_settings_shelf['sky_temperature_limit_setting'] = self.sky_temperature_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)
#plog ("woo")
#plog (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.local_cloud_cover_limit_on=wema_settings_shelf['local_cloud_cover_limit_on']
self.forecast_cloud_cover_limit_on=wema_settings_shelf['forecast_cloud_cover_limit_on']
self.warning_cloud_cover_limit_setting=wema_settings_shelf['warning_cloud_cover_limit_setting']
self.local_cloud_cover_limit_setting=wema_settings_shelf['local_cloud_cover_limit_setting']
self.forecast_cloud_cover_limit_setting=wema_settings_shelf['forecast_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_minus_ambient_limit_on=wema_settings_shelf['sky_minus_ambient_limit_on']
self.warning_sky_minus_ambient_limit_setting=wema_settings_shelf['warning_sky_minus_ambient_limit_setting']
self.sky_minus_ambient_limit_setting=wema_settings_shelf['sky_minus_ambient_limit_setting']
self.sky_temperature_limit_on=wema_settings_shelf['sky_temperature_limit_on']
self.warning_sky_temperature_limit_setting=wema_settings_shelf['warning_sky_temperature_limit_setting']
self.sky_temperature_limit_setting=wema_settings_shelf['sky_temperature_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_minus_ambient_limit_setting = self.config['sky_minus_ambient_limit']
self.sky_temperature_limit_setting = self.config['sky_temperature_limit']
self.local_cloud_cover_limit_setting = self.config['local_cloud_cover_limit']
self.forecast_cloud_cover_limit_setting = self.config['forecast_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_minus_ambient_limit_setting = self.config['warning_sky_minus_ambient_limit']
self.warning_sky_temperature_limit_setting = self.config['warning_sky_temperature_limit']
self.warning_local_cloud_cover_limit_setting = self.config['warning_local_cloud_cover_limit']
self.warning_forecast_cloud_cover_limit_setting = self.config['warning_forecast_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_minus_ambient_limit_on = self.config['sky_minus_ambient_limit_on']
self.sky_temperature_limit_on = self.config['sky_temperature_limit_on']
self.local_cloud_cover_limit_on = self.config['local_cloud_cover_limit_on']
self.forecast_cloud_cover_limit_on = self.config['forecast_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['local_cloud_cover_limit_on'] = self.local_cloud_cover_limit_on
wema_settings_shelf['forecast_cloud_cover_limit_on'] = self.forecast_cloud_cover_limit_on
wema_settings_shelf['warning_local_cloud_cover_limit_setting'] = self.warning_local_cloud_cover_limit_setting
wema_settings_shelf['warning_forecast_cloud_cover_limit_setting'] = self.warning_forecast_cloud_cover_limit_setting
wema_settings_shelf['local_cloud_cover_limit_setting'] = self.local_cloud_cover_limit_setting
wema_settings_shelf['forecast_cloud_cover_limit_setting'] = self.forecast_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_minus_ambient_limit_on'] = self.sky_minus_ambient_limit_on
wema_settings_shelf['warning_sky_minus_ambient_limit_setting'] = self.warning_sky_minus_ambient_limit_setting
wema_settings_shelf['sky_minus_ambient_limit_setting'] = self.sky_minus_ambient_limit_setting
wema_settings_shelf['sky_temperature_limit_on'] = self.sky_temperature_limit_on
wema_settings_shelf['warning_sky_temperature_limit_setting'] = self.warning_sky_temperature_limit_setting
wema_settings_shelf['sky_temperature_limit_setting'] = self.sky_temperature_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