-
Notifications
You must be signed in to change notification settings - Fork 0
/
fiwareorion.py
307 lines (244 loc) · 10.4 KB
/
fiwareorion.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
#!/usr/bin/python
#-*-coding: utf-8-*-
import requests
import json
import time
import datetime
import logging
import pickle
import sys
#logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(level=logging.INFO)
class FiwareOrion:
TOKEN_EXPIRE_MERGIN = 5*60 #sec, 残り何秒になったらupdateするか
#TOKEN_EXPIRE_MERGIN = 60*60-30 #sec
username = ""
password = ""
fiwareservice = ""
fiwareservicepath = ""
cb_host = ""
data_type = ""
data_name = ""
data_id = ""
token = ""
token_issued_time = ""
tokenfilename = ""
noauthflag = ""
def __init__(self, username, password, fiwareservice, fiwareservicepath, cb_host, data_type, data_name, tokenfilename, noauthflag):
self.username = username
self.password = password
self.cb_host = cb_host
self.data_type = data_type
self.data_name = data_name
self.data_id = 'urn:ngsi-ld:' + data_type + ':' + data_name
self.fiwareservice = fiwareservice
self.fiwareservicepath = fiwareservicepath
self.tokenfilename = tokenfilename
self.noauthflag = noauthflag
def mySendRequest(self, **kwargs):
# requestを発行
try:
if (('method', 'DELETE') in kwargs.items()):
response = requests.delete(kwargs['url'], headers=kwargs['headers'])
elif ('data' not in kwargs):
response = requests.get(kwargs['url'], headers=kwargs['headers'])
else:
response = requests.post(kwargs['url'], data=kwargs['data'], headers=kwargs['headers'])
response.raise_for_status()
except requests.exceptions.RequestException as e:
logging.error('Error code : %s' % e)
else:
# responseを出力
try:
response_json = json.loads(response.text)
logging.info('Response : %s' % response_json)
return response_json
except Exception:
pass
def isTokenExpired(self):
delta = datetime.datetime.now() - self.token_issued_time
logging.debug('Elapsed Time : %s' % delta)
if (self.token['expires_in'] - delta.total_seconds()) < self.TOKEN_EXPIRE_MERGIN :
logging.debug('isTokenExpired: true')
return True
else:
logging.debug('isTokenExpired: false')
return False
def updateToken(self):
url = self.cb_host + "/token"
header = {'Content-Type':'application/json'}
data = {
'refresh' : self.token['refresh_token']
}
body = json.dumps(data)
try:
result = self.mySendRequest({'url':url, 'headers':header})
except Exception:
# トークン更新に失敗している場合は、トークン取得からやり直す
logging.debug('token update failed')
try:
self.getAccessToken()
except Exception:
logging.debug('get access token error.')
return
else:
if result == None:
logging.debug('token update failed')
try:
self.getAccessToken()
except Exception:
logging.debug('get access token error.')
return
# トークン更新に成功の場合
self.token = result
self.token_issued_time = datetime.datetime.now()
logging.debug('Refreshed Token : %s' % self.token)
logging.debug('Token Issued Time : %s' % self.token_issued_time)
# トークンと更新時間をファイルに書き込む
with open(self.tokenfilename, "wb") as tokenfile:
pickle.dump(self.token, tokenfile)
pickle.dump(self.token_issued_time, tokenfile)
logging.debug('Updated Token : %s' % self.token)
logging.debug('Token Issued Time : %s' % self.token_issued_time)
def createHeaders(self):
headers = {
'Fiware-Service':self.fiwareservice,
'Fiware-ServicePath':self.fiwareservicepath
}
# 認証必要な系の場合には、トークンを付与する
if self.noauthflag == False:
# トークンを、トークン保存ファイルから取得する
try:
with open(self.tokenfilename, "rb") as tokenfile:
self.token = pickle.load(tokenfile)
self.token_issued_time = pickle.load(tokenfile)
except:
# ファイルオープンに失敗(=トークン保存ファイルがない)場合は、トークン取得からやり直す
logging.debug('token file could not open.')
try:
self.getAccessToken()
except Exception:
logging.debug('get access token error.')
raise Exception('createHeaders Error.')
return
# トークン内容をチェック、トークン内容がNoneの場合はトークン取得からやり直す
if self.token == None:
logging.debug('token file is not correct.')
try:
self.getAccessToken()
except Exception:
logging.debug('get access token error.')
raise Exception('createHeaders Error.')
return
# トークン内容をチェック、トークンが壊れている場合はやはりトークン取得からやり直す
if 'expires_in' not in self.token:
logging.debug('token file is not correct.')
try:
self.getAccessToken()
except Exception:
logging.debug('get access token error.')
raise Exception('createHeaders Error.')
return
# トークン有効期限をチェックし、必要ならupdateする
if self.isTokenExpired():
self.updateToken()
# トークンヘッダを追加
headers['X-Auth-Token'] = self.token['access_token']
logging.debug('Headers : %s' % headers)
return headers
def createHeaders_noauth(self):
headers = {
'Fiware-Service':self.fiwareservice,
'Fiware-ServicePath':self.fiwareservicepath
}
logging.debug('Headers : %s' % headers)
return headers
def updateEntity(self, bodypart):
try:
headers = self.createHeaders()
except Exception:
logging.debug('Create Headers error.')
return
headers['Content-Type'] = 'application/json'
#headers['Accept'] = 'application/json'
# URLを生成
url = self.cb_host + "/v2/entities" + "/" +self.data_id + "/" + "attrs"
self.mySendRequest(url=url, data=bodypart, headers=headers)
def registerEntity(self, body):
# すでに登録されているか調べ、登録されている場合は何もしない
#if self.getTargetEntity() != None:
# logging.debug('Already Registered!')
# return
try:
headers = self.createHeaders()
except Exception:
logging.debug('Create Headers error.')
return
headers['Content-Type'] = 'application/json'
url = self.cb_host + "/v2/entities"
return(self.mySendRequest(url=url, data=body, headers=headers))
def registerSubscription(self, subscription_body):
try:
headers = self.createHeaders()
except Exception:
logging.debug('Create Headers error.')
return
headers['Content-Type'] = 'application/json'
url = self.cb_host + "/v2/subscriptions"
#request = urllib2.Request(url, subscription_body, headers)
return(self.mySendRequest(url=url, data=subscription_body, headers=headers))
def getEntities(self):
url = self.cb_host + "/v2/entities"
headers = self.createHeaders()
return(self.mySendRequest(url=url, headers=headers))
def getTargetEntity(self, id):
url = self.cb_host + "/v2/entities" + "/" + id
logging.debug('url is %s' % url)
headers = self.createHeaders()
return(self.mySendRequest(url=url, headers=headers))
def getSubscriptions(self):
url = self.cb_host + "/v2/subscriptions"
headers = self.createHeaders()
return(self.mySendRequest(url=url, headers=headers))
def deleteEntity(self, id):
# 登録されているか調べ、登録されていなければ何もしない
#if self.getTargetEntity() == None:
# return
url = self.cb_host + "/v2/entities" + "/" + id
headers = self.createHeaders()
return(self.mySendRequest(url=url, headers=headers, method='DELETE'))
def deleteAllSubscriptions(self):
subscriptions = self.getSubscriptions()
for subsc in subscriptions:
logging.debug('subscription : %s' % subsc)
self.deleteSubscription(subsc)
return
def deleteSubscription(self, subscription_data):
headers = self.createHeaders()
subscriptionids = self.getSubscriptions()
for id in subscriptionids:
if id['notification']['http']['url'] == subscription_data['notification']['http']['url']:
url = self.cb_host + "/v2/subscriptions" + "/" + id['id']
self.mySendRequest(url=url, headers=headers, method='DELETE')
return
def getAccessToken(self):
header = {'Content-Type':'application/json'}
data = {
'username' : self.username,
'password' : self.password
}
body = json.dumps(data)
url = self.cb_host + "/token"
request = {'url':url, 'data':body, 'headers':header}
try:
self.token = self.mySendRequest(**request)
except Exception:
logging.debug('get new token error.')
sys.exit()
self.token_issued_time = datetime.datetime.now()
# トークンと更新時間をファイルに書き込む
with open(self.tokenfilename, "wb") as tokenfile:
pickle.dump(self.token, tokenfile)
pickle.dump(self.token_issued_time, tokenfile)
logging.debug('Acquired Token : %s' % self.token)
logging.debug('Token Issued Time : %s' % self.token_issued_time)