### 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!

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