-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauvstatus.py
executable file
·3724 lines (3198 loc) · 134 KB
/
auvstatus.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
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
'''
v 2.79 - WIP: adding indicator for Planktivore ROIs
v 2.78 - If vehicle is paused but a new command has been sent, show special icon
v 2.77 - DVL Error timeout after 6h. Drop weight gray if turned off
v 2.76 - Improved Water Leak location reporting
v 2.75 - Put Chiton/Ayeris indicator back on for Galene
v 2.74 - Support for docking ops - first working version
v 2.73 - Adding NeedCommsTimeProfileStation to the parsing
v 2.72 - Critical messages < 31 characters were sometimes not reported!
v 2.71 - Fixed bug parsing default timeout, etc, when mission is Run vs Loaded
v 2.70 - Moved next waypoint out of ImptMisc to its own mission-specific query
v 2.69 - Working on parsing one-waypoint missions in case of no Nav To entry
v 2.68 - Muting query timeout for average_current :^(
v 2.67 - Added Fore Aft Aux to water critical message
v 2.66 - Fixed copy/paste bug where OT triggers Paused event
v 2.65 - Removed old debugging code which made error in mission defaults
v 2.64 - Projected battery remaining shows days if > 5 days remaining
v 2.63 - Parsing powerOnly piscivore cam for ahi also
v 2.62 - Changed the way defaults and full mission names are retrieved
v 2.61 - Upped the mA expectation for piscivore
v 2.60 - Added Waterlinked to the list of potential DVLs, and Ahi DVL on = True
v 2.59 - Report piscivore powerOnly widget for daphne also
v 2.58 - Remove year from mission start time if not recovered
v 2.57 - Make mission name red if DEFAULT > 15 minutes
v 2.56 - Quieting the No dataProcessed message
v 2.55 - Properly come up paused after critical
v 2.54 - Smarter schedule parsing for upcoming missions
v 2.53 - Added age colors for argo battery and show ARGO battery when on shore
v 2.52 - Fixed integer timeout bug
v 2.51 - Fixed bug parsing Pause status when recent critical
v 2.50 - Show age of last good Argo Battery Record
v 2.49 - Show orange status for Piscivore cameras sending old data
v 2.48 - Updated battery to use 3 queries
v 2.47 - Implemented API-based retrieval of default values (lightly tested)
v 2.46 - Accounted for age of battery update in calculating Amps remaining
v 2.45 - YASD - Yet another speed definition ApproachSpeedNotFirstTime
v 2.44 - Added parsing of environmental critical
v 2.43 - Some light formatting
v 2.42 - If two GPS fixes are too close together (30 mins), get an older one
v 2.41 - Adding volt and amp battery threshold display
v 2.40 - Working on recovering dead reckon data
v 2.39 - Added piscivore camera debug info
v 2.38 - Increased URL timeout to 8s. Display version on widget
v 2.37 - Schedule is NOT paused upon boot-up or restart. Added mission default
v 2.36 - Added another overthreshold scenario (migrated to github)
v 2.35 - Make Next comm label red if more than an hour overdue
v 2.34 - Report piscivore cam amps instead of generic label
v 2.33 - Make Sat comm label red if last comm more than an hour overdue
v 2.32 - Don't pause schedule on ESP stop messages
v 2.31 - Adjusting range for piscivore camera current-to-status
v 2.3 - Added piscivore camera status widget
v 2.28 - If Critical since last schedule resume, then schedule = paused
v 2.27 - Add Schedule Pause indicator (untested)
v 2.26 - Maybe fixed a lastlines empty parsing bug around 431
v 2.25 - Added rudimentary camera indicator for Galene.
v 2.24 - Made station Lookup use 3 decimals.
v 2.24 - Added arrow for high-side/low-side GF.
v 2.23 - Lookup table for waypoint names in the Nav projection section
v 2.22 - Added dot for log age. Added [ASAP] to schedule. Extended sparkline.
v 2.21 - Added Argo battery status (low or OK)
v 2.20 - Added freshness label to the depth sparkline
v 2.19 - Use last 7 values to calculate current draw
v 2.18 - Added projection of hours remaining on battery
v 2.17 - Added new NeedComms syntax
v 2.16 - Dynamically adjust max depth for sparkline
v 2.15 - Improved retrieval of Depth Data for full record
v 2.14 - New style query for Depth Data. Changed GPS query to limit 2
v 2.13 - Reformatted and relocated sparkline
v 2.12 - In progress sparkline for depth
v 2.11 - Fixed data decoding from ASCII retrieve
v 2.1 - Updated to Python 3
v 2.03 - Fixed pontus-specific UBAT formatting
v 2.02 - Adding #sticky note functionality
v 2.01 - Missing variable initialization in recovered vehicle
v 2.0 - Implemented config file
v 1.96 - Starting to incorporate config file. Removed email function
v 1.95a - Implemented over threshold
v 1.94 - Added indicator for failure to communicate with CTD
v 1.93 - Added battery discharge rate meter indicator
v 1.92 - Added report for number of bad battery sticks
v 1.91 - In progress, Adding new Data parsing
v 1.9 - Fixed Navigating to Parsing
v 1.8 - Added Motor Lock Fault parsing
v 1.7 - Minor enhancements
v 1.6 - Updated needcomms parsing
v 1.5 - Updated default mission list
v 1.4 - Bumping version number after misc changes.
v 1.3 - Streamlined code so it doesn't download data for recovered vehicles
v 1.2 - making UBAT pontus-specific (move to svg["pontus"] for more vehicles)
v 1.1 - adding cart
v 1.0 - works for pontus
Usage: auvstatus.py -v pontus -r (see a summary of reports)
auvstatus.py -v pontus > pontusfile.svg (save svg display)
'''
import argparse
import sys
import time
import os
import urllib.request, urllib.error, urllib.parse
import json
import math
import re
from collections import deque
from LRAUV_svg import svgtext,svghead,svgpontus,svggalene,svgbadbattery,svgtail,svglabels,svgerror,svgerrorhead,svgwaterleak,svgstickynote,svgpiscivore,svg_planktivore # define the svg text?
from config_auv import servername, basefilepath
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
def get_options():
parser = argparse.ArgumentParser(usage = __doc__)
# parser.add_argument('infile', type = argparse.FileType('rU'), nargs='?',default = sys.stdin, help="output of vars_retrieve")
parser.add_argument("-b", "--DEBUG", action="store_true", help="Print debug info")
parser.add_argument("-r", "--report", action="store_true", help="print results")
parser.add_argument("-f", "--savefile", action="store_true", help="save to SVG named by vehicle at default location")
parser.add_argument("-v", "--vehicle", default="pontus" , help="specify vehicle")
parser.add_argument("--printhtml",action="store_true" , help="print auv.html web links")
parser.add_argument("-m", "--missions",action="store_true" , help="spit out mission defaults")
parser.add_argument("--newmissions",action="store_true" , help="test new mission defaults")
parser.add_argument("-a", "--anyway",action="store_true" , help="process even after recovery")
parser.add_argument("-i", "--inst",default="mbari" , help="choose the server (mbari or whoi)")
parser.add_argument("Args", nargs='*')
options = parser.parse_args()
return options
def unpackJSON(data):
if type(data) == type(b'x'):
data = data.decode('utf-8')
structured = json.loads(data)
# if DEBUG:
# print("### STRUCTURED:",structured, file=sys.stderr)
if 'result' in structured:
result = structured['result']
elif 'chartData' in structured:
result = structured['chartData']
else:
result = structured
return result
def runQuery(event="",limit="",name="",match="",timeafter="1234567890123"):
limit_str=""
if limit:
limit_str = "&limit={}".format(limit)
if match:
match = "&text.matches=" + match
if name:
name = "&name=" + name
if event:
event = "&eventTypes=" + event
'''send a generic query to the REST API. Extra parameters can be over packed into limit (2)'''
vehicle = VEHICLE
if not timeafter or int(timeafter) < 1234567890123:
timeafter="1234567890123"
BaseQuery = "https://{ser}/TethysDash/api/events?vehicles={v}{e}{n}{tm}{l}&from={t}"
URL = BaseQuery.format(ser=servername,v=vehicle,e=event,n=name,tm=match,l=limit_str,t=timeafter)
if DEBUG:
print("### QUERY:",URL, file=sys.stderr)
try:
connection = urllib.request.urlopen(URL,timeout=8)
if connection:
raw = connection.read()
structured = json.loads(raw)
connection.close()
result = structured['result']
else:
print("# Query timeout",URL, file=sys.stderr)
result = ''
return result
except urllib.error.HTTPError or ssl.SSLError:
if ssl.SSLError:
print("# QUERY TIMEOUT:",URL, file=sys.stderr)
else:
print("# FAILURE IN QUERY:",URL, file=sys.stderr)
handleURLerror()
return None
def runNewStyleQuery(api="",extrastring=""):
# example /events? or /data?
# https://okeanids.mbari.org/TethysDash/api/vconfig?vehicle=makai&gitTag=2020-07-18a&since=2020-07-21
# https://okeanids.mbari.org/TethysDash/api/deployments/last?vehicle=pontus
# https://okeanids.mbari.org/TethysDash/api/data?vehicle=pontus
if api:
apistring = "{a}?vehicle={v}".format(a=api,v=VEHICLE)
'''send a generic query to the REST API. Extra parameters can be over packed into limit (2)'''
NewBaseQuery = "https://{ser}/TethysDash/api/{apistring}{e}"
URL = NewBaseQuery.format(ser=servername,apistring=apistring,e=extrastring)
if DEBUG:
print("### NEW QUERY:",URL, file=sys.stderr)
try:
connection = urllib.request.urlopen(URL,timeout=8)
if connection:
datastream = connection.read()
result = unpackJSON(datastream)
else:
print("# Query timeout",URL, file=sys.stderr)
result = ''
return result
except urllib.error.HTTPError or ssl.SSLError:
if ssl.SSLError:
if DEBUG:
print("\n### HTTP ERROR:",URL, file=sys.stderr)
if not "PowerOnly" in URL and not "average_current" in URL and not "battery_voltage" in URL and not "battery_charge" in URL and not "data/depth" in URL:
print("# NEW QUERY TIMEOUT:",URL, file=sys.stderr)
handleURLerror()
else:
print("# FAILURE IN QUERY:",URL, file=sys.stderr)
handleURLerror()
return None
def getDeployment():
'''return start time for deployment'''
startTime = 0
try:
launchString = runQuery(event="launch",limit="1")
if launchString:
startTime = launchString[0]['unixTime']
if DEBUG:
print("# LAUNCH STRING:",launchString, file=sys.stderr)
except ssl.SSLError:
print("# DEPLOYMENT TIMEOUT",VEHICLE, file=sys.stderr)
return startTime
def getNewDeployment():
'''return start time for deployment and deploymentID. Starts too early!'''
startTime = 0
deployID = ""
try:
launchData = runNewStyleQuery(api="deployments/last")
if launchData:
startTime = launchData.get('startEvent',{}).get('unixTime',0)
deployID = launchData.get('deploymentId',"")
except ssl.SSLError:
print("# DEPLOYMENT TIMEOUT",VEHICLE, file=sys.stderr)
if DEBUG:
print("### DEPLOYMENT TIME:",startTime, file=sys.stderr)
print("### DEPLOYMENT ID:",deployID, file=sys.stderr)
print("### New Deploy String:",launchData, file=sys.stderr)
return startTime,deployID
def getRecovery(starttime):
launchString = runQuery(event="recover",limit="1",timeafter=starttime)
recover = False
if launchString:
recover = launchString[0]['unixTime']
return recover
def getPlugged(starttime):
launchString = runQuery(event="deploy",limit="1",timeafter=starttime)
plugged = False
if launchString:
plugged = launchString[0]['unixTime']
return plugged
def getGPS(starttime,mylimit="1"):
''' extract the most recent GPS entry'''
if DEBUG:
print("###\n### RUNNING GPS LIMIT 1 starttime:",starttime, file=sys.stderr)
qString = runQuery(event="gpsFix",limit=mylimit,timeafter=starttime)
retstring=""
if qString:
retstring = qString
return retstring
def getArgo(starttime,mylimit="1"):
''' extract the most recent GPS entry'''
if DEBUG:
print("###\n### RUNNING ARGO LIMIT 50 starttime:",starttime, file=sys.stderr)
qString = runQuery(event="argoReceive",limit=mylimit,timeafter=starttime)
retstring=""
if qString:
retstring = qString
return retstring
def getArgo50(starttime,mylimit="100"):
''' extract the most recent GPS entry'''
if DEBUG:
print("###\n### RUNNING ARGO LIMIT 50 starttime:",starttime, file=sys.stderr)
qString = runQuery(event="argoReceive",limit=mylimit,timeafter=starttime)
retstring=""
if qString:
retstring = qString
return retstring
def newGetOldGPS(starttime,mylimit="2"):
''' extract the most recent GPS entry'''
if DEBUG:
print("###\n### RUNNING NEW OLD GPS LIMIT 2 starttime:",starttime, file=sys.stderr)
qString = runQuery(event="gpsFix",limit=mylimit,timeafter=starttime)
retstring=""
if qString and len(qString) > 1:
# CHANGING FROM [1] to [-1] to allow getting older records
retstring = [qString[-1]]
if DEBUG:
print ("###\n### NEW OLD GPS:",retstring, file=sys.stderr)
return retstring
def getMissionDefaults():
'''https://okeanids.mbari.org/TethysDash/api/commands/script?path=Science/altitudeServo_approach_backseat_poweronly.tl'''
'''{"description":"Maximum duration of mission","name":"MissionTimeout","unit":"hour","value":"12"},{"description":"How often to surface for commumications","name":"NeedCommsTime","unit":"minute","value":"180"},'''
'''MBARI specific Utility script. Not routinely used.
SurfacingIntervalDuringListening
print standard defaults for the listed missions. some must have inheritance because it doesn't get them all'''
missions=["Science/profile_station","Science/sci2","Science/mbts_sci2","Transport/keepstation","Maintenance/ballast_and_trim","Transport/keepstation_3km","Transport/transit_3km","Science/spiral_cast"]
missions=["Science/mbts_sci2","Science/profile_station"]
for mission in missions:
URL = "https://{}/TethysDash/api/git/mission/{}.xml".format(servername,mission)
print("\n#===========================\n",mission, "\n", file=sys.stderr)
try:
connection = urllib.request.urlopen(URL,timeout=8)
if connection: # here?
raw = connection.read()
structured = json.loads(raw)
connection.close()
result = structured['result']
print(URL, file=sys.stderr)
try:
splitted = str(result).split("{")
for item in splitted:
print(item, file=sys.stderr)
except KeyError:
print("NA", file=sys.stderr)
except urllib.error.HTTPError:
print("# FAILED TO FIND MISSION",mission, file=sys.stderr)
def getNewMissionDefaults(missionn):
Speed = None
NCTime = None
TimeOut = None
Docked = False
"""NOTE: This mission name needs the suffix!"""
'''https://okeanids.mbari.org/TethysDash/api/commands/script?path=Science/altitudeServo_approach_backseat_poweronly.tl'''
'''{"description":"Maximum duration of mission","name":"MissionTimeout","unit":"hour","value":"12"},{"description":"How often to surface for commumications","name":"NeedCommsTime","unit":"minute","value":"180"},'''
missions=["Science/mbts_sci2.tl","Transport/keepstation.tl"]
# TEMPORARY FOR DEBUGGING
# missionn=missions[1]
URL = "https://{}/TethysDash/api/commands/script?path={}".format(servername,missionn)
if DEBUG:
print("\n#===========================\n",missionn, "\n", file=sys.stderr)
print("\n#===========================\n",URL, "\n", file=sys.stderr)
if missionn:
try:
connection = urllib.request.urlopen(URL,timeout=8)
if connection: # here?
raw = connection.read()
structured = json.loads(raw)
connection.close()
try:
result = structured['result']['scriptArgs']
except KeyError:
#print("\n#=Key Error in Mission Defaults=\n",missionn, VEHICLE,structured, "\n", file=sys.stderr)
result = structured['result']['inserts'][0]['scriptArgs']
# if DEBUG:
# print(result, file=sys.stderr)
for subfield in result:
sfn = subfield.get('name')
if "NeedCommsTime" in sfn:
'''needcomms expects minutes'''
NCTime = subfield.get('value',None)
if subfield.get('unit',0)=='hour':
NCTime = int(NCTime)*60
if DEBUG:
print("FOUND NEEDCOMMS TIME:",subfield, file=sys.stderr)
# Mission Timeout = DockedTime plus 5 mins
elif sfn=="DockedTime":
TimeOut = subfield.get('value',None)
Docked=True
if subfield.get('unit',0)=='minute':
TimeOut = int(TimeOut)/60
if DEBUG:
print("FOUND DOCKED TIME:", subfield, file=sys.stderr)
elif sfn=="MissionTimeout" and not Docked:
'''Timeout expects hours'''
TimeOut = subfield.get('value',None)
if subfield.get('unit',0)=='minute':
TimeOut = int(TimeOut)/60
if DEBUG:
print("FOUND MISSION TIMEOUT:", subfield, file=sys.stderr)
elif sfn=="Speed":
Speed = subfield.get('value',None)
if DEBUG:
print(f"FOUND SPEED IN NEW DEFAULTS {subfield}", file=sys.stderr)
# try:
# splitted = str(result).split("{")
# for item in splitted:
# print(item, file=sys.stderr)
# except KeyError:
# print("NA", file=sys.stderr)
if DEBUG:
print(NCTime,TimeOut,Speed, file=sys.stderr)
except urllib.error.HTTPError:
print("# FAILED TO FIND NEW MISSION",missionn, file=sys.stderr)
return NCTime,TimeOut,Speed,Docked
def getNotes(starttime):
'''get notes with #widget in the text'''
qString = runQuery(event="note",limit="10",timeafter=starttime)
# if DEBUG:
# print("# NOTESTRING FOUND",qString, file=sys.stderr)
retstring = ''
if qString:
retstring=qString
return retstring
def getCritical(starttime):
'''get critical entries, like drop weight'''
qString = runQuery(event="logCritical",limit="1000",timeafter=starttime)
retstring = ""
if qString:
retstring = qString
return retstring
def getCommands(starttime):
'''get commands which have been sent'''
qString = runQuery(event="command",limit="1000",timeafter=starttime)
retstring = ""
if qString:
retstring = qString
return retstring
def getFaults(starttime):
'''
Software Overcurrent Add swatch to thruster section?
LCB fault: Software Overcurrent
Hardware Overcurrent
On overcurrent errors, the component varies. Probably worth having a special indicator and report what is flagged
LCB Fault
2020-03-06T00:10:13.771Z,1583453413.771 [CBIT](CRITICAL): Communications Fault in component: RDI_Pathfinder
2020-03-06T00:09:26.051Z,1583453366.051 [RDI_Pathfinder](FAULT): DVL failed to acquire valid data within timeout.'''
qString = runQuery(event="logFault",limit="2000",timeafter=starttime)
retstring = ""
if qString:
retstring = qString
return retstring
def getImportant(starttime,inputname=""):
qString = runQuery(event="logImportant",name=inputname,limit="2000",timeafter=starttime)
retstring = ""
if qString:
retstring = qString
return retstring
def getCBIT(starttime):
'''may also hold some DVL info'''
qString = runQuery(name="CBIT",timeafter=starttime)
retstring = ""
if qString:
retstring = qString
return retstring
def getDrop(starttime):
qString = runQuery(name="DropWeight",limit="2000",timeafter=starttime)
retstring = ""
if qString:
retstring = qString
return retstring
def getComms(starttime):
qString = runQuery(event="sbdReceive",limit="2000",timeafter=starttime)
retstring = ""
if qString:
retstring = qString
if DEBUG:
print("# GETCOMMS\n#\nPrinting Comms SBD", len(retstring), file=sys.stderr)
# for rec in retstring:
# print >> sys.stderr, rec
return retstring
def getDataAsc(starttime,mission):
''' TODO: cache batteries for when there is a new log file
OR if you don't find it, rerun the Query with limit 2 and parse the second file
Entries from shore.asc use same deque "trick" to get values. get maybe 150 lines
2020-03-04T20:58:38.153Z,1583355518.153 Unknown==>platform_battery_charge=126.440002 Ah
2020-03-04T20:58:38.153Z,1583355518.153 Unknown==>platform_battery_voltage=14.332275 V
Split on '='
['2020-03-03T09:17:56.203Z,1583227076.203 Unknown', '', '>platform_battery_charge', '153.968887 Ah']
'''
'''https://okeanids.mbari.org/TethysDash/data/pontus/realtime/sbdlogs/2020/202003/20200303T074113/shore.csv
2020/202003/20200303T074113
With Ahi: 2023-10-25T01:52:45.597Z,1698198765.597 Unknown==>platform_battery_voltage=15.262939 V
look for platform_battery_charge or platform_battery_voltage
WetLabsUBAT.flow_rate=0.333607 l/s
'''
Bailout=False
DataURL='https://{ser}/TethysDash/data/{vehicle}/realtime/sbdlogs/{extrapath}/shore.asc'
volt = 0
amp = 0
volttime = 0
flowtime = 0
flow = 999
Tracking = []
TrackTime = []
allpaths =[]
NeedTracking = True
if DEBUG:
print("# Running Old Data query...")
record = runQuery(event="dataProcessed",limit="10",timeafter=starttime)
if record:
for checkpath in record:
if not (checkpath['path'] in allpaths):
allpaths.append(checkpath['path'])
if DEBUG:
print("# Found (allpaths) Data Path", allpaths,file=sys.stderr)
else:
if DEBUG:
print("# No dataProcessed Path found", file=sys.stderr)
return volt,amp,volttime,flow,flowtime,Tracking,TrackTime
#moving duplicate checking above
# if (len(allpaths) ==3): # get three most recent
# if allpaths[0]==allpaths[1]: # if first two are the same, drop second
# z=allpaths.pop(1)
# else: # otherwise drop last one
# z=allpaths.pop(2)
firstlast = 0
for pathpart in allpaths[:2]:
volt = 0
amp = 0
volttime=0
extrapath = pathpart
NewURL = DataURL.format(ser=servername,vehicle=VEHICLE,extrapath=extrapath)
if DEBUG:
print("# DATA ASC URL",NewURL, file=sys.stderr)
datacon = urllib.request.urlopen(NewURL,timeout=8)
content = datacon.read().decode('utf-8').splitlines()
# if DEBUG:
# print("# DATA content",content[:10], file=sys.stderr)
# pull last X lines from queue. This was causing problems on some missions so increased it
lastlines = list(deque(content))
#lastlines = list(deque(content))
lastlines.reverse() #in place
# if DEBUG:
# print("dimensions of lastlines",len(lastlines), file=sys.stderr)
# print("# Lastlines (reversed):",lastlines[0:10], file=sys.stderr)
# for li in lastlines:
# if "flow" in li:
# print("#",li, file=sys.stderr)
#
# if DEBUG:
# print("# Lastlines first):",lastlines[0], file=sys.stderr)
# trying to avoid parsing the same part twice
# THIS doesn't work even if the first entity is the same
if lastlines and (firstlast == lastlines[0]):
Bailout = True
lastlines=[]
break
elif lastlines:
firstlast = lastlines[0]
else: # not lastlines
Bailout = True
lastlines=[]
break
for nextline in lastlines:
# if DEBUG:
# print >> sys.stderr, "#Battery nextline:",nextline.rstrip()
if "platform_battery_" in nextline:
if not('BPC1' in nextline):
fields = nextline.split("=")
if (volt==0) and ("voltage" in nextline) and (VEHICLE!='ahi'):
if DEBUG:
print("# Found Data Battery Voltage",fields[2:], file=sys.stderr)
volt = float(fields[3].split(" ")[0])
# in seconds not MS
if amp == 0 and "charge" in nextline:
if DEBUG:
print("# Found Data Battery Charge",fields[2:], file=sys.stderr)
amp = float(fields[3].split(" ")[0])
volttime = int(float(fields[0].split(',')[1].split(" ")[0])*1000)
else:
# VEHICLE=='ahi' and "voltage" in nextline: # Use BPC1
fields = nextline.split('>')[1].split("=")
if (volt==0) and ("voltage" in nextline) and (VEHICLE=='ahi'):
if DEBUG:
print("\n# Found AHI Data Battery Voltage",fields, file=sys.stderr)
volt = float(fields[1].split(" ")[0])
volttime = int(float(nextline.split('>')[0].split(',')[1].split(" ")[0])*1000)
if VEHICLE == 'pontus':
''' Fault UBAT flow rate is below the specified threshold of 0.05 l/s. WetLabsUBAT'''
'''WetLabsUBAT.flow_rate=0.333607 l/s'''
if (flow == 999) and "WetLabsUBAT.flow_rate" in nextline:
if DEBUG:
print("# FLOWDATA",nextline.rstrip(), file=sys.stderr)
flowfields = nextline.split("=")
flow = int(1000 * float(flowfields[-1].split(" ")[0]))
flowtime = int(float(flowfields[0].split(',')[1].split(" ")[0])*1000)
if DEBUG:
print("# FLOWNUM",flow, file=sys.stderr)
if ("acoustic" in mission or "CircleSample" in mission) and NeedTracking:
'''2020-10-10T20:41:20.873Z,1602362480.873 Unknown-->Tracking.range_to_contact=389.093750 m'''
if len(Tracking) < 2:
if "Tracking.range" in nextline:
tfields = nextline.split("=")
trange = int(float(tfields[-1].split(" ")[0]))
ttime = int(float(tfields[0].split(',')[1].split(" ")[0])*1000)
if trange:
Tracking.append(trange)
TrackTime.append(ttime)
else:
NeedTracking = False
else:
NeedTracking = False
if (volt) and (amp) and (VEHICLE == 'pontus' and flow < 999) and (NeedTracking == False):
Bailout = True
break
if Bailout == True:
break
if DEBUG:
if len(TrackTime) > 1:
print("#> Complete tracking:",Tracking, TrackTime, elapsed(TrackTime[0] - now), file=sys.stderr)
return volt,amp,volttime,flow,flowtime,Tracking,TrackTime
def getNewUBATFlow(starttime):
'''Returns the most recent flow rate from the UBAT sensor'''
'''PowerOnly.component_avgCurrent_loadControl'''
'''https://okeanids.mbari.org/TethysDash/api/data/WetLabsUBAT.flow_rate?vehicle=pontus&from=0&maxlen=2'''
record = runNewStyleQuery(api="data/WetLabsUBAT.flow_rate",extrastring="&from=0&maxlen=1")
if record:
flow = record['values'][:]
flowtime = record['times'][:]
else:
flow=999
flowtime=""
return flow,flowtime
def ampToCat(val):
'''convert piscivore current draw to number of cameras'''
'''each camera draws 100, not 50, so upping ranges'''
'''Cameras now drawing 375 ma total. upping ranges again'''
cat = False
ival = int(val)
'''for piscivore, convert raw current to category'''
if ival <=30:
cat = 0
elif ival < 176:
cat = 1
elif ival > 390:
cat = 3
elif ival > 175:
cat = 2
return cat
def getNewPlanktivore(starttime):
'''https://okeanids.mbari.org/TethysDash/api/data/_.planktivore_HM_AvgRois?vehicle=ahi&maxlen=10&from=1701196801652
https://okeanids.mbari.org/TethysDash/api/data/_.ayeris_particle_counts?vehicle=galene&maxlen=10&from=1701196801652
_.ayeris_particle_counts=996.500000 count/s
{"name":"_.planktivore_HM_AvgRois","units":"count/s","values":[0.602051,0.0,0.301025,0.602051,0.0,0.0,0.301025,0.0,0.301025,0.0],"times":[1715273810966,1715273962095,1715273992123,1715274201341,1715274241384,1715274366502,1715274414547,1715274559677,1715274600716,1715274824916]}
2024-05-08T03:19:18.234Z,1715138358.234 Unknown-->_.planktivore_LM_AvgRois=2.650269 count/s
2024-05-08T03:19:39.255Z,1715138379.255 Unknown-->_.planktivore_HM_AvgRois=0.477119 count/s'''
nowcat=-999
origtime = False
nowpowtime = False
if DEBUG:
print(f"# Plank &maxlen=10&from={starttime}", file=sys.stderr)
record = runNewStyleQuery(api="data/_.planktivore_HM_AvgRois",extrastring=f"&maxlen=10&from={starttime}")
'''(-ago_cellcomms / (60*1000)) > (needcomms+60):'''
if record and nowcat < -998: #nowcat check not needed because no loop
nowcat = ampToCat(record['values'][-1])
nowpow = "{}".format(int(record['values'][-1])) + "ma"
nowpowtime = record['times'][-1]
# -1 to 15, 16-65, 66-125
agopowtime = now - nowpowtime
if (agopowtime / (60*1000)) > (needcomms+60):
nowpow="Too Old"
nowcat=5
if DEBUG:
print("# PowerOnly too old",elapsed(nowpowtime - now), file=sys.stderr)
for v,t in zip(record['values'][::-1],record['times'][::-1]):
tc = ampToCat(v)
if tc == nowcat:
nowpowtime = t
else:
break
if DEBUG:
print("# record",record['values'], file=sys.stderr)
# print("# ORIGTIME",elapsed(origtime - now), file=sys.stderr)
print("# FIRST TIME",elapsed(nowpowtime - now), file=sys.stderr)
else:
nowpow="PISC"
nowpowtime=False
return nowcat,nowpowtime,nowpow
def getNewCameraPower(starttime):
nowcat=-999
origtime = False
nowpowtime = False
'''Returns the most recent power consumption for the piscivore cameras'''
'''PowerOnly.component_avgCurrent_loadControl'''
'''https://okeanids.mbari.org/TethysDash/api/data/PowerOnly.component_avgCurrent_loadControl?vehicle=pontus
# updated to add extra string if values are not being reported?
https://okeanids.mbari.org/TethysDash/api/data/PowerOnly.component_avgCurrent_loadControl?vehicle=pontus&maxlen=10&from=1701196801652'''
if DEBUG:
print(f"# NewPowerOnly &maxlen=10&from={starttime}", file=sys.stderr)
record = runNewStyleQuery(api="data/PowerOnly.component_avgCurrent_loadControl",extrastring=f"&maxlen=10&from={starttime}")
'''(-ago_cellcomms / (60*1000)) > (needcomms+60):'''
if record and nowcat < -998: #nowcat check not needed because no loop
nowcat = ampToCat(record['values'][-1])
nowpow = "{}".format(int(record['values'][-1])) + "ma"
nowpowtime = record['times'][-1]
# -1 to 15, 16-65, 66-125
agopowtime = now - nowpowtime
if (agopowtime / (60*1000)) > (needcomms+60):
nowpow="Too Old"
nowcat=5
if DEBUG:
print("# PowerOnly too old",elapsed(nowpowtime - now), file=sys.stderr)
for v,t in zip(record['values'][::-1],record['times'][::-1]):
tc = ampToCat(v)
if tc == nowcat:
nowpowtime = t
else:
break
if DEBUG:
print("# record",record['values'], file=sys.stderr)
# print("# ORIGTIME",elapsed(origtime - now), file=sys.stderr)
print("# FIRST TIME",elapsed(nowpowtime - now), file=sys.stderr)
else:
nowpow="PISC"
nowpowtime=False
return nowcat,nowpowtime,nowpow
def getNewNavigating(missiontime):
recordlist = getImportant(missiontime)
StationLat = False
StationLon = False
ReachedWaypoint = False
NavigatingTo = False
WaypointName = "Waypoint"
myre = re.compile(r'WP ?([\d\.\-]+)[ ,]+([\d\.\-]+)')
wayre = re.compile(r'point: ?([\d\.\-]+)[ ,]+([\d\.\-]+)')
RawWaypoints={"C1" : "-121.847,36.797",
"M1" : "-122.022,36.750",
"M2" : "-122.375999,36.691",
"3km" : "-121.824326,36.806965",
"Sta.N" : "-121.9636,36.9026",
"Sta.S" : "-121.8934,36.6591",
"NEreal" : "-121.900002,36.919998",
"NE" : "-121.9,36.9"}
TruncatedWaypoints = {
"36.797,-121.847": "C1" ,
"36.797,-121.850": "C1 profile",
"36.750,-122.022": "M1" ,
"36.691,-122.376": "M2" ,
"36.807,-121.824": "3km" ,
"36.903,-121.964": "Sta.N" ,
"36.659,-121.893": "Sta.S" ,
"36.920,-121.900": "NE-b",
"36.900,-121.900": "NE",
"36.81,-121.98": "Lower Soquel",
"36.77,-121.89": "Krill Shelf",
"36.82,-121.86": "N. Spur",
"36.712,-122.187" : "MARS",
"36.722,-122.187" : "Canon 1N",
"36.713,-122.176" : "Canon 1E",
"36.704,-122.187" : "Canon 1S",
"36.713,-122.198" : "Canon 1W",
"36.731,-122.187" : "Canon 2N",
"36.713,-122.165" : "Canon 2E",
"36.695,-122.187" : "Canon 2S",
"36.713,-122.209" : "Canon 2W",
"36.87,-121.96" : "Upper Soquel",
"36.903,-121.113" : "Dock Site"
}
if DEBUG:
print(f"Parsing Waypoints for current mission",file=sys.stderr)
for Record in recordlist:
RecordText = Record.get("text","NA")
# This will only parse the most recent event in the queue between Reached or Nav
if not NavigatingTo and not ReachedWaypoint:
if RecordText.startswith("Navigating to") and not "box" in RecordText:
if DEBUG:
print("## Found Navigating To Event", RecordText, file=sys.stderr)
'''Navigating to waypoint: 36.750000,-122.022003'''
NavRes = wayre.search(RecordText.replace("arcdeg",""))
if NavRes:
textlat,textlon = NavRes.groups()
if textlat:
StationLat = float(textlat)
StationLon = float(textlon)
if DEBUG:
print("## Got LatLon from Navigating To", StationLat,StationLon, file=sys.stderr)
NavigatingTo = Record["unixTime"]
if RecordText.lower().startswith("reached waypoint"):
if DEBUG:
print("## Found Reached Event", RecordText, Record["unixTime"], file=sys.stderr)
waresult = wayre.search(RecordText)
if waresult:
textlat,textlon=waresult.groups()
if textlat:
StationLat = float(textlat)
StationLon = float(textlon)
if DEBUG:
print("## Got ReachedWaypoint", StationLat,StationLon, file=sys.stderr)
ReachedWaypoint = Record["unixTime"]
if StationLat:
LookupLL = f"{round(StationLat,3):.3f},{round(StationLon,3):.3f}"
if DEBUG:
print("## Looking up Station", LookupLL, file=sys.stderr)
WaypointName = TruncatedWaypoints.get(LookupLL,"Station.") # if not found, use "Station"
return StationLat, StationLon, ReachedWaypoint, WaypointName
def getNewNextWaypoint():
wpq = ""
'''https://okeanids.mbari.org/TethysDash/api/wp?vehicle=pontus
"result": {
"missionLatLonArgs": [
{
"name": "Lat",
"value": "36.806966"
},
{
"name": "Lon",
"value": "-121.824326"
}
],
"points": [
{
"lat": 36.903,
"lon": -122.113
}
],
'''
wpq = runNewStyleQuery(api="wp")
if DEBUG:
print("## QUERYING FOR WAYPOINTS", file=sys.stderr)
if not wpq:
return None,None
else:
wpr = wpq.get('points',None) # (get only First result of this)
# List will contain all the waypoints. Only use if there is only one.
if wpr and len(wpr)==1:
wp_lat = wpr[0].get('lat',None)
wp_lon = wpr[0].get('lon',None)
if DEBUG:
print(f"WAYPOINT LAT AND LON: {wpr} \n {wp_lat} {wp_lon}",file=sys.stderr)
return wp_lat,wp_lon
else:
return None,None
def getNewLatLon(starttime=1676609209829):
'''https://okeanids.mbari.org/TethysDash/api/data/depth?vehicle=pontus&maxlen=200
https://okeanids.mbari.org/TethysDash/api/data/depth?vehicle=triton&maxlen=2&from=1676609209829
'''
depthl = []
timed = []
choplat = []
choplon = []
chopt = []
maxdepthseconds = 480
# if we are constraining with a from statement
howlongago = int(now - 10+maxdepthseconds*60*1000)
rec_lat = runNewStyleQuery(api="data/latitude_fix",extrastring=f"&maxlen=400&from={starttime}")
rec_lon = runNewStyleQuery(api="data/longitude_fix",extrastring=f"&maxlen=400&from={starttime}")
# if DEBUG:
# print("# LATLON",rec_lat,rec_lon, file=sys.stderr)
if not rec_lat:
return choplat,choplon,False
latitudes = rec_lat['values'][:]
longitudes = rec_lon['values'][:]
millis = rec_lat['times'][:]
elapse_list = [elapsed(m - now) for m in millis]
from itertools import groupby
llist=[k for k, g in groupby(zip(latitudes,longitudes,millis,elapse_list))]
lat,lon,mill,elapse = zip(*llist)
# if DEBUG:
# for j in llist:
# print(j, file=sys.stderr)
bearinglist=[]
for i in range(len(llist)-1):
# deltadist,deltat,speedmadegood,bearing
# distance(site,gpstime,oldsite,oldgpstime)
bearinglist.append( (mill[i],) + distance( (lat[i+1],lon[i+1]),mill[i+1],(lat[i],lon[i]),mill[i]) )
# for z in bearinglist:
# print(z[0],z[3],z[4], file=sys.stderr)
# for k in cdd:
# print(f"{k};{cdd.get(k)}", file=sys.stderr)
# depthl = [-0.993011,0.102385,0.065651,0.117626,0.060571,0.105122,2.669861,17.237305,28.119141,31.023926,30.093750,29.107910,0.071512,0.076593,0.081284,0.126614,0.086754,0.059008,1.560425,40.828125,1.911346,20.146484,1.978973,40.566406,2.295471,40.296875,2.434631,40.497070,1.792938,40.433594,0.143028,0.074247,1.753479,40.653320,14.269775,1.691742,39.653320,1.316193,40.268555,1.810150,18.678711,17.157227,31.187012,30.313477,28.996582,0.170383,0.097305,0.067604,0.130524,0.091835,1.672180,39.883789,1.678436,40.720703,2.512756,3.323242,40.277344,1.808563,40.340820,3.286133,2.399048,12.588135,0.106293,0.089098,0.108639,1.649902,39.648438,10.620605,1.938721,30.812012,0.092224,0.044939,0.150452,0.158268,0.080893,0.059008,0.101604,0.103167,1.726135,40.442383,8.166504,1.699158,40.311523,2.993469,2.450623,34.390625,22.701172,0.234081,0.076202,1.844910,40.644531,34.384766,34.854492,27.496094,30.463867,30.583008,28.158691,0.100822,0.126614,0.150063,0.220406]
# millis = [1676497296190,1676497452506,1676497521881,1676497853558,1676497959418,1676497960217,1676498110631,1676498229806,1676498308178,1676498378481,1676498494060,1676500238921,1676500298712,1676500339930,1676500750518,1676501082201,1676501238954,1676501239366,1676501766221,1676501887410,1676502033260,1676502106414,1676502173458,1676502314893,1676502452638,1676502591218,1676502726162,1676502864738,1676503000918,1676503141900,1676503280473,1676503443286,1676503518242,1676503663286,1676503761056,1676503805098,1676503941247,1676504076986,1676504219634,1676504356158,1676504424433,1676504483023,1676504625626,1676504762994,1676506604327,1676506663304,1676506707348,1676507137945,1676507186970,1676507199997,1676507327348,1676507462698,1676507601282,1676507741872,1676507872787,1676507886522,1676508021049,1676508157225,1676508297401,1676508424267,1676508437599,1676508484061,1676508513148,1676508646066,1676508659573,1676508784502,1676508925910,1676509030133,1676509064074,1676509174778,1676509238600,1676509534745,1676510163866,1676510164308,1676510184145,1676510219290,1676510279217,1676510279612,1676510395234,1676510539487,1676510653418,1676510679673,1676510818271,1676510944323,1676510958462,1676511077685,1676511102317,1676511145158,1676511355273,1676511429762,1676511557810,1676511590196,1676511658837,1676511723883,1676511813189,1676513466133,1676513612535,1676513666698,1676513718046,1676513836238,1676513861722]
timed = [(x/1000)/60 for x in millis] # in minutes
nowmin = (now/1000)/60
fakedepth = 10
padded = False
if nowmin - max(timed) > 4:
timed = timed + [max(timed),max(timed)+2,nowmin]
depthl = depthl + [1,fakedepth,fakedepth]
padded = True
md = max(timed)
if (False): # TESTING
depthl = [1,1,10,10,50,50,100,100,150,150,200,200,250,250,150,150,25,25]
millis = [10,20,30,40,50,60,70,80,100,130,150,170,190,200,250,350,400,480]
timed = millis
# This list is now padded so the last 3 values are placeholders
if (md - min(timed) > maxdepthseconds-1):
chopt = [x for x in timed if md - x < maxdepthseconds]
chopd = depthl[-len(chopt):] # last n elements
else:
chopt = timed
chopd = depthl
# if DEBUG:
# for i in range(len(chopt)):
# print("# Chop",i,chopt[i],hours(60000*chopt[i]), file=sys.stderr)
return chopt,chopd,padded
def getNewROIs(starttime=1676609209829):
'''https://okeanids.mbari.org/TethysDash/api/data/_.planktivore_HM_AvgRois?vehicle=ahi&maxlen=20
https://okeanids.mbari.org/TethysDash/api/data/_.planktivore_LM_AvgRois?vehicle=ahi&maxlen=20
planktivore_HM_AvgRois'''
Ave_LM=-99
Ave_HM=-99
recent_LM=None
recent_HM=None
record_LM = runNewStyleQuery(api="data/_.planktivore_LM_AvgRois",extrastring=f"&maxlen=20&from={starttime}")
record_HM = runNewStyleQuery(api="data/_.planktivore_HM_AvgRois",extrastring=f"&maxlen=20&from={starttime}")
if record_LM:
roi_LM = record_LM['values'][:]
millis_LM = record_LM['times'][:]
Ave_LM = sum(roi_LM)/len(roi_LM)
recent_LM = millis_LM[-1]
old_LM = millis_LM[0]