Chromecast: using IS_CONNECTED_CHANGED to detect receiver connection - chromecast

I'm trying to add Chromecast capability to an existing app, using Google's CastVideos-chrome sample app as a guide. My question is about how the sender detects that it connected to a receiver.
What I expect/want to happen
The sample app includes the following, which I have basically copied in my implementation (CastVideos.js, lines 165-198):
CastPlayer.prototype.initializeCastPlayer = function() {
// ...
this.remotePlayerController.addEventListener(
cast.framework.RemotePlayerEventType.IS_CONNECTED_CHANGED,
function(e) {
this.switchPlayer(e.value);
}.bind(this)
);
};
Within the CastVideos-chrome app, setupRemotePlayer() is only called in switchPlayer(), and switchPlayer() is only called from the IS_CONNECTED_CHANGED listener in the snippet above. So, I ought to be seeing an IS_CONNECTED_CHANGED event whenever my app connects to a receiver, in order to set up the remote player.
My code
When initializing the sender, I add a listener for the IS_CONNECTED_CHANGED event. Below is my code (in kotlin-js) and a translation into javascript.
remotePlayerController = js("new cast.framework.RemotePlayerController(new cast.framework.RemotePlayer())")
remotePlayerController.addEventListener(Util.RemotePlayerEventType.IS_CONNECTED_CHANGED) {
js("function() {" +
"console.log(\"Remote Player event: IS_CONNECTED_CHANGED\");" +
"return switchPlayers();" +
"}")
}
The equivalent js code would be:
this.remotePlayerController = new cast.framework.RemotePlayerController(new cast.framework.RemotePlayer())
remotePlayerController.addEventListener(cast.framework.RemotePlayerEventType.IS_CONNECTED_CHANGED) {
function() {
console.log(\"Remote Player event: IS_CONNECTED_CHANGED\");
return switchPlayers();
}
}
Here's my receiver code, which exactly corresponds to step 7 of the Cast Receiver codelab and works correctly against the codelab's sample sender:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cast CAF Receiver</title>
<script type="text/javascript" src="//www.gstatic.com/cast/sdk/libs/mediaplayer/1.0.0/media_player.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/shaka-player/2.5.5/shaka-player.compiled.js"></script>
</head>
<body>
<cast-media-player></cast-media-player>
<script src="//www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js"></script>
<script>
const context = cast.framework.CastReceiverContext.getInstance();
const playerManager = context.getPlayerManager(); // the PlayerManager handles playback and provides hooks to plug-in custom logic
context.start(); // initialize sdk
</script>
</body>
</html>
What's wrong
Based on console logs that I've added, I know the event listener being added. Then, I click the cast button on my sender page, and my receiver app shows up on my TV. At this point, typing cast.framework.CastContext.getInstance().getCastState() into the sender console returns "CONNECTED" and the current session (
cast.framework.CastContext.getInstance().getCurrentSession()) is not null. BUT, the IS_CONNECTED_CHANGED event listener is never triggered. Neither the sender nor the receiver (Chrome Remote Debugger console) print errors or logs about this.
I've tried listening for ANY_CHANGE as well as IS_CONNECTED_CHANGED, but neither listener gets called.
My Question
What's an appropriate way to trigger setup of the remote player? Is there something wrong with how I'm listening for the IS_CONNECTED_CHANGED event? Or should I be listening for something else entirely?

HTML page example with Cast button using Chromecast framework API.
Upload the html code to webserver and viewed as webpage because CAST API cannot be loaded properly from local file HTML.
example code
screenshot

Actually, my problem was that the sender never connected to the receiver! It never detected a connection, because there never was one. As far as I can tell, listening for IS_CONNECTED_CHANGED is a perfectly appropriate way to detect a connection, if it would occur.
How I know this: The sender did cause my TV to load the receiver app, but afterwards on the sender, cast.framework.CastContext.getInstance().getCurrentSession() was null (where "session" refers to a connection to a receiver) and, more tellingly, cast.framework.CastContext.getInstance.getCastState() returned "NOT_CONNECTED". As far as I can tell, there was either never a time when the cast state was connected, or the connected state lasted for less than a second, even while the receiver kept going.

Related

display a flash message with events with vuejs

