Skip to main content

Getting Started with Pub/Sub

The following examples use methods that are related to the Echolo IoT Service using Topics for communication.

Initiate the Library

First, we must require the NPM and append our API credentials to it. Here we are using the custom SDK from Echolo; you can install it with: npm install echolo

JS
let Echolo = require('echolo')({ appId: 'appId', secret: 'secret', apiKey: 'apiKey' })

Having trouble with this step? - You may not have API credentials or understand what ones are needed to authenticate. Please see Authentication or Getting Started with the REST API.

Start the IoT Client

In order to start the IoT Client, you will have needed to create a Hub. On creation of the hub you will get the hubId and key you will need both of the items now.

JSON
{ "hubId": "myHubId", "key": "xxxx-xxxx-xxxx-xxxxx-xxxxxx-xxxxxxx" }


Now, lets open the Client with our Hub credentials.

JSON
let iot = Echolo.IoT({ "hubId": "myHubId", "key": "xxxx-xxxx-xxxx-xxxxx-xxxxxx-xxxxxxx" })

Listen for events

  • connect

  • message

  • reconnect

  • close

  • error

  • offline

  • end

  • packetsend

  • packetreceive

Example Usage:

JS
iot.on('connect', function() {
    console.log('connected')
})

Publish

A hub can publish messages by using the following command.

JS
let data = { temp: 43, other: 'Some data' }
iot.publish('hub/xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx/myHubId', JSON.stringify(data), (err, data) => {
  console.log("Sent!")
  iot.end()
})

Subscribe

A hub can subscribe to any topic it has access to. You can also subscribe to this topic in your web or mobile based application to get live data from the server.

JS
iot.subscribe('topic/path/and/name')

Close the Connection

Close the IoT connection or it will hang open. After closing no events will fire and any messages sent during this time will not be seen.

JS
iot.end()
JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.