class ROSCloudSubBridge(object):

    def __init__(self, ip, port, local_topic_name, remote_topic_name, message_type):
        self._ip = ip
        self._port = port
        self._local_topic_name = local_topic_name     
        self._remote_topic_name = remote_topic_name
        self._message_type = message_type
        self._ros_client= Ros(self._ip,self._port) 
        self._rosPub = None  # Should be specified by the automation engine
        self._listener = None
        self._logger = logging.getLogger(self.__class__.__name__)
        self._logger.setLevel(logging.DEBUG)

    def _run_topic_pubsub(self):
    	try:
            self._listener = Topic(self._ros_client, self._remote_topic_name, self._message_type)
            self._listener2= Topic(self._ros_client, self._remote_topic_name, self._message_type)
            rospy.init_node('cloudsub', anonymous=True)
            global my
            my=rospy.get_time()
            self._ros_client.on_ready(self._start_receiving, run_in_thread=True)
            self._ros_client.run_event_loop() 
        except:        
            self._logger.exception("Fatal error in constructor")
    

    def _receive_message(self,message):
        global my
        rospy.loginfo(rospy.get_caller_id() + " I heard a message of %s",self._message_type)
        rospy.loginfo(rospy.get_caller_id()  + " Time from previous message %s",(rospy.get_time()-my)  )#edw mou leei unicode type
        my=rospy.get_time()
        try:
            msg=Image()
            msg.header.seq=message['header']['seq']
            msg.header.stamp.secs=message['header']['stamp']['secs']
            msg.header.stamp.nsecs=message['header']['stamp']['nsecs'] 
            msg.header.frame_id=message['header']['frame_id']
            msg.height=message['height']
            msg.width=message['width']
            msg.encoding=str(message['encoding'])
            msg.is_bigendian=message['is_bigendian']
            msg.step=message['step']
            msg.data=message['data'].decode('base64')
            self._rosPub=rospy.Publisher(self._local_topic_name, Image, queue_size=10) #message type is String instead of msg_stds/String
            self._rosPub.publish(msg)
        except:
           print('Error')        


    def _start_receiving(self): 
        self._listener.subscribe(self._receive_message)

    def start(self):
        signal.signal(signal.SIGINT, lambda *x: self.stop())
        self._run_topic_pubsub()

    def stop(self):
        if self._ros_client is not None:
            self._ros_client.terminate()
Esempio n. 2
0
class ROSCloudSubBridge(object):

    def __init__(self, ip, port, local_topic_name, remote_topic_name, message_type):
        self._ip = ip
        self._port = port
        self._local_topic_name = local_topic_name     
        self._remote_topic_name = remote_topic_name
        self._message_type = message_type
        self._ros_client= Ros(self._ip,self._port) 
        self._rosPub = None  # Should be specified by the automation engine
        self._listener = None  # Should be specified by the automation engine

        self._logger = logging.getLogger(self.__class__.__name__)
        self._logger.setLevel(logging.DEBUG)
        self.br =tf2_ros.StaticTransformBroadcaster()
        self.t = []

    def _run_topic_pubsub(self):
        try:
            self._listener = Topic(self._ros_client, self._remote_topic_name, self._message_type)
            rospy.init_node('cloudsub', anonymous=True)
            global my
            my=rospy.get_time()
            self._ros_client.on_ready(self._start_receiving, run_in_thread=True)
            self._ros_client.run_event_loop() 
        except:        
            self._logger.exception("Fatal error in constructor")


    def _receive_message(self,message):
        global my
        rospy.loginfo(rospy.get_caller_id() + " Message type %s ",self._message_type)
        rospy.loginfo(rospy.get_caller_id() + " Time from previous message %s ",(rospy.get_time()-my))
        my=rospy.get_time()
        for i in range(len(message['transforms'])):
            self.t.append(TransformStamped())
            self.t[-1].header.stamp = rospy.Time.now()
            self.t[-1].header.frame_id = message['transforms'][i]['header']['frame_id']
            self.t[-1].child_frame_id =  message['transforms'][i]['child_frame_id']
            self.t[-1].transform.translation.x = message['transforms'][i]['transform']['translation']['x']
            self.t[-1].transform.translation.y = message['transforms'][i]['transform']['translation']['y']
            self.t[-1].transform.translation.z = message['transforms'][i]['transform']['translation']['z']
            self.t[-1].transform.rotation.x = message['transforms'][i]['transform']['rotation']['x']
            self.t[-1].transform.rotation.y = message['transforms'][i]['transform']['rotation']['y']
            self.t[-1].transform.rotation.z = message['transforms'][i]['transform']['rotation']['z']
            self.t[-1].transform.rotation.w = message['transforms'][i]['transform']['rotation']['w']
        self.br.sendTransform(self.t)


    def _start_receiving(self): 
        self._listener.subscribe(self._receive_message)


    def start(self):
        signal.signal(signal.SIGINT, lambda *x: self.stop())
        self._run_topic_pubsub()

    def stop(self):
        if self._ros_client is not None:
            self._ros_client.terminate()
def run_topic_pubsub():
    context = {'counter': 0}
    ros_client = Ros('127.0.0.1', 9090)
    listener = Topic(ros_client, '/chatter', 'std_msgs/String')
    publisher = Topic(ros_client, '/chatter', 'std_msgs/String')

    def receive_message(message):
        context['counter'] += 1
        assert message['data'] == 'hello world', 'Unexpected message content'

        if context['counter'] == 3:
            listener.unsubscribe()
            # Give it a bit of time, just to make sure that unsubscribe
            # really unsubscribed and counter stays at the asserted value
            ros_client.call_later(2, ros_client.terminate)

    def start_sending():
        while True:
            if not ros_client.is_connected:
                break
            publisher.publish(Message({'data': 'hello world'}))
            time.sleep(0.1)
        publisher.unadvertise()

    def start_receiving():
        listener.subscribe(receive_message)

    ros_client.on_ready(start_receiving, run_in_thread=True)
    ros_client.on_ready(start_sending, run_in_thread=True)
    ros_client.run_forever()

    assert context[
        'counter'] >= 3, 'Expected at least 3 messages but got ' + str(
            context['counter'])
class ROSCloudSubBridge(object):
    def __init__(self, ip, port, local_topic_name, remote_topic_name,
                 message_type, file):
        self._ip = ip
        self._port = port
        self._local_topic_name = local_topic_name
        self._remote_topic_name = remote_topic_name
        self._message_type = message_type
        self._ros_client = Ros(self._ip, self._port)
        self._rosPub = None  # Should be specified by the automation engine
        self._listener = None  # Should be specified by the automation engine
        self._service = None
        self._logger = logging.getLogger(self.__class__.__name__)
        self._logger.setLevel(logging.DEBUG)
        self._file = file

    def _run_topic_pubsub(self):
        try:
            self._listener = Topic(self._ros_client, self._remote_topic_name,
                                   self._message_type)
            rospy.init_node('cloudsub', anonymous=True)
            self._ros_client.send_on_ready(Message(self._file))
            global my
            my = rospy.get_time()
            self._ros_client.on_ready(self._start_receiving,
                                      run_in_thread=True)
            self._ros_client.run_event_loop()
        except:
            self._logger.exception("Fatal error in constructor")

    def _receive_message(self, message):
        global my
        rospy.loginfo(rospy.get_caller_id() + " Message type %s ",
                      self._message_type)
        rospy.loginfo(
            rospy.get_caller_id() + " Time from previous message %s ",
            (rospy.get_time() - my))
        my = rospy.get_time()
        try:
            msg = Clock()
            msg.clock.secs = message['clock']['secs']
            msg.clock.nsecs = message['clock']['nsecs']
            self._rosPub = rospy.Publisher(
                self._local_topic_name, Clock, queue_size=10
            )  #message type is String instead of msg_stds/String
            self._rosPub.publish(msg)
        except:
            print('Error')

    def _start_receiving(self):
        self._listener.subscribe(self._receive_message)

    def start(self):
        signal.signal(signal.SIGINT, lambda *x: self.stop())
        self._run_topic_pubsub()

    def stop(self):
        if self._ros_client is not None:
            self._ros_client.terminate()
