-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpse_outagesNoDB.py
392 lines (306 loc) · 13.7 KB
/
pse_outagesNoDB.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
#-------------------------------------------------------------------------------
# Name: PSE Power Outages Data Extraction
# Purpose: This script extracts all power outages from the PSE provided online
# map and applies it to ArcGIS Online.
#
# Author: John Spence
#
# https://developers.arcgis.com/documentation/common-data-types/geometry-objects.htm
#
#
# Created:
# Modified:
# Modification Purpose:
#
#
#-------------------------------------------------------------------------------
# 888888888888888888888888888888888888888888888888888888888888888888888888888888
# ------------------------------- Configuration --------------------------------
# To be completed.
#
# ------------------------------- Dependencies ---------------------------------
# 1) Using PIP, install PyODBC if you have not previously.
# 2) This script assumes you are using MS SQL as your RDBMS.
#
# 888888888888888888888888888888888888888888888888888888888888888888888888888888
# Puget Sound Eneregy Data Source
pse_status = 'https://www.pse.com/api/sitecore/OutageMap/AnonymoussMapListView'
# ArcGIS Online Portal
AGOL_Portal = '' #If blank, it will search for the active portal from your ArcGIS//Pro install
# Targeted Service & layer for Data
service_URL = 'https://services1.arcgis.com/YourPointsService'
service_URL_Area = 'https://services1.arcgis.com/YourAreaService'
# ArcGIS Online Credentials
AGOL_User = 'UserName'
AGOL_Pass = 'Password'
# ------------------------------------------------------------------------------
# DO NOT UPDATE BELOW THIS LINE OR RISK DOOM AND DISPAIR! Have a nice day!
# ------------------------------------------------------------------------------
# Import Python libraries
import urllib
import time
import datetime
import re
import requests, json, collections, string
#-------------------------------------------------------------------------------
#
#
# Functions
#
#
#-------------------------------------------------------------------------------
def get_token():
url = 'https://www.arcgis.com/sharing/rest/generateToken'
values = {'f': 'json',
'username': AGOL_User,
'password': AGOL_Pass,
'referer' : 'https://www.arcgis.com',
'expiration' : '10'}
data = urllib.parse.urlencode(values).encode("utf-8")
req = urllib.request.Request(url)
response = None
while response is None:
try:
response = urllib.request.urlopen(req,data=data)
except:
pass
the_page = response.read()
#Garbage Collection with some house building
payload_json = the_page.decode('utf8')
payload_json = json.loads(payload_json)
edit_token = payload_json['token']
return (edit_token)
def getPSE():
status_response = requests.get (pse_status)
status_data = status_response.json()
status_payload = status_data['PseMap']
print (status_payload)
for item in status_payload:
pse_poly = []
status_message = item['DataProvider']['Attributes']
poi_data = item['DataProvider']['PointOfInterest']
polygon_data = item['Polygon']
print ('ID: ' + poi_data['Id'])
outage_id = poi_data['Id']
print ('Title: ' + poi_data['Title'])
outage_title = poi_data['Title']
print (' Map Type: ' + poi_data['MapType'])
outage_mapType = poi_data['MapType']
print (' Pin Type: ' + poi_data['PinType'])
outage_pinType = poi_data['PinType']
print (' Planned Outage: ' + str(poi_data['PlannedOutage']))
if poi_data['PlannedOutage'] == True:
output_plannedoutage = 'Yes'
else:
output_plannedoutage = 'No'
for message in status_message:
if message['Name'] == 'Est. restoration time':
check_field = 1
break
else:
output_estrestore = 'TBD'
for message in status_message:
print (' ' + message['Name'] + ': ' + message['Value'])
if message['Name'] == 'Start time':
output_starttime = message['Value']
elif message['Name'] == 'Est. restoration time':
output_estrestore = message['Value']
elif message['Name'] == 'Customers impacted':
output_impact = message['Value']
elif message['Name'] == 'Cause':
output_cause = message['Value']
elif message['Name'] == 'Status':
output_status = message['Value']
elif message['Name'] == 'Last updated':
output_updatetime = message['Value']
else:
print (' ***UNKNOWN FIELD ID: ' + message['Name'])
print (' Longitude: ' + poi_data['Longitude'])
output_long_pt = float(poi_data['Longitude'])
print (' Latitude: ' + poi_data['Latitude'])
output_lat_pt = float(poi_data['Latitude'])
print('\n Polygon:')
init = 0
for tp in polygon_data:
temp_poly = []
print (' ' + tp['Longitude'] + ', ' + tp['Latitude'])
temp_poly.append(float(tp['Longitude']))
temp_poly.append(float(tp['Latitude']))
pse_poly.append(temp_poly)
#print (pse_poly)
pushToAGOL(outage_id, outage_title, outage_mapType, outage_pinType, output_plannedoutage, output_starttime,
output_estrestore, output_impact, output_cause, output_status, output_updatetime, output_long_pt, output_lat_pt, pse_poly)
def queryCount(outage_id,edit_token):
edit_token = get_token()
FS_service = service_URL + 'query/?token={}'.format(edit_token)
where_statement = 'ID=\'{}\''.format(outage_id)
data = urllib.parse.urlencode({'f': 'json', 'where': where_statement, 'returnCountOnly': 'true'}).encode('utf-8')
req = urllib.request.Request(FS_service)
response = urllib.request.urlopen(req,data=data)
response_payload = response.read()
response_payload = json.loads(response_payload)
item_count = response_payload['count']
if item_count > 0:
where_statement = 'ID=\'{}\''.format(outage_id)
data = urllib.parse.urlencode({'f': 'json', 'where': where_statement, 'outFields':'OBJECTID'}).encode('utf-8')
req = urllib.request.Request(FS_service)
response = urllib.request.urlopen(req,data=data)
response_payload = response.read()
response_payload = json.loads(response_payload)
for oid_item in response_payload['features']:
objectID = oid_item['attributes']['OBJECTID']
else:
objectID = '0'
if item_count > 0:
FS_service = service_URL_Area + 'query/?token={}'.format(edit_token)
where_statement = 'ID=\'{}\''.format(outage_id)
data = urllib.parse.urlencode({'f':'json', 'where': where_statement, 'outFields':'OBJECTID'}).encode('utf-8')
req = urllib.request.Request(FS_service)
response = urllib.request.urlopen(req,data=data)
response_payload = response.read()
response_payload = json.loads(response_payload)
for oid_item_area in response_payload['features']:
objectID_Area = oid_item_area['attributes']['OBJECTID']
else:
objectID_Area = '0'
return (item_count, objectID, objectID_Area)
def pushToAGOL(outage_id, outage_title, outage_mapType, outage_pinType, output_plannedoutage, output_starttime,
output_estrestore, output_impact, output_cause, output_status, output_updatetime, output_long_pt, output_lat_pt, pse_poly):
# Get token for editing/checking
edit_token = get_token()
# Get count
item_count, objectID, objectID_Area = queryCount(outage_id,edit_token)
if item_count > 0:
upload_payload = [{
'geometry' : {'x' : output_long_pt, 'y' : output_lat_pt},
'attributes' : {
'OBJECTID': objectID,
'Title' : outage_title,
'Map_Type': outage_mapType,
'Pin_Type': outage_pinType,
'Planned': output_plannedoutage,
'Start': output_starttime,
'EstRestore': output_estrestore,
'Impact': output_impact,
'Cause' : output_cause,
'Status' : output_status,
'Updated' : output_updatetime
}
}]
upload_payload_Area = [{
'geometry' : {
'rings' : [pse_poly]
},
'attributes' : {
'OBJECTID': objectID_Area,
'Status' : output_status,
}
}]
update_AGOL(upload_payload, upload_payload_Area, edit_token)
else:
upload_payload = [{
'geometry' : {'x' : output_long_pt, 'y' : output_lat_pt},
'attributes' : {
'ID' : outage_id,
'Title' : outage_title,
'Map_Type': outage_mapType,
'Pin_Type': outage_pinType,
'Planned': output_plannedoutage,
'Start': output_starttime,
'EstRestore': output_estrestore,
'Impact': output_impact,
'Cause' : output_cause,
'Status' : output_status,
'Updated' : output_updatetime
}
}]
upload_payload_Area = [{
'geometry' : {
'rings' : [pse_poly]
},
'attributes' : {
'ID' : outage_id,
'Status' : output_status,
}
}]
insert_AGOL(upload_payload, upload_payload_Area, edit_token)
return
def insert_AGOL(upload_payload, upload_payload_Area, edit_token):
FS_service = service_URL + 'addFeatures/?token={}'.format(edit_token)
data = urllib.parse.urlencode({'f': 'json', 'features': upload_payload}).encode('utf-8')
req = urllib.request.Request(FS_service)
response = urllib.request.urlopen(req,data=data)
the_page = response.read()
print (' Point Record inserted.')
FS_service = service_URL_Area + 'addFeatures/?token={}'.format(edit_token)
data = urllib.parse.urlencode({'f': 'json', 'features': upload_payload_Area}).encode('utf-8')
req = urllib.request.Request(FS_service)
response = urllib.request.urlopen(req,data=data)
the_page = response.read()
print (' Area Record inserted.')
return
def update_AGOL(upload_payload, upload_payload_Area, edit_token):
FS_service = service_URL + 'updateFeatures/?token={}'.format(edit_token)
data = urllib.parse.urlencode({'f': 'json', 'features': upload_payload}).encode('utf-8')
req = urllib.request.Request(FS_service)
response = urllib.request.urlopen(req,data=data)
the_page = response.read()
print (' Point Record updated.')
FS_service = service_URL_Area + 'updateFeatures/?token={}'.format(edit_token)
data = urllib.parse.urlencode({'f': 'json', 'features': upload_payload_Area}).encode('utf-8')
req = urllib.request.Request(FS_service)
response = urllib.request.urlopen(req,data=data)
the_page = response.read()
print (' Area Record updated.')
return
def aisle6Cleanup():
dt = datetime.datetime.utcnow()
dt = dt - datetime.timedelta(minutes=3)
dbdt = datetime.datetime.now()
print ('\n\nCompleting Prior to: {}'.format(dt))
edit_token = get_token()
FS_service = service_URL + 'query/?token={}'.format(edit_token)
where_statement = 'EditDate<\'{}\' and Status<>\'Complete\''.format(dt)
data = urllib.parse.urlencode({'f': 'json', 'where': where_statement, 'outFields':'OBJECTID, ID'}).encode('utf-8')
req = urllib.request.Request(FS_service)
response = urllib.request.urlopen(req,data=data)
response_payload = response.read()
response_payload = json.loads(response_payload)
count = 0
for oid_item in response_payload['features']:
objectID = oid_item['attributes']['OBJECTID']
ID = oid_item['attributes']['ID']
FS_service = service_URL_Area + 'query/?token={}'.format(edit_token)
where_statement = 'ID=\'{}\''.format(ID)
data = urllib.parse.urlencode({'f': 'json', 'where': where_statement, 'outFields':'OBJECTID'}).encode('utf-8')
req = urllib.request.Request(FS_service)
response = urllib.request.urlopen(req,data=data)
response_payload = response.read()
response_payload = json.loads(response_payload)
for oid_item in response_payload['features']:
objectID_Area = oid_item['attributes']['OBJECTID']
upload_payload = [{
'attributes' : {
'OBJECTID': objectID,
'Status' : 'Complete'
}
}]
upload_payload_Area = [{
'attributes' : {
'OBJECTID': objectID_Area,
'Status' : 'Complete'
}
}]
update_AGOL(upload_payload, upload_payload_Area, edit_token)
count += 1
print (' {} Records Completed.'.format(count))
return
#-------------------------------------------------------------------------------
#
#
# MAIN SCRIPT
#
#
#-------------------------------------------------------------------------------
getPSE()
aisle6Cleanup()