Steve Spencer's Blog

Blogging on Azure Stuff

Unlock The Door Demo Software on GitHub

If you attended my DDD East Anglia talk “A Raspberry Pi2, Azure ML and Project Oxford to unlock that door!” where I integrate a Raspberry Pi running Windows 10 IoT core with the service bus , Project Oxford for face recognition and a Windows Store App to take my picture and hopefully unlock my door. Yes I did bring a door with me. Thanks for attending and for your nice comments.

I have started to put my code up on GitHub. The code for the Raspberry Pi is already there - https://github.com/sdspencer-mvp/RaspberryPi2-UnlockTheDoor. More will appear later as I tidy it up and remove all my config secrets Winking smile

I will be repeating this talk at Smart Devs in Hereford on 12 October 2015 and again at DDD North in Sunderland on 24 October 2015.

Windows 10 IoT Core New Release

I’ve just upgraded my Raspberry Pi 2 with Windows 10 IoT Core Build Number 10531.0 (download , release notes). It fixes an issue I’ve been having with setting the application the runs when the Pi first starts up. Prior to this release my application would start up the first time and then shutdown and be replaced by the default app. It would then not start up at power up again. Now my application starts up every time I power on my Raspberry Pi Smile

It is also possible to set the computer name and set the administrator password from the Raspberry Pi administration website. Previously this was done using PowerShell.

In order to navigate to the administration page you must first know either the machine name or ip address of your Raspberry Pi. This can be found in the Windows 10 IoT Core watcher application that runs after you have installed the IoT core SDK. To access the admin website either enter the address into a browser (http://<ipaddressornameofPi>:8080) or right click on the Pi in the IoT Core Watcher application and select “Web Browse Here”. You will need to enter the username Administrator plus your password to access the site.

image

Here  you can enter a new device name (machine name) as well as change the password. A reboot will be required if you change the name.

In order to set the start up app click the Apps link on the menu panel

image

You will need to ensure that you have first deployed your application to the Raspberry Pi. If you have debugged your application using Visual Studio then a debug version will already have been installed on the Raspberry Pi.

From the Installed Apps drop down select your applications and click the Set Default button. Your application should start and replace the Default App in the running apps list. You can check this by clicking reboot or cycling the power to the Raspberry Pi and your app should start up after the Raspberry Pi has booted.

Windows 10 IoT core project issues when upgrading to VS2015RTM

Just updated my VS2015 to RTM and tried to load in my blinky Iot Project for Raspberry Pi 2. It didn’t load and I was informed that the project required updating

clip_image001

Right clicking on the project offers the option to download updates

Selecting this takes you to:

https://msdn.microsoft.com/en-us/library/windows/apps/xaml/mt188198.aspx

It looks like all I can do is to create a new blank project and copy the existing project files over.

Created a new project and copied the contents of MainPage.xaml.cs and MainPage.Xaml over the contents of the files created in the new project. I found it was quicker to do this than to copy the files over manually. Also, change the namespace (if you created a project with a different name) in both MainPage.xaml.cs and MainPage.xaml. Add in all other files you are using by right clicking on the project and clicking Add Existing Items…

Need to add the following reference:

clip_image002

In the project properties: I selected remote debugger and entered the ip address of my raspberry pi.

When I tried to debug the deployment failed because the version of the remote debugger on the raspberry pi2 was out of date. In order to upgrade it I needed to also upgrade my Windows 10 to the latest version.( https://ms-iot.github.io/content/en-US/win10/SetupPCRPI.htm ) then reflash my raspberry pi 2 sd card ( https://ms-iot.github.io/content/en-US/win10/SetupRPI.htm)

I first updated my Win 10 VM but when I ran the WindowsIoTImageHelper it would not recognise the SD card of the host machine and I couldn’t seem to force it to use the SD card on the host. I then updated my surface Pro to the latest Windows 10 and repeated the process to reflash my Pi.

With all the upgrades completed my project now deploys and runs fine on my updated Raspberry PI2.

Raspberry Pi2 , Iot Core and Azure Service Bus

Using Raspberry Pi2 on Windows 10 IoT core has a number of challenges mainly due to the limitations of both the universal app APIs and also the lack of APIs that currently run on the platform. I specifically wanted to utilise Azure Service Bus Topics to send/receive messages on my Raspberry Pi2. After a bit of searching around I decided that the easiest way to achieve this was to use the Service Bus REST API. There are a number of samples included in the documentation:

Receiving a message: https://msdn.microsoft.com/en-us/library/azure/hh690923.aspx

Sending a message: https://msdn.microsoft.com/en-us/library/azure/hh690922.aspx

The full code for the sample uses WebClient but I needed to use HttpClient so I converted the samples accordingly.

[EDIT] The above links don't work anymore so I've published my code on GitHub https://github.com/sdspencer-mvp/RaspberryPi2-UnlockTheDoor/blob/master/UnlockTheDoor/MainPage.xaml.cs 

Sending a message to the service bus requires a POST and receive and delete requires a DELETE. The following code shows how this was achieved using HttpClient

private async void SendMessage(string baseAddress, string queueTopicName, string token, string body, IDictionary<string, string> properties)

{

    string fullAddress = baseAddress + queueTopicName + "/messages" + "?timeout=60&api-version=2013-08 ";

    await SendViaHttp(token, body, properties, fullAddress, HttpMethod.Post);

}

 

 

 

// Receives and deletes the next message from the given resource (queue, topic, or subscription)

// using the resourceName and an HTTP DELETE request.

private static async System.Threading.Tasks.Task <string> ReceiveAndDeleteMessageFromSubscription(string baseAddress, string topic, string subscription, string token, IDictionary<string, string> properties)

{

    string fullAddress = baseAddress + topic + "/Subscriptions/" + subscription + "/messages/head" + "?timeout=60";

    HttpResponseMessage response = await SendViaHttp(token, "", properties, fullAddress, HttpMethod.Delete);

    string content = "";

    if (response.IsSuccessStatusCode)

    {

        // we should have retrieved a message

        content = await response.Content.ReadAsStringAsync();

    }

    return content;

}

 

 

 

private static async System.Threading.Tasks.Task<HttpResponseMessage> SendViaHttp(string token, string body, IDictionary<string, string> properties, string fullAddress, HttpMethod httpMethod )

{

    HttpClient webClient = new HttpClient();

    HttpRequestMessage request = new HttpRequestMessage()

    {

        RequestUri = new Uri(fullAddress),

        Method = httpMethod ,

 

    };

    webClient.DefaultRequestHeaders.Add("Authorization", token);

 

    if (properties != null)

    {

        foreach (string property in properties.Keys)

        {

            request.Headers.Add(property, properties[property]);

        }

    }

    request.Content = new FormUrlEncodedContent(new[] { new KeyValuePair<string, string>("", body) });

    HttpResponseMessage response = await webClient.SendAsync(request);

    if (!response.IsSuccessStatusCode)

    {

        string error = string.Format("{0} : {1}", response.StatusCode, response.ReasonPhrase);

        throw new Exception(error);

    }

    return response;

}

 

There was an issue with the GetSASToken method as some of the encryption classes weren't supported on the Universal App so I converted it to the following:

private string GetSASToken(string baseAddress, string SASKeyName, string SASKeyValue)

{

    TimeSpan fromEpochStart = DateTime.UtcNow - new DateTime(1970, 1, 1);

    string expiry = Convert.ToString((int)fromEpochStart.TotalSeconds + 3600);

    string stringToSign = WebUtility.UrlEncode(baseAddress) + "\n" + expiry;

    string hmac = GetSHA256Key(Encoding.UTF8.GetBytes(SASKeyValue), stringToSign);

    string hash = HmacSha256(SASKeyValue, stringToSign);

    string sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}",

        WebUtility.UrlEncode(baseAddress), WebUtility.UrlEncode(hash), expiry, SASKeyName);

    return sasToken;

}

 

 

public string HmacSha256(string secretKey, string value)

{

    // Move strings to buffers.

    var key = CryptographicBuffer.ConvertStringToBinary(secretKey, BinaryStringEncoding.Utf8);

    var msg = CryptographicBuffer.ConvertStringToBinary(value, BinaryStringEncoding.Utf8);

 

    // Create HMAC.

    var objMacProv = MacAlgorithmProvider.OpenAlgorithm(MacAlgorithmNames.HmacSha256);

    var hash = objMacProv.CreateHash(key);

    hash.Append(msg);

    return CryptographicBuffer.EncodeToBase64String(hash.GetValueAndReset());

}

 

This allowed me to send and receive messages on my Raspberry Pi2 using IoT core. I created the subscriptions for the topic using a separate app using the .NET SDK which is cheating I guess, but I’ll get around to converting it at some point.

 

In order to use this the following parameters are used:

 

SendMessage( BaseAddress, Username, Token, MessageBody, MessageProperties)

 

BaseAddress is “https://<yournamespace>.servicebus.windows.net/”

 

Token is the return value from the GetSASToken method. using the same base address as above and the KeyName and Key are obtained from the Azure portal and is of the format

 

Endpoint=sb://<yournamespace>.servicebus.windows.net/;SharedAccessKeyName=<KeyName>;SharedAccessKey=<Key>.

 

MessageBody – This is the string value of the message body

 

MessageProperties are a Dictionary containing name/value pairs that will get added to the Request headers. For example I have set the message properties when I press the door bell button on my Raspberry PI2

 

Dictionary<string, string> properties = new Dictionary<string, string>();

properties.Add("Priority", "High");

properties.Add("MessageType", "Command");

properties.Add("Command", "BingBong");

 

These are added to the service bus message and allow me to have subscriptions that filer on Command message types as well as the specific command of BingBong

 

Receiving messages are a bit trickier as we need to create a separate task that is continually running. Once the message is received we need to get back to the main tread to execute the action for the message

await Task.Run(async () =>

{

.

.

.

string message = await ReceiveAndDeleteMessageFromSubscription(_BaseAddress

,_TopicName

, _SubscriptionName

, token, null);

 if (message.Contains("Unlock"))

{

   await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(

      CoreDispatcherPriority.Normal,

      () =>

      {

          SwitchLED(false);

     });

}

 

.

.

}

 

You may want to put a delay in this if receiving the messages causes the app to slow down due to the message loop hogging all the resources. There’s a default timeout in the call to SendAsync and this will automatically slow the thread down.

 

I now have a working Raspberry PI2 that can send and receive message to the Azure Service bus. I’ve created a test win forms app that allows me to send messages to the Service bus and it allows me to control the Raspberry Pi2 remotely. The next phase is to build a workflow engine that hooks up to the service bus and allows me to automatically control the Raspberry Pi. 

Issues setting up Raspberry Pi, Windows 10 IoT core and Visual Studio on a Windows 10 VM

After setting up my Surface Pro with Windows 10 and IoT core I decided that in order to demo it all I needed a Windows 10 VM with it all on. I had a couple of issues that I didn’t get on my Surface Pro.

The first issue I had was that the Windows IoT core watcher application would not run properly and kept shutting down. This is a known bug and has a work around:

Launch the "Developer Command Prompt for VS2015" as Administrator
change the working directory over to "C:\Program Files (x86)\Microsoft IoT"
sn -Vr WindowsIoTCoreWatcher.exe
corflags WindowsIoTCoreWatcher.exe /32BIT+ /FORCE

 

The second issue was Visual Studio couldn’t connect to TFS online. When I tried to manage connections I got the following error:

SplitterDistance must be between Panel1MinSize and Width - Panel2MinSize.

This seems to happen on both VS 2015 Enterprise RC and Community RC editions. I found a work around as follows:

Open up Team Foundation Server online at <youraccount>.visualstudio.com. Click code, then navigate to the project you want to open, click on the solution file which then opens the solution in the web editor. Click the visual studio icon and VS opens with the team project now in team explorer. Close VS and open it again and your team project should still be  connected to team explorer

 

Now with Visual Studio working I needed to set Windows into developer mode. This can be done as follows:

Start->settings->Update & Security -> For Developers. However, when I tried this the setting page kept closing. You can also use the Group Policy editor (Gpedit.msc) as follows:

https://msdn.microsoft.com/en-us/library/windows/apps/dn706236.aspx

clip_image001