Skip to content

Commit

Permalink
Add support for "specialized" sockets.
Browse files Browse the repository at this point in the history
Thiese can be use for pointer events and button pressing,  and possibly more.
  • Loading branch information
forty2 committed Jun 29, 2016
1 parent 1dfc226 commit 2c593b6
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
60 changes: 60 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,26 @@ var WebSocketClient = require('websocket').client; // for communication with TV
var EventEmitter = require('events').EventEmitter;
var util = require('util');

var SpecializedSocket = function (ws) {
this.send = function(type, payload) {
payload = payload || {};
// the message should be key:value pairs, one per line,
// with an extra blank line to terminate.
var message =
Object.keys(payload)
.reduce(function(acc, k) {
return acc.concat([k + ':' + payload[k]]);
}, ['type:' + type])
.join('\n') + '\n\n';

ws.send(message);
};

this.close = function() {
ws.close();
};
};

var LGTV = function (config) {
if (!(this instanceof LGTV)) return new LGTV(config);
var that = this;
Expand Down Expand Up @@ -41,6 +61,8 @@ var LGTV = function (config) {
var isPaired = false;
var autoReconnect = config.reconnect;

var specializedSockets = {};

var callbacks = {};
var cidCount = 0;
var cidPrefix = ('0000000' + (Math.floor(Math.random() * 0xFFFFFFFF).toString(16))).slice(-8);
Expand Down Expand Up @@ -200,6 +222,40 @@ var LGTV = function (config) {
connection.send(json);
};

this.getSocket = function(url, cb) {
if (specializedSockets[url]) {
cb(null, specializedSockets[url]);
return;
}

that.request(url, function(err, data) {
if (err) {
cb(err);
return;
}

var special = new WebSocketClient();
special
.on('connect', function(conn) {
conn
.on('error', function(error) {
that.emit('error', error);
})
.on('close', function() {
delete specializedSockets[url];
});

specializedSockets[url] = new SpecializedSocket(conn);
cb(null, specializedSockets[url]);
})
.on('connectFailed', function(error) {
that.emit('error', error);
})

special.connect(data.socketPath);
});
};

/**
* Connect to TV using a websocket url (eg "ws://192.168.0.100:3000")
*
Expand All @@ -219,6 +275,10 @@ var LGTV = function (config) {
this.disconnect = function () {
connection.close();
autoReconnect = false;

Object.keys(specializedSockets).forEach(
function (k) { specializedSockets[k].close(); }
);
};

setTimeout(function () {
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "lgtv2",
"version": "1.0.3",
"version": "1.1.0",
"description": "Simple module to remote control LG WebOS smart TVs",
"main": "index.js",
"scripts": {
Expand Down

0 comments on commit 2c593b6

Please sign in to comment.