10 min read
.
on Sep 16, 2020
In this guide to PubNub Presence, we’ll talk about real-time Presence events, show how you can use them with your existing user database, and examine some practical use-cases.

Introduction

Presence, participants, occupants: whatever term you use, it means keeping track of the connected users or devices in your application. 

Presence has enormous value for a broad range of use cases. In a telemedicine application, it enables accurate virtual waiting rooms, which are crucial to efficient staffing and scheduling. In a logistics application, it lets you view activity in real time and log it precisely, ensuring timeliness and efficiency throughout your system. Beyond these examples, presence also has an important role to play in any chat implementation or multi-user application, where seeing who’s online is key. 

In short, presence helps to answer questions like:

“How many users are in my chat channel, and which users are they?”

“How many IoT devices are currently online, and which are transmitting data?” 

Answering these questions comes down to identifying which devices or users are active moment-to-moment and keeping a running tally of the ones that are currently connected. Even though this seems conceptually simple, it can be difficult to orchestrate at scale while maintaining accuracy and reliability. 

PubNub’s Presence API makes it easy to implement features that rely on user occupancy. It lets you keep track of the users or devices connected to your app and trigger logic based on their comings and goings. 

In this article, we will use two examples—a chat app and an IoT system—to explore the basics of PubNub Presence, and show how its simple, yet powerful, methods let you easily track and use the state of user devices within your application. 

How can I use Presence?

Broadly speaking, you can use Presence in two ways: 

  1. Handling events that occur when users come and go. 

  2. Through the use of client-side, on-demand functions that give you the current state of a user or channel. 

This article will focus primarily on exploring the first category: Presence events. We’ll look at what they are, how they function, and some practical ways to use them in your app.


How PubNub tracks and triggers Presence events

Presence lets you update your active user roster the moment changes occur. To do this, PubNub triggers events whenever a user’s occupancy state changes.

From a high-level, the three Presence events to track are: 

  • Join: Issued whenever a device subscribes to a channel. This means a user is “coming online.” 

  • Leave: Issued when a device unsubscribes from a channel. This means a user is “going offline.”

  • Timeout: Issued when a subscriber is not seen on a channel for 320 seconds (a little over five minutes). This interval can be adjusted manually.


Example payloads for Presence events

When triggered, Presence events issue JSON payloads that contain all the information you need to make use of those events. 

So, what’s actually in them? All payloads share a common format, which makes them easy to handle when you need to execute occupancy-based logic. They contain the following key-value pairs:

  • Action: What happened.

  • UUID: The identifier for the device triggering the event.

  • Timestamp: The time, in milliseconds, that the event occurred. You can use this to display “last seen” statuses in your app.

  • Occupancy: The current occupancy of a channel. 

  • Sub_key: Your subkey for this application.

  • Channel: The name of the channel for which the event is issued.

Here's an example of the JSON payload that PubNub will issue when a join event occurs:

{
   "action": "join",
   "uuid": "MatsArduino",
   "timestamp": 1598020519,
   "occupancy": 1,
   "sub_key": "sub-c-abc-123",
   "channel": "Mat"
}

Here’s one for leave: 

{
   "action": "leave",
   "uuid": "MatsArduino",
   "timestamp": 1598020579,
   "occupancy": 0,
   "sub_key": "sub-c-abc-123",
   "channel": "Mat"
}

And one for timeout: 

{
   "action": "timeout",
   "uuid": "MatsArduino",
   "timestamp": 1598020579,
   "occupancy": 0,
   "sub_key": "sub-c-abc-123",
   "channel": "Mat"
}

As you can see, all events share a common format.

When you have Presence enabled, PubNub automatically creates a sister Presence channel for each channel. Clients can subscribe to that Presence channel to directly receive events and handle them locally. But, as we’ll see, there is an even better way to use events.


Handling events with Presence webhooks 

With PubNub, Presence events are triggered when user state changes, but you likely store and maintain user account information in your own database. Naturally, you want an easy and efficient way to update that database to respond to live user activity. For example, you may want to log the duration of user sessions or to trigger logic whenever a user signs on. To do this, you need an easy, timely, and efficient way to use Presence events in your own environment.

Enter Presence webhooks, also called Presence triggers. These let you perform logic, both within your PubNub environment via Functions, and externally, on your own server, whenever a Presence event fires. 

Presence webhooks are the key to getting the most out of using Presence and are the best way to incorporate a full picture of your user activity into your product as a whole. 

So, let’s explore how you can actually use Presence webhooks through a chat example and an IoT example.

Using Presence events in chat apps

In a chat app, you can think of Presence as that “green circle” that changes depending on if users are active or offline.

Mat Chat App Presence

Demonstrating a user roster in a chat application. Notice the green dots on each active user.

Based on the join, leave, and timeout events, let’s break down the three states our chat user could be in and discuss some ways to handle each state for chat.


Coming online (join): 

Say a user has loaded your app, signing on from a cold boot. This could be the user signing into your chat app first thing in the morning to start the working day. 

At this point, PubNub will issue a “join” event. From here, you can:

  1. Use a PubNub Function to publish to an admin channel – such as a supervisor channel—that a user has connected to the chat app. For example, “Terry Crews has come online.”

  2. Send an HTTPS request to your application server to log the timestamp of when the user came online. 

As you can see, webhooks let you make use of Presence information immediately, both within the app, and on your back end.  


Going offline (leave): 

It’s important to know who’s there, but it’s equally important to see who’s not around. For this, our “leave” event comes in handy.

Let’s say that our user has finished for the day. They are closing the app and signing out (when working with web browsers you can actually catch the window close event, also called an unload event). 

Here, a “leave” event is emitted.  With this event, you could:

  1. Use a PubNub function to publish to an admin channel, similar to the join event. For example, “Terry Crews has left channel 99.” 

  2. Log the disconnection via an HTTPS request to your application server. You can then log this as the time when the user was ‘last seen,’ and present that back to other users looking to chat. 


Last Seen Message for Chat User

"Last seen" messages like this can be authored using the timestamp of Presence events.


Timeout (timeout): 

This event issues when a user has exceeded the grace period (also called “timeout interval”) for a connection. This can happen for a few reasons, but timeouts generally mean that either:

  1. A device lost internet connectivity.

  2. The user closed or left your chat abruptly.

If we think of a leave event as a ‘graceful’ disconnection, a timeout is a ‘disgraceful’ closing of the app.

In a chat app, a leave and a timeout will likely have the same effect, so you could bunch the leave and timeout events into the same endpoint and simply note different event types as needed.

Some handling options include: 

  1. Use a PubNub Function to publish a special message to an admin channel, similar to the leave event. For example, “Terry Crews has mysteriously disappeared. Send backup now!” 

  2. Log the timeout event via an HTTPS request to your app server. You could treat leave and timeout events as the same kind of event, especially when writing a ‘last seen’ timestamp to a database. 

chat.png
Engage more users with in-app chat
Chat APIs for experiences that keep users coming back.

Learn More

Overall, in chat, we primarily want to know who’s online at a given moment, and to update both our app and our database when users arrive and leave. The Presence events we covered here give us what we need to accomplish this goal, but Presence has use cases that extend beyond just chat.

Using Presence events for IoT applications and devices

When you deploy fleets of IoT devices into the field, you need to think about how you are going to monitor these devices for online/offline state. It can be incredibly valuable to know when a device is online or off, and whether devices are suddenly dropping their connections. Presence gives you a handy toolset to keep track of this information.

In this example, consider a logistics app that connects to in-vehicle units for geolocation. The transportation industry routinely uses GPS tracking for asset scheduling and management. This example app could use Presence events to log and send alerts when in-vehicle devices turn on, shut down, or unexpectedly stop transmitting location data.

Let’s revisit each event type, and examine how they can be handled in the context of an IoT app. 


Coming online (join)

“Join” events are used to identify when an IoT device has come online and is actively doing something. In the case of our transportation example, this could be when the driver turns on the vehicle and our tracking unit is supplied power from the engine. 

Some options include:

  1. Pass event details to a PubNub Function and drop a pin with a truck’s ID and location onto a digital map used by HQ. 

  2. Pass the event via HTTPS to the transportation API/server and log the timestamp of when the IoT device came online. 


Going offline (leave)

In our example, a “leave” event might show that a vehicle has finished for the day and is in the process of being shut down.

Again, we can label this kind of disconnect event as a ‘graceful’ disconnect, since the client is actively telling PubNub that it’s disconnecting from a channel.

As a result, we can:

  1. Use a PubNub Function to publish a message to a dashboard app with a notification that the vehicle has completed its route.

  2. Make an HTTPS request to our server, logging the “end of session” for this device, possibly to check against a pre-set schedule. 


Timeout (timeout)

In our previous chat example, “leave” and “timeout” look pretty similar. But in IoT, the two events mean very different things.

Our example transportation company might operate in an area of poor network signal. The default timeout interval of 320 seconds may not be adequate, causing excessive timeouts. So, a longer interval value would need to be set. This will give the vehicles enough time to move back into a service network before an alarm is triggered. 

Meanwhile, a different IoT use case, like a home security system, would need a very short timeout interval. This way, we know immediately when our monitoring system has gone down, and we can take swift action to bring it back online.

No matter the use case, to handle a timeout for IoT, you can: 

  1. Pass the event details to a PubNub Function, and use business logic to determine the course of action to take. This can include sending an email, pinging a slack channel, or triggering a mobile push notification

  2. Send an HTTPS request to your server to log the timeout. As with logging chat users, we can also present this information in our app as “time last active.” 

IoT Device Monitoring and Control
Connect and control IoT devices in realtime.

Learn more

Between chat and IoT, Presence event handling has much in common. However, depending on the severity of timeouts for your context, how you handle events may end up looking very different.

How to set up PubNub Presence webhooks

In practice, it’s remarkable simply to connect Presence to your app via webhooks. All you need to do is ensure that Presence is active for the proper keyset and provide a URL for each event trigger you wish to use. 

Here are the four steps you need to follow to activate PubNub Presence and set it up to connect to your server with webhooks:


1. Turn on Presence

If you already have a PubNub account, Presence setup can be found in your PubNub admin portal.

Go to admin.pubnub.com. There, choose an app, then a keyset. On the configuration page for that keyset, you’ll find a Presence section that looks like this:

Presence Options in the PubNub Portal

Presence options in the PubNub Admin Dashboard. Notice the fields for each event's callback URL.

Ensure that the “Presence” switch at the top is set to “On,” and the feature will now be activated for your chosen keyset. 


2. Set up webhooks with callback URLs

To actually implement Presence webhooks, you’ll need to populate the various “Callback” fields found in the admin portal with your desired endpoint. They accept HTTPS URLs, which can point either to your own server or straight to a PubNub Function designed to handle that event.

Presence Callback Tooltip

You can specify the HTTP url for each callback. This can point to your server, or to a PubNub Function.

For more detail on the callbacks available for Presence webhooks, you can always refer back to our documentation.


3. Build your event handlers

If you’re using webhooks to talk to your own server, you’re free to handle presence events in any way you wish. As mentioned above, you can also use PubNub Functions to trigger logic within your PubNub environment whenever Presence events occur.


4. Explore Presence and get in touch

If Presence is something you think your app or service could use, contact our solutions architect team today to learn more about the best ways to use, design, and implement PubNub Presence. We will work with you to develop a unique, robust solution.

Get started with PubNub

More From PubNub