import asyncio
import websockets
import ssl
import os
import json
import signal
import linecache
import sys
sys.path.append("/root/")
from CocoPi import AHT20
from CocoPi import LIGHTINTENSITY

aht20 = AHT20(2)
light_intensity = LIGHTINTENSITY()



ssl._create_default_https_context = ssl._create_unverified_context
ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ssl_context.load_cert_chain("/root/preset/server/ccrb.crt", "/root/preset/server/ccrb.key")
p1 = None
p2 = None
p3 = None
countn = 0

async def send(websocket):
    global p2
    global p1
    global countn
    await asyncio.create_subprocess_shell("echo > /root/event.log &")
    #open("/root/event.log", 'w').close()
    while True:
        await asyncio.sleep(0.03)
        if True:
            try:
                proxy_recv_msg = ""
                linecache.clearcache()
                logarr = linecache.getlines("/root/event.log")[-20:]
                open("/root/event.log", 'w').close()
                #os.remove(r'/root/event.log')
                #await asyncio.create_subprocess_shell("echo '' > /root/event.log")
                #print(linecache.getlines("/root/event.log")[-10:])
                proxy_recv_msg = "".join(logarr).rstrip('\x00')
                #print(len(logarr))
                if proxy_recv_msg != "" and proxy_recv_msg != "\n":                                                                         
                    try:                                                                                         
                        await websocket.send(proxy_recv_msg)
                    except websockets.ConnectionClosed:
                        try:
                            if p1.returncode == None:                                                                                                                                                
                                os.killpg(p1.pid, signal.SIGUSR1)
                            #open("/root/event.log", 'w').close()
                            #await asyncio.create_subprocess_shell("echo "" > /root/event.log")                                                                                                                
                        finally:                                                                                                                                             
                            pass                                                           
                        pass 
            finally:                                                                                         
                pass

async def receive(websocket):
    global p2
    global p3
    global p1    
#    if p2 == None and p3 == None:
#        p2 = await asyncio.create_subprocess_shell("echo '' > /tmp/event.log && tail -f /tmp/event.log", stdout=asyncio.subprocess.PIPE, preexec_fn = os.setsid)
#        p3 = p2
#    else:
#        p2 = p3
    while True:
        await asyncio.sleep(0.5)
        recv_text = await websocket.recv()
        if p1 != None:
            try:
                if p1.returncode == None:
                    p1.kill()
                    os.killpg(p1.pid, signal.SIGUSR1)
            finally:
                pass
        p1 = await asyncio.create_subprocess_shell(recv_text, stdout=None, preexec_fn = os.setsid)
        print(p1.pid)
async def system_monitor(websocket):
    print("客户端已连接")
    log_content = ""
    try:
        while True:
            # 获取系统信息
            with open("/root/send.txt", "r") as f:
                log_content = f.read()
            
            
            await websocket.send(json.dumps(log_content))
            await asyncio.sleep(2)  # 每3秒发送一次更新
            
    except websockets.exceptions.ConnectionClosed:
        print("客户端断开连接")
async def main_logic(websocket, path):
        await runstart(websocket, path)
        asyncio.run(runstart(websocket, path))

async def runstart(websocket, path):
        a = asyncio.create_task(send(websocket))
        b = asyncio.create_task(receive(websocket))
        c = asyncio.create_task(system_monitor(websocket))
        await a
        await b
        await c


start_server = websockets.serve(main_logic, '0.0.0.0', 5678, ssl=ssl_context)

asyncio.get_event_loop().run_until_complete(start_server)        
asyncio.get_event_loop().run_forever()
