Ignition as WebSocket client

Hi,

I would like to set up ignition so listen to a WebSocket server as a client. What is the best practices to do so?

Possible with jython scripts.

So, I managed to get this script working. At the moment just running for Script Console.

What is the best way to start the script on gateway startup and maintain the connection so it reconnect if it looses connection?

from java.net.http import HttpClient
from java.net.http import WebSocket
from java.net import URI
import sys

	# Define a custom listener class that implements WebSocket.Listener
class WebSocketListener(WebSocket.Listener):
    def onOpen(self, websocket):
    	print("WebSocket Connection Opened")
        # Request more messages, or send the first message here
        websocket.sendText("Hello from Ignition", True)
        websocket.request(1) # Request the next message

    def onText(self, websocket, data, last):
        print("Received message: " + str([data]))
        # Process the received data (e.g., write to a tag)
        system.tag.writeBlocking(["[default]My/Data/Tag"], str([data]))
        websocket.request(1) # Request the next message

    def onError(self, websocket, error):
        print("Error: " + str(error))
        # Handle the error
        error.printStackTrace()

    def onClose(self, websocket, statusCode, reason):
        print("Connection closed: " + reason + " Status Code: " + str(statusCode))

# Create an HttpClient instance and connect
try:
    client = HttpClient.newHttpClient()
    listener_instance = WebSocketListener()
    client.newWebSocketBuilder().buildAsync(URI.create("ws://192.168.2.21:1880/ws1"), listener_instance)
    print("Connecting to WebSocket server...")
except Exception as e:
    print("Failed to establish WebSocket connection: " + str(e))
 

You'll need to make a project library script out of this, and study the traps related to long-lived asynchronous threads:

Some reading for you: long lived async thread

1 Like