Using websocket protocol to gather data from device

Hello Community,

I am trying to integrate some noise meters to get live data feed from them using websocket. I believe I am able to establish a connection to the device and send command but I am not able to read the response or I am not sure If i am actually receiving any response. I am using the following code.

import json
from import HttpClient, WebSocket
from import URI

    class NoiseMeterListener(WebSocket.Listener):
    def onOpen(self, websocket):
        print("WebSocket connection opened")
        # Send command to get device information
        getDeviceInfoCommand = json.dumps({"cmd": "ver"})
        print websocket.sendText(getDeviceInfoCommand, True)
        print("Sent device info request:", getDeviceInfoCommand)
    def onText(self, websocket, message, last):
    	print "on Text"
        if message:
            print("Received message: ", message)
            print("Received an empty message")
            # Attempt to parse the message as JSON
            data = json.loads(message)
            print("Parsed JSON data: ", data)
        except json.JSONDecodeError as e:
            print("Error decoding JSON: ", e)
            print("Raw message content: ", message)

    def onError(self, websocket, error):
        print("Error occurred:", error)

    def onClose(self, websocket, statusCode, reason):
        print("WebSocket connection closed, Status:", statusCode, "Reason:", reason)

# Set up the WebSocket connection
httpClient = HttpClient.newHttpClient()
websocketUri = URI.create("ws://xx.xx.xx.xx")
print websocketUri# Adjust as necessary
listener = NoiseMeterListener()
print listener
websocket = httpClient.newWebSocketBuilder().buildAsync(websocketUri, listener).get()
print websocket

I see this in the output:

WebSocket connection opened[Completed normally] (id=1610)
('Sent device info request:', '{"cmd": "ver"}')[uri=ws://xx.xx.xx.xx]

It looks like the onText method is not triggering or the device is not responding.

Just wondering if there's any scripting errors causing the issue...

Has anyone ever done anything like this before?
Thanks and I appreciate the comments.

There's some potentially useful snippets for creating a websocket client in this thread - make sure you scroll all the way through :slight_smile: