One of the cooler things about the Spark Java framework is built in websocket support thanks to the embedded Jetty server. I've long been fascinated with websockets since they can push data in realtime to a subscribed client without the need for client side polling.

The first (and only) demo often seen is the good old "chat" demo. Don't get me wrong, chat is still a useful (and often implemented) feature, but I've always wanted to find a more interesting use case for them. I think I've finally found a pretty cool use case so I wanted to share it here.



I've blogged in the past about using Spark Java to get a simple website running on the Raspberry Pi. In this demo I'll do just that and in addition I'll implement a simple GPIO handler to listen for a button press event. When the event handler fires, I'll turn on an LED and broadcast a message to subscribed websocket clients to tell them about the message. The majority of the websocket code is altered from this demo.

Let's get started by looking at our build.gradle file as it has a few dependencies we'll need for this demo.

Next up - the Bootstrap.groovy class:

A few notes on the Bootstrap class:

Line 22 - we create our websocket endpoint and tell Spark to use the ChatWebSocketHandler class. Line 23 - call the static init() method on Spark since we have no other routes defined. GPIO is initialized next, using a singleton GpioHandler (code below). We attach a listener starting on line 36 that ultimately calls a broadcastMessage() method when it handles the button press event. broadcastMessage() notifies all connected clients of the event, passing a message to them.

GpioHandler

Here's the- nothing fancy here:

ChatWebSocketHandler

And the- mostly the same as the demo we're copying:

The view (unchanged from the demo):

And the JavaScript (mildly changed from the demo):

After pushing the code to the Pi and running the app, here's how it responds:

There are tons of possibilities for GPIO with websockets. Real-time temperature charts, sensors providing immediate feedback to the connected web client, etc.

Image by bichnguyenvo from Pixabay