import asyncio
import json
import threading
import websockets
import os
##
from message_base import MessageBase
 
 
class WebServer:
    def __init__(self, host, port, message_base: MessageBase):
        self.host = host
        self.port = port
        self.clients = []
        self.message_base = message_base

    async def echo(self, websocket, path):
        self.clients.append(websocket)
        client_ip, client_port = websocket.remote_address
        print(f"客户连接:{client_ip}:{client_port}")
        while True:
            try:
                recv_text = await websocket.recv()
                if recv_text:
                    byte_array = recv_text
                    print("ws收到", byte_array)
                    self.message_base.add("ws_recv", byte_array)

                send_text = self.message_base.get("ws_send")
                if send_text:
                    byte_array = send_text
                    print("ws发送", byte_array)
                    await websocket.send(byte_array)
                # data = json.loads(recv_text)
                # device = data.get("device")
                # if device:
                #     self.message_base.add(device, data)
                # else:
                #     continue
            except websockets.ConnectionClosed:
                print("ConnectionClosed...")  # 链接断开
                self.clients.remove(websocket)
                break
            except websockets.InvalidState:
                print("InvalidState...")  # 无效状态
                self.clients.remove(websocket)
                break
            except Exception as e:
                print("Err in {}[{}]:\n {}".format(os.path.basename(e.__traceback__.tb_frame.f_globals["__file__"]), e.__traceback__.tb_lineno, e))
        print("客户结束:{client_ip}:{client_port}");

    
    def connect(self):
        start_server = websockets.serve(self.echo, self.host, self.port)
        asyncio.get_event_loop().run_until_complete(start_server)
        asyncio.get_event_loop().run_forever()
 
    def run(self):
        t = threading.Thread(target=self.connect)
        t.start()
        print("ws服务已启动！")
 
 
if __name__ == '__main__':
    mb = MessageBase()
    ws = WebServer("192.168.6.28", 8001, mb)
    ws.run()