Advertisement
Guest User

Untitled

a guest
May 27th, 2017
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. var cfenv = require( 'cfenv' );
  2. var express = require( 'express' );
  3. var jsonfile = require( 'jsonfile' );
  4. var parser = require( 'body-parser' );
  5. var Particle = require( 'particle-api-js' );
  6. var request = require( 'request' );
  7.  
  8. // External configuration
  9. config = jsonfile.readFileSync( __dirname + '/config.json' );
  10.  
  11. // Application
  12. var app = express();
  13.  
  14. // Middleware
  15. app.use( parser.json() );
  16. app.use( parser.urlencoded( {
  17. extended: false
  18. } ) );
  19.  
  20. // Per-request actions
  21. app.use( function( req, res, next ) {
  22. // Configuration
  23. req.config = config;
  24.  
  25. // Just keep swimming
  26. next();
  27. } );
  28.  
  29. // Static for main files
  30. app.use( '/', express.static( 'public' ) );
  31.  
  32. // Bluemix
  33. var env = cfenv.getAppEnv();
  34.  
  35. // Listen
  36. var server = app.listen( env.port, env.bind, function() {
  37. // Debug
  38. console.log( 'Started on: ' + env.port );
  39. } );
  40.  
  41. // Socket
  42. var io = require( 'socket.io' )( server );
  43.  
  44. // Paricle
  45. var particle = new Particle();
  46.  
  47. // Login
  48. particle.login( {
  49. username: config.particle_username,
  50. password: config.particle_password
  51. } ).then(
  52. function( data ) {
  53. // Listen to event stream
  54. // Specific to my devices
  55. // Can use device ID if known
  56. particle.getEventStream( {
  57. auth: data.body.access_token,
  58. deviceId: 'mine',
  59. } ).then( function( stream ) {
  60. // Stream event arrived
  61. stream.on( 'event', function( evt ) {
  62. // Look for location-specific event
  63. if( evt.name.startsWith( 'hook-response/' + config.event_name ) ) {
  64. // Parse out location details
  65. var parts = evt.data.split( ',' );
  66.  
  67. // Assemble message
  68. var msg = JSON.stringify( {
  69. id: evt.name.split( '/' )[2],
  70. published: evt.published_at,
  71. position: {
  72. lat: parseFloat( parts[0] ),
  73. lng: parseFloat( parts[1] ),
  74. },
  75. accuracy: parseInt( parts[2] )
  76. } );
  77.  
  78. // Send to clients
  79. io.emit( 'location', msg );
  80. }
  81. } );
  82. } );
  83. },
  84. function( err ) {
  85. console.log( err );
  86. }
  87. );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement