コード例 #1
0
 def test_rosnode_kill(self):
     import rosnode
     cmd = 'rosnode'
     for n in ['to_kill/kill1', '/to_kill/kill2']:
         self.assert_(rosnode.rosnode_ping(n, max_count=1))
         rosnode._rosnode_cmd_kill([cmd, 'kill', n])
         self.failIf(rosnode.rosnode_ping(n, max_count=1))
コード例 #2
0
    def test_rosnode_ping(self):
        import rosnode
        cmd = 'rosnode'
        
        self.failIf(rosnode.rosnode_ping('/fake_node', max_count=1))
        self.assert_(rosnode.rosnode_ping('/rosout', max_count=1))
        self.assert_(rosnode.rosnode_ping('/rosout', max_count=2))        

        with fakestdout() as b:
            self.assert_(rosnode.rosnode_ping('/rosout', max_count=2, verbose=True))
            s = b.getvalue()
            self.assert_('xmlrpc reply' in s, s)
            self.assert_('ping average:' in s, s)
            
        # test via command-line API
        rosnode._rosnode_cmd_ping([cmd, 'ping', '-c', '1', '/fake_node'])
        with fakestdout() as b:
            rosnode._rosnode_cmd_ping([cmd, 'ping', '-c', '1', '/rosout'])
            s = b.getvalue()
            self.assert_('xmlrpc reply' in s, s)
        with fakestdout() as b:
            rosnode._rosnode_cmd_ping([cmd, 'ping', '-c', '1', 'rosout'])
            s = b.getvalue()
            self.assert_('xmlrpc reply' in s, s)
        with fakestdout() as b:
            rosnode._rosnode_cmd_ping([cmd, 'ping', '-c', '2', 'rosout'])
            s = b.getvalue()
            self.assertEquals(2, s.count('xmlrpc reply'))
コード例 #3
0
    def test_rostest_detection(self):
        # check that pyros_utils/rostest_nose is usable even without delay import magic
        from pyros_utils import rostest_nose

        print("Checking rostest detection...")
        # checking detection works properly
        assert rostest_nose.is_rostest_enabled()
        # checking setup is done as expected                

        # wait for the node to come up
        with timeout(5) as t:
            while not t.timed_out and not rosnode.rosnode_ping("string_pub_node", max_count=1):
                time.sleep(1)
        # TODO: improve this

        assert rosnode.rosnode_ping("string_pub_node", max_count=5)
コード例 #4
0
def rosnode_ping_all(verbose=False):
    """
    Ping all running nodes
    @return [str], [str]: pinged nodes, un-pingable nodes
    @raise ROSNodeIOException: if unable to communicate with master
    """
    master = rosnode.rosgraph.Master(rosnode.ID)
    try:
        state = master.getSystemState()
    except rosnode.socket.error:
        raise rosnode.ROSNodeIOException("Unable to communicate with master!")

    nodes = []
    for s in state:
        for t, l in s:
            nodes.extend(l)
    nodes = list(set(nodes))  #uniq
    if verbose:
        print("Will ping the following nodes: \n" +
              ''.join([" * %s\n" % n for n in nodes]))
    pinged = {}
    unpinged = []
    for node in nodes:
        start = time.time()
        status = rosnode.rosnode_ping(node, max_count=1, verbose=verbose)
        end = time.time()
        dur = (end - start) * 1000.
        if status:
            pinged.update({node: dur})
        else:
            unpinged.append(node)

    return pinged, unpinged
コード例 #5
0
 def _last_spin(self):
     if not rospy.is_shutdown() and not self.did_spin:
         self._spin_count += 1
         rospy.sleep(self.sleep_duration)
         self.ros.process_inbox()
         for node_name in self.cfg.nodes_under_test:
             assert rosnode_ping(node_name, max_count=1)
