DeviceInformation::FindAllAsync fails to find devices with RFCOMM service ID - windows-runtime

I want a simple client/server setup with two Windows Phones, and I'm using the following code to set up the server:
auto providerTask = create_task(RfcommServiceProvider::CreateAsync(RfcommServiceId::FromUuid(GetServiceGUID())));
providerTask.then([this](RfcommServiceProvider^ p) -> task < void >
{
this->provider = p;
this->listener = ref new StreamSocketListener();
listener->ConnectionReceived += ref new Windows::Foundation::TypedEventHandler < Windows::Networking::Sockets::StreamSocketListener ^,
Windows::Networking::Sockets::StreamSocketListenerConnectionReceivedEventArgs ^ >
(this, &ConnectionManager::OnConnectionReceived);
return create_task(listener->BindServiceNameAsync(provider->ServiceId->AsString())).then([this]()
{
this->provider->StartAdvertising(listener);
});
}).then([](task<void> t)
{
//handle exceptions at the end of the chain
try
{
t.get();
}
catch (Platform::Exception^ ex)
{
if (ex->HResult == 0x9000000F)
{
OutputDebugString(L"Bluetooth is disabled.\n");
}
else throw ex;
}
});
GetServiceGUID() just returns the identifier I created for my App with VS's built-in GUID tool; the same one is also declared in the app manifest.
On the second device I'm looking for servers like this:
auto query = RfcommDeviceService::GetDeviceSelector(RfcommServiceId::FromUuid(GetServiceGUID()));
create_task(DeviceInformation::FindAllAsync(query))
.then([this](DeviceInformationCollection^ services)
{
if (services->Size > 0)
{
OutputDebugString(L"We've found a server!\n");
OutputDebugString(services->First()->Current->Name->Data());
}
});
The call to FindAllAsync always returns an empty collection, even though both devices are shown as paired in the settings. However, if I use RfcommServiceId::ObexObjectPush instead of FromUuid when setting up the server and later when enumerating devices, it works fine. Does anyone know why this is happening?

What do the AQS selector strings look like in both cases?
The problem is either:
The selector doesn't match the interface on the system unexpectedly
Basically the filter is used to match properties on the devices interfaces currently in KM PnP state. If an interface's properties match what is logically being requested in the selector, then it is added to the device information collection.
Maybe try FindAllAsync without a selector, then see what interfaces are currently being enumerated by KM PnP. Request the properties that are in the selector. Once you see the interface that you think you should be seeing, logically figure out why it is not matching with the selector.
The device is not paired.
If the device is not paired, then there won't be any devnodes or interfaces to represent it. Hence it cannot be discovered by FindAllAsync
The device is paired, but does not have the profile you think it has.
The Bluetooth bus driver will only create PnP state for profiles it understands. The PnP state is required for FindAllAsync to find it. RFCOMM is a basic one, so it should work though.
Anyway, start with writing some test code as outlined in 1. That will give you some infortmation to get further in your investigation.
Also, checkout the new Windows 10 API changes for Windows.Devices.Enumeration. There are new ways to discover Bluetooth devices.
-Sam

Related

Which usage is best for adding TileTask to ScheduledActionService for WP?

There are some usages for adding TileTask to ScheduledActionService but I didn't understand which one is best usage. For example;
private void StartPeriodicAgent(string taskName)
{
tilePeriodicTask = ScheduledActionService.Find(taskName) as PeriodicTask;
if (tilePeriodicTask != null)
{
RemoveAgent(taskName);
}
tilePeriodicTask = new PeriodicTask(taskName);
tilePeriodicTask.Description = "App Tile Agent";
try
{
ScheduledActionService.Add(tilePeriodicTask);
// If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if(DEBUG)
ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(30));
#endif
}
catch (InvalidOperationException)
{
//MessageBox.Show(ex.ToString());
}
catch (SchedulerServiceException)
{
}
}
This method is remove existing tileTask and add again everytime. Is it true? Have I remove and add it again every usage? Or Shouldn't I remove-add it if it exists?
Thanks.
In all applications I have used LiveTiles in, I used the example provided my Microsoft for working with tiles. In that sample, they remove the existing task agent before recreating it, just like your code above. I would do that.
I realize there are cases where the samples Microsoft provides are completely against accepted best practices, but in this case, I believe that the sample is correct (and therefore, your code).
I hope this helps put your mind at ease.

