Commit eeca8fdf authored by Sylvain Renault's avatar Sylvain Renault
Browse files

Implementation of websockets

parent e970ef5b
Loading
Loading
Loading
Loading
+62 −52
Original line number Diff line number Diff line
@@ -77,6 +77,7 @@ print("Using Websockets server: " + webs_server)
print()

isTime = False
isPose = False
running = True
success = 0
#websocket = websockets.connect(my_ws_server)
@@ -136,7 +137,7 @@ def CheckRESTServer(client):
#
# WebSockets helpers
#
async def WS_sendNow(websocket, msg, isResponse):
async def WS_send(websocket, msg, isResponse):
    print(f"[WS] Send to server: {msg}")
    await websocket.send(msg)
    if isResponse: 
@@ -146,10 +147,10 @@ async def WS_sendNow(websocket, msg, isResponse):
async def WS_receive(websocket):
    #print(f"[WS] Waiting for response...")
    msgResponse = await websocket.recv()
    WS_OnReceiveText(msgResponse);
    _OnReceiveText(msgResponse);
    return msgResponse
    
def WS_OnReceiveText(msg):
def _OnReceiveText(msg):
    # Handle incoming text here?
    print(f"[WS] Received from server: {msg}")

@@ -171,7 +172,7 @@ async def WS_ConnectAndLoop():

            # Register the user
            print(f"[WS] Send registration request to server for {modulename}")
            registrationResponse = await WS_sendNow(websocket, "RegisterModule:" + modulename, isResponse=True)
            registrationResponse = await WS_send(websocket, "RegisterModule:" + modulename, isResponse=True)
            
            if not registrationResponse.find("You are now registered"):
                print(f"[WS] Error: Registration of {modulename} was not successful!")
@@ -198,7 +199,7 @@ async def WS_ConnectAndLoop():
                cap1.latency = 0.5
                cap1.accuracy = 0.8
                cap_json = cap1.to_json()
                await WS_sendNow(websocket, "Capabilities of:" + modulename + " Data=" + cap_json, isResponse=False)
                await WS_send(websocket, "Capabilities of:" + modulename + " Data=" + cap_json, isResponse=False)

            elif modulename == "HHI-MeshDetection":
                
@@ -214,7 +215,7 @@ async def WS_ConnectAndLoop():
                cap1.latency = 0.5
                cap1.accuracy = 0.9
                cap_json = cap1.to_json()
                await WS_sendNow(websocket, "Capabilities of:" + modulename + " Data=" + cap_json, isResponse=False)
                await WS_send(websocket, "Capabilities of:" + modulename + " Data=" + cap_json, isResponse=False)

                # Capability #2
                cap2 = Capability()
@@ -224,64 +225,73 @@ async def WS_ConnectAndLoop():
                cap2.latency = 0.05
                cap2.accuracy = 1
                cap_json = cap2.to_json()
                await WS_sendNow(websocket, "Capabilities of:" + modulename + " Data=" + cap_json, isResponse=False)
                await WS_send(websocket, "Capabilities of:" + modulename + " Data=" + cap_json, isResponse=False)

            msgToSend = "Time" # test
            #msgToSend = "Idle"
            msgToSend = "TimeStart" # test
            #msgToSend = "PoseStart"

            # Receive
            while running:
            #
                # WS LOOP
            # Websocket LOOP
            #
            while running:

                # Is s message to be send to the server?
                if msgToSend != "None":
                    serverResponse = await WS_sendNow(websocket, msgToSend, isResponse=True)
                    await WS_send(websocket, msgToSend, isResponse=False)
                    msgToSend = "None"

                # Wait for a message
                serverMessage = await WS_receive(websocket)

                    # Change state
                    if msgToSend == "TimeStart":
                # Stop the loop and disconnect the server
                if serverMessage == "SessionStop":
                    isPose = False
                    running = False

                elif serverMessage.startswith("Time="):
                    isTime = True
                        msgToSend = "None"
                    datetime = serverMessage.split('=')
                    print(f"New server time is: { datetime[1] }")

                elif serverMessage.startswith("TimeStop"):
                    isTime = False                    

                elif serverMessage.startswith("ConfigureFramerate:"):
                    json = serverMessage.split(':')[1]

                elif serverMessage.startswith("GetPose:"):
                    uuid2 = serverMessage.split(':')[1]
                    mode = serverMessage.split(':')[2]

                    # Send the pose
                    p = Pose()
                    msgToSend = "PoseNew:" + p.to_json()
                    print(f"Send pose for: uuid={ uuid2 }")

                elif serverMessage.startswith("SubscribePose:"):
                    uuid = serverMessage.split(':')[1]
                    msgToSend = "PoseIsRegistered"
                    isPose = True

                    elif msgToSend == "Idle":
                elif serverMessage.startswith("UnsubscribePose:"):
                    uuid = serverMessage.split(':')[1]
                    isPose = False                    

                elif isPose == True and serverMessage == "RequestNextPose":
                    time.sleep(1)
                        '''serverResponse = await WS_sendNow(websocket, queryFirstJob, isResponse=True)
                        if serverResponse != "Job not found":
                            currentJob = Job.from_json(serverResponse)
                            currentJob.state = JobState.INITIALISING
                            currentJob.creation_time = None
                            currentJob.last_write_time = None
                            currentJob.progress = "0"
                            currentJob.result = 'Scanning location'
                            msgToSend = "UpdateJob(" + currentJob.to_json() + ")"   '''         
                        msgToSend = "Idle"
                    
                    '''elif msgToSend == "Busy":
                        isJob = True
                        time.sleep(0.25)
                        progress = int(currentJob.progress) + 10
                        currentJob.progress = str(progress)
                        if progress >= 100:
                            if currentJob.state == JobState.INITIALISING:                                
                                currentJob.state = JobState.RUNNING
                                currentJob.result = 'Training and querying objects'
                                currentJob.progress = "0"
                            elif currentJob.state == JobState.RUNNING:
                                currentJob.state = JobState.READY
                                currentJob.result = 'Found x objects'
                                msgToSend = "idle"
                                isJob = False
                                
                        serverResponse = await WS_sendNow(websocket, "UpdateJob(" + currentJob.to_json() + ")", isResponse=True)
'''
                if isTime:
                    # Send the pose
                    p = Pose()
                    msgToSend = "PoseNew:" + p.to_json()
                    print(f"Send pose for: uuid={ uuid }")

                elif isTime:
                    serverResponse = await WS_receive(websocket)
                    if serverResponse == "TimeStop": 
                        isTime = False
                        msgToSend = "Idle"

                # Stop the loop and disconnect the server
                if msgToSend == "None" and serverResponse == "Stop":
                    running = False

    except websockets.exceptions.ConnectionClosed as e:
        print(f"[WS] Connection closed with error: {e}")