コード例 #6
0
ファイル: updater.py プロジェクト: vermeerlee/robin
    def _restart_robin_node(cls, node_path):  #TODO try to simplify
        """Restarts robin bridge node."""

        # if node alive
        if rosnode.rosnode_ping(node_path, max_count=3):

            # kill node
            if node_path not in rosnode.kill_nodes([node_path])[0]:
                raise RuntimeError(
                    "Failed to kill robin node '{}'.".format(node_path))

        else:

            master = rosgraph.Master(rosnode.ID)
            rosnode.cleanup_master_blacklist(master, [node_path])
        node_name = node_path.split('/')[-1]
        cls._wait_for(lambda: cls._get_node_path(node_name) == '')
        namespace = '/'.join(node_path.split('/')[:-1])
        cmd = '''bash -c "
                    cd {} &&
                    . *devel*/setup.bash &&
                    rosrun robin_bridge_generated robin_node __ns:={} &
                " > /dev/null 2>&1'''.format(catkin_ws, namespace)
        # " > /dev/null 2>&1'''.format(catkin_ws, node_path[:-len('/' + node_name)])
        if os.system(cmd) != 0:
            raise RuntimeError('Failed to rerun robin node.')
        cls._wait_for(lambda: cls._get_node_path(node_name) != '', timeout=10)
コード例 #7
0
def main_test_part(rostest_nose, roslaunch, rospy, rosnode):
    print("Entering main_test_part")

    # if running with rostest we cannot check the startup behavior from inside the test
    if not rostest_nose.is_rostest_enabled():
        rostest_nose.rostest_nose_setup_module()

        # Start roslaunch
        # Ref : http://wiki.ros.org/roslaunch/API%20Usage
        launch = roslaunch.scriptapi.ROSLaunch()
        launch.start()

        rospy.set_param('/string_pub_node/topic_name', '~test_str_topic')  # private topic name to not mess things up too much
        rospy.set_param('/string_pub_node/test_message', 'testing topic discovery')
        package = 'pyros_test'
        executable = 'string_pub_node.py'
        name = 'string_pub_node'
        node = roslaunch.core.Node(package, executable, name)

        talker_process = launch.launch(node)
        assert talker_process.is_alive()

    try:
        # wait for the node to come up (needed for both rostest and nosetest)
        with timeout(5) as t:
            while not t.timed_out and not rosnode.rosnode_ping("string_pub_node", max_count=1):
                time.sleep(1)
        # TODO: improve this

        # try a few times
        assert rosnode.rosnode_ping("string_pub_node", max_count=5)

    # we make sure this always run to avoid hanging with child processes
    finally:
        if not rostest_nose.is_rostest_enabled():
            talker_process.stop()
            assert not talker_process.is_alive()

            # if running with rostest, we cannot check the shutdown behavior form inside the test
            # so we do it here
            assert not rosnode.rosnode_ping("string_pub_node", max_count=5)

            rostest_nose.rostest_nose_teardown_module()

            rospy.signal_shutdown('test complete')

    print("Exiting main_test_part")
コード例 #8
0
def list() -> List[str]:
    # no freaking api for getting alive nodes, greato!
    active_nodes = rosnode.get_node_names()
    active_nodes = [
        node for node in active_nodes
        if rosnode.rosnode_ping(node, max_count=1)
    ]
    return active_nodes
コード例 #9
0
ファイル: listener.py プロジェクト: hshi123/ros-redis
def timer_callback(event):
    if rospy.is_shutdown():
        print("Unable to communicate with ROS_MASTER")

    if rosnode.rosnode_ping("/rosout"):
        print("Can communicate with this node")

    print("Timer callback")
コード例 #10
0
ファイル: robot_monitor.py プロジェクト: inomuh/agvpc_ros
def check():

    while not rospy.is_shutdown():

        bakim_node_check = rosnode.rosnode_ping("/agv1/bakim_ihtiyaci", 2,
                                                False)
        can2topic_node_check = rosnode.rosnode_ping("agv1/can2topic", 2, False)
        topic2can_node_check = rosnode.rosnode_ping("/agv1/topic2can", 2,
                                                    False)
        durum_node_check = rosnode.rosnode_ping("/agv1/durum", 2, False)
        odom_node_check = rosnode.rosnode_ping("agv1/ota_odometry", 2, False)
        sick_node_check = rosnode.rosnode_ping("/agv1/sick_s300", 2, False)
        socketcan_node_check = rosnode.rosnode_ping("/agv1/socketcanbridge", 2,
                                                    False)

        if bakim_node_check == False:
            print("Bakim node failed")

        if can2topic_node_check == False:
            print("Can2topic node failed")

        if topic2can_node_check == False:
            print("Topic2can node failed")

        if durum_node_check == False:
            print("Durum node failed")

        if odom_node_check == False:
            print("Odom node failed")

        if sick_node_check == False:
            print("Sick node failed")

        if socketcan_node_check == False:
            print("Socketcan node failed")