DalekJS and Mithril: Test are too fast

I use Dalek to test my sample to-do application written with help of Mithril framework.
Everything goes fine until .type() comes in.
If I .type() something in input that have bi-directional binding m.prop with m.withAttr and then assert values of that field i get strage behaviour. Instead "test title" I get "tsttle". It seems that test are running too quickly for Mithril to capture changes and render them back to DOM.
If assertions for input equality is removed — all works just fine.
Is there any workaround, can I slow down type process?
P.S. I use Chrome browser as test runner.
That definitely is an interesting issue, the problem is though, that Dalek can't control the speed of the letters typed. This is due to the fact that the JSON-Wire Protocol does not give us a way to handle that, see here
One thing you could do, even if it seems like overkill, is to add a long function chain with explicit waits, like this:
.type('#selector', 'H')
.wait(500)
.type('#selector', 'e')
.wait(500)
.type('#selector', 'l')
.wait(500)
.type('#selector', 'l')
.wait(500)
.type('#selector', 'o')
You also could go ahead & write a utility function that handles that for you
function myType (selector, keys, test, wait) {
var keysArr = keys.split('');
keysArr.forEach(function (key) {
test.type(selector, key).wait(wait);
});
return test;
}
And then use it in your test like this:
module.exports = {
'my test': function (test) {
test.open('http://foobar.com');
myType('#selector', 'Hello', test, 500);
test.done();
}
};
Mithril, as of when I'm writing this, does a re-render on onkey* events. An option to avoid this is coming.
You could use attr::config at present to handle the onkey* events as this will not cause a rerender. For example:
m('input', {config: addHandler});
function addHandler (el, isInitialized, context) {
if (!isinitialized) {
el.addEventListener('onkeyup', keyHandler, false);
}
}
function keyHandler (event) { /* do something with key press */ }
Its possible {config: addHandler, onchange: m.withAttr('value', mpropData)} will do what you want, but I don't know Dalek. If its doesn't, then you can consider updating mpropData inside keyHandler.
Mithril renders asynchronously in response to event handlers (basically so that related groups of events like keypress/input all get a chance to run before redrawing)
You could try a few things:
if you have access to your data model from your test, you could run your assertion against that model value (which is updated synchronously), as opposed to using the DOM value which only gets updated on the next animation frame
otherwise, you could force a synchronous redraw by explicitly calling m.render (yes, render, not redraw) before running the assertion, to ensure the view is actually in sync w/ the data model
alternatively, you could try waiting for one animation frame (or two) before running the assertion

HTML5 Gamepad API on Chrome

I'm using Chrome (Version 19.0.1084.46). I enabled the Gamepad API in chrome://flags. I plugged in some game pads, but navigator.webkitGamepads is always an array of length 4 containing only undefined.
navigator.webkitGamepads
GamepadList
0: undefined
1: undefined
2: undefined
3: undefined
length: 4
__proto__: GamepadList
What do I need to do to test out using gamepads? I'm on Ubuntu Linux if that matters.
I was having trouble with this as well (on Ubuntu 10.04 with Chrome 21.0.1163.0 dev). I ran across this from a thread on chromium-discussions:
Note that you need to press a face button on the gamepad before data
will be available. This is due to fingerprinting concerns.
I wrote a quick test page that seems to work if you hold a controller button down while refreshing the page. I'm using a Gamestop-branded Xbox 360 wired controller with the xboxdrv driver.
Also, one other important thing to note - Chrome treats these Gamepad objects like snapshots of the controller state. So if you pass around the actual Gamepad object, you'll never get updated information. Chrome seems to only poll the controller when you call the navigator.webkitGamepads[x] getter (see line 23 in my test page).
SPECIAL NOTE: The GamePad API is handled in two completely different ways by Firefox and Google Chrome. Because of this, you need to include code to test for your browser's identity, and handle the cases accordingly.
When the navigator.getGamePads() method is invoked, an array of objects is returned, and those objects contain information about the identity of your gamepads/joysticks, and the state of the axes/buttons thereof.
Here's the issue: on Firefox, the method hands the array to your calling code, and you can then examine that array repeatedly, to look for changes of axis/button state in your own code. Firefox behaves in the expected manner, and updates the objects you've received with new axis/button data, as and when it becomes available.
Google Chrome, on the other hand, treats the array totally differently. Chrome treats the array as a one-time snapshot of the status of your gamepads/joysticks, and if you want to fetch new data, you have to perform another invocation of navigator.getGamePads(), to fetch a new snapshot, discarding the old one.
As a consequence, you need something like this to make your code work on both browsers (assuming that the variable 'gp' is the variable in which you previously stored the return value from your first invocation of navigator.getGamePads() ...)
var ua = navigator.userAgent;
if (ua.toLowerCase().indexOf("chrome") != -1)
gp = navigator.getGamePads();
Why the two browsers behave so differently, is a topic for another thread, but I suspect it has much to do with the fact that the GamePad API is still somewhat experimental, and the fine detail of the standard applicable thereto has not yet been finalised.
In my case, running Chrome on Windows 7 64-bit (but the 32-bit version, for some strange reason best known to my computer's manufacturer, who installed it in this fashion), the array returned by navigator.getGamePads() currently contains only as many entries as there are actual gamepads/joysticks plugged into my computer. If you're experiencing something different on Chrome under Linux, then you need to take this into account also, by testing to see if you have any null values in the array.
Another factor to take into account, is that when selecting a gamepad/joystick, the standard in place calls for the index property of the GamePad object to be referenced, and used thereafter to index into the array. The reason for this is covered in more detail in this document:
W3C page : Editor's Draft on the GamePad interface
However, whilst the implementation of this works as documented above in my incarnation of Google Chrome, you may have to check your version experimentally to see if it behaves the same as mine. If it doesn't, adjust your code accordingly until such time as the standard is finalised, and proper conformity thereto is enforced in all modern browsers and all OS incarnations thereof.
So, when you're selecting a particular gamepad/joystick to work with, the code will look something like this (with the variable 'gid' as your index selector):
var gLen = this.gamePads.length;
done = false;
idx = 0;
while (!done)
{
if (this.gamePads[idx] !== null)
{
if (gid == this.gamePads[idx].index)
{
//Here, choose this GamePad as the selected GamePad, based upon the index number as per the W3C recommendation ...
selectedGamePadIndex = gid;
selectedGamePad = this.gamePads[idx];
done = true;
//End if
}
//End if
}
//Update counter in case we haven't selected one of the available GamePads above ...
idx++;
if (idx >= gLen)
done = true; //Exit loop altogether if we've exhausted the list of available GamePads
//End while
}
I actually implemented the above code (along with some tidying up at the end) as a method for a custom object, but the principle remains the same regardless of the implementation minutiae. (I'll confess at this juncture that I have a habit of writing my own short libraries to handle tasks like this!)
Another issue to watch out for, is the manner in which the gamepad API maps the physical data sources of your gamepad/joystick to the axis/button elements of the GamePad object, and the values contained therein. I have a Microsoft Sidewinder Pro USB joystick, and the mappings for this device on my computer are seriously weird, viz:
Axes 0/1: Joystick handle (as expected)
Axes 2/3: Not assigned
Axes 4/5: 4 not assigned, 5 assigned to twist grip
Axes 6/7: 6 assigned to round slider, 7 not assigned
Axes 8/9: 8 not assigned, 9 assigned to hat switch (er, WHAT???)
Yes, that's right, analogue axis 9 is assigned to the hat switch, and seriously odd values are returned, viz:
Hat switch centred: +1.2
Hat switch up: -1.0
Hat switch down: +0.1
Hat switch left: +0.7
Hat switch right: -0.42
Quirks like this are something you should be alert to as you experiment with the GamePad API. Even worse, a so-called "standard" GamePad (defined in that document I linked to above) may report as standard on some browsers, but not on others, or worse still, report as standard on browser X in Windows, but not on the same browser X in Linux! While this will induce much hair-tearing frustration as you try to fight your way through this software equivalent of bramble thicket, getting badly scratched by some of the thorns along the way, you can at least take comfort in the fact that browser developers are working to try and ameliorate this, but it'll take time, because other things take priority (such as making sure your browser doesn't become an easy target for ransomware to hijack, which will ruin you day immensely if it happens).
This didn't work for me but maybe it helps you? Pulled from here.
function updateStatus() {
window.webkitRequestAnimationFrame(updateStatus);
var gamepads = navigator.webkitGamepads;
var data = '';
for (var padindex = 0; padindex < gamepads.length; ++padindex)
{
var pad = gamepads[padindex];
if (!pad) continue;
data += '<pre>' + pad.index + ": " + pad.id + "<br/>";
for (var i = 0; i < pad.buttons.length; ++i)
data += "button" + i + ": " + pad.buttons[i] + "<br/>";
for (var i = 0; i < pad.axes.length; ++i)
data += "axis" + i + ": " + pad.axes[i] + "<br/>";
}
document.body.innerHTML = data;
}
window.webkitRequestAnimationFrame(updateStatus);
Or as a hard alternative, there's the Javascript Joystick Plug-in (demo here) but I don't think that works in Linux.

How can I configure call depth in PowerShell?

I was just trying things in PowerShell and got an error about call depth being set to 1000 in some test recursive function. I looked on the Internet for some information and found that this is due to error handling in PowerShell (if I got it right):
The recursion depth limit is fixed in version 1. Deep recursion was causing problems in 64-bit mode because of the way exceptions were being processed. It was causing cascading out-of-memory errors. The net result was that we hard-limited the recursion depth on all platforms to help ensure that scripts would be portable to all platforms.
- Bruce Payette, co-designer of PowerShell
I found it here.
Also I found this exception page on MSDN that states this limit is configurable (but I didn't find anything about how to do this) - see remarks section here.
How can this limit be set?
In PowerShell V1 the maximum call depth is 100:
Using .NET Reflector, we can see in this snippet from the System.Management.ExecutionContext class code,
internal int IncrementScopeDepth()
{
using (IDisposable disposable = tracer.TraceMethod("{0}", new object[] { this.scopeDepth }))
{
if (this.CurrentPipelineStopping)
{
throw new PipelineStoppedException();
}
this.scopeDepth++;
if (this.scopeDepth > 100)
{
ScriptCallDepthException exceptionRecord = new
ScriptCallDepthException(this.scopeDepth, 100);
tracer.TraceException(exceptionRecord);
throw exceptionRecord;
}
return this.scopeDepth;
}
}
that it is not possible to modify the hardcoded 100.
In PowerShell V2 the maximum call depth is 1000
Again when looking at the code, there doesn't seem to be a way around the default maximum call depth.
In PowerShell V3 (CTP) there doesn't seem to be a maximum call depth (unless you run out of resources of course). This behaviour has been described as a bug on connect, so it might change in the final version.

should the builder reset its build environment after delivering the product

I am implementing a builder where in the deliverable is retrieved by calling Builder::getProduct() . The director asks various parts to build Builder::buildPartA() , Builder::buildPartB() etc. in order to completely build the product.
My question is, once the product is delivered by the Builder by calling Builder::getProduct(), should it reset its environment (Builder::partA = NULL;, Builder::partB = NULL;) so that it is ready to build another product? (with same or different configuration?)
I ask this as I am using PHP wherein the objects are by default passed by reference (nope, I don't want to clone them, as one of their field is a Resource) . However, even if you think from a language agnostic point of view, should the Builder reset its build environment ? If your answer is 'it depends on the case' what use cases would justify reseting the environment (and other way round) ?
For the sake of providing code sample here's my Builder::gerProcessor() which shows what I mean by reseting the environment
/**
* #see IBuilder::getProessor()
*/
public function getProcessor()
{
if($this->_processor == NULL) {
throw new LogicException('Processor not yet built!');
} else {
$retval = $this->_processor;
$this->_product = NULL, $this->_processor = NULL;
}
return $retval;
}
Resetting the state in getProcessor() is non-obvious and if you want to do that the method should reflect that in it's name, e.g. getProcessorAndReset(). A cleaner solution would be to just give the builder a separate reset() method.
In general, your getProcessor() should not reset it's internal state because methods should not magically change behavior but reliably do the same. getProcessor() is a query and that query should return the same configured Processor on each call. It should not change state. Resetting the state is a command. You want to separate command and query methods.