Script (NodeJS): Chromecast status to virtual device

Post Reply
dhanjel
Posts: 132
Joined: Tuesday 05 August 2014 22:16
Target OS: Linux
Domoticz version: 3.5146
Location: Sweden
Contact:

Script (NodeJS): Chromecast status to virtual device

Post by dhanjel » Tuesday 07 June 2016 18:18

This is a simple script to get information pushed into Domoticz when chromecasts changes state to/from playing and idle.
(Just a basic script, it is possible to control chromecasts as well through https://www.npmjs.com/package/nodecastor).

My plan is to adjust the light on RGB-lists behind the tv:s depending on the source.

Create a virtual device (switch) for each Chromecast you want status on.

Install nodejs (preferably with pm2 in order to have the service running at startup).
Install the required libraries (npm install.. ): underscore, nodecastor, request.

Save this script and start it in node.js (after configuration):

Code: Select all

var _ = require("underscore");
var nodecastor = require('nodecastor');
var request = require('request');

//Settings
var domoticzIp = "192.168.1.200";
var domoticzPort = 8080;
var playerLookup = [
	{ Name: 'Sovrum', Id: 178},
	{ Name: 'Vardagsrum', Id: 179},
	{ Name: 'Allrum', Id: 180},
	{ Name: 'Matsal', Id: 181}
];


function deviceIsPlaying(deviceStatus) {
	
	if (deviceStatus.applications === undefined)
		return false;
	
	var match = _.find(deviceStatus.applications, function(item, index) {
		if (item.displayName != 'Backdrop')
			return true;
	});
	
	return !(match === undefined);
}

function lookupDeviceId(deviceName) {
	var match = _.find(playerLookup, function(item, index) {
		if (item.Name === deviceName)
			return true;
	});

	return (match === undefined) ? -1 : match.Id;
}

function updateDomoticz(playerId, isPlaying) {
	if (playerId < 0)
		return;

	var url = "http://" + domoticzIp + ":"  + domoticzPort + 
				"/json.htm?type=command&param=switchlight&idx=" + playerId + 
				"&switchcmd=" + (isPlaying ? "On" : "Off");
	request(url, function (error, response, body) {
		if (!error && response.statusCode == 200) {
			console.log(body)
		}
	});
}

function localServer() {
	//Chromecast scanner
	nodecastor.scan()
	  .on('online', function(d) {
		var playerName = d.friendlyName;
		var playerId = lookupDeviceId(playerName);
		d.on('connect', function() {
		  d.status(function(err, s) {			
			if (!err) {
				var devicePlaying = deviceIsPlaying(s);
				d.on('status', function(status) {
					var devicePlaying = deviceIsPlaying(s);			
				});
				updateDomoticz(playerId, devicePlaying);
			}
		  });
		});
	  })
	  .on('offline', function(d) {
		var playerName = d.friendlyName;
		var playerId = lookupDeviceId(playerName);
		updateDomoticz(playerId, devicePlaying);
	  })
	  .start();  
}

console.log("Starting server");
localServer();
The values under //Settings needs to be adapted.
IP and port to Domoticz and an array with mapping from chromecast name to virtual device id in Domoticz (can be found on http://domoticz_ip:domoticz_port/json.htm?type=devices.

Image

Heisenberg
Posts: 286
Joined: Monday 27 January 2014 15:12
Target OS: Raspberry Pi
Domoticz version:
Location: Netherlands
Contact:

Re: Script (NodeJS): Chromecast status to virtual device

Post by Heisenberg » Friday 17 June 2016 10:47

Thanks for the script. Is there a way to automatically start a (youtube) stream with the virtual switch?
Raspberry Pi Type B
Raspberry Pi Type B2
RFXCOMtrx433e

rednas
Posts: 123
Joined: Tuesday 20 October 2015 12:23
Target OS: Raspberry Pi
Domoticz version:
Location: Netherlands
Contact:

Re: Script (NodeJS): Chromecast status to virtual device

Post by rednas » Monday 04 July 2016 16:29

Would it be possible to add this to a future version of Domoticz, like Logitech Media Server & Kodi are included?

dhanjel
Posts: 132
Joined: Tuesday 05 August 2014 22:16
Target OS: Linux
Domoticz version: 3.5146
Location: Sweden
Contact:

Re: Script (NodeJS): Chromecast status to virtual device

Post by dhanjel » Monday 04 July 2016 19:08

This is my old play script for chromecast audio, I have not yet adapted it and modernize it. But could be something to start with.

Code: Select all

var http = require('http');
var chromecastjs = require('chromecast-js')

var port = 8001;

var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  
  var url = require('url');
  var url_parts = url.parse(request.url, true);
  var query = url_parts.query;
  
  if (query.action === undefined) {
	  response.end();	  
  }
  else {
	console.log("Incoming request.");
	console.log("Device: " + query.device);
	console.log("Action: " + query.action);	
  
	var browser = new chromecastjs.Browser();
	
	browser.on('deviceOn', function(device){
		
		if (device.config.name == query.device) {
			
			console.log("Connected to target device, " + query.device + ".");
		
			device.connect();
			device.on('connected', function(){
				
				if (query.action === "play") {
					
					if (query.volume !== undefined) {
						var targetVolume = (query.volume === undefined ? 0.2 : query.volume);
					
						device.setVolume(targetVolume, function() {
							console.log ("Volume set to " + (targetVolume*100) + "%.");
							
							device.play(query.stream, 0, function(){
								console.log('Playing stream: ' + query.stream);
								response.end();
							});	
						});
					} else  {
						device.play(query.stream, 0, function(){
								console.log('Playing stream: ' + query.stream);
								response.end();
							});	
					}
						
				} else if (query.action === "stop") {
					
					device.stop(function(){
						console.log('Stopped!')						
						response.end();
					});
				}
			});			
		}
	});
  }
  
});

