Let’s imagine you’ve got:

  • Some miniature tracking equipment
  • A load of bees
  • Patience

You could use up that patience by attaching a tracker to each bee. That way you can tabs on all your bees and see where they’re hanging out. Super neat!

This will generate some great data; you’ll be able to see the path that each of your bees take as they go about their business. I don’t have access to any real bees, so I’ve made some fake ones so we’ve got some data to play with.

bees 1-5 plotted

Your next step could be building a web app that allows you to access this data remotely, letting you see your bees while you’re out and about. This is where pusher comes in; each bee could have it’s own channel and you could trigger an event on that channel when you observe the bee move. This means that users can track a particular bee, and would only receive updates when that bee moves.

Though here’s the thing; you’ve got a load of bees. Sending the position of every bee is going to result in a lot of requests to pusher, even if no-one is actually subscribed for updates.

This is where our web hooks are super handy.

With web hooks, we can notify you when a channel becomes occupied (i.e. there is at least one subscriber), and when it becomes vacated. Combined with our rest api, it’s possible to maintain a list of channels that are in use.

Here’s an example in Node.JS (JavaScript is the most popular language for people who like bees):

const pusher = new Pusher({/* … */})

// create a set for storing channels
const channels = new Set()

// get initial set of channels
pusher.get(
  { path: '/channels', params: {} }, 
  (err, req, res) => {
    const json = JSON.parse(res.body)

    Object.keys(json.channels)
      .forEach( c => channels.add(c) )

  }
)


// update based on WebHook
const webhook = pusher.webhook(request)
webhook.getEvents().forEach( e => {

  if(e.name == 'channel_occupied')
    channels.add(e.channel)

  if(e.name == 'channel_vacated')
    channels.delete(e.channel)

})

For a full example with hook validation and the a full Node/express app, check out the bee-tracker github repo.

To link this with your pusher app:

  1. Make your WebHook endpoint to be publicly accessible (ngrok can be very handy for development).
  2. Register the callback on the pusher dashboard

Adding a WebHook

And you’re all done!

You can watch my virtual bees online at bee-tracker.herokuapp.com.

tracker

(pro tip, open as many windows as you want to see the bees in sync)

The full source is online at pusher-community/bee-tracker. Check it out and ping me at @benjaminbenben if you’ve got any comments, questions, or bee facts.

Links:

Note: as well as bees – this also works for cars, people, chat messages, blog post updates, aeroplanes, traffic alerts, delivery notifications, transit vans, server stats, bikes, cats, parcels & other things.