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
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.
{ "hubId": "myHubId", "key": "xxxx-xxxx-xxxx-xxxxx-xxxxxx-xxxxxxx" }
Now, lets open the Client with our Hub credentials.
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:
iot.on('connect', function() {
console.log('connected')
})
Publish
A hub can publish messages by using the following command.
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.
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.
iot.end()