Esempio n. 5
0
def run_rosapi_topics():
    ros_client = Ros('127.0.0.1', 9090)

    def callback(topic_list):
        assert ('/rosout' in topic_list['topics'])
        ros_client.terminate()

    def get_topics():
        ros_client.get_topics(callback)

    ros_client.on_ready(get_topics)
    ros_client.run_event_loop()
Esempio n. 6
0
def run_topic_pubsub():
    context = {'counter': 0}
    ros_client = Ros('192.168.1.106', 9090)
    listener = Topic(ros_client, '/chatter', 'std_msgs/String')
    publisher = Topic(ros_client, '/chatter', 'std_msgs/String')

    def receive_message(message):

        print("============================")
        context['counter'] += 1
        assert message['data'] == 'hello world', 'Unexpected message content'

        if context['counter'] == 3:
            listener.unsubscribe()
            # Give it a bit of time, just to make sure that unsubscribe
            # really unsubscribed and counter stays at the asserted value
            ros_client.call_later(2, ros_client.terminate)

    # def callback(topic_list):
    #     print(topic_list)
    #     assert('/rosout' in topic_list['topics'])
    #     time.sleep(1)
    #     ros_client.terminate()

    def start_sending():
        while True:
            print("---------------------")
            if not ros_client.is_connected:
                break
            publisher.publish(Message({'data': 'hello world'}))
            print(listener.is_subscribed)

            time.sleep(0.1)
            ros_client.terminate
            break
            # ros_client.get_topics(callback)

        publisher.unadvertise()

    def start_receiving():
        listener.subscribe(receive_message)

    ros_client.on_ready(start_receiving, run_in_thread=True)
    ros_client.on_ready(start_sending, run_in_thread=True)

    ros_client.run_forever()

    assert context[
        'counter'] >= 3, 'Expected at least 3 messages but got ' + str(
            context['counter'])
Esempio n. 7
0
def run_rosapi_topics(*args, **kwargs):
    ros_client = Ros(*args, **kwargs)

    def callback(topic_list):
        print(topic_list)
        assert('/rosout' in topic_list['topics'])
        time.sleep(1)
        ros_client.terminate()

    def get_topics():
        ros_client.get_topics(callback)

    ros_client.on_ready(get_topics)
    ros_client.run_forever()
Esempio n. 8
0
class rosbridge_client:
    def __init__(self):
        self.ros_client = Ros('127.0.0.1', 9090)
        print("wait for server")
        self.publisher = Topic(self.ros_client, '/cmd_vel',
                               'geometry_msgs/Twist')
        self.listener = Topic(self.ros_client, '/odom', 'nav_msgs/Odometry')
        self.listener.subscribe(self.callback)

        self.ros_client.on_ready(self.start_thread, run_in_thread=True)
        self.ros_client.run_forever()

    def callback(self, message):
        x = message["pose"]["pose"]["position"]["x"]
        y = message["pose"]["pose"]["position"]["y"]
        print(x, y)

    def start_thread(self):
        while True:
            if self.ros_client.is_connected:
                self.publisher.publish(
                    Message({
                        'linear': {
                            'x': 0.5,
                            'y': 0,
                            'z': 0
                        },
                        'angular': {
                            'x': 0,
                            'y': 0,
                            'z': 0.5
                        }
                    }))
            else:
                print("Disconnect")
                break
            time.sleep(1.0)
