优化。

This commit is contained in:
2025-04-26 01:34:04 +08:00
parent 52af9e397f
commit 8aa87900bf
2 changed files with 53 additions and 58 deletions

View File

@@ -40,12 +40,6 @@ def init_i2s():
class InterphoneHandler: 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): def play_wav_file(self, data):
try: try:

63
boot.py
View File

@@ -20,6 +20,8 @@ WS_SERVER = "wss://websocket.julecn.com:80"
HOST, PORT = WS_SERVER.replace("wss://", "").split(":") HOST, PORT = WS_SERVER.replace("wss://", "").split(":")
PORT = int(PORT) PORT = int(PORT)
WS_SOCK = None
action_handlers = { action_handlers = {
'interphone': InterphoneHandler() 'interphone': InterphoneHandler()
} }
@@ -37,7 +39,8 @@ def connect_wifi():
return sta_if return sta_if
def websocket_handshake(sock): def websocket_handshake():
global WS_SOCK
# 初始化一个空的字节数组,用于存储随机字节 # 初始化一个空的字节数组,用于存储随机字节
random_bytes = bytearray() random_bytes = bytearray()
@@ -58,21 +61,20 @@ def websocket_handshake(sock):
sha1_hash = hashlib.sha1(combined).digest() # 获取原始SHA1哈希字节数据 sha1_hash = hashlib.sha1(combined).digest() # 获取原始SHA1哈希字节数据
accept_key = ubinascii.b2a_base64(sha1_hash).decode().strip() # 转换为Base64字符串并去除换行符 accept_key = ubinascii.b2a_base64(sha1_hash).decode().strip() # 转换为Base64字符串并去除换行符
print(f"key: {key}")
handshake = f"GET / HTTP/1.1\r\n" \ handshake = f"GET / HTTP/1.1\r\n" \
f"Host: {HOST}\r\n" \ f"Host: {HOST}\r\n" \
f"Upgrade: websocket\r\n" \ f"Upgrade: websocket\r\n" \
f"Connection: Upgrade\r\n" \ f"Connection: Upgrade\r\n" \
f"Sec-WebSocket-Key: {key}\r\n" \ f"Sec-WebSocket-Key: {key}\r\n" \
f"Sec-WebSocket-Version: 13\r\n\r\n" f"Sec-WebSocket-Version: 13\r\n\r\n"
sock.send(handshake.encode()) WS_SOCK.send(handshake.encode())
response = b"" response = b""
while b"\r\n\r\n" not in response: 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) 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: if b"101 Switching Protocols" not in headers:
raise Exception("握手失败") raise Exception("握手失败")
@@ -89,17 +91,19 @@ def websocket_handshake(sock):
print("WebSocket握手成功") print("WebSocket握手成功")
def websocket_receive_thread():
def websocket_receive_thread(sock): print("开始接收消息...")
while True: while True:
try: try:
msg = receive_message(sock) global WS_SOCK
if WS_SOCK != None:
msg = receive_message(WS_SOCK)
if msg: if msg:
# 有新数据时调用处理方法 # 有新数据时调用处理方法
handle_new_data(msg) handle_new_data(msg)
except Exception as e: except Exception as e:
print(f"接收数据出错: {e}") print(f"接收数据出错: {e}")
time.sleep(1)
def handle_action(action, data): def handle_action(action, data):
""" """
@@ -230,61 +234,58 @@ def send_text(sock, message):
raise # 抛出异常供上层处理 raise # 抛出异常供上层处理
# 启动接收数据的线程
_thread.start_new_thread(websocket_receive_thread, ())
def ws_client(): def ws_client():
while True: global WS_SOCK
try: try:
sta_if = connect_wifi() sta_if = connect_wifi()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) WS_SOCK = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT)) WS_SOCK.connect((HOST, PORT))
websocket_handshake(sock)
print("开始接收消息...")
# 启动接收数据的线程
_thread.start_new_thread(websocket_receive_thread, (sock,))
websocket_handshake()
while True: while True:
time.sleep(30) time.sleep(30)
send_text(sock, '{"action":"sys.ping"}') send_text(WS_SOCK, '{"action":"sys.ping"}')
except OSError as e: except OSError as e:
print(f"连接异常: {str(e)}") print(f"连接异常: {str(e)}")
if 'sock' in locals():
sock.close()
if 'sta_if' in locals(): if 'sta_if' in locals():
sta_if.active(False) sta_if.active(False)
time.sleep(5) time.sleep(5)
reset() reset()
except Exception as e: except Exception as e:
print(f"发生错误: {str(e)}") print(f"发生错误: {str(e)}")
if 'sock' in locals(): WS_SOCK.close()
sock.close()
time.sleep(5) time.sleep(5)
reset()
def force_cleanup(sock):
def force_cleanup():
"""强制清理残留资源""" """强制清理残留资源"""
global WS_SOCK
try: try:
sock.shutdown(socket.SHUT_RDWR) # 完全关闭套接字 WS_SOCK.shutdown(socket.SHUT_RDWR) # 完全关闭套接字
except: except:
pass pass
finally: finally:
sock.close() WS_SOCK.close()
# 终止相关线程(需配合线程管理) # 终止相关线程(需配合线程管理)
_thread.exit() # MicroPython的线程终止方式 _thread.exit() # MicroPython的线程终止方式
def check_connection_alive():
def check_connection_alive(sock):
"""连接活性检测参考TCP状态检测""" """连接活性检测参考TCP状态检测"""
global WS_SOCK
try: try:
# 发送空数据检测写缓冲区 # 发送空数据检测写缓冲区
sock.send(b'\x00') WS_SOCK.send(b'\x00')
return True return True
except OSError as e: except OSError as e:
if e.args[0] == 9: # EBADF: 套接字已关闭 if e.args[0] == 9: # EBADF: 套接字已关闭
return False return False
raise raise
ws_client() ws_client()