server.listen(port);
console.log("Server started on port " + port)

DarkFoxDK
Posts: 30
Joined: Saturday 02 January 2016 3:22
Target OS: Raspberry Pi
Domoticz version: beta
Contact:

Re: Script (NodeJS): Chromecast status to virtual device

Post by DarkFoxDK » Saturday 26 November 2016 16:17

I'm not sure how your code was working before. For me it would only update devices when starting the script.

I've modified the localServer function to make it work correctly:

Code: Select all

function localServer() {
  //Chromecast scanner
  nodecastor.scan()
    .on('online', function(d) {
      var playerName = d.friendlyName;
      var playerId = lookupDeviceId(playerName);
      d.on('connect', function() {
        d.status(function(err, s) {
          if (!err) {
            var devicePlaying = deviceIsPlaying(s);
            updateDomoticz(playerId, devicePlaying);
          }
        });
      });
      d.on('status', function() {
        d.status(function(err, s) {
          if (!err) {
            var devicePlaying = deviceIsPlaying(s);
            updateDomoticz(playerId, devicePlaying);
          }
        });
      });
    })
    .on('offline', function(d) {
      var playerName = d.friendlyName;
      var playerId = lookupDeviceId(playerName);
      updateDomoticz(playerId, devicePlaying);
    })
    .start();
}

meanmrgreen
Posts: 9
Joined: Sunday 13 November 2016 12:05
Target OS: -
Domoticz version:
Contact:

Re: Script (NodeJS): Chromecast status to virtual device

Post by meanmrgreen » Saturday 03 December 2016 23:43

Sorry for this but im not used to linux and such.

HOW do i install this thing step by step on a raspberry 3?

turnhob
Posts: 6
Joined: Sunday 11 December 2016 10:44
Target OS: Raspberry Pi
Domoticz version:
Contact:

Re: Script (NodeJS): Chromecast status to virtual device

Post by turnhob » Sunday 11 December 2016 19:41

Any help would be nice.
I changed the settings and when I start it on my raspberry it says "Starting Server".
But nothing seems to happen after that.
None of my chromecast switches change status when i play content from youtube.

Im a little bit of a newbie so any help (or directions) would be nice.

turnhob
Posts: 6
Joined: Sunday 11 December 2016 10:44
Target OS: Raspberry Pi
Domoticz version:
Contact:

Re: Script (NodeJS): Chromecast status to virtual device

Post by turnhob » Friday 16 December 2016 19:59

turnhob wrote:Any help would be nice.
I changed the settings and when I start it on my raspberry it says "Starting Server".
But nothing seems to happen after that.
None of my chromecast switches change status when i play content from youtube.

Im a little bit of a newbie so any help (or directions) would be nice.
I fixed it myself. Thank you for the script.
Is it possible to see if its playing or is it only possible to see if an app is loaded on the Chromecast device?

meanmrgreen
Posts: 9
Joined: Sunday 13 November 2016 12:05
Target OS: -
Domoticz version:
Contact:

Re: Script (NodeJS): Chromecast status to virtual device

Post by meanmrgreen » Tuesday 03 January 2017 11:17

how did you fix it?

chrisfraser05
Posts: 33
Joined: Sunday 08 January 2017 19:59
Target OS: Windows
Domoticz version:
Contact:

Re: Script (NodeJS): Chromecast status to virtual device

Post by chrisfraser05 » Sunday 05 February 2017 2:04

This is interesting. I'll have to try this tomorrow

Post Reply

Who is online

Users browsing this forum: No registered users and 0 guests