Websockets Example

The map below displays the locations of nodes in Chicago. For each of the nodes, we setup a websocket that connects to the API and listens for new observation data to be pushed. The data is refreshed every 5 minutes from the source -- it's a slower process than what most people use websockets for, but if you want to passively consume observation data as it's made available then this is a great way to do it.

Sensor Value UOM
Click on a node marker to track its latest observaiton data.

Example Details

The Latest Observations websocket is available at /socket/websocket. The socket then can subscribe to node topics following the pattern nodes:${vsn} -- latest observations are tracked per node.

There are two responses that you can anticipate when connecting: 'ok' or 'error'. Both will include a JSON payload. In the case of a good connection, the payload will be the stored latest for the node you're watching. In the case of an error response, it will be some details about why the connection failed.

The event that notifies the client of new observation data is called latest and its JSON payload consists of a sing observations key. The value is an array of objects that are exactly the same as the observations API data without the node VSN (because that would be redundant and wasteful).

As a really basic example of connecting to the socket and listening for changes:

import socket from 'phoenix-socket'

let topic = 'nodes:004';
let channel = socket.channel(topic, {});

channel.join()
  .receive('ok', resp => { console.log('successfully joined channel', resp); })
  .receive('error', resp => { console.log('error joining channel', resp); });

channel.on('latest', observations => {
  console.log('new observations', observations);
});