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:
init()method on Spark since we have no other routes defined.
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- nothing fancy here:And the
ChatWebSocketHandler- mostly the same as the demo we're copying:
There are tons of possibilities for GPIO with websockets. Real-time temperature charts, sensors providing immediate feedback to the connected web client, etc.