可以接收远程图像,并进行操作且测试没有问题
This commit is contained in:
@@ -1,215 +1,341 @@
|
|||||||
#!/usr/bin/env python3
|
#!/usr/bin/env python3
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""
|
"""
|
||||||
远程显示 Web 服务 - Flask 实现
|
远程显示 Web 服务 - Flask + WebSocket 实现
|
||||||
|
|
||||||
|
通过 RemoDispBus 协议与 DTU 装置通信,将远程 LCD 画面以 Web 页面形式展示。
|
||||||
|
前端通过 WebSocket 连接,服务端主动推送屏幕数据,实现低延迟传输。
|
||||||
|
|
||||||
用法: python remo_disp_server.py [装置IP]
|
用法: python remo_disp_server.py [装置IP]
|
||||||
启动后访问 http://localhost:8181
|
启动后访问 http://localhost:8181
|
||||||
依赖: pip install flask
|
依赖: pip install flask flask-socketio pillow
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
# base64:将二进制 PNG 编码为字符串,便于通过 JSON/WebSocket 传输
|
||||||
|
import base64
|
||||||
|
# socket:与 DTU 装置的 TCP 通信
|
||||||
import socket
|
import socket
|
||||||
|
# struct:将整数打包为二进制(如起始地址 4 字节)
|
||||||
import struct
|
import struct
|
||||||
import time
|
# threading:后台线程持续拉取屏幕并推送
|
||||||
|
import threading
|
||||||
|
# sys:读取命令行参数(装置 IP)
|
||||||
import sys
|
import sys
|
||||||
|
# os:获取当前脚本目录,拼接 favicon 路径
|
||||||
import os
|
import os
|
||||||
|
# io:BytesIO 用于在内存中保存 PNG
|
||||||
import io
|
import io
|
||||||
from typing import Optional, Tuple
|
# typing:类型注解
|
||||||
|
from typing import Optional, Tuple, Set
|
||||||
|
|
||||||
from flask import Flask, request, jsonify, send_file, Response
|
# Flask:Web 框架,提供 HTTP 路由
|
||||||
|
from flask import Flask, request, send_file
|
||||||
|
# SocketIO:WebSocket 支持,实现实时双向通信
|
||||||
|
from flask_socketio import SocketIO, emit
|
||||||
|
|
||||||
# 协议常量
|
# =============================================================================
|
||||||
|
# 协议常量(RemoDispBus)
|
||||||
|
# =============================================================================
|
||||||
|
# TAG_CLIENT 0xAA:客户端发送帧的帧头标识
|
||||||
|
# TAG_DEVICE 0xBB:设备回复帧的帧头标识
|
||||||
TAG_CLIENT, TAG_DEVICE = 0xAA, 0xBB
|
TAG_CLIENT, TAG_DEVICE = 0xAA, 0xBB
|
||||||
|
# PORT 7003:RemoDispBus 协议默认端口
|
||||||
PORT = 7003
|
PORT = 7003
|
||||||
|
# CMD_KEEPLIVE 0:保活
|
||||||
|
# CMD_INIT 1:初始化,获取屏幕宽高、显存大小
|
||||||
|
# CMD_KEY 2:按键
|
||||||
|
# CMD_LCDMEM 3:读取显存(屏幕画面)
|
||||||
CMD_KEEPLIVE, CMD_INIT, CMD_KEY, CMD_LCDMEM = 0, 1, 2, 3
|
CMD_KEEPLIVE, CMD_INIT, CMD_KEY, CMD_LCDMEM = 0, 1, 2, 3
|
||||||
|
|
||||||
# 全局连接
|
# =============================================================================
|
||||||
|
# 全局状态
|
||||||
|
# =============================================================================
|
||||||
|
# _sock:与 DTU 装置的 TCP socket,None 表示未连接
|
||||||
_sock: Optional[socket.socket] = None
|
_sock: Optional[socket.socket] = None
|
||||||
|
# _init_info:初始化信息(width/height/mem_size),由 CMD_INIT 获取
|
||||||
_init_info: Optional[dict] = None
|
_init_info: Optional[dict] = None
|
||||||
|
# _screen_clients:当前需要接收屏幕推送的 WebSocket 客户端 sid 集合
|
||||||
|
_screen_clients: Set[str] = set()
|
||||||
|
# _refresh_thread:后台刷新线程,持续拉取屏幕并推送
|
||||||
|
_refresh_thread: Optional[threading.Thread] = None
|
||||||
|
# _refresh_stop:Event,set 时刷新线程退出
|
||||||
|
_refresh_stop = threading.Event()
|
||||||
|
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# 协议帧编解码
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
def calc_crc(data: bytes) -> int:
|
def calc_crc(data: bytes) -> int:
|
||||||
crc = 0
|
"""
|
||||||
|
对数据区逐字节异或,取低 8 位作为 CRC 校验码。
|
||||||
|
协议规定:CRC = data[0] ^ data[1] ^ ... ^ data[n-1],取低 8 位。
|
||||||
|
"""
|
||||||
|
crc = 0 # 初始值为 0
|
||||||
for b in data:
|
for b in data:
|
||||||
crc ^= b
|
crc ^= b # 逐字节异或
|
||||||
return crc & 0xFF
|
return crc & 0xFF # 取低 8 位作为最终 CRC
|
||||||
|
|
||||||
|
|
||||||
def build_frame(cmd: int, data: bytes) -> bytes:
|
def build_frame(cmd: int, data: bytes) -> bytes:
|
||||||
length = len(data)
|
"""
|
||||||
|
构造一帧发送数据,格式: [TAG(1)][cmd(1)][len_hi(1)][len_lo(1)][data][crc(1)]
|
||||||
|
length 大端 2 字节;crc 对 data 计算。
|
||||||
|
"""
|
||||||
|
length = len(data) # 数据区长度
|
||||||
|
# 构造帧头:TAG_CLIENT + cmd + 长度高字节 + 长度低字节(大端序)
|
||||||
header = bytes([TAG_CLIENT, cmd & 0xFF, (length >> 8) & 0xFF, length & 0xFF])
|
header = bytes([TAG_CLIENT, cmd & 0xFF, (length >> 8) & 0xFF, length & 0xFF])
|
||||||
return header + data + bytes([calc_crc(data)])
|
return header + data + bytes([calc_crc(data)]) # 帧头 + 数据 + CRC
|
||||||
|
|
||||||
|
|
||||||
def parse_frame(raw: bytes) -> Optional[Tuple[int, bytes]]:
|
def parse_frame(raw: bytes) -> Optional[Tuple[int, bytes]]:
|
||||||
if len(raw) < 6 or raw[0] != TAG_DEVICE:
|
"""
|
||||||
|
解析设备回复帧,返回 (cmd, data) 或 None。
|
||||||
|
帧格式: [TAG(1)][cmd(1)][len_hi(1)][len_lo(1)][data(length)][crc(1)]
|
||||||
|
"""
|
||||||
|
if len(raw) < 6 or raw[0] != TAG_DEVICE: # 至少 6 字节且帧头为 TAG_DEVICE
|
||||||
return None
|
return None
|
||||||
length = (raw[2] << 8) | raw[3]
|
length = (raw[2] << 8) | raw[3] # 大端序解析数据区长度
|
||||||
if len(raw) < 5 + length + 1:
|
if len(raw) < 4 + length + 1: # 检查是否收齐整帧(头4字节+数据+CRC1字节)
|
||||||
return None
|
return None
|
||||||
data = raw[4:4 + length]
|
data = raw[4:4 + length] # 提取数据区
|
||||||
if calc_crc(data) != raw[4 + length]:
|
if calc_crc(data) != raw[4 + length]: # CRC 校验失败
|
||||||
return None
|
return None
|
||||||
return (raw[1], data)
|
return (raw[1], data) # 返回 (命令码, 数据)
|
||||||
|
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# 连接与收发
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
def connect(host: str, port: int = PORT) -> bool:
|
def connect(host: str, port: int = PORT) -> bool:
|
||||||
|
"""
|
||||||
|
建立与 DTU 装置的 TCP 连接。
|
||||||
|
若有旧连接则先关闭;连接时超时 3 秒;连接成功后设为 2 秒。
|
||||||
|
"""
|
||||||
global _sock, _init_info
|
global _sock, _init_info
|
||||||
try:
|
try:
|
||||||
if _sock:
|
if _sock:
|
||||||
_sock.close()
|
_sock.close() # 关闭旧连接
|
||||||
_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建 TCP socket
|
||||||
_sock.settimeout(5.0)
|
_sock.settimeout(3.0) # 连接阶段超时 3 秒
|
||||||
_sock.connect((host, port))
|
_sock.connect((host, port)) # 连接目标主机和端口
|
||||||
_sock.settimeout(2.0)
|
_sock.settimeout(2.0) # 连接成功后收发超时 2 秒
|
||||||
_init_info = _request_init()
|
|
||||||
return True
|
return True
|
||||||
except Exception:
|
except Exception:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def _send(cmd: int, data: bytes = b"") -> bool:
|
def _send(cmd: int, data: bytes = b"") -> bool:
|
||||||
|
"""发送一帧到设备"""
|
||||||
if not _sock:
|
if not _sock:
|
||||||
return False
|
return False
|
||||||
try:
|
try:
|
||||||
_sock.sendall(build_frame(cmd, data))
|
_sock.sendall(build_frame(cmd, data)) # 构造帧并一次性发送
|
||||||
return True
|
return True
|
||||||
except Exception:
|
except Exception:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def _recv() -> Optional[Tuple[int, bytes]]:
|
def _recv() -> Optional[Tuple[int, bytes]]:
|
||||||
|
"""
|
||||||
|
从设备接收一帧,一次性 recv 最多 256KB。
|
||||||
|
至少需 5 字节(4 字节头+1 字节数据或 CRC);根据头中 length 检查是否收齐整帧。
|
||||||
|
"""
|
||||||
if not _sock:
|
if not _sock:
|
||||||
return None
|
return None
|
||||||
try:
|
try:
|
||||||
header = _sock.recv(5)
|
data = _sock.recv(256 * 1024) # 单次接收最多 256KB
|
||||||
if len(header) < 5:
|
if len(data) < 5: # 至少需要 5 字节(4 头 + 1 数据/CRC)
|
||||||
return None
|
return None
|
||||||
length = (header[2] << 8) | header[3]
|
length = (data[2] << 8) | data[3] # 解析数据区长度
|
||||||
rest = _sock.recv(length + 1)
|
if len(data) < 4 + length + 1: # 数据不完整
|
||||||
if len(rest) < length + 1:
|
|
||||||
return None
|
return None
|
||||||
return parse_frame(header + rest)
|
return parse_frame(data[:4 + length + 1]) # 解析并返回 (cmd, data)
|
||||||
except Exception:
|
except Exception:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _request_init() -> Optional[dict]:
|
|
||||||
if not _send(CMD_INIT):
|
|
||||||
return None
|
|
||||||
for _ in range(30):
|
|
||||||
result = _recv()
|
|
||||||
if result and result[0] == CMD_INIT:
|
|
||||||
data = result[1]
|
|
||||||
if len(data) >= 29:
|
|
||||||
return {
|
|
||||||
"width": (data[0] << 8) | data[1],
|
|
||||||
"height": (data[2] << 8) | data[3],
|
|
||||||
"mem_size": (data[5] << 24) | (data[6] << 16) | (data[7] << 8) | data[8],
|
|
||||||
}
|
|
||||||
time.sleep(0.05)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def send_key(code: int) -> bool:
|
def send_key(code: int) -> bool:
|
||||||
return _send(CMD_KEY, bytes([code & 0xFF]))
|
"""发送按键码到设备"""
|
||||||
|
return _send(CMD_KEY, bytes([code & 0xFF])) # 按键码单字节
|
||||||
|
|
||||||
|
|
||||||
def fetch_screen() -> Optional[bytes]:
|
def fetch_screen() -> Optional[bytes]:
|
||||||
global _init_info
|
"""
|
||||||
info = _init_info or _request_init()
|
向设备请求当前屏幕显存,返回 1bpp 位图数据。
|
||||||
if not info:
|
发送 CMD_LCDMEM + 起始地址 0;设备回复 payload 前 4 字节为地址,后续为位图,返回 payload[4:]。
|
||||||
|
"""
|
||||||
|
if not _sock:
|
||||||
return None
|
return None
|
||||||
mem_size = info["mem_size"]
|
if not _send(CMD_LCDMEM, struct.pack(">I", 0)): # 发送读取显存命令,起始地址 0(大端 4 字节)
|
||||||
buffer = bytearray(mem_size)
|
return None
|
||||||
pos = 0
|
result = _recv() # 接收设备回复
|
||||||
while pos < mem_size:
|
if result and result[0] == CMD_LCDMEM: # 确认为 LCDMEM 回复
|
||||||
if not _send(CMD_LCDMEM, struct.pack(">I", pos)):
|
payload = result[1] # 数据区
|
||||||
return None
|
if len(payload) >= 4: # 前 4 字节为地址,后面是位图
|
||||||
for _ in range(40):
|
return payload[4:]
|
||||||
result = _recv()
|
return payload or None
|
||||||
if result and result[0] == CMD_LCDMEM:
|
return None
|
||||||
payload = result[1]
|
|
||||||
if len(payload) >= 4:
|
|
||||||
start = struct.unpack(">I", payload[:4])[0]
|
|
||||||
chunk = payload[4:]
|
|
||||||
buffer[start : start + len(chunk)] = chunk
|
|
||||||
pos = start + len(chunk)
|
|
||||||
break
|
|
||||||
time.sleep(0.02)
|
|
||||||
else:
|
|
||||||
return None
|
|
||||||
return bytes(buffer)
|
|
||||||
|
|
||||||
|
|
||||||
def mono_to_png(data: bytes, width: int, height: int) -> Optional[bytes]:
|
def mono_to_png(data: bytes, width: int, height: int) -> Optional[bytes]:
|
||||||
|
"""
|
||||||
|
将 1bpp 位图转为 PNG 字节流。
|
||||||
|
每字节 8 像素,高位在前;bi=(y*w+x)//8 为字节索引,bit=7-(x%8) 为位索引;1 为白 255,0 为黑 0。
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
img = Image.new("1", (width, height))
|
img = Image.new("1", (width, height)) # 创建 1bpp 黑白图像
|
||||||
pix = img.load()
|
pix = img.load() # 获取像素访问对象
|
||||||
for y in range(height):
|
for y in range(height):
|
||||||
for x in range(width):
|
for x in range(width):
|
||||||
bi = (y * width + x) // 8
|
bi = (y * width + x) // 8 # 字节索引:每 8 像素一字节
|
||||||
bit = 7 - (x % 8)
|
bit = 7 - (x % 8) # 位索引:高位在前
|
||||||
pix[x, y] = 255 if (bi < len(data) and (data[bi] >> bit) & 1) else 0
|
pix[x, y] = 255 if (bi < len(data) and (data[bi] >> bit) & 1) else 0 # 1→白 0→黑
|
||||||
buf = io.BytesIO()
|
buf = io.BytesIO() # 内存缓冲区
|
||||||
img.save(buf, format="PNG")
|
img.save(buf, format="PNG") # 保存为 PNG 格式
|
||||||
return buf.getvalue()
|
return buf.getvalue() # 返回 PNG 字节流
|
||||||
except ImportError:
|
except ImportError:
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
app = Flask(__name__)
|
def disconnect_device():
|
||||||
|
"""关闭与设备的连接"""
|
||||||
|
global _sock, _init_info
|
||||||
|
try:
|
||||||
|
if _sock:
|
||||||
|
_sock.close() # 关闭 socket
|
||||||
|
_sock = None # 清空引用
|
||||||
|
_init_info = None # 清空初始化信息
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# 屏幕推送线程
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
def _screen_refresh_loop():
|
||||||
|
"""
|
||||||
|
后台线程:每约 100ms 拉取一帧屏幕,转 PNG 后 base64 推送给各 WebSocket 客户端。
|
||||||
|
_refresh_stop.wait(0.1) 既作间隔,也便于收到 set 时快速退出。
|
||||||
|
"""
|
||||||
|
global _screen_clients, _refresh_stop
|
||||||
|
while not _refresh_stop.is_set(): # 未被要求停止时持续循环
|
||||||
|
if _screen_clients and _sock: # 有客户端且已连接设备
|
||||||
|
data = fetch_screen() # 拉取屏幕位图
|
||||||
|
if data:
|
||||||
|
info = _init_info or {} # 获取宽高,缺省 160x160
|
||||||
|
w, h = info.get("width", 160), info.get("height", 160)
|
||||||
|
png = mono_to_png(data, w, h) # 转为 PNG
|
||||||
|
if png:
|
||||||
|
b64 = base64.b64encode(png).decode("ascii") # base64 编码便于 JSON 传输
|
||||||
|
for sid in list(_screen_clients): # 复制列表避免迭代时修改
|
||||||
|
try:
|
||||||
|
socketio.emit("screen", {"png": b64, "w": w, "h": h}, room=sid) # 推送给该客户端
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
_refresh_stop.wait(timeout=0.1) # 等待 100ms,若被 set 则立即返回
|
||||||
|
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# Flask + SocketIO
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
app = Flask(__name__) # 创建 Flask 应用
|
||||||
|
app.config["SECRET_KEY"] = "remo_disp" # 会话密钥
|
||||||
|
socketio = SocketIO(app, cors_allowed_origins="*") # 创建 SocketIO,允许跨域
|
||||||
|
|
||||||
|
FAVICON_PATH = os.path.join(os.path.dirname(__file__), "static", "favicon.ico") # favicon 文件路径
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/favicon.ico")
|
||||||
|
def favicon():
|
||||||
|
"""提供网站图标"""
|
||||||
|
if os.path.exists(FAVICON_PATH):
|
||||||
|
return send_file(FAVICON_PATH, mimetype="image/x-icon")
|
||||||
|
return "", 404 # 不存在则返回 404
|
||||||
|
|
||||||
|
|
||||||
@app.route("/")
|
@app.route("/")
|
||||||
@app.route("/index.html")
|
@app.route("/index.html")
|
||||||
def index():
|
def index():
|
||||||
|
"""主页,返回前端 HTML"""
|
||||||
return send_file(
|
return send_file(
|
||||||
os.path.join(os.path.dirname(__file__), "remo_disp_ui.html"),
|
os.path.join(os.path.dirname(__file__), "remo_disp_ui.html"),
|
||||||
mimetype="text/html; charset=utf-8",
|
mimetype="text/html; charset=utf-8",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.route("/connect")
|
@socketio.on("connect")
|
||||||
def api_connect():
|
def on_connect():
|
||||||
host = request.args.get("host", "").strip()
|
"""WebSocket 客户端连接时触发(可留空)"""
|
||||||
port = int(request.args.get("port", PORT))
|
pass
|
||||||
ok = connect(host, port)
|
|
||||||
return jsonify(success=ok, error=None if ok else "connect failed")
|
|
||||||
|
|
||||||
|
|
||||||
@app.route("/key")
|
@socketio.on("disconnect")
|
||||||
def api_key():
|
def on_disconnect():
|
||||||
code = int(request.args.get("code", 0))
|
"""WebSocket 客户端断开(关标签页等)时,从 _screen_clients 移除,若无客户端则断开设备"""
|
||||||
send_key(code)
|
global _screen_clients, _refresh_thread, _refresh_stop
|
||||||
return jsonify(ok=True)
|
sid = request.sid # 获取断开客户端的 session id
|
||||||
|
if sid in _screen_clients:
|
||||||
|
_screen_clients.discard(sid) # 从订阅列表移除
|
||||||
|
if not _screen_clients: # 若无其他客户端
|
||||||
|
_refresh_stop.set() # 通知刷新线程停止
|
||||||
|
disconnect_device() # 断开设备连接
|
||||||
|
|
||||||
|
|
||||||
@app.route("/screen")
|
@socketio.on("connect_device")
|
||||||
def api_screen():
|
def on_connect_device(data):
|
||||||
data = fetch_screen()
|
"""前端请求连接设备:连接成功后加入 _screen_clients,启动刷新线程,回复 connect_result"""
|
||||||
if not data:
|
global _screen_clients, _refresh_thread, _refresh_stop
|
||||||
return "", 500
|
host = (data.get("host") or "").strip() # 从 data 取 host,去空格
|
||||||
info = _init_info or {}
|
port = int(data.get("port") or PORT) # 从 data 取 port,缺省 7003
|
||||||
w, h = info.get("width", 160), info.get("height", 160)
|
ok = connect(host, port) # 建立 TCP 连接
|
||||||
png = mono_to_png(data, w, h)
|
if ok:
|
||||||
if png:
|
_screen_clients.add(request.sid) # 将当前客户端加入屏幕订阅
|
||||||
return Response(png, mimetype="image/png")
|
_refresh_stop.clear() # 清除停止标志,允许刷新线程运行
|
||||||
resp = Response(data, mimetype="application/octet-stream")
|
if _refresh_thread is None or not _refresh_thread.is_alive(): # 刷新线程未运行
|
||||||
resp.headers["X-Width"] = str(w)
|
_refresh_thread = threading.Thread(target=_screen_refresh_loop, daemon=True) # 创建后台线程
|
||||||
resp.headers["X-Height"] = str(h)
|
_refresh_thread.start() # 启动线程
|
||||||
return resp
|
emit("connect_result", {"success": True}) # 回复连接成功
|
||||||
|
else:
|
||||||
|
emit("connect_result", {"success": False, "error": "connect failed"}) # 回复连接失败
|
||||||
|
|
||||||
|
|
||||||
|
@socketio.on("disconnect_device")
|
||||||
|
def on_disconnect_device():
|
||||||
|
"""前端请求断开设备:从 _screen_clients 移除,若无客户端则断开设备,回复 disconnect_result"""
|
||||||
|
global _screen_clients, _refresh_stop
|
||||||
|
sid = request.sid
|
||||||
|
_screen_clients.discard(sid) # 从订阅列表移除
|
||||||
|
if not _screen_clients: # 若无其他客户端
|
||||||
|
_refresh_stop.set() # 通知刷新线程停止
|
||||||
|
disconnect_device() # 断开设备连接
|
||||||
|
emit("disconnect_result", {"ok": True}) # 回复断开成功
|
||||||
|
|
||||||
|
|
||||||
|
@socketio.on("key")
|
||||||
|
def on_key(data):
|
||||||
|
"""前端发送按键:从 data 取 code,转发给设备"""
|
||||||
|
code = int(data.get("code", 0)) # 按键码,缺省 0
|
||||||
|
send_key(code) # 发送给 DTU 设备
|
||||||
|
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# 启动
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
port = 8181
|
"""主入口:启动 Web 服务"""
|
||||||
|
port = 8181 # HTTP 服务端口
|
||||||
print(f"远程显示服务: http://localhost:{port}")
|
print(f"远程显示服务: http://localhost:{port}")
|
||||||
print("在浏览器中打开上述地址,点击「连接」输入装置 IP")
|
print("使用 WebSocket 传输,在浏览器中打开上述地址")
|
||||||
if len(sys.argv) >= 2:
|
if len(sys.argv) >= 2:
|
||||||
connect(sys.argv[1])
|
connect(sys.argv[1]) # 若命令行有 IP,预连接
|
||||||
print(f"已预连接: {sys.argv[1]}")
|
print(f"已预连接: {sys.argv[1]}")
|
||||||
app.run(host="0.0.0.0", port=port, debug=False, threaded=True)
|
socketio.run(app, host="0.0.0.0", port=port, debug=True, allow_unsafe_werkzeug=True) # 监听所有网卡
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -1,51 +1,83 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
|
<!-- 文档类型声明:HTML5 -->
|
||||||
<html lang="zh-CN">
|
<html lang="zh-CN">
|
||||||
|
<!-- 根元素,语言设为简体中文 -->
|
||||||
<head>
|
<head>
|
||||||
|
<!-- 头部:元数据与资源 -->
|
||||||
<meta charset="UTF-8">
|
<meta charset="UTF-8">
|
||||||
|
<!-- 字符编码:UTF-8 -->
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<!-- 视口:适配移动端,初始缩放 1 -->
|
||||||
<title>远程显示</title>
|
<title>远程显示</title>
|
||||||
|
<!-- 页面标题 -->
|
||||||
|
<link rel="icon" type="image/x-icon" href="/favicon.ico">
|
||||||
|
<!-- 网站图标 -->
|
||||||
|
<script src="https://cdn.socket.io/4.7.2/socket.io.min.js"></script>
|
||||||
|
<!-- Socket.IO 客户端库,用于 WebSocket 通信 -->
|
||||||
<style>
|
<style>
|
||||||
|
/* ========== 全局样式 ========== */
|
||||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
|
/* 通配符:盒模型为 border-box,去除默认边距 */
|
||||||
body {
|
body {
|
||||||
font-family: "Microsoft YaHei", "PingFang SC", sans-serif;
|
font-family: "Microsoft YaHei", "PingFang SC", sans-serif;
|
||||||
|
/* 字体:微软雅黑、苹方,无衬线回退 */
|
||||||
background: linear-gradient(135deg, #e8f4fc 0%, #f0f8ff 50%, #e6f2ff 100%);
|
background: linear-gradient(135deg, #e8f4fc 0%, #f0f8ff 50%, #e6f2ff 100%);
|
||||||
|
/* 背景:135 度渐变,浅蓝到淡蓝 */
|
||||||
min-height: 100vh;
|
min-height: 100vh;
|
||||||
|
/* 最小高度为视口高度 */
|
||||||
padding: 16px;
|
padding: 16px;
|
||||||
|
/* 内边距 */
|
||||||
}
|
}
|
||||||
|
/* ========== 主容器 ========== */
|
||||||
.app {
|
.app {
|
||||||
max-width: 900px;
|
max-width: 900px;
|
||||||
|
/* 最大宽度限制 */
|
||||||
margin: 0 auto;
|
margin: 0 auto;
|
||||||
|
/* 水平居中 */
|
||||||
background: #fff;
|
background: #fff;
|
||||||
|
/* 白色背景 */
|
||||||
border-radius: 12px;
|
border-radius: 12px;
|
||||||
|
/* 圆角 */
|
||||||
box-shadow: 0 4px 20px rgba(0,0,0,0.08);
|
box-shadow: 0 4px 20px rgba(0,0,0,0.08);
|
||||||
|
/* 阴影 */
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
|
/* 子元素超出则裁剪 */
|
||||||
}
|
}
|
||||||
/* 顶部菜单栏 */
|
/* ========== 顶部菜单栏 ========== */
|
||||||
.menu-bar {
|
.menu-bar {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
/* 弹性布局 */
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
/* 垂直居中 */
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
|
/* 水平居中 */
|
||||||
gap: 8px;
|
gap: 8px;
|
||||||
|
/* 子元素间距 */
|
||||||
padding: 12px 16px;
|
padding: 12px 16px;
|
||||||
background: #fff;
|
background: #fff;
|
||||||
border-bottom: 1px solid #e8e8e8;
|
border-bottom: 1px solid #e8e8e8;
|
||||||
|
/* 底部分割线 */
|
||||||
}
|
}
|
||||||
.menu-item {
|
.menu-item {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
|
/* 纵向排列图标和文字 */
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
padding: 8px 14px;
|
padding: 8px 14px;
|
||||||
border: none;
|
border: none;
|
||||||
background: transparent;
|
background: transparent;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
|
/* 鼠标指针为手型 */
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
transition: all 0.2s;
|
transition: all 0.2s;
|
||||||
|
/* 过渡动画 */
|
||||||
color: #333;
|
color: #333;
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
}
|
}
|
||||||
.menu-item:hover {
|
.menu-item:hover {
|
||||||
background: #f5f5f5;
|
background: #f5f5f5;
|
||||||
|
/* 悬停时浅灰背景 */
|
||||||
}
|
}
|
||||||
.menu-item .icon {
|
.menu-item .icon {
|
||||||
width: 28px;
|
width: 28px;
|
||||||
@@ -54,44 +86,59 @@
|
|||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
font-size: 18px;
|
font-size: 18px;
|
||||||
|
/* 图标区域 */
|
||||||
}
|
}
|
||||||
.menu-item.connect .icon { color: #22c55e; }
|
.menu-item.connect .icon { color: #22c55e; }
|
||||||
|
/* 连接按钮图标:绿色 */
|
||||||
.menu-item.settings .icon { color: #3b82f6; }
|
.menu-item.settings .icon { color: #3b82f6; }
|
||||||
|
/* 设置按钮图标:蓝色 */
|
||||||
.menu-item.exit .icon { color: #ef4444; }
|
.menu-item.exit .icon { color: #ef4444; }
|
||||||
|
/* 断开按钮图标:红色 */
|
||||||
.menu-item.about .icon { color: #64748b; }
|
.menu-item.about .icon { color: #64748b; }
|
||||||
|
/* 关于按钮图标:灰色 */
|
||||||
.menu-item.connected .icon { color: #22c55e; }
|
.menu-item.connected .icon { color: #22c55e; }
|
||||||
.menu-item.connected { color: #22c55e; }
|
.menu-item.connected { color: #22c55e; }
|
||||||
/* 主内容区 */
|
/* 已连接状态:绿色 */
|
||||||
|
/* ========== 主内容区 ========== */
|
||||||
.main {
|
.main {
|
||||||
display: flex;
|
display: flex;
|
||||||
padding: 16px;
|
padding: 16px;
|
||||||
gap: 20px;
|
gap: 20px;
|
||||||
|
/* 左右分栏间距 */
|
||||||
}
|
}
|
||||||
/* 显示区域 */
|
/* ========== 显示区域 ========== */
|
||||||
.display-area {
|
.display-area {
|
||||||
flex: 1;
|
flex: 1;
|
||||||
|
/* 占据剩余空间 */
|
||||||
min-width: 0;
|
min-width: 0;
|
||||||
|
/* 允许 flex 子项收缩 */
|
||||||
aspect-ratio: 1;
|
aspect-ratio: 1;
|
||||||
|
/* 宽高比 1:1 */
|
||||||
max-height: 420px;
|
max-height: 420px;
|
||||||
background: #1e3a5f;
|
background: #1e3a5f;
|
||||||
|
/* 深蓝背景,模拟 LCD 边框 */
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
overflow: hidden;
|
overflow: hidden;
|
||||||
box-shadow: inset 0 2px 8px rgba(0,0,0,0.2);
|
box-shadow: inset 0 2px 8px rgba(0,0,0,0.2);
|
||||||
|
/* 内阴影 */
|
||||||
}
|
}
|
||||||
.display-area canvas {
|
.display-area canvas {
|
||||||
max-width: 100%;
|
max-width: 100%;
|
||||||
max-height: 100%;
|
max-height: 100%;
|
||||||
|
/* canvas 自适应容器 */
|
||||||
image-rendering: pixelated;
|
image-rendering: pixelated;
|
||||||
image-rendering: crisp-edges;
|
image-rendering: crisp-edges;
|
||||||
|
/* 像素风格渲染,避免模糊 */
|
||||||
}
|
}
|
||||||
.display-placeholder {
|
.display-placeholder {
|
||||||
color: rgba(255,255,255,0.5);
|
color: rgba(255,255,255,0.5);
|
||||||
|
/* 半透明白色提示文字 */
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
}
|
}
|
||||||
/* 右侧控制面板 */
|
/* ========== 右侧控制面板 ========== */
|
||||||
.control-panel {
|
.control-panel {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
@@ -99,12 +146,13 @@
|
|||||||
gap: 16px;
|
gap: 16px;
|
||||||
padding: 8px;
|
padding: 8px;
|
||||||
}
|
}
|
||||||
/* D-pad */
|
/* ========== D-pad 方向键 ========== */
|
||||||
.dpad {
|
.dpad {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: 50px 50px 50px;
|
grid-template-columns: 50px 50px 50px;
|
||||||
grid-template-rows: 50px 50px 50px;
|
grid-template-rows: 50px 50px 50px;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
|
/* 3x3 网格布局 */
|
||||||
}
|
}
|
||||||
.dpad .btn {
|
.dpad .btn {
|
||||||
width: 50px;
|
width: 50px;
|
||||||
@@ -112,6 +160,7 @@
|
|||||||
border: none;
|
border: none;
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
background: linear-gradient(180deg, #f8f9fa 0%, #e9ecef 100%);
|
background: linear-gradient(180deg, #f8f9fa 0%, #e9ecef 100%);
|
||||||
|
/* 渐变背景 */
|
||||||
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -125,17 +174,24 @@
|
|||||||
background: linear-gradient(180deg, #fff 0%, #f1f3f5 100%);
|
background: linear-gradient(180deg, #fff 0%, #f1f3f5 100%);
|
||||||
box-shadow: 0 3px 6px rgba(0,0,0,0.15);
|
box-shadow: 0 3px 6px rgba(0,0,0,0.15);
|
||||||
transform: translateY(-1px);
|
transform: translateY(-1px);
|
||||||
|
/* 悬停上浮效果 */
|
||||||
}
|
}
|
||||||
.dpad .btn:active {
|
.dpad .btn:active {
|
||||||
transform: translateY(0);
|
transform: translateY(0);
|
||||||
box-shadow: 0 1px 2px rgba(0,0,0,0.1);
|
box-shadow: 0 1px 2px rgba(0,0,0,0.1);
|
||||||
|
/* 按下时恢复 */
|
||||||
}
|
}
|
||||||
.dpad .btn-up { grid-column: 2; grid-row: 1; }
|
.dpad .btn-up { grid-column: 2; grid-row: 1; }
|
||||||
|
/* 上键:中上 */
|
||||||
.dpad .btn-down { grid-column: 2; grid-row: 3; }
|
.dpad .btn-down { grid-column: 2; grid-row: 3; }
|
||||||
|
/* 下键:中下 */
|
||||||
.dpad .btn-left { grid-column: 1; grid-row: 2; }
|
.dpad .btn-left { grid-column: 1; grid-row: 2; }
|
||||||
|
/* 左键:左中 */
|
||||||
.dpad .btn-right { grid-column: 3; grid-row: 2; }
|
.dpad .btn-right { grid-column: 3; grid-row: 2; }
|
||||||
|
/* 右键:右中 */
|
||||||
.dpad .btn-ok { grid-column: 2; grid-row: 2; }
|
.dpad .btn-ok { grid-column: 2; grid-row: 2; }
|
||||||
/* 动作按钮 */
|
/* 确认键:正中 */
|
||||||
|
/* ========== 动作按钮 ========== */
|
||||||
.action-btns {
|
.action-btns {
|
||||||
display: flex;
|
display: flex;
|
||||||
gap: 12px;
|
gap: 12px;
|
||||||
@@ -160,17 +216,21 @@
|
|||||||
transform: translateY(-1px);
|
transform: translateY(-1px);
|
||||||
}
|
}
|
||||||
.action-btn .icon { color: #22c55e; font-size: 16px; }
|
.action-btn .icon { color: #22c55e; font-size: 16px; }
|
||||||
/* 连接设置弹窗 */
|
/* ========== 连接设置弹窗 ========== */
|
||||||
.modal {
|
.modal {
|
||||||
display: none;
|
display: none;
|
||||||
|
/* 默认隐藏 */
|
||||||
position: fixed;
|
position: fixed;
|
||||||
inset: 0;
|
inset: 0;
|
||||||
|
/* 全屏覆盖 */
|
||||||
background: rgba(0,0,0,0.4);
|
background: rgba(0,0,0,0.4);
|
||||||
|
/* 半透明黑色遮罩 */
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
z-index: 100;
|
z-index: 100;
|
||||||
}
|
}
|
||||||
.modal.show { display: flex; }
|
.modal.show { display: flex; }
|
||||||
|
/* 显示时用 flex 居中 */
|
||||||
.modal-content {
|
.modal-content {
|
||||||
background: #fff;
|
background: #fff;
|
||||||
padding: 24px;
|
padding: 24px;
|
||||||
@@ -203,16 +263,21 @@
|
|||||||
.modal-content .btn-primary {
|
.modal-content .btn-primary {
|
||||||
background: #22c55e;
|
background: #22c55e;
|
||||||
color: #fff;
|
color: #fff;
|
||||||
|
/* 主按钮:绿色 */
|
||||||
}
|
}
|
||||||
.modal-content .btn-secondary {
|
.modal-content .btn-secondary {
|
||||||
background: #e5e7eb;
|
background: #e5e7eb;
|
||||||
color: #333;
|
color: #333;
|
||||||
|
/* 次要按钮:灰色 */
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
<!-- 页面主体 -->
|
||||||
<div class="app">
|
<div class="app">
|
||||||
|
<!-- 主应用容器 -->
|
||||||
<div class="menu-bar">
|
<div class="menu-bar">
|
||||||
|
<!-- 顶部菜单栏 -->
|
||||||
<button class="menu-item connect" id="btnConnect" title="连接">
|
<button class="menu-item connect" id="btnConnect" title="连接">
|
||||||
<span class="icon">📶</span>
|
<span class="icon">📶</span>
|
||||||
<span>连接</span>
|
<span>连接</span>
|
||||||
@@ -221,9 +286,9 @@
|
|||||||
<span class="icon">⚙</span>
|
<span class="icon">⚙</span>
|
||||||
<span>设置</span>
|
<span>设置</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="menu-item exit" title="退出">
|
<button class="menu-item exit" title="断开">
|
||||||
<span class="icon">⏻</span>
|
<span class="icon">⏻</span>
|
||||||
<span>退出</span>
|
<span>断开</span>
|
||||||
</button>
|
</button>
|
||||||
<button class="menu-item about" id="btnAbout" title="关于">
|
<button class="menu-item about" id="btnAbout" title="关于">
|
||||||
<span class="icon">ℹ</span>
|
<span class="icon">ℹ</span>
|
||||||
@@ -231,12 +296,18 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="main">
|
<div class="main">
|
||||||
|
<!-- 主内容区:显示 + 控制 -->
|
||||||
<div class="display-area">
|
<div class="display-area">
|
||||||
|
<!-- 屏幕显示区域 -->
|
||||||
<canvas id="screen" style="display:none;"></canvas>
|
<canvas id="screen" style="display:none;"></canvas>
|
||||||
|
<!-- canvas 初始隐藏,有画面后显示 -->
|
||||||
<span class="display-placeholder" id="placeholder">点击「连接」连接装置</span>
|
<span class="display-placeholder" id="placeholder">点击「连接」连接装置</span>
|
||||||
|
<!-- 未连接时的提示文字 -->
|
||||||
</div>
|
</div>
|
||||||
<div class="control-panel">
|
<div class="control-panel">
|
||||||
|
<!-- 右侧控制面板 -->
|
||||||
<div class="dpad">
|
<div class="dpad">
|
||||||
|
<!-- 方向键 + 确认 -->
|
||||||
<button class="btn btn-up" data-key="U">▲</button>
|
<button class="btn btn-up" data-key="U">▲</button>
|
||||||
<button class="btn btn-left" data-key="L">◀</button>
|
<button class="btn btn-left" data-key="L">◀</button>
|
||||||
<button class="btn btn-ok" data-key="ENT">✓</button>
|
<button class="btn btn-ok" data-key="ENT">✓</button>
|
||||||
@@ -244,6 +315,7 @@
|
|||||||
<button class="btn btn-down" data-key="D">▼</button>
|
<button class="btn btn-down" data-key="D">▼</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="action-btns">
|
<div class="action-btns">
|
||||||
|
<!-- 复归、返回按钮 -->
|
||||||
<button class="action-btn" data-key="RESET">
|
<button class="action-btn" data-key="RESET">
|
||||||
<span class="icon">↺</span>
|
<span class="icon">↺</span>
|
||||||
<span>复归</span>
|
<span>复归</span>
|
||||||
@@ -260,7 +332,7 @@
|
|||||||
<div class="modal" id="connectModal">
|
<div class="modal" id="connectModal">
|
||||||
<div class="modal-content">
|
<div class="modal-content">
|
||||||
<h3>连接装置</h3>
|
<h3>连接装置</h3>
|
||||||
<input type="text" id="hostInput" placeholder="装置 IP 地址" value="192.168.1.100">
|
<input type="text" id="hostInput" placeholder="装置 IP 地址" value="192.168.253.3">
|
||||||
<input type="number" id="portInput" placeholder="端口" value="7003">
|
<input type="number" id="portInput" placeholder="端口" value="7003">
|
||||||
<div class="btn-row">
|
<div class="btn-row">
|
||||||
<button class="btn-secondary" id="modalCancel">取消</button>
|
<button class="btn-secondary" id="modalCancel">取消</button>
|
||||||
@@ -269,101 +341,134 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<script>
|
<script>
|
||||||
|
/**
|
||||||
|
* 前端逻辑:通过 Socket.IO 与后端 WebSocket 通信。
|
||||||
|
* - connect_device: 连接装置,成功后后端持续推送 screen 事件
|
||||||
|
* - disconnect_device: 断开装置
|
||||||
|
* - key: 发送按键码
|
||||||
|
*/
|
||||||
|
// ========== 常量与 DOM 引用 ==========
|
||||||
|
// 按键名 -> RemoDispBus 协议码:U/D/L/R 方向,ENT 确认,ESC 返回,RESET 复归
|
||||||
const KEY_MAP = { U: 0x02, D: 0x40, L: 0x10, R: 0x08, ENT: 0x20, ESC: 0x01, RESET: 0x04 };
|
const KEY_MAP = { U: 0x02, D: 0x40, L: 0x10, R: 0x08, ENT: 0x20, ESC: 0x01, RESET: 0x04 };
|
||||||
let apiBase = '';
|
|
||||||
let refreshTimer = null;
|
|
||||||
const canvas = document.getElementById('screen');
|
const canvas = document.getElementById('screen');
|
||||||
|
// canvas 元素,用于绘制远程屏幕
|
||||||
const placeholder = document.getElementById('placeholder');
|
const placeholder = document.getElementById('placeholder');
|
||||||
|
// 占位提示文字
|
||||||
const connectBtn = document.getElementById('btnConnect');
|
const connectBtn = document.getElementById('btnConnect');
|
||||||
|
// 连接按钮
|
||||||
const connectModal = document.getElementById('connectModal');
|
const connectModal = document.getElementById('connectModal');
|
||||||
|
// 连接弹窗
|
||||||
const hostInput = document.getElementById('hostInput');
|
const hostInput = document.getElementById('hostInput');
|
||||||
|
// IP 输入框
|
||||||
const portInput = document.getElementById('portInput');
|
const portInput = document.getElementById('portInput');
|
||||||
|
// 端口输入框
|
||||||
const modalConnect = document.getElementById('modalConnect');
|
const modalConnect = document.getElementById('modalConnect');
|
||||||
|
// 弹窗内「连接」按钮
|
||||||
const modalCancel = document.getElementById('modalCancel');
|
const modalCancel = document.getElementById('modalCancel');
|
||||||
function showConnectModal() {
|
// 弹窗内「取消」按钮
|
||||||
connectModal.classList.add('show');
|
|
||||||
}
|
// ========== WebSocket 连接 ==========
|
||||||
function hideConnectModal() {
|
const socket = io();
|
||||||
connectModal.classList.remove('show');
|
// 连接当前页面的 origin,建立 Socket.IO 连接
|
||||||
}
|
|
||||||
connectBtn.onclick = showConnectModal;
|
socket.on('connect', () => {});
|
||||||
modalCancel.onclick = hideConnectModal;
|
// 连接成功时(可留空)
|
||||||
modalConnect.onclick = async () => {
|
socket.on('connect_result', (data) => {
|
||||||
const host = hostInput.value.trim();
|
// 收到后端连接结果
|
||||||
const port = portInput.value || '7003';
|
if (data.success) {
|
||||||
try {
|
hideConnectModal();
|
||||||
const r = await fetch(`/connect?host=${encodeURIComponent(host)}&port=${port}`);
|
// 关闭弹窗
|
||||||
const ok = await r.json();
|
connectBtn.classList.add('connected');
|
||||||
if (ok.success) {
|
// 标记为已连接状态
|
||||||
hideConnectModal();
|
connectBtn.querySelector('span:last-child').textContent = '已连接';
|
||||||
connectBtn.classList.add('connected');
|
// 更新按钮文字
|
||||||
connectBtn.querySelector('span:last-child').textContent = '已连接';
|
} else {
|
||||||
apiBase = 'ok';
|
alert('连接失败: ' + (data.error || '未知错误'));
|
||||||
startRefresh();
|
// 弹出错误提示
|
||||||
} else {
|
|
||||||
alert('连接失败: ' + (ok.error || '未知错误'));
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
alert('连接失败,请先启动: python remo_disp_server.py');
|
|
||||||
}
|
}
|
||||||
};
|
|
||||||
async function sendKey(key) {
|
|
||||||
if (!connectBtn.classList.contains('connected')) return;
|
|
||||||
const code = KEY_MAP[key] ?? 0;
|
|
||||||
await fetch(`/key?code=${code}`);
|
|
||||||
}
|
|
||||||
async function fetchScreen() {
|
|
||||||
if (!connectBtn.classList.contains('connected')) return;
|
|
||||||
try {
|
|
||||||
const r = await fetch('/screen');
|
|
||||||
const ct = r.headers.get('Content-Type') || '';
|
|
||||||
const blob = await r.blob();
|
|
||||||
if (ct.includes('image/png')) {
|
|
||||||
const url = URL.createObjectURL(blob);
|
|
||||||
const img = new Image();
|
|
||||||
img.onload = () => {
|
|
||||||
canvas.width = img.width;
|
|
||||||
canvas.height = img.height;
|
|
||||||
const ctx = canvas.getContext('2d');
|
|
||||||
ctx.drawImage(img, 0, 0);
|
|
||||||
canvas.style.display = 'block';
|
|
||||||
placeholder.style.display = 'none';
|
|
||||||
URL.revokeObjectURL(url);
|
|
||||||
};
|
|
||||||
img.src = url;
|
|
||||||
} else {
|
|
||||||
const buf = await blob.arrayBuffer();
|
|
||||||
const data = new Uint8Array(buf);
|
|
||||||
const w = parseInt(r.headers.get('X-Width') || '160', 10);
|
|
||||||
const h = parseInt(r.headers.get('X-Height') || '160', 10);
|
|
||||||
canvas.width = w;
|
|
||||||
canvas.height = h;
|
|
||||||
const ctx = canvas.getContext('2d');
|
|
||||||
const id = ctx.createImageData(w, h);
|
|
||||||
for (let y = 0; y < h; y++)
|
|
||||||
for (let x = 0; x < w; x++) {
|
|
||||||
const bi = (y * w + x) >> 3, bit = 7 - (x & 7);
|
|
||||||
const v = (bi < data.length && (data[bi] >> bit) & 1) ? 255 : 0;
|
|
||||||
const i = (y * w + x) * 4;
|
|
||||||
id.data[i] = id.data[i+1] = id.data[i+2] = v;
|
|
||||||
id.data[i+3] = 255;
|
|
||||||
}
|
|
||||||
ctx.putImageData(id, 0, 0);
|
|
||||||
canvas.style.display = 'block';
|
|
||||||
placeholder.style.display = 'none';
|
|
||||||
}
|
|
||||||
} catch (e) {}
|
|
||||||
}
|
|
||||||
function startRefresh() {
|
|
||||||
fetchScreen();
|
|
||||||
if (refreshTimer) clearInterval(refreshTimer);
|
|
||||||
refreshTimer = setInterval(fetchScreen, 500);
|
|
||||||
}
|
|
||||||
document.querySelectorAll('.dpad .btn, .action-btn').forEach(btn => {
|
|
||||||
btn.onclick = () => sendKey(btn.dataset.key);
|
|
||||||
});
|
});
|
||||||
document.querySelector('.menu-item.exit').onclick = () => sendKey('ESC');
|
// 服务端推送屏幕:data.png 为 base64 编码的 PNG,解码后绘制到 canvas
|
||||||
|
socket.on('screen', (data) => {
|
||||||
|
if (!data.png) return;
|
||||||
|
// 无 base64 数据则跳过
|
||||||
|
const binary = atob(data.png);
|
||||||
|
// base64 解码为二进制字符串
|
||||||
|
const bytes = new Uint8Array(binary.length);
|
||||||
|
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
||||||
|
// 转为 Uint8Array
|
||||||
|
const blob = new Blob([bytes], { type: 'image/png' });
|
||||||
|
// 创建 PNG Blob
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
// 创建临时 URL
|
||||||
|
const img = new Image();
|
||||||
|
img.onload = () => {
|
||||||
|
// 图片加载完成后
|
||||||
|
canvas.width = img.width;
|
||||||
|
canvas.height = img.height;
|
||||||
|
// 设置 canvas 尺寸
|
||||||
|
canvas.getContext('2d').drawImage(img, 0, 0);
|
||||||
|
// 绘制到 canvas
|
||||||
|
canvas.style.display = 'block';
|
||||||
|
placeholder.style.display = 'none';
|
||||||
|
// 显示 canvas,隐藏占位符
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
// 释放临时 URL
|
||||||
|
};
|
||||||
|
img.src = url;
|
||||||
|
// 触发加载
|
||||||
|
});
|
||||||
|
socket.on('disconnect_result', () => {});
|
||||||
|
// 收到断开结果(可留空)
|
||||||
|
|
||||||
|
function showConnectModal() { connectModal.classList.add('show'); }
|
||||||
|
// 显示连接弹窗
|
||||||
|
function hideConnectModal() { connectModal.classList.remove('show'); }
|
||||||
|
// 隐藏连接弹窗
|
||||||
|
connectBtn.onclick = showConnectModal;
|
||||||
|
// 点击连接按钮 -> 显示弹窗
|
||||||
|
modalCancel.onclick = hideConnectModal;
|
||||||
|
// 点击取消 -> 隐藏弹窗
|
||||||
|
|
||||||
|
modalConnect.onclick = () => {
|
||||||
|
// 点击弹窗内「连接」按钮
|
||||||
|
const host = hostInput.value.trim();
|
||||||
|
// 获取 IP,去空格
|
||||||
|
const port = portInput.value || '7003';
|
||||||
|
// 获取端口,缺省 7003
|
||||||
|
socket.emit('connect_device', { host, port });
|
||||||
|
// 向后端发送连接请求
|
||||||
|
};
|
||||||
|
|
||||||
|
function sendKey(key) {
|
||||||
|
// 发送按键到后端
|
||||||
|
if (!connectBtn.classList.contains('connected')) return;
|
||||||
|
// 未连接则不发送
|
||||||
|
socket.emit('key', { code: KEY_MAP[key] ?? 0 });
|
||||||
|
// 根据按键名查协议码并发送
|
||||||
|
}
|
||||||
|
|
||||||
|
function doDisconnect() {
|
||||||
|
// 执行断开
|
||||||
|
socket.emit('disconnect_device');
|
||||||
|
// 通知后端断开设备
|
||||||
|
connectBtn.classList.remove('connected');
|
||||||
|
connectBtn.querySelector('span:last-child').textContent = '连接';
|
||||||
|
// 恢复按钮状态和文字
|
||||||
|
canvas.style.display = 'none';
|
||||||
|
placeholder.style.display = '';
|
||||||
|
placeholder.textContent = '点击「连接」连接装置';
|
||||||
|
// 隐藏 canvas,显示占位符
|
||||||
|
}
|
||||||
|
|
||||||
|
document.querySelectorAll('.dpad .btn, .action-btn').forEach(btn => {
|
||||||
|
// 为所有方向键和动作按钮绑定点击
|
||||||
|
btn.onclick = () => sendKey(btn.dataset.key);
|
||||||
|
// 点击时发送对应按键码
|
||||||
|
});
|
||||||
|
document.querySelector('.menu-item.exit').onclick = doDisconnect;
|
||||||
|
// 断开按钮 -> 执行断开
|
||||||
document.getElementById('btnAbout').onclick = () => alert('远程显示工具\n与 RemoDispBus 协议兼容\n端口 7003');
|
document.getElementById('btnAbout').onclick = () => alert('远程显示工具\n与 RemoDispBus 协议兼容\n端口 7003');
|
||||||
|
// 关于按钮 -> 弹出说明
|
||||||
</script>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
# 远程显示工具依赖
|
# 远程显示工具依赖
|
||||||
# 命令行工具 remo_disp_client.py 仅需 Python 标准库
|
# 命令行工具 remo_disp_client.py 仅需 Python 标准库
|
||||||
# Web 服务 remo_disp_server.py 需要 Flask
|
# Web 服务 remo_disp_server.py 需要 Flask + flask-socketio
|
||||||
# 保存 PNG 需要 Pillow(可选)
|
# 保存 PNG 需要 Pillow(可选)
|
||||||
Flask>=2.0.0
|
Flask>=2.0.0
|
||||||
Pillow>=9.0.0
|
Pillow>=9.0.0
|
||||||
|
flask-socketio>=5.0.0
|
||||||
|
python-socketio>=5.0.0
|
||||||
|
|||||||
BIN
static/favicon.ico
Normal file
BIN
static/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.9 MiB |
Reference in New Issue
Block a user