diff --git a/CMakeLists.txt~ b/CMakeLists.txt~ deleted file mode 100644 index 84d87a0..0000000 --- a/CMakeLists.txt~ +++ /dev/null @@ -1,163 +0,0 @@ -cmake_minimum_required(VERSION 2.8.3) -project(cloudRos) - -## Find catkin macros and libraries -## if COMPONENTS list like find_package(catkin REQUIRED COMPONENTS xyz) -## is used, also find other catkin packages -find_package(catkin REQUIRED COMPONENTS - roscpp - rospy - std_msgs - message_generation -) - -## System dependencies are found with CMake's conventions -# find_package(Boost REQUIRED COMPONENTS system) - - -## Uncomment this if the package has a setup.py. This macro ensures -## modules and global scripts declared therein get installed -## See http://ros.org/doc/api/catkin/html/user_guide/setup_dot_py.html -# catkin_python_setup() - -################################################ -## Declare ROS messages, services and actions ## -################################################ - -## To declare and build messages, services or actions from within this -## package, follow these steps: -## * Let MSG_DEP_SET be the set of packages whose message types you use in -## your messages/services/actions (e.g. std_msgs, actionlib_msgs, ...). -## * In the file package.xml: -## * add a build_depend and a run_depend tag for each package in MSG_DEP_SET -## * If MSG_DEP_SET isn't empty the following dependencies might have been -## pulled in transitively but can be declared for certainty nonetheless: -## * add a build_depend tag for "message_generation" -## * add a run_depend tag for "message_runtime" -## * In this file (CMakeLists.txt): -## * add "message_generation" and every package in MSG_DEP_SET to -## find_package(catkin REQUIRED COMPONENTS ...) -## * add "message_runtime" and every package in MSG_DEP_SET to -## catkin_package(CATKIN_DEPENDS ...) -## * uncomment the add_*_files sections below as needed -## and list every .msg/.srv/.action file to be processed -## * uncomment the generate_messages entry below -## * add every package in MSG_DEP_SET to generate_messages(DEPENDENCIES ...) - -## Generate messages in the 'msg' folder -# add_message_files( -# FILES -# Message1.msg -# Message2.msg -# ) - -## Generate services in the 'srv' folder - add_service_files( - FILES - Comando.srv - ) - -## Generate actions in the 'action' folder -# add_action_files( -# FILES -# Action1.action -# Action2.action -# ) - -## Generate added messages and services with any dependencies listed here - generate_messages( - DEPENDENCIES - std_msgs - ) - -################################### -## catkin specific configuration ## -################################### -## The catkin_package macro generates cmake config files for your package -## Declare things to be passed to dependent projects -## INCLUDE_DIRS: uncomment this if you package contains header files -## LIBRARIES: libraries you create in this project that dependent projects also need -## CATKIN_DEPENDS: catkin_packages dependent projects also need -## DEPENDS: system dependencies of this project that dependent projects also need -catkin_package( -# INCLUDE_DIRS include -# LIBRARIES space_ros - CATKIN_DEPENDS roscpp rospy std_msgs message_runtime -# DEPENDS system_lib -) - -########### -## Build ## -########### - -## Specify additional locations of header files -## Your package locations should be listed before other locations -# include_directories(include) -include_directories( - ${catkin_INCLUDE_DIRS} -) - -## Declare a cpp library -# add_library(space_ros -# src/${PROJECT_NAME}/space_ros.cpp -# ) - -## Declare a cpp executable -# add_executable(space_ros_node src/space_ros_node.cpp) - -## Add cmake target dependencies of the executable/library -## as an example, message headers may need to be generated before nodes -# add_dependencies(space_ros_node space_ros_generate_messages_cpp) - -## Specify libraries to link a library or executable target against -# target_link_libraries(space_ros_node -# ${catkin_LIBRARIES} -# ) - -############# -## Install ## -############# - -# all install targets should use catkin DESTINATION variables -# See http://ros.org/doc/api/catkin/html/adv_user_guide/variables.html - -## Mark executable scripts (Python etc.) for installation -## in contrast to setup.py, you can choose the destination -# install(PROGRAMS -# scripts/my_python_script -# DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} -# ) - -## Mark executables and/or libraries for installation -# install(TARGETS space_ros space_ros_node -# ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} -# LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} -# RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION} -# ) - -## Mark cpp header files for installation -# install(DIRECTORY include/${PROJECT_NAME}/ -# DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} -# FILES_MATCHING PATTERN "*.h" -# PATTERN ".svn" EXCLUDE -# ) - -## Mark other files for installation (e.g. launch and bag files, etc.) -# install(FILES -# # myfile1 -# # myfile2 -# DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION} -# ) - -############# -## Testing ## -############# - -## Add gtest based cpp test target and link libraries -# catkin_add_gtest(${PROJECT_NAME}-test test/test_space_ros.cpp) -# if(TARGET ${PROJECT_NAME}-test) -# target_link_libraries(${PROJECT_NAME}-test ${PROJECT_NAME}) -# endif() - -## Add folders to be run by python nosetests -# catkin_add_nosetests(test) diff --git a/package.xml b/package.xml index 52deb4d..56c459c 100644 --- a/package.xml +++ b/package.xml @@ -15,22 +15,6 @@ TODO - - - - - - - - - - - - - - - - message_generation @@ -43,6 +27,7 @@ roscpp rospy std_msgs + python3-websocket roscpp rospy std_msgs diff --git a/package.xml~ b/package.xml~ deleted file mode 100644 index d79dec3..0000000 --- a/package.xml~ +++ /dev/null @@ -1,56 +0,0 @@ - - - cloud_ros - 0.0.0 - The cloud_ros package - - - - - alyson - - - - - - TODO - - - - - - - - - - - - - - - - - - - message_generation - - - - message_runtime - - - catkin - roscpp - rospy - std_msgs - roscpp - rospy - std_msgs - - - - - - - - diff --git a/src/__pycache__/roscommands.cpython-38.pyc b/src/__pycache__/roscommands.cpython-38.pyc new file mode 100644 index 0000000..af35356 Binary files /dev/null and b/src/__pycache__/roscommands.cpython-38.pyc differ diff --git a/src/__pycache__/rosrun.cpython-38.pyc b/src/__pycache__/rosrun.cpython-38.pyc new file mode 100644 index 0000000..babe7fb Binary files /dev/null and b/src/__pycache__/rosrun.cpython-38.pyc differ diff --git a/src/__pycache__/rosservice.cpython-38.pyc b/src/__pycache__/rosservice.cpython-38.pyc new file mode 100644 index 0000000..ad4d3d5 Binary files /dev/null and b/src/__pycache__/rosservice.cpython-38.pyc differ diff --git a/src/__pycache__/rostopic.cpython-38.pyc b/src/__pycache__/rostopic.cpython-38.pyc new file mode 100644 index 0000000..7a3735c Binary files /dev/null and b/src/__pycache__/rostopic.cpython-38.pyc differ diff --git a/src/boolean_client.py b/src/boolean_client.py new file mode 100644 index 0000000..a158810 --- /dev/null +++ b/src/boolean_client.py @@ -0,0 +1,94 @@ +#!/usr/bin/python3 + +import time +import locale +import curses +import sys +from pySpacebrew.spacebrew import Spacebrew + +# set the encoding to use for the terminal string +locale.setlocale(locale.LC_ALL, '') +code = locale.getpreferredencoding() + +# initialize the terminal display +stdscr = curses.initscr() +stdscr.keypad(1) +curses.noecho() # turn off echo +curses.curs_set(0) # turn off cursor + +# set-up a variables to hold coordinates +pos_state = 15 +local_state = False +remote_state = False + +# get app name and server from query string +name = "pyBoolean Example" +# server = "sandbox.spacebrew.cc" +server = "forever-spacebrew.herokuapp.com/" + +for cur_ele in sys.argv: + if "name" in cur_ele: + name = cur_ele[5:] + if "server" in cur_ele: + server = cur_ele[7:] + + +# configure the spacebrew client +brew = Spacebrew(name=name, server=server) +brew.addPublisher("local state", "boolean") +brew.addSubscriber("remote state", "boolean") + + +def handleBoolean(value): + global code, stdscr + stdscr.addstr(pos_remote, pos_state, (str(value) + " ").encode(code)) + stdscr.refresh() + + +brew.subscribe("remote state", handleBoolean) + +try: + # start-up spacebrew + brew.start() + + # create and load info message at the top of the terminal window + info_msg = "This is the pySpacebrew library boolean example. It sends out a boolean message every time\n" + info_msg += "the enter or return key is pressed and displays the latest boolean value it has received.\n" + info_msg += "Connected to Spacebrew as: " + name + "\n" + info_msg += "IMPORTANT: don't shrink the Terminal window as it may cause app to crash (bug with curses lib)." + stdscr.addstr(0, 0, info_msg.encode(code)) + stdscr.refresh() + + # update the location for the remote and local dice state + pos_local = stdscr.getyx()[0] + 2 + pos_remote = pos_local + 2 + + # display the label for the remote and local boolean states + stdscr.addstr(pos_local, 0, "local state: ".encode(code), curses.A_BOLD) + stdscr.addstr(pos_remote, 0, "remote state: ".encode(code), curses.A_BOLD) + + # display the starting state for remote and local boolean states + stdscr.addstr(pos_local, pos_state, (str(local_state) + " ").encode(code)) + stdscr.addstr(pos_remote, pos_state, + (str(remote_state) + " ").encode(code)) + stdscr.refresh() + + # listen for keypresses and handle input + while 1: + c = stdscr.getch() + local_state = not local_state + brew.publish('local state', True) + + if (c == 10 or c == 13): + stdscr.addstr(pos_local, pos_state, + (str(local_state) + " ").encode(code)) + + stdscr.refresh() + +# closing out the app and returning terminal to old settings +finally: + brew.stop() + curses.nocbreak() + stdscr.keypad(0) + curses.echo() + curses.endwin() diff --git a/src/main_cloud_ros.py b/src/main_cloud_ros.py index 8b5195b..13c32bf 100755 --- a/src/main_cloud_ros.py +++ b/src/main_cloud_ros.py @@ -1,67 +1,68 @@ -#!/usr/bin/env python +#!/usr/bin/env python3 -import roslib; roslib.load_manifest('cloud_ros') -import rospy -from cloud_ros.srv import Comando -from std_msgs.msg import String -from pySpacebrew.spacebrew import Spacebrew -import rosgraph.masterapi - -import rostopic -from rostopic import rostopicFunctions - -import rosservice -from rosservice import rosserviceFunctions - -import rosrun +import termios +import tty +import time +import json +import sys +import threading +import subprocess +from roscommands import rosCommandsFunctions +import roscommands from rosrun import rosrunFunctions +import rosrun +from rosservice import rosserviceFunctions +import rosservice +from rostopic import rostopicFunctions +import rostopic +import rosgraph.masterapi +from pySpacebrew.spacebrew import Spacebrew +from std_msgs.msg import String +from cloud_ros.srv import Comando +import rospy +import roslib +roslib.load_manifest('cloud_ros') -import roscommands -from roscommands import rosCommandsFunctions -import subprocess -import threading +def send(req): + global brew -import sys, tty, termios + comando = req.comando.split(" ") -import json -import time + if(comando[0] == "rostopic"): + rostopicFunctions(req.comando, brew) + elif(comando[0] == "rosservice"): + rosserviceFunctions(req.comando, brew) + elif(comando[0] == "rosrun"): + rosrunFunctions(req.comando, brew) + elif(comando[0] == "roscommands"): + rosCommandsFunctions(req.comando, brew) + else: + rospy.logwarn("Incorrect command syntax") + return True -def send(req): - - global brew - - comando = req.command.split(" ") - - if(comando[0] == "rostopic"): - rostopicFunctions(req.command, brew) - elif(comando[0] == "rosservice"): - rosserviceFunctions(req.command, brew) - elif(comando[0] == "rosrun"): - rosrunFunctions(req.command, brew) - elif(comando[0] == "roscommands"): - rosCommandsFunctions(req.command, brew) - else: - rospy.logwarn("Incorrect command syntax") def received(data): - global brew - global start_time - - if data['action']=="send" and data['commandRos']=='rostopic': - method = getattr(rostopic, data['function']) - result = method(brew, data['topic'], data['freq'], data['ip']) - elif data['action']=="send" and data['commandRos']=='rosservice': - method = getattr(rosservice, data['function']) - result = method(brew, data['service'], data['args']) - elif data['action']=="send" and data['commandRos']=='rosrun': - method = getattr(rosrun, data['function']) - result = method(brew, data['package'], data['executable'], data['parameters']) - elif data['action']=="send" and data['commandRos']=='roscommands': - method = getattr(roscommands, data['function']) - result = method(brew, data['commands']) - else: - rospy.logwarn(data['title']+"\n"+data['datum']) + print("recieving data via the websocket: " + data) + global brew + global start_time + + if data['action'] == "send" and data['commandRos'] == 'rostopic': + method = getattr(rostopic, data['function']) + result = method(brew, data['topic'], data['freq'], data['ip']) + elif data['action'] == "send" and data['commandRos'] == 'rosservice': + method = getattr(rosservice, data['function']) + result = method(brew, data['service'], data['args']) + elif data['action'] == "send" and data['commandRos'] == 'rosrun': + method = getattr(rosrun, data['function']) + result = method(brew, data['package'], + data['executable'], data['parameters']) + elif data['action'] == "send" and data['commandRos'] == 'roscommands': + method = getattr(roscommands, data['function']) + result = method(brew, data['commands']) + else: + rospy.logwarn(data['title']+"\n"+data['datum']) + class myThread (threading.Thread): def __init__(self, threadID, name, counter): @@ -71,56 +72,70 @@ def __init__(self, threadID, name, counter): self.counter = counter def run(self): - - global brew - - while(True): - orig_settings = termios.tcgetattr(sys.stdin) - tty.setcbreak(sys.stdin) - #tty.setraw(sys.stdin) - ch=sys.stdin.read(1)[0] - - if(ch == 'A'): - comm = "up" - elif(ch == 'B'): - comm = "down" - elif(ch == 'C'): - comm = "right" - elif(ch == 'D'): - comm = "left" - else: - comm = "" - - if(comm != ""): - rosCommandsFunctions(comm, brew) + + global brew + + while(True): + orig_settings = termios.tcgetattr(sys.stdin) + tty.setcbreak(sys.stdin) + # tty.setraw(sys.stdin) + ch = sys.stdin.read(1)[0] + + if(ch == 'A'): + comm = "up" + elif(ch == 'B'): + comm = "down" + elif(ch == 'C'): + comm = "right" + elif(ch == 'D'): + comm = "left" + else: + comm = "" + + if(comm != ""): + rosCommandsFunctions(comm, brew) + def cloud_ros(): - name = "rosPy Example" + name = "rosPy Example" - server = "localhost" - #server = "sandbox.spacebrew.cc" - - global brew + # server = "localhost" + server = "forever-spacebrew.herokuapp.com/" - brew = Spacebrew(name=name, server=server) - brew.addPublisher("Publisher") - brew.addSubscriber("Subscriber") + global brew - try: - # start-up spacebrew - brew.start() - brew.subscribe("Subscriber", received) + brew = Spacebrew(name=name, server=server) + brew.addPublisher("ROS_Publisher") + brew.addPublisher("ROS_Publisher_two", "boolean") + print('main_cloud_ros: adding publisher') + brew.addSubscriber("Subscriber", "string") - thread2 = myThread(1, "Thread-2", 1) - thread2.start() - finally: - rospy.init_node('cloud_ros_node') - rospy.loginfo("cloud_ros node is up and running!!!") + try: + pass + # start-up spacebrew + brew.start() + brew.subscribe("Subscriber", received) - s = rospy.Service('send_data', Comando, send) + # thread2 = myThread(1, "Thread-2", 1) + # thread2.start() + finally: + rospy.init_node('cloud_ros_node') + rospy.loginfo("cloud_ros node is up and running!!!") - rospy.spin() + rospy.loginfo('service has been started') + s = rospy.Service('send_data', Comando, send) + rospy.spin() -if __name__ == '__main__': - cloud_ros() +def myhook(): + global thread2 + brew.stop() + # thread2.raise_exception() + print ("shutdown time!") + +if __name__ == '__main__': + rospy.on_shutdown(myhook) + try: + cloud_ros() + except rospy.ROSInterruptException: + pass \ No newline at end of file diff --git a/src/main_cloud_ros.py~ b/src/main_cloud_ros.py~ deleted file mode 100755 index b4fb82a..0000000 --- a/src/main_cloud_ros.py~ +++ /dev/null @@ -1,132 +0,0 @@ -#!/usr/bin/env python - -import roslib; roslib.load_manifest('cloud_ros') -import rospy -from cloud_ros.srv import Comando -from std_msgs.msg import String -from pySpacebrew.spacebrew import Spacebrew -import rosgraph.masterapi - -import rostopic -from rostopic import rostopicFunctions - -import rosservice -from rosservice import rosserviceFunctions - -import rosrun -from rosrun import rosrunFunctions - -import roscommands -from roscommands import rosCommandsFunctions - -<<<<<<< HEAD -import sensor -from sensor import rosSensors - -======= ->>>>>>> 76550579ceb2a72361e7c3e8cea62b2a3fd5cd65 -import subprocess -import threading - -import sys, tty, termios - -import json -import time - -def send(req): - - global brew - - comando = req.command.split(" ") - - if(comando[0] == "rostopic"): - rostopicFunctions(req.command, brew) - elif(comando[0] == "rosservice"): - rosserviceFunctions(req.command, brew) - elif(comando[0] == "rosrun"): - rosrunFunctions(req.command, brew) - elif(comando[0] == "roscommands"): - rosCommandsFunctions(req.command, brew) - else: - rospy.logwarn("Incorrect command syntax") - -def received(data): - global brew - global start_time - - if data['action']=="send" and data['commandRos']=='rostopic': - method = getattr(rostopic, data['function']) - result = method(brew, data['topic'], data['freq'], data['ip']) - elif data['action']=="send" and data['commandRos']=='rosservice': - method = getattr(rosservice, data['function']) - result = method(brew, data['service'], data['args']) - elif data['action']=="send" and data['commandRos']=='rosrun': - method = getattr(rosrun, data['function']) - result = method(brew, data['package'], data['executable'], data['parameters']) - elif data['action']=="send" and data['commandRos']=='roscommands': - method = getattr(roscommands, data['function']) - result = method(brew, data['commands']) - else: - rospy.logwarn(data['title']+"\n"+data['datum']) - -class myThread (threading.Thread): - def __init__(self, threadID, name, counter): - threading.Thread.__init__(self) - self.threadID = threadID - self.name = name - self.counter = counter - - def run(self): - - global brew - - while(True): - orig_settings = termios.tcgetattr(sys.stdin) - tty.setcbreak(sys.stdin) - #tty.setraw(sys.stdin) - ch=sys.stdin.read(1)[0] - - if(ch == 'A'): - comm = "up" - elif(ch == 'B'): - comm = "down" - elif(ch == 'C'): - comm = "right" - elif(ch == 'D'): - comm = "left" - else: - comm = "" - - if(comm != ""): - rosCommandsFunctions(comm, brew) - -def cloud_ros(): - name = "rosPy Example" - - server = "localhost" - #server = "sandbox.spacebrew.cc" - - global brew - - brew = Spacebrew(name=name, server=server) - brew.addPublisher("Publisher") - brew.addSubscriber("Subscriber") - - try: - # start-up spacebrew - brew.start() - brew.subscribe("Subscriber", received) - - thread2 = myThread(1, "Thread-2", 1) - thread2.start() - finally: - rospy.init_node('cloud_ros_node') - rospy.loginfo("cloud_ros node is up and running!!!") - - s = rospy.Service('send_data', Comando, send) - - rospy.spin() - -if __name__ == '__main__': - cloud_ros() - diff --git a/src/pySpacebrew/__pycache__/__init__.cpython-38.pyc b/src/pySpacebrew/__pycache__/__init__.cpython-38.pyc new file mode 100644 index 0000000..f947ed8 Binary files /dev/null and b/src/pySpacebrew/__pycache__/__init__.cpython-38.pyc differ diff --git a/src/pySpacebrew/__pycache__/spacebrew.cpython-38.pyc b/src/pySpacebrew/__pycache__/spacebrew.cpython-38.pyc new file mode 100644 index 0000000..8ea7193 Binary files /dev/null and b/src/pySpacebrew/__pycache__/spacebrew.cpython-38.pyc differ diff --git a/src/pySpacebrew/spacebrew.py b/src/pySpacebrew/spacebrew.py index a27f124..68ddaf7 100644 --- a/src/pySpacebrew/spacebrew.py +++ b/src/pySpacebrew/spacebrew.py @@ -3,135 +3,205 @@ import json import logging import time +import rospy + class Spacebrew(object): - # Define any runtime errors we'll need - class ConfigurationError(Exception): - def __init__(self, brew, explanation): - self.brew = brew - self.explanation = explanation - def __str__(self): - return repr(self.explanation) - - class Slot(object): - def __init__(self, name, brewType, default = None): - self.name = name - self.type = brewType - self.value = None - self.default = default - def makeConfig(self): - d = { 'name':self.name, 'type':self.type, 'default':self.default } - return d - - class Publisher(Slot): - pass - - class Subscriber(Slot): - def __init__(self, name, brewType, default = None): - super(Spacebrew.Subscriber,self).__init__(name,brewType,default) - self.callbacks=[] - def subscribe(self, target): - self.callbacks.append(target) - def unsubscribe(self, target): - self.callbacks.remove(target) - def disseminate(self, value): - for target in self.callbacks: - target(value) - - def __init__(self, name, description="", server="sandbox.spacebrew.cc", port=9000): - self.server = server - self.port = port - self.name = name - self.description = description - self.connected = False - self.started = False - self.publishers = {} - self.subscribers = {} - self.ws = None - - def addPublisher(self, name, brewType="string", default=None): - if self.connected: - raise ConfigurationError(self,"Can not add a new publisher to a running Spacebrew instance (yet).") - else: - self.publishers[name]=self.Publisher(name, brewType, default) - - def addSubscriber(self, name, brewType="string", default=None): - if self.connected: - raise ConfigurationError(self,"Can not add a new subscriber to a running Spacebrew instance (yet).") - else: - self.subscribers[name]=self.Subscriber(name, brewType, default) - - def makeConfig(self): - subs = map(lambda x:x.makeConfig(),self.subscribers.values()) - pubs = map(lambda x:x.makeConfig(),self.publishers.values()) - d = {'config':{ - 'name':self.name, - 'description':self.description, - 'publish':{'messages':pubs}, - 'subscribe':{'messages':subs}, - }} - return d - - def on_open(self,ws): - logging.info("Opening brew.") - ws.send(json.dumps(self.makeConfig())) - self.connected = True - - def on_message(self,ws,message): - msg = json.loads(message)['message'] - sub=self.subscribers[msg['name']] - sub.disseminate(msg['value']) - - def on_error(self,ws,error): - logging.error("[on_error] ERROR: {0}".format(error)) - logging.error("[on_error] self started " + str(self.started)) - self.on_close(ws) - - def on_close(self, ws): - self.connected = False - while self.started and not self.connected: - time.sleep(5) - self.run() - - def publish(self,name,value): - publisher = self.publishers[name] - message = {'message': { - 'clientName':self.name, - 'name':publisher.name, - 'type':publisher.type, - 'value':value } } - self.ws.send(json.dumps(message)) - - def subscribe(self,name,target): - subscriber = self.subscribers[name] - subscriber.subscribe(target) - - def run(self): - self.ws = websocket.WebSocketApp( "ws://{0}:{1}".format(self.server,self.port), - on_message = lambda ws, msg: self.on_message(ws, msg), - on_error = lambda ws, err: self.on_error(ws,err), - on_close = lambda ws: self.on_close(ws) ) - self.ws.on_open = lambda ws: self.on_open(ws) - self.ws.run_forever() - self.ws = None - - def start(self): - def run(*args): - self.run() - self.started = True - self.thread = threading.Thread(target=run) - self.thread.start() - - def stop(self): - self.started = False - if self.ws is not None: - self.ws.close() - self.thread.join() + # Define any runtime errors we'll need + class ConfigurationError(Exception): + def __init__(self, brew, explanation): + self.brew = brew + self.explanation = explanation + + def __str__(self): + return repr(self.explanation) + + class Slot(object): + def __init__(self, name, brewType, default=None): + self.name = name + self.type = brewType + self.value = None + self.default = default + + def makeConfig(self): + print("the name is: " + str(self.name)) + print("the type is: " + str(self.type)) + print("the default is: " + str(self.default)) + d = {'name': self.name, 'type': self.type, 'default': self.default} + return d + + class Publisher(Slot): + pass + + class Subscriber(Slot): + def __init__(self, name, brewType, default=None): + super(Spacebrew.Subscriber, self).__init__(name, brewType, default) + self.callbacks = [] + + def subscribe(self, target): + self.callbacks.append(target) + + def unsubscribe(self, target): + self.callbacks.remove(target) + + def disseminate(self, value): + for target in self.callbacks: + target(value) + + def __init__(self, name, description="", server="sandbox.spacebrew.cc", port=9090): + rospy.loginfo("initialising spacebrew function") + self.server = server + self.port = port + self.name = name + self.description = description + self.connected = False + self.started = False + self.publishers = {} + print("the length of publsihers is: " + + str(len(self.publishers.values()))) + self.subscribers = {} + self.ws = None + self.HOST = None + + def addPublisher(self, name, brewType="string", default=None): + if self.connected: + raise ConfigurationError( + self, "Can not add a new publisher to a running Spacebrew instance (yet).") + else: + self.publishers[name] = self.Publisher(name, brewType, default) + + def addSubscriber(self, name, brewType="string", default=None): + if self.connected: + raise ConfigurationError( + self, "Can not add a new subscriber to a running Spacebrew instance (yet).") + else: + self.subscribers[name] = self.Subscriber(name, brewType, default) + + def makeConfig(self): + print('inside make config') + subs = map(lambda x: x.makeConfig(), self.subscribers.values()) + print('Finished subs') + pubs = map(lambda x: x.makeConfig(), self.publishers.values()) + + print("the length of publsihers is: " + + str(len(self.publishers.values()))) + count = 0 + publisher_string = '' + for key, value in self.publishers.items(): + count += 1 + if count == len(self.publishers.values()): + publisher_string += str(value.makeConfig()) + else: + publisher_string += str(value.makeConfig()) + ', ' + print("Publisher consists of: {}".format(key)) + + print("The string is: " + publisher_string) + # print('Finished pubs') + # print("The pubs is: {}".format( + # list(pubs))) + # print("The pubs size: {}".format( + # type([{'name': 'ROS_Publisher', 'type': 'string', 'default': None}]))) + + # print("[{'name': 'ROS_Publisher', 'type': 'string', 'default': None}]") + # print("yolo: {}".format(list(pubs))) + # print("The pubs is: {}, of size: {}".format( + # list(pubs), type(list(pubs)))) + # TODO: do not print list(pubs), it somehow erases the value + d = {'config': { + 'name': self.name, + 'description': self.description, + 'publish': {'messages': list(pubs)}, + 'subscribe': {'messages': list(subs)}, + } + } + print('finished everything returning out of makeConfig function: ') + return d + + def on_open(self, ws): + rospy.loginfo("Opennninging brew") + logging.info("Opening brew.") + rospy.logwarn("hello") + result = json.dumps(self.makeConfig()) + rospy.logwarn("hello") + print(result) + self.connected = True + rospy.logwarn("hello2") + ws.send(result) + rospy.logwarn("self connected is changed to true: " + result) + + def on_message(self, ws, message): + msg = json.loads(message)['message'] + sub = self.subscribers[msg['name']] + sub.disseminate(msg['value']) + + def on_error(self, ws, error): + logging.error("[on_error] ERROdndndndnR: {0}".format(error)) + logging.error("[on_error] self started " + str(self.started)) + self.on_close(ws) + + def on_close(self, ws): + print("being asked to close") + self.connected = False + while self.started and not self.connected: + time.sleep(5) + self.run() + + def publish(self, name, value): + publisher = self.publishers[name] + message = {'message': { + 'clientName': self.name, + 'name': publisher.name, + 'type': publisher.type, + 'value': value}} + self.ws.send(json.dumps(message)) + + def subscribe(self, name, target): + subscriber = self.subscribers[name] + subscriber.subscribe(target) + + def run(self): + self.HOST = "ws://" + str(self.server) + ":" + str(self.port) + self.HOST = "ws://" + str(self.server) + + # print("inside the run function. Trying to connect to: "+ "ws://{0}:{1}".format(self.server, self.port)) + print("inside the run function. Trying to connect to: " + self.HOST) + + # self.ws = websocket.WebSocketApp("ws://{0}:{1}".format(self.server, self.port), + # on_message=lambda ws, msg: self.on_message( + # ws, msg), + # on_error=lambda ws, err: self.on_error( + # ws, err), + # on_close=lambda ws: self.on_close(ws)) + self.ws = websocket.WebSocketApp(self.HOST, + on_message=lambda ws, msg: self.on_message( + ws, msg), + on_error=lambda ws, err: self.on_error( + ws, err), + on_close=lambda ws: self.on_close(ws)) + self.ws.on_open = lambda ws: self.on_open(ws) + self.ws.run_forever() + # self.ws = None + + def start(self): + print("starting the brew service") + + def run(*args): + self.run() + rospy.loginfo("calling the run function") + self.started = True + self.thread = threading.Thread(target=run) + self.thread.start() + + def stop(self): + self.started = False + if self.ws is not None: + self.ws.close() + self.thread.join() + if __name__ == "__main__": - print """ + print(""" This is the Spacebrew module. See spacebrew_ex.py for usage examples. -""" - +""") diff --git a/src/roscommands.py b/src/roscommands.py index 4c12027..7ab51bb 100644 --- a/src/roscommands.py +++ b/src/roscommands.py @@ -1,80 +1,87 @@ #!/usr/bin/env python -import roslib; roslib.load_manifest('cloud_ros') -import rospy -from cloud_ros.srv import * -from pySpacebrew.spacebrew import Spacebrew -from std_msgs.msg import String -import rosgraph.masterapi -import time -import os -import subprocess -import threading -from geometry_msgs.msg import Twist from geometry_msgs.msg import Vector3 +from geometry_msgs.msg import Twist +import threading +import subprocess +import os +import time +import rosgraph.masterapi +from std_msgs.msg import String +from pySpacebrew.spacebrew import Spacebrew +from cloud_ros.srv import * +import rospy +import roslib +roslib.load_manifest('cloud_ros') + def rosCommandsFunctions(command, brew): - commandSplit = command.split(" ") - if len(commandSplit) == 1: - data = {'commandRos':'roscommands', 'function':'roscommands', 'action':'send', 'commands':commandSplit[0]} - brew.publish("Publisher", data) - rospy.logwarn("Command sent = "+command) - elif (comandoSplit[1] == "set_robot"): - data = {'commandRos':'roscommands', 'function':'set_robot', 'action':'send', 'commands':commandSplit[2]} - brew.publish("Publisher", data) - rospy.logwarn("Command sent = "+command) - else: - rospy.logwarn("Incorrect command syntax") - + commandSplit = command.split(" ") + if len(commandSplit) == 1: + data = {'commandRos': 'roscommands', 'function': 'roscommands', + 'action': 'send', 'commands': commandSplit[0]} + brew.publish("Publisher", data) + rospy.logwarn("Command sent = "+command) + elif (comandoSplit[1] == "set_robot"): + data = {'commandRos': 'roscommands', 'function': 'set_robot', + 'action': 'send', 'commands': commandSplit[2]} + brew.publish("Publisher", data) + rospy.logwarn("Command sent = "+command) + else: + rospy.logwarn("Incorrect command syntax") + + '''ROSCOMMANDS START''' + + def set_robot(brew, commands): - global robot - robot = commands + global robot + robot = commands + def roscommands(brew, commands): - global robot - rospy.logwarn(robot) + global robot + rospy.logwarn(robot) - vel = Twist() - global proc + vel = Twist() + global proc - vel.linear.x = 0 - vel.linear.y = 0 - vel.linear.z = 0 + vel.linear.x = 0 + vel.linear.y = 0 + vel.linear.z = 0 - vel.angular.x = 0 - vel.angular.y = 0 - vel.angular.z = 0 + vel.angular.x = 0 + vel.angular.y = 0 + vel.angular.z = 0 - if(commands == "up"): - vel.linear.x = 2 - elif(commands == "down"): - vel.linear.x = -2 - elif(commands == "right"): - vel.angular.z = -2 - elif(commands == "left"): - vel.angular.z = 2 + if(commands == "up"): + vel.linear.x = 2 + elif(commands == "down"): + vel.linear.x = -2 + elif(commands == "right"): + vel.angular.z = -2 + elif(commands == "left"): + vel.angular.z = 2 - robots = robot.split(":") + robots = robot.split(":") - for rob in robots: - pub = rospy.Publisher(rob+'/cmd_vel', Twist, queue_size=10) - pub.publish(vel) + for rob in robots: + pub = rospy.Publisher(rob+'/cmd_vel', Twist, queue_size=10) + pub.publish(vel) - vel.linear.x = 0 - vel.linear.y = 0 - vel.linear.z = 0 + vel.linear.x = 0 + vel.linear.y = 0 + vel.linear.z = 0 - vel.angular.x = 0 - vel.angular.y = 0 - vel.angular.z = 0 - - time.sleep(0.5) + vel.angular.x = 0 + vel.angular.y = 0 + vel.angular.z = 0 - pub = rospy.Publisher(rob+'/cmd_vel', Twist, queue_size=10) - pub.publish(vel) + time.sleep(0.5) -'''ROSCOMMANDS END''' + pub = rospy.Publisher(rob+'/cmd_vel', Twist, queue_size=10) + pub.publish(vel) +'''ROSCOMMANDS END''' diff --git a/src/roscommands.py~ b/src/roscommands.py~ deleted file mode 100644 index 0e0cc2e..0000000 --- a/src/roscommands.py~ +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env python - -import roslib; roslib.load_manifest('cloud_ros') -import rospy -from cloud_ros.srv import * -from pySpacebrew.spacebrew import Spacebrew -from std_msgs.msg import String -import rosgraph.masterapi -import time -import os -import subprocess -import threading -from geometry_msgs.msg import Twist -from geometry_msgs.msg import Vector3 - -def rosCommandsFunctions(command, brew): - - commandSplit = command.split(" ") - if len(commandSplit) == 1: - data = {'commandRos':'roscommands', 'function':'roscommands', 'action':'send', 'commands':commandSplit[0]} - brew.publish("Publisher", data) - rospy.logwarn("Command sent = "+command) - elif (comandoSplit[1] == "set_robot"): - data = {'commandRos':'roscommands', 'function':'set_robot', 'action':'send', 'commands':commandSplit[2]} - brew.publish("Publisher", data) - rospy.logwarn("Command sent = "+command) - else: - rospy.logwarn("Incorrect command syntax") - -'''INICIO ROSCOMMANDS''' -def set_robot(brew, commands): - global robot - robot = commands - -def roscommands(brew, commands): - global robot - rospy.logwarn(robot) - - vel = Twist() - global proc - - vel.linear.x = 0 - vel.linear.y = 0 - vel.linear.z = 0 - - vel.angular.x = 0 - vel.angular.y = 0 - vel.angular.z = 0 - - if(commands == "up"): - vel.linear.x = 2 - elif(commands == "down"): - vel.linear.x = -2 - elif(commands == "right"): - vel.angular.z = -2 - elif(commands == "left"): - vel.angular.z = 2 - - robots = robot.split(":") - - for rob in robots: - pub = rospy.Publisher(rob+'/cmd_vel', Twist, queue_size=10) - pub.publish(vel) - - vel.linear.x = 0 - vel.linear.y = 0 - vel.linear.z = 0 - - vel.angular.x = 0 - vel.angular.y = 0 - vel.angular.z = 0 - - time.sleep(0.5) - - pub = rospy.Publisher(rob+'/cmd_vel', Twist, queue_size=10) - pub.publish(vel) - -'''FIM ROSCOMMANDS''' - - diff --git a/src/rosrun.py b/src/rosrun.py index 3906ebc..7302581 100644 --- a/src/rosrun.py +++ b/src/rosrun.py @@ -1,69 +1,78 @@ #!/usr/bin/env python -import roslib; roslib.load_manifest('cloud_ros') -import rospy -from cloud_ros.srv import * -from pySpacebrew.spacebrew import Spacebrew -from std_msgs.msg import String -import rosgraph.masterapi -import time -import os -import subprocess import threading +import subprocess +import os +import time +import rosgraph.masterapi +from std_msgs.msg import String +from pySpacebrew.spacebrew import Spacebrew +from cloud_ros.srv import * +import rospy +import roslib +roslib.load_manifest('cloud_ros') + def rosrunFunctions(command, brew): - global stop_ - stop_ = False - - commandSplit = command.split(" ") - - if len(commandSplit) == 3: - data = {'commandRos':'rosrun', 'function':'rosrun', 'action':'send', 'package':commandSplit[1], 'executable':commandSplit[2], 'parameters':''} - brew.publish("Publisher", data) - rospy.logwarn("Command sent = "+command) - elif len(comandoSplit) == 4: - data = {'commandRos':'rosrun', 'function':'rosrun', 'action':'send', 'package':commandSplit[1], 'executable':commandSplit[2], 'parameters':commandSplit[3]} - brew.publish("Publisher", data) - rospy.logwarn("Command sent = "+command) - else: - rospy.logwarn("Incorrect command syntax") - + global stop_ + stop_ = False + + commandSplit = command.split(" ") + + if len(commandSplit) == 3: + data = {'commandRos': 'rosrun', 'function': 'rosrun', 'action': 'send', + 'package': commandSplit[1], 'executable': commandSplit[2], 'parameters': ''} + brew.publish("Publisher", data) + rospy.logwarn("Command sent = "+command) + elif len(comandoSplit) == 4: + data = {'commandRos': 'rosrun', 'function': 'rosrun', 'action': 'send', + 'package': commandSplit[1], 'executable': commandSplit[2], 'parameters': commandSplit[3]} + brew.publish("Publisher", data) + rospy.logwarn("Command sent = "+command) + else: + rospy.logwarn("Incorrect command syntax") + + '''ROSRUN START''' + def rosrun(brew, package, executable, parameters): - aux = parameters.split("@") - parameters = aux[0] - for i in range(1, len(aux)-1): - parameters+=":="+aux[i] + aux = parameters.split("@") + parameters = aux[0] + for i in range(1, len(aux)-1): + parameters += ":="+aux[i] + + global proc + if(parameters != ''): + proc = subprocess.Popen( + ["rosrun " + package + " " + executable+" "+parameters], stdout=subprocess.PIPE, shell=True) + else: + proc = subprocess.Popen( + ["rosrun " + package + " " + executable], stdout=subprocess.PIPE, shell=True) - global proc - if(parameters != ''): - proc = subprocess.Popen(["rosrun " +package +" "+ executable+" "+parameters], stdout=subprocess.PIPE, shell=True) - else: - proc = subprocess.Popen(["rosrun " +package +" "+ executable], stdout=subprocess.PIPE, shell=True) + data = {'datum': datum, 'title': 'Package running ', 'action': 'receive'} - data = {'datum':datum, 'title':'Package running ', 'action':'receive'} + brew.publish("Publisher", data) - brew.publish("Publisher", data) + thread1 = myThread(1, "Thread-1", 1) + thread1.start() - thread1 = myThread(1, "Thread-1", 1) - thread1.start() '''ROSRUN END''' + class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter - def run(self): - - global proc - print "Starting " + self.name - (datum, err) = proc.communicate() - print "Exiting " + self.name + def run(self): + global proc + print ("Starting " + self.name) + (datum, err) = proc.communicate() + print ("Exiting " + self.name) diff --git a/src/rosrun.py~ b/src/rosrun.py~ deleted file mode 100644 index cacdf70..0000000 --- a/src/rosrun.py~ +++ /dev/null @@ -1,69 +0,0 @@ -#!/usr/bin/env python - -import roslib; roslib.load_manifest('cloud_ros') -import rospy -from cloud_ros.srv import * -from pySpacebrew.spacebrew import Spacebrew -from std_msgs.msg import String -import rosgraph.masterapi -import time -import os -import subprocess -import threading - -def rosrunFunctions(command, brew): - global stop_ - stop_ = False - - commandSplit = command.split(" ") - - if len(commandSplit) == 3: - data = {'commandRos':'rosrun', 'function':'rosrun', 'action':'send', 'package':commandSplit[1], 'executable':commandSplit[2], 'parameters':''} - brew.publish("Publisher", data) - rospy.logwarn("Command sent = "+command) - elif len(comandoSplit) == 4: - data = {'commandRos':'rosrun', 'function':'rosrun', 'action':'send', 'package':commandSplit[1], 'executable':commandSplit[2], 'parameters':commandSplit[3]} - brew.publish("Publisher", data) - rospy.logwarn("Command sent = "+command) - else: - rospy.logwarn("Incorrect command syntax") - -'''INICIO ROSRUN''' - -def rosrun(brew, package, executable, parameters): - - aux = parameters.split("@") - parameters = aux[0] - for i in range(1, len(aux)-1): - parameters+=":="+aux[i] - - global proc - if(parameters != ''): - proc = subprocess.Popen(["rosrun " +package +" "+ executable+" "+parameters], stdout=subprocess.PIPE, shell=True) - else: - proc = subprocess.Popen(["rosrun " +package +" "+ executable], stdout=subprocess.PIPE, shell=True) - - data = {'datum':datum, 'title':'Package running ', 'action':'receive'} - - brew.publish("Publisher", data) - - thread1 = myThread(1, "Thread-1", 1) - thread1.start() - -'''FIM ROSRUN''' - -class myThread (threading.Thread): - def __init__(self, threadID, name, counter): - threading.Thread.__init__(self) - self.threadID = threadID - self.name = name - self.counter = counter - def run(self): - - global proc - - print "Starting " + self.name - (datum, err) = proc.communicate() - print "Exiting " + self.name - - diff --git a/src/rosservice.py b/src/rosservice.py index 51ee29c..96e9ec8 100644 --- a/src/rosservice.py +++ b/src/rosservice.py @@ -37,6 +37,10 @@ def rosserviceFunctions(command, brew): rospy.logwarn("Sent command = "+command) else: argsSplit = command.split('"') + + rospy.loginfo(commandSplit[2]) + rospy.loginfo(argsSplit[1]) + data = {'commandRos':'rosservice', 'function':'rosserviceCall', 'action':'send', 'service':commandSplit[2], 'args':argsSplit[1]} brew.publish("Publisher", data) rospy.logwarn("Sent command = "+command) diff --git a/src/rosservice.py~ b/src/rosservice.py~ deleted file mode 100644 index 137c2df..0000000 --- a/src/rosservice.py~ +++ /dev/null @@ -1,152 +0,0 @@ -#!/usr/bin/env python - -import roslib; roslib.load_manifest('cloud_ros') -import rospy -from cloud_ros.srv import * -from pySpacebrew.spacebrew import Spacebrew -from std_msgs.msg import String -import rosgraph.masterapi -import time -import os -import subprocess - -def rosserviceFunctions(command, brew): - global stop_ - stop_ = False - - commandSplit = command.split(" ") - if commandSplit[1] == "list": - data = {'commandRos':'rosservice', 'function':'rosserviceList', 'action':'send', 'service':'', 'args':''} - brew.publish("Publisher", data) -<<<<<<< HEAD - rospy.logwarn("Sent command = "+command) -======= - rospy.logwarn("sent command = "+command) ->>>>>>> 76550579ceb2a72361e7c3e8cea62b2a3fd5cd65 - - elif commandSplit[1] == "args": - if len(commandSplit) != 3: - rospy.logwarn("syntax = rosservice args /service") - else: - data = {'commandRos':'rosservice', 'function':'rosserviceArgs', 'action':'send', 'service':commandSplit[2], 'args':''} - brew.publish("Publisher", data) -<<<<<<< HEAD - rospy.logwarn("Sent command = "+command) -======= - rospy.logwarn("sent command = "+command) ->>>>>>> 76550579ceb2a72361e7c3e8cea62b2a3fd5cd65 - - elif commandSplit[1] == "call": - if len(commandSplit) < 3: - rospy.logwarn("syntax = rosservice call /service") - elif len(commandSplit) == 3: - data = {'commandRos':'rosservice', 'function':'rosserviceCall', 'action':'send', 'service':commandSplit[2], 'args':''} - brew.publish("Publisher", data) -<<<<<<< HEAD - rospy.logwarn("Sent command = "+command) -======= - rospy.logwarn("sent command = "+command) ->>>>>>> 76550579ceb2a72361e7c3e8cea62b2a3fd5cd65 - else: - argsSplit = command.split('"') - data = {'commandRos':'rosservice', 'function':'rosserviceCall', 'action':'send', 'service':commandSplit[2], 'args':argsSplit[1]} - brew.publish("Publisher", data) -<<<<<<< HEAD - rospy.logwarn("Sent command = "+command) -======= - rospy.logwarn("sent command = "+command) ->>>>>>> 76550579ceb2a72361e7c3e8cea62b2a3fd5cd65 - - elif commandSplit[1] == "node": - if len(commandSplit) != 3: - rospy.logwarn("syntax = rosservice node /service") - else: - data = {'commandRos':'rosservice', 'function':'rosserviceNode', 'action':'send', 'service':commandSplit[2], 'args':''} - brew.publish("Publisher", data) - - rospy.logwarn("Sent command = "+command) - - elif comandoSplit[1] == "type": - rospy.logwarn(command) - if len(commandSplit) < 3: - rospy.logwarn("syntax = rosservice node /service ( | rossrv (show | list | md5 | package | packages))") - elif len(comandoSplit) == 3: - data = {'commandRos':'rosservice', 'function':'rosserviceType', 'action':'send', 'service':commandSplit[2], 'args':''} - brew.publish("Publisher", data) - rospy.logwarn("Sent command = "+command) - else: - argsSplit = command.split('|') - rospy.logwarn('argssplit = '+argsSplit[1]) - data = {'commandRos':'rosservice', 'function':'rosserviceType', 'action':'send', 'service':commandSplit[2], 'args':argsSplit[1]} - brew.publish("Publisher", data) - rospy.logwarn("Sent command = "+command) - - elif commandSplit[1] == "stop": - stop_ = True - - else: - rospy.logwarn("Incorrect command syntax") - -'''ROSSERVICE LIST START''' -def rosserviceList(brew, service, args): - proc = subprocess.Popen(["rosservice list"], stdout=subprocess.PIPE, shell=True) - - (datum, err) = proc.communicate() - - data = {'datum':datum, 'title':"Rosservice list results from master "+brew.name, 'action':'receive'} - - brew.publish("Publisher", data) -'''ROSSERVICE LIST END''' - - -'''ROSSERVICE ARGS START''' -def rosserviceArgs(brew, service, args): - proc = subprocess.Popen(["rosservice args "+service], stdout=subprocess.PIPE, shell=True) - - (datum, err) = proc.communicate() - - data = {'datum':datum, 'title':"Rosservice args "+service+ " results from master "+brew.name, 'action':'receive'} - brew.publish("Publisher", data) -'''ROSSERVICE ARGS END''' - - -'''ROSSERVICE CALL START''' -def rosserviceCall(brew, service, args): - proc = subprocess.Popen(["rosservice call "+service+" '"+args+"'"], stdout=subprocess.PIPE, shell=True) - (dados, err) = proc.communicate() - - data = {'datum':datum, 'title':"Rosservice call "+service+" "+args+ " results from master "+brew.name, 'action':'receive'} - brew.publish("Publisher", data) -'''ROSSERVICE CALL END''' - - -'''ROSSERVICE NODE START''' -def rosserviceNode(brew, service, args): - proc = subprocess.Popen(["rosservice node "+service], stdout=subprocess.PIPE, shell=True) - (datum, err) = proc.communicate() - - data = {'datum':datum, 'title':"Rosservice node "+service+ " results from master "+brew.name, 'action':'receive'} - - brew.publish("Publisher", data) -'''ROSSERVICE NODE END''' - - -'''ROSSERVICE TYPE START''' -def rosserviceType(brew, service, args): - if args=="": - proc = subprocess.Popen(["rosservice type "+service], stdout=subprocess.PIPE, shell=True) - else: - proc = subprocess.Popen(["rosservice type "+service +" | "+ args], stdout=subprocess.PIPE, shell=True) - - (datum, err) = proc.communicate() - - data = {'datum':datum, 'title':"Rosservice type "+service+ " results from master "+brew.name, 'action':'receive'} - brew.publish("Publisher", data) -'''ROSSERVICE TYPE END''' - - - - - - - diff --git a/src/rostopic.py b/src/rostopic.py index 8bb97c4..e45840b 100644 --- a/src/rostopic.py +++ b/src/rostopic.py @@ -1,166 +1,191 @@ #!/usr/bin/env python -import roslib; roslib.load_manifest('cloud_ros') -import rospy -from cloud_ros.srv import * -from pySpacebrew.spacebrew import Spacebrew -from std_msgs.msg import String -from geometry_msgs.msg import Twist -import rosgraph.masterapi -import time -import os +import sys +import importlib import subprocess +import os +import time +import rosgraph.masterapi +from geometry_msgs.msg import Twist +from std_msgs.msg import String +from pySpacebrew.spacebrew import Spacebrew +from cloud_ros.srv import * +import rospy +import roslib +roslib.load_manifest('cloud_ros') -import importlib -import sys #from rosgraph_msgs.msg import Log -from geometry_msgs.msg import Twist #import std_msgs.msg #import geometry_msgs.msg #import rosgraph_msgs.msg + def rostopicFunctions(command, brew): - global stop_ - stop_ = False - global ip_ - - commandSplit = command.split(" ") - if commandSplit[1] == "list": - if(len(commandSplit) < 3): - ip = '' - else: - ip = commandSplit[2] - - data = {'commandRos':'rostopic', 'function':'rostopicList', 'action':'send', 'topic':'', 'freq':'0', 'ip':ip} - - brew.publish("Publisher", data) - rospy.logwarn("Sent command = "+command) - - elif commandSplit[1] == "echo": - if(len(commandSplit) < 5): - ip = '' - else: - ip = commandSplit[4] - - if len(commandSplit) < 4: - rospy.logwarn("syntax = rostopic echo /topic frequency") - else: - data = {'commandRos':'rostopic', 'function':'rostopicEcho', 'action':'send', 'topic':commandSplit[2][1:], 'freq':commandSplit[3], 'ip':ip} - brew.publish("Publisher", data) - rospy.logwarn("Sent command = "+command) - - elif commandSplit[1] == "info": - if(len(commandSplit) < 4): - ip = '' - else: - ip = commandSplit[3] - - data = {'commandRos':'rostopic', 'function':'rostopicInfo', 'action':'send', 'topic':commandSplit[2], 'freq':'0', 'ip':ip} - brew.publish("Publisher", data) - rospy.logwarn("Sent command = "+command) - - elif commandSplit[1] == "stop": - stop_ = True - else: - rospy.logwarn("Incorrect command syntax") - + global stop_ + stop_ = False + global ip_ + + commandSplit = command.split(" ") + if commandSplit[1] == "list": + if(len(commandSplit) < 3): + ip = '' + else: + ip = commandSplit[2] + + data = {'commandRos': 'rostopic', 'function': 'rostopicList', + 'action': 'send', 'topic': '', 'freq': '0', 'ip': ip} + + brew.publish("Publisher", data) + rospy.logwarn("Sent command = "+command) + + elif commandSplit[1] == "echo": + if(len(commandSplit) < 5): + ip = '' + else: + ip = commandSplit[4] + + if len(commandSplit) < 4: + rospy.logwarn("syntax = rostopic echo /topic frequency") + else: + data = {'commandRos': 'rostopic', 'function': 'rostopicEcho', 'action': 'send', + 'topic': commandSplit[2][1:], 'freq': commandSplit[3], 'ip': ip} + brew.publish("Publisher", data) + rospy.logwarn("Sent command = "+command) + + elif commandSplit[1] == "info": + if(len(commandSplit) < 4): + ip = '' + else: + ip = commandSplit[3] + + data = {'commandRos': 'rostopic', 'function': 'rostopicInfo', + 'action': 'send', 'topic': commandSplit[2], 'freq': '0', 'ip': ip} + brew.publish("Publisher", data) + rospy.logwarn("Sent command = "+command) + + elif commandSplit[1] == "stop": + stop_ = True + else: + rospy.logwarn("Incorrect command syntax") + + '''ROSTOPIC LIST START''' + + def rostopicList(brew, topic, freq, ip): - datum = "" + datum = "" + + master = rosgraph.masterapi.Master('/rostopic') + resp = master.getPublishedTopics('/') + + for i in range(0, len(resp)): + datum += "\n"+resp[i][0] - master = rosgraph.masterapi.Master('/rostopic') - resp = master.getPublishedTopics('/') + data = {'datum': datum, 'title': "Rostopic list results from master " + + brew.name, 'action': 'receive'} - for i in range(0, len(resp)): - datum += "\n"+resp[i][0] + brew.publish("Publisher", data) - data = {'datum':datum, 'title':"Rostopic list results from master "+brew.name, 'action':'receive'} - brew.publish("Publisher", data) '''ROSTOPIC LIST END''' '''ROSTOPIC ECHO START''' + + def ros2xml(msg, name, depth=0): - xml = ""; - tabs = "\t"*depth - - if hasattr(msg, "_type"): - type = msg._type - xml = xml + tabs + "<" + name + " type=\"" + type + "\">\n" - - try: - for slot in msg.__slots__: - xml = xml + ros2xml(getattr(msg, slot), slot, depth=depth+1) - except: - xml = xml + tabs + str(msg) - xml = xml + tabs + "\n" - else: - xml = xml + tabs + "<" + name + ">" + str(msg) + "\n" - return xml + xml = "" + tabs = "\t"*depth + + if hasattr(msg, "_type"): + type = msg._type + xml = xml + tabs + "<" + name + " type=\"" + type + "\">\n" + + try: + for slot in msg.__slots__: + xml = xml + ros2xml(getattr(msg, slot), slot, depth=depth+1) + except: + xml = xml + tabs + str(msg) + xml = xml + tabs + "\n" + else: + xml = xml + tabs + "<" + name + ">" + str(msg) + "\n" + return xml + def callback(resp): - global brew_ - global stop_ - global freq_ + global brew_ + global stop_ + global freq_ - #dados = resp.data - while(stop_ == False): - xml = ros2xml(resp, "") - data = {'datum':xml, 'title':"Rostopic echo results from master "+brew_.name, 'action':'receive'} - brew_.publish("Publisher", data) - time.sleep(float(freq_)) + #dados = resp.data + while(stop_ == False): + xml = ros2xml(resp, "") + data = {'datum': xml, 'title': "Rostopic echo results from master " + + brew_.name, 'action': 'receive'} + brew_.publish("Publisher", data) + time.sleep(float(freq_)) + + return - return def rostopicEcho(brew, topic, freq, ip): - global brew_ - brew_ = brew + global brew_ + brew_ = brew + + global freq_ + global stop_ + global ip_ - global freq_ - global stop_ - global ip_ + freq_ = freq + stop_ = False - freq_ = freq - stop_ = False + datum = "" - datum = "" + if(ip == '' or ip == ip_): + proc = subprocess.Popen( + ["rostopic type "+topic], stdout=subprocess.PIPE, shell=True) + (datum, err) = proc.communicate() - if(ip == '' or ip == ip_): - proc = subprocess.Popen(["rostopic type "+topic], stdout=subprocess.PIPE, shell=True) - (datum, err) = proc.communicate() + dado = datum.split("/") + dado[0] += ".msg" - dado = datum.split("/") - dado[0] += ".msg" + mod = __import__(dado[0], fromlist=[dado[1]]) - mod = __import__(dado[0], fromlist=[dado[1]]) + klass = getattr(mod, dado[1].strip()) + + rospy.Subscriber(topic, klass, callback) + else: + data = {'datum': datum, 'title': "IP = " + ip + + " does not correspond to the requested", 'action': 'receive'} + brew.publish("Publisher", data) - klass = getattr(mod, dado[1].strip()) - rospy.Subscriber(topic, klass, callback) - else: - data = {'datum':datum, 'title':"IP = " +ip+ " does not correspond to the requested", 'action':'receive'} - brew.publish("Publisher", data) '''FIM ROSTOPIC ECHO''' '''ROSTOPIC INFO START''' + + def rostopicInfo(brew, topic, freq, ip): - datum = "" + datum = "" + + if(ip == '' or ip == ip_): + proc = subprocess.Popen( + ["rostopic info "+topic], stdout=subprocess.PIPE, shell=True) + (datum, err) = proc.communicate() - if(ip == '' or ip == ip_): - proc = subprocess.Popen(["rostopic info "+topic], stdout=subprocess.PIPE, shell=True) - (datum, err) = proc.communicate() + data = {'datum': datum, 'title': "Rostopic info "+topic + + " results from master "+brew.name, 'action': 'receive'} + else: + data = {'datum': datum, 'title': "IP = " + ip + + " does not correspond to the requested", 'action': 'receive'} - data = {'datum':datum, 'title':"Rostopic info "+topic+ " results from master "+brew.name, 'action':'receive'} - else: - data = {'datum':datum, 'title':"IP = " +ip+ " does not correspond to the requested", 'action':'receive'} + brew.publish("Publisher", data) - brew.publish("Publisher", data) '''ROSTOPIC INFO END''' diff --git a/src/rostopic.py~ b/src/rostopic.py~ deleted file mode 100644 index 05db746..0000000 --- a/src/rostopic.py~ +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env python - -import roslib; roslib.load_manifest('cloud_ros') -import rospy -from cloud_ros.srv import * -from pySpacebrew.spacebrew import Spacebrew -from std_msgs.msg import String -from geometry_msgs.msg import Twist -import rosgraph.masterapi -import time -import os -import subprocess - -import importlib -import sys - -#from rosgraph_msgs.msg import Log -from geometry_msgs.msg import Twist - -#import std_msgs.msg -#import geometry_msgs.msg -#import rosgraph_msgs.msg - -def rostopicFunctions(command, brew): - - global stop_ - stop_ = False - global ip_ - - commandSplit = command.split(" ") - if commandSplit[1] == "list": - if(len(commandSplit) < 3): - ip = '' - else: - ip = commandSplit[2] - - data = {'commandRos':'rostopic', 'function':'rostopicList', 'action':'send', 'topic':'', 'freq':'0', 'ip':ip} - - brew.publish("Publisher", data) - rospy.logwarn("Sent command = "+command) - - elif commandSplit[1] == "echo": - if(len(commandSplit) < 5): - ip = '' - else: - ip = commandSplit[4] - - if len(commandSplit) < 4: - rospy.logwarn("syntax = rostopic echo /topic frequency") - else: - data = {'commandRos':'rostopic', 'function':'rostopicEcho', 'action':'send', 'topic':commandSplit[2][1:], 'freq':commandSplit[3], 'ip':ip} - brew.publish("Publisher", data) - rospy.logwarn("Sent command = "+command) - - elif commandSplit[1] == "info": - if(len(commandSplit) < 4): - ip = '' - else: - ip = commandSplit[3] - - data = {'commandRos':'rostopic', 'function':'rostopicInfo', 'action':'send', 'topic':commandSplit[2], 'freq':'0', 'ip':ip} - brew.publish("Publisher", data) - rospy.logwarn("Sent command = "+command) - - elif commandSplit[1] == "stop": - stop_ = True - else: - rospy.logwarn("Incorrect command syntax") - -'''INICIO ROSTOPIC LIST''' -def rostopicList(brew, topic, freq, ip): - - datum = "" - - master = rosgraph.masterapi.Master('/rostopic') - resp = master.getPublishedTopics('/') - - for i in range(0, len(resp)): - datum += "\n"+resp[i][0] - - data = {'datum':datum, 'title':"Rostopic list results from master "+brew.name, 'action':'receive'} - - brew.publish("Publisher", data) -'''ROSTOPIC LIST END''' - - -'''INICIO ROSTOPIC ECHO''' -def ros2xml(msg, name, depth=0): - xml = ""; - tabs = "\t"*depth - - if hasattr(msg, "_type"): - type = msg._type - xml = xml + tabs + "<" + name + " type=\"" + type + "\">\n" - - try: - for slot in msg.__slots__: - xml = xml + ros2xml(getattr(msg, slot), slot, depth=depth+1) - except: - xml = xml + tabs + str(msg) - xml = xml + tabs + "\n" - else: - xml = xml + tabs + "<" + name + ">" + str(msg) + "\n" - return xml - -def callback(resp): - - global brew_ - global stop_ - global freq_ - - #dados = resp.data - while(stop_ == False): - xml = ros2xml(resp, "") - data = {'datum':xml, 'title':"Rostopic echo results from master "+brew_.name, 'action':'receive'} - brew_.publish("Publisher", data) - time.sleep(float(freq_)) - - return - -def rostopicEcho(brew, topic, freq, ip): - global brew_ - brew_ = brew - - global freq_ - global stop_ - global ip_ - - freq_ = freq - stop_ = False - - datum = "" - - if(ip == '' or ip == ip_): - proc = subprocess.Popen(["rostopic type "+topic], stdout=subprocess.PIPE, shell=True) - (datum, err) = proc.communicate() - - dado = datum.split("/") - dado[0] += ".msg" - - mod = __import__(dado[0], fromlist=[dado[1]]) - - klass = getattr(mod, dado[1].strip()) - - rospy.Subscriber(topic, klass, callback) - else: - data = {'datum':datum, 'title':"IP = " +ip+ " does not correspond to the requested", 'action':'receive'} - brew.publish("Publisher", data) -'''FIM ROSTOPIC ECHO''' - - -'''ROSTOPIC INFO START''' -def rostopicInfo(brew, topic, freq, ip): - datum = "" - - if(ip == '' or ip == ip_): - proc = subprocess.Popen(["rostopic info "+topic], stdout=subprocess.PIPE, shell=True) - (datum, err) = proc.communicate() - - data = {'datum':datum, 'title':"Rostopic info "+topic+ " results from master "+brew.name, 'action':'receive'} - else: - data = {'datum':datum, 'title':"IP = " +ip+ " does not correspond to the requested", 'action':'receive'} - - brew.publish("Publisher", data) - -'''ROSTOPIC INFO END''' diff --git a/src/trial.py b/src/trial.py new file mode 100755 index 0000000..9cb74b2 --- /dev/null +++ b/src/trial.py @@ -0,0 +1,100 @@ +from websocket import create_connection +import json +import time +from cloudbrain.router.pySpacebrew.spacebrew import Spacebrew + +# add the shared settings file to namespace +import sys +from os.path import dirname, abspath +sys.path.insert(0, dirname(dirname(dirname(abspath(__file__))))) + + +class SpacebrewRouter(object): + def __init__(self, server='127.0.0.1', port=9000): + self.server = server + self.port = port + self.ws = create_connection("ws://%s" % (self.server, self.port)) + + self.ws.send(json.dumps({"admin": [{"admin": True, "no_msgs": False}]})) + + message = { + "config": { + "name": 'router', + "remoteAddress": self.server + } + } + + self.ws.send(json.dumps(message)) + + self.brew = Spacebrew("router", description="Spacebrew Router", server=server) + + # Add publishers for RFID connect and disconnect events + booth_number = 1 + self.brew.addPublisher("booth-{0}-connect".format(booth_number), "boolean") + self.brew.addPublisher("booth-{0}-disconnect".format(booth_number), "boolean") + + self.brew.start() + + def get_spacebrew_config(self): + message = { + "status": True + } + self.ws.send(json.dumps(message)) + return json.loads(self.ws.recv()) + + def link(self, pub_metric, sub_metric, publisher, subscriber, pub_ip, sub_ip): + message = { + "route": { + "type": "add", + "publisher": { + "clientName": publisher, + "name": pub_metric, + "type": "string", + "remoteAddress": pub_ip + }, + "subscriber": { + "clientName": subscriber, + "name": sub_metric, + "type": "string", + "remoteAddress": sub_ip + } + } + } + self.ws.send(json.dumps(message)) + return json.dumps(message) + + def unlink(self, pub_metric, sub_metric, publisher, subscriber, pub_ip, sub_ip): + message = { + "route": { + "type": "remove", + "publisher": { + "clientName": publisher, + "name": pub_metric, + "type": "string", + "remoteAddress": pub_ip + }, + "subscriber": { + "clientName": subscriber, + "name": sub_metric, + "type": "string", + "remoteAddress": sub_ip + } + }, + "targetType": "admin" + } + self.ws.send(json.dumps(message)) + return json.dumps(message) + + def connect_event(self, booth, muse): + self.brew.publish("{0}-connect".format(booth), muse) + + def disconnect_event(self, booth, muse): + self.brew.publish("{0}-disconnect".format(booth), muse) + + +if __name__ == "__main__": + router = SpacebrewRouter(server=forever-spacebrew.herokuapp.com) + router.link('eeg', 'eeg', 'muse-001', 'cloudbrain', '127.0.0.1', '127.0.0.1') + router.link('acc', 'acc', 'muse-001', 'cloudbrain', '127.0.0.1', '127.0.0.1') + time.sleep(1) + router.unlink("eeg", 'eeg', 'muse-001', 'cloudbrain', '127.0.0.1', '127.0.0.1') \ No newline at end of file diff --git a/srv/Comando.srv b/srv/Comando.srv old mode 100755 new mode 100644 diff --git a/srv/Comando.srv~ b/srv/Comando.srv~ deleted file mode 100755 index 671f33d..0000000 --- a/srv/Comando.srv~ +++ /dev/null @@ -1,3 +0,0 @@ -string comando ---- -string resp