Skip to content

4.13 机器人订阅发布接口

4.13.1 连接到 WebSocket 服务器

方法名SubPub.Connect()
描述连接到机器人控制器的 WebSocket 服务器
请求参数
返回值Task:异步连接操作结果
兼容的机器人软件版本协作 (Copper): v7.7.0.0+
工业 (Bronze): v7.7.0.0+

4.13.2 断开 WebSocket 服务器

方法名SubPub.Disconnect()
描述断开与机器人控制器 WebSocket 服务器的连接
请求参数
返回值Task:异步断开操作结果
兼容的机器人软件版本协作 (Copper): v7.7.0.0+
工业 (Bronze): v7.7.0.0+

4.13.3 添加机器人状态订阅

方法名SubPub.SubscribeStatus(RobotTopicType[] topicTypes , int frequency = 200)
描述添加机器人状态数据订阅
请求参数topicTypes : RobotTopicType [] 需要订阅的机器人主题类型列表
frequency : int 订阅频率,单位为 Hz,默认值 200
返回值Task:异步订阅操作结果
兼容的机器人软件版本协作 (Copper): v7.7.0.0+
工业 (Bronze): v7.7.0.0+

4.13.4 添加寄存器订阅

方法名SubPub.SubscribeRegister(RegTopicType regType , int[] regIds , int frequency = 200)
描述添加寄存器数据订阅
请求参数regType : RegTopicType 寄存器类型
regIds : int [] 需要订阅的寄存器 ID 列表
frequency : int 订阅频率,单位为 Hz,默认值 200
返回值Task:异步订阅操作结果
兼容的机器人软件版本协作 (Copper): v7.7.0.0+
工业 (Bronze): v7.7.0.0+

4.13.5 添加 IO 订阅

方法名SubPub.SubscribeIO((IOTopicType, int)[] ioList , int frequency = 200)
描述订阅 IO 信号数据,包括数字输入输出等
请求参数ioList : (IOTopicType, int)[] IO 列表,每个元素为 (IO类型, IO ID)
frequency : int 订阅频率,单位为 Hz,默认值 200
返回值Task:异步订阅操作结果
兼容的机器人软件版本协作 (Copper): v7.7.0.0+
工业 (Bronze): v7.7.0.0+

4.13.6 开始接收消息

方法名SubPub.StartReceiving(Func<Dictionary<string, object>, Task> onMessageReceived )
描述开始接收订阅消息,并通过回调函数处理接收到的数据
请求参数onMessageReceived : Func<Dictionary<string, object>, Task> 消息接收回调函数
返回值Task:异步接收任务
兼容的机器人软件版本协作 (Copper): v7.7.0.0+
工业 (Bronze): v7.7.0.0+

示例代码

SubPub/CallbackReceiving.cs
cs
using Agilebot.IR;
using Agilebot.IR.SubPub;
using Agilebot.IR.Types;

public class CallbackReceiving
{
    public static StatusCode Run(string controllerIP, bool useLocalProxy = true)
    {
        // [ZH] 初始化捷勃特机器人
        // [EN] Initialize the Agilebot robot
        Arm controller = new Arm(controllerIP, useLocalProxy);

        // [ZH] 连接捷勃特机器人
        // [EN] Connect to the Agilebot robot
        StatusCode code = controller.ConnectSync();
        Console.WriteLine(code != StatusCode.OK ? code.GetDescription() : "连接成功/Successfully connected.");

        // [ZH] 初始化捷勃特机器人SubPub
        // [EN] Initialize the Agilebot robot SubPub
        var subPub = controller.SubPub;

        try
        {
            Console.WriteLine("开始回调方式接收消息测试/Starting Callback Receiving Test");

            // [ZH] 连接到WebSocket服务器
            // [EN] Connect to WebSocket server
            subPub.Connect().Wait();
            Console.WriteLine("WebSocket连接成功/WebSocket Connected Successfully");

            // [ZH] 订阅机器人状态
            // [EN] Subscribe to robot status
            var topicTypes = new RobotTopicType[] { RobotTopicType.TopicCurrentJoint, RobotTopicType.TopicRobotStatus };
            subPub.SubscribeStatus(topicTypes, frequency: 100).Wait();
            Console.WriteLine("机器人状态订阅成功/Robot Status Subscription Successful");

            // [ZH] 订阅寄存器
            // [EN] Subscribe to registers
            var regIds = new int[] { 1, 2, 3 };
            subPub.SubscribeRegister(RegTopicType.R, regIds, frequency: 100).Wait();
            Console.WriteLine("寄存器订阅成功/Register Subscription Successful");

            // [ZH] 订阅IO
            // [EN] Subscribe to IO
            var ioList = new (IOTopicType, int)[] { (IOTopicType.DI, 0), (IOTopicType.DO, 1) };
            subPub.SubscribeIO(ioList, frequency: 100).Wait();
            Console.WriteLine("IO订阅成功/IO Subscription Successful");

            int messageCount = 0;
            int maxMessages = 10; // 接收10条消息后停止

            Console.WriteLine("开始接收消息/Starting to receive messages...");

            // [ZH] 开始接收消息(回调方式)
            // [EN] Start receiving messages (callback method)
            subPub
                .StartReceiving(async message =>
                {
                    messageCount++;
                    Console.WriteLine($"\n=== 收到第{messageCount}条消息/Received Message #{messageCount} ===");
                    foreach (var kv in message)
                    {
                        Console.WriteLine($"{kv.Key}: {kv.Value}");
                    }

                    // [ZH] 接收指定数量消息后主动断开
                    // [EN] Disconnect after receiving specified number of messages
                    if (messageCount >= maxMessages)
                    {
                        Console.WriteLine(
                            $"已接收{maxMessages}条消息,准备断开连接/Received {maxMessages} messages, preparing to disconnect"
                        );
                        subPub.Disconnect().Wait();
                        Console.WriteLine("WebSocket断开成功/WebSocket Disconnected Successfully");
                    }

                    await Task.CompletedTask;
                })
                .Wait();

            Console.WriteLine("回调方式接收消息测试完成/Callback Receiving Test Completed");
            return StatusCode.OK;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"执行过程中发生异常/Exception occurred during execution: {ex.Message}");
            return StatusCode.OtherReason;
        }
        finally
        {
            // [ZH] 关闭连接
            // [EN] Close the connection
            StatusCode disconnectCode = controller.Disconnect();
            if (disconnectCode != StatusCode.OK)
            {
                Console.WriteLine(disconnectCode.GetDescription());
                if (code == StatusCode.OK)
                    code = disconnectCode;
            }
        }
    }
}

4.13.7 接收下一条文本消息

方法名SubPub.Receive()
描述接收下一条文本消息并返回
请求参数
返回值Task<Dictionary<string, object>>:接收到的消息字典
兼容的机器人软件版本协作 (Copper): v7.7.0.0+
工业 (Bronze): v7.7.0.0+

示例代码

SubPub/PollingReceiving.cs
cs
using Agilebot.IR;
using Agilebot.IR.SubPub;
using Agilebot.IR.Types;

public class PollingReceiving
{
    public static StatusCode Run(string controllerIP, bool useLocalProxy = true)
    {
        // [ZH] 初始化捷勃特机器人
        // [EN] Initialize the Agilebot robot
        Arm controller = new Arm(controllerIP, useLocalProxy);

        // [ZH] 连接捷勃特机器人
        // [EN] Connect to the Agilebot robot
        StatusCode code = controller.ConnectSync();
        Console.WriteLine(code != StatusCode.OK ? code.GetDescription() : "连接成功/Successfully connected.");

        // [ZH] 初始化捷勃特机器人SubPub
        // [EN] Initialize the Agilebot robot SubPub
        var subPub = controller.SubPub;

        try
        {
            Console.WriteLine("开始轮询方式接收消息测试/Starting Polling Receiving Test");

            // [ZH] 连接到WebSocket服务器
            // [EN] Connect to WebSocket server
            subPub.Connect().Wait();
            Console.WriteLine("WebSocket连接成功/WebSocket Connected Successfully");

            // [ZH] 订阅机器人状态
            // [EN] Subscribe to robot status
            var topicTypes = new RobotTopicType[] { RobotTopicType.TopicCurrentJoint, RobotTopicType.TopicRobotStatus };
            subPub.SubscribeStatus(topicTypes, frequency: 100).Wait();
            Console.WriteLine("机器人状态订阅成功/Robot Status Subscription Successful");

            // [ZH] 订阅寄存器
            // [EN] Subscribe to registers
            var regIds = new int[] { 1, 2, 3 };
            subPub.SubscribeRegister(RegTopicType.R, regIds, frequency: 100).Wait();
            Console.WriteLine("寄存器订阅成功/Register Subscription Successful");

            // [ZH] 订阅IO
            // [EN] Subscribe to IO
            var ioList = new (IOTopicType, int)[] { (IOTopicType.DI, 0), (IOTopicType.DO, 1) };
            subPub.SubscribeIO(ioList, frequency: 100).Wait();
            Console.WriteLine("IO订阅成功/IO Subscription Successful");

            int messageCount = 0;
            int maxMessages = 10; // 接收10条消息后停止

            Console.WriteLine("开始轮询接收消息/Starting to poll messages...");

            // [ZH] 循环接收消息直到达到期望数量
            // [EN] Loop to receive messages until reaching desired count
            do
            {
                messageCount++;
                try
                {
                    // [ZH] 接收单条消息
                    // [EN] Receive single message
                    var message = subPub.Receive().Result;
                    Console.WriteLine($"\n=== 收到第{messageCount}条消息/Received Message #{messageCount} ===");
                    foreach (var kv in message)
                    {
                        Console.WriteLine($"{kv.Key}: {kv.Value}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"接收消息时发生异常/Exception while receiving message: {ex.Message}");
                    break;
                }
            } while (messageCount < maxMessages);

            // [ZH] 断开连接
            // [EN] Disconnect
            subPub.Disconnect().Wait();
            Console.WriteLine("WebSocket断开成功/WebSocket Disconnected Successfully");

            Console.WriteLine("轮询方式接收消息测试完成/Polling Receiving Test Completed");
            return StatusCode.OK;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"执行过程中发生异常/Exception occurred during execution: {ex.Message}");
            return StatusCode.OtherReason;
        }
        finally
        {
            // [ZH] 关闭连接
            // [EN] Close the connection
            StatusCode disconnectCode = controller.Disconnect();
            if (disconnectCode != StatusCode.OK)
            {
                Console.WriteLine(disconnectCode.GetDescription());
                if (code == StatusCode.OK)
                    code = disconnectCode;
            }
        }
    }
}