'Websockets connect fail after a while in execute

Excuse me, this is my IOT program, through bluetooth to receive sensor data, and then transfer the data, use websockets to transmit to the web page, but after a while to execute, my websockets will be disconnected, this is the error code, can someone give me some advice?

I've tried using threading, which executes read and transfer separately, but there will still be errors.


error : websockets.exceptions.ConnectionClosedError: no close frame received or sent


from bluepy import btle
import time
import json
import asyncio
import websockets
import requests

MAC = ""
SERVICE_UUID = ""
CHARACTERISTIC_UUID = ""

negotiation = requests.post('http://127.0.0.1/APP/hub/negotiate?negotiateVersion=0').json()

list1 = []
list2 = []
target =".."
dev = btle.Peripheral(MAC)
service_uuid = btle.UUID(SERVICE_UUID)
service = dev.getServiceByUUID(service_uuid)
characteristics = dev.getCharacteristics()

def not_empty(s):
    return s and s.strip()

def toSignalRMessage(data):
    return f'{json.dumps(data)}\u001e'


async def connectToHub(connectionId):
    uri = f"ws://127.0.0.1/APP/hub?id={connectionId}"
    async with websockets.connect(uri) as websocket:
         
        async def handshake():
            await websocket.send(toSignalRMessage({"protocol": "json", "version": 1}))
            handshake_response = await websocket.recv()
            print(f"handshake_response: {handshake_response}")
       
        async def send_data_to_websocket(characteristics):
            while _running:
                for char in characteristics:
                    if(char.uuid == CHARACTERISTIC_UUID ):                        
                        list1 =str(char.read(),encoding='utf-8').split(";")                            
                        list1 =list(filter(not_empty,list1))
                        list2=list(map(float,list1))
                        print (list2)
                        X = round(list2[1]/18,2)
                        Y = round(list2[2]/18*-1,2)                                          
                       
                        message = {
                            "type": 1,              
                            "target": "SendMessage",                              
                            "arguments": [f"{X}"]
                            }

                        await websocket.send(toSignalRMessage(message))                        
                                             
                        message = {
                            "type": 1,              
                            "target": "SendMessage2",                              
                            "arguments": [f"{Y}"]  
                            }
                        await websocket.send(toSignalRMessage(message))                            
        await handshake()    
        _running = True
        send_task = asyncio.create_task(send_data_to_websocket(characteristics))  
        await send_task
       
async def main():
    try:
        await connectToHub(negotiation['connectionId'])            
    except:
        print("connect fail")
       
if __name__ == '__main__':
    asyncio.run(main())


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source