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 java.net.http import HttpClient, WebSocket
from java.net 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)
else:
print("Received an empty message")
try:
# 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:
ws://xx.xx.xx.xx
org.python.proxies.__main__$NoiseMeterListener$48@354638ee
WebSocket connection opened
jdk.internal.net.http.common.MinimalFuture@5f496da7[Completed normally] (id=1610)
('Sent device info request:', '{"cmd": "ver"}')
jdk.internal.net.http.websocket.WebSocketImpl@1f25eeb[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.