Esempio n. 9
0
class ROSCloudSubBridge(object):
    def __init__(self, ip, port, local_topic_name, remote_topic_name,
                 message_type):
        self._ip = ip
        self._port = port
        self._local_topic_name = local_topic_name
        self._remote_topic_name = remote_topic_name
        self._message_type = message_type
        self._ros_client = Ros(self._ip, self._port)
        self._rosPub = None  # Should be specified by the automation engine
        self._listener = None  # Should be specified by the automation engine
        #        self._2listener = None  # Should be specified by the automation engine

        self._logger = logging.getLogger(self.__class__.__name__)
        self._logger.setLevel(logging.DEBUG)

    def _run_topic_pubsub(self):
        try:
            self._listener = Topic(self._ros_client, self._remote_topic_name,
                                   self._message_type)
            #            self._2listener = Topic(self._ros_client, self._remote_topic_name, self._message_type)
            rospy.init_node('cloudsub', anonymous=True)
            global my
            #            global my2
            #            my2=rospy.get_time()
            my = rospy.get_time()
            self._ros_client.on_ready(self._start_receiving,
                                      run_in_thread=True)
            self._ros_client.run_event_loop()
        except:
            self._logger.exception("Fatal error in constructor")

    def _receive_message(self, message):
        global my
        rospy.loginfo(rospy.get_caller_id() + " Message type %s ",
                      self._message_type)
        rospy.loginfo(
            rospy.get_caller_id() + " Time from previous message %s ",
            (rospy.get_time() - my))
        my = rospy.get_time()
        try:
            msg = Status()
            msg.header.seq = message['header']['seq']
            msg.header.stamp.secs = message['header']['stamp']['secs']
            msg.header.stamp.nsecs = message['header']['stamp']['nsecs']
            msg.header.frame_id = message['header']['frame_id']
            msg.id = message['id']
            msg.active = message['active']
            msg.heartbeat_timeout = message['heartbeat_timeout']
            msg.heartbeat_period = message['heartbeat_period']
            msg.instance_id = message['instance_id']
            #            for i in range(0,8):
            #             msg.orientation_covariance[i]=message['orientation_covariance'][i]
            #             msg.angular_velocity_covariance[i]=message['angular_velocity_covariance'][i]
            #             msg.linear_acceleration_covariance[i]=message['linear_acceleration_covariance'][i]
            self._rosPub = rospy.Publisher(self._local_topic_name,
                                           Status,
                                           queue_size=10)
            self._rosPub.publish(msg)
        except:
            print('Error')

#    def _2receive_message(self,message):
#        global my2
#        rospy.loginfo(rospy.get_caller_id() + "I heard a message %s",(rospy.get_time()-my2))
#        my2=rospy.get_time()
#        try:
#            msg=Clock()
#            msg.clock.secs=message['clock']['secs']
#            msg.clock.nsecs=message['clock']['nsecs']
#            self._rosPub=rospy.Publisher('/test/clock2', Clock, queue_size=10) #message type $
#            self._rosPub.publish(msg)
#        except:
#           print('Error')

    def _start_receiving(self):
        self._listener.subscribe(self._receive_message)


#        self._listener2.subscribe(self._2receive_message)

    def start(self):
        signal.signal(signal.SIGINT, lambda *x: self.stop())
        self._run_topic_pubsub()

    def stop(self):
        if self._ros_client is not None:
            self._ros_client.terminate()
class ROSCloudSubBridge(object):

    def __init__(self, ip, port, local_topic_name, remote_topic_name, message_type):
        self._ip = ip
        self._port = port
        self._local_topic_name = local_topic_name     
        self._remote_topic_name = remote_topic_name
        self._message_type = message_type
        self._ros_client= Ros(self._ip,self._port) 
        self._rosPub = None  # Should be specified by the automation engine
        self._listener = None  # Should be specified by the automation engine
#        self._2listener = None  # Should be specified by the automation engine

        self._logger = logging.getLogger(self.__class__.__name__)
        self._logger.setLevel(logging.DEBUG)

    def _run_topic_pubsub(self):
    	try:
            self._listener = Topic(self._ros_client, self._remote_topic_name, self._message_type)
#            self._2listener = Topic(self._ros_client, self._remote_topic_name, self._message_type)
            rospy.init_node('cloudsub', anonymous=True)
            global my
