ngsi9.py
Go to the documentation of this file.
00001 # MIT License
00002 #
00003 # Copyright (c) <2015> <Ikergune, Etxetar>
00004 #
00005 # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
00006 # (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge,
00007 # publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
00008 # subject to the following conditions:
00009 #
00010 # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
00011 #
00012 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
00013 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
00014 # FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
00015 # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
00016 
00017 import os
00018 import copy
00019 import json
00020 import urllib2
00021 
00022 from include.logger import Log
00023 from include.constants import INDEX_CONTEXTBROKER, DATA_CONTEXTBROKER, SUBSCRIPTION_LENGTH
00024 
00025 # PubSub Handlers
00026 from include.pubsub.contextbroker.cbPublisher import CbPublisher
00027 
00028 contexts = {}
00029 Publisher = CbPublisher()
00030 
00031 
00032 def registerContext(entity_id, data_type, robot, isPattern=False):
00033     ## \brief Register context in NGSI9
00034     # \param entity name
00035     # \param entity type
00036     # \param robot object (with topics)
00037     # \param if entity name is pattern (default false)
00038     url = "http://{}:{}/NGSI9/registerContext".format(INDEX_CONTEXTBROKER["ADDRESS"], INDEX_CONTEXTBROKER["PORT"])
00039     attributes = topics2NGSI9(robot)
00040     current_path = os.path.dirname(os.path.abspath(__file__))
00041     json_path = current_path.replace("scripts/include/pubsub/contextbroker", "config/robotdescriptions.json")
00042     description_data = json.load(open(json_path))
00043     if entity_id in description_data:
00044         attributes.append({
00045             "name": "descriptions",
00046             "type": "publisher:DescriptionData",
00047             "isDomain": "false"
00048         })
00049     data = {
00050         "contextRegistrations": [
00051             {
00052                 "entities": [
00053                     {
00054                         "type": data_type,
00055                         "isPattern": "false",
00056                         "id": entity_id
00057                     }
00058                 ],
00059                 "attributes": attributes,
00060                 "providingApplication": "http://{}:{}".format(DATA_CONTEXTBROKER["ADDRESS"], DATA_CONTEXTBROKER["PORT"])
00061             }
00062         ],
00063         "duration": SUBSCRIPTION_LENGTH
00064     }
00065     response_body = _sendRequest(url, json.dumps(data))
00066     if response_body is not None:
00067         if "registrationId" in response_body:
00068             contexts[entity_id] = {
00069                 "data": data,
00070                 "registrationId": response_body["registrationId"]
00071             }
00072 
00073             if entity_id in description_data:
00074                 _descs = ""
00075                 for link in description_data[entity_id]["descriptions"]:
00076                     _descs = _descs + "||" + link
00077                 Publisher.publish(entity_id, data_type, [{
00078                     "name": "descriptions",
00079                     "type": "DescriptionData",
00080                     "value": _descs[2:]
00081                 }])
00082 
00083 
00084 def deleteAllContexts():
00085     ## \brief Delete all contexts from NGSI9
00086     for key in contexts:
00087         deleteContext(key)
00088 
00089 
00090 def deleteContext(entity_id, delete=False):
00091     ## \brief Delete context from NGSI9
00092     # \param entity name
00093     # \param if context must be deleted locally (default false)
00094     if entity_id in contexts:
00095         url = "http://{}:{}/NGSI9/registerContext".format(INDEX_CONTEXTBROKER["ADDRESS"], INDEX_CONTEXTBROKER["PORT"])
00096         data = {
00097             "contextRegistrations": [
00098                 {
00099                     "providingApplication": "http://{}:{}".format(DATA_CONTEXTBROKER["ADDRESS"], DATA_CONTEXTBROKER["PORT"])
00100                 }
00101             ],
00102             "duration": "P0D",
00103             "registrationId": contexts[entity_id]["registrationId"]
00104         }
00105         _sendRequest(url, json.dumps(data))
00106         if delete:
00107             del contexts[entity_id]
00108 
00109 
00110 def refreshAllContexts():
00111     ## \brief Refresh exisiting NGSI9 contexts on context broker
00112     for key in contexts:
00113         refreshContext(key)
00114 
00115 
00116 def refreshContext(entity_id):
00117     ## \brief Refresh exisiting NGSI9 context on context broker
00118     # \param entity name
00119     url = "http://{}:{}/NGSI9/registerContext".format(INDEX_CONTEXTBROKER["ADDRESS"], INDEX_CONTEXTBROKER["PORT"])
00120     data = copy.deepcopy(contexts[entity_id]["data"])
00121     data["registrationId"] = contexts[entity_id]["registrationId"]
00122     _sendRequest(url, json.dumps(data))
00123 
00124 
00125 def topics2NGSI9(robot):
00126     ## \brief Robot topics to NGSI9 transcoder
00127     # \param robot
00128     return iterateTopics(robot["publisher"], "publisher") + iterateTopics(robot["subscriber"], "subscriber")
00129 
00130 
00131 def iterateTopics(topics, topic_type):
00132     ## \brief Topic iterator
00133     # \param topics
00134     # \param topic type
00135     elems = []
00136     for key in topics:
00137         elems.append({
00138             "name": key,
00139             "type": topic_type + ":" + topics[key]["class"]._type.replace("/", ".msg."),
00140             "isDomain": "false"
00141         })
00142     return elems
00143 
00144 
00145 def _sendRequest(url, data, method=None):
00146     ## \brief Send request to context broker
00147     # \param url to request to
00148     # \param data to send
00149     # \param HTTP method (GET by default)
00150     try:
00151         request = urllib2.Request(url, data, {'Content-Type': 'application/json', 'Accept': 'application/json'})
00152         if method is not None:
00153             request.get_method = lambda: method
00154         response = urllib2.urlopen(request)
00155         data = response.read()
00156         response_body = json.loads(data)
00157         response.close()
00158         return response_body
00159     except Exception as ex:
00160             Log("ERROR", ex.reason)
00161             return None


firos
Author(s): IƱigo Gonzalez, igonzalez@ikergune.com
autogenerated on Thu Jun 6 2019 17:51:04