-
Notifications
You must be signed in to change notification settings - Fork 11
/
AquariusUploadManager.py
2643 lines (2094 loc) · 113 KB
/
AquariusUploadManager.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
# All works in this code have been curated by ECCC and licensed under the GNU General Public License v3.0.
# Read more: https://www.gnu.org/licenses/gpl-3.0.en.html
from suds.client import Client
import suds
import datetime
#import pytz
from AquariusMiscUploadDialogs import *
from suds.xsd.doctor import Import, ImportDoctor
import xml.etree.ElementTree as ET
# import pdb
# from dateutil.tz import *
import re
import sys
# import dateutil.parser
dischargeSensors = {'QR' : 'm^3/s',
'LA' : 'km^2',
'HL' : 'm',
'HG' : 'm',
'IC' : '%',
'IO' : 'km',
'IE' : 'km',
'RiverSectionArea' : 'm^2',
'RiverSectionWidth' : 'm',
'WS' : 'ppt',
'SoundVel' : 'm/s',
'TW' : '\u00B0' + 'C',
'WV' : 'm/s',
}
stageSensors = {'HG' : 'm'}
environmentSensors = {'TA' : '\u00B0' + 'C',
'PA' : 'kPa',
'IO' : 'km',
'PN' : 'mm',
'SL' : 'kg',
'STR' : 'kg/s',
'SA' : '%',
'SD' : 'cm',
'UD' : 'deg',
'TW' : '\u00B0' + 'C',
'US' : 'km/hr'
}
stationhealthSensors = {'PA' : 'kPa',
'YBL' : 'V',
'InternalTemp' : '\u00B0' + 'C',
'N2BubbleRate' : 'B./min',
'YR' : 'W',
'YSS' : 'dBm',
'SolarPanelVoltage' : 'V',
'YP' : 'psi',
'VB' : 'V',
'YP2' : 'psi',
'TW' : '\u00B0' + 'C',
'TA' : '\u00B0' + 'C',
'PC' : 'mm',
'SW' : 'cm',
'YF' : 'W',
'PN' : 'mm',
'IO' : 'km',
'SL' : 'kg',
'STR' : 'kg/s',
'SA' : '%',
'SD' : 'cm',
'UD' : 'deg',
'RN' : 'W/m^2',
'HD' : 'm',
'PP' : 'mm'
}
# timeZones = {'PST' : datetime.timedelta(hours=0),
# 'MST' : datetime.timedelta(hours=0),
# 'CST' : datetime.timedelta(hours=0),
# 'EST' : datetime.timedelta(hours=0),
# 'AST' : datetime.timedelta(hours=0),
# 'NST' : datetime.timedelta(hours=0, minutes=0),
# 'UTC' : datetime.timedelta(hours=0)}
isoTail = ".000-00:00"
resultType = 0
resultType_NA = 0
resultType_RC = 1
resultType_TS = 2
resultType_All = 2147483647
storedUserName = ''
storedPassword = ''
# Attempt to log into AQ,
# If unable to log in, return error
# If able to log in, return Client
def AquariusLogin(mode, server, username, password):
try:
aq = Client('http://' + server + '/aquarius/AQAcquisitionService.svc?wsdl')
aq.set_options(headers={'AQAuthToken':aq.service.GetAuthToken(username, password)})
return True, aq
except suds.WebFault as e:
if mode == "DEBUG":
print(str(e))
return False, str(e)
#Check if the data already exist in the list by paramID
#return False if found the same paramID in the list given by the parameter 'list'
def FillInBlankDischarge(list, paramID):
if paramID in list:
return False
else:
return True
# Check if location exists (stationNum)
def AquariusCheckLocInfo(mode, aq, stationNum):
locid = aq.service.GetLocationId(stationNum)
locinf = aq.service.GetLocation(locid)
if mode == "DEBUG":
print(locinf)
if locinf is not None:
return True, locid
else:
return False, None
# Call AQ for Field Visit list
# Compare ALL Field Visits against given date
def AquariusFieldVisitExistsByDate(mode, aq, locid, fvDate):
fvDate = datetime.datetime.strptime(str(fvDate), "%Y/%m/%d")
if mode == "DEBUG":
print("Checking existance of Field Visit for given date")
#Find all field visits based on locid
fv = aq.service.GetFieldVisitsByLocation(locid)
if len(fv) < 1:
return None, None
#Parse field visit data as our own objects (SimpleFieldVisit)
disList = []
for i, visit in enumerate(fv[0]):
# if fv[0][i].Measurements is not None:
dt = datetime.datetime.strptime(str(visit.StartDate)[:19], "%Y-%m-%d %H:%M:%S")
if mode == "DEBUG":
print(dt)
print(str(dt.strftime("%Y/%m/%d")))
print(fvDate)
if dt.strftime("%Y/%m/%d") == fvDate.strftime("%Y/%m/%d"):
if visit.Measurements is not None:
for meas in visit.Measurements.FieldVisitMeasurement:
if "discharge" in meas.MeasurementType.lower():
disList.append(meas)
return visit, disList
## for i in range(len(date_list)):
# if fvDate.strftime("%Y/%m/%d") == date_list[i][0]:
# return date_list[i][1]
return 0, disList
# Return all the parameterID by given field visit
def GetParaIDByFV(discharge):
results = []
if discharge is None:
return None
if len(discharge) == 0:
return results
if discharge.Results is not None:
for mea in discharge.Results.FieldVisitResult:
results.append(mea.ParameterID)
return results
# Creates the Field Visit object and sends to AQ
def ExportToAquarius(mode, ver, EHSN, aq, FIELDVISIT, locid, discharge, levelNote, list, dischargeResult, server):
if mode == "DEBUG":
print("Saving Field Visit in Aquarius")
# try:
visit = CreateFieldVisitObject(mode, ver, aq, locid, EHSN, FIELDVISIT, discharge, levelNote, list, dischargeResult, server)
if mode == "DEBUG":
print("before field visit save")
print(visit)
try:
fieldV = aq.service.SaveFieldVisit(visit)
except Exception as e:
print(str(e))
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print((exc_type, fname, exc_tb.tb_lineno))
return -1
if mode == "DEBUG":
print(fieldV)
print("after field visit save")
return None
# Creates Field Visit object
# Calls each of 4 FVMeasurements (Disch, Stage, StationHealth, EnvConidtions)
# if discharge is false than discharge/area/velocity/mean gauge height will not be included
def CreateFieldVisitObject(mode, ver, aq, locid, EHSN, FIELDVISIT, discharge, levelNote, list, dischargeResult, server):
if FIELDVISIT == 0:
FIELDVISIT_ID = 0
else:
FIELDVISIT_ID = FIELDVISIT.FieldVisitID
src = "eHSN %s" % ver
if mode == "DEBUG":
print("Creating Field Visit")
tz = EHSN.genInfoManager.tzCmbo
#Convert to DateTime
start = datetime.datetime.strptime(str(EHSN.genInfoManager.datePicker), "%Y/%m/%d")
end = datetime.datetime.strptime(str(EHSN.genInfoManager.datePicker), "%Y/%m/%d")
startTime = None
endTime = None
#End Time
if EHSN.disMeasManager.GetEndTimeCtrl().IsCompleted():
endTime = EHSN.disMeasManager.gui.endTimeCtrl#.GetWxDateTime()
end = end.replace(hour=int(endTime.GetHourVal()), minute=int(endTime.GetMinuteVal()))
isoEnd = str(end.isoformat()) + isoTail
#Start time
if EHSN.disMeasManager.GetStartTimeCtrl().IsCompleted():
startTime = EHSN.disMeasManager.gui.startTimeCtrl#.GetWxDateTime()
##Here it assumes the date is the same day
start = start.replace(hour=int(startTime.GetHourVal()), minute=int(startTime.GetMinuteVal()))
isoStart = str(start.isoformat()) + isoTail
else:
startTime = EHSN.stageMeasManager.gui.GetFirstTime()
#Initialize time if it is none
if startTime is not None:
start = start.replace(hour=int(startTime.GetHourVal()), minute=int(startTime.GetMinuteVal()))
else:
# start time is null, so set the time to 0
start = start.replace(
hour = 0,
minute = 0,
second = 0,
microsecond = 0
)
if endTime is not None:
end = end.replace(hour=int(endTime.GetHourVal()), minute=int(endTime.GetMinuteVal()))
else:
# end time is null, so set the time to 0
end = end.replace(
hour = 0,
minute = 0,
second = 0,
microsecond = 0
)
fvStartDate = str(start.isoformat()) + isoTail
fvEndDate = str(end.isoformat()) + isoTail
isoStart = fvStartDate
isoEnd = fvEndDate
#==============================================================
dateInfo=start
#Create New Field Visit
visit = aq.factory.create("ns0:FieldVisit")
visit.LocationID = locid
visit.FieldVisitID = FIELDVISIT_ID
visit.StartDate = fvStartDate
visit.Party = EHSN.partyInfoManager.partyCtrl
visit.Remarks = ""
# visit.Remarks += "" if EHSN.instrDepManager.controlRemarksCtrl == "" else (EHSN.instrDepManager.controlRemarksCtrl + "\n")
# visit.Remarks += "" if EHSN.instrDepManager.dischRemarksCtrl == "" else (EHSN.instrDepManager.dischRemarksCtrl + "\n")
# visit.Remarks += EHSN.instrDepManager.genRemarksCtrl
visit.Remarks += "" if visit.Remarks == "" else "\n"
if FIELDVISIT_ID != 0:
visit.HistoryLog = FIELDVISIT.HistoryLog
if mode == "DEBUG":
print(FIELDVISIT.HistoryLog)
visit.Measurements = aq.factory.create("ns0:ArrayOfFieldVisitMeasurement")
visit.Measurements.FieldVisitMeasurement = []
#define measurement IDs
dMeas = 0
sMeas = 0
shMeas = 0
ecMeas = 0
lsMeas = 0
if str(EHSN.disMeasManager.mmtValTxt) == "" or str(EHSN.disMeasManager.mmtValTxt) is None:
if EHSN.stageMeasManager.CalculteMeanTime() != ":" and EHSN.stageMeasManager.CalculteMeanTime() != "0:0":
start = start.replace(hour=int(EHSN.stageMeasManager.GetFirstTime().GetHourVal()), minute=int(EHSN.stageMeasManager.GetFirstTime().GetMinuteVal()))
end = end.replace(hour=int(EHSN.stageMeasManager.GetLastTime().GetHourVal()), minute=int(EHSN.stageMeasManager.GetLastTime().GetMinuteVal()))
isoStart = str(start.isoformat()) + isoTail
isoEnd = str(end.isoformat()) + isoTail
if discharge:
EHSN.gui.deleteProgressDialog()
dmeasurement = CreateDischargeMeasurements(mode, src, aq, visit, dMeas, EHSN, dateInfo, isoStart, isoEnd, list, dischargeResult)
EHSN.gui.createProgressDialog("Uploading Field Visit to AQUARIUS", "Creating field visit to be uploaded to AQUARIUS")
else:
dmeasurement = None
smeasurement = CreateStageMeasurements(mode, src, aq, visit, sMeas, EHSN, dateInfo, fvStartDate, server)
shmeasurement = CreateStationHealthMeasurements(mode, src, aq, visit, shMeas, EHSN, dateInfo, fvStartDate)
ecmeasurement = CreateEnvironmentConditionsMeasurements(mode, src, aq, visit, ecMeas, EHSN, dateInfo, fvStartDate)
if levelNote:
lsmeasurement = CreateLevelSurveyMeasurements(mode, src, aq, visit, lsMeas, EHSN, dateInfo, server, fvStartDate)
else:
lsmeasurement = None
# Don't add the measurement if there was no results
if dmeasurement is not None:
visit.Measurements.FieldVisitMeasurement.append(dmeasurement)
if smeasurement is not None:
visit.Measurements.FieldVisitMeasurement.append(smeasurement)
if shmeasurement is not None:
visit.Measurements.FieldVisitMeasurement.append(shmeasurement)
if ecmeasurement is not None:
visit.Measurements.FieldVisitMeasurement.append(ecmeasurement)
if lsmeasurement is not None:
visit.Measurements.FieldVisitMeasurement.append(lsmeasurement)
if len(visit.Measurements.FieldVisitMeasurement) <= 0 and visit.Remarks == "":
raise ValueError("No valid measurements or remarks found. Cancelling upload.")
return visit
# Check values of eHSN to see if it will generate any errors on Field Visit creation
def CheckFVVals(mode, EHSN):
# #### DISCHARGE MEASUREMENTS CHECKS #### #
# discharge check
try:
if EHSN.disMeasManager.dischCtrl != "":
float(EHSN.disMeasManager.dischCtrl)
except ValueError:
raise ValueError("Discharge value: %s is not a float" % EHSN.disMeasManager.dischCtrl)
# mgh check
try:
if EHSN.disMeasManager.mghCtrl != "":
float(EHSN.disMeasManager.mghCtrl)
except ValueError:
raise ValueError("Mean Gauge Height: %s is not a float" % EHSN.disMeasManager.mghCtrl)
# river x area
try:
if EHSN.disMeasManager.areaCtrl != "":
float(EHSN.disMeasManager.areaCtrl)
except ValueError:
raise ValueError("Area: %s is not a float" % EHSN.disMeasManager.areaCtrl)
# water velocity
try:
if EHSN.disMeasManager.meanVelCtrl != "":
float(EHSN.disMeasManager.meanVelCtrl)
except ValueError:
raise ValueError("Water Velocity: %s is not a float" % EHSN.disMeasManager.meanVelCtrl)
# water temperature
try:
if EHSN.disMeasManager.waterTempCtrl != "":
float(EHSN.disMeasManager.waterTempCtrl)
except ValueError:
raise ValueError("Water Temp: %s is not a float" % EHSN.disMeasManager.waterTempCtrl)
# ###Stage Measurements###
for row in range(len(EHSN.stageMeasManager.timeValSizer.GetChildren())):
try:
if EHSN.stageMeasManager.GetHGVal(row) != "":
float(EHSN.stageMeasManager.GetHGVal(row))
except ValueError:
raise ValueError("Stage measurement: %s is not a float" % EHSN.stageMeasManager.GetHGVal(row))
try:
if EHSN.stageMeasManager.GetWLSubSizerLVal(row) != "":
float(EHSN.stageMeasManager.GetWLSubSizerLVal(row))
except ValueError:
raise ValueError("Stage measurement: %s is not a float" % EHSN.stageMeasManager.GetWLSubSizerLVal(row))
try:
if EHSN.stageMeasManager.GetWLSubSizerRVal(row) != "":
float(EHSN.stageMeasManager.GetWLSubSizerRVal(row))
except ValueError:
raise ValueError("Stage measurement: %s is not a float" % EHSN.stageMeasManager.GetWLSubSizerRVal(row))
# ###The rest###
# N2 Bubble rate
try:
if EHSN.envCondManager.bpmrotCtrl != "":
float(EHSN.envCondManager.bpmrotCtrl)
except ValueError:
raise ValueError("N2 bubble rate: %s is not float" % EHSN.envCondManager.bpmrotCtrl)
# battery voltage
try:
if EHSN.envCondManager.batteryCtrl != "":
float(EHSN.envCondManager.batteryCtrl)
except ValueError:
raise ValueError("Battery voltage: %s is not float" % EHSN.envCondManager.batteryCtrl)
# Air Temp
try:
if EHSN.disMeasManager.airTempCtrl != "":
float(EHSN.disMeasManager.airTempCtrl)
except ValueError:
raise ValueError("Air Temperature: %s is not float" % EHSN.disMeasManager.airTempCtrl)
# Wind veloc
try:
if EHSN.envCondManager.windMagCtrl != "":
float(EHSN.envCondManager.windMagCtrl)
except ValueError:
raise ValueError("Wind Velocity: %s is not float" % EHSN.envCondManager.windMagCtrl)
# Remaining sensor values
for index, sensorRefEntry in enumerate(EHSN.measResultsManager.sensorRefEntries):
# Is this a "valid" measurement result that can be uploaded to Aquarius?
if sensorRefEntry.GetValue().strip() in EHSN.measResultsManager.sensorRef:
try:
if EHSN.measResultsManager.observedVals[index].GetValue() != "":
float(EHSN.measResultsManager.observedVals[index].GetValue())
except ValueError:
raise ValueError("%s: %s is not float" % (sensorRefEntry.GetValue().strip(),
EHSN.measResultsManager.observedVals[index].GetValue()))
# HG and Water Level Reference cannot both be empty in a row
#if EHSN.stageMeasManager.emptyChecking():
# raise ValueError("Empty Stage measurement found")
if not EHSN.stageMeasManager.timeChecking():
raise ValueError("Invalid logger time found")
if not EHSN.measResultsManager.IsEmpty():
if EHSN.measResultsManager.timeCtrl == '00:00':
raise ValueError("Invalid sensor time found")
return True
# Escaping for spcial characters from xml
def repChar(str):
mlist = list(str)
nStr=""
for char in range(len(mlist)):
if(mlist[char] == '&'):
nStr += "<![CDATA[&]]>"
elif(mlist[char] == '<'):
nStr += "<![CDATA[<]]>"
elif(mlist[char] == '>'):
nStr += "<![CDATA[>]]>"
elif(mlist[char] == '\''):
nStr += "<![CDATA[']]>"
elif(mlist[char] == '\"'):
nStr += "<![CDATA[\"]]>"
else:
nStr += mlist[char]
return nStr
# Creates a FIeldVisitMeasurement with type WscFvtPlugin_ActivityTypeDischarge
def CreateDischargeMeasurements(mode, src, aq, visit, MEASUREMENT, EHSN, dateInfo, isoStart, isoEnd, list, dischargeResult):
if mode == "DEBUG":
print("Creating Discharge Measurements")
# Used to replace / modify existing Measurements
if MEASUREMENT == 0:
MEASUREMENT_ID = 0
else:
MEASUREMENT_ID = MEASUREMENT.MeasurementID
# Since we're not donig that, we just set to 0
# MEASUREMENT_ID = 0
hg = EHSN.stageMeasManager.MGHHG.strip()
hg2 = EHSN.stageMeasManager.MGHHG2.strip()
wl1 = EHSN.stageMeasManager.MGHWLRefL.strip()
wl2 = EHSN.stageMeasManager.MGHWLRefR.strip()
src1 = EHSN.stageMeasManager.SRCHG.strip()
src2= EHSN.stageMeasManager.SRCHG2.strip()
#Results
meanTime = str(EHSN.disMeasManager.mmtValTxt) if str(EHSN.disMeasManager.mmtValTxt) != '' else "00:00"
meanTime = datetime.datetime.strptime(meanTime, "%H:%M")
meanTime = meanTime.replace(dateInfo.year, dateInfo.month, dateInfo.day)
meanTime = str(meanTime.isoformat()) + isoTail
checkList = EHSN.instrDepManager.methodCBListBox.GetCheckedStrings()
method = "" if len(checkList) <= 0 else checkList[0]
if method != "" and EHSN.instrDepManager.deploymentCmbo != "":
method += "_" + EHSN.instrDepManager.deploymentCmbo
compassCali = "" if str(EHSN.instrDepManager.compassCaliCB) == "False" else str(EHSN.instrDepManager.compassCaliCB)
movingBedTest = str(EHSN.movingBoatMeasurementsManager.mbCmbo)+" Test" if EHSN.movingBoatMeasurementsManager.mbCmbo != "" else ""
cdataParty = repChar(visit.Party)
if dischargeResult is None:
dmeasurement = aq.factory.create("ns0:FieldVisitMeasurement")
dmeasurement.ApprovalLevelID = 3
dmeasurement.MeasurementID = MEASUREMENT_ID
dmeasurement.FieldVisitID = visit.FieldVisitID
dmeasurement.MeasurementType = "WscFvtPlugin_ActivityTypeDischarge"
dmeasurement.MeasurementTime = isoStart
dmeasurement.MeasurementEndTime = isoEnd
dmeasurement.LastModified = datetime.datetime(0o001, 0o1, 0o1)
# dischargeDetails = CreateDischargeDetails(EHSN)
if ('ADCP' in EHSN.instrDepManager.methodCBListBox.GetCheckedStrings() ) or ('ADCP' in EHSN.instrDepManager.instrumentCmbo):
dmeasurement.MeasurementDetails = """<?xml version="1.0" encoding="UTF-8"?>
<DiscreteMeasurementDetails xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ControlCondition>""" + str(EHSN.disMeasManager.controlConditionCmbo) + """</ControlCondition>
<Method>""" + method + """</Method>
<AdcpMeasurementDetails>
<Party>""" + cdataParty + """</Party>
<InstrumentType>""" + str(EHSN.instrDepManager.manufactureCmbo) + ' ' + str(EHSN.instrDepManager.modelCmbo) + ' ' + \
str(EHSN.instrDepManager.frequencyCmbo) + """</InstrumentType>
<TrackReference>""" + str(EHSN.movingBoatMeasurementsManager.trackRefCmbo) + """</TrackReference>
<Method>""" + method + """</Method>
<CompassCalibration>""" + compassCali + """</CompassCalibration>
<CompassError>""" + '' + """</CompassError>
<MovingBedTest>""" + movingBedTest + """</MovingBedTest>
<MovingBedCorrection>""" + str(EHSN.movingBoatMeasurementsManager.mbCorrAppCtrl) + """</MovingBedCorrection>
<SoftwareAndVersion>""" + str(EHSN.instrDepManager.softwareCtrl) + """</SoftwareAndVersion>
<FirmwareVersion>""" + str(EHSN.instrDepManager.firmwareCmbo) + """</FirmwareVersion>
<SerialNumber>""" + str(EHSN.instrDepManager.serialCmbo) + """</SerialNumber>
<ControlCondition>""" + EHSN.disMeasManager.controlConditionCmbo + """</ControlCondition>
</AdcpMeasurementDetails> </DiscreteMeasurementDetails>"""
elif 'ADV' in EHSN.instrDepManager.instrumentCmbo:
dmeasurement.MeasurementDetails = """<?xml version="1.0" encoding="UTF-8"?>
<DiscreteMeasurementDetails xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ControlCondition>""" + str(EHSN.disMeasManager.controlConditionCmbo) + """</ControlCondition>
<Method>""" + method + """</Method>
<AdcpMeasurementDetails>
<Party>""" + cdataParty + """</Party>
<InstrumentType>""" + str(EHSN.instrDepManager.manufactureCmbo) + ' ' + str(EHSN.instrDepManager.modelCmbo) + """</InstrumentType>
<TrackReference>""" + str(EHSN.movingBoatMeasurementsManager.trackRefCmbo) + """</TrackReference>
<Method>""" + method + """</Method>
<CompassCalibration>""" + compassCali + """</CompassCalibration>
<CompassError>""" + '' + """</CompassError>
<MovingBedTest>""" + movingBedTest + """</MovingBedTest>
<MovingBedCorrection>""" + str(EHSN.movingBoatMeasurementsManager.mbCorrAppCtrl) + """</MovingBedCorrection>
<SoftwareAndVersion>""" + str(EHSN.instrDepManager.softwareCtrl) + """</SoftwareAndVersion>
<FirmwareVersion>""" + str(EHSN.instrDepManager.firmwareCmbo) + """</FirmwareVersion>
<SerialNumber>""" + str(EHSN.instrDepManager.serialCmbo) + """</SerialNumber>
<ControlCondition>""" + str(EHSN.disMeasManager.controlConditionCmbo) + """</ControlCondition>
</AdcpMeasurementDetails>
</DiscreteMeasurementDetails>"""
else:
dmeasurement.MeasurementDetails = """<?xml version="1.0" encoding="UTF-8"?>
<DiscreteMeasurementDetails xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ControlCondition>""" + str(EHSN.disMeasManager.controlConditionCmbo) + """</ControlCondition>
<Method>""" + method + """</Method>
<AdcpMeasurementDetails>
<Party>""" + cdataParty + """</Party>
<InstrumentType>""" + str(EHSN.instrDepManager.modelCmbo) + """</InstrumentType>
<TrackReference>""" + str(EHSN.movingBoatMeasurementsManager.trackRefCmbo) + """</TrackReference>
<Method>""" + method + """</Method>
<CompassCalibration>""" + compassCali + """</CompassCalibration>
<CompassError>""" + '' + """</CompassError>
<MovingBedTest>""" + movingBedTest + """</MovingBedTest>
<MovingBedCorrection>""" + str(EHSN.movingBoatMeasurementsManager.mbCorrAppCtrl) + """</MovingBedCorrection>
<SoftwareAndVersion>""" + str(EHSN.instrDepManager.softwareCtrl) + """</SoftwareAndVersion>
<FirmwareVersion>""" + str(EHSN.instrDepManager.firmwareCmbo) + """</FirmwareVersion>
<SerialNumber>""" + str(EHSN.instrDepManager.serialCmbo) + """</SerialNumber>
<ControlCondition>""" + str(EHSN.disMeasManager.controlConditionCmbo) + """</ControlCondition>
</AdcpMeasurementDetails>
</DiscreteMeasurementDetails>"""
dmeasurement.Remarks = ""
asd = EHSN.disMeasManager.dischCombo.strip()
if EHSN.disMeasManager.dischCombo.strip() != "":
dmeasurement.Remarks = "Discharge Grade: " + EHSN.disMeasManager.dischCombo.strip() + "\n"
if EHSN.disMeasManager.dischRemarksCtrl.strip() != "":
dmeasurement.Remarks += "Discharge Remarks: " + EHSN.disMeasManager.dischRemarksCtrl.strip() + "\n"
if EHSN.disMeasManager.ControlConditionRemarksCtrl.strip() != "":
dmeasurement.Remarks += ("Control Condition Remarks: " + EHSN.disMeasManager.ControlConditionRemarksCtrl.strip() + "\n")
dmeasurement.Remarks += ("Depth Ref: " + EHSN.movingBoatMeasurementsManager.depthRefCmbo) if EHSN.movingBoatMeasurementsManager.depthRefCmbo != "" else ""
if 0 in EHSN.instrDepManager.methodCBListBox.GetCheckedItems():
if EHSN.movingBoatMeasurementsManager.velocityTopCombo != "" or \
EHSN.movingBoatMeasurementsManager.velocityBottomCombo != "" or \
EHSN.movingBoatMeasurementsManager.velocityExponentCtrl != "":
dmeasurement.Remarks += "\n" if dmeasurement.Remarks != "" else ""
dmeasurement.Remarks += ("Extrapolation: \n\tTop: " + EHSN.movingBoatMeasurementsManager.velocityTopCombo + "; Bottom: " + EHSN.movingBoatMeasurementsManager.velocityBottomCombo + "; Exponent: " + EHSN.movingBoatMeasurementsManager.velocityExponentCtrl)
dmeasurement.Remarks += ("\n% Difference in Q from extrap: " + EHSN.movingBoatMeasurementsManager.differenceCtrl) if EHSN.movingBoatMeasurementsManager.differenceCtrl != "" else ""
if EHSN.instrDepManager.gaugeCtrl != '':
dmeasurement.Remarks += "\n" if dmeasurement.Remarks != "" else ""
dmeasurement.Remarks += EHSN.instrDepManager.gaugeCtrl + " "
dmeasurement.Remarks += "metres " if EHSN.instrDepManager.lengthRadButBox == 0 else "kilometres "
dmeasurement.Remarks += "above " if EHSN.instrDepManager.posRadButBox == 0 else "below "
dmeasurement.Remarks += EHSN.instrDepManager.selectedGauge
dmeasurement.Results = aq.factory.create("ns0:ArrayOfFieldVisitResult")
dmeasurement.Results.FieldVisitResult = []
else:
dmeasurement = dischargeResult
start = datetime.datetime.strptime(isoStart, "%Y-%m-%dT%H:%M:%S.000-00:00")
end = datetime.datetime.strptime(isoEnd, "%Y-%m-%dT%H:%M:%S.000-00:00")
dmeasurement.MeasurementTime = dmeasurement.MeasurementTime.strftime("%Y-%m-%dT%H:%M:%S.000-00:00") if dmeasurement.MeasurementTime < start else\
isoStart
dmeasurement.MeasurementEndTime = dmeasurement.MeasurementEndTime.strftime("%Y-%m-%dT%H:%M:%S.000-00:00") if dmeasurement.MeasurementEndTime \
> end else\
isoEnd
start = datetime.datetime.strptime(dmeasurement.MeasurementTime, "%Y-%m-%dT%H:%M:%S.000-00:00")
end = datetime.datetime.strptime(dmeasurement.MeasurementEndTime, "%Y-%m-%dT%H:%M:%S.000-00:00")
df = start + ((end - start) / 2)
meanTime = df.strftime("%Y-%m-%dT%H:%M:%S.000-00:00")
if dmeasurement.Results is None:
dmeasurement.Results = aq.factory.create("ns0:ArrayOfFieldVisitResult")
dmeasurement.Results.FieldVisitResult = []
#Mean Gauge Height
# if str(EHSN.disMeasManager.mghCtrl).strip() != "":
if str(EHSN.disMeasManager.mghCtrl).strip() != "" and str(EHSN.disMeasManager.mghCmbo).strip() != "":
# eMGH = float(EHSN.disMeasManager.mghCtrl)
ParamID = 'HG'
# If we found the mgh in the field visit, then we ask and the user will choose
# If we could not find the mgh in the field visit, then we add automatically
mghFound = False
# Make mgh, only add if we should
mghResult = aq.factory.create("ns0:FieldVisitResult")
mghResult.MeasurementID = dmeasurement.MeasurementID
mghResult.ResultID = 0
# mghResult.BenchmarkOrRefPointName = None
# mghResult.EndTime = None
mghResult.StartTime = meanTime
# mghResult.PercentUncertainty = None
# mghResult.Qualifier = None
# mghResult.QualityCodeID = None
# mghResult.Remarks = None
mghResult.ParameterID = ParamID
mghResult.UnitID = dischargeSensors[ParamID]
mghCmbo = EHSN.disMeasManager.GetMghCmbo()
selection = mghCmbo.GetSelection()
if selection == 1:
eMGH = float(src1) + float(hg)
dmeasurement.Remarks += "\nMGH has had sensor reset applied at upload (" + hg + " + " + src1 + ")"
gaugeCorrection = EHSN.stageMeasManager.GCHG
elif selection == 2:
eMGH = float(src2) + float(hg2)
dmeasurement.Remarks += "\nMGH has had sensor reset applied at upload (" + hg2 + " + " + src2 + ")"
gaugeCorrection = EHSN.stageMeasManager.GCHG2
elif selection == 3:
eMGH = float(wl1)
gaugeCorrection = EHSN.stageMeasManager.GCWLRefL
elif selection == 4:
eMGH = float(wl2)
gaugeCorrection = EHSN.stageMeasManager.GCWLRefR
emptyTestList = [hg != '', hg2 != '', wl1 != '', wl2 != '']
i = iter(emptyTestList)
##################################For use of pop up message, let user choose if there are more then one MGH############
# #only one has value
# if (any(i) and not any(i)):
# if hg != '':
# if src1 != '':
# eMGH = float(src1) + float(hg)
# dmeasurement.Remarks += "\nMGH has had sensor reset applied at upload (" + hg + " + " + src1 + ")"
# else:
# eMGH = float(hg)
# gaugeCorrection = EHSN.stageMeasManager.GCHG
# elif hg2 != '':
# if src2 != '':
# eMGH = float(src2) + float(hg2)
# dmeasurement.Remarks += "\nMGH has had sensor reset applied at upload (" + hg2 + " + " + src2 + ")"
# else:
# eMGH = float(hg2)
# gaugeCorrection = EHSN.stageMeasManager.GCHG2
# elif wl1 != '':
# eMGH = float(wl1)
# gaugeCorrection = EHSN.stageMeasManager.GCWLRefL
# elif wl2 != '':
# eMGH = float(wl2)
# gaugeCorrection = EHSN.stageMeasManager.GCWLRefR
# #if only have hg values, uploading value from hg
# elif wl1 == '' and wl2 == '':
# if src1 != '':
# eMGH = float(src1) + float(hg)
# dmeasurement.Remarks += "\nMGH has had sensor reset applied at upload (" + hg + " + " + src1 + ")"
# else:
# eMGH = float(hg)
# gaugeCorrection = EHSN.stageMeasManager.GCHG
# #if they have the same value except the empty then shoulf follow the priority wl1 > wl2 > hg > hg2
# #if wl1 is not empty and all value are the same
# elif wl1 != '' and (wl2 == wl1 or wl2 == '') and (hg == wl1 or hg == '') and (hg2 == wl1 or hg2 == ''):
# eMGH = float(wl1)
# gaugeCorrection = EHSN.stageMeasManager.GCWLRefL
# #if wl2 is not empty and all value are the same
# elif wl2 != '' and (wl1 == wl2 or wl1 == '') and (hg == wl2 or hg == '') and (hg2 == wl2 or hg2 == ''):
# eMGH = float(wl2)
# gaugeCorrection = EHSN.stageMeasManager.GCWLRefR
# #if hg is not empty and all value are the same
# elif hg != '' and (wl1 == hg or wl1 == '') and (wl2 == hg or wl2 == '') and (hg2 == hg or hg2 == ''):
# if src1 != '':
# eMGH = float(src1) + float(hg)
# dmeasurement.Remarks += "\nMGH has had sensor reset applied at upload (" + hg + " + " + src1 + ")"
# else:
# eMGH = float(hg)
# gaugeCorrection = EHSN.stageMeasManager.GCHG
# # #if hg2 is not empty and all value are the same
# # elif hg2 != '' and (wl1 == hg2 or wl1 == '') and (wl2 == hg2 or wl2 == '') and (hg == hg2 or hg == ''):
# # if src2 != '':
# # eMGH = float(src2) + float(hg2)
# # dmeasurement.Remarks += "\nMGH has had sensor reset applied at upload (" + hg2 + " + " + src2 + ")"
# # else:
# # eMGH = float(hg2)
# # gaugeCorrection = EHSN.stageMeasManager.GCHG2
# #case to leave the selection for the user
# else:
# AMD = DuplicateMGHUpload(EHSN.gui.mode, emptyTestList[0], emptyTestList[1], emptyTestList[2], emptyTestList[3], parent=EHSN.gui.aquariusUploadDialog, title="Upload Field Visit to Aquarius")
# re = AMD.ShowModal()
# if re == ID_HG:
# if src1 != '':
# eMGH = float(src1) + float(hg)
# dmeasurement.Remarks += "\nMGH has had sensor reset applied at upload (" + hg + " + " + src1 + ")"
# else:
# eMGH = float(hg)
# gaugeCorrection = EHSN.stageMeasManager.GCHG
# elif re == ID_HG2:
# if src2 != '':
# eMGH = float(src2) + float(hg2)
# dmeasurement.Remarks += "\nMGH has had sensor reset applied at upload (" + hg2 + " + " + src2 + ")"
# else:
# eMGH = float(hg2)
# gaugeCorrection = EHSN.stageMeasManager.GCHG2
# elif re == ID_WL1:
# eMGH = float(wl1)
# gaugeCorrection = EHSN.stageMeasManager.GCWLRefL
# elif re == ID_WL2:
# eMGH = float(wl2)
# gaugeCorrection = EHSN.stageMeasManager.GCWLRefR
# else:
# eMGH = 0
# AMD.Destroy()
######################################################################################################
# mghResult.ObservedResult = float(EHSN.disMeasManager.mghCtrl)
mghResult.ObservedResult = eMGH
mghResult.Correction = 0.000 if gaugeCorrection == '' else float(gaugeCorrection)
mghResult.ResultType = resultType_RC
mghResult.ResultDetails = r"""<?xml version="1.0" encoding="UTF-8"?>
<DischargeResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Party>""" + cdataParty + """</Party>
<Source>
<SourceType>
<Id>Import</Id>
<DisplayName>""" + src + """</DisplayName>
</SourceType>
<DisplayName>""" + src + """</DisplayName>
<Sequence>1</Sequence>
</Source>
</DischargeResult>
"""
for mea in dmeasurement.Results.FieldVisitResult:
val = True
if mea.ParameterID == ParamID:
aMGH = mea.ObservedResult
mghFound = True
if aMGH != eMGH:
aMGH = str(aMGH)
eMGH = str(eMGH)
AQResultDetails = mea.ResultDetails
source = ET.fromstring(AQResultDetails).find("Source").find("SourceType").find("DisplayName").text
AUD = AquariusConflictUploadDialog("DEBUG", None, eMGH + " m", aMGH + " m", "M.G.H", source, None, title="Upload Field Visit to Aquarius")
while val:
re = AUD.ShowModal()
if re == wx.ID_YES:
# Add mgh to field visit with measurement ID
mghResult.ResultID = mea.ResultID
dmeasurement.Results.FieldVisitResult.append(mghResult)
val = False
break
else:
val = False
AUD.Destroy()
if not val:
break
# did not find mgh in the existing field visit, append to results list
if not mghFound:
mghResult.MeasurementID = 0
dmeasurement.Results.FieldVisitResult.append(mghResult)
elif str(EHSN.disMeasManager.widthCtrl).strip() != "" or str(EHSN.disMeasManager.areaCtrl).strip() != "" or str(EHSN.disMeasManager.meanVelCtrl).strip() != "" or \
str(EHSN.disMeasManager.dischCombo).strip() != "":
warning = wx.MessageDialog(None, "No MGH will be uploaded", "Warning!", wx.OK| wx.ICON_EXCLAMATION)
cont = warning.ShowModal()
if cont == wx.ID_OK:
warning.Destroy()
#Discharge
if str(EHSN.disMeasManager.dischCtrl).strip() != "":
eQR = float(EHSN.disMeasManager.dischCtrl)
ParamID = 'QR'
# If we found the qr in the field visit, then we ask and the user will choose
# If we could not find the qr in the field visit, then we add automatically
qrFound = False
dischargeResults = aq.factory.create("ns0:FieldVisitResult")
dischargeResults.MeasurementID = dmeasurement.MeasurementID
dischargeResults.ResultID = 0
dischargeResults.StartTime = meanTime
# dischargeResults.EndTime = visit.EndDate
dischargeResults.ParameterID = ParamID
dischargeResults.UnitID = dischargeSensors[ParamID]
dischargeResults.ObservedResult = float(EHSN.disMeasManager.dischCtrl)
dischargeResults.Correction = 0.000
dischargeResults.ResultType = resultType_All
dischargeResults.ResultDetails = r"""<?xml version="1.0" encoding="UTF-8"?>
<DischargeResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Party>""" + cdataParty + """</Party>
<Source>
<SourceType>
<Id>Import</Id>
<DisplayName>""" + src + """</DisplayName>
</SourceType>
<DisplayName>""" + src + """</DisplayName>
<Sequence>1</Sequence>
</Source>
</DischargeResult>
"""
for mea in dmeasurement.Results.FieldVisitResult:
val = True
if mea.ParameterID == ParamID:
aQR = mea.ObservedResult
AQResultDetails = mea.ResultDetails
source = ET.fromstring(AQResultDetails).find("Source").find("SourceType").find("DisplayName").text
qrFound = True
if aQR != eQR:
if "import" in source.lower():
break
else:
aQR = str(aQR)
eQR = str(eQR)
AUD = AquariusConflictUploadDialog("DEBUG", None, eQR + " m\N{SUPERSCRIPT THREE}/s", aQR + " m\N{SUPERSCRIPT THREE}/s", "Discharge", source, None, title="Upload Field Visit to Aquarius")
while val:
re = AUD.ShowModal()
# Overwrite
if re == wx.ID_YES:
# Add discharge to field visit with measurement ID
dischargeResults.ResultID = mea.ResultID
dmeasurement.Results.FieldVisitResult.append(dischargeResults)
val = False
break
else:
val = False
break
AUD.Destroy()
if not val:
break
# did not find q in the existing field visit, append to results list
if not qrFound:
dischargeResults.MeasurementID = 0