I'm trying to do what is here in the source code, but it is not working.
But event is sent but never received.
Here is the simplest example I could make:
in bootstrap.js:
window.events = new Vue();
window.flash = function (message, level = 'success') {
console.log('emit'); // This is working
window.events.$emit('flash', { message, level });
};
Vue.component('flash', require('./vue/components/Flash.vue'));
Flash.vue:
<template>
<div> MY FLASH</div>
</template>
<script>
export default {
created() {
window.events.$on(
'flash', data => alert('event!!!')
);
},
};
</script>
and in my view:
<flash></flash>
I can see in my view the component rendering ie MY FLASH message, but I never get the alert coming from emit!
I also have no error in debugger
Am I missing something? it seems quite simple....
The code in your question sets up a global function called flash that triggers the event. That function has to be called somewhere in order for the event to be triggered.
Here is a codesandbox that demonstrates. Everything except triggering the event is from your code.
Note that the alert will only show if the flash method is called after the Flash component is created.
Also, remember when using a bus to remove the listener when the component is destroyed to prevent adding multiple listeners if the component is created more than once.
This is an old question, but I fall in the same situation, my solution maybe is not the best but is working for me.
Based in this response "Note that the alert will only show if the flash method is called after the Flash component is created." by Bert.
The flash component may have a few uses cases, if you want to use in the same view/page it will be fine, because the component is mounted and still any event hasn't been fired. But if you wan to use in a view/page transition using vue router, you will need to use vuex to store your alert message and then fetch and display the alert.

AirConsole Controller Generator

I am having trouble figuring out the messages sent by controllers built using the AirConsole Controller Generator. I created a simple controller with a dpad, two middle buttons labeled Start and Back and two vertical buttons Jump and Attack and included the airconsole-controls folder in the directory. I am able to test my game using the simulator and my controller is displayed and the virtual buttons are clickable but the messages aren't being sent or received by the game correctly.
I did use the demo controller for the pong game and was able to correctly use the up and down buttons within my game so the issue is with the controller I generated or my understanding of the button messages that are sent from it.
Thanks for any help!
The generator always sends an object with a automatic- or self-defined key (depending on the element):
{
'element-key': {
message: <Object>,
pressed: <Boolean>
}
To use the data which was send by - for example a dpad - you can do s.t. like this:
// On the 'Screen-Side'
airconsole.onMessage = function(device_id, data) {
if (data.hasOwnProperty('dpad-left')) {
var message = data['dpad-left'].message;
var is_pressed = data['dpad-left'].pressed;
}
};
Otherwise try to write a console.log(data) within the onMessage method and see if anything is received.
Let me know if this helped you!

Can I access the default validationMessage of an element when using WebShim Polyfill lib?

When using the HTML5 Validation API it is possible to intercept the error, access the error message and render it differently.
When using the WebShim Polyfill, I would've hoped that this would work in the same way without having to access a customValidationMessage property.
Is there a way WebShim can be configured so we can write consistent code for intercepting these error messages as below.
$("input").on("invalid", function(evt) {
evt.preventDefault();
alert(evt.currentTarget.validationMessage);
});
... I would expect this code to work in a Polyfill, perhaps I have misunderstood it's setup or something?
The reason I want to do this is so that I can grab all the invalid fields and display the errors in one block, rather than next to each field.
Thanks,
Nick
Yes, this is possible. If you setup everything correctly you only have to change your call to validationMessage. Webshims always fixes elements through the jQuery API, not the DOM element itself. Which means you always have to use $.prop to access DOM properties.
$("input").on("invalid", function(evt) {
evt.preventDefault();
alert($.prop(evt.target, "validationMessage"));
});
You can also use eventdelegation:
$(function(){
$(document).on("invalid", function(evt) {
var message = $.prop(evt.target, "validationMessage");
if(message){
evt.preventDefault();
alert(message);
}
});
});
Note:
Eventdelegation for invalid is done through event capturing (which isn't normally used by jQuery). Therefore you have to wait untill polyfill is loaded. (Normally, jQuery's ready event is delayed untill then.)
I check if an validationMessage is there, although there was an invalid event. Here is why: There was a spec change and now an invalid event is also triggered on the form element. This is currently only polyfilled in an unstable version of webshims and only for incapable browsers (IE < 12, Safari < 8 ...).

jQuery 'on' not registering in dynamically generated modal popup

I was under the impression that jQuery's on event handler was meant to be able to 'listen' for dynamically created elements AND that it was supposed to replace the behavior of live. However, what I have experienced is that using on is not capturing the click event whereas using live is succeeding!
The tricky aspect of my situation is that I am not only dynamically creating content but I'm doing it via an AJAX .get() call, and inserting the resultant HTML into a modal .dialog() jQueryUI popup.
Here is a simplified version of what I was trying to accomplish (wrapped in $(document).ready(...) ):
$.get("getUserDataAjax.php", queryString, function(formToDisplay) {
$("#dialog").dialog({
autoOpen: true,
modal: true,
buttons...
}).html(formToDisplay);
});
$(".classThatExistsInFormToDisplay").on("click", function() {
alert("This doesn't get called");
});
From the documentation for on I found this which which was how I was approaching writing my on event:
$("p").on("click", function(){
alert( $(this).text() );
});
However, for some reason, live will work as I expect -- whereas on is failing me.
This isn't a question for "how can I make it work" because I have found that on will succeed (capture clicks) if I declare it inside the function(formToDisplay) callback.
My question is: what is wrong with on that it isn't finding my dynamically created elements within a modal popup? My jQuery instance is jquery-1.7.2. jQueryUI is 1.8.21.
Here are two jsFiddles that approximate the issue. Click the word "Test" in both instances to see the different behavior. The only difference in code is replacing on for live.
Where the click is captured by live.
Where the click is NOT captured by on (click 'Test - click me' to see nothing happen).
I realize I may just be using on inappropriately or asking it to do something that was not intended but I want to know why it is not working (but if you have something terribly clever, feel free to share). Thanks for your wisdom!
Update / Answer / Solution:
According to user 'undefined', the difference is that on is not delegated all the way from the top of the document object whereas live does/is.
As Claudio mentions, there are portions of the on documentation that reference dynamically created elements and that what you include in the $("") part of the query needs to exist at runtime.
Here is my new solution: Capture click events on my modal dialog, which, although it does not have any content when the event is created at runtime, will be able to find my content and element with special class that gets generated later.
$("#dialog").on("click", ".classThatExistsInFormToDisplay", function() {
... //(success! Event captured)
});
Thanks so much!
live delegates the event from document object, but on doesn't, if you want to delegate the event using on method, you should delegate the event from one of static parents of the element or document object:
$(document).on("click", ".clickHandle", function() {
alert("Content clicked");
});
The problem is that the element to which you attach the event has to exist.
You have to use on like this to capture clicks on p tags created dynamically
$("#existingContainerId").on("click", "p", function(){
alert( $(this).text() );
});
if you have no relevant existing container to use, you could use $("body") or $(document)
If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.
When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next
Take a look to section Direct and delegated events here for more details

jwplayer - detecting the start

I am trying to detect a start click in jwplayer. I am embedding it via swfobject so the method is slightly different from the example in the api, http://www.longtailvideo.com/support/jw-player/jw-player-for-flash-v5/16024/listening-for-player-events
I have tried
var flashvars = {
'file':'xxx',
'streamer':'xxxxxx',
'image':'xxxxx',
'plugins':'xxxxx',
'gapro.accountid':'xxxx',
'gapro.trackstarts':'xxxx',
'gapro.trackpercentage':'xxxx',
'gapro.tracktime':'xxxx',
'logo.file':'xxxxx',
'logo.link':'xxxx',
'logo.hide':'xxxx',
'logo.position':'xxxx'
};
jwplayer().onPlay(function() {alert('it has started'});
jwplayer() is not defined, how do I defined an object to detect the click?
The player is probably undefined because it hasn't been created yet. You should wrap your command in a callback from a DOM ready listener. Since you're using jQuery you can use its .ready() method (jQuery documentation):
$(document).ready(function(){
jwplayer().onPlay(function() { alert('it has started'); });
});
Just a note about jwplayer onPlay(), it doesn't necessarily happen from a click event, it fires whenever the video is played, which could be by clicking play, or by programmatically playing the video. All it's telling you is that the video is playing. (Corrected the syntax error)

Resources