コード例 #11
0
 def testNodePing(self, node_name):
     #Simplemente una funcion que devuelve bool de nodo si activo o no. SI NECESITA PALITO.
     master = rosgraph.Master('/rosnode')
     node_api = rosnode.get_api_uri(master, node_name)
     node_is_active = False
     if node_api:
         node_is_active = rosnode.rosnode_ping(
             node_name, 1, verbose=False)  #1: max ping request count
     return node_is_active
コード例 #12
0
    def get_node_status(self):
        size = len(self.nodes)
        self.status = [True] * size

        for i in range(size):
            try:
                self.status[i] = rosnode.rosnode_ping(self.nodes[i],
                                                      max_count=1)
            except Exception:
                self.status[i] = False
 def pingBlackboard(self, event):
     if self.pingLock.locked() is False:  # check lock
         self.pingLock.acquire()
         self.bbState = rosnode_ping(
             self.bbAdress,
             1)  # ping  blackboard node, assign result to bbstate
         if self.bbState is False:  # if node is offline
             self.bbthread = Thread(
                 target=self.bbBackupActivate
             )  # start backup function on a new thread
         self.pingLock.release()
コード例 #14
0
 def create_node_status(self):
     diag_status = DiagnosticStatus()
     diag_status.name = "BHG: Node Status"
     diag_status.message = "BHG: Normal"
     diag_status.hardware_id = socket.gethostname()
     for r_node in node_list:
         #            self.node_state[r_node] = rosnode.rosnode_ping(r_node, 1, False)
         node_case_kv = KeyValue()
         node_case_kv.key = r_node
         node_case_kv.value = str(rosnode.rosnode_ping(r_node, 1, False))
         diag_status.values.append(node_case_kv)
     return diag_status
コード例 #15
0
    def hasInitialized(self):
        # TODO: add more checks (battery measurement etc)
        check1 = rospy.get_rostime(
        ) - self.mode_start_time > rospy.Duration.from_sec(INIT_TIME)
        check2 = self.pos is not None  # check decawave and estimator
        check3 = rosnode.rosnode_ping(rospy.get_namespace() +
                                      rospy.get_param("ros_serial_node"),
                                      max_count=1)  # check teensy

        if check1 and check2 and check3:
            return True
        return False
コード例 #16
0
    def ping_node(self, node_name, cmd):
        rate = rospy.Rate(1) 
        ping_success = rosnode.rosnode_ping(node_name, 2)
        rate.sleep()

        # cmd_str = "This is the cmd: " + str(cmd[0])
        # rospy.logwarn(cmd_str)

        if (ping_success == False):
            rospy.logerr("" + node_name + " is not runinng.")
            rospy.logerr("Relaunching "  + node_name + " now...")
            for i in cmd:
                thread.start_new_thread(os.system, (i,)) # Make sure to keep comma. Must be a tuple for thread library to work
コード例 #17
0
 def _wait_for_nodes(self, timeout=60.0):
     now = rospy.get_rostime()
     to = rospy.Duration.from_sec(timeout)
     end = now + to
     rate = rospy.Rate(5)
     pending = set(self.cfg.nodes_under_test)
     while now < end and pending:
         for node_name in self.cfg.nodes_under_test:
             if node_name in pending:
                 if rosnode_ping(node_name, max_count=1):
                     pending.remove(node_name)
         rate.sleep()
         now = rospy.get_rostime()
     if pending:
         raise LookupError("Failed to find nodes " + str(pending))