#            global my2
#            my2=rospy.get_time()    
            my=rospy.get_time()
            self._ros_client.on_ready(self._start_receiving, run_in_thread=True)
            self._ros_client.run_event_loop() 
        except:        
            self._logger.exception("Fatal error in constructor")
    

    def _receive_message(self,message):
        global my
        rospy.loginfo(rospy.get_caller_id() + " Message type %s ",self._message_type)
        rospy.loginfo(rospy.get_caller_id() + " Time from previous message %s ",(rospy.get_time()-my))
        my=rospy.get_time()
        try:
           msg=TFMessage()
           msg1=TransformStamped()
           list_msg=[]
           for i in range(len(message['transforms'])) :
            msg1.header.seq=message['transforms'][i]['header']['seq']
            msg1.header.stamp.secs=message['transforms'][i]['header']['stamp']['secs']
            msg1.header.stamp.nsecs=message['transforms'][i]['header']['stamp']['nsecs']
            msg1.header.frame_id=message['transforms'][i]['header']['frame_id']
            msg1.child_frame_id=message['transforms'][i]['child_frame_id']
            msg1.transform.translation.x=message['transforms'][i]['transform']['translation']['x']
            msg1.transform.translation.y=message['transforms'][i]['transform']['translation']['y']
            msg1.transform.translation.z=message['transforms'][i]['transform']['translation']['z']
            msg1.transform.rotation.x=message['transforms'][i]['transform']['rotation']['x']
            msg1.transform.rotation.y=message['transforms'][i]['transform']['rotation']['y']
            msg1.transform.rotation.z=message['transforms'][i]['transform']['rotation']['z']
            msg1.transform.rotation.w=message['transforms'][i]['transform']['rotation']['w']
            list_msg.append(msg1)
           msg=TFMessage(list_msg)
           self._rosPub=rospy.Publisher(self._local_topic_name, TFMessage, queue_size=10)
           self._rosPub.publish(msg)
        except:
           print('Error')        
 


    def _start_receiving(self): 
        self._listener.subscribe(self._receive_message)
#        self._listener2.subscribe(self._2receive_message)


    def start(self):
        signal.signal(signal.SIGINT, lambda *x: self.stop())
        self._run_topic_pubsub()

    def stop(self):
        if self._ros_client is not None:
            self._ros_client.terminate()
class ROSCloudSubBridge(object):
    def __init__(self, ip, port, local_topic_name, remote_topic_name,
                 message_type):
        self._ip = ip
        self._port = port
        self._local_topic_name = local_topic_name
        self._remote_topic_name = remote_topic_name
        self._message_type = message_type
        self._ros_client = Ros(self._ip, self._port)
        self._rosPub = None  # Should be specified by the automation engine
        self._listener = None  # Should be specified by the automation engine

        self._logger = logging.getLogger(self.__class__.__name__)
        self._logger.setLevel(logging.DEBUG)

    def _run_topic_pubsub(self):
        try:
            self._listener = Topic(self._ros_client, self._remote_topic_name,
                                   self._message_type)
            rospy.init_node('cloudsub', anonymous=True)
            global my
            my = rospy.get_time()
            self._ros_client.on_ready(self._start_receiving,
                                      run_in_thread=True)
            self._ros_client.run_event_loop()
        except:
            self._logger.exception("Fatal error in constructor")

    def _receive_message(self, message):
        global my
        rospy.loginfo(rospy.get_caller_id() + " Message type %s ",
                      self._message_type)
        rospy.loginfo(
            rospy.get_caller_id() + " Time from previous message %s ",
            (rospy.get_time() - my))
        my = rospy.get_time()
        #          try:
        msg = OccupancyGrid()
        msg.header.seq = message['header']['seq']
        msg.header.stamp = rospy.Time.now(
        )  #.secs=message['header']['stamp']['secs']
        msg.header.frame_id = message['header']['frame_id']  #type unicode
        msg.info.map_load_time.secs = message['info']['map_load_time']['secs']
        msg.info.map_load_time.nsecs = message['info']['map_load_time'][
            'nsecs']
        msg.info.resolution = message['info']['resolution']
        msg.info.width = message['info']['width']
        msg.info.height = message['info']['height']
        msg.info.origin.position.x = message['info']['origin']['position']['x']
        msg.info.origin.position.y = message['info']['origin']['position']['y']
        msg.info.origin.position.z = message['info']['origin']['position']['z']
        msg.info.origin.orientation.x = message['info']['origin'][
            'orientation']['x']
        msg.info.origin.orientation.y = message['info']['origin'][
            'orientation']['y']
        msg.info.origin.orientation.z = message['info']['origin'][
            'orientation']['z']
        msg.info.origin.orientation.w = message['info']['origin'][
            'orientation']['w']
        msg.data = message['data']
        #            for i in range(len(message['data'])):
        #             print(i)
        #             msg.data[i]=message['data'][i]
        self._rosPub = rospy.Publisher(self._local_topic_name,
                                       OccupancyGrid,
                                       queue_size=10)
        self._rosPub.publish(msg)


