### Example: Run Application Source: http://www.ascript.cn/docs/service/cloud/http Example of sending a command to start a specific application on devices. ```APIDOC ## Example: Run Application ### Description Example of sending a command to start a specific application on devices. ### Method POST ### Endpoint http://py.airscript.cn/api/v1/con/sendMsg ### Parameters #### Header Parameters - **token** (string) - Required - Authentication token obtained from the token acquisition endpoint. #### Request Body - **path** (string) - Required - Command identifier, set to `/device/start`. - **deviceIdList** (array of strings) - Required - A list of device IDs. An empty array targets all online devices. - **params** (object) - Required - Parameters for the command. - **scriptid** (string) - Required - The ID of the application to run, obtained from the developer backend. ### Request Example ```json { "path": "/device/start", "deviceIdList": [], "params": { "scriptid": "19" } } ``` ``` -------------------------------- ### Quick Start - Rel Mode (Default) Source: http://www.ascript.cn/docs/ios/esp32 A quick start guide for using the ESP32 in relative (rel) mouse mode, including initial setup and basic operations. ```APIDOC ## Rel Mode (Default) First time use: 1. **Enable AssistiveTouch** (Settings → Accessibility → Touch → AssistiveTouch) 2. **Set Tracking Sensitivity to maximum** (Settings → Accessibility → Touch → AssistiveTouch → Tracking Sensitivity) 3. **Set Tracking Speed to maximum** (Settings → General → Trackpad & Mouse → Tracking Speed) 4. **Calibrate once** (Tap the 'Calibrate' button on the iOS App home page and follow the default process) Subsequent use: ```python from ascript.ios.esp32hid import BleDevice device = BleDevice() # Automatically detects screen size device.connect() # Automatically scans, connects, and logs in device.click(642, 1389) # Click a specific screen coordinate (physical pixel) device.home() # Return to the home screen ``` ``` -------------------------------- ### Basic Operations Example Source: http://www.ascript.cn/docs/ios/esp32 A comprehensive example demonstrating basic setup and operations with the BleDevice. ```APIDOC ## Basic Operations Example A comprehensive example demonstrating basic setup and operations with the BleDevice. ### Code Example ```python from ascript.ios.esp32hid import BleDevice import time # Create and connect to the device device = BleDevice() device.connect() # Auto-scans, connects, and logs in print(f"Current mode: {device.get_mode()}") # Example: Perform a click device.click(500, 1000) # Example: Swipe device.swipe(100, 100, 100, 500, 500) # Example: Type text device.print_text("Hello from ESP32 HID!") # Example: Simulate key press device.key("E3", "04") # Cmd+A # Example: Check device state if device.state(): print("Device is connected and ready.") # Disconnect (optional, often handled automatically on script end) # device.disconnect() ``` ``` -------------------------------- ### Comprehensive FloatScriptWindow Example Source: http://www.ascript.cn/docs/windows/ui/flot_window This example demonstrates initializing FloatScriptWindow with auto_start and use_process enabled, defining start and stop event handlers, and showing the window. It includes simulated time-consuming operations and resource cleanup. ```python import multiprocessing import time import sys from ascript.windows.system import R # 程序上下文与资源路由 from ascript.windows.ui import LicenseWindow # 安全验证组件 from ascript.windows.ui import FloatScriptWindow # 脚本控制台组件 # 初始化控制台:支持自启动 (auto_start) 与 多进程隔离 (use_process) app = FloatScriptWindow(R.img("logo.ico"), title="我的程序", auto_start=True) @app.on('start') def task_start(): # --------------------------------------------------------- # 入口程序 (Entry Point) # --------------------------------------------------------- """ [业务逻辑入口] 当用户点击启动按钮或触发自启动时,此函数将在独立的子进程中运行。 """ print(">>> [系统] 业务进程已建立,开始执行自动化任务...") i= 0 # 模拟耗时逻辑操作 while True: print(i) time.sleep(0.5) i += 1 @app.on('stop') def task_stop(): """ [善后处理回调] 当用户手动停止或任务结束时触发。 注意:您有约 3 秒的时间进行资源释放(如关闭文件、数据库断开等)。 即使此处存在死循环,系统也会在超时后强制回收进程资源。 """ print(">>> [系统] 接收到停止信号,正在释放系统资源...") # 模拟保存数据逻辑 time.sleep(1) print(">>> [系统] 资源释放完毕,安全退出。") if __name__ == '__main__': # 解决打包后子进程重复启动问题 app.show() ``` -------------------------------- ### Start Application Source: http://www.ascript.cn/docs/ios/api/system Opens an installed application. Supports launching by name, Bundle ID, or URL Scheme. ```APIDOC ## Start Application ### Description Opens an installed application. Supports launching by name, Bundle ID, or URL Scheme. ### Method `system.app_start(bundle_id: str = None, scheme: str = None, name: str = None, arguments: typing.List[str] = [], environment: typing.Dict[str, str] = {}) ### Parameters - **bundle_id** (str) - Optional - Bundle ID, e.g., "com.tencent.xin" - **scheme** (str) - Optional - URL Scheme, e.g., "weixin://" - **name** (str) - Optional - App name, e.g., "微信" - **arguments** (List[str]) - Optional - Launch arguments - **environment** (Dict[str, str]) - Optional - Environment variables ### Examples ```python from ascript.ios import system # Launch by name (simplest) system.app_start("微信") # Launch by Bundle ID system.app_start(bundle_id="com.tencent.xin") # Launch by URL Scheme system.app_start(scheme="weixin://") ``` ``` -------------------------------- ### Start Application by Name, Bundle ID, or URL Scheme Source: http://www.ascript.cn/docs/ios/api/system Launches an installed application. Supports starting via app name, Bundle ID, or URL Scheme. The system intelligently determines the identifier type based on the input format. Pre-built mappings for over 400 common apps are available. ```python from ascript.ios import system system.app_start(bundle_id: str = None, scheme: str = None, name: str = None, arguments: typing.List[str] = [], environment: typing.Dict[str, str] = {}) ``` ```python from ascript.ios import system # 通过名称启动(最简单) system.app_start("微信") # 通过 Bundle ID 启动 system.app_start(bundle_id="com.tencent.xin") # 通过 URL Scheme 启动 system.app_start(scheme="weixin://") ``` -------------------------------- ### Example: Locate and Click Menu Item Source: http://www.ascript.cn/docs/windows/window/selector This example demonstrates how to find a Notepad window, locate a 'File' menu item by name and type, and then click it. ```python # 导入模块 from ascript.windows.window import Window from ascript.windows.ui import Selector # 1. 关联窗口 win = Window.find(process_name="notepad.exe") # 2. 链式定位并点击 Selector(win).name("文件").type("MenuItem").click() ``` -------------------------------- ### Example Demonstrations Source: http://www.ascript.cn/docs/windows/accs/mouse Illustrative examples of using the Mouse class for various automation tasks. ```APIDOC ## Example Demonstrations ```python from ascript.windows.hardware import Mouse # 1. Right-click double-click with random offset Mouse.click(x=200, y=200, clicks=2, interval=0.2, button="secondary", offset=10) # 2. Simulate chained operations: move -> wait -> click -> scroll Mouse.mouse_move(100, 100, move_duration=0.5) .wait(1) .click() .scroll(-500) ``` ``` -------------------------------- ### Comprehensive Usage Example Source: http://www.ascript.cn/docs/windows/ui/license_window An example demonstrating the typical usage of LicenseWindow at the script entry point. ```APIDOC ## Comprehensive Usage Example Typically, `LicenseWindow` is used at the script entry point, and its return value determines whether to continue executing business logic. ```python from ascript.windows.tools import LicenseWindow def main(): # 1. Create an authorization window, passing your AppID auth_win = LicenseWindow(app_id="your_app_id_123") # 2. Display the window (this operation blocks until start_app is called or the window is closed) # Internally loads the built-in license_window.html interface auth_win.show(title="Software License Activation", width=400, height=500) # 3. Validate the final result # Only if the user clicks "Start" in the interface and passes the start_app logic validation, _return_value will be True if auth_win._return_value: print("Authorization passed, starting main program...") # Write your main business logic here else: print("Authorization failed or user cancelled the operation.") if __name__ == '__main__': main() ``` ``` -------------------------------- ### Quick Start - Abs Mode (iOS 18+ Recommended) Source: http://www.ascript.cn/docs/ios/esp32 A quick start guide for using the ESP32 in absolute (abs) mouse mode, recommended for iOS 18 and later. No calibration is needed after switching modes. ```APIDOC ## Abs Mode (iOS 18+ Recommended) After switching to abs mode, no calibration is required. Connect and use directly: ```python from ascript.ios.esp32hid import BleDevice device = BleDevice() device.connect() device.click(642, 1389) device.swipe(500, 1500, 500, 500, 400) # Swipe upwards, stable on iOS 18+ ``` `connect()` internally queries `getmode?` to automatically detect the current firmware mode (rel or abs). Your script uses unified interfaces like `device.click/swipe/...` without needing to know the underlying mode. ``` -------------------------------- ### Install AScript Tip Package with Pip Source: http://www.ascript.cn/docs/android/devtools/pycharm Use pip to install the ascript-tip package for code completion in PyCharm. Ensure Python is installed and configured. ```bash pip install ascript-tip ``` -------------------------------- ### Send Command to Start Application Source: http://www.ascript.cn/docs/service/cloud/http Instruct a device to start a specific application by providing the application's script ID. ```http http://py.airscript.cn/api/v1/con/sendMsg ``` ```json { "path": "/device/start", "deviceIdList": [], "params": { "scriptid": "19" } } ``` -------------------------------- ### Example: Navigate and Input Text Source: http://www.ascript.cn/docs/windows/window/selector This example shows how to find a 'Password' label, navigate to its parent, find the associated input field by type, and then input text into it. ```python # 3. 跨层级跳转输入 # 找到“密码”文字 -> 跳到父级 -> 找子级中的输入框 -> 输入 Selector(win).name("密码").parent().child().type("EditControl").input("secret123") ``` -------------------------------- ### Full Example: Canvas Drawing Operations Source: http://www.ascript.cn/docs/android/api/ui/canvas A comprehensive example demonstrating canvas initialization, drawing a region, and other potential operations. ```python from ascript.android.ui import Canvas import time canvas = Canvas() cans.show() # 标记搜索区域 canvas.draw_region(0, 200, 1080, 800, label="搜索区域", duration=5000) ``` -------------------------------- ### Synchronous Mode Examples Source: http://www.ascript.cn/docs/android/api/system/shell Examples demonstrating the synchronous usage of the system.shell function for various tasks. ```APIDOC ## Synchronous Mode Examples ### Get Current User ```python from ascript.android import system res = system.shell('whoami') print(res.res) # ['root'] print(res.code) # 0 ``` ### Read System File ```python res = system.shell('cat /system/build.prop | head -5') print(res.res) # ['', '# begin build properties', '# autogenerated by buildinfo.sh', ...] ``` ### List Installed Packages ```python res = system.shell('pm list packages -3') for line in res.res: print(line) ``` ### Get Screen Resolution ```python res = system.shell('wm size') print(res.res) # ['Physical size: 1080x2400'] ``` ### Reset Screen Resolution ```python res = system.shell('wm size reset') print(res.code) # 0 ``` ### Simulate Key Press (Back Button) ```python system.shell('input keyevent 4') ``` ### Simulate Tap ```python system.shell('input tap 500 1000') ``` ### Simulate Swipe ```python system.shell('input swipe 500 1500 500 500 300') ``` ### Take Screenshot ```python system.shell('screencap -p /sdcard/screen.png') ``` ### Error Handling ```python res = system.shell('ls /not_exist') if res.code != 0: print('执行失败:', res.error) ``` ``` -------------------------------- ### Quick Start: Rel Mode (Default) Source: http://www.ascript.cn/docs/ios/esp32 Basic setup and usage for the relative mouse mode. Requires initial calibration via the iOS App. Ensure accessibility features are configured correctly. ```python from ascript.ios.esp32hid import BleDevice device = BleDevice() # Auto-detects screen size device.connect() # Auto-scans, connects, and logs in device.click(642, 1389) # Clicks a specific screen position (physical pixel coordinates) device.home() # Returns to the home screen ``` -------------------------------- ### Start Online App Source: http://www.ascript.cn/docs/android/api/cloud_control Starts an online mini-program on the device, optionally with parameters. ```APIDOC ## Start Online App ### Description Starts an online mini-program on the device. You can provide an ID for the mini-program and optional parameters or an activation code for paid mini-programs. ### Request Message ```json { "path": "app_run", "id": "14", "param": {"params1": "v"}, "card": "xxx" } ``` ### Parameters - **path** (string) - Required - The command path, should be "app_run". - **id** (string) - Required - The ID of the mini-program to start. - **param** (object) - Optional - Initialization parameters for the mini-program. - **card** (string) - Optional - Activation code, only applicable for paid mini-programs. ### Response Message (Success) ```json { "msg": "success", "path": "app_run", "code": 1, "device_id": "f6c95072-8446-47d2-af2e-b787a094b644" } ``` ``` -------------------------------- ### Comprehensive UIElement Usage Example Source: http://www.ascript.cn/docs/windows/window/uielement This example demonstrates finding UI elements using Selector, performing actions like clicking and inputting text, capturing screenshots, and retrieving element coordinates. ```python from ascript.windows.ui import Selector # 1. 找到一个按钮并点击 btn = Selector(title="我的应用").name("登录").find() if btn: # 优先尝试后台点击 btn.click() # 2. 找到输入框并读取/设置值 edit = Selector(title="我的应用").type("EditControl").find() if edit: print(f"当前输入框内容是: {edit.value}") edit.input("新内容") # 3. 截图并获取坐标 icon = Selector(title="我的应用").res_id("UserIcon").find() if icon: icon.capture("icon.png") cx, cy = icon.center print(f"图标中心坐标: {cx}, {cy}") ``` -------------------------------- ### Full-Screen Recognition Example Source: http://www.ascript.cn/docs/windows/screen/rapidocr This example shows how to capture the entire screen, recognize text, and then find and click on a text element using its absolute screen coordinates. ```APIDOC ## Full-Screen Recognition Example ### Description This example shows how to capture the entire screen, recognize text, and then find and click on a text element using its absolute screen coordinates. ### Method ```python from rapidocr import RapidOCR from ascript.windows.screen import Screen engine = RapidOCR() # Capture the full screen and recognize text result = engine(Screen.capture()) # Find and perform a full-screen click result.find("我的电脑").click() ``` ### Parameters #### Request Body None ``` -------------------------------- ### Window Recognition Example Source: http://www.ascript.cn/docs/windows/screen/rapidocr This example demonstrates how to find a specific window, capture its content, and then use chainable methods to locate and click on a text element within that window. ```APIDOC ## Window Recognition Example ### Description This example demonstrates how to find a specific window, capture its content, and then use chainable methods to locate and click on a text element within that window. ### Method ```python from rapidocr import RapidOCR from ascript.windows.window import Window # 1. Find the target window win = Window.find("微软电脑管家") engine = RapidOCR() # 2. Chainable call: capture -> recognize -> find text -> click engine(win.capture()).find("立即加速").click(win) ``` ### Parameters #### Request Body None ``` -------------------------------- ### Wait and Click Text Example Source: http://www.ascript.cn/docs/ios/api/screen/ocr-baidu Example demonstrating the wait_click method to wait for and click the '同意' button within a 5-second timeout. ```python from ascript.ios.screen import Ocr Ocr.wait_click("同意", timeout=5) ``` -------------------------------- ### Example Usage Source: http://www.ascript.cn/docs/windows/window/uielement Demonstrates common use cases for UIElement interactions. ```APIDOC ## Example Demonstration ```python from ascript.windows.ui import Selector # 1. Find a button and click it btn = Selector(title="My Application").name("Login").find() if btn: # Prefer background click btn.click() # 2. Find an input field, read/set its value edit = Selector(title="My Application").type("EditControl").find() if edit: print(f"Current input field content is: {edit.value}") edit.input("New Content") # 3. Capture screenshot and get coordinates icon = Selector(title="My Application").res_id("UserIcon").find() if icon: icon.capture("icon.png") cx, cy = icon.center print(f"Icon center coordinates: {cx}, {cy}") ``` ``` -------------------------------- ### Example: Stop Application Source: http://www.ascript.cn/docs/service/cloud/http Example of sending a command to stop a specific application on devices. ```APIDOC ## Example: Stop Application ### Description Example of sending a command to stop a specific application on devices. ### Method POST ### Endpoint http://py.airscript.cn/api/v1/con/sendMsg ### Parameters #### Header Parameters - **token** (string) - Required - Authentication token obtained from the token acquisition endpoint. #### Request Body - **path** (string) - Required - Command identifier, set to `/device/stop`. - **deviceIdList** (array of strings) - Required - A list of device IDs. An empty array targets all online devices. - **params** (object) - Required - Empty object as no specific parameters are needed to stop. ### Request Example ```json { "path": "/device/stop", "deviceIdList": [], "params": {} } ``` ``` -------------------------------- ### Start Application with Permission Check Source: http://www.ascript.cn/docs/windows/ui/license_window Use the start_app method as the final gatekeeper for application access. It verifies the authorization status, allowing free versions directly or checking for valid status '1' in authorized versions. Failures will block the application start. ```python # Start the application after permission check start_status = window.start_app() ``` -------------------------------- ### Click Text Example Source: http://www.ascript.cn/docs/ios/api/screen/ocr-baidu Example demonstrating the click method to find and click the '确定' button on the screen. ```python from ascript.ios.screen import Ocr Ocr.click("确定") ``` -------------------------------- ### Start Scheme Source: http://www.ascript.cn/docs/ios/api/system Opens a URL scheme. ```APIDOC ## Start Scheme ### Description Opens a URL scheme. If it fails, please contact support. ### Method `system.scheme_start(scheme: str) ### Parameters - **scheme** (str) - Required - The scheme to open, e.g., "ctrip://..." ### Example ```python from ascript.ios import system system.scheme_start("ctrip://......") ``` ``` -------------------------------- ### Switching OCR Engine Example Source: http://www.ascript.cn/docs/ios/api/screen/ocr-baidu Example showing how to switch the default OCR engine to Apple Vision using the set_engine method with the 'vision' string argument. ```python from ascript.ios.screen import Ocr Ocr.set_engine("vision") # 切换到 Apple Vision ``` -------------------------------- ### Find All Text Example Source: http://www.ascript.cn/docs/ios/api/screen/ocr-baidu Example demonstrating how to find all occurrences of digits within a specific screen area using find_all and printing each matched digit. ```python from ascript.ios.screen import Ocr results = Ocr.find_all("\\d+", rect=[0, 0, 500, 500]) for r in results: print(r['text']) ``` -------------------------------- ### 同时启动多个线程 Source: http://www.ascript.cn/docs/android/api/tunner/thread 可以创建多个 `threading.Thread` 对象并分别调用 `start()` 方法,实现多个线程的并发执行。 ```python import threading import time def task(name, count): for i in range(count): print(f"线程 {name}: {i+1}") time.sleep(0.5) # 创建多个线程 t1 = threading.Thread(target=task, args=("A", 3)) t2 = threading.Thread(target=task, args=("B", 5)) t1.start() t2.start() print("两个线程已同时启动") ``` -------------------------------- ### Get Installed Applications List Source: http://www.ascript.cn/docs/ios/api/system Retrieves a list of all installed applications on the device. ```APIDOC ## Get Installed Applications List ### Description Retrieves a list of all installed applications on the device. ### Method `system.app_list() ### Returns A list of installed application information. ### Example ```python from ascript.ios import system apps = system.app_list() for app in apps: print(app) ``` ``` -------------------------------- ### system.app_start() Usage Examples Source: http://www.ascript.cn/docs/ios/api/system/scheme-list Demonstrates how to use the system.app_start() function to launch applications using their name, Bundle ID, or URL Scheme. ```APIDOC ## system.app_start() ### Description Launches an application on the iOS device. ### Method `system.app_start(name=None, bundle_id=None, scheme=None)` ### Parameters - **name** (string) - Optional - The name of the application to launch. - **bundle_id** (string) - Optional - The Bundle ID of the application to launch. - **scheme** (string) - Optional - The URL Scheme of the application to launch. ### Usage Examples ```python from ascript.ios import system system.app_start("微信") # 通过名称 system.app_start(bundle_id="com.tencent.xin") # 通过 Bundle ID system.app_start(scheme="weixin://") # 通过 URL Scheme ``` ``` -------------------------------- ### Start Application Request Source: http://www.ascript.cn/docs/android/api/cloud_control Request message format to start an online application. Includes the application ID, optional parameters, and an activation code for paid applications. ```json { "path":"app_run", "id":"14", "param":{"params1":"v"}, "card":"xxx" } ``` -------------------------------- ### Find All Images Example (Template Matching) Source: http://www.ascript.cn/docs/ios/api/screen/findimages Example of finding all occurrences of an image using template matching. Iterates through the results and prints their coordinates. Requires importing R for image resources. ```python from ascript.ios.screen import FindImages from ascript.ios.system import R res = FindImages.find_all_template(R.img("1.png"), rect=[657, 761, 1117, 1248], confidence=0.95) for p in res: print(p.x, p.y) ``` -------------------------------- ### Run Mini Program Source: http://www.ascript.cn/docs/android/devtools/open Starts a local mini-program within the AS APP. ```APIDOC ## POST /api/model/run ### Description Starts a local mini-program. ### Method POST ### Endpoint host/api/model/run ### Parameters #### Request Body - **name** (string) - Required - The name of the local mini-program to run. ### Response #### Success Response (200) (No specific success response body detailed in source, typically indicates operation success.) ``` -------------------------------- ### Find Image Example (Template Matching) Source: http://www.ascript.cn/docs/ios/api/screen/findimages Example of finding a single image using template matching. Prints the result, which is either a Point object or None. Requires importing R for image resources. ```python from ascript.ios.screen import FindImages from ascript.ios.system import R res = FindImages.find_template(R.img("1.png"), rect=[657, 761, 1117, 1248], confidence=0.95) print(res) ``` -------------------------------- ### Displaying the WebWindow Source: http://www.ascript.cn/docs/windows/ui/web_window Configure window properties and start the rendering process with the `show()` method. ```APIDOC ## Displaying the Window (`show`) ### Description Configures window properties and initiates the rendering process. This method starts the UI event loop. ### Method ```python win.show(title="AScript Window", debug=False, **kwargs) ``` ### Parameters #### Parameters - **title** (str): Text for the window's title bar. - **debug** (bool): Enables developer tools. Press `F12` or right-click to inspect elements when enabled. - **width / height** (int): Initial window width and height. - **resizable** (bool): Allows the user to resize the window. - **kwargs**: Additional parameters supported by the system's native window. ``` -------------------------------- ### Get Installed Apps List Source: http://www.ascript.cn/docs/android/api/system/device Retrieves information about all installed applications on the device. ```APIDOC ## Get Installed Apps List ### Description Retrieves information about all installed applications on the device. ### Function ```python Device.apps() ``` ### Return Value A list of AppBean objects, each containing app details like `appName`, `appSize`, `isSd()`, `isSystem()`, `appPackageName`, `apkPath`, `version`, `versionName`. ### Example ```python # Get information of all installed apps from ascript.android.system import Device apps = Device.apps() print(len(apps)) # Number of installed apps for app in apps: print(app.appName) # App name print(app.appSize) # App size print(app.isSd()) # Is on SD card print(app.isSystem()) # Is a system app print(app.appPackageName) # App package name print(app.apkPath) # App installation path print(app.version) # App version number print(app.versionName) # App version name ``` ``` -------------------------------- ### Get List of Installed Applications Source: http://www.ascript.cn/docs/ios/api/system Retrieves a list of all installed applications on the device, including their information. ```python from ascript.ios import system apps = system.app_list() for app in apps: print(app) ``` -------------------------------- ### Demonstration of Device Class Usage Source: http://www.ascript.cn/docs/windows/system/device This example demonstrates checking administrator privileges, printing screen scaling and resolution, monitoring memory usage, and retrieving disk space. It requires the Device class to be imported. ```python from ascript.windows.system import Device # 1. 检查运行权限 if not Device.env.is_admin: print("⚠️ 警告:当前未以管理员权限运行,部分操作可能受限") # 2. 打印屏幕适配信息 print(f"系统缩放: {Device.screen.percent}") print(f"逻辑分辨率: {Device.screen.logical} (脚本以此为准)") # 3. 监控硬件健康 if Device.memory.percent > 90: print("🚨 内存告急:当前占用已超过 90%!") # 4. 获取 D 盘剩余空间 d_info = Device.disks.get_detail("D") print(f"D 盘剩余空间: {d_info['free']}") ``` -------------------------------- ### Get Grandparent Element Source: http://www.ascript.cn/docs/android/api/node/app/selector Specify an integer argument to `parent(n)` to retrieve the nth ancestor. For example, `parent(3)` gets the great-grandparent element. ```python from ascript.android.node import Selector nodes = Selector().id("com.aojoy.airscript:id/search_bar_text").parent(3).find_all(); if nodes: for node in nodes: print(node) else: print('没有找到任何控件') ``` -------------------------------- ### Get Installed Apps List Source: http://www.ascript.cn/docs/android/api/system/device Retrieve a list of all installed applications on the device, including details like app name, size, package name, and version. ```python Device.apps() ``` ```python #获取所有已安装APP的信息 from ascript.android.system import Device apps = Device.apps() print(len(apps)) #共安装了多个APP for app in apps: print(app.appName) # app名称 print(app.appSize) # app大小 print(app.isSd()) # 是否在sd卡 print(app.isSystem()) # 是否为系统应用 print(app.appPackageName) # app包名 print(app.apkPath) # app 安装地址 print(app.version) # app 版本号 print(app.versionName) # app 版本名称 ``` -------------------------------- ### Example Usage Source: http://www.ascript.cn/docs/windows/system/device Demonstrates how to use various properties of the Device class to check system status, screen information, hardware health, and disk space. ```APIDOC ## Example Demonstration ### Code Example ```python from ascript.windows.system import Device # 1. Check for administrative privileges if not Device.env.is_admin: print("⚠️ Warning: Not running with administrator privileges, some operations may be restricted") # 2. Print screen scaling information print(f"System Scaling: {Device.screen.percent}") print(f"Logical Resolution: {Device.screen.logical} (script uses this as reference)") # 3. Monitor hardware health if Device.memory.percent > 90: print("🚨 Memory Critical: Current usage exceeds 90%!") # 4. Get remaining space on drive D d_info = Device.disks.get_detail("D") print(f"D Drive Free Space: {d_info['free']}") ``` ``` -------------------------------- ### Cancel Vibration Source: http://www.ascript.cn/docs/android/api/media Immediately stops any ongoing device vibration. Example shows starting vibration then cancelling it. ```python from ascript.android import media # 开始震动5秒 media.vibrate(5000) import time time.sleep(1) # 1秒后立刻停止 media.cancel_vibrate() ``` -------------------------------- ### Initializing WebWindow Source: http://www.ascript.cn/docs/windows/ui/web_window Instantiate a WebWindow with the path to the UI layout file. ```APIDOC ## Initializing WebWindow (`__init__`) ### Description Creates a window instance by specifying the path to the UI layout file. ### Method ```python win = WebWindow(html_path, project_root=None) ``` ### Parameters #### Parameters - **html_path** (str): The local path to the HTML file (recommended to use `R.ui()` for path compatibility). - **project_root** (str | None): The project's root directory. Defaults to the current script's directory if not provided. ``` -------------------------------- ### Launch Apps by Name, Bundle ID, or URL Scheme Source: http://www.ascript.cn/docs/ios/api/system/scheme-list Demonstrates how to use system.app_start() to launch an application. You can use the app's name, its Bundle ID, or its URL Scheme for launching. ```python from ascript.ios import system system.app_start("微信") # 通过名称 system.app_start(bundle_id="com.tencent.xin") # 通过 Bundle ID system.app_start(scheme="weixin://") # 通过 URL Scheme ``` -------------------------------- ### Get SMS by Range Source: http://www.ascript.cn/docs/android/api/sms Retrieve a specific range of SMS messages, identified by their 1-based start and end positions. Can be filtered by type and address. ```python from ascript.android import sms range_sms = sms.get_range(10, 20) print(f"第 10-20 条短信: {range_sms}") ``` -------------------------------- ### DrawWindow Case Demonstration Source: http://www.ascript.cn/docs/windows/ui/draw_window This example demonstrates drawing a rectangle, text, and lines on the screen, holding the display for 5 seconds, and then clearing the canvas. It requires importing time and DrawWindow. ```python import time from ascript.windows.system import DrawWindow # 1. 在屏幕中央绘制一个红色方框(用于标识目标区域) DrawWindow.draw_rect(900, 500, 120, 120, color=0x0000FF, thickness=3) # 2. 在方框上方标注文字 DrawWindow.draw_text(900, 470, "目标锁定", color=0x00FFFF, font_size=24) # 3. 绘制一个蓝色的 X 标记 DrawWindow.draw_line(100, 100, 200, 200, color=0xFF0000, thickness=2) DrawWindow.draw_line(200, 100, 100, 200, color=0xFF0000, thickness=2) # 4. 保持显示 5 秒后清除 time.sleep(5) DrawWindow.clear() ``` -------------------------------- ### Find Node and Get All Children Count Source: http://www.ascript.cn/docs/android/api/node/app/view This example shows how to find a FrameLayout node and then retrieve all of its child elements to count them. It requires importing the Selector class. ```python from ascript.android.node import Selector node = Selector().id("com.aojoy.airscript:id/search_query_section").type("FrameLayout").find() if node: node_childs = node.child() if node_childs: print(len(node_childs)) ``` -------------------------------- ### Initialize WebWindow Source: http://www.ascript.cn/docs/windows/ui/web_window Create an instance of WebWindow by specifying the path to the HTML layout file. The project_root parameter can be used to set the project's root directory. ```python win = WebWindow(html_path, project_root=None) ``` -------------------------------- ### Basic ESP32 HID Device Operations Source: http://www.ascript.cn/docs/ios/esp32 A foundational example demonstrating how to create, connect to, and get the mode of an ESP32 HID device using the `BleDevice` class. Ensure necessary imports are included. ```python from ascript.ios.esp32hid import BleDevice import time # 创建设备并连接 device = BleDevice() device.connect() # 自动扫描、连接、登录 print(f"当前模式: {device.get_mode()}") ``` -------------------------------- ### Example Usage Source: http://www.ascript.cn/docs/windows/window/selector Demonstrates how to chain selector methods to locate and interact with UI elements. ```APIDOC # Import modules from ascript.windows.window import Window from ascript.windows.ui import Selector # Associate window win = Window.find(process_name="notepad.exe") # Chain locate and click Selector(win).name("File").type("MenuItem").click() # Cross-level jump input # Find "Password" text -> jump to parent -> find child input box -> input Selector(win).name("Password").parent().child().type("EditControl").input("secret123") ``` -------------------------------- ### Comprehensive LicenseWindow Usage Example Source: http://www.ascript.cn/docs/windows/ui/license_window Demonstrates the typical integration of LicenseWindow in a script's entry point. It shows creating the window, displaying it, and checking the return value to decide whether to proceed with the main application logic. Ensure network connectivity for initial calls. ```python from ascript.windows.tools import LicenseWindow def main(): # 1. Create the authorization window, passing your AppID auth_win = LicenseWindow(app_id="your_app_id_123") # 2. Display the window (this operation blocks until start_app is called or the window is closed) # Internally loads the built-in license_window.html interface auth_win.show(title="Software License Activation", width=400, height=500) # 3. Check the final result # _return_value will be True only if the user clicked 'Start' and passed the start_app logic validation if auth_win._return_value: print("Authorization passed, starting main program...") # Write your main business logic here else: print("Authorization failed or user cancelled the operation.") if __name__ == '__main__': main() ``` -------------------------------- ### Accessing private members using Reflect Source: http://www.ascript.cn/docs/android/api/plug/simple_load While injected classes can be imported directly for public members, private attributes and methods still require the `Reflect` API for access. This example shows how to get the value of a private field. ```python from ascript.android import plug from ascript.android.system import R from org.joor import Reflect from java import jint plug.inject(R.res("app-release.apk")) from com.aojoy.plug.testloader import Person person = Person("张三", jint(18)) # Access private attribute 'age' age = Reflect.on(person).field("age").get() print(age) # Output: 18 ``` -------------------------------- ### Open Application by Name or Package Source: http://www.ascript.cn/docs/android/api/system Use system.open() to launch an installed application. Opening by package name is faster than by application name. Ensure necessary system permissions are granted on some devices (e.g., Huawei). ```python from ascript.android import system # 根据应用名称启动. PS:启动略慢于包名启动 system.open("微信") ``` ```python from ascript.android import system # 根据包名启动,推荐使用 system.open("com.autonavi.minimap") ``` -------------------------------- ### Start Online App Source: http://www.ascript.cn/docs/service/cloud/ws Command to start an online application on the device. ```APIDOC ## Start Online App ### Request Message ```json { "path":"app_run", "id":"14", "param":{"params1":"v"}, "card":"xxx" } ``` ### Attributes | Parameter | Required | Description | |---|---|---| | `path` | Yes | "app_run" - command to start an application. | | `id` | Yes | The ID of the application to start. | | `param` | No | Optional parameters for initializing the application. | | `card` | No | Activation code, valid only for paid applications. | ### Response Message ```json {"msg":"success","path":"app_run","code":1,"device_id":"f6c95072-8446-47d2-af2e-b787a094b644"} ``` ``` -------------------------------- ### Verify Python Installation Source: http://www.ascript.cn/docs/ios/devtools/pycharm Check if Python is installed correctly by running the 'python' command in the command prompt. A successful installation will display the Python version and interactive mode prompt. ```bash python ``` -------------------------------- ### Show WebWindow Source: http://www.ascript.cn/docs/ios/api/ui/webwindow Display the created WebWindow. This should be called after instantiating the WebWindow. ```python # 显示一个webUI from ascript.ios.ui import WebWindow ui = WebWindow("http://www.ascript.cn") ui.show() ``` -------------------------------- ### Start Scheme Source: http://www.ascript.cn/docs/ios/api/system Opens a URL scheme. If it fails, contact the official support. ```python from ascript.ios import system system.scheme_start("ctrip://......") ``` -------------------------------- ### AScript Project Structure Example Source: http://www.ascript.cn/docs/android/devtools/vscode A newly created AScript project includes essential files like `build.as`, `main.py`, and a `res/` directory for resources. `build.as` indicates a mobile-targeted project. ```plaintext build.as main.py res/ ``` -------------------------------- ### Create WebWindow Instance Source: http://www.ascript.cn/docs/ios/api/ui/webwindow Instantiate a WebWindow object, providing the path to the HTML file or a URL. ```python ui = WebWindow("http://www.ascript.cn") ``` -------------------------------- ### Install libusb on macOS Source: http://www.ascript.cn/docs/android/api/mode Use Homebrew to install the libusb library on macOS for HID device management. ```bash brew install libusb ``` -------------------------------- ### TomatoOCR Initialization and Configuration Source: http://www.ascript.cn/docs/ios/api/screen/ocr-tomato This section covers the basic setup for TomatoOCR, including license key, model path, and constructor parameters for language, detection box type, expansion ratio, confidence threshold, return type, binarization, and run mode. ```APIDOC ## Basic Configuration ```python LICENSE = "YOUR_LICENSE_KEY" MODEL_PATH = R.res("model") # Model directory, must contain files like det.opt, cls.opt, rec.opt ``` ## Model Download Download model files from [here](link_to_download) and place them in the `res/model/` directory of your project. ## Constructor Parameters ```python ocr = TomatoOCR( rec_type="ch-3.0", # Recognition language: "ch"(Chinese 1.0), "ch-2.0", "ch-3.0"(recommended), "cht"(Traditional Chinese), "japan", "korean" box_type="rect", # Detection box type: "rect"(rectangle, recommended for mobile), "quad"(quadrilateral, for tilted text) ratio=1.9, # Detection expansion ratio: 1.6-2.5, larger value means larger detection box threshold=0.3, # Recognition confidence threshold: 0.1-0.9, results below this value will be filtered return_type="json", # Return type: "json"(complete information), "text"(plain text), "num"(plain numbers) binary=0, # Binarization threshold: 0-255, 0=disabled run_mode="fast", # Run mode: "slow"(high precision), "normal", "fast"(high speed) ) ocr.setModelPath(MODEL_PATH) occr.setLicense(LICENSE) ``` ### Parameters Table | Parameter | Type | Default | Description | |---------------|-------|-----------|-----------------------------------------------------------------------------| | rec_type | str | "ch-3.0"| Recognition language: ch / ch-2.0 / ch-3.0(recommended) / cht(Traditional Chinese) / japan / korean | | box_type | str | "rect" | Detection box: rect(rectangle) / quad(quadrilateral, for tilted text) | | ratio | float | 1.9 | Detection expansion ratio, 1.6-2.5 | | threshold | float | 0.3 | Confidence threshold, 0.1-0.9 | | return_type | str | "json" | Return type: json / text / num | | binary | int | 0 | Binarization threshold, 0=disabled, 0-255 | | scale_ratio | float | 1.0 | Detection scale ratio | | run_mode | str | "slow" | Run mode: slow(high precision) / normal / fast(high speed) | ``` -------------------------------- ### Create WebWindow with HTML Resource Source: http://www.ascript.cn/docs/android/api/ui/window Create a WebWindow instance by providing a path to an HTML resource. Use R.ui() to reference local UI files. ```python from ascript.android.ui import WebWindow from ascript.android.system import R w = WebWindow(R.ui(‘a.html’)) w.show() ``` -------------------------------- ### Get Filename and Extension Source: http://www.ascript.cn/docs/ios/api/file Use `os.path.basename()` to get the filename from a path and `os.path.splitext()` to separate the filename from its extension. ```python import os # 获取文件名 name = os.path.basename("D:/folder/a.txt") print(name) # a.txt # 分离文件名和扩展名 name, ext = os.path.splitext("a.txt") print(name) # a print(ext) # .txt ``` -------------------------------- ### Install WebSocket Dependency Source: http://www.ascript.cn/docs/android/api/cloud_control Install the 'ws' package, a WebSocket client and server implementation for Node.js, as a project dependency. ```bash npm install ws ``` -------------------------------- ### Start Application Acknowledgment Source: http://www.ascript.cn/docs/android/api/cloud_control Acknowledgment message received after attempting to start an application. Indicates success or failure of the operation. ```json {"msg":"success","path":"app_run","code":1,"device_id":"f6c95072-8446-47d2-af2e-b787a094b644"} ``` -------------------------------- ### Scan Result Example Source: http://www.ascript.cn/docs/ios/api/screen/coder_scanner Example of the dictionary array returned by the scan method, showing detected code information. ```python [ { 'result': (641.5, 1362.5), # 中心点坐标 'rect': (254.0, 975.0, 1029.0, 1750.0), 'center_x': 641.5, #中心点坐标x 'center_y': 1362.5, #中心点坐标y 'value': 'https://u.wechat.com/ENdK2gzTLSXi3HiCTsyK2Gw', #识别到的值 'type': 8, # 码类型 'format': 256 } ] ``` -------------------------------- ### Serve Production Build Locally Source: http://www.ascript.cn/docs/tutorial-basics/deploy-your-site Use this command to test your production build locally. The `build` folder will be served at http://localhost:3000/. ```bash npm run serve ``` -------------------------------- ### GET Request with Parameters Source: http://www.ascript.cn/docs/android/api/tunner/http Perform a GET request with parameters, either by appending them to the URL or using the 'params' argument. ```python import requests # 方式1: 参数拼在 URL 中 r = requests.get("https://httpbin.org/get?name=airscript&version=3.3") print(r.text) # 方式2: 通过 params 传参 (推荐) params = {"name": "airscript", "version": "3.3"} r = requests.get("https://httpbin.org/get", params=params) print(r.json()) ```