### Plugin Packaging, Installation, and API Calls Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/04-data-persistence Instructions on how to package, install, and interact with the created simple service plugin. ```APIDOC ### Step 2: Package and Install Refer to the "Packaging and Installation" section for plugin packaging instructions. ### Step 3: Call Interfaces 1. **Set Configuration**: Access `http://10.27.1.254:5616/DataService/set_robot_config?key=model_type&value=GBT-C5A` This operation writes a configuration item named `model_type` with the value `GBT-C5A`. 2. **Get Configuration**: Access `http://10.27.1.254:5616/DataService/get_robot_config?key=model_type` Under normal circumstances, this will return: ```json { "result": "GBT-C5A" } ``` 3. **Delete Configuration**: Access `http://10.27.1.254:5616/DataService/delete_robot_config?key=model_type` This operation deletes the configuration item `model_type`. Note: For more calling methods, please refer to the relevant chapters. ``` -------------------------------- ### Installation Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/02-web-runtime-package Instructions on how to install the Agilebot Extension Runtime library using npm, yarn, or pnpm, as well as how to include it directly in a browser. ```APIDOC ## Installation ### Description Instructions on how to install the Agilebot Extension Runtime library using npm, yarn, or pnpm, as well as how to include it directly in a browser. ### Package Managers #### npm ```sh npm install @agilebot/extension-runtime ``` #### yarn ```sh yarn add @agilebot/extension-runtime ``` #### pnpm ```sh pnpm add @agilebot/extension-runtime ``` ### Browser Include the library directly in your HTML file using a script tag. The library will be available under the global `gbtExtension` namespace. ```html ``` ``` -------------------------------- ### Simple Service Plugin Package Creation Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/04-data-persistence Steps and code examples for creating a simple service plugin package with data persistence using SQLite. ```APIDOC ## Create a Simple Service Plugin Package This section demonstrates creating a simple service plugin that provides interfaces for configuration write, read, and delete operations, persisting data to an SQLite database. ### Step 1: Create Plugin Folder Structure A basic plugin folder structure is required, including a `config.json` configuration file and a Python file. For simple services, the **Python file name must match the plugin name**. **Directory Structure**: ``` * DataService * config.json * DataService.py ``` #### config.json ```json { "name": "DataService", "type": "easyService", "scriptLang": "python", "description": "数据服务", "version": "0.1" } ``` #### DataService.py ```python from pathlib import Path import sqlite3 # Get global logger instance, only available in simple services logger = globals().get('logger') if logger is None: # Use built-in logging library for local debugging import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def __init_db(): """ Initialize the database. """ try: current_dir = Path(__file__).parent.resolve() data_dir = current_dir / 'data' # Create data directory if it doesn't exist if not data_dir.exists(): data_dir.mkdir(parents=True) db_path = data_dir / 'data.db' # Connect to the database conn = sqlite3.connect(db_path) cursor = conn.cursor() logger.info("Database opened successfully") # Create table cursor.execute(''' CREATE TABLE IF NOT EXISTS `robot_config` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `key` VARCHAR(255) NOT NULL UNIQUE, `value` TEXT NOT NULL ); ''') logger.info("Table created successfully") conn.commit() return conn except Exception as e: logger.error(f"Failed to initialize database: {e}") return None conn = __init_db() """ Global variable to hold the unique database connection instance """ def get_robot_config(key: str): """Retrieve configuration value by key.""" try: cursor = conn.cursor() cursor.execute('SELECT value FROM robot_config WHERE key = ?', (key,)) result = cursor.fetchone() return result[0] if result else None except sqlite3.Error as e: logger.error(f"Failed to get configuration '{key}': {e}") return None def set_robot_config(key: str, value: str): """Set or update a configuration item.""" try: cursor = conn.cursor() cursor.execute('INSERT OR REPLACE INTO robot_config (key, value) VALUES (?, ?)', (key, str(value))) conn.commit() logger.info(f"Configuration '{key}' set to '{value}'.") return True except sqlite3.Error as e: logger.error(f"Failed to set configuration '{key}': {e}") return False def delete_robot_config(key: str): """Delete a configuration item by key.""" try: cursor = conn.cursor() cursor.execute('DELETE FROM robot_config WHERE key = ?', (key,)) conn.commit() logger.info(f"Configuration '{key}' deleted.") return True except sqlite3.Error as e: logger.error(f"Failed to delete configuration '{key}': {e}") return False ``` ``` -------------------------------- ### 使用 Python 请求简单服务接口 Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/02-quick-start/02-easy-service 此 Python 脚本使用 `requests` 库向 'MathService' 插件的 'add' 接口发送 GET 请求,并传递参数 `a=1` 和 `b=2`。它会检查响应状态码,如果成功(200),则解析 JSON 响应并打印结果,否则打印错误状态码。该代码是 Python 语言。 ```python import requests response = requests.get('http://10.27.1.254:5616/MathService/add', { 'a': 1, 'b': 2 }) if response.status_code == 200: # 解析 JSON 响应 data = response.json() # 输出结果 print(f"Result: {data['result']}") else: print(f"Request failed with status code: {response.status_code}") ``` -------------------------------- ### GET /MathService/add - Add Two Numbers Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/02-quick-start/02-easy-service This endpoint allows you to perform addition of two integer numbers using the MathService. ```APIDOC ## GET /MathService/add ### Description This endpoint performs the addition of two integer numbers provided as query parameters. ### Method GET ### Endpoint /MathService/add ### Parameters #### Query Parameters - **a** (int) - Required - The first number. - **b** (int) - Required - The second number. ### Request Example None ### Response #### Success Response (200) - **result** (int) - The sum of a and b. #### Response Example ```json { "result": 3 } ``` ``` -------------------------------- ### Python: Connect and Subscribe to Robot Status Source: https://dev.sh-agilebot.com/docs/extension/zh/03-detailed-case/01-tcp-velocity Establishes a connection to the robot using the Agilebot Python SDK and subscribes to essential robot status topics like Cartesian Position and TP Program Status. It also starts receiving messages from the robot. ```python await self.arm.sub_pub.connect() await self.arm.sub_pub.subscribe_status( [ RobotTopicType.CARTESIAN_POSITION, RobotTopicType.TP_PROGRAM_STATUS, ], frequency=200, ) await self.arm.sub_pub.start_receiving(self.handle_robot_message) ``` -------------------------------- ### 编译 Vue 项目 Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/01-complex-page 使用 pnpm build 命令编译 Vue 项目,生成生产环境所需的静态文件。 ```bash pnpm build ``` -------------------------------- ### Get Language Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/02-web-runtime-package Retrieve the current language setting of the AgileLink App. This is useful for internationalizing your Web extension. ```APIDOC ## Get Language ### Description Retrieve the current language setting of the AgileLink App. This is useful for internationalizing your Web extension. ### Method `getLanguage` ### Endpoint N/A (This is a client-side library function) ### Parameters None ### Request Example ```typescript import { getLanguage } from '@agilebot/extension-runtime'; async function displayLanguage() { const currentLang = await getLanguage(); console.log(`Current language: ${currentLang}`); } displayLanguage(); ``` ### Response #### Success Response - **currentLang** (string) - The current language code (e.g., 'en', 'zh'). #### Response Example ```json { "currentLang": "en" } ``` ``` -------------------------------- ### 简单服务插件的配置文件 Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/02-quick-start/02-easy-service 这是一个 `config.json` 文件,用于配置简单服务插件的基本信息。它定义了插件的名称(MathService)、类型(easyService)、脚本语言(python)、描述以及版本号。此文件是 JSON 格式。 ```json { "name": "MathService", "type": "easyService", "scriptLang": "python", "description": "数学服务", "version": "0.1" } ``` -------------------------------- ### 创建 Vue 项目并安装依赖 Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/01-complex-page 使用 pnpm 创建一个新的 Vue 项目,并安装 @agilebot/extension-runtime 依赖。这是构建 Web 小程序插件的第一步。 ```bash pnpm create vue@latest cd MathPage pnpm i pnpm i @agilebot/extension-runtime ``` -------------------------------- ### Get Extension State Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/02-web-runtime-package Retrieves the current state of a specified extension, including whether it is enabled and its associated port number. ```APIDOC ## Get Extension State ### Description Retrieves the current state of a specified extension, including whether it is enabled and its associated port number. ### Method `getExtensionState(extensionId)` ### Endpoint N/A (This is a client-side library function) ### Parameters #### Path Parameters - **extensionId** (string) - Required - The unique identifier of the extension. ### Request Example ```typescript import { getExtensionState } from '@agilebot/extension-runtime'; async function checkExtensionStatus() { const extension = await getExtensionState('myService'); console.log(`Extension enabled: ${extension.enabled}, Port: ${extension.port}`); } checkExtensionStatus(); ``` ### Response #### Success Response - **extension** (object) - **enabled** (boolean) - Indicates if the extension is currently enabled. - **port** (number) - The network port associated with the extension, if applicable. #### Response Example ```json { "extension": { "enabled": true, "port": 8080 } } ``` ``` -------------------------------- ### HTML 结构示例 Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/02-quick-start/01-web-mini-program 一个基本的 HTML 文件,用于创建一个显示 'Hello Agilebot!' 消息的 Web 页面。该文件包含必要的 meta 标签和简单的 body 内容,设置了背景色和文本样式。 ```html
Hello Agilebot!
``` -------------------------------- ### 创建简单服务插件的 Python 脚本 Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/02-quick-start/02-easy-service 这是用于实现加法运算的简单服务插件的 Python 脚本。它定义了一个 `add` 函数,该函数接收两个整数并返回它们的和。脚本还包含了日志记录功能,以便在出现异常时进行错误处理。该脚本仅支持 Python 语言。 ```python # 获取全局logger实例,只能在简单服务中使用 logger = globals().get('logger') if logger is None: # 本地调试时,使用自带日志库 import logging logger = logging.getLogger(__name__) def add(a: int, b: int) -> int: """ 执行两个整数的加法运算 参数: - a (int): 第一个加数 - b (int): 第二个加数 返回: - int: 返回加法结果 """ try: result = a + b return result except Exception as ex: logger.error(ex) return 0 ``` -------------------------------- ### SQLite 数据库操作 - Python Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/04-data-persistence 提供了一组 Python 函数,用于与 SQLite 数据库中的 `robot_config` 表进行交互。包括根据键获取配置值 (`get_robot_config`),设置或更新配置项 (`set_robot_config`),以及根据键删除配置项 (`delete_robot_config`)。所有操作都经过了错误处理和日志记录。 ```python def get_robot_config(key: str): """根据 key 获取配置值。""" try: cursor = conn.cursor() cursor.execute('SELECT value FROM robot_config WHERE key = ?', (key,)) result = cursor.fetchone() return result[0] if result else None except sqlite3.Error as e: logger.error(f"获取配置 '{key}' 失败: {e}") return None def set_robot_config(key: str, value: str): """设置或更新一个配置项。""" try: cursor = conn.cursor() cursor.execute('INSERT OR REPLACE INTO robot_config (key, value) VALUES (?, ?)', (key, str(value))) conn.commit() logger.info(f"配置 '{key}' 已设置为 '{value}'。") return True except sqlite3.Error as e: logger.error(f"设置配置 '{key}' 失败: {e}") return False def delete_robot_config(key: str): """根据 key 删除一个配置项。""" try: cursor = conn.cursor() cursor.execute('DELETE FROM robot_config WHERE key = ?', (key,)) conn.commit() logger.info(f"配置 '{key}' 已删除。") return True except sqlite3.Error as e: logger.error(f"删除配置 '{key}' 失败: {e}") return False ``` -------------------------------- ### Vue 加法计算器组件 Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/01-complex-page 一个 Vue 3 组件,使用 Composition API 实现一个加法计算器。它通过 @agilebot/extension-runtime 的 callEasyService 方法调用远程的 'math' 服务,并显示计算结果。组件包含输入框、按钮和结果显示区域。 ```vue < div class ="math"> < h1 >加法计算器 h1 > < div class ="container"> < label for ="inputA">a: label > < input type ="number" v-model=" a " placeholder ="输入第一个数字" /> < label for ="inputB">b: label > < input type ="number" v-model=" b " placeholder ="输入第二个数字" /> < button @ click =" handleCalculate ">计算 a + b button > div > < div class ="result"> < p > 结果: < span >{{ c }} span > p > div > div > template> ``` -------------------------------- ### 定义简单服务插件配置 (config.json) Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/03-complex-backend 此 JSON 文件定义了一个简单服务插件的元数据。它指定了插件的名称(MathServiceComplex)、类型(easyService)、脚本语言(python)、描述(数学服务)以及版本(0.1)。 ```json { "name": "MathServiceComplex", "type": "easyService", "scriptLang": "python", "description": "数学服务", "version": "0.1" } ``` -------------------------------- ### 创建 SQLite 数据库和表 - Python Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/04-data-persistence 该 Python 代码片段展示了如何初始化一个 SQLite 数据库 (`data.db`),并在插件的 `data` 目录下创建 `robot_config` 表。`robot_config` 表包含 `id`、`key` 和 `value` 三个字段,用于存储键值对配置。代码包含了错误处理和日志记录,并确保 `data` 目录的存在。 ```python from pathlib import Path import sqlite3 # 获取全局logger实例,只能在简单服务中使用 logger = globals().get('logger') if logger is None: # 本地调试时,使用自带日志库 import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def __init_db(): """ 初始化数据库 """ try: current_dir = Path(__file__).parent.resolve() data_dir = current_dir / 'data' # 如果data目录不存在,手动创建 if not data_dir.exists(): data_dir.mkdir(parents=True) db_path = data_dir / 'data.db' # 连接到数据库 conn = sqlite3.connect(db_path) cursor = conn.cursor() logger.info("数据库打开成功") # 创建表 cursor.execute(''' CREATE TABLE IF NOT EXISTS `robot_config` ( `id` INTEGER PRIMARY KEY AUTOINCREMENT, `key` VARCHAR(255) NOT NULL UNIQUE, `value` TEXT NOT NULL ); ''') logger.info("表创建成功") conn.commit() return conn except Exception as e: logger.error(f"初始化数据库失败: {e}") return None conn = __init_db() """ 全局变量,用于持有唯一的数据库连接实例 """ ``` -------------------------------- ### Python 插件日志记录 Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/05-debug 使用 `globals().get('logger')` 获取日志对象,并使用 `logger.info()` 打印日志信息。此方法适用于简单服务,日志将在插件管理界面中显示。 ```python logger = globals().get('logger') logger.info("这是一条日志") ``` -------------------------------- ### Enable Shortcut Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/02-web-runtime-package Enables physical shortcut keys on industrial touchscreens that might otherwise be disabled when a Web extension's page is open. ```APIDOC ## Enable Shortcut ### Description Enables physical shortcut keys on industrial touchscreens that might otherwise be disabled when a Web extension's page is open. **Warning**: If this method is not called, the screen may not be able to wake up via physical buttons after locking, requiring a forced shutdown. ### Method `enableShortcut` ### Endpoint N/A (This is a client-side library function) ### Parameters None ### Request Example ```typescript import { enableShortcut } from '@agilebot/extension-runtime'; enableShortcut(); ``` ### Response None ### Error Handling This function does not return a value but performs an action. Potential issues are related to the environment it's called in. ``` -------------------------------- ### Vue App 主文件导入加法组件 Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/01-complex-page 在 Vue 应用的入口文件 `src/App.vue` 中导入并渲染 `Math` 组件,以在主页面显示加法计算器。 ```vue ``` -------------------------------- ### Data Persistence Guidelines Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/04-data-persistence Guidelines and best practices for persisting data within the Agilebot extension. ```APIDOC ## Data Persistence Guidelines ### Description Data for backend plugins should be stored in the `data` directory within the plugin's directory. This directory is automatically mounted as writable when the plugin starts. Storing data here ensures it is not lost after plugin restarts. **Warning**: File cache data may be lost if the robot loses power. It is recommended to call the `sync` command after writing data files to ensure data is flushed to disk. ### Best Practices for Data Operations 1. **Local File Storage**: For small amounts of data, consider using file storage solutions like JSON or SQLite. 2. **Database Storage**: For more complex data requirements, opt for database storage. ``` -------------------------------- ### 创建 Python 简单服务插件 (MathServiceComplex.py) Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/03-complex-backend 此 Python 脚本定义了一个简单的加法服务,该服务能够接收两个整数作为输入,计算它们的和,并将结果写入名为 'math_result' 的寄存器。它还包含了连接到 Agilebot ARM 设备、错误日志记录以及本地调试支持。 ```python from Agilebot.IR.A.arm import Arm from Agilebot.IR.A.status_code import StatusCodeEnum from Agilebot.IR.A.sdk_classes import Register # 获取全局logger实例,只能在简单服务中使用 logger = globals().get('logger') if logger is None: # 本地调试时,使用自带日志库 import logging logger = logging.getLogger(__name__) arm = Arm() ret = arm.connect("10.27.1.254") if ret != StatusCodeEnum.OK: logger.error("连接失败") def add(a: int, b: int) -> int: """ 执行两个整数的加法运算,并写入寄存器 参数: - a (int): 第一个加数 - b (int): 第二个加数 返回: - int: 返回加法结果 """ try: result = a + b # 将结果写入寄存器 register = Register() register.id = 1 register.name = "math_result" register.comment = "加法服务的结果" register.value = result ret = arm.register.write(1, register) if ret != StatusCodeEnum.OK: logger.error("更新R失败") return result except Exception as ex: logger.error(ex) return 0 ``` -------------------------------- ### 通用服务插件的config.json配置文件 Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/02-quick-start/03-general-service 定义了一个名为WeatherService的通用服务插件的配置文件。它指定了插件的名称、类型、脚本语言、描述、版本和入口文件。 ```json { "name": "WeatherService", "type": "generalService", "scriptLang": "python", "description": "天气服务", "version": "0.1", "entry": "app.py" } ``` -------------------------------- ### 同步文件到磁盘 - Python Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/04-data-persistence 在写入数据文件后调用 `sync` 命令,以确保数据立即刷新到磁盘,防止因机器人断电导致缓存数据丢失。此操作在 Linux/macOS 系统下生效。 ```python import os os.system("sync") ``` -------------------------------- ### 在 Web 小程序中调用简单服务 Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/02-quick-start/02-easy-service 这段 TypeScript 代码演示了如何在 Web 小程序中使用 `callEasyService` 函数来调用名为 'MathService' 的简单服务插件的 'add' 接口。它接收一个 Promise 并处理加法计算的结果。该代码片段是 TypeScript 语言。 ```typescript import { callEasyService } from '@agilebot/extension-runtime'; callEasyService ('MathService', 'add', { a : 1, b : 2 }). then ( result => { // 输出:加法计算结果为 3 console . log (`加法计算结果为${ result }`); }); ``` -------------------------------- ### 获取插件状态 (TypeScript) Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/02-web-runtime-package 展示了如何使用 @agilebot/extension-runtime 库中的 getExtensionState 函数来获取指定插件的启用状态和端口号。 ```ts import { getExtensionState } from '@agilebot/extension-runtime'; const extension = await getExtensionState('myService'); console.log( `插件是否已经启用: ${extension.enabled}, 端口号:${extension.port}` ); ``` -------------------------------- ### 判断是否处于插件环境 (TypeScript) Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/02-web-runtime-package 演示了如何使用 @agilebot/extension-runtime 库中的 isInExtension 函数来判断当前 Web 页面是在插件环境中运行还是在本地调试。 ```ts import { isInExtension } from '@agilebot/extension-runtime'; console.log(`当前是否处于插件环境:${isInExtension()}`); ``` -------------------------------- ### Vite 配置修改 - base 选项 Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/01-complex-page 修改 `vite.config.ts` 文件中的 `base` 选项为 './',这是 VITEPress 插件开发中需要注意的配置项,以确保正确加载静态资源。 ```typescript import { fileURLToPath, URL } from 'node:url' import { defineConfig } from 'vite' import vue from '@vitejs/plugin-vue' import vueDevTools from 'vite-plugin-vue-devtools' // https://vite.dev/config/ export default defineConfig({ base: './', plugins: [ vue(), vueDevTools(), ], resolve: { alias: { '@': fileURLToPath(new URL('./src', import.meta.url)) }, }, }) ``` -------------------------------- ### Parameter Mapping Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/02-quick-start/02-easy-service Describes the mapping of URL query parameters to the function parameters of the simple service. ```APIDOC ## Parameter Mapping ### Description This section describes the mapping between HTTP query parameters and function parameters within your simple service. ### Method N/A ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters | Function Parameter Type | Example Parameter | Actual URI | Parameter Mapping Explanation | |---|---|---|---| | `int` | `a=1` | `?param1=1¶m2=2` | `param1` is mapped to the function's `int` type parameter, with a value of `1`. | | `str` | `name=John` | `?name=John` | `name` is mapped to the function's `str` type parameter, with a value of `"John"`. | | `bool` | `isActive=true` | `?isActive=true` | `isActive` is mapped to the function's `bool` type parameter, with a value of `true`. | | `List[dict]` | `items=[{"id":1,"name":"item1"}]` | `?items[0][id]=1&items[0][name]=item1` | `items` is mapped to the function's `List[dict]` type parameter, with a value of a list of dictionaries. | ``` -------------------------------- ### 启用快捷按键 (TypeScript) Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/02-web-runtime-package 展示了如何调用 @agilebot/extension-runtime 库中的 enableShortcut 函数来在插件 Web 页面中重新启用被禁用的快捷按键。 ```ts import { enableShortcut } from '@agilebot/extension-runtime'; enableShortcut(); ``` -------------------------------- ### 在浏览器中引用 AgileBot Extension Runtime Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/02-web-runtime-package 展示了如何在 HTML 中通过 ``` -------------------------------- ### 安装 AgileBot Extension Runtime Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/02-web-runtime-package 展示了使用 npm, yarn, 和 pnpm 安装 @agilebot/extension-runtime 包的命令。 ```sh npm install @agilebot/extension-runtime ``` ```sh yarn add @agilebot/extension-runtime ``` ```sh pnpm add @agilebot/extension-runtime ``` -------------------------------- ### 简单服务插件配置 - JSON Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/04-data-persistence 这是一个 `config.json` 文件示例,用于定义一个名为 `DataService` 的简单服务类型插件。文件中指定了插件的名称、类型、脚本语言、描述和版本信息,是插件系统识别和加载插件的依据。 ```json { "name": "DataService", "type": "easyService", "scriptLang": "python", "description": "数据服务", "version": "0.1" } ``` -------------------------------- ### 显示通知和弹框 (TypeScript) Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/03-advanced/02-web-runtime-package 演示了如何使用 @agilebot/extension-runtime 库中的 rtmNotification 和 rtmMessageBox 对象来显示信息、错误、成功、警告通知以及确认对话框。 ```ts import { rtmNotification, rtmMessageBox } from '@agilebot/extension-runtime'; // 显示信息通知 rtmNotification.info('这是一个信息消息'); // 显示错误通知 rtmNotification.error('这是一个错误消息'); // 显示成功通知 rtmNotification.success('操作成功'); // 显示警告通知 rtmNotification.warning('这是一个警告消息'); // 显示确认对话框 rtmMessageBox .confirm('您确定要删除吗?') .then(() => { console.log('用户确认了操作'); }) .catch(() => { console.log('用户取消了操作'); }); ``` -------------------------------- ### Python调用通用服务天气查询接口 Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/02-quick-start/03-general-service 使用Python的requests库调用已部署的通用服务插件提供的天气查询接口。此代码展示了如何发送GET请求并处理响应。需要安装requests库。 ```python import requests url = "http://10.27.1.254:6100/weather" try: response = requests.get(url) # 判断请求是否成功 if response.status_code == 200: result = response.json() print("天气信息:") print(result) else: print(f"请求失败,状态码: {response.status_code}") except requests.exceptions.RequestException as e: print("请求过程中出现错误:", e) ``` -------------------------------- ### 插件配置文件示例 Source: https://dev.sh-agilebot.com/docs/extension/zh/02-development/02-quick-start/01-web-mini-program 一个 JSON 格式的配置文件,用于定义 Web 小程序插件的基本信息。包括插件名称、类型、描述、版本和入口 URL。 ```json { "name": "HelloAgilebot", "type": "webMiniProgram", "description": "显示 Hello Agilebot!", "version": "0.1", "url": "index.html" } ``` -------------------------------- ### Python: IPC Manager for Robot Data Source: https://dev.sh-agilebot.com/docs/extension/zh/03-detailed-case/01-tcp-velocity Initializes an IPCManager to spawn a robot worker process for data collection. It handles incoming messages from the worker, broadcasts them via WebSocket, and updates the shared state with the latest TCP velocity. ```python ipc = IPCManager( spawn_proc=lambda q: start_robot_process(ROBOT_IP, q), handler=_ipc_handle, log=logger, watch_interval=2.0, ) async def _ipc_handle(item): await ws_server.broadcast(item) if isinstance(item, dict) and item.get("type") == MessageType.TCP_VELOCITY: SharedState.set("last_tcp_velocity", float(item.get("velocity") or 0.0)) ```