#           except:
#            print('Error')

    def _start_receiving(self):
        self._listener.subscribe(self._receive_message)

    def start(self):
        signal.signal(signal.SIGINT, lambda *x: self.stop())
        self._run_topic_pubsub()

    def stop(self):
        if self._ros_client is not None:
            self._ros_client.terminate()
Esempio n. 12
0
class Muse_app:
    def __init__(self):
        self.client = mqtt.Client()
        self.client2 = mqtt.Client()
        self.ros_client = Ros(host='10.205.240.34', port=9090)  
        self.publisher = Topic(self.ros_client, '/chatter', 'std_msgs/String')
        self.muse_left = "DC11"
        self.muse_right = "C00E"
        self.status_left = False
        self.status_right = False
        self.action_mode = 0

        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message
        self.client.connect("localhost", 1883, 60)
        t = threading.Thread(target=self.worker)
        t.start()

        self.client2.on_connect = self.on_connect2
        self.client2.on_message = self.on_message
        self.client2.connect("localhost", 1883, 60)
        t2 = threading.Thread(target=self.worker2)
        t2.start()

        self.ros_client.on_ready(self.subscribing, run_in_thread=True)
        t3 = threading.Thread(target=self.worker3)
        t3.start()
        while True:
            pass

    def on_connect(self, client, userdata, flags, rc):
        print("Connected with result code "+str(rc))

        # Subscribing in on_connect() means that if we lose the connection and
        # reconnect then subscriptions will be renewed.
        self.client.subscribe("topic/" + self.muse_left)
        #self.client.subscribe("topic/test")

    def on_connect2(self, client, userdata, flags, rc):
        print("Connected with result code "+str(rc))

        # Subscribing in on_connect() means that if we lose the connection and
        # reconnect then subscriptions will be renewed.
        self.client2.subscribe("topic/" + self.muse_right)


    def worker(self):
        self.client.loop_forever()
        return

    def worker2(self):
        self.client2.loop_forever()
        return

    def on_message(self, client, userdata, message):
        print("message received " ,str(message.payload.decode("utf-8")))
        print("message topic=",message.topic)
        if message.topic == "topic/" + self.muse_left:
            if(message.payload.decode("utf-8") == '0'):
                self.status_left = False
            elif(message.payload.decode("utf-8") == '1'):
                self.status_left = True
            print("left = " , self.status_left)
        if message.topic == "topic/" + self.muse_right:
            if(message.payload.decode("utf-8") == '0'):
                self.status_right = False
            elif(message.payload.decode("utf-8") == '1'):
                self.status_right = True
            print("right = " , self.status_right)
        # print("message qos=",message.qos)
        # print("message retain flag=",message.retain)

    def subscribing(self):
        print("subscribe to Ros..")
        self.publisher.subscribe(self.receive_message)
        

    def uninitialize(self):
        # nop
        return

    def receive_message(self, message):
        # context['counter'] += 1
        print('Receive data from Ros, ' , message['data'])
        #assert message['data'] == 'hello world', 'Unexpected message content'
        if(message['data'] == "action"):
            self.client.publish("topic/parameters", 'action')
            time.sleep(3)
            print("lastest status from left = " , self.status_left)
            print("lastest status from right = " , self.status_right)
            if self.status_left and not self.status_right: ##======================TURN LEFT
                self.action_mode = 1
            elif not self.status_left and self.status_right: ##======================TURN RIGHT
                self.action_mode = 2
            elif not self.status_left and not self.status_right: ##======================MOVE FORWARD
                self.action_mode = 3
            elif self.status_left and self.status_right: ##======================MOVE BACKWARD
                self.action_mode = 4
            print("summary action mode = ", str(self.action_mode))
            self.client.publish("topic/parameters", 'wait')
            isConnected = self.ros_client.is_connected
            print("isConnected = ", isConnected)
            if(isConnected):
                self.publisher.publish(Message({'data': str(self.action_mode)}))

    def worker3(self):
        self.ros_client.run_forever()	
