From 8aa87900bf47949400980a1ff7dc2e44a11f0e28 Mon Sep 17 00:00:00 2001 From: JULM-COMPUTER Date: Sat, 26 Apr 2025 01:34:04 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- InterphoneHandler.py | 6 --- boot.py | 105 ++++++++++++++++++++++--------------------- 2 files changed, 53 insertions(+), 58 deletions(-) diff --git a/InterphoneHandler.py b/InterphoneHandler.py index 2be2bec..4fd5a0f 100644 --- a/InterphoneHandler.py +++ b/InterphoneHandler.py @@ -40,12 +40,6 @@ def init_i2s(): class InterphoneHandler: - def new_voice(self, data): - print(f"[Interphone] 接收到新数据: {data}") - i2s = init_i2s() - url = "http://iot.julecn.com/interphone/get_voice?name=" + data['name'] # 替换为音频文件的URL - print(url) - self.play_audio_stream(i2s, url) def play_wav_file(self, data): try: diff --git a/boot.py b/boot.py index 92bcf68..562f67c 100644 --- a/boot.py +++ b/boot.py @@ -20,6 +20,8 @@ WS_SERVER = "wss://websocket.julecn.com:80" HOST, PORT = WS_SERVER.replace("wss://", "").split(":") PORT = int(PORT) +WS_SOCK = None + action_handlers = { 'interphone': InterphoneHandler() } @@ -37,7 +39,8 @@ def connect_wifi(): return sta_if -def websocket_handshake(sock): +def websocket_handshake(): + global WS_SOCK # 初始化一个空的字节数组,用于存储随机字节 random_bytes = bytearray() @@ -58,21 +61,20 @@ def websocket_handshake(sock): sha1_hash = hashlib.sha1(combined).digest() # 获取原始SHA1哈希字节数据 accept_key = ubinascii.b2a_base64(sha1_hash).decode().strip() # 转换为Base64字符串并去除换行符 - print(f"key: {key}") - handshake = f"GET / HTTP/1.1\r\n" \ f"Host: {HOST}\r\n" \ f"Upgrade: websocket\r\n" \ f"Connection: Upgrade\r\n" \ f"Sec-WebSocket-Key: {key}\r\n" \ f"Sec-WebSocket-Version: 13\r\n\r\n" - sock.send(handshake.encode()) + WS_SOCK.send(handshake.encode()) response = b"" while b"\r\n\r\n" not in response: - response += sock.recv(1024) + response += WS_SOCK.recv(1) headers, _ = response.split(b"\r\n\r\n", 1) - print(headers, response) + print(f"headers:{headers}") + print(f"_{_}") if b"101 Switching Protocols" not in headers: raise Exception("握手失败") @@ -89,17 +91,19 @@ def websocket_handshake(sock): print("WebSocket握手成功") - -def websocket_receive_thread(sock): +def websocket_receive_thread(): + print("开始接收消息...") while True: try: - msg = receive_message(sock) - if msg: - # 有新数据时调用处理方法 - handle_new_data(msg) + global WS_SOCK + if WS_SOCK != None: + msg = receive_message(WS_SOCK) + if msg: + # 有新数据时调用处理方法 + handle_new_data(msg) except Exception as e: print(f"接收数据出错: {e}") - + time.sleep(1) def handle_action(action, data): """ @@ -230,61 +234,58 @@ def send_text(sock, message): raise # 抛出异常供上层处理 +# 启动接收数据的线程 +_thread.start_new_thread(websocket_receive_thread, ()) + def ws_client(): - while True: - try: - sta_if = connect_wifi() - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.connect((HOST, PORT)) - - websocket_handshake(sock) - - print("开始接收消息...") - # 启动接收数据的线程 - _thread.start_new_thread(websocket_receive_thread, (sock,)) - - while True: - time.sleep(30) - send_text(sock, '{"action":"sys.ping"}') - - except OSError as e: - print(f"连接异常: {str(e)}") - if 'sock' in locals(): - sock.close() - if 'sta_if' in locals(): - sta_if.active(False) - time.sleep(5) - reset() - except Exception as e: - print(f"发生错误: {str(e)}") - if 'sock' in locals(): - sock.close() - time.sleep(5) - - -def force_cleanup(sock): - """强制清理残留资源""" + global WS_SOCK try: - sock.shutdown(socket.SHUT_RDWR) # 完全关闭套接字 + sta_if = connect_wifi() + WS_SOCK = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + WS_SOCK.connect((HOST, PORT)) + + websocket_handshake() + while True: + time.sleep(30) + send_text(WS_SOCK, '{"action":"sys.ping"}') + + except OSError as e: + print(f"连接异常: {str(e)}") + if 'sta_if' in locals(): + sta_if.active(False) + time.sleep(5) + reset() + except Exception as e: + print(f"发生错误: {str(e)}") + WS_SOCK.close() + time.sleep(5) + reset() + + + +def force_cleanup(): + """强制清理残留资源""" + global WS_SOCK + try: + WS_SOCK.shutdown(socket.SHUT_RDWR) # 完全关闭套接字 except: pass finally: - sock.close() + WS_SOCK.close() # 终止相关线程(需配合线程管理) _thread.exit() # MicroPython的线程终止方式 - -def check_connection_alive(sock): +def check_connection_alive(): """连接活性检测(参考TCP状态检测)""" + global WS_SOCK try: # 发送空数据检测写缓冲区 - sock.send(b'\x00') + WS_SOCK.send(b'\x00') return True except OSError as e: if e.args[0] == 9: # EBADF: 套接字已关闭 return False raise - ws_client()