The PubNub Data Stream Network (DSN) provides a globally replicated and redundant infrastructure to build and operate realtime applications at Internet scale to millions of users reliably and securely. The PubNub DSN offers powerful features including Pub/Sub, Presence, Storage and Playback, Access Management, and Mobile Push notifications. Ubidots' application enablement platform is now integrated with PubNubs data stream for a fast, reliable, and secure means to transmit data from a device to the cloud and then transform this data into insights for an end-user.
PubNub BLOCKS enables users to quickly and easily spin up microservices in the PubNub Data Stream Network (DSN) without the requirement of any additional supporting infrastructure. By providing the ability to Program the network, BLOCKS simplifies deploying custom, realtime, logic on a reliable, serverless architecture.
With PubNub's BLOCKS, you can now Program the Network for executing a variety of operations with your data streams. For example:
Fork the original (or create a modified version) message to an alternate.
Mutate messages in-flight (e.g. add a new attribute, or modify or delete an existing attribute), altering the final message received by the publish.
Filter messages based on some of their attributes, so that only messages with the right values are passed to subscribing clients.
Redirect message data to other 3rd party services via web service calls.
Aggregate multiple messages and send a single message to subscribing clients.
To get more information about PubNub and their services, please reference PubNub's Documentation.
In this guide you will learn how to manage data between PubNub and Ubidots using the customized PubNub BLOCK. This BLOCK is a customizable microservices that give developers a simple way to add code and deploy features for realtime applications.
Requirements
Introduction
Before starting with PubNub, it is important know some Key Concepts to become familiar BLOCKS and how to use them.
PubNub Channels: A channel represents a virtual path between publishing and subscribing clients in the PubNub Data Stream Network(DSN). The channel is similar to a topic.
Any message will have exactly one channel associated with it. As an example, in order to receive a message published on the channel UbidotsChannel, the client must be subscribed to [at least] the UbidotsChannel (a subscribing client may be subscribed to more than one channel at a time).
A channel doesn't need to be declared, defined, or instantiated in any way, they can be considered unlimited and arbitrary in scope.
You can choose as many, or as few channels as you'd like to use in your app – consider the channel as metadata on the message itself. In BLOCKS, a specific Event Handler (written in Javascript) can be associated with one or more channels. Every message published on a given channel will be processed by its associated event handler (if defined).
API Keysets: The first level of partitioning data between PubNub accounts is via the PubNub API keysets. Keysets are managed by PubNub and created by users from their admin portal.
Each Keyset contains a Publish, Subscribe, and Secret Key. Secret keys are also unique to a keyset, and are used for management functions.
Consider a publish key, subscribe key, and channel name the composite identifier for any message over the PubNub network. In other words, any channel is namespaced by the subscribe and publish keyset used to publish it.
For example, anyone publishing with a PubNub instance defined against keyset-ubidots on channel-ubidots can be received only by subscribers defined against keyset-ubidots on channel-ubidots. To be more clear, consider channel-ubidots' real name in this case to be keyset-ubidots:channel-ubidots… if someone published in a different keyset, but same channel, then the channel is name space by the keyset, and there would be no collision.
Event Handlers: An Event Handler (EH) is the user-defined Javascript code which runs when triggered by a given event, against a given keyset and channel(s) – it is the logic to perform against a message meeting certain criteria.
Event Handler Types: When an EH runs, there are Event Handler types it can be run with respect to:
Before Publish or Fire - If your intent is to operate on, or mutate the message before it has been forwarded on to awaiting subscribers, this is the event handler type to use.
After Publish or Fire - If your intent is not to mutate, but in some way operate on the message after it has been forwarded on to awaiting subscribers, this is the event handler type to use.
After Presence - If your intent is not to mutate, but in some way operate on a Presence event after it has been forwarded on to awaiting subscribers, this is the event handler type to use.
Before Publish or Fire as well as After Publish or Fire events operate against a triggering message. After Presence events operate against a triggering presence event.
BLOCKS: BLOCK (uppercase) refers to the PubNub feature.
The grouping of Event Handlers (EH) that together provide features and functionality for your applications is called a block (regular case).
Now that you get an idea how everything works on PubNub, it is time to start!
Setting up the PubNub BLOCKS
Sign in on the PubNub:
2. Once you signed in to the account, scroll down to the end of the page and create a new app. Assigns a name of your choosing to the app, in this case I decided to call it: "My First App."
3. To create the application you have to press the blue button "CREATE NEW APP." This will be create the app automatically. Select the app to enter into it the below figures:
4. After "creating a new app," another window will appear and be able to create or select a Keyset to better be able to manage data.
In this case I decide to call the Keyset "Ubidots" as you can see on the image below:
NOTE: It’s important know how PubNub works, so prior to beginning I recommend you familiarize yourself with the menu on the left and take a look of the functions within it.
5. Once you select the Keyset called “Ubidots” you will be able to visualize the keys (Publish Key/Subscribe Key/Secret Key).
6. To be able to manage the data through the BLOCKS (publish) or Webhook (subscribe) you have assign the channels where you desire publish and subscribe data functions. To create or visualize the channels, select the last option of the menu called “Debug Console”.
Inside the debug console, create channels to publish and subscribe to the data. Assign the name "ubidots-DataPub" for the published page, and "ubidots-DataSub" for Ubidots subscription based pricing. The client named setted it automatice (if you desire, you can modify it).
Also, pressing the setting icon you will be able to visualize and edit the channel configurations (client, channels, security).
Now that you have the parameters required to manage the data, it is time to know how publish and subscribe the data to/from Ubidots.
Management of Published Data
Firstly, make sure that the BLOCK function is already ENABLED in the Keyset. To verify this, enter to the keyset “Ubidots” and scroll down until you see the BLOCK section. Please note that if the BLOCK is disabled you will not enable it to send data to Ubidots.
Once the PubNub BLOCK is ENABLED, select the BLOCK section of the menu.
Create a new BLOCK called “Ubidots API” and assign a description of your preference:
Once you've created the BLOCKS name and description press the blue button to create new BLOCKS. Then, enter the BLOCKS already created:
2. The following window let you know how the BLOCKS works, and the state of it (running, failed, stopped, or pending). Create the a new BLOCKS by pressing the blue button called "CREATE":
3. Set the following parameteres to the create the Event Handler:
Name: ubidots
Event Handler Type: Before Publish or Fire
Publish Channel: ubidots-DataPub
Please, take a look of the image below to verify if it looks like yours!
If everything looks similar or the same, press "create."
Now, your BLOCK will be created. It is important become familiar with the PubNub environment before starting with a BLOCKS configurations. As you can see on the image below:
The box #1 is the Event Handler Section where you can verify and edit the information of it, also you can verify the status of the block "Stopped"; "Running"; "Pending".
The box #2 is the Code Section where the BLOCKS code is written in JavaScript. In this case, this is where you assign the Ubidots API code.
The box #3 is the Debug Console of the BLOCKS, where you can visualize the management of the data between PubNub and Ubidots.
4. Now it's time to assign the Ubidots API to the BLOCK and test how it works.
in the section below, erase the default BLOCKS and attached the one provided by Ubidots -> Ubidots API.
Once you've pasted the code into the IDE, you will see something like this:
5. Using the Test Payload from the Event Handler section we're going to test the BLOCKS to verify how everything works:
Erase the default Test Payload and assigns the following one to test the Ubidots API:
{
"token": "{Assign_your_Ubidots_token_here}",
"labelDevice": "my-device",
"action": "send-value",
"url": "things.ubidots.com",
"payload": {
"temperature": 26,
"humidity": 59.99,
"pressure": 846.17
}
}
Once you've assigned it into the Test Payload section, and it should look like the image below. Don't forget save the event handler before running the block:
6. Now that everything is ready, press "Start Block" at the upper right part of the page:
To verify if the BLOCKS is running, take a look of the status at the event handler section:
7. Once the BLOCKS is running press the button "PUBLISH" to publish the payload and make the request to Ubidots:
You'll received the response in the debug console(#3) and you will see in the image below:
The message [ { "status_code": 201 } ]
means "Created – Successful request + an item was created". The Ubidots API uses the following response codes; in each case you receive a different response, please reference this link to know where the problem may exist - if one exists.
8. Now that the BLOCK is running and you had a successful request, go to your Ubidots account and verify if the device called "my-device" was created?
Go to the device section to visualize the data received for the device named “my-device”
As you can see the device was created automatically:
9. Click on the Device to visualize the variables created:
Management of Subscribed Data
Now that you are able to publish data to Ubidots, we are going to show you how to Subscribe it to a channel using a Ubidots' WebHook. To do this you will have to set up an Event - Webhook in Ubidots.
Setting up the WebHook
Before starting with the WebHook configurations, you have to create a variable inside the device called "my-device," This variable will be set to post its values to PubNub.
To create the variable, go to my-device, press add variable > default, and assign the name "relay" to the variable:
2. Once the variable is created, go to the Dashboard section to add a control widget which will be tasked with sending the different values to the variable. From the upper right side of the webpage, select add widget then select control > switch > my-device > relay > finish.
As you can see, the control widget is created on your dashboard, and now you can proceed with the WebHook configurations, once you've finished with this go back to the dashboard to change the status of the variable and visualize how the data is posting to PubNub.
3. Now that the variable and widget are created go to the Events tab and press + Add event:
4. Select the device, variable and the conditions for the event, in this case will be "my-devices > relay > less or equal > 0", as you can see on the image below:
Once you finished the previous step, select "WebHook"
Firstly, you have to assign the URL that will let you publish a JSON to a channel via POST. Following the structure below assign the PubNub parameters (Publish Key, Subscribe Key, the subscribe channel, client UUID):
URL example:
To get a better idea on how build the message, please reference to this link.
Once you've the URL, place it into the Webhook settings. Also, set the method POST. Next, build the payload that you want to send, in this case it will be
{"value": {{last_value}}}
.
To finish with the WebHook setting press Add Header and assign the following parameters:
content-type
application/json
After assigns all the parameters required, press "Finish".
In the Events tab you will be able to visualize the event already created; if you wish, event settings can be altered at your leisure.
This event will post a "0" to PubNub every time the variable is less than or equal to 0, so you have to set another event with the same parameters, to be able to send a "1". After this step, you are able to Publish two different values to PubNub from Ubidots in case you need to control a variable.
5. Following the previous steps and using the same parameters to the WebHook settings, create a new event but with the conditions if relay is equal to 1.
6. Once both events exist (0 and 1), you will be able to visualize them in the Events section:
NOTE: You have to use the same Keyset to Publish and Subscribe to/from Ubidots, if you don’t do it this way, the channels will not see to each other because they are publishing on a different Keyset.
7. After setting up the Event-Webhook, change the status of the relay from the dashboard section and visualize the results in the Debug console on PubNub. As you can see you'll be able to visualize the data published from Ubidots to PubNub:
Result
In this guide you learned how to setup a PubNub BLOCKS to the Ubidots API, also you've learned how to post data to PubNub from Ubidots using a WebHook. This will help you with the application that you desire to implement using PubNub. If you wish, you may reference the following article that shows how to manage data between a Electric Imp device, PubNub, and Ubidots.