【ROSBridge】连接与简单收发数据(1)

  • Post author:
  • Post category:其他




0.ifconfig查看ip地址



1.连接

首要的工作是建立手机与电脑端的连接

(1)复制开源库

1 app/libs
2 jilk/ros
3 RCApplication(与主文件在同一文件夹下)

(2)添加权限

​ 在AndroidManifest文件中xmlns:tools的下一行添加:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

​ 由于添加了RCApplication文件,所以在AndroidManifest文件中添加(位置在application下,注意包名):

android:name="com.example.test1rosbridge.RCApplication"

(3)添加依赖

​ app/build.gradle文件下,添加

implementation fileTree(include: ['*.jar'], dir: 'libs')

(4)搭建界面

所需要的:

1 TextView 表示IP和端口号
2 EditView 填入所需的IP和端口号
3 两个Button 连接和断开

(5)连接所需的具体代码

private void connect(String ip, String port) {
        client = new ROSBridgeClient("ws://" + ip + ":" + port);
        Flag_Connect = client.connect(new ROSClient.ConnectionStatusListener() {
            @Override
            public void onConnect() {
                client.setDebug(true);
                ((RCApplication)getApplication()).setRosClient(client);
                showTip("连接成功");
                runOnUiThread(() -> state.setText("已连接"));
                Log.d(TAG, "Connect ROS success");
            }

            @Override
            public void onDisconnect(boolean normal, String reason, int code) {
                showTip("连接断开");
                runOnUiThread(() -> state.setText("未连接"));
                Log.d(TAG, "ROS Connect ERROR");
            }

            @Override
            public void onError(Exception ex) {
                ex.printStackTrace();
                showTip("ROS communication error");
                Log.d(TAG, "ROS communication error");
            }
        });
    }
    private void showTip(final String tip) {
        runOnUiThread(() -> Toast.makeText(MainActivity.this, tip, Toast.LENGTH_SHORT).show());
    }



2.接收数据

(0)Ros端所需要的代码(发布者)

    #!/usr/bin/env python
    # license removed for brevity
import rospy
from std_msgs.msg import String
    
def talker():
    pub = rospy.Publisher('chatter', String, queue_size=10)
    rospy.init_node('talker', anonymous=True)
    rate = rospy.Rate(1) # 1hz
    while not rospy.is_shutdown():
       hello_str = "hello world"
       rospy.loginfo(hello_str)
       pub.publish(hello_str)
       rate.sleep()
   
if __name__ == '__main__':
     try:
          talker()
     except rospy.ROSInterruptException:
          pass

(1)接收代码

    //接收来自Ros端的数据
    private void ReceiveDataToRos() {
        String msg1 = "{\"op\":\"subscribe\",\"topic\":\"/chatter\"}";
        client.send(msg1);
    }

(2)匹配话题并显示

    public void onEvent(final PublishEvent event) {
        if ("/chatter".equals(event.name)) {
            parseChatterTopic(event);
            return;
        }
        Log.d("Aachen", event.msg);
    }

    private void parseChatterTopic(PublishEvent event) {
        try {
            JSONParser parser = new JSONParser();
            org.json.simple.JSONObject jsonObject = (org.json.simple.JSONObject) parser.parse(event.msg);
            String json_data = (String) jsonObject.get("data");

            textSub.setText(json_data);

            Log.i("Aachen", json_data);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

(3)总结

因为发送的数据不变,所以不论点击多少次接收按钮,总是显示所发送的数据。此处可以应用的地方为:订阅机器人的位置及速度等数据并实时显示。



3.发送数据

(0)Ros端所需要的代码(订阅者)

#! /usr/bin/env python3
import rospy
from std_msgs.msg import String #发布的消息的类型

def doMsg(msg):
    rospy.loginfo("订阅的数据: %s ", msg.data)

if __name__ == "__main__":
    
    rospy.init_node("listener")
    sub = rospy.Subscriber("chatter", String, doMsg, queue_size=10)
    rospy.spin()
    pass

(1)发送代码

    private void SendDataToRos(String data) {
        msg = "{\"op\":\"publish\",\"topic\":\"/chatter\",\"msg\":{ \"data\": \"" + data + "\" }}";
        Log.d(TAG,msg);
        client.send(msg);
    }

(2)安卓相关

​ 点击按钮将需要发送的数据发送出去



4.启动流程

1 roscore
2 roslaunch rosbridge_server rosbridge_websocket.launch
3 进入工作空间,启动节点:rosrun 包名 节点名
4 启动安卓app,点击连接



5.参考博客


Android和ROS的通信 消息的传递



版权声明:本文为ASUNAchan原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。