Script (NodeJS): Chromecast status to virtual device

Moderator: leecollings

Post Reply
dhanjel
Posts: 102
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 »

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: 135
Joined: Monday 27 January 2014 14:12
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: Netherlands
Contact:

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

Post by Heisenberg »

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: 132
Joined: Tuesday 20 October 2015 12:23
Target OS: Raspberry Pi / ODroid
Domoticz version:
Location: Netherlands
Contact:

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

Post by rednas »

Would it be possible to add this to a future version of Domoticz, like Logitech Media Server & Kodi are included?
dhanjel
Posts: 102
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 »

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: 26
Joined: Saturday 02 January 2016 2:22
Target OS: Raspberry Pi / ODroid
Domoticz version: beta
Contact:

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

Post 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();
}
meanmrgreen
Posts: 9
Joined: Sunday 13 November 2016 11:05
Target OS: -
Domoticz version:
Contact:

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

Post 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?
turnhob
Posts: 7
Joined: Sunday 11 December 2016 9:44
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

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

Post 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.
turnhob
Posts: 7
Joined: Sunday 11 December 2016 9:44
Target OS: Raspberry Pi / ODroid
Domoticz version:
Contact:

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

Post 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?
meanmrgreen
Posts: 9
Joined: Sunday 13 November 2016 11:05
Target OS: -
Domoticz version:
Contact:

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

Post by meanmrgreen »

how did you fix it?
chrisfraser05
Posts: 32
Joined: Sunday 08 January 2017 18:59
Target OS: Windows
Domoticz version:
Contact:

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

Post by chrisfraser05 »

This is interesting. I'll have to try this tomorrow
User avatar
DewGew
Posts: 581
Joined: Thursday 21 April 2016 12:01
Target OS: Raspberry Pi / ODroid
Domoticz version: V4.10618
Location: Sweden
Contact:

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

Post 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??
Raspberry Pi 3 | domoticz | Aeon Labs Z-Stick GEN5 | RFlink gateway
NanoPi NEO-air | REGO6XX interface | Machinon theme | Homebridge | Domoticz Google Assistant | ideAlarm
freijn
Posts: 536
Joined: Friday 23 December 2016 16:40
Target OS: Raspberry Pi / ODroid
Domoticz version: Stable
Location: Netherlands Purmerend
Contact:

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

Post by freijn »

Perhaps show us the error you are hitting?
User avatar
DewGew
Posts: 581
Joined: Thursday 21 April 2016 12:01
Target OS: Raspberry Pi / ODroid
Domoticz version: V4.10618
Location: Sweden
Contact:

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

Post by DewGew »

freijn wrote: Friday 29 June 2018 9:24 Perhaps show us the error you are hitting?
I got no erros ..
Raspberry Pi 3 | domoticz | Aeon Labs Z-Stick GEN5 | RFlink gateway
NanoPi NEO-air | REGO6XX interface | Machinon theme | Homebridge | Domoticz Google Assistant | ideAlarm
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest