Skip to content
This repository has been archived by the owner on Jan 8, 2024. It is now read-only.

Commit

Permalink
Redesign of constants.py and corresponding changes #3
Browse files Browse the repository at this point in the history
  • Loading branch information
iml-dlux committed Feb 6, 2019
1 parent f78011a commit bf7fa68
Show file tree
Hide file tree
Showing 11 changed files with 247 additions and 237 deletions.
54 changes: 29 additions & 25 deletions scripts/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@
import signal
import argparse

current_path = os.path.dirname(os.path.abspath(__file__))
FIROS_CONF_PATH = [current_path + "/../config"]


from include.constants import Constants as C

# Main function.
if __name__ == '__main__':
Expand All @@ -51,60 +52,62 @@
# Get Input
results = parser.parse_args()



current_path = os.path.dirname(os.path.abspath(__file__))
conf_path = current_path + "/../config"
if results.conf_Fold is not None:
current_path = os.getcwd()
FIROS_CONF_PATH[0] = current_path + "/" + results.conf_Fold
conf_path= current_path + "/" + results.conf_Fold
# TODO DL This re-assignment is currently not working!

C.init(conf_path)


# Importing firos specific scripts
from setup import launchSetup
from include import constants as c


from include import confManager
from include.logger import Log
from include.logger import Log
from include.mapServer import MapServer
from include.server.firosServer import FirosServer

from include.ros.topicHandler import RosTopicHandler, loadMsgHandlers, createConnectionListeners
from include.rcm import topicManager
from include.ros.topicHandler import RosTopicHandler, loadMsgHandlers, createConnectionListeners, initPubAndSub
from include.rcm.topicManager import TopicManager




if results.port is not None and type(results.port) is int:
c.MAP_SERVER_PORT = results.port
if results.port is not None:
C.MAP_SERVER_PORT = int(results.port)

if results.ros_port is not None and type(results.ros_port) is int:
c.ROSBRIDGE_PORT = results.ros_port
if results.ros_port is not None:
C.ROSBRIDGE_PORT = int(results.ros_port)

if results.ros_node_name is not None and type(results.ros_node_name) is str:
c.ROS_NODE_NAME = results.ros_node_name
if results.ros_node_name is not None:
C.ROS_NODE_NAME = results.ros_node_name

if results.loglevel is not None and type(results.loglevel) is int:
c.LOGLEVEL = results.loglevel
if results.loglevel is not None:
C.LOGLEVEL = results.loglevel


Log("INFO", "Initializing ROS node: " + c.ROS_NODE_NAME)
rospy.init_node(c.ROS_NODE_NAME)
Log("INFO", "Initializing ROS node: " + C.ROS_NODE_NAME)
rospy.init_node(C.ROS_NODE_NAME)
Log("INFO", "Initialized")




print C.ROS_NODE_NAME
toMa = TopicManager()

try:
server = FirosServer("0.0.0.0", c.MAP_SERVER_PORT)
server = FirosServer("0.0.0.0", C.MAP_SERVER_PORT)
except Exception as ex:
sys.stderr.write('CB_COMMUNICATION_FAILED')
exit(1)
else:
def signal_handler(signal, frame):
Log("INFO", ('\nExiting from the application'))
RosTopicHandler.unregisterAll()
topicManager.removeListeners()
toMa.removeListeners()
server.close()
Log("INFO", ('\nExit'))
sys.exit(0)
Expand All @@ -116,11 +119,12 @@ def signal_handler(signal, frame):
Log("INFO", "\nStarting Firos...")
Log("INFO", "---------------------------------\n")

#Topic Handler Routine:
initPubAndSub()
loadMsgHandlers(confManager.getRobots(True, True))
createConnectionListeners()
topicManager.setListeners()

MapServer.load()
maSe = MapServer()

Log("INFO", "\nPress Ctrl+C to Exit\n")
server.start()
Expand Down
5 changes: 2 additions & 3 deletions scripts/include/confManager.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@
# FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import os
import json
import copy
import traceback

from include.logger import Log
from include.ros.rosConfigurator import RosConfigurator
from include.constants import Constants as C


def getRobots(refresh=False, withJson=True):
Expand Down Expand Up @@ -55,8 +55,7 @@ def getRobots(refresh=False, withJson=True):
def getRobotsByJson():
## \brief Get robots in the JSON file
try:
current_path = os.path.dirname(os.path.abspath(__file__))
json_path = current_path.replace("scripts/include", "config/robots.json")
json_path = C.PATH + "/robots.json"
return json.load(open(json_path))
except:
return {}
172 changes: 84 additions & 88 deletions scripts/include/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,94 +19,90 @@
import urllib2
import netifaces

from core import FIROS_CONF_PATH



def setConfiguration(path):
try:
data = json.load(open(path + "/config.json"))
return data[data["environment"]]
except:
return {}

configured = False

# All Constants with their default value!
PATH = None

LOGLEVEL = "INFO"
INTERFACE = "public"

MAP_SERVER_ADRESS = None
MAP_SERVER_PORT = 10100
ROSBRIDGE_PORT = 9090
CONTEXTBROKER_ADRESS = None
CONTEXTBROKER_PORT = None

CB_THROTTLING = 0
CB_SUB_LENGTH = 300 # In Seconds!
CB_SUB_REFRESH = 0.9 # After 90% of time is exceeded
CB_CONTEXT_TYPE = "ROBOT"

ROS_NODE_NAME = "firos"
ROS_SUB_QUEUE_SIZE = 10



if not configured:
configured = True
PATH = FIROS_CONF_PATH[0]
print PATH

configData = setConfiguration(PATH)

if "interface" in configData:
INTERFACE = configData["interface"]

if "log_level" in configData:
LOGLEVEL = configData["log_level"]

if "server" in configData and "port" in configData["server"]:
MAP_SERVER_PORT = configData["server"]["port"]

try:
CONTEXTBROKER_ADRESS = configData["contextbroker"]["address"]
CONTEXTBROKER_PORT = configData["contextbroker"]["port"]
except:
print "TODO DL"

if "contextbroker" in configData and "subscription" in configData["contextbroker"]:
# Configuration for Subscription
subConfig = configData["contextbroker"]["subscription"]
if "throttling" in subConfig:
CB_THROTTLING = subConfig["throttling"]

if "subscription_length" in subConfig:
CB_SUB_LENGTH = subConfig["subscription_length"]

if "subscription_refresh_delay" in subConfig:
CB_SUB_REFRESH = subConfig["subscription_refresh_delay"]


if "node_name" in configData:
ROS_NODE_NAME = configData["node_name"]

if "ros_subscriber_queue" in configData:
ROS_SUB_QUEUE_SIZE = configData["ros_subscriber_queue"]

if "cb_type" in configData:
CB_CONTEXT_TYPE = configData["cb_type"]


if INTERFACE == "public":
MAP_SERVER_ADRESS = urllib2.urlopen('http://ip.42.pl/raw').read()
else:
netifaces.ifaddresses(INTERFACE)
MAP_SERVER_ADRESS = netifaces.ifaddresses(INTERFACE)[2][0]['addr']

if "rosbridge_port" in configData:
ROSBRIDGE_PORT = configData["rosbridge_port"]
class Constants:
configured = False
PATH = None
# All Constants with their default value!
LOGLEVEL = "INFO"
INTERFACE = "public"

MAP_SERVER_ADRESS = None
MAP_SERVER_PORT = 10100
ROSBRIDGE_PORT = 9090
CONTEXTBROKER_ADRESS = None
CONTEXTBROKER_PORT = None

CB_THROTTLING = 0
CB_SUB_LENGTH = 300 # In Seconds!
CB_SUB_REFRESH = 0.9 # After 90% of time is exceeded
CB_CONTEXT_TYPE = "ROBOT"

ROS_NODE_NAME = "firos"
ROS_SUB_QUEUE_SIZE = 10

@classmethod
def setConfiguration(cls, path):
try:
data = json.load(open(path + "/config.json"))
return data[data["environment"]]
except:
return {}

@classmethod
def init(cls, path):
if not cls.configured:
configured = True
cls.PATH = path
print cls.PATH # TODO DL print

configData = cls.setConfiguration(path)

if "interface" in configData:
cls.INTERFACE = configData["interface"]

if "log_level" in configData:
cls.LOGLEVEL = configData["log_level"]

if "server" in configData and "port" in configData["server"]:
cls. MAP_SERVER_PORT = configData["server"]["port"]

try:
cls.CONTEXTBROKER_ADRESS = configData["contextbroker"]["address"]
cls.CONTEXTBROKER_PORT = configData["contextbroker"]["port"]
except:
print "TODO DL"

if "contextbroker" in configData and "subscription" in configData["contextbroker"]:
# Configuration for Subscription
subConfig = configData["contextbroker"]["subscription"]
if "throttling" in subConfig:
cls.CB_THROTTLING = subConfig["throttling"]

if "subscription_length" in subConfig:
cls.CB_SUB_LENGTH = subConfig["subscription_length"]

if "subscription_refresh_delay" in subConfig:
cls.CB_SUB_REFRESH = subConfig["subscription_refresh_delay"]


if "node_name" in configData:
cls.ROS_NODE_NAME = configData["node_name"]

if "ros_subscriber_queue" in configData:
cls.ROS_SUB_QUEUE_SIZE = configData["ros_subscriber_queue"]

if "cb_type" in configData:
cls.CB_CONTEXT_TYPE = configData["cb_type"]


if cls.INTERFACE == "public":
cls.MAP_SERVER_ADRESS = urllib2.urlopen('http://ip.42.pl/raw').read()
else:
netifaces.ifaddresses(cls.INTERFACE)
cls.MAP_SERVER_ADRESS = netifaces.ifaddresses(cls.INTERFACE)[2][0]['addr']

if "rosbridge_port" in configData:
cls.ROSBRIDGE_PORT = configData["rosbridge_port"]



20 changes: 13 additions & 7 deletions scripts/include/contextbroker/cbPublisher.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,11 @@
import requests

from include.logger import Log
from include.constants import CONTEXTBROKER_ADRESS, CONTEXTBROKER_PORT, PATH
from include.constants import Constants as C
from include.FiwareObjectConverter.objectFiwareConverter import ObjectFiwareConverter


CB_BASE_URL = "http://{}:{}/v2/entities/".format(CONTEXTBROKER_ADRESS, CONTEXTBROKER_PORT)
CB_HEADER = {'Content-Type': 'application/json'}


class CbPublisher(object):
''' The CbPublisher handles the Enities on CONTEXT_BROKER / v2 / entities .
Expand All @@ -44,6 +43,13 @@ class CbPublisher(object):
# Keeps track of the posted Content on the ContextBroker
# via posted_history[ROBOT_ID][TOPIC]
posted_history = {}
CB_HEADER = {'Content-Type': 'application/json'}
CB_BASE_URL = None

def __init__(self):
''' Lazy Initialization of CB_BASE_URL
'''
self.CB_BASE_URL = "http://{}:{}/v2/entities/".format(C.CONTEXTBROKER_ADRESS, C.CONTEXTBROKER_PORT)

def publishToCB(self, robotID, topic, rawMsg, msgDefintionDict):
''' This is the actual publish-Routine which updates and creates Entities on the
Expand All @@ -64,7 +70,7 @@ def publishToCB(self, robotID, topic, rawMsg, msgDefintionDict):
self.posted_history[robotID]['id'] = robotID
# Intitialize Entitiy/Robot-Construct on ContextBroker
jsonStr = ObjectFiwareConverter.obj2Fiware(self.posted_history[robotID], ind=0, ignorePythonMetaData=True)
response = requests.post(CB_BASE_URL, data=jsonStr, headers=CB_HEADER)
response = requests.post(self.CB_BASE_URL, data=jsonStr, headers=self.CB_HEADER)
self._responseCheck(response, attrAction=0, topEnt=robotID)

if topic not in self.posted_history[robotID]:
Expand Down Expand Up @@ -98,15 +104,15 @@ def publishToCB(self, robotID, topic, rawMsg, msgDefintionDict):


# Update attribute on ContextBroker
response = requests.post(CB_BASE_URL + robotID + "/attrs", data=partJsonStr, headers=CB_HEADER)
response = requests.post(self.CB_BASE_URL + robotID + "/attrs", data=partJsonStr, headers=self.CB_HEADER)
self._responseCheck(response, attrAction=1, topEnt=topic)


def unpublishALLFromCB(self):
''' Removes all previously tracked Entities/Robots on ContextBroker
'''
for robotID in self.posted_history:
response = requests.delete(CB_BASE_URL + robotID)
response = requests.delete(self.CB_BASE_URL + robotID)
self._responseCheck(response, attrAction=2, topEnt=robotID)


Expand All @@ -116,7 +122,7 @@ def _loadDescriptions(self, robotID):
robotID: The Robot-Id-String
'''
json_path = PATH + "/robotdescriptions.json"
json_path = C.PATH + "/robotdescriptions.json"
description_data = json.load(open(json_path))

# Check if a robotID has descriptions
Expand Down
Loading

0 comments on commit bf7fa68

Please sign in to comment.