-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsenseapi.py
executable file
·1867 lines (1518 loc) · 79.5 KB
/
senseapi.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
"""
Copyright (C) [2012] Sense Observation Systems B.V.
Licensed under the Apache License, Version 2.0 (the 'License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import md5, urllib, httplib, json, socket, oauth.oauth as oauth, urlparse, string
class SenseAPI:
"""
Class for interacting with CommonSense Api.
Can be set to interact with either the live or test server.
Can authenticate using session_id and oauth.
"""
def __init__(self):
"""
Constructor function.
"""
self.__api_key__ = ""
self.__session_id__ = ""
self.__status__ = 0
self.__headers__ = {}
self.__response__ = ""
self.__error__ = ""
self.__verbose__ = False
self.__server__ = 'live'
self.__server_url__ = 'api.sense-os.nl'
self.__authentication__ = 'not_authenticated'
self.__oauth_consumer__ = {}
self.__oauth_token__ = {}
self.__use_https__ = True
#===============================================
# C O N F I G U R A T I O N F U N C T I O N S =
#===============================================
def setVerbosity(self, verbose):
"""
Set verbosity of the SenseApi object.
@param verbose (boolean) - True of False
@return (boolean) - Boolean indicating whether setVerbosity succeeded
"""
if not (verbose == True or verbose == False):
return False
else:
self.__verbose__ = verbose
return True
def setServer(self, server):
"""
Set server to interact with.
@param server (string) - 'live' for live server, 'dev' for test server, 'rc' for release candidate
@return (boolean) - Boolean indicating whether setServer succeeded
"""
if server == 'live':
self.__server__ = server
self.__server_url__ = 'api.sense-os.nl'
self.setUseHTTPS()
return True
elif server == 'dev':
self.__server__ = server
self.__server_url__ = 'api.dev.sense-os.nl'
# the dev server doesn't support https
self.setUseHTTPS(False)
return True
elif server == 'rc':
self.__server__ = server
self.__server_url__ = 'api.rc.dev.sense-os.nl'
self.setUseHTTPS(False)
else:
return False
def setUseHTTPS(self, enable = True):
"""
Set whether to use https or http.
@param enable (boolean) - True to enable https (default), False to use http
"""
self.__use_https__ = enable
def __setAuthenticationMethod__(self, method):
if not (method in ['session_id', 'oauth', 'authenticating_session_id', 'authenticating_oauth', 'not_authenticated', 'api_key']):
return False
else:
self.__authentication__ = method
return True
#=======================================
# R E T R I E V A L F U N C T I O N S =
#=======================================
def getResponseStatus(self):
"""
Retrieve the response status code of the last api call
@return (integer) - Http status code
"""
return self.__status__
def getResponseHeaders(self):
"""
Retrieve the response headers of the last api call
@return (dictionary) - Dictonary containing headers
"""
return self.__headers__
def getResponse(self):
"""
Retrieve the response of the last api call
@return (string) - The literal response body, which is likely to be in json format
"""
return self.__response__
def getError(self):
"""
Retrieve the error value
@return (string) - The most recent error message
"""
return self.__error__
def getLocationId(self):
"""
Retrieve the integer that should be present in the Location header after creating an object in CommonSense
@return (string) - String containing the id of the created object, or empty if nothing was created
"""
location = self.__headers__.get('location')
return location.split('/')[-1] if location is not None else None;
def getAllSensors(self):
"""
Retrieve all the user's own sensors by iterating over the SensorsGet function
@return (list) - Array of sensors
"""
j = 0
sensors = []
parameters = {'page':0, 'per_page':1000, 'owned':1}
while True:
parameters['page'] = j
if self.SensorsGet(parameters):
s = json.loads(self.getResponse())['sensors']
sensors.extend(s)
else:
# if any of the calls fails, we cannot be cannot be sure about the sensors in CommonSense
return None
if len(s) < 1000:
break
j += 1
return sensors
def findSensor(self, sensors, sensor_name, device_type = None):
"""
Find a sensor in the provided list of sensors
@param sensors (list) - List of sensors to search in
@param sensor_name (string) - Name of sensor to find
@param device_type (string) - Device type of sensor to find, can be None
@return (string) - sensor_id of sensor or None if not found
"""
if device_type == None:
for sensor in sensors:
if sensor['name'] == sensor_name:
return sensor['id']
else:
for sensor in sensors:
if sensor['name'] == sensor_name and sensor['device_type'] == device_type:
return sensor['id']
return None
#=======================================
# B A S E A P I C A L L M E T H O D =
#=======================================
def __SenseApiCall__ (self, url, method, parameters = None, headers = {}):
heads = {}
heads.update(headers)
body = ''
http_url = url
if self.__authentication__ == 'not_authenticated' and (url == '/users.json' or url == '/users.json?disable_mail=1') and method == 'POST':
heads.update({"Content-type": "application/json", "Accept":"*"})
body = json.dumps(parameters)
elif self.__authentication__ == 'not_authenticated':
self.__status__ = 401
return False
elif self.__authentication__ == 'authenticating_oauth':
heads.update({"Content-type": "application/x-www-form-urlencoded", "Accept":"*"})
if not parameters is None:
http_url = '{0}?{1}'.format(url, urllib.urlencode(parameters, True))
elif self.__authentication__ == 'authenticating_session_id':
heads.update({"Content-type": "application/json", "Accept":"*"})
if not parameters is None:
body = json.dumps(parameters)
elif self.__authentication__ == 'oauth':
oauth_url = 'http://{0}{1}'.format(self.__server_url__, url)
if not parameters is None and (method == 'GET' or method == 'DELETE'):
oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.__oauth_consumer__, token = self.__oauth_token__, http_method = method, http_url = oauth_url, parameters = parameters)
else:
oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.__oauth_consumer__, token = self.__oauth_token__, http_method = method, http_url = oauth_url)
oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), self.__oauth_consumer__, self.__oauth_token__)
http_url = oauth_request.to_url()
# heads.update(oauth_request.to_header())
if not parameters is None:
if method == 'GET' or method == 'DELETE':
pass
# heads.update({"Accept":"*"})
# http_url = '{0}?{1}'.format(url, urllib.urlencode(parameters,True))
else:
heads.update({"Content-type": "application/json", "Accept":"*"})
body = json.dumps(parameters)
elif self.__authentication__ == 'session_id':
heads.update({'X-SESSION_ID':"{0}".format(self.__session_id__)})
if not parameters is None:
if method == 'GET' or method == 'DELETE':
heads.update({"Content-type": "application/x-www-form-urlencoded", "Accept":"*"})
http_url = '{0}?{1}'.format(url, urllib.urlencode(parameters, True))
else:
heads.update({"Content-type": "application/json", "Accept":"*"})
body = json.dumps(parameters)
elif self.__authentication__ == 'api_key':
if parameters is None:
parameters = {}
parameters['API_KEY'] = self.__api_key__
if method == 'GET' or method == 'DELETE':
heads.update({"Content-type": "application/x-www-form-urlencoded", "Accept":"*"})
http_url = '{0}?{1}'.format(url, urllib.urlencode(parameters, True))
else:
heads.update({"Content-type": "application/json", "Accept":"*"})
body = json.dumps(parameters)
else:
self.__status__ = 418
return False
if self.__use_https__ and not self.__authentication__ == 'authenticating_oauth' and not self.__authentication__ == 'oauth':
connection = httplib.HTTPSConnection(self.__server_url__, timeout = 60)
else:
connection = httplib.HTTPConnection(self.__server_url__, timeout = 60)
try:
connection.request(method, http_url, body, heads);
result = connection.getresponse();
except: # TODO: check if this doesnt already generate a status
self.__status__ = 408
return False
self.__headers__ = {}
self.__response__ = result.read()
self.__status__ = result.status
resp_headers = result.getheaders()
connection.close()
for h in resp_headers:
self.__headers__.update({h[0]:h[1]})
self.__headers__ = dict(zip(map(string.lower, self.__headers__.keys()), self.__headers__.values()))
if self.__verbose__:
print "===================CALL==================="
print "Call: {0} {1}".format(method, http_url)
print "Server: {0}".format(self.__server__)
print "Headers: {0}".format(heads)
print "Body: {0}".format(body)
print "==================RESPONSE================"
print "Status: {0}".format(self.__status__)
print "Headers: {0}".format(self.__headers__)
print "Response: {0}".format(self.__response__)
print "==========================================\n"
if self.__status__ == 200 or self.__status__ == 201 or self.__status__ == 302:
return True
else:
return False
#=============================================
# A P I _ K E Y A U T H E N T I C A T I O N =
#=============================================
def SetApiKey(self, api_key):
"""
Set the api key.
@param api_key (string) - A valid api key to authenticate with CommonSense
"""
self.__setAuthenticationMethod__('api_key')
self.__api_key__ = api_key
#==================================================
# S E S S I O N I D A U T H E N T I C A T I O N =
#==================================================
def SetSessionId(self, session_id):
"""
Pass an existing session_id to SenseApi object. Use with care!
@param session_id (string) - A valid session_id obtained by logging into CommonSense
"""
self.__setAuthenticationMethod__('session_id')
self.__session_id__ = session_id
def AuthenticateSessionId(self, username, password):
"""
Authenticate using a username and password.
The SenseApi object will store the obtained session_id internally until a call to LogoutSessionId is performed.
@param username (string) - CommonSense username
@param password (string) - MD5Hash of CommonSense password
@return (bool) - Boolean indicating whether AuthenticateSessionId was successful
"""
self.__setAuthenticationMethod__('authenticating_session_id')
parameters = {'username':username, 'password':password}
if self.__SenseApiCall__("/login.json", "POST", parameters = parameters):
try:
response = json.loads(self.__response__)
except:
self.__setAuthenticationMethod__('not_authenticated')
self.__error__ = "notjson"
return False
try:
self.__session_id__ = response['session_id']
self.__setAuthenticationMethod__('session_id')
return True
except:
self.__setAuthenticationMethod__('not_authenticated')
self.__error__ = "no session_id"
return False
else:
self.__setAuthenticationMethod__('not_authenticated')
self.__error__ = "api call unsuccessful"
return False
def LogoutSessionId(self):
"""
Logout the current session_id from CommonSense
@return (bool) - Boolean indicating whether LogoutSessionId was successful
"""
if self.__SenseApiCall__('/logout.json', 'POST'):
self.__setAuthenticationMethod__('not_authenticated')
return True
else:
self.__error__ = "api call unsuccessful"
return False
# deprecated
def Login (self, username, password):
"""
Deprecated, use AuthenticateSessionId instead
"""
return self.AuthenticateSessionId(username, password)
# deprecated
def Logout (self):
"""
Deprecated, use LogoutSessionId instead
"""
return self.LogoutSessionId()
#=========================================
# O A U T H A U T H E N T I C A T I O N =
#=========================================
def AuthenticateOauth (self, oauth_token_key, oauth_token_secret, oauth_consumer_key, oauth_consumer_secret):
"""
Authenticate using Oauth
@param oauth_token_key (string) - A valid oauth token key obtained from CommonSense
@param oauth_token_secret (string) - A valid oauth token secret obtained from CommonSense
@param oauth_consumer_key (string) - A valid oauth consumer key obtained from CommonSense
@param oauth_consumer_secret (string) - A valid oauth consumer secret obtained from CommonSense
@return (boolean) - Boolean indicating whether the provided credentials were successfully authenticated
"""
self.__oauth_consumer__ = oauth.OAuthConsumer(str(oauth_consumer_key), str(oauth_consumer_secret))
self.__oauth_token__ = oauth.OAuthToken(str(oauth_token_key), str(oauth_token_secret))
self.__authentication__ = 'oauth'
if self.__SenseApiCall__('/users/current.json', 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False
#=======================================
# O A U T H A U T H O R I Z A T I O N =
#=======================================
def OauthSetConsumer(self, oauth_consumer_key, oauth_consumer_secret):
"""
@param oauth_consumer_key (string) - A valid oauth consumer key obtained from CommonSense
@param oauth_consumer_secret (string) - A valid oauth consumer secret obtained from CommonSense
"""
self.__oauth_consumer__ = oauth.OAuthConsumer(str(oauth_consumer_key), str(oauth_consumer_secret))
def OauthSetToken(self, token_key, token_secret, token_verifier = None):
"""
@param token_key (string) - A valid oauth token key obtained from CommonSense
@param token_secret (string) - A valid oauth token secret obtained from CommonSense
@param token_verifier (string) - A valid oauth token verifier obtained from CommonSense
"""
self.__oauth_token__ = oauth.OAuthToken(str(token_key), str(token_secret))
if not token_verifier == None:
self.__oauth_token__.set_verifier(str(token_verifier))
def OauthGetRequestToken(self, oauth_callback = 'http://www.sense-os.nl'):
"""
Obtain temporary credentials at CommonSense. If this function returns True, the clients __oauth_token__ member
contains the temporary oauth request token.
@param oauth_consumer_key (string) - A valid oauth consumer key obtained from CommonSense
@param oauth_consumer_secret (string) - A valid oauth consumer secret obtained from CommonSense
@param oauth_callback (string) (optional) - Oauth callback url
@return (boolean) - Boolean indicating whether OauthGetRequestToken was successful
"""
self.__setAuthenticationMethod__('authenticating_oauth')
# obtain a request token
oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.__oauth_consumer__, \
http_method = 'GET', \
callback = oauth_callback, \
http_url = 'http://api.sense-os.nl/oauth/request_token')
oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), self.__oauth_consumer__, None)
parameters = []
for key in oauth_request.parameters.iterkeys():
parameters.append((key, oauth_request.parameters[key]))
parameters.sort()
if self.__SenseApiCall__('/oauth/request_token', 'GET', parameters = parameters):
response = urlparse.parse_qs(self.__response__)
self.__oauth_token__ = oauth.OAuthToken(response['oauth_token'][0], response['oauth_token_secret'][0])
return True
else:
self.__setAuthenticationMethod__('not_authenticated')
self.__error__ = "error getting request token"
return False
def OauthGetAccessToken(self):
"""
Use token_verifier to obtain an access token for the user. If this function returns True, the clients __oauth_token__ member
contains the access token.
@return (boolean) - Boolean indicating whether OauthGetRequestToken was successful
"""
self.__setAuthenticationMethod__('authenticating_oauth')
# obtain access token
oauth_request = oauth.OAuthRequest.from_consumer_and_token(self.__oauth_consumer__, \
token = self.__oauth_token__, \
callback = '', \
verifier = self.__oauth_token__.verifier, \
http_url = 'http://api.sense-os.nl/oauth/access_token')
oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), self.__oauth_consumer__, self.__oauth_token__)
parameters = []
for key in oauth_request.parameters.iterkeys():
parameters.append((key, oauth_request.parameters[key]))
parameters.sort()
if self.__SenseApiCall__('/oauth/access_token', 'GET', parameters = parameters):
response = urlparse.parse_qs(self.__response__)
self.__oauth_token__ = oauth.OAuthToken(response['oauth_token'][0], response['oauth_token_secret'][0])
self.__setAuthenticationMethod__('oauth')
return True
else:
self.__setAuthenticationMethod__('session_id')
self.__error__ = "error getting access token"
return False
def OauthAuthorizeApplication(self, oauth_duration = 'hour'):
"""
Authorize an application using oauth. If this function returns True, the obtained oauth token can be retrieved using getResponse and will be in url-parameters format.
TODO: allow the option to ask the user himself for permission, instead of doing this automatically. Especially important for web applications.
@param oauth_duration (string) (optional) -'hour', 'day', 'week', 'year', 'forever'
@return (boolean) - Boolean indicating whether OauthAuthorizeApplication was successful
"""
if self.__session_id__ == '':
self.__error__ = "not logged in"
return False
# automatically get authorization for the application
parameters = {'oauth_token':self.__oauth_token__.key, 'tok_expir':self.__OauthGetTokExpir__(oauth_duration), 'action':'ALLOW', 'session_id':self.__session_id__}
if self.__SenseApiCall__('/oauth/provider_authorize', 'POST', parameters = parameters):
if self.__status__ == 302:
response = urlparse.parse_qs(urlparse.urlparse(self.__headers__['location'])[4])
verifier = response['oauth_verifier'][0]
self.__oauth_token__.set_verifier(verifier)
return True
else:
self.__setAuthenticationMethod__('session_id')
self.__error__ = "error authorizing application"
return False
else:
self.__setAuthenticationMethod__('session_id')
self.__error__ = "error authorizing application"
return False
def __OauthGetTokExpir__ (self, duration):
if duration == 'hour':
return 1
if duration == 'day':
return 2
if duration == 'week':
return 3
if duration == 'month':
return 4
if duration == 'forever':
return 0
#================
# S E N S O R S =
#================
def SensorsGet_Parameters(self):
return {'page':0, 'per_page':100, 'shared':0, 'owned':0, 'physical':0, 'details':'full'}
def SensorsGet(self, parameters = None, sensor_id = -1):
"""
Retrieve sensors from CommonSense, according to parameters, or by sensor id.
If successful, result can be obtained by a call to getResponse(), and should be a json string.
@param parameters (dictionary) (optional) - Dictionary containing the parameters for the api-call.
@note - http://www.sense-os.nl/45?nodeId=45&selectedId=11887
@param sensor_id (int) (optional) - Sensor id of sensor to retrieve details from.
@return (boolean) - Boolean indicating whether SensorsGet was successful.
"""
url = ''
if parameters is None and sensor_id <> -1:
url = '/sensors/{0}.json'.format(sensor_id)
else:
url = '/sensors.json'
if self.__SenseApiCall__(url, 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def SensorsDelete(self, sensor_id):
"""
Delete a sensor from CommonSense.
@param sensor_id (int) - Sensor id of sensor to delete from CommonSense.
@return (bool) - Boolean indicating whether SensorsDelete was successful.
"""
if self.__SenseApiCall__('/sensors/{0}.json'.format(sensor_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def SensorsPost_Parameters(self):
return {'sensor': {'name':'', 'display_name':'', 'device_type':'', 'pager_type':'', 'data_type':'', 'data_structure':''}}
def SensorsPost(self, parameters):
"""
Create a sensor in CommonSense.
If SensorsPost is successful, the sensor details, including its sensor_id, can be obtained by a call to getResponse(), and should be a json string.
@param parameters (dictonary) - Dictionary containing the details of the sensor to be created.
@note - http://www.sense-os.nl/46?nodeId=46&selectedId=11887
@return (bool) - Boolean indicating whether SensorsPost was successful.
"""
if self.__SenseApiCall__('/sensors.json', 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def SensorsPut(self, sensor_id, parameters):
"""
Update a sensor in CommonSense.
@param parameters (dictionary) - Dictionary containing the sensor parameters to be updated.
@return (bool) - Boolean indicating whether SensorsPut was successful.
"""
if self.__SenseApiCall__('/sensors/{0}.json'.format(sensor_id), 'PUT', parameters = parameters):
return True
else:
self.__error__ = "api call unscuccessful"
return False
#==================
# M E T A T A G S =
#==================
def SensorsMetatagsGet(self, parameters, namespace = None):
"""
Retrieve sensors with their metatags.
@param namespace (string) - Namespace for which to retrieve the metatags.
@param parameters (dictionary - Dictionary containing further parameters.
@return (bool) - Boolean indicating whether SensorsMetatagsget was successful
"""
ns = "default" if namespace is None else namespace
parameters['namespace'] = ns
if self.__SenseApiCall__('/sensors/metatags.json', 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def GroupSensorsMetatagsGet(self, group_id, parameters, namespace = None):
"""
Retrieve sensors in a group with their metatags.
@param group_id (int) - Group id for which to retrieve metatags.
@param namespace (string) - Namespace for which to retrieve the metatags.
@param parameters (dictionary) - Dictionary containing further parameters.
@return (bool) - Boolean indicating whether GroupSensorsMetatagsGet was successful
"""
ns = "default" if namespace is None else namespace
parameters['namespace'] = ns
if self.__SenseApiCall__('/groups/{0}/sensors/metatags.json'.format(group_id), 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def SensorMetatagsGet(self, sensor_id, namespace = None):
"""
Retrieve the metatags of a sensor.
@param sensor_id (int) - Id of the sensor to retrieve metatags from
@param namespace (stirng) - Namespace for which to retrieve metatags.
@return (bool) - Boolean indicating whether SensorMetatagsGet was successful
"""
ns = "default" if namespace is None else namespace
if self.__SenseApiCall__('/sensors/{0}/metatags.json'.format(sensor_id), 'GET', parameters = {'namespace': ns}):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def SensorMetatagsPost(self, sensor_id, metatags, namespace = None):
"""
Attach metatags to a sensor for a specific namespace
@param sensor_id (int) - Id of the sensor to attach metatags to
@param namespace (string) - Namespace for which to attach metatags
@param metatags (dictionary) - Metatags to attach to the sensor
@return (bool) - Boolean indicating whether SensorMetatagsPost was successful
"""
ns = "default" if namespace is None else namespace
if self.__SenseApiCall__("/sensors/{0}/metatags.json?namespace={1}".format(sensor_id, ns), "POST", parameters = metatags):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def SensorMetatagsPut(self, sensor_id, metatags, namespace = None):
"""
Overwrite the metatags attached to a sensor for a specific namespace
@param sensor_id (int) - Id of the sensor to overwrite metatags for
@param namespace (string) - Namespace for which to overwrite metatags
@param metatags (dictionary) - Metatags to overwrite the existing metatags with
@return (bool) - Boolean indicating whether SensorMetatagsPut was successful
"""
ns = "default" if namespace is None else namespace
if self.__SenseApiCall__("/sensors/{0}/metatags.json?namespace={1}".format(sensor_id, ns), "POST", parameters = metatags):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def SensorMetatagsDelete(self, sensor_id, namespace = None):
"""
Delete the metatags attached to a sensor for a specific namespace
@param sensor_id (int) - Id of the sensor to delete metatags for
@param namespace (string) - Namespace for which to delete metatags
@return (bool) - Boolean indicating whether SensorMetatagsDelete was successful
"""
ns = "default" if namespace is None else namespace
if self.__SenseApiCall__("/sensors/{0}/metatags.json".format(sensor_id), "POST", parameters = {'namespace':ns}):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def SensorsFind(self, parameters, filters, namespace = None):
"""
Find sensors based on a number of filters on metatags in a specific namespace
@param namespace (string) - Namespace to use in filtering on metatags
@param parameters (dictionary) - Dictionary containing additional parameters
@param filters (dictionary) - Dictionary containing the filters on metatags
@return (bool) - Boolean indicating whetehr SensorsFind was successful
"""
ns = "default" if namespace is None else namespace
parameters['namespace'] = ns
if self.__SenseApiCall__("/sensors/find.json?{0}".format(urllib.urlencode(parameters, True)), "POST", parameters = filters):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def GroupSensorsFind(self, group_id, parameters, filters, namespace = None):
"""
Find sensors in a group based on a number of filters on metatags
@param group_id (int) - Id of the group in which to find sensors
@param namespace (string) - Namespace to use in filtering on metatags
@param parameters (dictionary) - Dictionary containing additional parameters
@param filters (dictionary) - Dictioanry containing the filters on metatags
@return (bool) - Boolean indicating whether GroupSensorsFind was successful
"""
ns = "default" if namespace is None else namespace
parameters['namespace'] = ns
if self.__SenseApiCall__("/groups/{0}/sensors/find.json?{1}".format(group_id, urllib.urlencode(parameters, True)), "POST", parameters = filters):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def MetatagDistinctValuesGet(self, metatag_name, namespace = None):
"""
Find the distinct value of a metatag name in a certain namespace
@param metatag_name (string) - Name of the metatag for which to find the distinct values
@param namespace (stirng) - Namespace in which to find the distinct values
@return (bool) - Boolean indicating whether MetatagDistinctValuesGet was successful
"""
ns = "default" if namespace is None else namespace
if self.__SenseApiCall__("/metatag_name/{0}/distinct_values.json", "GET", parameters = {'namespace': ns}):
return True
else:
self.__error__ = "api call unsuccessful"
return False
#=======================
# S E N S O R D A T A =
#=======================
def SensorDataGet_Parameters(self):
return {'page':0, 'per_page':100, 'start_date':0, 'end_date':4294967296, 'date':0, 'next':0, 'last':0, 'sort':'ASC', 'total':1}
def SensorDataGet(self, sensor_id, parameters):
"""
Retrieve sensor data for a specific sensor from CommonSense.
If SensorDataGet is successful, the result can be obtained by a call to getResponse(), and should be a json string.
@param sensor_id (int) - Sensor id of the sensor to retrieve data from.
@param parameters (dictionary) - Dictionary containing the parameters for the api call.
@note - http://www.sense-os.nl/52?nodeId=52&selectedId=11887
@return (bool) - Boolean indicating whether SensorDataGet was successful.
"""
if self.__SenseApiCall__('/sensors/{0}/data.json'.format(sensor_id), 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def SensorsDataGet(self, sensorIds, parameters):
"""
Retrieve sensor data for the specified sensors from CommonSense.
If SensorsDataGet is successful, the result can be obtained by a call to getResponse(), and should be a json string.
@param sensorIds (list) a list of sensor ids to retrieve the data for
@param parameters (dictionary) - Dictionary containing the parameters for the api call.
@return (bool) - Boolean indicating whether SensorsDataGet was successful.
"""
if parameters is None:
parameters = {}
parameters["sensor_id[]"] = sensorIds
if self.__SenseApiCall__('/sensors/data.json', 'GET', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def SensorDataPost(self, sensor_id, parameters):
"""
Post sensor data to a specific sensor in CommonSense.
@param sensor_id (int) - Sensor id of the sensor to post data to.
@param parameters (dictionary) - Data to post to the sensor.
@note - http://www.sense-os.nl/53?nodeId=53&selectedId=11887
"""
if self.__SenseApiCall__('/sensors/{0}/data.json'.format(sensor_id), 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def SensorDataDelete(self, sensor_id, data_id):
"""
Delete a sensor datum from a specific sensor in CommonSense.
@param sensor_id (int) - Sensor id of the sensor to delete data from
@param data_id (int) - Id of the data point to delete
@return (bool) - Boolean indicating whether SensorDataDelete was successful.
"""
if self.__SenseApiCall__('/sensors/{0}/data/{1}.json'.format(sensor_id, data_id), 'DELETE'):
return True
else:
self.__error_ = "api call unsuccessful"
return False
def SensorsDataPost(self, parameters):
"""
Post sensor data to multiple sensors in CommonSense simultaneously.
@param parameters (dictionary) - Data to post to the sensors.
@note - http://www.sense-os.nl/59?nodeId=59&selectedId=11887
@return (bool) - Boolean indicating whether SensorsDataPost was successful.
"""
if self.__SenseApiCall__('/sensors/data.json', 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False
#==================
# S E R V I C E S =
#==================
def ServicesGet (self, sensor_id):
"""
Retrieve services connected to a sensor in CommonSense.
If ServicesGet is successful, the result can be obtained by a call to getResponse() and should be a json string.
@sensor_id (int) - Sensor id of sensor to retrieve services from.
@return (bool) - Boolean indicating whether ServicesGet was successful.
"""
if self.__SenseApiCall__('/sensors/{0}/services.json'.format(sensor_id), 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def ServicesPost_Parameters (self):
return {'service':{'name':'math_service', 'data_fields':['sensor']}, 'sensor':{'name':'', 'device_type':''}}
def ServicesPost (self, sensor_id, parameters):
"""
Create a new service in CommonSense, attached to a specific sensor.
If ServicesPost was successful, the service details, including its service_id, can be obtained from getResponse(), and should be a json string.
@param sensor_id (int) - The sensor id of the sensor to connect the service to.
@param parameters (dictionary) - The specifics of the service to create.
@note: http://www.sense-os.nl/81?nodeId=81&selectedId=11887
@return (bool) - Boolean indicating whether ServicesPost was successful.
"""
if self.__SenseApiCall__('/sensors/{0}/services.json'.format(sensor_id), 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def ServicesDelete (self, sensor_id, service_id):
"""
Delete a service from CommonSense.
@param sensor_id (int) - Sensor id of the sensor the service is connected to.
@param service_id (int) - Sensor id of the service to delete.
@return (bool) - Boolean indicating whether ServicesDelete was successful.
"""
if self.__SenseApiCall__('/sensors/{0}/services/{1}.json'.format(sensor_id, service_id), 'DELETE'):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def ServicesGetExpression(self, sensor_id, service_id):
"""
Get expression for the math service.
@param sensor_id (int) - Id of the sensor to which the service is connected
@param service_id (int) - Id of the service for which to get the expression
@return (bool) - Boolean indicating whether ServicesGetExpression was successful
"""
if self.__SenseApiCall__('/sensors/{0}/services/{1}/GetExpression.json'.format(sensor_id, service_id), "GET"):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def ServicesSet_Parameters (self):
return {'parameters':[]}
def ServicesSetExpression (self, sensor_id, service_id, parameters):
"""
Set expression for the math service.
@param sensor_id (int) - Sensor id of the sensor the service is connected to.
@param service_id (int) - Service id of the service for which to set the expression.
@param parameters (dictonary) - Parameters to set the expression of the math service.
@note - http://www.sense-os.nl/85?nodeId=85&selectedId=11887
@return (bool) - Boolean indicating whether ServicesSetExpression was successful.
"""
if self.__SenseApiCall__('/sensors/{0}/services/{1}/SetExpression.json'.format(sensor_id, service_id), 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def ServicesSetMetod (self, sensor_id, service_id, method, parameters):
"""
Set expression for the math service.
@param sensor_id (int) - Sensor id of the sensor the service is connected to.
@param service_id (int) - Service id of the service for which to set the expression.
@param method (string) - The set method name.
@param parameters (dictonary) - Parameters to set the expression of the math service.
@return (bool) - Boolean indicating whether ServicesSetMethod was successful.
"""
if self.__SenseApiCall__('/sensors/{0}/services/{1}/{2}.json'.format(sensor_id, service_id, method), 'POST', parameters = parameters):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def ServicesGetMetod (self, sensor_id, service_id, method):
"""
Set expression for the math service.
@param sensor_id (int) - Sensor id of the sensor the service is connected to.
@param service_id (int) - Service id of the service for which to set the expression.
@param method (string) - The get method name.
@return (bool) - Boolean indicating whether ServicesSetExpression was successful.
"""
if self.__SenseApiCall__('/sensors/{0}/services/{1}/{2}.json'.format(sensor_id, service_id, method), 'GET'):
return True
else:
self.__error__ = "api call unsuccessful"
return False
def ServicesSetUseDataTimestamp(self, sensor_id, service_id, parameters):
"""
Indicate whether a math service should use the original timestamps of the incoming data, or let CommonSense timestamp the aggregated data.
@param sensors_id (int) - Sensor id of the sensor the service is connected to.
@param service_id (int) - Service id of the service for which to set the expression.
@param parameters (dictonary) - Parameters to set the expression of the math service.
@note - http://www.sense-os.nl/85?nodeId=85&selectedId=11887
@return (bool) - Boolean indicating whether ServicesSetuseDataTimestamp was successful.
"""
if self.__SenseApiCall__('/sensors/{0}/services/{1}/SetUseDataTimestamp.json'.format(sensor_id, service_id), 'POST', parameters = parameters):
return True