コード例 #18
0
 def loop(self):
     r = rospy.Rate(1)
     while not rospy.is_shutdown():
         isNodeAlive = rosnode.rosnode_ping("/mybag",
                                            max_count=1,
                                            verbose=False)
         rospy.loginfo(isNodeAlive)
         if self.base_mode == ARDUPILOT_AUTO_BASE and self.custom_mode == ARDUPILOT_AUTO_CUSTOM:
             if isNodeAlive == False:
                 p = subprocess.Popen(
                     ["rosbag", "record", "-a", "__name:=mybag"])
         else:
             if isNodeAlive == True:
                 p = subprocess.Popen(["rosnode", "kill", "/mybag"])
         r.sleep()
コード例 #19
0
def kill_node(nodename):
    isNodeAlive = rosnode.rosnode_ping(nodename, max_count=1, verbose=False)
    if isNodeAlive:
        p2 = Popen(["rosnode", "list"], stdout=PIPE)
        p2.wait()
        nodelist = p2.communicate()
        nd = nodelist[0]
        nd = nd.split("\n")
        for i in range(len(nd)):
            tmp = nd[i]
            ind = tmp.find(nodename)
            if ind == 1:
                call(["rosnode", "kill", nd[i]])
                return True
    else:
        return False
コード例 #20
0
ファイル: collect_pr2.py プロジェクト: lyltc1/LTAMP
def launch_kinect():
    record = rosnode.rosnode_ping("/camera/camera_nodelet_manager", 1e-2)
    print('Record:', record)
    if not record:
        return None
    # TODO: set arguments
    launch_path = os.path.abspath('utils/record_video.launch')
    #video_path = os.path.abspath(os.path.join(DATA_DIRECTORY, 'video2.avi'))
    #cli_args = [launch_path, 'filename:={}'.format(video_path)]
    #roslaunch_args = roslaunch.rlutil.resolve_launch_arguments(cli_args)
    uuid = roslaunch.rlutil.get_or_generate_uuid(None, False)
    roslaunch.configure_logging(uuid)
    launch = roslaunch.parent.ROSLaunchParent(uuid, [launch_path])
    #launch = roslaunch.parent.ROSLaunchParent(uuid, [(roslaunch_args[0], cli_args[1:])])
    launch.start()
    return launch
コード例 #21
0
    def test_rviz_exists(self):
        rospy.logwarn("[{}] Check rviz node exists {}".format(
            rospy.get_name(), self.rviz_node_name))
        subs = []
        t_start = time.time()
        while not rospy.is_shutdown():
            t_now = time.time()
            t_elapsed = t_now - t_start
            if t_elapsed > self.test_duration:
                break

            # info = rosnode.rosnode_info(self.rviz_node_name) does not return values, so we need to expand functions
            node_api = rosnode.rosnode_ping(self.rviz_node_name,
                                            max_count=1,
                                            skip_cache=True)
            if not node_api:
                rospy.logerr(
                    "[{}] Could not find rviz node api on rosmaster".format(
                        rospy.get_name()))
                raise AssertionError

            rospy.logwarn("[{}] {:.3f} Rviz node found at {}".format(
                rospy.get_name(), t_elapsed, node_api))

            # check if topic exists
            master = rosgraph.Master('/rosnode')

            state = master.getSystemState()
            subs.extend(
                sorted([t for t, l in state[1] if self.rviz_node_name in l]))
            subs = list(set(subs))
            rospy.logwarn('[{}] rviz subscribes {}'.format(
                rospy.get_name(), subs))
            time.sleep(0.5)

        for topic in self.topics:
            if topic in subs:
                rospy.logwarn('[{}] rviz subscribes {}'.format(
                    rospy.get_name(), topic))
            else:
                rospy.logerr('[{}] rviz did not subscribes {}'.format(
                    rospy.get_name(), topic))
                raise AssertionError

        rospy.logwarn("[{}] rviz keep alive for {}[sec] and found {}".format(
            rospy.get_name(), self.test_duration, self.topics))
        self.assertTrue(True, "check {}/rviz alives".format(rospy.get_name()))
コード例 #22
0
 def spin_phase(self):
     self.rate.sleep()
     for node_name in self.cfg.nodes_under_test:
         assert rosnode_ping(node_name, max_count=1)
     for cb, event in self.ros.get_event_queue():
         try:
             if event.published:
                 for trace in self.traces.itervalues():
                     trace.append(event)
                 cb(event)
             else:
                 self.traces[event.topic].append(event)
                 cb(event)
                 self.traces[event.topic] = [event]
         except BaseException:
             self.ros_trace = self.traces.get(event.topic, [event])
             raise
