Enabling Data Roaming for one application only on my Firefox-OS Phone - firefox-os

I wanted to use Usage default app to determine how much data my own app send when in roaming mode.
I was very surprised to see that my device sent about 500 Mo. Then I realised that other apps on my phone should have used the network also.
So my question is: how can I enable roaming for just my app and prevent network access for everything else (updates, agenda, mail, ...)?
I run Firefox-OS 2.0 on a ZTE-Open device.

No, this is not possible.
The Data Usage App performs a test like this using the with the Network Stats API:
var end = new Date();
var start = new Date();
// Returns a mozNetworkStats object
var test = navigator.mozNetworkStats.getSamples('mobile', start, end);
console.log(test);
But this test will return a sample of all device connections, not only yours. The simplest solution is to measure the traffic in your Network Monitor.
However, if you want to reduce the amount of mobile traffic for your application, you can restrict all connections to specific connection types (like wifi). Just listen to the typechange event of the NetworkInformation.connection API.
In your WebIDE console (Firefox OS 2.0):
navigator.connection
NetworkInformation { type: "wifi", ontypechange: null }
or
navigator.connection
NetworkInformation { type: "cellular", ontypechange: null }
Please notice, that Firefox OS <=1.5 will never show you a cellular type of connection (it will return none if not wifi).

Related

Do leaf/downstream devices connect directly to iot-hub even when edge is used as gateway?

I am trying to setup an iot-edge device as an edge gateway. We wouldn't want our leaf/sensor/downstream devices directly connecting to the internet/cloud, and thus I would expect the iot-edge-gateway(as it name suggests) to bridge the connection between downstream devices and the cloud/iot-hub. However, I realize that the connection string for iot-hub/edge at any device level is simply
connection-string-for-iothub-with-gatewayhostwayAppended
This makes me assume that downstream devices transmit messages to an endpoint (prolly messages/* )to cloud/iot-hub and it is from there that gateway gets it(works with that data maybe then) and forwards it back to the $upstream, which shuns the whole point of a gateway.
Here in the message routing section of IOT-EDGE-GATEWAY
https://learn.microsoft.com/en-us/azure/iot-edge/how-to-create-transparent-gateway, in the ROUTE MESSAGES FROM DOWNSTREAM DEVICES section
{
"routes":{
"sensorToAIInsightsInput1":"FROM /messages/* WHERE NOT IS_DEFINED($connectionModuleId) INTO BrokeredEndpoint(\"/modules/ai_insights/inputs/input1\")",
"AIInsightsToIoTHub":"FROM /messages/modules/ai_insights/outputs/output1 INTO $upstream"
}
}
makes it sound like the gateway is routing messages falling on the built-in-endpoint(Default) to $upstream. I can't find any other clearer documentations over the web on this subject. I would really appreciate if someone clears this up. I was expecting the connection string for edge-gateway(that i'd mention in the device end to be something along the lines of localhost:port and not cloudaddress+gatewayhostname)
If your connection string contains a gateway hostname - and the SDK you are using on the device properly handles this, the device only connects to the gateway, not to the IoT Hub.
You can see the example from the .NET SDK here:
this.HostName = builder.GatewayHostName == null || builder.GatewayHostName == "" ? builder.HostName : builder.GatewayHostName;
https://github.com/Azure/azure-iot-sdk-csharp/blob/f86cb76470326f5af8426f3c2695279f51f6e0c8/iothub/device/src/IotHubConnectionString.cs#L30
If the gateway hostname is set, it actually overwrites the IoT Hub hostname for the connection.

Web Bluetooth Bypass Pairing Screen

The BLE Peripheral Simulator app, combined with the Web Bluetooth Samples, is a tremendous resource for developers.
Once a device is paired, is there any way through Web Bluetooth to bypass the pairing screen and go straight to the app?
Yes, this is possible. Code Source. Not my code though.
// Selected device object cache
let deviceCache = null;
// Launch Bluetooth device chooser and connect to the selected
function connect() {
return (deviceCache ? Promise.resolve(deviceCache) :
requestBluetoothDevice())
.then(device => connectDeviceAndCacheCharacteristic(device))
.then(characteristic => startNotifications(characteristic))
.catch(error => log(error));
function requestBluetoothDevice() {
log('Requesting bluetooth device...');
return navigator.bluetooth.requestDevice({
filters: [{services: [myService]}],
})
.then(device => {
log('"' + device.name + '" bluetooth device selected');
deviceCache = device;
// Listen for disconnet event
deviceCache.addEventListener('gattserverdisconnected',
handleDisconnection);
return deviceCache;
});
}
Also, there is a way of reconnecting after site refresh, but it is not implemented yet
I recently implemented a new permissions backend as well as two APIs that will enable previously permitted Bluetooth devices to be used.
The new permissions backend is implemented behind the chrome://flags/#enable-web-bluetooth-new-permissions-backend. The new backend will persist device permissions granted through requestDevice() until the permission is reset in Site Settings or the Page Info dialog box.
The getDevices() and watchAdvertisements() are implemented behind the chrome://flags/#enable-experimental-web-platform-features flag for Chrome 85.0.4165.0 or greater. The recommended use of these APIs is to use getDevices() to retrieve an array of permitted BluetoothDevices and then calling watchAdvertisements() on these devices to start a scan. When advertisement packets are detected from the devices, the advertisementreceived Event will be fired on the device that it corresponds to. At this point, the Bluetooth device is in range and can be connected to.
Please give this new feature a try, and file any bugs at https://crbug.com using the Blink>Bluetooth component.

Random 21/42 seconds timeout in outgoing traffic on Azure Web Sites

I have an ASP.NET MVC 5 application running in the azure german cloud as Azure Web App (single instance - Standard S3 size).
I'm calling a non azure hosted REST/SOAP service on a particular host and the web requests either succeed promptly or timeout after 21 / 42 seconds.
I've load tested the requests and the percentile of requests timing out is between 20 and 80.
One particular remarkable property of the timeout is, that they occur after exactly 21 or 42 seconds (this is serious, no reference to hitchhiker's guide to the galaxy intended).
Calling a different service from the web app works just fine, temporarily at least.
We've already checked the firewall of the non azure service and if the timeout occurs, not a single packet reached the host.
This issue occurred once in the past one year ago and support was unable to tell what the cause was until the issue suddenly went away roughly two weeks after first occuring, so the ticket got closed as fixed itself but now its back.
The code is using https://github.com/canton7/RestEase (uses HttpClient underneath) and looks like
[Header("Content-Type", "application/json")]
public interface IApi
{
[Post("/Login")]
Task<LoginToken> Login([Body]LoginRequest request);
}
private static Dictionary<string, IApi> ApiClientsByHost = new Dictionary<string, IApi>();
private IApi GetApiForHost(string host)
{
if (!ApiClientsByHost.TryGetValue(host, out var client))
{
lock (ApiClientsByHost)
{
if (!ApiClientsByHost.TryGetValue(host, out client))
{
ApiClientsByHost[host] = client = RestClient.For<IApi>(host);
}
}
}
return client;
}
var client = GetApiForHost("https://production/");
var loginToken = await client.Login(new LoginRequest { Username = username, Password = password });
By different service, i mean using "https://testserver/" instead of "https://production/" (testserver is located in a different data center with different IP and all).
The API authentication is passing a token via query but it timeouts already before being able to get a token.
The code is caching the IApi to avoid the TCP starvation problems of disposing HttpClients (but i've never run into port exhaustion).
Restarting the app does not resolve the issue and the issue only occurs to production currently (but a year ago, when this issue occurred on production, we've switched to testserver which worked initially but after some time, ran into the same problem)
EDIT: Found some explanation in the last answer as to where those magical 21 seconds are comming from.
EDIT: One way i've found to workaround is, is to setup a azure vm with a proxy on it and configure defaultProxy to pass through that vm.
That's TCP retransmission timing out. It's odd that you are getting different values though.

Windows 10 - how to detect when a Bluetooth device is in range

I have previously paired with a Bluetooth device that supports RFCOMM.
When my app is opened I continuously try to connect to the device by opening the RFCOMM. This way my app automatically connects when the device comes in range.
deviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));
LogData(String.Format("Number of mldp devices is {0}", deviceInfoCollection.Count));
foreach (DeviceInformation deviceInfo in deviceInfoCollection)
{
LogData(String.Format("ID:{0}, NAME:{1}", deviceInfo.Id, deviceInfo.Name));
}
Then run this on a timer:
try
{
// The first time this method is invoked by a store app, it should be called
// from a UI thread in order to display the consent prompt
// https://msdn.microsoft.com/en-us/windows.devices.bluetooth.rfcomm.rfcommdeviceservice.fromidasync
RfcommDeviceService rfcommService = await RfcommDeviceService.FromIdAsync(deviceInfo.Id);
LogData(String.Format("ID:{0}, NAME:{1}", deviceInfo.Id, deviceInfo.Name));
}
catch (Exception)
{
LogData(String.Format("Can not request rfcomm service from device ID:{0}, NAME:{1}", deviceInfo.Id, deviceInfo.Name));
}
Is there any way to query when the device is in range , rather than trying to connect? I would prefer to only attempt connection when the device is in range.
For RFCOMM (BT2.0, BT2.1) you can run a device enumeration periodically, see also Get bluetooth devices in range
However your actual implementation with a connection attempt may work a little better.
For Bluetooth 4.0, you can listen to the advertisements of the BT module, see also https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BluetoothAdvertisement
If you're talking to an embedded device (e.g. some robot, or homebrew appliances using RFCOMM) I am afraid there is no better solution than what you're doing.
If you're taking to a phone (which supports both BT4.0 and BT2.1) you can use the BT4 advertisements to signal the proximity of the device, then connect via RFCOMM.

Pusher Account over quota

We use Puhser in our application in order to have real-time updates.
Something very stange happens - while google analytics says that we have around 200 simultaneous connections, Pusher says that we have 1500.
I would like to monitor Pusher connections in real-time but could not find any method to do so. Somebody can help??
Currently there's no way to get realtime stats on the number of connections you currently have open for your app. However, it is something that we're investigating currently.
In terms of why the numbers vary between Pusher and Google Analytics, it's usually down to the fact that Google Analytics uses different methods of tracking whether or not a user is on the site. We're confident that our connection counting is correct, however, that's not to say that there isn't a potentially unexpected reason for your count to be high.
A connection is counted as a WebSocket connection to Pusher. When using the Pusher JavaScript library a new WebSocket connection is created when you create a new Pusher instance.
var pusher = new Pusher('APP_KEY');
Channel subscriptions are created over the existing WebSocket connection (known as multiplexing), and do not count towards your connection quota (there is no limit on the number allowed per connection).
var channel1 = pusher.subscribe('ch1');
var channel2 = pusher.subscribe('ch2');
// All done over as single connection
// more subscriptions
// ...
var channel 100 = pusher.subscribe('ch100');
// Still just a 1 connection
Common reasons why connections are higher than expected
Users open multiple tabs
If a user has multiple tabs open to the same application, multiple instances of Pusher will be created and therefore multiple connections will be used e.g. 2 tabs open will mean 2 connections are established.
Incorrectly coded applications
As mentioned above, a new connection is created every time a new Pusher object is instantiated. It is therefore possible to create many connections in the same page.
Using an older version of one our libraries
Our connection strategies have improved over time, and we recommend that you keep up to date with the latest versions.
Specifically, in newer versions of our JS library, we carry out ping-pong requests between server and client to verify that the client is still around.
Other remedies
While our efforts are always to keep a connection going indefinitely to an application, it is possible to disconnect manually if you feel this works in your scenario. It can be achieved by making a call to Pusher.disconnect(). Below is some example code:
var pusher = new Pusher("APP_KEY");
var timeoutId = null;
function startInactivityCheck() {
timeoutId = window.setTimeout(function(){
pusher.disconnect();
}, 5 * 60 * 1000); // called after 5 minutes
};
// called by something that detects user activity
function userActivityDetected(){
if(timeoutId !== null) {
window.clearTimeout(timeoutId);
}
startInactivityCheck();
};
How this disconnection is transmitted to the user is up to you but you may consider prompting them to let them know that they will not receive any further real-time updates due to a long period of inactivity. If they wish to start receiving real-time updates again they should click a button.

Resources