# `EHLS.PubSub`
[🔗](https://github.com/elixir-hls/elixir-hls/blob/v0.1.0/lib/ehls/pubsub.ex#L1)

Topics: what instances publish and processes or other instances receive, as `Phoenix.PubSub`, written with the module
as it is.

In a `definstance`:

- `x |> EHLS.PubSub.broadcast(topic)` ends a pipe: each element is an event of `topic`, one value up to 32 bits, of one
  type for all its publishers;
- `EHLS.PubSub.subscribe(topic)` starts one: the events of `topic` as a stream, in the FPGA, from any instance of the
  module.

```elixir
definstance presses do
  changes(:button0, :rising) |> transform(0, &count/2) |> EHLS.PubSub.broadcast(:presses)
end

definstance lit do
  EHLS.PubSub.subscribe(:presses) |> map(&low_bit/1) |> pin_out(:led0)
end
```

On the CPU a process receives a topic's events as messages with `subscribe/2` (below). `EHLS.Pipeline`, "Events",
has the rest: what each event is, how the circuit hands them over, the topics of a module.

# `subscribe`

Receive the events of `topic`: the elements an instance gives to `EHLS.PubSub.broadcast(topic)` (`EHLS.Pipeline`,
"Events"), each as a message `{topic, value}` to this process. Any number of processes can subscribe
to a topic (up to 4 at once today). Returns `:ok`, or `{:error, :full}`. Needs the runtime backend (on
the board); without one it raises.

    EHLS.PubSub.subscribe(:presses)

    def handle_info({:presses, n}, st), do: ...

`opts`, as a socket's:

  * `active: true` (every event, the default), `:once` (the next one) or `n` (the next n): the events
    after them are kept (16 at most) until this process subscribes again, and come then, oldest first; a
    `{:ehls_lost, topic, n}` before them says how many did not fit.
  * `timestamps: true`: `{topic, value, t}`, t when the event came in the FPGA, in microseconds on the
    clock of `:erlang.monotonic_time(:microsecond)` (the event's time in the FPGA, not its message's).

Subscribing again changes the options, and gives what was kept.

    EHLS.PubSub.subscribe(:presses, active: :once, timestamps: true)

    def handle_info({:presses, n, t}, st) do
      EHLS.PubSub.subscribe(:presses, active: :once, timestamps: true)    # the next one
      ...

# `unsubscribe`

No more events of `topic` for this process.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
