Files
CPY_HV_Scripts/webserver.py
T
2026-06-10 11:23:24 +08:00

217 lines
8.7 KiB
Python

import sys
import time
import _thread
import json
import gc
import machine
import os
import binascii
sys.path.append('/script/MicroWebSrv')
from microWebSrv import MicroWebSrv
# ----------------------------------------------------------------------------
# ========== 文件系统API ========== #
SCRIPT_ROOT = '/'
web_socket_list = []
wslock = None
def send_ws_list(topic, msg):
for ws in web_socket_list:
ws.SendText(json.dumps({'topic':topic, 'message':msg}))
def send_ws(webSocket,topic, msg):
webSocket.SendText(json.dumps({'topic':topic, 'message':msg}))
@MicroWebSrv.route('/api/script/list')
def api_script_list(httpClient, httpResponse):
params = httpClient.GetRequestQueryParams()
rel_path = params.get('id', '')
if rel_path.startswith('#'):
rel_path = rel_path[1:]
print("Listing scripts in path: ", rel_path)
abs_path = rel_path if rel_path else '/'
if abs_path == '#':
abs_path = '/'
if not abs_path.startswith('/'):
abs_path = '/' + abs_path
print("abs path: ", abs_path)
# 防止越权
if not abs_path.startswith(SCRIPT_ROOT):
httpResponse.WriteResponseJSONOk({"success": False, "message": "Invalid path"})
return
data = []
try:
for name in os.listdir(abs_path):
# item_path = os.path.join(abs_path, name)
if abs_path.endswith('/'):
item_path = abs_path + name
else:
item_path = abs_path + '/' + name
try:
is_dir = os.stat(item_path)[0] & 0x4000 == 0x4000
except:
is_dir = False
file_type = 'folder' if is_dir else 'file'
if not is_dir:
# ext = os.path.splitext(name)[1].lower()
dotidx = name.rfind('.')
ext = name[dotidx:].lower() if dotidx >= 0 else ''
if ext == '.py': file_type = 'python'
elif ext == '.json': file_type = 'json'
elif ext == '.sh': file_type = 'shell'
elif ext == '.js': file_type = 'js'
elif ext == '.css': file_type = 'css'
elif ext == '.html': file_type = 'html'
# id_path = os.path.join(rel_path, name).replace('\\', '/')
if rel_path.endswith('/') or rel_path == '':
id_path = rel_path + name
else:
id_path = rel_path + '/' + name
id_path = id_path.replace('\\', '/')
data.append({
"id": id_path,
"text": name,
"type": file_type,
"children": is_dir,
"state": {"opened": False, "disabled": False, "selected": False}
})
httpResponse.WriteResponseJSONOk({"success": True, "data": data})
except Exception as e:
httpResponse.WriteResponseJSONOk({"success": False, "message": str(e)})
@MicroWebSrv.route('/api/script/read')
def api_script_read(httpClient, httpResponse):
params = httpClient.GetRequestQueryParams()
rel_path = params.get('path', '')
# abs_path = os.path.abspath(os.path.join(SCRIPT_ROOT, rel_path.lstrip('/')))
abs_path = '/' + rel_path
if not abs_path.startswith(SCRIPT_ROOT):
httpResponse.WriteResponseJSONOk({"success": False, "message": "Invalid path"})
return
# 判断文件是否存在
try:
st = os.stat(abs_path)
is_file = not (st[0] & 0x4000 == 0x4000)
except:
is_file = False
if not is_file:
httpResponse.WriteResponseJSONOk({"success": False, "message": "File not found"})
return
try:
with open(abs_path, 'rb') as f:
content = f.read()
encoded = binascii.b2a_base64(content).decode('ascii').rstrip('\n')
httpResponse.WriteResponseJSONOk({"success": True, "data": encoded})
except Exception as e:
httpResponse.WriteResponseJSONOk({"success": False, "message": str(e)})
@MicroWebSrv.route('/api/script/write', 'POST')
def api_script_write(httpClient, httpResponse):
try:
data = httpClient.ReadRequestContentAsJSON()
rel_path = data.get('path', '')
content_b64 = data.get('content', '')
abs_path = '/' + rel_path
if not abs_path.startswith(SCRIPT_ROOT):
httpResponse.WriteResponseJSONOk({"success": False, "message": "Invalid path"})
return
# 确保目录存在
# dir_path = os.path.dirname(abs_path)
slash_idx = abs_path.rfind('/')
if slash_idx > 0:
dir_path = abs_path[:slash_idx]
try:
os.mkdir(dir_path)
except:
pass
# base64解码
content = binascii.a2b_base64(content_b64)
with open(abs_path, 'wb') as f:
f.write(content)
httpResponse.WriteResponseJSONOk({"success": True, "message": "File saved successfully"})
except Exception as e:
httpResponse.WriteResponseJSONOk({"success": False, "message": str(e)})
@MicroWebSrv.route('/api/script/delete', 'POST')
def api_script_delete(httpClient, httpResponse):
try:
data = httpClient.ReadRequestContentAsJSON()
rel_path = data.get('path', '')
abs_path = '/' + rel_path
if not abs_path.startswith(SCRIPT_ROOT):
httpResponse.WriteResponseJSONOk({"success": False, "message": "Invalid path"})
return
# 判断文件是否存在
try:
st = os.stat(abs_path)
is_file = not (st[0] & 0x4000 == 0x4000)
except:
is_file = False
if is_file:
os.remove(abs_path)
httpResponse.WriteResponseJSONOk({"success": True, "message": "File deleted successfully"})
else:
httpResponse.WriteResponseJSONOk({"success": False, "message": "File not found"})
except Exception as e:
httpResponse.WriteResponseJSONOk({"success": False, "message": str(e)})
@MicroWebSrv.route('/api/device/reboot', 'GET')
def api_device_reboot(httpClient, httpResponse):
try:
httpResponse.WriteResponseJSONOk({"success": True, "message": "device reboot now"})
machine.reset()
except Exception as e:
httpResponse.WriteResponseJSONOk({"success": False, "message": str(e)})
# ----------------------------------------------------------------------------
ws_cmd_handler = None
def _acceptWebSocketCallback(webSocket, httpClient) :
print("WS ACCEPT")
webSocket.RecvTextCallback = _recvTextCallback
webSocket.RecvBinaryCallback = _recvBinaryCallback
webSocket.ClosedCallback = _closedCallback
def _recvTextCallback(webSocket, msg) :
global web_socket_list
print("WS RECV TEXT : %s" % msg)
try:
obj = json.loads(msg)
if obj['action'] == 'subscribe':
if webSocket not in web_socket_list:
web_socket_list.append(webSocket)
else:
if ws_cmd_handler:
ws_cmd_handler(webSocket, msg)
except Exception as e:
sys.print_exception(e)
def _recvBinaryCallback(webSocket, data) :
print("WS RECV DATA : %s" % data)
def _closedCallback(webSocket):
print("WS CLOSED")
if webSocket in web_socket_list:
web_socket_list.remove(webSocket)
def py_server(cmd_handler):
global ws_cmd_handler
ws_cmd_handler = cmd_handler
print('py server start')
srv = MicroWebSrv(port=80,webPath='/web_root/py_admin/')
srv.MaxWebSocketRecvLen = 256
srv.WebSocketThreaded = True
srv.AcceptWebSocketCallback = _acceptWebSocketCallback
srv.Start()
def main():
py_server(())
if __name__ == '__main__':
main()