feat(lua): enhance runtime environment with resilient module loading

Introduce robust Lua module deployment strategy that ensures proper library
availability across different system configurations. The implementation now
prioritizes Home Assistant's configuration directory for persistent storage,
with automatic failover to temporary locations when permission restrictions
occur. Additionally, the runtime now validates module dependencies during
initialization and provides clear diagnostic warnings for any loading failures.
This commit is contained in:
happyhaha1
2025-10-31 10:44:42 +08:00
parent af6f2d1789
commit 05e30ab414
2 changed files with 59 additions and 13 deletions

View File

@@ -1,5 +1,5 @@
import traceback
import os
import lupa
import threading
import json
@@ -9,6 +9,23 @@ from .logger import MideaLogger
class LuaRuntime:
def __init__(self, file):
self._runtimes = lupa.lua51.LuaRuntime()
# 设置Lua路径包含cjson.lua和bit.lua的目录
lua_dir = os.path.dirname(os.path.abspath(file))
self._runtimes.execute(f'package.path = package.path .. ";{lua_dir}/?.lua"')
# 加载必需的Lua库
try:
self._runtimes.execute('require "cjson"')
except Exception as e:
MideaLogger.warning(f"Failed to load cjson: {e}")
try:
self._runtimes.execute('require "bit"')
except Exception as e:
MideaLogger.warning(f"Failed to load bit: {e}")
# 加载设备特定的Lua文件
string = f'dofile("{file}")'
self._runtimes.execute(string)
self._lock = threading.Lock()