-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsendToLive.py
197 lines (169 loc) · 7.41 KB
/
sendToLive.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
# Copyright (C) Mark McIntyre
#
# python script to upload one event to a target bucket for live feeds
#
# to use this file to manually upload a file do
# python sendToLive.py cap_dir ff_name
#
import os
import sys
import Utils.BatchFFtoImage as bff
import shutil
import tempfile
import boto3
from uploadToArchive import readKeyFile, readIniFile
import logging
import RMS.ConfigReader as cr
import numpy as np
from RMS.Formats.FieldIntensities import readFieldIntensitiesBin
log = logging.getLogger("logger")
def getBlockBrightness(dirpath, filename):
filename = filename.replace('FF_', 'FS_')
filename = filename.replace('.fits', '_fieldsum.bin')
if not os.path.isfile(os.path.join(dirpath, filename)):
return {'max':99, 'avg':99, 'std':99, 'frNo':99}
frnos, intens = readFieldIntensitiesBin(dirpath, filename)
maxInten = max(intens)
avgInten = int(np.average(intens))
stdInten = int(np.std(intens))
idx = np.argwhere(intens == maxInten)[0][0]
maxFr = int(frnos[idx])
return {'max':maxInten, 'avg':avgInten, 'std':stdInten, 'frNo':maxFr}
def createXMLfile(tmpdir, cap_dir, dir_file, camloc, cfg):
camid = cfg.stationID
briInfo = getBlockBrightness(cap_dir, dir_file)
spls = dir_file.split('_')
camid = spls[1]
ymd = spls[2]
hms = spls[3]
millis = spls[4]
yr = ymd[:4]
mth = ymd[4:6]
dy = ymd[6:8]
hr = hms[:2]
mi = hms[2:4]
se = '{}.{}'.format(hms[4:6], millis)
xmlname = 'M' + ymd + '_' + hms + '_' + camloc + '_' + camid + '.xml'
fullxml = os.path.join(tmpdir, xmlname)
with open(fullxml, 'w') as ofl:
ofl.write('<?xml version="1.0" encoding="UTF-8" ?>\n')
ofl.write('<ufocapture_record version="215" ')
ofl.write('y="{:s}" mo="{:s}" d="{:s}" h="{:s}" m="{:s}" s="{:s}" '.format(yr, mth, dy, hr, mi, se))
ofl.write('trig="1" frames="68" lng="{:.4f}" lat="{:.4f}" alt="{:.1f}" '.format(cfg.longitude, cfg.latitude, cfg.elevation))
ofl.write('tz="0" u2="224" cx="{}" cy="{}" fps="{:.3f}" head="30" '.format(cfg.width, cfg.height, cfg.fps))
ofl.write('tail="30" diff="2" sipos="6" sisize="15" dlev="40" dsize="4" ')
ofl.write('lid="{:s}" observer="" sid="{:s}" cam="{:s}" lens="" cap="{}" '.format(camloc, camid, camid, dir_file))
ofl.write('comment="" interlace="1" bbf="0" dropframe="0">\n')
ofl.write(' <ufocapture_paths hit="3">\n')
# the three lines are max, average and stdev of frame brightnesses
ofl.write(' <uc_path fno="{}" ono="18" pixel="3" bmax="{}" x="395.7" y="282.3"></uc_path>\n'.format(briInfo['frNo'], briInfo['max']))
ofl.write(' <uc_path fno="{}" ono="18" pixel="9" bmax="{}" x="393.6" y="288.1"></uc_path>\n'.format(briInfo['frNo']+1, briInfo['avg']))
ofl.write(' <uc_path fno="{}" ono="18" pixel="16" bmax="{}" x="391.1" y="295.5"></uc_path>\n'.format(briInfo['frNo']+2, briInfo['std']))
ofl.write(' </ufocapture_paths>\n')
ofl.write('</ufocapture_record>\n')
return fullxml, xmlname
def createJpg(tmpdir, cap_dir, dir_file, camloc):
spls = dir_file.split('_')
camid = spls[1]
ymd = spls[2]
hms = spls[3]
shutil.copy2(os.path.join(cap_dir, dir_file), tmpdir)
try:
bff.batchFFtoImage(tmpdir, 'jpg', True)
except Exception:
bff.batchFFtoImage(tmpdir, 'jpg')
file_name, _ = os.path.splitext(dir_file)
ojpgname = file_name + '.jpg'
njpgname = 'M' + ymd + '_' + hms + '_' + camloc + '_' + camid + 'P.jpg'
fulljpg = os.path.join(tmpdir, njpgname)
if os.path.isfile(fulljpg):
os.remove(fulljpg)
os.rename(os.path.join(tmpdir, ojpgname), fulljpg)
return fulljpg, njpgname
def uploadOneEvent(cap_dir, dir_file, cfg, keys, camloc):
mdaconn = boto3.Session(aws_access_key_id=keys['AWS_ACCESS_KEY_ID'],
aws_secret_access_key=keys['AWS_SECRET_ACCESS_KEY'], region_name=keys['AWS_DEFAULT_REGION'])
s3mda = mdaconn.resource('s3')
mdabuck = keys['LIVEBUCKET'].replace('ukmon','ukmda')
tmpdir = tempfile.mkdtemp()
if not os.path.isfile(os.path.join(cap_dir, dir_file)):
retmsg = '{} not present in {}'.format(dir_file, cap_dir)
log.warning(retmsg)
return retmsg
fulljpg, njpgname = createJpg(tmpdir, cap_dir, dir_file, camloc)
fullxml, xmlname = createXMLfile(tmpdir, cap_dir, dir_file, camloc, cfg)
try:
s3mda.meta.client.upload_file(fulljpg, mdabuck, njpgname, ExtraArgs={'ContentType': 'image/jpeg'})
s3mda.meta.client.upload_file(fullxml, mdabuck, xmlname, ExtraArgs={'ContentType': 'application/xml'})
retmsg = 'upload of {} successful'.format(njpgname)
except Exception as e:
retmsg = 'unable to upload to {}'.format(mdabuck)
log.warning(retmsg)
log.info(e, exc_info=True)
sys.stdout.flush()
shutil.rmtree(tmpdir)
return retmsg
def testFeed(keys, cfg):
camid = cfg.stationID
with open('/tmp/test.txt', 'w') as f:
f.write('{}'.format(camid))
mdaconn = boto3.Session(aws_access_key_id=keys['AWS_ACCESS_KEY_ID'],
aws_secret_access_key=keys['AWS_SECRET_ACCESS_KEY'], region_name=keys['AWS_DEFAULT_REGION'])
s3mda = mdaconn.resource('s3')
mdabuck = keys['LIVEBUCKET'].replace('ukmon','ukmda')
try:
s3mda.meta.client.upload_file('/tmp/test.txt', mdabuck, 'test/{}_{}.txt'.format(keys['CAMLOC'], camid))
retmsg = 'test successful'
except Exception:
retmsg = 'unable to upload to {} - check key information'.format(mdabuck)
try:
os.remove('/tmp/test.txt')
except Exception:
pass
return retmsg
def singleUpload(cap_dir, dir_file):
"""This function is used to manually upload a single event.
It can also be used to test the connection - see note below.
To invoke this function, open a Terminal window and type
*python ../ukmon-pitools/sendToLive.py cap_dir file_to_send*
args:
cap_dir (str): capture dir
file_to_send (str): file to upload
Comments:
If both arguments are 'test' then a test file is uploaded and the status reported back.
"""
camloc = None
myloc = os.path.split(os.path.abspath(__file__))[0]
# get camera location from ini file
inifvals = readIniFile(os.path.join(myloc, 'ukmon.ini'))
if not inifvals:
log.warning('unable to open ini file')
return 'unable to open ini file'
camloc = inifvals['LOCATION']
try:
rmscfg = inifvals['RMSCFG']
except Exception:
rmscfg='~/source/RMS/.config'
if camloc == 'NOTCONFIGURED':
print('LOCATION not found in ini file, aborting')
return 'not configured'
# get credentials
keys = readKeyFile(os.path.join(myloc, 'live.key'), inifvals)
if not keys:
log.warning('unable to open keyfile')
return 'unable to open keyfile'
# read a few variables from the RMS config file
cfg = cr.parse(os.path.expanduser(rmscfg))
# configpath, configname = os.path.split(os.path.expanduser(rmscfg))
# cfg = cr.loadConfigFromDirectory(configname, configpath)
if cap_dir == 'test' and dir_file == 'test':
retmsg = testFeed(keys, cfg)
else:
retmsg = uploadOneEvent(cap_dir, dir_file, cfg, keys, camloc)
return retmsg
if __name__ == '__main__':
if len(sys.argv) < 3:
print('usage: python sendToLive.py capdir ffname')
exit(1)
retmsg = singleUpload(sys.argv[1], sys.argv[2])
print(retmsg)