Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const superagent = require('superagent')
- const WebSocket = require('ws')
- var ws = new WebSocket('ws://tenant.cumulocity.com/cep/realtime', {
- perMessageDeflate: false
- })
- // process websocket messages
- ws.on('message', function incoming(data) {
- res = JSON.parse(data)
- if( res[0].channel === '/meta/handshake' ) {
- // process successful handshake
- wsClientId = res[0].clientId
- console.log('wsClientId = ' + wsClientId)
- } else if( res[0].channel === '/meta/subscribe' ) {
- // nothing to do here
- } else {
- // this is where you get the measurements from devices you are subscribed to
- }
- }
- function lookupDevice(serialNumber) {
- superagent.get(`https://tenant.cumulocity.com/identity/externalIds/c8y_Serial/${serialNumber}`)
- .set('Authorization', 'Basic ' + basicAuthBase64)
- .then(function (res) {
- success = res.statusCode
- if (success == 200) {
- devId = res.body.managedObject.id
- return devId
- } else {
- return null
- }
- })
- }
- async function wsHandshake() {
- let request = [{
- "channel": "/meta/handshake",
- "ext": {
- "com.cumulocity.authn": {
- "token": "bGVlLmdyZXl...6cXdlcjQzMjE="
- }
- },
- "version": "1.0",
- "mininumVersion": "1.0beta",
- "supportedConnectionTypes": ["websocket"],
- "advice": {"timeout": 120000, "interval": 30000}
- }]
- ws.send(JSON.stringify(request), function ack(err) {
- if( err )
- console.log('wsHandshake returned error '+err)
- })
- }
- async function wsSubscribe(subscriptionPath) {
- let request = [{
- "channel": "/meta/subscribe",
- "clientId": wsClientId,
- "subscription": subscriptionPath,
- }]
- ws.send(JSON.stringify(request), function ack(err) {
- if( err )
- console.log('wsSubscribe returned error '+err)
- })
- }
- async function wsConnect() {
- let request = [{
- "channel": "/meta/connect",
- "clientId": wsClientId,
- 'connectionType': 'websocket',
- "advice": {"timeout":1200000,"interval":30000},
- }]
- ws.send(JSON.stringify(request), function ack(err) {
- if( err )
- console.log('wsConnect returned error '+err)
- })
- }
- // this is sort of pseudo-code that does not properly handle the asynchronous aspects of the flow
- await wsHandshake()
- let devId = lookupDevice('ABC123')
- await wsSubscribe(`/measurements/${devId}`)
- wsConnect()
Add Comment
Please, Sign In to add comment