### Example output for list_py_pkg Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/mini.pkg_tool.html The returned list of installed Python programs and their versions on the robot. ```text Package Version ———- ——- alphamini 0.1.0 ifaddr 0.1.7 pip 20.1.1 protobuf 3.12.2 setuptools 47.3.1 six 1.15.0 tts-demo 0.0.2 websockets 8.1 wheel 0.34.2 ``` -------------------------------- ### Install or update packaging tools Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Run this command on your PC to ensure the latest versions of setuptools, wheel, and twine are installed for project packaging. ```bash python -m pip install --user --upgrade setuptools wheel twine ``` -------------------------------- ### Build Install Package Message Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/pkg_tool.html Constructs a protobuf message for installing a wheel package. ```python def _build_install_py_pkg_msg(package_path: str, debug: bool) -> _Message: from mini.tool.pb2.PyPi_InstallWheel_pb2 import InstallWheelRequest request = InstallWheelRequest() # 获取文件路径中的文件名 request.wheelName = os.path.basename(package_path) # 把文件转成字节 request.serializePacket = _read_into_buffer(package_path) request.debug = debug cmd_id = _PCPyCmdId.PYPI_INSTALL_WHEEL_REQUEST.value # message message: _Message = msg_utils.build_request_msg(cmd_id, 0, request) return message ``` -------------------------------- ### Install or uninstall AlphaMini SDK via command line Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Uses the run_cmd tool to install or uninstall the alphamini library on the robot. ```bash run_cmd "pip install alphamini" "0090" --type "edu" run_cmd "pip uninstall -y alphamini" "0090" --type "edu" ``` -------------------------------- ### Install package via Python SDK Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Install a .whl file using the Python SDK. Ensure the robot type is set to EDU for overseas versions. ```python import mini.pkg_tool as Tool from mini import mini_sdk as MiniSdk # Set the robot type MiniSdk.set_robot_type(MiniSdk.RobotType.EDU) # Install the file simple_socket-0.0.2-py3-none-any.whl in the current directory. Tool.install_py_pkg(package_path="simple_socket-0.0.2-py3-none-any.whl", robot_id="robot_number") ``` -------------------------------- ### Install package via AlphaMini CLI Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Install a .whl file to a robot using the CLI. Overseas users must specify the --type "edu" flag. ```shell install_py_pkg "packaged .whl path" "robot serial number" --type "edu" ``` -------------------------------- ### Install or uninstall third-party programs via command line Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Uses the pkg command to install or uninstall third-party executable programs or libraries on the robot. ```bash run_cmd "pkg install -f xx" "0090" --type "edu" run_cmd "pkg uninstall -f xx" "0090" --type "edu" ``` -------------------------------- ### Configure setup.py for uninstall_py_pkg Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/mini.pkg_tool.html Example configuration for a setup.py file to determine the pkg_name used for uninstallation. ```python setuptools.setup( name=”tts_demo”, …#Omitted ), ``` -------------------------------- ### Configure setup.py for query_py_pkg Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/mini.pkg_tool.html Example setup.py configuration used to define package metadata for query_py_pkg. ```python setuptools.setup( name=”tts_demo”, version=”0.0.2”, author=’Gino Deng’, author_email=’jingjing.deng@ubtrobot.com’, description=”demo with mini_sdk”, long_description=’demo with mini_sdk,xxxxxxx’, long_description_content_type=”text/markdown”, license=”GPLv3”, packages=setuptools.find_packages(), classifiers=[ “Programming Language :: Python :: 3”, “Programming Language :: Python :: 3.6”, “Programming Language :: Python :: 3.7”, “Programming Language :: Python :: 3.8”, “License :: OSI Approved :: MIT License”, “Operating System :: OS Independent”, ], install_requires=[ ‘alphamini’, ], ), ``` -------------------------------- ### Configure entry_points in setup.py Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/mini.pkg_tool.html Example configuration for entry_points in setup.py to define the program entry name for run_py_pkg. ```python ‘console_scripts’: [ ‘XXX = Packages.Modules:XXX’ ], }, ``` -------------------------------- ### Verify Python and Pip Installation Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Use these commands to verify that Python and pip are correctly installed on your system. ```bash python –version & pip –version ``` -------------------------------- ### RobotAudioStartPlay.execute() Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/mini.apis.api_sound.html Controls the robot to start playing a recording. Inherits from ControlRobotAudioRecord. ```APIDOC ## RobotAudioStartPlay.execute() ### Description Controls the robot to start playing a recording. Inherits from ControlRobotAudioRecord. ### Method async execute() ### Parameters - **is_serial** (bool) - Optional - Whether to wait for a reply, default is True - **file_name** (str) - Optional - Recording file name, cannot be empty or None ### Returns ControlRobotRecordResponse ### Response Fields - **isSuccess** - Whether the operation was successful - **resultCode** - Return code - **id** - The name of the generated recording file ``` -------------------------------- ### Async main function for test_expression Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/test/test_expression.html Defines the async main function that gets a WiFiDevice by name, and if found, runs the test sequence: connect, start run program, play expression, set mouth lamp, control mouth lamp, control behavior, and shutdown. ```python async def main(): device: WiFiDevice = await test_get_device_by_name() if device: await test_connect(device) await test_start_run_program() await test_play_expression() await test_set_mouth_lamp() await test_control_mouth_lamp() await test_control_behavior() await shutdown() ``` -------------------------------- ### Install Python Package Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/pkg_tool.html Installs a Python package on a robot. It verifies the file exists and is a .whl file before initiating the installation. ```python def install_py_pkg(package_path: str, robot_id: str, debug: bool = False): """ Install a py program installation package on the robot with the specified serial number. Args: package_path: the absolute path of the installation package robot_id: robot serial number debug: Whether to print the log when pkg is uninstalled on the robot side Returns: None """ # 校验文件 if not os.path.isfile(package_path): print(f'file is not exist:{package_path}') return base_name = os.path.basename(package_path) if not base_name.endswith('.whl'): print(f'文件不是一个pypi安装包') return device: _WiFiDevice = _found_devices.get(robot_id) # 搜索设备 if device is None: device = asyncio.get_event_loop().run_until_complete(mini.get_device_by_name(robot_id, 10)) if device is None: print(f"不能找到机器人:{robot_id}") return else: _found_devices[robot_id] = device # 上传 asyncio.run(_send_msg0(_build_install_py_pkg_msg(package_path, debug), device)) ``` -------------------------------- ### mini.pkg_tool.install_py_pkg(package_path: str, robot_id: str, debug: bool = False) Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/mini.pkg_tool.html Installs a Python program installation package on the robot with the specified serial number. Optionally prints logs during uninstallation on the robot side. ```APIDOC ## mini.pkg_tool.install_py_pkg(package_path: str, robot_id: str, debug: bool = False) ### Description Install a py program installation package on the robot with the specified serial number. ### Method Function call ### Endpoint mini.pkg_tool.install_py_pkg ### Parameters #### Parameters - **package_path** (str) - Required - the absolute path of the installation package - **robot_id** (str) - Required - robot serial number - **debug** (bool) - Optional - Whether to print the log when pkg is uninstalled on the robot side ### Returns None ``` -------------------------------- ### install_py_pkg(package_path: str, robot_id: str, debug: bool = False) Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/pkg_tool.html Installs a Python installation package (.whl file) on the robot with the specified serial number. The package_path must be an absolute path to a .whl file. ```APIDOC ## install_py_pkg(package_path: str, robot_id: str, debug: bool = False) ### Description Installs a Python installation package (.whl file) on the robot with the specified serial number. The package_path must be an absolute path to a .whl file. ### Parameters - **package_path** (str) - Required - The absolute path of the installation package. - **robot_id** (str) - Required - The robot serial number. - **debug** (bool) - Optional - Whether to print the log when the package is uninstalled on the robot side. Default is False. ### Returns None ### Example ```python install_py_pkg('/path/to/package.whl', 'robot123') ``` ``` -------------------------------- ### Install or uninstall AlphaMini SDK via Python code Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Uses the mini.pkg_tool module to execute pip install or uninstall commands for the AlphaMini SDK. ```python import mini.pkg_tool as Tool from mini import mini_sdk as MiniSdk # Set the robot type MiniSdk.set_robot_type(MiniSdk.RobotType.EDU) # Execute a shell command Tool.run_py_pkg("pip install alphamini", robot_id="0090") Tool.run_py_pkg("pip uninstall -y alpahmini", robot_id="0090") ``` -------------------------------- ### Example output for query_py_pkg Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/mini.pkg_tool.html The returned information when querying a package named tts_demo. ```text Name: tts-demo Version: 0.0.2 Summary: demo with mini_sdk Home-page: UNKNOWN Author: Gino Deng Author-email: jingjing.deng@ubtrobot.com License: GPLv3 Location: /data/data/com.termux/files/usr/lib/python3.8/site-packages Requires: alphamini Required-by: ``` -------------------------------- ### Install and Uninstall AlphaMini SDK Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Commands to manage the AlphaMini SDK package using pip. ```bash pip install alphamini ``` ```bash pip uninstall alphamini ``` -------------------------------- ### Start the listener Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/apis/base_api.html Initiates the listener by sending the command and registering the message handler with the socket. ```python [docs] def start(self): """Start the listener """ # 发送消息 asyncio.create_task(self.send(cmd_id=self.__cmd_id, message=self.__request)) # 注册监听 socket.register_msg_handler(cmd=self.__cmd_id, handler=self) ``` -------------------------------- ### RobotAudioStartRecord.execute() Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/mini.apis.api_sound.html Controls the robot to start recording. Inherits from ControlRobotAudioRecord. ```APIDOC ## RobotAudioStartRecord.execute() ### Description Controls the robot to start recording. Inherits from ControlRobotAudioRecord. ### Method async execute() ### Parameters - **is_serial** (bool) - Optional - Whether to wait for a reply, default is True - **time_limit** (int) - Optional - Recording length in ms, default 60000 ### Returns ControlRobotRecordResponse ### Response Fields - **isSuccess** - Whether the operation was successful - **resultCode** - Return code - **id** - The name of the generated recording file ``` -------------------------------- ### StartBehavior Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/apis/api_behavior.html Controls the robot to start dancing. The constructor requires a name parameter and optionally an is_serial flag. The execute method sends the start dance command and returns a ControlBehaviorResponse. ```APIDOC ## StartBehavior ### Description Controls the robot to start dancing. The constructor requires a name parameter and optionally an is_serial flag. The execute method sends the start dance command and returns a ControlBehaviorResponse. ### Constructor - **is_serial** (bool) - Optional - Whether to wait for a reply, default is True. - **name** (str) - Required - Expressive name, cannot be empty or None. ### Method - **execute** (async) - Performs the start dance instruction. ### Returns - **ControlBehaviorResponse** - Contains isSuccess (bool) indicating success and resultCode (int) result code. ### Example ```python start_behavior = StartBehavior(name="dance") response = await start_behavior.execute() ``` ``` -------------------------------- ### RobotAudioStartPlay Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/apis/api_sound.html Controls the robot to start playing the recording. Requires a file name and optionally waits for a reply. ```APIDOC ## RobotAudioStartPlay ### Description Control the robot to start playing the recording. ### Constructor RobotAudioStartPlay(is_serial: bool = True, file_name: str = None) ### Parameters - **is_serial** (bool) - Optional - Whether to wait for a reply, the default is True. - **file_name** (str) - Required - Recording file name, cannot be empty or None. ### Response - **ControlRobotRecordResponse.isSuccess** (bool) - Is it successful. - **ControlRobotRecordResponse.resultCode** (int) - Return code. - **ControlRobotRecordResponse.id** (str) - The name of the generated recording file. ``` -------------------------------- ### RobotAudioStartPlay Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/apis/api_sound.html Controls the robot to start playing a recording. Inherits from ControlRobotAudioRecord and sets the control type to START_PLAY. ```APIDOC ## RobotAudioStartPlay ### Description Controls the robot to start playing a recording. Inherits from ControlRobotAudioRecord and sets the control type to START_PLAY. ### Constructor Parameters - is_serial (bool) - Whether to wait for a reply, default True. - file_name (str) - The name of the recording file to play. ### Returns ControlRobotRecordResponse - The response object containing the result of the start play operation. ### Response Fields - isSuccess (bool) - Whether the operation was successful. - resultCode (int) - The return code. - id (string) - The name of the generated recording file. ``` -------------------------------- ### Demo setup.py for tts_demo project Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Example setup.py using setuptools.setup() with package metadata, classifiers, install_requires for alphamini, and a console_scripts entry point. Note that find_packages() includes all subdirectories containing __init__.py. ```python import setuptools setuptools.setup( name="tts_demo", # Your library (program) name version="0.0.2", # version number author='Gino Deng', # developer name, author_email='jingjing.deng@ubtrobot.com', # Email, optional description="demo with mini_sdk", #short description long_description='demo with mini_sdk,xxxxxxx', #long description, optional long_description_content_type="text/markdown", #The format of the long description content, optional license="GPLv3", # copyright packages=setuptools.find_packages(), #*Note*: By default, all subdirectories containing __init__.py in the project directory are taken here classifiers=[ "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", ], install_requires=[ # Dependent module 'alphamini', ], entry_points={ 'console_scripts': [# Command line entry definition 'tts_demo = play_tts.test_playTTS:main' ], }, ) ``` -------------------------------- ### Touch Listening: ObserveHeadRacket with dance trigger and program entry Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html The example creates an ObserveHeadRacket listener, sets a handler that stops listening on an event and triggers a dance (ControlBehavior with name 'dance_0002'), then starts the listener. The program entry connects to the device, runs the listener, and keeps the event loop running forever, as required for event listeners. ```Python # Test, touch listen. async def test_ObserveHeadRacket(): # Create a listen observer: ObserveHeadRacket = ObserveHeadRacket() # Event processors # ObserveHeadRacketResponse.type: # @enum.unique # class HeadRacketType(enum.Enum): # SINGLE_CLICK = 1 # Click on the # LONG_PRESS = 2 # Press and hold... # DOUBLE_CLICK = 3 # DOUBLE_CLICK def handler(msg: ObserveHeadRacketResponse): # Stop listening when an event is monitored, observer.stop() print("{0}".format(str(msg.type))) # Execute a dance asyncio.create_task(__dance())) observer.set_handler(handler) #begin observer.start() await asyncio.sleep(0) async def __dance(): await ControlBehavior(name="dance_0002").execute() # end event_loop asyncio.get_running_loop().run_in_executor(None, asyncio.get_running_loop().stop) # Program entry if __name__ == '__main__': device: WiFiDevice = asyncio.get_event_loop().run_until_complete(test_get_device_by_name()) if device: asyncio.get_event_loop().run_until_complete(test_connect(device)) asyncio.get_event_loop().run_until_complete(test_start_run_program()) asyncio.get_event_loop().run_until_complete(test_ObserveHeadRacket()) asyncio.get_event_loop().run_forever() # If you define an event listener, you must make event_loop.run_forver. asyncio.get_event_loop().run_until_complete(shutdown()) ``` -------------------------------- ### setup.py parameters list Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html List of setuptools setup.py parameters with brief descriptions, including --name, --version, --author, --packages, --install_requires, and --entry_points. Note that --find_packages() searches for packages containing __init__.py in the same directory as setup.py by default. ```text --name Package name --version (-V) package version --author Author of the program --author_email The email address of the program's author. --maintainer maintainer --maintainer_email The email address of the maintainer. --url The program's official website address --Authorization information for the license program --description A brief description of the program. --long_description Detailed description of the program List of software platforms for the --platforms program --List of classifiers to which the program belongs. --keywords List of keywords for the program --packages Directory of packages to be processed (folder containing __init__.py) --py_modules List of python files to be packaged. --download_url The download address of the program. --cmdclass --data_files The data files to be packaged, such as images, configuration files, etc. --scripts List of footsteps to be performed during installation --package_dir tells setuptools which files in which directories are mapped to which source packages. An example: package_dir = {'': 'lib'}, indicating that the modules in the "root package" are in the lib directory. --define which modules are dependent --provides definitions for which modules can be provided with dependencies ---find_packages() It's easy to manually add packages to a simple project, but we just used this function to search for packages containing __init__.py in the same directory as setup.py by default. In fact, you can put the packages in a single src directory, and there may be aaa.txt files and data folders inside the package. In addition, you can exclude specific packages from the find_packages(exclude=["*.tests", "*.tests.*", "tests.*", "tests"]) --install_requires = ["requests"] Dependencies to install --entry_points Dynamic discovery of services and plugins, discussed in detail below ``` -------------------------------- ### Package project using python setup.py Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Use the standard Python setup command to create a distribution package in the project directory. ```shell python setup.py sdist bdist_wheel ``` -------------------------------- ### List installed modules via Python SDK Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html List modules installed on the robot using the Python SDK. ```python import mini.pkg_tool as Tool from mini import mini_sdk as MiniSdk # Set the robot type MiniSdk.set_robot_type(MiniSdk.RobotType.EDU) # List the py packages in the robot list_info = Tool.list_py_pkg(robot_id="0090") print(f'{list_info}') ``` -------------------------------- ### Tool.setup_py_pkg (Python) Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Packages a Python project directory into a wheel file using the mini.pkg_tool module. ```APIDOC ## [FUNCTION] Tool.setup_py_pkg ### Description Packages a Python project directory into a wheel file and returns the path to the generated .whl file. ### Method Python Function ### Function Signature Tool.setup_py_pkg(project_directory) ### Parameters - **project_directory** (string) - Required - The path to the Python project directory to package. ### Request Example ```python import mini.pkg_tool as Tool pkg_path = Tool.setup_py_pkg("tts_demo") print(f'{pkg_path}') ``` ### Response Returns the path to the generated .whl file. ``` -------------------------------- ### setup_py_pkg(project_dir: str) -> str Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/pkg_tool.html Packages a Python project into a .whl file. The project directory must contain a setup.py file. Returns the absolute path of the generated .whl file. ```APIDOC ## setup_py_pkg(project_dir: str) -> str ### Description Packages a Python project into a .whl file. The project directory must contain a setup.py file. Returns the absolute path of the generated .whl file. ### Parameters - **project_dir** (str) - Required - The project file root directory. ### Returns - **str** - The absolute path of the generated .whl file. Returns an empty string if the directory is invalid or setup.py is missing. ### Example ```python whl_path = setup_py_pkg('/path/to/project') ``` ``` -------------------------------- ### setup_py_pkg (command line) Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Packages a Python project directory using the AlphaMini command line tool. ```APIDOC ## [COMMAND] setup_py_pkg ### Description Packages a Python project directory into a wheel file using the AlphaMini command line tool. ### Method Command Line ### Command setup_py_pkg "your py project directory" ### Parameters - **project directory** (string) - Required - The path to the Python project directory to package. ### Request Example ``` setup_py_pkg "your py project directory" ``` ### Response Creates a dist directory with the .whl file. ``` -------------------------------- ### SDK Initialization and Logging Setup Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/mini_sdk.html Initializes the SDK logging and websocket client. The log level can be adjusted using set_log_level. ```python import asyncio import logging from asyncio.futures import Future import enum from google.protobuf import message as _message from typing import Any, Set, Optional from mini import MoveRobotDirection, MiniApiResultType, MouthLampMode, \ MouthLampColor, ServicePlatform, LanType from mini.pb2.codemao_faceanalyze_pb2 import FaceAnalyzeResponse from mini.pb2.codemao_facedetect_pb2 import FaceDetectResponse from mini.pb2.codemao_facerecognise_pb2 import FaceRecogniseResponse from mini.pb2.codemao_getaudiolist_pb2 import GetAudioListResponse from mini.pb2.codemao_getinfrareddistance_pb2 import GetInfraredDistanceResponse from mini.pb2.codemao_getregisterfaces_pb2 import GetRegisterFacesResponse from mini.pb2.codemao_recogniseobject_pb2 import RecogniseObjectResponse from mini.pb2.codemao_takepicture_pb2 import TakePictureResponse from .channels.websocket_client import AbstractMsgHandler as _AbstractMsgHandler from .channels.websocket_client import ubt_websocket as _websocket from .dns.dns_browser import WiFiDeviceListener, WiFiDevice from .dns.dns_browser import browser as _browser _log = logging.getLogger(__name__) _log.addHandler(logging.StreamHandler()) if _log.level == logging.NOTSET: _log.setLevel(logging.INFO) browser = _browser() websocket = _websocket() ``` -------------------------------- ### install_py_pkg (command line) Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Installs a packaged .whl file onto a robot using the AlphaMini command line tool. ```APIDOC ## [COMMAND] install_py_pkg ### Description Installs a packaged .whl file onto a robot. The robot type can be specified with --type. ### Method Command Line ### Command install_py_pkg "packaged .whl path" "robot serial number" --type "edu" ### Parameters - **packaged .whl path** (string) - Required - The path to the .whl file to install. - **robot serial number** (string) - Required - The last 4 digits of the robot serial number. - **--type** (string) - Optional - The robot type. Use "edu" for AlphaMini overseas education version. Default is china educational version. ### Request Example ``` install_py_pkg "packaged .whl path" "robot serial number" --type "edu" ``` ### Response Installs the package on the robot. ``` -------------------------------- ### List installed modules via AlphaMini CLI Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html List modules installed on the robot using the CLI. Specify --type "edu" for overseas robots. ```shell list_py_pkg "0090" --type "edu" ``` -------------------------------- ### python setup.py sdist bdist_wheel Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Packages a Python project into source distribution and wheel files using the setup.py script. ```APIDOC ## [COMMAND] python setup.py sdist bdist_wheel ### Description Packages the Python project in the current directory into a source distribution and a wheel file. ### Method Command Line ### Command python setup.py sdist bdist_wheel ### Parameters None ### Request Example ``` python setup.py sdist bdist_wheel ``` ### Response Creates a dist directory containing the .whl file and source archive. ``` -------------------------------- ### Main execution loop Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/test/test_sound.html The main entry point for running the sound and audio test suite. ```python async def main(): device: WiFiDevice = await test_get_device_by_name() if device: await test_connect(device) await test_start_run_program() await test_play_tts() await test_stop_play_tts() await test_get_audio_list() await test_play_local_audio() await test_play_online_audio() await test_stop_audio_tts() await test_change_robot_volume() await shutdown() if __name__ == '__main__': asyncio.run(main()) ``` -------------------------------- ### Get Egg Info Path Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/pkg_tool.html Retrieves the path for the egg-info directory. ```python def _get_eggInfo_path(): return _get_file('.', 'egg-info', True) ``` -------------------------------- ### Get Registered Faces Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Retrieve information about all faces currently registered in the robot. ```python # Test to get the number of faces currently registered in the bot async def test_get_register_faces(): """Test gets registered faces information Get all the faces registered in the bot and wait for the results. #GetRegisterFacesResponse.faceInfos : [FaceInfoResponse] face information array #FaceInfoResponse.id : face id #FaceInfoResponse.name : Name #FaceInfoResponse.gender : gender #FaceInfoResponse.age : age #GetRegisterFacesResponse.isSuccess : whether it succeeds or not #GetRegisterFacesResponse.resultCode : Return Code Returns: """ # reponse : GetRegisterFacesResponse (resultType, response) = await GetRegisterFaces().execute() print(f'test_get_register_faces result: {response}') ``` -------------------------------- ### Package project using Python SDK Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Use the mini.pkg_tool module to package a project directory into a wheel file. ```python import mini.pkg_tool as Tool # Package the tts_demo project in the current directory into a py wheel, the return value is the path of whl after packaging. pkg_path = Tool.setup_py_pkg("tts_demo") print(f'{pkg_path}') ``` -------------------------------- ### list_py_pkg(robot_id) Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/pkg_tool.html Lists all Python packages installed on the robot along with their version numbers. ```APIDOC ## list_py_pkg(robot_id) ### Description Lists all Python packages installed on the robot. ### Method Function call ### Parameters - **robot_id** (string) - Required - The serial number of the target robot. ### Returns - **str** - A list of all installed Python packages with their version numbers. ``` -------------------------------- ### entry_points console_scripts example Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Shows the entry_points dictionary with console_scripts defining a command-line tool. The part before the equals sign is the toolkit name, and after is the program entry address. ```python entry_points={ 'console_scripts': [ # Command-line entry definition 'tts_demo = play_tts.test_playTTS:main' ], } ``` -------------------------------- ### Play behavior using play_behavior() Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/mini_sdk.html Starts a dance behavior by name and waits for the result. ```python from mini.apis.api_behavior import StartBehavior block: StartBehavior = StartBehavior(True, behavior_name) (resultType, response) = await block.execute() _log.info(f'play behavior result:{response}') return resultType == MiniApiResultType.Success and response.isSuccess ``` -------------------------------- ### ServiceInfo.__init__ Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/dns/zeroconf.html Constructor for the ServiceInfo class. Initializes a service information object with type, name, port, properties, and other optional parameters. ```APIDOC ## ServiceInfo.__init__ ### Description Initializes a new ServiceInfo instance with the given service type, name, and optional parameters such as port, weight, priority, properties, server, TTLs, and addresses. ### Method Constructor ### Signature ServiceInfo(type_: str, name: str, address: Optional[Union[bytes, List[bytes]]] = None, port: Optional[int] = None, weight: int = 0, priority: int = 0, properties: Union[bytes, Dict] = b'', server: Optional[str] = None, host_ttl: int = _DNS_HOST_TTL, other_ttl: int = _DNS_OTHER_TTL, *, addresses: Optional[List[bytes]] = None) ### Parameters - **type_** (str) - Required - Fully qualified service type name. - **name** (str) - Required - Fully qualified service name. - **address** (Optional[Union[bytes, List[bytes]]]) - Optional - IP address as unsigned short, network byte order (deprecated, use addresses). - **port** (Optional[int]) - Optional - Port that the service runs on. - **weight** (int) - Optional - Weight of the service. Defaults to 0. - **priority** (int) - Optional - Priority of the service. Defaults to 0. - **properties** (Union[bytes, Dict]) - Optional - Dictionary of properties (or a bytes object holding the contents of the text field). Defaults to b''. - **server** (Optional[str]) - Optional - Fully qualified name for service host. Defaults to name. - **host_ttl** (int) - Optional - TTL used for A/SRV records. Defaults to _DNS_HOST_TTL. - **other_ttl** (int) - Optional - TTL used for PTR/TXT records. Defaults to _DNS_OTHER_TTL. - **addresses** (Optional[List[bytes]]) - Optional - List of IP addresses as unsigned short (IPv4) or unsigned 128 bit number (IPv6), network byte order. ### Exceptions - **TypeError** - Raised if both address and addresses are provided, or if any address is not bytes or has length not in (4, 16). - **BadTypeInNameException** - Raised if type_ does not end with the service type name derived from name. ### Notes - The address parameter is deprecated; use addresses instead. - Properties are converted to str and then encoded to bytes using UTF-8. Keys with None values are converted to value-less attributes. ``` -------------------------------- ### get_device_list(timeout: int) -> tuple Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/mini.mini_sdk.html Gets all robot device information in the current LAN. ```APIDOC ## get_device_list(timeout: int) -> tuple ### Description Get all the robot device information in the current LAN. ### Parameters - **timeout** (int) - Required - Timeout ### Returns Optional[WiFiDevice] ``` -------------------------------- ### StartRunProgram Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/apis/api_setup.html Enter programming mode api. Robot enters programming mode. The execute method sends a GetAppVersionRequest and returns a GetAppVersionResponse. ```APIDOC ## StartRunProgram ### Description Enter programming mode api. Robot enters programming mode. ### Constructor - **is_serial** (bool) - Optional - Whether to wait for a reply, the default is True. ### Method async execute() ### Returns - **GetAppVersionResponse** - Contains fields: isSuccess (bool) - Is it successful; resultCode (int) - Return code; version (string) - Version information. ### Usage Example ```python api = StartRunProgram(is_serial=True) response = await api.execute() ``` ``` -------------------------------- ### Get All IPv4 Addresses Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/dns/zeroconf.html Retrieves a list of all IPv4 addresses from local network adapters. ```python def get_all_addresses() -> List[str]: return list(set(addr.ip for iface in ifaddr.get_adapters() for addr in iface.ips if addr.is_IPv4)) ``` -------------------------------- ### Get current time in milliseconds Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/dns/zeroconf.html Returns the current system time in milliseconds as a float. ```python def current_time_millis() -> float: """Current system time in milliseconds""" return time.time() * 1000 ``` -------------------------------- ### Get Custom Audio List Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/mini_sdk.html Retrieves the list of sound effects from the /sdcard/customize/music/ directory. ```python from mini.apis.api_sound import FetchAudioList from mini import AudioSearchType block: FetchAudioList = FetchAudioList(True, search_type=AudioSearchType.CUSTOM) (resultType, response) = await block.execute() _log.info(f'stop audio result:{response}') return response ``` -------------------------------- ### Get System Audio List Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/mini_sdk.html Retrieves the list of sound effects built into the robot. ```python from mini.apis.api_sound import FetchAudioList from mini import AudioSearchType block: FetchAudioList = FetchAudioList(True, search_type=AudioSearchType.INNER) (resultType, response) = await block.execute() _log.info(f'stop audio result:{response}') return response ``` -------------------------------- ### ServiceInfo class constructor Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/dns/zeroconf.html Initializes service information with type, name, port, and network address details. Validates that address and addresses are not provided simultaneously and ensures address formats are correct. ```python def __init__( self, type_: str, name: str, address: Optional[Union[bytes, List[bytes]]] = None, port: Optional[int] = None, weight: int = 0, priority: int = 0, properties: Union[bytes, Dict] = b'', server: Optional[str] = None, host_ttl: int = _DNS_HOST_TTL, other_ttl: int = _DNS_OTHER_TTL, *, addresses: Optional[List[bytes]] = None ) -> None: # Accept both none, or one, but not both. if address is not None and addresses is not None: raise TypeError("address and addresses cannot be provided together") if not type_.endswith(service_type_name(name, allow_underscores=True)): raise BadTypeInNameException self.type = type_ self.name = name if addresses is not None: self._addresses = addresses elif address is not None: warnings.warn("address is deprecated, use addresses instead", DeprecationWarning) if isinstance(address, list): self._addresses = address else: self._addresses = [address] else: self._addresses = [] # This results in an ugly error when registering, better check now invalid = [a for a in self._addresses if not isinstance(a, bytes) or len(a) not in (4, 16)] if invalid: raise TypeError('Addresses must be bytes, got %s. Hint: convert string addresses ' 'with socket.inet_pton' % invalid) self.port = port self.weight = weight self.priority = priority if server: self.server = server else: self.server = name self._properties = {} # type: Dict self._set_properties(properties) self.host_ttl = host_ttl self.other_ttl = other_ttl ``` -------------------------------- ### Get Built-in Action List Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/mini_sdk.html Retrieves the list of actions built into the robot system. ```python from mini.apis.api_action import GetActionList from mini import RobotActionType block: GetActionList = GetActionList(True, RobotActionType.INNER) (resultType, response) = await block.execute() if resultType == MiniApiResultType.Success and response.isSuccess: return response.actionList else: return [] ``` -------------------------------- ### Clone the AlphaMini Demo Repository Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/guide.html Clone the demo project from GitHub to your local machine. ```bash git clone git@github.com:marklogg/mini_demo.git ``` -------------------------------- ### Public API: get_device_by_name Source: http://docs.ubtrobot.com/alphamini/python-sdk-en/_modules/mini/mini_sdk.html Public wrapper to get robot device information by name. ```python [docs]async def get_device_by_name(name: str, timeout: int) -> Optional[WiFiDevice]: """ Get the robot device information with the specified name in the current LAN Args: name: device serial number timeout: scan timeout Returns: Optional[WiFiDevice] """ return await _get_device_by_name(name, timeout) ```