class ROSCloudSubBridge(object):

    def __init__(self, ip, port, local_topic_name, remote_topic_name, message_type):
        self._ip = ip
        self._port = port
        self._local_topic_name = local_topic_name     
        self._remote_topic_name = remote_topic_name
        self._message_type = message_type
        self._ros_client= Ros(self._ip,self._port) 
        self._rosPub = None  # Should be specified by the automation engine
        self._listener = None  # Should be specified by the automation engine

        self._logger = logging.getLogger(self.__class__.__name__)
        self._logger.setLevel(logging.DEBUG)

    def _run_topic_pubsub(self):
    	try:
            self._listener = Topic(self._ros_client, self._remote_topic_name, self._message_type)
            rospy.init_node('cloudsub', anonymous=True)
            global my
            my=rospy.get_time()
            self._ros_client.on_ready(self._start_receiving, run_in_thread=True)
            self._ros_client.run_event_loop() 
        except:        
            self._logger.exception("Fatal error in constructor")
    

    def _receive_message(self,message):
           global my
           rospy.loginfo(rospy.get_caller_id() + " Message type %s ",self._message_type)
           rospy.loginfo(rospy.get_caller_id() + " Time from previous message %s ",(rospy.get_time()-my))
           my=rospy.get_time()
           try:
            msg=LaserScan()
            msg.header.seq=message['header']['seq']
            msg.header.stamp.secs=message['header']['stamp']['secs']
            msg.header.stamp.nsecs=message['header']['stamp']['nsecs']
            msg.header.frame_id=message['header']['frame_id']
            msg.angle_min=message['angle_min'] 
            msg.angle_max=message['angle_max'] 
            msg.angle_increment=message['angle_increment']
            msg.time_increment=message['time_increment'] 
            msg.scan_time=message['scan_time']
            msg.range_min=message['range_min']
            msg.range_max=message['range_max']
            ranges_list=[]
            intensities_list=[] 
            for i in range(len(message['ranges'])):
             ranges_list.append(float)
             if message['ranges'][i]==None:
              ranges_list[i]=float('NaN')
             else:
              ranges_list[i]=message['ranges'][i]
            for i in range(len(message['intensities'])):
             intensities_list.append(float)
             if message['intensities'][i]==None:
              intensities_list[i]=float('NaN')
             else:
              intensities_list[i]=message['intensities'][i]
            msg.ranges=ranges_list
            msg.intensities=intensities_list
            self._rosPub=rospy.Publisher(self._local_topic_name, LaserScan, queue_size=10)
            self._rosPub.publish(msg)
           except:
            print('Error')        


    def _start_receiving(self): 
        self._listener.subscribe(self._receive_message)


    def start(self):
        signal.signal(signal.SIGINT, lambda *x: self.stop())
        self._run_topic_pubsub()

    def stop(self):
        if self._ros_client is not None:
            self._ros_client.terminate()
