cbPublisher.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 json
00018 import time
00019 import rospy
00020 import urllib2
00021 
00022 from include.logger import Log
00023 from include.constants import INDEX_CONTEXTBROKER, DATA_CONTEXTBROKER, SEPARATOR_CHAR
00024 from include.pubsub.iPubSub import Ipublisher
00025 
00026 PUBLISH_FREQUENCY = 250
00027 posted_history = {}
00028 
00029 
00030 class CbPublisher(Ipublisher):
00031     ## \brief Context broker publisher class
00032     def createContent(self, topic, datatype, data):
00033         ## \brief Format the data into FIROS format
00034         # \param topic name
00035         # \param topic type
00036         # \param topic value
00037         data["firosstamp"] = time.time()
00038         return {
00039             "name": topic,
00040             "type": datatype,
00041             "value": json.dumps(data).replace('"', SEPARATOR_CHAR)
00042         }
00043 
00044     def publish(self, context_id, datatype, attributes=[]):
00045         ## \brief Publish data of an entity in context broker
00046         # \param entity name
00047         # \param entity type
00048         # \param entity attributes
00049         _publish(context_id, datatype, attributes, DATA_CONTEXTBROKER)
00050 
00051     def publishMap(self, context_id, attributes=[]):
00052         ## \brief Publish data of an entity in context broker
00053         # \param map topic name
00054         # \param map connections
00055         _publish(context_id, "MAP", attributes, DATA_CONTEXTBROKER, False)
00056 
00057     def publishMsg(self, attributes=[]):
00058         ## \brief Publish message structures in context broker
00059         # \param entity attributes
00060         _publish("rosmsg", "ROSDEFINITION", attributes, INDEX_CONTEXTBROKER, False)
00061 
00062 
00063 def _publish(context_id, datatype, attributes, connection, sendCommand=True):
00064     ## \brief Publish data of an entity in context broker
00065     # \param entity name
00066     # \param entity type
00067     # \param entity attributes
00068     # \param context broker to send to
00069     if context_id not in posted_history:
00070         posted_history[context_id] = {}
00071     commands = []
00072     attr2Send = []
00073     current = time.time() * 1000
00074     for attribute in attributes:
00075         if attribute["name"] not in posted_history[context_id]:
00076             posted_history[context_id][attribute["name"]] = 0
00077         if (current - posted_history[context_id][attribute["name"]]) > PUBLISH_FREQUENCY:
00078             commands.append(attribute["name"])
00079             attr2Send.append(attribute)
00080             posted_history[context_id][attribute["name"]] = current
00081 
00082     if len(commands) > 0:
00083         if(sendCommand):
00084             attr2Send.insert(0, {
00085                 "name": "COMMAND",
00086                 "type": "COMMAND",
00087                 "value": commands
00088             })
00089         data = {
00090             "contextElements": [
00091                 {
00092                     "id": context_id,
00093                     "type": datatype,
00094                     "isPattern": "false",
00095                     "attributes": attr2Send
00096                 }
00097             ],
00098             "updateAction": "APPEND"
00099         }
00100 
00101         url = "http://{}:{}/NGSI10/updateContext".format(connection["ADDRESS"], connection["PORT"])
00102         data_json = json.dumps(data)
00103         try:
00104             request = urllib2.Request(url, data_json, {'Content-Type': 'application/json', 'Accept': 'application/json'})
00105             response = urllib2.urlopen(request)
00106             response_body = json.loads(response.read())
00107             response.close()
00108 
00109             if "errorCode" in response_body:
00110                 rospy.logerr("Error sending data to Context Broker:")
00111                 rospy.logerr(response_body["errorCode"]["details"])
00112         except Exception as ex:
00113             Log("ERROR", ex.reason)
00114             return None


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