← Cookbook Web servers Intermediate · Pooka 0.5.0

Keep sensor state over WebSockets

Build a small temperature monitor. A Pooka actor holds the latest reading and serves it to every connected client.

You will use

  • whiplash for the WebSocket listener
  • An actor for shared state
  • A class for an immutable reading
  • match and ? for command parsing

The whole program

src/main.pooka
module main

import pooka/http
import pooka/int
import pooka/otp
import pooka/string
import whiplash
import whiplash/websocket as ws
import whiplash/websocket/route

class Reading(celsius: Int, samples: Int)

actor Thermometer {
  var celsius: Int
  var samples: Int

  new(initial: Int) {
    self.celsius = initial
    self.samples = 0
  }

  be sample(value: Int) {
    celsius = value
    samples += 1
  }

  reading() -> Reading {
    Reading(celsius, samples)
  }
}

parse_command(text: String) -> Result(Option(Int), String) {
  match string.split(string.trim(text), " ") {
    ["read"] -> Ok(None)
    ["sample", value] -> {
      let celsius = _temperature(value)?
      Ok(Some(celsius))
    }
    _ -> Error("use read or sample <celsius>")
  }
}

_temperature(value: String) -> Result(Int, String) {
  match int.parse(value) {
    Ok(celsius) if celsius >= -40 && celsius <= 85 -> Ok(celsius)
    _ -> Error("temperature must be a whole number from -40 to 85")
  }
}

reply(sensor: Thermometer, text: String) -> String {
  match parse_command(text) {
    Error(reason) -> "error: " + reason
    Ok(command) -> {
      match command {
        Some(value) -> sensor.sample(value)
        None -> Nil
      }
      let reading = sensor.reading()
      int.to_string(reading.celsius) + " C | samples: " + int.to_string(
        reading.samples
      )
    }
  }
}

on_message(sensor: Thermometer, message: ws.Message) -> List(ws.Message) {
  match message {
    ws.TextMessage(text) -> [ws.TextMessage(reply(sensor, text))]
    _ -> []
  }
}

main() {
  let sensor = Thermometer(21)
  let app = whiplash.Application(
    fn(_) { http.text(200, "Connect a WebSocket to /sensors") },
    fn(request) {
      match request.path {
        "/sensors" -> Some(
          route.Route(fn(message) { on_message(sensor, message) }, None, False)
        )
        _ -> None
      }
    }
  )
  let assert Ok(_) = whiplash.start_application(whiplash.options(8080), app)
  otp.sleep_forever()
}
test/sensors.spec.pooka
module sensors_test

import main
import whiplash/websocket as ws

test "a reading sees the preceding sample" {
  let sensor = main.Thermometer(21)
  assert main.reply(sensor, "read") == "21 C | samples: 0"
  assert main.reply(sensor, "sample 24") == "24 C | samples: 1"
  assert main.reply(sensor, "read") == "24 C | samples: 1"
}

test "invalid input leaves the actor unchanged" {
  let sensor = main.Thermometer(21)
  assert main.reply(sensor, "sample 90") ==
  "error: temperature must be a whole number from -40 to 85"
  assert main.reply(sensor, "battery") == "error: use read or sample <celsius>"
  assert main.reply(sensor, "read") == "21 C | samples: 0"
}

test "only text frames reach the command parser" {
  let sensor = main.Thermometer(21)
  assert main.on_message(sensor, ws.BinaryMessage(<<"read":utf8>>)) == []
  assert main.on_message(sensor, ws.TextMessage("read")) == [
    ws.TextMessage("21 C | samples: 0")
  ]
}

Set up the project

pooka new websocket_sensors
cd websocket_sensors
pooka add whiplash
pooka add pooka_http
pooka add pooka_otp

Replace src/main.pooka with the program above. Add the test to test/sensors.spec.pooka and run pooka test.

Read a temperature

Run pooka run, open http://127.0.0.1:8080/, and paste this into the browser console:

const sensor = new WebSocket("ws://127.0.0.1:8080/sensors");
sensor.onmessage = ({ data }) => console.log(data);
sensor.onopen = () => {
  sensor.send("read");
  sensor.send("sample 24");
  sensor.send("sample 90");
  sensor.send("read");
};
21 C | samples: 0
24 C | samples: 1
error: temperature must be a whole number from -40 to 85
24 C | samples: 1

Open another tab and send read to see the same reading. The actor is created once, before the listener starts. Each WebSocket callback closes over that same actor.

Follow a message

The parser matches the shape of the command. The ? operator returns a validation error before a rejected sample can reach the actor. A valid sample sends an asynchronous be message. The following reading() call from the same handler comes after it in the actor's mailbox. It returns an immutable Reading with the latest temperature and sample count.

All tabs share the reading, and another client's sample can arrive between the update and the read. The example uses simulated input on a local listener, so you can try the state changes without connecting any equipment.

Whiplash WebSocket guide

If you already have Erlang message logic, see Bridge a WebSocket to Erlang.