コード例 #23
0
def LaunchNode(packageName, launchFile, nodesList, timeOut=10):
    print "launching: " + launchFile
    my_env = os.environ.copy()
    my_env["TURTLEBOT_3D_SENSOR"] = "commonsense"
    my_env["TURTLEBOT_STACKS"] = "hexagons"
    proc = subprocess.Popen(['roslaunch', packageName, launchFile], env=my_env)
    allNodes = 0
    while allNodes != len(nodesList) and timeOut > 0:
        allNodes = 0
        sleep(1)
        for node in nodesList:
            if rosnode.rosnode_ping(node, 1, False) == True:
                allNodes = allNodes + 1
            else:
                break
        timeOut = timeOut - 1
    print "Process pid: " + str(proc.pid)
    return proc.pid
コード例 #24
0
    def check_vital_nodes(self):
        alive_nodes = rosnode.get_node_names()

        self.__python_wrapper_nodes = {
            pywrapper_node
            for pywrapper_node in self.__python_wrapper_nodes
            if pywrapper_node in alive_nodes
        }

        missing_nodes = [
            vital_node for vital_node in self.__vital_nodes
            if vital_node not in alive_nodes
            or not rosnode.rosnode_ping(vital_node, 1)
        ]

        self.__are_vital_nodes_alive = not bool(missing_nodes)
        self.__missing_vital_nodes = missing_nodes

        return self.__are_vital_nodes_alive
def initialize():
    print("########### ROCKIE EXECUTIVE NODE ###########")
    print("Rockie executive node running...")

    # Test if nodes are alive
    print("Making sure nodes are alive...")
    # Add more node names to this string array
    dependent_nodes = ["cam_capture", "cam_display"]  
    for node in dependent_nodes:
        print("Checking"), 
        print(node), 
        print("..."),
        ping_count = 0
        while ping_count < 25:
            camera_capture_node_ALIVE = rosnode.rosnode_ping(node_name=node,max_count=1,verbose=False)
            if camera_capture_node_ALIVE:
                print("ALIVE")
                break
            else:
                if pint_count == 24:
                    print("DEAD")
コード例 #26
0
def wait_until_online(node_name, timeout=rospy.Duration(5)):
    """
    blocks until a node has become online and can be pinged
    :param node_name: name of the node (including namespace)
    :param timeout: time to wait until failure is reported
    :return: true if contact was made with the node
    """
    # wait until node is listed in rosmaster
    waitcount = 0
    online = False
    while waitcount < 5 and not rospy.is_shutdown():
        if node_name in rosnode.get_node_names():
            online = True
            break
        waitcount += 1
        rospy.sleep(timeout / 5.)
    if not online:
        return False

    # ping the node
    return rosnode.rosnode_ping(node_name, int(math.ceil(timeout.to_sec())))
コード例 #27
0
ファイル: control.py プロジェクト: Kenkoko/ua-ros-pkg
import rospy
import rosnode
from std_msgs.msg import String

def robotalker():
    robotalker = rospy.Publisher('woz/robotcontrol', String)
    
    # valid commands
    valid = rospy.get_param('robot/validcommands', [])
    command_help = rospy.get_param('robot/commandhelp', 'Help is not available.')
    print command_help
    
    while not rospy.is_shutdown():
        try:
            cmd = sys.stdin.readline().strip()
            if not cmd in valid:
                print command_help
            robotalker.publish(String(cmd))
        except IOError, e:
            pass

if __name__ == '__main__':
    rospy.init_node('robotcontrol',anonymous=True)
    while not rosnode.rosnode_ping('charlie_robot', max_count=1, verbose=True):
        rospy.sleep(1)
    try:
        robotalker()
    except rospy.ROSInterruptException: pass


コード例 #28
0
def IsNodeRunning(nodeName):
    return rosnode.rosnode_ping(nodeName, 1, False)
コード例 #29
0
#!/usr/bin/env python 
import roslib
roslib.load_manifest('rosnode')
roslib.load_manifest('rospy')
import rospy
#from rospy import ROSException
from rosnode import rosnode_ping
from rospy import logerr

