工具 API
概述
MatrixOS 的工具 API 提供了常用操作的实用函数,比如字符串哈希和其他辅助功能。工具 API 可通过 MatrixOS.Utils
访问,默认已导入。
Python 工具 API 实现在 Applications/Python/PikaPython/MatrixOS_Utils.py,类型提示在 Applications/Python/PikaPython/_MatrixOS_Utils.pyi。
StringHash
def StringHash(text: str) -> int
从文本字符串生成哈希值。这对于从字符串数据创建一致的数字标识符很有用,特别适用于 NVS 存储键或其他识别目的。
参数:
text
(str
):要哈希的输入字符串
返回值:
int
:输入字符串的哈希值
Example:
# Generate hash for NVS key
app_key = StringHash("MyApplication")
user_key = StringHash("UserSettings")
print(f"App key: {app_key}")
print(f"User key: {user_key}")
# Use with NVS storage
config_hash = StringHash("brightness_config")
MatrixOS.NVS.SetVariable(config_hash, b"128")
实际示例
NVS 键生成
def create_nv_storage_manager():
"""Create a storage manager using string-based keys"""
class StringKeyNVS:
def save(self, key_name: str, data: bytes) -> bool:
"""Save data using a string key name"""
hash_key = StringHash(key_name)
return MatrixOS.NVS.SetVariable(hash_key, data)
def load(self, key_name: str) -> bytes:
"""Load data using a string key name"""
hash_key = StringHash(key_name)
return MatrixOS.NVS.GetVariable(hash_key)
def delete(self, key_name: str) -> bool:
"""Delete data using a string key name"""
hash_key = StringHash(key_name)
return MatrixOS.NVS.DeleteVariable(hash_key)
def exists(self, key_name: str) -> bool:
"""Check if data exists using a string key name"""
hash_key = StringHash(key_name)
return MatrixOS.NVS.GetSize(hash_key) > 0
return StringKeyNVS()
# Usage example
storage = create_nv_storage_manager()
# Save settings with readable names
storage.save("user_brightness", b"200")
storage.save("last_used_app", b"Performance")
storage.save("device_name", b"MyMatrix")
# Load settings
brightness = storage.load("user_brightness")
last_app = storage.load("last_used_app")
print(f"Brightness: {brightness.decode()}")
print(f"Last app: {last_app.decode()}")
# Check existence
if storage.exists("device_name"):
name = storage.load("device_name")
print(f"Device name: {name.decode()}")