Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
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
00032 def createContent(self, topic, datatype, data):
00033
00034
00035
00036
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
00046
00047
00048
00049 _publish(context_id, datatype, attributes, DATA_CONTEXTBROKER)
00050
00051 def publishMap(self, context_id, attributes=[]):
00052
00053
00054
00055 _publish(context_id, "MAP", attributes, DATA_CONTEXTBROKER, False)
00056
00057 def publishMsg(self, attributes=[]):
00058
00059
00060 _publish("rosmsg", "ROSDEFINITION", attributes, INDEX_CONTEXTBROKER, False)
00061
00062
00063 def _publish(context_id, datatype, attributes, connection, sendCommand=True):
00064
00065
00066
00067
00068
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