if __name__ == '__main__':

    if rosnode_ping("morse", 5, 0) == 1:
        pass
    else: 
        logerr("Could not find MORSE-rosnode. Please make sure it is running.")

    if rosnode_ping("morse_tf_broadcaster_navstack", 5, 0) == 1:
        pass
    else: 
        logerr("Could not find MORSE-TF-BROADCASTER. Please make sure it is running.")

    if rosnode_ping("robot_state_publisher", 5, 0) == 1:
        pass
    else: 
        logerr("Could not find ROBOT_STATE_PUBLISHER. Please make sure it is running and the JointStates are published on the correct topic!")
コード例 #30
0
 def test_node(self):
     """ Verify that we can ping the node. """
     result = rosnode_ping('test_spacenav_inverter', max_count=1)
     self.assertTrue(result)
コード例 #31
0
    if os.path.exists(_fol + sound + ".wav"):
        sender.playWave(_fol + sound + ".wav")
    elif os.path.exists(_fol + sound + ".mp3"):
        sender.playWave(_fol + sound + ".mp3")
    else:
        pass


if __name__ == "__main__":
    rospy.init_node("presentation")
    if not rospy.has_param("/speech_root"):
        rospy.set_param(
            "/speech_root",
            os.path.dirname(os.path.realpath(__file__)) + "/speeches")
    makesrv = rospy.Service("make_presentation_waves", Presentation,
                            make_handle)
    runsrv = rospy.Service("do_presentation", Presentation, pres_handle)
    soundstatus = rospy.Subscriber("diagnostics", DiagnosticArray,
                                   sound_status)
    #wait for sound service to be operational (take 1)
    #while _sound_running is None:
    #	pass
    #	rospy.
    #Need to spin to fire the subscriber callback, but python doesn't have spinOnce(). Because it's a bad language
    #take 2
    while not rosnode.rosnode_ping("soundplay_node", 1, False):
        rospy.sleep(1)
        pass
    rospy.loginfo("Presentation server running")
    rospy.spin()
コード例 #32
0
 def check_node_ping(name):
     try:
         return rosnode.rosnode_ping(name, 1)
     except:
         return False
コード例 #33
0
ファイル: moveit_widget.py プロジェクト: 130s/rqt_moveit
    def _monitor_nodes(self):
        for nodename in self._nodes_monitored:
            is_node_running = rosnode_ping(nodename, 1)

            #TODO: segfault occurs here most of every time the plugin shut down
            self._signal.emit(is_node_running, nodename)
