Page 1 of 1

Script (NodeJS): Chromecast status to virtual device

Posted: Tuesday 07 June 2016 18:18
by dhanjel
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

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

Posted: Friday 17 June 2016 10:47
by Heisenberg
Thanks for the script. Is there a way to automatically start a (youtube) stream with the virtual switch?

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

Posted: Monday 04 July 2016 16:29
by rednas
Would it be possible to add this to a future version of Domoticz, like Logitech Media Server & Kodi are included?

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

Posted: Monday 04 July 2016 19:08
by dhanjel
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)

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

Posted: Saturday 26 November 2016 15:17
by DarkFoxDK
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();
}

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

Posted: Saturday 03 December 2016 22:43
by meanmrgreen
Sorry for this but im not used to linux and such.

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

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

Posted: Sunday 11 December 2016 18:41
by turnhob
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.

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

Posted: Friday 16 December 2016 18:59
by turnhob
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?

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

Posted: Tuesday 03 January 2017 10:17
by meanmrgreen
how did you fix it?

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

Posted: Sunday 05 February 2017 1:04
by chrisfraser05
This is interesting. I'll have to try this tomorrow

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

Posted: Thursday 28 June 2018 14:33
by DewGew
I updated my rpi to stretch and now my script is not working. I reinstalled node.js and underscore, require and nodecastor. Still not working.
Anyone with idea who can help me??

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

Posted: Friday 29 June 2018 9:24
by freijn
Perhaps show us the error you are hitting?

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

Posted: Monday 02 July 2018 14:56
by DewGew
freijn wrote: Friday 29 June 2018 9:24 Perhaps show us the error you are hitting?
I got no erros ..