Guest User

Untitled

a guest
Jun 20th, 2018
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. const superagent = require('superagent')
  2. const WebSocket = require('ws')
  3. var ws = new WebSocket('ws://tenant.cumulocity.com/cep/realtime', {
  4. perMessageDeflate: false
  5. })
  6.  
  7. // process websocket messages
  8. ws.on('message', function incoming(data) {
  9. res = JSON.parse(data)
  10. if( res[0].channel === '/meta/handshake' ) {
  11. // process successful handshake
  12. wsClientId = res[0].clientId
  13. console.log('wsClientId = ' + wsClientId)
  14. } else if( res[0].channel === '/meta/subscribe' ) {
  15. // nothing to do here
  16. } else {
  17. // this is where you get the measurements from devices you are subscribed to
  18. }
  19. }
  20.  
  21.  
  22. function lookupDevice(serialNumber) {
  23. superagent.get(`https://tenant.cumulocity.com/identity/externalIds/c8y_Serial/${serialNumber}`)
  24. .set('Authorization', 'Basic ' + basicAuthBase64)
  25. .then(function (res) {
  26. success = res.statusCode
  27. if (success == 200) {
  28. devId = res.body.managedObject.id
  29. return devId
  30. } else {
  31. return null
  32. }
  33. })
  34. }
  35.  
  36. async function wsHandshake() {
  37. let request = [{
  38. "channel": "/meta/handshake",
  39. "ext": {
  40. "com.cumulocity.authn": {
  41. "token": "bGVlLmdyZXl...6cXdlcjQzMjE="
  42. }
  43. },
  44. "version": "1.0",
  45. "mininumVersion": "1.0beta",
  46. "supportedConnectionTypes": ["websocket"],
  47. "advice": {"timeout": 120000, "interval": 30000}
  48. }]
  49. ws.send(JSON.stringify(request), function ack(err) {
  50. if( err )
  51. console.log('wsHandshake returned error '+err)
  52. })
  53. }
  54.  
  55. async function wsSubscribe(subscriptionPath) {
  56. let request = [{
  57. "channel": "/meta/subscribe",
  58. "clientId": wsClientId,
  59. "subscription": subscriptionPath,
  60. }]
  61. ws.send(JSON.stringify(request), function ack(err) {
  62. if( err )
  63. console.log('wsSubscribe returned error '+err)
  64. })
  65. }
  66.  
  67. async function wsConnect() {
  68. let request = [{
  69. "channel": "/meta/connect",
  70. "clientId": wsClientId,
  71. 'connectionType': 'websocket',
  72. "advice": {"timeout":1200000,"interval":30000},
  73. }]
  74. ws.send(JSON.stringify(request), function ack(err) {
  75. if( err )
  76. console.log('wsConnect returned error '+err)
  77. })
  78. }
  79.  
  80. // this is sort of pseudo-code that does not properly handle the asynchronous aspects of the flow
  81. await wsHandshake()
  82. let devId = lookupDevice('ABC123')
  83. await wsSubscribe(`/measurements/${devId}`)
  84. wsConnect()
Add Comment
Please, Sign In to add comment