Last active
March 11, 2019 21:22
-
-
Save dirkvm/3f7ea380b8d2dd675aa96d78c131fb0b to your computer and use it in GitHub Desktop.
websocket test, copy to examples/streamws.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const teslams = require('../teslams.js'); | |
const WebSocket = require('ws'); | |
const util = require('util'); | |
var argv = require('optimist') | |
.usage('Usage: $0 -u <username> -p <password>') | |
.alias('u', 'username') | |
.describe('u', 'Teslamotors.com login') | |
.alias('p', 'password') | |
.describe('p', 'Teslamotors.com password') | |
.alias('?', 'help') | |
.describe('?', 'Print usage information'); | |
// get credentials either from command line or config.json in ~/.teslams/config.js | |
const creds = require('./config.js').config(argv); | |
argv = argv.argv; | |
if (argv.help == true) { | |
console.log( 'Usage: streamws.js -u <username> -p <password>'); | |
process.exit(1); | |
} | |
teslams.vehicles( { email: creds.username, password: creds.password, token: creds.token }, function (response) { | |
console.log(util.inspect(response)); | |
let ws = new WebSocket('wss://streaming.vn.teslamotors.com/streaming/', { | |
followRedirects: true, | |
}); | |
ws.on('open', () => { | |
const msg = { | |
msg_type: 'data:subscribe', | |
token: new Buffer.from(creds.username + ':' + response.tokens[0]).toString('base64'), | |
value: teslams.stream_columns.join(','), | |
tag: response.vehicle_id.toString(), | |
}; | |
ws.send(JSON.stringify(msg)); | |
}); | |
ws.on('close', (code, reason) => { | |
util.log('websocket closed, code=' + code + ', reason=' + reason); | |
}); | |
ws.on('error', (err) => { | |
util.log('websocket error: ' + err); | |
}); | |
ws.on('message', (data) => { | |
const msg = JSON.parse(data); | |
util.log(msg); | |
}); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment