Author Archives: purpleblob

Bluetooth Proximity

This post is going to cover aspects of determining proximity with Bluetooth devices and hence covers a couple of key pieces of data.

RSSI

RSSI stands for Received Signal Strength Indication as is a measurement of radio signal strength, measure in dBm (decibel-milliwatts). The higher the RSSI value, the stronger the signal.

Signal strength can be affected by many things. Along with the obvious environment affects, such as walls and interference the different chipsets used can give wide variations and hence cannot be guaranteed to indicate whether one Bluetooth device is actually closer than another.

To use RSSI effectively to try to approximate proximity, at least in terms of whether we’re getting closer to the device or moving further away, we should track multiple samples of RSSI over time. If the signal is getting weaker then we might suggest the device is getting further away (ofcourse taking into account any environment and others forms of interference).

RSSI can be calculated (although it will likely be available from your preferred Bluetooth LE library) using the following formula (although this includes distance as a parameter which is, after all what we’re after with proximity so unlikely to have).

RSSI = -10n log(d) + A

where 

d is distance
A is txPower
and
n is a signal propagation constant 
(for example it might be set to 2 in free space, but 
vary in a walled area).

In situations where we have RSSI only (i.e. no TX Power) we can approximate proximity using the signal strength by checking the RSSI against the following range of values

RSSI of -50dBm to 0dBm – very close
RSSI of -90dBm to -50dBm – medium distance
RSSI of less than -90dBm – far away

However, as stated, signals may be affected by different forms of interference and also by the chipsets and power used for the radio, so can only be taken as “guesses” to proximity.

TX Power

If you see the an option on your preferred Bluetooth LE library called txPower which stands for transmitted power (also known as measured power).

Note: This doesn’t seem to be available/used by all Bluetooth devices. In which case it’ll be defaulted to zero.

TX power is used within the previous formula (along with the RSSI value) to help determine distance or proximity estimates. It allows us to take into consideration the actual power of the Bluetooth device as it’s a calibrated (read-only constant) which indicates the expected RSSI at a distance of 1 metre from the Bluetooth device. So with RSSI and TX Power we can rearrange the previous equation to calculate distance, here’s a C# implementation of that

public static double GetProximity(int rssi, int txPower)
{
   const int signalPropagationConstant = 2; 
   return Math.Pow(10d, ((double) txPower - rssi) / (10 * signalPropagationConstant));
}

Obviously when calculating proximity with a 0 txPower the distance will no longer be valid and hence you’ll have to simply have to use sample RSSI to get a basic idea of signal strength).

References
Bluetooth LE Advertisements – Gauging Distance
How to Calculate Distance from the RSSI value of the BLE Beacon
Estimating beacon proximity/distance based on RSSI – Bluetooth LE
Proximity And RSSI

Taking a screen shot on your phone/tablet

Whilst developing application for phones and/or tablets we might like to take some screenshots of a “live” application, as opposed to one within an emulator etc.

To take a screenshot we simply do the following.

  • Android – hold the power button and volume down button for a second.
  • iOS – press the home button and the power button
  • Windows 10 mobile – hold the power button and volume up button

Android application’s default theme colours

Note: I’m developing an application with Xamarin Forms, so, although I assume this is the same across Android development, I have not verified this.

We define a style for an Android application (see Resources/values/styles.xml). This consists of the theme being used as well as some values for customisation. These include the status bar (the bar at the top of the screen which contains notification icons such as wi-fi, Bluetooth icons etc.) as well as the caption/title colour, navigation bar colour etc.

The default colours for this and/or your applications toolbar etc. are customisable via this styles.xml file. Here’s some of the values available

  • colorPrimaryDark – this is the status bar colour, by default it’s set to #1976D2
  • colorPrimary – this is the action bar/toolbar colour, by default it’s set to #2196F3
  • colorAccent – this is the tint colour (used on controls/widgets as a highlight), by default it’s set to #FF4081

References

Material Design for Android
Styles and Themes

Enumerating available devices in UWP

In my previous post (Displaying the device picker in a UWP application) I showed how to reuse the UWP device picker flyout within an application.

However, it’s possible that the developer would prefer to offer devices in some alternate UI or, of course, simply locate a known device for an application to use. In the previous post I looked at filtering for Bluetooth devices and those are what I’m after for a little application I’m writing in which I do not require the DevicePicker UI.

Filtering

Before I get into code to enumerate the devices, I’ll first expand on the lines of code from my previous post, that look like this

BluetoothDevice.GetDeviceSelectorFromPairingState(false)

Each of the lines like this one actually returns a string which is an Advanced Query Syntax (AQS) language query. So for example this line will produce the following string (formatted to make it more readable)

System.Devices.DevObjectType:=5 AND 
System.Devices.Aep.ProtocolId:=\"{E0CBF06C-CD8B-4647-BB8A-263B43F0F974}\" AND 
(System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#False OR
System.Devices.Aep.Bluetooth.IssueInquiry:=System.StructuredQueryType.Boolean#True)

For completeness, here’s the results of each of the other GetDeviceSelectorFromPairingState calls

BluetoothLEDevice.GetDeviceSelectorFromPairingState(false)

System.Devices.DevObjectType:=5 AND 
System.Devices.Aep.ProtocolId:=\"{BB7BB05E-5972-42B5-94FC-76EAA7084D49}\" AND 
(System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#False OR 
System.Devices.Aep.Bluetooth.IssueInquiry:=System.StructuredQueryType.Boolean#True)

BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)

System.Devices.DevObjectType:=5 AND 
System.Devices.Aep.ProtocolId:=\"{BB7BB05E-5972-42B5-94FC-76EAA7084D49}\" AND 
(System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True OR 
System.Devices.Aep.Bluetooth.IssueInquiry:=System.StructuredQueryType.Boolean#False)

BluetoothDevice.GetDeviceSelectorFromPairingState(true)

System.Devices.DevObjectType:=5 AND 
System.Devices.Aep.ProtocolId:=\"{E0CBF06C-CD8B-4647-BB8A-263B43F0F974}\" AND 
(System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True OR 
System.Devices.Aep.Bluetooth.IssueInquiry:=System.StructuredQueryType.Boolean#False)

Hence we could now create our own AQS query to search for devices.

See Using Advanced Query Syntax Programmatically for more information on AQS.

Enumerating over devices (simple approach)

A simple approach to enumerating over all the available devices is to use the DeviceInformation.FindAllAsync() method, which is async/await compatible, hence we simply use it like this

var devices = await DeviceInformation.FindAllAsync();

// output all devices
foreach (var device in devices)
{
   Debug.WriteLine(device.Name);
}

Obviously this is a little over the top if we’re looking for a specific device or set of devices. In such cases we can create an AQS query and pass this into one of the FindAllAsync overloads. Hence to recreate my previous post’s query looking for all Bluetooth devices we might prefer to use

var devices = await DeviceInformation.FindAllAsync(
    BluetoothDevice.GetDeviceSelectorFromPairingState(
        false));

Whilst this solution to the problem of locating devices may fulfil many of the developer’s requirements, an area it fails on is that once the developer has a list of devices they do not have a way to tell when devices are turned off/disabled/or otherwise no longer available. In such situations it’s better to watch for device changes.

Watching for device changes

The DeviceInformation.CreateWatcher method allows the developer to query for devices and via events, watch for items to be added, updated or removed. This would suit an RX type of implementation.

Here’s some code that demonstrates possible usage of the CreateWatcher

try
{
   deviceWatcher = DeviceInformation.CreateWatcher(
      BluetoothDevice.GetDeviceSelectorFromPairingState(false), 
      null,
      DeviceInformationKind.Device);

      deviceWatcher.Added += (watcher, args) =>
      {
         Debug.WriteLine($"Added {args.Name}");
      };
      deviceWatcher.Updated += (watcher, args) =>
      {
         Debug.WriteLine($"Updated {args.Id}");
      };
      deviceWatcher.Removed += (watcher, args) =>
      {
         Debug.WriteLine($"Removed {args.Id}");
      };
      deviceWatcher.EnumerationCompleted += (watcher, args) => 
      { 
         Debug.WriteLine("No more devices found"); 
      };
      deviceWatcher.Start();
}
catch (ArgumentException ex)
{
   Debug.WriteLine(ex.Message);
}

Again we’re using the AQS created via the GetDeviceSelectoryFromPairingState method and in this simplistic example, we simply subscribe to the Added/Updated/Removed and EnumerationCompleted events to output what devices have been added etc. We also need to be aware of possible ArgumentExceptions, such as incorrectly formatted GUID’s etc. See DeviceInformation Class for a more complete example of this usage.

Displaying the device picker in a UWP application

Developers can use the UWP device picker flyout control within their application to allow the user to select a device from a list of available devices. The list can be filtered to display only particular types of devices.

For example, here’s how to display the DevicePicker flyout without filtering, i.e. showing all available devices

var devicePicker = new DevicePicker();
devicePicker.Show(new Rect(x, y, width, height));

In this case we simply create a DevicePicker and call the Show method which is passed a rectangle where you want the picker to flyout from.

There’s an overload Show method which allows a placement as well.

If you run this code in your application you’ll find that devices are enumerated over and displayed as they are found, so obviously this may take a little bit of time to enumerate all devices.

In most cases we probably want to filter the DevicePicker for a certain type of device. For example if we want to locate all Bluetooth devices we would use the following

var devicePicker = new DevicePicker();

devicePicker.Filter
   .SupportedDeviceSelectors.Add(
      BluetoothLEDevice.GetDeviceSelectorFromPairingState(false));
devicePicker.Filter
   .SupportedDeviceSelectors.Add(
      BluetoothLEDevice.GetDeviceSelectorFromPairingState(true));
devicePicker.Filter
   .SupportedDeviceSelectors.Add(
      BluetoothDevice.GetDeviceSelectorFromPairingState(false));
devicePicker.Filter
   .SupportedDeviceSelectors.Add(
      BluetoothDevice.GetDeviceSelectorFromPairingState(true));

devicePicker.Show(new Rect(x, y, width, height));

In this case we’ve filtered the DevicePicker so it will only display BluetoothLE devices and Bluetooth devices both in a paired (the true parameter) or unpaired (the false parameter).

Obviously we’re going to want to get at the device information or the selected device, when using the Show method, we will need to subscribe to the DevicePicker’s DeviceSelected event, for example

devicePicker.DeviceSelected += (picker, args) =>
{
   // outputs the selected device name
   Debug.WriteLine(args.SelectedDevice.Name);
};

We can also respond to a couple of other events such as the DevicePickerDismissed and DisconnectButtonClicked.

As an alternate to the event approach, we could switch from using the Show method to use the async/await implementation which combines the Show and the DeviceSelected into he PickSingleDeviceAsync method, i.e.

var device = await 
   devicePicker.PickSingleDeviceAsync(
      new Rect(x, y, width, height));
// outputs the selected device name
Debug.WriteLine(device.Name);

IValueConverter.Convert return values

I was updating some value converters in my converters GitHub repos. PutridParrot.Presentation.Converters and realised I had been returning a null in situations where I really should have been returning DependencyProperty.UnsetValue.

Generally we’ll either return a valid value from a converter or one of the following

  • null
  • DependencyProperty.UnsetValue
  • Binding.DoNothing
  • The original value

The documentation (see References) states that when a null is returned then a “valid null value is used”.

However we may actually prefer that the FallbackValue is used (if supplied) instead, hence we can return a DependencyProperty.UnsetValue.

In cases where we neither want a value returned and do not want the FallbackValue to be called, then we return the Binding.DoNothing.

Obviously, in situations where you do not know what to do with a binding value, it might be better to simply return the value passed into the Convert method.

References

IValueConverter.Convert(Object, Type, Object, CultureInfo) Method

Creating a Prism.DryIoc.Forms application from scratch

I must have created my last Prism.DryIoc.Forms application using a project template but this time created a standard Xamarin.Forms application and then realised I wanted/meant to use DryIoc.

So here’s the steps to turn my “standard” Xamarin.Forms application into a Prism.DryIoc.Forms application.

  • Add the Prism.DryIoc.Forms nuget package to your application
  • Delete the MainPage.xaml files generated by Xamarin.Forms
  • Change the App.xaml to use PrismApplication i.e.
    <?xml version="1.0" encoding="utf-8" ?>
    <prism:PrismApplication 
       xmlns="http://xamarin.com/schemas/2014/forms"
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
       xmlns:prism="clr-namespace:Prism.DryIoc;assembly=Prism.DryIoc.Forms"
       x:Class="MyDemo.App">
        <Application.Resources>
    
        </Application.Resources>
    </prism:PrismApplication>
    
  • Change the App.xaml.cs to derive from PrismApplication, for example
    public partial class App : PrismApplication
    
  • Remove/replace the App constructor with the following
    public App() :
       this(null) { }
    
    public App(IPlatformInitializer initializer) :
       base(initializer) { }
    
  • Now override the OnInitialized method and put the IntitializeComponent call within this, i.e.
    protected override async void OnInitialized()
    {
       InitializeComponent();
    }
    
  • Add folders to the solution named ViewModels and Views
  • Within the Views folder add a MainPage.xaml Xamarin.Forms ContentPage (or page type as required)
  • To register our MainPage and the NavigationPage go back to the App.xaml.cs and add the following method
    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
       containerRegistry.RegisterForNavigation<NavigationPage>();
       containerRegistry.RegisterForNavigation<MainPage>();
    }
    
  • Finally, in the App.xaml.cs within the OnIntialized method we’ll navigate to the new page. As the NavigateAsync returns a Task, we can await it so we’ll add async to the OnInitialized method – here’s what that will look like
    protected override async void OnInitialized()
    {
       InitializeComponent();
    
       await NavigationService.NavigateAsync("NavigationPage/MainPage");
    }
    

Now place any further page’s within the Views folder and add to the RegisterTypes method (if required) and add any view models to the ViewModels folder deriving from BindableBase (if you want to use the Prism MVVM base class).

Creating a pre-commit hook for TortoiseGit

Note: This is specific to using TortoiseGit to add your hooks.

I’ve covered Creating a pre-commit hook for TortoiseSvn previously for SVN. We can create similar hooks for GIT also.

Either create a script or other form of executable (this one’s a C# console application). This example is going to do nothing of real interest. It’ll simply stop commits to a repo. but is useful if we place a Debugger.Break before the Console line, for debugging purposes

static int Main(string[] args)
{
   Console.Error.WriteLine("No commits allowed");
   return 1;
}

A non-zero return value indicates a failure and hence this code will effectively stop any commits to the repository it’s applied to.

The arguments sent to the method will be as follows

* 1st arg is the file name of a file which contains a list of files that have changed
* 2nd arg is the file name of a file which has the commit message
* 3rd arg is the folder being committed

Now we compile our application and place it in the .git\hooks\ folder and we need to name it pre-commit.exe.

That’s all there is to it.

Singletons using C# 6 syntax

A while back I wrote the post The Singleton Pattern in C# and just thought it’d be nice to use C# 6 syntax to update this post.

So here’s the code with the change for to use default property syntax

public sealed class Singleton
{
public static Singleton Instance { get; } = new Singleton();

static Singleton() { }
private Singleton() { }
}

Advanced Git CLI

Having covered the “basic” commands in my previous post, I wanted to look at some of the more advanced stuff. I’m basically meaning things we probably won’t use as regularly as the previous post’s commands.

Rebasing

Rebasing isn’t necessarily advanced in it’s basic form but I’ve not had any real use for it so far apart from in more complicated scenarios.

Rebasing allows us to apply commits from, for example one branch, onto another branch. For example, let’s say we created a branch off of the wrong branch and so want to move commits from the incorrect branch onto the other branch.

So let’s assume we have feature/mybranch and we need to rebase it onto correct_branch, then we use

git rebase --onto correct_branch feature/mybranch 
git force push

Staging parts of a file

Git allows us to stage whole files/folders as well as parts of a file. For example, maybe we’ve made several changes, but we currently only want to stage a subset of these changes. We can use

git add --patch filename

// or short form

git add --p filename

We’ll now be presented with a list of the new lines and a lot of options. Selecting ? will list what each of the options means.

We can use commands such as e to edit the patch diff file, allowing us to delete lines etc. that are to be staged.

I’ll be adding further “advanced” situations/commands and when I need them.