コード例 #34
0
ファイル: diagnostic.py プロジェクト: guevvy561/homebot
    def __init__(self, name):

        self.running = True

        rospy.on_shutdown(self.shutdown)

        print('Looking for section...')
        self.section = None
        try:
            self.section = (rospy.get_param('~section') or '').upper() # head|torso
            assert self.section in (c.HEAD, c.TORSO, '')
            if self.section == 'none':
                self.section = ''
        except KeyError:
            pass
        if self.section:
            print('Checking section %s.' % self.section)
        else:
            print('No section specified. Checking all sections.')

        print('Looking for part...')
        self.part = None
        try:
            self.part = (rospy.get_param('~part') or '').lower().strip()
            if self.part == 'none':
                self.part = ''
        except KeyError:
            pass
        if self.part:
            print('Checking part %s.' % self.part)
        else:
            print('No part specified. Checking all part.')

        skip_device = int(rospy.get_param('~skip_device_check', 0))

        print('skip_device:', skip_device)

        if not skip_device:
            if not self.section or self.section == c.HEAD:
                while not rospy.is_shutdown() and self.running:
                    try:
                        print('Looking for head...')
                        device = utils.find_serial_device(c.HEAD)
                        break
                    except DeviceNotFound:
                        self.wait_until_continue('Attach the head via USB.')

            if not self.section or self.section == c.TORSO:
                while not rospy.is_shutdown() and self.running:
                    try:
                        print('Looking for torso...')
                        device = utils.find_serial_device(c.TORSO)
                        break
                    except DeviceNotFound:
                        self.wait_until_continue('Attach the torso via USB.')

        if not self.section or self.section == c.HEAD:
            print('Pinging head node...')
            assert rosnode.rosnode_ping('/head_arduino', max_count=1, verbose=True), \
                'Head arduino node not detected.'

        if not self.section or self.section == c.TORSO:
            print('Pinging torso node...')
            assert rosnode.rosnode_ping('/torso_arduino', max_count=1, verbose=True), \
                'Torso arduino node not detected.'

        if (not self.section or self.section == c.HEAD) and (not self.part or self.part == 'lrf'):
            print('Pinging LRF node...')
            assert rosnode.rosnode_ping('homebot_lrf', max_count=1, verbose=True), \
                'LRF node not detected.'
            print('Pinging Raspicam node...')
            assert rosnode.rosnode_ping('raspicam_node', max_count=1, verbose=True), \
                'Raspicam node not detected.'

        self.check_results = {} # {name: success}

        self.checks = []

        self.handlers = {} # {msg: latch}

        # Torso arduino subscriptions.
        self.subscribe_torso(c.ID_BUMPER)
        self.subscribe_torso(c.ID_EDGE)
        self.subscribe_torso(c.ID_ULTRASONIC)
        self.subscribe_torso(c.ID_STATUS_BUTTON)
        self.subscribe_torso(c.ID_IMU_ACCELEROMETER)
        self.subscribe_torso(c.ID_IMU_EULER)
        self.subscribe_torso(c.ID_IMU_MAGNETOMETER)
        self.subscribe_torso(c.ID_ARDUINO_TEMP)
        self.subscribe_torso(c.ID_BATTERY_VOLTAGE)
        self.subscribe_torso(c.ID_EXTERNAL_POWER)

        # Head arduino subscriptions.
        self.subscribe_head(c.ID_PAN_CENTERMARK)
        self.subscribe_head(c.ID_PAN_ANGLE)

        # Other head subscriptions.
        self.handlers[ros_homebot_msgs.msg.LaserLineColumns] = MessageHandler()
        rospy.Subscriber(
            '/homebot_lrf/line/columns',
            ros_homebot_msgs.msg.LaserLineColumns,
            self.record_topic)

        print('Subscribed to topics.')

        self.add_checks()

        self.wait_until_continue(
            'Place the torso on struts so the treads are at least 3cm off the ground.')

        # Run all checks.
        total = len(self.checks)
        passed = 0
        for i, check in enumerate(self.checks):
            sys.stdout.write('%02i/%02i ' % (i+1, total))
            check.run()
            passed += check.success
            if rospy.is_shutdown():
                sys.exit()

        print('-'*80)
        print('Passed %i of %i checks.' % (passed, total))
        score = passed/float(total)*100
        print('Score: %.02f%%' % score)
コード例 #35
0
 def pingNode(self):
    res = rosnode.rosnode_ping(self.name,2,1)
    return res
コード例 #36
0
def kill_node(nodename):
    p2 = Popen(['rosnode', 'list'], stdout=PIPE)
    p2.wait()
    nodelist = p2.communicate()
    nd = nodelist[0]
    nd = nd.split("\n")
    for i in range(len(nd)):
        tmp = nd[i]
        ind = tmp.find(nodename)
        if ind == 1:
            call(['rosnode', 'kill', nd[i]])
            break


rospy.init_node('tester3', anonymous=True)

#cmd = ["rosrun","pcl_ros","pointcloud_to_pcd","input:=camera/depth/points"]
cmd = ["roslaunch", "pir2_description", "pir2_description.launch"]
proc = Popen(cmd)
#proc = call(cmd)
#time.sleep(1)  # maybe needed to wait the process to do something useful
print "finish"
time.sleep(5)
#proc.kill()

isNodeAlive = rosnode.rosnode_ping("/rviz", max_count=1, verbose=False)
print isNodeAlive
if isNodeAlive:
    kill_node('rviz')
コード例 #37
0
ファイル: node.py プロジェクト: OSUrobotics/rosh_core
 def __call__(self):
     """
     Ping the node.
     """
     return rosnode.rosnode_ping(self._name, max_count=1, verbose=False)