-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path1_ElectronicFieldNotes.py
More file actions
1677 lines (1253 loc) · 68.6 KB
/
Copy path1_ElectronicFieldNotes.py
File metadata and controls
1677 lines (1253 loc) · 68.6 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
# 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 ElectronicFieldNotesGUI import *
from TitleHeaderManager import *
from GenInfoManager import *
from DischargeMeasurementsManager import *
from StageMeasurementsManager import *
from EnvironmentConditionsManager import *
from MeasurementResultsManager import *
from InstrumentDeploymentInfoManager import *
from PartyInfoManager import *
from WaterLevelRunManager import *
# from AnnualLevellingManager import *
from FRChecklistManager import *
from InnovTechChecklistManager import *
from MovingBoatMeasurementsManager import *
from MidSectionMeasurementsManager import *
# from RemarksManager import *
from AttachmentManager import *
from RatingCurveViewerToolManager import *
# from UserConfigManager import *
from AquariusMiscUploadDialogs import *
import VersionCheck
import XMLManager
import AquariusUploadManager
import IngestQRevManager
import IngestQRevIntMSManager
import IngestFlowTrackerDisManager
import IngestHfcManager
import IngestFt2Manager
import IngestSxsManager
import IngestRSSLDisManager
from xml.etree import ElementTree
from xml.etree.ElementTree import Element
from xml.etree.ElementTree import SubElement
from xml.dom import minidom
from lxml import etree
import os
from os import chdir
from os import environ
from os.path import join
from os.path import dirname
import sys
import _thread
import suds
import datetime
import sys
import threading
import requests
import re
import json
import shutil
from zipfile import ZipFile
import importlib
from xhtml2pdf import pisa
# Aquarius Python Wrapper created by Doug Schmidt
from timeseries_client import timeseries_client
from requests.exceptions import HTTPError
###########################################
#only used for generating excutable
if 0:
# import common
from reportlab.graphics.barcode import *
import reportlab.graphics.barcode.common
import reportlab.graphics.barcode.code128
import reportlab.graphics.barcode.code93
import reportlab.graphics.barcode.code39
import reportlab.graphics.barcode.usps
import reportlab.graphics.barcode.usps4s
import reportlab.graphics.barcode.ecc200datamatrix
import reportlab.graphics.barcode.eanbc
import reportlab.graphics.barcode.fourstate
import reportlab.graphics.barcode.lto
import reportlab.graphics.barcode.qr
import reportlab.graphics.barcode.qrencoder
import reportlab.graphics.barcode.test
import reportlab.graphics.barcode.widgets
##########################################
##mode = "DEBUG"
mode = "PRODUCTION"
EHSN_VERSION = "v2.4.1"
eHSN_WINDOW_SIZE = (1100, 730)
# import wx.lib.inspection
# wx.lib.inspection.InspectionTool().Show()
class ElectronicHydrometricSurveyNotes:
def __init__(self):
importlib.reload(sys)
#sys.setdefaultencoding('utf-8')
self.headerTitle = "Hydrometric Survey Notes " + EHSN_VERSION
# Label variables
self.exportAQTitle = "Uploading Field Visit to AQUARIUS"
self.exportAQLoginMessage = "Logging into AQUARIUS..."
self.exportAQLocMessage = "Checking location..."
self.exportAQNoLoc = "Location does not exist. Please enter valid location number."
self.exportAQFVMessage = "Checking if a Field Visit exists for selected date..."
self.exportAQNoFV = "Could not find Field Visits for location:"
self.exportAQNewFV = "Creating new Field Visit in AQUARIUS..."
# self.exportAQAppendFV = "It appears that a Field Visit exists for this date. The data in this Hydrometric Survey note will be appended to the Field Visit. Continue?"
self.exportAQAppendFV = "It appears that a Field Visit exists for this date. Press OK to append the HSN to this field visit."
self.exportAQWarning = "Upload Warning!"
self.exportAQCancel = "Upload cancelled"
self.exportAQExist = "Saving parsed data would result in duplicates!"
self.exportAQFVUpdate = "Updating Field Visit in AQUARIUS"
self.saveXMLErrorDesc = "Failed on saving to XML"
self.saveXMLErrorTitle = "Failed on saving to XML"
self.lockWarningTitle = "Are you sure?"
self.lockWarningMessage = "If unlocked, it means that the user has made a decision to view or modify the uploaded xml file because any changes in the xml may not be reflected in AQUARIUS unless the file is uploaded again or modified manually in AQUARIUS."
self.ctrlKeyDownFlag = False
self.resizingLock = threading.Lock()
self.stationNumProcessed = False
self.InitUI()
def InitUI(self):
if mode == "DEBUG":
print("EHSN")
# Delete any existing iniPath.ini files stored in the temp directory
if os.path.exists('c:\\temp\\eHSN\\iniPath.ini'):
os.remove('c:\\temp\\eHSN\\iniPath.ini')
app = wx.App()
self.uploadRecord = None
self.gui = EHSNGui(mode, EHSN_VERSION, None, title=self.headerTitle, size=eHSN_WINDOW_SIZE)
self.SetupManagers()
self.stageMeasManager.AddEntry()
self.stationBmUpdate()
# 6 Entries
for i in range(9):
self.movingBoatMeasurementsManager.AddEntry()
self.BindAutoSave()
self.BindCorrectedMGH()
self.gui.LoadDefaultConfig()
self.midSectionDetailXml = {}
self.midSectionRawData = None
# try:
# self.gui.OpenStationFile('stations.csv')
# except:
# pass
# try:
# self.gui.OpenLevelFile('levels.csv')
# except:
# pass
# try:
# self.gui.OpenMeterFile('meters.csv')
# except:
# pass
self.DT_FORMAT = "%Y/%m/%d"
############################################
#Version checking
# latest = self.find(files)
# if latest is not None:
# if not self.compare(EHSN_VERSION, self.find(files)):
# self.CreateDialog('System out of update, please download the newest version from the server.')
############################################
## self.gui.Centre()
app.Bind(wx.EVT_KEY_DOWN, self.OnKeyDownEvent)
app.Bind(wx.EVT_KEY_UP, self.OnKeyUpEvent)
self.gui.Show()
# Muluken! if the new midsection is giving you problems, uncomment the below line!!
#self.gui.form4.Disable()
# atexit.register(self.OnExit())
# wx.lib.inspection.InspectionTool().Show()
try:
app.MainLoop()
except:
if self.gui.fullname == '':
self.ExportAsXML(str(os.getcwd()) + '\\' + self.genInfoManager.stnNumCmbo + "_CrashLog.xml", None)
self.ExportAsXML(self.gui.fullname, None)
# VersionCheck.Check(EHSN_VERSION, self, False)
def GetLayout(self):
return self.gui.layout
def stationBmUpdate(self):
for station in self.waterLevelRunManager.gui.levelNotes.panel.stationList:
station.Bind(wx.EVT_TEXT, self.gui.OnLevelNoteStationSelect)
for descButton in self.waterLevelRunManager.gui.levelNotes.panel.descList:
descButton.Bind(wx.EVT_BUTTON, self.gui.OnLevelNoteEstablishedBtn)
# def OnExit(self):
# # if self.gui.fullname == '':
# # self.ExportAsXML(str(os.getcwd()) + '\\' + self.genInfoManager.stnNumCmbo + "_CrashLog.xml")
# # self.ExportAsXML(self.gui.fullname)
# print "You are now leaving the eHSN, Have a nie day"
# Instantiates all Managers and gives their respective GUIs
def SetupManagers(self):
self.gui.manager = self
self.titleHeaderManager = TitleHeaderManager(mode, self.gui.titleHeader, self)
self.genInfoManager = GenInfoManager(mode, self.gui.genInfo, self)
self.disMeasManager = DischargeMeasurementsManager(mode, self.gui.disMeas, self)
self.stageMeasManager = StageMeasurementsManager(mode, self.gui.stageMeas, self)
self.envCondManager = EnvironmentConditionsManager(mode, self.gui.envCond, self)
self.measResultsManager = MeasurementResultsManager(mode, self.gui.measResults, self)
self.instrDepManager = InstrumentDeploymentInfoManager(mode, self.gui.instrDep, self)
self.attachmentManager = AttachmentManager(mode, self.gui.attachment, self)
# self.remarksManager = RemarksManager(mode, self.gui.remarks, self)
self.partyInfoManager = PartyInfoManager(mode, self.gui.partyInfo, self)
self.waterLevelRunManager = WaterLevelRunManager(mode, self.gui.waterLevelRun, self)
# self.annualLevelNotesManager = AnnualLevellingManager(mode, self.gui.annualLevelNotes, self)
self.frChecklistManager = FRChecklistManager(mode, self.gui.frChecklist, self)
self.innovTechChecklistManager = InnovTechChecklistManager(mode, self.gui.innovTechChecklist, self)
self.movingBoatMeasurementsManager = MovingBoatMeasurementsManager(mode, self.gui.movingBoatMeasurements, self)
self.midsecMeasurementsManager = MidSectionMeasurementsManager(mode, self.gui.midsecMeasurements, self)
# self.ratingCurveExtractionToolmanager = RatingCurveExtractionToolManager()
self.ratingCurveViewerToolManager = RatingCurveViewerToolManager(mode, self.gui.ratingFileDir, None, \
self.disMeasManager, wx.LANGUAGE_ENGLISH, None, self)
# self.userConfigManager = UserConfigManager(mode, self.gui.userConfig, self)
# Update the Field Review Checklist and the InnovTech Checklist with the value of depType
def DeploymentUpdate(self, depType):
self.frChecklistManager.changeDepType(depType)
self.innovTechChecklistManager.changeDepType(depType)
def FieldReviewChecklistUpdate(self, val):
self.frChecklistManager.onInstrumentType(val)
def InnovTechChecklistUpdate(self, choice):
self.innovTechChecklistManager.onMonitoringType(choice)
def ExportAsPDFWithoutOpen(self, filePath, xslPath):
if mode == "DEBUG":
print("Saving PDF")
xml = self.EHSNToXML()
print(xslPath)
self.gui.createProgressDialogPDF('PDF Creation In Progress...', 'Transform XML to HTML string')
# transform = etree.XSLT(etree.parse(xslPath))
transform = etree.XSLT(etree.parse(xslPath))
result = transform(etree.fromstring(xml))
self.gui.updateProgressDialog('Set Logo and QR paths')
# result = str(result).replace("%5C", "\\")
result = str(result).replace("logo_path", self.gui.logo_path)
result = result.replace("qr_path", self.gui.qr_path)
self.gui.updateProgressDialog('Converting HTML to PDF file')
# open output file for writing (truncated binary)
resultFile = open(filePath, "w+b")
# convert HTML to PDF
pisa.CreatePDF(
src=result, # the HTML to convert
dest=resultFile, show_error_as_pdf = True) # file handle to receive result
resultFile.close()
self.gui.updateProgressDialog('Successfully created PDF file')
self.gui.deleteProgressDialog()
# Call EHSNToXML() to create xml tree
# transform xml tree into html format (based on xsl)
# create PDF based on html
def ExportAsPDF(self, filePath, xslPath):
self.ExportAsPDFWithoutOpen(filePath, xslPath)
#Open the pdf
if sys.platform == 'linux2':
subprocess.call(["xdg-open", filePath])
else:
os.startfile(filePath)
#create pdf from a given xml file without open
def ExportAsPDFFromXML(self, filePath, xslPath, xml):
if mode == "DEBUG":
print("Saving PDF")
self.gui.createProgressDialogPDF('PDF Creation In Progress...', 'Transform XML to HTML string')
transform = etree.XSLT(etree.parse(xslPath))
result = transform(etree.fromstring(xml))
self.gui.updateProgressDialog('Set Logo and QR paths')
result = str(result).replace("logo_path", self.gui.logo_path)
result = result.replace("qr_path", self.gui.qr_path)
self.gui.updateProgressDialog('Converting HTML to PDF file')
# open output file for writing (truncated binary)
resultFile = open(filePath, "w+b")
# convert HTML to PDF
pisa.CreatePDF(
src=result, # the HTML to convert
dest=resultFile, show_error_as_pdf = True) # file handle to receive result
resultFile.close()
self.gui.updateProgressDialog('Successfully created PDF file')
self.gui.deleteProgressDialog()
#After generating the pdf from xml, open the pdf
def ExportAsPDFFromXMLOpen(self, filePath, xslPath, xml):
self.ExportAsPDFFromXML(filePath, xslPath, xml)
#Open the pdf
if sys.platform == 'linux2':
subprocess.call(["xdg-open", filePath])
else:
os.startfile(filePath)
#validate the mandatory value before uploading to AQ
def CheckFVVals(self):
AquariusUploadManager.CheckFVVals(mode, self)
# Check if the values in the eHSN will cause an error during upload to AQ
# Log in to AQ
# Check Location (based on StationNumber)
# Check if Field Visit exists for given date
# If it exists, prompt user for append of info
# If it doesn't exist, create new FV
def ExportToAquarius(self, server, username, password, fvDate, discharge, levelNote):
# Aquarius Login
self.gui.createProgressDialog(self.exportAQTitle, self.exportAQLoginMessage)
exists, value = AquariusUploadManager.AquariusLogin(mode, server, username, password)
if exists:
aq = value
#See if location exists
self.gui.updateProgressDialog(self.exportAQLocMessage)
exists, locid = AquariusUploadManager.AquariusCheckLocInfo(mode, aq, self.genInfoManager.stnNumCmbo)
if not exists:
self.gui.deleteProgressDialog()
return self.exportAQNoLoc
# See if Field Visit Exists in Aquarius
self.gui.updateProgressDialog(self.exportAQFVMessage)
fv, val = AquariusUploadManager.AquariusFieldVisitExistsByDate(mode, aq, locid, fvDate)
if val is None:
self.gui.deleteProgressDialog()
return self.exportAQNoFV + " %d" % locid
if fv or len(val) > 0:
self.gui.deleteProgressDialog()
warning = wx.MessageDialog(None,
self.exportAQAppendFV,
self.exportAQWarning, wx.OK | wx.CANCEL | wx.ICON_EXCLAMATION)
cont = warning.ShowModal()
if cont == wx.ID_CANCEL:
return self.exportAQCancel
self.gui.createProgressDialog(self.exportAQTitle, self.exportAQFVUpdate)
if len(val) >= 1:
# make popup
displayLis = []
for dis in val:
disTime = dis.MeasurementTime
startDate = datetime.datetime.strptime(str(self.genInfoManager.datePicker), "%Y/%m/%d")
startDate = startDate.replace(hour=disTime.hour, minute=disTime.minute, second=disTime.second)
disName = startDate.strftime("%Y/%m/%d") + " discharge activity started at " + startDate.strftime("%H:%M:%S")
displayLis.append(disName)
self.gui.deleteProgressDialog()
if discharge:
AMDUD = AquariusMultDisUploadDialog("DEBUG", None, displayLis, None, title="Upload Field Visit to Aquarius")
AMDUD.Show()
re = AMDUD.ShowModal()
if re == wx.ID_YES:
if AMDUD.MergeRBIsSelected():
selectedDis = AMDUD.GetSelectedDisMeas()
index = displayLis.index(selectedDis)
val = [val[index]]
else:
val = []
else:
print("Cancel")
return "Cancelled out of field visit" + " %d" % locid
AMDUD.Destroy()
self.gui.createProgressDialog(self.exportAQTitle, self.exportAQFVMessage)
#There is no Field Visit for this day
if len(val) == 0:
self.gui.updateProgressDialog(self.exportAQNewFV)
try:
emptyList = []
export = AquariusUploadManager.ExportToAquarius(mode, EHSN_VERSION, self, aq, fv, locid, discharge, levelNote, emptyList, None, server)
self.gui.deleteProgressDialog()
return export
except suds.WebFault as e:
self.gui.deleteProgressDialog()
print(e)
return str(e)
except ValueError as e:
self.gui.deleteProgressDialog()
return str(e)
else:
if mode == "DEBUG":
print("Field Visit for selected date")
print(val)
paraList = AquariusUploadManager.GetParaIDByFV(val[0])
export = AquariusUploadManager.ExportToAquarius(mode, EHSN_VERSION, self, aq, fv, locid, discharge, levelNote, paraList, val[0], server)
self.gui.deleteProgressDialog()
return export
else:
self.gui.deleteProgressDialog()
return value
# export ehsn to ng
def ExportToAquariusNg(self, server, username, password, fvPath, fvDate):
print("NG")
self.gui.createProgressDialog(self.exportAQTitle, self.exportAQLoginMessage)
# Login
try:
# Using Aquarius Python Wrapper created by Doug Schmidt
aq = timeseries_client('https://' + server, username, password)
exists = True
except HTTPError as e:
exists = False
self.gui.deleteProgressDialog()
if e.response.status_code == 401:
return "The username or the password is incorrect."
else:
return "Failed to login."
print("login")
if exists:
try:
parameters = {'LocationIdentifier': self.genInfoManager.stnNumCmbo}
req = aq.publish.get('/GetLocationDescriptionList', params=parameters)
try:
locid = req['LocationDescriptions'][0]['UniqueId']
exists = True
# print locid
except:
exists = False
print("Id not exist1")
except:
exists = False
print("Id not exist")
if not exists:
self.gui.deleteProgressDialog()
return self.exportAQNoLoc
else:
self.gui.updateProgressDialog(self.exportAQLocMessage)
fvDate = str(datetime.datetime.strptime(str(fvDate), "%Y/%m/%d").strftime('%Y-%m-%d'))
fvDate1 = fvDate[:-2]
midtime = str(int(fvDate[-2:]) + 1)
if len(midtime) == 1:
fvDate1 = fvDate1 + "0" + midtime
else:
fvDate1 = fvDate1 + midtime
# get the field visit data from NG check if the fv already exist
# self.gui.updateProgressDialog(self.exportAQFVMessage)
try:
parameters = {'LocationIdentifier': self.genInfoManager.stnNumCmbo, 'QueryFrom': fvDate, 'QueryTo': fvDate1}
req = aq.publish.get('/GetFieldVisitDescriptionList', params=parameters)
fvexData = req['FieldVisitDescriptions'][0]['Identifier']
# print fvexData
exists = True
except:
# print "field data doesn't exist."
exists = False
# upload to NG
if exists:
self.gui.deleteProgressDialog()
return self.exportAQExist
else:
self.gui.updateProgressDialog("Uploading...")
print(fvPath)
# uploading the zip file
if fvPath.endswith(".zip"):
uploadZipDir = fvPath
else:
dirName = fvPath[-19:]
fvPath = fvPath.replace("\\", "\\\\")
dirPath = fvPath.replace("\\", "/")
fvPathPdf = fvPath.replace("\\", "\\\\")
fvPath = fvPath + ".xml"
fvPathPdf = fvPathPdf + ".pdf"
xmlPath = fvPath[-23:]
uploadDir = dirName + "_a"
# make an empty directory, move the pdf file in, create a directory with _a move the directory and xml file in
if os.path.exists(dirName):
shutil.rmtree(dirName)
if os.path.exists(uploadDir):
shutil.rmtree(uploadDir)
if os.path.exists(uploadDir + ".zip"):
os.remove(uploadDir + ".zip")
try:
os.mkdir(dirName)
shutil.move(fvPathPdf, dirName)
os.mkdir(uploadDir)
shutil.move(dirName, uploadDir)
shutil.move(fvPath, uploadDir)
shutil.make_archive(uploadDir, 'zip', uploadDir)
except:
print('Error occured while creating zip file for upload')
self.gui.deleteProgressDialog()
return None
# create the zip file
uploadZipDir = dirName + "_a.zip"
# files = {'file': open(fvPath, 'rb')}
files = {'file': open(uploadZipDir, 'rb')}
payload = {}
print("Uploading")
try:
req = aq.acquisition.post('/locations/' + locid + '/visits/upload/plugins', json=payload, files=files)
visitUris = req
try:
visitUris = req['ResponseStatus']['Message']
self.gui.deleteProgressDialog()
return visitUris
except:
try:
visitUris = visitUris['VisitUris'][0]
except:
self.gui.deleteProgressDialog()
return "Failed"
except HTTPError as e:
visitUris = json.loads(e.response.text)['ResponseStatus']['Message']
self.gui.deleteProgressDialog()
return visitUris
# return self.exportAQWarning
self.gui.deleteProgressDialog()
return None
# Locks all the pages except the title header.
def LockEvent(self, e):
if e is not None:
dlg = wx.MessageDialog(None, self.lockWarningMessage, self.lockWarningTitle, wx.YES_NO)
res = dlg.ShowModal()
if res==wx.ID_YES:
for widget in self.gui.form.GetChildren():
widget.Enable()
self.gui.form2_1.Enable()
self.gui.form3.Enable()
self.gui.form4.Enable()
self.gui.form5.Enable()
else:
for widget in self.gui.form.GetChildren():
widget.Enable()
self.gui.form2_1.Enable()
self.gui.form3.Enable()
self.gui.form4.Enable()
self.gui.form5.Enable()
def Lock(self):
for widget in self.gui.form.GetChildren():
widget.Disable()
self.gui.titleHeader.Enable()
self.gui.form2_1.Disable()
self.gui.form3.Disable()
self.gui.form4.Disable()
self.gui.form5.Disable()
# Generates xml from all info from eHSN
# Writes to file based on filePath
def ExportAsXML(self, filePath, msg):
if mode == "DEBUG":
print("Saving File")
#########################for testing without catching exceptions###################################
pretty_xml = self.EHSNToXML() # Collects all info and puts into eTree
if mode == "DEBUG":
print(pretty_xml)
print(filePath)
output = open(filePath, 'wb')
output.write( pretty_xml.encode('utf-8') )
output.close()
return pretty_xml
##################################################################################################
# Creates xml tree based on eHSN values
# Puts in human readable format
def EHSNToXML(self):
if mode == "DEBUG":
print("To XML")
#Page 1
#Create XML Tree structure
EHSN = Element('EHSN', version=EHSN_VERSION)
# if hasattr(sys, '_MEIPASS'):
# DirInfo = SubElement(EHSN, 'dirInfo')
# DirInfo.text = (join(sys._MEIPASS, "icon_transparent.png"))
#Title Header Branch
TitleHeader = SubElement(EHSN, 'TitleHeader')
self.TitleHeaderAsXMLTree(TitleHeader)
#General Info Branch
GenInfo = SubElement(EHSN, 'GenInfo')
self.GenInfoAsXMLTree(GenInfo)
#Stage Measurements Branch
StageMeas = SubElement(EHSN, 'StageMeas')
self.StageMeasAsXMLTree(StageMeas)
#Discharge Measurements Branch
DisMeas = SubElement(EHSN, 'DisMeas')
self.DischMeasAsXMLTree(DisMeas)
#Environment Conditions Branch
EnvCond = SubElement(EHSN, 'EnvCond')
self.EnvCondAsXMLTree(EnvCond)
#Measurement Results Branch
MeasResults = SubElement(EHSN, 'MeasResults', empty = 'False')
self.MeasResultsAsXMLTree(MeasResults)
#Instrument Deployment Branch
InstrumentDeployment = SubElement(EHSN, 'InstrumentDeployment')
self.InstrumentDepAsXMLTree(InstrumentDeployment)
#Party Information Branch
PartyInfo = SubElement(EHSN, 'PartyInfo')
self.PartyInfoAsXMLTree(PartyInfo)
#Page 2
#LevelNotes
LevelNotes = SubElement(EHSN, 'LevelNotes')
# Conventional Leveling vs Total Station
ConventionalTotal = SubElement(LevelNotes, 'ConventionalTotal')
self.ConventionalTotalAsXMLTree(ConventionalTotal)
#Level Checks
LevelChecks = SubElement(LevelNotes, 'LevelChecks')
self.LevelChecksAsXMLTree(LevelChecks)
# #Annual Levels
# AnnualLevels = SubElement(LevelNotes, 'AnnualLevels')
# self.AnnualLevelsAsXMLTree(AnnualLevels)
#Page 3
#Checklist
FieldReview = SubElement(EHSN, "FieldReview")
self.FieldReviewAsXMLTree(FieldReview)
#InnovTech Checklist
InnovTechData = SubElement(EHSN, "InnovTech")
self.InnovTechAsXMLTree(InnovTechData)
#Page 4
#ADCP Measurements
MovingBoatMeas = SubElement(EHSN, "MovingBoatMeas", empty="False")
self.MovingBoatMeasAsXMLTree(MovingBoatMeas)
#Page 5
#Midsection Measurements
MidsecMeas = SubElement(EHSN, "MidsecMeas", empty="False")
self.MidsecMeasAsXMLTree(MidsecMeas)
# Page 6
Attachments = SubElement(EHSN, "Attachments")
self.AttachmentAsXMLTree(Attachments)
#Imported
#Midsection
if len(self.midSectionDetailXml) != 0:
Imported = SubElement(EHSN, "Imported")
self.ImportedMidsectionAsXMLTree(Imported)
#save current upload record
if self.uploadRecord is not None:
UploadRecord = SubElement(EHSN, "AQ_Upload_Record")
for row in self.uploadRecord.findall('record'):
details = []
for col in row.getchildren():
details.append(col.text)
self.UploadInfoAsXMLTree(UploadRecord, details)
# EHSN.append(self.uploadRecord)
doc_string = ElementTree.tostring(EHSN)
reparsed = minidom.parseString(doc_string)
style = reparsed.createProcessingInstruction('xml-stylesheet',
'type="text/xsl" href="WSC_EHSN.xsml"')
root = reparsed.firstChild
reparsed.insertBefore(style, root)
pretty_xml = reparsed.toprettyxml(indent="\t")
return pretty_xml
#Read from external xml files for moving boat
def OpenMovingBoatMmt(self, filePath):
if mode == "DEBUG":
print("Opening Moving Boat XML")
winRiver = ElementTree.parse(filePath).getroot()
# siteInformation = winRiver.find('Project').find('Site_Information')
# dischargeSummary = winRiver.find('Project').find('Site_Discharge').find('Discharge_Summary')
self.MovingBoatTransectFromMmt(winRiver)
def OpenEHSNMidsection(self, filePath):
if mode == "DEBUG":
print("Opening File")
EHSN = ElementTree.parse(filePath).getroot()
MidsecMeas = EHSN.find('MidsecMeas')
self.MidsecMeasFromXML(MidsecMeas)
#Read xml file and place each val into text fields in eHSN
def OpenFile(self, filePath):
if mode == "DEBUG":
print("Opening File")
try:
EHSN = ElementTree.parse(filePath).getroot()
XML_version = EHSN.get('version') #get the eHSN version used to create the XML file
if XML_version.split("_",1)[0] > EHSN_VERSION.split("_",1)[0]: #if eHSN version obtained from xml file is newer than user's eHSN version, display a warning
dlg = wx.MessageDialog(self.gui, "You are attempting to open an XML file for "+XML_version+" of eHSN using "+EHSN_VERSION+" of eHSN. There is no guarantee an older version of eHSN will open the file successfully so please update to the newest version.","EHSN Version Error", wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
except:
pass
#First Page
TitleHeader = EHSN.find('TitleHeader')
self.TitleHeaderFromXML(TitleHeader)
try:
GenInfo = EHSN.find('GenInfo')
self.GenInfoFromXML(GenInfo)
except:
dlg = wx.MessageDialog(self.gui,"The format of selected XML file is invalid.", "Invalid eHSN XML!", wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
return
StageMeas = EHSN.find('StageMeas')
self.StageMeasFromXML(StageMeas)
DisMeas = EHSN.find('DisMeas')
self.DischMeasFromXML(DisMeas)
EnvCond = EHSN.find('EnvCond')
self.EnvCondFromXML(EnvCond)
MeasResults = EHSN.find('MeasResults')
self.MeasResultsFromXML(MeasResults)
InstrumentDeployment = EHSN.find('InstrumentDeployment')
self.InstrumentDepFromXML(InstrumentDeployment)
PartyInfo = EHSN.find('PartyInfo')
self.PartyInfoFromXML(PartyInfo)
#Second Page
LevelNotes = EHSN.find('LevelNotes')
LevelChecks = LevelNotes.find('LevelChecks')
self.LevelChecksFromXML(LevelChecks)
# AnnualLevels = LevelNotes.find('AnnualLevels')
# self.AnnualLevelsFromXML(AnnualLevels)
#Third Page
FieldReview = EHSN.find('FieldReview')
self.FieldReviewFromXML(FieldReview)
#Fourth Page
MovingBoatMeas = EHSN.find('MovingBoatMeas')
MovingBoatMeas = EHSN.find('ADCPMeas') if MovingBoatMeas is None else MovingBoatMeas
self.MovingMeasFromXML(MovingBoatMeas)
#Fifth Page
MidsecMeas = EHSN.find('MidsecMeas')
self.MidsecMeasFromXML(MidsecMeas)
# for i in self.midsecMeasurementsManager.gui.table.panelObjs:
# i.ToString()
# Sixth Page
Attachments = EHSN.find('Attachments')
self.AttachmentFromXML(Attachments)
#Seventh Page
InnovTechData = EHSN.find('InnovTech')
self.InnovTechFromXML(InnovTechData)
#Upload Record
self.uploadRecord = EHSN.find('AQ_Upload_Record')
# try:
# MidSectionDetail = EHSN.find('Imported')
# if MidSectionDetail is not None:
# self.MidSectionDetailsFromXML(MidSectionDetail)
# except Exception as e:
# print e
def TitleHeaderAsXMLTree(self, TitleHeader):
XMLManager.TitleHeaderAsXMLTree(TitleHeader, self.titleHeaderManager)
def TitleHeaderFromXML(self, TitleHeader):
XMLManager.TitleHeaderFromXML(TitleHeader, self.titleHeaderManager)
def GenInfoAsXMLTree(self, GenInfo):
XMLManager.GenInfoAsXMLTree(GenInfo, self.genInfoManager)
def GenInfoFromXML(self, GenInfo):
XMLManager.GenInfoFromXML(GenInfo, self.genInfoManager)
def StageMeasAsXMLTree(self, StageMeas):
XMLManager.StageMeasAsXMLTree(StageMeas, self.stageMeasManager)
def StageMeasFromXML(self, StageMeas):
XMLManager.StageMeasFromXML(StageMeas, self.stageMeasManager)
def DischMeasAsXMLTree(self, DisMeas):
XMLManager.DischMeasAsXMLTree(DisMeas, self.disMeasManager)
def DischMeasFromXML(self, DisMeas):
XMLManager.DischMeasFromXML(DisMeas, self.disMeasManager)
def EnvCondAsXMLTree(self, EnvCond):
XMLManager.EnvCondAsXMLTree(EnvCond, self.envCondManager)
def EnvCondFromXML(self, EnvCond):
XMLManager.EnvCondFromXML(EnvCond, self.envCondManager)
def MeasResultsAsXMLTree(self, MeasResults):
XMLManager.MeasResultsAsXMLTree(MeasResults, self.measResultsManager)
def MeasResultsFromXML(self, MeasResults):
XMLManager.MeasResultsFromXML(MeasResults, self.measResultsManager)
def InstrumentDepAsXMLTree(self, InstrumentDeployment):
XMLManager.InstrumentDepAsXMLTree(InstrumentDeployment, self.instrDepManager, self.attachmentManager)
def InstrumentDepFromXML(self, InstrumentDeployment):
XMLManager.InstrumentDepFromXML(InstrumentDeployment, self.instrDepManager, self.attachmentManager)
def PartyInfoAsXMLTree(self, PartyInfo):
XMLManager.PartyInfoAsXMLTree(PartyInfo, self.partyInfoManager)
def PartyInfoFromXML(self, PartyInfo):
XMLManager.PartyInfoFromXML(PartyInfo, self.partyInfoManager)
def ConventionalTotalAsXMLTree(self, ConventionalTotal):
XMLManager.ConventionalTotalAsXMLTree(ConventionalTotal, self.waterLevelRunManager)
def LevelChecksAsXMLTree(self, LevelChecks):
XMLManager.LevelChecksAsXMLTree(LevelChecks, self.waterLevelRunManager)
def LevelChecksFromXML(self, LevelChecks):
XMLManager.LevelChecksFromXML(LevelChecks, self.waterLevelRunManager)
# self.gui.LoadDefaultConfig()
# def AnnualLevelsAsXMLTree(self, AnnualLevels):
# XMLManager.AnnualLevelsAsXMLTree(AnnualLevels, self.annualLevelNotesManager)
# def AnnualLevelsFromXML(self, AnnualLevels):
# XMLManager.AnnualLevelsFromXML(AnnualLevels, self.annualLevelNotesManager)
def FieldReviewAsXMLTree(self, FieldReview):
XMLManager.FieldReviewAsXMLTree(FieldReview, self.frChecklistManager)
def FieldReviewFromXML(self, FieldReview):
XMLManager.FieldReviewFromXML(FieldReview, self.frChecklistManager)
def InnovTechAsXMLTree(self, InnovTechData):
XMLManager.InnovTechAsXMLTree(InnovTechData, self.innovTechChecklistManager)
def InnovTechFromXML(self, InnovTechData):
XMLManager.InnovTechFromXML(InnovTechData, self.innovTechChecklistManager)
def MovingBoatMeasAsXMLTree(self, MovingBoatMeas):
XMLManager.MovingBoatMeasAsXMLTree(MovingBoatMeas, self.movingBoatMeasurementsManager)
def MovingMeasFromXML(self, MovingBoatMeas):
XMLManager.MovingBoatMeasFromXML(MovingBoatMeas, self.movingBoatMeasurementsManager)
def MidsecMeasAsXMLTree(self, MidsecMeas):
XMLManager.MidsecMeasAsXMLTree(MidsecMeas, self.midsecMeasurementsManager)
def MidsecMeasFromXML(self, MidsecMeas):
XMLManager.MidsecMeasFromXML(MidsecMeas, self.midsecMeasurementsManager)