Esempio n. 14
0
class MyOVBox(OVBox):
    def __init__(self):
        OVBox.__init__(self)
        self.signalHeader = None

        self.ros_client = Ros(host='10.204.231.147', port=9090)
        #self.listener = Topic(self.ros_client, '/chatter', 'std_msgs/String')
        self.publisher = Topic(self.ros_client, '/chatter', 'std_msgs/String')
        self.ros_client.on_ready(self.subscribing, run_in_thread=True)
        self.phase = 0
        self.parameters = {
            "count": "4",
            "scenario": "4",
            "gender": "Male",
            "age": "25",
            "subjectno": "55",
            "phase": 5,
            "type": 2
        }
        # ros_client.on_ready(start_receiving, run_in_thread=True)

    def initialize(self):
        self.counter = 0
        t = threading.Thread(target=self.worker)
        t.start()
        s = threading.Thread(target=self.workerMQTT)
        s.start()
        # self.ros_client.run_forever()
        return

    def on_connect(self, client, userdata, flags, rc):
        print("Connected with result code " + str(rc))

        # Subscribing in on_connect() means that if we lose the connection and
        # reconnect then subscriptions will be renewed.
        self.client.subscribe("topic/parameters")

    # The callback for when a PUBLISH message is received from the server.
    def on_message(self, client, userdata, msg):
        #print(msg.topic+" "+str(msg.payload))
        parameters = msg.payload
        print("parameters = ", parameters)
        self.parameters = json.loads(parameters)
        self.phase = int(self.parameters.get('phase'))
        print("phase = ", self.phase)

    def worker(self):
        self.ros_client.run_forever()

    def workerMQTT(self):
        self.client = mqtt.Client()
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message

        self.client.connect("localhost", 1883, 60)

        # Blocking call that processes network traffic, dispatches callbacks and
        # handles reconnecting.
        # Other loop*() functions are available that give a threaded interface and a
        # manual interface.
        self.client.loop_forever()

    def process(self):
        self.counter += 1
        for chunkIndex in range(len(self.input[0])):
            if (type(self.input[0][chunkIndex]) == OVSignalHeader):
                self.signalHeader = self.input[0].pop()
                outputHeader = OVSignalHeader(
                    self.signalHeader.startTime, self.signalHeader.endTime,
                    [1, self.signalHeader.dimensionSizes[1]],
                    ['Mean'] + self.signalHeader.dimensionSizes[1] * [''],
                    self.signalHeader.samplingRate)

                self.output[0].append(outputHeader)

            elif (type(self.input[0][chunkIndex]) == OVSignalBuffer):
                #Check if Condition != 0 , Meaning user has been clicked start scenario
                #if(self.phase != 0):
                chunk = self.input[0].pop()
                numpyBuffer = np.array(chunk).reshape(
                    tuple(self.signalHeader.dimensionSizes))
                #with open("C:/Users/h4wk/Desktop/Temp/foo.csv",'ab') as f:
                #path = os.getcwd() + datetime.datetime.now().strftime("%B %d, %Y") + ".csv"
                # if(self.phase != 0):
                path = self.setting[
                    'OutputPath'] + '/BCI_GTEC_' + datetime.datetime.now(
                    ).strftime("%Y%m%d_" + self.setting['subject_no']) + ".csv"
                with open(path, 'ab') as f:
                    #t = time.localtime()
                    #print("Current path:" + path)
                    x = datetime.datetime.now()
                    #a = np.asarray([[time.mktime(x.timetuple()),
                    #Header Pattern: Timestamp, phase, scenario, subjectno, gender, age, type, count
                    a = np.asarray(int(round(time.time() * 1000)),
                                   dtype=object)
                    # print(a)
                    # np.savetxt(f, a, delimiter=",", fmt='%5s')
                    for channel in numpyBuffer:
                        channel = np.insert(channel, 0, a, axis=0)
                        # print(channel.shape)
                        np.savetxt(f, [channel], delimiter=",")
                #==================Sending to ROS Server==========================#
                #print(self.counter)
                # if(self.counter >= 20):
                # 	self.counter = 0
                # 	#self.ros_client.on_ready(self.publisher.publish(Message({'data': numpyBuffer})))
                # 	isConnected = self.ros_client.is_connected
                # 	#print("isConnected = ", isConnected)
                # 	if(isConnected):
                # 		print("sending data... ", numpyBuffer.tolist())
                # 		#self.publisher.publish(Message({'data': numpyBuffer.tolist()}))
                # 		a = " ".join(str(i) for i in numpyBuffer.tolist())
                # 		self.publisher.publish(Message({'data': a}))
                # 		#self.publisher.publish(Message({'data': 'hello test'}))
                # 		#self.publisher.unadvertise()
                # ==================End Sending to ROS Server==========================#
                numpyBuffer = numpyBuffer.mean(axis=0)
                chunk = OVSignalBuffer(chunk.startTime, chunk.endTime,
                                       numpyBuffer.tolist())
                self.output[0].append(chunk)

            elif (type(self.input[0][chunkIndex]) == OVSignalEnd):
                self.output[0].append(self.input[0].pop())

    def subscribing(self):
        self.publisher.subscribe(receive_message)

    def uninitialize(self):
        # nop
        return