You will use
whiplashfor the WebSocket listener and route- A Pooka
externaldeclaration for an Erlang function - A browser to send a message
The whole program
module main
import pooka/http
import pooka/list
import pooka/otp
import whiplash
import whiplash/websocket as ws
import whiplash/websocket/route
external SensorProtocol from erlang "sensor_protocol" {
handle_text(command: String) -> List(String)
}
on_message(message: ws.Message) -> List(ws.Message) {
match message {
ws.TextMessage(command) ->
list.map(SensorProtocol.handle_text(command), fn(reply) {
ws.TextMessage(reply)
})
_ -> []
}
}
main() {
let app = whiplash.Application(
fn(_) { http.text(404, "Not found") },
fn(request) {
match request.path {
"/sensors" -> Some(route.Route(on_message, None, False))
_ -> None
}
}
)
let assert Ok(_) = whiplash.start_application(whiplash.options(8080), app)
otp.sleep_forever()
}
Set up the project
pooka new sensor_bridge
cd sensor_bridge
pooka add whiplash
pooka add pooka_http
pooka add pooka_otp
mkdir -p ffi
Replace src/main.pooka with the program above. Put this small stand-in for an
existing sensor handler in ffi/sensor_protocol.erl:
-module(sensor_protocol).
-export([handle_text/1]).
handle_text(<<"temperature">>) ->
[<<"temperature: 21.5 C">>];
handle_text(_) ->
[<<"error: unknown command">>].
Pooka builds the Erlang module alongside the app. A Pooka String crosses the
boundary as a UTF-8 binary. The Erlang function returns a list of UTF-8 binaries,
and the adapter wraps each one in a WebSocket text message.
Ask for a reading
Run pooka run. Open the browser at http://127.0.0.1:8080/ and use its
developer console. The page itself returns 404, and the WebSocket listens at
/sensors.
const socket = new WebSocket("ws://127.0.0.1:8080/sensors");
socket.onmessage = ({ data }) => console.log(data);
socket.onopen = () => {
socket.send("temperature");
socket.send("battery");
};
temperature: 21.5 C
error: unknown command
Reuse your handler
If your existing handler is a Cowboy module, pull the application logic out
of websocket_handle/2 into an ordinary Erlang function. Both Cowboy and
Whiplash can call that function. For a stateful application, let your existing
Erlang process (such as a gen_server) own the state and have the shared
function call it. Whiplash supplies its own connection lifecycle and callback
contract.
This sample binds locally and reads a fixed value. Before connecting it to real equipment, decide which clients may read telemetry and which may send commands. See the Whiplash WebSocket guide or Call Pooka from Erlang if you want to keep your Erlang listener and call Pooka instead.
For a new project with sensor state owned by a Pooka actor, see Keep sensor state over WebSockets.